/*!--------------------------------------------------------
 * 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 T0=Object.defineProperty;var w0=Object.getOwnPropertyDescriptor;var w=(i,n,e,t)=>{for(var r=t>1?void 0:t?w0(n,e):n,o=i.length-1,s;o>=0;o--)(s=i[o])&&(r=(t?s(n,e,r):s(r))||r);return t&&r&&T0(n,e,r),r},C=(i,n)=>(e,t)=>n(e,t,i);function R0(i,n,e=0,t=i.length){let r=e,o=t;for(;r<o;){let s=Math.floor((r+o)/2);n(i[s])?r=s+1:o=s}return r-1}var xC=class i{constructor(n){this._array=n;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(n){if(i.assertInvariants){if(this._prevFindLastPredicate){for(let t of this._array)if(this._prevFindLastPredicate(t)&&!n(t))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=n}let e=R0(this._array,n,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var Ah=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(n){setTimeout(()=>{throw n.stack?ur.isErrorNoTelemetry(n)?new ur(n.message+`

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

`+n.stack):n},0)}}addListener(n){return this.listeners.push(n),()=>{this._removeListener(n)}}emit(n){this.listeners.forEach(e=>{e(n)})}_removeListener(n){this.listeners.splice(this.listeners.indexOf(n),1)}setUnexpectedErrorHandler(n){this.unexpectedErrorHandler=n}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(n){this.unexpectedErrorHandler(n),this.emit(n)}onUnexpectedExternalError(n){this.unexpectedErrorHandler(n)}},Eh=new Ah;function bi(i){Eh.onUnexpectedError(i)}function st(i){Kn(i)||Eh.onUnexpectedError(i)}function AC(i){Kn(i)||Eh.onUnexpectedExternalError(i)}var mu="Canceled";function Kn(i){return i instanceof Y?!0:i instanceof Error&&i.name===mu&&i.message===mu}var Y=class extends Error{constructor(){super(mu),this.name=this.message}},PC=class i extends Error{static{this._name="PendingMigrationError"}static is(n){return n instanceof i||n instanceof Error&&n.name===i._name}constructor(n){super(n),this.name=i._name}};function hu(){let i=new Error(mu);return i.name=i.message,i}function kh(i){return i?new Error(`Illegal argument: ${i}`):new Error("Illegal argument")}function yu(i){return i?new Error(`Illegal state: ${i}`):new Error("Illegal state")}function Ur(i){return i?i.message?i.message:i.stack?i.stack.split(`
`)[0]:String(i):"Error"}var ur=class i extends Error{constructor(n){super(n),this.name="CodeExpectedError"}static fromError(n){if(n instanceof i)return n;let e=new i;return e.message=n.message,e.stack=n.stack,e}static isErrorNoTelemetry(n){return n.name==="CodeExpectedError"}},$e=class i extends Error{constructor(n){super(n||"An unexpected bug occurred."),Object.setPrototypeOf(this,i.prototype)}};function bn(i,n,e=(t,r)=>t===r){if(i===n)return!0;if(!i||!n||i.length!==n.length)return!1;for(let t=0,r=i.length;t<r;t++)if(!e(i[t],n[t]))return!1;return!0}function Ci(i){return i.filter(n=>!!n)}function Fr(i,n=e=>e){let e=new Set;return i.filter(t=>{let r=n(t);return e.has(r)?!1:(e.add(r),!0)})}function Dh(i,n){return i.push(n),()=>x0(i,n)}function x0(i,n){let e=i.indexOf(n);if(e>-1)return i.splice(e,1),n}function Mh(i,n){let e;if(typeof n=="number"){let t=n;e=()=>{let r=Math.sin(t++)*179426549;return r-Math.floor(r)}}else e=Math.random;for(let t=i.length-1;t>0;t-=1){let r=Math.floor(e()*(t+1)),o=i[t];i[t]=i[r],i[r]=o}}function DC(i){return i[Math.floor(Math.random()*i.length)]}var MC;(a=>{function i(l){return l<0}a.isLessThan=i;function n(l){return l<=0}a.isLessThanOrEqual=n;function e(l){return l>0}a.isGreaterThan=e;function t(l){return l===0}a.isNeitherLessOrGreaterThan=t,a.greaterThan=1,a.lessThan=-1,a.neitherLessOrGreaterThan=0})(MC||={});function OC(i,n){return(e,t)=>n(i(e),i(t))}var LC=(i,n)=>i-n;var kC=class i{constructor(n){this.iterate=n}static{this.empty=new i(n=>{})}forEach(n){this.iterate(e=>(n(e),!0))}toArray(){let n=[];return this.iterate(e=>(n.push(e),!0)),n}filter(n){return new i(e=>this.iterate(t=>n(t)?e(t):!0))}map(n){return new i(e=>this.iterate(t=>e(n(t))))}some(n){let e=!1;return this.iterate(t=>(e=n(t),!e)),e}findFirst(n){let e;return this.iterate(t=>n(t)?(e=t,!1):!0),e}findLast(n){let e;return this.iterate(t=>(n(t)&&(e=t),!0)),e}findLastMaxBy(n){let e,t=!0;return this.iterate(r=>((t||MC.isGreaterThan(n(r,e)))&&(t=!1,e=r),!0)),e}};function HC(i,n){let e=Object.create(null);for(let t of i){let r=n(t),o=e[r];o||(o=e[r]=[]),o.push(t)}return e}var UC,FC,NC=class{constructor(n,e){this.toKey=e;this._map=new Map;this[UC]="SetWithKey";for(let t of n)this.add(t)}get size(){return this._map.size}add(n){let e=this.toKey(n);return this._map.set(e,n),this}delete(n){return this._map.delete(this.toKey(n))}has(n){return this._map.has(this.toKey(n))}*entries(){for(let n of this._map.values())yield[n,n]}keys(){return this.values()}*values(){for(let n of this._map.values())yield n}clear(){this._map.clear()}forEach(n,e){this._map.forEach(t=>n.call(e,t,t,this))}[(FC=Symbol.iterator,UC=Symbol.toStringTag,FC)](){return this.values()}};function gs(i,n){let e=this,t=!1,r;return function(){if(t)return r;if(t=!0,n)try{r=i.apply(e,arguments)}finally{n()}else r=i.apply(e,arguments);return r}}var Lh=class{constructor(n,e){this.uri=n;this.value=e}};function P0(i){return Array.isArray(i)}var $C,We=class i{constructor(n,e){this[$C]="ResourceMap";if(n instanceof i)this.map=new Map(n.map),this.toKey=e??i.defaultToKey;else if(P0(n)){this.map=new Map,this.toKey=e??i.defaultToKey;for(let[t,r]of n)this.set(t,r)}else this.map=new Map,this.toKey=n??i.defaultToKey}static{this.defaultToKey=n=>n.toString()}set(n,e){return this.map.set(this.toKey(n),new Lh(n,e)),this}get(n){return this.map.get(this.toKey(n))?.value}has(n){return this.map.has(this.toKey(n))}get size(){return this.map.size}clear(){this.map.clear()}delete(n){return this.map.delete(this.toKey(n))}forEach(n,e){typeof e<"u"&&(n=n.bind(e));for(let[t,r]of this.map)n(r.value,r.uri,this)}*values(){for(let n of this.map.values())yield n.value}*keys(){for(let n of this.map.values())yield n.uri}*entries(){for(let n of this.map.values())yield[n.uri,n.value]}*[($C=Symbol.toStringTag,Symbol.iterator)](){for(let[,n]of this.map)yield[n.uri,n.value]}},WC,pr=class{constructor(n,e){this[WC]="ResourceSet";!n||typeof n=="function"?this._map=new We(n):(this._map=new We(e),n.forEach(this.add,this))}get size(){return this._map.size}add(n){return this._map.set(n,n),this}clear(){this._map.clear()}delete(n){return this._map.delete(n)}forEach(n,e){this._map.forEach((t,r)=>n.call(e,r,r,this))}has(n){return this._map.has(n)}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.keys()}[(WC=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var qC,Bl=class{constructor(){this[qC]="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(n){return this._map.has(n)}get(n,e=0){let t=this._map.get(n);if(t)return e!==0&&this.touch(t,e),t.value}set(n,e,t=0){let r=this._map.get(n);if(r)r.value=e,t!==0&&this.touch(r,t);else{switch(r={key:n,value:e,next:void 0,previous:void 0},t){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(n,r),this._size++}return this}delete(n){return!!this.remove(n)}remove(n){let e=this._map.get(n);if(e)return this._map.delete(n),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 n=this._head;return this._map.delete(n.key),this.removeItem(n),this._size--,n.value}forEach(n,e){let t=this._state,r=this._head;for(;r;){if(e?n.bind(e)(r.value,r.key,this):n(r.value,r.key,this),this._state!==t)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){let n=this,e=this._state,t=this._head,r={[Symbol.iterator](){return r},[Symbol.dispose](){},next(){if(n._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let o={value:t.key,done:!1};return t=t.next,o}else return{value:void 0,done:!0}}};return r}values(){let n=this,e=this._state,t=this._head,r={[Symbol.iterator](){return r},[Symbol.dispose](){},next(){if(n._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let o={value:t.value,done:!1};return t=t.next,o}else return{value:void 0,done:!0}}};return r}entries(){let n=this,e=this._state,t=this._head,r={[Symbol.iterator](){return r},[Symbol.dispose](){},next(){if(n._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let o={value:[t.key,t.value],done:!1};return t=t.next,o}else return{value:void 0,done:!0}}};return r}[(qC=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(n){if(n>=this.size)return;if(n===0){this.clear();return}let e=this._head,t=this.size;for(;e&&t>n;)this._map.delete(e.key),e=e.next,t--;this._head=e,this._size=t,e&&(e.previous=void 0),this._state++}trimNew(n){if(n>=this.size)return;if(n===0){this.clear();return}let e=this._tail,t=this.size;for(;e&&t>n;)this._map.delete(e.key),e=e.previous,t--;this._tail=e,this._size=t,e&&(e.next=void 0),this._state++}addItemFirst(n){if(!this._head&&!this._tail)this._tail=n;else if(this._head)n.next=this._head,this._head.previous=n;else throw new Error("Invalid list");this._head=n,this._state++}addItemLast(n){if(!this._head&&!this._tail)this._head=n;else if(this._tail)n.previous=this._tail,this._tail.next=n;else throw new Error("Invalid list");this._tail=n,this._state++}removeItem(n){if(n===this._head&&n===this._tail)this._head=void 0,this._tail=void 0;else if(n===this._head){if(!n.next)throw new Error("Invalid list");n.next.previous=void 0,this._head=n.next}else if(n===this._tail){if(!n.previous)throw new Error("Invalid list");n.previous.next=void 0,this._tail=n.previous}else{let e=n.next,t=n.previous;if(!e||!t)throw new Error("Invalid list");e.previous=t,t.next=e}n.next=void 0,n.previous=void 0,this._state++}touch(n,e){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(e!==1&&e!==2)){if(e===1){if(n===this._head)return;let t=n.next,r=n.previous;n===this._tail?(r.next=void 0,this._tail=r):(t.previous=r,r.next=t),n.previous=void 0,n.next=this._head,this._head.previous=n,this._head=n,this._state++}else if(e===2){if(n===this._tail)return;let t=n.next,r=n.previous;n===this._head?(t.previous=void 0,this._head=t):(t.previous=r,r.next=t),n.next=void 0,n.previous=this._tail,this._tail.next=n,this._tail=n,this._state++}}}toJSON(){let n=[];return this.forEach((e,t)=>{n.push([t,e])}),n}fromJSON(n){this.clear();for(let[e,t]of n)this.set(e,t)}},Nh=class extends Bl{constructor(n,e=1){super(),this._limit=n,this._ratio=Math.min(Math.max(0,e),1)}get limit(){return this._limit}set limit(n){this._limit=n,this.checkTrim()}get ratio(){return this._ratio}set ratio(n){this._ratio=Math.min(Math.max(0,n),1),this.checkTrim()}get(n,e=2){return super.get(n,e)}peek(n){return super.get(n,0)}set(n,e){return super.set(n,e,2),this}checkTrim(){this.size>this._limit&&this.trim(Math.round(this._limit*this._ratio))}},sn=class extends Nh{constructor(n,e=1){super(n,e)}trim(n){this.trimOld(n)}set(n,e){return super.set(n,e),this.checkTrim(),this}};var vu=class{constructor(){this.map=new Map}add(n,e){let t=this.map.get(n);t||(t=new Set,this.map.set(n,t)),t.add(e)}delete(n,e){let t=this.map.get(n);t&&(t.delete(e),t.size===0&&this.map.delete(n))}forEach(n,e){let t=this.map.get(n);t&&t.forEach(e)}get(n){let e=this.map.get(n);return e||new Set}};var zl=class{constructor(){this._data=new Map}set(n,...e){let t=this._data;for(let r=0;r<e.length-1;r++){let o=t.get(e[r]);o===void 0&&(o=new Map,t.set(e[r],o)),t=o}t.set(e[e.length-1],n)}get(...n){let e=this._data;for(let t=0;t<n.length-1;t++){let r=e.get(n[t]);if(r===void 0)return;e=r}return e.get(n[n.length-1])}delete(...n){let e=[this._data],t=this._data;for(let o=0;o<n.length-1;o++){let s=t.get(n[o]);if(s===void 0)return!1;t=s,e.push(t)}let r=t.delete(n[n.length-1]);for(let o=n.length-2;r&&o>=0;o--)e[o+1].size===0&&e[o].delete(n[o]);return r}deleteAll(...n){if(n.length===0){let o=this._data.size>0;return this._data.clear(),o}let e=[this._data],t=this._data;for(let o=0;o<n.length-1;o++){let s=t.get(n[o]);if(s===void 0)return!1;t=s,e.push(t)}let r=t.delete(n[n.length-1]);for(let o=n.length-2;r&&o>=0;o--)e[o+1].size===0&&e[o].delete(n[o]);return r}clear(){this._data.clear()}*getAll(...n){let e=this._data;for(let t of n){let r=e.get(t);if(r===void 0)return;e=r}yield*this._values(e)}*values(){yield*this._values(this._data)}*_values(n){for(let e of n.values())e instanceof Map?yield*this._values(e):yield e}toString(){let n=(e,t)=>{let r="";for(let[o,s]of e)r+=`${"  ".repeat(t)}${o}: `,s instanceof Map?r+=`
`+n(s,t+1):r+=`${s}
`;return r};return n(this._data,0)}};function Su(i,n){if(!i)throw new Error(n?`Assertion failed (${n})`:"Assertion Failed")}function Vl(i,n="unexpected state"){if(!i)throw typeof n=="string"?new $e(`Assertion Failed: ${n}`):n}function jl(i){if(!i()){debugger;i(),st(new $e("Assertion Failed"))}}function Ve(i){return typeof i=="string"}function Qe(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof RegExp)&&!(i instanceof Date)}function BC(i){let n=Object.getPrototypeOf(Uint8Array);return typeof i=="object"&&i instanceof n}function So(i){return typeof i=="number"&&!isNaN(i)}function zC(i){return!!i&&typeof i[Symbol.iterator]=="function"}function bu(i){return i===!0||i===!1}function ms(i){return typeof i>"u"}function Gn(i){return!Jn(i)}function Jn(i){return ms(i)||i===null}function VC(i,n){if(!i)throw new Error(n?`Unexpected type, expected '${n}'`:"Unexpected type")}var E0=Object.prototype.hasOwnProperty;function Cu(i){if(!Qe(i))return!1;for(let n in i)if(E0.call(i,n))return!1;return!0}function Kl(i){return typeof i=="function"}function me(i,n){for(let e in n)if(!(e in i))return!1;return!0}var ys;(X=>{function i(E){return!!E&&typeof E=="object"&&typeof E[Symbol.iterator]=="function"}X.is=i;let n=Object.freeze([]);function e(){return n}X.empty=e;function*t(E){yield E}X.single=t;function r(E){return i(E)?E:t(E)}X.wrap=r;function o(E){return E??n}X.from=o;function*s(E){for(let z=E.length-1;z>=0;z--)yield E[z]}X.reverse=s;function a(E){return!E||E[Symbol.iterator]().next().done===!0}X.isEmpty=a;function l(E){return E[Symbol.iterator]().next().value}X.first=l;function d(E,z){let x=0;for(let B of E)if(z(B,x++))return!0;return!1}X.some=d;function c(E,z){let x=0;for(let B of E)if(!z(B,x++))return!1;return!0}X.every=c;function u(E,z){for(let x of E)if(z(x))return x}X.find=u;function*p(E,z){for(let x of E)z(x)&&(yield x)}X.filter=p;function*m(E,z){let x=0;for(let B of E)yield z(B,x++)}X.map=m;function*h(E,z){let x=0;for(let B of E)yield*z(B,x++)}X.flatMap=h;function*y(...E){for(let z of E)zC(z)?yield*z:yield z}X.concat=y;function S(E,z,x){let B=x;for(let K of E)B=z(B,K);return B}X.reduce=S;function b(E){let z=0;for(let x of E)z++;return z}X.length=b;function*I(E,z,x=E.length){for(z<-E.length&&(z=0),z<0&&(z+=E.length),x<0?x+=E.length:x>E.length&&(x=E.length);z<x;z++)yield E[z]}X.slice=I;function _(E,z=Number.POSITIVE_INFINITY){let x=[];if(z===0)return[x,E];let B=E[Symbol.iterator]();for(let K=0;K<z;K++){let N=B.next();if(N.done)return[x,X.empty()];x.push(N.value)}return[x,{[Symbol.iterator](){return B}}]}X.consume=_;async function R(E){let z=[];for await(let x of E)z.push(x);return z}X.asyncToArray=R;async function A(E){let z=[];for await(let x of E)z=z.concat(x);return z}X.asyncToArrayFlat=A})(ys||={});var k0=!1,vs=null;var jC=class i{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(n){let e=this.livingDisposables.get(n);return e||(e={parent:null,source:null,isSingleton:!1,value:n,idx:i.idx++},this.livingDisposables.set(n,e)),e}trackDisposable(n){let e=this.getDisposableData(n);e.source||(e.source=new Error().stack)}setParent(n,e){let t=this.getDisposableData(n);t.parent=e}markAsDisposed(n){this.livingDisposables.delete(n)}markAsSingleton(n){this.getDisposableData(n).isSingleton=!0}getRootParent(n,e){let t=e.get(n);if(t)return t;let r=n.parent?this.getRootParent(this.getDisposableData(n.parent),e):n;return e.set(n,r),r}getTrackedDisposables(){let n=new Map;return[...this.livingDisposables.entries()].filter(([,t])=>t.source!==null&&!this.getRootParent(t,n).isSingleton).flatMap(([t])=>t)}computeLeakingDisposables(n=10,e){let t;if(e)t=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(t=d.filter(u=>!(u.parent&&c.has(u.parent))),t.length===0)throw new Error("There are cyclic diposable chains!")}if(!t)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 vu;for(let l of t){let d=r(l);for(let c=0;c<=d.length;c++)o.add(d.slice(0,c).join(`
`),l)}t.sort(OC(l=>l.idx,LC));let s="",a=0;for(let l of t.slice(0,n)){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}/${t.length} leaks) at ${p}`;let h=o.get(d.slice(0,u).join(`
`)),y=HC([...h].map(S=>r(S)[u]),S=>S);delete y[d[u]];for(let[S,b]of Object.entries(y))b&&c.unshift(`    - stacktraces of ${b.length} other leaks continue with ${S}`);c.unshift(p)}s+=`


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

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


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

`),{leaks:t,details:s}}};function D0(i){vs=i}if(k0){let i="__is_disposable_tracked__";D0(new class{trackDisposable(n){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{n[i]||console.log(e)},3e3)}setParent(n,e){if(n&&n!==T.None)try{n[i]=!0}catch{}}markAsDisposed(n){if(n&&n!==T.None)try{n[i]=!0}catch{}}markAsSingleton(n){}})}function Ii(i){return vs?.trackDisposable(i),i}function _i(i){vs?.markAsDisposed(i)}function bo(i,n){vs?.setParent(i,n)}function M0(i,n){if(vs)for(let e of i)vs.setParent(e,n)}function bs(i){return typeof i=="object"&&i!==null&&typeof i.dispose=="function"&&i.dispose.length===0}function jt(i){if(ys.is(i)){let n=[];for(let e of i)if(e)try{e.dispose()}catch(t){n.push(t)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function _u(...i){let n=M(()=>jt(i));return M0(i,n),n}var Uh=class{constructor(n){this._isDisposed=!1,this._fn=n,Ii(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,_i(this),this._fn()}}};function M(i){return new Uh(i)}var G=class i{constructor(){this._toDispose=new Set;this._isDisposed=!1;Ii(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(_i(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{jt(this._toDispose)}finally{this._toDispose.clear()}}add(n){if(!n||n===T.None)return n;if(n===this)throw new Error("Cannot register a disposable on itself!");return bo(n,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(n),n}delete(n){if(n){if(n===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(n),n.dispose()}}deleteAndLeak(n){n&&this._toDispose.delete(n)&&bo(n,null)}assertNotDisposed(){this._isDisposed&&st(new $e("Object disposed"))}},T=class{constructor(){this._store=new G;Ii(this),bo(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){_i(this),this._store.dispose()}_register(n){if(n===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(n)}},At=class{constructor(){this._isDisposed=!1;Ii(this)}get value(){return this._isDisposed?void 0:this._value}set value(n){this._isDisposed||n===this._value||(this._value?.dispose(),n&&bo(n,this),this._value=n)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,_i(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let n=this._value;return this._value=void 0,n&&bo(n,null),n}};var Ss=class{constructor(){this.references=new Map}acquire(n,...e){let t=this.references.get(n);t||(t={counter:0,object:this.createReferencedObject(n,...e)},this.references.set(n,t));let{object:r}=t,o=gs(()=>{--t.counter===0&&(this.destroyReferencedObject(n,t.object),this.references.delete(n))});return t.counter++,{object:r,dispose:o}}};var Re=class{constructor(n=new Map){this._isDisposed=!1;this._store=n,Ii(this)}dispose(){_i(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{jt(this._store.values())}finally{this._store.clear()}}has(n){return this._store.has(n)}get size(){return this._store.size}get(n){return this._store.get(n)}set(n,e,t=!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),t||this._store.get(n)?.dispose(),this._store.set(n,e),bo(e,this)}deleteAndDispose(n){this._store.get(n)?.dispose(),this._store.delete(n)}deleteAndLeak(n){let e=this._store.get(n);return e&&bo(e,null),this._store.delete(n),e}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}};function Fh(i,n){return i.then(e=>(n.isDisposed?e.dispose():n.add(e),e))}var Iu=class extends Re{constructor(){super(new We)}};var Ge=class i{static{this.Undefined=new i(void 0)}constructor(n){this.element=n,this.next=i.Undefined,this.prev=i.Undefined}},Gl=class{constructor(){this._first=Ge.Undefined;this._last=Ge.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===Ge.Undefined}clear(){let n=this._first;for(;n!==Ge.Undefined;){let e=n.next;n.prev=Ge.Undefined,n.next=Ge.Undefined,n=e}this._first=Ge.Undefined,this._last=Ge.Undefined,this._size=0}unshift(n){return this._insert(n,!1)}push(n){return this._insert(n,!0)}_insert(n,e){let t=new Ge(n);if(this._first===Ge.Undefined)this._first=t,this._last=t;else if(e){let o=this._last;this._last=t,t.prev=o,o.next=t}else{let o=this._first;this._first=t,t.next=o,o.prev=t}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(t))}}shift(){if(this._first!==Ge.Undefined){let n=this._first.element;return this._remove(this._first),n}}pop(){if(this._last!==Ge.Undefined){let n=this._last.element;return this._remove(this._last),n}}peek(){if(this._last!==Ge.Undefined)return this._last.element}_remove(n){if(n.prev!==Ge.Undefined&&n.next!==Ge.Undefined){let e=n.prev;e.next=n.next,n.next.prev=e}else n.prev===Ge.Undefined&&n.next===Ge.Undefined?(this._first=Ge.Undefined,this._last=Ge.Undefined):n.next===Ge.Undefined?(this._last=this._last.prev,this._last.next=Ge.Undefined):n.prev===Ge.Undefined&&(this._first=this._first.next,this._first.prev=Ge.Undefined);this._size-=1}*[Symbol.iterator](){let n=this._first;for(;n!==Ge.Undefined;)yield n.element,n=n.next}};function O0(){return globalThis._VSCODE_NLS_MESSAGES}function Hh(){return globalThis._VSCODE_NLS_LANGUAGE}var L0=Hh()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function KC(i,n){let e;return n.length===0?e=i:e=i.replace(/\{(\d+)\}/g,(t,r)=>{let o=r[0],s=n[o],a=t;return typeof s=="string"?a=s:(typeof s=="number"||typeof s=="boolean"||s===void 0||s===null)&&(a=String(s)),a}),L0&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function f(i,n,...e){return KC(typeof i=="number"?N0(i,n):n,e)}function N0(i,n){let e=O0()?.[i];if(typeof e!="string"){if(typeof n=="string")return n;throw new Error(`!!! NLS MISSING: ${i} !!!`)}return e}var wi="en",Yl=!1,Ql=!1,Jl=!1,JC=!1,YC=!1,$h=!1,U0=!1,QC=!1,F0=!1,H0=!1,wu,Ru=wi,GC=wi,$0,Hr,$r=globalThis,an;typeof $r.vscode<"u"&&typeof $r.vscode.process<"u"?an=$r.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(an=process);var XC=typeof an?.versions?.electron=="string",W0=XC&&an?.type==="renderer";if(typeof an=="object"){Yl=an.platform==="win32",Ql=an.platform==="darwin",Jl=an.platform==="linux",JC=Jl&&!!an.env.SNAP&&!!an.env.SNAP_REVISION,U0=XC,F0=!!an.env.CI||!!an.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!an.env.GITHUB_WORKSPACE,wu=wi,Ru=wi;let i=an.env.VSCODE_NLS_CONFIG;if(i)try{let n=JSON.parse(i);wu=n.userLocale,GC=n.osLocale,Ru=n.resolvedLanguage||wi,$0=n.languagePack?.translationsConfigFile}catch{}YC=!0}else typeof navigator=="object"&&!W0?(Hr=navigator.userAgent,Yl=Hr.indexOf("Windows")>=0,Ql=Hr.indexOf("Macintosh")>=0,QC=(Hr.indexOf("Macintosh")>=0||Hr.indexOf("iPad")>=0||Hr.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Jl=Hr.indexOf("Linux")>=0,H0=Hr?.indexOf("Mobi")>=0,$h=!0,Ru=Hh()||wi,wu=navigator.language.toLowerCase(),GC=wu):console.error("Unable to resolve platform.");function ZC(i){switch(i){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var xu=0;Ql?xu=1:Yl?xu=3:Jl&&(xu=2);var Q=Yl,dt=Ql,Oe=Jl,eI=JC,tI=YC;var Zt=$h,q0=$h&&typeof $r.importScripts=="function",nI=q0?$r.origin:void 0;var Wh=xu,fr=Hr,Ti=Ru,B0;(t=>{function i(){return Ti}t.value=i;function n(){return Ti.length===2?Ti==="en":Ti.length>=3?Ti[0]==="e"&&Ti[1]==="n"&&Ti[2]==="-":!1}t.isDefaultVariant=n;function e(){return Ti==="en"}t.isDefault=e})(B0||={});var z0=typeof $r.postMessage=="function"&&!$r.importScripts,rI=(()=>{if(z0){let i=[];$r.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let t=0,r=i.length;t<r;t++){let o=i[t];if(o.id===e.data.vscodeScheduleAsyncWork){i.splice(t,1),o.callback();return}}});let n=0;return e=>{let t=++n;i.push({id:t,callback:e}),$r.postMessage({vscodeScheduleAsyncWork:t},"*")}}return i=>setTimeout(i)})();var Et=Ql||QC?2:Yl?1:3;var qh=!!(fr&&fr.indexOf("Chrome")>=0),iI=!!(fr&&fr.indexOf("Firefox")>=0),oI=!!(!qh&&fr&&fr.indexOf("Safari")>=0),sI=!!(fr&&fr.indexOf("Edg/")>=0),M8=!!(fr&&fr.indexOf("Android")>=0);var Co,Bh=globalThis.vscode;if(typeof Bh<"u"&&typeof Bh.process<"u"){let i=Bh.process;Co={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"?Co={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:Co={get platform(){return Q?"win32":dt?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var Io=Co.cwd,Xe=Co.env,Cs=Co.platform,aI=Co.arch;var V0=globalThis.performance.now.bind(globalThis.performance),Dn=class i{static create(n){return new i(n)}constructor(n){this._now=n===!1?Date.now:V0,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 lI=!1,j0=!1,K0=100,dI=6e4;function cI(){return!!Xe.VSCODE_DEV}var ee;(de=>{de.None=()=>T.None;function n(F){if(j0){let{onDidAddListener:O}=F,W=_s.create(),q=0;F.onDidAddListener=()=>{++q===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),W.print()),O?.()}}}function e(F,O,W){return m(F,()=>{},0,void 0,O??!0,void 0,W)}de.defer=e;function t(F){return(O,W=null,q)=>{let J=!1,Z;return Z=F(ae=>{if(!J)return Z?Z.dispose():J=!0,O.call(W,ae)},null,q),J&&Z.dispose(),Z}}de.once=t;function r(F,O){return de.once(de.filter(F,O))}de.onceIf=r;function o(F,O,W){return u((q,J=null,Z)=>F(ae=>q.call(J,O(ae)),null,Z),W)}de.map=o;function s(F,O,W){return u((q,J=null,Z)=>F(ae=>{O(ae),q.call(J,ae)},null,Z),W)}de.forEach=s;function a(F,O,W){return u((q,J=null,Z)=>F(ae=>O(ae)&&q.call(J,ae),null,Z),W)}de.filter=a;function l(F){return F}de.signal=l;function d(...F){return(O,W=null,q)=>{let J=_u(...F.map(Z=>Z(ae=>O.call(W,ae))));return p(J,q)}}de.any=d;function c(F,O,W,q){let J=W;return o(F,Z=>(J=O(J,Z),J),q)}de.reduce=c;function u(F,O){let W,q={onWillAddFirstListener(){W=F(J.fire,J)},onDidRemoveLastListener(){W?.dispose()}};O||n(q);let J=new P(q);return O?.add(J),J.event}function p(F,O){return O instanceof Array?O.push(F):O&&O.add(F),F}function m(F,O,W=100,q=!1,J=!1,Z,ae){let ft,Me,yt,vt=0,Pt,Nr={leakWarningThreshold:Z,onWillAddFirstListener(){ft=F(wC=>{vt++,Me=O(Me,wC),q&&!yt&&(vo.fire(Me),Me=void 0),Pt=()=>{let RC=Me;Me=void 0,yt=void 0,(!q||vt>1)&&vo.fire(RC),vt=0},typeof W=="number"?(yt&&clearTimeout(yt),yt=setTimeout(Pt,W)):yt===void 0&&(yt=null,queueMicrotask(Pt))})},onWillRemoveListener(){J&&vt>0&&Pt?.()},onDidRemoveLastListener(){Pt=void 0,ft.dispose()}};ae||n(Nr);let vo=new P(Nr);return ae?.add(vo),vo.event}de.debounce=m;function h(F,O=0,W,q){return de.debounce(F,(J,Z)=>J?(J.push(Z),J):[Z],O,void 0,W??!0,void 0,q)}de.accumulate=h;function y(F,O,W=100,q=!0,J=!0,Z,ae){let ft,Me,yt,vt=0,Pt={leakWarningThreshold:Z,onWillAddFirstListener(){ft=F(vo=>{vt++,Me=O(Me,vo),yt===void 0&&(q&&(Nr.fire(Me),Me=void 0,vt=0),typeof W=="number"?yt=setTimeout(()=>{J&&vt>0&&Nr.fire(Me),Me=void 0,yt=void 0,vt=0},W):(yt=0,queueMicrotask(()=>{J&&vt>0&&Nr.fire(Me),Me=void 0,yt=void 0,vt=0})))})},onDidRemoveLastListener(){ft.dispose()}};ae||n(Pt);let Nr=new P(Pt);return ae?.add(Nr),Nr.event}de.throttle=y;function S(F,O=(q,J)=>q===J,W){let q=!0,J;return a(F,Z=>{let ae=q||!O(Z,J);return q=!1,J=Z,ae},W)}de.latch=S;function b(F,O,W){return[de.filter(F,O,W),de.filter(F,q=>!O(q),W)]}de.split=b;function I(F,O,W=!1,q=[],J){let Z=q.slice(),ae;cI()&&(ae={stack:_s.create(),timerId:setTimeout(()=>{Z&&Z.length>0&&ae&&!ae.warned&&(ae.warned=!0,console.warn(`[Event.buffer][${O}] potential LEAK detected: ${Z.length} events buffered for ${dI/1e3}s without being consumed. Buffered here:`),ae.stack.print())},dI),warned:!1},J&&J.add(M(()=>clearTimeout(ae.timerId))));let ft=()=>{ae&&clearTimeout(ae.timerId)},Me=F(Pt=>{Z?(Z.push(Pt),cI()&&ae&&!ae.warned&&Z.length>=K0&&(ae.warned=!0,console.warn(`[Event.buffer][${O}] potential LEAK detected: ${Z.length} events buffered without being consumed. Buffered here:`),ae.stack.print())):vt.fire(Pt)});J&&J.add(Me);let yt=()=>{Z?.forEach(Pt=>vt.fire(Pt)),Z=null,ft()},vt=new P({onWillAddFirstListener(){Me||(Me=F(Pt=>vt.fire(Pt)),J&&J.add(Me))},onDidAddFirstListener(){Z&&(W?setTimeout(yt):yt())},onDidRemoveLastListener(){Me&&Me.dispose(),Me=null,ft()}});return J&&J.add(vt),vt.event}de.buffer=I;function _(F,O){return(q,J,Z)=>{let ae=O(new A);return F(function(ft){let Me=ae.evaluate(ft);Me!==R&&q.call(J,Me)},void 0,Z)}}de.chain=_;let R=Symbol("HaltChainable");class A{constructor(){this.steps=[]}map(O){return this.steps.push(O),this}forEach(O){return this.steps.push(W=>(O(W),W)),this}filter(O){return this.steps.push(W=>O(W)?W:R),this}reduce(O,W){let q=W;return this.steps.push(J=>(q=O(q,J),q)),this}latch(O=(W,q)=>W===q){let W=!0,q;return this.steps.push(J=>{let Z=W||!O(J,q);return W=!1,q=J,Z?J:R}),this}evaluate(O){for(let W of this.steps)if(O=W(O),O===R)break;return O}}function X(F,O,W=q=>q){let q=(...ft)=>ae.fire(W(...ft)),J=()=>F.on(O,q),Z=()=>F.removeListener(O,q),ae=new P({onWillAddFirstListener:J,onDidRemoveLastListener:Z});return ae.event}de.fromNodeEventEmitter=X;function E(F,O,W=q=>q){let q=(...ft)=>ae.fire(W(...ft)),J=()=>F.addEventListener(O,q),Z=()=>F.removeEventListener(O,q),ae=new P({onWillAddFirstListener:J,onDidRemoveLastListener:Z});return ae.event}de.fromDOMEventEmitter=E;function z(F,O){let W,q,J=new Promise(Z=>{q=t(F)(Z),Jh(q,O),W=()=>{pI(q,O)}});return J.cancel=W,O&&J.finally(()=>pI(q,O)),J}de.toPromise=z;function x(F,O){return F(W=>O.fire(W))}de.forward=x;function B(F,O,W){return O(W),F(q=>O(q))}de.runAndSubscribe=B;class K{constructor(O,W){this._observable=O;this._counter=0;this._hasChanged=!1;let q={onWillAddFirstListener:()=>{O.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{O.removeObserver(this)}};W||n(q),this.emitter=new P(q),W&&W.add(this.emitter)}beginUpdate(O){this._counter++}handlePossibleChange(O){}handleChange(O,W){this._hasChanged=!0}endUpdate(O){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function N(F,O){return new K(F,O).emitter.event}de.fromObservable=N;function V(F){return(O,W,q)=>{let J=0,Z=!1,ae={beginUpdate(){J++},endUpdate(){J--,J===0&&(F.reportChanges(),Z&&(Z=!1,O.call(W)))},handlePossibleChange(){},handleChange(){Z=!0}};F.addObserver(ae),F.reportChanges();let ft={dispose(){F.removeObserver(ae)}};return Jh(ft,q),ft}}de.fromObservableLight=V})(ee||={});var Vh=class i{constructor(n){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${n}_${i._idPool++}`,i.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(n){this._stopWatch=new Dn,this.listenerCount=n}stop(){if(this._stopWatch){let n=this._stopWatch.elapsed();this.durations.push(n),this.elapsedOverall+=n,this.invocationCount+=1,this._stopWatch=void 0}}},uI=-1;var jh=class i{constructor(n,e,t=(i._idPool++).toString(16).padStart(3,"0")){this._errorHandler=n;this.threshold=e;this.name=t;this._warnCountdown=0}static{this._idPool=1}dispose(){this._stacks?.clear()}check(n,e){let t=this.threshold;if(t<=0||e<t)return;this._stacks||(this._stacks=new Map);let r=this._stacks.get(n.value)||0;if(this._stacks.set(n.value,r+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=t*.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 Pu(d,l,o,e,a);this._errorHandler(c)}return()=>{let o=this._stacks.get(n.value)||0;this._stacks.set(n.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let n,e=0;for(let[t,r]of this._stacks)(!n||e<r)&&(n=[t,r],e=r);return n}},_s=class i{constructor(n){this.value=n}static create(){let n=new Error;return new i(n.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},Pu=class i extends Error{constructor(n,e,t,r,o){super(o?`[${o}] potential listener LEAK detected, ${n}`:`potential listener LEAK detected, ${n}`),this.name="ListenerLeakError",this.kind=n,this.listenerCount=r,this.details=e,this.stack=t}static is(n){return n instanceof i||n instanceof Error&&typeof n.kind=="string"&&typeof n.listenerCount=="number"}},Kh=class extends Pu{constructor(n,e,t,r,o){super(n,e,t,r,o),this.name="ListenerRefusalError"}},G0=0,Is=class{constructor(n){this.value=n;this.id=G0++}},J0=2,Y0=(i,n)=>{if(i instanceof Is)n(i);else for(let e=0;e<i.length;e++){let t=i[e];t&&n(t)}},P=class{constructor(n){this._size=0;this._options=n,this._leakageMon=uI>0||this._options?.leakWarningThreshold?new jh(n?.onListenerError??st,this._options?.leakWarningThreshold??uI,this._options?.leakWarningName):void 0,this._perfMon=this._options?._profName?new Vh(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(lI){let n=this._listeners;queueMicrotask(()=>{Y0(n,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(n,e,t)=>{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 Kh(c,`${l}. HINT: Stack shows most frequent listener (${d[1]}-times)`,d[0],this._size,this._options?.leakWarningName);return(this._options?.onListenerError||st)(u),T.None}if(this._disposed)return T.None;e&&(n=n.bind(e));let r=new Is(n),o,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=_s.create(),o=this._leakageMon.check(r.stack,this._size+1)),lI&&(r.stack=s??_s.create()),this._listeners?this._listeners instanceof Is?(this._deliveryQueue??=new Gh,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=M(()=>{o?.(),this._removeListener(r)});return Jh(a,t),a},this._event}_removeListener(n){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,t=e.indexOf(n);if(t===-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[t]=void 0;let r=this._deliveryQueue.current===this;if(this._size*J0<=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(n,e){if(!n)return;let t=this._options?.onListenerError||st;if(!t){n.value(e);return}try{n.value(e)}catch(r){t(r)}}_deliverQueue(n){let e=n.current._listeners;for(;n.i<n.end;)this._deliver(e[n.i++],n.value);n.reset()}fire(n){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Is)this._deliver(this._listeners,n);else{let e=this._deliveryQueue;e.enqueue(this,n,this._listeners.length),this._deliverQueue(e)}this._perfMon?.stop()}hasListeners(){return this._size>0}};var Gh=class{constructor(){this.i=-1;this.end=0}enqueue(n,e,t){this.i=0,this.end=t,this.current=n,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Au=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new P({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(n){let e={event:n,listener:null};return this.events.push(e),this.hasListeners&&this.hook(e),M(gs(()=>{this.hasListeners&&this.unhook(e);let r=this.events.indexOf(e);this.events.splice(r,1)}))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach(n=>this.hook(n))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach(n=>this.unhook(n))}hook(n){n.listener=n.event(e=>this.emitter.fire(e))}unhook(n){n.listener?.dispose(),n.listener=null}dispose(){this.emitter.dispose();for(let n of this.events)n.listener?.dispose();this.events=[]}};var Xl=class{constructor(){this.listening=!1;this.inputEvent=ee.None;this.inputEventListener=T.None;this.emitter=new P({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(n){this.inputEvent=n,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=n(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}};function Jh(i,n){n instanceof G?n.add(i):Array.isArray(n)&&n.push(i)}function pI(i,n){if(n instanceof G)n.delete(i);else if(Array.isArray(n)){let e=n.indexOf(i);e!==-1&&n.splice(e,1)}i.dispose()}var fI=Object.freeze(function(i,n){let e=setTimeout(i.bind(n),0);return{dispose(){clearTimeout(e)}}}),Ae;(t=>{function i(r){return r===t.None||r===t.Cancelled||r instanceof Ts?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}t.isCancellationToken=i,t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ee.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:fI})})(Ae||={});var Ts=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?fI:(this._emitter||(this._emitter=new P),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Ze=class{constructor(n){this._token=void 0;this._parentListener=void 0;this._parentListener=n&&n.onCancellationRequested(this.cancel,this)}get token(){return this._token||(this._token=new Ts),this._token}cancel(){this._token?this._token instanceof Ts&&this._token.cancel():this._token=Ae.Cancelled}dispose(n=!1){n&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof Ts&&this._token.dispose():this._token=Ae.None}};var Q0=65,X0=97,Z0=90,ek=122,_o=46,kt=47,ln=92,Wr=58,tk=63,Eu=class extends Error{constructor(n,e,t){let r;typeof e=="string"&&e.indexOf("not ")===0?(r="must not be",e=e.replace(/^not /,"")):r="must be";let o=n.indexOf(".")!==-1?"property":"argument",s=`The "${n}" ${o} ${r} of type ${e}`;s+=`. Received type ${typeof t}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function nk(i,n){if(i===null||typeof i!="object")throw new Eu(n,"Object",i)}function ct(i,n){if(typeof i!="string")throw new Eu(n,"string",i)}var dn=Cs==="win32";function ue(i){return i===kt||i===ln}function Yh(i){return i===kt}function qr(i){return i>=Q0&&i<=Z0||i>=X0&&i<=ek}function ku(i,n,e,t){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(t(l))break;l=kt}if(t(l)){if(!(s===d-1||a===1))if(a===2){if(r.length<2||o!==2||r.charCodeAt(r.length-1)!==_o||r.charCodeAt(r.length-2)!==_o){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}}n&&(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===_o&&a!==-1?++a:a=-1}return r}function rk(i){return i?`${i[0]==="."?"":"."}${i}`:""}function gI(i,n){nk(n,"pathObject");let e=n.dir||n.root,t=n.base||`${n.name||""}${rk(n.ext)}`;return e?e===n.root?`${e}${t}`:`${e}${i}${t}`:t}var he={resolve(...i){let n="",e="",t=!1;for(let r=i.length-1;r>=-1;r--){let o;if(r>=0){if(o=i[r],ct(o,`paths[${r}]`),o.length===0)continue}else n.length===0?o=Io():(o=Xe[`=${n}`]||Io(),(o===void 0||o.slice(0,2).toLowerCase()!==n.toLowerCase()&&o.charCodeAt(2)===ln)&&(o=`${n}\\`));let s=o.length,a=0,l="",d=!1,c=o.charCodeAt(0);if(s===1)ue(c)&&(a=1,d=!0);else if(ue(c))if(d=!0,ue(o.charCodeAt(1))){let u=2,p=u;for(;u<s&&!ue(o.charCodeAt(u));)u++;if(u<s&&u!==p){let m=o.slice(p,u);for(p=u;u<s&&ue(o.charCodeAt(u));)u++;if(u<s&&u!==p){for(p=u;u<s&&!ue(o.charCodeAt(u));)u++;(u===s||u!==p)&&(l=`\\\\${m}\\${o.slice(p,u)}`,a=u)}}}else a=1;else qr(c)&&o.charCodeAt(1)===Wr&&(l=o.slice(0,2),a=2,s>2&&ue(o.charCodeAt(2))&&(d=!0,a=3));if(l.length>0)if(n.length>0){if(l.toLowerCase()!==n.toLowerCase())continue}else n=l;if(t){if(n.length>0)break}else if(e=`${o.slice(a)}\\${e}`,t=d,d&&n.length>0)break}return e=ku(e,!t,"\\",ue),t?`${n}\\${e}`:`${n}${e}`||"."},normalize(i){ct(i,"path");let n=i.length;if(n===0)return".";let e=0,t,r=!1,o=i.charCodeAt(0);if(n===1)return Yh(o)?"\\":i;if(ue(o))if(r=!0,ue(i.charCodeAt(1))){let a=2,l=a;for(;a<n&&!ue(i.charCodeAt(a));)a++;if(a<n&&a!==l){let d=i.slice(l,a);for(l=a;a<n&&ue(i.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!ue(i.charCodeAt(a));)a++;if(a===n)return`\\\\${d}\\${i.slice(l)}\\`;a!==l&&(t=`\\\\${d}\\${i.slice(l,a)}`,e=a)}}}else e=1;else qr(o)&&i.charCodeAt(1)===Wr&&(t=i.slice(0,2),e=2,n>2&&ue(i.charCodeAt(2))&&(r=!0,e=3));let s=e<n?ku(i.slice(e),!r,"\\",ue):"";if(s.length===0&&!r&&(s="."),s.length>0&&ue(i.charCodeAt(n-1))&&(s+="\\"),!r&&t===void 0&&i.includes(":")){if(s.length>=2&&qr(s.charCodeAt(0))&&s.charCodeAt(1)===Wr)return`.\\${s}`;let a=i.indexOf(":");do if(a===n-1||ue(i.charCodeAt(a+1)))return`.\\${s}`;while((a=i.indexOf(":",a+1))!==-1)}return t===void 0?r?`\\${s}`:s:r?`${t}\\${s}`:`${t}${s}`},isAbsolute(i){ct(i,"path");let n=i.length;if(n===0)return!1;let e=i.charCodeAt(0);return ue(e)||n>2&&qr(e)&&i.charCodeAt(1)===Wr&&ue(i.charCodeAt(2))},join(...i){if(i.length===0)return".";let n,e;for(let o=0;o<i.length;++o){let s=i[o];ct(s,"path"),s.length>0&&(n===void 0?n=e=s:n+=`\\${s}`)}if(n===void 0)return".";let t=!0,r=0;if(typeof e=="string"&&ue(e.charCodeAt(0))){++r;let o=e.length;o>1&&ue(e.charCodeAt(1))&&(++r,o>2&&(ue(e.charCodeAt(2))?++r:t=!1))}if(t){for(;r<n.length&&ue(n.charCodeAt(r));)r++;r>=2&&(n=`\\${n.slice(r)}`)}return he.normalize(n)},relative(i,n){if(ct(i,"from"),ct(n,"to"),i===n)return"";let e=he.resolve(i),t=he.resolve(n);if(e===t||(i=e.toLowerCase(),n=t.toLowerCase(),i===n))return"";if(e.length!==i.length||t.length!==n.length){let h=e.split("\\"),y=t.split("\\");h[h.length-1]===""&&h.pop(),y[y.length-1]===""&&y.pop();let S=h.length,b=y.length,I=S<b?S:b,_;for(_=0;_<I&&h[_].toLowerCase()===y[_].toLowerCase();_++);return _===0?t:_===I?b>I?y.slice(_).join("\\"):S>I?"..\\".repeat(S-1-_)+"..":"":"..\\".repeat(S-_)+y.slice(_).join("\\")}let r=0;for(;r<i.length&&i.charCodeAt(r)===ln;)r++;let o=i.length;for(;o-1>r&&i.charCodeAt(o-1)===ln;)o--;let s=o-r,a=0;for(;a<n.length&&n.charCodeAt(a)===ln;)a++;let l=n.length;for(;l-1>a&&n.charCodeAt(l-1)===ln;)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!==n.charCodeAt(a+p))break;h===ln&&(u=p)}if(p!==c){if(u===-1)return t}else{if(d>c){if(n.charCodeAt(a+p)===ln)return t.slice(a+p+1);if(p===2)return t.slice(a+p)}s>c&&(i.charCodeAt(r+p)===ln?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)===ln)&&(m+=m.length===0?"..":"\\..");return a+=u,m.length>0?`${m}${t.slice(a,l)}`:(t.charCodeAt(a)===ln&&++a,t.slice(a,l))},toNamespacedPath(i){if(typeof i!="string"||i.length===0)return i;let n=he.resolve(i);if(n.length<=2)return i;if(n.charCodeAt(0)===ln){if(n.charCodeAt(1)===ln){let e=n.charCodeAt(2);if(e!==tk&&e!==_o)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(qr(n.charCodeAt(0))&&n.charCodeAt(1)===Wr&&n.charCodeAt(2)===ln)return`\\\\?\\${n}`;return n},dirname(i){ct(i,"path");let n=i.length;if(n===0)return".";let e=-1,t=0,r=i.charCodeAt(0);if(n===1)return ue(r)?i:".";if(ue(r)){if(e=t=1,ue(i.charCodeAt(1))){let a=2,l=a;for(;a<n&&!ue(i.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&ue(i.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!ue(i.charCodeAt(a));)a++;if(a===n)return i;a!==l&&(e=t=a+1)}}}}else qr(r)&&i.charCodeAt(1)===Wr&&(e=n>2&&ue(i.charCodeAt(2))?3:2,t=e);let o=-1,s=!0;for(let a=n-1;a>=t;--a)if(ue(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,n){n!==void 0&&ct(n,"suffix"),ct(i,"path");let e=0,t=-1,r=!0,o;if(i.length>=2&&qr(i.charCodeAt(0))&&i.charCodeAt(1)===Wr&&(e=2),n!==void 0&&n.length>0&&n.length<=i.length){if(n===i)return"";let s=n.length-1,a=-1;for(o=i.length-1;o>=e;--o){let l=i.charCodeAt(o);if(ue(l)){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===n.charCodeAt(s)?--s===-1&&(t=o):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=i.length),i.slice(e,t)}for(o=i.length-1;o>=e;--o)if(ue(i.charCodeAt(o))){if(!r){e=o+1;break}}else t===-1&&(r=!1,t=o+1);return t===-1?"":i.slice(e,t)},extname(i){ct(i,"path");let n=0,e=-1,t=0,r=-1,o=!0,s=0;i.length>=2&&i.charCodeAt(1)===Wr&&qr(i.charCodeAt(0))&&(n=t=2);for(let a=i.length-1;a>=n;--a){let l=i.charCodeAt(a);if(ue(l)){if(!o){t=a+1;break}continue}r===-1&&(o=!1,r=a+1),l===_o?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===t+1?"":i.slice(e,r)},format:gI.bind(null,"\\"),parse(i){ct(i,"path");let n={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return n;let e=i.length,t=0,r=i.charCodeAt(0);if(e===1)return ue(r)?(n.root=n.dir=i,n):(n.base=n.name=i,n);if(ue(r)){if(t=1,ue(i.charCodeAt(1))){let u=2,p=u;for(;u<e&&!ue(i.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&ue(i.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&!ue(i.charCodeAt(u));)u++;u===e?t=u:u!==p&&(t=u+1)}}}}else if(qr(r)&&i.charCodeAt(1)===Wr){if(e<=2)return n.root=n.dir=i,n;if(t=2,ue(i.charCodeAt(2))){if(e===3)return n.root=n.dir=i,n;t=3}}t>0&&(n.root=i.slice(0,t));let o=-1,s=t,a=-1,l=!0,d=i.length-1,c=0;for(;d>=t;--d){if(r=i.charCodeAt(d),ue(r)){if(!l){s=d+1;break}continue}a===-1&&(l=!1,a=d+1),r===_o?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?n.base=n.name=i.slice(s,a):(n.name=i.slice(s,o),n.base=i.slice(s,a),n.ext=i.slice(o,a))),s>0&&s!==t?n.dir=i.slice(0,s-1):n.dir=n.root,n},sep:"\\",delimiter:";",win32:null,posix:null},ik=(()=>{if(dn){let i=/\\/g;return()=>{let n=Io().replace(i,"/");return n.slice(n.indexOf("/"))}}return()=>Io()})(),re={resolve(...i){let n="",e=!1;for(let t=i.length-1;t>=0&&!e;t--){let r=i[t];ct(r,`paths[${t}]`),r.length!==0&&(n=`${r}/${n}`,e=r.charCodeAt(0)===kt)}if(!e){let t=ik();n=`${t}/${n}`,e=t.charCodeAt(0)===kt}return n=ku(n,!e,"/",Yh),e?`/${n}`:n.length>0?n:"."},normalize(i){if(ct(i,"path"),i.length===0)return".";let n=i.charCodeAt(0)===kt,e=i.charCodeAt(i.length-1)===kt;return i=ku(i,!n,"/",Yh),i.length===0?n?"/":e?"./":".":(e&&(i+="/"),n?`/${i}`:i)},isAbsolute(i){return ct(i,"path"),i.length>0&&i.charCodeAt(0)===kt},join(...i){if(i.length===0)return".";let n=[];for(let e=0;e<i.length;++e){let t=i[e];ct(t,"path"),t.length>0&&n.push(t)}return n.length===0?".":re.normalize(n.join("/"))},relative(i,n){if(ct(i,"from"),ct(n,"to"),i===n||(i=re.resolve(i),n=re.resolve(n),i===n))return"";let e=1,t=i.length,r=t-e,o=1,s=n.length-o,a=r<s?r:s,l=-1,d=0;for(;d<a;d++){let u=i.charCodeAt(e+d);if(u!==n.charCodeAt(o+d))break;u===kt&&(l=d)}if(d===a)if(s>a){if(n.charCodeAt(o+d)===kt)return n.slice(o+d+1);if(d===0)return n.slice(o+d)}else r>a&&(i.charCodeAt(e+d)===kt?l=d:d===0&&(l=0));let c="";for(d=e+l+1;d<=t;++d)(d===t||i.charCodeAt(d)===kt)&&(c+=c.length===0?"..":"/..");return`${c}${n.slice(o+l)}`},toNamespacedPath(i){return i},dirname(i){if(ct(i,"path"),i.length===0)return".";let n=i.charCodeAt(0)===kt,e=-1,t=!0;for(let r=i.length-1;r>=1;--r)if(i.charCodeAt(r)===kt){if(!t){e=r;break}}else t=!1;return e===-1?n?"/":".":n&&e===1?"//":i.slice(0,e)},basename(i,n){n!==void 0&&ct(n,"suffix"),ct(i,"path");let e=0,t=-1,r=!0,o;if(n!==void 0&&n.length>0&&n.length<=i.length){if(n===i)return"";let s=n.length-1,a=-1;for(o=i.length-1;o>=0;--o){let l=i.charCodeAt(o);if(l===kt){if(!r){e=o+1;break}}else a===-1&&(r=!1,a=o+1),s>=0&&(l===n.charCodeAt(s)?--s===-1&&(t=o):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=i.length),i.slice(e,t)}for(o=i.length-1;o>=0;--o)if(i.charCodeAt(o)===kt){if(!r){e=o+1;break}}else t===-1&&(r=!1,t=o+1);return t===-1?"":i.slice(e,t)},extname(i){ct(i,"path");let n=-1,e=0,t=-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}t===-1&&(r=!1,t=s+1),a==="."?n===-1?n=s:o!==1&&(o=1):n!==-1&&(o=-1)}return n===-1||t===-1||o===0||o===1&&n===t-1&&n===e+1?"":i.slice(n,t)},format:gI.bind(null,"/"),parse(i){ct(i,"path");let n={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return n;let e=i.charCodeAt(0)===kt,t;e?(n.root="/",t=1):t=0;let r=-1,o=0,s=-1,a=!0,l=i.length-1,d=0;for(;l>=t;--l){let c=i.charCodeAt(l);if(c===kt){if(!a){o=l+1;break}continue}s===-1&&(a=!1,s=l+1),c===_o?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?n.base=n.name=i.slice(c,s):(n.name=i.slice(c,r),n.base=i.slice(c,s),n.ext=i.slice(r,s))}return o>0?n.dir=i.slice(0,o-1):e&&(n.dir="/"),n},sep:"/",delimiter:":",win32:null,posix:null};re.win32=he.win32=he;re.posix=he.posix=re;var cn=dn?he.normalize:re.normalize,Ft=dn?he.isAbsolute:re.isAbsolute,j=dn?he.join:re.join,Mn=dn?he.resolve:re.resolve,mI=dn?he.relative:re.relative,le=dn?he.dirname:re.dirname,Te=dn?he.basename:re.basename,To=dn?he.extname:re.extname,X8=dn?he.format:re.format,hI=dn?he.parse:re.parse,Z8=dn?he.toNamespacedPath:re.toNamespacedPath,Le=dn?he.sep:re.sep,ws=dn?he.delimiter:re.delimiter;function ok(i){return i}var Du=class{constructor(n,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof n=="function"?(this._fn=n,this._computeKey=ok):(this._fn=e,this._computeKey=n.getCacheKey)}get(n){let e=this._computeKey(n);return this.lastArgKey!==e&&(this.lastArgKey=e,this.lastCache=this._fn(n)),this.lastCache}};var qe=class{constructor(n){this.executor=n;this._state=0}get hasValue(){return this._state===2}get value(){if(this._state===0){this._state=1;try{this._value=this.executor()}catch(n){this._error=n}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 CI(i){return!i||typeof i!="string"?!0:i.trim().length===0}var sk=/{(\d+)}/g;function wo(i,...n){return n.length===0?i:i.replace(sk,function(e,t){let r=parseInt(t,10);return isNaN(r)||r<0||r>=n.length?e:n[r]})}var ak=/{([^}]+)}/g;function II(i,n){return Object.keys(n).length===0?i:i.replace(ak,(e,t)=>n[t]??e)}function Cn(i){return i.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function Yn(i,n,e=gk){return i.length<=n?i:`${i.substr(0,n)}${e}`}function Qh(i,n){if(!i||!n)return i;let e=n.length,t=0;if(e===1){let r=n.charCodeAt(0);for(;t<i.length&&i.charCodeAt(t)===r;)t++}else for(;i.startsWith(n,t);)t+=e;return i.substring(t)}function Rs(i,n){if(!i||!n)return i;let e=n.length,t=i.length;if(e===1){let o=t,s=n.charCodeAt(0);for(;o>0&&i.charCodeAt(o-1)===s;)o--;return i.substring(0,o)}let r=t;for(;r>0&&i.endsWith(n,r);)r-=e;return i.substring(0,r)}function _I(i){return i.source==="^"||i.source==="^$"||i.source==="$"||i.source==="^\\s*$"?!1:!!(i.exec("")&&i.lastIndex===0)}function TI(i){let n=[],e=i.split(/(\r\n|\r|\n)/);for(let t=0;t<Math.ceil(e.length/2);t++)n.push(e[2*t]+(e[2*t+1]??""));return n}function On(i,n){return i<n?-1:i>n?1:0}function Mu(i,n,e=0,t=i.length,r=0,o=n.length){for(;e<t&&r<o;e++,r++){let l=i.charCodeAt(e),d=n.charCodeAt(r);if(l<d)return-1;if(l>d)return 1}let s=t-e,a=o-r;return s<a?-1:s>a?1:0}function Xh(i,n){return Ro(i,n,0,i.length,0,n.length)}function Ro(i,n,e=0,t=i.length,r=0,o=n.length){for(;e<t&&r<o;e++,r++){let l=i.charCodeAt(e),d=n.charCodeAt(r);if(l===d)continue;if(l>=128||d>=128)return Mu(i.toLowerCase(),n.toLowerCase(),e,t,r,o);yI(l)&&(l-=32),yI(d)&&(d-=32);let c=l-d;if(c!==0)return c}let s=t-e,a=o-r;return s<a?-1:s>a?1:0}function yI(i){return i>=97&&i<=122}function Zh(i){return i>=65&&i<=90}function zr(i,n){return i.length===n.length&&Ro(i,n)===0}function Pi(i,n){let e=n.length;return e<=i.length&&Ro(i,n,0,e)===0}function wI(i,n){let e=i.length,t=e-n.length;return t>=0&&Ro(i,n,t,e)===0}function RI(i){return 55296<=i&&i<=56319}function ey(i){return 56320<=i&&i<=57343}function xI(i,n){return(i-55296<<10)+(n-56320)+65536}var lk=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,dk=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,ck=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,uk=new RegExp("(?:"+[lk.source,dk.source,ck.source].join("|")+")","g");function PI(i){return i&&(i=i.replace(uk,"")),i}var c6=String.fromCharCode(65279);function pk(i){return!!(i&&i.length>0&&i.charCodeAt(0)===65279)}function AI(i){return pk(i)?i.substr(1):i}var vI=class i{static{this._INSTANCE=null}static getInstance(){return i._INSTANCE||(i._INSTANCE=new i),i._INSTANCE}constructor(){this._data=fk()}getGraphemeBreakType(n){if(n<32)return n===10?3:n===13?2:4;if(n<127)return 0;let e=this._data,t=e.length/3,r=1;for(;r<=t;)if(n<e[3*r])r=2*r;else if(n>e[3*r+1])r=2*r+1;else return e[3*r+2];return 0}};function fk(){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 SI=class i{constructor(n){this.confusableDictionary=n}static{this.ambiguousCharacterData=new qe(()=>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 Du(n=>{let e=n.split(",");function t(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,y]of p)m.set(h,y);return m}function o(u,p){if(!u)return p;let m=new Map;for(let[h,y]of u)p.has(h)&&m.set(h,y);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=t(s[u]);l=o(l,p)}let d=t(s._common),c=r(d,l);return new i(c)})}static getInstance(n){return i.cache.get(Array.from(n).join(","))}static{this._locales=new qe(()=>Object.keys(i.ambiguousCharacterData.value).filter(n=>!n.startsWith("_")))}static getLocales(){return i._locales.value}isAmbiguous(n){return this.confusableDictionary.has(n)}containsAmbiguousCharacter(n){for(let e=0;e<n.length;e++){let t=n.codePointAt(e);if(typeof t=="number"&&this.isAmbiguous(t))return!0}return!1}getPrimaryConfusable(n){return this.confusableDictionary.get(n)}getConfusableCodePoints(){return new Set(this.confusableDictionary.keys())}},bI=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(n){return i.getData().has(n)}static containsInvisibleCharacter(n){for(let e=0;e<n.length;e++){let t=n.codePointAt(e);if(typeof t=="number"&&(i.isInvisibleCharacter(t)||t===32))return!0}return!1}static get codePoints(){return i.getData()}},gk="\u2026";function Ai(i){return i===47||i===92}function Ou(i){return i.replace(/[\\/]/g,re.sep)}function EI(i){return i.indexOf("/")===-1&&(i=Ou(i)),/^[a-zA-Z]:(\/|$)/.test(i)&&(i="/"+i),i}function ny(i,n=re.sep){if(!i)return"";let e=i.length,t=i.charCodeAt(0);if(Ai(t)){if(Ai(i.charCodeAt(1))&&!Ai(i.charCodeAt(2))){let o=3,s=o;for(;o<e&&!Ai(i.charCodeAt(o));o++);if(s!==o&&!Ai(i.charCodeAt(o+1))){for(o+=1;o<e;o++)if(Ai(i.charCodeAt(o)))return i.slice(0,o+1).replace(/[\\/]/g,n)}}return n}else if(kI(t)&&i.charCodeAt(1)===58)return Ai(i.charCodeAt(2))?i.slice(0,2)+n:i.slice(0,2);let r=i.indexOf("://");if(r!==-1){for(r+=3;r<e;r++)if(Ai(i.charCodeAt(r)))return i.slice(0,r+1)}return""}function xs(i,n,e){let t=i===n;return!e||t?t:!i||!n?!1:zr(i,n)}function Vr(i,n,e,t=!1){let r=t?re.sep:Le;if(i===n)return!0;if(!i||!n||((i.indexOf("..")>=0||n.indexOf("..")>=0)&&(i=t?re.normalize(i):cn(i),n=t?re.normalize(n):cn(n)),n.length>i.length))return!1;if(e){if(!Pi(i,n))return!1;if(n.length===i.length)return!0;let s=n.length;return n.charAt(n.length-1)===r&&s--,i.charAt(s)===r}return n.charAt(n.length-1)!==r&&(n+=r),i.indexOf(n)===0}function kI(i){return i>=65&&i<=90||i>=97&&i<=122}function DI(i){return Q?(i=Rs(i,Le),i.endsWith(":")&&(i+=Le)):(i=Rs(i,Le),i||(i=Le)),i}function ry(i){let n=cn(i);return Q?i.length>3?!1:MI(n)&&(i.length===2||n.charCodeAt(2)===92):n===re.sep}function MI(i,n=Q){return n?kI(i.charCodeAt(0))&&i.charCodeAt(1)===58:!1}var mk="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",hk="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function OI(i,n,e=8){let t="";for(let o=0;o<e;o++){let s;o===0&&Q&&!n&&(e===3||e===4)?s=hk:s=mk,t+=s.charAt(Math.floor(Math.random()*s.length))}let r;return n?r=`${n}-${t}`:r=t,i?j(i,r):r}var vk=/^\w[\w\d+.-]*$/,Sk=/^\//,bk=/^\/\//;function Ck(i,n){if(!i.scheme&&n)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${i.authority}", path: "${i.path}", query: "${i.query}", fragment: "${i.fragment}"}`);if(i.scheme&&!vk.test(i.scheme)){let e=[...i.scheme.matchAll(/[^\w\d+.-]/gu)],t=e.length>0?` Found '${e[0][0]}' at index ${e[0].index} (${e.length} total)`:"";throw new Error(`[UriError]: Scheme contains illegal characters.${t} (len:${i.scheme.length})`)}if(i.path){if(i.authority){if(!Sk.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(bk.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 Ik(i,n){return!i&&!n?"file":i}function _k(i,n){switch(i){case"https":case"http":case"file":n?n[0]!==Qn&&(n=Qn+n):n=Qn;break}return n}var je="",Qn="/",Tk=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,v=class i{static isUri(n){return n instanceof i?!0:!n||typeof n!="object"?!1:typeof n.authority=="string"&&typeof n.fragment=="string"&&typeof n.path=="string"&&typeof n.query=="string"&&typeof n.scheme=="string"&&typeof n.fsPath=="string"&&typeof n.with=="function"&&typeof n.toString=="function"}constructor(n,e,t,r,o,s=!1){typeof n=="object"?(this.scheme=n.scheme||je,this.authority=n.authority||je,this.path=n.path||je,this.query=n.query||je,this.fragment=n.fragment||je):(this.scheme=Ik(n,s),this.authority=e||je,this.path=_k(this.scheme,t||je),this.query=r||je,this.fragment=o||je,Ck(this,s))}get fsPath(){return Zl(this,!1)}with(n){if(!n)return this;let{scheme:e,authority:t,path:r,query:o,fragment:s}=n;return e===void 0?e=this.scheme:e===null&&(e=je),t===void 0?t=this.authority:t===null&&(t=je),r===void 0?r=this.path:r===null&&(r=je),o===void 0?o=this.query:o===null&&(o=je),s===void 0?s=this.fragment:s===null&&(s=je),e===this.scheme&&t===this.authority&&r===this.path&&o===this.query&&s===this.fragment?this:new Ei(e,t,r,o,s)}static parse(n,e=!1){let t=Tk.exec(n);return t?new Ei(t[2]||je,Lu(t[4]||je),Lu(t[5]||je),Lu(t[7]||je),Lu(t[9]||je),e):new Ei(je,je,je,je,je)}static file(n){let e=je;if(Q&&(n=n.replace(/\\/g,Qn)),n[0]===Qn&&n[1]===Qn){let t=n.indexOf(Qn,2);t===-1?(e=n.substring(2),n=Qn):(e=n.substring(2,t),n=n.substring(t)||Qn)}return new Ei("file",e,n,je,je)}static from(n,e){return new Ei(n.scheme,n.authority,n.path,n.query,n.fragment,e)}static joinPath(n,...e){if(!n.path)throw new Error(`[UriError]: cannot call joinPath on URI without path: ${n.toString()}`);let t;return Q&&n.scheme==="file"?t=i.file(he.join(Zl(n,!0),...e)).path:t=re.join(n.path,...e),n.with({path:t})}toString(n=!1){return iy(this,n)}toJSON(){return this}static revive(n){if(n){if(n instanceof i)return n;{let e=new Ei(n);return e._formatted=n.external??null,e._fsPath=n._sep===FI?n.fsPath??null:null,e}}else return n}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};function UI(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 FI=Q?1:void 0,Ei=class extends v{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=Zl(this,!1)),this._fsPath}toString(e=!1){return e?iy(this,!0):(this._formatted||(this._formatted=iy(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=FI),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}},HI={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 LI(i,n,e){let t,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||n&&s===47||e&&s===91||e&&s===93||e&&s===58)r!==-1&&(t+=encodeURIComponent(i.substring(r,o)),r=-1),t!==void 0&&(t+=i.charAt(o));else{t===void 0&&(t=i.substr(0,o));let a=HI[s];a!==void 0?(r!==-1&&(t+=encodeURIComponent(i.substring(r,o)),r=-1),t+=a):r===-1&&(r=o)}}return r!==-1&&(t+=encodeURIComponent(i.substring(r))),t!==void 0?t:i}function wk(i){let n;for(let e=0;e<i.length;e++){let t=i.charCodeAt(e);t===35||t===63?(n===void 0&&(n=i.substr(0,e)),n+=HI[t]):n!==void 0&&(n+=i[e])}return n!==void 0?n:i}function Zl(i,n){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?n?e=i.path.substr(1):e=i.path[1].toLowerCase()+i.path.substr(2):e=i.path,Q&&(e=e.replace(/\//g,"\\")),e}function iy(i,n){let e=n?wk:LI,t="",{scheme:r,authority:o,path:s,query:a,fragment:l}=i;if(r&&(t+=r,t+=":"),(o||r==="file")&&(t+=Qn,t+=Qn),o){let d=o.indexOf("@");if(d!==-1){let c=o.substr(0,d);o=o.substr(d+1),d=c.lastIndexOf(":"),d===-1?t+=e(c,!1,!1):(t+=e(c.substr(0,d),!1,!1),t+=":",t+=e(c.substr(d+1),!1,!0)),t+="@"}o=o.toLowerCase(),d=o.lastIndexOf(":"),d===-1?t+=e(o,!1,!0):(t+=e(o.substr(0,d),!1,!0),t+=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)}`)}t+=e(s,!0,!1)}return a&&(t+="?",t+=e(a,!1,!1)),l&&(t+="#",t+=n?l:LI(l,!1,!1)),t}function $I(i){try{return decodeURIComponent(i)}catch{return i.length>3?i.substr(0,3)+$I(i.substr(3)):i}}var NI=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function Lu(i){return i.match(NI)?i.replace(NI,n=>$I(n)):i}var ie;(se=>(se.inMemory="inmemory",se.vscode="vscode",se.internal="private",se.walkThrough="walkThrough",se.walkThroughSnippet="walkThroughSnippet",se.http="http",se.https="https",se.file="file",se.mailto="mailto",se.untitled="untitled",se.data="data",se.command="command",se.vscodeRemote="vscode-remote",se.vscodeRemoteResource="vscode-remote-resource",se.vscodeManagedRemoteResource="vscode-managed-remote-resource",se.vscodeUserData="vscode-userdata",se.vscodeCustomEditor="vscode-custom-editor",se.vscodeNotebookCell="vscode-notebook-cell",se.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",se.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",se.vscodeNotebookCellOutput="vscode-notebook-cell-output",se.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",se.vscodeNotebookMetadata="vscode-notebook-metadata",se.vscodeInteractiveInput="vscode-interactive-input",se.vscodeSettings="vscode-settings",se.vscodeWorkspaceTrust="vscode-workspace-trust",se.vscodeTerminal="vscode-terminal",se.vscodeImageCarousel="vscode-image-carousel",se.vscodeChatCodeBlock="vscode-chat-code-block",se.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",se.vscodeChatEditor="vscode-chat-editor",se.vscodeChatInput="chatSessionInput",se.vscodeLocalChatSession="vscode-chat-session",se.webviewPanel="webview-panel",se.vscodeWebview="vscode-webview",se.vscodeBrowser="vscode-browser",se.extension="extension",se.vscodeFileResource="vscode-file",se.tmp="tmp",se.vsls="vsls",se.vscodeSourceControl="vscode-scm",se.commentsInput="comment",se.codeSetting="code-setting",se.outputChannel="output",se.accessibleView="accessible-view",se.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",se.chatEditingModel="chat-editing-text-model",se.copilotPr="copilot-pr"))(ie||={});var ly="tkn",sy=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(n){this._preferredWebSchema=n}setDelegate(n){this._delegate=n}setServerRootPath(n,e){this._serverRootPath=re.join(e??"/",xk(n))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return re.join(this._serverRootPath,ie.vscodeRemoteResource)}set(n,e,t){this._hosts[n]=e,this._ports[n]=t}setConnectionToken(n,e){this._connectionTokens[n]=e}getPreferredWebSchema(){return this._preferredWebSchema}rewrite(n){if(this._delegate)try{return this._delegate(n)}catch(a){return AC(a),n}let e=n.authority,t=this._hosts[e];t&&t.indexOf(":")!==-1&&t.indexOf("[")===-1&&(t=`[${t}]`);let r=this._ports[e],o=this._connectionTokens[e],s=`path=${encodeURIComponent(n.path)}`;return typeof o=="string"&&(s+=`&${ly}=${encodeURIComponent(o)}`),v.from({scheme:Zt?this._preferredWebSchema:ie.vscodeRemoteResource,authority:`${t}:${r}`,path:Zt?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},Rk=new sy;function xk(i){return`${i.quality??"oss"}-${i.commit??"dev"}`}var WI="vs/../../node_modules",qI="vs/../../node_modules.asar";var dy="vscode-app",ay=class i{static{this.FALLBACK_AUTHORITY=dy}asBrowserUri(n){let e=this.toUri(n);return this.uriToBrowserUri(e)}uriToBrowserUri(n){return n.scheme===ie.vscodeRemote?Rk.rewrite(n):n.scheme===ie.file&&(tI||nI===`${ie.vscodeFileResource}://${i.FALLBACK_AUTHORITY}`)?n.with({scheme:ie.vscodeFileResource,authority:n.authority||i.FALLBACK_AUTHORITY,query:null,fragment:null}):n}asFileUri(n){let e=this.toUri(n);return this.uriToFileUri(e)}uriToFileUri(n){return n.scheme===ie.vscodeFileResource?n.with({scheme:ie.file,authority:n.authority!==i.FALLBACK_AUTHORITY?n.authority:null,query:null,fragment:null}):n}toUri(n){if(v.isUri(n))return n;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return v.joinPath(v.parse(e,!0),n);let t=j(e,n);return v.file(t)}throw new Error("Cannot determine URI for module id!")}},Dt=new ay,_6=Object.freeze({"Cache-Control":"no-cache, no-store"}),T6=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),Pk;(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 t(s){let a;typeof s=="string"?a=new URL(s).searchParams:s instanceof URL?a=s.searchParams:v.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return i.get(l)}o.getHeadersFromQuery=t;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})(Pk||={});function jr(i){return Zl(i,!0)}var xo=class{constructor(n){this._ignorePathCasing=n}compare(n,e,t=!1){return n===e?0:On(this.getComparisonKey(n,t),this.getComparisonKey(e,t))}isEqual(n,e,t=!1){return n===e?!0:!n||!e?!1:this.getComparisonKey(n,t)===this.getComparisonKey(e,t)}getComparisonKey(n,e=!1){return n.with({path:this._ignorePathCasing(n)?n.path.toLowerCase():void 0,fragment:e?null:void 0}).toString()}ignorePathCasing(n){return this._ignorePathCasing(n)}isEqualOrParent(n,e,t=!1){if(n.scheme===e.scheme){if(n.scheme===ie.file)return Vr(jr(n),jr(e),this._ignorePathCasing(n))&&n.query===e.query&&(t||n.fragment===e.fragment);if(BI(n.authority,e.authority))return Vr(n.path,e.path,this._ignorePathCasing(n),!0)&&n.query===e.query&&(t||n.fragment===e.fragment)}return!1}joinPath(n,...e){return v.joinPath(n,...e)}basenameOrAuthority(n){return pe(n)||n.authority}basename(n,e){return re.basename(n.path,e)}extname(n){return re.extname(n.path)}dirname(n){if(n.path.length===0)return n;let e;return n.scheme===ie.file?e=v.file(le(jr(n))).path:(e=re.dirname(n.path),n.authority&&e.length&&e.charCodeAt(0)!==47&&(console.error(`dirname("${n.toString})) resulted in a relative path`),e="/")),n.with({path:e})}normalizePath(n){if(!n.path.length)return n;let e;return n.scheme===ie.file?e=v.file(cn(jr(n))).path:e=re.normalize(n.path),n.with({path:e})}relativePath(n,e){if(n.scheme!==e.scheme||!BI(n.authority,e.authority))return;if(n.scheme===ie.file){let o=mI(jr(n),jr(e));return Q?Ou(o):o}let t=n.path||"/",r=e.path||"/";if(this._ignorePathCasing(n)){let o=0;for(let s=Math.min(t.length,r.length);o<s&&!(t.charCodeAt(o)!==r.charCodeAt(o)&&t.charAt(o).toLowerCase()!==r.charAt(o).toLowerCase());o++);t=r.substr(0,o)+t.substr(o)}return re.relative(t,r)}resolvePath(n,e){if(n.scheme===ie.file){let t=v.file(Mn(jr(n),e));return n.with({authority:t.authority,path:t.path})}return e=EI(e),n.with({path:re.resolve(n.path,e)})}isAbsolutePath(n){return!!n.path&&n.path[0]==="/"}isEqualAuthority(n,e){return n===e||n!==void 0&&e!==void 0&&zr(n,e)}hasTrailingPathSeparator(n,e=Le){if(n.scheme===ie.file){let t=jr(n);return t.length>ny(t).length&&t[t.length-1]===e}else{let t=n.path;return t.length>1&&t.charCodeAt(t.length-1)===47&&!/^[a-zA-Z]:(\/$|\\$)/.test(n.fsPath)}}removeTrailingPathSeparator(n,e=Le){return zI(n,e)?n.with({path:n.path.substr(0,n.path.length-1)}):n}addTrailingPathSeparator(n,e=Le){let t=!1;if(n.scheme===ie.file){let r=jr(n);t=r!==void 0&&r.length===ny(r).length&&r[r.length-1]===e}else{e="/";let r=n.path;t=r.length===1&&r.charCodeAt(r.length-1)===47}return!t&&!zI(n,e)?n.with({path:n.path+"/"}):n}},ge=new xo(()=>!1),rt=new xo(i=>i.scheme===ie.file?!Oe:!0),cy=new xo(i=>!0),gr=ge.isEqual.bind(ge),Kr=ge.isEqualOrParent.bind(ge),k6=ge.getComparisonKey.bind(ge),D6=ge.basenameOrAuthority.bind(ge),pe=ge.basename.bind(ge),ed=ge.extname.bind(ge),In=ge.dirname.bind(ge),te=ge.joinPath.bind(ge),_n=ge.normalizePath.bind(ge),Gr=ge.relativePath.bind(ge),M6=ge.resolvePath.bind(ge),VI=ge.isAbsolutePath.bind(ge),BI=ge.isEqualAuthority.bind(ge),zI=ge.hasTrailingPathSeparator.bind(ge),O6=ge.removeTrailingPathSeparator.bind(ge),L6=ge.addTrailingPathSeparator.bind(ge);var Ak;(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})(Ak||={});var jI=Symbol("MicrotaskDelay");function Bu(i){return!!i&&typeof i.then=="function"}function Mi(i){let n=new Ze,e=i(n.token),t=!1,r=new Promise((o,s)=>{let a=n.token.onCancellationRequested(()=>{t=!0,a.dispose(),s(new Y)});Promise.resolve(e).then(l=>{a.dispose(),n.dispose(),t?bs(l)&&l.dispose():o(l)},l=>{a.dispose(),n.dispose(),s(l)})});return new class{cancel(){n.cancel(),n.dispose()}then(o,s){return r.then(o,s)}catch(o){return this.then(void 0,o)}finally(o){return r.finally(o)}}}function zu(i,n){return new Promise((e,t)=>{let r=n.onCancellationRequested(()=>{r.dispose(),t(new Y)});i.then(e,t).finally(()=>r.dispose())})}function JI(i){let n=-1,e=i.map((r,o)=>r.then(s=>(n=o,s))),t=Promise.race(e);return t.cancel=()=>{i.forEach((r,o)=>{o!==n&&r.cancel&&r.cancel()})},t.finally(()=>{t.cancel()}),t}function YI(i,n,e){let t,r=setTimeout(()=>{t?.(void 0),e?.()},n);return Promise.race([i.finally(()=>clearTimeout(r)),new Promise(o=>t=o)])}var Uu=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new Ze}queue(n){if(this.cancellationTokenSource.token.isCancellationRequested)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=n,!this.queuedPromise){let e=()=>{if(this.queuedPromise=null,this.cancellationTokenSource.token.isCancellationRequested)return;let t=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,t};this.queuedPromise=new Promise(t=>{this.activePromise.then(e,e).then(t)})}return new Promise((e,t)=>{this.queuedPromise.then(e,t)})}return this.activePromise=n(this.cancellationTokenSource.token),new Promise((e,t)=>{this.activePromise.then(r=>{this.activePromise=null,e(r)},r=>{this.activePromise=null,t(r)})})}dispose(){this.cancellationTokenSource.cancel()}};var Fu=class{constructor(){this.throttlers=new Map}queue(n,e){let t=this.throttlers.get(n);return t||(t={throttler:new Uu,count:0},this.throttlers.set(n,t)),t.count++,t.throttler.queue(e).finally(()=>{--t.count===0&&(t.throttler.dispose(),this.throttlers.delete(n))})}dispose(){for(let{throttler:n}of this.throttlers.values())n.dispose();this.throttlers.clear()}},at=class{constructor(){this.promiseMap=new Map}queue(n,e){let r=(this.promiseMap.get(n)??Promise.resolve()).catch(()=>{}).then(e).finally(()=>{this.promiseMap.get(n)===r&&this.promiseMap.delete(n)});return this.promiseMap.set(n,r),r}peek(n){return this.promiseMap.get(n)||void 0}keys(){return this.promiseMap.keys()}},kk=(i,n)=>{let e=!0,t=setTimeout(()=>{e=!1,n()},i);return{isTriggered:()=>e,dispose:()=>{clearTimeout(t),e=!1}}},Dk=i=>{let n=!0;return queueMicrotask(()=>{n&&(n=!1,i())}),{isTriggered:()=>n,dispose:()=>{n=!1}}},Po=class{constructor(n){this.defaultDelay=n;this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(n,e=this.defaultDelay){this.task=n,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 t=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=e===jI?Dk(t):kk(e,t),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new Y),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},Ao=class{constructor(n){this.delayer=new Po(n),this.throttler=new Uu}trigger(n,e){return this.delayer.trigger(()=>this.throttler.queue(n),e)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}},Hu=class{constructor(){this._isOpen=!1,this._promise=new Promise((n,e)=>{this._completePromise=n})}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}};function Tn(i,n){return n?new Promise((e,t)=>{let r=setTimeout(()=>{o.dispose(),e()},i),o=n.onCancellationRequested(()=>{clearTimeout(r),o.dispose(),t(new Y)})}):Mi(e=>Tn(i,e))}function Kt(i,n=0,e){let t=setTimeout(()=>{i(),e&&r.dispose()},n),r=M(()=>{clearTimeout(t),e?.delete(r)});return e?.add(r),r}var J6=2**31-1;var Ps=class{constructor(n){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=n,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new P}whenIdle(){return this.size>0?ee.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(n){if(this._isDisposed)throw new Error("Object has been disposed");return this._size++,new Promise((e,t)=>{this.outstandingPromises.push({factory:n,c:e,e:t}),this.consume()})}consume(){for(;this.outstandingPromises.length&&this.runningPromises<this.maxDegreeOfParalellism;){let n=this.outstandingPromises.shift();this.runningPromises++;let e=n.factory();e.then(n.c,n.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()}},ki=class extends Ps{constructor(){super(1)}};var As=class{constructor(){this.queues=new Map;this.drainers=new Set;this.drainListeners=void 0;this.drainListenerCount=0}async whenDrained(){if(this.isDrained())return;let n=new Ee;return this.drainers.add(n),n.p}isDrained(){for(let[,n]of this.queues)if(n.size>0)return!1;return!0}queueSize(n,e=ge){let t=e.getComparisonKey(n);return this.queues.get(t)?.size??0}queueFor(n,e,t=ge){let r=t.getComparisonKey(n),o=this.queues.get(r);if(!o){o=new ki;let s=this.drainListenerCount++,a=ee.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 Re),this.drainListeners.set(s,a),this.queues.set(r,o)}return o.queue(e)}onDidQueueDrain(){this.isDrained()&&this.releaseDrainers()}releaseDrainers(){for(let n of this.drainers)n.complete();this.drainers.clear()}dispose(){for(let[,n]of this.queues)n.dispose();this.queues.clear(),this.releaseDrainers(),this.drainListeners?.dispose()}};var $u=class{constructor(n,e){this._isDisposed=!1;this._token=void 0,typeof n=="function"&&typeof e=="number"&&this.setIfNotSet(n,e)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==void 0&&(clearTimeout(this._token),this._token=void 0)}cancelAndSet(n,e){if(this._isDisposed)throw new $e("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=void 0,n()},e)}setIfNotSet(n,e){if(this._isDisposed)throw new $e("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===void 0&&(this._token=setTimeout(()=>{this._token=void 0,n()},e))}};var Di=class{constructor(n,e){this.timeoutToken=void 0,this.runner=n,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(n=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,n)}get delay(){return this.timeout}set delay(n){this.timeout=n}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 Wu=class extends Di{constructor(e,t){super(e,t);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()}},Es=class extends T{constructor(e,t){super();this.options=e;this.handler=t;this.pendingWork=[];this.throttler=this._register(new At);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 t=Date.now()-this.lastExecutionTime;return!this.throttler.value&&(!this.options.waitThrottleDelayBetweenWorkUnits||t>=this.options.throttleDelay)?this.doWork():!this.throttler.value&&this.options.waitThrottleDelayBetweenWorkUnits&&this.scheduleThrottler(Math.max(this.options.throttleDelay-t,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 Di(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},Mk,Nu;(function(){let i=globalThis;typeof i.requestIdleCallback!="function"||typeof i.cancelIdleCallback!="function"?Nu=(n,e,t)=>{rI(()=>{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)}}}:Nu=(n,e,t)=>{let r=n.requestIdleCallback(e,typeof t=="number"?{timeout:t}:void 0),o=!1;return{dispose(){o||(o=!0,n.cancelIdleCallback(r))}}},Mk=(n,e)=>Nu(globalThis,n,e)})();var uy=class{constructor(n,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(t){this._error=t}finally{this._didRun=!0}},this._handle=Nu(n,()=>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}},qu=class extends uy{constructor(n){super(globalThis,n)}};async function QI(i,n,e){let t;for(let r=0;r<e;r++)try{return await i()}catch(o){t=o,await Tn(n)}throw t}var Ee=class i{static fromPromise(n){let e=new i;return e.settleWith(n),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((n,e)=>{this.completeCallback=n,this.errorCallback=e})}complete(n){return this.isSettled?Promise.resolve():new Promise(e=>{this.completeCallback(n),this.outcome={outcome:0,value:n},e()})}error(n){return this.isSettled?Promise.resolve():new Promise(e=>{this.errorCallback(n),this.outcome={outcome:1,value:n},e()})}settleWith(n){return n.then(e=>this.complete(e),e=>this.error(e))}cancel(){return this.error(new Y)}},Xn;(e=>{async function i(t){let r,o=await Promise.all(t.map(s=>s.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return o}e.settled=i;function n(t){return new Promise(async(r,o)=>{try{await t(r,o)}catch(s){o(s)}})}e.withAsyncBody=n})(Xn||={});var KI=class i{static fromArray(n){return new i(e=>{e.emitMany(n)})}static fromPromise(n){return new i(async e=>{e.emitMany(await n)})}static fromPromisesResolveOrder(n){return new i(async e=>{await Promise.all(n.map(async t=>e.emitOne(await t)))})}static merge(n){return new i(async e=>{await Promise.all(n.map(async t=>{for await(let r of t)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}constructor(n,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new P,queueMicrotask(async()=>{let t={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(n(t)),this.resolve()}catch(r){this.reject(r)}finally{t.emitOne=()=>{},t.emitMany=()=>{},t.reject=()=>{}}})}[Symbol.asyncIterator](){let n=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(n<this._results.length)return{done:!1,value:this._results[n++]};if(this._state===1)return{done:!0,value:void 0};await ee.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(n,e){return new i(async t=>{for await(let r of n)t.emitOne(e(r))})}map(n){return i.map(this,n)}static filter(n,e){return new i(async t=>{for await(let r of n)e(r)&&t.emitOne(r)})}filter(n){return i.filter(this,n)}static coalesce(n){return i.filter(n,e=>!!e)}coalesce(){return i.coalesce(this)}static async toPromise(n){let e=[];for await(let t of n)e.push(t);return e}toPromise(){return i.toPromise(this)}emitOne(n){this._state===0&&(this._results.push(n),this._onStateChanged.fire())}emitMany(n){this._state===0&&(this._results=this._results.concat(n),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(n){this._state===0&&(this._state=2,this._error=n,this._onStateChanged.fire())}};var py=class{constructor(){this._unsatisfiedConsumers=[];this._unconsumedValues=[]}get hasFinalValue(){return!!this._finalValue}produce(n){if(this._ensureNoFinalValue(),this._unsatisfiedConsumers.length>0){let e=this._unsatisfiedConsumers.shift();this._resolveOrRejectDeferred(e,n)}else this._unconsumedValues.push(n)}produceFinal(n){this._ensureNoFinalValue(),this._finalValue=n;for(let e of this._unsatisfiedConsumers)this._resolveOrRejectDeferred(e,n);this._unsatisfiedConsumers.length=0}_ensureNoFinalValue(){if(this._finalValue)throw new $e("ProducerConsumer: cannot produce after final value has been set")}_resolveOrRejectDeferred(n,e){e.ok?n.complete(e.value):n.error(e.error)}consume(){if(this._unconsumedValues.length>0||this._finalValue){let n=this._unconsumedValues.length>0?this._unconsumedValues.shift():this._finalValue;return n.ok?Promise.resolve(n.value):Promise.reject(n.error)}else{let n=new Ee;return this._unsatisfiedConsumers.push(n),n.p}}},GI=class i{constructor(n,e){this._onReturn=e;this._producerConsumer=new py;this._iterator={next:()=>this._producerConsumer.consume(),return:()=>(this._onReturn?.(),Promise.resolve({done:!0,value:void 0})),throw:async n=>(this._finishError(n),{done:!0,value:void 0})};queueMicrotask(async()=>{let t=n({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 t,this._finishOk()}catch(r){this._finishError(r)}})}static fromArray(n){return new i(e=>{e.emitMany(n)})}static fromPromise(n){return new i(async e=>{e.emitMany(await n)})}static fromPromisesResolveOrder(n){return new i(async e=>{await Promise.all(n.map(async t=>e.emitOne(await t)))})}static merge(n){return new i(async e=>{await Promise.all(n.map(async t=>{for await(let r of t)e.emitOne(r)}))})}static{this.EMPTY=i.fromArray([])}static map(n,e){return new i(async t=>{for await(let r of n)t.emitOne(e(r))})}static tee(n){let e,t,r=new Ee,o=async()=>{if(!(!e||!t))try{for await(let l of n)e.emitOne(l),t.emitOne(l)}catch(l){e.reject(l),t.reject(l)}finally{r.complete()}},s=new i(async l=>(e=l,o(),r.p)),a=new i(async l=>(t=l,o(),r.p));return[s,a]}map(n){return i.map(this,n)}static coalesce(n){return i.filter(n,e=>!!e)}coalesce(){return i.coalesce(this)}static filter(n,e){return new i(async t=>{for await(let r of n)e(r)&&t.emitOne(r)})}filter(n){return i.filter(this,n)}_finishOk(){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!0,value:{done:!0,value:void 0}})}_finishError(n){this._producerConsumer.hasFinalValue||this._producerConsumer.produceFinal({ok:!1,error:n})}[Symbol.asyncIterator](){return this._iterator}};function td(i){let n=i;return n?[n.on,n.pause,n.resume,n.destroy].every(e=>typeof e=="function"):!1}function Vu(i){let n=i;return n?td(n.stream)&&Array.isArray(n.buffer)&&typeof n.ended=="boolean":!1}function Jr(i,n){return new fy(i,n)}var fy=class{constructor(n,e){this.reducer=n;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(n){if(!this.state.destroyed){if(this.state.flowing)this.emitData(n);else if(this.buffer.data.push(n),typeof this.options?.highWaterMark=="number"&&this.buffer.data.length>this.options.highWaterMark)return new Promise(e=>this.pendingWritePromises.push(e))}}error(n){this.state.destroyed||(this.state.flowing?this.emitError(n):this.buffer.error.push(n))}end(n){this.state.destroyed||(typeof n<"u"&&this.write(n),this.state.flowing?(this.emitEnd(),this.destroy()):this.state.ended=!0)}emitData(n){this.listeners.data.slice(0).forEach(e=>e(n))}emitError(n){this.listeners.error.length===0?st(n):this.listeners.error.slice(0).forEach(e=>e(n))}emitEnd(){this.listeners.end.slice(0).forEach(n=>n())}on(n,e){if(!this.state.destroyed)switch(n){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(n,e){if(this.state.destroyed)return;let t;switch(n){case"data":t=this.listeners.data;break;case"end":t=this.listeners.end;break;case"error":t=this.listeners.error;break}if(t){let r=t.indexOf(e);r>=0&&t.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 n=[...this.pendingWritePromises];this.pendingWritePromises.length=0,n.forEach(e=>e())}flowErrors(){if(this.listeners.error.length>0){for(let n of this.buffer.error)this.emitError(n);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 XI(i,n){let e=[],t;for(;(t=i.read())!==null;)e.push(t);return n(e)}function ZI(i,n,e){let t=[],r;for(;(r=i.read())!==null&&t.length<e;)t.push(r);return r===null&&t.length>0?n(t):{read:()=>{if(t.length>0)return t.shift();if(typeof r<"u"){let o=r;return r=void 0,o}return i.read()}}}function ju(i,n){return new Promise((e,t)=>{let r=[];Ku(i,{onData:o=>{n&&r.push(o)},onError:o=>{n?t(o):e(void 0)},onEnd:()=>{e(n?n(r):void 0)}})})}function Ku(i,n,e){i.on("error",t=>{e?.isCancellationRequested||n.onError(t)}),i.on("end",()=>{e?.isCancellationRequested||n.onEnd()}),i.on("data",t=>{e?.isCancellationRequested||n.onData(t)})}function e_(i,n){return new Promise((e,t)=>{let r=new G,o=[],s=d=>{if(o.push(d),o.length>n)return r.dispose(),i.pause(),e({stream:i,buffer:o,ended:!1})},a=d=>(r.dispose(),t(d)),l=()=>(r.dispose(),e({stream:i,buffer:o,ended:!0}));r.add(M(()=>i.removeListener("error",a))),i.on("error",a),r.add(M(()=>i.removeListener("end",l))),i.on("end",l),r.add(M(()=>i.removeListener("data",s))),i.on("data",s)})}function t_(i){let n=!1;return{read:()=>n?null:(n=!0,i)}}function Gu(i,n,e){let t=Jr(e);return Ku(i,{onData:r=>t.write(n.data(r)),onError:r=>t.error(n.error?n.error(r):r),onEnd:()=>t.end()}),t}var nd=typeof Buffer<"u",Lk=new qe(()=>new Uint8Array(256)),gy,my,U=class i{static alloc(n){return nd?new i(Buffer.allocUnsafe(n)):new i(new Uint8Array(n))}static wrap(n){return nd&&!Buffer.isBuffer(n)&&(n=Buffer.from(n.buffer,n.byteOffset,n.byteLength)),new i(n)}static fromString(n,e){return!(e?.dontUseNodeBuffer||!1)&&nd?new i(Buffer.from(n)):(gy||(gy=new TextEncoder),new i(gy.encode(n)))}static fromByteArray(n){let e=i.alloc(n.length);for(let t=0,r=n.length;t<r;t++)e.buffer[t]=n[t];return e}static concat(n,e){if(typeof e>"u"){e=0;for(let o=0,s=n.length;o<s;o++)e+=n[o].byteLength}let t=i.alloc(e),r=0;for(let o=0,s=n.length;o<s;o++){let a=n[o];t.set(a,r),r+=a.byteLength}return t}static isNativeBuffer(n){return nd&&Buffer.isBuffer(n)}constructor(n){this.buffer=n,this.byteLength=this.buffer.byteLength}clone(){let n=i.alloc(this.byteLength);return n.set(this),n}toString(){return nd?this.buffer.toString():(my||(my=new TextDecoder(void 0,{ignoreBOM:!0})),my.decode(this.buffer))}slice(n,e){return new i(this.buffer.subarray(n,e))}set(n,e){if(n instanceof i)this.buffer.set(n.buffer,e);else if(n instanceof Uint8Array)this.buffer.set(n,e);else if(n instanceof ArrayBuffer)this.buffer.set(new Uint8Array(n),e);else if(ArrayBuffer.isView(n))this.buffer.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),e);else throw new Error("Unknown argument 'array'")}readUInt32BE(n){return Uk(this.buffer,n)}writeUInt32BE(n,e){Fk(this.buffer,n,e)}readUInt32LE(n){return Hk(this.buffer,n)}writeUInt32LE(n,e){$k(this.buffer,n,e)}readUInt8(n){return Wk(this.buffer,n)}writeUInt8(n,e){qk(this.buffer,n,e)}indexOf(n,e=0){return Nk(this.buffer,n instanceof i?n.buffer:n,e)}equals(n){return this===n?!0:this.byteLength!==n.byteLength?!1:this.buffer.every((e,t)=>e===n.buffer[t])}};function Nk(i,n,e=0){let t=n.byteLength,r=i.byteLength;if(t===0)return 0;if(t===1)return i.indexOf(n[0],e);if(t>r-e)return-1;let o=Lk.value;o.fill(n.length);for(let d=0;d<n.length;d++)o[n[d]]=n.length-d-1;let s=e+n.length-1,a=s,l=-1;for(;s<r;)if(i[s]===n[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(n.length-a,o[i[s]]),a=n.length-1;return l}function Uk(i,n){return i[n]*2**24+i[n+1]*2**16+i[n+2]*2**8+i[n+3]}function Fk(i,n,e){i[e+3]=n,n=n>>>8,i[e+2]=n,n=n>>>8,i[e+1]=n,n=n>>>8,i[e]=n}function Hk(i,n){return i[n+0]<<0>>>0|i[n+1]<<8>>>0|i[n+2]<<16>>>0|i[n+3]<<24>>>0}function $k(i,n,e){i[e+0]=n&255,n=n>>>8,i[e+1]=n&255,n=n>>>8,i[e+2]=n&255,n=n>>>8,i[e+3]=n&255}function Wk(i,n){return i[n]}function qk(i,n,e){i[e]=n}function i_(i){return XI(i,n=>U.concat(n))}function o_(i){return t_(i)}function Oi(i){return ju(i,n=>U.concat(n))}async function s_(i){return i.ended?U.concat(i.buffer):U.concat([...i.buffer,await Oi(i.stream)])}function a_(i){return Gu(i,{data:n=>typeof n=="string"?U.fromString(n):U.wrap(n)},n=>U.concat(n))}function l_(i){return Jr(n=>U.concat(n),i)}function un(i){let n=0,e=0,t=0,r=new Uint8Array(Math.floor(i.length/4*3)),o=a=>{switch(e){case 3:r[t++]=n|a,e=0;break;case 2:r[t++]=n|a>>>2,n=a<<6,e=3;break;case 1:r[t++]=n|a>>>4,n=a<<4,e=2;break;default:n=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=t;for(;e>0;)o(0);return U.wrap(r).slice(0,s)}var Bk="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",zk="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Zn({buffer:i},n=!0,e=!1){let t=e?zk:Bk,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+=t[a>>>2],r+=t[(a<<4|l>>>4)&63],r+=t[(l<<2|d>>>6)&63],r+=t[d&63]}if(o===1){let a=i[s+0];r+=t[a>>>2],r+=t[a<<4&63],n&&(r+="==")}else if(o===2){let a=i[s+0],l=i[s+1];r+=t[a>>>2],r+=t[(a<<4|l>>>4)&63],r+=t[l<<2&63],n&&(r+="=")}return r}var n_="0123456789abcdef";function Li({buffer:i}){let n="";for(let e=0;e<i.length;e++){let t=i[e];n+=n_[t>>>4],n+=n_[t&15]}return n}function hy(i){if(i.length%2!==0)throw new SyntaxError("Hex string must have an even length");let n=new Uint8Array(i.length>>1);for(let e=0;e<i.length;)n[e>>1]=r_(i,e++)<<4|r_(i,e++);return U.wrap(n)}function r_(i,n){let e=i.charCodeAt(n);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 ${n}`)}function Se(i,n,e){let t=null,r=null;if(typeof e.value=="function"?(t="value",r=e.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(t="get",r=e.get),!r)throw new Error("not supported");let o=`$memoize$${n}`;e[t]=function(...s){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,s)}),this[o]}}function rd(i,n=0){if(!i||n>200)return i;if(typeof i=="object"){switch(i.$mid){case 1:return v.revive(i);case 2:return new RegExp(i.source,i.flags);case 17:return new Date(i.source)}if(i instanceof U||i instanceof Uint8Array)return i;if(Array.isArray(i))for(let e=0;e<i.length;++e)i[e]=rd(i[e],n+1);else for(let e in i)Object.hasOwnProperty.call(i,e)&&(i[e]=rd(i[e],n+1))}return i}function Ms(i){switch(i){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Ju(i){switch(i){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function ks(i){let n=0;for(let e=0;;e+=7){let t=i.read(1);if(n|=(t.buffer[0]&127)<<e,!(t.buffer[0]&128))return n}}var Vk=Ni(0);function Ds(i,n){if(n===0){i.write(Vk);return}let e=0;for(let r=n;r!==0;r=r>>>7)e++;let t=U.alloc(e);for(let r=0;n!==0;r++)t.buffer[r]=n&127,n=n>>>7,n>0&&(t.buffer[r]|=128);i.write(t)}var id=class{constructor(n){this.buffer=n;this.pos=0}read(n){let e=this.buffer.slice(this.pos,this.pos+n);return this.pos+=e.byteLength,e}},Yu=class{constructor(){this.buffers=[]}get buffer(){return U.concat(this.buffers)}write(n){this.buffers.push(n)}dispose(){this.buffers.length=0}};function Ni(i){let n=U.alloc(1);return n.writeUInt8(i,0),n}var Eo={Undefined:Ni(0),String:Ni(1),Buffer:Ni(2),VSBuffer:Ni(3),Array:Ni(4),Object:Ni(5),Uint:Ni(6)};function od(i,n){if(typeof n>"u")i.write(Eo.Undefined);else if(typeof n=="string"){let e=U.fromString(n);i.write(Eo.String),Ds(i,e.byteLength),i.write(e)}else if(U.isNativeBuffer(n)){let e=U.wrap(n);i.write(Eo.Buffer),Ds(i,e.byteLength),i.write(e)}else if(n instanceof U)i.write(Eo.VSBuffer),Ds(i,n.byteLength),i.write(n);else if(Array.isArray(n)){i.write(Eo.Array),Ds(i,n.length);for(let e of n)od(i,e)}else if(typeof n=="number"&&(n|0)===n)i.write(Eo.Uint),Ds(i,n);else{let e=U.fromString(JSON.stringify(n));i.write(Eo.Object),Ds(i,e.byteLength),i.write(e)}}function Ls(i){switch(i.read(1).readUInt8(0)){case 0:return;case 1:return i.read(ks(i)).toString();case 2:return i.read(ks(i)).buffer;case 3:return i.read(ks(i));case 4:{let e=ks(i),t=[];for(let r=0;r<e;r++)t.push(Ls(i));return t}case 5:return JSON.parse(i.read(ks(i)).toString());case 6:return ks(i)}}var sd=class{constructor(n,e,t=null,r=1e3){this.protocol=n;this.ctx=e;this.logger=t;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(n,e){this.channels.set(n,e),setTimeout(()=>this.flushPendingRequests(n),0)}sendResponse(n){switch(n.type){case 200:{let e=this.send([n.type]);this.logger?.logOutgoing(e,0,1,Ju(n.type));return}case 201:case 202:case 204:case 203:{let e=this.send([n.type,n.id],n.data);this.logger?.logOutgoing(e,n.id,1,Ju(n.type),n.data);return}}}send(n,e=void 0){let t=new Yu;try{return od(t,n),od(t,e),this.sendBuffer(t.buffer)}finally{t.dispose()}}sendBuffer(n){try{return this.protocol.send(n),n.byteLength}catch{return 0}}onRawMessage(n){let e=new id(n),t=Ls(e),r=Ls(e),o=t[0];switch(o){case 100:return this.logger?.logIncoming(n.byteLength,t[1],1,`${Ms(o)}: ${t[2]}.${t[3]}`,r),this.onPromise({type:o,id:t[1],channelName:t[2],name:t[3],arg:r});case 102:return this.logger?.logIncoming(n.byteLength,t[1],1,`${Ms(o)}: ${t[2]}.${t[3]}`,r),this.onEventListen({type:o,id:t[1],channelName:t[2],name:t[3],arg:r});case 101:return this.logger?.logIncoming(n.byteLength,t[1],1,`${Ms(o)}`),this.disposeActiveRequest({type:o,id:t[1]});case 103:return this.logger?.logIncoming(n.byteLength,t[1],1,`${Ms(o)}`),this.disposeActiveRequest({type:o,id:t[1]})}}onPromise(n){let e=this.channels.get(n.channelName);if(!e){this.collectPendingRequest(n);return}let t=new Ze,r;try{r=e.call(this.ctx,n.name,n.arg,t.token)}catch(a){r=Promise.reject(a)}let o=n.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(n.id)});let s=M(()=>t.cancel());this.activeRequests.set(n.id,s)}onEventListen(n){let e=this.channels.get(n.channelName);if(!e){this.collectPendingRequest(n);return}let t=n.id,o=e.listen(this.ctx,n.name,n.arg)(s=>this.sendResponse({id:t,data:s,type:204}));this.activeRequests.set(n.id,o)}disposeActiveRequest(n){let e=this.activeRequests.get(n.id);e&&(e.dispose(),this.activeRequests.delete(n.id))}collectPendingRequest(n){let e=this.pendingRequests.get(n.channelName);e||(e=[],this.pendingRequests.set(n.channelName,e));let t=setTimeout(()=>{console.error(`Unknown channel: ${n.channelName}`),n.type===100&&this.sendResponse({id:n.id,data:{name:"Unknown channel",message:`Channel name '${n.channelName}' timed out after ${this.timeoutDelay}ms`,stack:void 0},type:202})},this.timeoutDelay);e.push({request:n,timeoutTimer:t})}flushPendingRequests(n){let e=this.pendingRequests.get(n);if(e){for(let t of e)switch(clearTimeout(t.timeoutTimer),t.request.type){case 100:this.onPromise(t.request);break;case 102:this.onEventListen(t.request);break}this.pendingRequests.delete(n)}}dispose(){this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),jt(this.activeRequests.values()),this.activeRequests.clear()}};var Os=class{constructor(n,e=null){this.protocol=n;this.isDisposed=!1;this.state=0;this.activeRequests=new Set;this.handlers=new Map;this.lastRequestId=0;this._onDidInitialize=new P;this.onDidInitialize=this._onDidInitialize.event;this.protocolListener=this.protocol.onMessage(t=>this.onBuffer(t)),this.logger=e}getChannel(n){let e=this;return{call(t,r,o){return e.isDisposed?Promise.reject(new Y):e.requestPromise(n,t,r,o)},listen(t,r){return e.isDisposed?ee.None:e.requestEvent(n,t,r)}}}requestPromise(n,e,t,r=Ae.None){let o=this.lastRequestId++,a={id:o,type:100,channelName:n,name:e,arg:t};if(r.isCancellationRequested)return Promise.reject(new Y);let l,d;return new Promise((u,p)=>{if(r.isCancellationRequested)return p(new Y);let m=()=>{let S=b=>{switch(b.type){case 201:this.handlers.delete(o),u(b.data);break;case 202:{this.handlers.delete(o);let I=new Error(b.data.message);I.stack=Array.isArray(b.data.stack)?b.data.stack.join(`
`):b.data.stack,I.name=b.data.name,p(I);break}case 203:this.handlers.delete(o),p(b.data);break}};this.handlers.set(o,S);try{this.sendRequest(a)}catch(b){this.handlers.delete(o),p(b)}},h=null;this.state===1?m():(h=Mi(S=>this.whenInitialized()),h.then(()=>{h=null,m()}));let y=()=>{h?(h.cancel(),h=null):this.sendRequest({id:o,type:101}),p(new Y)};l=r.onCancellationRequested(y),d={dispose:gs(()=>{y(),l.dispose()})},this.activeRequests.add(d)}).finally(()=>{l?.dispose(),this.activeRequests.delete(d)})}requestEvent(n,e,t){let r=this.lastRequestId++,s={id:r,type:102,channelName:n,name:e,arg:t},a=null,l=new P({onWillAddFirstListener:()=>{let c=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?c():(a=Mi(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(n){switch(n.type){case 100:case 102:{let e=this.send([n.type,n.id,n.channelName,n.name],n.arg);this.logger?.logOutgoing(e,n.id,0,`${Ms(n.type)}: ${n.channelName}.${n.name}`,n.arg);return}case 101:case 103:{let e=this.send([n.type,n.id]);this.logger?.logOutgoing(e,n.id,0,Ms(n.type));return}}}send(n,e=void 0){let t=new Yu;try{return od(t,n),od(t,e),this.sendBuffer(t.buffer)}finally{t.dispose()}}sendBuffer(n){try{return this.protocol.send(n),n.byteLength}catch{return 0}}onBuffer(n){let e=new id(n),t=Ls(e),r=Ls(e),o=t[0];switch(o){case 200:return this.logger?.logIncoming(n.byteLength,0,0,Ju(o)),this.onResponse({type:t[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(n.byteLength,t[1],0,Ju(o),r),this.onResponse({type:t[0],id:t[1],data:r})}}onResponse(n){if(n.type===200){this.state=1,this._onDidInitialize.fire();return}this.handlers.get(n.id)?.(n)}get onDidInitializePromise(){return ee.toPromise(this.onDidInitialize)}whenInitialized(){return this.state===1?Promise.resolve():this.onDidInitializePromise}dispose(){this.isDisposed=!0,this.protocolListener&&(this.protocolListener.dispose(),this.protocolListener=null),jt(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};w([Se],Os.prototype,"onDidInitializePromise",1);var Qu=class{constructor(n,e,t){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new P;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new P;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new G;this.disposables.add(n(({protocol:r,onDidClientDisconnect:o})=>{let s=ee.once(r.onMessage),a=new G,l=s(d=>{let c=new id(d),u=Ls(c),p=new sd(r,u,e,t),m=new Os(r,e);this.channels.forEach((y,S)=>p.registerChannel(S,y));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 n=[];return this._connections.forEach(e=>n.push(e)),n}getChannel(n,e){let t=this;return{call(r,o,s){let a;if(Kl(e)){let d=DC(t.connections.filter(e));a=d?Promise.resolve(d):ee.toPromise(ee.filter(t.onDidAddConnection,e))}else a=e.routeCall(t,r,o);let l=a.then(d=>d.channelClient.getChannel(n));return d_(l).call(r,o,s)},listen(r,o){if(Kl(e))return t.getMulticastEvent(n,e,r,o);let s=e.routeEvent(t,r,o).then(a=>a.channelClient.getChannel(n));return d_(s).listen(r,o)}}}getMulticastEvent(n,e,t,r){let o=this,s,a=new P({onWillAddFirstListener:()=>{s=new G;let l=new Au,d=new Map,c=p=>{let h=p.channelClient.getChannel(n).listen(t,r),y=l.add(h);d.set(p,y)},u=p=>{let m=d.get(p);m&&(m.dispose(),d.delete(p))};o.connections.filter(e).forEach(c),ee.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(n,e){this.channels.set(n,e);for(let t of this._connections)t.channelServer.registerChannel(n,e)}dispose(){this.disposables.dispose();for(let n of this._connections)n.channelClient.dispose(),n.channelServer.dispose();this._connections.clear(),this.channels.clear(),this._onDidAddConnection.dispose(),this._onDidRemoveConnection.dispose()}};function d_(i){return{call(n,e,t){return i.then(r=>r.call(n,e,t))},listen(n,e){let t=new Xl;return i.then(r=>t.input=r.listen(n,e)),t.event}}}function c_(i){let n=!1;return{call(e,t,r){return n?i.call(e,t,r):Tn(0).then(()=>n=!0).then(()=>i.call(e,t,r))},listen(e,t){if(n)return i.listen(e,t);let r=new Xl;return Tn(0).then(()=>n=!0).then(()=>r.input=i.listen(e,t)),r.event}}}var Ns;(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,ee.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 y=l[p];if(typeof y=="function"){if(t(p))return y.call(l,m);if(e(p))return c.set(p,ee.buffer(l[p],p,!0,void 0,s)),c.get(p)}throw new ur(`Event not found: ${p}`)}call(u,p,m){let h=l[p];if(typeof h=="function"){if(!d&&Array.isArray(m))for(let S=0;S<m.length;S++)m[S]=rd(m[S]);let y=h.apply(l,m);return y instanceof Promise||(y=Promise.resolve(y)),y}throw new ur(`Method not found: ${p}`)}}}r.fromService=i;function n(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):t(d)?function(c){return o.listen(d,c)}:e(d)?o.listen(d):async function(...c){let u;s&&!Jn(s.context)?u=[s.context,...c]:u=c;let p=await o.call(d,u);return a?p:rd(p)};throw new ur(`Property not found: ${String(d)}`)}})}r.toService=n;function e(o){return o[0]==="o"&&o[1]==="n"&&Zh(o.charCodeAt(2))}function t(o){return/^onDynamic/.test(o)&&Zh(o.charCodeAt(9))}})(Ns||={});import{fork as SD}from"child_process";function u_(i){let n=i;return n&&typeof n.type=="string"&&typeof n.severity=="string"}function jk(i){let n=[],e;try{let t=JSON.parse(i.arguments),r=t[t.length-1];r&&r.__$stack&&(t.pop(),e=r.__$stack),n.push(...t)}catch{n.push("Unable to log remote console arguments",i.arguments)}return{args:n,stack:e}}function Kk(i){if(!i)return i;let n=i.indexOf(`
`);return n===-1?i:i.substring(0,n)}function p_(i,n){let{args:e,stack:t}=jk(i),r=typeof e[0]=="string"&&e.length===1,o=Kk(t);o&&(o=`(${o.trim()})`);let s=[];if(typeof e[0]=="string"?o&&r?s=[`%c[${n}] %c${e[0]} %c${o}`,Us("blue"),Us(""),Us("grey")]:s=[`%c[${n}] %c${e[0]}`,Us("blue"),Us(""),...e.slice(1)]:s=[`%c[${n}]%`,Us("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 Us(i){return`color: ${i}`}function Ln(i){if(!i||typeof i!="object"||i instanceof RegExp)return i;let n=Array.isArray(i)?[]:{};return Object.entries(i).forEach(([e,t])=>{n[e]=t&&typeof t=="object"?Ln(t):t}),n}function f_(i){if(!i||typeof i!="object")return i;let n=[i];for(;n.length>0;){let e=n.shift();Object.freeze(e);for(let t in e)if(g_.call(e,t)){let r=e[t];typeof r=="object"&&!Object.isFrozen(r)&&!BC(r)&&n.push(r)}}return i}var g_=Object.prototype.hasOwnProperty;function ad(i,n){return yy(i,n,new Set)}function yy(i,n,e){if(Jn(i))return i;let t=n(i);if(typeof t<"u")return t;if(Array.isArray(i)){let r=[];for(let o of i)r.push(yy(o,n,e));return r}if(Qe(i)){if(e.has(i))throw new Error("Cannot clone recursive data-structure");e.add(i);let r={};for(let o in i)g_.call(i,o)&&(r[o]=yy(i[o],n,e));return e.delete(i),r}return i}function Fs(i,n,e=!0){return Qe(i)?(Qe(n)&&Object.keys(n).forEach(t=>{t in i?e&&(Qe(i[t])&&Qe(n[t])?Fs(i[t],n[t],e):i[t]=n[t]):i[t]=n[t]}),i):n}function Fe(i,n){if(i===n)return!0;if(i==null||n===null||n===void 0||typeof i!=typeof n||typeof i!="object"||Array.isArray(i)!==Array.isArray(n))return!1;let e,t;if(Array.isArray(i)){if(i.length!==n.length)return!1;for(e=0;e<i.length;e++)if(!Fe(i[e],n[e]))return!1}else{let r=[];for(t in i)r.push(t);r.sort();let o=[];for(t in n)o.push(t);if(o.sort(),!Fe(r,o))return!1;for(e=0;e<r.length;e++)if(!Fe(i[r[e]],n[r[e]]))return!1}return!0}function ld(i){let n=new Set;return JSON.stringify(i,(e,t)=>{if(Qe(t)||Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t)}return typeof t=="bigint"?`[BigInt ${t.toString()}]`:t})}function Yr(i,n){let e=n.toLowerCase(),t=Object.keys(i).find(r=>r.toLowerCase()===e);return t?i[t]:i[n]}import*as hD from"child_process";import{promises as w_}from"fs";function m_(i){i&&(delete i.DEBUG,delete i.NODE_OPTIONS,Oe&&delete i.LD_PRELOAD)}import*as oe from"fs";import{tmpdir as eD}from"os";import{promisify as cd}from"util";var Jk=new sn(1e4);function dd(i){return h_(i,"NFC",Jk)}var Yk=new sn(1e4);function Qk(i){return h_(i,"NFD",Yk)}var Xk=/[^\u0000-\u0080]/;function h_(i,n,e){if(!i)return i;let t=e.get(i);if(t)return t;let r;return Xk.test(i)?r=i.normalize(n):r=i,e.set(i,r),r}var Zk=(function(){let i=new sn(1e4),n=/[\u0300-\u036f]/g;return function(e){let t=i.get(e);if(t)return t;let r=Qk(e).replace(n,""),o=(r.length===e.length?r:e).toLowerCase();return i.set(e,o),o}})();async function S_(i,n=0,e){if(ry(i))throw new Error("rimraf - will refuse to recursively delete root");return n===0?vy(i):tD(i,e)}async function tD(i,n=OI(eD())){try{try{await oe.promises.rename(i,n)}catch(e){return e.code==="ENOENT"?void 0:vy(i)}vy(n).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function vy(i){return oe.promises.rm(i,{recursive:!0,force:!0,maxRetries:3})}async function Xu(i,n){try{return await y_(i,n)}catch(e){if(e.code==="ENOENT"&&Q&&ry(i))try{return await y_(`${i}.`,n)}catch{}throw e}}async function y_(i,n){return rD(await(n?nD(i):oe.promises.readdir(i)))}async function nD(i){try{return await oe.promises.readdir(i,{withFileTypes:!0})}catch(t){t.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",t)}let n=[],e=await Xu(i);for(let t of e){let r=!1,o=!1,s=!1;try{let a=await oe.promises.lstat(j(i,t));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)}n.push({name:t,isFile:()=>r,isDirectory:()=>o,isSymbolicLink:()=>s})}return n}function rD(i){return i.map(n=>typeof n=="string"?dt?dd(n):n:(n.name=dt?dd(n.name):n.name,n))}async function iD(i){let n=await Xu(i),e=[];for(let t of n)await en.existsDirectory(j(i,t))&&e.push(t);return e}var en;(t=>{async function i(r){let o;try{if(o=await oe.promises.lstat(r),!o.isSymbolicLink())return{stat:o}}catch{}try{return{stat:await oe.promises.stat(r),symbolicLink:o?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};if(Q&&s.code==="EACCES")try{return{stat:await oe.promises.stat(await oe.promises.readlink(r)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&o)return{stat:o,symbolicLink:{dangling:!0}};throw a}throw s}}t.stat=i;async function n(r){try{let{stat:o,symbolicLink:s}=await t.stat(r);return o.isFile()&&s?.dangling!==!0}catch{}return!1}t.existsFile=n;async function e(r){try{let{stat:o,symbolicLink:s}=await t.stat(r);return o.isDirectory()&&s?.dangling!==!0}catch{}return!1}t.existsDirectory=e})(en||={});var oD=new As;function sD(i,n,e){return oD.queueFor(v.file(i),()=>{let t=dD(e);return new Promise((r,o)=>lD(i,n,t,s=>s?o(s):r()))},rt)}var b_=!0;function aD(i){b_=i}function lD(i,n,e,t){if(!b_)return oe.writeFile(i,n,{mode:e.mode,flag:e.flag},t);oe.open(i,e.flag,e.mode,(r,o)=>{if(r)return t(r);oe.writeFile(o,n,s=>{if(s)return oe.close(o,()=>t(s));oe.fdatasync(o,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),aD(!1)),oe.close(o,l=>t(l))))})})}function dD(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 cD(i,n,e=6e4){if(i!==n)try{Q&&typeof e=="number"?await C_(i,n,Date.now(),e):await oe.promises.rename(i,n)}catch(t){if(i.toLowerCase()!==n.toLowerCase()&&t.code==="EXDEV"||i.endsWith("."))await I_(i,n,{preserveSymlinks:!1}),await S_(i,1);else throw t}}async function C_(i,n,e,t,r=0){try{return await oe.promises.rename(i,n)}catch(o){if(o.code!=="EACCES"&&o.code!=="EPERM"&&o.code!=="EBUSY")throw o;if(Date.now()-e>=t)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 en.stat(n);a.isFile()||(s=!0)}catch{}if(s)throw o}return await Tn(Math.min(100,r*10)),C_(i,n,e,t,r+1)}}async function I_(i,n,e){return __(i,n,{root:{source:i,target:n},options:e,handledSourcePaths:new Set})}var v_=511;async function __(i,n,e){if(e.handledSourcePaths.has(i))return;e.handledSourcePaths.add(i);let{stat:t,symbolicLink:r}=await en.stat(i);if(r){if(e.options.preserveSymlinks)try{return await fD(i,n,e)}catch{}if(r.dangling)return}return t.isDirectory()?uD(i,n,t.mode&v_,e):pD(i,n,t.mode&v_)}async function uD(i,n,e,t){await oe.promises.mkdir(n,{recursive:!0,mode:e});let r=await Xu(i);for(let o of r)await __(j(i,o),j(n,o),t)}async function pD(i,n,e){await oe.promises.copyFile(i,n),await oe.promises.chmod(n,e)}async function fD(i,n,e){let t=await oe.promises.readlink(i);Vr(t,e.root.source,!Oe)&&(t=j(e.root.target,t.substr(e.root.source.length+1))),await oe.promises.symlink(t,n)}async function gD(i){try{return await cd(oe.realpath)(i)}catch{let n=mD(i);return await oe.promises.access(n,oe.constants.R_OK),n}}function mD(i){return Rs(cn(i),Le)}var Ne=new class{get read(){return(i,n,e,t,r)=>new Promise((o,s)=>{oe.read(i,n,e,t,r,(a,l,d)=>a?s(a):o({bytesRead:l,buffer:d}))})}get write(){return(i,n,e,t,r)=>new Promise((o,s)=>{oe.write(i,n,e,t,r,(a,l,d)=>a?s(a):o({bytesWritten:l,buffer:d}))})}get fdatasync(){return cd(oe.fdatasync)}get open(){return cd(oe.open)}get close(){return cd(oe.close)}get ftruncate(){return cd(oe.ftruncate)}async exists(i){try{return await oe.promises.access(i),!0}catch{return!1}}get readdir(){return Xu}get readDirsInDir(){return iD}get writeFile(){return sD}get rm(){return S_}get rename(){return cD}get copy(){return I_}get realpath(){return gD}};function R_(i=Xe){return i.comspec||"cmd.exe"}function x_(i){let n=[],e=!1,t=function(r){if(e){n.push(r);return}(!i.send(r,s=>{if(s&&console.error(s),e=!1,n.length>0){let a=n.slice(0);n=[],a.forEach(l=>t(l))}})||Q)&&(e=!0)};return{send:t}}async function yD(i){if(await Ne.exists(i)){let n;try{n=await w_.stat(i)}catch(e){e.message.startsWith("EACCES")&&(n=await w_.lstat(i))}return n?!n.isDirectory():!1}return!1}async function Zu(i,n,e,t=Xe,r=yD){if(Ft(i))return await r(i)?i:void 0;if(n===void 0&&(n=Io()),le(i)!=="."){let l=j(n,i);return await r(l)?l:void 0}let s=Yr(t,"PATH");if(e===void 0&&Ve(s)&&(e=s.split(ws)),e===void 0||e.length===0){let l=j(n,i);return await r(l)?l:void 0}for(let l of e){let d;if(Ft(l)?d=j(l,i):d=j(n,l,i),Q){let u=(Yr(t,"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=j(n,i);return await r(a)?a:void 0}var ep=class extends sd{constructor(n){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:ee.fromNodeEventEmitter(process,"message",e=>U.wrap(Buffer.from(e,"base64")))},n),process.once("disconnect",()=>this.dispose())}},tp=class{constructor(n,e){this.modulePath=n;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new P;this.onDidProcessExit=this._onDidProcessExit.event;let t=e.timeout||6e4;this.disposeDelayer=new Po(t),this.child=null,this._client=null}getChannel(n){let e=this;return{call(t,r,o){return e.requestPromise(n,t,r,o)},listen(t,r){return e.requestEvent(n,t,r)}}}requestPromise(n,e,t,r=Ae.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(r.isCancellationRequested)return Promise.reject(hu());this.disposeDelayer.cancel();let o=this.getCachedChannel(n),s=Mi(d=>o.call(e,t,d)),a=r.onCancellationRequested(()=>s.cancel()),l=M(()=>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(n,e,t){if(!this.disposeDelayer)return ee.None;this.disposeDelayer.cancel();let r,o=new P({onWillAddFirstListener:()=>{r=this.getCachedChannel(n).listen(e,t)(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 n=this.options.args||[],e=Object.create(null);e.env={...Ln(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-"))),m_(e.env),this.child=SD(this.modulePath,n,e);let t=new P,o=ee.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(u_(u)){p_(u,`IPC Library: ${this.options.serverName}`);return}t.fire(U.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?x_(this.child):this.child,a=u=>this.child?.connected&&s.send(u.buffer.toString("base64")),l=t.event,d={send:a,onMessage:l};this._client=new Os(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=>jt(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(n){let e=this.channels.get(n);return e||(e=this.client.getChannel(n),this.channels.set(n,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 np(i){return!!i.parentPort}var Sy=class{constructor(n){this.port=n;this.onMessage=ee.fromNodeEventEmitter(this.port,"message",e=>e.data?U.wrap(e.data):U.alloc(0)),n.start()}send(n){this.port.postMessage(n.buffer)}disconnect(){this.port.close()}},ud=class i extends Qu{static getOnDidClientConnect(n){VC(np(process),"Electron Utility Process");let e=new P;return process.parentPort.on("message",t=>{if(n?.handledClientConnection(t))return;let r=t.ports.at(0);r&&e.fire(r)}),ee.map(e.event,t=>({protocol:new Sy(t),onDidClientDisconnect:ee.fromNodeEventEmitter(t,"close")}))}constructor(n){super(i.getOnDidClientConnect(n))}};var H=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let i=new Uint8Array(16),n=[];for(let e=0;e<256;e++)n.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 t=0,r="";return r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r+="-",r+=n[i[t++]],r+=n[i[t++]],r+="-",r+=n[i[t++]],r+=n[i[t++]],r+="-",r+=n[i[t++]],r+=n[i[t++]],r+="-",r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r+=n[i[t++]],r}})();import*as gu from"os";import*as fu from"inspector";var er;(r=>{r.serviceIds=new Map,r.DI_TARGET="$di$target",r.DI_DEPENDENCIES="$di$dependencies";function t(o){return o[r.DI_DEPENDENCIES]||[]}r.getServiceDependencies=t})(er||={});var Ie=$("instantiationService");function CD(i,n,e){n[er.DI_TARGET]===n?n[er.DI_DEPENDENCIES].push({id:i,index:e}):(n[er.DI_DEPENDENCIES]=[{id:i,index:e}],n[er.DI_TARGET]=n)}function $(i){if(er.serviceIds.has(i))return er.serviceIds.get(i);let n=function(e,t,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");CD(n,e,r)};return n.toString=()=>i,er.serviceIds.set(i,n),n}var Ke="ahp-root://",ID="ahp-root",Iy="ahp-resource-watch";function D_(i){let n={root:i.root};i.recursive&&(n.recursive=!0),i.excludes&&i.excludes.items.length>0&&(n.excludes=[...i.excludes.items]),i.includes&&i.includes.items.length>0&&(n.includes=[...i.includes.items]);let e=Zn(U.fromString(JSON.stringify(n)),!1,!0);return`${Iy}://r/${e}`}function M_(i){let n;try{n=v.parse(i)}catch{return}if(n.scheme!==Iy)return;let e=n.path.replace(/^\//,"");if(e)try{let t=JSON.parse(un(e).toString());return typeof t.root!="string"?void 0:{root:t.root,recursive:t.recursive===!0,...Array.isArray(t.excludes)?{excludes:{items:t.excludes.filter(r=>typeof r=="string")}}:{},...Array.isArray(t.includes)?{includes:{items:t.includes.filter(r=>typeof r=="string")}}:{}}}catch{return}}function O_(i){try{return v.parse(i).scheme===Iy}catch{return!1}}function Mo(i){if(i===Ke)return!0;try{return v.parse(i).scheme===ID}catch{return!1}}function Ot(i,n){return n?`${i.replace(/#/g,"%23")}#range=${n.start.line}:${n.start.character}-${n.end.line}:${n.end.character}`:i}function L_(i){if(!i.content||i.content.length===0)return[];let n=[];for(let e of i.content)me(e,{type:!0})&&e.type==="fileEdit"&&n.push(e);return n}function N_(i){if(!(!i.content||i.content.length===0)){for(let n of i.content)if(me(n,{type:!0})&&n.type==="subagent")return n}}var _D="subagent",TD=`/${_D}/`,wD=/^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;function U_(i){return typeof i=="string"?v.parse(i):i}function RD(i){let n=U_(i),e=n.path.endsWith("/")?n.path.slice(0,-1):n.path;return{parent:n,path:`${e}${TD}`}}function qs(i,n){let{parent:e,path:t}=RD(i);return e.with({path:`${t}${n}`}).toString()}function gt(i){let n=U_(i),e=wD.exec(n.path);if(e?.groups)return{parentSession:n.with({path:e.groups.parentPath}),toolCallId:e.groups.toolCallId}}function Qr(i){return gt(i)!==void 0}function F_(){return{agents:[],activeSessions:0}}function _y(i){let n={provider:i.provider,title:i.title,status:i.status,lifecycle:"creating",activeClients:[],chats:[],defaultChat:void 0};return i.activity!==void 0&&(n.activity=i.activity),i.project!==void 0&&(n.project=i.project),i.workingDirectory!==void 0&&(n.workingDirectory=i.workingDirectory),i.annotations!==void 0&&(n.annotations=i.annotations),i._meta!==void 0&&(n._meta=i._meta),n}function sp(i){return{resource:i.resource,title:i.title,status:i.status,activity:i.activity,modifiedAt:i.modifiedAt,origin:i.origin,interactivity:i.interactivity,workingDirectory:i.workingDirectory,turns:[],activeTurn:void 0}}function ap(i,n){let e={resource:n,title:i.title,status:i.status,modifiedAt:i.modifiedAt,origin:{kind:"user"}};return i.activity!==void 0&&(e.activity=i.activity),e}function H_(i){let n={resource:i.resource,title:i.title,status:i.status,modifiedAt:i.modifiedAt};return i.activity!==void 0&&(n.activity=i.activity),i.origin!==void 0&&(n.origin=i.origin),i.interactivity!==void 0&&(n.interactivity=i.interactivity),i.workingDirectory!==void 0&&(n.workingDirectory=i.workingDirectory),n}var bd="ahp-chat",$_="default";function Ty(i,n){let e=typeof i=="string"?i:i.toString(),t=Zn(U.fromString(e),!1,!0);return`${bd}://${n}/${t}`}function be(i){return Ty(i,$_)}var rp="subagent";function Cd(i){let n=typeof i=="string"?v.parse(i):i;return n.scheme===bd&&n.authority===rp}function Bs(i,n){let e=typeof i=="string"?i:i.toString(),t=Zn(U.fromString(e),!1,!0);return`${bd}://${rp}/${t}/${encodeURIComponent(n)}`}function He(i){let n;try{n=typeof i=="string"?v.parse(i):i}catch{return}if(n.scheme!==bd||!n.authority)return;let e=n.path.replace(/^\//,"");if(e)try{if(n.authority===rp){let[t,...r]=e.split("/"),o=r.join("/");return!t||!o?void 0:{session:un(t).toString(),chatId:`${rp}/${decodeURIComponent(o)}`}}return{session:un(e).toString(),chatId:n.authority}}catch{return}}function zs(i){return He(i)?.session}function fe(i){let n=zs(i);if(n===void 0)throw new Error(`Malformed AHP chat URI: ${typeof i=="string"?i:i.toString()}`);return n}function Ue(i){return He(i)?.chatId===$_}function ce(i){try{return v.parse(i).scheme===bd}catch{return!1}}function W_(i,n){return{...i,workingDirectory:n?.workingDirectory??i.workingDirectory,turns:n?.turns??[],activeTurn:n?.activeTurn,steeringMessage:n?.steeringMessage,queuedMessages:n?.queuedMessages,inputRequests:n?.inputRequests,draft:n?.draft}}var pd="git",fd="github";function Tt(i){let n=i?.[pd];if(!n||typeof n!="object"||Array.isArray(n))return;let e=n,t={};return typeof e.hasGitHubRemote=="boolean"&&(t.hasGitHubRemote=e.hasGitHubRemote),typeof e.branchName=="string"&&(t.branchName=e.branchName),typeof e.baseBranchName=="string"&&(t.baseBranchName=e.baseBranchName),typeof e.upstreamBranchName=="string"&&(t.upstreamBranchName=e.upstreamBranchName),typeof e.incomingChanges=="number"&&(t.incomingChanges=e.incomingChanges),typeof e.outgoingChanges=="number"&&(t.outgoingChanges=e.outgoingChanges),typeof e.uncommittedChanges=="number"&&(t.uncommittedChanges=e.uncommittedChanges),typeof e.githubOwner=="string"&&(t.githubOwner=e.githubOwner),typeof e.githubRepo=="string"&&(t.githubRepo=e.githubRepo),t}function lp(i,n){let e={...i};return n!==void 0?e[pd]=n:delete e[pd],Object.keys(e).length>0?e:void 0}function Ui(i){let n=i?.[fd];if(!n||typeof n!="object"||Array.isArray(n))return;let e=n,t={};return typeof e.owner=="string"&&(t.owner=e.owner),typeof e.repo=="string"&&(t.repo=e.repo),typeof e.pullRequestUrl=="string"&&(t.pullRequestUrl=e.pullRequestUrl),t}function dp(i,n){let e={...i};return n!==void 0?e[fd]=n:delete e[fd],Object.keys(e).length>0?e:void 0}var by="workspaceless",Fn="agentHost.workspaceless";function wy(i){return i?.[by]===!0}function cp(i,n){let e={...i};return n?e[by]=!0:delete e[by],Object.keys(e).length>0?e:void 0}var P_="hostBuild";function q_(i){return{version:i.version,commit:i.commit,date:i.date,quality:i.quality}}function B_(i,n){let e={...i};return n!==void 0?e[P_]=n:delete e[P_],Object.keys(e).length>0?e:void 0}var up="VSCODE_AGENT_HOST_CLAUDE_SDK_ROOT",z_="VSCODE_AGENT_HOST_CLAUDE_AGENT_ENABLED",V_="VSCODE_AGENT_HOST_CODEX_AGENT_ENABLED",j_="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED";function pp(i,n){if(i===void 0||i==="")return n;let e=i.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:n}var K_="VSCODE_AGENT_HOST_CODEX_SDK_ROOT",G_="CODEX_HOME",J_="VSCODE_AGENT_HOST_CODEX_APP_SERVER_ARGS";var Y_="agent-host/otel/agent-host-traces.db",M$=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",OtlpTracesProtocol:"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL",OtlpMetricsProtocol:"OTEL_EXPORTER_OTLP_METRICS_PROTOCOL",OtlpHeaders:"OTEL_EXPORTER_OTLP_HEADERS",CaptureContent:"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",FilePath:"COPILOT_OTEL_FILE_EXPORTER_PATH",SourceName:"COPILOT_OTEL_SOURCE_NAME",ServiceName:"OTEL_SERVICE_NAME",ResourceAttributes:"OTEL_RESOURCE_ATTRIBUTES",DbSpanExporterEnabled:"COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED"});var Q_="claude",mt={resource:"https://api.github.com",resource_name:"GitHub Copilot",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["read:user","user:email"],required:!0},Ht={resource:"https://api.github.com/repos",resource_name:"GitHub Repository",authorization_servers:["https://github.com/login/oauth"],scopes_supported:["repo"],required:!1},xD=60;function Ry(i,n){let e=i?.trim();return e?Yn(e,xD):n?.trim()||"Subagent"}var Oo;(n=>{function i(e){if(e.kind!=="subagent_started")return;let t;try{t=fe(e.chat)}catch{return}return{session:v.parse(t),chat:v.parse(Bs(t,e.toolCallId)),parent:{chat:e.chat,toolCallId:e.toolCallId},title:Ry(e.taskDescription,e.agentDisplayName)}}n.toSpawnEvent=i})(Oo||={});var L;(t=>{function i(r,o){return v.from({scheme:r,path:`/${o}`})}t.uri=i;function n(r){return(typeof r=="string"?v.parse(r):r).path.substring(1)}t.id=n;function e(r){return(typeof r=="string"?v.parse(r):r).scheme||void 0}t.provider=e})(L||={});var yr=$("agentService"),O$=$("agentHostService");function Gt(i,n){return i===n}function PD(){return(i,n)=>i===n}function xy(i,n,e){return bn(i,n,e??Gt)}function AD(i){return(n,e)=>bn(n,e,i??Gt)}function Fi(i,n){if(i===n)return!0;if(Array.isArray(i)&&Array.isArray(n)){if(i.length!==n.length)return!1;for(let e=0;e<i.length;e++)if(!Fi(i[e],n[e]))return!1;return!0}if(i&&typeof i=="object"&&n&&typeof n=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.getPrototypeOf(n)===Object.prototype){let e=i,t=n,r=Object.keys(e),o=Object.keys(t),s=new Set(o);if(r.length!==o.length)return!1;for(let a of r)if(!s.has(a)||!Fi(e[a],t[a]))return!1;return!0}return!1}function ED(){return(i,n)=>Fi(i,n)}function kD(i,n){return JSON.stringify(i)===JSON.stringify(n)}function DD(){return(i,n)=>JSON.stringify(i)===JSON.stringify(n)}function MD(){return(i,n)=>i.equals(n)}function OD(i,n,e){return i==null||n===void 0||n===null?n===i:e(i,n)}function LD(i){return(n,e)=>n==null||e===void 0||e===null?e===n:i(n,e)}var ND;(u=>(u.strict=Gt,u.strictC=PD,u.array=xy,u.arrayC=AD,u.structural=Fi,u.structuralC=ED,u.jsonStringify=kD,u.jsonStringifyC=DD,u.thisC=MD,u.ifDefined=OD,u.ifDefinedC=LD))(ND||={});var Hi=$("configurationService");function fp(i){let n=i;return n&&typeof n=="object"&&(!n.overrideIdentifier||typeof n.overrideIdentifier=="string")&&(!n.resource||n.resource instanceof v)}function X_(i){let n=i;return n&&typeof n=="object"&&(!n.overrideIdentifiers||Array.isArray(n.overrideIdentifiers))&&!n.overrideIdentifier&&(!n.resource||n.resource instanceof v)}function gp(i,n){let e=Object.create(null);for(let t in i)Py(e,t,i[t],n);return e}function Py(i,n,e,t){let r=n.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){t(`Ignoring ${n} as ${r.slice(0,a+1).join(".")} is null`);return}break;default:t(`Ignoring ${n} 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{t(`Ignoring ${n} as ${r.join(".")} is ${JSON.stringify(s)}`)}else t(`Ignoring ${n} as ${r.join(".")} is ${JSON.stringify(s)}`)}function Z_(i,n){let e=n.split(".");eT(i,e)}function eT(i,n){if(!i)return;let e=i,t=n.shift();if(n.length===0){delete e[t];return}if(Object.keys(e).indexOf(t)!==-1){let r=e[t];typeof r=="object"&&r!==null&&!Array.isArray(r)&&(eT(r,n),Object.keys(r).length===0&&delete e[t])}}function Id(i,n,e){function t(s,a){let l=s;for(let d of a){if(typeof l!="object"||l===null)return;l=l[d]}return l}let r=n.split("."),o=t(i,r);return typeof o>"u"?e:o}function tT(i){return i.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}var Hn=$("telemetryService");var B$=$("customEndpointTelemetryService");var nT="telemetry",Vs="telemetry.telemetryLevel",mp="telemetry.enableCrashReporter",_d="telemetry.enableTelemetry";var ne={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603},ye={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010,Conflict:-32011};var rT=-32700,Lo=-32603,ut=-32001,iT=-32002;var oT=-32005;var tr=-32007;function sT(i){return"method"in i&&"id"in i}function aT(i){return"method"in i&&!("id"in i)}var k=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}};function we(i){let n=Ey(i);return{protocol:i,validate:r=>{try{return n(r,""),!0}catch{return!1}},assertValid:(r,o="")=>n(r,o)}}function pn(i){return{definition:i,toProtocol(){let n={};for(let e of Object.keys(i))n[e]=i[e].protocol;return{type:"object",properties:n}},values(n){let e=n;for(let t of Object.keys(i)){let r=e[t];if(r===void 0)continue;i[t].assertValid(r,t)}return{...e}},validate(n,e){let t=i[n];return t?t.validate(e):!1},assertValid(n,e){let t=i[n];if(!t)throw new k(ne.InvalidParams,`Unknown schema key '${n}'`);t.assertValid(e,n)},validateOrDefault(n,e){let t={},r=n??{};for(let o of Object.keys(i)){let s=i[o],a=r[o];a!==void 0&&s.validate(a)?t[o]=a:Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t}}}function Ey(i){if(i.type==="object"&&i.properties){let n={};for(let t of Object.keys(i.properties))n[t]=Ey(i.properties[t]);let e=new Set(i.required??[]);return(t,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw No(r,"object",t);let o=t;for(let s of Object.keys(n)){let a=BD(r,s);if(o[s]===void 0){if(e.has(s))throw new k(ne.InvalidParams,`Missing required property at '${a}'`);continue}n[s](o[s],a)}}}if(i.type==="array"&&i.items){let n=Ey(i.items);return(e,t)=>{if(!Array.isArray(e))throw No(t,"array",e);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`)}}return qD(i)}function qD(i){let n=i.enumDynamic===!0;return(e,t)=>{switch(i.type){case"string":if(typeof e!="string")throw No(t,"string",e);break;case"number":if(typeof e!="number")throw No(t,"number",e);break;case"boolean":if(typeof e!="boolean")throw No(t,"boolean",e);break;case"array":if(!Array.isArray(e))throw No(t,"array",e);break;case"object":if(typeof e!="object"||e===null||Array.isArray(e))throw No(t,"object",e);break}if(i.enum&&!n&&!i.enum.includes(e))throw new k(ne.InvalidParams,`Invalid value at '${t||"<root>"}': ${dT(e)} is not one of [${i.enum.map(r=>JSON.stringify(r)).join(", ")}]`)}}function No(i,n,e){return new k(ne.InvalidParams,`Invalid value at '${i||"<root>"}': expected ${n}, got ${dT(e)}`)}function BD(i,n){return i?`${i}.${n}`:n}function dT(i){try{return JSON.stringify(i)}catch{return String(i)}}var cT=we({type:"object",title:f(1909,null),description:f(1913,null),properties:{allow:{type:"array",title:f(1910,null),items:{type:"string",title:f(1912,null)}},deny:{type:"array",title:f(1911,null),items:{type:"string",title:f(1912,null)}}},default:{allow:[],deny:[]},sessionMutable:!0}),Jt=pn({autoApprove:we({type:"string",title:f(1895,null),description:f(1900,null),enum:["default","autoApprove"],enumLabels:[f(1898,null),f(1896,null)],enumDescriptions:[f(1899,null),f(1897,null)],default:"default",sessionMutable:!0}),permissions:cT,mode:we({type:"string",title:f(1901,null),description:f(1908,null),enum:["interactive","plan","autopilot"],enumLabels:[f(1904,null),f(1906,null),f(1902,null)],enumDescriptions:[f(1905,null),f(1907,null),f(1903,null)],default:"interactive",sessionMutable:!0})});function uT(i){if(!i||i.autoApprove!=="autopilot")return i;let n={...i};return n.mode!=="plan"&&(n.mode="autopilot"),n.autoApprove="default",n}var Td="telemetryLevel",wd="sessionSyncEnabled",ky="codexAgentEnabled",Dy="terminalAutoApproveEnabled";var Rd="globalAutoApproveEnabled";var My="autoReplyEnabled";var Oy="terminalAutoApproveRules";var Ly="mcpServers";function pT(i){switch(i){case 0:return"off";case 1:return"crash";case 2:return"error";case 3:return"all"}}function fT(i){switch(i){case"off":return 0;case"crash":return 1;case"error":return 2;case"all":return 3;default:return}}var zD={type:{type:"string",title:f(1884,null),description:f(1883,null),enum:["stdio","http"]},command:{type:"string",title:f(1872,null),description:f(1871,null)},args:{type:"array",title:f(1870,null),description:f(1869,null),items:{type:"string",title:f(1868,null)}},env:{type:"object",title:f(1879,null),description:f(1878,null)},cwd:{type:"string",title:f(1874,null),description:f(1873,null)},url:{type:"string",title:f(1886,null),description:f(1885,null)},headers:{type:"object",title:f(1881,null),description:f(1880,null)}},VD={"<serverName>":{type:"object",title:f(1877,null),description:f(1876,null),properties:zD}},$t=pn({permissions:cT,[Td]:we({type:"string",title:f(1890,null),description:f(1889,null),enum:["all","error","crash","off"],default:"all"}),[wd]:we({type:"boolean",title:f(1888,null),description:f(1887,null),default:!1}),[ky]:we({type:"boolean",title:f(1865,null),description:f(1864,null),default:!1}),[Dy]:we({type:"boolean",title:f(1892,null),description:f(1891,null),default:!0}),[Rd]:we({type:"boolean",title:f(1867,null),description:f(1866,null),default:!1}),[My]:we({type:"boolean",title:f(1863,null),description:f(1862,null),default:!1}),[Oy]:we({type:"object",title:f(1894,null),description:f(1893,null),default:{}}),[Ly]:we({type:"object",title:f(1882,null),description:f(1875,null),properties:VD,default:{}})});function Ny(i,n){return n&&(i.stack||i.stacktrace)?f(116,null,mT(i),gT(i.stack)||gT(i.stacktrace)):mT(i)}function gT(i){return Array.isArray(i)?i.join(`
`):i}function mT(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"?f(115,null,i.message):i.message||f(113,null)}function ke(i=null,n=!1){if(!i)return f(113,null);if(Array.isArray(i)){let e=Ci(i),t=ke(e[0],n);return e.length>1?f(114,null,t,e.length):t}if(Ve(i))return i;if(i.detail){let e=i.detail;if(e.error)return Ny(e.error,n);if(e.exception)return Ny(e.exception,n)}return i.stack?Ny(i,n):i.message?i.message:f(113,null)}var dW=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 Uy={".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 yp(i){let n=To(i),e=Uy[n.toLowerCase()];return Array.isArray(e)?e[0]:e}function hT(i){for(let n in Uy){let e=Uy[n];if(Array.isArray(e)?e.includes(i):e===i)return n}}var St=class{constructor(n,e,t){this.owner=n;this.debugNameSource=e;this.referenceFn=t}getDebugName(n){return bT(n,this)}},yT=new Map,Fy=new WeakMap;function bT(i,n){let e=Fy.get(i);if(e)return e;let t=jD(i,n);if(t){let r=yT.get(t)??0;r++,yT.set(t,r);let o=r===1?t:`${t}#${r}`;return Fy.set(i,o),o}}function jD(i,n){let e=Fy.get(i);if(e)return e;let t=n.owner?GD(n.owner)+".":"",r,o=n.debugNameSource;if(o!==void 0)if(typeof o=="function"){if(r=o(),r!==void 0)return t+r}else return t+o;let s=n.referenceFn;if(s!==void 0&&(r=xd(s),r!==void 0))return t+r;if(n.owner!==void 0){let a=KD(n.owner,i);if(a!==void 0)return t+a}}function KD(i,n){for(let e in i)if(i[e]===n)return e}var vT=new Map,ST=new WeakMap;function GD(i){let n=ST.get(i);if(n)return n;let e=Hy(i)??"Object",t=vT.get(e)??0;t++,vT.set(e,t);let r=t===1?e:`${e}#${t}`;return ST.set(i,r),r}function Hy(i){let n=i.constructor;if(n)return n.name==="Object"?void 0:n.name}function xd(i){let n=i.toString(),t=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(n);return(t?t[1]:void 0)?.trim()}function $y(i){let n=new Error("BugIndicatingErrorRecovery: "+i);st(n),console.error("recovered from an error that indicates a bug",n)}var Fo;function Pd(i){Fo?Fo instanceof vp?Fo.loggers.push(i):Fo=new vp([Fo,i]):Fo=i}function Be(){return Fo}var Wy;function CT(i){Wy=i}function IT(i){Wy&&Wy(i)}var vp=class{constructor(n){this.loggers=n}handleObservableCreated(n,e){for(let t of this.loggers)t.handleObservableCreated(n,e)}handleOnListenerCountChanged(n,e){for(let t of this.loggers)t.handleOnListenerCountChanged(n,e)}handleObservableUpdated(n,e){for(let t of this.loggers)t.handleObservableUpdated(n,e)}handleAutorunCreated(n,e){for(let t of this.loggers)t.handleAutorunCreated(n,e)}handleAutorunDisposed(n){for(let e of this.loggers)e.handleAutorunDisposed(n)}handleAutorunDependencyChanged(n,e,t){for(let r of this.loggers)r.handleAutorunDependencyChanged(n,e,t)}handleAutorunStarted(n){for(let e of this.loggers)e.handleAutorunStarted(n)}handleAutorunFinished(n){for(let e of this.loggers)e.handleAutorunFinished(n)}handleDerivedDependencyChanged(n,e,t){for(let r of this.loggers)r.handleDerivedDependencyChanged(n,e,t)}handleDerivedCleared(n){for(let e of this.loggers)e.handleDerivedCleared(n)}handleBeginTransaction(n){for(let e of this.loggers)e.handleBeginTransaction(n)}handleEndTransaction(n){for(let e of this.loggers)e.handleEndTransaction(n)}};function nr(i,n){let e=new $i(i,n);try{i(e)}finally{e.finish()}}function qy(i,n,e){i?n(i):nr(n,e)}var $i=class{constructor(n,e){this._fn=n;this._getDebugName=e;this._updatingObservers=[];Be()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():xd(this._fn)}updateObserver(n,e){if(!this._updatingObservers){$y("Transaction already finished!"),nr(t=>{t.updateObserver(n,e)});return}this._updatingObservers.push({observer:n,observable:e}),n.beginUpdate(e)}finish(){let n=this._updatingObservers;if(!n){$y("transaction.finish() has already been called!");return}for(let e=0;e<n.length;e++){let{observer:t,observable:r}=n[e];t.endUpdate(r)}this._updatingObservers=null,Be()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var pt;(t=>{let i=!1;function n(){i=!0}t.enable=n;function e(){if(!i)return;let r=Error,o=r.stackTraceLimit;r.stackTraceLimit=3;let s=new Error().stack;return r.stackTraceLimit=o,By.fromStack(s,2)}t.ofCaller=e})(pt||={});var By=class i{constructor(n,e,t,r){this.fileName=n;this.line=e;this.column=t;this.id=r}static fromStack(n,e){let t=n.split(`
`),r=JD(t[e+1]);if(r)return new i(r.fileName,r.line,r.column,r.id)}};function JD(i){let n=i.match(/\((.*):(\d+):(\d+)\)/);if(n)return{fileName:n[1],line:parseInt(n[2]),column:parseInt(n[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 zy;function _T(i){zy=i}var TT;function wT(i){TT=i}var RT;function xT(i){RT=i}var Vy;function PT(i){Vy=i}var Sp=class{get TChange(){return null}reportChanges(){this.get()}read(n){return n?n.readObservable(this):this.get()}map(n,e,t=pt.ofCaller()){let r=e===void 0?void 0:n,o=e===void 0?n:e;return zy({owner:r,debugName:()=>{let s=xd(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),t)}flatten(){return zy({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},n=>this.read(n).read(n))}recomputeInitiallyAndOnChange(n,e){return n.add(TT(this,e)),this}keepObserved(n){return n.add(RT(this)),this}get debugValue(){return this.get()}get debug(){return new jy(this)}},jy=class{constructor(n){this.observable=n}getDependencyGraph(){return Vy(this.observable,{type:"dependencies"})}getObserverGraph(){return Vy(this.observable,{type:"observers"})}},$n=class extends Sp{constructor(e){super();this._observers=new Set;Be()?.handleObservableCreated(this,e)}addObserver(e){let t=this._observers.size;this._observers.add(e),t===0&&this.onFirstObserverAdded(),t!==this._observers.size&&Be()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let t=this._observers.delete(e);t&&this._observers.size===0&&this.onLastObserverRemoved(),t&&Be()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!Be();return IT(this),e||Be()?.handleObservableCreated(this,pt.ofCaller()),this}debugGetObservers(){return this._observers}};function nn(i,n,e=pt.ofCaller()){let t;return typeof i=="string"?t=new St(void 0,i,void 0):t=new St(i,void 0,void 0),new vr(t,n,Gt,e)}var vr=class extends $n{constructor(e,t,r,o){super(o);this._debugNameData=e;this._equalityComparator=r;this._value=t,Be()?.handleObservableUpdated(this,{hadValue:!1,newValue:t,change:void 0,didChange:!0,oldValue:void 0})}get debugName(){return this._debugNameData.getDebugName(this)??"ObservableValue"}get(){return this._value}set(e,t,r){if(r===void 0&&this._equalityComparator(this._value,e))return;let o;t||(t=o=new $i(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),Be()?.handleObservableUpdated(this,{oldValue:s,newValue:e,change:r,didChange:!0,hadValue:!0});for(let a of this._observers)t.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 bp=class extends $n{constructor(e,t,r,o){super(o);this._debugNameData=e;this._equalityComparator=r;this._isUpToDate=!0;this._deltas=[];this._updateCounter=0;this._value=t}get debugName(){return this._debugNameData.getDebugName(this)??"LazyObservableValue"}get(){return this._update(),this._value}_update(){if(!this._isUpToDate)if(this._isUpToDate=!0,this._deltas.length>0){for(let e of this._deltas){Be()?.handleObservableUpdated(this,{change:e,didChange:!0,oldValue:"(unknown)",newValue:this._value,hadValue:!0});for(let t of this._observers)t.handleChange(this,e)}this._deltas.length=0}else{Be()?.handleObservableUpdated(this,{change:void 0,didChange:!0,oldValue:"(unknown)",newValue:this._value,hadValue:!0});for(let e of this._observers)e.handleChange(this,void 0)}}_beginUpdate(){if(this._updateCounter++,this._updateCounter===1)for(let e of this._observers)e.beginUpdate(this)}_endUpdate(){if(this._updateCounter--,this._updateCounter===0){this._update();let e=[...this._observers];for(let t of e)t.endUpdate(this)}}addObserver(e){let t=!this._observers.has(e)&&this._updateCounter>0;super.addObserver(e),t&&e.beginUpdate(this)}removeObserver(e){let t=this._observers.has(e)&&this._updateCounter>0;super.removeObserver(e),t&&e.endUpdate(this)}set(e,t,r){if(r===void 0&&this._equalityComparator(this._value,e))return;let o;t||(t=o=new $i(()=>{},()=>`Setting ${this.debugName}`));try{if(this._isUpToDate=!1,this._setValue(e),r!==void 0&&this._deltas.push(r),t.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 Ho(i,n,e=pt.ofCaller()){return i.lazy?new bp(new St(i.owner,i.debugName,void 0),n,i.equalsFn??Gt,e):new vr(new St(i.owner,i.debugName,void 0),n,i.equalsFn??Gt,e)}function YD(i){switch(i){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var Xr=class{constructor(n,e,t,r){this._debugNameData=n;this._runFn=e;this._changeTracker=t;this._state=2;this._updateCount=0;this._disposed=!1;this._dependencies=new Set;this._dependenciesToBeRemoved=new Set;this._isRunning=!1;this._iteration=0;this._store=void 0;this._delayedStore=void 0;this._changeSummary=this._changeTracker?.createChangeSummary(void 0),Be()?.handleAutorunCreated(this,r),this._run(),Ii(this)}get debugName(){return this._debugNameData.getDebugName(this)??"(anonymous)"}dispose(){if(!this._disposed){this._disposed=!0;for(let n of this._dependencies)n.removeObserver(this);this._dependencies.clear(),this._store!==void 0&&this._store.dispose(),this._delayedStore!==void 0&&this._delayedStore.dispose(),Be()?.handleAutorunDisposed(this),_i(this)}}_run(){let n=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=n,this._state=3;try{if(!this._disposed){Be()?.handleAutorunStarted(this);let e=this._changeSummary,t=this._delayedStore;t!==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){bi(r)}finally{this._isRunning=!1,t!==void 0&&t.dispose()}}}finally{this._disposed||Be()?.handleAutorunFinished(this);for(let e of this._dependenciesToBeRemoved)e.removeObserver(this);this._dependenciesToBeRemoved.clear()}}toString(){return`Autorun<${this.debugName}>`}beginUpdate(n){this._state===3&&(this._checkIterations(),this._state=1),this._updateCount++}endUpdate(n){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--}jl(()=>this._updateCount>=0)}handlePossibleChange(n){this._state===3&&this._isDependency(n)&&(this._checkIterations(),this._state=1)}handleChange(n,e){if(this._isDependency(n)){Be()?.handleAutorunDependencyChanged(this,n,e);try{(!this._changeTracker||this._changeTracker.handleChange({changedObservable:n,change:e,didChange:r=>r===n},this._changeSummary))&&(this._checkIterations(),this._state=2)}catch(t){bi(t)}}}_isDependency(n){return this._dependencies.has(n)&&!this._dependenciesToBeRemoved.has(n)}_ensureNoRunning(){if(!this._isRunning)throw new $e("The reader object cannot be used outside its compute function!")}readObservable(n){if(this._ensureNoRunning(),this._disposed)return n.get();n.addObserver(this);let e=n.get();return this._dependencies.add(n),this._dependenciesToBeRemoved.delete(n),e}get store(){if(this._ensureNoRunning(),this._disposed)throw new $e("Cannot access store after dispose");return this._store===void 0&&(this._store=new G),this._store}get delayedStore(){if(this._ensureNoRunning(),this._disposed)throw new $e("Cannot access store after dispose");return this._delayedStore===void 0&&(this._delayedStore=new G),this._delayedStore}debugGetState(){return{isRunning:this._isRunning,updateCount:this._updateCount,dependencies:this._dependencies,state:this._state,stateStr:YD(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(bi(new $e(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function Wn(i,n=pt.ofCaller()){return new Xr(new St(void 0,void 0,i),i,void 0,n)}function QD(i){switch(i){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var bt=class extends $n{constructor(e,t,r,o=void 0,s,a){super(a);this._debugNameData=e;this._computeFn=t;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,Be()?.handleDerivedCleared(this);for(let e of this._dependencies)e.removeObserver(this);this._dependencies.clear(),this._store!==void 0&&(this._store.dispose(),this._store=void 0),this._delayedStore!==void 0&&(this._delayedStore.dispose(),this._delayedStore=void 0),this._handleLastObserverRemoved?.()}get(){if(this._isComputing,this._observers.size===0){let t;try{this._isReaderValid=!0;let r;this._changeTracker&&(r=this._changeTracker.createChangeSummary(void 0),this._changeTracker.beforeUpdate?.(this,r)),t=this._computeFn(this,r)}finally{this._isReaderValid=!1}return this.onLastObserverRemoved(),t}else{do{if(this._state===1){for(let t of this._dependencies)if(t.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 t=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=t;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),Be()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:o})}catch(r){bi(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 $e("Cyclic deriveds are not supported yet!");this._updateCount++,this._isUpdating=!0;try{let t=this._updateCount===1;if(this._state===3&&(this._state=1,!t))for(let r of this._observers)r.handlePossibleChange(this);if(t)for(let r of this._observers)r.beginUpdate(this)}finally{this._isUpdating=!1}}endUpdate(e){if(this._updateCount--,this._updateCount===0){let t=[...this._observers];for(let r of t)r.endUpdate(this);if(this._removedObserverToCallEndUpdateOn){let r=[...this._removedObserverToCallEndUpdateOn];this._removedObserverToCallEndUpdateOn=null;for(let o of r)o.endUpdate(this)}}jl(()=>this._updateCount>=0)}handlePossibleChange(e){if(this._state===3&&this._dependencies.has(e)&&!this._dependenciesToBeRemoved.has(e)){this._state=1;for(let t of this._observers)t.handlePossibleChange(this)}}handleChange(e,t){if(this._dependencies.has(e)&&!this._dependenciesToBeRemoved.has(e)||this._isInBeforeUpdate){Be()?.handleDerivedDependencyChanged(this,e,t);let r=!1;try{r=this._changeTracker?this._changeTracker.handleChange({changedObservable:e,change:t,didChange:s=>s===e},this._changeSummary):!0}catch(s){bi(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 $e("The reader object cannot be used outside its compute function!")}readObservable(e){this._ensureReaderValid(),e.addObserver(this);let t=e.get();return this._dependencies.add(e),this._dependenciesToBeRemoved.delete(e),t}reportChange(e){this._ensureReaderValid(),this._didReportChange=!0;for(let t of this._observers)t.handleChange(this,e)}get store(){return this._ensureReaderValid(),this._store===void 0&&(this._store=new G),this._store}get delayedStore(){return this._ensureReaderValid(),this._delayedStore===void 0&&(this._delayedStore=new G),this._delayedStore}addObserver(e){let t=!this._observers.has(e)&&this._updateCount>0;super.addObserver(e),t&&(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:QD(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,t,r){this._value=e;let o=this._observers;t.updateObserver(this,this);for(let s of o)s.handleChange(this,r)}};function Ad(i,n,e=pt.ofCaller()){return n!==void 0?new bt(new St(i,void 0,n),n,void 0,void 0,Gt,e):new bt(new St(void 0,void 0,i),i,void 0,void 0,Gt,e)}function Ed(i,n,e=pt.ofCaller()){return new bt(new St(i.owner,i.debugName,i.debugReferenceFn),n,void 0,i.onLastObserverRemoved,i.equalsFn??Gt,e)}_T(Ed);function $o(...i){let n,e,t,r;return i.length===2?[e,t]=i:[n,e,t,r]=i,new qn(new St(n,void 0,t),e,t,()=>qn.globalTransaction,Gt,r??pt.ofCaller())}var qn=class extends $n{constructor(e,t,r,o,s,a){super(a);this._debugNameData=e;this.event=t;this._getValue=r;this._getTransaction=o;this._equalityComparator=s;this._hasValue=!1;this.handleEvent=e=>{let t=this._getValue(e),r=this._value,o=!this._hasValue||!this._equalityComparator(r,t),s=!1;o&&(this._value=t,this._hasValue&&(s=!0,qy(this._getTransaction(),a=>{Be()?.handleObservableUpdated(this,{oldValue:r,newValue:t,change:void 0,didChange:o,hadValue:this._hasValue});for(let l of this._observers)a.updateObserver(l,this),l.handleChange(this,void 0)},()=>{let a=this.getDebugName();return"Event fired"+(a?`: ${a}`:"")})),this._hasValue=!0),s||Be()?.handleObservableUpdated(this,{oldValue:r,newValue:t,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=qn;function n(t,r){let o=!1;qn.globalTransaction===void 0&&(qn.globalTransaction=t,o=!0);try{r()}finally{o&&(qn.globalTransaction=void 0)}}e.batchEventsGlobally=n})($o||={});function AT(i){let n=new Cp(!1,void 0);return i.addObserver(n),M(()=>{i.removeObserver(n)})}xT(AT);function ET(i,n){let e=new Cp(!0,n);i.addObserver(e);try{e.beginUpdate(i)}finally{e.endUpdate(i)}return M(()=>{i.removeObserver(e)})}wT(ET);var Cp=class{constructor(n,e){this._forceRecompute=n;this._handleValue=e;this._counter=0}beginUpdate(n){this._counter++}endUpdate(n){this._counter===1&&this._forceRecompute&&(this._handleValue?this._handleValue(n.get()):n.reportChanges()),this._counter--}handlePossibleChange(n){}handleChange(n,e){}};var Ip;function kT(i){Ip||(Ip=new kd,Pd(Ip)),Ip.addFilteredObj(i)}var kd=class{constructor(){this.indentation=0;this.changedObservablesSets=new WeakMap}addFilteredObj(n){this._filteredObjects||(this._filteredObjects=new Set),this._filteredObjects.add(n)}_isIncluded(n){return this._filteredObjects?.has(n)??!0}textToConsoleArgs(n){return rM([js(sM("|  ",this.indentation)),n])}formatInfo(n){return n.hadValue?n.didChange?[js(" "),Bn(wn(n.oldValue,70),{color:"red",strikeThrough:!0}),js(" "),Bn(wn(n.newValue,60),{color:"green"})]:[js(" (unchanged)")]:[js(" "),Bn(wn(n.newValue,60),{color:"green"}),js(" (initial)")]}handleObservableCreated(n){if(n instanceof bt){let e=n;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(n,e){}handleObservableUpdated(n,e){if(this._isIncluded(n)){if(n instanceof bt){this._handleDerivedRecomputed(n,e);return}console.log(...this.textToConsoleArgs([Ks("observable value changed"),Bn(n.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(n){if(n.size!==0)return Bn(" (changed deps: "+[...n].map(e=>e.debugName).join(", ")+")",{color:"gray"})}handleDerivedDependencyChanged(n,e,t){this._isIncluded(n)&&this.changedObservablesSets.get(n)?.add(e)}_handleDerivedRecomputed(n,e){if(!this._isIncluded(n))return;let t=this.changedObservablesSets.get(n);t&&(console.log(...this.textToConsoleArgs([Ks("derived recomputed"),Bn(n.debugName,{color:"BlueViolet"}),...this.formatInfo(e),this.formatChanges(t),{data:[{fn:n._debugNameData.referenceFn??n._computeFn}]}])),t.clear())}handleDerivedCleared(n){this._isIncluded(n)&&console.log(...this.textToConsoleArgs([Ks("derived cleared"),Bn(n.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(n,e){this._isIncluded(n)&&console.log(...this.textToConsoleArgs([Ks("observable from event triggered"),Bn(n.debugName,{color:"BlueViolet"}),...this.formatInfo(e),{data:[{fn:n._getValue}]}]))}handleAutorunCreated(n){this._isIncluded(n)&&this.changedObservablesSets.set(n,new Set)}handleAutorunDisposed(n){}handleAutorunDependencyChanged(n,e,t){this._isIncluded(n)&&this.changedObservablesSets.get(n).add(e)}handleAutorunStarted(n){let e=this.changedObservablesSets.get(n);e&&(this._isIncluded(n)&&console.log(...this.textToConsoleArgs([Ks("autorun"),Bn(n.debugName,{color:"BlueViolet"}),this.formatChanges(e),{data:[{fn:n._debugNameData.referenceFn??n._runFn}]}])),e.clear(),this.indentation++)}handleAutorunFinished(n){this.indentation--}handleBeginTransaction(n){let e=n.getDebugName();e===void 0&&(e=""),this._isIncluded(n)&&console.log(...this.textToConsoleArgs([Ks("transaction"),Bn(e,{color:"BlueViolet"}),{data:[{fn:n._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function rM(i){let n=new Array,e=[],t="";function r(s){if("length"in s)for(let a of s)a&&r(a);else"text"in s?(t+=`%c${s.text}`,n.push(s.style),s.data&&e.push(...s.data)):"data"in s&&e.push(...s.data)}r(i);let o=[t,...n];return o.push(...e),o}function js(i){return Bn(i,{color:"black"})}function Ks(i){return Bn(aM(`${i}: `,10),{color:"black",bold:!0})}function Bn(i,n={color:"black"}){function e(r){return Object.entries(r).reduce((o,[s,a])=>`${o}${s}:${a};`,"")}let t={color:n.color};return n.strikeThrough&&(t["text-decoration"]="line-through"),n.bold&&(t["font-weight"]="bold"),{text:i,style:e(t)}}function wn(i,n){switch(typeof i){case"number":return""+i;case"string":return i.length+2<=n?`"${i}"`:`"${i.substr(0,n-7)}"+...`;case"boolean":return i?"true":"false";case"undefined":return"undefined";case"object":return i===null?"null":Array.isArray(i)?iM(i,n):oM(i,n);case"symbol":return i.toString();case"function":return`[[Function${i.name?" "+i.name:""}]]`;default:return""+i}}function iM(i,n){let e="[ ",t=!0;for(let r of i){if(t||(e+=", "),e.length-5>n){e+="...";break}t=!1,e+=`${wn(r,n-e.length)}`}return e+=" ]",e}function oM(i,n){if(typeof i.toString=="function"&&i.toString!==Object.prototype.toString){let o=i.toString();return o.length<=n?o:o.substring(0,n-3)+"..."}let e=Hy(i),t=e?e+"(":"{ ",r=!0;for(let[o,s]of Object.entries(i)){if(r||(t+=", "),t.length-5>n){t+="...";break}r=!1,t+=`${o}: ${wn(s,n-t.length)}`}return t+=e?")":" }",t}function sM(i,n){let e="";for(let t=1;t<=n;t++)e+=i;return e}function aM(i,n){for(;i.length<n;)i+=" ";return i}var _p=class i{constructor(n,e){this._channelFactory=n;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 t=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:t}}static createHost(n,e){return new i(n,e)}static createClient(n,e){return new i(n,e)}};function DT(i,n){let e=globalThis,t=[],r,{channel:o,handler:s}=lM({sendNotification:l=>{r?r.sendNotification(l):t.push(l)}}),a;return(e.$$debugValueEditor_debugChannels??(e.$$debugValueEditor_debugChannels={}))[i]=l=>{a=n(),r=l;for(let d of t)l.sendNotification(d);return t=[],s},_p.createClient(o,()=>{if(!a)throw new Error("Not supported");return a})}function lM(i){let n;return{channel:t=>(n=t,{sendNotification:r=>{i.sendNotification(r)},sendRequest:r=>{throw new Error("not supported")}}),handler:{handleRequest:t=>t.type==="notification"?n?.handleNotification(t.data):n?.handleRequest(t.data)}}}var Tp=class{constructor(){this._timeout=void 0}throttle(n,e){this._timeout===void 0&&(this._timeout=setTimeout(()=>{this._timeout=void 0,n()},e))}dispose(){this._timeout!==void 0&&clearTimeout(this._timeout)}};function Ky(i,n){for(let e in n)i[e]&&typeof i[e]=="object"&&n[e]&&typeof n[e]=="object"?Ky(i[e],n[e]):i[e]=n[e]}function Gy(i,n){for(let e in n)n[e]===null?delete i[e]:i[e]&&typeof i[e]=="object"&&n[e]&&typeof n[e]=="object"?Gy(i[e],n[e]):i[e]=n[e]}var wp=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=DT("observableDevTools",()=>({notifications:{setDeclarationIdFilter:n=>{},logObservableValue:n=>{console.log("logObservableValue",n)},flushUpdates:()=>{this._flushUpdates()},resetUpdates:()=>{this._pendingChanges=null,this._channel.api.notifications.handleChange(this._fullState,!0)}},requests:{getDeclarations:()=>{let n={};for(let e of this._declarations.values())n[e.id]=e;return{decls:n}},getSummarizedInstances:()=>null,getObservableValueInfo:n=>({observers:[...this._aliveInstances.get(n).debugGetObservers()].map(t=>this._formatObserver(t)).filter(Gn)}),getDerivedInfo:n=>{let e=this._aliveInstances.get(n);return{dependencies:[...e.debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(Gn),observers:[...e.debugGetObservers()].map(t=>this._formatObserver(t)).filter(Gn)}},getAutorunInfo:n=>({dependencies:[...this._aliveInstances.get(n).debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(Gn)}),getTransactionState:()=>this.getTransactionState(),setValue:(n,e)=>{let t=this._aliveInstances.get(n);if(t instanceof bt)t.debugSetValue(e);else if(t instanceof vr)t.debugSetValue(e);else if(t instanceof qn)t.debugSetValue(e);else throw new $e("Observable is not supported");let r=[...t.debugGetObservers()];for(let o of r)o.beginUpdate(t);for(let o of r)o.handleChange(t,void 0);for(let o of r)o.endUpdate(t)},getValue:n=>{let e=this._aliveInstances.get(n);if(e instanceof bt)return wn(e.debugGetState().value,200);if(e instanceof vr)return wn(e.debugGetState().value,200)},logValue:n=>{let e=this._aliveInstances.get(n);if(e&&"get"in e)console.log("Logged Value:",e.get());else throw new $e("Observable is not supported")},rerun:n=>{let e=this._aliveInstances.get(n);if(e instanceof bt)e.debugRecompute();else if(e instanceof Xr)e.debugRerun();else throw new $e("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new Tp;this._fullState={};this._flushUpdates=()=>{this._pendingChanges!==null&&(this._channel.api.notifications.handleChange(this._pendingChanges,!1),this._pendingChanges=null)};pt.enable()}static{this._instance=void 0}static getInstance(){return i._instance===void 0&&(i._instance=new i),i._instance}getTransactionState(){let n=[],e=[...this._activeTransactions];if(e.length===0)return;let t=e.flatMap(o=>o.debugGetUpdatingObservers()??[]).map(o=>o.observer),r=new Set;for(;t.length>0;){let o=t.shift();if(r.has(o))continue;r.add(o);let s=this._getInfo(o,a=>{r.has(a)||t.push(a)});s&&n.push(s)}return{names:e.map(o=>o.getDebugName()??"tx"),affected:n}}_getObservableInfo(n){let e=this._instanceInfos.get(n);if(!e){st(new $e("No info found"));return}return e}_getAutorunInfo(n){let e=this._instanceInfos.get(n);if(!e){st(new $e("No info found"));return}return e}_getInfo(n,e){if(n instanceof bt){let t=[...n.debugGetObservers()];for(let l of t)e(l);let r=this._getObservableInfo(n);if(!r)return;let o=n.debugGetState(),s={name:n.debugName,instanceId:r.instanceId,updateCount:o.updateCount},a=[...r.changedObservables].map(l=>this._instanceInfos.get(l)?.instanceId).filter(Gn);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(n instanceof Xr){let t=this._getAutorunInfo(n);if(!t)return;let r={name:n.debugName,instanceId:t.instanceId,updateCount:t.updateCount},o=[...t.changedObservables].map(s=>this._instanceInfos.get(s).instanceId);if(n.debugGetState().isRunning)return{...r,type:"autorun",state:"updating",changedDependencies:o};switch(n.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(n){let e=this._getObservableInfo(n);if(e)return{name:n.debugName,instanceId:e.instanceId}}_formatObserver(n){if(n instanceof bt)return{name:n.toString(),instanceId:this._getObservableInfo(n)?.instanceId};let e=this._getAutorunInfo(n);if(e)return{name:n.toString(),instanceId:e.instanceId}}_handleChange(n){Gy(this._fullState,n),this._pendingChanges===null?this._pendingChanges=n:Ky(this._pendingChanges,n),this._changeThrottler.throttle(this._flushUpdates,10)}_getDeclarationId(n,e){if(!e)return-1;let t=this._declarations.get(e.id);return t===void 0&&(t={id:this._declarationId++,type:n,url:e.fileName,line:e.line,column:e.column},this._declarations.set(e.id,t),this._handleChange({decls:{[t.id]:t}})),t.id}handleObservableCreated(n,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(n,r)}handleOnListenerCountChanged(n,e){let t=this._getObservableInfo(n);if(t){if(t.listenerCount===0&&e>0){let r=n instanceof bt?"observable/derived":"observable/value";this._aliveInstances.set(t.instanceId,n),this._handleChange({instances:{[t.instanceId]:{instanceId:t.instanceId,declarationId:t.declarationId,formattedValue:t.lastValue,type:r,name:n.debugName}}})}else t.listenerCount>0&&e===0&&(this._handleChange({instances:{[t.instanceId]:null}}),this._aliveInstances.delete(t.instanceId));t.listenerCount=e}}handleObservableUpdated(n,e){if(n instanceof bt){this._handleDerivedRecomputed(n,e);return}let t=this._getObservableInfo(n);t&&e.didChange&&(t.lastValue=wn(e.newValue,30),t.listenerCount>0&&this._handleChange({instances:{[t.instanceId]:{formattedValue:t.lastValue}}}))}handleAutorunCreated(n,e){let r={declarationId:this._getDeclarationId("autorun",e),instanceId:this._instanceId++,updateCount:0,changedObservables:new Set};this._instanceInfos.set(n,r),this._aliveInstances.set(r.instanceId,n),r&&this._handleChange({instances:{[r.instanceId]:{instanceId:r.instanceId,declarationId:r.declarationId,runCount:0,type:"autorun",name:n.debugName}}})}handleAutorunDisposed(n){let e=this._getAutorunInfo(n);e&&(this._handleChange({instances:{[e.instanceId]:null}}),this._instanceInfos.delete(n),this._aliveInstances.delete(e.instanceId))}handleAutorunDependencyChanged(n,e,t){let r=this._getAutorunInfo(n);r&&r.changedObservables.add(e)}handleAutorunStarted(n){}handleAutorunFinished(n){let e=this._getAutorunInfo(n);e&&(e.changedObservables.clear(),e.updateCount++,this._handleChange({instances:{[e.instanceId]:{runCount:e.updateCount}}}))}handleDerivedDependencyChanged(n,e,t){let r=this._getObservableInfo(n);r&&r.changedObservables.add(e)}_handleDerivedRecomputed(n,e){let t=this._getObservableInfo(n);if(!t)return;let r=wn(e.newValue,30);t.updateCount++,t.changedObservables.clear(),t.lastValue=r,t.listenerCount>0&&this._handleChange({instances:{[t.instanceId]:{formattedValue:r,recomputationCount:t.updateCount}}})}handleDerivedCleared(n){let e=this._getObservableInfo(n);e&&(e.lastValue=void 0,e.changedObservables.clear(),e.listenerCount>0&&this._handleChange({instances:{[e.instanceId]:{formattedValue:void 0}}}))}handleBeginTransaction(n){this._activeTransactions.add(n)}handleEndTransaction(n){this._activeTransactions.delete(n)}};function MT(i,n){let e=n?.debugNamePostProcessor??(o=>o),t=Wo.from(i,e);if(!t)return"";let r=new Set;return n.type==="observers"?LT(t,0,r,n).trim():OT(t,0,r,n).trim()}function OT(i,n,e,t){let r="		".repeat(n),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: ${wn(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=Wo.from(a,t.debugNamePostProcessor??(d=>d))??Wo.unknown(a);o.push(OT(l,n+1,e,t))}}return o.join(`
`)}function LT(i,n,e,t){let r="		".repeat(n),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: ${wn(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=Wo.from(a,t.debugNamePostProcessor??(d=>d))??Wo.unknown(a);o.push(LT(l,n+1,e,t))}}return o.join(`
`)}var Wo=class i{constructor(n,e,t,r,o,s,a){this.sourceObj=n;this.name=e;this.type=t;this.value=r;this.state=o;this.dependencies=s;this.observers=a}static from(n,e){if(n instanceof Xr){let t=n.debugGetState();return new i(n,e(n.debugName),"autorun",void 0,t.stateStr,Array.from(t.dependencies),[])}else if(n instanceof bt){let t=n.debugGetState();return new i(n,e(n.debugName),"derived",t.value,t.stateStr,Array.from(t.dependencies),Array.from(n.debugGetObservers()))}else if(n instanceof vr){let t=n.debugGetState();return new i(n,e(n.debugName),"observableValue",t.value,"upToDate",[],Array.from(n.debugGetObservers()))}else if(n instanceof qn){let t=n.debugGetState();return new i(n,e(n.debugName),"fromEvent",t.value,t.hasValue?"upToDate":"initial",[],Array.from(n.debugGetObservers()))}}static unknown(n){return new i(n,"(unknown)","unknown",void 0,"unknown",[],[])}};PT(MT);CT(kT);var dM=!1;dM&&Pd(new kd);Xe&&Xe.VSCODE_DEV_DEBUG_OBSERVABLES&&Pd(wp.getInstance());var Jy=class{constructor(){this._value="";this._pos=0}reset(n){return this._value=n,this._pos=0,this}next(){return this._pos+=1,this}hasNext(){return this._pos<this._value.length-1}cmp(n){let e=n.charCodeAt(0),t=this._value.charCodeAt(this._pos);return e-t}value(){return this._value[this._pos]}},Yy=class{constructor(n=!0){this._caseSensitive=n}reset(n){return this._value=n,this._from=0,this._to=0,this.next()}hasNext(){return this._to<this._value.length}next(){this._from=this._to;let n=!0;for(;this._to<this._value.length;this._to++)if(this._value.charCodeAt(this._to)===46)if(n)this._from++;else break;else n=!1;return this}cmp(n){return this._caseSensitive?Mu(n,this._value,0,n.length,this._from,this._to):Ro(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},Rp=class{constructor(n=!0,e=!0){this._splitOnBackslash=n;this._caseSensitive=e}reset(n){this._from=0,this._to=0,this._value=n,this._valueLen=n.length;for(let e=n.length-1;e>=0;e--,this._valueLen--){let t=this._value.charCodeAt(e);if(!(t===47||this._splitOnBackslash&&t===92))break}return this.next()}hasNext(){return this._to<this._valueLen}next(){this._from=this._to;let n=!0;for(;this._to<this._valueLen;this._to++){let e=this._value.charCodeAt(this._to);if(e===47||this._splitOnBackslash&&e===92)if(n)this._from++;else break;else n=!1}return this}cmp(n){return this._caseSensitive?Mu(n,this._value,0,n.length,this._from,this._to):Ro(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var Qy=class{constructor(n,e){this._ignorePathCasing=n;this._ignoreQueryAndFragment=e;this._states=[];this._stateIdx=0}reset(n){return this._value=n,this._states=[],this._value.scheme&&this._states.push(1),this._value.authority&&this._states.push(2),this._value.path&&(this._pathIterator=new Rp(!1,!this._ignorePathCasing(n)),this._pathIterator.reset(n.path),this._pathIterator.value()&&this._states.push(3)),this._ignoreQueryAndFragment(n)||(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(n){if(this._states[this._stateIdx]===1)return Xh(n,this._value.scheme);if(this._states[this._stateIdx]===2)return Xh(n,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(n);if(this._states[this._stateIdx]===4)return On(n,this._value.query);if(this._states[this._stateIdx]===5)return On(n,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}},Zr=class i{static{this.Val=Symbol("undefined_placeholder")}static wrap(n){return n===void 0?i.Val:n}static unwrap(n){return n===i.Val?void 0:n}},Gs=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 n=this.right;return this.right=n.left,n.left=this,this.updateHeight(),n.updateHeight(),n}rotateRight(){let n=this.left;return this.left=n.right,n.right=this,this.updateHeight(),n.updateHeight(),n}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 Sr=class i{static forUris(n=()=>!1,e=()=>!1){return new i(new Qy(n,e))}static forPaths(n=!1){return new i(new Rp(void 0,!n))}static forStrings(){return new i(new Jy)}static forConfigKeys(){return new i(new Yy)}constructor(n){this._iter=n}clear(){this._root=void 0}fill(n,e){if(e){let t=e.slice(0);Mh(t);for(let r of t)this.set(r,n)}else{let t=n.slice(0);Mh(t);for(let r of t)this.set(r[0],r[1])}}set(n,e){let t=this._iter.reset(n),r;this._root||(this._root=new Gs,this._root.segment=t.value());let o=[];for(r=this._root;;){let a=t.cmp(r.segment);if(a>0)r.left||(r.left=new Gs,r.left.segment=t.value()),o.push([-1,r]),r=r.left;else if(a<0)r.right||(r.right=new Gs,r.right.segment=t.value()),o.push([1,r]),r=r.right;else if(t.hasNext())t.next(),r.mid||(r.mid=new Gs,r.mid.segment=t.value()),o.push([0,r]),r=r.mid;else break}let s=Zr.unwrap(r.value);r.value=Zr.wrap(e),r.key=n;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(n){return Zr.unwrap(this._getNode(n)?.value)}_getNode(n){let e=this._iter.reset(n),t=this._root;for(;t;){let r=e.cmp(t.segment);if(r>0)t=t.left;else if(r<0)t=t.right;else if(e.hasNext())e.next(),t=t.mid;else break}return t}has(n){let e=this._getNode(n);return!(e?.value===void 0&&e?.mid===void 0)}delete(n){return this._delete(n,!1)}deleteSuperstr(n){return this._delete(n,!0)}_delete(n,e){let t=this._iter.reset(n),r=[],o=this._root;for(;o;){let s=t.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(t.hasNext())t.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:Vl(!1);case 1:Vl(!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(n,e){for(;n.left;)e.push([-1,n]),n=n.left;return n}_balanceByStack(n){for(let e=n.length-1;e>=0;e--){let t=n[e][1];t.updateHeight();let r=t.balanceFactor();if(r>1?(t.right.balanceFactor()>=0||(t.right=t.right.rotateRight()),n[e][1]=t.rotateLeft()):r<-1&&(t.left.balanceFactor()<=0||(t.left=t.left.rotateLeft()),n[e][1]=t.rotateRight()),e>0)switch(n[e-1][0]){case-1:n[e-1][1].left=n[e][1];break;case 1:n[e-1][1].right=n[e][1];break;case 0:n[e-1][1].mid=n[e][1];break}else return n[0][1]}}findSubstr(n){let e=this._iter.reset(n),t=this._root,r;for(;t;){let o=e.cmp(t.segment);if(o>0)t=t.left;else if(o<0)t=t.right;else if(e.hasNext())e.next(),r=Zr.unwrap(t.value)||r,t=t.mid;else break}return t&&Zr.unwrap(t.value)||r}findSuperstr(n){return this._findSuperstrOrElement(n,!1)}_findSuperstrOrElement(n,e){let t=this._iter.reset(n),r=this._root;for(;r;){let o=t.cmp(r.segment);if(o>0)r=r.left;else if(o<0)r=r.right;else if(t.hasNext())t.next(),r=r.mid;else return r.mid?this._entries(r.mid):e?Zr.unwrap(r.value):void 0}}hasElementOrSubtree(n){return this._findSuperstrOrElement(n,!0)!==void 0}forEach(n){for(let[e,t]of this)n(t,e)}*[Symbol.iterator](){yield*this._entries(this._root)}_entries(n){let e=[];return this._dfsEntries(n,e),e[Symbol.iterator]()}_dfsEntries(n,e){n&&(n.left&&this._dfsEntries(n.left,e),n.value!==void 0&&e.push([n.key,Zr.unwrap(n.value)]),n.mid&&this._dfsEntries(n.mid,e),n.right&&this._dfsEntries(n.right,e))}_isBalanced(){let n=e=>{if(!e)return!0;let t=e.balanceFactor();return t<-1||t>1?!1:n(e.left)&&n(e.right)};return n(this._root)}};var xe=$("fileService");function ti(i){return i.create===!0}function Rn(i){return!!(i.capabilities&2)}function NT(i){return!!(i.capabilities&524288)}function Xy(i){return!!(i.capabilities&8)}function UT(i){return!!(i.capabilities&131072)}function FT(i){return!!(i.capabilities&262144)}function ni(i){return!!(i.capabilities&4)}function Ap(i){return!!(i.capabilities&16)}function Ep(i){return Rn(i)?!!(i.capabilities&16384):!1}function Zy(i){return Rn(i)?!!(i.capabilities&32768):!1}function HT(i){return!!(i.capabilities&65536)}var Js=class i extends Error{constructor(e,t){super(e);this.code=t}static create(e,t){let r=new i(e.toString(),t);return cM(r,t),r}};function De(i,n){return Js.create(i,n)}function ri(i){return i||De(f(2616,null),"Unknown")}function cM(i,n){return i.name=n?`${n} (FileSystemError)`:"FileSystemError",i}function fn(i){if(!i)return"Unknown";if(i instanceof Js)return i.code;let n=/^(.+) \(FileSystemError\)$/.exec(i.name);if(!n)return"Unknown";switch(n[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 ii(i){if(i instanceof lt)return i.fileOperationResult;switch(fn(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 ei=class{constructor(n,e,t){this.resource=n;this.operation=e;this.target=t}isOperation(n){return this.operation===n}};var xp=class i{constructor(n,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new qe(()=>{let n=Sr.forUris(()=>this.ignorePathCasing);return n.fill(this.rawAdded.map(e=>[e,!0])),n});this.updated=new qe(()=>{let n=Sr.forUris(()=>this.ignorePathCasing);return n.fill(this.rawUpdated.map(e=>[e,!0])),n});this.deleted=new qe(()=>{let n=Sr.forUris(()=>this.ignorePathCasing);return n.fill(this.rawDeleted.map(e=>[e,!0])),n});this.rawAdded=[];this.rawUpdated=[];this.rawDeleted=[];for(let t of n){switch(t.type){case 1:this.rawAdded.push(t.resource);break;case 0:this.rawUpdated.push(t.resource);break;case 2:this.rawDeleted.push(t.resource);break}this.correlationId!==i.MIXED_CORRELATION&&(typeof t.cId=="number"?this.correlationId===void 0?this.correlationId=t.cId:this.correlationId!==t.cId&&(this.correlationId=i.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=i.MIXED_CORRELATION))}}static{this.MIXED_CORRELATION=null}contains(n,...e){return this.doContains(n,{includeChildren:!1},...e)}affects(n,...e){return this.doContains(n,{includeChildren:!0},...e)}doContains(n,e,...t){if(!n)return!1;let r=t.length>0;return!!((!r||t.includes(1))&&(this.added.value.get(n)||e.includeChildren&&this.added.value.findSuperstr(n))||(!r||t.includes(0))&&(this.updated.value.get(n)||e.includeChildren&&this.updated.value.findSuperstr(n))||(!r||t.includes(2))&&(this.deleted.value.findSubstr(n)||e.includeChildren&&this.deleted.value.findSuperstr(n)))}gotAdded(){return this.rawAdded.length>0}gotDeleted(){return this.rawDeleted.length>0}gotUpdated(){return this.rawUpdated.length>0}correlates(n){return this.correlationId===n}hasCorrelation(){return typeof this.correlationId=="number"}};function $T(i,n,e){return!i||!n||i===n||n.length>i.length?!1:(n.charAt(n.length-1)!==Le&&(n+=Le),e?Pi(i,n):i.indexOf(n)===0)}var lt=class extends Error{constructor(e,t,r){super(e);this.fileOperationResult=t;this.options=r}},Ys=class extends lt{constructor(e,t,r,o){super(e,t,o);this.fileOperationResult=t;this.size=r}},Qs=class extends lt{constructor(e,t,r){super(e,2,r);this.stat=t}};var kp="";function ev(i){if(!(typeof i.size!="number"||typeof i.mtime!="number"))return i.mtime.toString(29)+i.size.toString(31)}var Pp=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(n){return So(n)||(n=0),n<i.KB?f(2611,null,n.toFixed(0)):n<i.MB?f(2613,null,(n/i.KB).toFixed(2)):n<i.GB?f(2614,null,(n/i.MB).toFixed(2)):n<i.TB?f(2612,null,(n/i.GB).toFixed(2)):f(2615,null,(n/i.TB).toFixed(2))}};var zn=class{constructor(n,e=[],t=!1){this.ctor=n,this.staticArguments=e,this.supportsDelayedInstantiation=t}};var tv=class{constructor(n,e){this.key=n;this.data=e;this.incoming=new Map;this.outgoing=new Map}},Dd=class{constructor(n){this._hashFn=n;this._nodes=new Map}roots(){let n=[];for(let e of this._nodes.values())e.outgoing.size===0&&n.push(e);return n}insertEdge(n,e){let t=this.lookupOrInsertNode(n),r=this.lookupOrInsertNode(e);t.outgoing.set(r.key,r),r.incoming.set(t.key,t)}removeNode(n){let e=this._hashFn(n);this._nodes.delete(e);for(let t of this._nodes.values())t.outgoing.delete(e),t.incoming.delete(e)}lookupOrInsertNode(n){let e=this._hashFn(n),t=this._nodes.get(e);return t||(t=new tv(e,n),this._nodes.set(e,t)),t}lookup(n){return this._nodes.get(this._hashFn(n))}isEmpty(){return this._nodes.size===0}toString(){let n=[];for(let[e,t]of this._nodes)n.push(`${e}
	(-> incoming)[${[...t.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...t.outgoing.keys()].join(",")}]
`);return n.join(`
`)}findCycleSlow(){for(let[n,e]of this._nodes){let t=new Set([n]),r=this._findCycle(e,t);if(r)return r}}_findCycle(n,e){for(let[t,r]of n.outgoing){if(e.has(t))return[...e,t].join(" -> ");e.add(t);let o=this._findCycle(r,e);if(o)return o;e.delete(t)}}};var Wi=class{constructor(...n){this._entries=new Map;for(let[e,t]of n)this.set(e,t)}set(n,e){let t=this._entries.get(n);return this._entries.set(n,e),t}has(n){return this._entries.has(n)}get(n){return this._entries.get(n)}};var uM=!1,Dp=class extends Error{constructor(n){super("cyclic dependency between services"),this.message=n.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${n.toString()}`}},Xs=class i{constructor(n=new Wi,e=!1,t,r=uM){this._services=n;this._strict=e;this._parent=t;this._enableTracing=r;this._isDisposed=!1;this._servicesToMaybeDispose=new Set;this._children=new Set;this._activeInstantiations=new Set;this._services.set(Ie,this),this._globalGraph=r?t?._globalGraph??new Dd(o=>o):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,jt(this._children),this._children.clear();for(let n of this._servicesToMaybeDispose)bs(n)&&n.dispose();this._servicesToMaybeDispose.clear()}}_throwIfDisposed(){if(this._isDisposed)throw new Error("InstantiationService has been disposed")}createChild(n,e){this._throwIfDisposed();let t=this,r=new class extends i{dispose(){t._children.delete(r),super.dispose()}}(n,this._strict,this,this._enableTracing);return this._children.add(r),e?.add(r),r}invokeFunction(n,...e){this._throwIfDisposed();let t=Md.traceInvocation(this._enableTracing,n),r=!1;try{return n({get:s=>{if(r)throw yu("service accessor is only valid during the invocation of its target method");let a=this._getOrCreateServiceInstance(s,t);return a||this._throwIfStrict(`[invokeFunction] unknown service '${s}'`,!1),a}},...e)}finally{r=!0,t.stop()}}createInstance(n,...e){this._throwIfDisposed();let t,r;return n instanceof zn?(t=Md.traceCreation(this._enableTracing,n.ctor),r=this._createInstance(n.ctor,n.staticArguments.concat(e),t)):(t=Md.traceCreation(this._enableTracing,n),r=this._createInstance(n,e,t)),t.stop(),r}_createInstance(n,e=[],t){let r=er.getServiceDependencies(n).sort((a,l)=>a.index-l.index),o=[];for(let a of r){let l=this._getOrCreateServiceInstance(a.id,t);l||this._throwIfStrict(`[createInstance] ${n.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 ${n.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(n,e.concat(o))}_setCreatedServiceInstance(n,e){if(this._services.get(n)instanceof zn)this._services.set(n,e);else if(this._parent)this._parent._setCreatedServiceInstance(n,e);else throw new Error("illegalState - setting UNKNOWN service instance")}_getServiceInstanceOrDescriptor(n){let e=this._services.get(n);return!e&&this._parent?this._parent._getServiceInstanceOrDescriptor(n):e}_getOrCreateServiceInstance(n,e){this._globalGraph&&this._globalGraphImplicitDependency&&this._globalGraph.insertEdge(this._globalGraphImplicitDependency,String(n));let t=this._getServiceInstanceOrDescriptor(n);return t instanceof zn?this._safeCreateAndCacheServiceInstance(n,t,e.branch(n,!0)):(e.branch(n,!1),t)}_safeCreateAndCacheServiceInstance(n,e,t){if(this._activeInstantiations.has(n))throw new Error(`illegal state - RECURSIVELY instantiating service '${n}'`);this._activeInstantiations.add(n);try{return this._createAndCacheServiceInstance(n,e,t)}finally{this._activeInstantiations.delete(n)}}_createAndCacheServiceInstance(n,e,t){let r=new Dd(l=>l.id.toString()),o=0,s=[{id:n,desc:e,_trace:t}],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 Dp(r);for(let d of er.getServiceDependencies(l.desc.ctor)){let c=this._getServiceInstanceOrDescriptor(d.id);if(c||this._throwIfStrict(`[createInstance] ${n} depends on ${d.id} which is NOT registered.`,!0),this._globalGraph?.insertEdge(String(l.id),String(d.id)),c instanceof zn){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 Dp(r);break}for(let{data:d}of l){if(this._getServiceInstanceOrDescriptor(d.id)instanceof zn){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(n)}_createServiceInstanceWithOwner(n,e,t=[],r,o){if(this._services.get(n)instanceof zn)return this._createServiceInstance(n,e,t,r,o,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(n,e,t,r,o);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(n,e,t=[],r,o,s){if(r){let a=new i(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(n);let l=new Map,d=new qu(()=>{let c=a._createInstance(e,t,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 Gl,l.set(u,h)),(S,b,I)=>{if(d.isInitialized)return d.value[u](S,b,I);{let _={listener:[S,b,I],disposable:void 0},R=h.push(_);return M(()=>{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,t,o);return s.add(a),a}}_throwIfStrict(n,e){if(e&&console.warn(n),this._strict)throw new Error(n)}};var Md=class i{constructor(n,e){this.type=n;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(n,e){return n?new i(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):i._None}static traceCreation(n,e){return n?new i(1,e.name):i._None}static{this._totals=0}branch(n,e){let t=new i(3,n.toString());return this._dep.push([n,e,t]),t}stop(){let n=Date.now()-this._start;i._totals+=n;let e=!1;function t(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=t(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}`,`${t(1,this)}`,`DONE, took ${n.toFixed(2)}ms (grand total ${i._totals.toFixed(2)}ms)`];(n>2||e)&&i.all.add(r.join(`
`))}};function br(i){return rv(i,0)}function rv(i,n){switch(typeof i){case"object":return i===null?oi(349,n):Array.isArray(i)?fM(i,n):gM(i,n);case"string":return qT(i,n);case"boolean":return pM(i,n);case"number":return oi(i,n);case"undefined":return oi(937,n);default:return oi(617,n)}}function oi(i,n){return(n<<5)-n+i|0}function pM(i,n){return oi(i?433:863,n)}function qT(i,n){n=oi(149417,n);for(let e=0,t=i.length;e<t;e++)n=oi(i.charCodeAt(e),n);return n}function fM(i,n){return n=oi(104579,n),i.reduce((e,t)=>rv(t,e),n)}function gM(i,n){return n=oi(181387,n),Object.keys(i).sort().reduce((e,t)=>(e=qT(t,e),rv(i[t],e)),n)}function nv(i,n,e=32){let t=e-n,r=~((1<<t)-1);return(i<<n|(r&i)>>>t)>>>0}function Od(i,n=32){return i instanceof ArrayBuffer?Li(U.wrap(new Uint8Array(i))):(i>>>0).toString(16).padStart(n/4,"0")}var WT=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(n){let e=n.length;if(e===0)return;let t=this._buff,r=this._buffLen,o=this._leftoverHighSurrogate,s,a;for(o!==0?(s=o,a=-1,o=0):(s=n.charCodeAt(0),a=0);;){let l=s;if(RI(s))if(a+1<e){let d=n.charCodeAt(a+1);ey(d)?(a++,l=xI(s,d)):l=65533}else{o=s;break}else ey(s)&&(l=65533);if(r=this._push(t,r,l),a++,a<e)s=n.charCodeAt(a);else break}this._buffLen=r,this._leftoverHighSurrogate=o}_push(n,e,t){return t<128?n[e++]=t:t<2048?(n[e++]=192|(t&1984)>>>6,n[e++]=128|(t&63)>>>0):t<65536?(n[e++]=224|(t&61440)>>>12,n[e++]=128|(t&4032)>>>6,n[e++]=128|(t&63)>>>0):(n[e++]=240|(t&1835008)>>>18,n[e++]=128|(t&258048)>>>12,n[e++]=128|(t&4032)>>>6,n[e++]=128|(t&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,n[0]=n[64],n[1]=n[65],n[2]=n[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()),Od(this._h0)+Od(this._h1)+Od(this._h2)+Od(this._h3)+Od(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 n=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(n/4294967296),!1),this._buffDV.setUint32(60,n%4294967296,!1),this._step()}_step(){let n=i._bigBlock32,e=this._buffDV;for(let u=0;u<64;u+=4)n.setUint32(u,e.getUint32(u,!1),!1);for(let u=64;u<320;u+=4)n.setUint32(u,nv(n.getUint32(u-12,!1)^n.getUint32(u-32,!1)^n.getUint32(u-56,!1)^n.getUint32(u-64,!1),1),!1);let t=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=nv(t,5)+l+a+d+n.getUint32(u*4,!1)&4294967295,a=s,s=o,o=nv(r,30),r=t,t=c;this._h0=this._h0+t&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 iv(...i){switch(i.length){case 1:return f(2417,null,i[0]);case 2:return f(2418,null,i[0],i[1]);case 3:return f(2419,null,i[0],i[1],i[2]);default:return}}var mM=f(2416,null),hM=f(2415,null),qi=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(n){switch(n.type){case 0:return"(";case 1:return")";case 2:return"!";case 3:return n.isTripleEq?"===":"==";case 4:return n.isTripleEq?"!==":"!=";case 5:return"<";case 6:return"<=";case 7:return">";case 8:return">=";case 9:return"=~";case 10:return n.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 n.lexeme;case 18:return n.lexeme;case 19:return n.lexeme;case 20:return"EOF";default:throw yu(`unhandled token type: ${JSON.stringify(n)}; have you forgotten to add a case?`)}}static{this._regexFlags=new Set(["i","g","s","m","y","u"].map(n=>n.charCodeAt(0)))}static{this._keywords=new Map([["not",14],["in",13],["false",12],["true",11]])}get errors(){return this._errors}reset(n){return this._input=n,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(iv("==","=~"));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(iv("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(iv("||"));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(n){return this._isAtEnd()||this._input.charCodeAt(this._current)!==n?!1:(this._current++,!0)}_advance(){return this._input.charCodeAt(this._current++)}_peek(){return this._isAtEnd()?0:this._input.charCodeAt(this._current)}_addToken(n){this._tokens.push({type:n,offset:this._start})}_error(n){let e=this._start,t=this._input.substring(this._start,this._current),r={type:19,offset:this._start,lexeme:t};this._errors.push({offset:e,lexeme:t,additionalInfo:n}),this._tokens.push(r)}_string(){this.stringRe.lastIndex=this._start;let n=this.stringRe.exec(this._input);if(n){this._current=this._start+n[0].length;let e=this._input.substring(this._start,this._current),t=i._keywords.get(e);t?this._addToken(t):this._tokens.push({type:17,lexeme:e,offset:this._start})}}_quotedString(){for(;this._peek()!==39&&!this._isAtEnd();)this._advance();if(this._isAtEnd()){this._error(mM);return}this._advance(),this._tokens.push({type:18,lexeme:this._input.substring(this._start+1,this._current-1),offset:this._start+1})}_regex(){let n=this._current,e=!1,t=!1;for(;;){if(n>=this._input.length){this._current=n,this._error(hM);return}let o=this._input.charCodeAt(n);if(e)e=!1;else if(o===47&&!t){n++;break}else o===91?t=!0:o===92?e=!0:o===93&&(t=!1);n++}for(;n<this._input.length&&i._regexFlags.has(this._input.charCodeAt(n));)n++;this._current=n;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 wt=new Map;wt.set("false",!1);wt.set("true",!0);wt.set("isMac",dt);wt.set("isLinux",Oe);wt.set("isWindows",Q);wt.set("isWeb",Zt);wt.set("isMacNative",dt&&!Zt);wt.set("isEdge",sI);wt.set("isFirefox",iI);wt.set("isChrome",qh);wt.set("isSafari",oI);var yM=Object.prototype.hasOwnProperty;var vM={regexParsingWithErrorRecovery:!0},SM=f(2396,null),bM=f(2397,null),CM=f(2399,null),BT=f(2395,null),IM=f(2402,null),_M=f(2403,null),TM=f(2400,null),wM=f(2401,null),ov=class i{constructor(n=vM){this._config=n;this._scanner=new qi;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(n){if(n===""){this._parsingErrors.push({message:SM,offset:0,lexeme:"",additionalInfo:bM});return}this._tokens=this._scanner.reset(n).scan(),this._current=0,this._parsingErrors=[];try{let e=this._expr();if(!this._isAtEnd()){let t=this._peek(),r=t.type===17?_M:void 0;throw this._parsingErrors.push({message:IM,offset:t.offset,lexeme:qi.getLexeme(t),additionalInfo:r}),i._parseError}return e}catch(e){if(e!==i._parseError)throw e;return}}_expr(){return this._or()}_or(){let n=[this._and()];for(;this._matchOne(16);){let e=this._and();n.push(e)}return n.length===1?n[0]:Lt.or(...n)}_and(){let n=[this._term()];for(;this._matchOne(15);){let e=this._term();n.push(e)}return n.length===1?n[0]:Lt.and(...n)}_term(){if(this._matchOne(2)){let n=this._peek();switch(n.type){case 11:return this._advance(),Wt.INSTANCE;case 12:return this._advance(),Yt.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,BT),e?.negate()}case 17:return this._advance(),Bo.create(n.lexeme);default:throw this._errExpectedButGot("KEY | true | false | '(' expression ')'",n)}}return this._primary()}_primary(){let n=this._peek();switch(n.type){case 11:return this._advance(),Lt.true();case 12:return this._advance(),Lt.false();case 0:{this._advance();let e=this._expr();return this._consume(1,BT),e}case 17:{let e=n.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 Wd.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(qi.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 Lt.regex(e,u)}case 18:{let o=r.lexeme;this._advance();let s=null;if(!CI(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 Wd.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,CM);let r=this._value();return Lt.notIn(e,r)}switch(this._peek().type){case 3:{this._advance();let r=this._value();if(this._previous().type===18)return Lt.equals(e,r);switch(r){case"true":return Lt.has(e);case"false":return Lt.not(e);default:return Lt.equals(e,r)}}case 4:{this._advance();let r=this._value();if(this._previous().type===18)return Lt.notEquals(e,r);switch(r){case"true":return Lt.not(e);case"false":return Lt.has(e);default:return Lt.notEquals(e,r)}}case 5:return this._advance(),Hd.create(e,this._value());case 6:return this._advance(),$d.create(e,this._value());case 7:return this._advance(),Zs.create(e,this._value());case 8:return this._advance(),Fd.create(e,this._value());case 13:return this._advance(),Lt.in(e,this._value());default:return Lt.has(e)}}case 20:throw this._parsingErrors.push({message:TM,offset:n.offset,lexeme:"",additionalInfo:wM}),i._parseError;default:throw this._errExpectedButGot(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`,this._peek())}}_value(){let n=this._peek();switch(n.type){case 17:case 18:return this._advance(),n.lexeme;case 11:return this._advance(),"true";case 12:return this._advance(),"false";case 13:return this._advance(),"in";default:return""}}_removeFlagsGY(n){return n.replaceAll(this._flagsGYRe,"")}_previous(){return this._tokens[this._current-1]}_matchOne(n){return this._check(n)?(this._advance(),!0):!1}_advance(){return this._isAtEnd()||this._current++,this._previous()}_consume(n,e){if(this._check(n))return this._advance();throw this._errExpectedButGot(e,this._peek())}_errExpectedButGot(n,e,t){let r=f(2398,null,n,qi.getLexeme(e)),o=e.offset,s=qi.getLexeme(e);return this._parsingErrors.push({message:r,offset:o,lexeme:s,additionalInfo:t}),i._parseError}_check(n){return this._peek().type===n}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},Lt=class{static false(){return Wt.INSTANCE}static true(){return Yt.INSTANCE}static has(n){return qo.create(n)}static equals(n,e){return Nd.create(n,e)}static notEquals(n,e){return Ud.create(n,e)}static regex(n,e){return Wd.create(n,e)}static in(n,e){return Mp.create(n,e)}static notIn(n,e){return Op.create(n,e)}static not(n){return Bo.create(n)}static and(...n){return Lp.create(n,null,!0)}static or(...n){return qd.create(n,null,!0)}static greater(n,e){return Zs.create(n,e)}static greaterEquals(n,e){return Fd.create(n,e)}static smaller(n,e){return Hd.create(n,e)}static smallerEquals(n,e){return $d.create(n,e)}static{this._parser=new ov({regexParsingWithErrorRecovery:!1})}static deserialize(n){return n==null?void 0:this._parser.parse(n)}};function Ld(i,n){return i.cmp(n)}var Wt=class i{constructor(){this.type=0}static{this.INSTANCE=new i}cmp(n){return this.type-n.type}equals(n){return n.type===this.type}substituteConstants(){return this}evaluate(n){return!1}serialize(){return"false"}keys(){return[]}map(n){return this}negate(){return Yt.INSTANCE}},Yt=class i{constructor(){this.type=1}static{this.INSTANCE=new i}cmp(n){return this.type-n.type}equals(n){return n.type===this.type}substituteConstants(){return this}evaluate(n){return!0}serialize(){return"true"}keys(){return[]}map(n){return this}negate(){return Wt.INSTANCE}},qo=class i{constructor(n,e){this.key=n;this.negated=e;this.type=2}static create(n,e=null){let t=wt.get(n);return typeof t=="boolean"?t?Yt.INSTANCE:Wt.INSTANCE:new i(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:jT(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=wt.get(this.key);return typeof n=="boolean"?n?Yt.INSTANCE:Wt.INSTANCE:this}evaluate(n){return!!n.getValue(this.key)}serialize(){return this.key}keys(){return[this.key]}map(n){return n.mapDefined(this.key)}negate(){return this.negated||(this.negated=Bo.create(this.key,this)),this.negated}},Nd=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=4}static create(n,e,t=null){if(typeof e=="boolean")return e?qo.create(n,t):Bo.create(n,t);let r=wt.get(n);return typeof r=="boolean"?e===(r?"true":"false")?Yt.INSTANCE:Wt.INSTANCE:new i(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){let n=wt.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?Yt.INSTANCE:Wt.INSTANCE}return this}evaluate(n){return n.getValue(this.key)==this.value}serialize(){return`${this.key} == '${this.value}'`}keys(){return[this.key]}map(n){return n.mapEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Ud.create(this.key,this.value,this)),this.negated}},Mp=class i{constructor(n,e){this.key=n;this.valueKey=e;this.type=10;this.negated=null}static create(n,e){return new i(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.valueKey,n.key,n.valueKey)}equals(n){return n.type===this.type?this.key===n.key&&this.valueKey===n.valueKey:!1}substituteConstants(){return this}evaluate(n){let e=n.getValue(this.valueKey),t=n.getValue(this.key);if(Array.isArray(e)){if(e.includes(t))return!0;if(Q&&typeof t=="string"&&t.startsWith("file:///")){let r=t.toLowerCase();return e.some(o=>typeof o=="string"&&o.toLowerCase()===r)}return!1}if(typeof t=="string"&&typeof e=="object"&&e!==null){if(yM.call(e,t))return!0;if(Q&&t.startsWith("file:///")){let r=t.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(n){return n.mapIn(this.key,this.valueKey)}negate(){return this.negated||(this.negated=Op.create(this.key,this.valueKey)),this.negated}},Op=class i{constructor(n,e){this.key=n;this.valueKey=e;this.type=11;this._negated=Mp.create(n,e)}static create(n,e){return new i(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:this._negated.cmp(n._negated)}equals(n){return n.type===this.type?this._negated.equals(n._negated):!1}substituteConstants(){return this}evaluate(n){return!this._negated.evaluate(n)}serialize(){return`${this.key} not in '${this.valueKey}'`}keys(){return this._negated.keys()}map(n){return n.mapNotIn(this.key,this.valueKey)}negate(){return this._negated}},Ud=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=5}static create(n,e,t=null){if(typeof e=="boolean")return e?Bo.create(n,t):qo.create(n,t);let r=wt.get(n);return typeof r=="boolean"?e===(r?"true":"false")?Wt.INSTANCE:Yt.INSTANCE:new i(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){let n=wt.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?Wt.INSTANCE:Yt.INSTANCE}return this}evaluate(n){return n.getValue(this.key)!=this.value}serialize(){return`${this.key} != '${this.value}'`}keys(){return[this.key]}map(n){return n.mapNotEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Nd.create(this.key,this.value,this)),this.negated}},Bo=class i{constructor(n,e){this.key=n;this.negated=e;this.type=3}static create(n,e=null){let t=wt.get(n);return typeof t=="boolean"?t?Wt.INSTANCE:Yt.INSTANCE:new i(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:jT(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=wt.get(this.key);return typeof n=="boolean"?n?Wt.INSTANCE:Yt.INSTANCE:this}evaluate(n){return!n.getValue(this.key)}serialize(){return`!${this.key}`}keys(){return[this.key]}map(n){return n.mapNot(this.key)}negate(){return this.negated||(this.negated=qo.create(this.key,this)),this.negated}};function Up(i,n){if(typeof i=="string"){let e=parseFloat(i);isNaN(e)||(i=e)}return typeof i=="string"||typeof i=="number"?n(i):Wt.INSTANCE}var Zs=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=12}static create(n,e,t=null){return Up(e,r=>new i(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){return this}evaluate(n){return typeof this.value=="string"?!1:parseFloat(n.getValue(this.key))>this.value}serialize(){return`${this.key} > ${this.value}`}keys(){return[this.key]}map(n){return n.mapGreater(this.key,this.value)}negate(){return this.negated||(this.negated=$d.create(this.key,this.value,this)),this.negated}},Fd=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=13}static create(n,e,t=null){return Up(e,r=>new i(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){return this}evaluate(n){return typeof this.value=="string"?!1:parseFloat(n.getValue(this.key))>=this.value}serialize(){return`${this.key} >= ${this.value}`}keys(){return[this.key]}map(n){return n.mapGreaterEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Hd.create(this.key,this.value,this)),this.negated}},Hd=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=14}static create(n,e,t=null){return Up(e,r=>new i(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){return this}evaluate(n){return typeof this.value=="string"?!1:parseFloat(n.getValue(this.key))<this.value}serialize(){return`${this.key} < ${this.value}`}keys(){return[this.key]}map(n){return n.mapSmaller(this.key,this.value)}negate(){return this.negated||(this.negated=Fd.create(this.key,this.value,this)),this.negated}},$d=class i{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=15}static create(n,e,t=null){return Up(e,r=>new i(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:zo(this.key,this.value,n.key,n.value)}equals(n){return n.type===this.type?this.key===n.key&&this.value===n.value:!1}substituteConstants(){return this}evaluate(n){return typeof this.value=="string"?!1:parseFloat(n.getValue(this.key))<=this.value}serialize(){return`${this.key} <= ${this.value}`}keys(){return[this.key]}map(n){return n.mapSmallerEquals(this.key,this.value)}negate(){return this.negated||(this.negated=Zs.create(this.key,this.value,this)),this.negated}},Wd=class i{constructor(n,e){this.key=n;this.regexp=e;this.type=7;this.negated=null}static create(n,e){return new i(n,e)}cmp(n){if(n.type!==this.type)return this.type-n.type;if(this.key<n.key)return-1;if(this.key>n.key)return 1;let e=this.regexp?this.regexp.source:"",t=n.regexp?n.regexp.source:"";return e<t?-1:e>t?1:0}equals(n){if(n.type===this.type){let e=this.regexp?this.regexp.source:"",t=n.regexp?n.regexp.source:"";return this.key===n.key&&e===t}return!1}substituteConstants(){return this}evaluate(n){let e=n.getValue(this.key);return this.regexp?this.regexp.test(e):!1}serialize(){let n=this.regexp?`/${this.regexp.source}/${this.regexp.flags}`:"/invalid/";return`${this.key} =~ ${n}`}keys(){return[this.key]}map(n){return n.mapRegex(this.key,this.regexp)}negate(){return this.negated||(this.negated=sv.create(this)),this.negated}},sv=class i{constructor(n){this._actual=n;this.type=8}static create(n){return new i(n)}cmp(n){return n.type!==this.type?this.type-n.type:this._actual.cmp(n._actual)}equals(n){return n.type===this.type?this._actual.equals(n._actual):!1}substituteConstants(){return this}evaluate(n){return!this._actual.evaluate(n)}serialize(){return`!(${this._actual.serialize()})`}keys(){return this._actual.keys()}map(n){return new i(this._actual.map(n))}negate(){return this._actual}};function VT(i){let n=null;for(let e=0,t=i.length;e<t;e++){let r=i[e].substituteConstants();if(i[e]!==r&&n===null){n=[];for(let o=0;o<e;o++)n[o]=i[o]}n!==null&&(n[e]=r)}return n===null?i:n}var Lp=class i{constructor(n,e){this.expr=n;this.negated=e;this.type=6}static create(n,e,t){return i._normalizeArr(n,e,t)}cmp(n){if(n.type!==this.type)return this.type-n.type;if(this.expr.length<n.expr.length)return-1;if(this.expr.length>n.expr.length)return 1;for(let e=0,t=this.expr.length;e<t;e++){let r=Ld(this.expr[e],n.expr[e]);if(r!==0)return r}return 0}equals(n){if(n.type===this.type){if(this.expr.length!==n.expr.length)return!1;for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].equals(n.expr[e]))return!1;return!0}return!1}substituteConstants(){let n=VT(this.expr);return n===this.expr?this:i.create(n,this.negated,!1)}evaluate(n){for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].evaluate(n))return!1;return!0}static _normalizeArr(n,e,t){let r=[],o=!1;for(let s of n)if(s){if(s.type===1){o=!0;continue}if(s.type===0)return Wt.INSTANCE;if(s.type===6){r.push(...s.expr);continue}r.push(s)}if(r.length===0&&o)return Yt.INSTANCE;if(r.length!==0){if(r.length===1)return r[0];r.sort(Ld);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=qd.create(s.expr.map(c=>i.create([c,a],null,t)),null,l);d&&(r.push(d),r.sort(Ld))}if(r.length===1)return r[0];if(t){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(n=>n.serialize()).join(" && ")}keys(){let n=[];for(let e of this.expr)n.push(...e.keys());return n}map(n){return new i(this.expr.map(e=>e.map(n)),null)}negate(){if(!this.negated){let n=[];for(let e of this.expr)n.push(e.negate());this.negated=qd.create(n,this,!0)}return this.negated}},qd=class i{constructor(n,e){this.expr=n;this.negated=e;this.type=9}static create(n,e,t){return i._normalizeArr(n,e,t)}cmp(n){if(n.type!==this.type)return this.type-n.type;if(this.expr.length<n.expr.length)return-1;if(this.expr.length>n.expr.length)return 1;for(let e=0,t=this.expr.length;e<t;e++){let r=Ld(this.expr[e],n.expr[e]);if(r!==0)return r}return 0}equals(n){if(n.type===this.type){if(this.expr.length!==n.expr.length)return!1;for(let e=0,t=this.expr.length;e<t;e++)if(!this.expr[e].equals(n.expr[e]))return!1;return!0}return!1}substituteConstants(){let n=VT(this.expr);return n===this.expr?this:i.create(n,this.negated,!1)}evaluate(n){for(let e=0,t=this.expr.length;e<t;e++)if(this.expr[e].evaluate(n))return!0;return!1}static _normalizeArr(n,e,t){let r=[],o=!1;if(n){for(let s=0,a=n.length;s<a;s++){let l=n[s];if(l){if(l.type===0){o=!0;continue}if(l.type===1)return Yt.INSTANCE;if(l.type===9){r=r.concat(l.expr);continue}r.push(l)}}if(r.length===0&&o)return Wt.INSTANCE;r.sort(Ld)}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(t){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 Yt.INSTANCE;if(r.length===1)return r[0]}return new i(r,e)}}serialize(){return this.expr.map(n=>n.serialize()).join(" || ")}keys(){let n=[];for(let e of this.expr)n.push(...e.keys());return n}map(n){return new i(this.expr.map(e=>e.map(n)),null)}negate(){if(!this.negated){let n=[];for(let e of this.expr)n.push(e.negate());for(;n.length>1;){let e=n.shift(),t=n.shift(),r=[];for(let o of zT(e))for(let s of zT(t))r.push(Lp.create([o,s],null,!1));n.unshift(i.create(r,null,!1))}this.negated=i.create(n,this,!0)}return this.negated}},Np=class i extends qo{static{this._info=[]}static all(){return i._info.values()}constructor(n,e,t){super(n,null),this._defaultValue=e,typeof t=="object"?i._info.push({...t,key:n}):t!==!0&&i._info.push({key:n,description:t,type:e!=null?typeof e:void 0})}bindTo(n){return n.createKey(this.key,this._defaultValue)}getValue(n){return n.getContextKeyValue(this.key)}toNegated(){return this.negate()}isEqualTo(n){return Nd.create(this.key,n)}notEqualsTo(n){return Ud.create(this.key,n)}greater(n){return Zs.create(this.key,n)}},Qj=$("contextKeyService");function jT(i,n){return i<n?-1:i>n?1:0}function zo(i,n,e,t){return i<e?-1:i>e?1:n<t?-1:n>t?1:0}function zT(i){return i.type===9?i.expr:[i]}var D=$("logService"),GT=$("loggerService");function lv(i){return So(i)}var JT=3;function RM(i,n){return i!==0&&i<=n}function xM(i,n,e){switch(n){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 ${n}`)}}var YT=!1,KT=!1,PM=!1;function Bd(i,n){switch(i){case"debug":console.debug=n;break;case"error":console.error=n;break;case"info":console.info=n;break;case"log":console.log=n;break;case"warn":console.warn=n;break}}function QT(i){let n={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn},e=(r,o,s)=>{if(!PM){KT=!0;try{xM(i,o,si(s))}catch{}finally{KT=!1}}n[r].apply(console,s)},t={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 Bd("debug",t.debug),Bd("error",t.error),Bd("info",t.info),Bd("log",t.log),Bd("warn",t.warn),M(()=>{console.debug===t.debug&&(console.debug=n.debug),console.error===t.error&&(console.error=n.error),console.info===t.info&&(console.info=n.info),console.log===t.log&&(console.log=n.log),console.warn===t.warn&&(console.warn=n.warn)})}function si(i,n=!1){let e="";for(let t=0;t<i.length;t++){let r=i[t];if(r instanceof Error&&(r=ke(r,n)),typeof r=="object")try{r=JSON.stringify(r)}catch{}e+=(t>0?" ":"")+r}return e}var Fp=class extends T{constructor(){super(...arguments);this.level=JT;this._onDidChangeLogLevel=this._register(new P)}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 RM(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},Vo=class extends Fp{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...t){this.canLog(1)&&this.log(1,si([e,...t],!0))}debug(e,...t){this.canLog(2)&&this.log(2,si([e,...t]))}info(e,...t){this.canLog(3)&&this.log(3,si([e,...t]))}warn(e,...t){this.canLog(4)&&this.log(4,si([e,...t]))}error(e,...t){if(this.canLog(5))if(e instanceof Error){let r=Array.prototype.slice.call(arguments);r[0]=e.stack,this.log(5,si(r))}else this.log(5,si([e,...t]))}flush(){}};var Hp=class extends Fp{constructor(e){super();this.loggers=e;e.length&&this.setLevel(e[0].getLevel())}setLevel(e){for(let t of this.loggers)t.setLevel(e);super.setLevel(e)}trace(e,...t){for(let r of this.loggers)r.trace(e,...t)}debug(e,...t){for(let r of this.loggers)r.debug(e,...t)}info(e,...t){for(let r of this.loggers)r.info(e,...t)}warn(e,...t){for(let r of this.loggers)r.warn(e,...t)}error(e,...t){for(let r of this.loggers)r.error(e,...t)}flush(){for(let e of this.loggers)e.flush()}dispose(){for(let e of this.loggers)e.dispose();super.dispose()}},zd=class extends T{constructor(e,t,r){super();this.logLevel=e;this.logsHome=t;this._loggers=new We;this._onDidChangeLoggers=this._register(new P);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new P);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new P);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 Ve(e)?[...this._loggers.values()].find(t=>t.info.id===e):this._loggers.get(e)}getLogger(e){return this.getLoggerEntry(e)?.logger}createLogger(e,t){let r=this.toResource(e),o=Ve(e)?e:t?.id??br(r.toString()).toString(16),s=this._loggers.get(r)?.logger,a=t?.logLevel==="always"?1:t?.logLevel;s||(s=this.doCreateLogger(r,a??this.getLogLevel(r)??this.logLevel,{...t,id:o}));let l={logger:s,info:{resource:r,id:o,logLevel:a,name:t?.name,hidden:t?.hidden,group:t?.group,extensionId:t?.extensionId,when:t?.when}};return this.registerLogger(l.info),this._loggers.set(r,l),s}toResource(e){return Ve(e)?te(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,t){if(v.isUri(e)){let r=e,o=t,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,t){let r=this.getLoggerEntry(e);r&&t!==!r.info.hidden&&(r.info.hidden=!t,this._loggers.set(r.info.resource,r),this._onDidChangeVisibility.fire([r.info.resource,t]))}getLogLevel(e){let t;return e&&(t=this._loggers.get(e)?.info.logLevel),t??this.logLevel}registerLogger(e){let t=this._loggers.get(e.resource);t?t.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 t=this.toResource(e),r=this._loggers.get(t);r&&(r.logger&&r.logger.dispose(),this._loggers.delete(t),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()}},av=class{constructor(){this.onDidChangeLogLevel=new P().event}setLevel(n){}getLevel(){return 3}trace(n,...e){}debug(n,...e){}info(n,...e){}warn(n,...e){}error(n,...e){}critical(n,...e){}dispose(){}flush(){}},$p=class extends av{};function XT(i){if(i.verbose)return 1;if(typeof i.logLevel=="string"){let n=EM(i.logLevel.toLowerCase());if(n!==void 0)return n}return JT}function AM(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 EM(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 fK=new Np("logLevel",AM(3));var Je=$("sessionDataService"),ea="session.db",Wp="attachments";var iw="branch",ow="uncommitted",sw="session",qp="turn/",aw="{turnId}",Bp="compare/",lw="{originalTurnId}",dw="{modifiedTurnId}",kM=()=>f(1946,null),ZT=()=>f(1950,null),ew=()=>f(1949,null),DM=()=>f(1954,null),MM=()=>f(1953,null),tw=()=>f(1952,null),nw=()=>f(1951,null),OM=()=>f(1948,null),LM=()=>f(1947,null);function NM(i){let{baseBranchName:n,branchName:e,upstreamBranchName:t}=i;return n&&e?`${e} \u2192 ${n}`:t&&e?`${e} \u2192 ${t}`:e}var ai="/changeset/";function di(i){return`${i}${ai}${iw}`}function li(i){return`${i}${ai}${sw}`}function Bi(i){return`${i}${ai}${ow}`}function rw(i){return`${i}${ai}${qp}${aw}`}function zp(i,n){if(!n||n.includes("/"))throw new Error(`buildTurnChangesetUri: turnId must be non-empty and not contain '/' (got ${JSON.stringify(n)})`);return`${i}${ai}${qp}${n}`}function UM(i){return`${i}${ai}${Bp}${lw}/${dw}`}function cw(i,n,e){if(!n||n.includes("/"))throw new Error(`buildCompareTurnsChangesetUri: originalTurnId must be non-empty and not contain '/' (got ${JSON.stringify(n)})`);if(!e||e.includes("/"))throw new Error(`buildCompareTurnsChangesetUri: modifiedTurnId must be non-empty and not contain '/' (got ${JSON.stringify(e)})`);return`${i}${ai}${Bp}${n}/${e}`}function et(i){let n=i.lastIndexOf(ai);if(n<0)return;let e=i.slice(n+ai.length);if(!e)return;let t=i.slice(0,n);if(e===iw)return{sessionUri:t,changesetId:e,kind:"branch"};if(e===ow)return{sessionUri:t,changesetId:e,kind:"uncommitted"};if(e===sw)return{sessionUri:t,changesetId:e,kind:"session"};if(e.startsWith(qp)){let r=e.slice(qp.length);return!r||r.includes("/")||r===aw?void 0:{sessionUri:t,changesetId:e,kind:"turn",turnId:r}}if(e.startsWith(Bp)){let o=e.slice(Bp.length).split("/");if(o.length!==2)return;let[s,a]=o;return!s||!a||s===lw||a===dw?void 0:{sessionUri:t,changesetId:e,kind:"compare-turns",originalTurnId:s,modifiedTurnId:a}}if(!e.includes("/"))return{sessionUri:t,changesetId:e,kind:"unknown"}}function uw(i,n){return n?[{label:kM(),description:n?NM(n):void 0,uriTemplate:di(i),changeKind:"branch"},{label:DM(),description:MM(),uriTemplate:Bi(i),changeKind:"uncommitted"},{label:ZT(),description:ew(),uriTemplate:li(i),changeKind:"session"},{label:tw(),description:nw(),uriTemplate:rw(i),changeKind:"turn"},{label:OM(),description:LM(),uriTemplate:UM(i),changeKind:"compare-turns"}]:[{label:ZT(),description:ew(),uriTemplate:li(i),changeKind:"session"},{label:tw(),description:nw(),uriTemplate:rw(i),changeKind:"turn"}]}function pw(i){return i.type.startsWith("root/")}function Vd(i){return i.type.startsWith("session/")}function rr(i){return i.type.startsWith("chat/")}function Vp(i){return i.type.startsWith("terminal/")}function dv(i){return i.type.startsWith("changeset/")}function cv(i){return i.type.startsWith("annotations/")}var Ct=$("productService");import*as jd from"fs";var qt=pn({customizations:we({type:"array",title:f(1852,null),description:f(1848,null),default:[],items:{type:"object",title:f(1851,null),properties:{uri:{type:"string",title:f(1853,null)},displayName:{type:"string",title:f(1850,null)},description:{type:"string",title:f(1849,null)}},required:["uri","displayName"]}}),defaultShell:we({type:"string",title:f(1855,null),description:f(1854,null)}),enableCustomTerminalTool:we({type:"boolean",title:f(1857,null),description:f(1856,null),default:!1}),rubberDuck:we({type:"boolean",title:f(1861,null),description:f(1860,null),default:!1}),opus48Prompt:we({type:"boolean",title:f(1859,null),description:f(1858,null),default:!1}),claudeUseCopilotProxy:we({type:"boolean",title:f(1847,null),description:f(1846,null),default:!0})}),fw={customizations:[]};function gw(i){return{type:"plugin",id:Ot(i.uri),uri:i.uri,name:i.displayName,enabled:!0}}function uv(i){return i===!0?"on":i===!1?"off":i}function pv(i){return i!==void 0&&uv(i)!=="off"}var Cr=pn({sandbox:we({type:"object",title:f(1981,null),properties:{enabled:{type:"string",title:f(1978,null),enum:["off","on","allowNetwork"]},"enabled.windows":{type:"string",title:f(1982,null),enum:["off","on","allowNetwork"]},allowNetwork:{type:"boolean",title:f(1974,null)},allowUnsandboxedCommands:{type:"boolean",title:f(1975,null)},"fileSystem.linux":{type:"object",title:f(1979,null)},"fileSystem.mac":{type:"object",title:f(1980,null)},"fileSystem.windows":{type:"object",title:f(1983,null)},"advanced.runtime":{type:"object",title:f(1971,null)},allowedNetworkDomains:{type:"array",title:f(1973,null),items:{type:"string",title:f(1972,null)}},deniedNetworkDomains:{type:"array",title:f(1977,null),items:{type:"string",title:f(1976,null)}}}})}),hw={"chat.agent.sandbox.enabled":"enabled","chat.agent.sandbox.enabledWindows":"enabled.windows","chat.agent.sandbox.allowNetwork":"allowNetwork","chat.agent.sandbox.allowUnsandboxedCommands":"allowUnsandboxedCommands","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 ze=$("agentConfigurationService"),ta=class extends T{constructor(e,t,r){super();this._stateManager=e;this._logService=t;this._rootConfigResource=r;this._rootConfigWrite=Promise.resolve();this._onDidRootConfigChange=this._register(new P);this.onDidRootConfigChange=this._onDidRootConfigChange.event;let o=this._stateManager.rootState.config,s=qt.toProtocol(),a=Cr.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,t,r){for(let o of this._effectiveChain(e)){let s=o[r];if(s!==void 0)try{return t.assertValid(r,s),s}catch(a){let l=a instanceof k?a.message:String(a);this._logService.warn(`[AgentConfigurationService] Value for '${r}' on ${e} failed schema validation, falling back: ${l}`)}}}getEffectiveWorkingDirectory(e){let t=this._stateManager.getSessionState(e)?.workingDirectory;if(t!==void 0)return t;let r=gt(e);if(r)return this._stateManager.getSessionState(r.parentSession.toString())?.workingDirectory}updateSessionConfig(e,t){this._stateManager.dispatchServerAction(e,{type:"session/configChanged",config:t})}getSessionConfigValues(e){return this._stateManager.getSessionState(e)?.config?.values}getRootValue(e,t){let o=this._stateManager.rootState.config?.values?.[t];if(o!==void 0)try{return e.assertValid(t,o),o}catch(s){let a=s instanceof k?s.message:String(s);this._logService.warn(`[AgentConfigurationService] Host value for '${t}' failed schema validation, ignoring: ${a}`);return}}updateRootConfig(e,t=!1){this._stateManager.dispatchServerAction(Ke,{type:"root/configChanged",config:e,replace:t}),this.persistRootConfig()}persistRootConfig(){if(!this._rootConfigResource)return;let e=this._stateManager.rootState.config?.values??{customizations:[]},t=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 jd.promises.mkdir(le(r.fsPath),{recursive:!0}),await jd.promises.writeFile(r.fsPath,`${t}
`,"utf8")}).catch(o=>{this._logService.error(`[AgentConfigurationService] Failed to persist host config to ${r.fsPath}`,o)})}async whenIdle(){await this._rootConfigWrite}*_effectiveChain(e){let t=this._stateManager.getSessionState(e)?.config?.values;t&&(yield t);let r=gt(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=fw;if(!this._rootConfigResource)return{...e};try{let t=jd.readFileSync(this._rootConfigResource.fsPath,"utf8"),r=JSON.parse(t);return{...qt.validateOrDefault(r,e),...Cr.validateOrDefault(r,{})}}catch(t){return(t&&typeof t=="object"&&me(t,{code:!0})?String(t.code):void 0)!=="ENOENT"&&this._logService.warn(`[AgentConfigurationService] Failed to read host config from ${this._rootConfigResource.fsPath}: ${t instanceof Error?t.message:String(t)}`),{...e}}}};ta=w([C(1,D)],ta);import*as Go from"fs";import{userInfo as JM}from"os";import*as fv from"os";var yw=/^\d+$/,WM=/^Microsoft.PowerShell_.*/,qM=/^Microsoft.PowerShellPreview_.*/;var Kd;switch(process.arch){case"ia32":Kd=1;break;case"arm":case"arm64":Kd=2;break;default:Kd=0;break}var ra;process.env.PROCESSOR_ARCHITEW6432?ra=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?ra=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?ra=1:ra=0;var jo=class{constructor(n,e,t){this.exePath=n;this.displayName=e;this.knownToExist=t}async exists(){return this.knownToExist===void 0&&(this.knownToExist=await en.existsFile(this.exePath)),this.knownToExist}};function BM({useAlternateBitness:i=!1}={}){return i?Kd===0?process.env["ProgramFiles(x86)"]||null:ra===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function jp({useAlternateBitness:i=!1,findPreview:n=!1}={}){let e=BM({useAlternateBitness:i});if(!e)return null;let t=j(e,"PowerShell");if(!await en.existsDirectory(t))return null;let r=-1,o=null;for(let l of await Ne.readdir(t)){let d=-1;if(n){let u=l.indexOf("-");if(u<0)continue;let p=l.substring(0,u);if(!yw.test(p)||l.substring(u+1)!=="preview")continue;d=parseInt(p,10)}else{if(!yw.test(l))continue;d=parseInt(l,10)}if(d<=r)continue;let c=j(t,l,"pwsh.exe");await en.existsFile(c)&&(o=c,r=d)}if(!o)return null;let s=e.includes("x86")?" (x86)":"",a=n?" Preview":"";return new jo(o,`PowerShell${a}${s}`,!0)}async function vw({findPreview:i}={}){if(!process.env.LOCALAPPDATA)return null;let n=j(process.env.LOCALAPPDATA,"Microsoft","WindowsApps");if(!await en.existsDirectory(n))return null;let{pwshMsixDirRegex:e,pwshMsixName:t}=i?{pwshMsixDirRegex:qM,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:WM,pwshMsixName:"PowerShell (Store)"};for(let r of await Ne.readdir(n))if(e.test(r)){let o=j(n,r,"pwsh.exe");return new jo(o,t)}return null}function zM(){let i=j(fv.homedir(),".dotnet","tools","pwsh.exe");return new jo(i,".NET Core PowerShell Global Tool")}function VM(){let i=j(fv.homedir(),"scoop","apps"),n=j(i,"pwsh","current","pwsh.exe");return new jo(n,"PowerShell (Scoop)")}function jM(){let i=j(process.env.windir,Kd===1&&ra!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new jo(i,"Windows PowerShell",!0)}async function*KM(){let i=await jp();i&&(yield i),i=await jp({useAlternateBitness:!0}),i&&(yield i),i=await vw(),i&&(yield i),i=zM(),i&&(yield i),i=await jp({findPreview:!0}),i&&(yield i),i=await vw({findPreview:!0}),i&&(yield i),i=await jp({useAlternateBitness:!0,findPreview:!0}),i&&(yield i),i=await VM(),i&&(yield i),i=jM(),i&&(yield i)}async function*GM(){for await(let i of KM())await i.exists()&&(yield i)}async function Sw(){for await(let i of GM())return i;return null}async function Kp(i,n){return i===1?Q?QM():R_(n):YM(i,n)}var gv=null;function YM(i,n){if(Oe&&i===2||dt&&i===3)return"/bin/bash";if(!gv){let e;if(Q)e="/bin/bash";else{if(e=n.SHELL,!e)try{e=JM().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}gv=e}return gv}var mv=null;async function QM(){return mv||(mv=(await Sw()).exePath),mv}import*as ia from"os";var hv=class{constructor(){this.data=new Map}add(n,e){Su(Ve(n)),Su(Qe(e)),Su(!this.data.has(n),"There is already an extension with this id"),this.data.set(n,e)}knows(n){return this.data.has(n)}as(n){return this.data.get(n)||null}dispose(){this.data.forEach(n=>{Kl(n.dispose)&&n.dispose()}),this.data.clear()}},Nt=new hv;var yG=$("ptyService");var ZM={Backend:"workbench.contributions.terminal.processBackend"},yv=class{constructor(){this._backends=new Map}get backends(){return this._backends}registerTerminalBackend(n){let e=this._sanitizeRemoteAuthority(n.remoteAuthority);if(this._backends.has(e))throw new Error(`A terminal backend with remote authority '${e}' was already registered.`);this._backends.set(e,n)}getTerminalBackend(n){return this._backends.get(this._sanitizeRemoteAuthority(n))}_sanitizeRemoteAuthority(n){return n?.toLowerCase()??""}};Nt.add(ZM.Backend,new yv);var vG=$("localPtyService"),SG=$("terminalLogService");function eO(i){return new Map(i)}function tO(i){return new Map(i??[])}function bw(i){return new Map(i.map(n=>[n[0],{map:eO(n[1]),descriptionMap:tO(n[2])}]))}var rO=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),iO=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,oO="ms-python.vscode-python-envs",Gp=class{constructor(n){this.collections=n;this.map=new Map;this.descriptionMap=new Map;n.forEach((e,t)=>{this.populateDescriptionMap(e,t);let r=e.map.entries(),o=r.next();for(;!o.done;){let s=o.value[1],a=o.value[0];if(this.blockPythonActivationVar(a,t)){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:t,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(n,e,t){let r;Q&&(r={},Object.keys(n).forEach(o=>r[o.toLowerCase()]=o));for(let[o,s]of this.getVariableMap(e)){let a=Q&&r[o.toLowerCase()]||o;for(let l of s){let d=t?await t(l.value):l.value;if(!this.blockPythonActivationVar(l.variable,l.extensionIdentifier)){if(l.options?.applyAtProcessCreation??!0)switch(l.type){case 2:n[a]=(n[a]||"")+d;break;case 3:n[a]=d+(n[a]||"");break;case 1:n[a]=d;break}if(l.options?.applyAtShellIntegration??!1){let c=`VSCODE_ENV_${rO.get(l.type)}`;n[c]=(n[c]?n[c]+":":"")+o+"="+this._encodeColons(d)}}}}}_encodeColons(n){return n.replaceAll(":","\\x3a")}blockPythonActivationVar(n,e){return!!(iO.test(n)&&oO!==e)}diff(n,e){let t=new Map,r=new Map,o=new Map;if(n.getVariableMap(e).forEach((s,a)=>{let l=this.getVariableMap(e).get(a),d=Iw(s,l);d&&t.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=Iw(s,l);d&&o.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=sO(s,l);d&&r.set(a,d)}),!(t.size===0&&r.size===0&&o.size===0))return{added:t,changed:r,removed:o}}getVariableMap(n){let e=new Map;for(let t of this.map.values()){let r=t.filter(o=>Cw(o,n));r.length>0&&e.set(r[0].variable,r)}return e}getDescriptionMap(n){let e=new Map;for(let t of this.descriptionMap.values()){let r=t.filter(o=>Cw(o,n,!0));for(let o of r)e.set(o.extensionIdentifier,o.description)}return e}populateDescriptionMap(n,e){if(!n.descriptionMap)return;let t=n.descriptionMap.entries(),r=t.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=t.next()}}};function Cw(i,n,e=!1){return i.scope?!!(i.scope.workspaceFolder&&n?.workspaceFolder&&i.scope.workspaceFolder.index===n.workspaceFolder.index):e?n===i.scope:!0}function Iw(i,n){if(!n)return i;let e=new Set;n.forEach(r=>e.add(r.extensionIdentifier));let t=[];return i.forEach(r=>{e.has(r.extensionIdentifier)||t.push(r)}),t.length===0?void 0:t}function sO(i,n){if(!n)return;let e=new Map;n.forEach(r=>e.set(r.extensionIdentifier,r));let t=[];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)&&t.push(o)}),t.length===0?void 0:t}import{chmod as Tw,realpathSync as dO,mkdirSync as cO}from"fs";import{promisify as ww}from"util";import*as Jp from"os";var Gd;async function aO(){if(Gd)return;if(!Q){Gd={release:Jp.release(),buildNumber:0};return}let i,n;try{let e=await import("@vscode/windows-registry"),t="SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",r=e.GetStringRegKey("HKEY_LOCAL_MACHINE",t,"CurrentBuild");r!==void 0&&(i=parseInt(r,10),isNaN(i)&&(i=void 0));let o=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",t,"CurrentMajorVersionNumber"),s=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",t,"CurrentMinorVersionNumber");o!==void 0&&s!==void 0&&r!==void 0&&(n=`${o}.${s}.${r}`)}catch{}finally{Gd={release:n||Jp.release(),buildNumber:i||lO()}}}async function _w(){return Gd||await aO(),Gd.buildNumber}function lO(){let i=/(\d+)\.(\d+)\.(\d+)/g.exec(Jp.release());return i&&i.length===4?parseInt(i[3],10):0}async function Aw(i,n,e,t,r,o=!1){if(!n.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=Q?await _w():0;if(Q&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=i.args,l=Cs==="win32"?Te(i.executable).toLowerCase():Te(i.executable),d=le(Dt.asFileUri("").fsPath),c="injection",u,p={VSCODE_INJECTION:"1"};n.shellIntegration.nonce&&(p.VSCODE_NONCE=n.shellIntegration.nonce);let m=["PATH","VIRTUAL_ENV","HOME","SHELL","PWD"];if(i.shellIntegrationEnvironmentReporting&&(Q?(n.windowsUseConptyDll||s>=22631&&l!=="bash.exe")&&(p.VSCODE_SHELL_ENV_REPORTING=m.join(",")):p.VSCODE_SHELL_ENV_REPORTING=m.join(",")),Q)return l==="pwsh.exe"||l==="powershell.exe"?(p.VSCODE_A11Y_MODE=n.isScreenReaderOptimized?"1":"0",!a||Pw(a)?u=tt.get("windows-pwsh"):xw(a)&&(u=tt.get("windows-pwsh-login")),u?(u=[...u],u[u.length-1]=wo(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=tt.get("bash"):Xp(a)&&(p.VSCODE_SHELL_LOGIN="1",Yp(n,p,l),u=tt.get("bash")),u?(u=[...u],u[u.length-1]=wo(u[u.length-1],d),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"}):(t.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=tt.get("bash"):Xp(a)&&(p.VSCODE_SHELL_LOGIN="1",Yp(n,p,l),u=tt.get("bash")),u?(u=[...u],u[u.length-1]=wo(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=tt.get("fish"):Xp(a)?u=tt.get("fish-login"):(a===tt.get("fish")||a===tt.get("fish-login"))&&(u=a),u?(Yp(n,p,l),u=[...u],u[u.length-1]=wo(u[u.length-1],d),{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||Pw(a)?u=tt.get("pwsh"):xw(a)&&(u=tt.get("pwsh-login")),u?(u=[...u],u[u.length-1]=wo(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=tt.get("zsh"):Xp(a)?(u=tt.get("zsh-login"),Yp(n,p,l)):(a===tt.get("zsh")||a===tt.get("zsh-login"))&&(u=a),!u)return{type:"failure",reason:"unsupportedArgs"};u=[...u],u[u.length-1]=wo(u[u.length-1],d);let h;try{h=ia.userInfo().username}catch{h="unknown"}let y=dO(ia.tmpdir()),S=j(y,`${h}-${r.applicationName}-zsh`);if(!o)try{await ww(Tw)(S,960)}catch(_){if(_.message.includes("ENOENT")){try{cO(S)}catch(R){return t.error(`Failed to create zdotdir at ${S}: ${R}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await ww(Tw)(S,960)}catch{return t.error(`Failed to set sticky bit on ${S}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}}return t.error(`Failed to set sticky bit on ${S}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}p.ZDOTDIR=S;let b=e?.ZDOTDIR??ia.homedir()??"~";p.USER_ZDOTDIR=b;let I=[];return I.push({source:j(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh"),dest:j(S,".zshrc")}),I.push({source:j(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-profile.zsh"),dest:j(S,".zprofile")}),I.push({source:j(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-env.zsh"),dest:j(S,".zshenv")}),I.push({source:j(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-login.zsh"),dest:j(S,".zlogin")}),{type:c,newArgs:u,envMixin:p,filesToCopy:I}}}return t.warn(`Shell integration cannot be enabled for executable "${i.executable}" and args`,i.args),{type:"failure",reason:"unsupportedShell"}}function Yp(i,n,e){if((dt||e==="fish")&&i.environmentVariableCollections){let t=bw(i.environmentVariableCollections),o=new Gp(t).getVariableMap({workspaceFolder:i.workspaceFolder}).get("PATH"),s=[];if(o)for(let a of o)a.type===3&&s.push(a.value);s.length>0&&(n.VSCODE_PATH_PREFIX=s.join(""))}}var tt=new Map;tt.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);tt.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);tt.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);tt.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);tt.set("zsh",["-i"]);tt.set("zsh-login",["-il"]);tt.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);tt.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);tt.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var Qp=["-login","-l"],Rw=["--login","-l"],uO=["-i","--interactive"],Zp=["-nol","-nologo"];function xw(i){return Ve(i)?Qp.includes(i.toLowerCase()):i.length===1&&Qp.includes(i[0].toLowerCase())||i.length===2&&(Qp.includes(i[0].toLowerCase())||Qp.includes(i[1].toLowerCase()))&&(Zp.includes(i[0].toLowerCase())||Zp.includes(i[1].toLowerCase()))}function Pw(i){return Ve(i)?Zp.includes(i.toLowerCase()):i.length===0||i?.length===1&&Zp.includes(i[0].toLowerCase())}function Xp(i){return Ve(i)||(i=i.filter(n=>!uO.includes(n.toLowerCase()))),Ve(i)&&Rw.includes(i.toLowerCase())||!Ve(i)&&i.length===1&&Rw.includes(i[0].toLowerCase())}import pO from"@xterm/headless";var{Terminal:fO}=pO,ef=class extends T{constructor(e){super();this._onResponseData=this._register(new P);this.onResponseData=this._onResponseData.event;this._writeBarrier=Promise.resolve();this._isDisposed=!1;this._logService=e.logService;let t={cols:e.cols,rows:e.rows,scrollback:e.scrollback,allowProposedApi:!0};this._terminal=e.terminalFactory?.(t)??new fO(t),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(t=>{try{this._terminal.write(e,t)}catch{t()}})}),this._writeBarrier}whenPtyDataFlushed(){return this._writeBarrier.catch(()=>{})}resize(e,t){this._terminal.resize(e,t)}isBracketedPasteMode(){return this._terminal.modes.bracketedPasteMode}isInAltBuffer(){return this._terminal.buffer.active===this._terminal.buffer.alternate}createAltBufferPromise(e){let t=new Ee,r=()=>{t.isSettled||(this._logService.debug("[AgentHostHeadlessTerminal] Detected alternate buffer entry"),t.complete())};return this.isInAltBuffer()?r():e.add(this._terminal.buffer.onBufferChange(()=>{this.isInAltBuffer()&&r()})),t.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 tf(i){return Et===1?/^zsh(?:\.exe)?$/i.test(he.basename(i)):/^zsh$/.test(re.basename(i))}function Ew(i){return i.indexOf("\\")===-1?i:i.replaceAll(/\\(\\|x([0-9a-f]{2}))/gi,(n,e,t)=>t?String.fromCharCode(parseInt(t,16)):e)}function gO(i){let n=i.indexOf(";");if((n===-1?i.length:n)!==1)return;let e=i[0],t=n===-1?"":i.substring(n+1);switch(e){case"A":return{type:0};case"B":return{type:1};case"C":return{type:2};case"D":{let r=t.length>0?parseInt(t,10):void 0;return{type:3,exitCode:r!==void 0&&!isNaN(r)?r:void 0}}case"E":{let r=t.indexOf(";"),o=Ew(r===-1?t:t.substring(0,r)),s=r===-1?void 0:t.substring(r+1);return{type:4,commandLine:o,nonce:s}}case"P":{let r=Ew(t),o=r.indexOf("=");return o===-1?void 0:{type:5,key:r.substring(0,o),value:r.substring(o+1)}}default:return}}var bv="\x1B",vv=bv+"]",Sv="\x07",kw=bv+"\\",nf=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(n){let e=[];if(!this._inOsc&&n.indexOf(vv)===-1)return{cleanedData:n,events:e};let t="",r=0;for(;r<n.length;){if(this._inOsc){if(this._pendingEscInOsc){if(this._pendingEscInOsc=!1,n[r]==="\\"){r++,this._inOsc=!1;let d=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(d,e,{value:t,append(c){t=c}},kw);continue}this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:t,append(d){t=d}});continue}let a=this._consumeOscBody(n,r);if(r=a.nextIndex,a.complete){this._inOsc=!1;let l=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(l,e,{value:t,append(d){t=d}},a.terminator)}else a.pendingEsc&&(this._pendingEscInOsc=!0);continue}let o=n.indexOf(vv,r);if(o===-1){t+=n.substring(r),r=n.length;continue}t+=n.substring(r,o),r=o+2,this._pendingOsc="",this._inOsc=!0;let s=this._consumeOscBody(n,r);if(r=s.nextIndex,s.complete){this._inOsc=!1;let a=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(a,e,{value:t,append(l){t=l}},s.terminator)}else s.pendingEsc&&(this._pendingEscInOsc=!0)}return{cleanedData:t,events:e}}_consumeOscBody(n,e){let t=n.indexOf(Sv,e),r=n.indexOf(bv,e);return t!==-1&&(r===-1||t<r)?(this._pendingOsc+=n.substring(e,t),{nextIndex:t+1,complete:!0,terminator:Sv}):r!==-1?r+1>=n.length?(this._pendingOsc+=n.substring(e,r),{nextIndex:n.length,complete:!1,pendingEsc:!0}):(this._pendingOsc+=n.substring(e,r),n[r+1]==="\\"?{nextIndex:r+2,complete:!0,terminator:kw}:{nextIndex:r,complete:!0}):(this._pendingOsc+=n.substring(e),{nextIndex:n.length,complete:!1})}_handleOscPayload(n,e,t,r=Sv){if(n.startsWith("633;")){let o=n.substring(4),s=gO(o);s&&e.push(s)}else t&&t.append(t.value+vv+n+r)}};var mO=1e4,hO=0,Cv="\x1B[6n",Iv="\x1B[?6n",yO=["\x1B[?6","\x1B[?","\x1B[6","\x1B[","\x1B"],Ir=$("agentHostTerminalManager");function vO(i,n){if(!n.pendingData&&!i.includes(Cv)&&!i.includes(Iv)&&!Dw(i))return i;let e=n.pendingData+i,t=Dw(e),r=t?e.substring(0,e.length-t.length):e;return n.pendingData=t,!r.includes(Cv)&&!r.includes(Iv)?r:r.replaceAll(Iv,"").replaceAll(Cv,"")}function Dw(i){for(let n of yO)if(i.endsWith(n))return n;return""}function SO(i,n){return n.forceBracketedPasteMode&&(i=`\x1B[200~${i}\x1B[201~`),i=i.replace(/\r?\n/g,"\r"),n.shouldExecute&&!i.endsWith("\r")&&(i+="\r"),i}var _v;async function bO(){return _v||(_v=await import("node-pty")),_v}var oa=class extends T{constructor(e,t,r,o){super();this._stateManager=e;this._logService=t;this._productService=r;this._configurationService=o;this._terminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(s=>{let a=s.action;if(!Vp(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 t=this._terminals.get(e);if(t)return{title:t.title,cwd:t.cwd,cols:t.cols,rows:t.rows,content:t.content,exitCode:t.exitCode,claim:t.claim,supportsCommandDetection:t.commandTracker?.detectionAvailableEmitted}}async createTerminal(e,t){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=t?.shell??await this.getDefaultShell(),d=Q?"cmd":"xterm-256color";this._logService.info(`[TerminalManager] Creating terminal ${r}: shell=${l}, cwd=${o}, cols=${s}, rows=${a}`);let c=H(),u={...process.env};t?.preventShellHistory&&(u.VSCODE_PREVENT_SHELL_HISTORY="1"),e.claim?.kind==="session"&&tf(l)&&(u.VSCODE_AGENT_ZSH_FIXUPS="1"),t?.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=[];dt&&hI(l).name.match(/(zsh|bash)/)&&(p=["--login"]);let m=await Aw({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[K,N]of Object.entries(m.envMixin))N!==void 0&&(u[K]=N);if(m.newArgs&&(p=m.newArgs),m.filesToCopy)for(let K of m.filesToCopy)try{await Go.promises.mkdir(le(K.dest),{recursive:!0}),await Go.promises.copyFile(K.source,K.dest)}catch{}h={parser:new nf,nonce:c,commandCounter:0,detectionAvailableEmitted:!1}}else this._logService.info(`[TerminalManager] Shell integration not available for ${r}: ${m.reason}`);let y=await this._spawnPty(l,p,{name:d,cwd:o,env:u,cols:s,rows:a}),S=new G,b=e.claim??{kind:"client",clientId:""},I=S.add(new P),_=S.add(new P),R=S.add(new P),A=S.add(new P),X=S.add(new ef({cols:s,rows:a,scrollback:hO,logService:this._logService})),E={uri:r,store:S,pty:y,onDataEmitter:I,onExitEmitter:_,onClaimChangedEmitter:R,onCommandFinishedEmitter:A,title:e.name??l,cwd:o,cols:s,rows:a,content:[],contentSize:0,claim:b,commandTracker:h,headlessTerminal:X,terminalQueryFilterState:{pendingData:""}};this._terminals.set(r,E),S.add(X.onResponseData(K=>{this._logService.debug(`[TerminalManager] Writing headless terminal response for ${r}: ${JSON.stringify(K)}`);try{y.write(K)}catch(N){this._logService.debug(`[TerminalManager] Failed to write headless terminal response for ${r}: ${N instanceof Error?N.message:String(N)}`)}})),S.add(M(()=>{try{y.kill()}catch{}}));let z=new Ee,x=y.onData(K=>{E.headlessTerminal?.writePtyData(K),this._handlePtyData(E,K),z.complete()});S.add(M(()=>x.dispose()));let B=y.onExit(K=>{E.exitCode=K.exitCode,E.onExitEmitter.fire(K.exitCode),z.complete(),this._stateManager.dispatchServerAction(r,{type:"terminal/exited",exitCode:K.exitCode}),this._broadcastTerminalList()});if(S.add(M(()=>B.dispose())),!Q){let K=setInterval(()=>{let N=y.process;N&&N!==E.title&&(E.title=N,this._stateManager.dispatchServerAction(r,{type:"terminal/titleChanged",title:N}),this._broadcastTerminalList())},200);S.add(M(()=>clearInterval(K)))}await JI([z.p,Tn(mO)]),this._broadcastTerminalList()}async _spawnPty(e,t,r){return(await bO()).spawn(e,t,r)}_writeInput(e,t){this.writeInput(e,t)}writeInput(e,t){let r=this._terminals.get(e);r&&r.exitCode===void 0&&r.pty.write(t)}async sendText(e,t,r){let o=this._terminals.get(e),s=!1;r.bracketedPasteMode&&(await o?.headlessTerminal?.whenPtyDataFlushed(),s=!!o?.headlessTerminal?.isBracketedPasteMode()),this.writeInput(e,SO(t,{shouldExecute:r.shouldExecute,forceBracketedPasteMode:s}))}onData(e,t){let r=this._terminals.get(e);return r?r.onDataEmitter.event(t):M(()=>{})}onExit(e,t){let r=this._terminals.get(e);return r?r.onExitEmitter.event(t):M(()=>{})}onClaimChanged(e,t){let r=this._terminals.get(e);return r?r.onClaimChangedEmitter.event(t):M(()=>{})}onCommandFinished(e,t){let r=this._terminals.get(e);return r?r.onCommandFinishedEmitter.event(t):M(()=>{})}createAltBufferPromise(e,t){let r=this._terminals.get(e);return r?.headlessTerminal?r.headlessTerminal.createAltBufferPromise(t):new Promise(()=>{})}getContent(e){let t=this._terminals.get(e);if(t)return t.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,t,r){let o=this._terminals.get(e);o&&o.exitCode===void 0&&(o.cols=t,o.rows=r,o.pty.resize(t,r),o.headlessTerminal?.resize(t,r))}_setClaim(e,t){let r=this._terminals.get(e);r&&(r.claim=t,r.onClaimChangedEmitter.fire(t),this._broadcastTerminalList())}_setTitle(e,t){let r=this._terminals.get(e);r&&(r.title=t,this._broadcastTerminalList())}_clearContent(e){let t=this._terminals.get(e);t&&(t.content=[],t.contentSize=0,t.headlessTerminal?.clear())}_handlePtyData(e,t){let r=e.commandTracker,o;if(r){let s=r.parser.parse(t);o=s.cleanedData;for(let a of s.events)this._handleOsc633Event(e,r,a)}else o=t;o=vO(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,t,r){switch(t.detectionAvailableEmitted||(t.detectionAvailableEmitted=!0,this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandDetectionAvailable"})),r.type){case 4:{r.nonce===t.nonce&&(t.pendingCommandLine=r.commandLine);break}case 2:{let o=`cmd-${++t.commandCounter}`,s=t.pendingCommandLine??"",a=Date.now();t.pendingCommandLine=void 0,t.activeCommandId=o,t.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=t.activeCommandId;if(!o)break;let s=t.activeCommandTimestamp!==void 0?Date.now()-t.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}t.activeCommandId=void 0,t.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,t){let r=e.content.length>0?e.content[e.content.length-1]:void 0;r?.type==="command"&&!r.isComplete?(r.output+=t,e.contentSize+=t.length):r?.type==="unclassified"?(r.value+=t,e.contentSize+=t.length):(e.content.push({type:"unclassified",value:t}),e.contentSize+=t.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 t=this._terminals.get(e);t&&(this._terminals.delete(e),t.store.dispose(),this._broadcastTerminalList())}async getDefaultShell(){let e=this._configurationService.getRootValue(qt,"defaultShell");if(e)try{return await Go.promises.access(e,Go.constants.X_OK),e}catch(t){this._logService.warn(`[TerminalManager] Configured defaultShell '${e}' is not accessible, falling back to system shell: ${t instanceof Error?t.message:String(t)}`)}return Kp(Et,process.env)}async _resolveCwd(e,t){let r=e;if(e){let s=v.parse(e);s.scheme==="file"&&s.fsPath&&s.fsPath!=="/"?r=s.fsPath:this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${t}: ${e}`)}try{if(r&&(await Go.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(Ke,{type:"root/terminalsChanged",terminals:this.getTerminalInfos()})}dispose(){for(let e of this._terminals.values())e.store.dispose();this._terminals.clear(),super.dispose()}};oa=w([C(1,D),C(2,Ct),C(3,ze)],oa);var rf=$("diffComputeService"),Mw=5e3;function Ow(i,n,e){switch(i){case"Write":return of(n,"content");case"Edit":return of(n,"new_string");case"MultiEdit":return CO(n,"new_string");case"create":return of(n,"file_text");case"edit":case"str_replace":case"insert":return of(n,"new_str");case"str_replace_editor":return IO(n);case"apply_patch":case"git_apply_patch":return TO(n,e);default:return[]}}function of(i,n){if(typeof i!="object"||i===null)return[];let e=i[n];return typeof e=="string"?[e]:[]}function CO(i,n){if(typeof i!="object"||i===null)return[];let e=i.edits;if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="object"&&r!==null){let o=r[n];typeof o=="string"&&t.push(o)}return t}function IO(i){if(typeof i!="object"||i===null)return[];let n=i;switch(n.command){case"create":return typeof n.file_text=="string"?[n.file_text]:[];case"str_replace":case"insert":return typeof n.new_str=="string"?[n.new_str]:[];default:return[]}}var _O=[/^\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 TO(i,n){let e;if(typeof i=="string")e=i;else if(typeof i=="object"&&i!==null){let l=i;typeof l.input=="string"?e=l.input:typeof l.patch=="string"&&(e=l.patch)}if(!e)return[];let t=new Map,r=[],o;for(let l of e.split(`
`)){let d=!1;for(let c of _O){let u=c.exec(l);if(u&&u[1]){o=u[1],t.has(o)||(t.set(o,[]),r.push(o)),d=!0;break}}d||!o||l.startsWith("+")&&!l.startsWith("+++")&&t.get(o).push(l.slice(1))}let s=l=>l.length===0?"":l.join(`
`)+`
`;if(n!==void 0){let l=t.get(n);return!l||l.length===0?[]:[s(l)]}let a=[];for(let l of r){let d=s(t.get(l));d.length>0&&a.push(d)}return a}function sf(i,n){if(i.length<4||n.length<4)return i===n?1:0;let t=new Map;for(let a=0;a<=i.length-4;a++){let l=i.substring(a,a+4),d=t.get(l)||0;t.set(l,d+1)}for(let a=0;a<=n.length-4;a++){let l=n.substring(a,a+4),d=t.get(l)||0;t.set(l,d-1)}let r=i.length-4+1+n.length-4+1,o=0;for(let a of t.values())o+=Math.abs(a);return(r-o)/r}function wO(i,n){let e=new Set;for(let t=0;t<=i.length-n;t++)e.add(i.substring(t,t+n));return e}function RO(i,n,e){let t=i.length-e+1,r=0;for(let o=0;o<t;o++)n.has(i.substring(o,o+e))&&r++;return r/t}function xO(i,n){if(i.length===0)return 0;let e=4,t=n.length>=e?wO(n,e):void 0,r=0,o=0;for(let s of i){let a=Math.max(1,s.length-e+1),l;s.length===0?l=1:s.length<e?l=n.includes(s)?1:0:t?l=RO(s,t,e):l=0,o+=l*a,r+=a}return o/r}function Lw(i,n,e){let t=sf(n,i);if(t===1)return 1;let r=sf(e,i);return 1-Math.max(r-t,0)/(1-t)}function Nw(i,n,e){return{fourGram:sf(e,n),noRevert:Lw(i,n,e)}}function Uw(i,n,e,t){return{fourGram:e.length===0?sf(t,n):xO(e,t),noRevert:Lw(i,n,t)}}var lf=$("editSurvivalReporterFactory");var wv=[0,5e3,3e4,12e4,3e5,6e5,9e5],Rv=class extends T{constructor(e,t,r,o){super();this._params=e;this._fileService=t;this._logService=r;this._telemetryService=o;this._startTime=Date.now();this._samplesTaken=0;this._scheduleNext()}_scheduleNext(){if(this._samplesTaken>=wv.length){this.dispose();return}let e=Date.now()-this._startTime,t=Math.max(0,wv[this._samplesTaken]-e);this._register(new $u).setIfNotSet(()=>this._takeSample(),t)}async _takeSample(){let e=this._samplesTaken++,t=wv[e];try{let r,o=!1;try{r=(await this._fileService.readFile(v.file(this._params.filePath))).value.toString()}catch(u){if(ii(u)===1)o=!0,r="";else{this._logService.warn(`[EditSurvivalReporter] readFile failed for ${this._params.filePath}, skipping sample: ${u}`),this._scheduleNext();return}}let s=this._params.aiChunks??[],a=s.length>0,l=a?s.reduce((u,p)=>u+p.length,0):0,d=o?{fourGram:0,noRevert:0}:a?Uw(this._params.beforeText,this._params.afterText,s,r):Nw(this._params.beforeText,this._params.afterText,r),c=ce(this._params.sessionUri)?fe(this._params.sessionUri):this._params.sessionUri;if(this._telemetryService.publicLog2("agentHost.trackEditSurvival",{provider:L.provider(c)??"unknown",modelId:this._params.modelId??"",toolName:this._params.toolName??"",agentSessionId:L.id(c),turnId:this._params.turnId,toolCallId:this._params.toolCallId,fileExtension:To(this._params.filePath),survivalRateFourGram:d.fourGram,survivalRateNoRevert:d.noRevert,scoringMode:a?"chunked":"whole-file",aiChunkCount:s.length,aiCharCount:l,timeDelayMs:t,didFileGetDeleted:o?1:0,isCreate:this._params.isCreate?1:0,beforeTextLength:this._params.beforeText.length,afterTextLength:this._params.afterText.length,currentTextLength:o?0:r.length}),o){this.dispose();return}}catch(r){this._logService.warn(`[EditSurvivalReporter] sample failed for ${this._params.filePath}: ${r}`)}this._scheduleNext()}},PO=5*1024*1024,sa=class{constructor(n,e,t){this._fileService=n;this._logService=e;this._telemetryService=t}launch(n){return To(n.filePath).toLowerCase()===".ipynb"?{dispose(){}}:Math.max(n.beforeText.length,n.afterText.length)>PO?{dispose(){}}:new Rv(n,this._fileService,this._logService,this._telemetryService)}};sa=w([C(0,xe),C(1,D),C(2,Hn)],sa);var Hw="session-db";function Vi(i,n,e,t){return v.from({scheme:Hw,authority:Li(U.fromString(i)).toString(),path:`/${encodeURIComponent(n)}/${Li(U.fromString(e))}/${t}/${Te(e)}`}).toString()}function $w(i){let n=v.parse(i);if(n.scheme!==Hw)return;let[,e,t,r]=n.path.split("/");if(!(!e||!t||r!=="before"&&r!=="after"))try{return{sessionUri:hy(n.authority).toString(),toolCallId:decodeURIComponent(e),filePath:hy(t).toString(),part:r}}catch{return}}var zi=class{constructor(n,e,t,r,o,s){this._sessionUri=n;this._db=e;this._fileService=t;this._logService=r;this._diffComputeService=o;this._editSurvivalReporterFactory=s;this._pendingEdits=new Map;this._completedEdits=new Map}async trackEditStart(n){let e=this._readFileWithExistence(n),t={beforeContent:U.fromString(""),beforeExisted:!1,snapshotDone:e.then(({content:r,existed:o})=>{t.beforeContent=r,t.beforeExisted=o})};this._pendingEdits.set(n,t),await t.snapshotDone}async completeEdit(n){let e=this._pendingEdits.get(n);if(!e)return;this._pendingEdits.delete(n),await e.snapshotDone;let t=await this._readFile(n);this._completedEdits.set(n,{beforeContent:e.beforeContent,beforeExisted:e.beforeExisted,afterContent:t})}async takeCompletedEdit(n,e,t,r,o,s){let a=this._completedEdits.get(t);if(!a)return;this._completedEdits.delete(t),s||this._logService.warn(`[FileEditTracker] No modelId for completed edit: ${t} (turn=${n}, toolCall=${e}, tool=${r||"<unknown>"}). Edit-survival telemetry will be emitted with an empty modelId.`);let l=a.beforeContent.buffer,d=a.afterContent.buffer,c=a.beforeContent.toString(),u=a.afterContent.toString(),p=!a.beforeExisted&&d.length>0,m,h;try{let y=await this._diffComputeService.computeDiffCounts(c,u);m=y.added,h=p?0:y.removed}catch(y){this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${t}`,y)}try{await this._db.storeFileEdit({turnId:n,toolCallId:e,filePath:t,kind:p?"create":"edit",beforeContent:l,afterContent:d,addedLines:m,removedLines:h})}catch(y){this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${t}`,y)}return this._editSurvivalReporterFactory.launch({sessionUri:this._sessionUri,turnId:n,toolCallId:e,filePath:t,beforeText:c,afterText:u,isCreate:p,modelId:s,toolName:r,aiChunks:Ow(r,o,t)}),{type:"fileEdit",before:{uri:v.file(t).toString(),content:{uri:Vi(this._sessionUri,e,t,"before")}},after:{uri:v.file(t).toString(),content:{uri:Vi(this._sessionUri,e,t,"after")}},diff:m!==void 0?{added:m,removed:h}:void 0}}async _readFile(n){try{return(await this._fileService.readFile(v.file(n))).value}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),U.fromString("")}}async _readFileWithExistence(n){try{return{content:(await this._fileService.readFile(v.file(n))).value,existed:!0}}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),{content:U.fromString(""),existed:!1}}}};zi=w([C(2,xe),C(3,D),C(4,rf),C(5,lf)],zi);var Ww="git-blob";function xv(i,n,e,t){return v.from({scheme:Ww,path:t,query:JSON.stringify({sessionUri:i,sha:n,repoRelativePath:e})}).toString()}function qw(i){let n;try{n=v.parse(i)}catch{return}if(!(n.scheme!==Ww||!n.query))try{let e=JSON.parse(n.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 AO={"root/agentsChanged":!1,"root/activeSessionsChanged":!1,"root/terminalsChanged":!1,"root/configChanged":!0,"session/ready":!1,"session/creationFailed":!1,"session/chatAdded":!1,"session/chatRemoved":!1,"session/chatUpdated":!1,"session/defaultChatChanged":!1,"session/titleChanged":!0,"session/serverToolsChanged":!1,"session/activeClientSet":!0,"session/activeClientRemoved":!0,"session/inputNeededSet":!1,"session/inputNeededRemoved":!1,"session/customizationsChanged":!1,"session/customizationToggled":!0,"session/customizationUpdated":!1,"session/customizationRemoved":!1,"session/mcpServerStateChanged":!1,"session/isReadChanged":!0,"session/isArchivedChanged":!0,"session/activityChanged":!1,"session/changesetsChanged":!1,"session/configChanged":!0,"session/metaChanged":!1,"chat/turnStarted":!0,"chat/delta":!1,"chat/responsePart":!1,"chat/toolCallStart":!1,"chat/toolCallDelta":!1,"chat/toolCallReady":!1,"chat/toolCallConfirmed":!0,"chat/toolCallComplete":!0,"chat/toolCallResultConfirmed":!0,"chat/toolCallContentChanged":!0,"chat/turnComplete":!1,"chat/turnCancelled":!0,"chat/error":!1,"chat/activityChanged":!1,"chat/usage":!1,"chat/reasoning":!1,"chat/pendingMessageSet":!0,"chat/pendingMessageRemoved":!0,"chat/queuedMessagesReordered":!0,"chat/draftChanged":!0,"chat/inputRequested":!1,"chat/inputAnswerChanged":!0,"chat/inputCompleted":!0,"chat/truncated":!0,"changeset/statusChanged":!1,"changeset/fileSet":!1,"changeset/fileRemoved":!1,"changeset/contentChanged":!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 xn(i,n){let e=`Unhandled action type: ${JSON.stringify(i)}`;(n??console.warn)(e)}function Jd(i,n,e){switch(n.type){case"root/agentsChanged":return{...i,agents:n.agents};case"root/activeSessionsChanged":return{...i,activeSessions:n.activeSessions};case"root/terminalsChanged":return{...i,terminals:n.terminals};case"root/configChanged":return i.config?{...i,config:{...i.config,values:n.replace?{...n.config}:{...i.config.values,...n.config}}}:i;default:return xn(n,e),i}}var EO=31;function Bw(i,n,e){return e?i|n:i&~n}function zw(i,n){return n.length>0?i&~EO|24:i&-17}function Yd(i,n,e){switch(n.type){case"session/ready":return{...i,lifecycle:"ready"};case"session/creationFailed":return{...i,lifecycle:"creationFailed",creationError:n.error};case"session/chatAdded":{let t=i.chats,r=t.findIndex(s=>s.resource===n.summary.resource);if(r<0)return{...i,chats:[...t,n.summary]};let o=t.slice();return o[r]=n.summary,{...i,chats:o}}case"session/chatRemoved":{let t=i.chats,r=t.findIndex(a=>a.resource===n.chat);if(r<0)return i;let o=t.slice();o.splice(r,1);let s={...i,chats:o};return i.defaultChat===n.chat&&delete s.defaultChat,s}case"session/chatUpdated":{let t=i.chats,r=t.findIndex(l=>l.resource===n.chat);if(r<0)return i;let{resource:o,...s}=n.changes,a=t.slice();return a[r]={...t[r],...s},{...i,chats:a}}case"session/defaultChatChanged":return{...i,defaultChat:n.defaultChat};case"session/titleChanged":return{...i,title:n.title};case"session/isReadChanged":return{...i,status:Bw(i.status,32,n.isRead)};case"session/isArchivedChanged":return{...i,status:Bw(i.status,64,n.isArchived)};case"session/activityChanged":return{...i,activity:n.activity};case"session/changesetsChanged":{let{changesets:t,...r}=i;return n.changesets?{...r,changesets:n.changesets}:r}case"session/configChanged":return i.config?{...i,config:{...i.config,values:n.replace?{...n.config}:{...i.config.values,...n.config}}}:i;case"session/metaChanged":return{...i,_meta:n._meta};case"session/serverToolsChanged":return{...i,serverTools:n.tools};case"session/activeClientSet":{let t=i.activeClients,r=t.findIndex(s=>s.clientId===n.activeClient.clientId);if(r<0)return{...i,activeClients:[...t,n.activeClient]};let o=t.slice();return o[r]=n.activeClient,{...i,activeClients:o}}case"session/activeClientRemoved":{let t=i.activeClients,r=t.findIndex(s=>s.clientId===n.clientId);if(r<0)return i;let o=t.slice();return o.splice(r,1),{...i,activeClients:o}}case"session/inputNeededSet":{let t=i.inputNeeded??[],r=t.findIndex(s=>s.id===n.request.id),o=r<0?[...t,n.request]:t.slice();return r>=0&&(o[r]=n.request),{...i,inputNeeded:o,status:zw(i.status,o)}}case"session/inputNeededRemoved":{let t=i.inputNeeded;if(!t)return i;let r=t.findIndex(a=>a.id===n.id);if(r<0)return i;let o=t.slice();o.splice(r,1);let s={...i,status:zw(i.status,o)};return o.length>0?s.inputNeeded=o:delete s.inputNeeded,s}case"session/customizationsChanged":return{...i,customizations:n.customizations};case"session/customizationToggled":{let t=i.customizations;if(!t)return i;let r=t.findIndex(s=>s.id===n.id);if(r<0)return i;let o=[...t];return o[r]={...t[r],enabled:n.enabled},{...i,customizations:o}}case"session/customizationUpdated":{let t=i.customizations??[],r=t.findIndex(s=>s.id===n.customization.id);if(r<0)return{...i,customizations:[...t,n.customization]};let o=[...t];return o[r]=n.customization,{...i,customizations:o}}case"session/customizationRemoved":{let t=i.customizations;if(!t)return i;let r=t.findIndex(a=>a.id===n.id);if(r>=0){let a=t.slice();return a.splice(r,1),{...i,customizations:a}}let o=!1,s=t.map(a=>{if(a.type==="mcpServer")return a;let l=a.children;if(!l)return a;let d=l.findIndex(u=>u.id===n.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 t=i.customizations;if(!t)return i;let r=t.findIndex(a=>a.id===n.id);if(r>=0){let a=t[r];if(a.type!=="mcpServer")return i;let l={...a,state:n.state,channel:n.channel},d=t.slice();return d[r]=l,{...i,customizations:d}}let o=!1,s=t.map(a=>{if(a.type==="mcpServer")return a;let l=a.children;if(!l)return a;let d=l.findIndex(m=>m.id===n.id);if(d<0)return a;let c=l[d];if(c.type!=="mcpServer")return a;o=!0;let u={...c,state:n.state,channel:n.channel},p=l.slice();return p[d]=u,{...a,children:p}});return o?{...i,customizations:s}:i}default:return xn(n,e),i}}function jw(i){return{toolCallId:i.toolCallId,toolName:i.toolName,displayName:i.displayName,intention:i.intention,contributor:i.contributor,_meta:i._meta}}function df(i,n){return{...jw(i),_meta:n??i._meta}}function kO(i,n){if(!(!n||!i))return i.find(e=>e.id===n)}function DO(i){return i.activeTurn?i.activeTurn.responseParts.some(n=>n.kind==="toolCall"&&(n.toolCall.status==="pending-confirmation"||n.toolCall.status==="pending-result-confirmation")):!1}var MO=31;function Kw(i,n,e){return e?i|n:i&~n}function la(i,n){let e;return n?e=n:(i.inputRequests?.length??0)>0||DO(i)?e=24:i.activeTurn?e=8:e=1,i.status&~MO|e}function cf(i){let n=la(i);return n===i.status?i:{...i,status:n}}function Pv(i,n,e,t,r){if(!i.activeTurn||i.activeTurn.id!==n)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",...jw(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,modifiedAt:new Date(Date.now()).toISOString()};return delete l.inputRequests,{...l,status:la(l,t)}}function OO(i,n){let e=i.inputRequests??[],t=e.findIndex(s=>s.id===n.id),r=[...e];if(t>=0){let s=n.answers??r[t].answers;r[t]={...n,answers:s}}else r.push(n);let o={...i,inputRequests:r};return{...o,status:Kw(la(o),32,!1),modifiedAt:new Date(Date.now()).toISOString()}}function aa(i,n,e,t){let r=i.activeTurn;if(!r||r.id!==n)return i;let o=!1,s=r.responseParts.map(a=>{if(a.kind==="toolCall"&&a.toolCall.toolCallId===e){let l=t(a.toolCall);return l===a.toolCall?a:(o=!0,{...a,toolCall:l})}return a});return o?{...i,activeTurn:{...r,responseParts:s}}:i}function Vw(i,n,e,t){let r=i.activeTurn;if(!r||r.id!==n)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,t(a)):a);return o?{...i,activeTurn:{...r,responseParts:s}}:i}function Qd(i,n,e){switch(n.type){case"chat/turnStarted":{let t={...i,activeTurn:{id:n.turnId,message:n.message,responseParts:[],usage:void 0}};if(t={...t,status:Kw(la(t),32,!1),modifiedAt:new Date(Date.now()).toISOString()},n.queuedMessageId&&(t.steeringMessage?.id===n.queuedMessageId&&(t={...t,steeringMessage:void 0}),t.queuedMessages)){let r=t.queuedMessages.filter(o=>o.id!==n.queuedMessageId);t={...t,queuedMessages:r.length>0?r:void 0}}return t}case"chat/delta":return Vw(i,n.turnId,n.partId,t=>t.kind==="markdown"?{...t,content:t.content+n.content}:t);case"chat/responsePart":return!i.activeTurn||i.activeTurn.id!==n.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,n.part]}};case"chat/turnComplete":return Pv(i,n.turnId,"complete");case"chat/turnCancelled":return Pv(i,n.turnId,"cancelled");case"chat/error":return Pv(i,n.turnId,"error",2,n.error);case"chat/activityChanged":return{...i,activity:n.activity};case"chat/toolCallStart":return!i.activeTurn||i.activeTurn.id!==n.turnId?i:{...i,activeTurn:{...i.activeTurn,responseParts:[...i.activeTurn.responseParts,{kind:"toolCall",toolCall:{toolCallId:n.toolCallId,toolName:n.toolName,displayName:n.displayName,intention:n.intention,contributor:n.contributor,_meta:n._meta,status:"streaming"}}]}};case"chat/toolCallDelta":return aa(i,n.turnId,n.toolCallId,t=>t.status!=="streaming"?t:{...t,...n._meta!==void 0?{_meta:n._meta}:{},partialInput:(t.partialInput??"")+n.content,invocationMessage:n.invocationMessage??t.invocationMessage});case"chat/toolCallReady":return cf(aa(i,n.turnId,n.toolCallId,t=>{if(t.status!=="streaming"&&t.status!=="running")return t;let r=df(t,n._meta);return n.confirmed?{status:"running",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:n.confirmed}:{status:"pending-confirmation",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmationTitle:n.confirmationTitle,edits:n.edits,editable:n.editable,...n.options?{options:n.options}:{}}}));case"chat/toolCallConfirmed":return cf(aa(i,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-confirmation")return t;let r=df(t,n._meta),o=kO(t.options,n.selectedOptionId);return n.approved?{status:"running",...r,invocationMessage:t.invocationMessage,toolInput:n.editedToolInput??t.toolInput,confirmed:n.confirmed,...o?{selectedOption:o}:{}}:{status:"cancelled",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,reason:n.reason,reasonMessage:n.reasonMessage,userSuggestion:n.userSuggestion,...o?{selectedOption:o}:{}}}));case"chat/toolCallComplete":return cf(aa(i,n.turnId,n.toolCallId,t=>{if(t.status!=="running"&&t.status!=="pending-confirmation")return t;let r=df(t,n._meta),o=t.status==="running"?t.confirmed:"not-needed",s=t.status==="running"?t.selectedOption:void 0;return n.requiresResultConfirmation?{status:"pending-result-confirmation",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:o,...s?{selectedOption:s}:{},...n.result}:{status:"completed",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:o,...s?{selectedOption:s}:{},...n.result}}));case"chat/toolCallResultConfirmed":return cf(aa(i,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-result-confirmation")return t;let r=df(t,n._meta);return n.approved?{status:"completed",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed,...t.selectedOption?{selectedOption:t.selectedOption}:{},success:t.success,pastTenseMessage:t.pastTenseMessage,content:t.content,structuredContent:t.structuredContent,error:t.error}:{status:"cancelled",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,reason:"result-denied",...t.selectedOption?{selectedOption:t.selectedOption}:{}}}));case"chat/toolCallContentChanged":return aa(i,n.turnId,n.toolCallId,t=>t.status!=="running"?t:{...t,...n._meta!==void 0?{_meta:n._meta}:{},content:n.content});case"chat/usage":return!i.activeTurn||i.activeTurn.id!==n.turnId?i:{...i,activeTurn:{...i.activeTurn,usage:n.usage}};case"chat/reasoning":return Vw(i,n.turnId,n.partId,t=>t.kind==="reasoning"?{...t,content:t.content+n.content}:t);case"chat/truncated":{let t;if(n.turnId===void 0)t=[];else{let o=i.turns.findIndex(s=>s.id===n.turnId);if(o<0)return i;t=i.turns.slice(0,o+1)}let r={...i,turns:t,activeTurn:void 0,modifiedAt:new Date(Date.now()).toISOString()};return delete r.inputRequests,{...r,status:la(r)}}case"chat/inputRequested":return OO(i,n.request);case"chat/inputAnswerChanged":{let t=i.inputRequests,r=t?.findIndex(l=>l.id===n.requestId)??-1;if(!t||r<0)return i;let o=t[r],s={...o.answers??{}};n.answer===void 0?delete s[n.questionId]:s[n.questionId]=n.answer;let a=[...t];return a[r]={...o,answers:Object.keys(s).length>0?s:void 0},{...i,inputRequests:a,modifiedAt:new Date(Date.now()).toISOString()}}case"chat/inputCompleted":{let t=i.inputRequests;if(!t?.some(s=>s.id===n.requestId))return i;let r=t.filter(s=>s.id!==n.requestId),o={...i};return r.length>0?o.inputRequests=r:delete o.inputRequests,{...o,status:la(o),modifiedAt:new Date(Date.now()).toISOString()}}case"chat/pendingMessageSet":{let t={id:n.id,message:n.message};if(n.kind==="steering")return{...i,steeringMessage:t};let r=i.queuedMessages??[],o=r.findIndex(s=>s.id===n.id);if(o>=0){let s=[...r];return s[o]=t,{...i,queuedMessages:s}}return{...i,queuedMessages:[...r,t]}}case"chat/pendingMessageRemoved":{if(n.kind==="steering")return!i.steeringMessage||i.steeringMessage.id!==n.id?i:{...i,steeringMessage:void 0};let t=i.queuedMessages;if(!t)return i;let r=t.filter(o=>o.id!==n.id);return r.length===t.length?i:{...i,queuedMessages:r.length>0?r:void 0}}case"chat/queuedMessagesReordered":{let t=i.queuedMessages;if(!t)return i;let r=new Map(t.map(a=>[a.id,a])),o=new Set,s=n.order.filter(a=>r.has(a)&&!o.has(a)?(o.add(a),!0):!1).map(a=>r.get(a));for(let a of t)o.has(a.id)||s.push(a);return{...i,queuedMessages:s}}case"chat/draftChanged":return{...i,draft:n.draft};default:return xn(n,e),i}}function Xd(i,n,e){switch(n.type){case"changeset/statusChanged":{if(n.status==="error")return{...i,status:n.status,error:n.error};let{error:t,...r}=i;return{...r,status:n.status}}case"changeset/fileSet":{let t=i.files.findIndex(o=>o.id===n.file.id);if(t<0)return{...i,files:[...i.files,n.file]};let r=[...i.files];return r[t]=n.file,{...i,files:r}}case"changeset/fileRemoved":{let t=i.files.findIndex(o=>o.id===n.fileId);if(t<0)return i;let r=[...i.files];return r.splice(t,1),{...i,files:r}}case"changeset/contentChanged":{let t=n.operations===void 0?{...i,files:n.files}:{...i,files:n.files,operations:n.operations};if(n.error===void 0){let{error:r,...o}=t;return o}return{...t,error:n.error}}case"changeset/operationsChanged":{if(n.operations===void 0){let{operations:t,...r}=i;return r}return{...i,operations:n.operations}}case"changeset/operationStatusChanged":{if(i.operations===void 0)return i;let t=i.operations.findIndex(a=>a.id===n.operationId);if(t<0)return i;let r=i.operations[t],o;if(n.status==="error")o={...r,status:n.status,error:n.error};else{let{error:a,...l}=r;o={...l,status:n.status}}let s=[...i.operations];return s[t]=o,{...i,operations:s}}case"changeset/cleared":return i.files.length===0?i:{...i,files:[]};default:return xn(n,e),i}}function Zd(i,n,e){switch(n.type){case"annotations/set":{let t=i.annotations.findIndex(o=>o.id===n.annotation.id);if(t<0)return{...i,annotations:[...i.annotations,n.annotation]};let r=[...i.annotations];return r[t]=n.annotation,{...i,annotations:r}}case"annotations/updated":{let t=i.annotations.findIndex(a=>a.id===n.annotationId);if(t<0)return i;let o={...i.annotations[t]};n.turnId!==void 0&&(o.turnId=n.turnId),n.resource!==void 0&&(o.resource=n.resource),n.range!==void 0&&(o.range=n.range),n.resolved!==void 0&&(o.resolved=n.resolved);let s=[...i.annotations];return s[t]=o,{...i,annotations:s}}case"annotations/removed":{let t=i.annotations.findIndex(o=>o.id===n.annotationId);if(t<0)return i;let r=[...i.annotations];return r.splice(t,1),{...i,annotations:r}}case"annotations/entrySet":{let t=i.annotations.findIndex(l=>l.id===n.annotationId);if(t<0)return i;let r=i.annotations[t],o=r.entries.findIndex(l=>l.id===n.entry.id),s;o<0?s=[...r.entries,n.entry]:(s=[...r.entries],s[o]=n.entry);let a=[...i.annotations];return a[t]={...r,entries:s},{...i,annotations:a}}case"annotations/entryRemoved":{let t=i.annotations.findIndex(l=>l.id===n.annotationId);if(t<0)return i;let r=i.annotations[t],o=r.entries.findIndex(l=>l.id===n.entryId);if(o<0)return i;let s=[...r.entries];s.splice(o,1);let a=[...i.annotations];return a[t]={...r,entries:s},{...i,annotations:a}}default:return xn(n,e),i}}function UO(i){return i==="terminal"||i==="subagent"||i==="search"}function FO(i){if(!i||typeof i!="object"||Array.isArray(i))return;let n=i;if(typeof n.resourceUri!="string"||n.resourceUri.length===0)return;let e={resourceUri:n.resourceUri};return typeof n.channel=="string"&&n.channel.length>0&&(e.channel=n.channel),e}function ec(i){let n=i._meta;if(!n)return{};let e={};UO(n.toolKind)&&(e.toolKind=n.toolKind),typeof n.language=="string"&&(e.language=n.language),typeof n.subagentDescription=="string"&&(e.subagentDescription=n.subagentDescription),typeof n.subagentAgentName=="string"&&(e.subagentAgentName=n.subagentAgentName),n.toolArguments!==void 0&&(e.toolArguments=n.toolArguments),typeof n.mcpServerName=="string"&&(e.mcpServerName=n.mcpServerName),typeof n.mcpToolName=="string"&&(e.mcpToolName=n.mcpToolName),typeof n.autoApproveBySetting=="boolean"&&(e.autoApproveBySetting=n.autoApproveBySetting);let t=FO(n.ui);return t&&(e.ui=t),e}function Qt(i){let n={};for(let[e,t]of Object.entries(i))t!==void 0&&(n[e]=t);return Object.keys(n).length>0?n:void 0}var Av="/annotations";function uf(i){return`${i}${Av}`}function HO(i){if(!i.endsWith(Av))return;let n=i.slice(0,i.length-Av.length);if(n)return{sessionUri:n}}function Gw(i){return HO(i)!==void 0}var $O=500,pf=class{constructor(n={}){this._states=new Map;this._lru=new Bl;this._softLimit=Math.max(0,n.softLimit??$O),this._canEvict=n.canEvict??(()=>!0)}keys(){return this._states.keys()}has(n){return this._states.has(n)}get(n){return this._touch(n),this._states.get(n)}set(n,e){this._states.set(n,e),this._touch(n),this._evictIfOverLimit()}delete(n){this._states.delete(n),this._lru.delete(n)}register(n,e="computing"){if(this._states.has(n)){this._touch(n);return}this.set(n,{status:e,files:[]})}trimEvictableEntries(){this._evictIfOverLimit()}_touch(n){this._states.has(n)&&this._lru.set(n,!0,2)}_evictIfOverLimit(){if(this._softLimit===0){for(let n of[...this._lru.keys()])this._canEvict(n)&&this.delete(n);return}for(let n of[...this._lru.keys()]){if(this._states.size<=this._softLimit)return;if(!this._states.has(n)){this._lru.delete(n);continue}this._canEvict(n)&&this.delete(n)}}};var Ev=class extends T{constructor(e,t){super();this._getSummary=e;this._emit=t;this._lastNotified=new Map;this._dirty=new Set;this._scheduler=this._register(new Di(()=>this._flushAll(),100))}announce(e,t){this._lastNotified.set(e,t)}isAnnounced(e){return this._lastNotified.has(e)}markDirty(e){this._dirty.add(e),this._scheduler.schedule()}isDirty(e){return this._dirty.has(e)}clearDirty(e){this._dirty.delete(e)}remove(e){this._lastNotified.delete(e),this._dirty.delete(e)}_flushAll(){for(let e of this._dirty)this.flush(e);this._dirty.clear()}flush(e){let t=this._getSummary(e),r=this._lastNotified.get(e);if(!t||!r)return;let o={};t.title!==r.title&&(o.title=t.title),t.status!==r.status&&(o.status=t.status),t.activity!==r.activity&&(o.activity=t.activity),t.modifiedAt!==r.modifiedAt&&(o.modifiedAt=t.modifiedAt),t.project!==r.project&&(o.project=t.project),t.changes!==r.changes&&(o.changes=t.changes),t.workingDirectory!==r.workingDirectory&&(o.workingDirectory=t.workingDirectory),t._meta!==r._meta&&(o._meta=t._meta),this._lastNotified.set(e,t),Object.keys(o).length>0&&this._emit(e,o)}},da=class extends T{constructor(e,t={}){super();this._logService=e;this._serverSeq=0;this._sessionStates=new Map;this._chatStates=new Map;this._chatProviderData=new Map;this._annotations=new Map;this._sessionsWithActiveTurn=new Map;this._onDidEmitEnvelope=this._register(new P);this.onDidEmitEnvelope=this._onDidEmitEnvelope.event;this._onDidEmitNotification=this._register(new P);this.onDidEmitNotification=this._onDidEmitNotification.event;this._onDidChangeSessionActiveTurn=this._register(new P);this.onDidChangeSessionActiveTurn=this._onDidChangeSessionActiveTurn.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._changesets=new pf(t.changesetStateRetention),this._rootState=F_(),this._rootState={...this._rootState,config:{schema:$t.toProtocol(),values:$t.validateOrDefault({},{permissions:{allow:[],deny:[]},[Td]:pT(3)})},_meta:B_(this._rootState._meta,t.hostBuildInfo)},this._summaryNotifier=this._register(new Ev(r=>{let o=this._sessionStates.get(r);return o?this._toSummary(r,o):void 0},(r,o)=>this._onDidEmitNotification.fire({type:"root/sessionSummaryChanged",channel:Ke,session:r,changes:o})))}get hasActiveSessions(){return this._sessionsWithActiveTurn.size>0}hasActiveTurn(e){return this._sessionsWithActiveTurn.has(e)}get rootState(){return this._rootState}getSessionState(e){let t=ce(e),r=t?zs(e):e;if(r===void 0)return;let o=this._sessionStates.get(r);if(!o)return;let s=t?e:be(r);return W_(o.state,this._chatStates.get(s))}getSessionSummary(e){let t=this._sessionStates.get(e);return t?this._toSummary(e,t):void 0}_toSummary(e,t){let{state:r}=t,o={resource:e,provider:r.provider,title:r.title,status:r.status,createdAt:t.createdAt,modifiedAt:t.modifiedAt};return r.activity!==void 0&&(o.activity=r.activity),r.project!==void 0&&(o.project=r.project),r.workingDirectory!==void 0&&(o.workingDirectory=r.workingDirectory),r.annotations!==void 0&&(o.annotations=r.annotations),t.changes!==void 0&&(o.changes=t.changes),r._meta!==void 0&&(o._meta=r._meta),o}_summaryFieldsEqual(e,t){return e.title===t.title&&e.status===t.status&&e.activity===t.activity&&e.project===t.project&&e.workingDirectory===t.workingDirectory&&e.annotations===t.annotations&&e._meta===t._meta}getDefaultChatState(e){return this._chatStates.get(be(e))}getChatState(e){return this._chatStates.get(e)}getChatProviderData(e){return this._chatProviderData.get(e)}seedDefaultChatTurns(e,t){let r=this._chatStates.get(be(e));r&&(r.turns=t)}get serverSeq(){return this._serverSeq}getSessionUris(){return[...this._sessionStates.keys()]}getOverlaySessionSummaries(){let e=[];for(let[t,r]of this._sessionStates){let o=this._chatStates.get(be(t));r.state.lifecycle==="creating"&&!o?.activeTurn&&(o?.turns.length??0)===0||e.push(this._toSummary(t,r))}return e}getSessionUrisWithPrefix(e){let t=[];for(let r of this._sessionStates.keys())r.startsWith(e)&&t.push(r);return t}getSnapshot(e){if(Mo(e))return{resource:Ke,state:this._rootState,fromSeq:this._serverSeq};let t=this._changesets.get(e);if(t)return{resource:e,state:t,fromSeq:this._serverSeq};if(ce(e)){let o=this._chatStates.get(e);return o?{resource:e,state:o,fromSeq:this._serverSeq}:void 0}if(Gw(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.state,fromSeq:this._serverSeq}}getChangesetState(e){return this._changesets.get(e)}onChangesetLivenessChanged(){this._changesets.trimEvictableEntries()}createSession(e,t){let r=e.resource,o=this._sessionStates.get(r);if(o)return this._logService.warn(`[AgentHostStateManager] Session already exists: ${r}`),o.state;let s=_y(e);return this._sessionStates.set(r,this._newEntry(s,e)),this._ensureDefaultChat(r,e),this._logService.trace(`[AgentHostStateManager] Created session: ${r}`),t?.emitNotification!==!1&&(this._summaryNotifier.announce(r,e),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Ke,summary:e})),s}_newEntry(e,t){return{state:e,createdAt:t.createdAt,modifiedAt:t.modifiedAt,changes:t.changes}}markSessionPersisted(e,t){let r=e.toString(),o=this._sessionStates.get(r);if(!o){this._logService.warn(`[AgentHostStateManager] markSessionPersisted: unknown session ${r}`);return}if(this._summaryNotifier.isAnnounced(r))return;o.state={...o.state,project:t.project,workingDirectory:t.workingDirectory},o.modifiedAt=t.modifiedAt,o.changes=t.changes;let s=this._toSummary(r,o);this._summaryNotifier.announce(r,s),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Ke,summary:s})}restoreSession(e,t,r){let o=e.resource,s=this._sessionStates.get(o);if(s)return this._logService.warn(`[AgentHostStateManager] Session already exists (restore): ${o}`),s.state;let a={..._y(e),lifecycle:"ready"};return this._sessionStates.set(o,this._newEntry(a,e)),this._ensureDefaultChat(o,e,t,r?.draft,r?.defaultChatTitle),this._summaryNotifier.announce(o,e),this._logService.trace(`[AgentHostStateManager] Restored session: ${o} (${t.length} turns)`),a}_ensureDefaultChat(e,t,r,o,s){let a=be(e),l={...ap(t,a),title:s??""};this._chatStates.set(a,{...sp(l),turns:r??[],draft:o});let d=this._sessionStates.get(e);d&&(d.state.chats=[l],d.state.defaultChat=a)}addChat(e,t,r){let o=this._sessionStates.get(e);if(!o){this._logService.warn(`[AgentHostStateManager] addChat for unknown session: ${e}`);return}let s=o.state,a=s.chats.find(u=>u.resource===t);if(a)return a;let l=s.defaultChat??be(e),d=s.chats.find(u=>u.resource===l);d&&!d.title&&s.title&&this.updateChatTitle(e,l,s.title);let c={...ap(this._toSummary(e,o),t),title:r?.title??"",status:1,origin:r?.origin,interactivity:r?.interactivity};return this._chatStates.set(t,{...sp(c),turns:r?.turns??[]}),r?.providerData!==void 0&&this._chatProviderData.set(t,r.providerData),this.dispatchServerAction(e,{type:"session/chatAdded",summary:c}),c}restoreChat(e,t,r){let o=this._sessionStates.get(e);if(!o){this._logService.warn(`[AgentHostStateManager] restoreChat for unknown session: ${e}`);return}let s=o.state;if(s.chats.some(l=>l.resource===t))return;let a={...ap(this._toSummary(e,o),t),title:r.title??"",status:1};this._chatStates.set(t,{...sp(a),turns:r.turns,draft:r.draft}),r.providerData!==void 0&&this._chatProviderData.set(t,r.providerData),s.chats=[...s.chats,a]}removeChat(e,t){let r=this._sessionStates.get(e);if(!r||!r.state.chats.some(s=>s.resource===t))return;let o=r.state;if(t===o.defaultChat||Ue(t)){this._logService.warn(`[AgentHostStateManager] refusing to remove default chat: ${t}`);return}this._removeChatActiveTurn(e,t),this._chatStates.delete(t),this._chatProviderData.delete(t),this.dispatchServerAction(e,{type:"session/chatRemoved",chat:t})}updateChatTitle(e,t,r){let o=this._chatStates.get(t);o&&this._chatStates.set(t,{...o,title:r}),this.dispatchServerAction(e,{type:"session/chatUpdated",chat:t,changes:{title:r}})}removeSession(e){let t=this._sessionStates.get(e);if(t){this._summaryNotifier.isDirty(e)&&this._summaryNotifier.flush(e),this._sessionsWithActiveTurn.delete(e)&&(this._onDidChangeSessionActiveTurn.fire({session:e,active:!1}),this.dispatchServerAction(Ke,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size}));for(let r of t.state.chats)this._chatStates.delete(r.resource),this._chatProviderData.delete(r.resource);this._chatStates.delete(be(e)),this._sessionStates.delete(e),this._summaryNotifier.remove(e),this._logService.trace(`[AgentHostStateManager] Removed session: ${e}`)}}deleteSession(e){let t=this._summaryNotifier.isAnnounced(e);this._summaryNotifier.clearDirty(e),this.disposeSessionChangesets(e),this.disposeSessionAnnotations(e),this.removeSession(e),t&&this._onDidEmitNotification.fire({type:"root/sessionRemoved",channel:Ke,session:e})}setSessionMeta(e,t){this.dispatchServerAction(e,{type:"session/metaChanged",_meta:t})}setSessionConfig(e,t){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionConfig: unknown session ${e}`);return}r.state.config=t}setSessionCustomizations(e,t){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionCustomizations: unknown session ${e}`);return}r.state.customizations=t?[...t]:void 0}registerChangeset(e,t="computing"){return this._changesets.register(e,t),e}setSessionSummaryChanges(e,t){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionSummaryChanges: unknown session ${e}`);return}Fi(r.changes,t)||(r.changes=t,this._summaryNotifier.markDirty(e))}setSessionChangesets(e,t){let r=this._sessionStates.get(e);if(!r){this._logService.warn(`[AgentHostStateManager] setSessionChangesets: unknown session ${e}`);return}let o=r.state;if(xy(o.changesets??[],t??[],Fi))return;let s=t?t.slice():void 0;this.dispatchServerAction(e,{type:"session/changesetsChanged",changesets:s})}disposeChangeset(e){this._changesets.has(e)&&(this.dispatchServerAction(e,{type:"changeset/cleared"}),this._changesets.delete(e))}disposeSessionChangesets(e){let t=[];for(let r of this._changesets.keys()){let o=et(r);o&&o.sessionUri===e&&t.push(r)}for(let r of t)this.disposeChangeset(r)}disposeSessionAnnotations(e){this._annotations.delete(uf(e))}getActiveTurnId(e){let t=ce(e)?e:be(e);return this._chatStates.get(t)?.activeTurn?.id}dispatchServerAction(e,t){this._applyAndEmit(e,t,void 0)}dispatchClientAction(e,t,r){return this._applyAndEmit(e,t,r)}_applyAndEmit(e,t,r){let o;if(pw(t)){if(t.type==="root/configChanged"&&this._rootState.config){let a=this._rootState.config.values,l=t.config;if(t.replace?Fe(a,l):Fe({...a,...l},a))return this._rootState}this._rootState=Jd(this._rootState,t,this._log),o=this._rootState}if(Vd(t)){let a=t,l=e,d=this._sessionStates.get(l);if(d){let c=Yd(d.state,a,this._log),u=!this._summaryFieldsEqual(d.state,c);d.state=c,u&&this._summaryNotifier.markDirty(l),o=c}else ce(l)||this._logService.warn(`[AgentHostStateManager] Action for unknown session: ${l}, type=${t.type}`)}if(rr(t)){if(!ce(e))throw new Error(`[AgentHostStateManager] Chat action dispatched to non-chat channel: ${e}, type=${t.type}`);let a=t,l=fe(e),d=this._chatStates.get(e);if(d&&l!==void 0){let c=Qd(d,a,this._log);this._chatStates.set(e,c),this._onChatStateChanged(l,e,d,c),o=c}else this._logService.warn(`[AgentHostStateManager] Action for unknown chat: ${e}, type=${t.type}`)}if(dv(t)){let a=t,l=e,d=this._changesets.get(l);if(!d){this._logService.warn(`[AgentHostStateManager] Action for unknown changeset: ${l}, type=${t.type}`);return}let c=Xd(d,a,this._log);c!==d&&this._changesets.set(l,c),o=c}if(cv(t)){let a=t,l=e,d=this._annotations.get(l)??{annotations:[]},c=Zd(d,a,this._log);c!==d&&this._annotations.set(l,c),o=c}let s={channel:e,action:t,serverSeq:++this._serverSeq,origin:r};return this._logService.trace(`[AgentHostStateManager] Emitting envelope: seq=${s.serverSeq}, channel=${s.channel}, type=${t.type}${r?`, origin=${r.clientId}:${r.clientSeq}`:""}`),this._onDidEmitEnvelope.fire(s),o}_removeChatActiveTurn(e,t){let r=this._sessionsWithActiveTurn.get(e);!r||!r.delete(t)||r.size===0&&(this._sessionsWithActiveTurn.delete(e),this._onDidChangeSessionActiveTurn.fire({session:e,active:!1}),this.dispatchServerAction(Ke,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size}))}_onChatStateChanged(e,t,r,o){let s=!!r.activeTurn,a=!!o.activeTurn;if(s!==a)if(a){let _=this._sessionsWithActiveTurn.get(e),R=!!_?.size;_||(_=new Set,this._sessionsWithActiveTurn.set(e,_)),_.add(t),R||(this._onDidChangeSessionActiveTurn.fire({session:e,active:!0}),this.dispatchServerAction(Ke,{type:"root/activeSessionsChanged",activeSessions:this._sessionsWithActiveTurn.size}))}else this._removeChatActiveTurn(e,t);let l=this._sessionStates.get(e);if(!l)return;let d=l.state,c=H_(o),u=d.chats.find(_=>_.resource===t),p=d.chats.map(_=>_.resource===t?c:_);u?.status!==c.status&&this.dispatchServerAction(e,{type:"session/chatUpdated",chat:t,changes:{status:c.status,activity:c.activity}});let m=this._aggregateChatSummaries(p,d.defaultChat),h=m.status!==void 0?this._mergeSessionStatus(d.status,m.status):d.status,y=h!==d.status,S=m.activity!==d.activity;l.state={...d,chats:p,...y?{status:h}:void 0,...S?{activity:m.activity}:void 0};let b=m.modifiedAt!==void 0?new Date(m.modifiedAt).toISOString():void 0,I=b!==void 0&&b!==l.modifiedAt;I&&(l.modifiedAt=b),(y||S||I)&&this._summaryNotifier.markDirty(e)}_aggregateChatSummaries(e,t){if(e.length===0)return{};let r=-97,o=(t!==void 0?e.find(p=>p.resource===t):void 0)??e.reduce((p,m)=>Date.parse(m.modifiedAt)>Date.parse(p.modifiedAt)?m:p),s=o.status&r,a=o,l=e.find(p=>(p.status&2)===2),d=e.find(p=>(p.status&24)===24),c=e.find(p=>(p.status&24)===8);d?(s=24,a=d):l?(s=2,a=l):c&&(s=8,a=c);let u=e.reduce((p,m)=>Math.max(p,Date.parse(m.modifiedAt)),0);return{status:s,activity:a.activity,modifiedAt:u}}_mergeSessionStatus(e,t){let r=e&96;return t&-97|r}emitProgress(e){this._onDidEmitNotification.fire({type:"root/progress",channel:Ke,...e})}emitAuthRequired(e){this._onDidEmitNotification.fire({type:"auth/required",channel:Ke,...e})}};da=w([C(0,D)],da);var ca="agentHost.diffBaseBranch";function ff(i,n){return i??n}var Jo="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ye=$("agentHostGitService");function Jw(i){return i==="main"?0:i==="master"?1:2}function Yw(i,n){let e=n?.query?.toLowerCase(),t=e?i.filter(r=>r.toLowerCase().includes(e)):[...i];return t.sort((r,o)=>Jw(r)-Jw(o)),n?.limit?t.slice(0,n.limit):t}var ua="agentHost.changeset.branch",tc="agentHost.changeset.session",pa="diffs",Yo="agentHost.changes",gf={[ua]:!0,[tc]:!0,[Yo]:!0,[pa]:!0},ji=$("agentHostChangesetService");var _r=$("agentHostCheckpointService"),Qo="checkpoint.baseRef";function kv(i,n){return`refs/agents/${i}/checkpoints/turn/${n}`}var Qw={_serviceBrand:void 0,captureBaseline:async()=>{},captureTurnCheckpoint:async()=>{},getTurnCheckpointPair:async()=>{},getBaselineCheckpointRef:async()=>{},disposeSessionData:async()=>{}};function Dv(i){let n=[];for(let e of i)if(e.kind==="markdown"){let t=e.content.trim();t&&n.push(t)}return n.join(`

`)}function mf(i,n){let e=[];for(let o of i){let s=o.message.text.trim(),a=Dv(o.responseParts);!s&&!a||e.push(a?`User request:
${s}

Agent response:
${a}`:`User request:
${s}`)}if(e.length===0)return;let t=e.join(`

---

`),r=t.length>n.maxChars?hf(t,n.maxChars):t;return`${n.framing??""}${r}`}function hf(i,n){if(i.length<=n)return i;let e=`
...
`;if(n<=e.length)return i.slice(0,n);let t=n-e.length,r=Math.ceil(t/2),o=t-r;return`${i.slice(0,r)}${e}${i.slice(i.length-o)}`}var Xw=200,Mv=2e4,fa=class extends T{constructor(e,t,r){super();this._stateManager=e;this._options=t;this._logService=r;this._titleGenerationCancellationSources=new Map;this._lastAppliedTitle=new Map}seedTitleFromFirstMessage(e,t,r){let o=t.trim().replace(/\s+/g," ").slice(0,Xw);if(o.length===0)return;if(!!r&&ce(r)&&!Ue(r)){let d=this._stateManager.getChatState(r);if(!d||d.turns.length!==0||d.title)return;let c=u=>this._applyTitle(r,u,p=>this._stateManager.updateChatTitle(e,r,p));c(o),this._generateTitleSoon(r,t,!1,o,c,()=>this._stateManager.getChatState(r)?.title===this._lastAppliedTitle.get(r),u=>this._persistSessionFlag(e,`customChatTitle:${r}`,u));return}let a=this._stateManager.getSessionState(e);if(!a||a.turns.length!==0||a.title)return;let l=d=>this._applyTitle(e,d,c=>this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:c}));l(o),this._generateTitleSoon(e,t,!1,o,l,()=>this._stateManager.getSessionState(e)?.title===this._lastAppliedTitle.get(e),d=>this._persistSessionFlag(e,"customTitle",d))}refineTitleFromFirstTurn(e,t){if(!!t&&ce(t)&&!Ue(t)){let d=this._stateManager.getChatState(t);if(!d||d.turns.length!==1)return;let c=this._lastAppliedTitle.get(t);if(c===void 0||d.title!==c)return;let u=this._buildFirstTurnContext(d.turns[0]);if(!u)return;let p=m=>this._applyTitle(t,m,h=>this._stateManager.updateChatTitle(e,t,h));this._generateTitleSoon(t,u,!0,c,p,()=>this._stateManager.getChatState(t)?.title===this._lastAppliedTitle.get(t),m=>this._persistSessionFlag(e,`customChatTitle:${t}`,m));return}let o=this._stateManager.getSessionState(e);if(!o||o.turns.length!==1)return;let s=this._lastAppliedTitle.get(e);if(s===void 0||o.title!==s)return;let a=this._buildFirstTurnContext(o.turns[0]);if(!a)return;let l=d=>this._applyTitle(e,d,c=>this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:c}));this._generateTitleSoon(e,a,!0,s,l,()=>this._stateManager.getSessionState(e)?.title===this._lastAppliedTitle.get(e),d=>this._persistSessionFlag(e,"customTitle",d))}generateForkedTitle(e,t,r,o,s){let a=this._buildConversationContext(r,s);if(!a)return;if(!!t&&ce(t)&&!Ue(t)){let c=t;this._lastAppliedTitle.set(c,o);let u=p=>this._applyTitle(c,p,m=>this._stateManager.updateChatTitle(e,c,m));this._generateTitleSoon(c,a,!0,o,u,()=>this._stateManager.getChatState(c)?.title===this._lastAppliedTitle.get(c),p=>this._persistSessionFlag(e,`customChatTitle:${c}`,p));return}this._lastAppliedTitle.set(e,o);let d=c=>this._applyTitle(e,c,u=>this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:u}));this._generateTitleSoon(e,a,!0,o,d,()=>this._stateManager.getSessionState(e)?.title===this._lastAppliedTitle.get(e),c=>this._persistSessionFlag(e,"customTitle",c))}_applyTitle(e,t,r){this._lastAppliedTitle.set(e,t),r(t)}cancelTitleGeneration(e){this._cancelTitleGeneration(e)}_generateTitleSoon(e,t,r,o,s,a,l){this._cancelTitleGeneration(e);let d=new Ze;this._titleGenerationCancellationSources.set(e,d),this._generateTitle(e,t,r,o,s,a,l,d.token).catch(c=>{d.token.isCancellationRequested||this._logService.warn(`[AgentHostSessionTitleController] Failed to apply generated title for ${e}`,c)}).finally(()=>{this._titleGenerationCancellationSources.get(e)===d&&(this._titleGenerationCancellationSources.delete(e),d.dispose())})}async _generateTitle(e,t,r,o,s,a,l,d){let c=await this._generateTitleFromPrompt(t,r,d);d.isCancellationRequested||!c||a()&&(c!==o&&s(c),l(c))}async _generateTitleFromPrompt(e,t,r){if(r.isCancellationRequested)return;let o=this._options.getGitHubCopilotToken?.(),s=this._options.copilotApiService;if(!o||!s)return;let a=new AbortController,l=r.onCancellationRequested(()=>a.abort());try{let d=await s.utilityChatCompletion(o,{messages:this._buildTitlePrompt(e,t)},{signal:a.signal});return this._cleanTitle(d)}catch(d){if(r.isCancellationRequested)return;this._logService.warn("[AgentHostSessionTitleController] Failed to generate session title",d);return}finally{l.dispose()}}_buildTitlePrompt(e,t){let r=t?`Please write a brief title for the following conversation:

${e}`:`Please write a brief title for the following request:

${e}`;return[{role:"system",content:["You are an expert in crafting ultra-compact titles for chatbot conversations.","You are presented with a chat request or conversation, and you reply with only a brief title that captures the main topic.","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".',"Never describe the chat itself as forked, branched, or continued \u2014 title only the underlying topic.","Prefer short, concrete synonyms and omit unnecessary words.","Do not wrap the title in quotes or add trailing punctuation."].join(" ")},{role:"user",content:r}]}_cleanTitle(e){let t=e.trim();if(t=t.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)??"",t.startsWith('"')&&t.endsWith('"')&&t.length>1&&(t=t.slice(1,-1).trim()),t=t.replace(/[.!?]+$/,"").trim(),!(!t||t.includes("can't assist with that")))return t.slice(0,Xw)}_buildFirstTurnContext(e){let t=Dv(e.responseParts);if(!t)return;let r=Math.floor(Mv/2),o=e.message.text.trim();o.length>r&&(o=hf(o,r));let s=`User request:
${o}`,a=`

Agent response:
`,l=Math.max(0,Mv-s.length-a.length),d=t.length>l?hf(t,l):t;return d?`${s}${a}${d}`:s}_buildConversationContext(e,t){let r=t?.trim(),o=r?`This conversation was branched from an earlier chat titled "${r}". The turns below, oldest first, are the inherited history up to the branch point.

`:void 0;return mf(e,{maxChars:Mv,framing:o})}_persistSessionFlag(e,t,r){let o=this._options.sessionDataService.openDatabase(v.parse(e));o.object.setMetadata(t,r).catch(s=>{this._logService.warn(`[AgentHostSessionTitleController] Failed to persist ${t}`,s)}).finally(()=>{o.dispose()})}_cancelTitleGeneration(e){let t=this._titleGenerationCancellationSources.get(e);t&&(t.dispose(!0),this._titleGenerationCancellationSources.delete(e))}dispose(){for(let e of this._titleGenerationCancellationSources.values())e.dispose(!0);this._titleGenerationCancellationSources.clear(),this._lastAppliedTitle.clear(),super.dispose()}};fa=w([C(2,D)],fa);var WO="7d7048df-6dd0-4048-bb23-b716c1461f8f",qO="3fdd7f28-937a-48c8-9a21-ba337db23bd1",Zw="https://copilot-telemetry.githubusercontent.com/telemetry",BO="copilot-chat",nc=8192,zO=50;function eR(i){let n={...i};for(let e in i){let t=i[e],r=t?.length??0;if(r>nc){let o=0,s=0;for(;r>0&&s<zO;){s+=1;let a=e;s>1&&(a=e+"_"+(s<10?"0":"")+s);let l=o+nc;r<nc&&(l=o+r),n[a]=t.slice(o,l),r-=nc,o+=nc}}}return n}var yf=class{constructor(n,e,t=Zw,r,o=globalThis.fetch){this._logService=e;this._endpointUrl=t;this._internalSink=r;this._fetchFn=o;this._restrictedTelemetryEnabled=!1;this._commonProps={client_machineid:rc(n["common.machineId"]),client_deviceid:rc(n["common.devDeviceId"]),client_sessionid:rc(n.sessionID),common_os:rc(n["common.nodePlatform"])??process.platform,editor_version:rc(n.version)}}sendGHTelemetryEvent(n,e,t){this._post(WO,n,e,t)}sendEnhancedGHTelemetryEvent(n,e,t){this._restrictedTelemetryEnabled&&this._post(qO,n,e,t)}sendInternalMSFTTelemetryEvent(n,e,t){if(this._internalSink){this._internalSink(n,e,t);return}this._logService.trace(`[ahp-restricted] internal MSFT event (not sent, no internal key): ${n}`)}setCopilotTrackingId(n){this._commonProps.copilot_trackingId=n||void 0}setRestrictedTelemetryEndpoint(n){this._endpointUrl=n||Zw}setRestrictedTelemetryEnabled(n){this._restrictedTelemetryEnabled=n}_post(n,e,t,r){let o=e.includes("/")?e:`${BO}/${e}`,s={ver:1,name:`Microsoft.ApplicationInsights.${n.replace(/-/g,"")}.Event`,time:new Date().toISOString(),sampleRate:100,seq:"",iKey:n,tags:{"ai.operation.id":H()},data:{baseType:"EventData",baseData:{name:o,properties:{unique_id:H(),...this._commonProps,...t},measurements:r??{}}}};if(this._logService.trace(`[ahp-restricted] emit ${o} (iKey ${n.slice(0,8)})`),typeof this._fetchFn!="function"){this._logService.warn("[ahp-restricted] global fetch unavailable; telemetry not sent");return}this._fetchFn(this._endpointUrl,{method:"POST",headers:{"Content-Type":"application/x-json-stream"},body:JSON.stringify(s)}).then(a=>{a.ok||this._logService.warn(`[ahp-restricted] ${o} rejected: HTTP ${a.status}`)}).catch(a=>{this._logService.warn(`[ahp-restricted] ${o} POST failed: ${a instanceof Error?a.message:String(a)}`)})}};function rc(i){return typeof i=="string"?i:i===void 0?void 0:String(i)}var ga=class{constructor(n){this._telemetryService=n}get _restricted(){let n=this._telemetryService;return typeof n.sendEnhancedGHTelemetryEvent=="function"?n:void 0}userMessageSent(n,e,t,r,o){let s=o?.length??0,a=t?.activeClients??[],l=ce(e)?fe(e):e;this._telemetryService.publicLog2("agentHost.userMessageSent",{provider:n,agentSessionId:L.id(l),source:r,isSubagentSession:Qr(l),turnCount:t?.turns.length??0,...a.length>0?{activeClientId:a[0].clientId,activeClientToolCount:a.reduce((d,c)=>d+c.tools.length,0),activeClientCustomizationCount:a.reduce((d,c)=>d+(c.customizations?.length??0),0)}:{},attachmentCount:s})}assistantMessageReceived(n,e,t){let r=this._restricted;!r||!e||t.length===0||r.sendEnhancedGHTelemetryEvent("request.options.tools",eR({headerRequestId:e,conversationId:L.id(n),messagesJson:JSON.stringify(t)}))}turnCompleted(n){let e=ce(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.turnCompleted",{provider:n.provider,agentSessionId:L.id(e),timeToFirstProgress:n.timeToFirstProgress,totalTime:n.totalTime,result:n.result,model:n.model,permissionLevel:n.permissionLevel})}toolInvoked(n){let e=ce(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("languageModelToolInvoked",{result:n.result,chatSessionId:e,toolId:n.toolId,toolExtensionId:void 0,toolSourceKind:n.toolSourceKind,invocationTimeMs:n.invocationTimeMs,provider:n.provider})}toolCallStalled(n){let e=ce(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.toolCallStalled",{provider:n.provider,agentSessionId:L.id(e),isSubagentSession:Cd(n.session)||Qr(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,stalledTimeMs:n.stalledTimeMs})}stalledToolCallCompleted(n){let e=ce(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.stalledToolCallCompleted",{provider:n.provider,agentSessionId:L.id(e),isSubagentSession:Cd(n.session)||Qr(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,result:n.result,totalTimeMs:n.totalTimeMs,timeAfterStallMs:n.timeAfterStallMs})}};var VO=300*1e3;function jO(i){if(i.success)return"success";let n=i.error?.code;return n==="rejected"||n==="denied"||n==="cancelled"?"userCancelled":"error"}function tR(i){if(!i)return"agentHost";let n=i.kind;switch(n){case"mcp":return"mcp";case"client":return"client";default:return n}}var vf=class extends T{constructor(e){super();this._reporter=e;this._toolCalls=new Map;this._toolCallStallTimers=this._register(new Re);this._stalledToolCalls=new Map}toolCallStarted(e,t,r,o,s){this._toolCalls.set(this._key(t,r),{stopWatch:Dn.create(!0),provider:e,session:t,toolId:o,toolSourceKind:tR(s)})}toolCallCompleted(e,t,r){let o=this._key(e,t),s=this._toolCalls.get(o);if(!s)return;this._toolCalls.delete(o);let a=jO(r),l=s.stopWatch.elapsed();this._reporter.toolInvoked({provider:s.provider,session:s.session,toolId:s.toolId,toolSourceKind:s.toolSourceKind,result:a,invocationTimeMs:l});let d=this._stalledToolCalls.get(o);d&&(this._stalledToolCalls.delete(o),this._reporter.stalledToolCallCompleted({provider:s.provider,session:s.session,blockerKind:d.blockerKind,toolId:s.toolId,toolSourceKind:s.toolSourceKind,result:a,totalTimeMs:l,timeAfterStallMs:d.completionStopWatch.elapsed()}))}toolCallBlocked(e,t,r){let o=this._key(t,r.id),s=this._key(t,r.toolCall.toolCallId);if(this._toolCallStallTimers.has(o)||this._stalledToolCalls.has(s))return;let a=Dn.create(!0);this._toolCallStallTimers.set(o,Kt(()=>{let l=a.elapsed();this._stalledToolCalls.set(s,{blockerKind:r.kind,completionStopWatch:Dn.create(!0)}),this._reporter.toolCallStalled({provider:e,session:t,blockerKind:r.kind,toolId:r.toolCall.toolName,toolSourceKind:tR(r.toolCall.contributor),stalledTimeMs:l})},VO))}toolCallUnblocked(e,t){this._toolCallStallTimers.deleteAndDispose(this._key(e,t))}clearSession(e){let t=`${e}\0`;for(let r of this._toolCalls.keys())r.startsWith(t)&&this._toolCalls.delete(r);for(let r of this._toolCallStallTimers.keys())r.startsWith(t)&&this._toolCallStallTimers.deleteAndDispose(r);for(let r of this._stalledToolCalls.keys())r.startsWith(t)&&this._stalledToolCalls.delete(r)}clear(){this._toolCalls.clear(),this._toolCallStallTimers.clearAndDisposeAll(),this._stalledToolCalls.clear()}_key(e,t){return`${e}\0${t}`}};import{hostname as CL,release as IL}from"os";import{networkInterfaces as YO}from"os";import{networkInterfaces as KO}from"os";var GO=new Set(["00:00:00:00:00:00","ff:ff:ff:ff:ff:ff","ac:de:48:00:11:22"]);function JO(i){let n=i.replace(/\-/g,":").toLowerCase();return!GO.has(n)}function nR(){let i=KO();for(let n in i){let e=i[n];if(e){for(let{mac:t}of e)if(JO(t))return t}}throw new Error("Unable to retrieve mac address (unexpected format)")}var CX=new class{_isVirtualMachineMacAddress(i){return this._virtualMachineOUIs||(this._virtualMachineOUIs=Sr.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,n=0,e=YO();for(let t in e){let r=e[t];if(r)for(let{mac:o,internal:s}of r)s||(n+=1,this._isVirtualMachineMacAddress(o.toUpperCase())&&(i+=1))}this._value=n>0?i/n:0}return this._value}},Ov;async function Sf(i){return Ov||(Ov=(async()=>await QO(i)||H())()),Ov}async function QO(i){try{let n=await import("crypto"),e=nR();return n.createHash("sha256").update(e,"utf8").digest("hex")}catch(n){i(n);return}}var XO="Software\\Microsoft\\SQMClient";async function rR(i){if(Q){let n=await import("@vscode/windows-registry");try{return n.GetStringRegKey("HKEY_LOCAL_MACHINE",XO,"MachineId")||""}catch(e){return i(e),""}}return""}async function bf(i){try{let e=await(await import("@vscode/deviceid")).getDeviceId();return AI(e)}catch(n){return i(n),H()}}var If;(n=>n.DEFAULT={allowTrailingComma:!0})(If||={});function Nv(i,n=!1){let e=0,t=i.length,r="",o=0,s=16,a=0;function l(y){let S=0,b=0;for(;S<y;){let I=i.charCodeAt(e);if(I>=48&&I<=57)b=b*16+I-48;else if(I>=65&&I<=70)b=b*16+I-65+10;else if(I>=97&&I<=102)b=b*16+I-97+10;else break;e++,S++}return S<y&&(b=-1),b}function d(y){e=y,r="",o=0,s=16,a=0}function c(){let y=e;if(i.charCodeAt(e)===48)e++;else for(e++;e<i.length&&ma(i.charCodeAt(e));)e++;if(e<i.length&&i.charCodeAt(e)===46)if(e++,e<i.length&&ma(i.charCodeAt(e)))for(e++;e<i.length&&ma(i.charCodeAt(e));)e++;else return a=3,i.substring(y,e);let S=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&&ma(i.charCodeAt(e))){for(e++;e<i.length&&ma(i.charCodeAt(e));)e++;S=e}else a=3;return i.substring(y,S)}function u(){let y="",S=e;for(;;){if(e>=t){y+=i.substring(S,e),a=2;break}let b=i.charCodeAt(e);if(b===34){y+=i.substring(S,e),e++;break}if(b===92){if(y+=i.substring(S,e),e++,e>=t){a=2;break}switch(i.charCodeAt(e++)){case 34:y+='"';break;case 92:y+="\\";break;case 47:y+="/";break;case 98:y+="\b";break;case 102:y+="\f";break;case 110:y+=`
`;break;case 114:y+="\r";break;case 116:y+="	";break;case 117:{let _=l(4);_>=0?y+=String.fromCharCode(_):a=4;break}default:a=5}S=e;continue}if(b>=0&&b<=31)if(Cf(b)){y+=i.substring(S,e),a=2;break}else a=6;e++}return y}function p(){if(r="",a=0,o=e,e>=t)return o=t,s=17;let y=i.charCodeAt(e);if(Lv(y)){do e++,r+=String.fromCharCode(y),y=i.charCodeAt(e);while(Lv(y));return s=15}if(Cf(y))return e++,r+=String.fromCharCode(y),y===13&&i.charCodeAt(e)===10&&(e++,r+=`
`),s=14;switch(y){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 S=e-1;if(i.charCodeAt(e+1)===47){for(e+=2;e<t&&!Cf(i.charCodeAt(e));)e++;return r=i.substring(S,e),s=12}if(i.charCodeAt(e+1)===42){e+=2;let b=t-1,I=!1;for(;e<b;){if(i.charCodeAt(e)===42&&i.charCodeAt(e+1)===47){e+=2,I=!0;break}e++}return I||(e++,a=1),r=i.substring(S,e),s=13}return r+=String.fromCharCode(y),e++,s=16}case 45:if(r+=String.fromCharCode(y),e++,e===t||!ma(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<t&&m(y);)e++,y=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(y),e++,s=16}}function m(y){if(Lv(y)||Cf(y))return!1;switch(y){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function h(){let y;do y=p();while(y>=12&&y<=15);return y}return{setPosition:d,getPosition:()=>e,scan:n?h:p,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>o,getTokenLength:()=>e-o,getTokenError:()=>a}}function Lv(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 Cf(i){return i===10||i===13||i===8232||i===8233}function ma(i){return i>=48&&i<=57}function _f(i,n=[],e=If.DEFAULT){let t=null,r=[],o=[];function s(l){Array.isArray(r)?r.push(l):t!==null&&(r[t]=l)}return ha(i,{onObjectBegin:()=>{let l={};s(l),o.push(r),r=l,t=null},onObjectProperty:l=>{t=l},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let l=[];s(l),o.push(r),r=l,t=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:s,onError:(l,d,c)=>{n.push({error:l,offset:d,length:c})}},e),r[0]}function iR(i,n=[],e=If.DEFAULT){let t={type:"array",offset:-1,length:-1,children:[],parent:void 0};function r(l){t.type==="property"&&(t.length=l-t.offset,t=t.parent)}function o(l){return t.children.push(l),l}ha(i,{onObjectBegin:l=>{t=o({type:"object",offset:l,length:-1,parent:t,children:[]})},onObjectProperty:(l,d,c)=>{t=o({type:"property",offset:d,length:-1,parent:t,children:[]}),t.children.push({type:"string",value:l,offset:d,length:c,parent:t})},onObjectEnd:(l,d)=>{t.length=l+d-t.offset,t=t.parent,r(l+d)},onArrayBegin:(l,d)=>{t=o({type:"array",offset:l,length:-1,parent:t,children:[]})},onArrayEnd:(l,d)=>{t.length=l+d-t.offset,t=t.parent,r(l+d)},onLiteralValue:(l,d,c)=>{o({type:ZO(l),offset:d,length:c,parent:t,value:l}),r(d+c)},onSeparator:(l,d,c)=>{t.type==="property"&&(l===":"?t.colonOffset=d:l===","&&r(d))},onError:(l,d,c)=>{n.push({error:l,offset:d,length:c})}},e);let a=t.children[0];return a&&delete a.parent,a}function Uv(i,n){if(!i)return;let e=i;for(let t of n)if(typeof t=="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===t){e=o.children[1],r=!0;break}if(!r)return}else{let r=t;if(e.type!=="array"||r<0||!Array.isArray(e.children)||r>=e.children.length)return;e=e.children[r]}return e}function ha(i,n,e=If.DEFAULT){let t=Nv(i,!1);function r(x){return x?()=>x(t.getTokenOffset(),t.getTokenLength()):()=>!0}function o(x){return x?B=>x(B,t.getTokenOffset(),t.getTokenLength()):()=>!0}let s=r(n.onObjectBegin),a=o(n.onObjectProperty),l=r(n.onObjectEnd),d=r(n.onArrayBegin),c=r(n.onArrayEnd),u=o(n.onLiteralValue),p=o(n.onSeparator),m=r(n.onComment),h=o(n.onError),y=e&&e.disallowComments,S=e&&e.allowTrailingComma;function b(){for(;;){let x=t.scan();switch(t.getTokenError()){case 4:I(14);break;case 5:I(15);break;case 3:I(13);break;case 1:y||I(11);break;case 2:I(12);break;case 6:I(16);break}switch(x){case 12:case 13:y?I(10):m();break;case 16:I(1);break;case 15:case 14:break;default:return x}}}function I(x,B=[],K=[]){if(h(x),B.length+K.length>0){let N=t.getToken();for(;N!==17;){if(B.indexOf(N)!==-1){b();break}else if(K.indexOf(N)!==-1)break;N=b()}}}function _(x){let B=t.getTokenValue();return x?u(B):a(B),b(),!0}function R(){switch(t.getToken()){case 11:{let x=0;try{x=JSON.parse(t.getTokenValue()),typeof x!="number"&&(I(2),x=0)}catch{I(2)}u(x);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return b(),!0}function A(){return t.getToken()!==10?(I(3,[],[2,5]),!1):(_(!1),t.getToken()===6?(p(":"),b(),z()||I(4,[],[2,5])):I(5,[],[2,5]),!0)}function X(){s(),b();let x=!1;for(;t.getToken()!==2&&t.getToken()!==17;){if(t.getToken()===5){if(x||I(4,[],[]),p(","),b(),t.getToken()===2&&S)break}else x&&I(6,[],[]);A()||I(4,[],[2,5]),x=!0}return l(),t.getToken()!==2?I(7,[2],[]):b(),!0}function E(){d(),b();let x=!1;for(;t.getToken()!==4&&t.getToken()!==17;){if(t.getToken()===5){if(x||I(4,[],[]),p(","),b(),t.getToken()===4&&S)break}else x&&I(6,[],[]);z()||I(4,[],[4,5]),x=!0}return c(),t.getToken()!==4?I(8,[4],[]):b(),!0}function z(){switch(t.getToken()){case 3:return E();case 1:return X();case 10:return _(!0);default:return R()}}return b(),t.getToken()===17?e.allowEmptyContent?!0:(I(4,[],[]),!1):z()?(t.getToken()!==17&&I(9,[],[]),!0):(I(4,[],[]),!1)}function ZO(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 sR(i,n,e){let t,r,o,s,a;if(n){for(s=n.offset,a=s+n.length,o=s;o>0&&!ic(i,o-1);)o--;let _=a;for(;_<i.length&&!ic(i,_);)_++;r=i.substring(o,_),t=eL(r,e)}else r=i,t=0,o=0,s=0,a=i.length;let l=tL(e,i),d=!1,c=0,u;e.insertSpaces?u=Fv(" ",e.tabSize||4):u="	";let p=Nv(r,!1),m=!1;function h(){return l+Fv(u,t+c)}function y(){let _=p.scan();for(d=!1;_===15||_===14;)d=d||_===14,_=p.scan();return m=_===16||p.getTokenError()!==0,_}let S=[];function b(_,R,A){!m&&R<a&&A>s&&i.substring(R,A)!==_&&S.push({offset:R,length:A-R,content:_})}let I=y();if(I!==17){let _=p.getTokenOffset()+o,R=Fv(u,t);b(R,o,_)}for(;I!==17;){let _=p.getTokenOffset()+p.getTokenLength()+o,R=y(),A="";for(;!d&&(R===12||R===13);){let E=p.getTokenOffset()+o;b(" ",_,E),_=p.getTokenOffset()+p.getTokenLength()+o,A=R===12?h():"",R=y()}if(R===2)I!==1&&(c--,A=h());else if(R===4)I!==3&&(c--,A=h());else{switch(I){case 3:case 1:c++,A=h();break;case 5:case 12:A=h();break;case 13:d?A=h():A=" ";break;case 6:A=" ";break;case 10:if(R===6){A="";break}case 7:case 8:case 9:case 11:case 2:case 4:R===12||R===13?A=" ":R!==5&&R!==17&&(m=!0);break;case 16:m=!0;break}d&&(R===12||R===13)&&(A=h())}let X=p.getTokenOffset()+o;b(A,_,X),I=R}return S}function Fv(i,n){let e="";for(let t=0;t<n;t++)e+=i;return e}function eL(i,n){let e=0,t=0,r=n.tabSize||4;for(;e<i.length;){let o=i.charAt(e);if(o===" ")t++;else if(o==="	")t+=r;else break;e++}return Math.floor(t/r)}function tL(i,n){for(let e=0;e<n.length;e++){let t=n.charAt(e);if(t==="\r")return e+1<n.length&&n.charAt(e+1)===`
`?`\r
`:"\r";if(t===`
`)return`
`}return i&&i.eol||`
`}function ic(i,n){return`\r
`.indexOf(i.charAt(n))!==-1}function aR(i,n,e,t,r){let o=n.slice(),a=iR(i,[]),l,d;for(;o.length>0&&(d=o.pop(),l=Uv(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=Uv(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 ya(i,{offset:p,length:m-p,content:""},t)}else return ya(i,{offset:c.offset,length:c.length,content:JSON.stringify(e)},t);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 ya(i,m,t)}}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 ya(i,u,t)}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,y=l.offset+l.length;p={offset:h,length:y-2-h,content:""}}else p={offset:u.offset,length:l.children[c+1].offset-u.offset,content:""};return ya(i,p,t)}else throw new Error(`Can not add ${typeof d!="number"?"index":"property"} to parent of type ${l.type}`);else return e===void 0?[]:ya(i,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},t)}function ya(i,n,e){let t=Hv(i,n),r=n.offset,o=n.offset+n.content.length;if(n.length===0||n.content.length===0){for(;r>0&&!ic(t,r-1);)r--;for(;o<t.length&&!ic(t,o);)o++}let s=sR(t,{offset:r,length:o-r},e);for(let l=s.length-1;l>=0;l--){let d=s[l];t=Hv(t,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-(t.length-o)-r;return[{offset:r,length:a,content:t.substring(r,o)}]}function Hv(i,n){return i.substring(0,n.offset)+n.content+i.substring(n.offset+n.length)}function lR(i,n){let e=n.slice(0).sort((r,o)=>{let s=r.offset-o.offset;return s===0?r.length-o.length:s}),t=i.length;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.offset+o.length<=t)i=Hv(i,o);else throw new Error("Overlapping edit");t=o.offset}return i}function dR(i){let n=!1,e=new Map,t=new Map;if(nL(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),t.set(c,m),!0}return p.schemas.push(c),t.set(c,p),n=!0,!1}),e.clear(),!n)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=t.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 va(i){return typeof i=="object"&&i!==null}function nL(i,n){if(!i||typeof i!="object")return;let e=(...l)=>{for(let d of l)va(d)&&s.push(d)},t=(...l)=>{for(let d of l)if(va(d))for(let c in d){let u=d[c];va(u)&&s.push(u)}},r=(...l)=>{for(let d of l)if(Array.isArray(d))for(let c of d)va(c)&&s.push(c)},o=l=>{if(Array.isArray(l))for(let d of l)va(d)&&s.push(d);else va(l)&&s.push(l)},s=[i],a=s.pop();for(;a;)n(a)&&(e(a.additionalItems,a.additionalProperties,a.not,a.contains,a.propertyNames,a.if,a.then,a.else,a.unevaluatedItems,a.unevaluatedProperties),t(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 Wv={JSONContribution:"base.contributions.json"};function cR(i){return i.length>0&&i.charAt(i.length-1)==="#"?i.substring(0,i.length-1):i}var $v=class extends T{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new P);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new P);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,t,r){let o=cR(e);this.schemasById[o]=t,this._onDidChangeSchema.fire(e),r&&r.add(M(()=>{delete this.schemasById[o],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,t){let r=cR(e);return this.schemaAssociations[r]||(this.schemaAssociations[r]=[]),this.schemaAssociations[r].includes(t)||(this.schemaAssociations[r].push(t),this._onDidChangeSchemaAssociations.fire()),M(()=>{let o=this.schemaAssociations[r];if(o){let s=o.indexOf(t);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 t=this.schemasById[e];return t?dR(t):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},rL=new $v;Nt.add(Wv.JSONContribution,rL);var Bt,qv=globalThis.vscode;if(typeof qv<"u"&&typeof qv.context<"u"){let i=qv.context.configuration();if(i)Bt=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(Bt=globalThis._VSCODE_PRODUCT_JSON,Xe.VSCODE_DEV&&Object.assign(Bt,{nameShort:`${Bt.nameShort} Dev`,nameLong:`${Bt.nameLong} Dev`,dataFolderName:`${Bt.dataFolderName}-dev`,serverDataFolderName:Bt.serverDataFolderName?`${Bt.serverDataFolderName}-dev`:void 0}),!Bt.version){let i=globalThis._VSCODE_PACKAGE_JSON;Object.assign(Bt,{version:i.version})}Object.assign(Bt,{extensionsGallery:Xe.EXTENSIONS_GALLERY?JSON.parse(Xe.EXTENSIONS_GALLERY):Bt.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:Xe.CS_TELEMETRY_URL||Bt.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else Bt={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",nodejsArtifactFeed:"",electronArtifactFeed:"",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",optimizeUsageDocumentationUrl:"https://aka.ms/token-usage-tips",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.128.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.128.0",commit:"cb22f74650a539d6f824d5944ec34d9e74844f66",date:"2026-07-07T15:14:24-07:00"},Object.keys(Bt).length===0&&Object.assign(Bt,{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 gn=Bt;var Vn={Configuration:"base.contributions.configuration"};function iL(i,n){return i===n?!0:!i||!n?!1:typeof i=="string"||typeof n=="string"?i===n:i.id===n.id}var Tf={properties:{},patternProperties:{}},wf={properties:{},patternProperties:{}},Rf={properties:{},patternProperties:{}},xf={properties:{},patternProperties:{}},Pf={properties:{},patternProperties:{}},Af={properties:{},patternProperties:{}},oc={properties:{},patternProperties:{}},Xo="vscode://schemas/settings/resourceLanguage";var Ef=Nt.as(Wv.JSONContribution),Bv=class extends T{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new P);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new P);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:f(2391,null),properties:{}},this.configurationContributors=[this.defaultLanguageConfigurationOverridesNode],this.resourceLanguageSettingsSchema={properties:{},patternProperties:{},additionalProperties:!0,allowTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.policyConfigurations=new Map,this.policyReferenceConfigurations=new Map,this.excludedConfigurationProperties={},Ef.registerSchema(Xo,this.resourceLanguageSettingsSchema),this.registerOverridePropertyPatternKey()}registerConfiguration(e,t=!0){return this.registerConfigurations([e],t),e}registerConfigurations(e,t=!0){let r=new Set;this.doRegisterConfigurations(e,t,r),Ef.registerSchema(Xo,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}deregisterConfigurations(e){let t=new Set;this.doDeregisterConfigurations(e,t),Ef.registerSchema(Xo,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t})}updateConfigurations({add:e,remove:t}){let r=new Set;this.doDeregisterConfigurations(t,r),this.doRegisterConfigurations(e,!1,r),Ef.registerSchema(Xo,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}registerDefaultConfigurations(e){let t=new Set;this.doRegisterDefaultConfigurations(e,t),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t,defaultsOverrides:!0})}doRegisterDefaultConfigurations(e,t){this.registeredConfigurationDefaults.push(...e);let r=[];for(let{overrides:o,source:s}of e)for(let a in o){t.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}),Tr.test(a)){let c=this.mergeDefaultConfigurationsForOverrideIdentifier(a,d,s,l.configurationDefaultOverrideValue);if(!c)continue;l.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(a,c,s),r.push(...Sa(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 t=new Set;this.doDeregisterDefaultConfigurations(e,t),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:t,defaultsOverrides:!0})}doDeregisterDefaultConfigurations(e,t){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?iL(d.source,o):d.value===r[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),Tr.test(s)){let d;for(let c of a.configurationDefaultOverrides)d=this.mergeDefaultConfigurationsForOverrideIdentifier(s,c.value,c.source,d);d&&!Cu(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))}t.add(s)}}this.updateOverridePropertyPatternKey()}updateDefaultOverrideProperty(e,t,r){let o={section:{id:this.defaultLanguageConfigurationOverridesNode.id,title:this.defaultLanguageConfigurationOverridesNode.title,order:this.defaultLanguageConfigurationOverridesNode.order,extensionInfo:this.defaultLanguageConfigurationOverridesNode.extensionInfo},type:"object",default:t.value,description:f(2390,null,tT(e)),$ref:Xo,defaultDefaultValue:t.value,source:r,defaultValueSource:r};this.configurationProperties[e]=o,this.defaultLanguageConfigurationOverridesNode.properties[e]=o}mergeDefaultConfigurationsForOverrideIdentifier(e,t,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(t)){let d=t[l];if(Qe(d)&&(ms(s[l])||Qe(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,t,r,o){let s=this.configurationProperties[e],a=o?.value??s?.defaultDefaultValue,l=r;if(Qe(t)&&(s!==void 0&&s.type==="object"||s===void 0&&(ms(a)||Qe(a)))){if(l=o?.source??new Map,!(l instanceof Map)){console.error("defaultValueSource is not a Map");return}for(let c in t)r&&l.set(`${e}.${c}`,r);t={...Qe(a)?a:{},...t}}return{value:t,source:l}}deltaConfiguration(e){let t=!1,r=new Set;e.removedDefaults&&(this.doDeregisterDefaultConfigurations(e.removedDefaults,r),t=!0),e.addedDefaults&&(this.doRegisterDefaultConfigurations(e.addedDefaults,r),t=!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:t})}notifyConfigurationSchemaUpdated(...e){this._onDidSchemaChange.fire()}registerOverrideIdentifiers(e){this.doRegisterOverrideIdentifiers(e),this._onDidSchemaChange.fire()}doRegisterOverrideIdentifiers(e){for(let t of e)this.overrideIdentifiers.add(t);this.updateOverridePropertyPatternKey()}doRegisterConfigurations(e,t,r){e.forEach(o=>{this.validateAndRegisterProperties(o,t,o.extensionInfo,o.restrictedProperties,void 0,r),this.configurationContributors.push(o),this.registerJSONConfiguration(o)})}doDeregisterConfigurations(e,t){let r=o=>{if(o.properties)for(let s in o.properties){t.add(s);let a=this.configurationProperties[s];if(a?.policy?.name&&this.policyConfigurations.delete(a.policy.name),a?.policyReference?.name){let l=this.policyReferenceConfigurations.get(a.policyReference.name);l&&(l.delete(s),l.size===0&&this.policyReferenceConfigurations.delete(a.policyReference.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,t=!0,r,o,s=4,a){s=Jn(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},t&&sL(c,u,r?.id)){delete l[c];continue}u.source=r,u.defaultDefaultValue=l[c].default,this.updatePropertyDefaultValue(c,u),Tr.test(c)?u.scope=void 0:(u.scope=Jn(u.scope)?s:u.scope,u.restricted=Jn(u.restricted)?!!o?.includes(c):u.restricted),u.experiment?u.tags?.some(y=>y.toLowerCase()==="onexp")||(u.tags=u.tags??[],u.tags.push("onExP")):u.tags?.some(y=>y.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,h=l[c].policyReference?.name;p?(this.excludedConfigurationProperties[c]=l[c],m&&(this.policyConfigurations.set(m,c),a.add(c)),h&&(this.addPolicyReferenceConfiguration(h,c),a.add(c)),delete l[c]):(a.add(c),m&&this.policyConfigurations.set(m,c),h&&this.addPolicyReferenceConfiguration(h,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,t,r,o,s,a)}addPolicyReferenceConfiguration(e,t){let r=this.policyReferenceConfigurations.get(e);r||(r=new Set,this.policyReferenceConfigurations.set(e,r)),r.add(t)}getConfigurations(){return this.configurationContributors}getConfigurationProperties(){return this.configurationProperties}getPolicyConfigurations(){return this.policyConfigurations}getPolicyReferenceConfigurations(){return this.policyReferenceConfigurations}getExcludedConfigurationProperties(){return this.excludedConfigurationProperties}getRegisteredDefaultConfigurations(){return[...this.registeredConfigurationDefaults]}getConfigurationDefaultsOverrides(){let e=new Map;for(let[t,r]of this.configurationDefaultsOverrides)r.configurationDefaultOverrideValue&&e.set(t,r.configurationDefaultOverrideValue);return e}registerJSONConfiguration(e){let t=r=>{let o=r.properties;if(o)for(let a in o)this.updateSchema(a,o[a]);r.allOf?.forEach(t)};t(e)}updateSchema(e,t){switch(Tf.properties[e]=t,t.scope){case 1:wf.properties[e]=t;break;case 2:xf.properties[e]=t;break;case 3:Rf.properties[e]=t;break;case 7:Pf.properties[e]=t;break;case 4:Af.properties[e]=t;break;case 5:oc.properties[e]=t;break;case 6:oc.properties[e]=t,this.resourceLanguageSettingsSchema.properties[e]=t;break}}removeFromSchema(e,t){switch(delete Tf.properties[e],t.scope){case 1:delete wf.properties[e];break;case 2:delete xf.properties[e];break;case 3:delete Rf.properties[e];break;case 7:delete Pf.properties[e];break;case 4:delete Af.properties[e];break;case 5:case 6:delete oc.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let t=`[${e}]`,r={type:"object",description:f(2392,null),errorMessage:f(2393,null),$ref:Xo};this.updatePropertyDefaultValue(t,r),Tf.properties[t]=r,wf.properties[t]=r,Rf.properties[t]=r,xf.properties[t]=r,Pf.properties[t]=r,Af.properties[t]=r,oc.properties[t]=r}}registerOverridePropertyPatternKey(){let e={type:"object",description:f(2392,null),errorMessage:f(2393,null),$ref:Xo};Tf.patternProperties[Ki]=e,wf.patternProperties[Ki]=e,Rf.patternProperties[Ki]=e,xf.patternProperties[Ki]=e,Pf.patternProperties[Ki]=e,Af.patternProperties[Ki]=e,oc.patternProperties[Ki]=e,this._onDidSchemaChange.fire()}updatePropertyDefaultValue(e,t){let r=this.configurationDefaultsOverrides.get(e)?.configurationDefaultOverrideValue,o,s;r&&(!t.disallowConfigurationDefault||!r.source)&&(o=r.value,s=r.source),ms(o)&&(o=t.defaultDefaultValue,s=void 0),ms(o)&&(o=oL(t.type)),t.default=o,t.defaultValueSource=s}},pR="\\[([^\\]]+)\\]",uR=new RegExp(pR,"g"),Ki=`^(${pR})+$`,Tr=new RegExp(Ki);function Sa(i){let n=[];if(Tr.test(i)){let e=uR.exec(i);for(;e?.length;){let t=e[1].trim();t&&n.push(t),e=uR.exec(i)}}return Fr(n)}function fR(i){return i.reduce((n,e)=>`${n}[${e}]`,"")}function oL(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 kf=new Bv;Nt.add(Vn.Configuration,kf);function sL(i,n,e){return i.trim()?Tr.test(i)?f(2389,null,i):kf.getConfigurationProperties()[i]!==void 0&&(!e||!aL.has(e.toLowerCase()))?f(2387,null,i):n.policy&&n.policyReference?f(2385,null,i):n.policy?.name&&kf.getPolicyConfigurations().get(n.policy?.name)!==void 0?f(2386,null,i,n.policy?.name,kf.getPolicyConfigurations().get(n.policy?.name)):null:f(2388,null)}var aL=new Set(gn.defaultChatAgent?[gn.defaultChatAgent.extensionId,gn.defaultChatAgent.chatExtensionId].map(i=>i.toLowerCase()):[]);function sc(i){return Object.isFrozen(i)?i:f_(i)}var nt=class i{constructor(n,e,t,r,o){this._contents=n;this._keys=e;this._overrides=t;this._raw=r;this.logService=o;this.overrideConfigurations=new Map}static createEmptyModel(n){return new i({},[],[],void 0,n)}get rawConfiguration(){if(!this._rawConfiguration)if(this._raw){let n=(Array.isArray(this._raw)?this._raw:[this._raw]).map(e=>{if(e instanceof i)return e;let t=new Df("",this.logService);return t.parseRaw(e),t.configurationModel});this._rawConfiguration=n.reduce((e,t)=>t===e?t:e.merge(t),n[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(n=>n instanceof i)))return this._raw}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}getValue(n){return n?Id(this.contents,n):this.contents}inspect(n,e){let t=this;return{get value(){return sc(t.rawConfiguration.getValue(n))},get override(){return e?sc(t.rawConfiguration.getOverrideValue(n,e)):void 0},get merged(){return sc(e?t.rawConfiguration.override(e).getValue(n):t.rawConfiguration.getValue(n))},get overrides(){let r=[];for(let{contents:o,identifiers:s,keys:a}of t.rawConfiguration.overrides){let l=new i(o,a,[],void 0,t.logService).getValue(n);l!==void 0&&r.push({identifiers:s,value:l})}return r.length?sc(r):void 0}}}getOverrideValue(n,e){let t=this.getContentsForOverrideIdentifer(e);return t?n?Id(t,n):t:void 0}getKeysForOverrideIdentifier(n){let e=[];for(let t of this.overrides)t.identifiers.includes(n)&&e.push(...t.keys);return Fr(e)}getAllOverrideIdentifiers(){let n=[];for(let e of this.overrides)n.push(...e.identifiers);return Fr(n)}override(n){let e=this.overrideConfigurations.get(n);return e||(e=this.createOverrideConfigurationModel(n),this.overrideConfigurations.set(n,e)),e}merge(...n){let e=Ln(this.contents),t=Ln(this.overrides),r=[...this.keys],o=this._raw?Array.isArray(this._raw)?[...this._raw]:[this._raw]:[this];for(let s of n)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]=t.filter(d=>bn(d.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=Fr(l.keys)):t.push(Ln(a))}for(let a of s.keys)r.indexOf(a)===-1&&r.push(a)}return new i(e,r,t,!o.length||o.every(s=>s instanceof i)?void 0:o,this.logService)}createOverrideConfigurationModel(n){let e=this.getContentsForOverrideIdentifer(n);if(!e||typeof e!="object"||!Object.keys(e).length)return this;let t={};for(let r of Fr([...Object.keys(this.contents),...Object.keys(e)])){let o=this.contents[r],s=e[r];s&&(typeof o=="object"&&typeof s=="object"?(o=Ln(o),this.mergeContents(o,s)):o=s),t[r]=o}return new i(t,this.keys,this.overrides,void 0,this.logService)}mergeContents(n,e){for(let t of Object.keys(e)){if(t in n&&Qe(n[t])&&Qe(e[t])){this.mergeContents(n[t],e[t]);continue}n[t]=Ln(e[t])}}getContentsForOverrideIdentifer(n){let e=null,t=null,r=o=>{o&&(t?this.mergeContents(t,o):t=Ln(o))};for(let o of this.overrides)o.identifiers.length===1&&o.identifiers[0]===n?e=o.contents:o.identifiers.includes(n)&&r(o.contents);return r(e),t}toJSON(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}}addValue(n,e){this.updateValue(n,e,!0)}setValue(n,e){this.updateValue(n,e,!1)}removeValue(n){let e=this.keys.indexOf(n);e!==-1&&(this.keys.splice(e,1),Z_(this.contents,n),Tr.test(n)&&this.overrides.splice(this.overrides.findIndex(t=>bn(t.identifiers,Sa(n))),1))}updateValue(n,e,t){if(Py(this.contents,n,e,r=>this.logService.error(r)),t=t||this.keys.indexOf(n)===-1,t&&this.keys.push(n),Tr.test(n)){let r=this.contents[n],o=Sa(n),s={identifiers:o,keys:Object.keys(r),contents:gp(r,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>bn(l.identifiers,o));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},Df=class{constructor(n,e){this._name=n;this.logService=e;this._raw=null;this._configurationModel=null;this._restrictedConfigurations=[];this._parseErrors=[]}get configurationModel(){return this._configurationModel||nt.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(n,e){if(!Jn(n)){let t=this.doParseContent(n);this.parseRaw(t,e)}}reparse(n){this._raw&&this.parseRaw(this._raw,n)}parseRaw(n,e){this._raw=n;let{contents:t,keys:r,overrides:o,restricted:s,hasExcludedProperties:a}=this.doParseRaw(n,e);this._configurationModel=new nt(t,r,o,a?[n]:void 0,this.logService),this._restrictedConfigurations=s||[]}doParseContent(n){let e={},t=null,r=[],o=[],s=[];function a(d){Array.isArray(r)?r.push(d):t!==null&&(r[t]=d)}let l={onObjectBegin:()=>{let d={};a(d),o.push(r),r=d,t=null},onObjectProperty:d=>{t=d},onObjectEnd:()=>{r=o.pop()},onArrayBegin:()=>{let d=[];a(d),o.push(r),r=d,t=null},onArrayEnd:()=>{r=o.pop()},onLiteralValue:a,onError:(d,c,u)=>{s.push({error:d,offset:c,length:u})}};if(n)try{ha(n,l),e=r[0]||{}}catch(d){this.logService.error(`Error while parsing settings file ${this._name}: ${d}`),this._parseErrors=[d]}return e}doParseRaw(n,e){let t=Nt.as(Vn.Configuration),r=t.getConfigurationProperties(),o=t.getExcludedConfigurationProperties(),s=this.filter(n,r,o,!0,e);n=s.raw;let a=gp(n,c=>this.logService.error(`Conflict in settings file ${this._name}: ${c}`)),l=Object.keys(n),d=this.toOverrides(n,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(n,e,t,r,o){let s=!1;if(!o?.scopes&&!o?.skipRestricted&&!o?.skipUnregistered&&!o?.exclude?.length)return{raw:n,restricted:[],hasExcludedProperties:s};let a={},l=[];for(let d in n)if(Tr.test(d)&&r){let c=this.filter(n[d],e,t,!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,t,o)?a[d]=n[d]:s=!0}return{raw:a,restricted:l,hasExcludedProperties:s}}shouldInclude(n,e,t,r){if(r.exclude?.includes(n))return!1;if(r.include?.includes(n))return!0;if(r.skipRestricted&&e?.restricted||r.skipUnregistered&&!e)return!1;let o=e??t[n],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(n,e){let t=[];for(let r of Object.keys(n))if(Tr.test(r)){let o={},s=n[r];for(let a in s)o[a]=s[a];t.push({identifiers:Sa(r),keys:Object.keys(o),contents:gp(o,e)})}return t}},Mf=class extends T{constructor(e,t,r,o,s){super();this.userSettingsResource=e;this.parseOptions=t;this.fileService=o;this.logService=s;this._onDidChange=this._register(new P);this.onDidChange=this._onDidChange.event;this.parser=new Df(this.userSettingsResource.toString(),s),this._register(this.fileService.watch(r.dirname(this.userSettingsResource))),this._register(this.fileService.watch(this.userSettingsResource)),this._register(ee.any(ee.filter(this.fileService.onDidFilesChange,a=>a.contains(this.userSettingsResource)),ee.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 nt.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},zv=class{constructor(n,e,t,r,o,s,a,l,d,c,u,p,m){this.key=n;this.overrides=e;this._value=t;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 sc(this._value)}toInspectValue(n){return n?.value!==void 0||n?.override!==void 0||n?.overrides!==void 0?n: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)}},ba=class i{constructor(n,e,t,r,o,s,a,l,d,c){this._defaultConfiguration=n;this._policyConfiguration=e;this._applicationConfiguration=t;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 We;this._userConfiguration=null}getValue(n,e,t){return this.getConsolidatedConfigurationModel(n,e,t).getValue(n)}updateValue(n,e,t={}){let r;t.resource?(r=this._memoryConfigurationByResource.get(t.resource),r||(r=nt.createEmptyModel(this.logService),this._memoryConfigurationByResource.set(t.resource,r))):r=this._memoryConfiguration,e===void 0?r.removeValue(n):r.setValue(n,e),t.resource||(this._workspaceConsolidatedConfiguration=null)}inspect(n,e,t){let r=this.getConsolidatedConfigurationModel(n,e,t),o=this.getFolderConfigurationModelForResource(e.resource,t),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(n,d)!==void 0&&a.add(d);return new zv(n,e,r.getValue(n),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,t?this._workspaceConfiguration:void 0,o||void 0,s)}keys(n){let e=this.getFolderConfigurationModelForResource(void 0,n);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(n){this._defaultConfiguration=n,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updatePolicyConfiguration(n){this._policyConfiguration=n}updateApplicationConfiguration(n){this._applicationConfiguration=n,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateLocalUserConfiguration(n){this._localUserConfiguration=n,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateRemoteUserConfiguration(n){this._remoteUserConfiguration=n,this._userConfiguration=null,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateWorkspaceConfiguration(n){this._workspaceConfiguration=n,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()}updateFolderConfiguration(n,e){this._folderConfigurations.set(n,e),this._foldersConsolidatedConfigurations.delete(n)}deleteFolderConfiguration(n){this.folderConfigurations.delete(n),this._foldersConsolidatedConfigurations.delete(n)}compareAndUpdateDefaultConfiguration(n,e){let t=[];if(!e){let{added:r,updated:o,removed:s}=Gi(this._defaultConfiguration,n);e=[...r,...o,...s]}for(let r of e)for(let o of Sa(r)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(o),a=n.getKeysForOverrideIdentifier(o),l=[...a.filter(d=>s.indexOf(d)===-1),...s.filter(d=>a.indexOf(d)===-1),...s.filter(d=>!Fe(this._defaultConfiguration.override(o).getValue(d),n.override(o).getValue(d)))];t.push([o,l])}return this.updateDefaultConfiguration(n),{keys:e,overrides:t}}compareAndUpdatePolicyConfiguration(n){let{added:e,updated:t,removed:r}=Gi(this._policyConfiguration,n),o=[...e,...t,...r];return o.length&&this.updatePolicyConfiguration(n),{keys:o,overrides:[]}}compareAndUpdateApplicationConfiguration(n){let{added:e,updated:t,removed:r,overrides:o}=Gi(this.applicationConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateApplicationConfiguration(n),{keys:s,overrides:o}}compareAndUpdateLocalUserConfiguration(n){let{added:e,updated:t,removed:r,overrides:o}=Gi(this.localUserConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateLocalUserConfiguration(n),{keys:s,overrides:o}}compareAndUpdateRemoteUserConfiguration(n){let{added:e,updated:t,removed:r,overrides:o}=Gi(this.remoteUserConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateRemoteUserConfiguration(n),{keys:s,overrides:o}}compareAndUpdateWorkspaceConfiguration(n){let{added:e,updated:t,removed:r,overrides:o}=Gi(this.workspaceConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateWorkspaceConfiguration(n),{keys:s,overrides:o}}compareAndUpdateFolderConfiguration(n,e){let t=this.folderConfigurations.get(n),{added:r,updated:o,removed:s,overrides:a}=Gi(t,e),l=[...r,...o,...s];return(l.length||!t)&&this.updateFolderConfiguration(n,e),{keys:l,overrides:a}}compareAndDeleteFolderConfiguration(n){let e=this.folderConfigurations.get(n);if(!e)throw new Error("Unknown folder");this.deleteFolderConfiguration(n);let{added:t,updated:r,removed:o,overrides:s}=Gi(e,void 0);return{keys:[...t,...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 n=this._localUserConfiguration.merge(this._remoteUserConfiguration);this._userConfiguration=new nt(n.contents,n.keys,n.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(n,e,t){let r=this.getConsolidatedConfigurationModelForResource(e,t);if(e.overrideIdentifier&&(r=r.override(e.overrideIdentifier)),!this._policyConfiguration.isEmpty()&&this._policyConfiguration.getValue(n)!==void 0){r=r.merge();for(let o of this._policyConfiguration.keys)r.setValue(o,this._policyConfiguration.getValue(o))}return r}getConsolidatedConfigurationModelForResource({resource:n},e){let t=this.getWorkspaceConsolidatedConfiguration();if(e&&n){let r=e.getFolder(n);r&&(t=this.getFolderConsolidatedConfiguration(r.uri)||t);let o=this._memoryConfigurationByResource.get(n);o&&(t=t.merge(o))}return t}getWorkspaceConsolidatedConfiguration(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this.applicationConfiguration,this.userConfiguration,this._workspaceConfiguration,this._memoryConfiguration)),this._workspaceConsolidatedConfiguration}getFolderConsolidatedConfiguration(n){let e=this._foldersConsolidatedConfigurations.get(n);if(!e){let t=this.getWorkspaceConsolidatedConfiguration(),r=this._folderConfigurations.get(n);r?(e=t.merge(r),this._foldersConsolidatedConfigurations.set(n,e)):e=t}return e}getFolderConfigurationModelForResource(n,e){if(e&&n){let t=e.getFolder(n);if(t)return this._folderConfigurations.get(t.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((n,e)=>{let{contents:t,overrides:r,keys:o}=this._folderConfigurations.get(e);return n.push([e,{contents:t,overrides:r,keys:o}]),n},[])}}allKeys(){let n=new Set;return this._defaultConfiguration.keys.forEach(e=>n.add(e)),this.userConfiguration.keys.forEach(e=>n.add(e)),this._workspaceConfiguration.keys.forEach(e=>n.add(e)),this._folderConfigurations.forEach(e=>e.keys.forEach(t=>n.add(t))),[...n.values()]}allOverrideIdentifiers(){let n=new Set;return this._defaultConfiguration.getAllOverrideIdentifiers().forEach(e=>n.add(e)),this.userConfiguration.getAllOverrideIdentifiers().forEach(e=>n.add(e)),this._workspaceConfiguration.getAllOverrideIdentifiers().forEach(e=>n.add(e)),this._folderConfigurations.forEach(e=>e.getAllOverrideIdentifiers().forEach(t=>n.add(t))),[...n.values()]}getAllKeysForOverrideIdentifier(n){let e=new Set;return this._defaultConfiguration.getKeysForOverrideIdentifier(n).forEach(t=>e.add(t)),this.userConfiguration.getKeysForOverrideIdentifier(n).forEach(t=>e.add(t)),this._workspaceConfiguration.getKeysForOverrideIdentifier(n).forEach(t=>e.add(t)),this._folderConfigurations.forEach(t=>t.getKeysForOverrideIdentifier(n).forEach(r=>e.add(r))),[...e.values()]}static parse(n,e){let t=this.parseConfigurationModel(n.defaults,e),r=this.parseConfigurationModel(n.policy,e),o=this.parseConfigurationModel(n.application,e),s=this.parseConfigurationModel(n.userLocal,e),a=this.parseConfigurationModel(n.userRemote,e),l=this.parseConfigurationModel(n.workspace,e),d=n.folders.reduce((c,u)=>(c.set(v.revive(u[0]),this.parseConfigurationModel(u[1],e)),c),new We);return new i(t,r,o,s,a,l,d,nt.createEmptyModel(e),new We,e)}static parseConfigurationModel(n,e){return new nt(n.contents,n.keys,n.overrides,n.raw,e)}};var Of=class{constructor(n,e,t,r,o){this.change=n;this.previous=e;this.currentConfiguraiton=t;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 n.keys)this.affectedKeys.add(s);for(let[,s]of n.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=ba.parse(this.previous.data,this.logService)),this._previousConfiguration}affectsConfiguration(n,e){let t=this._marker+n,r=this._affectsConfigStr.indexOf(t);if(r<0)return!1;let o=r+t.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(n,e,this.previous?.workspace):void 0,l=this.currentConfiguraiton.getValue(n,e,this.currentWorkspace);return!Fe(a,l)}return!0}};function Gi(i,n){let{added:e,removed:t,updated:r}=gR(n?.rawConfiguration,i?.rawConfiguration),o=[],s=i?.getAllOverrideIdentifiers()||[],a=n?.getAllOverrideIdentifiers()||[];if(n){let l=a.filter(d=>!s.includes(d));for(let d of l)o.push([d,n.getKeysForOverrideIdentifier(d)])}if(i){let l=s.filter(d=>!a.includes(d));for(let d of l)o.push([d,i.getKeysForOverrideIdentifier(d)])}if(n&&i){for(let l of s)if(a.includes(l)){let d=gR({contents:i.getOverrideValue(void 0,l)||{},keys:i.getKeysForOverrideIdentifier(l)},{contents:n.getOverrideValue(void 0,l)||{},keys:n.getKeysForOverrideIdentifier(l)});o.push([l,[...d.added,...d.removed,...d.updated]])}}return{added:e,removed:t,updated:r,overrides:o}}function gR(i,n){let e=i?n?i.keys.filter(o=>n.keys.indexOf(o)===-1):[...i.keys]:[],t=n?i?n.keys.filter(o=>i.keys.indexOf(o)===-1):[...n.keys]:[],r=[];if(i&&n){for(let o of n.keys)if(i.keys.indexOf(o)!==-1){let s=Id(n.contents,o),a=Id(i.contents,o);Fe(s,a)||r.push(o)}}return{added:e,removed:t,updated:r}}var Lf=$("policy");var Ji=class{constructor(){this.onDidChange=ee.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var Nf=class extends T{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new P);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=nt.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(Nt.as(Vn.Configuration).onDidUpdateConfiguration(({properties:e,defaultsOverrides:t})=>this.onDidUpdateConfiguration(Array.from(e),t))),this.configurationModel}reload(){return this.resetConfigurationModel(),this.configurationModel}onDidUpdateConfiguration(e,t){this.updateConfigurationModel(e,Nt.as(Vn.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=nt.createEmptyModel(this.logService);let e=Nt.as(Vn.Configuration).getConfigurationProperties();this.updateConfigurationModel(Object.keys(e),e)}updateConfigurationModel(e,t){let r=this.getConfigurationDefaultOverrides();for(let o of e){let s=r[o],a=t[o];s!==void 0?this._configurationModel.setValue(o,s):a?this._configurationModel.setValue(o,this.getDefaultValue(o,a)):this._configurationModel.removeValue(o)}}getDefaultValue(e,t){return Ln(t.default)}},Uf=class{constructor(){this.onDidChangeConfiguration=ee.None;this.configurationModel=nt.createEmptyModel(new $p)}async initialize(){return this.configurationModel}},Ca=class extends T{constructor(e,t,r){super();this.defaultConfiguration=e;this.policyService=t;this.logService=r;this._onDidChangeConfiguration=this._register(new P);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._submittedPolicyDefinitions=new Map;this._policyNameByKey=new Map;this._configurationModel=nt.createEmptyModel(this.logService),this.configurationRegistry=Nt.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}toPolicyDefinitionType(e,t){let o=(Array.isArray(e)?e:[e]).filter(s=>s==="string"||s==="number"||s==="array"||s==="object"||s==="boolean");if(o.length===0){this.logService.warn(`PolicyConfiguration#updatePolicyDefinitions - policy '${t}' has unsupported type '${e}'`);return}return o.includes("number")?"number":o.includes("boolean")?"boolean":"string"}async updatePolicyDefinitions(e){this.logService.trace("PolicyConfiguration#updatePolicyDefinitions",e);let t=[],r=new Set,o=this.configurationRegistry.getConfigurationProperties(),s=this.configurationRegistry.getExcludedConfigurationProperties();for(let l of e){let d=o[l]??s[l];if(!d){t.push(l);let u=this._policyNameByKey.get(l);u!==void 0&&(this._policyNameByKey.delete(l),r.add(u));continue}let c=d.policy?.name??d.policyReference?.name;c&&(t.push(l),r.add(c),this._policyNameByKey.set(l,c))}let a={};for(let l of r){let d=this.resolvePolicyDefinition(l);d&&!this.isSamePolicyDefinition(this._submittedPolicyDefinitions.get(l),d)&&(this._submittedPolicyDefinitions.set(l,d),a[l]=d)}return Cu(a)||await this.policyService.updatePolicyDefinitions(a),t}isSamePolicyDefinition(e,t){return!!e&&e.type===t.type&&e.value===t.value&&e.managedSettings===t.managedSettings&&e.restrictedValue===t.restrictedValue}resolvePolicyDefinition(e){let t=this.configurationRegistry.getConfigurationProperties(),r=this.configurationRegistry.getExcludedConfigurationProperties(),o=this.configurationRegistry.getPolicyConfigurations().get(e);if(o!==void 0){let a=t[o]??r[o];if(a?.policy){let l=this.toPolicyDefinitionType(a.type,e),{value:d,managedSettings:c,restrictedValue:u}=a.policy;return l?{type:l,value:d,managedSettings:c,restrictedValue:u}:void 0}}let s=this.configurationRegistry.getPolicyReferenceConfigurations().get(e);for(let a of s??[]){let l=t[a]??r[a];if(l?.policyReference){let d=this.toPolicyDefinitionType(l.type,e);return d?{type:d}:void 0}}}onDidChangePolicies(e){this.logService.trace("PolicyConfiguration#onDidChangePolicies",e);let t=this.configurationRegistry.getPolicyConfigurations(),r=this.configurationRegistry.getPolicyReferenceConfigurations(),o=[];for(let s of e){let a=t.get(s);a&&o.push(a);let l=r.get(s);l&&o.push(...l)}this.update(o,!0)}update(e,t){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??d?.policyReference?.name;if(c){let u=this.policyService.getPolicyValue(c),p=Array.isArray(d.type)?d.type.includes("string"):d.type==="string";if(Ve(u)&&!p)try{u=this.parse(u)}catch(m){this.logService.error(`Error parsing policy value ${c}:`,Ur(m));continue}(a?u!==void 0:!Fe(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=nt.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);t&&this._onDidChangeConfiguration.fire(this._configurationModel)}}parse(e){let t={},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&&(ha(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})}}),t=o[0]||t),a.length>0)throw new Error(a.map(c=>Ur(c.error)).join(`
`));return t}};Ca=w([C(1,Lf),C(2,D)],Ca);var Ia=class extends T{constructor(e,t,r,o){super();this.settingsResource=e;this.logService=o;this._onDidChangeConfiguration=this._register(new P);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new Nf(o)),this.policyConfiguration=r instanceof Ji?new Uf:this._register(new Ca(this.defaultConfiguration,r,o)),this.userConfiguration=this._register(new Mf(this.settingsResource,{},rt,t,o)),this.configuration=new ba(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,nt.createEmptyModel(o),nt.createEmptyModel(o),nt.createEmptyModel(o),nt.createEmptyModel(o),new We,nt.createEmptyModel(o),new We,o),this.configurationEditing=new Vv(e,t,this),this.reloadConfigurationScheduler=this._register(new Di(()=>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,t,r]=await Promise.all([this.defaultConfiguration.initialize(),this.policyConfiguration.initialize(),this.userConfiguration.loadConfiguration()]);this.configuration=new ba(e,t,nt.createEmptyModel(this.logService),r,nt.createEmptyModel(this.logService),nt.createEmptyModel(this.logService),new We,nt.createEmptyModel(this.logService),new We,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,t){let r=typeof e=="string"?e:void 0,o=fp(e)?e:fp(t)?t:{};return this.configuration.getValue(r,o,void 0)}async updateValue(e,t,r,o,s){let a=X_(r)?r:fp(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=Fr(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(Fe(t,d.defaultValue)&&(t=void 0),a?.overrideIdentifiers?.length&&a.overrideIdentifiers.length>1){let u=a.overrideIdentifiers.sort(),p=this.configuration.localUserConfiguration.overrides.find(m=>bn([...m.identifiers].sort(),u));p&&(a.overrideIdentifiers=p.identifiers)}let c=a?.overrideIdentifiers?.length?[fR(a.overrideIdentifiers),e]:[e];await this.configurationEditing.write(c,t),await this.reloadConfiguration()}inspect(e,t={}){return this.configuration.inspect(e,t,void 0)}keys(){return this.configuration.keys(void 0)}async reloadConfiguration(){let e=await this.userConfiguration.loadConfiguration();this.onDidChangeUserConfiguration(e)}onDidChangeUserConfiguration(e){let t=this.configuration.toData(),r=this.configuration.compareAndUpdateLocalUserConfiguration(e);this.trigger(r,t,2)}onDidDefaultConfigurationChange(e,t){let r=this.configuration.toData(),o=this.configuration.compareAndUpdateDefaultConfiguration(e,t);this.trigger(o,r,7)}onDidPolicyConfigurationChange(e){let t=this.configuration.toData(),r=this.configuration.compareAndUpdatePolicyConfiguration(e);this.trigger(r,t,7)}trigger(e,t,r){let o=new Of(e,{data:t},this.configuration,void 0,this.logService);o.source=r,this._onDidChangeConfiguration.fire(o)}},Vv=class{constructor(n,e,t){this.settingsResource=n;this.fileService=e;this.configurationService=t;this.queue=new ki}write(n,e){return this.queue.queue(()=>this.doWriteConfiguration(n,e))}async doWriteConfiguration(n,e){let t;try{t=(await this.fileService.readFile(this.settingsResource)).value.toString()}catch(s){if(s.fileOperationResult===1)t="{}";else throw s}let r=[];if(_f(t,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(t,n,e);t=lR(t,o),await this.fileService.writeFile(this.settingsResource,U.fromString(t))}getEdits(n,e,t){let{tabSize:r,insertSpaces:o,eol:s}=this.formattingOptions;if(!e.length){let a=JSON.stringify(t,null,o?" ".repeat(r):"	");return[{content:a,length:a.length,offset:0}]}return aR(n,e,t,{tabSize:r,insertSpaces:o,eol:s})}get formattingOptions(){if(!this._formattingOptions){let n=Et===3||Et===2?`
`:`\r
`,e=this.configurationService.getValue("files.eol",{overrideIdentifier:"jsonc"});e&&typeof e=="string"&&e!=="auto"&&(n=e),this._formattingOptions={eol:n,insertSpaces:!!this.configurationService.getValue("editor.insertSpaces",{overrideIdentifier:"jsonc"}),tabSize:this.configurationService.getValue("editor.tabSize",{overrideIdentifier:"jsonc"})}}return this._formattingOptions}};var _a=$("requestService"),vR="NO_FETCH_TELEMETRY",Kv=class{constructor(n){this.original=n}toJSON(){if(!this.headers){let n=Object.create(null);for(let e in this.original)e.toLowerCase()==="authorization"||e.toLowerCase()==="proxy-authorization"?n[e]="*****":n[e]=this.original[e];this.headers=n}return this.headers}},Ff=class extends T{constructor(e){super();this.logService=e;this.counter=0;this._onDidCompleteRequest=this._register(new P);this.onDidCompleteRequest=this._onDidCompleteRequest.event}async logAndRequest(e,t){let r=`#${++this.counter}: ${e.url}`;this.logService.trace(`${r} - begin`,e.type,new Kv(e.headers??{}));let o=Date.now();try{let s=await t();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,Ur(s)),s}}};var Ta=!1,jv=[],hR,yR;function dL(i=!0,n=!0){if(hR===i&&yR===n)return;hR=i,yR=n;let e=Nt.as(Vn.Configuration),t=jv;jv=[{id:"http",order:15,title:f(2759,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:n,markdownDescription:f(2774,null),restricted:!0}}},{id:"http",order:15,title:f(2759,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:f(2757,null),restricted:!0}}},{id:"http",order:15,title:f(2759,null),type:"object",scope:i?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:f(2762,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:f(2770,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:f(2764,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:f(2761,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:f(2763,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[f(2767,null),f(2768,null),f(2766,null),f(2769,null)],default:"override",markdownDescription:f(2765,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:f(2771,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:Ta,markdownDescription:f(2772,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:f(2773,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2758,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.webSocketAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2775,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:f(2760,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:jv,remove:t})}dL();var cL=!1,Jv=class{constructor(n,e,t){this.id=n;this.dependencies=e;this.callback=t}};var Yv=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=(n,e,t)=>{typeof n!="string"&&(t=e,e=n,n=null),(typeof e!="object"||!Array.isArray(e))&&(t=e,e=null),this._defineCalls.push(new Jv(n,e,t))},globalThis.define.amd=!0,this._isRenderer?this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??window.trustedTypes?.createPolicy("amdLoader",{createScriptURL(n){if(n.startsWith(window.location.origin)||n.startsWith(`${ie.vscodeFileResource}://${dy}`))return n;throw new Error(`[trusted_script_src] Invalid script url: ${n}`)}}):this._isWebWorker&&(this._amdPolicy=globalThis._VSCODE_WEB_PACKAGE_TTP??globalThis.trustedTypes?.createPolicy("amdLoader",{createScriptURL(n){return n}}))}async load(n){if(this._initialize(),this._state===3)return new Promise(s=>{let a=H();globalThis.define(a,[n],function(l){s(l)})});let e=await(this._isWebWorker?this._workerLoadScript(n):this._isRenderer?this._rendererLoadScript(n):this._nodeJSLoadScript(n));if(!e){console.warn(`Did not receive a define call from script ${n}`);return}let t={},r=[],o=[];if(Array.isArray(e.dependencies))for(let s of e.dependencies)s==="exports"?r.push(t):o.push(s);if(o.length>0)throw new Error(`Cannot resolve dependencies for script ${n}. The dependencies are: ${o.join(", ")}`);return typeof e.callback=="function"?e.callback(...r)??t:e.callback}_rendererLoadScript(n){return new Promise((e,t)=>{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(),t(l)};r.addEventListener("load",s),r.addEventListener("error",a),this._amdPolicy&&(n=this._amdPolicy.createScriptURL(n)),r.setAttribute("src",n),window.document.getElementsByTagName("head")[0].appendChild(r)})}async _workerLoadScript(n){return this._amdPolicy&&(n=this._amdPolicy.createScriptURL(n)),await import(n),this._defineCalls.pop()}async _nodeJSLoadScript(n){try{let e=(await import("fs")).default,t=(await import("vm")).default,r=(await import("module")).default,o=v.parse(n).fsPath,s=e.readFileSync(o).toString(),a=r.wrap(s.replace(/^#!.*/,""));return new t.Script(a).runInThisContext().apply(),this._defineCalls.pop()}catch(e){throw e}}},Gv=new Map;async function Qv(i,n,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let t=n?`${i}/${n}`:i;if(Gv.has(t))return Gv.get(t);let r;if(/^\w[\w\d+.-]*:\/\//.test(t))r=t;else{let l=`${cL&&e&&!Zt?qI:WI}/${t}`;r=Dt.asBrowserUri(l).toString(!0)}let o=Yv.INSTANCE.load(r);return Gv.set(t,o),o}function uL(i){if(Wh===2&&/^penguin(\.|$)/i.test(i))return"chromebook"}function SR(i,n,e,t,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=H()+Date.now(),u.commitHash=t,u.version=r,u["common.releaseDate"]=d,u["common.platformVersion"]=(i||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=ZC(Wh),u["common.nodePlatform"]=Cs,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}}),eI&&(u["common.snap"]="true");let h=uL(n);return h&&(u["common.platformDetail"]=h),u}function bR(i){let n=Xe.USERDNSDOMAIN;if(!n)return!1;let e=n.toLowerCase();return i.some(t=>e===t)}var ac=class{constructor(n){this.value=n;this.isTrustedTelemetryValue=!0}},Xv=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(){}},Hf=new Xv;var Zv="telemetry",IR={id:Zv,name:f(2799,null)};function _R(i,n){return!n.isBuilt&&!n.disableTelemetry?!0:!(n.disableTelemetry||!i.enableTelemetry)}function $f(i,n){return n.extensionTestsLocationURI?!0:!(n.isBuilt||n.disableTelemetry||i.enableTelemetry&&i.aiConfig?.ariaKey)}function TR(i){let n=i.getValue(Vs),e=i.getValue(mp);if(i.getValue(_d)===!1||e===!1)return 0;switch(n??"all"){case"all":return 3;case"error":return 2;case"crash":return 1;case"off":return 0}}function Wf(i){let n={},e={},t={};wR(i,t);for(let r in t){r=r.length>150?r.substr(r.length-149):r;let o=t[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}`),n[r]=o.substring(0,8191)):typeof o<"u"&&o!==null&&(n[r]=String(o))}return{properties:n,measurements:e}}function wR(i,n,e=0,t){if(!i||typeof i!="object"&&typeof i!="function")return;let r=i;for(let o of Object.getOwnPropertyNames(r)){let s=r[o],a=t?t+o:o;Array.isArray(s)?n[a]=ld(s):s instanceof Date?n[a]=s.toISOString():Qe(s)?e<2?wR(s,n,e+1,a+"."):n[a]=ld(s):n[a]=s}}function RR(i,n){let e=i.msftInternalDomains||[],t=n.getValue("telemetry.internalTesting");return bR(e)||t}function xR(i){return[i.appRoot,i.extensionsPath,i.userHome.fsPath,i.tmpDir.fsPath,i.userDataPath]}function pL(i,n){if(!i||!i.includes("/")&&!i.includes("\\"))return i;let e=i,t=[];for(let l of n)for(;;){let d=l.exec(i);if(!d)break;t.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(!t.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 PR=[{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 CR(i,n=i){for(let e of PR)if(e.regex.test(n))return`<REDACTED: ${e.label}>`;return i}function fL(i){if(!i)return i;let n=!1;for(let t of PR)if(t.regex.test(i)){n=!0;break}if(!n)return i;if(!i.includes(`
`))return CR(i);let e=i.split(`
`);for(let t=0;t<e.length;t++){let r=t<e.length-1?e[t]+`
`:e[t];e[t]=CR(e[t],r)}return e.join(`
`)}function AR(i,n){return i?ad(i,e=>{if(e instanceof ac||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let t=e.replaceAll("%20"," ");t=pL(t,n);for(let r of n)t=t.replace(r,"");return t=fL(t),t}}):{}}var ER="https://mobile.events.data.microsoft.com/OneCollector/1.0",gL="https://mobile.events.data.microsoft.com/ping";async function mL(i,n,e){let t=Zt?await Qv("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),r=Zt?await Qv("@microsoft/1ds-post-js","bundle/ms.post.min.js"):await import("@microsoft/1ds-post-js"),o=new t.AppInsightsCore,s=new r.PostChannel,a={instrumentationKey:i,endpointUrl:ER,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}',n&&(l.ext.utc=l.ext.utc??{},l.ext.utc.flags=8462029)}),o}var qf=class{constructor(n,e,t,r,o){this._isInternalTelemetry=n;this._eventPrefix=e;this._defaultData=t;this._xhrOverride=o;this.endPointUrl=ER;this.endPointHealthUrl=gL;this._defaultData||(this._defaultData={}),typeof r=="function"?this._aiCoreOrKey=r():this._aiCoreOrKey=r,this._asyncAiCore=null}_withAIClient(n){if(this._aiCoreOrKey){if(typeof this._aiCoreOrKey!="string"){n(this._aiCoreOrKey);return}this._asyncAiCore||(this._asyncAiCore=mL(this._aiCoreOrKey,this._isInternalTelemetry,this._xhrOverride)),this._asyncAiCore.then(e=>{n(e)},e=>{st(e),console.error(e)})}}log(n,e){if(!this._aiCoreOrKey)return;e=Fs(e,this._defaultData);let t=Wf(e),r=this._eventPrefix+"/"+n;try{this._withAIClient(o=>{o.pluginVersionString=t?.properties.version??"Unknown",o.track({name:r,baseData:{name:r,properties:t?.properties,measurements:t?.measurements}})})}catch{}}flush(){return this._aiCoreOrKey?new Promise(n=>{this._withAIClient(e=>{e.unload(!0,()=>{this._aiCoreOrKey=void 0,n(void 0)})})}):Promise.resolve(void 0)}};async function hL(i,n){let e=await n.request(i,Ae.None),t=(await Oi(e.stream)).toString(),r=e.res.statusCode??200;return{headers:e.res.headers,statusCode:r,responseData:t}}async function yL(i){let n=await import("https"),e={method:i.type,headers:i.headers};return new Promise((r,o)=>{let s=n.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 vL(i,n,e){let t=typeof n.data=="string"?n.data:new TextDecoder().decode(n.data),r={type:"POST",headers:{...n.headers,"Content-Type":"application/json","Content-Length":Buffer.byteLength(n.data).toString()},url:n.urlString,data:t,callSite:vR};try{let o=i?await hL(r,i):await yL(r);e(o.statusCode,o.headers,o.responseData)}catch{e(0,{})}}var Bf=class extends qf{constructor(n,e,t,r,o){let s={sendPOST:(a,l)=>{vL(n,a,l)}};super(e,t,r,o,s)}};var lc=$("environmentService"),Rt=lc;var wa=class extends T{constructor(e,t,r,o,s){super();this.prefix=e;let a=t?"remoteTelemetry":Zv,l=r.getLogger(a);if(l)this.logger=this._register(l);else{let c=$f(s,o)?" (Not Sent)":"";this.logger=this._register(r.createLogger(a,{name:f(2779,null,c),group:IR,hidden:!0}))}}flush(){return Promise.resolve()}log(e,t){this.logger.trace(`${this.prefix}telemetry/${e}`,Wf(t))}};wa=w([C(2,GT),C(3,lc),C(4,Ct)],wa);var Wte={Extensions:{name:{key:"extensionsConfigurationTitle",value:f(138,null)}},IntegratedTerminal:{name:{key:"terminalIntegratedConfigurationTitle",value:f(141,null)}},InteractiveSession:{name:{key:"interactiveSessionConfigurationTitle",value:f(139,null)}},Telemetry:{name:{key:"telemetryConfigurationTitle",value:f(140,null)}},Update:{name:{key:"updateConfigurationTitle",value:f(142,null)}}};var ci=class{constructor(n,e,t){this._configurationService=e;this._productService=t;this._experimentProperties={};this._pendingEvents=[];this._isExperimentPropertySet=!1;this._disposables=new G;this._cleanupPatterns=[];this._appenders=n.appenders,this._commonProperties=n.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=n.piiPaths||[],this._telemetryLevel=3,this._sendErrorTelemetry=!!n.sendErrorTelemetry,this._meteredConnectionService=n.meteredConnectionService,this._cleanupPatterns=[/(vscode-)?file:\/\/.*?\/resources\/app\//gi];for(let r of this._piiPaths)this._cleanupPatterns.push(new RegExp(Cn(r),"gi")),r.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(Cn(r.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(r=>{(r.affectsConfiguration(Vs)||r.affectsConfiguration(_d)||r.affectsConfiguration(mp))&&this._updateTelemetryLevel()})),n.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),ci.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(n,e){this._experimentProperties[n]=new ac(e),this._isExperimentPropertySet||this._flushPendingEvents()}setCommonProperty(n,e){this._commonProperties[n]=e}_flushPendingEvents(){if(!this._isExperimentPropertySet){this._isExperimentPropertySet=!0,this._flushTimeout!==void 0&&(clearTimeout(this._flushTimeout),this._flushTimeout=void 0);for(let n of this._pendingEvents)this._doLog(n.eventName,n.eventLevel,n.data);this._pendingEvents=[]}}_updateTelemetryLevel(){let n=TR(this._configurationService),e=this._productService.enabledTelemetryLevels;if(e){this._sendErrorTelemetry=this.sendErrorTelemetry?e.error:!1;let t=e.usage?3:e.error?2:0;n=Math.min(n,t)}this._telemetryLevel=n}get sendErrorTelemetry(){return this._sendErrorTelemetry}get telemetryLevel(){return this._telemetryLevel}dispose(){this._flushPendingEvents(),this._disposables.dispose()}_log(n,e,t){if(!(this._telemetryLevel<e)&&!this._meteredConnectionService?.isConnectionMetered){if(!this._isExperimentPropertySet){this._pendingEvents.length<ci.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:n,eventLevel:e,data:t});return}this._doLog(n,e,t)}}_doLog(n,e,t){t=Fs(t,this._experimentProperties),t=AR(t,this._cleanupPatterns),t=Fs(t,this._commonProperties),e===2&&(t={...t,isError:!0}),this._appenders.forEach(r=>r.log(n,t??{}))}publicLog(n,e){this._log(n,3,e)}publicLog2(n,e){this.publicLog(n,e)}publicLogError(n,e){this._sendErrorTelemetry&&this._log(n,2,e)}publicLogError2(n,e){this.publicLogError(n,e)}};ci=w([C(1,Hi),C(2,Ct)],ci);function SL(){let i=f(2796,null,gn.nameLong),n=gn.privacyStatementUrl?f(2782,null,"https://aka.ms/vscode-telemetry",gn.privacyStatementUrl):f(2783,null,"https://aka.ms/vscode-telemetry"),e=Zt?"":f(2788,null),t=f(2781,null),r=f(2786,null),o=f(2797,null),s=f(2795,null),a=`
|       | ${t} | ${r} | ${o} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,l=f(2791,null);return`
${i} ${n} ${e}

&nbsp;

${s}
${a}

&nbsp;

${l}
`}var bL=Nt.as(Vn.Configuration);bL.registerConfiguration({id:nT,order:1,type:"object",title:f(2798,null),properties:{[Vs]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[f(2790,null),f(2792,null),f(2789,null),f(2793,null)],markdownDescription:SL(),default:"all",restricted:!0,scope:1,tags:["usesOnlineServices","telemetry"],policy:{name:"TelemetryLevel",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.telemetryLevel.policyDescription",value:f(2794,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:f(2790,null)},{key:"telemetry.telemetryLevel.error",value:f(2792,null)},{key:"telemetry.telemetryLevel.crash",value:f(2789,null)},{key:"telemetry.telemetryLevel.off",value:f(2793,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:f(2787,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:f(2787,null)}}}},[_d]:{type:"boolean",markdownDescription:gn.privacyStatementUrl?f(2785,null,gn.nameLong,gn.privacyStatementUrl):f(2784,null,gn.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:f(2780,null,`\`#${Vs}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var kR="VSCODE_AGENT_HOST_MACHINE_ID",DR="VSCODE_AGENT_HOST_SQM_ID",MR="VSCODE_AGENT_HOST_DEV_DEVICE_ID";var zf=class extends T{constructor(e,t){super();this._delegate=e;this._restricted=t;this._telemetryLevel=3;this._restrictedTelemetryEnabled=!1;bs(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,t){this.telemetryLevel<3||this._delegate.publicLog(e,t)}publicLogError(e,t){this.telemetryLevel<2||this._delegate.publicLogError(e,t)}publicLog2(e,t){this.telemetryLevel<3||this._delegate.publicLog2(e,t)}publicLogError2(e,t){this.telemetryLevel<2||this._delegate.publicLogError2(e,t)}sendGHTelemetryEvent(e,t,r){this.telemetryLevel<3||this._restricted?.sendGHTelemetryEvent(e,t,r)}sendEnhancedGHTelemetryEvent(e,t,r){this.telemetryLevel<3||!this._restrictedTelemetryEnabled||this._restricted?.sendEnhancedGHTelemetryEvent(e,t,r)}sendInternalMSFTTelemetryEvent(e,t,r){this.telemetryLevel<3||this._restricted?.sendInternalMSFTTelemetryEvent(e,t,r)}setCopilotTrackingId(e){this._restricted?.setCopilotTrackingId(e)}setRestrictedTelemetryEndpoint(e){this._restricted?.setRestrictedTelemetryEndpoint(e)}setRestrictedTelemetryEnabled(e){this._restrictedTelemetryEnabled=e,this._restricted?.setRestrictedTelemetryEnabled(e)}setExperimentProperty(e,t){this._delegate.setExperimentProperty(e,t)}setCommonProperty(e,t){this._delegate.setCommonProperty(e,t)}updateTelemetryLevel(e){this._telemetryLevel=Math.min(this._telemetryLevel,e)}};function Vf(i,n){let e=n?.[Td],t=fT(e);!eS(i)||t===void 0||i.updateTelemetryLevel(t)}function eS(i){return typeof i.updateTelemetryLevel=="function"}async function OR(i){let{environmentService:n,productService:e,fileService:t,loggerService:r,logService:o,disposables:s}=i;if(i.disableTelemetry||!r||!_R(e,n))return s.add(new zf(Hf));let a=s.add(new Ia(te(n.appSettingsHome,"settings.json"),t,new Ji,o));await a.initialize();let l=[s.add(new wa("",!1,r,n,e))],d=RR(e,a);if(!$f(e,n)&&e.aiConfig?.ariaKey){let S=new Bf(void 0,d,"monacoworkbench",null,e.aiConfig.ariaKey);s.add(M(()=>{S.flush()})),l.push(S)}let[c,u,p]=await Promise.all([process.env[kR]||Sf(S=>o.error(S)),process.env[DR]||rR(S=>o.error(S)),process.env[MR]||bf(S=>o.error(S))]),m=SR(IL(),CL(),process.arch,e.commit,e.version,c,u,p,d,e.date),h=new ci({appenders:l,sendErrorTelemetry:!0,commonProperties:m,piiPaths:xR(n)},a,e),y=new yf(m,o);return s.add(new zf(h,y))}var jf=class{constructor(n){this._reporter=n;this._turnTimings=new Map}turnStarted(n,e,t,r,o){let s=this._key(e,t);this._turnTimings.set(s,{stopWatch:Dn.create(!1),provider:n,session:e,model:r,permissionLevel:o,firstProgressMs:void 0})}markFirstProgress(n,e){let t=this._turnTimings.get(this._key(n,e));t&&t.firstProgressMs===void 0&&(t.firstProgressMs=t.stopWatch.elapsed())}turnCompleted(n,e,t){let r=this._key(n,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:t,model:o.model,permissionLevel:o.permissionLevel}))}_key(n,e){return`${n}\0${e}`}};function Kf(i,n,e,t,r){let o=i.openDatabase(v.parse(e));o.object.setMetadata(t,r).catch(s=>{n.warn(`[AgentHost] Failed to persist session metadata '${t}'`,s)}).finally(()=>{o.dispose()})}var tS=class{constructor(){this._ctors=[]}register(n){this._ctors.push(n)}createAll(n){return this._ctors.map(e=>new e(n))}},dc=new tS,Ra=class extends T{constructor(e,t,r,o,s,a){super();this._stateManager=e;this._localTurns=t;this._notifyTurnConsumable=r;this._logService=o;this._terminalManager=s;this._sessionDataService=a;let l={logService:this._logService,terminalManager:this._terminalManager,dispatch:(d,c)=>this._stateManager.dispatchServerAction(d,c),getState:d=>this._stateManager.getSessionState(d),updateChatTitle:(d,c,u)=>this._stateManager.updateChatTitle(d,c,u),persistSessionFlag:(d,c,u)=>Kf(this._sessionDataService,this._logService,d,c,u)};this._commands=dc.createAll(l).map(d=>this._register(d))}tryHandle(e){for(let t of this._commands){let r=t.tryHandle(e);if(r)return this._run(t,r,e),!0}return!1}async _run(e,t,r){try{await t()}catch(o){this._logService.error(`[AgentHostLocalCommands] Command '${e.name}' failed: ${o instanceof Error?o.message:String(o)}`,o)}finally{this._stateManager.dispatchServerAction(r.turnChannel,{type:"chat/turnComplete",turnId:r.turnId}),e.recordsLocalTurn&&this._recordLocalTurn(r.turnChannel,r.turnId),this._notifyTurnConsumable(r.turnChannel)}}_recordLocalTurn(e,t){let r=e,o=ce(e)?fe(e):e,s=this._stateManager.getSessionState(e)?.turns;if(!s)return;let a=s.findIndex(d=>d.id===t);if(a<0)return;let l;for(let d=a-1;d>=0;d--)if(!this._localTurns.isLocal(r,s[d].id)){l=s[d].id;break}this._localTurns.record(o,r,_L(s[a]),l)}};Ra=w([C(3,D),C(4,Ir),C(5,Je)],Ra);function _L(i){let n=i.responseParts.map(e=>{if(e.kind!=="toolCall")return e;let t=e.toolCall;if(t.status!=="running"&&t.status!=="completed"&&t.status!=="pending-result-confirmation"||!t.content)return e;let r=t.content.filter(o=>o.type!=="terminal");return r.length===t.content.length?e:{...e,toolCall:{...t,content:r}}});return{...i,responseParts:n}}function Gf(i){let n={command:i.command};return i.description!==void 0&&(n.description=i.description),n}function LR(i){let n={uri:i.uri};return i.name!==void 0&&(n.name=i.name),i.displayName!==void 0&&(n.displayName=i.displayName),i.description!==void 0&&(n.description=i.description),n}var Jf=$("agentHostCompletions");var xa=class extends T{constructor(e){super();this._logService=e;this._providers=new Set}get triggerCharacters(){let e=new Set;for(let t of this._providers)if(t.triggerCharacters)for(let r of t.triggerCharacters)e.add(r);return[...e]}registerProvider(e){return this._providers.add(e),M(()=>this._providers.delete(e))}async completions(e,t=Ae.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,t))),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}}};xa=w([C(0,D)],xa);function Yf(i,n){if(i.length===0||i.charCodeAt(0)!==47)return;let e=1;for(;e<i.length&&!nS(i.charCodeAt(e));)e++;if(n<0||n>e)return;let t=i.slice(0,e);return{token:t,typed:t.slice(1),rangeStart:0,rangeEnd:e}}function Qf(i,n){if(i.length===0||n<0||n>i.length)return;let e=n;for(;e>0&&!nS(i.charCodeAt(e-1));)e--;if(e>=i.length||i.charCodeAt(e)!==47)return;let t=e+1;for(;t<i.length&&!nS(i.charCodeAt(t));)t++;if(n>t)return;let r=i.slice(e,t);return{token:r,typed:r.slice(1),rangeStart:e,rangeEnd:t}}function nS(i){return i===32||i===9||i===10||i===13}var Xf="rename";function NR(i){let n=/^\/rename(?:$|\s+([\s\S]*))/.exec(i);if(n)return(n[1]??"").trim()}var Zf=class{constructor(n){this._hasHistory=n;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){let t=Yf(n.text,n.offset);if(!t)return[];if(!this._hasHistory(n.channel))return[];let r=t.typed;return r.length>0&&!Xf.startsWith(r)?[]:[{insertText:"/"+Xf+" ",rangeStart:t.rangeStart,rangeEnd:t.rangeEnd,attachment:{type:"simple",label:"/"+Xf,_meta:Gf({command:Xf,description:f(2019,null)})}}]}};var oS=class extends T{constructor(e){super();this._context=e;this.name="rename";this.recordsLocalTurn=!0}tryHandle(e){let t=NR(e.text);if(t!==void 0)return async()=>this._run(e.turnChannel,e.turnId,t)}_run(e,t,r){if(r.length===0)return;let s=(l=>ce(l)&&!Ue(l))(e)?e:void 0,a=ce(e)?fe(e):e;s?(this._context.updateChatTitle(a,s,r),this._context.persistSessionFlag(a,`customChatTitle:${s}`,r)):(this._context.dispatch(a,{type:"session/titleChanged",title:r}),this._context.persistSessionFlag(a,"customTitle",r)),this._context.dispatch(e,{type:"chat/responsePart",turnId:t,part:{kind:"markdown",id:H(),content:f(2348,null,r)}})}};dc.register(oS);function UR(i){if(!i.startsWith("!"))return;let n=i.slice(1).trim();return n.length>0?n:void 0}var FR=8e4,eg=12e4,sS="<<<COPILOT_SENTINEL_";function tg(i){let n=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\"));switch(i.slice(n+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 Q?"powershell":"bash"}}function aS(i){return i==="powershell"?"":" "}function HR(i){let n=i.replace(/\r\n|\r/g,`
`);return/(?<!\\)\n/.test(n)}function $R(i){return dt||HR(i)}function TL(){return H().replace(/-/g,"")}function wL(i,n){return n==="powershell"?`Write-Output "${sS}${i}_EXIT_$LASTEXITCODE>>>"`:`echo "${sS}${i}_EXIT_$?>>>"`}function RL(i,n){let e=`${sS}${n}_EXIT_`,t=i.lastIndexOf(e);for(;t!==-1;){let r=i.substring(0,t),o=i.substring(t+e.length),s=o.indexOf(">>>");if(s!==-1){let a=o.substring(0,s).trim();if(/^-?\d+$/.test(a))return{found:!0,exitCode:parseInt(a,10),outputBeforeSentinel:r}}t=i.lastIndexOf(e,t-1)}return{found:!1,exitCode:-1,outputBeforeSentinel:i}}function Yi(i){let n=PI(i).trim();return n.length>FR&&(n=n.substring(n.length-FR)),n}function ng(i,n,e,t,r){return t.supportsCommandDetection(i.terminalUri)?xL(i,n,e,t,r):PL(i,n,e,t,r)}function WR(i,n,e,t,r){n.createAltBufferPromise(i.terminalUri,t).then(()=>{e.info("[ShellCommand] Command entered alternate buffer"),r({status:"altBuffer",output:""})})}async function xL(i,n,e,t,r){let o=new G,s=new Promise(a=>{let l=!1,d=u=>{l||(l=!0,o.dispose(),a(u))};o.add(t.onCommandFinished(i.terminalUri,u=>{let p=Yi(u.output),m=u.exitCode??0;r.info(`[ShellCommand] Command completed (shell integration) with exit code ${m}`),d({status:"completed",exitCode:m,output:p})})),WR(i,t,r,o,d),o.add(t.onExit(i.terminalUri,u=>{r.info(`[ShellCommand] Shell exited unexpectedly with code ${u}`);let p=t.getContent(i.terminalUri)??"";d({status:"shellExited",exitCode:u,output:Yi(p)})})),o.add(t.onClaimChanged(i.terminalUri,u=>{u.kind==="session"&&!u.toolCallId&&(r.info("[ShellCommand] Continuing in background (claim narrowed)"),d({status:"background",output:""}))}));let c=setTimeout(()=>{r.warn(`[ShellCommand] Command timed out after ${e}ms`);let u=t.getContent(i.terminalUri)??"";d({status:"timeout",output:Yi(u)})},e);o.add(M(()=>clearTimeout(c)))});try{await t.sendText(i.terminalUri,`${aS(i.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:$R(n)})}catch(a){throw o.dispose(),a}return s}async function PL(i,n,e,t,r){let o=TL(),s=wL(o,i.shellType),a=new G,d=(t.getContent(i.terminalUri)??"").length,c=new Promise(u=>{let p=!1,m=S=>{p||(p=!0,a.dispose(),u(S))},h=()=>{let S=t.getContent(i.terminalUri)??"",b=Math.min(d,S.length),I=S.substring(b),_=RL(I,o);if(_.found){let R=Yi(_.outputBeforeSentinel);r.info(`[ShellCommand] Command completed with exit code ${_.exitCode}`),m({status:"completed",exitCode:_.exitCode,output:R})}};a.add(t.onData(i.terminalUri,()=>{h()})),WR(i,t,r,a,m),a.add(t.onExit(i.terminalUri,S=>{r.info(`[ShellCommand] Shell exited unexpectedly with code ${S}`);let I=(t.getContent(i.terminalUri)??"").substring(d);m({status:"shellExited",exitCode:S,output:Yi(I)})})),a.add(t.onClaimChanged(i.terminalUri,S=>{S.kind==="session"&&!S.toolCallId&&(r.info("[ShellCommand] Continuing in background (claim narrowed)"),m({status:"background",output:""}))}));let y=setTimeout(()=>{r.warn(`[ShellCommand] Command timed out after ${e}ms`);let b=(t.getContent(i.terminalUri)??"").substring(d);m({status:"timeout",output:Yi(b)})},e);a.add(M(()=>clearTimeout(y))),h()});try{await t.sendText(i.terminalUri,`${aS(i.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:$R(n)}),await t.sendText(i.terminalUri,s,{shouldExecute:!0})}catch(u){throw a.dispose(),u}return c}var lS=class extends T{constructor(e){super();this._context=e;this.name="bang";this.recordsLocalTurn=!0;this._terminals=new Set;this._register(M(()=>{for(let t of this._terminals)this._context.terminalManager.disposeTerminal(t);this._terminals.clear()}))}tryHandle(e){let t=UR(e.text);if(t!==void 0)return()=>this._run(e.turnChannel,e.turnId,t)}async _run(e,t,r){let o=this._context,s=ce(e)?fe(e):e,a=H(),l=`agenthost-terminal://bang/${H()}`,d=f(2346,null),c=!1;try{let u=o.getState(s)?.workingDirectory,p=u?v.parse(u).fsPath:void 0,m=await o.terminalManager.getDefaultShell(),h=tg(m);o.dispatch(e,{type:"chat/toolCallStart",turnId:t,toolCallId:a,toolName:"terminal",displayName:d,intention:r}),o.dispatch(e,{type:"chat/toolCallReady",turnId:t,toolCallId:a,invocationMessage:r,toolInput:r,confirmed:"not-needed"});let y={kind:"session",session:s,turnId:t,toolCallId:a},S={channel:l,claim:y,name:d,cwd:p};await o.terminalManager.createTerminal(S,{shell:m,preventShellHistory:!0,nonInteractive:!0}),c=!0,this._terminals.add(l);let b={type:"terminal",resource:l,title:d};o.dispatch(e,{type:"chat/toolCallContentChanged",turnId:t,toolCallId:a,content:[b]});let I=await ng({terminalUri:l,shellType:h},r,eg,o.terminalManager,o.logService),{success:_,pastTenseMessage:R}=this._summarizeResult(I),A=[b];I.output&&A.push({type:"text",text:I.output}),o.dispatch(e,{type:"chat/toolCallComplete",turnId:t,toolCallId:a,result:{success:_,pastTenseMessage:R,content:A}})}catch(u){o.logService.error(`[BangLocalCommand] Command failed for session=${s}: ${u instanceof Error?u.message:String(u)}`,u),c&&(o.terminalManager.disposeTerminal(l),this._terminals.delete(l)),o.dispatch(e,{type:"chat/toolCallComplete",turnId:t,toolCallId:a,result:{success:!1,pastTenseMessage:f(2342,null),error:{message:u instanceof Error?u.message:String(u)}}})}}_summarizeResult(e){switch(e.status){case"completed":{let t=e.exitCode??0;return t===0?{success:!0,pastTenseMessage:f(2344,null)}:{success:!1,pastTenseMessage:f(2341,null,t)}}case"timeout":return{success:!1,pastTenseMessage:f(2347,null)};case"shellExited":return{success:!1,pastTenseMessage:f(2345,null)};case"background":return{success:!0,pastTenseMessage:f(2340,null)};case"altBuffer":return{success:!0,pastTenseMessage:f(2343,null)}}}};dc.register(lS);import{homedir as ag}from"os";var Pa="**",qR="/",rg="[/\\\\]",ig="[^/\\\\]",AL=/\//g;function BR(i,n){switch(i){case 0:return"";case 1:return`${ig}*?`;default:return`(?:${rg}|${ig}+${rg}${n?`|${rg}${ig}+`:""})*?`}}function zR(i,n){if(!i)return[];let e=[],t=!1,r=!1,o="";for(let s of i){switch(s){case n:if(!t&&!r){e.push(o),o="";continue}break;case"{":t=!0;break;case"}":t=!1;break;case"[":r=!0;break;case"]":r=!1;break}o+=s}return o&&e.push(o),e}function JR(i){if(!i)return"";let n="",e=zR(i,qR);if(e.every(t=>t===Pa))n=".*";else{let t=!1;e.forEach((r,o)=>{if(r===Pa){if(t)return;n+=BR(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===qR?u="":u=Cn(c),d+=u;continue}switch(c){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let p=`(?:${zR(a,",").map(m=>JR(m)).join("|")})`;n+=p,s=!1,a="";break}case"]":{n+="["+d+"]",l=!1,d="";break}case"?":n+=ig;continue;case"*":n+=BR(1);continue;default:n+=Cn(c)}}o<e.length-1&&(e[o+1]!==Pa||o+2<e.length)&&(n+=rg)}t=r===Pa})}return n}var EL=/^\*\*\/\*\.[\w\.-]+$/,kL=/^\*\*\/([\w\.-]+)\/?$/,DL=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,ML=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,OL=/^\*\*((\/[\w\.-]+)+)\/?$/,LL=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,VR=new sn(1e4),jR=function(){return!1},wr=function(){return null};function cS(i,n){if(!i)return wr;let e;typeof i!="string"?e=i.pattern:e=i,e=e.trim();let t=n.ignoreCase??!1,r={...n,equals:t?zr:(l,d)=>l===d,endsWith:t?wI:(l,d)=>l.endsWith(d),isEqualOrParent:(l,d)=>Vr(l,d,n.ignoreCase??!Oe)},o=`${t?e.toLowerCase():e}_${!!n.trimForExclusions}_${t}`,s=VR.get(o);if(s)return KR(s,i,r);let a;return EL.test(e)?s=NL(e.substring(4),e,r):(a=kL.exec(dS(e,r)))?s=UL(a[1],e,r):(n.trimForExclusions?ML:DL).test(e)?s=FL(e,r):(a=OL.exec(dS(e,r)))?s=GR(a[1].substring(1),e,!0,r):(a=LL.exec(dS(e,r)))?s=GR(a[1],e,!1,r):s=HL(e,r),VR.set(o,s),KR(s,i,r)}function KR(i,n,e){if(typeof n=="string")return i;let t=function(r,o){return e.isEqualOrParent(r,n.base)?i(Qh(r.substring(n.base.length),Le),o):null};return t.allBasenames=i.allBasenames,t.allPaths=i.allPaths,t.basenames=i.basenames,t.patterns=i.patterns,t}function dS(i,n){return n.trimForExclusions&&i.endsWith("/**")?i.substring(0,i.length-2):i}function NL(i,n,e){return function(t,r){return typeof t=="string"&&e.endsWith(t,i)?n:null}}function UL(i,n,e){let t=`/${i}`,r=`\\${i}`,o=function(a,l){return typeof a!="string"?null:l?e.equals(l,i)?n:null:e.equals(a,i)||e.endsWith(a,t)||e.endsWith(a,r)?n:null},s=[i];return o.basenames=s,o.patterns=[n],o.allBasenames=s,o}function FL(i,n){let e=YR(i.slice(1,-1).split(",").map(a=>cS(a,n)).filter(a=>a!==wr),i),t=e.length;if(!t)return wr;if(t===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 GR(i,n,e,t){let r=Le===re.sep,o=r?i:i.replace(AL,Le),s=Le+o,a=re.sep+i,l;return e?l=function(d,c){return typeof d=="string"&&(t.equals(d,o)||t.endsWith(d,s)||!r&&(t.equals(d,i)||t.endsWith(d,a)))?n:null}:l=function(d,c){return typeof d=="string"&&(t.equals(d,o)||!r&&t.equals(d,i))?n:null},l.allPaths=[(e?"*/":"./")+i],l}function HL(i,n){try{let e=new RegExp(`^${JR(i)}$`,n.ignoreCase?"i":void 0);return function(t){return e.lastIndex=0,typeof t=="string"&&e.test(t)?i:null}}catch{return wr}}function og(i,n,e){return!i||typeof n!="string"?!1:Qi(i,e)(n)}function Qi(i,n={}){if(!i)return jR;if(typeof i=="string"||$L(i)){let e=cS(i,n);if(e===wr)return jR;let t=function(r,o){return!!e(r,o)};return e.allBasenames&&(t.allBasenames=e.allBasenames),e.allPaths&&(t.allPaths=e.allPaths),t}return WL(i,n)}function $L(i){let n=i;return n?typeof n.base=="string"&&typeof n.pattern=="string":!1}function WL(i,n){let e=YR(Object.getOwnPropertyNames(i).map(a=>qL(a,i[a],n)).filter(a=>a!==wr)),t=e.length;if(!t)return wr;if(!e.some(a=>!!a.requiresSiblings)){if(t===1)return e[0];let a=function(c,u){let p;for(let m=0,h=e.length;m<h;m++){let y=e[m](c,u);if(typeof y=="string")return y;Bu(y)&&(p||(p=[]),p.push(y))}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=Te(a)),c||(c=l.substring(0,l.length-To(a).length)));let y=h(a,l,c,d);if(typeof y=="string")return y;Bu(y)&&(u||(u=[]),u.push(y))}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 qL(i,n,e){if(n===!1)return wr;let t=cS(i,e);if(t===wr)return wr;if(typeof n=="boolean")return t;if(n){let r=n.when;if(typeof r=="string"){let o=(s,a,l,d)=>{if(!d||!t(s,a))return null;let c=r.replace("$(basename)",()=>l),u=d(c);return Bu(u)?u.then(p=>p?i:null):u?i:null};return o.requiresSiblings=!0,o}}return t}function YR(i,n){let e=i.filter(a=>!!a.basenames);if(e.length<2)return i;let t=e.reduce((a,l)=>{let d=l.basenames;return d?a.concat(d):a},[]),r;if(n){r=[];for(let a=0,l=t.length;a<l;a++)r.push(n)}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=t.indexOf(l);return d!==-1?r[d]:null};o.basenames=t,o.patterns=r,o.allBasenames=t;let s=i.filter(a=>!a.basenames);return s.push(o),s}function uS(i,n){return bn(i,n,(e,t)=>typeof e=="string"&&typeof t=="string"?e===t:typeof e!="string"&&typeof t!="string"?e.base===t.base&&e.pattern===t.pattern:!1)}function QR(i,n){return i.replace(/^~($|\/|\\)/,`${n}$1`)}import*as XR from"fs";var BL=new Set(["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"]);function zL(i){let n=i.trim();return n.length===0?!1:((n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1)),/^&[0-9]+-?$/.test(n)?!0:BL.has(n))}function VL(i){if(!i.includes(">"))return{kind:"read"};let n=i.match(/(?:[0-9]+|&)?>>?\|?\s*(.+)$/);if(!n)return{kind:"unsafeWrite",dest:void 0};let e=n[1].trim();if(zL(e))return{kind:"safeWrite"};let t=e;return(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),{kind:"unsafeWrite",dest:t}}var pS=/(?!.*)/,jL=/^[A-Z_][A-Z0-9_]*=/i,sg=class extends T{constructor(e){super();this._logService=e;this._initPromise=this._initTreeSitter()}initialize(){return this._initPromise}shouldAutoApprove(e,t){let r=e.trimStart();if(r.length===0)return"approved";let o=this._compileRules(t?.autoApproveRules),s=this._extractSubCommands(r);if(!s)return this._logService.trace("[CommandAutoApprover] Tree-sitter unavailable, requiring confirmation"),"noMatch";if(this._matchesRule(r,o.denyCommandLineRules))return"denied";let a=this._matchSubCommands(s.subCommands,o);if(a!=="denied"&&this._matchesRule(r,o.allowCommandLineRules)&&(a="approved"),a==="approved"&&s.unsafeWriteDests.length>0){for(let l of s.unsafeWriteDests)if(l===void 0||!t?.isWriteDestApproved?.(l))return this._logService.trace("[CommandAutoApprover] Write redirection to non-approved destination, requiring confirmation"),"noMatch"}return a}_matchSubCommands(e,t){let r=!0;for(let o of e){if(jL.test(o))return"denied";let s=this._matchSingleCommand(o,t);if(s==="denied")return"denied";s!=="approved"&&(r=!1)}return r?"approved":"noMatch"}_matchSingleCommand(e,t){return this._matchesRule(e,t.denyRules)?"denied":this._matchesRule(e,t.allowRules)?"approved":"noMatch"}_matchesRule(e,t){for(let r of t)if(r.regex.test(e))return!0;return!1}_extractSubCommands(e){if(!(!this._parser||!this._bashLanguage||!this._queryClass))try{this._parser.setLanguage(this._bashLanguage);let t=this._parser.parse(e);if(!t)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(t.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=VL(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{t.delete()}}catch(t){this._logService.warn("[CommandAutoApprover] Tree-sitter parsing failed",t);return}}async _initTreeSitter(){try{let{default:e}=await import("@vscode/tree-sitter-wasm");if(this._store.isDisposed)return;let t=v.joinPath(Dt.asFileUri(""),"..","node_modules","@vscode","tree-sitter-wasm","wasm"),r=v.joinPath(t,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return r}}),this._store.isDisposed)return;let o=new e.Parser;this._register(M(()=>{try{o.delete()}catch{}}));let s=v.joinPath(t,"tree-sitter-bash.wasm").fsPath,a=await XR.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)}}_compileRules(e){return e?this._cachedRuleConfig===e&&this._cachedRules?this._cachedRules:(this._cachedRuleConfig=e,this._cachedRules=this._compileRuleEntries(e),this._cachedRules):(this._fallbackRules||(this._fallbackRules=this._compileRuleEntries(GL)),this._fallbackRules)}_compileRuleEntries(e){let t=[],r=[],o=[],s=[];for(let[a,l]of Object.entries(e)){let d=KL(a);l===!0?t.push({regex:d}):l===!1?r.push({regex:d}):l&&typeof l=="object"&&typeof l.approve=="boolean"&&(l.approve?l.matchCommandLine===!0?o.push({regex:d}):t.push({regex:d}):l.matchCommandLine===!0?s.push({regex:d}):r.push({regex:d}))}return{allowRules:t,denyRules:r,allowCommandLineRules:o,denyCommandLineRules:s}}};function KL(i){let n=i.match(/^\/(?<pattern>.+)\/(?<flags>[dgimsuvy]*)$/),e=n?.groups?.pattern;if(e){let r=n.groups?.flags;if(r&&(r=r.replaceAll("g","")),e===".*")return new RegExp(e);try{let o=new RegExp(e,r||void 0);return _I(o)?pS:o}catch{return pS}}if(i==="")return pS;let t;if(i.includes("/")||i.includes("\\")){let r=i.replace(/[/\\]/g,"%%PATH_SEP%%");r=Cn(r),r=r.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),t=`^(?:\\.[/\\\\])?${r}`}else t=Cn(i);return new RegExp(`^${t}\\b`)}var GL={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 ZR="allow-session",YL=[{id:ZR,label:f(2350,null),kind:"approve",group:1},{id:"allow-once",label:f(2349,null),kind:"approve"},{id:"skip",label:f(2351,null),kind:"deny",group:2}],QL={"**/*":!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},XL=[Qi(ag()+"/.*"),Qi(ag()+"/.*/**")],ZL=(Q?[process.env.APPDATA,process.env.LOCALAPPDATA]:dt?[ag()+"/Library"]:[]).filter(Gn);function e2(i,n=Q){if(i.includes("\0"))throw new Error(`Path contains null bytes: ${i}`);if(!n)return;if(i.indexOf(":",2)!==-1)throw new Error(`Path contains invalid characters (alternate data stream): ${i}`);let t=/[<>"|?*]/,r=i.length>2?i.substring(2):i;if(t.test(r))throw new Error(`Path contains invalid characters: ${i}`);if(i.startsWith("\\\\.")||i.startsWith("\\\\?"))throw new Error(`Path is a reserved device path: ${i}`);let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,s=i.split("\\");for(let a of s){if(a.length===0)continue;if(o.test(a))throw new Error(`Reserved device name in path: ${i}`);if(a.endsWith(".")||a.endsWith(" "))throw new Error(`Path contains invalid trailing characters: ${i}`);let l=a.indexOf("~");if(l!==-1){let d=a.substring(l+1);if(d.length>0&&/^\d/.test(d))throw new Error(`Path appears to use short filename format (8.3 names): ${i}. Please use the full path.`)}}}async function t2(i){try{return await Ne.realpath(i)}catch(t){if(t.code!=="ENOENT")throw t}let n=[Te(i)],e=le(i);for(;;){let t=le(e);if(t===e)return i;try{let r=await Ne.realpath(e);return j(r,...n)}catch(r){let o=r.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw r}n.unshift(Te(e)),e=t}}var Aa=class extends T{constructor(e,t,r){super();this._stateManager=e;this._configService=t;this._logService=r;this._commandAutoApprover=this._register(new sg(this._logService))}initialize(){return this._commandAutoApprover.initialize()}async getAutoApproval(e,t){let r=this._configService.getEffectiveWorkingDirectory(t);if(!e.requestSandboxBypass){if(this.isGlobalAutoApproveEnabled())return"setting";if(this.isSessionAutoApproveEnabled(t))return"setting";if(this._isToolAllowedByPermissions(t,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 await this._isEditAutoApproved(e.permissionPath,r)?(this._logService.trace(`[SessionPermissionManager] Auto-approving write to ${e.permissionPath}`),"not-needed"):void 0;if(e.permissionKind==="shell"&&e.toolInput){if(this._configService.getRootValue($t,Dy)===!1)return;let o=this._commandAutoApprover.shouldAutoApprove(e.toolInput,{autoApproveRules:this._configService.getRootValue($t,Oy),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}}}isGlobalAutoApproveEnabled(){return this._configService.getRootValue($t,Rd)===!0}isSessionAutoApproveEnabled(e){return this._configService.getEffectiveValue(e,Jt,"autoApprove")==="autoApprove"}createToolReadyAction(e,t,r){let o=e.state;return o.confirmationTitle?{type:"chat/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():YL.slice()}:{type:"chat/toolCallReady",turnId:r,toolCallId:o.toolCallId,invocationMessage:o.invocationMessage,toolInput:o.toolInput,confirmed:"not-needed",...o._meta?{_meta:o._meta}:{}}}handleToolCallConfirmed(e,t,r){if(!ce(e))throw new Error(`Tool call confirmations must be handled on an AHP chat channel: ${e}`);let o=fe(e);if(r===ZR){let s=this._getToolNameForToolCall(e,t);s&&this._addToolToSessionPermissions(o,s)}}_isPathInWorkingDirectory(e,t){if(!t)return!1;let r=v.parse(t);return rt.isEqualOrParent(_n(v.file(e)),r)}_isShellWriteDestApproved(e,t){let r=this._resolveShellRedirectPath(e,t);return r?this._checkWritePath(r,t):!1}_resolveShellRedirectPath(e,t){let r=QR(e.trim(),ag());if(r){if(Ft(r))return r;if(t)return Mn(v.parse(t).fsPath,r)}}async _isEditAutoApproved(e,t){let r=await this._resolveWritePaths(e);return r!==void 0&&r.every(o=>this._checkWritePath(o,t))}async _resolveWritePaths(e){let t=[e];if(Ft(e))try{let r=await t2(e);r!==e&&t.push(r)}catch(r){let o=r.code;if(o==="EPERM"||o==="EACCES")return}return t}_checkWritePath(e,t){try{e2(e)}catch{return!1}return!this._isPathInWorkingDirectory(e,t)||this._isPlatformRestrictedPath(e,t)?!1:this._matchesEditAutoApprovePatterns(e)}_isPlatformRestrictedPath(e,t){if(XL.some(s=>s(e)))return!0;let r=v.file(e),o=t?v.parse(t):void 0;for(let s of ZL){let a=v.file(s);if(rt.isEqualOrParent(r,a))return!(o&&rt.isEqualOrParent(o,a))}return!1}_matchesEditAutoApprovePatterns(e){let t=!0;for(let[r,o]of Object.entries(QL))o!==t&&og(r,e)&&(t=o);return t}_isToolAllowedByPermissions(e,t){let r=this._getToolNameForToolCall(e,t);if(!r)return!1;let s=this._configService.getEffectiveValue(e,Jt,"permissions")?.allow.includes(r)??!1;return s&&this._logService.trace(`[SessionPermissionManager] Auto-approving "${r}" via permissions`),s}_getToolNameForToolCall(e,t){let o=this._stateManager.getSessionState(e)?.activeTurn?.responseParts;if(o){for(let s of o)if(s.kind==="toolCall"&&s.toolCall.toolCallId===t)return s.toolCall.toolName}}_addToolToSessionPermissions(e,t){let r=this._configService.getEffectiveValue(e,Jt,"permissions")??{allow:[],deny:[]};r.allow.includes(t)||(this._configService.updateSessionConfig(e,{permissions:{allow:[...r.allow,t],deny:[...r.deny]}}),this._logService.info(`[SessionPermissionManager] Added "${t}" to session permissions for ${e}`))}};Aa=w([C(1,ze),C(2,D)],Aa);import{CAPIClient as r2,RequestType as cc}from"@vscode/copilot-api";var fS="code-oss";function ex(i){let n=new Map;if(!i)return n;let e=i.indexOf(":"),t=e===-1?i:i.substring(0,e);for(let r of t.split(";")){let o=r.indexOf("=");o<=0||n.set(r.substring(0,o),r.substring(o+1))}return n}var uc=520,i2=300,tx=1800,nx="2025-04-01",o2="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE";function s2(i){let n;try{n=new URL(i).hostname}catch{return!1}let e=n.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}var a2=300,l2="gpt-4o-mini",d2=.1,c2=1,u2="conversation-background",ir=class extends Error{constructor(e,t,r){super(r??t.error.message);this.status=e;this.envelope=t;this.name="CopilotApiError"}};function lg(i,n,e,t="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} ${n}`},request_id:null}),new ir(i,r,`${t}: ${i} ${n} \u2014 ${r.error.message}`)}var It=$("copilotApiService"),Xi=class{constructor(n,e,t){this._logService=e;this._productService=t;this._capiBasePromise=null;this._clientsByToken=new Map;this._copilotTokensByGithub=new Map;this._fetch=n??globalThis.fetch}messages(n,e,t){return e.stream?this._messagesStreaming(n,e,t):this._messagesNonStreaming(n,e,t)}async countTokens(n,e,t){throw new Error("countTokens not supported by CAPI")}async models(n,e){let t=await this._getClientForToken(n);this._logService.debug("[CopilotApiService] GET models");let r=await t.makeRequest({method:"GET",headers:{...e?.headers,Authorization:`Bearer ${n}`},suppressIntegrationId:e?.suppressIntegrationId,signal:e?.signal},{type:cc.Models});if(!r.ok){(r.status===401||r.status===403)&&this._invalidateClientForToken(n);let s=await r.text().catch(()=>"");throw lg(r.status,r.statusText,s,"CAPI models request failed")}return(await r.json()).data??[]}async responses(n,e,t){let r=await this._getClientForToken(n),o=H(),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:{...t?.headers,"Content-Type":"application/json",Authorization:`Bearer ${n}`,"X-Request-Id":o,"OpenAI-Intent":"conversation"},suppressIntegrationId:t?.suppressIntegrationId,body:e,signal:t?.signal},{type:cc.ChatResponses});if(this._logService.info(`[CopilotApiService] responses status=${a.status}, requestId=${o}`),!a.ok){(a.status===401||a.status===403)&&this._invalidateClientForToken(n);let l=await a.text().catch(()=>"");throw lg(a.status,a.statusText,l,"CAPI responses request failed")}return a}async utilityChatCompletion(n,e,t){let r=await this._getClientForToken(n),o=await this._getCopilotToken(n),s=await this._resolveUtilityModelId(n,l2),a=H();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??d2,top_p:c2}),d=await r.makeRequest({method:"POST",headers:{...t?.headers,"Content-Type":"application/json",Authorization:`Bearer ${o}`,"X-Request-Id":a,"OpenAI-Intent":u2},body:l,signal:t?.signal},{type:cc.ChatCompletions});if(!d.ok){(d.status===401||d.status===403)&&this._invalidateCopilotTokenForGithub(n);let p=await d.text().catch(()=>"");throw lg(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(n=>{throw this._capiBasePromise=null,n})),this._capiBasePromise}async _buildCapiBase(){let[n,e]=await Promise.all([Sf(o=>this._logService.warn("[CopilotApiService] getMachineId failed",o)),bf(o=>this._logService.warn("[CopilotApiService] getDevDeviceId failed",o))]);return{extensionInfo:{name:"agent-host",sessionId:H(),machineId:n,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(n,e,t){let r=await this._sendRequest(n,e,!0,t);if(!r.body)throw new Error("CAPI response has no body");yield*this._readSSE(r.body)}async _messagesNonStreaming(n,e,t){return(await this._sendRequest(n,e,!1,t)).json()}async _sendRequest(n,e,t,r){let o=await this._getClientForToken(n),s=H();this._logService.debug("[CopilotApiService] POST messages",`model=${e.model} stream=${t} requestId=${s}`);let{system:a,...l}=e,d=JSON.stringify({...l,stream:t,...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 ${n}`,"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:cc.ChatMessages});if(!c.ok){(c.status===401||c.status===403)&&this._invalidateClientForToken(n);let u=await c.text().catch(()=>"");throw lg(c.status,c.statusText,u)}return c}_getClientForToken(n){return this._getEntryForToken(n).then(e=>e.capiClient)}async resolveRestrictedTelemetryContext(n){let e=ex(await this._getCopilotToken(n)),t=e.get("rt")==="1",r=e.get("tid"),o=t?(await this._getEntryForToken(n)).telemetryEndpoint:void 0;return{restrictedTelemetryEnabled:t,trackingId:r,telemetryEndpoint:o}}async resolveApiEndpoint(n){return(await this._getEntryForToken(n)).apiEndpoint}_getEntryForToken(n){let e=Date.now()/1e3,t=this._clientsByToken.get(n);if(t)return t.then(o=>o.expiresAt-e>i2?o:(this._clientsByToken.delete(n),this._getEntryForToken(n))).catch(o=>{throw this._clientsByToken.delete(n),o});let r=this._buildClientForToken(n).catch(o=>{throw this._clientsByToken.delete(n),o});return this._clientsByToken.set(n,r),r}_invalidateClientForToken(n){this._clientsByToken.delete(n)}async _buildClientForToken(n){let{extensionInfo:e,userUrl:t}=await this._getCapiBase(),r=this._fetch,o=new r2(e,void 0,{fetch:(d,c)=>r(d,{method:c.method??"GET",headers:c.headers,body:c.body,signal:c.signal})});this._logService.debug("[CopilotApiService] Discovering CAPI endpoints via /copilot_internal/user");let s=process.env[o2];if(s){if(s2(s))return this._logService.info(`[CopilotApiService] Using CAPI URL override ${s}; skipping endpoint discovery`),o.updateDomains({endpoints:{api:s,proxy:s},sku:""},void 0),{capiClient:o,expiresAt:Date.now()/1e3+tx,apiEndpoint:s};this._logService.warn(`[CopilotApiService] Ignoring non-loopback CAPI URL override ${s}; falling back to normal endpoint discovery`)}let a=await this._fetch(t,{method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json","X-GitHub-Api-Version":nx}});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Copilot endpoint discovery failed: ${a.status} ${a.statusText} \u2014 ${d}`)}let l=await a.json();return o.updateDomains({endpoints:l.endpoints??{},sku:l.access_type_sku??""},void 0),this._logService.debug("[CopilotApiService] CAPI endpoint discovered, api=",l.endpoints?.api),{capiClient:o,expiresAt:Date.now()/1e3+tx,telemetryEndpoint:l.endpoints?.telemetry,apiEndpoint:l.endpoints?.api}}_getCopilotToken(n){let e=Date.now()/1e3,t=this._copilotTokensByGithub.get(n);if(t)return t.then(o=>o.expiresAt-e>a2?o.token:(this._copilotTokensByGithub.get(n)===t&&this._copilotTokensByGithub.delete(n),this._getCopilotToken(n))).catch(o=>{throw this._copilotTokensByGithub.get(n)===t&&this._copilotTokensByGithub.delete(n),o});let r=this._buildCopilotToken(n).catch(o=>{throw this._copilotTokensByGithub.get(n)===r&&this._copilotTokensByGithub.delete(n),o});return this._copilotTokensByGithub.set(n,r),r.then(o=>o.token)}_invalidateCopilotTokenForGithub(n){this._copilotTokensByGithub.delete(n)}async _buildCopilotToken(n){let e=await this._getClientForToken(n);this._logService.debug("[CopilotApiService] Minting Copilot session token");let t=await e.makeRequest({method:"GET",headers:{Authorization:`token ${n}`,"X-GitHub-Api-Version":nx}},{type:cc.CopilotToken});if(!t.ok){let l=await t.text().catch(()=>"");throw new Error(`Copilot session token mint failed: ${t.status} ${t.statusText} \u2014 ${l}`)}let r=await t.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(n,e){let t=this._copilotTokensByGithub.get(n),r=t?await t:void 0,o=r?.modelIdsByFamily.get(e);if(o)return o;let a=(await this.models(n)).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(n){let e=n.getReader(),t=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=t.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(n){if(!n.startsWith("data: "))return;let e=n.slice(6).trim(),t;try{t=JSON.parse(e)}catch{this._logService.warn("[CopilotApiService] Failed to parse SSE data:",e);return}if(typeof t!="object"||t===null)return;let o=t.type;if(typeof o=="string"){if(o==="error"){let s=t.error,a;if(s&&typeof s=="object"&&typeof s.type=="string"&&typeof s.message=="string")a=t;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 ir(uc,a)}if(p2.has(o))return t}}};Xi=w([C(1,D),C(2,Ct)],Xi);var p2=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);var dg="VSCODE_PROXY_ERROR:",f2=8*1024,g2=/^[A-Za-z0-9+/]+={0,2}$/;function rx(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 cg(i){let n=i.status===uc?502:i.status,e=typeof i.envelope.request_id=="string"?i.envelope.request_id:"",t=m2(i.envelope.error.message)??{code:i.envelope.error.type,message:i.envelope.error.message};return{fetchError:{type:rx(n),reason:t.message??i.envelope.error.message,requestId:e,capiError:t}}}function m2(i){let n;try{n=JSON.parse(i)}catch{return}if(!n||typeof n!="object")return;let e=n.error;if(!e||typeof e!="object")return;let t=e.code,r=e.message;if(!(typeof t!="string"&&typeof r!="string"))return{code:typeof t=="string"?t:void 0,message:typeof r=="string"?r:void 0}}function ug(i){return`${dg}${Buffer.from(JSON.stringify(i)).toString("base64")}`}function h2(i,n){switch(i){case"quota":return"quotaExceeded";case"rate_limit":return"rateLimited";case"context_limit":return"length";case"authentication":case"authorization":return"agent_unauthorized"}return n!==void 0?rx(n):void 0}function y2(i){let n=h2(i.errorType,i.statusCode);if(!n)return;let e=i.errorCode??(n==="quotaExceeded"?"quota_exceeded":void 0),t=e||i.message?{code:e,message:i.message}:void 0;return{fetchError:{type:n,reason:i.message,requestId:i.providerCallId??"",serverRequestId:i.serviceRequestId,...t&&{capiError:t}}}}function pg(i){if(!i)return;let n=i.indexOf(dg);if(n===-1)return;let e=n+dg.length,t=i.slice(e).search(/[\s"']/),r=t===-1?i.slice(e):i.slice(e,e+t);if(!(r.length===0||r.length>f2||!g2.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 pc(i){let n=i.indexOf(dg);return n===-1?i:i.slice(0,n).trim()||i.slice(0,n)}function fc(i){return{chatError:i}}function ix(i){let n=pg(i);return n?fc(n):void 0}function ox(i){let n=y2(i);return n?fc(n):void 0}function Ea(i){let n=pg(i);return n?{message:pc(i),_meta:fc(n)}:{message:i}}var ka=class extends T{constructor(e,t,r,o,s,a,l){super();this._stateManager=e;this._options=t;this._logService=o;this._changesets=s;this._telemetryService=a;this._checkpointService=l;this._toolCallAgents=new Map;this._lastAgentInfos=[];this._subagentChats=new zl;this._pendingSubagentSignals=new zl;this._telemetryReporter=new ga(this._telemetryService),this._turnTracker=new jf(this._telemetryReporter),this._toolCallTracker=this._register(new vf(this._telemetryReporter)),this._permissionManager=this._register(r.createInstance(Aa,this._stateManager)),this._localCommands=this._register(r.createInstance(Ra,this._stateManager,this._options.localTurns,d=>this._tryConsumeNextQueuedMessage(d))),this._titleController=this._register(r.createInstance(fa,this._stateManager,{sessionDataService:this._options.sessionDataService,getGitHubCopilotToken:this._options.getGitHubCopilotToken,copilotApiService:this._options.copilotApiService})),this._register(Wn(d=>{let c=this._options.agents.read(d);this._publishAgentInfos(c,d)})),this._register(this._stateManager.onDidEmitEnvelope(d=>{if(ce(d.channel)&&rr(d.action)&&this._syncSessionInputNeededForChatAction(d.channel,d.action),!d.origin&&d.action.type==="chat/toolCallComplete"){let c=d.action;if(!ce(d.channel))return;let u=fe(d.channel);this._notifyClientToolCallComplete(u,d.channel,c.toolCallId,c.result,"server-envelope")}d.action.type==="chat/draftChanged"&&this._persistChatDraft(d.channel,d.action.draft)}))}_publishAgentInfos(e,t){let r=e.map(o=>{let s=o.getDescriptor(),a=o.getProtectedResources(),l=t?o.models.read(t):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,maxOutputTokens:c.maxOutputTokens,maxPromptTokens:c.maxPromptTokens,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,capabilities:s.capabilities?{...s.capabilities}:void 0}});Fe(this._lastAgentInfos,r)||(this._lastAgentInfos=r,this._stateManager.dispatchServerAction(Ke,{type:"root/agentsChanged",agents:r}))}async _publishSessionCustomizations(e,t){if(!e.getSessionCustomizations)return;let r=await e.getSessionCustomizations(v.parse(t));this._stateManager.dispatchServerAction(t,{type:"session/customizationsChanged",customizations:[...r]})}_publishSessionCustomizationsSoon(e,t){this._publishSessionCustomizations(e,t).catch(r=>{this._logService.error("[AgentSideEffects] getSessionCustomizations failed",r)})}_publishSessionCustomizationsForAgent(e){for(let t of this._stateManager.getSessionUris())this._options.getAgent(t)===e&&this._publishSessionCustomizationsSoon(e,t)}_publishAllSessionCustomizations(){for(let e of this._stateManager.getSessionUris()){let t=this._options.getAgent(e);t&&this._publishSessionCustomizationsSoon(t,e)}}_syncSessionInputNeededForChatAction(e,t){switch(t.type){case"chat/inputRequested":this._setSessionInputNeeded(e,{id:this._chatInputNeededId(e,t.request.id),kind:"chatInput",chat:e,request:t.request});break;case"chat/inputCompleted":this._removeSessionInputNeeded(e,this._chatInputNeededId(e,t.requestId));break;case"chat/toolCallStart":case"chat/toolCallReady":case"chat/toolCallConfirmed":case"chat/toolCallComplete":case"chat/toolCallResultConfirmed":this._syncToolInputNeeded(e,t.turnId,t.toolCallId);break;case"chat/turnComplete":case"chat/turnCancelled":case"chat/error":case"chat/truncated":this._removeSessionInputNeededForChat(e);break}}_syncToolInputNeeded(e,t,r){let o=this._toolConfirmationNeededId(e,t,r),s=this._toolClientExecutionNeededId(e,t,r),a=this._findToolCall(e,t,r);(a?.status==="pending-confirmation"||a?.status==="pending-result-confirmation")&&a?this._setSessionInputNeeded(e,{id:o,kind:"toolConfirmation",chat:e,turnId:t,toolCall:a}):this._removeSessionInputNeeded(e,o);let d=a?.contributor;a?.status==="running"&&d?.kind==="client"?this._setSessionInputNeeded(e,{id:s,kind:"toolClientExecution",chat:e,turnId:t,clientId:d.clientId,toolCall:a}):this._removeSessionInputNeeded(e,s)}_findToolCall(e,t,r){let o=this._stateManager.getSessionState(e),a=(o?.activeTurn?.id===t?o.activeTurn:o?.turns.find(l=>l.id===t))?.responseParts.find(l=>l.kind==="toolCall"&&l.toolCall.toolCallId===r);return a?.kind==="toolCall"?a.toolCall:void 0}_setSessionInputNeeded(e,t){let r=fe(e),o=this._stateManager.getSessionState(r)?.inputNeeded?.find(s=>s.id===t.id);if(!(o&&Fe(o,t))&&(this._stateManager.dispatchServerAction(r,{type:"session/inputNeededSet",request:t}),t.kind!=="chatInput")){let s=this._options.getAgent(r);s&&this._toolCallTracker.toolCallBlocked(s.id,e,t)}}_removeSessionInputNeeded(e,t){let r=fe(e);this._toolCallTracker.toolCallUnblocked(e,t),this._stateManager.getSessionState(r)?.inputNeeded?.some(o=>o.id===t)&&this._stateManager.dispatchServerAction(r,{type:"session/inputNeededRemoved",id:t})}_removeSessionInputNeededForChat(e){let t=fe(e);for(let r of this._stateManager.getSessionState(t)?.inputNeeded??[])r.chat===e&&this._removeSessionInputNeeded(e,r.id)}_chatInputNeededId(e,t){return`chatInput:${e}:${t}`}_toolConfirmationNeededId(e,t,r){return`toolConfirmation:${e}:${t}:${r}`}_toolClientExecutionNeededId(e,t,r){return`toolClientExecution:${e}:${t}:${r}`}initialize(){return this._permissionManager.initialize()}registerProgressListener(e){let t=new G;return t.add(e.onDidSessionProgress(r=>{this._handleAgentSignal(e,r)})),e.onDidCustomizationsChange&&t.add(e.onDidCustomizationsChange(()=>{this._publishAgentInfos(this._options.agents.get()),this._publishSessionCustomizationsForAgent(e)})),e.onDidRequireAuth&&t.add(e.onDidRequireAuth(r=>this._stateManager.emitAuthRequired(r))),t}_handleAgentSignal(e,t){if(t.kind==="subagent_started"){this._handleSubagentStarted(t.chat.toString(),t.toolCallId,t.agentName,t.agentDisplayName,t.agentDescription,t.parentToolCallId),this._drainPendingSubagentSignals(t.chat.toString(),t.toolCallId);return}if(t.kind==="subagent_completed"){this.completeSubagentSession(t.chat.toString(),t.toolCallId);return}if(t.kind==="steering_consumed"){this._stateManager.dispatchServerAction(t.chat.toString(),{type:"chat/pendingMessageRemoved",kind:"steering",id:t.id});return}let r=t.kind==="action"?t.resource.toString():t.chat.toString(),o=t.parentToolCallId;if(o){let a=this._subagentChats.get(r,o);if(a){let d=this._stateManager.getActiveTurnId(a.chatUri);d&&this._dispatchActionForSession(t,a.chatUri,d,e);return}this._logService.trace(`[AgentSideEffects] Buffering ${this._describeSignal(t)} for pending subagent ${r}/${o}`);let l=this._pendingSubagentSignals.get(r,o);l||(l=[],this._pendingSubagentSignals.set(l,r,o)),l.push({signal:t,agent:e});return}if(t.kind==="pending_confirmation"){let a=this._findSubagentChatForToolCall(r,t.state.toolCallId);if(a){let l=this._stateManager.getActiveTurnId(a)??"";this._handleToolReady(t,a,l,e).catch(d=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",d)});return}}let s=this._stateManager.getActiveTurnId(r);if(s){this._dispatchActionForSession(t,r,s,e);return}if(t.kind==="pending_confirmation"){this._handleToolReady(t,r,"",e).catch(a=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",a)});return}t.kind==="action"&&(this._stateManager.dispatchServerAction(r,t.action),t.action.type==="chat/turnComplete"&&this._runTurnCompleteSideEffects(r,void 0))}_dispatchActionForSession(e,t,r,o){if(e.kind==="pending_confirmation"){o&&this._handleToolReady(e,t,r,o).catch(l=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",l)});return}if(e.kind!=="action")return;let s=e.action;me(s,{turnId:!0})&&s.turnId!==r&&(s={...s,turnId:r}),s.type==="chat/toolCallStart"&&o&&(this._toolCallAgents.set(`${t}:${s.toolCallId}`,o.id),this._toolCallTracker.toolCallStarted(o.id,t,s.toolCallId,s.toolName,s.contributor));let a=ce(t)?fe(t):t;if(s.type==="chat/toolCallComplete"&&this._subagentChats.get(t,s.toolCallId)){let d=this._stateManager.getSessionState(t),u=this._getRunningToolCallContent(d,r,s.toolCallId).find(p=>me(p,{type:!0})&&p.type==="subagent");if(u){let p=[...s.result.content??[],u];s={...s,result:{...s.result,content:p}}}}this._stateManager.dispatchServerAction(t,s),(s.type==="chat/delta"||s.type==="chat/responsePart"||s.type==="chat/toolCallStart"||s.type==="chat/reasoning")&&this._turnTracker.markFirstProgress(t,r),s.type==="chat/toolCallComplete"&&(this._toolCallTracker.toolCallCompleted(t,s.toolCallId,s.result),this._pendingSubagentSignals.delete(t,s.toolCallId),L_(s.result).length>0&&this._changesets.onToolCallEditsApplied(a,r)),s.type==="chat/turnComplete"&&(this._turnTracker.turnCompleted(t,r,"success"),this._toolCallTracker.clearSession(t),this._runTurnCompleteSideEffects(t,r)),s.type==="chat/turnCancelled"&&(this._turnTracker.turnCompleted(t,r,"cancelled"),this._toolCallTracker.clearSession(t)),s.type==="chat/error"&&(this._turnTracker.turnCompleted(t,r,"error"),this._toolCallTracker.clearSession(t))}_runTurnCompleteSideEffects(e,t){let r=ce(e)?fe(e):e;t!==void 0?this._checkpointService.captureTurnCheckpoint(v.parse(r),t).then(()=>{this._changesets.onTurnComplete(r,t)},s=>{this._logService.warn(`[AgentSideEffects] Turn checkpoint capture failed for ${r}/${t}: ${s instanceof Error?s.message:String(s)}`),this._changesets.onTurnComplete(r,t)}):this._changesets.onTurnComplete(r,t),this._tryConsumeNextQueuedMessage(e),this._options.onTurnComplete(r);let o=ce(e)&&!Ue(e)?e:void 0;this._titleController.refineTitleFromFirstTurn(r,o)}_describeSignal(e){return e.kind==="action"?`action(${e.action.type})`:e.kind}_drainPendingSubagentSignals(e,t){let r=this._pendingSubagentSignals.get(e,t);if(r){this._pendingSubagentSignals.delete(e,t),this._logService.trace(`[AgentSideEffects] Draining ${r.length} buffered signal(s) for subagent ${e}/${t}`);for(let{signal:o,agent:s}of r)this._handleAgentSignal(s,o)}}_handleSubagentStarted(e,t,r,o,s,a){let l=fe(e),d=Bs(l,t);if(this._subagentChats.get(e,t))return;this._logService.info(`[AgentSideEffects] Starting subagent turn: ${d} (parent=${e}, toolCallId=${t})`);let c=H();this._stateManager.dispatchServerAction(d,{type:"chat/turnStarted",turnId:c,message:{text:"",origin:{kind:"user"}}}),this._subagentChats.set({parentChatUri:e,toolCallId:t,sessionUri:l,chatUri:d},e,t);let u=a?this._subagentChats.get(e,a)?.chatUri??e:e,p=this._stateManager.getActiveTurnId(u);if(p){let m=this._stateManager.getSessionState(u),h=this._getRunningToolCallContent(m,p,t);this._stateManager.dispatchServerAction(u,{type:"chat/toolCallContentChanged",turnId:p,toolCallId:t,content:[...h,{type:"subagent",resource:d,title:o,agentName:r,description:s}]})}}_getRunningToolCallContent(e,t,r){if(!e?.activeTurn||e.activeTurn.id!==t)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 t of this._subagentChats.getAll(e)){let r=this._stateManager.getActiveTurnId(t.chatUri);r&&(this._stateManager.dispatchServerAction(t.chatUri,{type:"chat/turnCancelled",turnId:r}),this._turnTracker.turnCompleted(t.chatUri,r,"cancelled")),this._toolCallTracker.clearSession(t.chatUri)}this._subagentChats.deleteAll(e),this._pendingSubagentSignals.deleteAll(e)}completeSubagentSession(e,t){this._pendingSubagentSignals.delete(e,t);let r=this._subagentChats.get(e,t);if(!r)return;let o=this._stateManager.getActiveTurnId(r.chatUri);o&&this._stateManager.dispatchServerAction(r.chatUri,{type:"chat/turnComplete",turnId:o}),this._subagentChats.delete(e,t)}removeSubagentSessions(e){let t=new Set;for(let r of this._subagentChats.values())r.sessionUri===e&&(this._stateManager.removeChat(r.sessionUri,r.chatUri),this._toolCallTracker.clearSession(r.chatUri),t.add(r.parentChatUri));for(let r of t)this._subagentChats.deleteAll(r),this._pendingSubagentSignals.deleteAll(r)}_findSubagentChatForToolCall(e,t){for(let r of this._subagentChats.getAll(e))if(this._toolCallAgents.has(`${r.chatUri}:${t}`))return r.chatUri}_toolCallCompletionChat(e){if(!Cd(e))return e;for(let t of this._subagentChats.values())if(t.chatUri===e)return this._toolCallCompletionChat(t.parentChatUri);return this._logService.warn(`[AgentSideEffects] Missing parent chat for subagent tool completion: chat=${e}`),e}_notifyClientToolCallComplete(e,t,r,o,s){let a=this._toolCallCompletionChat(t),l=this._options.getAgent(e);if(!l){this._logService.warn(`[AgentSideEffects] No agent for client tool completion: source=${s}, session=${e}, chat=${t}, completionChat=${a}, toolCallId=${r}`);return}this._logService.info(`[AgentSideEffects] Forwarding client tool completion: source=${s}, session=${e}, chat=${t}, completionChat=${a}, toolCallId=${r}, success=${o.success}`),l.onClientToolCallComplete(v.parse(e),v.parse(a),r,o)}async _handleToolReady(e,t,r,o){let s={toolCallId:e.state.toolCallId,session:e.chat,permissionKind:e.permissionKind,permissionPath:e.permissionPath,toolInput:e.state.toolInput,requestSandboxBypass:e.requestSandboxBypass},a=await this._permissionManager.getAutoApproval(s,t),l=this._stateManager.getSessionState(t)?.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(`${t}:${e.state.toolCallId}`,o.id),u={...e,state:{...e.state,_meta:{...d?._meta,...e.state._meta,...Qt({autoApproveBySetting:!0})}}}):a!==void 0?(this._toolCallAgents.delete(`${t}:${e.state.toolCallId}`),o.respondToPermissionRequest(e.state.toolCallId,!0),u={...e,state:{...e.state,confirmationTitle:void 0}}):u.state.confirmationTitle&&this._toolCallAgents.set(`${t}:${e.state.toolCallId}`,o.id),this._stateManager.dispatchServerAction(t,this._permissionManager.createToolReadyAction(u,t,r))}handleAction(e,t,r){let o=ce(e)?e:void 0,s=o?fe(o):e;switch(t.type){case"chat/turnStarted":{if(!o)throw new Error(`ChatTurnStarted must be handled on an AHP chat channel: ${e}`);if(this._localCommands.tryHandle({turnChannel:e,turnId:t.turnId,text:t.message.text}))break;let a=this._stateManager.getSessionState(e);a||this._logService.info(`[AgentSideEffects] Turn started for session not in state manager: ${e}, turnId=${t.turnId} - status/summary updates may be dropped unless the session is restored`),this._titleController.seedTitleFromFirstMessage(s,t.message.text,o);let l=this._options.getAgent(s);if(!l){this._stateManager.dispatchServerAction(e,{type:"chat/error",turnId:t.turnId,error:{errorType:"noAgent",message:"No agent found for session"}});return}let d=t.message.attachments;this._telemetryReporter.userMessageSent(l.id,e,a,"direct",d);let{model:c,permissionLevel:u}=this._getTurnTelemetryContext(a,t.message.model?.id);this._turnTracker.turnStarted(l.id,e,t.turnId,c,u),this._sendTurnMessage({agent:l,sessionChannel:s,turnChannel:e,chat:e,message:t.message,turnId:t.turnId,senderClientId:r});break}case"chat/toolCallConfirmed":{if(!o)throw new Error(`ChatToolCallConfirmed must be handled on an AHP chat channel: ${e}`);let a=`${e}:${t.toolCallId}`,l=this._toolCallAgents.get(a);l?(this._toolCallAgents.delete(a),this._options.agents.get().find(c=>c.id===l)?.respondToPermissionRequest(t.toolCallId,t.approved)):this._logService.warn(`[AgentSideEffects] No agent for tool call confirmation: ${t.toolCallId}`),t.approved&&this._permissionManager.handleToolCallConfirmed(e,t.toolCallId,t.selectedOptionId);break}case"chat/inputCompleted":{if(!o)throw new Error(`ChatInputCompleted must be handled on an AHP chat channel: ${e}`);this._options.getAgent(s)?.respondToUserInputRequest(t.requestId,t.response,t.answers);break}case"chat/turnCancelled":{if(!o)throw new Error(`ChatTurnCancelled must be handled on an AHP chat channel: ${e}`);this._turnTracker.turnCompleted(e,t.turnId,"cancelled"),this._toolCallTracker.clearSession(e),this.cancelSubagentSessions(e);let a=this._options.getAgent(s);if(a){let l=v.parse(e);a.chats.abort(l).catch(d=>{this._logService.error("[AgentSideEffects] abort failed",d)})}break}case"session/titleChanged":{if(o){this._stateManager.updateChatTitle(s,o,t.title),this._persistSessionFlag(s,`customChatTitle:${o}`,t.title);break}this._persistSessionFlag(e,"customTitle",t.title);break}case"chat/pendingMessageSet":case"chat/pendingMessageRemoved":case"chat/queuedMessagesReordered":{if(!o)throw new Error(`${t.type} must be handled on an AHP chat channel: ${e}`);this._syncPendingMessages(e);break}case"chat/truncated":{if(!o)throw new Error(`ChatTruncated must be handled on an AHP chat channel: ${e}`);let a=this._options.getAgent(s),l=t.turnId!==void 0?this._options.localTurns.resolveConcreteTurnId(o,t.turnId):t.turnId;a?.truncateSession?.(v.parse(s),l,v.parse(o)).catch(u=>{this._logService.error("[AgentSideEffects] truncateSession failed",u)});let d=new Set((this._stateManager.getChatState(o)?.turns??[]).map(u=>u.id)),c=this._options.localTurns.getLocalTurnIds(o).filter(u=>!d.has(u));this._options.localTurns.deleteLocals(s,c),this._changesets.onSessionTruncated(s);break}case"session/activeClientSet":{let a=this._options.getAgent(e);if(!a)break;let l=t.activeClient,d=a.getOrCreateActiveClient(v.parse(e),{clientId:l.clientId,displayName:l.displayName});d.tools=l.tools,d.customizations=l.customizations??[];break}case"session/activeClientRemoved":{this._options.getAgent(e)?.removeActiveClient(v.parse(e),t.clientId);break}case"root/configChanged":{Vf(this._telemetryService,t.config),this._publishAgentInfos(this._options.agents.get()),this._publishAllSessionCustomizations();break}case"session/customizationToggled":{this._options.getAgent(e)?.setCustomizationEnabled?.(t.id,t.enabled);break}case"session/isReadChanged":{this._persistSessionFlag(e,"isRead",t.isRead?"true":"");break}case"session/isArchivedChanged":{this._persistSessionFlag(e,"isArchived",t.isArchived?"true":""),this._options.getAgent(e)?.onArchivedChanged?.(v.parse(e),t.isArchived).catch(l=>{this._logService.warn(`[AgentSideEffects] onArchivedChanged failed for ${e}`,l)});break}case"session/configChanged":{let l=this._stateManager.getSessionState(e)?.config?.values;l&&this._persistSessionFlag(e,"configValues",JSON.stringify(l));break}case"chat/toolCallComplete":{if(!o)break;this._notifyClientToolCallComplete(s,o,t.toolCallId,t.result,"client-dispatch");break}}}cancelSessionTitleGeneration(e){this._titleController.cancelTitleGeneration(e)}generateForkedTitle(e,t,r,o,s){this._titleController.generateForkedTitle(e,t,r,o,s)}_persistSessionFlag(e,t,r){Kf(this._options.sessionDataService,this._logService,e,t,r)}_persistChatDraft(e,t){if(!ce(e))return;let r=He(e);if(!r)return;let o=v.parse(r.session),s=this._options.sessionDataService.openDatabase(o);s.object.setChatDraft(v.parse(e),t).catch(a=>{this._logService.warn(`[AgentSideEffects] Failed to persist chat draft for ${e.toString()}`,a)}).finally(()=>{s.dispose()})}_syncPendingMessages(e){let t=fe(e),r=this._stateManager.getSessionState(e);if(!r)return;this._options.getAgent(t)?.setPendingMessages?.(v.parse(t),r.steeringMessage,[],Ue(e)?void 0:v.parse(e)),this._tryConsumeNextQueuedMessage(e)}_tryConsumeNextQueuedMessage(e){let t=fe(e);if(this._stateManager.getActiveTurnId(e))return;let r=this._stateManager.getSessionState(e);if(!r?.queuedMessages?.length)return;let o=r.queuedMessages[0],s=H();if(this._stateManager.dispatchServerAction(e,{type:"chat/turnStarted",turnId:s,message:o.message,queuedMessageId:o.id}),this._localCommands.tryHandle({turnChannel:e,turnId:s,text:o.message.text}))return;let a=this._options.getAgent(t);if(!a){this._stateManager.dispatchServerAction(e,{type:"chat/error",turnId:s,error:{errorType:"noAgent",message:"No agent found for session"}});return}let l=o.message.attachments,d=this._stateManager.getSessionState(e);this._telemetryReporter.userMessageSent(a.id,e,d,"queued",l);let{model:c,permissionLevel:u}=this._getTurnTelemetryContext(d,o.message.model?.id);this._turnTracker.turnStarted(a.id,e,s,c,u),this._sendTurnMessage({agent:a,sessionChannel:t,turnChannel:e,chat:e,message:o.message,turnId:s,senderClientId:void 0})}_getTurnTelemetryContext(e,t){let r=e?.config?.values.autoApprove;return{model:t,permissionLevel:typeof r=="string"?r:void 0}}async _sendTurnMessage(e){let{agent:t,turnChannel:r,chat:o,message:s,turnId:a,senderClientId:l}=e,d=v.parse(o),c=[];s.model&&c.push(t.chats.changeModel(d,s.model).catch(u=>{this._logService.error("[AgentSideEffects] changeModel failed",u)})),c.push(t.chats.changeAgent(d,s.agent).catch(u=>{this._logService.error("[AgentSideEffects] changeAgent failed",u)})),await Promise.all(c),await t.chats.sendMessage(d,s.text,s.attachments,a,l).catch(u=>{let p=u?.code;this._logService.error(`[AgentSideEffects] sendMessage failed for session=${r}: code=${p}, message=${u instanceof Error?u.message:String(u)}, type=${u?.constructor?.name}`,u),this._stateManager.dispatchServerAction(r,{type:"chat/error",turnId:a,error:v2(u)}),this._turnTracker.turnCompleted(r,a,"error"),this._toolCallTracker.clearSession(r)})}dispose(){this._toolCallAgents.clear(),this._toolCallTracker.clear(),super.dispose()}};ka=w([C(2,Ie),C(3,D),C(4,ji),C(5,Hn),C(6,_r)],ka);function v2(i){let n=String(i),e=pg(i instanceof Error?i.message:n);return e?{errorType:"sendFailed",message:pc(n),_meta:fc(e)}:{errorType:"sendFailed",message:n}}var fg=class{constructor(n,e){this._sessionDataService=n;this._logService=e;this._byChat=new Map;this._seqBySession=new Map}isLocal(n,e){return this._byChat.get(n)?.has(e)??!1}getLocalTurnIds(n){let e=this._byChat.get(n);return e?[...e.keys()]:[]}resolveConcreteTurnId(n,e){let t=this._byChat.get(n)?.get(e);return t?t.anchorTurnId:e}record(n,e,t,r){let o=(this._seqBySession.get(n)??0)+1;this._noteInMemory(n,e,t.id,r,o);let s={turnId:t.id,chatUri:e,anchorTurnId:r,seq:o,payload:JSON.stringify(t)},a;try{a=this._sessionDataService.openDatabase(v.parse(n))}catch(l){this._logService.warn(`[AgentHostLocalTurns] Failed to open database to persist local turn ${t.id}`,l);return}a.object.insertLocalTurn(s).catch(l=>{this._logService.warn(`[AgentHostLocalTurns] Failed to persist local turn ${t.id}`,l)}).finally(()=>a.dispose())}async loadForChat(n,e){return(await this._load(n)).filter(r=>r.chatUri===e)}noteInMemory(n,e,t,r,o){this._noteInMemory(n,e,t,r,o)}deleteLocals(n,e){if(e.length===0)return;let t=new Set(e);for(let o of this._byChat.values())for(let s of t)o.delete(s);let r;try{r=this._sessionDataService.openDatabase(v.parse(n))}catch(o){this._logService.warn(`[AgentHostLocalTurns] Failed to open database to delete local turns for ${n}`,o);return}r.object.deleteLocalTurns(e).catch(o=>{this._logService.warn(`[AgentHostLocalTurns] Failed to delete local turns for ${n}`,o)}).finally(()=>r.dispose())}forgetChat(n){this._byChat.delete(n)}async _load(n){let e=this._sessionDataService.tryOpenDatabase?.(v.parse(n));if(!e)return[];try{let t=await e;if(!t)return[];try{let r=await t.object.getLocalTurns();for(let o of r)this._noteInMemory(n,o.chatUri,o.turnId,o.anchorTurnId,o.seq);return r}finally{t.dispose()}}catch(t){return this._logService.warn(`[AgentHostLocalTurns] Failed to load local turns for ${n}`,t),[]}}_noteInMemory(n,e,t,r,o){let s=this._byChat.get(e);s||(s=new Map,this._byChat.set(e,s)),s.set(t,{anchorTurnId:r,seq:o}),this._seqBySession.set(n,Math.max(this._seqBySession.get(n)??0,o))}};var gg=class{constructor(n,e){this._stateManager=n;this._groupByToolName=new Map;for(let t of e)for(let r of t.definitions){if(this._groupByToolName.has(r.name))throw new Error(`Duplicate server tool registered: ${r.name}`);this._groupByToolName.set(r.name,t)}this.definitions=e.flatMap(t=>t.definitions),this.toolNames=this.definitions.map(t=>t.name)}advertise(n){this._stateManager.dispatchServerAction(n,{type:"session/serverToolsChanged",tools:[...this.definitions]})}requiresConfirmation(n){return this._groupByToolName.get(n)?.requiresConfirmation?.(n)??!1}executeTool(n,e,t){let r=this._groupByToolName.get(e);if(!r)throw new Error(`Unknown server tool: ${e}`);return r.execute(this._stateManager,n,e,t)}};var gc="vscode.agentFeedback",sx="viewUnreviewedComments",ax="addComment";function S2(i){return i==="user"||i==="codeReview"||i==="prReview"}function b2(i){return i==="created"||i==="accepted"||i==="submitted"||i==="resolved"}function lx(i){let e=i._meta?.[gc];if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(!S2(t.kind)||!b2(t.state)||typeof t.sessionResource!="string")return;let r={kind:t.kind,state:t.state,sessionResource:t.sessionResource};return t.suggestion!==void 0&&(r.suggestion=t.suggestion),typeof t.codeSelection=="string"&&(r.codeSelection=t.codeSelection),typeof t.diffHunks=="string"&&(r.diffHunks=t.diffHunks),typeof t.sourcePRReviewCommentId=="string"&&(r.sourcePRReviewCommentId=t.sourcePRReviewCommentId),typeof t.pendingAgentReveal=="boolean"&&(r.pendingAgentReveal=t.pendingAgentReveal),r}var Rr=ax,hS="listComments",hg="deleteComments",hc="resolveComments",yc=sx,ux=new Set(["prReview","codeReview"]),C2=new Set([yc]);function I2(i){return C2.has(i)}var _2={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"]},T2={type:"object",properties:{}},w2={type:"object",properties:{}},R2={type:"object",properties:{commentIds:{type:"array",items:{type:"string"},description:"Comment IDs to delete."}},required:["commentIds"]},x2={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"]},P2=[{name:Rr,title:"Add Comment (Agent Feedback)",description:"Add a comment to a file range.",inputSchema:_2,annotations:{readOnlyHint:!1}},{name:hS,title:"List Comments (Agent Feedback)",description:"List comments for this session.",inputSchema:T2,annotations:{readOnlyHint:!0}},{name:hg,title:"Delete Comments (Agent Feedback)",description:"Delete comments for this session.",inputSchema:R2,annotations:{readOnlyHint:!1,destructiveHint:!0}},{name:hc,title:"Resolve Comments (Agent Feedback)",description:"Mark comments for this session as resolved or unresolved.",inputSchema:x2,annotations:{readOnlyHint:!1}},{name:yc,title:"View Unreviewed Comments (Agent Feedback)",description:"View pull request or code review comments that the user has not reviewed yet. Calling this asks the user to choose which of those comments to reveal; only the comments the user reveals are returned.",inputSchema:w2,annotations:{readOnlyHint:!0}}];function mS(i,n,e){if(typeof i!="string"||i.length===0)throw new Error(`Invalid ${e} input: ${n} must be a non-empty string.`);return i}function mg(i,n,e){if(typeof i!="number"||!Number.isInteger(i)||i<1)throw new Error(`Invalid ${e} input: ${n} must be a positive integer.`);return i}function A2(i){let n=i??{},e=mS(n.resourceUri,"resourceUri",Rr),t=mS(n.text,"text",Rr);if(!n.range||typeof n.range!="object"||Array.isArray(n.range))throw new Error(`Invalid ${Rr} input: range must be an object.`);let r=n.range;return{resourceUri:e,text:t,range:{startLineNumber:mg(r.startLineNumber,"range.startLineNumber",Rr),startColumn:mg(r.startColumn,"range.startColumn",Rr),endLineNumber:mg(r.endLineNumber,"range.endLineNumber",Rr),endColumn:mg(r.endColumn,"range.endColumn",Rr)}}}function dx(i,n){if(!Array.isArray(i)||i.length===0)throw new Error(`Invalid ${n} input: commentIds must be a non-empty string array.`);let e=[];for(let t of i)e.push(mS(t,"commentIds[]",n));return[...new Set(e)]}function E2(i){if(i===void 0)return!0;if(typeof i!="boolean")throw new Error(`Invalid ${hc} input: resolved must be a boolean.`);return i}function k2(i){return{start:{line:i.startLineNumber-1,character:i.startColumn-1},end:{line:i.endLineNumber-1,character:i.endColumn-1}}}function D2(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 cx(i){return typeof i=="string"?i:i.markdown}function Zo(i){return lx(i)}function mc(i){let n=i.entries??[],e=Zo(i),t=n.slice(1).map(r=>cx(r.text));return{id:i.id,resourceUri:i.resource,range:D2(i.range),text:n.length?cx(n[0].text):"",kind:e?.kind??"user",resolved:i.resolved,...t.length?{replies:t}:{}}}function gS(i){return i.annotations.filter(n=>{let e=Zo(n);return!e||!n.entries?.length?!1:(n.resolved?"resolved":e.state??"accepted")!=="created"})}function M2(i){return i.annotations.filter(n=>{let e=Zo(n);return!e||!n.entries?.length?!1:ux.has(e.kind)&&e.pendingAgentReveal===!0})}function O2(i){let n=Zo(i);if(!n)return i;let e={...n,pendingAgentReveal:void 0};return{...i,_meta:{...i._meta,[gc]:e}}}function L2(i){return i.annotations.filter(n=>{let e=Zo(n);return!e||!n.entries?.length?!1:ux.has(e.kind)&&!n.resolved&&(e.state??"accepted")==="created"})}function N2(i){let n=L2(i);if(!n.length)return;let e=0,t=0;for(let a of n){let l=Zo(a)?.kind;l==="prReview"?e++:l==="codeReview"&&t++}let r=[];e>0&&r.push(`${e} pull request comment${e===1?"":"s"}`),t>0&&r.push(`${t} code review comment${t===1?"":"s"}`);let o=r.join(" and ");return`There ${n.length===1?"is":"are"} ${o} which the user has not reviewed yet. If the user wants you to tackle them, call the \`${yc}\` tool to view them.`}function U2(i,n,e,t){switch(e){case Rr:{let{resourceUri:r,range:o,text:s}=A2(t),a=H(),l={kind:"codeReview",state:"created",sessionResource:n},d={id:a,turnId:"",resource:r,range:k2(o),resolved:!1,entries:[{id:`${a}:0`,text:s}],_meta:{[gc]:l}};return{actions:[{type:"annotations/set",annotation:d}],result:"Comment added."}}case hS:{let r={comments:gS(i).map(mc)},o=N2(i);return o&&(r.note=o),{actions:[],result:JSON.stringify(r,void 0,2)}}case yc:{let r=M2(i),o=r.map(mc);return{actions:r.map(a=>({type:"annotations/set",annotation:O2(a)})),result:JSON.stringify({comments:o},void 0,2)}}case hg:{let r=dx(t?.commentIds,hg),o=gS(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(mc);return{actions:a,result:JSON.stringify({deletedCommentIds:l,notFoundCommentIds:d,remainingComments:c},void 0,2)}}case hc:{let r=t??{},o=dx(r.commentIds,hc),s=E2(r.resolved),a=gS(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 y=Zo(h),S={...y,kind:y?.kind??"user",state:s?"resolved":"submitted",sessionResource:y?.sessionResource??n},b={...h,resolved:s,_meta:{...h._meta,[gc]:S}};d.push({type:"annotations/set",annotation:b}),c.push(m)}let p=a.map(m=>c.includes(m.id)?mc({...m,resolved:s}):mc(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}`)}}function F2(i){if(i)try{let n=JSON.parse(i);return Array.isArray(n.comments)?n.comments.length:void 0}catch{return}}function H2(i,n,e){switch(i){case Rr:return{displayName:f(2364,null),invocationMessage:f(2359,null),pastTenseMessage:f(2352,null)};case hS:{let t,r=e?F2(e.text):void 0;return r===void 0?t=f(2354,null):r===1?t=f(2356,null):t=f(2355,null,r),{displayName:f(2366,null),invocationMessage:f(2361,null),pastTenseMessage:t}}case hg:return{displayName:f(2365,null),invocationMessage:f(2360,null),pastTenseMessage:f(2353,null)};case hc:return{displayName:f(2367,null),invocationMessage:f(2362,null),pastTenseMessage:f(2357,null)};case yc:return{displayName:f(2368,null),invocationMessage:f(2363,null),pastTenseMessage:f(2358,null)};default:return}}var px={definitions:P2,requiresConfirmation(i){return I2(i)},getDisplay(i,n,e){return H2(i,n,e)},execute(i,n,e,t){let r=He(n)?.session??n,o=uf(r),a=i.getSnapshot(o)?.state??{annotations:[]},l=U2(a,r,e,t);for(let d of l.actions)i.dispatchServerAction(o,d);return l.result}};var yS=[px];function $2(i,n){return i===n||i.endsWith(`__${n}`)}function or(i,n,e){for(let t of yS)if(t.getDisplay){for(let r of t.definitions)if($2(i,r.name))return t.getDisplay(r.name,n,e)}}import{Worker as W2}from"worker_threads";var Zi=class extends T{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,t,r=Mw){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,t,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,t=new W2(e,{name:"Diff compute worker"});t.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)}),t.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=t}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()}};Zi=w([C(0,D)],Zi);function fx(i){return i.after?.uri??i.before?.uri}function vS(i,n,e,t,r){let o=e.firstKind!=="create",s=e.lastKind!=="delete";return{...o?{before:{uri:v.file(e.firstFilePath).toString(),content:{uri:Vi(i,e.firstToolCallId,e.firstFilePath,"before")}}}:{},...s?{after:{uri:v.file(e.terminalPath).toString(),content:{uri:Vi(n,e.lastToolCallId,e.lastFilePath,"after")}}}:{},diff:{added:t,removed:r}}}async function gx(i,n,e,t){if(!t)return SS([{sessionUri:i,db:n}],e);let r,o=!1,s=await n.getFileEditsByTurn(t.changedTurnId);if(s.length===0)return[...t.previousDiffs];let a=new Set(t.previousDiffs.map(fx));if(s.some(y=>y.kind==="rename"||a.has(v.file(y.filePath).toString()))?r=await n.getAllFileEdits():(r=s,o=!0),r.length===0)return[];let d=new Map,c=new Map,u=o?void 0:new Set;for(let y of r){let S;y.kind==="rename"&&y.originalPath?(S=d.get(y.originalPath)??y.originalPath,d.set(y.filePath,S),d.delete(y.originalPath)):(S=d.get(y.filePath)??y.filePath,d.set(y.filePath,S)),u&&y.turnId===t.changedTurnId&&u.add(S);let b=c.get(S);b?(b.terminalPath=y.filePath,b.lastToolCallId=y.toolCallId,b.lastFilePath=y.filePath,b.lastKind=y.kind):c.set(S,{terminalPath:y.filePath,firstToolCallId:y.toolCallId,firstFilePath:y.kind==="rename"&&y.originalPath?y.originalPath:y.filePath,firstKind:y.kind,firstSourceIdx:0,lastToolCallId:y.toolCallId,lastFilePath:y.filePath,lastKind:y.kind,lastSourceIdx:0})}let p=o?void 0:new Map(t.previousDiffs.map(y=>[fx(y),y])),m=[],h=[];for(let[y,S]of c){if(u&&!u.has(y)){let b=v.file(S.terminalPath).toString(),I=p.get(b);I&&m.push(I);continue}h.push((async()=>{let b;if(S.firstKind==="create")b="";else{let R=await n.readFileEditContent(S.firstToolCallId,S.firstFilePath);b=R?.beforeContent?new TextDecoder().decode(R.beforeContent):""}let I;if(S.lastKind==="delete")I="";else{let R=await n.readFileEditContent(S.lastToolCallId,S.lastFilePath);I=R?.afterContent?new TextDecoder().decode(R.afterContent):""}if(b===I)return;let _=await e.computeDiffCounts(b,I);m.push(vS(i,i,S,_.added,_.removed))})())}return await Promise.allSettled(h),o&&m.push(...t.previousDiffs),m}async function SS(i,n){let e=await Promise.all(i.map(l=>l.db.getAllFileEdits())),t=new Map,r=new Map,o=0;for(let l=0;l<e.length;l++)for(let d of e[l]){o++;let c;d.kind==="rename"&&d.originalPath?(c=t.get(d.originalPath)??d.originalPath,t.set(d.filePath,c),t.delete(d.originalPath)):(c=t.get(d.filePath)??d.filePath,t.set(d.filePath,c));let u=r.get(c);u?(u.terminalPath=d.filePath,u.lastToolCallId=d.toolCallId,u.lastFilePath=d.filePath,u.lastKind=d.kind,u.lastSourceIdx=l):r.set(c,{terminalPath:d.filePath,firstToolCallId:d.toolCallId,firstFilePath:d.kind==="rename"&&d.originalPath?d.originalPath:d.filePath,firstKind:d.kind,firstSourceIdx:l,lastToolCallId:d.toolCallId,lastFilePath:d.filePath,lastKind:d.kind,lastSourceIdx:l})}if(o===0)return[];let s=[],a=[];for(let l of r.values())a.push((async()=>{let d=i[l.firstSourceIdx],c=i[l.lastSourceIdx],u;if(l.firstKind==="create")u="";else{let h=await d.db.readFileEditContent(l.firstToolCallId,l.firstFilePath);u=h?.beforeContent?new TextDecoder().decode(h.beforeContent):""}let p;if(l.lastKind==="delete")p="";else{let h=await c.db.readFileEditContent(l.lastToolCallId,l.lastFilePath);p=h?.afterContent?new TextDecoder().decode(h.afterContent):""}if(u===p)return;let m=await n.computeDiffCounts(u,p);s.push(vS(d.sessionUri,c.sessionUri,l,m.added,m.removed))})());return await Promise.allSettled(a),s}async function mx(i,n,e,t){let r=await n.getFileEditsByTurn(t);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,firstSourceIdx:0,lastToolCallId:d.toolCallId,lastFilePath:d.filePath,lastKind:d.kind,lastSourceIdx:0})}let a=[],l=[];for(let d of s.values())l.push((async()=>{let c;if(d.firstKind==="create")c="";else{let m=await n.readFileEditContent(d.firstToolCallId,d.firstFilePath);c=m?.beforeContent?new TextDecoder().decode(m.beforeContent):""}let u;if(d.lastKind==="delete")u="";else{let m=await n.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(vS(i,i,d,p.added,p.removed))})());return await Promise.allSettled(l),a}var vc="checkpoint.workingDir",Da=class extends T{constructor(e,t,r){super();this._sessionDataService=e;this._gitService=t;this._logService=r;this._sequencer=new at;this._register(this._sessionDataService.onWillDeleteSessionData(o=>{o.waitUntil(this.disposeSessionData(o.session))}))}captureBaseline(e,t){return this._sequencer.queue(e.toString(),()=>this._captureBaseline(e,t))}async _captureBaseline(e,t){if(!t)return;let r=this._sessionDataService.openDatabase(e);try{let o=await r.object.getMetadata(Qo);if(o)return o;let s=this._sanitizedSessionId(e),a=kv(s,0),l=await this._writeCheckpointCommit(t,void 0,`Agent host session ${s} - baseline checkpoint`);if(!l)return;let d=await this._gitService.getRepositoryRoot(t);return d?(await this._gitService.updateRef(d,a,l.commitOid),await r.object.setMetadata(Qo,a),await r.object.setMetadata(vc,t.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,t){return this._sequencer.queue(e.toString(),()=>this._captureTurnCheckpoint(e,t))}async _captureTurnCheckpoint(e,t){let r=this._sessionDataService.openDatabase(e);try{let[o,s,a,l]=await Promise.all([r.object.getMetadata(Qo),r.object.getMetadata(vc),r.object.getTurnCheckpointRef(t),r.object.getPreviousCheckpointRef(t)]);if(a)return a;if(!o||!s)return;let d=v.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(t,u),this._logService.trace(`[AgentHostCheckpoint] No-op turn ${t} for ${e.toString()}; reusing ${u}`),u;let y=this._sanitizedSessionId(e),S=await this._nextTurnNumber(r.object),b=kv(y,S),I=await this._gitService.commitTree(c,m,p,`Agent host session ${y} - turn ${S}`);return I?(await this._gitService.updateRef(c,b,I),await r.object.setTurnCheckpointRef(t,b),this._logService.trace(`[AgentHostCheckpoint] Captured turn ${S} for ${e.toString()} at ${b}`),b):void 0}catch(o){this._logService.warn(`[AgentHostCheckpoint] Failed to capture turn checkpoint for ${e.toString()}/${t}`,o);return}finally{r.dispose()}}async getTurnCheckpointPair(e,t){let r=this._sessionDataService.openDatabase(e);try{let[o,s,a]=await Promise.all([r.object.getTurnCheckpointRef(t),r.object.getPreviousCheckpointRef(t),r.object.getMetadata(Qo)]);if(!o)return;let l=s??a;return l?{parent:l,current:o}:void 0}finally{r.dispose()}}async getBaselineCheckpointRef(e){let t=this._sessionDataService.openDatabase(e);try{return await t.object.getMetadata(Qo)}finally{t.dispose()}}async disposeSessionData(e){await this._sequencer.queue(e.toString(),()=>this._disposeSessionData(e))}async _disposeSessionData(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(t)try{let[r,o,s]=await Promise.all([t.object.getMetadata(vc),t.object.getMetadata(Qo),t.object.getAllCheckpointRefs()]);if(!r)return;let a=v.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{t.dispose()}}async _writeCheckpointCommit(e,t,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,t,r);if(a)return{commitOid:a}}async _nextTurnNumber(e){let t=await e.getAllCheckpointRefs(),r=0;for(let o of t){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 L.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};Da=w([C(0,Je),C(1,Ye),C(2,D)],Da);var eo=$("agentHostChangesetSubscriptionService");var Ma=$("agentHostChangesetOperationService");var to=$("agentHostReviewService");function Sc(i){return`refs/agents/${i}/reviewed`}function yg(i,n){return n==="branch"?di(i):li(i)}function q2(i){return i==="branch"?ua:tc}function CS(i){if(!i)return;let n=0,e=0;for(let t of i)n+=t.diff?.added??0,e+=t.diff?.removed??0;return{additions:n,deletions:e,files:i.length}}function B2(i){let n=i?.status==="ready"?i.files.map(e=>e.edit):void 0;return CS(n)}function z2(i){return CS(i)}function bS(i,n,e,t){if(i)try{return JSON.parse(i)}catch(r){t.warn(`[AgentHostChangesetService] Failed to parse persisted ${e} diffs for ${n}: ${ke(r)}`);return}}var ui=class extends T{constructor(e,t,r,o,s,a,l,d,c){super();this._stateManager=e;this._logService=t;this._sessionDataService=r;this._gitService=o;this._checkpointService=s;this._configurationService=a;this._changesetOperationService=l;this._changesetSubscriptions=d;this._reviewService=c;this._diffComputationSequencer=new at;this._debouncedDiffTimers=this._register(new Re);this._perTurnDebouncedDiffTimers=this._register(new Re);this._activeStaticComputes=new Set;this._pendingMaterialization=new Set;this._diffComputeService=this._register(new Zi(this._logService))}static{this._DIFF_DEBOUNCE_MS=5e3}_hasSubscription(e,t){return this._changesetSubscriptions.getSessionSubscriptions(e).has(t)}_hasWorkingDirectory(e){return!!this._configurationService.getEffectiveWorkingDirectory(e)}registerStaticChangesets(e){this._stateManager.registerChangeset(di(e)),this._stateManager.registerChangeset(Bi(e)),this._stateManager.registerChangeset(li(e))}restoreStaticChangeset(e,t,r){let o=this._stateManager.registerChangeset(yg(e,t));this._publishChangesetDiffs(e,o,r)}parsePersistedStaticChangesets(e,t){let r=bS(t.branchRaw,e,"branch",this._logService),o=bS(t.sessionRaw,e,"session",this._logService)??bS(t.legacyRaw,e,"session (legacy)",this._logService);return{branch:r,session:o}}applyPersistedStaticChangesets(e,t){this._seedIfEmpty(e,"branch",t.branch),this._seedIfEmpty(e,"session",t.session)}restorePersistedStaticChangesets(e,t){let r=this.parsePersistedStaticChangesets(e,t);return this.applyPersistedStaticChangesets(e,r),r}persistChangesSummary(e,t){this._persistSessionFlag(e,Yo,JSON.stringify(t))}getListMetadataKeys(e){if(!(this._stateManager.getSessionSummary(e)?.changes||this._stateManager.getChangesetState(li(e))?.status==="ready"))return gf}computeListEntryChanges(e,t){if(this._stateManager.getSessionState(e))return;let r=t[Yo];if(r!==void 0)try{return JSON.parse(r)}catch{return}let o=this._stateManager.getChangesetState(di(e)),s=B2(o);if(s)return this.persistChangesSummary(e,s),s;let a=t[ua],l=t[pa];if(a===void 0&&l===void 0)return;let d=this.parsePersistedStaticChangesets(e,{branchRaw:a,legacyRaw:l}),c=z2(d.branch);if(c)return this.persistChangesSummary(e,c),c}isStaticChangesetComputeActive(e){return this._activeStaticComputes.has(e)}_seedIfEmpty(e,t,r){if(!r)return;let o=this._stateManager.getChangesetState(yg(e,t));o&&o.files.length>0||this.restoreStaticChangeset(e,t,r)}refreshChangesetCatalog(e){let t=this._stateManager.getSessionState(e);if(t?.lifecycle!=="ready")return;let r=Tt(t?._meta),o=uw(e,r);this._stateManager.setSessionChangesets(e,o)}refreshBranchChangeset(e){if(!this._hasWorkingDirectory(e)){this._pendingMaterialization.add(e);return}this._scheduleStaticRecompute(e,"branch",void 0,this._markStaticChangesetComputing(e,"branch"))}refreshSessionChangeset(e){if(!this._hasWorkingDirectory(e)){this._pendingMaterialization.add(e);return}this._scheduleStaticRecompute(e,"session",void 0,this._markStaticChangesetComputing(e,"session"))}onWorkingDirectoryAvailable(e){this._pendingMaterialization.delete(e)&&this.recomputeSubscribedChangesets(e)}recomputeSubscribedChangesets(e){let t=this._changesetSubscriptions.getSessionSubscriptions(e);if(t.size!==0)for(let r of t){let o=et(r);switch(o?.kind){case"branch":this.refreshBranchChangeset(e);break;case"session":this.refreshSessionChangeset(e);break;case"uncommitted":this.computeUncommittedChangeset(e);break;case"turn":o.turnId!==void 0&&this.computeTurnChangeset(e,o.turnId);break;default:r===e&&(this.refreshBranchChangeset(e),this.refreshSessionChangeset(e));break}}}onSessionDisposed(e){this._pendingMaterialization.delete(e)}async computeTurnChangeset(e,t){let r=this._stateManager.registerChangeset(zp(e,t)),o;try{o=this._sessionDataService.openDatabase(v.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,t);this._publishChangesetDiffs(e,r,s)}catch(s){this._logService.warn(`[AgentHostChangesetService] Failed to compute turn diffs for ${e}/${t}`,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,t,r){let o=this._stateManager.registerChangeset(cw(e,t,r)),s;try{s=this._sessionDataService.openDatabase(v.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=v.parse(e),[l,d]=await Promise.all([this._checkpointService.getTurnCheckpointPair(a,t).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}/${t}/${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 t=this._stateManager.registerChangeset(Bi(e));if(!this._hasSubscription(e,t))return t;if(!this._hasWorkingDirectory(e))return this._pendingMaterialization.add(e),t;this._stateManager.getChangesetState(t)?.status!=="computing"&&this._stateManager.dispatchServerAction(t,{type:"changeset/statusChanged",status:"computing"});try{let o=await this._computeUncommittedDiffs(e);if(o===void 0)return this._stateManager.dispatchServerAction(t,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:"Failed to compute uncommitted diff from git."}}),t;this._publishChangesetDiffs(e,t,o)}catch(o){this._logService.warn(`[AgentHostChangesetService] Failed to compute uncommitted diffs for ${e}`,o),this._stateManager.dispatchServerAction(t,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:o instanceof Error?o.message:String(o)}})}return t}async _computeUncommittedDiffs(e){let t=this._stateManager.getSessionState(e)?.workingDirectory;if(!t)return;let r;try{r=v.parse(t)}catch{return}return this._gitService.computeSessionFileDiffs(r,{sessionUri:e})}async _computeTurnDiffsPreferCheckpoint(e,t,r){let o=await this._checkpointService.getTurnCheckpointPair(v.parse(e),r);if(o&&o.parent!==o.current){let s=await this._resolveWorkingDirectory(t);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 mx(e,t,this._diffComputeService,r)}async _resolveWorkingDirectory(e){let t=await e.getMetadata(vc);return t?v.parse(t):void 0}onToolCallEditsApplied(e,t){this._scheduleDebouncedDiffComputation(e,t),this._hasSubscription(e,zp(e,t))&&this._scheduleDebouncedTurnDiffComputation(e,t)}onTurnComplete(e,t){this._cancelDebouncedDiffComputation(e),t!==void 0&&(this._cancelDebouncedTurnDiffComputation(e,t),this._hasSubscription(e,zp(e,t))&&this._scheduleTurnRecompute(e,t)),this._hasSubscription(e,Bi(e))&&this._scheduleUncommittedRecompute(e),this._scheduleStaticRecompute(e,"branch",t),this._scheduleStaticRecompute(e,"session",t)}onSessionTruncated(e){this._scheduleStaticRecompute(e,"branch"),this._scheduleStaticRecompute(e,"session")}_scheduleDebouncedDiffComputation(e,t){this._debouncedDiffTimers.set(e,Kt(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._scheduleStaticRecompute(e,"branch",t),this._scheduleStaticRecompute(e,"session",t)},ui._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_scheduleDebouncedTurnDiffComputation(e,t){let r=`${e}\0${t}`;this._perTurnDebouncedDiffTimers.set(r,Kt(()=>{this._perTurnDebouncedDiffTimers.deleteAndDispose(r),this._scheduleTurnRecompute(e,t)},ui._DIFF_DEBOUNCE_MS))}_cancelDebouncedTurnDiffComputation(e,t){this._perTurnDebouncedDiffTimers.deleteAndDispose(`${e}\0${t}`)}_scheduleTurnRecompute(e,t){this._diffComputationSequencer.queue(`${e}\0turn\0${t}`,()=>this.computeTurnChangeset(e,t).then(()=>{}))}_scheduleUncommittedRecompute(e){this._diffComputationSequencer.queue(`${e}\0uncommitted`,()=>this.computeUncommittedChangeset(e).then(()=>{}))}_scheduleStaticRecompute(e,t,r,o){this._diffComputationSequencer.queue(`${e}\0${t}`,()=>this._doComputeStaticChangeset(e,t,r,o))}_markStaticChangesetComputing(e,t){let r=yg(e,t);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,t,r,o){let s=yg(e,t);this._activeStaticComputes.add(s);let a=o??this._stateManager.getChangesetState(s)?.status,l;try{l=this._sessionDataService.openDatabase(v.parse(e))}catch(d){this._logService.warn(`[AgentHostChangesetService] Failed to open session database for ${t} 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,t);if(!d){if(t==="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 u=this._openPeerChatSources(e);try{if(u.length>0){let p=[{sessionUri:e,db:l.object},...u.map(m=>({sessionUri:m.sessionUri,db:m.ref.object}))];d=await SS(p,this._diffComputeService)}else{let p;if(r){let m=this._readPreviousChangesetDiffs(s);m&&(p={changedTurnId:r,previousDiffs:[...m]})}d=await gx(e,l.object,this._diffComputeService,p)}}finally{for(let p of u)p.ref.dispose()}}let c=t==="branch"?await this._computeReviewedInfo(e,l.object):void 0;if(this._publishChangesetDiffs(e,s,d,c),this._persistSessionFlag(e,q2(t),JSON.stringify(d)),t==="branch"){this._persistSessionFlag(e,pa,JSON.stringify(d));let u=CS(d)??{additions:0,deletions:0,files:0};this.persistChangesSummary(e,u),this._stateManager.setSessionSummaryChanges(e,u)}}catch(d){this._logService.warn(`[AgentHostChangesetService] Failed to compute ${t} 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,t){!t||t==="computing"||this._stateManager.dispatchServerAction(e,{type:"changeset/statusChanged",status:t})}_readPreviousChangesetDiffs(e){let t=this._stateManager.getChangesetState(e);if(!(!t||t.files.length===0))return t.files.map(r=>r.edit)}_publishChangesetDiffs(e,t,r,o){let s=this._changesetOperationService.getOperations(e,t),a=[];for(let d of r){let c=d.after?.uri??d.before?.uri;if(c)if(o){let u=Gr(o.repoRoot,v.parse(c));a.push({id:c,edit:d,_meta:{reviewed:u?o.paths.has(u):!1}})}else a.push({id:c,edit:d})}this._stateManager.dispatchServerAction(t,{type:"changeset/contentChanged",files:a,operations:s?[...s]:void 0}),this._stateManager.getChangesetState(t)?.status!=="ready"&&this._stateManager.dispatchServerAction(t,{type:"changeset/statusChanged",status:"ready"})}_openPeerChatSources(e){let t=this._stateManager.getSessionState(e)?.chats??[],r=[];for(let o of t)if(!Ue(o.resource))try{let s=this._sessionDataService.openDatabase(v.parse(o.resource));r.push({sessionUri:o.resource,ref:s})}catch(s){this._logService.warn(`[AgentHostChangesetService] Failed to open peer chat database for session changes: ${o.resource}`,s)}return r}_latestTurnIdAcrossChats(e){let t=this._stateManager.getSessionState(e);if(!t)return;let r=t.chats??[];if(r.length<=1)return t.turns.at(-1)?.id;let o,s="";for(let a of r){let d=(Ue(a.resource)?t.turns:this._stateManager.getChatState(a.resource)?.turns)?.at(-1)?.id;d&&a.modifiedAt>=s&&(s=a.modifiedAt,o=d)}return o}async _tryComputeGitDiffs(e,t,r){let o=this._stateManager.getSessionState(e)?.workingDirectory;if(!o)return;let s;try{s=v.parse(o)}catch{return}if(r==="session"){let l=this._latestTurnIdAcrossChats(e);if(!l)return;let d=v.parse(e),[c,u]=await Promise.all([this._checkpointService.getBaselineCheckpointRef(d),this._checkpointService.getTurnCheckpointPair(d,l)]);if(!c||!u)return;try{return await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:e,fromRef:c,toRef:u.current})}catch(p){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,p);return}}let a=await this._resolveBranchBaseBranch(e,t);try{return await this._gitService.computeSessionFileDiffs(s,{sessionUri:e,baseBranch:a})}catch(l){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,l);return}}async _resolveBranchBaseBranch(e,t){let r=await t.getMetadata(ca),o=Tt(this._stateManager.getSessionState(e)?._meta)?.baseBranchName;return!r&&o&&this._logService.debug(`[AgentHostChangesetService] Using _meta.git base branch fallback for Branch Changes in ${e}: ${o}`),ff(r,o)}async _computeReviewedInfo(e,t){let r=this._stateManager.getSessionState(e)?.workingDirectory;if(!r)return;let o;try{o=v.parse(r)}catch{return}let s=await this._gitService.getRepositoryRoot(o);if(!s)return;let a=await this._resolveBranchBaseBranch(e,t),l=await this._reviewService.getReviewedPaths(e,o,a);return{repoRoot:s,paths:l}}_persistSessionFlag(e,t,r){let o=this._sessionDataService.openDatabase(v.parse(e));o.object.setMetadata(t,r).catch(s=>{this._logService.warn(`[AgentHostChangesetService] Failed to persist ${t}`,s)}).finally(()=>{o.dispose()})}};ui=w([C(1,D),C(2,Je),C(3,Ye),C(4,_r),C(5,ze),C(6,Ma),C(7,eo),C(8,to)],ui);var Oa=$("agentHostFileMonitorService"),IS=Object.freeze(["**/.git","**/.git/lfs/**","**/.git/logs/**","**/.git/objects/**","**/.git/subtree-cache/**","**/.git/**/*.lock","**/.git/**/FETCH_HEAD","**/.git/**/fsmonitor--daemon/**","**/*.watchman-cookie-*"]);function V2(i){return[...i].sort()}function j2(i){let n=Object.create(null);for(let e of i)n[e]=!0;return Qi(n)}var xr=class extends T{constructor(e,t){super();this._fileService=e;this._logService=t;this._entries=this._register(new Re);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,t,r={}){let o=this._canonicalizeFolder(e),s=V2(r.excludes??IS),a=r.debounceMs??xr._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(t),M(()=>{let c=this._entries.get(l);c&&(c.callbacks.delete(t),c.callbacks.size===0&&this._entries.deleteAndDispose(l))})}_createEntry(e,t,r,o){let s=new G;try{let a=s.add(new At),l=new Set,d=j2(r);return s.add(this._fileService.watch(t,{recursive:!0,excludes:[...r]})),{folder:t,callbacks:l,debounce:a,debounceMs:o,excludeMatcher:d,dispose:()=>s.dispose()}}catch(a){throw s.dispose(),a}}_onDidFilesChange(e){for(let t of this._entries.keys())this._onDidFilesChangeEntry(t,e)}_onDidFilesChangeEntry(e,t){let r=this._entries.get(e);!r||r.callbacks.size===0||!t.affects(r.folder)||!this._hasRelevantRawChange(r,t)||(r.debounce.value=Kt(()=>{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,t){return this._hasRelevantRawResources(e,t.rawAdded)||this._hasRelevantRawResources(e,t.rawUpdated)||this._hasRelevantRawResources(e,t.rawDeleted)}_hasRelevantRawResources(e,t){for(let r of t)if(rt.isEqualOrParent(r,e.folder)&&!this._isExcluded(e,r))return!0;return!1}_isExcluded(e,t){let r=rt.basename(t),o=rt.relativePath(e.folder,t);return o!==void 0&&this._matchesExclude(e,o,r)?!0:this._matchesExclude(e,t.path,r)}_matchesExclude(e,t,r){return typeof e.excludeMatcher(t,r)=="string"}_canonicalizeFolder(e){return rt.removeTrailingPathSeparator(rt.normalizePath(e))}_key(e,t,r){return`${rt.getComparisonKey(e)}\0${r}\0${t.join(`
`)}`}};xr=w([C(0,xe),C(1,D)],xr);var no="agentHost.git",ro="agentHost.github",vg={[no]:!0,[ro]:!0},Pr=$("agentHostGitStateService");var _S=class extends Ss{constructor(e,t){super();this._create=e;this._destroy=t}createReferencedObject(e){return this._create(e),e}destroyReferencedObject(e){this._destroy(e)}},La=class extends T{constructor(e,t,r,o,s,a){super();this._stateManager=e;this._configurationService=t;this._fileMonitorService=r;this._gitService=o;this._gitStateService=s;this._logService=a;this._watchInterestReferences=this._register(new Re);this._watchInterestCollection=new _S(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 Re);this._rootUris=new Map;this._activeSessionRoots=new Map;this._rootActiveSessions=new Map;this._unresolvedActiveSessions=new Set;this._watchAttachmentSequencer=new at;this._activeTurnSequencer=new at}trackSessionChanges(e,t){this._watchInterestReferences.has(e)||this._watchInterestReferences.set(e,this._watchInterestCollection.acquire(t))}untrackSessionChanges(e){this._watchInterestReferences.deleteAndDispose(e)}onSessionRestored(e){this._retryWatchAttachment(e)}onSessionMaterialized(e){this._retryWatchAttachment(e)}onSessionDisposed(e){this.untrackSessionChanges(Bi(e)),this.untrackSessionChanges(li(e)),this.untrackSessionChanges(e),this._removeActiveSession(e),this._destroyWatchInterest(e)}onSessionTurnActiveChanged(e,t){this._activeTurnSequencer.queue(e,async()=>{t?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(di(e))||this._watchInterestReferences.has(Bi(e))||this._watchInterestReferences.has(li(e))}_attachWatcherIfPossible(e){this._watchAttachmentSequencer.queue(e,async()=>{if(!this._shouldAttachSession(e))return;let t=this._configurationService.getEffectiveWorkingDirectory(e);if(!t){this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}let r;try{r=v.parse(t)}catch(s){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse working directory URI for ${e}: ${t}`,s),this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}if(this._sessionRoot.has(e)&&this._sessionWorkingDirectory.get(e)===t){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,t)}})}_attachSessionToRoot(e,t,r){let o=t.toString();if(this._sessionRoot.get(e)===o){this._sessionWorkingDirectory.set(e,r),this._ensureRootWatcher(o,t);return}this._releaseSessionRoot(e);let s=this._rootSessions.get(o);s||(s=new Set,this._rootSessions.set(o,s),this._rootUris.set(o,t)),s.add(e),this._sessionRoot.set(e,o),this._sessionWorkingDirectory.set(e,r),this._ensureRootWatcher(o,t)}_releaseSessionRoot(e){let t=this._sessionRoot.get(e);if(!t){this._sessionWorkingDirectory.delete(e);return}this._sessionRoot.delete(e),this._sessionWorkingDirectory.delete(e);let r=this._rootSessions.get(t);r&&(r.delete(e),r.size===0&&(this._rootSessions.delete(t),this._rootUris.delete(t),this._rootWatchAcquisitions.deleteAndDispose(t)))}_onRootChanged(e){if(this._isRootActive(e))return;let t=this._rootSessions.get(e);if(!t||t.size===0)return;let r=[...t].filter(s=>this._hasWatchInterest(s)&&this._sessionRoot.get(s)===e&&!this._activeSessionRoots.has(s)&&!this._unresolvedActiveSessions.has(s)&&!!this._stateManager.getSessionState(s));if(r.length===0)return;let o=v.parse(e);for(let s of r)this._gitStateService.refreshSessionGitState(s,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,t){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(t,()=>this._onRootChanged(e),{excludes:IS,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 t=await this._resolveActivityRepositoryRoot(e);if(!t){this._unresolvedActiveSessions.add(e),this._releaseSessionRoot(e);return}let r=t.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,t),this._suspendRootWatcher(r),this._sessionRoot.get(e)!==r&&this._releaseSessionRoot(e)}_markSessionInactive(e){let t=this._removeActiveSession(e);if(t){let r=this._rootUris.get(t);r&&this._ensureRootWatcher(t,r)}(this._hasWatchInterest(e)||this._pendingWatchInterest.has(e))&&this._attachWatcherIfPossible(e)}_removeActiveSession(e){this._unresolvedActiveSessions.delete(e);let t=this._activeSessionRoots.get(e);if(!t)return;this._activeSessionRoots.delete(e);let r=this._rootActiveSessions.get(t);return r&&(r.delete(e),r.size===0&&this._rootActiveSessions.delete(t)),t}async _resolveActivityRepositoryRoot(e){let t=this._getActivityWorkingDirectory(e);if(!t)return;let r;try{r=v.parse(t)}catch(o){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse active working directory URI for ${e}: ${t}`,o);return}return this._gitService.getRepositoryRoot(r)}_getActivityWorkingDirectory(e){let t=this._configurationService.getEffectiveWorkingDirectory(e);if(t)return t;let r=gt(e);if(r)return this._configurationService.getEffectiveWorkingDirectory(r.parentSession.toString())}};La=w([C(1,ze),C(2,Oa),C(3,Ye),C(4,Pr),C(5,D)],La);var Na=class extends T{constructor(e,t,r,o,s,a){super();this._stateManager=e;this._changesetOperationService=t;this._changesets=r;this._changesetSubscriptions=o;this._changesetFileMonitor=this._register(a.createInstance(La,this._stateManager)),this._register(s.onDidRefreshSessionGitState(l=>this.onDidRunSessionGitStateRefresh(l)))}onSessionCreated(e){this._changesets.refreshChangesetCatalog(e),this._changesets.registerStaticChangesets(e)}onSessionRestored(e,t){this._changesets.refreshChangesetCatalog(e),this._changesets.registerStaticChangesets(e),this._changesets.restorePersistedStaticChangesets(e,{branchRaw:t[ua],sessionRaw:t[tc],legacyRaw:t[pa]}),this._changesets.onWorkingDirectoryAvailable(e),this._changesetFileMonitor.onSessionRestored(e)}onSessionMaterialized(e){this._changesets.refreshChangesetCatalog(e),this._changesets.onWorkingDirectoryAvailable(e),this._changesetFileMonitor.onSessionMaterialized(e)}onSessionDisposed(e){this._changesets.onSessionDisposed(e),this._changesetFileMonitor.onSessionDisposed(e),this._changesetSubscriptions.clearSessionSubscriptions(e)}onSessionTurnActiveChanged(e,t){this._changesetFileMonitor.onSessionTurnActiveChanged(e,t),this._changesetOperationService.updateOperations(e)}onFirstSubscriber(e){let t=e.toString(),r=et(t);if(!r&&!ce(t)&&this._stateManager.getSessionState(t)){this._addSubscription(t,di(t)),this._changesets.refreshBranchChangeset(t),this._changesetFileMonitor.trackSessionChanges(t,t);return}if(r?.kind==="branch"){this._addSubscription(r.sessionUri,t),this._changesets.refreshBranchChangeset(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(t,r.sessionUri);return}if(r?.kind==="uncommitted"){this._addSubscription(r.sessionUri,t),this._changesets.computeUncommittedChangeset(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(t,r.sessionUri);return}if(r?.kind==="session"){this._addSubscription(r.sessionUri,t),this._changesets.refreshSessionChangeset(r.sessionUri),this._changesetFileMonitor.trackSessionChanges(t,r.sessionUri);return}if(r?.kind==="turn"&&r.turnId!==void 0){this._addSubscription(r.sessionUri,t);return}}onLastSubscriber(e){let t=e.toString(),r=et(t);if(r?.kind==="branch"){this._removeSubscription(r.sessionUri,t),this._changesetFileMonitor.untrackSessionChanges(t);return}if(r?.kind==="uncommitted"){this._removeSubscription(r.sessionUri,t),this._changesetFileMonitor.untrackSessionChanges(t);return}if(r?.kind==="session"){this._removeSubscription(r.sessionUri,t),this._changesetFileMonitor.untrackSessionChanges(t);return}if(r?.kind==="turn"&&r.turnId!==void 0){this._removeSubscription(r.sessionUri,t);return}r||(this._removeSubscription(t,t),this._changesetFileMonitor.untrackSessionChanges(t))}async restoreSessionIfChangesetSubscription(e,t){let r=e.toString(),o=et(r);if(o){if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);this._stateManager.getSessionState(o.sessionUri)||await t(v.parse(o.sessionUri))}}async tryHandleSubscribe(e,t){let r=e.toString(),o=et(r);if(!o)return!1;if(o.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);return await this.restoreSessionIfChangesetSubscription(e,t),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}_addSubscription(e,t){this._changesetSubscriptions.addSubscription(e,t)}_removeSubscription(e,t){this._changesetSubscriptions.removeSubscription(e,t)}getListMetadataKeys(e){return this._changesets.getListMetadataKeys(e)}decorateListEntry(e,t){let r=this._changesets.computeListEntryChanges(e.session.toString(),t);return r?{...e,changes:r}:e}onDidRunSessionGitStateRefresh(e){this._changesets.refreshChangesetCatalog(e),this._changesets.recomputeSubscribedChangesets(e)}};Na=w([C(1,Ma),C(2,ji),C(3,eo),C(4,Pr),C(5,Ie)],Na);var K2=60,G2=K2*60,TS=G2*24,Dae=TS*7,Mae=TS*30,Oae=TS*365;function hx(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 Sg={DateTimeFormat(i,n){return new qe(()=>{try{return new Intl.DateTimeFormat(i,n)}catch{return new Intl.DateTimeFormat(void 0,n)}})},Collator(i,n){return new qe(()=>{try{return new Intl.Collator(i,n)}catch{return new Intl.Collator(void 0,n)}})},Segmenter(i,n){return new qe(()=>{try{return new Intl.Segmenter(i,n)}catch{return new Intl.Segmenter(void 0,n)}})},Locale(i,n){return new qe(()=>{try{return new Intl.Locale(i,n)}catch{return new Intl.Locale(wi,n)}})},NumberFormat(i,n){return new qe(()=>{try{return new Intl.NumberFormat(i,n)}catch{return new Intl.NumberFormat(void 0,n)}})}};var yx=new qe(()=>{let i=Sg.Collator(void 0,{numeric:!0,sensitivity:"base"}).value;return{collator:i,collatorIsNumeric:i.resolvedOptions().numeric}}),Hae=new qe(()=>({collator:Sg.Collator(void 0,{numeric:!0}).value})),$ae=new qe(()=>({collator:Sg.Collator(void 0,{numeric:!0,sensitivity:"accent"}).value}));function J2(i,n,e=!1){let t=i||"",r=n||"",o=yx.value.collator.compare(t,r);return yx.value.collatorIsNumeric&&o===0&&t!==r?t<r?-1:1:o}function bg(i,n,e){let t=i.toLowerCase(),r=n.toLowerCase(),o=Y2(i,n,e);if(o)return o;let s=t.endsWith(e),a=r.endsWith(e);if(s!==a)return s?-1:1;let l=J2(t,r);return l!==0?l:t.localeCompare(r)}function Y2(i,n,e){let t=i.toLowerCase(),r=n.toLowerCase(),o=t.startsWith(e),s=r.startsWith(e);if(o!==s)return o?-1:1;if(o&&s){if(t.length<r.length)return-1;if(t.length>r.length)return 1}return 0}var qae=new Uint32Array(10);var Bae=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),zae=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),Vae=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]),jae=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 Sx(...i){return function(n,e){for(let t=0,r=i.length;t<r;t++){let o=i[t](n,e);if(o)return o}return null}}var tle=bx.bind(void 0,!1),Ig=bx.bind(void 0,!0);function bx(i,n,e){if(!e||e.length<n.length)return null;let t;return i?t=Pi(e,n):t=e.indexOf(n)===0,t?n.length>0?[{start:0,end:n.length}]:[]:null}function Q2(i,n){if(i.length>n.length)return null;let e=n.toLowerCase().indexOf(i.toLowerCase());return e===-1?null:[{start:e,end:e+i.length}]}function X2(i,n){return i.length>n.length?null:wS(i.toLowerCase(),n.toLowerCase(),0,0)}function wS(i,n,e,t){if(e===i.length)return[];if(t===n.length)return null;if(i[e]===n[t]){let r=null;return(r=wS(i,n,e+1,t+1))?Ix({start:t,end:t+1},r):null}return wS(i,n,e,t+1)}function xS(i){return 97<=i&&i<=122}function Ua(i){return 65<=i&&i<=90}function PS(i){return 48<=i&&i<=57}function Z2(i){return i===32||i===9||i===10||i===13}var eN=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(i=>eN.add(i.charCodeAt(0)));function Cx(i){return xS(i)||Ua(i)||PS(i)}function Ix(i,n){return n.length===0?n=[i]:i.end===n[0].start?n[0].start=i.start:n.unshift(i),n}function _x(i,n){for(let e=n;e<i.length;e++){let t=i.charCodeAt(e);if(Ua(t)||PS(t)||e>0&&!Cx(i.charCodeAt(e-1)))return e}return i.length}function RS(i,n,e,t){if(e===i.length)return[];if(t===n.length)return null;if(i[e]!==n[t].toLowerCase())return null;{let r=null,o=t+1;for(r=RS(i,n,e+1,t+1);!r&&(o=_x(n,o))<n.length;)r=RS(i,n,e+1,o),o++;return r===null?null:Ix({start:t,end:t+1},r)}}function tN(i){let n=0,e=0,t=0,r=0,o=0;for(let c=0;c<i.length;c++)o=i.charCodeAt(c),Ua(o)&&n++,xS(o)&&e++,Cx(o)&&t++,PS(o)&&r++;let s=n/i.length,a=e/i.length,l=t/i.length,d=r/i.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:d}}function nN(i){let{upperPercent:n,lowerPercent:e}=i;return e===0&&n>.6}function rN(i){let{upperPercent:n,lowerPercent:e,alphaPercent:t,numericPercent:r}=i;return e>.2&&n<.8&&t>.6&&r<.2}function iN(i){let n=0,e=0,t=0,r=0;for(let o=0;o<i.length;o++)t=i.charCodeAt(o),Ua(t)&&n++,xS(t)&&e++,Z2(t)&&r++;return(n===0||e===0)&&r===0?i.length<=30:n<=5}function Tx(i,n){if(!n||(n=n.trim(),n.length===0)||!iN(i))return null;n.length>60&&(n=n.substring(0,60));let e=tN(n);if(!rN(e)){if(!nN(e))return null;n=n.toLowerCase()}let t=null,r=0;for(i=i.toLowerCase();r<n.length&&(t=RS(i,n,0,r))===null;)r=_x(n,r+1);return t}var nle=Sx(Ig,Tx,Q2),rle=Sx(Ig,Tx,X2),ile=new sn(1e4);var Cg=128;function AS(){let i=[],n=[];for(let e=0;e<=Cg;e++)n[e]=0;for(let e=0;e<=Cg;e++)i.push(n.slice(0));return i}function wx(i){let n=[];for(let e=0;e<=i;e++)n[e]=0;return n}var ole=wx(2*Cg),sle=wx(2*Cg),ale=AS(),lle=AS(),dle=AS();var oN;(e=>{e.Default=[-100,0];function n(t){return!t||t.length===2&&t[0]===-100&&t[1]===0}e.isDefault=n})(oN||={});var vx=class{constructor(n,e){this.firstMatchCanBeWeak=n;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var Tg=0,Rx=[Tg,[]];function xx(i,n,e,t){if(!i||!n)return Rx;let r=i.length,o=n.length;if(r<o)return Rx;let s=i.toLowerCase();return sN(n,e,o,i,s,r,t)}function sN(i,n,e,t,r,o,s){let a=[],l=[];for(let p=0;p<e;p++){let m=p*o,h=m-o,y=p>0,S=i[p],b=n[p];for(let I=0;I<o;I++){let _=I>0,R=m+I,A=R-1,X=h+I-1,E=_?a[A]:0,z=y&&_?a[X]:0,x=y&&_?l[X]:0,B;!z&&y?B=0:B=aN(S,b,t,r,I,x),B&&z+B>=E&&(s||y||r.startsWith(n,I))?(l[R]=x+1,a[R]=z+B):(l[R]=Tg,a[R]=E)}}let d=[],c=e-1,u=o-1;for(;c>=0&&u>=0;){let p=c*o+u;l[p]===Tg||(d.push(u),c--),u--}return[a[e*o-1],d.reverse()]}function aN(i,n,e,t,r,o){let s=0;if(!lN(n,t[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=dN(e.charCodeAt(r-1));a?s+=a:Ua(e.charCodeAt(r))&&o===0&&(s+=2)}return s}function lN(i,n){return i===n?!0:i==="/"||i==="\\"?n==="/"||n==="\\":!1}function dN(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 wg=Object.freeze({score:0}),_g=1<<18,ES=1<<17,kS=65536;function cN(i,n,e,t){let r=t.values?t.values:[t];return br({[t.normalized]:{values:r.map(s=>({value:s.normalized,expectContiguousMatch:s.expectContiguousMatch})),label:i,description:n,allowNonContiguousMatches:e}})}function Rg(i,n,e,t,r){if(!i||!n.normalized)return wg;let o=t.getItemLabel(i);if(!o)return wg;let s=t.getItemDescription(i),a=cN(o,s,e,n),l=r[a];if(l)return l;let d=uN(o,s,t.getItemPath(i),n,e);return r[a]=d,d}function uN(i,n,e,t,r){let o=!e||!t.containsPathSeparator;return e&&(Oe?t.pathNormalized===e:zr(t.pathNormalized,e))?{score:_g,labelMatch:[{start:0,end:i.length}],descriptionMatch:n?[{start:0,end:n.length}]:void 0}:t.values&&t.values.length>1?pN(i,n,e,t.values,o,r):Mx(i,n,e,t,o,r)}function pN(i,n,e,t,r,o){let s=0,a=[],l=[];for(let d of t){let{score:c,labelMatch:u,descriptionMatch:p}=Mx(i,n,e,d,r,o);if(c===Tg)return wg;s+=c,u&&a.push(...u),p&&l.push(...p)}return{score:s,labelMatch:Ax(a),descriptionMatch:Ax(l)}}function Mx(i,n,e,t,r,o){if(r||!n){let[s,a]=xx(i,t.normalized,t.normalizedLowercase,o&&!t.expectContiguousMatch);if(s){let l=Ig(t.normalized,i),d;if(l){d=ES;let c=Math.round(t.normalized.length/i.length*100);d+=c}else d=kS;return{score:d+s,labelMatch:l||Px(a)}}}if(n){let s=n;e&&(s=`${n}${Le}`);let a=s.length,l=`${s}${i}`,[d,c]=xx(l,t.normalized,t.normalizedLowercase,o&&!t.expectContiguousMatch);if(d){let u=Px(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 wg}function Px(i){let n=[];if(!i)return n;let e;for(let t of i)e&&e.end===t?e.end+=1:(e={start:t,end:t+1},n.push(e));return n}function Ax(i){let n=i.sort((r,o)=>r.start-o.start),e=[],t;for(let r of n)!t||!fN(t,r)?(t=r,e.push(r)):(t.start=Math.min(t.start,r.start),t.end=Math.max(t.end,r.end));return e}function fN(i,n){return!(i.end<n.start||n.end<i.start)}function Ox(i,n,e,t,r,o){let s=Rg(i,e,t,r,o),a=Rg(n,e,t,r,o),l=s.score,d=a.score;if((l===_g||d===_g)&&l!==d)return l===_g?-1:1;if(l>kS||d>kS){if(l!==d)return l>d?-1:1;if(l<ES&&d<ES){let S=gN(s.labelMatch,a.labelMatch);if(S!==0)return S}let h=r.getItemLabel(i)||"",y=r.getItemLabel(n)||"";if(h.length!==y.length)return h.length-y.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=Ex(i,s,r),m=Ex(n,a,r);return p&&m&&p!==m?m>p?-1:1:mN(i,n,e,r)}function Ex(i,n,e){let t=-1,r=-1;if(n.descriptionMatch?.length?t=n.descriptionMatch[0].start:n.labelMatch?.length&&(t=n.labelMatch[0].start),n.labelMatch?.length){if(r=n.labelMatch[n.labelMatch.length-1].end,n.descriptionMatch?.length){let o=e.getItemDescription(i);o&&(r+=o.length)}}else n.descriptionMatch?.length&&(r=n.descriptionMatch[n.descriptionMatch.length-1].end);return r-t}function gN(i,n){if(!i&&!n||!i?.length&&!n?.length)return 0;if(!n?.length)return-1;if(!i?.length)return 1;let e=i[0].start,r=i[i.length-1].end-e,o=n[0].start,a=n[n.length-1].end-o;return r===a?0:a<r?1:-1}function mN(i,n,e,t){let r=t.getItemLabel(i)||"",o=t.getItemLabel(n)||"",s=t.getItemDescription(i),a=t.getItemDescription(n),l=r.length+(s?s.length:0),d=o.length+(a?a.length:0);if(l!==d)return l-d;let c=t.getItemPath(i),u=t.getItemPath(n);return c&&u&&c.length!==u.length?c.length-u.length:r!==o?bg(r,o,e.normalized):s&&a&&s!==a?bg(s,a,e.normalized):c&&u&&c!==u?bg(c,u,e.normalized):0}function kx(i){return i.startsWith('"')&&i.endsWith('"')}var hN=" ";function Lx(i){typeof i!="string"&&(i="");let n=i.toLowerCase(),{pathNormalized:e,normalized:t,normalizedLowercase:r}=Dx(i),o=e.indexOf(Le)>=0,s=kx(i),a,l=i.split(hN);if(l.length>1)for(let d of l){let c=kx(d),{pathNormalized:u,normalized:p,normalizedLowercase:m}=Dx(d);p&&(a||(a=[]),a.push({original:d,originalLowercase:d.toLowerCase(),pathNormalized:u,normalized:p,normalizedLowercase:m,expectContiguousMatch:c}))}return{original:i,originalLowercase:n,pathNormalized:e,normalized:t,normalizedLowercase:r,values:a,containsPathSeparator:o,expectContiguousMatch:s}}function Dx(i){let n;Q?n=i.replace(/\//g,Le):n=i.replace(/\\/g,Le);let e=n.replace(/[\*\u2026\s"]/g,"").replace(/(?<=.)#$/,"");return{pathNormalized:n,normalized:e,normalizedLowercase:e.toLowerCase()}}var Nx=50;function yN(i,n){if(!(n<0||n>i.length))for(let e=n-1;e>=0;e--){let t=i.charCodeAt(e);if(t===32||t===9||t===10||t===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,n),triggerChar:i[e],rangeStart:e,rangeEnd:n}}}}var DS=class{constructor(n){this._workingDirectory=n}getItemLabel(n){return pe(n)}getItemDescription(n){let e=Gr(this._workingDirectory,n);if(!e)return;let t=e.lastIndexOf("/");return t>0?e.slice(0,t):void 0}getItemPath(n){return Gr(this._workingDirectory,n)??n.fsPath}},xg=class{constructor(n,e){this._stateManager=n;this._workspaceFiles=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["@","#"]}async provideCompletionItems(n,e){let t=this._stateManager.getSessionState(n.channel)?.workingDirectory;if(!t)return[];let r=v.parse(t);if(r.scheme!==ie.file)return[];let o=yN(n.text,n.offset);if(!o)return[];let s;try{s=await this._workspaceFiles.getFiles(r,e)}catch(u){if(Kn(u))return[];throw u}if(e.isCancellationRequested||s.length===0)return[];let a=new DS(r),l=Lx(o.token),d=Object.create(null),c;if(!l.normalized)c=s.slice(0,Nx);else{let u=s.filter(p=>Rg(p,l,!0,a,d).score>0);u.sort((p,m)=>Ox(p,m,l,!0,a,d)),c=u.slice(0,Nx)}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 Cc=class{constructor(n){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n}},io=class{constructor(n){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n,this.entries=new Map}},Fa=class extends T{constructor(){super(...arguments);this.memoryFdCounter=0;this.fdMemory=new Map;this._onDidChangeCapabilities=this._register(new P);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._capabilities=525318;this.root=new io("");this._onDidChangeFile=this._register(new P);this.onDidChangeFile=this._onDidChangeFile.event;this._bufferedChanges=[]}get capabilities(){return this._capabilities}setReadOnly(e){let t=!!(this._capabilities&2048);e!==t&&(this._capabilities=525314|(e?2048:0),this._onDidChangeCapabilities.fire())}async stat(e){return this._lookup(e,!1)}async readdir(e){let t=this._lookupAsDirectory(e,!1),r=[];return t.entries.forEach((o,s)=>r.push([s,o.type])),r}async readFile(e){let t=this._lookupAsFile(e,!1).data;if(t)return t;throw De("file not found","EntryNotFound")}readFileStream(e){let t=this._lookupAsFile(e,!1).data,r=Jr(o=>U.concat(o.map(s=>U.wrap(s))).buffer);return r.end(t),r}async writeFile(e,t,r){let o=pe(e),s=this._lookupParentDirectory(e),a=s.entries.get(o);if(a instanceof io)throw De("file is directory","EntryIsADirectory");if(!a&&!r.create)throw De("file not found","EntryNotFound");if(a&&r.create&&!r.overwrite)throw De("file exists already","EntryExists");if(a||(a=new Cc(o),s.entries.set(o,a),this._fireSoon({type:1,resource:e})),a.mtime=Date.now(),r.append){a.size+=t.byteLength;let l=a.data??new Uint8Array(0),d=new Uint8Array(l.byteLength+t.byteLength);d.set(l,0),d.set(t,l.byteLength),a.data=d}else a.size=t.byteLength,a.data=t;this._fireSoon({type:0,resource:e})}open(e,t){let r=this._lookup(e,!0),o=ti(t),s=o&&!!t.append;if(r){if(r instanceof io)throw De("file is directory","EntryIsADirectory")}else{if(!o)throw De("file not found","EntryNotFound");let l=pe(e),d=this._lookupParentDirectory(e);r=new Cc(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 t=this.fdMemory.get(e);return t?.write&&(t.file.mtime=Date.now(),t.file.size=t.file.data?.byteLength??0,this._fireSoon({type:0,resource:t.resource})),this.fdMemory.delete(e),Promise.resolve()}read(e,t,r,o,s){let a=this.fdMemory.get(e);if(!a)throw De("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=U.wrap(a.file.data).slice(t,t+s);return r.set(l.buffer,o),Promise.resolve(l.byteLength)}write(e,t,r,o,s){let a=this.fdMemory.get(e);if(!a)throw De("No file with that descriptor open","Unavailable");let l=U.wrap(r).slice(o,o+s);a.file.data??=new Uint8Array(0);let d=a.append?a.file.data.byteLength:t,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,t,r){if(!r.overwrite&&this._lookup(t,!0))throw De("file exists already","EntryExists");let o=this._lookup(e,!1),s=this._lookupParentDirectory(e),a=this._lookupParentDirectory(t),l=pe(t);s.entries.delete(o.name),o.name=l,a.entries.set(l,o),this._fireSoon({type:2,resource:e},{type:1,resource:t})}async delete(e,t){let r=In(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 De("file exists already","EntryExists");let t=pe(e),r=In(e),o=this._lookupAsDirectory(r,!1),s=new io(t);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,t){let r=e.path.split("/"),o=this.root;for(let s of r){if(!s)continue;let a;if(o instanceof io&&(a=o.entries.get(s)),!a){if(t)return;throw De("file not found","EntryNotFound")}o=a}return o}_lookupAsDirectory(e,t){let r=this._lookup(e,t);if(r instanceof io)return r;throw De("file not a directory","EntryNotADirectory")}_lookupAsFile(e,t){let r=this._lookup(e,t);if(r instanceof Cc)return r;throw De("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let t=In(e);return this._lookupAsDirectory(t,!1)}watch(e,t){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 vN=[];function Ux(i,n,e){n instanceof zn||(n=new zn(n,[],!!e)),vN.push([i,n])}var Fx=$("labelService");var Tc="vscode-agent-host",Hx="_ah";function $x(i,n){if(n==="local"&&i.scheme===ie.file)return i;let e={scheme:i.scheme,...i.authority?{authority:i.authority}:{},...i.query?{query:i.query}:{}},t=new URLSearchParams;return t.set(Hx,Zn(U.fromString(JSON.stringify(e)),!1,!0)),v.from({scheme:Tc,authority:n,path:i.path||"/",query:t.toString(),fragment:i.fragment})}function Wx(i){if(i.scheme!==Tc)return i;let n,e=i.query?new URLSearchParams(i.query).get(Hx):null;if(e)try{n=JSON.parse(un(e).toString())}catch{n=void 0}return!n||typeof n.scheme!="string"?v.from({scheme:ie.file,path:i.path,fragment:i.fragment}):v.from({scheme:n.scheme,authority:n.authority||void 0,path:i.path,query:n.query||"",fragment:i.fragment})}var qx={scheme:Tc,formatting:{label:"${path}",separator:"/"}};var wc=class i extends T{constructor(e=i._DEFAULT_CONNECTION_GRACE_MS){super();this._connectionGraceMs=e;this.capabilities=263178;this._onDidChangeCapabilities=this._register(new P);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new P);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new P);this.onDidWatchError=this._onDidWatchError.event;this._authorities=new Map;this._onDidChangeConnection=this._register(new P)}static{this._DEFAULT_CONNECTION_GRACE_MS=5e3}registerAuthority(e,t){let r=this._authorities.get(e);r?(r.expiry.clear(),r.connections.push(t)):(r={connections:[t],expiry:new At},this._authorities.set(e,r));let o=r;return this._onDidChangeConnection.fire(e),M(()=>{let s=o.connections.indexOf(t);if(s===-1)return;let a=s===o.connections.length-1;o.connections.splice(s,1),o.connections.length===0&&(o.expiry.value=Kt(()=>this._expireAuthority(e,o),this._connectionGraceMs,this._store)),a&&this._onDidChangeConnection.fire(e)})}_expireAuthority(e,t){this._authorities.get(e)!==t||t.connections.length>0||(this._authorities.delete(e),t.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,t){let r=new G,o=r.add(new At),s=e.authority,a={channel:Ke,uri:this._decodeUri(e).toString(),recursive:t.recursive,...t.excludes.length>0?{excludes:{items:[...t.excludes]}}:{},...t.includes&&t.includes.length>0?{includes:{items:t.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 y=m;try{let S=await h.call(y,a);if(r.isDisposed){S.dispose();return}let b=this._authorities.get(s);if(!b||b.connections.at(-1)!==y){S.dispose();return}let I=S.onDidChange(_=>this._onDidChangeFile.fire(_.map(R=>({resource:this._encodeUri(R.resource,e.authority),type:R.type}))));o.value=M(()=>{I.dispose(),S.dispose()}),l=y}catch(S){this._onDidWatchError.fire(S instanceof Error?S.message:String(S))}finally{d=!1,c&&(c=!1,u())}};return r.add(this._onDidChangeConnection.event(p=>{p===s&&u()})),u(),r}async stat(e){let t=e.path;if(t==="/"||t==="")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 t=e.path;if(t==="/"||t==="")return t;let r=this._decodeUri(e);if(r.scheme==="session-db"||r.scheme==="git-blob"||r.path==="/"||r.path==="")return t;let o=await this._getConnection(e.authority);try{let s=await this._resolve(o,r);return this._encodeUri(v.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 t=await this._getConnection(e.authority);try{let r=this._decodeUri(e),o=await t.resourceRead(r);return o.encoding==="base64"?un(o.data).buffer:U.fromString(o.data).buffer}catch(r){throw this._mapError(r,"EntryNotFound")}}async writeFile(e,t,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e);await o.resourceWrite({channel:Ke,uri:s.toString(),data:U.wrap(t).toString(),encoding:"utf-8"})}catch(s){throw this._mapError(s,"NoPermissions")}}async mkdir(e){let t=await this._getConnection(e.authority);try{let r=this._decodeUri(e);await t.resourceMkdir({channel:Ke,uri:r.toString()})}catch(r){throw this._mapError(r,"NoPermissions")}}async delete(e,t){let r=await this._getConnection(e.authority);try{let o=this._decodeUri(e);await r.resourceDelete({channel:Ke,uri:o.toString(),recursive:t.recursive})}catch(o){throw this._mapError(o,"NoPermissions")}}async rename(e,t,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(t);await o.resourceMove({channel:Ke,source:s.toString(),destination:a.toString(),failIfExists:!r.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async copy(e,t,r){let o=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(t);await o.resourceCopy({channel:Ke,source:s.toString(),destination:a.toString(),failIfExists:!r.overwrite})}catch(s){throw this._mapError(s,"NoPermissions")}}async requestResourceAccess(e,t){let r=await this._getConnection(e.authority);if(!r.resourceRequest)throw De(`Connection for ${e.authority} does not support resourceRequest`,"Unavailable");let o=this._decodeUri(e);try{await r.resourceRequest({channel:Ke,uri:o.toString(),read:t.read,write:t.write})}catch(s){throw this._mapError(s,"NoPermissions")}}_getConnection(e){let t=this._authorities.get(e);if(!t)return Promise.reject(De(`No connection for authority: ${e}`,"Unavailable"));let r=t.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(De(`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,t){return e instanceof k&&e.code===ye.PermissionDenied?De(e.message,"NoPermissions"):De(e instanceof Error?e.message:String(e),t)}_resolve(e,t){return e.resourceResolve({channel:Ke,uri:t.toString()})}async _listDirectory(e,t){let r=await this._getConnection(e);try{let o=this._decodeUri(t);return(await r.resourceList(o)).entries}catch(o){throw this._mapError(o,"Unavailable")}}},Pg=class extends wc{_decodeUri(n){return Wx(n)}_encodeUri(n,e){return $x(n,e)}};var xc="vscode-synced-customization",SN=$("agentHostFileSystemService"),Rc=class extends T{constructor(e,t){super();this._fileService=e;this._syncedCustomizationProviderRegistered=!1;this._fsProvider=this._register(new Pg),this._register(e.registerProvider(Tc,this._fsProvider)),this._register(t.registerFormatter(qx))}registerAuthority(e,t){return this._fsProvider.registerAuthority(e,t)}ensureSyncedCustomizationProvider(){if(!this._syncedCustomizationProviderRegistered){this._syncedCustomizationProviderRegistered=!0;let e=this._register(new Fa);this._register(this._fileService.registerProvider(xc,e))}}};Rc=w([C(0,xe),C(1,Fx)],Rc);Ux(SN,Rc,1);var Ag=class extends T{constructor(e){super();this._getAgent=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(e,t){let r=Qf(e.text,e.offset);if(!r)return[];let o=typeof e.channel=="string"?v.parse(e.channel):e.channel,s=this._getAgent(o);if(!s)return[];let a=await this._getCandidates(s,o);if(t.isCancellationRequested||a.length===0)return[];let l=r.typed,d=new Set;return a.filter(c=>{let u=c.uri;return(!l.length||c.slashCommandName.startsWith(l))&&!d.has(u)?(d.add(u),!0):!1}).map(c=>({insertText:"/"+c.slashCommandName+" ",rangeStart:r.rangeStart,rangeEnd:r.rangeEnd,attachment:{type:"simple",label:"/"+c.slashCommandName,_meta:LR({uri:c.uri,name:c.name,displayName:c.slashCommandName,description:c.description})}}))}async _getCandidates(e,t){if(!e.getSessionCustomizations)return[];let r=await e.getSessionCustomizations(t),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(this._toSlashCommandCandidate(s,a));return o}_toSlashCommandCandidate(e,t){let r=t.name;return e.type==="plugin"&&!bN(e)&&t.name!==e.name&&(r=`${e.name}:${t.name}`),{slashCommandName:r,name:t.name,description:t.description,uri:t.uri}}};function bN(i){return i.uri.startsWith(xc+":")}import*as zx from"child_process";var CN=new qe(async()=>(await import("@vscode/ripgrep-universal")).rgPath.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"));function Ha(){return CN.value}var IN=5e4,_N=3e4,$a=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,t){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+_N};this._cache.set(r,l),a.catch(()=>{this._cache.get(r)===l&&this._cache.delete(r)})}if(t.isCancellationRequested)throw new Y;return t===Ae.None?a:new Promise((l,d)=>{let c=t.onCancellationRequested(()=>{c.dispose(),d(new Y)});a.then(u=>{c.dispose(),l(u)},u=>{c.dispose(),d(u)})})}async _enumerate(e){let t=await Ha();return new Promise(r=>{let o=e.fsPath,s=["--files","--hidden","--no-require-git","--follow","--no-config","--glob","!.git"],a;try{a=zx.spawn(t,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 y;for(;(y=d.indexOf(`
`))>=0;){let S=d.slice(0,y).replace(/\r$/,"");if(d=d.slice(y+1),!!S&&(l.push(v.joinPath(e,S)),l.length>=IN)){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(v.joinPath(e,h)),d=""}m&&this._logService.trace(`[AgentHostWorkspaceFiles] ripgrep stderr: ${m}`),p(l)})})}};$a=w([C(0,D)],$a);var Vx={serverTools:{listChanged:!0},serverResources:{},sampling:{}},Eg={capabilities:Vx};var Wa=class extends T{constructor(e){super();this._options=e;this._live=nn(this,new Map);this.runtimeStates=Ad(this,t=>{let r=new Map;for(let o of this._live.read(t).values()){let s=o.topLevelId??this._options.resolveChildId(o.serverName);s!==void 0&&r.set(s,{state:o.state,channel:this._buildChannel(o.serverName,o.state)})}return r})}topLevelCustomizations(){let e=[];for(let t of this._live.get().values())t.topLevelId!==void 0&&e.push(this._buildTopLevel(t.topLevelId,t.serverName,t.state));return e}readyChannels(){let e=[];for(let t of this._live.get().values()){if(t.state.kind!=="ready")continue;let r=this._buildChannel(t.serverName,t.state);r!==void 0&&e.push({serverName:t.serverName,channel:r})}return e}customizationIdForServer(e){let t=this._live.get().get(e);return t?.topLevelId!==void 0?t.topLevelId:this._options.resolveChildId(e)}channelForServer(e){let t=this._live.get().get(e);if(!(!t||t.state.kind!=="ready"))return this._buildChannel(e,t.state)}applyAll(e){nr(t=>{let r=new Set;for(let o of e)r.add(o.name),this._applyOne(o,t);for(let o of[...this._live.get().keys()])r.has(o)||this._remove(o,t)})}applyOne(e){nr(t=>this._applyOne(e,t))}_applyOne(e,t){let r=this._live.get().get(e.name),o=this._stateForUpdate(r?.state,e.state),s=r?.topLevelId;if(s===void 0){let a=this._options.resolveChildId(e.name);if(a!==void 0){this._setLiveEntry(e.name,{serverName:e.name,state:o,topLevelId:void 0},t),this._options.emit({type:"session/mcpServerStateChanged",id:a,state:o,channel:this._buildChannel(e.name,o)});return}s=this._mintTopLevelId(e.name)}this._setLiveEntry(e.name,{serverName:e.name,state:o,topLevelId:s},t),this._options.emit({type:"session/customizationUpdated",customization:this._buildTopLevel(s,e.name,o)})}remove(e){nr(t=>this._remove(e,t))}_remove(e,t){let r=this._live.get().get(e);if(!r)return;if(this._deleteLiveEntry(e,t),r.topLevelId!==void 0){this._options.emit({type:"session/customizationRemoved",id:r.topLevelId});return}let o=this._options.resolveChildId(e);o!==void 0&&this._options.emit({type:"session/mcpServerStateChanged",id:o,state:{kind:"stopped"}})}_setLiveEntry(e,t,r){let o=new Map(this._live.get());o.set(e,t),this._live.set(o,r)}_deleteLiveEntry(e,t){let r=this._live.get();if(!r.has(e))return;let o=new Map(r);o.delete(e),this._live.set(o,t)}_stateForUpdate(e,t){return e?.kind==="authRequired"&&t.kind==="starting"?e:t}_mintTopLevelId(e){return`mcp-top-level:${this._options.providerId}:${this._options.sessionId}:${e}`}_buildChannel(e,t){if(t.kind==="ready")return`mcp://${this._options.providerId}/${encodeURIComponent(this._options.sessionId)}/${encodeURIComponent(e)}`}_buildTopLevel(e,t,r){let o=this._buildChannel(t,r),s=this._options.capabilities?{capabilities:this._options.capabilities}:Eg;return{type:"mcpServer",id:e,uri:this._mintTopLevelId(t),name:t,enabled:!0,state:r,channel:o,mcpApp:s}}};function Dg(i,n){for(let e of i){if(e.type==="mcpServer"){if(e.name===n)return e.id;continue}let t=e.children;if(t){for(let r of t)if(r.type==="mcpServer"&&r.name===n)return r.id}}}function jx(i){let n="mcp://";if(!i.startsWith(n))return;let e=i.slice(n.length),t=e.indexOf("/");if(t<=0)return;let r=e.slice(0,t),o=e.slice(t+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 LS="vscode-agent-client";function qa(i,n){let e=i.authority||"-",t=i.path.length>0&&!i.path.startsWith("/"),r=t?`${i.scheme}!`:i.scheme,o=t?`/${i.path}`:i.path;return v.from({scheme:LS,authority:n,path:`/${r}/${e}${o}`,query:i.query||void 0,fragment:i.fragment||void 0})}function Kx(i){let n=i.path,e=i.query||void 0,t=i.fragment||void 0,r=n.indexOf("/",1);if(r===-1)return v.from({scheme:"file",path:n,query:e,fragment:t});let o=n.substring(1,r),s=o.endsWith("!");s&&(o=o.substring(0,o.length-1));let a=n.indexOf("/",r+1);if(a===-1){let c=n.substring(r+1);return v.from({scheme:o,authority:c==="-"?"":c,path:"/",query:e,fragment:t})}let l=n.substring(r+1,a);l==="-"&&(l="");let d=n.substring(a);return s&&(d=d.substring(1)),v.from({scheme:o,authority:l||void 0,path:d,query:e,fragment:t})}var Ba=class extends T{constructor(e,t,r){super();this._stateManager=e;this._gitStateService=t;this._changesetSubscriptions=r;this._handlerRegistrations=this._register(new Re);this._changesetOperationHandlers=new Map;this._inFlightOperations=new Map;this._registry={registerChangesetOperationHandler:(o,s)=>this._registerChangesetOperationHandler(o,s),refreshSessionGitState:o=>this._gitStateService.refreshSessionGitState(o),onDidChangeOperations:o=>this.updateOperations(o)}}registerContribution(e){if(this._handlerRegistrations.has(e))throw new Error("Changeset operation contribution already registered");return this._handlerRegistrations.set(e,e.registerHandlers(this._registry)),M(()=>{this._handlerRegistrations.deleteAndDispose(e),e.dispose()})}getOperations(e,t,r,o){if(!r){let a=this._stateManager.getSessionState(e);if(r=Tt(a?._meta),!r)return[]}o||(o=Ui(this._stateManager.getSessionState(e)?._meta));let s=et(t);return s?this._getOperations({sessionKey:e,changesetUri:t,changesetKind:s.kind,gitState:r,gitHubState:o}):[]}_getOperations(e){let t=[];for(let r of this._handlerRegistrations.keys()){let o=r.getOperations(e);o&&t.push(...o)}return this._stateManager.hasActiveTurn(e.sessionKey)?t.map(r=>({...r,status:"disabled"})):t}updateOperations(e,t,r,o){if(!r){let a=this._stateManager.getSessionState(e);if(r=Tt(a?._meta),!r)return}if(!o){let a=this._stateManager.getSessionState(e);o=Ui(a?._meta)}let s=t?[t]:this._changesetSubscriptions.getSessionSubscriptions(e);for(let a of s){let l=this.getOperations(e,a,r,o);this._stateManager.dispatchServerAction(a,{type:"changeset/operationsChanged",operations:[...l]})}}async invokeChangesetOperation(e){let t=this._stateManager.getChangesetState(e.channel);if(!t)throw new k(ut,`Changeset not found: ${e.channel}`);let r=t.operations?.find(l=>l.id===e.operationId);if(!r)throw new k(ne.InvalidParams,`Unknown operation '${e.operationId}' on changeset ${e.channel}`);if(r.status==="disabled")throw new k(ne.InvalidParams,`Operation '${e.operationId}' is disabled on changeset ${e.channel}`);let o=et(e.channel);if(o&&this._stateManager.hasActiveTurn(o.sessionUri))throw new k(ne.InvalidParams,`Operation '${e.operationId}' is disabled while a turn is active on changeset ${e.channel}`);let s=e.target?.kind==="resource"?"resource":e.target?.kind==="range"?"range":"changeset";if(!r.scopes.includes(s))throw new k(ne.InvalidParams,`Operation '${e.operationId}' does not support scope '${s}' (allowed: ${r.scopes.join(", ")})`);let a=this._changesetOperationHandlers.get(e.operationId);if(!a)throw new k(ne.InternalError,`No operation handler registered for '${e.operationId}' on changeset ${e.channel}`);return this._invokeChangesetOperation(a,e)}_invokeChangesetOperation(e,t){let r=`${t.channel}\0${t.operationId}\0${JSON.stringify(t.target??null)}`,o=this._inFlightOperations.get(r);if(o)return o;this._stateManager.dispatchServerAction(t.channel,{type:"changeset/operationStatusChanged",operationId:t.operationId,status:"running"});let s=e.invoke(t,Ae.None).then(a=>(this._stateManager.dispatchServerAction(t.channel,{type:"changeset/operationStatusChanged",operationId:t.operationId,status:"idle"}),a)).catch(a=>{throw this._stateManager.dispatchServerAction(t.channel,{type:"changeset/operationStatusChanged",operationId:t.operationId,status:"error",error:TN(a)}),a}).finally(()=>{this._inFlightOperations.get(r)===s&&this._inFlightOperations.delete(r)});return this._inFlightOperations.set(r,s),s}_registerChangesetOperationHandler(e,t){if(this._changesetOperationHandlers.has(e))throw new Error(`Changeset operation handler already registered for '${e}'`);return this._changesetOperationHandlers.set(e,t),M(()=>{this._changesetOperationHandlers.get(e)===t&&this._changesetOperationHandlers.delete(e)})}};Ba=w([C(1,Pr),C(2,eo)],Ba);function TN(i){let n=ke(i);return i instanceof Error?{errorType:i.name,message:n,stack:i.stack}:{errorType:"Error",message:n}}var Va=$("agentHostOctoKitService"),Gx="https://api.github.com",Jx="2022-11-28",Yx=500,wN=`mutation EnableAutoMerge($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
	enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
		pullRequest { id }
	}
}`,za=class{constructor(n,e){this._logService=e;this.pullRequestSearchEtags=new sn(100);this._fetch=n??globalThis.fetch}async createPullRequest(n,e,t,r,o,s,a,l,d){let c=await this._makeGHAPIRequest(`repos/${n}/${e}/pulls`,"POST",l,d,{title:t,body:r,head:o,base:s,draft:a}),u=c.data?.number,p=c.data?.html_url;if(typeof p!="string"||typeof u!="number")throw new Error(`Failed to create pull request for ${n}/${e}`);let m=c.data?.node_id;return{url:p,number:u,nodeId:typeof m=="string"?m:void 0}}async findPullRequestByHeadBranch(n,e,t,r,o){let s=`repos/${n}/${e}/pulls?head=${encodeURIComponent(`${n}:${t}`)}&state=all&sort=updated&direction=desc&per_page=1`,a=this.pullRequestSearchEtags.get(s),l=await this._makeGHAPIRequest(s,"GET",r,o,void 0,a);if(l.etag&&this.pullRequestSearchEtags.set(s,l.etag),l.statusCode===304||!Array.isArray(l.data)||l.data.length===0)return;let d=l.data[0],c=d?.html_url,u=d?.number,p=d?.node_id;return typeof c=="string"&&typeof u=="number"?{number:u,url:c,nodeId:typeof p=="string"?p:void 0}:void 0}async enablePullRequestAutoMerge(n,e,t,r){await this._makeGraphQLRequest(wN,{pullRequestId:n,mergeMethod:e},t,r)}async _makeGHAPIRequest(n,e,t,r,o,s){let a=`${Gx}/${n}`,l={Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":Jx};s&&(l["If-None-Match"]=s),o&&(l["Content-Type"]="application/json");let d;try{d=await this._fetch(a,{method:e,headers:l,body:o?JSON.stringify(o):void 0,signal:r})}catch(m){throw r.aborted||this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Network error`,m),m}let c=d.headers.get("x-ratelimit-remaining");if(c){let m=RN(c);m!==void 0&&m<100&&this._logService.warn(`[AgentHostOctoKitService] ${e} ${a} - GitHub API rate limit low: ${m} remaining`)}let u=d.status??0,p=d.headers.get("etag")??void 0;if(u===204||u===304)return{data:void 0,statusCode:u,etag:p};if(!d.ok){let m=await d.text().catch(()=>{}),h=this._formatErrorResponseBody(m);throw this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Status: ${d.status}${h?` - ${h}`:""}`),new Error(`GitHub API request failed: ${e} ${n} - ${d.status} ${d.statusText}${h?` - ${h}`:""}`)}try{return{data:await d.json(),statusCode:u,etag:p}}catch(m){throw this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Failed to parse JSON`,m),m}}async _makeGraphQLRequest(n,e,t,r){let o=`${Gx}/graphql`,s={Accept:"application/json",Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-GitHub-Api-Version":Jx},a;try{a=await this._fetch(o,{method:"POST",headers:s,body:JSON.stringify({query:n,variables:e}),signal:r})}catch(d){throw r.aborted||this._logService.error(`[AgentHostOctoKit] POST ${o} - Network error`,d),d}if(!a.ok){let d=await a.text().catch(()=>{}),c=this._formatErrorResponseBody(d);throw this._logService.error(`[AgentHostOctoKit] POST ${o} - Status: ${a.status}${c?` - ${c}`:""}`),new Error(`GitHub GraphQL request failed: ${a.status} ${a.statusText}${c?` - ${c}`:""}`)}let l;try{l=await a.json()}catch(d){throw this._logService.error(`[AgentHostOctoKit] POST ${o} - Failed to parse JSON`,d),d}if(Array.isArray(l.errors)&&l.errors.length>0){let d=l.errors.map(c=>typeof c?.message=="string"?c.message:JSON.stringify(c)).join("; ");throw this._logService.error(`[AgentHostOctoKit] POST ${o} - GraphQL error: ${d}`),new Error(`GitHub GraphQL request failed: ${d}`)}return l.data}_formatErrorResponseBody(n){let e=n?.replace(/\s+/g," ").trim();if(e)return e.length>Yx?`${e.substring(0,Yx)}...`:e}};za=w([C(1,D)],za);function RN(i){if(i===void 0)return;let n=Array.isArray(i)?i[0]:i,e=parseInt(n,10);return isNaN(e)?void 0:e}var ja=class extends T{constructor(e,t,r,o,s,a){super();this._stateManager=e;this._gitService=t;this._octoKitService=r;this._agentService=o;this._logService=s;this._sessionDataService=a;this._onDidRefreshSessionGitState=this._register(new P);this.onDidRefreshSessionGitState=this._onDidRefreshSessionGitState.event;this._gitStateRefreshThrottler=this._register(new Fu);this._gitStateRefreshCancellationTokenSource=new Ze;this._register(M(()=>this._gitStateRefreshCancellationTokenSource.dispose(!0)))}async attachSessionGitHubPullRequest(e){let t=this._stateManager.getSessionState(e);if(!t||t.lifecycle!=="ready")return;let r=Ui(this._stateManager.getSessionState(e)?._meta);if(!r?.owner||!r?.repo||r?.pullRequestUrl)return;let o=Tt(t._meta);if(!(!o?.branchName||o.branchName===o.baseBranchName))try{let s=this._agentService.getAuthToken({resource:Ht.resource,scopes:Ht.scopes_supported});if(!s)return;let a=new AbortController().signal,l=await this._octoKitService.findPullRequestByHeadBranch(r.owner,r.repo,o.branchName,s,a);if(!l?.url)return;this.setSessionGitHubState(e,{owner:r.owner,repo:r.repo,pullRequestUrl:l.url})}catch(s){this._logService.warn(`[AgentHostGitStateService][attachSessionGitHubPullRequest] Failed to find pull request for ${e}`,s)}}async refreshSessionGitState(e,t){let r=this._stateManager.getSessionState(e);if(r?.lifecycle!=="creating"){if(!t){let o=r?.workingDirectory;o&&(t=v.parse(o))}t&&await this._gitStateRefreshThrottler.queue(e,async()=>{try{this._logService.trace(`[AgentHostGitStateService][refreshSessionGitState] Refreshing git state for ${e}, ${t?.fsPath}`);let o=await this._gitService.getSessionGitState(t);if(o){let s=this._stateManager.getSessionState(e)?._meta;Fe(Tt(s),o)||(await this._setSessionGitState(e,o),o.githubOwner&&o.githubRepo&&await this.setSessionGitHubState(e,{owner:o.githubOwner,repo:o.githubRepo}))}this._onDidRefreshSessionGitState.fire(e),await Tn(5e3,this._gitStateRefreshCancellationTokenSource.token)}catch(o){if(Kn(o))return;this._logService.warn(`[AgentHostGitStateService][refreshSessionGitState] Failed to compute git state for ${e}:`,o)}})}}async setSessionGitHubState(e,t){let r=this._stateManager.getSessionState(e)?._meta,o=Ui(r),s={...o??{},...t};if(Fe(o,s))return;let a=dp(r,s);this._stateManager.setSessionMeta(e,a),await this._saveSessionState(e,ro,JSON.stringify(s))}async _setSessionGitState(e,t){let r=this._stateManager.getSessionState(e)?._meta,o=lp(r,t);this._stateManager.setSessionMeta(e,o),await this._saveSessionState(e,no,JSON.stringify(t))}async _saveSessionState(e,t,r){if(this._stateManager.getSessionState(e)?.lifecycle==="creating")return;let s;try{s=this._sessionDataService.openDatabase(v.parse(e))}catch(a){this._logService.warn(`[AgentHostGitStateService][_saveSessionState] Failed to open session database for ${e}`,a);return}try{await s.object.setMetadata(t,r)}catch(a){this._logService.warn(`[AgentHostGitStateService][_saveSessionState] Failed to persist ${t}`,a)}finally{s.dispose()}}};ja=w([C(1,Ye),C(2,Va),C(3,yr),C(4,D),C(5,Je)],ja);var Mg=class{constructor(n){this._logService=n;this._tokens=new Map}async authenticate(n,e){this._logService.trace(`[AgentHostAuthenticationService] authenticate called: resource=${n.resource}`);let t=[...e],r=t.filter(d=>d.getProtectedResources().some(c=>c.resource===n.resource)),o=await Promise.allSettled(r.map(d=>d.authenticate(n.resource,n.token))),s=!1;for(let d=0;d<o.length;d++){let c=o[d];c.status==="fulfilled"?s||=c.value:this._logService.error(c.reason,`[AgentHostAuthenticationService] Provider '${r[d].id}' authenticate threw for resource=${n.resource}`)}let a=t.filter(d=>d.handleAuthenticationToken),l=await Promise.allSettled(a.map(d=>d.handleAuthenticationToken?d.handleAuthenticationToken(n):Promise.resolve(!1)));for(let d=0;d<l.length;d++){let c=l[d];c.status==="fulfilled"?s||=c.value:this._logService.error(c.reason,`[AgentHostAuthenticationService] Provider '${a[d].id}' handleAuthenticationToken threw for resource=${n.resource}`)}if(s){let d=this._normalizeScopes(n.scopes);this._tokens.set(this._key(n.resource,d),{resource:n.resource,scopes:d,token:n.token})}return{authenticated:s}}getAuthToken(n){let e=this._normalizeScopes(n.scopes),t=this._tokens.get(this._key(n.resource,e));if(t)return t.token;if(e.length===0)return;let r=new Set(e),o;for(let s of this._tokens.values())s.resource!==n.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(n.resource,[]))?.token}_containsAll(n,e){for(let t of e)if(!n.includes(t))return!1;return!0}_key(n,e){return`${n}\0${e.join("\0")}`}_normalizeScopes(n){return n?[...new Set(n)].sort():[]}};var xN=new Set,Og=class{constructor(){this._subscriptions=new Map}getSessionSubscriptions(n){return this._subscriptions.get(n)??xN}addSubscription(n,e){let t=this._subscriptions.get(n);t||(t=new Set,this._subscriptions.set(n,t)),t.add(e)}removeSubscription(n,e){let t=this._subscriptions.get(n);t&&(t.delete(e),t.size===0&&this._subscriptions.delete(n))}clearSessionSubscriptions(n){this._subscriptions.delete(n)}};var PN=2e4,oo=class{constructor(n,e,t,r,o,s){this._getSessionState=n;this._onCommitted=e;this._agentService=t;this._gitService=r;this._copilotApiService=o;this._logService=s}static{this.OPERATION_COMMIT="commit"}async invoke(n,e){let t=new AbortController;e.isCancellationRequested&&t.abort();let r=e.onCancellationRequested(()=>t.abort());try{return await this._invoke(n,e,t.signal)}finally{r.dispose()}}async _invoke(n,e,t){let r=et(n.channel);if(!r)throw new k(ne.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let o=r.sessionUri,s=this._getSessionState(o);if(!s)throw new k(ut,`Session not found: ${o}`);let a=s.workingDirectory;if(!a)throw new k(ne.InternalError,`Session has no working directory: ${o}`);let l=v.parse(a),d=Tt(s._meta);if(!d)throw new k(ne.InternalError,`Session's working directory is not a git repo: ${o}`);if(!await this._gitService.hasUncommittedChanges(l))return{message:{markdown:f(1990,null)}};this._throwIfCancelled(e);let u=this._agentService.getAuthToken({resource:mt.resource,scopes:mt.scopes_supported});if(!u)throw new k(tr,f(1985,null),[mt]);let p=await this._gitService.computeSessionFileDiffs(l,{sessionUri:o});if(!p||p.length===0)throw new k(ne.InternalError,f(1988,null));this._throwIfCancelled(e);let m;try{m=this._cleanCommitMessage(await this._copilotApiService.utilityChatCompletion(u,{messages:this._buildCommitMessagePrompt(l,d.branchName,p)},{signal:t}))}catch(h){throw this._throwIfCancelled(e),this._isAuthFailure(h)?new k(tr,f(1984,null),[mt]):h}if(!m)throw new k(ne.InternalError,f(1989,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 k(ne.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{message:{markdown:f(1987,null,m.split(`
`)[0])}}}_buildCommitMessagePrompt(n,e,t){let r=this._summarizeDiffsForPrompt(t);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(n)}`,`Branch: ${e??"unknown"}`,"Changed files:",r].join(`
`)}]}_summarizeDiffsForPrompt(n){let e=[];for(let t of n){let r=t.before?.uri,o=t.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)} (+${t.diff?.added??0} -${t.diff?.removed??0})`),e.join(`
`).length>PN){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=v.parse(n);return e.scheme==="file"?e.fsPath:e.path||n}catch{return n}}_cleanCommitMessage(n){let e=n.trim().replace(/\r\n/g,`
`),t=/^```(?:text|gitcommit)?\s*([\s\S]*?)\s*```$/i.exec(e);return t&&(e=t[1].trim()),e}_isAuthFailure(n){if(n instanceof ir)return n.status===401||n.status===403;let e=n instanceof Error?n.message:String(n);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(n){if(n.isCancellationRequested)throw new k(ne.InternalError,f(1986,null))}};oo=w([C(2,yr),C(3,Ye),C(4,It),C(5,D)],oo);var Ka=class extends T{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new G,r=s=>this._stateManager.getSessionState(s),o=this._instantiationService.createInstance(oo,r,s=>this._onCommitted(s));return t.add(e.registerChangesetOperationHandler(oo.OPERATION_COMMIT,o)),t.add({dispose:()=>{this._registry=void 0}}),t}getOperations({changesetKind:e,gitHubState:t,gitState:r}){return(r?.uncommittedChanges??0)<=0?[]:!t?.pullRequestUrl&&e!=="uncommitted"?[]:[{id:oo.OPERATION_COMMIT,label:f(1991,null),icon:"git-commit",group:"commit",scopes:["changeset"],status:"idle"}]}async _onCommitted(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};Ka=w([C(1,Ie)],Ka);var Ar=class{constructor(n,e,t){this._getSessionState=n;this._agentHostGitService=e;this._logService=t}static{this.OPERATION_DISCARD_CHANGES="discard-changes"}async invoke(n,e){let t=new AbortController;e.isCancellationRequested&&t.abort();let r=e.onCancellationRequested(()=>t.abort());try{return await this._invoke(n,e,t.signal)}finally{r.dispose()}}async _invoke(n,e,t){let r=et(n.channel);if(!r||r.kind!=="uncommitted")throw new k(ne.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let o=r.sessionUri,s=this._getSessionState(o);if(!s)throw new k(ut,`Session not found: ${o}`);if(n.target?.kind!=="resource")throw new k(ne.InvalidParams,`Operation '${Ar.OPERATION_DISCARD_CHANGES}' requires a resource target.`);let a=s.workingDirectory;if(!a)throw new k(ne.InternalError,`Session has no working directory: ${o}`);let l=v.parse(a),d=v.parse(n.target.resource);this._logService.info(`[AgentHostDiscardChangesOperationHandler] Restoring '${d.fsPath}' for session ${o}`);try{await this._agentHostGitService.restore(l,[d.fsPath])}catch(c){throw this._throwIfCancelled(e),new k(ne.InternalError,`Failed to discard changes: ${c instanceof Error?c.message:String(c)}`)}return{message:{markdown:f(1993,null,pe(d))}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new k(ne.InternalError,f(1992,null))}};Ar=w([C(1,Ye),C(2,D)],Ar);var Ga=class extends T{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){let t=new G,r=s=>this._stateManager.getSessionState(s),o=this._instantiationService.createInstance(Ar,r);return t.add(e.registerChangesetOperationHandler(Ar.OPERATION_DISCARD_CHANGES,o)),t}getOperations({changesetKind:e,gitState:t}){return e!=="uncommitted"||(t?.uncommittedChanges??0)<=0?[]:[{id:Ar.OPERATION_DISCARD_CHANGES,label:f(1994,null),confirmation:f(1995,null),icon:"discard",scopes:["resource"],status:"idle"}]}};Ga=w([C(1,Ie)],Ga);var mn=class{constructor(n,e,t,r,o,s){this._reviewed=n;this._getSessionState=e;this._reviewService=t;this._changesetService=r;this._sessionDataService=o;this._logService=s}static{this.OPERATION_MARK_AS_REVIEWED="mark-as-reviewed"}static{this.OPERATION_MARK_AS_UNREVIEWED="mark-as-unreviewed"}get _operationId(){return this._reviewed?mn.OPERATION_MARK_AS_REVIEWED:mn.OPERATION_MARK_AS_UNREVIEWED}async invoke(n,e){let t=et(n.channel);if(!t||t.kind!=="branch")throw new k(ne.InvalidParams,`Not a branch changeset URI: ${n.channel}`);this._throwIfCancelled(e);let r=t.sessionUri,o=this._getSessionState(r);if(!o)throw new k(ut,`Session not found: ${r}`);if(n.target?.kind!=="resource")throw new k(ne.InvalidParams,`Operation '${this._operationId}' requires a resource target.`);let s=o.workingDirectory;if(!s)throw new k(ne.InternalError,`Session has no working directory: ${r}`);let a=v.parse(s),l=v.parse(n.target.resource),d=await this._resolveBaseBranch(r,o);try{return this._reviewed?(this._logService.info(`[AgentHostReviewFileOperationHandler] Marking '${l.fsPath}' as reviewed for session ${r}`),await this._reviewService.markFileReviewed(r,a,d,l),this._changesetService.refreshBranchChangeset(r),{message:{markdown:f(2021,null,pe(l))}}):(this._logService.info(`[AgentHostReviewFileOperationHandler] Removing reviewed mark for '${l.fsPath}' in session ${r}`),await this._reviewService.markFileUnreviewed(r,a,d,l),this._changesetService.refreshBranchChangeset(r),{message:{markdown:f(2022,null,pe(l))}})}catch(c){throw this._throwIfCancelled(e),new k(ne.InternalError,`Failed to update reviewed state: ${c instanceof Error?c.message:String(c)}`)}}async _resolveBaseBranch(n,e){let t=this._sessionDataService.openDatabase(v.parse(n));try{let r=await t.object.getMetadata(ca),o=Tt(e._meta)?.baseBranchName;return ff(r,o)}finally{t.dispose()}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new k(ne.InternalError,f(2020,null))}};mn=w([C(2,to),C(3,ji),C(4,Je),C(5,D)],mn);var Ja=class extends T{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){let t=new G,r=a=>this._stateManager.getSessionState(a),o=this._instantiationService.createInstance(mn,!0,r),s=this._instantiationService.createInstance(mn,!1,r);return t.add(e.registerChangesetOperationHandler(mn.OPERATION_MARK_AS_REVIEWED,o)),t.add(e.registerChangesetOperationHandler(mn.OPERATION_MARK_AS_UNREVIEWED,s)),t}getOperations({changesetKind:e}){return e!=="branch"?[]:[{id:mn.OPERATION_MARK_AS_REVIEWED,label:f(2023,null),icon:"check",group:"review",scopes:["resource"],status:"idle"},{id:mn.OPERATION_MARK_AS_UNREVIEWED,label:f(2024,null),icon:"check",group:"review",scopes:["resource"],status:"idle"}]}};Ja=w([C(1,Ie)],Ja);var AN=12e3,EN=4e3,rn=class{constructor(n,e,t,r,o,s,a,l,d){this._draft=n;this._autoMergeMethod=e;this._getSessionState=t;this._onPullRequestCreated=r;this._agentService=o;this._gitService=s;this._octoKitService=a;this._copilotApiService=l;this._logService=d}static{this.OPERATION_CREATE_PR="create-pr"}static{this.OPERATION_CREATE_DRAFT_PR="create-draft-pr"}static{this.OPERATION_CREATE_PR_AUTO_MERGE="create-pr-auto-merge"}static{this.OPERATION_CREATE_PR_AUTO_SQUASH="create-pr-auto-squash"}static{this.OPERATION_CREATE_PR_AUTO_REBASE="create-pr-auto-rebase"}async invoke(n,e){let t=new AbortController;e.isCancellationRequested&&t.abort();let r=e.onCancellationRequested(()=>t.abort());try{return await this._invoke(n,e,t.signal)}finally{r.dispose()}}async _invoke(n,e,t){let r=et(n.channel);if(!r)throw new k(ne.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let o=r.sessionUri,s=this._getSessionState(o);if(!s)throw new k(ut,`Session not found: ${o}`);let a=s.workingDirectory;if(!a)throw new k(ne.InternalError,`Session has no working directory: ${o}`);let l=Ui(s._meta);if(!l?.owner||!l?.repo)throw new k(ne.InternalError,`Session's working directory is not a GitHub-backed git repo: ${o}`);let d=v.parse(a),c=Tt(s._meta),u=c?.branchName??await this._gitService.getCurrentBranch(d);if(!u)throw new k(ne.InternalError,`Could not determine current branch for ${d}`);let p=c?.baseBranchName??await this._gitService.getDefaultBranch(d);if(!p)throw new k(ne.InternalError,`Could not determine base branch for ${d}`);let m=p.startsWith("origin/")?p.substring(7):p,h=this._agentService.getAuthToken({resource:Ht.resource,scopes:Ht.scopes_supported});if(!h)throw new k(tr,f(1997,null),[Ht]);if(await this._gitService.hasUncommittedChanges(d)){this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Committing uncommitted changes for session ${o}`);try{await this._gitService.commitAll(d,this._formatCommitMessage(u))}catch(E){throw this._throwIfCancelled(e),new k(ne.InternalError,`Failed to commit changes before creating a pull request: ${E instanceof Error?E.message:String(E)}`)}}this._throwIfCancelled(e);let S=await this._gitService.computeSessionFileDiffs(d,{sessionUri:o,baseBranch:m});if(S===void 0)throw new k(ne.InternalError,f(2005,null));if(S!==void 0&&S.length===0)throw new k(ne.InternalError,f(2013,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Pushing branch ${u} for session ${o}`);let b=await this._gitService.hasUpstream(d,u);this._throwIfCancelled(e);try{await this._gitService.push(d,{ref:u,setUpstream:!b})}catch(E){throw this._throwIfCancelled(e),new k(ne.InternalError,`Failed to push branch '${u}': ${E instanceof Error?E.message:String(E)}`)}this._throwIfCancelled(e);let I=await this._octoKitService.findPullRequestByHeadBranch(l.owner,l.repo,u,h,t);if(I)return this._throwIfCancelled(e),await this._finalize(I,!0,o,l.owner,l.repo,h,t,e);this._throwIfCancelled(e);let _=await this._generateTitleAndDescription(s,u,m,S,t,e);this._throwIfCancelled(e);let R=_?.title??this._formatTitle(u),A=_?.description??this._formatBody(u,m);this._logService.info(`[AgentHostPullRequestOperationHandler] Creating ${this._draft?"draft ":""}PR ${l.owner}/${l.repo} ${u} -> ${m}`);let X;try{X=await this._octoKitService.createPullRequest(l.owner,l.repo,R,A,u,m,this._draft,h,t)}catch(E){this._throwIfCancelled(e);let z;try{z=await this._octoKitService.findPullRequestByHeadBranch(l.owner,l.repo,u,h,t)}catch{throw this._throwIfCancelled(e),E}if(z)return this._throwIfCancelled(e),await this._finalize(z,!0,o,l.owner,l.repo,h,t,e);throw E}return this._throwIfCancelled(e),await this._finalize(X,!1,o,l.owner,l.repo,h,t,e)}async _finalize(n,e,t,r,o,s,a,l){if(!this._autoMergeMethod)return this._onPullRequestCreated({sessionKey:t,pullRequestUrl:n.url}),this._createResult(n,this._buildMessage(n,e,"none",void 0));let d,c="none";if(n.nodeId)try{await this._octoKitService.enablePullRequestAutoMerge(n.nodeId,this._autoMergeMethod,s,a),c="enabled"}catch(u){this._throwIfCancelled(l),d=u instanceof Error?u.message:String(u),c="failed",this._logService.warn(`[AgentHostPullRequestOperationHandler] Failed to enable auto-merge for ${r}/${o}#${n.number}: ${d}`)}else d=f(1999,null),c="failed",this._logService.warn(`[AgentHostPullRequestOperationHandler] Cannot enable auto-merge for ${r}/${o}#${n.number}: missing pull request node id`);return this._onPullRequestCreated({sessionKey:t,pullRequestUrl:n.url}),this._createResult(n,this._buildMessage(n,e,c,d))}_buildMessage(n,e,t,r){let o;switch(this._autoMergeMethod){case"SQUASH":o=f(2001,null);break;case"REBASE":o=f(2000,null);break;default:o=f(1998,null);break}if(e)switch(t){case"enabled":return f(2011,null,n.number,n.url,o);case"failed":return f(2012,null,n.number,n.url,r??"");default:return f(2010,null,n.number,n.url)}switch(t){case"enabled":return f(2007,null,n.number,n.url,o);case"failed":return f(2008,null,n.number,n.url,r??"");default:return this._draft?f(2009,null,n.number,n.url):f(2006,null,n.number,n.url)}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new k(ne.InternalError,f(2003,null))}_formatTitle(n){let e=n.indexOf("/");if(e>0&&e<n.length-1){let t=n.substring(0,e),r=n.substring(e+1).replace(/[-_]+/g," ");return`${t}: ${r}`}return n.replace(/[-_]+/g," ")}_formatCommitMessage(n){return f(2004,null,n)}_formatBody(n,e){return f(2002,null,n,e)}async _generateTitleAndDescription(n,e,t,r,o,s){let a=this._agentService.getAuthToken({resource:mt.resource,scopes:mt.scopes_supported});if(!a)return;let l=mf(n.turns,{maxChars:AN}),d=this._summarizeDiffsForPrompt(r);if(!(!l&&!d))try{let c=await this._copilotApiService.utilityChatCompletion(a,{messages:this._buildTitleAndDescriptionPrompt(e,t,l,d)},{signal:o});return this._throwIfCancelled(s),this._parseTitleAndDescription(c)}catch(c){if(s.isCancellationRequested)return;this._logService.warn(`[AgentHostPullRequestOperationHandler] Failed to generate PR title and description: ${c instanceof Error?c.message:String(c)}`);return}}_buildTitleAndDescriptionPrompt(n,e,t,r){let o=[`Branch: ${n}`,`Base branch: ${e}`];return r&&o.push(`Changed files:
${r}`),t&&o.push(`Conversation (the request that produced these changes):
${t}`),[{role:"system",content:["You write clear, concise GitHub pull request titles and descriptions.",'The first line of your reply is the PR title: a short imperative summary under 72 characters, with no "Title:" prefix, no surrounding quotes, and no markdown heading.',"After the title, add one blank line, then write the PR description in GitHub-flavored markdown.","Summarize what changed and why, grounded in the conversation and changed files. Use a short paragraph and/or bullet points.","Do not invent changes that are not supported by the provided context, and do not wrap the whole reply in code fences."].join(" ")},{role:"user",content:o.join(`

`)}]}_summarizeDiffsForPrompt(n){let e=[],t=0;for(let r of n){let o=r.before?.uri,s=r.after?.uri,a=s??o??"(unknown)",l="Edit";!o&&s?l="Create":o&&!s?l="Delete":o&&s&&o!==s&&(l="Rename");let d=`- ${l}: ${this._displayUri(a)} (+${r.diff?.added??0} -${r.diff?.removed??0})`;if(e.push(d),t+=d.length+(e.length>1?1:0),t>EN){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=v.parse(n);return e.scheme==="file"?e.fsPath:e.path||n}catch{return n}}_parseTitleAndDescription(n){let e=n.trim().replace(/\r\n/g,`
`),t=/^```(?:markdown|md|text)?\s*([\s\S]*?)\s*```$/i.exec(e);if(t&&(e=t[1].trim()),!e)return;let r=e.split(`
`),o=0;for(;o<r.length&&r[o].trim().length===0;)o++;if(o>=r.length)return;let s=r[o].trim().replace(/^#+\s*/,"").replace(/^title:\s*/i,"").trim().replace(/^"(?<inner>.+)"$/,(l,d)=>d).trim();if(!s)return;let a=r.slice(o+1).join(`
`).trim().replace(/^description:\s*/i,"").trim();return{title:s,description:a}}_createResult(n,e){let t={content:{uri:n.url,contentType:"text/html"},external:!0};return{message:{markdown:e},followUp:t}}};rn=w([C(4,yr),C(5,Ye),C(6,Va),C(7,It),C(8,D)],rn);var Ya=class extends T{constructor(e,t,r){super();this._stateManager=e;this._instantiationService=t;this._gitStateService=r}registerHandlers(e){this._registry=e;let t=new G,r=u=>this._stateManager.getSessionState(u),o=u=>this._onPullRequestCreated(u),s=this._instantiationService.createInstance(rn,!1,void 0,r,o),a=this._instantiationService.createInstance(rn,!0,void 0,r,o),l=this._instantiationService.createInstance(rn,!1,"MERGE",r,o),d=this._instantiationService.createInstance(rn,!1,"SQUASH",r,o),c=this._instantiationService.createInstance(rn,!1,"REBASE",r,o);return t.add(e.registerChangesetOperationHandler(rn.OPERATION_CREATE_PR,s)),t.add(e.registerChangesetOperationHandler(rn.OPERATION_CREATE_DRAFT_PR,a)),t.add(e.registerChangesetOperationHandler(rn.OPERATION_CREATE_PR_AUTO_MERGE,l)),t.add(e.registerChangesetOperationHandler(rn.OPERATION_CREATE_PR_AUTO_SQUASH,d)),t.add(e.registerChangesetOperationHandler(rn.OPERATION_CREATE_PR_AUTO_REBASE,c)),t.add({dispose:()=>{this._registry=void 0}}),t}getOperations({gitState:e,gitHubState:t}){if(t?.pullRequestUrl)return;let r=e?.outgoingChanges??0,o=e?.uncommittedChanges??0,s=r>0||o>0;if(!(!e?.hasGitHubRemote||!s))return[{id:"create-pr",label:f(2015,null),icon:"git-pull-request-create",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-merge",label:f(2016,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-squash",label:f(2018,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-rebase",label:f(2017,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-draft-pr",label:f(2014,null),icon:"git-pull-request-draft",group:"pull-request_draft",scopes:["changeset"],status:"idle"}]}_onPullRequestCreated(e){let t=e.sessionKey;this._registry?.onDidChangeOperations(t),this._registry?.refreshSessionGitState(t),this._gitStateService.setSessionGitHubState(t,{pullRequestUrl:e.pullRequestUrl})}};Ya=w([C(1,Ie),C(2,Pr)],Ya);var so=class{constructor(n,e,t,r){this._getSessionState=n;this._onSynced=e;this._gitService=t;this._logService=r}static{this.OPERATION_SYNC="sync"}async invoke(n,e){let t=et(n.channel);if(!t)throw new k(ne.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let r=t.sessionUri,o=this._getSessionState(r);if(!o)throw new k(ut,`Session not found: ${r}`);let s=o.workingDirectory;if(!s)throw new k(ne.InternalError,`Session has no working directory: ${r}`);let a=v.parse(s),d=Tt(o._meta)?.branchName??await this._gitService.getCurrentBranch(a);if(!d)throw new k(ne.InternalError,`Could not determine current branch for ${a}`);this._throwIfCancelled(e),this._logService.info(`[AgentHostSyncOperationHandler] Syncing branch ${d} for session ${r}`);try{await this._gitService.pull(a),await this._gitService.push(a)}catch(c){throw this._throwIfCancelled(e),new k(ne.InternalError,`Failed to sync changes: ${c instanceof Error?c.message:String(c)}`)}try{await this._onSynced(r)}catch(c){this._logService.warn(`[AgentHostSyncOperationHandler] Post-sync refresh failed for session ${r}: ${c instanceof Error?c.message:String(c)}`)}return{message:{markdown:f(2026,null)}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new k(ne.InternalError,f(2025,null))}};so=w([C(2,Ye),C(3,D)],so);var Qa=class extends T{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new G,r=s=>this._stateManager.getSessionState(s),o=this._instantiationService.createInstance(so,r,s=>this._onSynced(s));return t.add(e.registerChangesetOperationHandler(so.OPERATION_SYNC,o)),t.add({dispose:()=>{this._registry=void 0}}),t}getOperations({gitState:e}){if(!(!e?.upstreamBranchName||(e?.outgoingChanges??0)===0))return[{id:so.OPERATION_SYNC,label:f(2027,null,e.outgoingChanges),icon:"sync",group:"sync",scopes:["changeset"],status:"idle"}]}async _onSynced(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};Qa=w([C(1,Ie)],Qa);var Xa=class extends T{constructor(e,t,r,o){super();this._stateManager=e;this._gitService=t;this._sessionDataService=r;this._logService=o;this._sequencer=new at;this._register(this._sessionDataService.onWillDeleteSessionData(s=>{s.waitUntil(this.disposeSessionData(s.session.toString()))}))}markFileReviewed(e,t,r,o){return this._sequencer.queue(e,()=>this._setReviewed(e,t,r,o,!0))}markFileUnreviewed(e,t,r,o){return this._sequencer.queue(e,()=>this._setReviewed(e,t,r,o,!1))}getReviewedPaths(e,t,r){return this._sequencer.queue(e,()=>this._getReviewedPaths(e,t,r))}copyReviewedRef(e,t,r){return this._sequencer.queue(t,()=>this._copyReviewedRef(e,t,r))}async _copyReviewedRef(e,t,r){let o=await this._gitService.getRepositoryRoot(r);if(!o)return;let s=Sc(this._sanitizedSessionId(e)),a=await this._gitService.revParse(o,s);if(!a)return;let l=Sc(this._sanitizedSessionId(t));await this._gitService.updateRef(o,l,a),this._logService.trace(`[AgentHostReview][_copyReviewedRef] Copied reviewed ref ${s} -> ${l} for fork`)}async _setReviewed(e,t,r,o,s){let a=await this._resolveContext(e,t,r);if(!a)return;let l=Gr(a.repoRoot,o);if(!l){this._logService.warn(`[AgentHostReview][_setReviewed] '${o.toString()}' is not under the repository root '${a.repoRoot.toString()}'; skipping`);return}let d;if(s?d=await this._gitService.captureWorkingTreeAsTree(t):d=a.baselineTree,!d)return;let c=await this._gitService.overlayPathIntoTree(a.repoRoot,a.reviewedTree,l,d);if(!c||c===a.reviewedTree)return;let u=`review: ${s?"mark":"unmark"} ${l}`,p=await this._gitService.commitTree(a.repoRoot,c,a.reviewedCommit,u);p&&(await this._gitService.updateRef(a.repoRoot,a.reviewedRef,p),this._logService.trace(`[AgentHostReview][_setReviewed] ${u} for ${e.toString()} -> ${a.reviewedRef}@${p}`))}async _getReviewedPaths(e,t,r){let o=await this._resolveContext(e,t,r);if(!o?.reviewedCommit)return new Set;let s=await this._gitService.captureWorkingTreeAsTree(t);if(!s)return new Set;let[a,l]=await Promise.all([this._gitService.diffTreePaths(o.repoRoot,o.baselineTree,s),this._gitService.diffTreePaths(o.repoRoot,o.reviewedTree,s)]);if(!a)return new Set;let d=new Set(l??[]);return new Set(a.filter(c=>!d.has(c)))}async _resolveContext(e,t,r){let o=await this._gitService.getRepositoryRoot(t);if(!o)return;let s=await this._gitService.resolveBranchBaselineCommit(t,r);if(!s)return;let a=s!==Jo?await this._gitService.revParse(o,`${s}^{tree}`):Jo;if(!a)return;let l=Sc(this._sanitizedSessionId(e)),d=await this._gitService.revParse(o,l),c=d?await this._gitService.revParse(o,`${d}^{tree}`)??a:a;return{repoRoot:o,baselineTree:a,reviewedRef:l,reviewedCommit:d,reviewedTree:c}}async disposeSessionData(e){await this._sequencer.queue(e,()=>this._disposeSessionData(e))}async _disposeSessionData(e){let t=this._stateManager.getSessionState(e)?.workingDirectory;if(!t)return;let r=await this._gitService.getRepositoryRoot(v.parse(t));if(r)try{let o=Sc(this._sanitizedSessionId(e));await this._gitService.deleteRefs(r,[o]),this._logService.trace(`[AgentHostReview][_disposeSessionData] Deleted reviewed ref for ${e}`)}catch(o){this._logService.warn(`[AgentHostReview][_disposeSessionData] Failed to dispose reviewed ref for ${e}`,o)}}_sanitizedSessionId(e){return L.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};Xa=w([C(1,Ye),C(2,Je),C(3,D)],Xa);var kN=3e4,DN=3e4,NS="peerChats",Lg="peerChatBacking",Ng=class extends T{constructor(e,t,r,o,s,a=Qw,l,d=Hf,c,u){super();this._logService=e;this._fileService=t;this._sessionDataService=r;this._productService=o;this._gitService=s;this._checkpointService=a;this._rootConfigResource=l;this._telemetryService=d;this._onDidAction=this._register(new P);this.onDidAction=this._onDidAction.event;this._onDidNotification=this._register(new P);this.onDidNotification=this._onDidNotification.event;this._onMcpNotification=this._register(new P);this.onMcpNotification=this._onMcpNotification.event;this._providers=new Map;this._sessionToProvider=new Map;this._downloadProgressInterest=new Map;this._providerSubscriptions=this._register(new G);this._peerChatCatalogWrites=new Map;this._agents=nn("agents",[]);this._skillCompletionProviderRegistered=!1;this._resourceSubscribers=new We;this._restoreSessionInFlight=new Map;this._restoreSubagentInFlight=new Map;this._pendingSessionGc=this._register(new Iu);this._resourceWatches=this._register(new Re);this._clientDispatchQueues=new Map;this._logService.info("AgentService initialized"),this._authService=new Mg(e),this._stateManager=this._register(new da(e,{hostBuildInfo:q_(this._productService),changesetStateRetention:{canEvict:R=>this._changesets?this._isChangesetEvictable(R):!1}})),this._register(this._stateManager.onDidEmitEnvelope(R=>this._onDidAction.fire(R))),this._register(this._stateManager.onDidEmitNotification(R=>this._onDidNotification.fire(R)));let p=this._register(new ta(this._stateManager,this._logService,this._rootConfigResource));this._configurationService=p;let m=c??this._register(new xr(this._fileService,this._logService));Vf(this._telemetryService,this._stateManager.rootState.config?.values);let h=new Wi([D,this._logService],[yr,this],[Ct,this._productService],[ze,p],[Oa,m],[Ye,this._gitService],[Hn,this._telemetryService],[Je,this._sessionDataService]),y=this._register(new Xs(h,!0)),S=y.createInstance(za,void 0);h.set(Va,S);let b=u??y.createInstance(Xi,void 0);h.set(It,b),this._gitStateService=this._register(y.createInstance(ja,this._stateManager)),h.set(Pr,this._gitStateService),h.set(_r,this._checkpointService),this._changesetSubscriptions=y.createInstance(Og),h.set(eo,this._changesetSubscriptions),this._changesetOperationService=this._register(y.createInstance(Ba,this._stateManager)),h.set(Ma,this._changesetOperationService);let I=this._register(y.createInstance(Xa,this._stateManager));h.set(to,I),this._changesets=this._register(y.createInstance(ui,this._stateManager)),h.set(ji,this._changesets),this._changesetCoordinator=this._register(y.createInstance(Na,this._stateManager)),this._register(this._stateManager.onDidChangeSessionActiveTurn(R=>this._changesetCoordinator.onSessionTurnActiveChanged(R.session,R.active))),this._register(this._changesetOperationService.registerContribution(y.createInstance(Ka,this._stateManager))),this._register(this._changesetOperationService.registerContribution(y.createInstance(Ya,this._stateManager))),this._register(this._changesetOperationService.registerContribution(y.createInstance(Qa,this._stateManager))),this._register(this._changesetOperationService.registerContribution(y.createInstance(Ga,this._stateManager))),this._register(this._changesetOperationService.registerContribution(y.createInstance(Ja,this._stateManager))),this._completions=this._register(y.createInstance(xa));let _=this._register(y.createInstance($a));this._register(this._completions.registerProvider(new xg(this._stateManager,_))),this._register(this._completions.registerProvider(new Zf(R=>(this._stateManager.getSessionState(R)?.turns.length??0)>0))),this._terminalManager=this._register(y.createInstance(oa,this._stateManager)),h.set(Ir,this._terminalManager),this._localTurns=new fg(this._sessionDataService,this._logService),this._sideEffects=this._register(y.createInstance(ka,this._stateManager,{getAgent:R=>this._findProviderForSession(R),sessionDataService:this._sessionDataService,localTurns:this._localTurns,agents:this._agents,copilotApiService:b,getGitHubCopilotToken:()=>this.getAuthToken({resource:mt.resource,scopes:mt.scopes_supported}),onTurnComplete:async R=>{let A=this._stateManager.getSessionState(R)?.workingDirectory;this._gitStateService.refreshSessionGitState(R,A?v.parse(A):void 0),this._gitStateService.attachSessionGitHubPullRequest(R.toString())}})),this._serverToolHost=new gg(this._stateManager,yS)}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(e.onDidSessionProgress(t=>this._sequenceSpawnedChat(t))),this._providerSubscriptions.add(this._sideEffects.registerProgressListener(e)),e.onDidMaterializeSession&&this._providerSubscriptions.add(e.onDidMaterializeSession(t=>this._onDidMaterializeSession(t))),e.onMcpNotification&&this._providerSubscriptions.add(e.onMcpNotification(t=>this._onMcpNotification.fire(t))),e.onDidChangeChatData&&this._providerSubscriptions.add(e.onDidChangeChatData(t=>this._onChatDataChanged(t))),e.onDidSpawnChat&&this._providerSubscriptions.add(e.onDidSpawnChat(t=>this._onChatSpawned(t))),this._registerSkillCompletionProvider(),this._defaultProvider||(this._defaultProvider=e.id),this._updateAgents()}_registerSkillCompletionProvider(){if(this._skillCompletionProviderRegistered)return;this._skillCompletionProviderRegistered=!0;let e=this._register(new Ag(t=>this._findProviderForSession(t)));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._changesetOperationService.invokeChangesetOperation(e)}async handleMcpRequest(e,t,r){let o=jx(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=L.uri(o.providerId,o.sessionId);return s.handleMcpRequest(a,o.serverName,t,r)}async listSessions(){this._logService.trace("[AgentService] listSessions called");let t=(await Promise.all([...this._providers.values()].map(c=>c.listSessions()))).flat(),s=(await Promise.all(t.map(async c=>{try{let u=await this._sessionDataService.tryOpenDatabase(c.session);if(!u)return c;try{let p=c.session.toString(),m=this._changesetCoordinator.getListMetadataKeys(p),h=m?{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,[Fn]:!0,[Lg]:!0,...vg,...m}:{customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,[Fn]:!0,[Lg]:!0,...vg},y=await u.object.getMetadataObject(h);if(y[Lg])return;let S=c;if(y.customTitle&&(S={...S,summary:y.customTitle}),y.isRead!==void 0&&(S={...S,isRead:y.isRead==="true"}),y.isArchived!==void 0?S={...S,isArchived:y.isArchived==="true"}:y.isDone!==void 0&&(S={...S,isArchived:y.isDone==="true"}),y[no])try{let b=JSON.parse(y[no]);S={...S,_meta:lp(S._meta,b)}}catch(b){this._logService.warn(`[AgentService][listSessions] Failed to parse Git state for ${c.session}`,b)}if(y[ro])try{let b=JSON.parse(y[ro]);S={...S,_meta:dp(S._meta,b)}}catch(b){this._logService.warn(`[AgentService][listSessions] Failed to parse GitHub state for ${c.session}`,b)}return y[Fn]!==void 0&&(S={...S,_meta:cp(S._meta,y[Fn]==="true")}),this._changesetCoordinator.decorateListEntry(S,y)}finally{u.dispose()}}catch(u){this._logService.warn(`[AgentService] Failed to read session metadata overlay for ${c.session}`,u)}return c}))).filter(c=>c!==void 0).map(c=>{let u=this._stateManager.getSessionSummary(c.session.toString());if(u){let p=u._meta!==void 0||c._meta!==void 0?{...c._meta,...u._meta}:void 0;return{...c,summary:u.title||c.summary,status:u.status,activity:u.activity,modifiedTime:Date.parse(u.modifiedAt),project:u.project?{uri:v.parse(u.project.uri),displayName:u.project.displayName}:c.project,workingDirectory:typeof u.workingDirectory=="string"?v.parse(u.workingDirectory):c.workingDirectory,changes:u.changes??c.changes,changesets:this._stateManager.getSessionState(c.session.toString())?.changesets??c.changesets,...p!==void 0?{_meta:p}:{}}}return c}),a=new Set(s.map(c=>c.session.toString())),l=[];for(let c of this._stateManager.getOverlaySessionSummaries())a.has(c.resource)||Qr(c.resource)||l.push({session:v.parse(c.resource),startTime:Date.parse(c.createdAt),modifiedTime:Date.parse(c.modifiedAt),summary:c.title,status:c.status,activity:c.activity,workingDirectory:typeof c.workingDirectory=="string"?v.parse(c.workingDirectory):void 0,...c.project?{project:{uri:v.parse(c.project.uri),displayName:c.project.displayName}}:{},changes:c.changes,...c._meta!==void 0?{_meta:c._meta}:{}});let d=l.length>0?[...s,...l]:s;return this._logService.trace(`[AgentService] listSessions returned ${d.length} sessions (${l.length} state-manager fallback)`),d}async createSession(e){let t=e?.provider??this._defaultProvider,r=t?this._providers.get(t):void 0;if(!r)throw new Error(`No agent provider registered for: ${t??"(none)"}`);if(e?.fork){let c=this._stateManager.getSessionState(e.fork.session.toString())?.turns.slice(0,e.fork.turnIndex+1)??[];if(c.length===0)e={...e,fork:void 0};else{let u=new Map;for(let m of c)u.set(m.id,H());let p=this._localTurns.resolveConcreteTurnId(be(e.fork.session).toString(),e.fork.turnId);e={...e,fork:{...e.fork,turnIdMapping:u,...p!==void 0?{turnId:p}:{}}}}}this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,o]=await Promise.all([this._sideEffects.initialize(),this._createSession(r,e)]),s=o.session;if(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),e?.progressToken){let d=this._downloadProgressInterest.get(r.id);d||(d=new Set,this._downloadProgressInterest.set(r.id,d)),d.add(s.toString())}this._logService.trace(`[AgentService] createSession returned: ${s.toString()}`);let[a,l]=await Promise.all([this._resolveCreatedSessionConfig(r,e),r.getSessionCustomizations?r.getSessionCustomizations(s).catch(d=>{this._logService.error("[AgentService] createSession: failed to resolve initial customizations",d)}):Promise.resolve(void 0)]);if(e?.fork){let d=this._stateManager.getSessionState(e.fork.session.toString()),c=be(e.fork.session).toString(),u=be(s).toString(),p=[];if(d&&e.fork.turnIdMapping){let I=d.turns.slice(0,e.fork.turnIndex+1),_=e.fork.turnIdMapping;p=I.map(R=>({...R,id:_.get(R.id)??H()})),this._persistForkedLocalTurns(s.toString(),c,u,I,p,_)}let m=f(2031,null),h=d?.title,y=h?h.startsWith(m)?h:`${m}${h}`:f(2030,null),S=this._buildInitialSummary(r,s,e,o,y),b=this._stateManager.createSession(S);b.config=a,this._stateManager.seedDefaultChatTurns(S.resource,p),b.activeClients=e.activeClient?[e.activeClient]:[],l&&l.length>0&&(b.customizations=[...l]),p.length>0&&this._sideEffects.generateForkedTitle(S.resource,void 0,p,y,h)}else{let d=this._buildInitialSummary(r,s,e,o,""),c=this._stateManager.createSession(d,{emitNotification:!o.provisional});c.config=a,c.activeClients=e?.activeClient?[e.activeClient]:[],l&&l.length>0&&(c.customizations=[...l])}if(a?.values&&Object.keys(a.values).length>0&&!o.provisional&&this._persistConfigValues(s,a.values),this._changesetCoordinator.onSessionCreated(s.toString()),!o.provisional){this._persistWorkspaceless(s,wy(this._stateManager.getSessionSummary(s.toString())?._meta)),this._stateManager.dispatchServerAction(s.toString(),{type:"session/ready"});let d=o.workingDirectory??e?.workingDirectory;this._gitStateService.refreshSessionGitState(s.toString(),d)}return s}async createChat(e,t,r){let o=e.toString(),s=this._findProviderForSession(e);if(!s)throw new Error(`[AgentService] createChat: no provider for session ${o}`);if(!this._supportsChats(s))throw new Error(`[AgentService] createChat: provider ${s.id} does not support multiple chats`);let a,l,d,c=r;if(r?.fork){let m=r.fork.source.toString(),h=this._stateManager.getChatState(m),y=h??this._stateManager.getDefaultChatState(m),S=h?m:be(m),b=y?.turns??[],I=b.findIndex(_=>_.id===r.fork.turnId);if(I<0)c={...r,fork:void 0};else{let _=b.slice(0,I+1),R=new Map;for(let E of _)R.set(E.id,H());a=_.map(E=>({...E,id:R.get(E.id)??H()})),this._persistForkedLocalTurns(o,S,t.toString(),_,a,R);let A=f(2031,null);d=y?.title||this._stateManager.getSessionState(o)?.title,l=d?d.startsWith(A)?d:`${A}${d}`:f(2029,null);let X=this._localTurns.resolveConcreteTurnId(S,r.fork.turnId);c={...r,fork:{...r.fork,turnIdMapping:R,...X!==void 0?{turnId:X}:{}}}}}let u=await this._createChat(s,t,c),p=u?.providerData;this._stateManager.addChat(o,t.toString(),{...l!==void 0?{title:l}:r?.title!==void 0?{title:r.title}:{},...a!==void 0?{turns:a}:{},...p!==void 0?{providerData:p}:{}}),this._persistPeerChat(e,t,p),u?.backingSession&&this._markPeerChatBacking(u.backingSession,t),a&&a.length>0&&l!==void 0&&this._sideEffects.generateForkedTitle(o,t.toString(),a,l,d)}async disposeChat(e,t){let r=e.toString(),o=this._findProviderForSession(e);this._stateManager.removeChat(r,t.toString()),this._removePersistedPeerChat(e,t),o&&await this._disposeChat(o,t)}_supportsChats(e){return!!e.chats}_createSession(e,t){return e.createSession(t)}async _disposeSession(e,t){await e.disposeSession(t)}_getChatMessages(e,t){return e.chats.getMessages(t)}async _interleaveLocalTurns(e,t,r){let o=await this._localTurns.loadForChat(e,t);if(o.length===0)return[...r];let s=new Set(r.map(c=>c.id)),a=new Map,l=[];for(let c of o){let u;try{u=JSON.parse(c.payload)}catch{continue}if(c.anchorTurnId===void 0)l.push(u);else if(s.has(c.anchorTurnId)){let p=a.get(c.anchorTurnId)??[];p.push(u),a.set(c.anchorTurnId,p)}}let d=[...l];for(let c of r){d.push(c);let u=a.get(c.id);u&&d.push(...u)}return d}_persistForkedLocalTurns(e,t,r,o,s,a){for(let l=0;l<o.length;l++){let d=o[l];if(!this._localTurns.isLocal(t,d.id))continue;let c=this._localTurns.resolveConcreteTurnId(t,d.id),u=c!==void 0?a.get(c):void 0;this._localTurns.record(e,r,s[l],u)}}_createChat(e,t,r){let o=r&&(r.title!==void 0||r.model!==void 0)?{...r.title!==void 0?{title:r.title}:{},...r.model!==void 0?{model:r.model}:{}}:void 0;return r?.fork?e.chats.fork(t,r.fork,o):e.chats.createChat(t,o)}async _disposeChat(e,t){await e.chats.disposeChat(t)}_buildInitialSummary(e,t,r,o,s){let a=new Date().toISOString();return{resource:t.toString(),provider:e.id,title:s,status:1,createdAt:a,modifiedAt:a,...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},workingDirectory:(o.workingDirectory??r?.workingDirectory)?.toString(),...r&&!r.fork&&!r.workingDirectory?{_meta:cp(void 0,!0)}:{}}}_onDidMaterializeSession(e){let t=e.session.toString();this._clearDownloadProgressInterest(t);let r=this._stateManager.getSessionState(t);if(!r){this._logService.warn(`[AgentService] onDidMaterializeSession for unknown session: ${t}`);return}let o=this._stateManager.getSessionSummary(t);if(!o){this._logService.warn(`[AgentService] onDidMaterializeSession missing summary for session: ${t}`);return}let s={...o,...e.project?{project:{uri:e.project.uri.toString(),displayName:e.project.displayName}}:{},workingDirectory:e.workingDirectory?.toString()??o.workingDirectory,modifiedAt:new Date().toISOString()},a=r.config?.values;a&&Object.keys(a).length>0&&this._persistConfigValues(e.session,a),this._persistWorkspaceless(e.session,wy(s._meta)),this._stateManager.markSessionPersisted(t,s),this._stateManager.dispatchServerAction(t,{type:"session/ready"}),this._gitStateService.refreshSessionGitState(e.session.toString(),e.workingDirectory),this._changesetCoordinator.onSessionMaterialized(t)}_clearDownloadProgressInterest(e){for(let[t,r]of this._downloadProgressInterest)r.delete(e)&&r.size===0&&this._downloadProgressInterest.delete(t)}emitDownloadProgress(e,t,r,o,s){let a=this._downloadProgressInterest.get(e);if(!a||a.size===0)return;let l=s?r:o,d=f(2028,null,t);this._stateManager.emitProgress({progressToken:e,progress:r,total:l,message:d}),s&&this._downloadProgressInterest.delete(e)}_persistWorkspaceless(e,t){let r;try{r=this._sessionDataService.openDatabase(e)}catch(o){this._logService.warn(`[AgentService] Failed to open session database to persist workspaceless for ${e.toString()}: ${ke(o)}`);return}r.object.setMetadata(Fn,t?"true":"false").catch(o=>{this._logService.warn(`[AgentService] Failed to persist workspaceless for ${e.toString()}: ${ke(o)}`)}).finally(()=>{r.dispose()})}_persistConfigValues(e,t){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()}: ${ke(o)}`);return}r.object.setMetadata("configValues",JSON.stringify(t)).catch(o=>{this._logService.warn(`[AgentService] Failed to persist configValues for ${e.toString()}: ${ke(o)}`)}).finally(()=>{r.dispose()})}async _resolveCreatedSessionConfig(e,t){if(!(!t?.config&&!t?.workingDirectory))try{let r=await e.resolveSessionConfig({provider:e.id,workingDirectory:t.workingDirectory,config:t.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),t.config?{schema:{type:"object",properties:{}},values:t.config}:void 0}}async resolveSessionConfig(e){let t=e.provider??this._defaultProvider,r=t?this._providers.get(t):void 0;if(!r)throw new Error(`No agent provider registered for: ${t??"(none)"}`);return r.resolveSessionConfig(e)}async sessionConfigCompletions(e){let t=e.provider??this._defaultProvider,r=t?this._providers.get(t):void 0;if(!r)throw new Error(`No agent provider registered for: ${t??"(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 t=this._findProviderForSession(e);t&&(await this._disposeSession(t,e),this._sessionToProvider.delete(e.toString()),this._clearDownloadProgressInterest(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,t){this._logService.trace(`[AgentService] subscribe: ${e.toString()}`);let r=e.toString();this.addSubscriber(e,t);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=et(r);if(s&&a&&!this._stateManager.getSessionState(a.sessionUri)&&(await this._changesetCoordinator.restoreSessionIfChangesetSubscription(e,d=>this.restoreSession(d)),s=this._stateManager.getSnapshot(r)),!s){let d=zs(r);if(d!==void 0){if(!this._stateManager.getSessionState(d)){let c=v.parse(d),u=gt(c);u?await this._restoreSubagentSession(d,u.parentSession):await this.restoreSession(c)}s=this._stateManager.getSnapshot(r)}}if(!s)if(await this._changesetCoordinator.tryHandleSubscribe(e,c=>this.restoreSession(c)))s=this._stateManager.getSnapshot(r);else{let c=gt(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(!ce(r)&&l&&Tt(l._meta)===void 0){let d=l.workingDirectory?v.parse(l.workingDirectory):void 0;this._gitStateService.refreshSessionGitState(r,d)}return s}catch(o){throw this.unsubscribe(e,t),o}}addSubscriber(e,t){let r=this._resourceSubscribers.get(e),o=!r||r.size===0;r||(r=new Set,this._resourceSubscribers.set(e,r)),r.add(t),this._cancelPendingSessionGc(e),o&&this._changesetCoordinator.onFirstSubscriber(e)}unsubscribe(e,t){let r=this._resourceSubscribers.get(e);r&&(r.delete(t),!(r.size>0)&&(this._resourceSubscribers.delete(e),this._changesetCoordinator.onLastSubscriber(e),this._stateManager.onChangesetLivenessChanged(),!this._maybeScheduleSessionGc(e)&&this._maybeEvictIdleSession(e)))}_maybeScheduleSessionGc(e){if(gt(e))return!1;let t=e.toString(),r=this._stateManager.getSessionState(t);return!r||r.turns.length>0||r.activeTurn!==void 0?!1:(this._pendingSessionGc.set(e,Kt(()=>{this._pendingSessionGc.deleteAndDispose(e),this._runSessionGc(e).catch(o=>{this._logService.error(o,`[AgentService] GC failed for ${t}`)})},kN)),!0)}_cancelPendingSessionGc(e){this._pendingSessionGc.deleteAndDispose(e)}async _runSessionGc(e){let t=e.toString();if(this._resourceSubscribers.has(e))return;let r=this._stateManager.getSessionState(t);r&&(r.turns.length>0||r.activeTurn!==void 0)||(this._logService.info(`[AgentService] GC: disposing empty unsubscribed session ${t}`),await this.disposeSession(e))}_maybeEvictIdleSession(e){}_isChangesetEvictable(e){let t=v.parse(e);if(this._resourceSubscribers.has(t))return!1;let r=et(e);if(!r)return!1;let o=v.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,t){let r=gt(e);for(;r;){if(gr(r.parentSession,t))return!0;r=gt(r.parentSession)}return!1}dispatchAction(e,t,r,o){this._logService.trace(`[AgentService] dispatchAction: type=${t.type}, clientId=${r}, clientSeq=${o}`,t);let s=ce(e)?e:void 0,a=s?fe(s):e,l=this._clientDispatchQueues.get(r);if(!l&&!this._needsAsyncRewrite(a,t)){this._dispatchActionNow(e,a,t,r,o);return}let d=(l??Promise.resolve()).then(async()=>{let c=this._needsAsyncRewrite(a,t)?await this._rewriteUserMessageAttachments(a,t,r):t;this._dispatchActionNow(e,a,c,r,o)}).catch(c=>{this._logService.error(`[AgentService] async dispatchAction failed: ${ke(c)}`)});this._clientDispatchQueues.set(r,d.finally(()=>{this._clientDispatchQueues.get(r)===d&&this._clientDispatchQueues.delete(r)}))}_dispatchActionNow(e,t,r,o,s){let a={clientId:o,clientSeq:s};this._stateManager.dispatchClientAction(e,r,a),r.type==="root/configChanged"&&this._configurationService.persistRootConfig(),this._sideEffects.handleAction(e,r,o)}_needsAsyncRewrite(e,t){if(t.type!=="chat/turnStarted"&&t.type!=="chat/pendingMessageSet")return!1;let r=this._attachmentsRoot(e).toString();return!!t.message.attachments?.some(o=>this._isRewritableAttachment(o,r))}_isRewritableAttachment(e,t){return e.type==="embeddedResource"?!0:e.type==="resource"?!(e.displayKind==="directory"||e.uri.startsWith(t)):!1}_attachmentsRoot(e){return te(this._sessionDataService.getSessionDataDir(v.parse(e)),Wp)}async _rewriteUserMessageAttachments(e,t,r){let o=t.message.attachments;if(!o?.length)return t;let s=this._attachmentsRoot(e),a=s.toString(),l=await Promise.all(o.map(d=>this._rewriteSingleAttachment(d,s,a,r)));return{...t,message:{...t.message,attachments:l}}}async _rewriteSingleAttachment(e,t,r,o){try{if(e.type==="embeddedResource"){let s=un(e.data).buffer,a=this._attachmentBasename(e.label,e.contentType);return this._writeAndRewrite(e,s,a,t)}if(e.type==="resource"&&this._isRewritableAttachment(e,r)){let s=v.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,yp(s.path));return this._writeAndRewrite(e,a,l,t)}}catch(s){this._logService.warn(`[AgentService] Failed to rewrite attachment '${e.label}': ${ke(s)}`)}return e}async _fileExistsSafe(e){try{return await this._fileService.exists(e)}catch{return!1}}async _readClientResource(e,t){let r=t?qa(e,t):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,t,r,o){let s=H(),a=te(o,s,r);await this._fileService.writeFile(a,U.wrap(t));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,t){let r=(e||"attachment").replace(/[\\/:*?"<>|\u0000-\u001f]/g,"_");if(ed(v.file(r)))return r;let o=t?hT(t):void 0;return o?`${r}${o}`:r}async resourceList(e){let t;try{t=await this._fileService.resolve(e)}catch{throw new k(ye.NotFound,`Directory not found: ${e.toString()}`)}if(!t.isDirectory)throw new k(ye.NotFound,`Not a directory: ${e.toString()}`);return{entries:(t.children??[]).map(o=>({name:o.name,type:o.isDirectory?"directory":"file"}))}}async restoreSession(e){let t=e.toString();if(this._stateManager.getSessionState(t))return;let r=this._restoreSessionInFlight.get(t);if(r)return r;let o=this._doRestoreSession(e,t);this._restoreSessionInFlight.set(t,o);try{await o}finally{this._restoreSessionInFlight.get(t)===o&&this._restoreSessionInFlight.delete(t)}}async _doRestoreSession(e,t){if(this._stateManager.getSessionState(t))return;let r=this._findProviderForSession(e);if(!r)throw new k(ut,`No agent for session: ${t}`);let o=await this._getSessionMetadataForRestore(r,e);if(!o)throw new k(ut,`Session not found on backend: ${t}`);let s=v.parse(be(t)),a;try{a=await this._getChatMessages(r,s)}catch(x){if(x instanceof k)throw x;let B=x instanceof Error?x.message:String(x);throw new k(Lo,`Failed to restore session ${t}: ${B}`)}let l=o.summary??"Session",d,c,u,p,m,h,y,S=this._sessionDataService.tryOpenDatabase?.(e);if(S)try{let x=await S;if(x)try{let B=await x.object.getMetadataObject({customTitle:!0,isRead:!0,isArchived:!0,isDone:!0,configValues:!0,[Fn]:!0,...vg,...gf});if(B.customTitle&&(l=B.customTitle),B.isRead!==void 0&&(d=B.isRead==="true"),B.isArchived!==void 0?c=B.isArchived==="true":B.isDone!==void 0&&(c=B.isDone==="true"),h=B,h[Yo])try{p=JSON.parse(h[Yo])}catch(K){this._logService.warn(`[AgentService] Failed to parse changes summary for ${t}: ${ke(K)}`)}if(m=B,m[no])try{let K=JSON.parse(m[no]);y={[pd]:K}}catch(K){this._logService.warn(`[AgentService] Failed to parse Git state for ${t}: ${ke(K)}`)}if(m[ro])try{let K=JSON.parse(m[ro]);y={...y||{},[fd]:K}}catch(K){this._logService.warn(`[AgentService] Failed to parse GitHub state for ${t}: ${ke(K)}`)}if(B[Fn]!==void 0&&(y=cp(y,B[Fn]==="true")),B.configValues)try{u=JSON.parse(B.configValues)}catch(K){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${t}: ${ke(K)}`)}}finally{x.dispose()}}catch{}let b=1;d&&(b|=32),c&&(b|=64);let I={resource:t,provider:r.id,title:l,status:b,createdAt:new Date(o.startTime).toISOString(),modifiedAt:new Date(o.modifiedTime).toISOString(),...o.project?{project:{uri:o.project.uri.toString(),displayName:o.project.displayName}}:{},changes:o.changes??p,workingDirectory:o.workingDirectory?.toString(),_meta:y||o._meta?{...o._meta??{},...y??{}}:void 0},[_,R]=await Promise.all([this._getChatDraft(e,s),this._readPersistedChatTitle(e,s)]),A=await this._interleaveLocalTurns(t,s.toString(),a);this._stateManager.restoreSession(I,A,{draft:_,defaultChatTitle:R});let X=[];X.push((async()=>{if(r.getSubagentSessions)try{let x=await r.getSubagentSessions(e);for(let B of x)this._registerRestoredSubagent(B,I,t)}catch(x){this._logService.warn(`[AgentService] restoreSession failed to eagerly register subagents session=${t}`,x)}})()),X.push(this._restorePeerChats(r,e)),this._changesetCoordinator.onSessionRestored(t,h??{}),o._meta&&this._stateManager.setSessionMeta(t,o._meta);let[E,z]=await Promise.all([this._resolveCreatedSessionConfig(r,{workingDirectory:o.workingDirectory,config:u}),r.getSessionCustomizations?r.getSessionCustomizations(e).catch(x=>{this._logService.error("[AgentService] restoreSession: failed to resolve session customizations",x)}):Promise.resolve(void 0),...X]);E&&this._stateManager.setSessionConfig(t,E),z&&z.length>0&&this._stateManager.setSessionCustomizations(t,z),this._logService.info(`[AgentService] Restored session ${t} with ${a.length} turns`),this._gitStateService.refreshSessionGitState(t,o.workingDirectory),this._gitStateService.attachSessionGitHubPullRequest(t)}async _restorePeerChats(e,t){let r=await this._readPersistedPeerChatCatalog(t);if(r!==void 0){await this._restorePeerChatsFromCatalog(e,t,r);return}await this._migrateLegacyPeerChats(e,t)}async _migrateLegacyPeerChats(e,t){let r=await e.listLegacyChats?.(t);if(!r||r.length===0){await this._enqueuePeerChatCatalogWrite(t,()=>[]);return}let o=r.map(s=>({uri:s.uri.toString(),...s.providerData!==void 0?{providerData:s.providerData}:{}}));await this._restorePeerChatsFromCatalog(e,t,o),await this._enqueuePeerChatCatalogWrite(t,()=>[...o])}async _restorePeerChatsFromCatalog(e,t,r){let o=await Promise.all(r.map(async s=>{let a;try{a=v.parse(s.uri)}catch(p){this._logService.warn(`[AgentService] Skipping malformed persisted peer chat URI '${s.uri}': ${ke(p)}`);return}if(e.materializeChat)try{await e.materializeChat(a,s.providerData)}catch(p){this._logService.warn(`[AgentService] Failed to materialize peer chat ${s.uri}: ${ke(p)}`)}let l=[];try{l=await this._getChatMessages(e,a)}catch(p){this._logService.warn(`[AgentService] Failed to load history for peer chat ${a.toString()}: ${ke(p)}`)}let[d,c]=await Promise.all([this._readPersistedChatTitle(t,a),this._getChatDraft(t,a)]),u=await this._interleaveLocalTurns(t.toString(),a.toString(),l);return{chatUri:a,title:d,turns:u,draft:c,providerData:s.providerData}}));for(let s of o){if(!s)continue;let{chatUri:a,title:l,turns:d,draft:c,providerData:u}=s;this._stateManager.restoreChat(t.toString(),a.toString(),{title:l,turns:d,draft:c,...u!==void 0?{providerData:u}:{}})}}_onChatDataChanged(e){let t=zs(e.chat);if(t===void 0){this._logService.warn(`[AgentService] onDidChangeChatData for malformed chat URI: ${e.chat.toString()}`);return}this._persistPeerChat(v.parse(t),e.chat,e.providerData)}_sequenceSpawnedChat(e){let t=Oo.toSpawnEvent(e);t&&this._onChatSpawned(t)}_onChatSpawned(e){this._stateManager.addChat(e.session.toString(),e.chat.toString(),{...e.title!==void 0?{title:e.title}:{},...e.parent?{origin:{kind:"tool",chat:e.parent.chat.toString(),toolCallId:e.parent.toolCallId},interactivity:"read-only"}:{}})}async _readPersistedPeerChatCatalog(e){let t=await this._sessionDataService.tryOpenDatabase?.(e);if(t)try{let r=await t.object.getMetadata(NS);if(r===void 0)return;let o=JSON.parse(r);if(!Array.isArray(o)){this._logService.warn(`[AgentService] Ignoring malformed peer-chat catalog for ${e.toString()}`);return}return o.filter(s=>typeof s?.uri=="string").map(s=>({uri:s.uri,...typeof s.providerData=="string"?{providerData:s.providerData}:{}}))}catch(r){this._logService.warn(`[AgentService] Failed to read peer-chat catalog for ${e.toString()}: ${ke(r)}`);return}finally{t.dispose()}}_markPeerChatBacking(e,t){let r;try{r=this._sessionDataService.openDatabase(e)}catch(o){this._logService.warn(`[AgentService] Failed to open backing session database to mark peer-chat backing for ${e.toString()}: ${ke(o)}`);return}r.object.setMetadata(Lg,t.toString()).catch(o=>{this._logService.warn(`[AgentService] Failed to mark peer-chat backing for ${e.toString()}: ${ke(o)}`)}).finally(()=>{r.dispose()})}_persistPeerChat(e,t,r){let o=t.toString();return this._enqueuePeerChatCatalogWrite(e,s=>{let a=s.filter(l=>l.uri!==o);return a.push({uri:o,...r!==void 0?{providerData:r}:{}}),a})}_removePersistedPeerChat(e,t){let r=t.toString();return this._enqueuePeerChatCatalogWrite(e,o=>o.filter(s=>s.uri!==r))}_enqueuePeerChatCatalogWrite(e,t){let r=e.toString(),s=(this._peerChatCatalogWrites.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this._applyPeerChatCatalogWrite(e,t));return this._peerChatCatalogWrites.set(r,s.finally(()=>{this._peerChatCatalogWrites.get(r)===s&&this._peerChatCatalogWrites.delete(r)})),s}async _applyPeerChatCatalogWrite(e,t){let r=await this._sessionDataService.tryOpenDatabase?.(e);if(r)try{let o=[];try{let a=await r.object.getMetadata(NS);if(a!==void 0){let l=JSON.parse(a);Array.isArray(l)&&(o=l.filter(d=>typeof d?.uri=="string"))}}catch(a){this._logService.warn(`[AgentService] Replacing malformed peer-chat catalog for ${e.toString()}: ${ke(a)}`)}let s=t(o);await r.object.setMetadata(NS,JSON.stringify(s))}catch(o){this._logService.warn(`[AgentService] Failed to persist peer-chat catalog for ${e.toString()}: ${ke(o)}`)}finally{r.dispose()}}async _readPersistedChatTitle(e,t){let r=await this._sessionDataService.tryOpenDatabase?.(e);if(r)try{return await r.object.getMetadata(`customChatTitle:${t.toString()}`)??void 0}catch{return}finally{r.dispose()}}async _getChatDraft(e,t){let r=await this._sessionDataService.tryOpenDatabase(e);if(r)try{return await r.object.getChatDraft(t)}finally{r.dispose()}}async _getSessionMetadataForRestore(e,t){let r=t.toString();if(e.getSessionMetadata)try{return await e.getSessionMetadata(t)}catch(o){if(o instanceof k)throw o;try{return await this._getSessionMetadataFromCatalog(e,t)}catch(s){if(s instanceof k){let a=o instanceof Error?o.message:String(o);throw new k(s.code,`Failed to get session metadata for ${r}: ${a}; ${s.message}`,s.data)}throw s}}return this._getSessionMetadataFromCatalog(e,t)}async _getSessionMetadataFromCatalog(e,t){let r=t.toString(),o;try{o=await e.listSessions()}catch(s){if(s instanceof k)throw s;let a=s instanceof Error?s.message:String(s);throw new k(Lo,`Failed to list sessions for ${r}: ${a}`)}return o.find(s=>s.session.toString()===r)}async resourceRead(e){let t=$w(e.toString());if(t)return this._fetchSessionDbContent(t);let r=qw(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(o){let s=o instanceof Error?o:new Error(String(o)),a=ii(s);throw a===1?new k(ye.NotFound,`Content not found: ${e.toString()}`):a===6?new k(ye.PermissionDenied,`Permission denied: ${e.toString()}`):new k(Lo,`Failed to read content: ${e.toString()}: ${ke(s)}`)}}async resourceWrite(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri),r;e.encoding==="base64"?r=un(e.data):r=U.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(t,r,o,s,e):e.createOnly?await this._fileService.createFile(t,r,{overwrite:!1}):await this._fileService.writeFile(t,r),{}}catch(a){if(a instanceof k)throw a;if(a instanceof lt&&a.fileOperationResult===3)throw new k(ye.Conflict,`ifMatch precondition failed for: ${t.toString()}`);let l=fn(a);throw l==="EntryExists"?new k(ye.AlreadyExists,`File already exists: ${t.toString()}`):l==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Failed to write file: ${t.toString()}`)}}async _resourceWriteWithMode(e,t,r,o,s){let a,l;try{let u=await this._fileService.readFile(e);a=u.value,l=u.etag}catch(u){if(fn(u)!=="EntryNotFound")throw u}if(s.ifMatch!==void 0&&(a===void 0||l!==s.ifMatch))throw new k(ye.Conflict,`ifMatch precondition failed for: ${e.toString()}`);let d=a??U.alloc(0),c;switch(r){case"append":{let u=d.byteLength,p=Math.max(0,u-o);c=U.concat([d.slice(0,p),t,d.slice(p,u)]);break}case"insert":{let u=Math.min(o,d.byteLength);c=U.concat([d.slice(0,u),t,d.slice(u,d.byteLength)]);break}case"truncate":default:{let u=Math.min(o,d.byteLength);c=U.concat([d.slice(0,u),t]);break}}await this._fileService.writeFile(e,c,{etag:l})}async resourceCopy(e){let t=v.parse(e.source),r=v.parse(e.destination);try{return await this._fileService.copy(t,r,!e.failIfExists),{}}catch(o){let s=fn(o);throw s==="EntryExists"?new k(ye.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Source not found: ${t.toString()}`)}}async resourceDelete(e){let t=v.parse(e.uri);try{return await this._fileService.del(t,{recursive:e.recursive}),{}}catch(r){throw fn(r)==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMove(e){let t=v.parse(e.source),r=v.parse(e.destination);try{return await this._fileService.move(t,r,!e.failIfExists),{}}catch(o){let s=fn(o);throw s==="EntryExists"?new k(ye.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Source not found: ${t.toString()}`)}}async resourceResolve(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{let r=await this._fileService.stat(t),o;return r.isSymbolicLink&&e.followSymlinks===!1?o="symlink":r.isDirectory?o="directory":o="file",{uri:t.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 fn(r)==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMkdir(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{let r=await this._fileService.stat(t).catch(()=>{});if(r&&!r.isDirectory)throw new k(ye.AlreadyExists,`Path exists and is not a directory: ${t.toString()}`);return await this._fileService.createFolder(t),{}}catch(r){throw r instanceof k?r:fn(r)==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Failed to create directory: ${t.toString()}`)}}async createResourceWatch(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{await this._fileService.stat(t)}catch(o){throw fn(o)==="NoPermissions"?new k(ye.PermissionDenied,`Permission denied: ${t.toString()}`):new k(ye.NotFound,`Resource not found: ${t.toString()}`)}return{channel:D_({root:t.toString(),recursive:e.recursive===!0,excludes:e.excludes,includes:e.includes})}}onResourceWatchSubscribed(e){let t=M_(e);if(!t)return;let r=this._resourceWatches.get(e);if(r)return r.subscribers++,r.pendingGc&&r.pendingGc.clear(),r.descriptor;let o=new G;try{let s=v.parse(t.root),a={recursive:t.recursive,excludes:t.excludes?.items??[],includes:t.includes?.items};if(t.recursive)o.add(this._fileService.watch(s,a)),o.add(this._fileService.onDidFilesChange(l=>{let d=ON(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,MN(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:t,subscribers:1,disposables:o,pendingGc:o.add(new At),dispose:()=>o.dispose()}),t}onResourceWatchUnsubscribed(e){let t=this._resourceWatches.get(e);return t?(t.subscribers=Math.max(0,t.subscribers-1),t.subscribers>0||(t.pendingGc.value=Kt(()=>{let r=this._resourceWatches.get(e);!r||r.subscribers>0||this._resourceWatches.deleteAndDispose(e)},DN)),!0):!1}_dispatchResourceWatchChanges(e,t){if(t.length===0)return;let r=t.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 t of this._providers.values())e.push(t.shutdown());await Promise.all(e),this._sessionToProvider.clear(),this._downloadProgressInterest.clear()}async _fetchSessionDbContent(e){let t=v.parse(e.sessionUri),r=this._sessionDataService.openDatabase(t);try{let o=await r.object.readFileEditContent(e.toolCallId,e.filePath);if(!o)throw new k(ye.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?o.beforeContent:o.afterContent;if(!s)throw new k(ye.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 k(ye.NotFound,`git service unavailable for: ${e.repoRelativePath}`);let t=this._stateManager.getSessionState(e.sessionUri)?.workingDirectory;if(!t)throw new k(ye.NotFound,`Session has no working directory for git-blob URI: ${e.sessionUri}`);let r=await this._gitService.showBlob(v.parse(t),e.sha,e.repoRelativePath);if(!r)throw new k(ye.NotFound,`git blob not found: ${e.sha}:${e.repoRelativePath}`);return{data:r.toString(),encoding:"utf-8",contentType:"text/plain"}}async _restoreSubagentSession(e,t){if(this._stateManager.getSessionState(e))return;let r=this._restoreSubagentInFlight.get(e);if(r)return r;let o=this._doRestoreSubagentSession(e,t);this._restoreSubagentInFlight.set(e,o);try{await o}finally{this._restoreSubagentInFlight.get(e)===o&&this._restoreSubagentInFlight.delete(e)}}async _doRestoreSubagentSession(e,t){let r=t.toString();if(!this._stateManager.getSessionState(r))try{await this.restoreSession(t)}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 m of s){for(let h of m.responseParts)if(h.kind==="toolCall"){let y=h.toolCall,S=y.status==="completed"||y.status==="running"?y.content:void 0;if(S){for(let b of S)if(b.type==="subagent"&&b.resource===e){a=b;break}}}if(a)break}let l=[],d=this._findProviderForSession(t);if(d)try{l=await this._getChatMessages(d,v.parse(e))}catch(m){this._logService.warn(`[AgentService] Failed to load subagent turns for ${e}`,m)}let c=a?.title??"Subagent",u=new Date().toISOString(),p=await this._interleaveLocalTurns(t.toString(),e,l);this._stateManager.restoreSession({resource:e,provider:"subagent",title:c,status:1,createdAt:u,modifiedAt:u,...o?.project?{project:o.project}:{}},p),this._logService.info(`[AgentService] Restored subagent session: ${e} with ${l.length} turn(s)`)}_registerRestoredSubagent(e,t,r){let o=e.resource.toString();if(this._stateManager.getSessionState(o))return;let s=new Date().toISOString();this._stateManager.restoreSession({resource:o,provider:"subagent",title:e.title,status:1,createdAt:s,modifiedAt:s,...t.project?{project:t.project}:{}},[...e.turns]);let a=Bs(r,e.toolCallId);this._stateManager.addChat(r,a,{title:e.title,turns:[...e.turns],origin:{kind:"tool",chat:be(r),toolCallId:e.toolCallId},interactivity:"read-only"})}_findProviderForSession(e){let t=typeof e=="string"?e:e.toString(),r=this._sessionToProvider.get(t);if(r)return this._providers.get(r);let o=L.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 MN(i){let n=[];for(let e of i.rawAdded)n.push({resource:e,type:1});for(let e of i.rawUpdated)n.push({resource:e,type:0});for(let e of i.rawDeleted)n.push({resource:e,type:2});return n}function ON(i,n){let e=[],t=(r,o)=>{Kr(r,n)&&e.push({resource:r,type:o})};for(let r of i.rawAdded)t(r,1);for(let r of i.rawUpdated)t(r,0);for(let r of i.rawDeleted)t(r,2);return e}import{CopilotClient as i4,RuntimeConnection as o4}from"@github/copilot-sdk";import*as zt from"fs/promises";import*as T1 from"os";var Qx=Object.create(null);function g(i,n){if(Ve(n)){let e=Qx[n];if(e===void 0)throw new Error(`${i} references an unknown codicon: ${n}`);n=e}return Qx[i]=n,{id:i}}var Xx={add:g("add",6e4),plus:g("plus",6e4),gistNew:g("gist-new",6e4),repoCreate:g("repo-create",6e4),lightbulb:g("lightbulb",60001),lightBulb:g("light-bulb",60001),repo:g("repo",60002),repoDelete:g("repo-delete",60002),gistFork:g("gist-fork",60003),repoForked:g("repo-forked",60003),gitPullRequest:g("git-pull-request",60004),gitPullRequestAbandoned:g("git-pull-request-abandoned",60004),recordKeys:g("record-keys",60005),keyboard:g("keyboard",60005),tag:g("tag",60006),gitPullRequestLabel:g("git-pull-request-label",60006),tagAdd:g("tag-add",60006),tagRemove:g("tag-remove",60006),person:g("person",60007),personFollow:g("person-follow",60007),personOutline:g("person-outline",60007),personFilled:g("person-filled",60007),sourceControl:g("source-control",60008),mirror:g("mirror",60009),mirrorPublic:g("mirror-public",60009),star:g("star",60010),starAdd:g("star-add",60010),starDelete:g("star-delete",60010),starEmpty:g("star-empty",60010),comment:g("comment",60011),commentAdd:g("comment-add",60011),alert:g("alert",60012),warning:g("warning",60012),search:g("search",60013),searchSave:g("search-save",60013),logOut:g("log-out",60014),signOut:g("sign-out",60014),logIn:g("log-in",60015),signIn:g("sign-in",60015),eye:g("eye",60016),eyeUnwatch:g("eye-unwatch",60016),eyeWatch:g("eye-watch",60016),circleFilled:g("circle-filled",60017),primitiveDot:g("primitive-dot",60017),closeDirty:g("close-dirty",60017),debugBreakpoint:g("debug-breakpoint",60017),debugBreakpointDisabled:g("debug-breakpoint-disabled",60017),debugHint:g("debug-hint",60017),terminalDecorationSuccess:g("terminal-decoration-success",60017),primitiveSquare:g("primitive-square",60018),edit:g("edit",60019),pencil:g("pencil",60019),info:g("info",60020),issueOpened:g("issue-opened",60020),gistPrivate:g("gist-private",60021),gitForkPrivate:g("git-fork-private",60021),lock:g("lock",60021),mirrorPrivate:g("mirror-private",60021),close:g("close",60022),removeClose:g("remove-close",60022),x:g("x",60022),repoSync:g("repo-sync",60023),sync:g("sync",60023),clone:g("clone",60024),desktopDownload:g("desktop-download",60024),beaker:g("beaker",60025),microscope:g("microscope",60025),vm:g("vm",60026),deviceDesktop:g("device-desktop",60026),file:g("file",60027),more:g("more",60028),ellipsis:g("ellipsis",60028),kebabHorizontal:g("kebab-horizontal",60028),mailReply:g("mail-reply",60029),reply:g("reply",60029),organization:g("organization",60030),organizationFilled:g("organization-filled",60030),organizationOutline:g("organization-outline",60030),newFile:g("new-file",60031),fileAdd:g("file-add",60031),newFolder:g("new-folder",60032),fileDirectoryCreate:g("file-directory-create",60032),trash:g("trash",60033),trashcan:g("trashcan",60033),history:g("history",60034),clock:g("clock",60034),folder:g("folder",60035),fileDirectory:g("file-directory",60035),symbolFolder:g("symbol-folder",60035),logoGithub:g("logo-github",60036),markGithub:g("mark-github",60036),github:g("github",60036),terminal:g("terminal",60037),console:g("console",60037),repl:g("repl",60037),zap:g("zap",60038),symbolEvent:g("symbol-event",60038),error:g("error",60039),stop:g("stop",60039),variable:g("variable",60040),symbolVariable:g("symbol-variable",60040),array:g("array",60042),symbolArray:g("symbol-array",60042),symbolModule:g("symbol-module",60043),symbolPackage:g("symbol-package",60043),symbolNamespace:g("symbol-namespace",60043),symbolObject:g("symbol-object",60043),symbolMethod:g("symbol-method",60044),symbolFunction:g("symbol-function",60044),symbolConstructor:g("symbol-constructor",60044),symbolBoolean:g("symbol-boolean",60047),symbolNull:g("symbol-null",60047),symbolNumeric:g("symbol-numeric",60048),symbolNumber:g("symbol-number",60048),symbolStructure:g("symbol-structure",60049),symbolStruct:g("symbol-struct",60049),symbolParameter:g("symbol-parameter",60050),symbolTypeParameter:g("symbol-type-parameter",60050),symbolKey:g("symbol-key",60051),symbolText:g("symbol-text",60051),symbolReference:g("symbol-reference",60052),goToFile:g("go-to-file",60052),symbolEnum:g("symbol-enum",60053),symbolValue:g("symbol-value",60053),symbolRuler:g("symbol-ruler",60054),symbolUnit:g("symbol-unit",60054),activateBreakpoints:g("activate-breakpoints",60055),archive:g("archive",60056),arrowBoth:g("arrow-both",60057),arrowDown:g("arrow-down",60058),arrowLeft:g("arrow-left",60059),arrowRight:g("arrow-right",60060),arrowSmallDown:g("arrow-small-down",60061),arrowSmallLeft:g("arrow-small-left",60062),arrowSmallRight:g("arrow-small-right",60063),arrowSmallUp:g("arrow-small-up",60064),arrowUp:g("arrow-up",60065),bell:g("bell",60066),bold:g("bold",60067),book:g("book",60068),bookmark:g("bookmark",60069),debugBreakpointConditionalUnverified:g("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:g("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:g("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:g("debug-breakpoint-data-unverified",60072),debugBreakpointData:g("debug-breakpoint-data",60073),debugBreakpointDataDisabled:g("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:g("debug-breakpoint-log-unverified",60074),debugBreakpointLog:g("debug-breakpoint-log",60075),debugBreakpointLogDisabled:g("debug-breakpoint-log-disabled",60075),briefcase:g("briefcase",60076),broadcast:g("broadcast",60077),browser:g("browser",60078),bug:g("bug",60079),calendar:g("calendar",60080),caseSensitive:g("case-sensitive",60081),check:g("check",60082),checklist:g("checklist",60083),chevronDown:g("chevron-down",60084),chevronLeft:g("chevron-left",60085),chevronRight:g("chevron-right",60086),chevronUp:g("chevron-up",60087),chromeClose:g("chrome-close",60088),chromeMaximize:g("chrome-maximize",60089),chromeMinimize:g("chrome-minimize",60090),chromeRestore:g("chrome-restore",60091),circleOutline:g("circle-outline",60092),circle:g("circle",60092),debugBreakpointUnverified:g("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:g("terminal-decoration-incomplete",60092),circleSlash:g("circle-slash",60093),circuitBoard:g("circuit-board",60094),clearAll:g("clear-all",60095),clippy:g("clippy",60096),closeAll:g("close-all",60097),cloudDownload:g("cloud-download",60098),cloudUpload:g("cloud-upload",60099),code:g("code",60100),collapseAll:g("collapse-all",60101),colorMode:g("color-mode",60102),commentDiscussion:g("comment-discussion",60103),creditCard:g("credit-card",60105),dash:g("dash",60108),dashboard:g("dashboard",60109),database:g("database",60110),debugContinue:g("debug-continue",60111),debugDisconnect:g("debug-disconnect",60112),debugPause:g("debug-pause",60113),debugRestart:g("debug-restart",60114),debugStart:g("debug-start",60115),debugStepInto:g("debug-step-into",60116),debugStepOut:g("debug-step-out",60117),debugStepOver:g("debug-step-over",60118),debugStop:g("debug-stop",60119),debug:g("debug",60120),deviceCameraVideo:g("device-camera-video",60121),deviceCamera:g("device-camera",60122),deviceMobile:g("device-mobile",60123),diffAdded:g("diff-added",60124),diffIgnored:g("diff-ignored",60125),diffModified:g("diff-modified",60126),diffRemoved:g("diff-removed",60127),diffRenamed:g("diff-renamed",60128),diff:g("diff",60129),diffSidebyside:g("diff-sidebyside",60129),discard:g("discard",60130),editorLayout:g("editor-layout",60131),emptyWindow:g("empty-window",60132),exclude:g("exclude",60133),extensions:g("extensions",60134),eyeClosed:g("eye-closed",60135),fileBinary:g("file-binary",60136),fileCode:g("file-code",60137),fileMedia:g("file-media",60138),filePdf:g("file-pdf",60139),fileSubmodule:g("file-submodule",60140),fileSymlinkDirectory:g("file-symlink-directory",60141),fileSymlinkFile:g("file-symlink-file",60142),fileZip:g("file-zip",60143),files:g("files",60144),filter:g("filter",60145),flame:g("flame",60146),foldDown:g("fold-down",60147),foldUp:g("fold-up",60148),fold:g("fold",60149),folderActive:g("folder-active",60150),folderOpened:g("folder-opened",60151),gear:g("gear",60152),gift:g("gift",60153),gistSecret:g("gist-secret",60154),gist:g("gist",60155),gitCommit:g("git-commit",60156),gitCompare:g("git-compare",60157),compareChanges:g("compare-changes",60157),gitMerge:g("git-merge",60158),githubAction:g("github-action",60159),githubAlt:g("github-alt",60160),globe:g("globe",60161),grabber:g("grabber",60162),graph:g("graph",60163),gripper:g("gripper",60164),heart:g("heart",60165),home:g("home",60166),horizontalRule:g("horizontal-rule",60167),hubot:g("hubot",60168),inbox:g("inbox",60169),issueReopened:g("issue-reopened",60171),issues:g("issues",60172),italic:g("italic",60173),jersey:g("jersey",60174),json:g("json",60175),bracket:g("bracket",60175),kebabVertical:g("kebab-vertical",60176),key:g("key",60177),law:g("law",60178),lightbulbAutofix:g("lightbulb-autofix",60179),linkExternal:g("link-external",60180),link:g("link",60181),listOrdered:g("list-ordered",60182),listUnordered:g("list-unordered",60183),liveShare:g("live-share",60184),loading:g("loading",60185),location:g("location",60186),mailRead:g("mail-read",60187),mail:g("mail",60188),markdown:g("markdown",60189),megaphone:g("megaphone",60190),mention:g("mention",60191),milestone:g("milestone",60192),gitPullRequestMilestone:g("git-pull-request-milestone",60192),mortarBoard:g("mortar-board",60193),move:g("move",60194),multipleWindows:g("multiple-windows",60195),mute:g("mute",60196),noNewline:g("no-newline",60197),note:g("note",60198),octoface:g("octoface",60199),openPreview:g("open-preview",60200),package:g("package",60201),paintcan:g("paintcan",60202),pin:g("pin",60203),play:g("play",60204),run:g("run",60204),plug:g("plug",60205),preserveCase:g("preserve-case",60206),preview:g("preview",60207),project:g("project",60208),pulse:g("pulse",60209),question:g("question",60210),quote:g("quote",60211),radioTower:g("radio-tower",60212),reactions:g("reactions",60213),references:g("references",60214),refresh:g("refresh",60215),regex:g("regex",60216),remoteExplorer:g("remote-explorer",60217),remote:g("remote",60218),remove:g("remove",60219),replaceAll:g("replace-all",60220),replace:g("replace",60221),repoClone:g("repo-clone",60222),repoForcePush:g("repo-force-push",60223),repoPull:g("repo-pull",60224),repoPush:g("repo-push",60225),report:g("report",60226),requestChanges:g("request-changes",60227),rocket:g("rocket",60228),rootFolderOpened:g("root-folder-opened",60229),rootFolder:g("root-folder",60230),rss:g("rss",60231),ruby:g("ruby",60232),saveAll:g("save-all",60233),saveAs:g("save-as",60234),save:g("save",60235),screenFull:g("screen-full",60236),screenNormal:g("screen-normal",60237),searchStop:g("search-stop",60238),server:g("server",60240),settingsGear:g("settings-gear",60241),settings:g("settings",60242),shield:g("shield",60243),smiley:g("smiley",60244),sortPrecedence:g("sort-precedence",60245),splitHorizontal:g("split-horizontal",60246),splitVertical:g("split-vertical",60247),squirrel:g("squirrel",60248),starFull:g("star-full",60249),starHalf:g("star-half",60250),symbolClass:g("symbol-class",60251),symbolColor:g("symbol-color",60252),symbolConstant:g("symbol-constant",60253),symbolEnumMember:g("symbol-enum-member",60254),symbolField:g("symbol-field",60255),symbolFile:g("symbol-file",60256),symbolInterface:g("symbol-interface",60257),symbolKeyword:g("symbol-keyword",60258),symbolMisc:g("symbol-misc",60259),symbolOperator:g("symbol-operator",60260),symbolProperty:g("symbol-property",60261),wrench:g("wrench",60261),wrenchSubaction:g("wrench-subaction",60261),symbolSnippet:g("symbol-snippet",60262),tasklist:g("tasklist",60263),telescope:g("telescope",60264),textSize:g("text-size",60265),threeBars:g("three-bars",60266),thumbsdown:g("thumbsdown",60267),thumbsup:g("thumbsup",60268),tools:g("tools",60269),triangleDown:g("triangle-down",60270),triangleLeft:g("triangle-left",60271),triangleRight:g("triangle-right",60272),triangleUp:g("triangle-up",60273),twitter:g("twitter",60274),unfold:g("unfold",60275),unlock:g("unlock",60276),unmute:g("unmute",60277),unverified:g("unverified",60278),verified:g("verified",60279),versions:g("versions",60280),vmActive:g("vm-active",60281),vmOutline:g("vm-outline",60282),vmRunning:g("vm-running",60283),watch:g("watch",60284),whitespace:g("whitespace",60285),wholeWord:g("whole-word",60286),window:g("window",60287),wordWrap:g("word-wrap",60288),zoomIn:g("zoom-in",60289),zoomOut:g("zoom-out",60290),listFilter:g("list-filter",60291),listFlat:g("list-flat",60292),listSelection:g("list-selection",60293),selection:g("selection",60293),listTree:g("list-tree",60294),debugBreakpointFunctionUnverified:g("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:g("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:g("debug-breakpoint-function-disabled",60296),debugStackframeActive:g("debug-stackframe-active",60297),circleSmallFilled:g("circle-small-filled",60298),debugStackframeDot:g("debug-stackframe-dot",60298),terminalDecorationMark:g("terminal-decoration-mark",60298),debugStackframe:g("debug-stackframe",60299),debugStackframeFocused:g("debug-stackframe-focused",60299),debugBreakpointUnsupported:g("debug-breakpoint-unsupported",60300),symbolString:g("symbol-string",60301),debugReverseContinue:g("debug-reverse-continue",60302),debugStepBack:g("debug-step-back",60303),debugRestartFrame:g("debug-restart-frame",60304),debugAlt:g("debug-alt",60305),callIncoming:g("call-incoming",60306),callOutgoing:g("call-outgoing",60307),menu:g("menu",60308),expandAll:g("expand-all",60309),feedback:g("feedback",60310),gitPullRequestReviewer:g("git-pull-request-reviewer",60310),groupByRefType:g("group-by-ref-type",60311),ungroupByRefType:g("ungroup-by-ref-type",60312),account:g("account",60313),gitPullRequestAssignee:g("git-pull-request-assignee",60313),bellDot:g("bell-dot",60314),debugConsole:g("debug-console",60315),library:g("library",60316),output:g("output",60317),runAll:g("run-all",60318),syncIgnored:g("sync-ignored",60319),pinned:g("pinned",60320),githubInverted:g("github-inverted",60321),serverProcess:g("server-process",60322),serverEnvironment:g("server-environment",60323),pass:g("pass",60324),issueClosed:g("issue-closed",60324),stopCircle:g("stop-circle",60325),playCircle:g("play-circle",60326),record:g("record",60327),debugAltSmall:g("debug-alt-small",60328),vmConnect:g("vm-connect",60329),cloud:g("cloud",60330),merge:g("merge",60331),export:g("export",60332),graphLeft:g("graph-left",60333),magnet:g("magnet",60334),notebook:g("notebook",60335),redo:g("redo",60336),checkAll:g("check-all",60337),pinnedDirty:g("pinned-dirty",60338),passFilled:g("pass-filled",60339),circleLargeFilled:g("circle-large-filled",60340),circleLarge:g("circle-large",60341),circleLargeOutline:g("circle-large-outline",60341),combine:g("combine",60342),gather:g("gather",60342),table:g("table",60343),variableGroup:g("variable-group",60344),typeHierarchy:g("type-hierarchy",60345),typeHierarchySub:g("type-hierarchy-sub",60346),typeHierarchySuper:g("type-hierarchy-super",60347),gitPullRequestCreate:g("git-pull-request-create",60348),runAbove:g("run-above",60349),runBelow:g("run-below",60350),notebookTemplate:g("notebook-template",60351),debugRerun:g("debug-rerun",60352),workspaceTrusted:g("workspace-trusted",60353),workspaceUntrusted:g("workspace-untrusted",60354),workspaceUnknown:g("workspace-unknown",60355),terminalCmd:g("terminal-cmd",60356),terminalDebian:g("terminal-debian",60357),terminalLinux:g("terminal-linux",60358),terminalPowershell:g("terminal-powershell",60359),terminalTmux:g("terminal-tmux",60360),terminalUbuntu:g("terminal-ubuntu",60361),terminalBash:g("terminal-bash",60362),arrowSwap:g("arrow-swap",60363),copy:g("copy",60364),personAdd:g("person-add",60365),filterFilled:g("filter-filled",60366),wand:g("wand",60367),debugLineByLine:g("debug-line-by-line",60368),inspect:g("inspect",60369),layers:g("layers",60370),layersDot:g("layers-dot",60371),layersActive:g("layers-active",60372),compass:g("compass",60373),compassDot:g("compass-dot",60374),compassActive:g("compass-active",60375),azure:g("azure",60376),issueDraft:g("issue-draft",60377),gitPullRequestClosed:g("git-pull-request-closed",60378),gitPullRequestDraft:g("git-pull-request-draft",60379),debugAll:g("debug-all",60380),debugCoverage:g("debug-coverage",60381),runErrors:g("run-errors",60382),folderLibrary:g("folder-library",60383),debugContinueSmall:g("debug-continue-small",60384),beakerStop:g("beaker-stop",60385),graphLine:g("graph-line",60386),graphScatter:g("graph-scatter",60387),pieChart:g("pie-chart",60388),bracketDot:g("bracket-dot",60389),bracketError:g("bracket-error",60390),lockSmall:g("lock-small",60391),azureDevops:g("azure-devops",60392),verifiedFilled:g("verified-filled",60393),newline:g("newline",60394),layout:g("layout",60395),layoutActivitybarLeft:g("layout-activitybar-left",60396),layoutActivitybarRight:g("layout-activitybar-right",60397),layoutPanelLeft:g("layout-panel-left",60398),layoutPanelCenter:g("layout-panel-center",60399),layoutPanelJustify:g("layout-panel-justify",60400),layoutPanelRight:g("layout-panel-right",60401),layoutPanel:g("layout-panel",60402),layoutSidebarLeft:g("layout-sidebar-left",60403),layoutSidebarRight:g("layout-sidebar-right",60404),layoutStatusbar:g("layout-statusbar",60405),layoutMenubar:g("layout-menubar",60406),layoutCentered:g("layout-centered",60407),target:g("target",60408),indent:g("indent",60409),recordSmall:g("record-small",60410),errorSmall:g("error-small",60411),terminalDecorationError:g("terminal-decoration-error",60411),arrowCircleDown:g("arrow-circle-down",60412),arrowCircleLeft:g("arrow-circle-left",60413),arrowCircleRight:g("arrow-circle-right",60414),arrowCircleUp:g("arrow-circle-up",60415),layoutSidebarRightOff:g("layout-sidebar-right-off",60416),layoutPanelOff:g("layout-panel-off",60417),layoutSidebarLeftOff:g("layout-sidebar-left-off",60418),blank:g("blank",60419),heartFilled:g("heart-filled",60420),map:g("map",60421),mapHorizontal:g("map-horizontal",60421),foldHorizontal:g("fold-horizontal",60421),mapFilled:g("map-filled",60422),mapHorizontalFilled:g("map-horizontal-filled",60422),foldHorizontalFilled:g("fold-horizontal-filled",60422),circleSmall:g("circle-small",60423),bellSlash:g("bell-slash",60424),bellSlashDot:g("bell-slash-dot",60425),commentUnresolved:g("comment-unresolved",60426),gitPullRequestGoToChanges:g("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:g("git-pull-request-new-changes",60428),searchFuzzy:g("search-fuzzy",60429),commentDraft:g("comment-draft",60430),send:g("send",60431),sparkle:g("sparkle",60432),insert:g("insert",60433),mic:g("mic",60434),thumbsdownFilled:g("thumbsdown-filled",60435),thumbsupFilled:g("thumbsup-filled",60436),coffee:g("coffee",60437),snake:g("snake",60438),game:g("game",60439),vr:g("vr",60440),chip:g("chip",60441),piano:g("piano",60442),music:g("music",60443),micFilled:g("mic-filled",60444),repoFetch:g("repo-fetch",60445),copilot:g("copilot",60446),lightbulbSparkle:g("lightbulb-sparkle",60447),robot:g("robot",60448),sparkleFilled:g("sparkle-filled",60449),diffSingle:g("diff-single",60450),diffMultiple:g("diff-multiple",60451),surroundWith:g("surround-with",60452),share:g("share",60453),gitStash:g("git-stash",60454),gitStashApply:g("git-stash-apply",60455),gitStashPop:g("git-stash-pop",60456),vscode:g("vscode",60457),vscodeInsiders:g("vscode-insiders",60458),codeOss:g("code-oss",60459),runCoverage:g("run-coverage",60460),runAllCoverage:g("run-all-coverage",60461),coverage:g("coverage",60462),githubProject:g("github-project",60463),mapVertical:g("map-vertical",60464),foldVertical:g("fold-vertical",60464),mapVerticalFilled:g("map-vertical-filled",60465),foldVerticalFilled:g("fold-vertical-filled",60465),goToSearch:g("go-to-search",60466),percentage:g("percentage",60467),sortPercentage:g("sort-percentage",60467),attach:g("attach",60468),goToEditingSession:g("go-to-editing-session",60469),editSession:g("edit-session",60470),codeReview:g("code-review",60471),copilotWarning:g("copilot-warning",60472),python:g("python",60473),copilotLarge:g("copilot-large",60474),copilotWarningLarge:g("copilot-warning-large",60475),keyboardTab:g("keyboard-tab",60476),copilotBlocked:g("copilot-blocked",60477),copilotNotConnected:g("copilot-not-connected",60478),flag:g("flag",60479),lightbulbEmpty:g("lightbulb-empty",60480),symbolMethodArrow:g("symbol-method-arrow",60481),copilotUnavailable:g("copilot-unavailable",60482),repoPinned:g("repo-pinned",60483),keyboardTabAbove:g("keyboard-tab-above",60484),keyboardTabBelow:g("keyboard-tab-below",60485),gitPullRequestDone:g("git-pull-request-done",60486),mcp:g("mcp",60487),extensionsLarge:g("extensions-large",60488),layoutPanelDock:g("layout-panel-dock",60489),layoutSidebarLeftDock:g("layout-sidebar-left-dock",60490),layoutSidebarRightDock:g("layout-sidebar-right-dock",60491),copilotInProgress:g("copilot-in-progress",60492),copilotError:g("copilot-error",60493),copilotSuccess:g("copilot-success",60494),chatSparkle:g("chat-sparkle",60495),searchSparkle:g("search-sparkle",60496),editSparkle:g("edit-sparkle",60497),copilotSnooze:g("copilot-snooze",60498),sendToRemoteAgent:g("send-to-remote-agent",60499),commentDiscussionSparkle:g("comment-discussion-sparkle",60500),chatSparkleWarning:g("chat-sparkle-warning",60501),chatSparkleError:g("chat-sparkle-error",60502),collection:g("collection",60503),newCollection:g("new-collection",60504),thinking:g("thinking",60505),build:g("build",60506),commentDiscussionQuote:g("comment-discussion-quote",60507),cursor:g("cursor",60508),eraser:g("eraser",60509),fileText:g("file-text",60510),quotes:g("quotes",60512),rename:g("rename",60513),runWithDeps:g("run-with-deps",60514),debugConnected:g("debug-connected",60515),strikethrough:g("strikethrough",60516),openInProduct:g("open-in-product",60517),indexZero:g("index-zero",60518),agent:g("agent",60519),editCode:g("edit-code",60520),repoSelected:g("repo-selected",60521),skip:g("skip",60522),mergeInto:g("merge-into",60523),gitBranchChanges:g("git-branch-changes",60524),gitBranchStagedChanges:g("git-branch-staged-changes",60525),gitBranchConflicts:g("git-branch-conflicts",60526),gitBranch:g("git-branch",60527),gitBranchCreate:g("git-branch-create",60527),gitBranchDelete:g("git-branch-delete",60527),searchLarge:g("search-large",60528),terminalGitBash:g("terminal-git-bash",60529),windowActive:g("window-active",60530),forward:g("forward",60531),download:g("download",60532),clockface:g("clockface",60533),unarchive:g("unarchive",60534),sessionInProgress:g("session-in-progress",60535),collectionSmall:g("collection-small",60536),vmSmall:g("vm-small",60537),cloudSmall:g("cloud-small",60538),addSmall:g("add-small",60539),removeSmall:g("remove-small",60540),worktreeSmall:g("worktree-small",60541),worktree:g("worktree",60542),screenCut:g("screen-cut",60543),ask:g("ask",60544),openai:g("openai",60545),claude:g("claude",60546),openInWindow:g("open-in-window",60547),newSession:g("new-session",60548),terminalSecure:g("terminal-secure",60549),chatImport:g("chat-import",60550),chatExport:g("chat-export",60551),shareWindow:g("share-window",60552),circleSlashCompact:g("circle-slash-compact",60553),copilotCompact:g("copilot-compact",60554),folderOpenedCompact:g("folder-opened-compact",60555),folderCompact:g("folder-compact",60556),gearCompact:g("gear-compact",60557),gitBranchCompact:g("git-branch-compact",60558),libraryCompact:g("library-compact",60559),recordKeysCompact:g("record-keys-compact",60560),remoteCompact:g("remote-compact",60561),repoForkedCompact:g("repo-forked-compact",60562),repoCompact:g("repo-compact",60563),shieldCompact:g("shield-compact",60564),sparkleCompact:g("sparkle-compact",60565),symbolColorCompact:g("symbol-color-compact",60566),windowCompact:g("window-compact",60567),errorCompact:g("error-compact",60568),warningCompact:g("warning-compact",60569),passCompact:g("pass-compact",60570),important:g("important",60571),importantCompact:g("important-compact",60572),rocketCompact:g("rocket-compact",60573),unpin:g("unpin",60574),addCompact:g("add-compact",60575),attachCompact:g("attach-compact",60576),beakerCompact:g("beaker-compact",60577),checkCompact:g("check-compact",60578),checklistCompact:g("checklist-compact",60579),chevronDownCompact:g("chevron-down-compact",60580),chevronLeftCompact:g("chevron-left-compact",60581),chevronRightCompact:g("chevron-right-compact",60582),chevronUpCompact:g("chevron-up-compact",60583),circleFilledCompact:g("circle-filled-compact",60584),circleSmallFilledCompact:g("circle-small-filled-compact",60585),closeCompact:g("close-compact",60586),collapseAllCompact:g("collapse-all-compact",60587),commentCompact:g("comment-compact",60588),commentUnresolvedCompact:g("comment-unresolved-compact",60589),debugConnectedCompact:g("debug-connected-compact",60590),debugDisconnectCompact:g("debug-disconnect-compact",60591),editCompact:g("edit-compact",60592),fileMediaCompact:g("file-media-compact",60593),gitFetch:g("git-fetch",60594),lightbulbCompact:g("lightbulb-compact",60595),loadingCompact:g("loading-compact",60596),passFilledCompact:g("pass-filled-compact",60597),projectCompact:g("project-compact",60598),refreshCompact:g("refresh-compact",60599),searchCompact:g("search-compact",60600),sessionInProgressCompact:g("session-in-progress-compact",60601),syncCompact:g("sync-compact",60602),terminalCompact:g("terminal-compact",60603),vmPending:g("vm-pending",60604),worktreeCompact:g("worktree-compact",60605),developerTools:g("developer-tools",60606),cloudCompact:g("cloud-compact",60607),agentCompact:g("agent-compact",60608),askCompact:g("ask-compact",60609),settingsCompact:g("settings-compact",60610),vmCompact:g("vm-compact",60611),runCompact:g("run-compact",60612),gitPullRequestComment:g("git-pull-request-comment",60613),gitPullRequestError:g("git-pull-request-error",60614),rightPanelHide:g("right-panel-hide",60615),rightPanelShow:g("right-panel-show",60616),vscodeInsidersOutline:g("vscode-insiders-outline",60617),vscodeOutline:g("vscode-outline",60618),voiceMode:g("voice-mode",60619),voiceModeCompact:g("voice-mode-compact",60620)};var LN={dialogError:g("dialog-error","error"),dialogWarning:g("dialog-warning","warning"),dialogInfo:g("dialog-info","info"),dialogClose:g("dialog-close","close"),treeItemExpanded:g("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:g("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:g("tree-filter-on-type-off","list-selection"),treeFilterClear:g("tree-filter-clear","close"),treeItemLoading:g("tree-item-loading","loading"),menuSelection:g("menu-selection","check"),menuSubmenu:g("menu-submenu","chevron-right"),menuBarMore:g("menubar-more","more"),scrollbarButtonLeft:g("scrollbar-button-left","triangle-left"),scrollbarButtonRight:g("scrollbar-button-right","triangle-right"),scrollbarButtonUp:g("scrollbar-button-up","triangle-up"),scrollbarButtonDown:g("scrollbar-button-down","triangle-down"),toolBarMore:g("toolbar-more","more"),quickInputBack:g("quick-input-back","arrow-left"),dropDownButton:g("drop-down-button",60084),symbolCustomColor:g("symbol-customcolor",60252),exportIcon:g("export",60332),workspaceUnspecified:g("workspace-unspecified",60355),newLine:g("newline",60394),thumbsDownFilled:g("thumbsdown-filled",60435),thumbsUpFilled:g("thumbsup-filled",60436),gitFetch:g("git-fetch",60445),lightbulbSparkleAutofix:g("lightbulb-sparkle-autofix",60447),debugBreakpointPending:g("debug-breakpoint-pending",60377),chatImport:g("chat-import",60550),chatExport:g("chat-export",60551)},Ug={...Xx,...LN};var Zx;(n=>{function i(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}n.isThemeColor=i})(Zx||={});var Pc;(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(I){let _=r.exec(I.id);if(!_)return o(Ug.error);let[,R,A]=_,X=["codicon","codicon-"+R];return A&&X.push("codicon-modifier-"+A.substring(1)),X}b.asClassNameArray=o;function s(I){return o(I).join(" ")}b.asClassName=s;function a(I){return"."+o(I).join(".")}b.asCSSSelector=a;function l(I){return!!I&&typeof I=="object"&&typeof I.id=="string"&&(typeof I.color>"u"||Zx.isThemeColor(I.color))}b.isThemeIcon=l;let d=new RegExp(`^\\$\\((${b.iconNameExpression}(?:${b.iconModifierExpression})?)\\)$`);function c(I){let _=d.exec(I);if(!_)return;let[,R]=_;return{id:R}}b.fromString=c;function u(I){return{id:I}}b.fromId=u;function p(I,_){let R=I.id,A=R.lastIndexOf("~");return A!==-1&&(R=R.substring(0,A)),_&&(R=`${R}~${_}`),{id:R}}b.modify=p;function m(I){let _=I.id.lastIndexOf("~");if(_!==-1)return I.id.substring(_+1)}b.getModifier=m;function h(I,_){return I.id===_.id&&I.color?.id===_.color?.id}b.isEqual=h;function y(I){return I?.id===Ug.file.id}b.isFile=y;function S(I){return I?.id===Ug.folder.id}b.isFolder=S})(Pc||={});var US=new RegExp(`\\$\\(${Pc.iconNameExpression}(?:${Pc.iconModifierExpression})?\\)`,"g"),NN=new RegExp(`(\\\\)?${US.source}`,"g");function eP(i){return i.replace(NN,(n,e)=>e?n:`\\${n}`)}var bme=new RegExp(`\\\\${US.source}`,"g");var Cme=new RegExp(`(\\s)?(\\\\)?${US.source}(\\s)?`,"g");var Ime=new RegExp(`\\$\\(${Pc.iconNameCharacter}+\\)`,"g");var Fg=class i{static lift(n){let e=new i(n.value,n);return e.uris=n.uris,e.baseUri=n.baseUri?v.revive(n.baseUri):void 0,e}constructor(n="",e=!1){if(this.value=n,typeof this.value!="string")throw kh("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(n,e=0){return this.value+=FS(this.supportThemeIcons?eP(n):n).replace(/([ \t]+)/g,(t,r)=>"&nbsp;".repeat(r.length)).replace(/\>/gm,"\\>").replace(/\n/g,e===1?`\\
`:`

`),this}appendMarkdown(n){return this.value+=n,this}appendCodeblock(n,e){return this.value+=`
${UN(e,n)}
`,this}appendLink(n,e,t){return this.value+="[",this.value+=this._escape(e,"]"),this.value+="](",this.value+=this._escape(String(n),")"),t&&(this.value+=` "${this._escape(this._escape(t,'"'),")")}"`),this.value+=")",this}_escape(n,e){let t=new RegExp(Cn(e),"g");return n.replace(t,(r,o)=>n.charAt(o-1)!=="\\"?`\\${r}`:r)}};function FS(i){return i.replace(/[\\`*_{}[\]()#+!~]/g,"\\$&").replace(/^([ \t]*)-/gm,"$1\\-")}function es(i){return i.replace(/[\\\]]/g,"\\$&")}function UN(i,n){let e=i.match(/^`+/gm)?.reduce((r,o)=>r.length>o.length?r:o).length??0,t=e>=3?e+1:3;return[`${"`".repeat(t)}${n}`,i,`${"`".repeat(t)}`].join(`
`)}function it(i){let n=Math.max(0,...(i.match(/`+/g)??[]).map(o=>o.length)),e="`".repeat(n+1),r=i.startsWith("`")||i.endsWith("`")?` ${i} `:i;return`${e}${r}${e}`}function tP(i,n,e){return Math.min(Math.max(i,n),e)}function Hg(i){if(i>=1e6){let n=i/1e6,e=Math.floor(n*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 FN(i,n=[],e={}){let r=new $g(i).scan();return new Wg(r,i,n,e).parse()}function Za(i,n=[],e={}){let t=new $g(i).scan();if(t.length===0||t[0].type!==11)return new Ac(void 0,i);if(!t.slice(1).some(l=>l.type===11))return new Ac(void 0,i);let o=new Wg(t,i,n,e).parse(),s=t[t.length-1],a=s.type===13?i.substring(s.startOffset):"";return new Ac(o,a)}var Ac=class{constructor(n,e){this.header=n;this.body=e}getStringValue(n){if(this.header&&this.header.type==="map"){let e=this.header.properties.find(t=>t.key.value===n);if(e&&e.value.type==="scalar")return e.value.value}}getStringArrayValue(n){if(this.header&&this.header.type==="map"){let e=this.header.properties.find(t=>t.key.value===n);if(e&&e.value.type==="sequence")return e.value.items.filter(t=>t.type==="scalar").map(t=>t.value);if(e&&e.value.type==="scalar")return e.value.format==="none"?HN(e.value.value,0).map(t=>t.value):[e.value.value]}}getBooleanValue(n){let e=this.getStringValue(n);if(e==="true")return!0;if(e==="false")return!1}};function HN(i,n=0){let e=FN(`[${i}]`),t=n-1,r=[];if(e&&e.type==="sequence")for(let o of e.items)o.type==="scalar"&&r.push({...o,startOffset:o.startOffset+t,endOffset:o.endOffset+t});else r.push({type:"scalar",value:i,rawValue:i,startOffset:n,endOffset:i.length+n,format:"none"});return r}function ht(i,n,e,t){return{type:i,startOffset:n,endOffset:e,rawValue:t?.rawValue??"",value:t?.value??"",format:t?.format??"none",indent:t?.indent??0}}var $g=class{constructor(n){this.input=n;this.pos=0;this.tokens=[];this.flowDepth=0;this.seenBlockColon=!1;this.seenDocumentStart=0}scan(n=1){for(;this.pos<this.input.length&&(this.scanLine(),!(this.seenDocumentStart>n)););return this.tokens.push(ht(13,this.pos,this.pos)),this.tokens}scanLine(){if(this.seenBlockColon=!1,this.peekChar()===`
`){this.tokens.push(ht(8,this.pos,this.pos+1)),this.pos++;return}if(this.peekChar()==="\r"){let t=this.pos+(this.input[this.pos+1]===`
`?2:1);this.tokens.push(ht(8,this.pos,t)),this.pos=t;return}let n=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(ht(9,n,this.pos,{indent:e})),this.pos>=this.input.length||this.peekChar()===`
`||this.peekChar()==="\r"){if(this.pos<this.input.length){let t=this.pos,r=this.peekChar()==="\r"&&this.input[this.pos+1]===`
`?this.pos+2:this.pos+1;this.tokens.push(ht(8,t,r)),this.pos=r}return}if(e===0&&this.input.length-this.pos>=3){let t=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(t==="-"&&r==="-"&&o==="-"&&a){this.tokens.push(ht(11,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline(),this.seenDocumentStart++;return}if(t==="."&&r==="."&&o==="."&&a){this.tokens.push(ht(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 n=this.peekChar();if(n==="#"){this.scanComment();break}else if(n==="{")this.flowDepth++,this.tokens.push(ht(4,this.pos,this.pos+1)),this.pos++;else if(n==="}"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(ht(5,this.pos,this.pos+1)),this.pos++;else if(n==="[")this.flowDepth++,this.tokens.push(ht(6,this.pos,this.pos+1)),this.pos++;else if(n==="]"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(ht(7,this.pos,this.pos+1)),this.pos++;else if(n===","&&this.flowDepth>0)this.tokens.push(ht(3,this.pos,this.pos+1)),this.pos++;else if(n==="-"&&this.isBlockDash())this.tokens.push(ht(2,this.pos,this.pos+1)),this.pos++;else if(n===":"&&this.isBlockColon())this.tokens.push(ht(1,this.pos,this.pos+1)),this.pos++,this.flowDepth===0&&(this.seenBlockColon=!0);else if(n===":"&&this.flowDepth>0&&this.lastTokenIsJsonLike())this.tokens.push(ht(1,this.pos,this.pos+1)),this.pos++;else if(n==="'"||n==='"')this.scanQuotedScalar(n);else if((n==="|"||n===">")&&this.flowDepth===0&&this.isBlockScalarStart()){this.scanBlockScalar(n);break}else this.scanUnquotedScalar()}}isBlockDash(){let n=this.input[this.pos+1];return n===void 0||n===" "||n==="	"||n===`
`||n==="\r"}isBlockColon(){if(this.seenBlockColon&&this.flowDepth===0)return!1;let n=this.input[this.pos+1];return n===void 0||n===" "||n==="	"||n===`
`||n==="\r"||this.flowDepth>0&&(n===","||n==="}"||n==="]")}lastTokenIsJsonLike(){for(let n=this.tokens.length-1;n>=0;n--){let e=this.tokens[n];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(n){let e=this.pos;this.pos++;let t="",r=0;for(;this.pos<this.input.length;){let s=this.input[this.pos];if(s===n){if(n==="'"&&this.input[this.pos+1]==="'"){t+="'",this.pos+=2,r=0;continue}this.pos++;let a=this.input.substring(e,this.pos);this.tokens.push(ht(0,e,this.pos,{rawValue:a,value:t,format:n==="'"?"single":"double"}));return}if(n==='"'&&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":t+=`
`;break;case"t":t+="	";break;case"\\":t+="\\";break;case'"':t+='"';break;case"/":t+="/";break;case"r":t+="\r";break;case"0":t+="\0";break;case"a":t+="\x07";break;case"b":t+="\b";break;case"e":t+="\x1B";break;case"v":t+="\v";break;case"f":t+="\f";break;case" ":t+=" ";break;case"_":t+="\xA0";break;case"x":{let l=this.input.substring(this.pos+2,this.pos+4),d=parseInt(l,16);l.length===2&&!isNaN(d)?(t+=String.fromCharCode(d),this.pos+=4):(t+="\\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)?(t+=String.fromCodePoint(d),this.pos+=6):(t+="\\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)?(t+=String.fromCodePoint(d),this.pos+=10):(t+="\\U",this.pos+=2),r=0;continue}default:t+="\\"+(a??"");break}this.pos+=2,r=0;continue}if(s===`
`||s==="\r"){r>0&&(t=t.substring(0,t.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?t+=`
`.repeat(a):t+=" ";continue}s===" "||s==="	"?r++:r=0,t+=s,this.pos++}let o=this.input.substring(e,this.pos);this.tokens.push(ht(0,e,this.pos,{rawValue:o,value:t,format:n==="'"?"single":"double"}))}scanUnquotedScalar(){let n=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>n&&(this.input[this.pos-1]===" "||this.input[this.pos-1]==="	"))break;this.pos++,r!==" "&&r!=="	"&&(e=this.pos)}let t=this.input.substring(n,e);this.tokens.push(ht(0,n,e,{rawValue:t,value:t,format:"none"}))}isBlockScalarStart(){let n=this.pos+1;for(;n<this.input.length;){let t=this.input[n];if(t>="1"&&t<="9"){n++;continue}if(t==="+"||t==="-"){n++;continue}break}for(;n<this.input.length&&(this.input[n]===" "||this.input[n]==="	");)n++;if(n>=this.input.length)return!0;let e=this.input[n];return e===`
`||e==="\r"||e==="#"}scanBlockScalar(n){let e=this.pos;this.pos++;let t=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"&&t===0?(t=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=t>0?o+t: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 S=this.input.substring(p+s,this.pos);a.push(S),S===""?l++:l=0}else a.push(""),l++;this.consumeNewline();continue}if(m===0&&this.input.length-this.pos>=3){let S=this.input[this.pos],b=this.input[this.pos+1],I=this.input[this.pos+2],_=this.input[this.pos+3],R=_===void 0||_===" "||_==="	"||_===`
`||_==="\r";if(S==="-"&&b==="-"&&I==="-"&&R||S==="."&&b==="."&&I==="."&&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 y=this.input.substring(h,this.pos);a.push(y),l=0,this.consumeNewline()}let d;if(n==="|")d=a.join(`
`);else{d="";let p=!1,m=!1,h=!1;for(let y=0;y<a.length;y++){let S=a[y],b=S.length>0&&(S[0]===" "||S[0]==="	");S===""?(d+=`
`,m=!0):y===0?(d=S,p=b,h=!0):m?((p||b)&&h?d+=`
`+S:d+=S,p=b,m=!1,h=!0):b||p?(d+=`
`+S,p=b,h=!0):(d+=" "+S,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(ht(0,e,this.pos,{rawValue:u,value:d,format:n==="|"?"literal":"folded"}))}getParentBlockIndent(n){for(let e=this.tokens.length-1;e>=0;e--){let t=this.tokens[e];if(!(t.type===8||t.type===10||t.type===9)){if(t.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(t.type===2)return this.getColumnAt(t.startOffset);if(t.type===11)return-1;break}}return 0}getColumnAt(n){let e=0,t=n-1;for(;t>=0&&this.input[t]!==`
`&&this.input[t]!=="\r";)e++,t--;return e}scanComment(){let n=this.pos;for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;this.tokens.push(ht(10,n,this.pos,{rawValue:this.input.substring(n,this.pos),value:this.input.substring(n,this.pos)}))}scanNewline(){let n=this.pos;this.consumeNewline()&&this.tokens.push(ht(8,n,this.pos))}skipInlineWhitespace(){for(;this.pos<this.input.length;){let n=this.input[this.pos];if(n===" "||n==="	")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]}},Wg=class{constructor(n,e,t,r){this.tokens=n;this.input=e;this.errors=t;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(n=0){return this.tokens[Math.min(this.pos+n,this.tokens.length-1)]}advance(){let n=this.tokens[this.pos];return n.type!==13&&this.pos++,n}expect(n){let e=this.currentToken();return e.type===n?this.advance():e}emitError(n,e,t,r){this.errors.push({message:n,startOffset:e,endOffset:t,code:r})}skipNewlinesAndComments(){for(;this.currentToken().type===8||this.currentToken().type===10||this.currentToken().type===9&&this.isFollowedByNewlineOrComment();)this.advance()}isFollowedByNewlineOrComment(){let n=this.peek(1);return n.type===8||n.type===10||n.type===13}currentIndent(){return this.currentToken().type===9?this.currentToken().indent:0}parseValue(n){this.skipNewlinesAndComments();let e=this.currentToken(),t=e.type===9?this.peek(1):e;if(t.type===4||t.type===6)return e.type===9&&this.advance(),t.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(n)}peekPastIndent(){return this.currentToken().type===9?this.peek(1):this.currentToken()}looksLikeMapping(){let n=0;return this.peek(n).type===9&&n++,this.peek(n).type===0&&(n++,this.peek(n).type===1)}parseScalar(n=-1){this.currentToken().type===9&&this.advance();let e=this.expect(0);return e.format!=="none"?this.scalarFromToken(e):this.parsePlainMultiline(e,n)}parsePlainMultiline(n,e){let t=n.value,r=n.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?t+=`
`.repeat(s):t+=" ",t+=c;continue}this.pos=o;break}if(this.peek(1).type===1){this.pos=o;break}let l=this.advance();s>0?t+=`
`.repeat(s):t+=" ",t+=l.value,r=l.endOffset}return{type:"scalar",value:t,rawValue:this.input.substring(n.startOffset,r),startOffset:n.startOffset,endOffset:r,format:"none"}}parseBlockMapping(n,e=!1){let t=this.currentToken().startOffset,r=[],o=new Set;if(e){let a=this.parseMappingEntry(n);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<n)break;if(a!==n)if(a>n)this.emitError(f(150,null,n,a),this.currentToken().startOffset,this.currentToken().endOffset,"unexpected-indentation");else break;if(!this.looksLikeMapping())break;let l=this.parseMappingEntry(n);if(!l)break;!this.options.allowDuplicateKeys&&o.has(l.key.value)&&this.emitError(f(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:t;return{type:"map",properties:r,style:"block",startOffset:t,endOffset:s}}parseMappingEntry(n){this.currentToken().type===9&&this.advance();let e=this.expect(0),t=this.scalarFromToken(e),r=this.expect(1);if(r.type!==1){this.emitError(f(144,null),r.startOffset,r.endOffset,"expected-colon");return}let o=this.parseMappingValue(n,r);return{key:t,value:o}}parseMappingValue(n,e){let t=this.currentToken();if(t.type===4)return this.parseFlowMap();if(t.type===6)return this.parseFlowSeq();if(t.type===0){this.currentToken().type===9&&this.advance();let s=this.advance();return s.format!=="none"?this.scalarFromToken(s):this.parsePlainMultiline(s,n)}if(this.skipNewlinesAndComments(),this.currentToken().type===13)return this.emitError(f(149,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset);let o=this.currentIndent();return o===n&&this.peekPastIndent().type===2?this.parseValue(n)??this.makeEmptyScalar(e.endOffset):o<=n?(this.emitError(f(149,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.parseValue(n)??this.makeEmptyScalar(e.endOffset)}parseBlockSequence(n){let e=[],t=this.currentToken().startOffset,r=t,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<n)break;if(s!==n)if(s>n)this.emitError(f(150,null,n,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(n,l);e.push(d),r=d.endOffset}return{type:"sequence",items:e,style:"block",startOffset:t,endOffset:r}}parseSequenceItemValue(n,e){let t=this.currentToken();if(t.type===10&&this.advance(),t.type===4)return this.parseFlowMap();if(t.type===6)return this.parseFlowSeq();if(t.type===2){let o=t.startOffset-this.getLineStart(t.startOffset);return this.parseBlockSequence(o)}if(t.type===0){if(this.peek(1).type===1){let o=t.startOffset-this.getLineStart(t.startOffset);return this.parseBlockMapping(o,!0)}return this.parseScalar(n)}return this.skipNewlinesAndComments(),this.currentToken().type===13?(this.emitError(f(148,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.currentIndent()<=n?(this.emitError(f(148,null),e.startOffset,e.endOffset,"missing-value"),this.makeEmptyScalar(e.endOffset)):this.parseValue(n)??this.makeEmptyScalar(e.endOffset)}getLineStart(n){let e=n-1;for(;e>=0&&this.input[e]!==`
`&&this.input[e]!=="\r";)e--;return e+1}parseFlowMap(){let n=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(f(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 t=this.currentToken();return t.type===5?this.advance():this.emitError(f(145,null),t.startOffset,t.endOffset,"expected-flow-map-end"),{type:"map",properties:e,style:"flow",startOffset:n.startOffset,endOffset:t.type===5?t.endOffset:t.startOffset}}parseFlowSeq(){let n=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(f(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 t=this.currentToken();return t.type===7?this.advance():this.emitError(f(146,null),t.startOffset,t.endOffset,"expected-flow-seq-end"),{type:"sequence",items:e,style:"flow",startOffset:n.startOffset,endOffset:t.type===7?t.endOffset:t.startOffset}}parseFlowScalar(){let n=this.advance();if(n.format!=="none")return this.scalarFromToken(n);let e=n.value,t=n.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,t=s.endOffset;else break}return{type:"scalar",value:e,rawValue:this.input.substring(n.startOffset,t),startOffset:n.startOffset,endOffset:t,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 n=this.currentToken().type;if(n===8||n===9||n===10)this.advance();else break}}scalarFromToken(n){return{type:"scalar",value:n.value,rawValue:n.rawValue,startOffset:n.startOffset,endOffset:n.endOffset,format:n.format}}makeEmptyScalar(n){return{type:"scalar",value:"",rawValue:"",startOffset:n,endOffset:n,format:"none"}}};var WN;(n=>{function i(e,t){return e===t?!0:!e||!t?!1:e.command===t.command&&e.windows===t.windows&&e.linux===t.linux&&e.osx===t.osx&&gr(e.cwd,t.cwd)&&Fe(e.env,t.env)&&e.timeout===t.timeout&&gr(e.sourceUri,t.sourceUri)}n.isEquals=i})(WN||={});var qN={format:0,manifestPath:"plugin.json",hookConfigPath:"hooks.json",pluginRootToken:void 0,pluginRootEnvVar:void 0,parseHooks(i,n,e,t,r){return Bg(i,n,t,r)}},BN={format:1,manifestPath:".claude-plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${CLAUDE_PLUGIN_ROOT}",pluginRootEnvVar:"CLAUDE_PLUGIN_ROOT",parseHooks(i,n,e,t,r){return sP(i,n,e,t,r,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},zN={format:2,manifestPath:".plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootToken:"${PLUGIN_ROOT}",pluginRootEnvVar:"PLUGIN_ROOT",parseHooks(i,n,e,t,r){return sP(i,n,e,t,r,"${PLUGIN_ROOT}","PLUGIN_ROOT")}};async function Dc(i,n){return await ts(te(i,".plugin","plugin.json"),n)?zN:i.path.split("/").includes(".claude")||await ts(te(i,".claude-plugin","plugin.json"),n)?BN:qN}function Mc(i,n){let e=Ot(i.toString());return n?`${e.replace(/#/g,"%23")}#${n}`:e}function VN(i){let n=i.uri.toString();return{type:"agent",id:Mc(i.uri),uri:n,name:i.name,...i.description?{description:i.description}:{}}}function jN(i){let n=i.uri.toString();return{type:"skill",id:Mc(i.uri),uri:n,name:i.name,...i.description?{description:i.description}:{}}}function KN(i){let n=i.uri.toString();return{type:"rule",id:Mc(i.uri),uri:n,name:i.name,...i.description?{description:i.description}:{}}}function GN(i){return{type:"hook",id:Mc(i),uri:i.toString(),name:pe(i)}}function Oc(i,n){return{type:"mcpServer",id:Mc(i,`mcp=${encodeURIComponent(n)}`),uri:i.toString(),name:n,enabled:!0,state:{kind:"starting"},mcpApp:Eg}}var HS={paths:[],exclusive:!1};function Ec(i){if(i==null)return HS;if(typeof i=="string"){let n=i.trim();return n?{paths:[n],exclusive:!1}:HS}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 n=i;if(Array.isArray(n.paths)){let e=n.paths.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0),t=n.exclusive===!0;return{paths:e,exclusive:t}}}return HS}function kc(i,n,e,t){let r=t&&Kr(i,t)?t:i,o=[];e.exclusive||o.push(te(i,n));for(let s of e.paths){let a=_n(te(i,s));Kr(a,r)&&o.push(a)}return o}function JN(i){if(!i||typeof i!="object"||Array.isArray(i))return;let n=i;return Object.hasOwn(n,"mcpServers")?n.mcpServers:n}function YN(i){if(!i||typeof i!="object")return;let n=i,e=typeof n.type=="string"?n.type:void 0,t=typeof n.command=="string"?n.command:void 0,r=typeof n.url=="string"?n.url:void 0,o=Array.isArray(n.args)?n.args.filter(u=>typeof u=="string"):void 0,s=n.env&&typeof n.env=="object"?Object.fromEntries(Object.entries(n.env).filter(([,u])=>typeof u=="string"||typeof u=="number"||u===null).map(([u,p])=>[u,p])):void 0,a=typeof n.envFile=="string"?n.envFile:void 0,l=typeof n.cwd=="string"?n.cwd:void 0,d=n.headers&&typeof n.headers=="object"?Object.fromEntries(Object.entries(n.headers).filter(([,u])=>typeof u=="string").map(([u,p])=>[u,p])):void 0,c=n.dev&&typeof n.dev=="object"?n.dev:void 0;if(e!=="ws"){if(e==="stdio"||!e&&t)return t?{type:"stdio",command:t,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 QN=/[\s&|<>()^;!`"']/;function XN(i,n,e){if(!i.includes(e))return i;if(!QN.test(n))return i.replaceAll(e,n);let t=Cn(e),r=new RegExp(`(["']?)`+t+"([\\w./\\\\~:-]*)","g");return i.replace(r,(o,s,a)=>{let l=n+a;return s?s+l:'"'+l.replace(/"/g,'\\"')+'"'})}function ZN(i,n,e,t){let r=a=>a.replaceAll(e,n),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[t]=n,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 eU=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function tU(i){return ad(i,n=>{if(v.isUri(n))return n;if(typeof n=="string"){let e=n.replace(eU,"${env:$1}");return e!==n?e:void 0}})}var nU={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 rU(i){if(i.type!==void 0&&i.type!=="command")return;let n=typeof i.command=="string"&&i.command.length>0,e=typeof i.bash=="string"&&i.bash.length>0,t=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(!n&&!e&&!t&&!r&&!o&&!s)return;let a=r?i.windows:t?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{...n&&{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 nP(i,n,e){let t=rU(i);if(!t)return;let r,o=typeof i.cwd=="string"?i.cwd:void 0;return o?o.startsWith("~/")?r=v.joinPath(e,o.substring(2)):Ft(o)?r=v.file(o):n&&(r=te(n,o)):r=n,{...t,cwd:r}}function iU(i,n,e){if(!i||typeof i!="object")return[];let t=i,r=[],o=t.hooks;if(o!==void 0&&Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=nP(s,n,e);a&&r.push(a)}else{let s=nP(t,n,e);s&&r.push(s)}return r}function Bg(i,n,e,t){if(!n||typeof n!="object")return[];let r=n;if(r.disableAllHooks===!0)return[];let o=r.hooks;if(!o||typeof o!="object")return[];let s=o,a=[],l=GN(i);for(let d of Object.keys(s)){let c=nU[d];if(!c)continue;let u=s[d];if(!Array.isArray(u))continue;let p=[];for(let m of u)p.push(...iU(m,e,t));p.length>0&&a.push({type:c,commands:p,uri:i,originalId:d,customization:l})}return a}function sP(i,n,e,t,r,o,s){let a=e.fsPath,l=n,d=u=>{for(let p of["command","windows","linux","osx"])typeof u[p]=="string"&&(u[p]=XN(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 Bg(i,ad(n,u=>typeof u=="string"?u.replaceAll(o,e.fsPath):void 0),t,r)}async function pi(i,n){try{let e=await n.readFile(i);return _f(e.value.toString())}catch{return}}async function ts(i,n){try{return await n.resolve(i),!0}catch{return!1}}var qg=".md",rP=".mdc",iP=".instructions.md";async function $S(i,n,e){let t=new Set,r=[],o=async(s,a)=>{let l;try{let d=await WS(a,e);l=d.description,s=d.name||s}catch{}t.has(s)||(t.add(s),r.push({uri:a,name:s,...l?{description:l}:{}}))};if(await Promise.all(n.map(async s=>{let a=v.joinPath(s,"SKILL.md");if(await ts(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=v.joinPath(d.resource,"SKILL.md");await ts(c,e)&&await o(pe(d.resource),c)}))})),r.length===0){let s=v.joinPath(i,"SKILL.md");await ts(s,e)&&await o(pe(i),s)}return r.sort((s,a)=>s.name.localeCompare(a.name)),r}async function oU(i,n){let e=new Set,t=[],r=(o,s)=>{e.has(o)||(e.add(o),t.push({uri:s,name:o}))};for(let o of i){let s;try{s=await n.resolve(o)}catch{continue}if(s.isFile&&ed(o).toLowerCase()===qg){r(pe(o).slice(0,-qg.length),o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||ed(a.resource).toLowerCase()!==qg||r(pe(a.resource).slice(0,-qg.length),a.resource)}return t.sort((o,s)=>o.name.localeCompare(s.name)),t}function oP(i){let n=pe(i),e=n.toLowerCase();if(e.endsWith(rP))return n.slice(0,-rP.length);if(e.endsWith(iP))return n.slice(0,-iP.length)}async function sU(i,n){let e=new Set,t=[],r=(o,s)=>{e.has(o)||(e.add(o),t.push({uri:s,name:o}))};for(let o of i){let s;try{s=await n.resolve(o)}catch{continue}if(s.isFile){let a=oP(o);a&&r(a,o);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children){if(!a.isFile)continue;let l=oP(a.resource);l&&r(l,a.resource)}}return t.sort((o,s)=>o.name.localeCompare(s.name)),t}async function zg(i,n){let e=await oU(i,n);if(e.length===0)return e;let t=await Promise.all(e.map(async s=>{try{let{name:a,description:l}=await Lc(s.uri,n);return{uri:s.uri,name:a||s.name,...l?{description:l}:{}}}catch{return s}})),r=new Set,o=[];for(let s of t)r.has(s.name)||(r.add(s.name),o.push(s));return o.sort((s,a)=>s.name.localeCompare(a.name)),o}async function Lc(i,n){let e=pe(i).replace(/(\.agent)?\.md$/i,"");try{let t=await n.readFile(i),r=Za(t.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 WS(i,n){try{let e=await n.readFile(i),t=Za(e.value.toString()),r=t?.getStringValue("name")?.trim()||pe(In(i)),o=t?.getStringValue("description")?.trim(),s=t?.getBooleanValue("user-invocable");return{name:r,description:o,userInvokable:s}}catch{return{name:pe(In(i))}}}async function Vg(i,n){let e=pe(i).replace(/(\.instructions)?\.md$/i,"");try{let t=await n.readFile(i),r=Za(t.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 aU(i,n,e,t,r,o){for(let s of n){let a=await pi(s,t);if(a)return e.parseHooks(s,a,i,r,o)}return[]}async function lU(i,n,e,t){let r=new Map;for(let o of i){let s=await pi(o,t);for(let a of aP(o,s,n,e))r.has(a.name)||r.set(a.name,a)}return[...r.values()].sort((o,s)=>o.name.localeCompare(s.name))}function aP(i,n,e,t){let r=JN(n);if(!r)return[];let o=[];for(let[s,a]of Object.entries(r)){let l=YN(a);if(!l)continue;let d={name:s,configuration:l,uri:i,customization:Oc(i,s)};t.pluginRootToken&&t.pluginRootEnvVar&&(d=ZN(d,e,t.pluginRootToken,t.pluginRootEnvVar)),d=tU(d),o.push(d)}return o}async function jg(i,n,e,t,r){let o=await Dc(i,n),s=await pi(te(i,o.manifestPath),n),a=s&&typeof s=="object"?s:void 0,l=kc(i,o.hookConfigPath,Ec(a?.hooks),r),d=kc(i,".mcp.json",Ec(a?.mcpServers),r),c=kc(i,"skills",Ec(a?.skills),r),u=kc(i,"agents",Ec(a?.agents),r),p=kc(i,"rules",Ec(a?.rules),r),m=[],h=a?.mcpServers;h&&typeof h=="object"&&!Array.isArray(h)&&!me(h,{paths:!0})&&(m=aP(te(i,o.manifestPath),{mcpServers:h},i.fsPath,o));let y=[],S=a?.hooks;if(S&&typeof S=="object"&&!Array.isArray(S)&&!me(S,{paths:!0})){let X=te(i,o.manifestPath);y=o.parseHooks(X,{hooks:S},i,e,t)}let[b,I,_,R,A]=await Promise.all([y.length>0?Promise.resolve(y):aU(i,l,o,n,e,t),m.length>0?Promise.resolve(m):lU(d,i.fsPath,o,n),$S(i,c,n),zg(u,n),sU(p,n)]);return{hooks:b,mcpServers:I,skills:_.map(Kg),agents:R.map(el),instructions:A.map(dU)}}function el(i){return{...i,customization:VN(i)}}function Kg(i){return{...i,customization:jN(i)}}function dU(i){return{...i,customization:KN(i)}}import*as lP from"fs/promises";function qS(i,n){return te(i,".copilot","chats",n)}async function dP(i,n){let e=qS(i,n);return await lP.mkdir(e.fsPath,{recursive:!0}),e}function cU(i){let n=Object.entries(i).filter(([,e])=>e!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Gg(i){if(!i||typeof i!="object")return;let n=i,e=typeof n.multiplier=="number"?n.multiplier:void 0,t=typeof n.priceCategory=="string"?n.priceCategory:typeof n.price_category=="string"?n.price_category:void 0,r=typeof n.discountPercent=="number"?n.discountPercent:typeof n.discount_percent=="number"?n.discount_percent:void 0,o=n.tokenPrices??n.token_prices,s;if(o&&typeof o=="object"){let a=o.default,l=a&&typeof a=="object",d=_t(o.inputPrice)??_t(l?a.input_price:void 0),c=_t(o.cachePrice)??_t(l?a.cache_price:void 0),u=_t(o.cacheWritePrice)??_t(l?a.cache_write_price:void 0),p=_t(o.outputPrice)??_t(l?a.output_price:void 0),m=_t(o.contextMax)??_t(l?a.context_max:void 0),h=o.longContext??o.long_context,y;h&&typeof h=="object"&&(y={inputPrice:_t(h.inputPrice)??_t(h.input_price),cachePrice:_t(h.cachePrice)??_t(h.cache_price),cacheWritePrice:_t(h.cacheWritePrice)??_t(h.cache_write_price),outputPrice:_t(h.outputPrice)??_t(h.output_price),contextMax:_t(h.contextMax)??_t(h.context_max)}),s={inputPrice:d,cachePrice:c,cacheWritePrice:u,outputPrice:p,contextMax:m,longContext:y}}return{multiplier:e,priceCategory:t,discountPercent:r,tokenPrices:s}}function _t(i){return typeof i=="number"?i:void 0}function tl(i,n){let e=i?.tokenPrices,t=e?.longContext,r=t!==void 0&&(t.inputPrice!==void 0&&t.inputPrice!==e?.inputPrice||t.outputPrice!==void 0&&t.outputPrice!==e?.outputPrice||t.cachePrice!==void 0&&t.cachePrice!==e?.cachePrice||t.cacheWritePrice!==void 0&&t.cacheWritePrice!==e?.cacheWritePrice);return cU({multiplierNumeric:typeof i?.multiplier=="number"?i.multiplier:void 0,inputCost:e?.inputPrice,cacheCost:e?.cachePrice,cacheWriteCost:e?.cacheWritePrice,outputCost:e?.outputPrice,longContextInputCost:r?t.inputPrice??e?.inputPrice:void 0,longContextCacheCost:r?t.cachePrice??e?.cachePrice:void 0,longContextCacheWriteCost:r?t.cacheWritePrice??e?.cacheWritePrice:void 0,longContextOutputCost:r?t.outputPrice??e?.outputPrice:void 0,priceCategory:n??(typeof i?.priceCategory=="string"?i.priceCategory:void 0),discountPercent:typeof i?.discountPercent=="number"?i.discountPercent:void 0})}function BS(i){let n=i?.tokenPrices,e=n?.longContext;return e?e.inputPrice!==void 0&&e.inputPrice!==n?.inputPrice||e.outputPrice!==void 0&&e.outputPrice!==n?.outputPrice||e.cachePrice!==void 0&&e.cachePrice!==n?.cachePrice||e.cacheWritePrice!==void 0&&e.cacheWritePrice!==n?.cacheWritePrice:!1}var nl=$("agentPluginManager");function Er(i){return JSON.stringify(i)}function Jg(i){try{let n=JSON.parse(i);if(!n||typeof n!="object")return;let{sdkSessionId:e,model:t}=n;if(typeof e!="string"||!e)return;let r=t&&typeof t=="object"&&typeof t.id=="string"?t:void 0;return{sdkSessionId:e,...r?{model:r}:{}}}catch{return}}var rl=class extends T{constructor(e){super();this._chats=this._register(new Re);e&&(this._ownSession=e,this._register(e))}get ownSession(){return this._ownSession}addDisposable(e){this._register(e)}setDefaultChat(e,t){this._chats.set(e,t),this._defaultChatKey=e}clearDefaultChat(){this._defaultChatKey!==void 0&&(this._chats.deleteAndDispose(this._defaultChatKey),this._defaultChatKey=void 0)}get defaultChat(){return this._defaultChatKey!==void 0?this._chats.get(this._defaultChatKey)?.ownSession:void 0}getChat(e){return this._chats.get(e)?.ownSession}resolveChat(e){let t=this._chats.get(e)?.ownSession;if(t)return{chatSession:t,isDefault:e===this._defaultChatKey}}allChatSessions(){let e=[];for(let t of this._chats.values())t.ownSession&&e.push(t.ownSession);return e}getPeerChat(e){return e===this._defaultChatKey?void 0:this._chats.get(e)?.ownSession}hasPeerChat(e){return e!==this._defaultChatKey&&this._chats.has(e)}registerPeerChat(e,t){this._chats.set(e,t)}disposePeerChat(e){e!==this._defaultChatKey&&this._chats.deleteAndDispose(e)}peerChatKeys(){return[...this._chats.keys()].filter(e=>e!==this._defaultChatKey)}peerChatSessions(){let e=[];for(let t of this._chats.keys()){if(t===this._defaultChatKey)continue;let r=this._chats.get(t)?.ownSession;r&&e.push(r)}return e}};function cP(i){let n=new Map;if(i){for(let t of i)if(t.type!=="mcpServer"&&!(t.enabled===!1||!t.children))for(let r of t.children){if(r.type!=="agent")continue;let o=r.uri.toString();n.has(o)||n.set(o,r)}}let e=[...n.values()];return e.sort((t,r)=>t.name.localeCompare(r.name)||t.uri.toString().localeCompare(r.uri.toString())),e}function ns(i){switch(i){case"none":return f(1967,null);case"minimal":return f(1965,null);case"low":return f(1959,null);case"medium":return f(1963,null);case"high":return f(1957,null);case"xhigh":return f(1969,null);case"max":return f(1961,null);default:return i.charAt(0).toUpperCase()+i.slice(1)}}function rs(i){switch(i){case"none":return f(1968,null);case"minimal":return f(1966,null);case"low":return f(1960,null);case"medium":return f(1964,null);case"high":return f(1958,null);case"xhigh":return f(1970,null);case"max":return f(1962,null);default:return}}var Yg=$("agentHostOTelService");import{LogLevel as is,createProxyResolver as uU,loadSystemCertificates as pU}from"@vscode/proxy-agent";var Qg=$("agentHostProxyResolver"),il=class{constructor(n,e){this._configurationService=n;this._logService=e;this._connections=new Map}register(n,e){return this._connections.set(n,e),M(()=>{this._connections.get(n)===e&&this._connections.delete(n)})}resolveProxy(n){return this._getResolveProxyURL()(n)}_getResolveProxyURL(){if(!this._resolveProxyURL){let n=o=>this._configurationService.getValue(o),e=()=>n("http.experimental.systemCertificatesV2")??!1,t=()=>!!n("http.systemCertificates"),r={resolveProxy:o=>this._hostResolveProxy(o),getProxyURL:()=>n("http.proxy"),getProxySupport:()=>n("http.proxySupport")||"off",getNoProxyConfig:()=>n("http.noProxy")||[],isAdditionalFetchSupportEnabled:()=>n("http.fetchAdditionalSupport")??!0,isWebSocketPatchEnabled:()=>n("http.webSocketAdditionalSupport")??!0,addCertificatesV1:()=>!e()&&t(),addCertificatesV2:()=>e()&&t(),loadSystemCertificatesFromNode:()=>n("http.systemCertificatesNode")??Ta,loadAdditionalCertificates:async()=>pU({loadSystemCertificatesFromNode:()=>n("http.systemCertificatesNode")??Ta,log:this._logService}),log:this._logService,getLogLevel:()=>{switch(this._logService.getLevel()){case 1:return is.Trace;case 2:return is.Debug;case 3:return is.Info;case 4:return is.Warning;case 5:return is.Error;case 0:return is.Off;default:return is.Info}},proxyResolveTelemetry:()=>{},isUseHostProxyEnabled:()=>this._connections.size>0,getNetworkInterfaceCheckInterval:()=>(n("http.experimental.networkInterfaceCheckInterval")??300)*1e3,env:process.env};this._resolveProxyURL=uU(r).resolveProxyURL}return this._resolveProxyURL}async _hostResolveProxy(n){for(let e of this._connections.values())try{return await e.resolveProxy(n)}catch{}}};il=w([C(0,Hi),C(1,D)],il);function Xg(i,n){let e=i??[],t=n??[];if(e.length!==t.length)return!1;let r=new Map;for(let o of e)r.set(o.name,o);for(let o of t){let s=r.get(o.name);if(!s||s.description!==o.description||!Fe(s.inputSchema,o.inputSchema))return!1}return!0}var Pn=class{constructor(){this._byClient=new Map}get size(){return this._byClient.size}has(n){return this._byClient.has(n)}clientIds(){return this._byClient.keys()}get(n){return this._byClient.get(n)??[]}set(n,e){this._byClient.set(n,e)}delete(n){return this._byClient.delete(n)}merged(){let n=new Set,e=[];for(let t of this._byClient.values())for(let r of t)n.has(r.name)||(n.add(r.name),e.push(r));return e}ownerOf(n,e){if(e&&this.get(e).some(t=>t.name===n))return e;for(let[t,r]of this._byClient)if(r.some(o=>o.name===n))return t}structuralEquals(n){return Xg(this.merged(),n)}};var ao=$("byokLmBridgeRegistry"),Zg=class{constructor(){this._entries=new Map;this._changeListeners=new Set}onDidChangeModels(n){return this._changeListeners.add(n),M(()=>{this._changeListeners.delete(n)})}_notifyChanged(){for(let n of[...this._changeListeners])n()}register(n,e){this._entries.get(n)?.store.dispose();let t=new G,r={connection:e,models:void 0,store:t};return this._entries.set(n,r),e.onDidChangeModels&&t.add(e.onDidChangeModels(()=>{this._refreshConnection(n)})),this._notifyChanged(),this._refreshConnection(n),M(()=>{this._entries.get(n)===r&&(this._entries.delete(n),r.store.dispose(),this._notifyChanged())})}async listModels(){return await Promise.all([...this._entries.keys()].map(n=>this._refreshConnection(n))),[...this.getModels()]}getModels(){return this._servingEntry()?.models??[]}getServingConnection(){return this._servingEntry()?.connection}_servingEntry(){let n;for(let e of this._entries.values())if(e.models!==void 0){if(e.models.length>0)return e;n??=e}return n}async _refreshConnection(n){let e=this._entries.get(n);if(!e)return;let t;try{t=await e.connection.listModels()}catch{return}this._entries.get(n)===e&&(e.models===void 0||!fU(e.models,t))&&(e.models=t,this._notifyChanged())}};function fU(i,n){return i.length!==n.length?!1:i.every((e,t)=>{let r=n[t];return e.vendor===r.vendor&&e.id===r.id&&e.name===r.name&&e.maxContextWindowTokens===r.maxContextWindowTokens&&e.supportsVision===r.supportsVision})}var Nc="agents/",gU=8,uP=48,mU=8,em=$("copilotBranchNameGenerator"),sl=class{constructor(n,e){this._copilotApiService=n;this._logService=e}async generateBranchName(n){let e=await this._generateBranchNameHint(n)??yU(n.message??"");return this._buildBranchName(n,e)}async _generateBranchNameHint(n){let e=n.message?.trim();if(!(!e||!n.githubToken))try{let t=await this._copilotApiService.utilityChatCompletion(n.githubToken,{messages:this._buildBranchNamePrompt(e)},{signal:n.signal});if(n.signal?.aborted)return;let r=t.trim();if(r.match(/^".*"$/)&&(r=r.slice(1,-1)),r.includes("can't assist with that"))return;if(r=hU(r).slice(0,uP).replace(/-+$/g,""),r.length<mU){this._logService.warn("Generated branch name is too short after normalization, discarding.");return}return r}catch(t){this._logService.warn("[CopilotBranchNameGenerator] Failed to generate branch name",t);return}}_buildBranchNamePrompt(n){return[{role:"system",content:["You are an expert in crafting pithy branch names for Git Repos based on chatbot conversations.","You are presented with a chat request, and you reply with a brief branch name that captures the main topic of that request.","The branch name should not be wrapped in quotes. It should be between 8-50 characters.","Here are some examples of good branch names:","- linkedlist-implementation","- adding-tree-view","- react-usestate-hook-usage"].join(" ")},{role:"user",content:`Please write a brief branch name for the following request:

${n}`}]}async _buildBranchName(n,e){if(!e)return`${Nc}${n.sessionId}`;let t=`${Nc}${e}`;return n.branchExists&&await n.branchExists(t)?`${t}-${n.sessionId.substring(0,gU)}`:t}};sl=w([C(0,It),C(1,D)],sl);function hU(i){let n=i.replace(/[^a-zA-Z0-9\-]/g,"").toLowerCase();return n=n.replace(/\.{2,}/g,"."),n=n.replace(/^[-.]+/,""),n=n.replace(/[./]+$/,""),n=n.replace(/\.lock$/,""),n}function yU(i){let e=i.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").split("-").filter(t=>t.length>0).slice(0,8).join("-").slice(0,uP).replace(/-+$/g,"");return e.length>0?e:void 0}var zS="/.well-known",Uhe=`${zS}/oauth-protected-resource`,Fhe=`${zS}/oauth-authorization-server`,Hhe=`${zS}/openid-configuration`;function pP(i){if(typeof i!="object"||i===null)return!1;let n=i;return!(!n.resource||n.scopes_supported!==void 0&&!Array.isArray(n.scopes_supported))}function vU(i,n){let e=i.match(n?/^(?:cd(?: \/d)?|Set-Location(?: -Path)?) (?<dir>"[^"]*"|[^\s]+) *(?:&&|;|\r?\n)\s*(?<suffix>[\s\S]+)$/i:/^cd (?<dir>"[^"]*"|[^\s]+) *(?:&&|\r?\n)\s*(?<suffix>[\s\S]+)$/),t=e?.groups?.dir,r=e?.groups?.suffix;if(t&&r){let o=t;return o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1)),{directory:o,command:r}}}function os(i,n,e){if(!e||!n)return!1;let t=i==="bash",r=i==="powershell";if(!t&&!r)return!1;let o=n.command;if(typeof o!="string")return!1;let s=vU(o,r);return!s||!SU(s.directory,e)?!1:(n.command=s.command,!0)}function SU(i,n){if(!i)return!1;let e=a=>a.replace(/[\\/]+$/,""),t=e(i),r=e(n.fsPath);if(!t||!r)return!1;let o,s;try{o=v.file(t),s=v.file(r)}catch{return!1}return rt.isEqual(o,s)}var fP="ahp-otlp://logs/{level}",gP="ahp-otlp",bU=["trace","debug","info","warn","error","fatal"];function mP(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 CU(i){let n=i.toLowerCase();return bU.includes(n)?n:void 0}function IU(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 al=class{constructor(n){this.attributes=n}toJSON(){return this.attributes}},tm=class extends T{constructor(){super(...arguments);this._onDidLog=this._register(new P);this.onDidLog=this._onDidLog.event}emit(e){this._onDidLog.fire(e)}},nm=class extends Vo{constructor(e,t=1){super();this._emitter=e;this.setLevel(t)}trace(e,...t){this.canLog(1)&&this._emit(1,e,t,!0)}debug(e,...t){this.canLog(2)&&this._emit(2,e,t)}info(e,...t){this.canLog(3)&&this._emit(3,e,t)}warn(e,...t){this.canLog(4)&&this._emit(4,e,t)}error(e,...t){if(this.canLog(5)){let r=e instanceof Error?e.stack??e.message:e;this._emit(5,r,t)}}log(e,t){e!==0&&this._emit(e,t,[])}_emit(e,t,r,o=!1){let s,a=r.findIndex(c=>c instanceof al);a!==-1&&(s=r[a].attributes,r=r.slice(0,a).concat(r.slice(a+1)));let{severityNumber:l,severityText:d}=IU(e);this._emitter.emit({timeUnixNano:RU(Date.now()),severityNumber:l,severityText:d,body:si([t,...r],o),...s?{attributes:s}:void 0})}};function hP(i){return _U([i])}function _U(i){return{resourceLogs:[{resource:{attributes:[]},scopeLogs:[{scope:{name:"vscode.agentHost"},logRecords:i.map(n=>({timeUnixNano:n.timeUnixNano,observedTimeUnixNano:n.timeUnixNano,severityNumber:n.severityNumber,severityText:n.severityText,body:{stringValue:n.body},...n.attributes?{attributes:TU(n.attributes)}:void 0}))}]}]}}function TU(i){return Object.entries(i).map(([n,e])=>({key:n,value:wU(e)}))}function wU(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 RU(i){return`${i}000000`}function yP(i){let n=/^ahp-otlp:\/\/logs\/([^/?#]+)/i.exec(i);if(n)return CU(n[1])}function vP(i){return`ahp-otlp://logs/${i}`}var xU="agentFeedback";function rm(i){return i.type==="annotations"&&i.displayKind===xU}function im(i){let n=i.annotationIds?.filter(Ve)??[];return n.length===0?void 0:`The user attached specific feedback comments to act on (comment ids):
${n.map(t=>`- ${t}`).join(`
`)}

Use the \`listComments\` tool to read their content and focus on these comments.`}var VS=Object.freeze({valid:!1,sessionId:void 0});function om(i,n){let e=i.authorization;if(typeof e!="string"||!e.startsWith("Bearer "))return VS;let t=e.slice(7),r=t.indexOf(".");if(r===-1)return VS;let o=t.slice(0,r),s=t.slice(r+1);return o!==n||s.length===0?VS:{valid:!0,sessionId:s}}function PU(){let i=new Uint8Array(32);crypto.getRandomValues(i);let n="";for(let e=0;e<i.length;e++)n+=i[e].toString(16).padStart(2,"0");return n}function ll(i){return new Promise((n,e)=>{let t=[];i.on("data",r=>t.push(Buffer.isBuffer(r)?r:Buffer.from(r))),i.on("end",()=>n(Buffer.concat(t).toString("utf8"))),i.on("error",e)})}var lo=class{constructor(n,e){this.name=n;this._logService=e;this._disposed=!1}get isDisposed(){return this._disposed}writeInternalError(n){n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:{type:"api_error",message:"Internal proxy error"}}))}async acquire(n){if(this._disposed)throw new Error(`${this.name} has been disposed`);let e=await this._ensureRuntime(n);if(this._disposed||this._runtime!==e)throw new Error(`${this.name} has been disposed`);e.refcount++;let t=!1;return{runtime:e,release:()=>{t||(t=!0,this._releaseHandle(e))}}}dispose(){this._disposed||(this._disposed=!0,this._teardownRuntime())}_ensureRuntime(n){return this._runtime?Promise.resolve(this._runtime):(this._starting||(this._starting=(async()=>{try{let e=await this._startServer(n);if(this._disposed)throw e.server.closeAllConnections(),e.server.close(),new Error(`${this.name} has been disposed`);return this._runtime=e,e}finally{this._starting=void 0}})()),this._starting)}_releaseHandle(n){this._runtime===n&&(n.refcount--,n.refcount===0&&this._teardownRuntime())}_teardownRuntime(){let n=this._runtime;if(n){this._runtime=void 0;for(let e of n.inFlight)e.ac.abort();n.server.closeAllConnections(),n.server.close(e=>{e&&this._logService.warn(`[${this.name}] server.close error: ${e.message}`)})}}async _startServer(n){let e=PU(),t=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(`${this.name} failed to bind: unexpected address ${String(s)}`);let a=`http://127.0.0.1:${s.port}`;this._logService.info(`[${this.name}] listening on ${a}`);let l={server:o,baseUrl:a,nonce:e,inFlight:t,refcount:0,state:this.createState(n)};return o.on("request",(d,c)=>{this.handleRequest(d,c,l).catch(u=>{if(this._logService.error(`[${this.name}] unhandled request error: ${u instanceof Error?u.message:String(u)}`),c.headersSent){if(!c.writableEnded)try{c.end()}catch{}}else try{this.writeInternalError(c)}catch{}})}),l}};var dl=class extends Error{};function AU(i){if(typeof i=="string")return i;if(Array.isArray(i)){let n="";for(let e of i)e&&e.type==="text"&&typeof e.text=="string"&&(n+=e.text);return n}return""}function EU(i){switch(i){case"system":case"developer":return"system";case"assistant":return"assistant";case"tool":case"function":return"tool";default:return"user"}}function kU(i){if(!i||i.length===0)return;let n=[];for(let e=0;e<i.length;e++){let t=i[e],r=t.function?.name;if(!r)throw new dl(`tool_calls[${e}].function.name is required`);n.push({id:t.id??`call_${e}`,name:r,argumentsJson:t.function?.arguments??"{}"})}return n}function DU(i){if(!i||i.length===0)return;let n=[];for(let e of i){let t=e.function;t?.name&&n.push({name:t.name,description:t.description,parametersSchema:t.parameters})}return n.length?n:void 0}function SP(i,n){let e=typeof n.model=="string"?n.model:"";if(!e)throw new dl('Request is missing the "model" field');let r=(Array.isArray(n.messages)?n.messages:[]).map(s=>({role:EU(s.role),content:AU(s.content),toolCalls:kU(s.tool_calls),toolCallId:s.tool_call_id})),o={};return typeof n.temperature=="number"&&(o.temperature=n.temperature),typeof n.top_p=="number"&&(o.top_p=n.top_p),typeof n.max_tokens=="number"&&(o.max_tokens=n.max_tokens),{vendor:i,modelId:e,messages:r,tools:DU(n.tools),modelOptions:Object.keys(o).length?o:void 0}}var jS=0;function MU(){return jS=(jS+1)%Number.MAX_SAFE_INTEGER,`chatcmpl-byok-${Date.now().toString(36)}-${jS.toString(36)}`}function sm(i){return`data: ${JSON.stringify(i)}

`}function bP(i,n){let e=MU(),t=Math.floor(Date.now()/1e3),r={id:e,object:"chat.completion.chunk",created:t,model:n},o=[];o.push(sm({...r,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})),i.content&&o.push(sm({...r,choices:[{index:0,delta:{content:i.content},finish_reason:null}]}));let s="stop";if(i.toolCalls&&i.toolCalls.length>0){s="tool_calls";let l=i.toolCalls.map((d,c)=>({index:c,id:d.id,type:"function",function:{name:d.name,arguments:d.argumentsJson}}));o.push(sm({...r,choices:[{index:0,delta:{tool_calls:l},finish_reason:null}]}))}let a={...r,choices:[{index:0,delta:{},finish_reason:s}]};return i.usage&&(a.usage={prompt_tokens:i.usage.promptTokens??0,completion_tokens:i.usage.completionTokens??0,total_tokens:(i.usage.promptTokens??0)+(i.usage.completionTokens??0)}),o.push(sm(a)),o.push(`data: [DONE]

`),o}function CP(i,n="api_error"){return JSON.stringify({error:{message:i,type:n}})}var am=$("byokLmProxyService"),IP="ByokLmProxyService",KS="/v/",_P="/chat/completions",cl=class extends lo{constructor(e,t){super(IP,e);this._bridgeRegistry=t}createState(){}async start(){let{runtime:e,release:t}=await this.acquire(),r=!1;return{baseUrl:e.baseUrl,nonce:e.nonce,providerBaseUrl:o=>`${e.baseUrl}${KS}${encodeURIComponent(o)}`,dispose:()=>{r||(r=!0,t())}}}writeInternalError(e){this._writeJsonError(e,500,"Internal proxy error")}async handleRequest(e,t,r){let o=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${IP}] ${o} ${s}`),o==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=om(e.headers,r.nonce);if(!a.valid||!a.sessionId){this._writeJsonError(t,401,"Invalid authentication","authentication_error");return}let l=this._parseVendorFromChatPath(s);if(o==="POST"&&l!==void 0){await this._handleChatCompletions(e,t,r,l);return}this._writeJsonError(t,404,`No route for ${o} ${s}`,"not_found_error")}_parseVendorFromChatPath(e){if(!e.startsWith(KS)||!e.endsWith(_P))return;let t=e.slice(KS.length,e.length-_P.length);if(!t)return;let r;try{r=decodeURIComponent(t)}catch{return}if(!(!r||r.includes("/")))return r}async _handleChatCompletions(e,t,r,o){let s;try{let u=await ll(e);s=JSON.parse(u)}catch(u){this._writeJsonError(t,400,`Invalid request body: ${u instanceof Error?u.message:String(u)}`,"invalid_request_error");return}let a;try{a=SP(o,s)}catch(u){let p=u instanceof dl?u.message:String(u);this._writeJsonError(t,400,p,"invalid_request_error");return}let l=this._bridgeRegistry.getServingConnection();if(!l){this._writeJsonError(t,503,"No renderer connection available to service BYOK models","api_error");return}let d={ac:new AbortController,res:t,clientGone:!1};r.inFlight.add(d);let c=()=>{d.clientGone=!0,d.ac.abort()};t.on("close",c);try{let u=await l.chat(a);if(d.ac.signal.aborted||t.writableEnded)return;if(u.error){this._writeJsonError(t,502,u.error,"api_error");return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});for(let p of bP(u,a.modelId))t.write(p);t.end()}catch(u){if(d.ac.signal.aborted||t.writableEnded)return;let p=u instanceof Error?u.message:String(u);if(!t.headersSent)this._writeJsonError(t,502,p,"api_error");else try{t.end()}catch{}}finally{t.removeListener("close",c),r.inFlight.delete(d)}}_writeJsonError(e,t,r,o="api_error"){e.headersSent||e.writableEnded||(e.writeHead(t,{"Content-Type":"application/json"}),e.end(CP(r,o)))}};cl=w([C(0,D),C(1,ao)],cl);var Uc=class extends T{constructor(e){super();this.session=e;this._handledEventTypes=new Set;this._onUnhandledEvent=this._register(new P);this.onUnhandledEvent=this._onUnhandledEvent.event;let t=e.on(r=>{this._handledEventTypes.has(r.type)||this._onUnhandledEvent.fire(r)});this._register(M(t)),this._register(M(()=>{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")}get onCommandsChanged(){return this._onCommandsChanged??=this._sdkEvent("commands.changed")}_sdkEvent(e){let t=this._register(new P({onDidAddFirstListener:()=>this._handledEventTypes.add(e),onDidRemoveLastListener:()=>this._handledEventTypes.delete(e)})),r=this.session.on(e,o=>t.fire(o));return this._register(M(r)),t.event}};var lm=$("sandboxHelperService");import{createHash as zU}from"crypto";var OU=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"]),LU=new Set(["ai","cloud","com","dev","io","me","net","org","tech"]);function Fc(i,n=!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 t=e.replace(/[),;:!?]+$/,"");if(!t)return;let r=t.startsWith("*.")?t.slice(2):t;if(!/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))*$/.test(r))return;let o=t.startsWith("*."),s=o?t.slice(2):t;if(s&&/^[a-z0-9.-]+$/.test(s)){if(!n){let a=s.slice(s.lastIndexOf(".")+1);if(OU.has(a)||!LU.has(a))return}return o?`*.${s}`:s}}function NU(i){let n=i.trim();if(n==="*"||!n.includes("://"))return n;try{return v.parse(n).authority}catch{return n}}function GS(i,n){let e=Fc(NU(n),n.includes("://"));if(!e)return!1;if(e==="*")return!0;if(e.startsWith("*.")){let t=e.slice(2);return i===t||i.endsWith(`.${t}`)}return i===e}var cm=$("windowsMxcTerminalSandboxRuntime"),dm=class{constructor(){this._configVersion="0.6.0-alpha"}getExecutablePath(n,e){let t=e==="arm64"?"arm64":"x64";return he.join(n,"node_modules","@microsoft","mxc-sdk","bin",t,"wxc-exec.exe")}getRuntimeReadPaths(n,e){let t=[];return n&&t.push(n),e&&t.push(e,he.dirname(e)),[...new Set(t)]}async createConfig(n,e){let t=this.toWindowsPath(n.tempDir),o=`${n.shell?this._quoteWindowsCommandLineArgument(n.shell):"pwsh.exe"} -NoProfile -Command ${this._quoteWindowsCommandLineArgument(n.command)}`,s=n.cwd?this.toWindowsPath(n.cwd):t,a={version:n.schemaVersion??this._configVersion,timeoutMs:0,filesystem:{readwritePaths:n.allowWritePaths.map(d=>this._normalizeWindowsPath(d)),readonlyPaths:[t,...n.shell&&he.isAbsolute(n.shell)?[he.dirname(n.shell)]:[],...n.allowReadPaths].map(d=>this._normalizeWindowsPath(d)),deniedPaths:n.denyReadPaths.map(d=>this._normalizeWindowsPath(d))},network:this._createNetworkPolicy(n.allowNetwork),ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}},l=await e(o,a,s);if(!l?.process)throw new Error("Unable to build Windows MXC sandbox payload");return l.process.env=[...n.env],l}wrapCommand(n,e){return`& ${this._quotePowerShellArgument(n)} ${this._quotePowerShellArgument(e)}`}wrapUnsandboxedCommand(n){return n}toWindowsPath(n){let e;return n.authority&&n.path.length>1&&n.scheme==="file"?e=`\\\\${n.authority}${n.path}`:/^\/[a-zA-Z]:/.test(n.path)?e=n.path.slice(1):e=n.fsPath,this._normalizeWindowsPath(e)}_normalizeWindowsPath(n){return n.replace(/\//g,"\\")}_createNetworkPolicy(n){return{allowOutbound:n}}_quotePowerShellArgument(n){return`'${n.replace(/'/g,"''")}'`}_quoteWindowsCommandLineArgument(n){return`"${n.replace(/(\\*)"/g,'$1$1\\"').replace(/\\+$/g,"$&$&")}"`}};function um(i,n,e){if(!n.keywords.includes(i.keyword.toLowerCase())||n.condition&&(!e||!n.condition(e)))return!1;if(n.subcommands){let t=UU(i.args,n.optionsWithValue);if(t===void 0||!n.subcommands.includes(t))return!1}return n.when?.(i)??!0}function UU(i,n){for(let e=0;e<i.length;e++){let t=i[e];if(t==="--")return;if(t.startsWith("-")){let r=t.includes("=")?t.substring(0,t.indexOf("=")):t;!t.includes("=")&&n?.has(r)&&e++;continue}return t.toLowerCase()}}var FU=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 wP(i,n){if(n===1)return[];switch(i){case"git":switch(n){case 2:case 3:default:return["~/.gitconfig","~/.config/gh/config.yml","~/.config/git/config","~/.gitignore","~/.gitignore_global","~/.config/git/ignore","~/.config/git/attributes"]}case"node":switch(n){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(n){case 2:case 3:default:return["~/.cargo/bin","~/.cargo/registry","~/.cargo/git","~/.rustup/toolchains"]}case"go":switch(n){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(n){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(n){case 2:case 3:default:return["~/.m2/repository","~/.gradle/caches","~/.gradle/wrapper/dists","~/.sdkman/candidates"]}case"dotnet":switch(n){case 2:case 3:default:return["~/.dotnet"]}case"nuget":switch(n){case 2:return["~/.nuget/packages","~/Library/Caches/NuGet/v3-cache"];case 3:default:return["~/.nuget/packages","~/.local/share/NuGet/v3-cache"]}case"msbuild":switch(n){case 2:case 3:default:return[]}case"ruby":switch(n){case 2:return["~/.gem","~/.rbenv/versions","~/.rbenv/shims","~/.rvm/rubies"];case 3:default:return["~/.gem","~/.rbenv/versions","~/.rbenv/shims","~/.rvm/rubies"]}case"nativeBuild":switch(n){case 2:return["~/Library/Caches/ccache","~/Library/Caches/sccache"];case 3:default:return["~/.cache/ccache","~/.cache/sccache"]}case"conan":switch(n){case 2:case 3:default:return["~/.conan2/p","~/.conan2/b"]}case"gnupg":switch(n){case 2:case 3:default:return["~/.gnupg"]}}}function TP(i,n){let e=new Set;for(let r of n)for(let o of HU)um(r,o,{os:i})&&e.add(o.value);let t=[...e].flatMap(r=>wP(r,i));return[...new Set(t)]}var HU=[{keywords:["gpg","gpg2"],value:"gnupg"},{keywords:["git"],value:"gnupg"}];function pm(i,n,e=[]){if(n.length===0)return TP(i,e);let t=new Set;for(let o of n){let s=FU.get(o.toLowerCase());s&&t.add(s)}let r=[...t].flatMap(o=>wP(o,i));return[...new Set([...r,...TP(i,e)])]}var $U=[{keywords:["node","npm","npx","pnpm","yarn","corepack","bun","deno","nvm","volta","fnm","asdf","mise"],value:"node"},{keywords:["git"],value:"gnupg",condition:({os:i})=>i!==1}],WU=new Set(["git","gh","gpg","gpg2"]);function qU(i,n){switch(i){case"gnupg":switch(n){case 1:return{};case 2:case 3:default:return{network:{allowAllUnixSockets:!0},filesystem:{allowRead:["~/.gnupg"],allowWrite:["~/.gnupg"]}}}case"node":switch(n){case 1:return{};case 2:case 3:default:return{filesystem:{allowWrite:["~/.volta/"]}}}}}function Hc(i,n){let e=new Set;for(let r of n)for(let o of $U)um(r,o,{os:i})&&BU(o.value,n)&&e.add(o.value);let t={};for(let r of e)xP(t,qU(r,i));return t}function BU(i,n){switch(i){case"gnupg":return n.every(e=>WU.has(e.keyword.toLowerCase()));case"node":return!0}}function xP(i,n){for(let[e,t]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(i,e)){i[e]=t;continue}let r=i[e];if(Array.isArray(r)&&Array.isArray(t)){i[e]=[...new Set([...r,...t])];continue}RP(r)&&RP(t)&&xP(r,t)}}function RP(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}var Oye=$("terminalSandboxService");var An=class extends T{constructor(e,t,r,o){super();this._host=e;this._fileService=t;this._logService=r;this._windowsMxcRuntime=o;this._sandboxSettingsId=H();this._runtimeResolved=!1;this._runAsNode=!1;this._needsForceUpdateConfigFile=!0;this._commandAllowListKeywords=[];this._commandAllowListCommandDetails=[];this._commandAllowNetwork=!1;this._os=Et;this._defaultWritePaths=[];this._fileSystemPathExtUri=new xo(()=>this._os===1);this._buildSandboxPayload=(e,t,r,o,s)=>this._host.buildWindowsMxcSandboxPayload(e,t,r,o,s);this._pathJoin=(...e)=>(this._os===1?he:re).join(...e);this._register(ee.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()}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")??[],t=this._getSettingValue("chat.agent.deniedNetworkDomains")??[];return{allowedDomains:e,deniedDomains:t}}async wrapCommand(e,t,r,o,s,a){let l=this._areUnsandboxedCommandsAllowed(),d=this._areRetryWithAllowNetworkRequestsAllowed(),u=t!==!0&&a!==!0&&(d||l)?this._getBlockedDomains(e):{blockedDomains:[],deniedDomains:[]},p=d&&u.blockedDomains.length>0,m=t!==!0&&(a===!0&&d||p),h=this._normalizeCommandDetails(s??[]),y=this._normalizeCommandKeywords(h.map(z=>z.keyword)),S=pm(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),b=pm(this._os,y,h),I=Hc(this._os,this._commandAllowListCommandDetails),_=Hc(this._os,h);if((this._commandAllowListKeywords.length===0||this._needsForceUpdateConfigFile||!this._areStringArraysEqual(this._commandAllowListKeywords,y)||!this._areStringArraysEqual(S,b)||!this._areObjectsEqual(I,_)||this._commandCwd?.toString()!==o?.toString()||this._commandAllowNetwork!==m||this._os===1&&(this._commandLine!==e||this._commandShell!==r))&&(this._commandAllowListKeywords=y,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(!t&&!d&&l&&u.blockedDomains.length>0)return{command:this._wrapUnsandboxedCommand(e,r),isSandboxWrapped:!1,blockedDomains:u.blockedDomains,deniedDomains:u.deniedDomains,requiresUnsandboxConfirmation:!0};if(t&&l)return{command:this._wrapUnsandboxedCommand(e,r),isSandboxWrapped:!1};let A=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,...A}}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 X=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(X)}`;if(this._runAsNode){let z=`ELECTRON_RUN_AS_NODE=1 ${E}`;return{command:this._wrapSandboxRuntimeCommandForLaunch(z,o),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...A}}return{command:this._wrapSandboxRuntimeCommandForLaunch(E,o),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...A}}async checkForSandboxingPrereqs(e=!1,t){if(!await this._isSandboxConfiguredEnabled(t))return{enabled:!1,sandboxConfigPath:void 0,failedCheck:void 0};let r=await this.getSandboxConfigPath(e,t);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 checkFileAccess(e,t,r){if(!await this._isSandboxConfiguredEnabled(r))return{allowed:!0,denied:[]};await this._resolveRuntimeInfo(),this._tempDir||await this._initTempDir();let o=this._tempDir?this._getUriPath(v.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`)):void 0,s=await this._getFileSystemAccessPaths(o),a=[];for(let l of t)(!l||!await this._hasFileSystemAccess(e,l,s))&&a.push(l);return{allowed:a.length===0,denied:a}}async getSandboxConfigPath(e=!1,t){if(await this._isSandboxConfiguredEnabled(t))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 t=[];return this._sandboxDependencyStatus&&!this._sandboxDependencyStatus.bubblewrapInstalled&&t.push("bubblewrap"),this._sandboxDependencyStatus&&!this._sandboxDependencyStatus.socatInstalled&&t.push("socat"),t}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,t){return this._os!==3||!t?.path||t.path===this._tempDir?.path?e:`cd ${this._quoteShellArgument(t.path)} && ${e}`}_wrapSandboxRuntimeCommandForLaunch(e,t){let r=this._tempDir?.path;return this._os===3&&t?.path&&r&&t.path!==r?`cd ${this._quoteShellArgument(r)}; ${e}`:e}_wrapUnsandboxedCommand(e,t){return this._os===1?this._windowsMxcRuntime.wrapUnsandboxedCommand(e):this._tempDir?.path?t?`env TMPDIR="${this._tempDir.path}" ${this._quoteShellArgument(t)} -c ${this._quoteShellArgument(e)}`:`(TMPDIR="${this._tempDir.path}"; export TMPDIR; ${e})`:e}_getBlockedDomains(e){if(this._isSandboxAllowNetworkConfigured())return{blockedDomains:[],deniedDomains:[]};let t=this._extractDomains(e);if(t.length===0)return{blockedDomains:[],deniedDomains:[]};let{allowedDomains:r,deniedDomains:o}=this.getResolvedNetworkDomains(),s=new Set,a=new Set;for(let l of t){if(o.some(d=>GS(l,d))){s.add(l),a.add(l);continue}r.some(d=>GS(l,d))||s.add(l)}return{blockedDomains:[...s],deniedDomains:[...a]}}_extractDomains(e){let t=new Set,r;for(An._urlRegex.lastIndex=0;(r=An._urlRegex.exec(e))!==null;){let o=this._extractDomainFromUrl(r[0]);o&&t.add(o)}for(An._sshRemoteRegex.lastIndex=0;(r=An._sshRemoteRegex.exec(e))!==null;){let o=Fc(r[1],!0);o&&t.add(o)}for(An._hostRegex.lastIndex=0;(r=An._hostRegex.exec(e))!==null;){let o=Fc(r[1]);o&&t.add(o)}return[...t]}_extractDomainFromUrl(e){try{let t=v.parse(e).authority;return Fc(t,!0)}catch{return}}_normalizeCommandKeywords(e){return[...new Set(e.map(t=>t.toLowerCase()))].sort()}_normalizeCommandDetails(e){let t=new Set,r=[];for(let o of e){let s={keyword:o.keyword.toLowerCase(),args:[...o.args]},a=JSON.stringify(s);t.has(a)||(t.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,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}_areObjectsEqual(e,t){return JSON.stringify(e)===JSON.stringify(t)}_isSandboxAllowedByPrecheckInputs(e){return e?.isDefaultApprovalPermissionEnabled!==!1}async _isSandboxConfiguredEnabled(e){if(!this._isSandboxAllowedByPrecheckInputs(e))return!1;if(await this.getOS(),this._os===1){let r=this._getSandboxConfiguredWindowsEnabledValue();return pv(r)}let t=this._getSandboxConfiguredEnabledValue();return pv(t)}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 t=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",`${t}-${aI}`,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(),t=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=Hc(this._os,this._commandAllowListCommandDetails),d=this._getCommandRuntimeFileSystemPaths(l,"allowRead"),c=this._getCommandRuntimeFileSystemPaths(l,"allowWrite"),u=v.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`),p=this._getUriPath(u),m=[],h=[],y=[],S;if(this._os===1){let I=await this._getWindowsMxcFilesystemPolicy(),_=await this._getWindowsMxcEnvironment();m=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(o.allowWrite),...I.readwritePaths]),h=await this._resolveFileSystemPaths([...o.allowRead??[],...I.readonlyPaths]),y=await this._resolveFileSystemPaths(o.denyRead??[]),this._windowsMxcEnvironment=_}else this._os===2?(m=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,c))).filter(I=>I!==p),h=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(r.allowRead,m,d)),y=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...r.denyRead??[],p])),S=r.denyWrite?await this._resolveFileSystemPaths(r.denyWrite):void 0):this._os===3&&(m=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(t.allowWrite,c))).filter(I=>I!==p),h=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(t.allowRead,m,d)),y=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...t.denyRead??[],p])),S=await this._resolveFileSystemPaths(t.denyWrite));let b=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,allowReadPaths:h,allowWritePaths:m,denyReadPaths:y,env:this._windowsMxcEnvironment??[]},this._buildSandboxPayload):{network:e?{allowedDomains:[],deniedDomains:[],enabled:!1}:this.getResolvedNetworkDomains(),filesystem:{denyRead:y,allowRead:h,allowWrite:m,denyWrite:S}};if(this._os!==1){let I=b;this._mergeAdditionalSandboxConfigProperties(I,a),this._mergeAdditionalSandboxConfigProperties(I,l),this._os===2&&(I.allowPty??=!0)}return this._sandboxConfigPath=p,await this._fileService.createFile(u,U.fromString(JSON.stringify(b,null,"	")),{overwrite:!0}),this._sandboxConfigPath}async _getFileSystemAccessPaths(e){let t=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=Hc(this._os,this._commandAllowListCommandDetails),a=this._getCommandRuntimeFileSystemPaths(s,"allowRead"),l=this._getCommandRuntimeFileSystemPaths(s,"allowWrite"),d=[],c=[],u=[],p;if(this._os===1){let m=await this._getWindowsMxcFilesystemPolicy();d=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(o.allowWrite),...m.readwritePaths]),c=await this._resolveFileSystemPaths([...o.allowRead??[],...m.readonlyPaths]),u=await this._resolveFileSystemPaths(o.denyRead??[])}else this._os===2?(d=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,l))).filter(m=>m!==e),c=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(r.allowRead,d,a)),u=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...r.denyRead??[],...e?[e]:[]])),p=r.denyWrite?await this._resolveFileSystemPaths(r.denyWrite):void 0):this._os===3&&(d=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(t.allowWrite,l))).filter(m=>m!==e),c=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(t.allowRead,d,a)),u=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...t.denyRead??[],...e?[e]:[]])),p=await this._resolveFileSystemPaths(t.denyWrite));return{allowReadPaths:c,allowWritePaths:d,denyReadPaths:u,denyWritePaths:p}}async _hasFileSystemAccess(e,t,r){let o=await this._resolveFileSystemPath(t);return e==="write"?this._os===1&&this._matchesAnyFileSystemPath(o,r.denyReadPaths)||this._matchesAnyFileSystemPath(o,r.denyWritePaths??[])?!1:this._matchesAnyFileSystemPath(o,r.allowWritePaths):this._matchesAnyFileSystemPath(o,[...r.allowReadPaths,...r.allowWritePaths])?!0:!this._matchesAnyFileSystemPath(o,r.denyReadPaths)}_matchesAnyFileSystemPath(e,t){return e.some(r=>t.some(o=>this._matchesFileSystemPath(r,o)))}_matchesFileSystemPath(e,t){let r=this._normalizeFileSystemAccessPath(e),o=this._normalizeFileSystemAccessPath(t,!0),s=this._os===1;return this._containsGlobPattern(o)?og(o,r,{ignoreCase:s}):this._fileSystemPathExtUri.isEqualOrParent(this._toFileSystemAccessUri(r),this._toFileSystemAccessUri(o))}_toFileSystemAccessUri(e){return v.from({scheme:"terminal-sandbox-path",path:e.startsWith("/")?e:`/${e}`})}_normalizeFileSystemAccessPath(e,t=!1){let r=this._os===1?e.replace(/\\/g,"/"):e;return this._os===1&&/^\/[a-zA-Z]:($|\/)/.test(r)&&(r=r.slice(1)),(!t||!this._containsGlobPattern(r))&&(r=re.normalize(r)),r.length>1&&r.endsWith("/")&&!/^[a-zA-Z]:\/$/.test(r)&&(r=r.replace(/\/+$/,"")),r}_containsGlobPattern(e){return/[*?{\[]/.test(e)}_getCommandRuntimeFileSystemPaths(e,t){let r=e.filesystem;if(!this._isObjectForSandboxConfigMerge(r))return[];let o=r[t];return Array.isArray(o)?o.filter(s=>typeof s=="string"):[]}_mergeAdditionalSandboxConfigProperties(e,t){for(let[r,o]of Object.entries(t)){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?he:re).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,t=[]){let r=this._host.getWriteRoots().map(o=>this._getUriPath(o));return[...new Set([...r,...this._defaultWritePaths,...await this._getWorkspaceStorageReadPaths(),...e??[],...t])]}_updateDenyReadPathsWithHome(e){if(this._os===1)return[...new Set(e??[])];let t=this._userHome?this._getUriPath(this._userHome):void 0;return[...new Set([...e??[],...t?[t]:[]])]}async _updateAllowReadPathsWithAllowWrite(e,t,r=[]){return[...new Set([...e??[],...pm(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),...r,...this._getSandboxRuntimeReadPaths(),...await this._getWorkspaceStorageReadPaths(),...t])]}async _resolveFileSystemPaths(e){let t=await Promise.all((e??[]).map(o=>this._resolveFileSystemPath(o))),r=new Set;return t.flat().filter(o=>{let s=this._getFileSystemPathComparisonKey(o);return r.has(s)?!1:(r.add(s),!0)})}_getFileSystemPathComparisonKey(e){return this._os===1?e.replace(/\//g,"\\").toLowerCase():e}async _resolveFileSystemPath(e){let t=this._os===3?this._expandHomePath(e):e;if(!this._isAbsoluteFileSystemPath(t))return[t];try{let r=await this._fileService.realpath(this._toFileSystemResource(t)),o=r?this._getUriPath(r):void 0;return o&&o!==t?[t,o]:[t]}catch{return[t]}}_isAbsoluteFileSystemPath(e){return(this._os===1?he:re).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})??v.file(e)}_toWindowsFileSystemResource(e){let t=e.replace(/\\/g,"/");if(/^\/\/[^/]/.test(t)){let r=t.indexOf("/",2);return r===-1?v.from({scheme:"file",authority:t.slice(2),path:"/"}):v.from({scheme:"file",authority:t.slice(2,r),path:t.slice(r)||"/"})}return/^[a-zA-Z]:($|\/)/.test(t)?v.from({scheme:"file",path:`/${t[0].toLowerCase()}${t.slice(1)}`}):/^\/[a-zA-Z]:($|\/)/.test(t)?v.from({scheme:"file",path:`/${t[1].toLowerCase()}${t.slice(2)}`}):v.from({scheme:"file",path:t})}_expandHomePath(e){let t=this._userHome?.path;return t?e==="~"?t:e.startsWith("~/")?this._pathJoin(t,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 t of[this._execPath,this._pathDirname(this._execPath)])this._isPathUnderAppRoot(t)||e.push(t);return e}_isPathUnderAppRoot(e){return this._appRoot?e===this._appRoot||e.startsWith(`${this._appRoot}${this._os===1?he.sep:re.sep}`):!1}async _getWorkspaceStorageReadPaths(){let e=await this._host.getWorkspaceStorageReadRoot();return e?[this._getUriPath(e)]:[]}_getDefaultWindowsMxcCwd(){return this._host.getWriteRoots()[0]}_getSandboxConfiguredEnabledValue(){return this._normalizeSandboxEnabledValue(this._getSettingValue("chat.agent.sandbox.enabled"))}_getSandboxConfiguredWindowsEnabledValue(){return this._normalizeSandboxEnabledValue(this._getSettingValue("chat.agent.sandbox.enabledWindows"))}_normalizeSandboxEnabledValue(e){return e===void 0?"off":uv(e)}_isSandboxAllowNetworkConfigured(){return this._getSettingValue("chat.agent.sandbox.allowNetwork")===!0?!0: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=w([C(1,xe),C(2,D),C(3,cm)],An);var VU="tmp",JS=class{constructor(n,e,t,r,o,s){this._sessionId=n;this._workingDirectory=e;this._environmentService=t;this._productService=r;this._agentConfigurationService=o;this.onDidChangeRoots=ee.None;this._sandboxHelper=s,this.onDidChangeSandboxSettings=this._agentConfigurationService.onDidRootConfigChange}async getOS(){return Et}async getRuntimeInfo(){let n=le(Dt.asFileUri("").path),e=!!process.versions.electron;return{appRoot:n,execPath:process.execPath,runAsNode:e}}async getUserHome(){return this._environmentService.userHome}async getSandboxTempDir(){let n=this._environmentService.userHome;if(!n)return;let e=v.joinPath(n,this._productService.dataFolderName,VU),r=`agenthost_${zU("sha256").update(this._sessionId).digest("hex").substring(0,16)}`;return v.joinPath(e,r)}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(n,e,t,r,o){return this._sandboxHelper.buildWindowsMxcSandboxPayload(n,e,t,r,o)}getSandboxSetting(n){let e=hw[n];return e===void 0?void 0:this._agentConfigurationService.getRootValue(Cr,"sandbox")?.[e]}};function AP(i,n,e,t,r,o,s){let a=new JS(o,s,n,e,t,r);return i.createInstance(An,a)}var jU="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.",gi=class extends T{constructor(e,t,r,o,s,a,l,d,c){super();this._sessionUri=e;this.workingDirectory=t;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 P);this.onDidAssociateTerminal=this._onDidAssociateTerminal.event;this._register(M(()=>{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()??H(),t=AP(this._instantiationService,this._environmentService,this._productService,this._agentConfigurationService,this._sandboxHelper,e,this.workingDirectory);this._register(t),this._register(M(()=>{t.cleanupTempDir().catch(r=>this._logService.warn("[ShellManager] Sandbox temp dir cleanup failed",r))})),this._sandboxEngine=t}return this._sandboxEngine}async getOrCreateShell(e,t,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=H(),a=`agenthost-terminal://shell/${s}`,l={kind:"session",session:this._sessionUri.toString(),turnId:t,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 t=!1;return{object:e,dispose:()=>{t||(t=!0,this._busyShellIds.delete(e.id))}}}holdShellUntilCommandFinishes(e){if(this._heldShellReleaseListeners.has(e.id))return;let t=new G,r=()=>{this._busyShellIds.delete(e.id),this._heldShellReleaseListeners.delete(e.id),t.dispose()};t.add(this._terminalManager.onCommandFinished(e.terminalUri,r)),t.add(this._terminalManager.onExit(e.terminalUri,r)),this._heldShellReleaseListeners.set(e.id,t)}_trackToolCall(e,t){this._toolCallShells.set(e,t);let r=this._shells.get(t);if(r){let o=r.shellType==="bash"?"Bash":"PowerShell";this._onDidAssociateTerminal.fire({toolCallId:e,terminalUri:r.terminalUri,displayName:o})}}getTerminalUriForToolCall(e){let t=this._toolCallShells.get(e);if(t)return this._shells.get(t)?.terminalUri}getShell(e){return this._shells.get(e)}listShells(){let e=[];for(let t of this._shells.values())this._terminalManager.hasTerminal(t.terminalUri)&&e.push(t);return e}shutdownShell(e){let t=this._shells.get(e);return t?(this._heldShellReleaseListeners.get(e)?.dispose(),this._heldShellReleaseListeners.delete(e),this._terminalManager.disposeTerminal(t.terminalUri),this._shells.delete(e),this._busyShellIds.delete(e),this._logService.info(`[ShellManager] Shut down shell ${e}`),!0):!1}};gi=w([C(2,Ir),C(3,D),C(4,Ie),C(5,lc),C(6,Ct),C(7,ze),C(8,lm)],gi);function fi(i){return{textResultForLlm:i,resultType:"success"}}function En(i,n){return{textResultForLlm:i,resultType:"failure",error:n}}function $c(i,n){return{toolResult:i,keepShellBusy:n?.keepShellBusy}}function KU(i,n){switch(i.status){case"completed":{let e=i.exitCode??0,t=`Exit code: ${e}
${i.output}`;return $c(e===0?fi(t):En(t))}case"shellExited":return $c(En(`Shell exited with code ${i.exitCode}
${i.output}`));case"timeout":return $c(En(`Command timed out after ${Math.round(n/1e3)}s. Partial output:
${i.output}`,"timeout"));case"background":return $c(fi("The user chose to continue this command in the background. The terminal is still running."),{keepShellBusy:!0});case"altBuffer":return $c(En(jU,"alternateBuffer"),{keepShellBusy:!0})}}async function GU(i,n,e,t,r){let o=KU(await ng(i,n,e,t,r),e);return{...o,toolResult:{...o.toolResult,textResultForLlm:`Shell ID: ${i.id}
${o.toolResult.textResultForLlm}`}}}async function EP(i,n,e,t){let r=await i.getResolvedExecutable(),o=tg(r),s=i.getOrCreateSandboxEngine(),a=await s.isEnabled(),l=a?s.getResolvedNetworkDomains():void 0,d={name:o,description:o==="bash"?tf(r)?XU(a,l):QU(a,l):YU(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,I)=>{let _=b.timeout??eg,R=await i.getOrCreateShell(o,I.toolCallId,I.toolCallId),A=!0;try{let X=b.command;if(a){if(b.requestUnsandboxedExecution&&!s.areUnsandboxedCommandsAllowed())return En("Unsandboxed execution is disabled by the chat.agent.sandbox.allowUnsandboxedCommands setting.","unsandboxed_disabled");let z=async B=>{if(!t){let N=B?.join(", ")??"(unknown)";return En(`Command requires approval to run outside the sandbox. Blocked domains: ${N}. Re-run with requestUnsandboxedExecution=true and requestUnsandboxedExecutionReason explaining why unsandboxed access is required.`,"sandbox_blocked")}return await t({toolCallId:I.toolCallId,toolName:I.toolName,shellExecutable:r,command:b.command,reason:b.requestUnsandboxedExecutionReason,blockedDomains:B})},x=await s.wrapCommand(b.command,b.requestUnsandboxedExecution,r,R.object.shellType==="bash"?i.workingDirectory:void 0);if(b.requestUnsandboxedExecution&&!x.isSandboxWrapped){let B=await z(x.blockedDomains);if(typeof B!="boolean")return B;if(!B){let K=x.blockedDomains?.join(", ")??"(none)";return En(`User declined to run command outside the sandbox. Blocked domains: ${K}.`,"sandbox_blocked")}}if(x.requiresUnsandboxConfirmation){let B=await z(x.blockedDomains);if(typeof B!="boolean")return B;if(!B){let K=x.blockedDomains?.join(", ")??"(unknown)";return En(`User declined to run command outside the sandbox. Blocked domains: ${K}.`,"sandbox_blocked")}x=await s.wrapCommand(b.command,!0,r,R.object.shellType==="bash"?i.workingDirectory:void 0)}X=x.command}let E=await GU(R.object,X,_,n,e);return E.keepShellBusy&&(A=!1,i.holdShellUntilCommandFinishes(R.object)),E.toolResult}finally{A&&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 I=i.listShells(),_=b.shell_id?i.getShell(b.shell_id):I[I.length-1];if(!_)return En("No active shell found.","no_shell");let R=n.getContent(_.terminalUri);return fi(R?Yi(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 I=i.listShells(),_=I[I.length-1];return _?(await n.sendText(_.terminalUri,b.command,{shouldExecute:!1}),fi("Input sent to shell.")):En("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)?fi("Shell stopped."):En("Shell not found.","not_found");let I=i.listShells(),_=I[I.length-1];return _?(i.shutdownShell(_.id),fi("Shell stopped.")):En("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 fi("No active shells.");let I=b.map(_=>{let R=n.getExitCode(_.terminalUri),A=R!==void 0?`exited (${R})`:"running";return`- ${_.id}: ${_.shellType} [${A}]`});return fi(I.join(`
`))}},h=o==="bash"?"powershell":"bash",y=`This tool is disabled because the configured shell is ${r}. Use the \`${o}\` tool instead.`;return[d,c,u,p,m,{name:h,description:y,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:()=>En(y,"wrong_shell")}]}function JU(i){return i.endsWith("System32\\WindowsPowerShell\\v1.0\\powershell.exe")}function YU(i,n,e,t){let r=JU(n),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(...kP(t)),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 kP(i){let n=["","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),t=i.allowedDomains.filter(r=>!e.has(r));t.length===0?n.push("- All network access is blocked in the sandbox"):n.push(`- Only the following domains are accessible in the sandbox (all other network access is blocked): ${t.join(", ")}`),i.deniedDomains.length>0&&n.push(`- The following domains are explicitly blocked in the sandbox: ${i.deniedDomains.join(", ")}`)}return n}function DP(i,n,e){let t=[`
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 n&&t.push(kP(e).join(`
`)),t.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.`),t.join("")}function QU(i,n){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.",DP("bash",i,n),"- 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 XU(i,n){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.",DP("bash",i,n),"- 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(`
`)}import{spawn as ZU}from"child_process";function LP(i){let n={};for(let e of i)n[e.name]=UP(e.name,e.configuration);return n}function NP(i){let n={};for(let[e,t]of Object.entries(i))eF(t)&&(n[e]=UP(e,t));return n}function eF(i){if(!i||typeof i!="object")return!1;let n=i;return n.type==="stdio"?typeof n.command=="string":n.type==="http"?typeof n.url=="string":!1}function UP(i,n){return n.type==="stdio"?{type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:tF(n.env)},...n.cwd&&{cwd:n.cwd}}:{type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}function tF(i){let n={};for(let[e,t]of Object.entries(i))t!==null&&(n[e]=String(t));return n}async function MP(i,n){let e=[];for(let t of i)try{let o=(await n.readFile(t.uri)).value.toString(),s=Za(o),a=s?.getStringValue("name")?.trim()||t.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}async function FP(i,n,e){let t=i.filter(o=>!o.pluginDir||o.pluginDir.scheme!==ie.file),r=await MP(t.flatMap(o=>o.agents),e);if(n&&!r.some(o=>o.name===n)){let o=i.flatMap(s=>s.agents).filter(s=>s.name===n);for(let s of await MP(o,e))r.some(a=>a.name===s.name)||r.push(s)}return r}function YS(i){let n=new Map,e=t=>{n.has(t.id)||n.set(t.id,t)};for(let t of i){for(let r of t.agents)e(r.customization);for(let r of t.skills)e(r.customization);for(let r of t.instructions)e(r.customization);for(let r of t.hooks)e(r.customization);for(let r of t.mcpServers)e(r.customization)}return[...n.values()]}function HP(i){return WP(i)}function $P(i){return WP(i)}function WP(i){let n=new Set,e=[];for(let t of i){let r=le(t.uri.fsPath);n.has(r)||(n.add(r),e.push(r))}return e}function nF(i,n){return n===1&&i.windows?i.windows:n===2&&i.osx?i.osx:n===3&&i.linux?i.linux:i.command}function Wc(i,n){let e=nF(i,Et);if(!e)return Promise.resolve("");let t=(i.timeout??30)*1e3,r=i.cwd?.fsPath;return new Promise((o,s)=>{let a=Et===1,c=ZU(a?"cmd.exe":"/bin/sh",a?["/c",e]:["-c",e],{cwd:r,env:{...process.env,...i.env},stdio:["pipe","pipe","pipe"],timeout:t}),u="",p="";c.stdout.on("data",m=>{u+=m.toString()}),c.stderr.on("data",m=>{p+=m.toString()}),n&&c.stdin.write(n),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 OP(i,n){if(!i)return;let e=JSON.stringify(n);for(let t of i)try{let r=await Wc(t,e);if(r.trim())try{let o=JSON.parse(r);if(o&&typeof o=="object")return o}catch{}}catch{}}var rF={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function qP(i,n){let e=new Map;for(let c of i){let u=rF[c.type];if(!u)continue;let p=e.get(u)??[];p.push(...c.commands),e.set(u,p)}let t={},r=e.get("onPreToolUse");(r?.length||n)&&(t.onPreToolUse=async c=>(await n?.onPreToolUse(c),OP(r,c)));let o=e.get("onPostToolUse");(o?.length||n)&&(t.onPostToolUse=async c=>(await n?.onPostToolUse(c),OP(o,c)));let s=e.get("onUserPromptSubmitted");s?.length&&(t.onUserPromptSubmitted=async c=>{let u=JSON.stringify(c);for(let p of s)try{await Wc(p,u)}catch{}});let a=e.get("onSessionStart");a?.length&&(t.onSessionStart=async c=>{let u=JSON.stringify(c);for(let p of a)try{await Wc(p,u)}catch{}});let l=e.get("onSessionEnd");l?.length&&(t.onSessionEnd=async c=>{let u=JSON.stringify(c);for(let p of l)try{await Wc(p,u)}catch{}});let d=e.get("onErrorOccurred");return d?.length&&(t.onErrorOccurred=async c=>{let u=JSON.stringify(c);for(let p of d)try{await Wc(p,u)}catch{}}),t}function BP(i,n){let e=t=>JSON.stringify(t.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(n)}var iF=!1;function qc(i,n){if(!n||i==="win32"&&!iF)return;let e=i==="win32"&&n["enabled.windows"]!==void 0?n["enabled.windows"]:n.enabled;if(e!=="on"&&e!=="allowNetwork")return;let t=i==="win32"?n["fileSystem.windows"]:i==="darwin"?n["fileSystem.mac"]:n["fileSystem.linux"],r=t&&typeof t=="object"?t:{},o=new Set(r.denyRead??[]),s=new Set,a=new Set;for(let S of r.denyWrite??[])o.has(S)||s.add(S);for(let S of r.allowWrite??[])!o.has(S)&&!s.has(S)&&a.add(S);for(let S of r.allowRead??[])!o.has(S)&&!s.has(S)&&!a.has(S)&&s.add(S);let d=e==="allowNetwork"||e==="on"&&n.allowNetwork===!0,c=!1,u=n.allowedNetworkDomains,p=n.deniedNetworkDomains,m=!d&&c&&u?.length?[...u]:void 0,h=!d&&c&&p?.length?[...p]:void 0,y=d||!!m||!!h;return{enabled:!0,allowBypass:!0,userPolicy:{filesystem:{...a.size?{readwritePaths:[...a]}:{},...s.size?{readonlyPaths:[...s]}:{},...o.size?{deniedPaths:[...o]}:{}},network:{allowOutbound:y,...y&&m?{allowedHosts:m}:{},...y&&h?{blockedHosts:h}:{}}}}}var QS="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.",zP=["<file_folder_and_symbol_links>","Always use Markdown links when referring to existing files, folders, or symbols in the workspace. This is very important for helping the user understand your responses.","- File: use the file name as the link text and the absolute filesystem path as the target, for example [foo.ts](/path/to/foo.ts).","- Folder: links to folders are also supported, with an absolute path to the folder as the target, for example [src/](/path/to/src).","- Symbol: link to symbols by using the containing file path with a 1-based line number as the target, for example [myMethod](/path/to/foo.ts:42).","- Use `/` path separators in link targets, including on Windows (`C:/path/to/foo.ts`).","- Use absolute filesystem paths rather than `file://` URIs.","- Do not provide line ranges.","- Use a markdown link format every time you refer to a file, folder, or symbol, not just the first time.","</file_folder_and_symbol_links>"].join(`
`),Bc={mode:"customize",sections:{identity:{action:"replace",content:QS}}},XS=["<workspaceless_chat>","This is a lightweight workspace-less chat, not tied to any project or workspace. The user opens it for quick questions, navigation, and triage.","","- Your working directory is a SCRATCH directory for running commands and saving throwaway artifacts \u2014 it is NOT a code repository. Do not treat it as a project to build, test, or commit.","- If the user points you at a real repository, prefer read-only operations: read files, search code, and inspect git metadata (branch, log, diff, status) to answer questions. Avoid modifying files or running builds, tests, linters, or installs in their working copies.","- When the user wants code changes, test runs, or any work that modifies or executes against a real project, delegate it to a dedicated session rather than doing it here.","</workspaceless_chat>"].join(`
`);function VP(i){return{mode:"replace",content:i}}function jP(i){return{mode:"customize",sections:i}}function KP(i,n){if(i.mode==="replace")return i;let e=i.content;return{...i,content:e?`${e}

${n}`:n}}function GP(i){if(i.mode==="replace")return`mode=replace (content length ${i.content.length})`;if(i.mode==="customize"){let n=Object.entries(i.sections??{}).map(([t,r])=>{let o=r?.action;return`${t}:${typeof o=="function"?"transform":o}`}),e=i.content?` +content(length ${i.content.length})`:"";return`mode=customize sections=[${n.join(", ")}]${e}`}return`mode=append (content length ${i.content?.length??0})`}var zc={OpenBrowserPage:"openBrowserPage",ReadPage:"readPage",ScreenshotPage:"screenshotPage",NavigatePage:"navigatePage",ClickElement:"clickElement",TypeInPage:"typeInPage",HoverElement:"hoverElement",DragElement:"dragElement",HandleDialog:"handleDialog",RunPlaywrightCode:"runPlaywrightCode"},JP=Object.values(zc);var oF=JP.filter(i=>i!==zc.OpenBrowserPage),sF=i=>{if(!i(zc.OpenBrowserPage))return;let n=oF.find(i);if(n)return`Use the browser tools (${zc.OpenBrowserPage}, ${n}, etc.) when beneficial for front-end tasks, such as when visualizing or validating UI changes.`},YP=[sF];function aF(i,n=YP){let e=Ci(n.map(t=>t(i)));return e.length>0?e.join(`
`):void 0}function lF(i,n){if(!i)return{action:"append",content:`
${n}`};if(i.action==="remove"||typeof i.action=="function")return i;let e=i.content??"",t=e?`${e}
${n}`:n;switch(i.action){case"append":return{action:"append",content:`
${t}`};case"prepend":return{action:"prepend",content:`${t}
`};default:return{action:i.action,content:t}}}function QP(i,n,e=YP){let t=aF(i,e);return t===void 0?void 0:lF(n,t)}var ZS=class{constructor(){this._promptsWithMatcher=[];this._familyPrefixList=[]}registerPrompt(n){n.matchesModel&&this._promptsWithMatcher.push(n);for(let e of n.familyPrefixes)this._familyPrefixList.push({prefix:e,ctor:n})}_getContributor(n){for(let e of this._promptsWithMatcher)if(e.matchesModel(n))return e;for(let{prefix:e,ctor:t}of this._familyPrefixList)if(n.id.startsWith(e))return t}resolveSystemMessageConfig(n,e){let t=this._withUniversalSections(this._resolveModelConfig(n,e),e),r=this._withWorkspacelessScratch(t,e);return KP(r,zP)}_resolveModelConfig(n,e){if(!n)return Bc;let t=this._getContributor(n);if(!t)return Bc;let r=new t,o=r.resolveFullSystemPrompt?.(n,e);if(o!==void 0)return VP(o);let s=r.resolveSectionOverrides?.(n,e);return s&&Object.keys(s).length>0?jP(s):Bc}_withUniversalSections(n,e){if(n.mode!=="customize")return n;let t=QP(r=>e.hasClientTool(r),n.sections?.tool_instructions);return t?{...n,sections:{...n.sections,tool_instructions:t}}:n}_withWorkspacelessScratch(n,e){if(!e.workspaceless||n.mode!=="customize")return n;let t=n.content?`${n.content}

${XS}`:XS;return{...n,content:t}}},fm=new ZS;function dF(){return{identity:{action:"replace",content:QS},tone:{action:"append",content:`
Provide concise, focused responses. Skip non-essential context, and keep examples minimal. Use a direct style and use emojis sparingly.`},guidelines:{action:"append",content:["Do not spawn a subagent for work you can complete directly in a single response (e.g. refactoring a function you can already see).","Spawn multiple subagents in the same turn when fanning out across items or reading multiple files."].join(`
`)}}}function cF(i){return i.id.startsWith("claude-opus-4-8")||i.id.startsWith("claude-opus-4.8")}var eb=class{static{this.familyPrefixes=[]}static matchesModel(n){return cF(n)}resolveSectionOverrides(n,e){return e.getSetting("opus48Prompt")===!0?dF():void 0}};fm.registerPrompt(eb);var tb="thinkingLevel",gm="contextSize",uF="contextTier",pF=["low","medium","high","xhigh"],fF=["default","long_context"];function nb(i){return new Set(i.tools.map(n=>n.name))}function gF(i){return pF.some(n=>n===i)}function mF(i){return fF.some(n=>n===i)}function XP(i){if(typeof i!="object"||i===null)return;let n=Object.getOwnPropertyDescriptor(i,"code")?.value;return typeof n=="number"?n:void 0}function ZP(i){if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null){let n=Object.getOwnPropertyDescriptor(i,"message")?.value;if(typeof n=="string")return n}return String(i)}function hF(i){if(XP(i)!==-32603)return!1;let n=ZP(i);return!/\b(corrupt|corrupted|invalid|validation|schema|must be|parse|malformed|unexpected token)\b/i.test(n)}function mm(i){let n=i?.config?.[tb];return gF(n)?n:void 0}function hm(i,n,e){let t=i?.config?.[uF];if(mF(t))return t;let r=i?.config?.[gm];if(r===void 0)return e?"long_context":void 0;let o=Number(r);if(!(!Number.isFinite(o)||typeof n!="number"))return o>=n?"long_context":"default"}async function yF(i,n,e,t){let r;try{r=await n.listModels()}catch(l){return t.warn(`[Copilot:${i}] Failed to enumerate BYOK models from renderer bridges`,l),{}}if(r.length===0)return{};let o;try{o=await e()}catch(l){return t.warn(`[Copilot:${i}] Failed to start BYOK loopback proxy`,l),{}}let s=[...new Set(r.map(l=>l.vendor))].map(l=>({name:l,type:"openai",wireApi:"completions",baseUrl:o.providerBaseUrl(l),bearerToken:`${o.nonce}.${i}`})),a=r.map(l=>({id:l.id,provider:l.vendor,...l.name!==void 0?{name:l.name}:{},...l.maxContextWindowTokens!==void 0?{maxContextWindowTokens:l.maxContextWindowTokens}:{}}));return t.info(`[Copilot:${i}] Wired ${a.length} BYOK model(s) across ${s.length} provider(s) via loopback proxy ${o.baseUrl}`),{providers:s,models:a}}var ul=class{constructor(n,e,t,r,o,s){this._configurationService=n;this._terminalManager=e;this._logService=t;this._fileService=r;this._byokLmProxyService=o;this._byokLmBridgeRegistry=s}async launch(n,e){let t=await this._buildSessionConfig(n,e),r=this._computeSandboxConfig();if(n.kind==="create")return this._createSession(n,t,r);try{let o=new Dn;this._logService.trace(`[Copilot:${n.sessionId}] Calling SDK resumeSession...`);let s=await n.client.resumeSession(n.sessionId,{...t,workingDirectory:n.workingDirectory.fsPath,...n.resolvedAgentName?{agent:n.resolvedAgentName}:{}});return this._logService.trace(`[Copilot:${n.sessionId}] SDK resumeSession succeeded after ${o.elapsed()}ms`),await this._applySandboxConfig(s,r,n.sessionId),new Uc(s)}catch(o){let s=XP(o),a=ZP(o);if(this._logService.warn(`[Copilot:${n.sessionId}] SDK resumeSession failed: code=${s}, message=${a}`),!hF(o))throw o;this._logService.warn(`[Copilot:${n.sessionId}] Resume failed (code=-32603), falling back to createSession with same ID`);let l=await this._createSession({...n,kind:"create",model:n.fallback.model,longContextWindow:n.fallback.longContextWindow,freeLongContext:n.fallback.freeLongContext},t,r);return this._logService.info(`[Copilot:${n.sessionId}] Fallback createSession succeeded`),l}}async _createSession(n,e,t){let r=await n.client.createSession({...e,sessionId:n.sessionId,streaming:!0,model:n.model?.id,reasoningEffort:mm(n.model),contextTier:hm(n.model,n.longContextWindow,n.freeLongContext),...n.resolvedAgentName?{agent:n.resolvedAgentName}:{},workingDirectory:n.workingDirectory?.fsPath});return await this._applySandboxConfig(r,t,n.sessionId),new Uc(r)}_computeSandboxConfig(){if(this._configurationService.getRootValue(qt,"enableCustomTerminalTool")!==!0)return qc(process.platform,this._configurationService.getRootValue(Cr,"sandbox"))}async _applySandboxConfig(n,e,t){if(e)try{await n.rpc.options.update({sandboxConfig:e}),this._logService.info(`[Copilot:${t}] Applied SDK sandboxConfig via session.options.update`)}catch(r){this._logService.warn(`[Copilot:${t}] Failed to apply SDK sandboxConfig`,r)}}_resolveByokSessionConfig(n){return yF(n,this._byokLmBridgeRegistry,()=>(this._byokProxyHandle||(this._byokProxyHandle=this._byokLmProxyService.start()),this._byokProxyHandle),this._logService)}async disposeByokProxyHandle(){let n=this._byokProxyHandle;if(this._byokProxyHandle=void 0,!!n)try{(await n).dispose()}catch{}}async _buildSessionConfig(n,e){let t=n.snapshot.plugins,r=await this._resolveByokSessionConfig(n.sessionId),o=this._configurationService.getRootValue(qt,"enableCustomTerminalTool")===!0,s=[];if(o){if(!n.shellManager)throw new Error(`ShellManager is required to launch Copilot session '${n.sessionId}'`);s=await EP(n.shellManager,this._terminalManager,this._logService,y=>e.requestUnsandboxedCommandConfirmation(y))}let a=t.filter(y=>!y.pluginDir||y.pluginDir.scheme!==ie.file),l=await FP(t,n.resolvedAgentName,this._fileService),d=HP(a.flatMap(y=>y.skills)),c=$P(t.flatMap(y=>y.instructions)),u=n.kind==="create"?n.model:n.fallback.model,p=nb(n.snapshot),m={getSetting:y=>this._configurationService.getRootValue(qt,y),hasClientTool:y=>p.has(y),workspaceless:n.workspaceless===!0},h=fm.resolveSystemMessageConfig(u,m);return this._logService.info(`[Copilot:${n.sessionId}] Resolved system message: ${GP(h)}`),this._logService.getLevel()<=1&&this._logService.trace(`[Copilot:${n.sessionId}] System message config: ${JSON.stringify(h,(y,S)=>typeof S=="function"?"[transform fn]":S)}`),{...r,clientName:"vscode",enableMcpApps:!0,enableFileHooks:!0,enableConfigDiscovery:!0,onPermissionRequest:y=>e.handlePermissionRequest(y),onUserInputRequest:(y,S)=>e.handleUserInputRequest(y,S),onElicitationRequest:y=>e.handleElicitationRequest(y),onMcpAuthRequest:(y,S)=>e.handleMcpAuthRequest(y,S),hooks:qP(a.flatMap(y=>y.hooks),{onPreToolUse:y=>e.handlePreToolUse(y),onPostToolUse:y=>e.handlePostToolUse(y)}),mcpServers:{...NP(n.snapshot.mcpServers),...LP(a.flatMap(y=>y.mcpServers))},onExitPlanModeRequest:(y,S)=>e.handleExitPlanModeRequest(y,S),workingDirectory:n.workingDirectory?.fsPath,customAgents:l,skillDirectories:d,instructionDirectories:c,systemMessage:h,pluginDirectories:Ci(t.map(y=>y.pluginDir)).filter(y=>y.scheme===ie.file).map(y=>y.fsPath),tools:[...s,...e.createClientSdkTools(),...e.createServerSdkTools()],gitHubToken:n.githubToken,infiniteSessions:{enabled:!0},remoteSession:this._configurationService.getRootValue($t,wd)===!0?"export":void 0}}};ul=w([C(0,ze),C(1,Ir),C(2,D),C(3,xe),C(4,am),C(5,ao)],ul);var xt=class{constructor(){this._entries=new Map;this._earlyResults=new Map}registerAndFire(n,e){if(this._earlyResults.has(n)){let r=this._earlyResults.get(n);return this._earlyResults.delete(n),Promise.resolve(r)}let t=new Ee;return this._entries.set(n,t),e(),t.p}register(n){if(this._earlyResults.has(n)){let r=this._earlyResults.get(n);return this._earlyResults.delete(n),Promise.resolve(r)}let e=this._entries.get(n);e&&!e.isSettled&&e.error(new Y);let t=new Ee;return this._entries.set(n,t),t.p}respond(n,e){let t=this._entries.get(n);return t?(this._entries.delete(n),t.complete(e),!0):!1}respondOrBuffer(n,e){this.respond(n,e)||this._earlyResults.set(n,e)}denyAll(n){for(let[,e]of this._entries)e.isSettled||e.complete(n);this._entries.clear(),this._earlyResults.clear()}rejectAll(n){for(let[,e]of this._entries)e.isSettled||e.error(n);this._entries.clear(),this._earlyResults.clear()}};function ym(i){let n=i.data,e=n.kind;if(vF(n.content))switch(e.type){case"shell_completed":case"shell_detached_completed":{let r=e.description,o=e.shellId;return{messageText:r?f(2222,null,r):o?f(2223,null,o):f(2221,null),startsTurn:!0}}case"agent_completed":return{messageText:e.status==="failed"?f(2217,null,e.agentId):f(2216,null,e.agentId),startsTurn:!0};case"agent_idle":return{messageText:f(2218,null,e.agentId),startsTurn:!0};case"new_inbox_message":return{messageText:f(2220,null,e.senderName),startsTurn:!1};case"instruction_discovered":return{messageText:f(2219,null,e.description??e.sourcePath),startsTurn:!1};default:return}}function vF(i){let n=i.trim();return(/^<system_notification>\s*([\s\S]*?)\s*<\/system_notification>$/.exec(n)?.[1]??n).trim()}var e1=new Set(["agent","app","changelog","context","copy","cwd","exit","extensions","feedback","help","ide","instructions","login","logout","mcp","model","new","plugin","rename","restart","resume","sandbox","session","settings","skills","statusline","streamer-mode","subagents","tasks","terminal-setup","theme","undo","update","user","voice","worktree","autopilot","yolo"]),SF=300,bF={"chronicle:cost-tips":f(2210,null),"chronicle:improve":f(2211,null),"chronicle:reindex":f(2212,null),"chronicle:search":f(2213,null),"chronicle:standup":f(2214,null),"chronicle:tips":f(2215,null)},CF=new Set(["add-dir:directory","after:<delay> <prompt>","compact:focus instructions","directory","every:<interval> <prompt>","fleet:prompt","loop:<interval> <prompt>","plan:prompt","research:topic","review:additional instructions","security-review:additional instructions"]);function t1(i){let n=/^\/([^\s/]+)(?:$|\s+([\s\S]*))/.exec(i);if(!n)return;let e=n[2]??"";return{command:n[1],rest:e.trim(),rawRest:e}}var vm=class{constructor(n,e,t=SF){this.copilotcliId=n;this._sessionInfo=e;this._runtimeSlashCommandCompletionWaitMs=t;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){if(L.provider(n.channel)!==this.copilotcliId)return[];let t=Qf(n.text,n.offset),r=Yf(n.text,n.offset),o=r??t,s=!r&&!!t;if(!o)return[];let a=L.id(n.channel),l=o.typed;return await this._getRuntimeSlashCommandCompletionInfo(a,l,o,s)}async _getKnownSkills(n){let e=new Set,t=await this._sessionInfo.getSessionCustomizations(n)??[];for(let r of t)if(!(r.type==="mcpServer"||!r.enabled||!r.children))for(let o of r.children)o.type==="skill"&&e.add(this._toSlashCommandCandidate(r,o));return e}_toSlashCommandCandidate(n,e){let t=e.name;return n.type==="plugin"&&!IF(n)&&e.name!==n.name&&(t=`${n.name}:${e.name}`),t}async _getRuntimeSlashCommandCompletionInfo(n,e,{rangeStart:t,rangeEnd:r},o){let[s,a]=await Promise.all([this._sessionInfo.getRuntimeSlashCommands?.(n,{maxWaitMs:this._runtimeSlashCommandCompletionWaitMs})??[],this._getKnownSkills(n)]),l=e.toLowerCase(),d=this._sessionInfo?.isRubberDuckEnabled?.()??!0,c=[],u=new Set;for(let p of s){if(!p.name||o&&p.kind!=="skill"||p.kind==="skill"&&a.has(p.name)||e1.has(p.name)||p.aliases?.some(S=>e1.has(S))||!d&&p.name==="rubber-duck"||e.length>0&&!p.name.toLowerCase().startsWith(l)&&!p.aliases?.some(S=>S.toLowerCase().startsWith(l)))continue;let m=[],h="";p.kind==="skill"?h=p.input?.hint?`  
(Prompt: ${p.input.hint})`:"":(m.push(...(p.input?.hint??"").replace(/[\[\]]/g,"").split("|")),m.length&&!p.input?.required&&m.unshift("")),Array.from(new Set([p.name].concat(p.aliases??[]))).filter(S=>!u.has(S)).forEach(S=>{Array.from(new Set(m.length?m:[""])).filter(b=>!CF.has(`${p.name}:${b}`)).forEach(b=>{let I=`/${S}${b?" "+b:""} `,R=`${(b?bF[`${p.name}:${b}`]:p.description)??p.description}${h}`;u.add(S),c.push({insertText:I,rangeStart:t,rangeEnd:r,attachment:{type:"simple",label:I,_meta:Gf({command:p.name,...R!==void 0?{description:R}:{}})}})})})}return c.sort((p,m)=>p.insertText.localeCompare(m.insertText))}};function IF(i){return i.uri.startsWith(xc+":")}function r1(i){if(!Array.isArray(i)||i.length!==2)return;let[n,e]=i;if(!(!Number.isInteger(n)||!Number.isInteger(e))&&!(n<0)&&!(e!==-1&&e<n))return{startLine:n,endLine:e}}function n1(i){let n=i?.agent_id;return typeof n=="string"&&n.length>0?n:void 0}var _F=[/^\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 rb(i){let n=typeof i=="string"?i:i?.input??i?.patch;if(typeof n!="string"||n.length===0)return[];let e=new Set,t=[];for(let r of n.split(`
`))for(let o of _F){let s=o.exec(r);if(s){let a=s[1];a&&!e.has(a)&&(e.add(a),t.push(a));break}}return t}var TF=new Set(["edit","str_replace","insert","create","apply_patch","git_apply_patch"]),wF=new Set(["edit","str_replace","insert","create"]);function pl(i,n){return TF.has(i)?!0:i==="str_replace_editor"?n!==void 0&&wF.has(n):!1}function Sm(i){if(typeof i=="string"){try{i=JSON.parse(i)}catch{return rb(i)}if(typeof i=="string")return rb(i)}if(!i||typeof i!="object")return[];let n=i;if(typeof n.input=="string"||typeof n.patch=="string")return rb(n);let e=i;return typeof e.path=="string"?[e.path]:[]}var Vc=new Set(["bash","powershell"]),ib=new Set(["write_bash","write_powershell"]),i1=new Set(["read_bash","read_powershell"]),RF=new Set(["task"]),xF=new Set(["grep","rg","glob"]),PF=new Set(["report_intent","skill"]);function bm(i){return PF.has(i)}function o1(i){return i==="list_agents"||i==="read_agent"||i==="write_agent"}function fl(i){return i==="task_complete"}function AF(i,n){if(n&&n.trim().length>0)return n;let e=i?.summary;return typeof e=="string"&&e.trim().length>0?e:void 0}function jc(i,n){let e=AF(i,n);if(e)return`

`+f(2296,null,e)}function Kc(i){return Vc.has(i)}function Cm(i,n){if(Kc(i)&&typeof n?.description=="string"&&n.description.length>0)return n.description}function sr(i,n){return i.length>n?i.substring(0,n-3)+"...":i}function kr(i){let n=v.file(i);return`[${es(pe(n))}](${n})`}function s1(i){return new Fg().appendLink(i,sr(i,80)).value}function _e(i){return{markdown:i}}function Dr(i){let n=or(i,void 0)?.displayName;if(n!==void 0)return n;switch(i){case"str_replace_editor":case"edit":case"str_replace":case"insert":return f(2303,null);case"create":return f(2301,null);case"view":return f(2317,null);case"bash":case"powershell":return f(2325,null);case"read_bash":case"read_powershell":return f(2319,null);case"write_bash":return f(2338,null);case"write_powershell":return f(2339,null);case"stop_bash":case"stop_powershell":case"bash_shutdown":case"powershell_shutdown":return f(2329,null);case"list_bash":case"list_powershell":return f(2310,null);case"grep":case"rg":case"glob":return f(2323,null);case"search_code_subagent":return f(2324,null);case"apply_patch":return f(2297,null);case"git_apply_patch":return f(2315,null);case"codeql_checker":return f(2299,null);case"code_review":return f(2300,null);case"reply_to_comment":return f(2320,null);case"think":return f(2333,null);case"report_intent":return f(2321,null);case"report_progress":return f(2322,null);case"web_search":return f(2336,null);case"web_fetch":return f(2306,null);case"update_todo":return f(2335,null);case"show_file":return f(2326,null);case"fetch_copilot_cli_documentation":return f(2305,null);case"propose_work":return f(2316,null);case"task_complete":return f(2332,null);case"ask_user":return f(2298,null);case"skill":return f(2308,null);case"task":return f(2331,null);case"list_agents":return f(2309,null);case"read_agent":return f(2318,null);case"exit_plan_mode":return f(2304,null);case"sql":return f(2328,null);case"lsp":return f(2311,null);case"create_pull_request":return f(2302,null);case"gh-advisory-database":return f(2307,null);case"store_memory":return f(2330,null);case"parallel_validation":return f(2314,null);case"write_agent":return f(2337,null);case"mcp_reload":return f(2312,null);case"mcp_validate":return f(2313,null);case"tool_search_tool_regex":return f(2334,null);default:return i}}function mi(i,n,e){let t=or(i,e)?.invocationMessage;if(t!==void 0)return t;if(Vc.has(i)){let r=e;if(r?.command){let o=r.command.split(`
`)[0];return _e(f(2282,null,it(sr(o,80))))}return f(2281,null,n)}if(ib.has(i)){let r=e;if(r?.command){let o=r.command.split(`
`)[0];return _e(f(2295,null,it(sr(o,80))))}return f(2294,null)}if(i1.has(i))return f(2280,null);switch(i){case"view":{let r=e;if(r?.path){let o=kr(r.path),s=r1(r.view_range);return s?s.endLine===-1?_e(f(2289,null,o,s.startLine)):s.endLine!==s.startLine?_e(f(2291,null,o,s.startLine,s.endLine)):_e(f(2290,null,o,s.startLine)):_e(f(2288,null,o))}return f(2287,null)}case"edit":{let r=e;return r?.path?_e(f(2271,null,kr(r.path))):f(2270,null)}case"create":{let r=e;return r?.path?_e(f(2269,null,kr(r.path))):f(2268,null)}case"grep":{let r=e;return r?.pattern?_e(f(2276,null,it(sr(r.pattern,80)))):f(2275,null)}case"rg":{let r=e;return r?.pattern?_e(f(2276,null,it(sr(r.pattern,80)))):f(2275,null)}case"glob":{let r=e;return r?.pattern?_e(f(2274,null,it(sr(r.pattern,80)))):f(2273,null)}case"apply_patch":case"git_apply_patch":{let r=Sm(e);return r.length===1?_e(f(2278,null,kr(r[0]))):r.length>1?_e(f(2279,null,r.map(kr).join(", "))):f(2277,null)}case"sql":return e?.description||f(2285,null);case"web_fetch":{let r=e;return r?.url?_e(f(2292,null,s1(r.url))):f(2293,null)}case"exit_plan_mode":return f(2272,null);case"task":return f(2286,null);case"list_agents":case"read_agent":case"write_agent":return Gc(i,n,e,!0);default:return n}}function Gc(i,n,e,t,r){if(!t)return f(2239,null,n);let o=or(i,e,{text:r,success:t})?.pastTenseMessage;if(o!==void 0)return o;if(Vc.has(i)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return _e(f(2252,null,it(sr(a,80))))}return f(2251,null,n)}if(ib.has(i)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return _e(f(2267,null,it(sr(a,80))))}return f(2266,null)}if(i1.has(i))return f(2250,null);switch(i){case"view":{let s=e;if(s?.path){let a=kr(s.path),l=r1(s.view_range);return l?l.endLine===-1?_e(f(2259,null,a,l.startLine)):l.endLine!==l.startLine?_e(f(2261,null,a,l.startLine,l.endLine)):_e(f(2260,null,a,l.startLine)):_e(f(2258,null,a))}return f(2257,null)}case"edit":{let s=e;return s?.path?_e(f(2237,null,kr(s.path))):f(2236,null)}case"create":{let s=e;return s?.path?_e(f(2235,null,kr(s.path))):f(2234,null)}case"grep":{let s=e;return s?.pattern?_e(f(2243,null,it(sr(s.pattern,80)))):f(2242,null)}case"rg":{let s=e;return s?.pattern?_e(f(2243,null,it(sr(s.pattern,80)))):f(2242,null)}case"glob":{let s=e;return s?.pattern?_e(f(2241,null,it(sr(s.pattern,80)))):f(2240,null)}case"apply_patch":case"git_apply_patch":{let s=Sm(e);return s.length===1?_e(f(2246,null,kr(s[0]))):s.length>1?_e(f(2247,null,s.map(kr).join(", "))):f(2245,null)}case"sql":return e?.description||f(2255,null);case"web_fetch":{let s=e;return s?.url?_e(f(2262,null,s1(s.url))):f(2263,null)}case"exit_plan_mode":return f(2238,null);case"task":return f(2256,null);case"list_agents":return f(2244,null);case"read_agent":{let s=n1(e);return s?_e(f(2248,null,it(s))):f(2249,null)}case"write_agent":{let s=n1(e);return s?_e(f(2264,null,it(s))):f(2265,null)}default:return n}}function EF(i,n){if(i)return`synth-skill-${i}`;let e=n.path??n.name;return`synth-skill-${br(e).toString(16)}`}function Im(i,n){let e=EF(n,i),t=f(2327,null),r=es(i.name),o=i.path?`[${r}](${v.file(i.path)})`:void 0,s=o?_e(f(2283,null,o)):f(2284,null,i.name),a=o?_e(f(2253,null,o)):f(2254,null,i.name);return{toolCallId:e,toolName:"skill",displayName:t,invocationMessage:s,pastTenseMessage:a}}function Jc(i,n,e){if(!(!n&&!e)){if(Vc.has(i)||ib.has(i)){let t=n,r=t?.command??t?.args;return typeof r=="string"?r:typeof r=="object"&&r!==null&&me(r,{command:!0})?r.command:e}switch(i){case"grep":return n?.pattern??e;case"rg":return n?.pattern??e;case"web_fetch":return n?.url??e;default:if(n)try{return JSON.stringify(n,null,2)}catch{return e}return e}}}function _m(i){if(Vc.has(i))return"terminal";if(RF.has(i))return"subagent";if(xF.has(i))return"search"}function Tm(i){if(!i)return{};let n=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:n,description:e}}function wm(i){switch(i){case"powershell":case"write_powershell":case"read_powershell":return"powershell";default:return"shellscript"}}function uo(i){try{return JSON.stringify(i)}catch{return}}function co(i){return typeof i=="string"?i:void 0}function a1(i,n){let e=co(i.path)??co(i.fileName),t=co(i.fullCommandText),r=co(i.intention),o=co(i.serverName),s=co(i.toolName),a=i.requestSandboxBypass?f(2229,null):f(2230,null);switch(i.kind){case"shell":{let l=t?{command:t}:void 0;os("bash",l,n);let d=typeof l?.command=="string"?l.command:t;return{confirmationTitle:a,invocationMessage:r??mi("bash",Dr("bash"),d?{command:d}:void 0),toolInput:d,permissionKind:"shell",permissionPath:e}}case"custom-tool":{let l=typeof i.args=="object"&&i.args!==null?i.args:void 0,d=co(i.toolName);if(l&&d&&Kc(d)&&typeof l.command=="string"){os(d,l,n);let c=l.command;return{confirmationTitle:a,invocationMessage:mi(d,Dr(d),{command:c}),toolInput:c,permissionKind:"shell",permissionPath:e}}return{confirmationTitle:f(2225,null),invocationMessage:_e(f(2224,null,it(s??i.kind))),toolInput:uo(l||i),permissionKind:i.kind,permissionPath:e}}case"write":return{confirmationTitle:f(2233,null),invocationMessage:mi("edit",Dr("edit"),e?{path:e}:void 0),toolInput:uo(e?{path:e}:i)??void 0,permissionKind:"write",permissionPath:e};case"mcp":{let l=s??f(2226,null);return{confirmationTitle:o?f(2227,null,o):f(2225,null),invocationMessage:o?`${o}: ${l}`:l,toolInput:uo({serverName:o,toolName:s})??void 0,permissionKind:"mcp",permissionPath:e}}case"read":return{confirmationTitle:f(2228,null),invocationMessage:mi("view",Dr("view"),e?{path:e}:void 0),permissionKind:"read",permissionPath:e};case"url":{let l=co(i.url),d=l?URL.canParse(l)?new URL(l).href:l:void 0;return{confirmationTitle:f(2232,null),invocationMessage:_e(f(2231,null)),toolInput:d?JSON.stringify({url:d}):void 0,permissionKind:"url"}}default:return{confirmationTitle:f(2225,null),invocationMessage:_e(f(2224,null,it(s??i.kind))),toolInput:uo(i)??void 0,permissionKind:i.kind,permissionPath:e}}}function l1(i){try{return JSON.stringify(i)}catch{return}}function kF(i){if(i.type!=="user.message")return!1;let n=i.data.source;return!!n&&n.toLowerCase()!=="user"}function ob(i,n){for(let e of n??[])e.type==="shell_exit"&&i.push({type:"shell_exit",shellId:e.shellId,exitCode:e.exitCode,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.outputPreview!==void 0?{outputPreview:e.outputPreview}:{},...e.outputTruncated!==void 0?{outputTruncated:e.outputTruncated}:{}})}function Yc(i,n,e){let t={text:n,origin:{kind:e?.origin??"user"},...e?.attachments?.length?{attachments:e.attachments}:{},...e?.model?{model:e.model}:{},...e?.agent?{agent:e.agent}:{}};return{id:i,message:t,responseParts:[],pendingTools:new Map}}function d1(i,n,e,t){if(bm(i))return;let r=n!==void 0?l1(n):void 0,o;if(r)try{o=JSON.parse(r)}catch{}let a=(os(i,o,t)?l1(o):void 0)??r,l=_m(i),d=l==="subagent"?Tm(o):void 0,c=Dr(i);return{toolName:i,displayName:c,invocationMessage:mi(i,c,o),toolInput:Jc(i,o,a),toolKind:l,language:l==="terminal"?wm(i):void 0,intention:Cm(i,o),subagentAgentName:d?.agentName,subagentDescription:d?.description,parameters:o,parentToolCallId:e}}function c1(i,n){return{id:i.id,message:i.message,responseParts:i.responseParts,usage:void 0,state:n}}async function p1(i,n,e,t=void 0){let r=t instanceof v?t:t?.workingDirectory,o=t instanceof v?void 0:t?.model,s=t instanceof v?void 0:t?.agent,a=new Map,l=[],d=new Map,c=new Map,u=(N,V)=>(N?c.get(N):void 0)??V;for(let N of e)if(N.type==="subagent.started"&&N.agentId&&c.set(N.agentId,N.data.toolCallId),N.type==="tool.execution_complete"&&d.set(N.data.toolCallId,N.data),N.type==="tool.execution_start"){let V=N.data,de=u(N.agentId,V.parentToolCallId),F=d1(V.toolName,V.arguments,de,r);if(!F)continue;a.set(V.toolCallId,F);let O=Ve(F.parameters?.command)?F.parameters.command:void 0;pl(V.toolName,O)&&l.push(V.toolCallId)}let p;if(n&&l.length>0)try{let N=await n.getFileEdits(l);if(N.length>0){p=new Map;for(let V of N){let de=p.get(V.toolCallId);de||(de=[],p.set(V.toolCallId,de)),de.push(V)}}}catch{}let m=i.toString(),h=[],y=new Map,S=new Map,b=new Map,I=new Map,_,R="cancelled",A=!1,X=!1,E=()=>{_&&(h.push(c1(_,R)),_=void 0,R="cancelled",A=!1)},z=N=>{let V=y.get(N);if(!V){S.delete(N);return}y.delete(N);let de=S.get(N)??"complete";if(S.delete(N),V.responseParts.length===0)return;let F=b.get(N)??[];F.push(c1(V,de)),b.set(N,F)},x=N=>{let V=y.get(N);return V||(V=Yc(H(),""),y.set(N,V),S.has(N)||S.set(N,"complete")),V},B=N=>N?x(N):_;for(let N of e)switch(N.type){case"assistant.turn_start":N.agentId||(X=!0);break;case"assistant.turn_end":N.agentId||(X=!1);break;case"session.model_change":{o={id:N.data.newModel};break}case"subagent.deselected":{N.agentId||(s=void 0);break}case"user.message":{if(kF(N))continue;let V=N.data,de=V.interactionId??"",F=V.content??"",O=DF(V.attachments),W=u(N.agentId,void 0);if(W){let q=x(W);F&&q.responseParts.push({kind:"markdown",id:H(),content:F}),O?.length&&(q.message={...q.message,attachments:O})}else{E();let q=N.id??de;_=Yc(q,F,{attachments:O,model:o,agent:s})}break}case"assistant.message":{let V=N.data,de=V.messageId??V.interactionId??"",F=V.content??"",O=V.reasoningText,W=!!V.toolRequests&&V.toolRequests.length>0,q=u(N.agentId,V.parentToolCallId);if(!F&&!O&&!W){!q&&_&&!A&&(R="complete");break}let J=N.id??de,Z=B(q)??(_=Yc(J,""));O&&Z.responseParts.push({kind:"reasoning",id:H(),content:O}),F&&Z.responseParts.push({kind:"markdown",id:H(),content:F}),!q&&Z===_&&!A&&(R=W?"cancelled":"complete"),V.toolRequests?.length&&K(Z,V.toolRequests,q);break}case"system.notification":{let V=ym(N);if(!V)break;X&&_?_.responseParts.push({kind:"systemNotification",content:V.messageText}):V.startsTurn&&(E(),_=Yc(N.id,V.messageText,{origin:"systemNotification"}));break}case"subagent.started":{let V=N.data;I.set(V.toolCallId,{agentName:V.agentName,agentDisplayName:V.agentDisplayName,agentDescription:V.agentDescription});break}case"tool.execution_start":{!u(N.agentId,N.data.parentToolCallId)&&_&&(R="cancelled");break}case"tool.execution_complete":{let V=N.data,de=a.get(V.toolCallId);if(!de)continue;a.delete(V.toolCallId);let F=u(N.agentId,V.parentToolCallId);if(fl(de.toolName)){let q=B(F);if(!q)continue;let J=jc(de.parameters,V.error?.message??V.result?.content);J&&q.responseParts.push({kind:"markdown",id:H(),content:J}),!F&&V.success&&q===_&&!A&&(R="complete");continue}let O=B(F);if(!O)continue;let W=u1(V,de,m,p,I.get(V.toolCallId));O.responseParts.push(W),!F&&I.has(V.toolCallId)&&z(V.toolCallId);break}case"skill.invoked":{let V=Im(N.data,N.id),de=u(N.agentId,void 0),F=B(de)??(_=Yc(H(),""));!de&&F===_&&(R="cancelled"),F.responseParts.push({kind:"toolCall",toolCall:{status:"completed",toolCallId:V.toolCallId,toolName:V.toolName,displayName:V.displayName,invocationMessage:V.invocationMessage,success:!0,pastTenseMessage:V.pastTenseMessage,confirmed:"not-needed"}});break}case"abort":{let V=u(N.agentId,void 0);V?S.set(V,"cancelled"):(X=!1,_&&(R="cancelled",A=!0));break}default:break}E();for(let N of[...y.keys()])z(N);return{turns:h,subagentTurnsByToolCallId:b};function K(N,V,de){for(let F of V){let O=d.get(F.toolCallId);if(O&&a.has(F.toolCallId))continue;let W=a.get(F.toolCallId)??d1(F.name,F.arguments,de,r);if(W){if(fl(W.toolName)){let q=jc(W.parameters,O?.error?.message??O?.result?.content);q&&N.responseParts.push({kind:"markdown",id:H(),content:q}),!de&&O?.success&&N===_&&!A&&(R="complete");continue}N.responseParts.push(u1(O??{toolCallId:F.toolCallId,success:!0},W,m,p,I.get(F.toolCallId)))}}}}function DF(i){if(!i?.length)return;let n=[];for(let e of i){let t=MF(e);t&&n.push(t)}return n.length>0?n:void 0}function MF(i){switch(i.type){case"file":return{type:"resource",uri:v.file(i.path).toString(),label:i.displayName||Te(i.path),displayKind:yp(i.path)?.startsWith("image/")?"image":"document"};case"directory":return{type:"resource",uri:v.file(i.path).toString(),label:i.displayName||Te(i.path),displayKind:"directory"};case"selection":return{type:"resource",uri:v.file(i.filePath).toString(),label:i.displayName,displayKind:"selection",selection:{range:i.selection}};case"blob":{if(typeof i.data!="string")return;if(i.mimeType.startsWith("text/plain"))return{type:"simple",label:i.displayName??"attachment",modelRepresentation:un(i.data??"").toString()};let n=i.mimeType.startsWith("image/")?"image":void 0;return{type:"embeddedResource",label:i.displayName??"attachment",data:i.data??"",contentType:i.mimeType,displayKind:n}}default:return}}function u1(i,n,e,t,r){let o=i.error?.message??i.result?.content,s=[];o!==void 0&&s.push({type:"text",text:o}),ob(s,i.result?.contents);let a=t?.get(i.toolCallId);if(a)for(let d of a){let c=d.kind==="rename"&&d.originalPath?v.file(d.originalPath).toString():v.file(d.filePath).toString(),u=v.file(d.filePath).toString(),p=d.kind!=="create",m=d.kind!=="delete";s.push({type:"fileEdit",before:p?{uri:c,content:{uri:Vi(e,d.toolCallId,d.filePath,"before")}}:void 0,after:m?{uri:u,content:{uri:Vi(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:qs(e,i.toolCallId),title:r.agentDisplayName,agentName:r.agentName,description:r.agentDescription});let l={status:"completed",toolCallId:i.toolCallId,toolName:n.toolName,displayName:n.displayName,intention:n.intention,invocationMessage:n.invocationMessage,toolInput:n.toolInput,success:i.success,pastTenseMessage:Gc(n.toolName,n.displayName,n.parameters,i.success,i.success?o:void 0),content:s.length>0?s:void 0,error:i.error,confirmed:"not-needed",_meta:Qt({toolKind:n.toolKind,language:n.language,subagentDescription:n.subagentDescription,subagentAgentName:n.subagentAgentName})};return{kind:"toolCall",toolCall:l}}var f1="pending-edit-content";function g1(i,n,e){return v.from({scheme:f1,authority:Li(U.fromString(i)).toString(),path:`/${encodeURIComponent(n)}/${Li(U.fromString(e))}`})}function m1(i){let n=new Fa,e=i.registerProvider(f1,n);return{dispose(){e.dispose(),n.dispose()}}}var OF=".copilot",h1=j(OF,"session-state"),LF="<empty />";function NF(i){if(!i?.length)return LF;let n=i.some(t=>t.type==="image"),e=i.some(t=>t.type==="resource");return n&&e?"Tool produced the attached image and file":n?"Tool produced the attached image":"Tool produced the attached file"}function UF(i){switch(i){case"autopilot":return{label:f(2193,null),description:f(2192,null)};case"autopilot_fleet":return{label:f(2195,null),description:f(2194,null)};case"interactive":return{label:f(2200,null),description:f(2199,null)};case"exit_only":return{label:f(2197,null),description:f(2196,null)};default:return}}function y1(i){let n=Qe(i.toolArgs)?Reflect.get(i.toolArgs,"command"):void 0;return Ve(n)?n:void 0}function FF(i){switch(i){case"interactive":case"plan":case"autopilot":return i;default:return}}function HF(i,n,e){let t={id:i,title:n.title??i,message:n.description??n.title??i,required:e};switch(n.type){case"boolean":return{...t,kind:"boolean",defaultValue:n.default};case"integer":case"number":return{...t,kind:n.type==="integer"?"integer":"number",min:n.minimum,max:n.maximum,defaultValue:n.default};case"array":{let r=me(n.items,{enum:!0})?n.items.enum.map(o=>({id:o,label:o})):n.items.anyOf.map(o=>({id:o.const,label:o.title}));return{...t,kind:"multi-select",options:r,min:n.minItems,max:n.maxItems}}case"string":{if(me(n,{enum:!0})){let r=n.enumNames,o=n.enum.map((s,a)=>({id:s,label:r?.[a]??s}));return{...t,kind:"single-select",options:o}}if(me(n,{oneOf:!0})){let r=n.oneOf.map(o=>({id:o.const,label:o.title}));return{...t,kind:"single-select",options:r}}return{...t,kind:"text",format:n.format,min:n.minLength,max:n.maxLength,defaultValue:n.default}}}}function $F(i,n){if(!n||n.state==="skipped")return;let e=n.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 t=Number(e.value);return Number.isFinite(t)?i.type==="integer"?Math.trunc(t):t: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 WF(i){let n=process.env.XDG_STATE_HOME;return n?j(n,h1):j(i,h1)}var qF=/^(?:\d{10,}-copilot-tool-output-[a-z0-9]{6}|copilot-tool-output-\d{10,}-[a-z0-9]{6})\.txt$/i;function BF(i,n){let e=_n(v.file(i)),t=_n(v.file(n)),r=_n(v.joinPath(e,".."));if(!rt.isEqual(r,t))return!1;let o=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\")),s=o>=0?i.substring(o+1):i;return qF.test(s)}var sb=class{constructor(n,e){this.id=n;this.senderClientId=e;this._state="pending";this.copilotUsageTotalNanoAiuByScope=new Map;this.markdownPartIds=new Map;this.reasoningPartIds=new Map}get state(){return this._state}get isPending(){return this._state==="pending"}get isRunning(){return this._state==="running"}markRunning(){this._state==="pending"&&(this._state="running")}markCompleted(){this._state="completed"}markAborted(){this._state="aborted"}},gl=class extends T{constructor(e,t,r,o,s,a,l,d){super();this._instantiationService=t;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._steeringMessagesInFlight=new Set;this._pendingSteeringFlips=new Map;this._pendingClientToolCalls=new xt;this._pendingMcpAuthRequests=new Map;this._pendingEditContentUris=new Map;this._onMcpNotification=this._register(new P);this.onMcpNotification=this._onMcpNotification.event;this._pendingMcpSamplings=new Set;this._hasActivity=!1;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._chatChannelUri=e.chatChannelUri,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._platform=e.platform??process.platform,this._telemetryReporter=new ga(this._telemetryService),this._appliedSnapshot=e.clientSnapshot??{tools:[],plugins:[],mcpServers:{}},this._clientToolNames=nb(this._appliedSnapshot),this._activeClientToolSet=e.activeClientToolSet??new Pn,this._databaseRef=o.openDatabase(e.sessionUri),this._register(M(()=>this._databaseRef.dispose())),this._sessionDataDir=o.getSessionDataDir(e.sessionUri),this._editTracker=this._instantiationService.createInstance(zi,e.sessionUri.toString(),this._databaseRef.object),this._mcpCustomizations=this._register(new Wa({providerId:this.sessionUri.scheme,sessionId:this.sessionId,resolveChildId:e.resolveMcpChildId,emit:c=>this._emitAction(c)})),this._register(M(()=>this._denyPendingPermissions())),this._register(M(()=>this._shellManager?.dispose())),this._register(M(()=>this._cancelPendingUserInputs())),this._register(M(()=>this._cancelPendingElicitations())),this._register(M(()=>this._cancelPendingPlanReviews())),this._register(M(()=>this._drainPendingSteeringFlips())),this._register(M(()=>this._cancelPendingMcpSamplings())),this._register(M(()=>this._cancelPendingMcpAuthRequests())),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:"chat/toolCallContentChanged",turnId:this._turnId,toolCallId:c,content:m.content}))})),this._register(M(()=>this._cancelPendingClientToolCalls()))}get workingDirectory(){return this._workingDirectory}get _turnId(){return this._currentTurn?.id??""}get mcpServerStates(){return this._mcpCustomizations.runtimeStates}_emitAction(e,t){this._onDidSessionProgress.fire({kind:"action",resource:rr(e)?this._chatChannelUri:this.sessionUri,action:e,parentToolCallId:t})}_beginSteeringTurn(e){let t=this._turnId;t&&this._emitAction({type:"chat/turnComplete",turnId:t});let r=H();return this._emitAction({type:"chat/turnStarted",turnId:r,message:e.message,queuedMessageId:e.id}),this.resetTurnState(r),this._currentTurn?.markRunning(),r}_drainPendingSteeringFlips(){if(this._pendingSteeringFlips.size===0)return;let e=[...this._pendingSteeringFlips.keys()];this._pendingSteeringFlips.clear();for(let t of e)this._onDidSessionProgress.fire({kind:"steering_consumed",chat:this._chatChannelUri,id:t})}_takeMatchingPendingSteering(e){if(this._pendingSteeringFlips.size!==0){for(let[t,r]of this._pendingSteeringFlips)if(r.message.text===e)return this._pendingSteeringFlips.delete(t),r}}_parentToolCallIdForSubagentEvent(e){return e.agentId?this._parentToolCallIdsByAgentId.get(e.agentId):void 0}_shouldDropUnmappedSubagentEvent(e,t){return!this._parentToolCallIdForSubagentEvent(e)&&e.agentId?(this._logService.warn(`[Copilot:${this.sessionId}] Dropping ${t} for unknown subagent agentId=${e.agentId}`),!0):!1}resetTurnState(e,t){this._currentTurn=new sb(e,t)}_completeActiveTurn(){let e=this._currentTurn;e&&(e.markCompleted(),this._emitAction({type:"chat/turnComplete",turnId:e.id}),this._currentTurn=void 0)}_getEditFilePaths(e){return Sm(e).map(t=>this._resolveEditFilePath(t))}_resolveEditFilePath(e){return Ft(e)||!this._workingDirectory||this._workingDirectory.scheme!==ie.file?e:j(this._workingDirectory.fsPath,e)}emitInitialMarkdown(e){this._emitMarkdownDelta(e)}_emitMarkdownDelta(e,t){let r=this._currentTurn;if(!r){this._logService.error(`[Copilot:${this.sessionId}] Markdown delta emitted with no active turn; dropping`);return}let o=t??"",s=r.markdownPartIds.get(o);if(!s){s=H(),r.markdownPartIds.set(o,s),this._emitAction({type:"chat/responsePart",turnId:r.id,part:{kind:"markdown",id:s,content:e}},t);return}this._emitAction({type:"chat/delta",turnId:r.id,partId:s,content:e},t)}_emitReasoningDelta(e,t){let r=this._currentTurn;if(!r){this._logService.error(`[Copilot:${this.sessionId}] Reasoning delta emitted with no active turn; dropping`);return}let o=t??"",s=r.reasoningPartIds.get(o);if(!s){s=H(),r.reasoningPartIds.set(o,s),this._emitAction({type:"chat/responsePart",turnId:r.id,part:{kind:"reasoning",id:s,content:e}},t);return}this._emitAction({type:"chat/reasoning",turnId:r.id,partId:s,content:e},t)}get appliedSnapshot(){return this._appliedSnapshot}get customizationDirectory(){return this._customizationDirectory}_createClientSdkTools(){let e=this._appliedSnapshot.tools;return e.length===0?[]:e.map(t=>({name:t.name,description:t.description??"",parameters:t.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=${t.name}, toolCallId=${o}`),s}}}))}_createServerSdkTools(){let e=this._serverToolHost;return e?e.definitions.map(t=>({name:t.name,description:t.description??"",parameters:t.inputSchema??{type:"object",properties:{}},handler:async r=>{try{return{textResultForLlm:e.executeTool(this._chatChannelUri.toString(),t.name,r),resultType:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return this._logService.error(o,`[Copilot:${this.sessionId}] Failed in server tool handler: tool=${t.name}`),{textResultForLlm:s,resultType:"failure",error:s}}}})):[]}handleClientToolCallComplete(e,t){let r=t.content?.filter(a=>a.type==="text").map(a=>a.text).join(`
`)??"",o=t.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:NF(o);t.success?this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:s,resultType:"success",binaryResultsForLlm:o?.length?o:void 0}):this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:r.trim()?r:t.error?.message||"Tool call failed",resultType:"failure",error:t.error?.message,binaryResultsForLlm:o?.length?o:void 0}),this.respondToPermissionRequest(e,!0)}async initializeSession(){let e=await this._sessionLauncher.launch(this._launchPlan,this._createRuntimeAdapter());if(this._store.isDisposed)throw e.dispose(),new Y;this._wrapper=this._register(e),this._subscribeToEvents(),this._subscribeForLogging(),this._subscribeForMemoInvalidation(),this._serverToolHost?.advertise(this.sessionUri.toString())}_createRuntimeAdapter(){return{handlePermissionRequest:e=>this._handlePermissionRequest(e),handleExitPlanModeRequest:(e,t)=>this._handleExitPlanModeRequest(e,t),handleUserInputRequest:(e,t)=>this._handleUserInputRequest(e,t),handleElicitationRequest:e=>this._handleElicitationRequest(e),handleMcpAuthRequest:e=>this._handleMcpAuthRequest(e),requestUnsandboxedCommandConfirmation:e=>this._requestUnsandboxedCommandConfirmation(e),createClientSdkTools:()=>this._createClientSdkTools(),createServerSdkTools:()=>this._createServerSdkTools(),handlePreToolUse:e=>this._handlePreToolUse(e),handlePostToolUse:e=>this._handlePostToolUse(e)}}async resolveMcpAuthentication(e){let t=!1;for(let[r,o]of this._pendingMcpAuthRequests)o.resource.resource!==e.resource||!this._scopesSatisfy(e.scopes,o.requiredScopes)||(this._pendingMcpAuthRequests.delete(r),o.deferred.complete({kind:"token",accessToken:e.token}),t=!0);return t}async _handleMcpAuthRequest(e){let t=this._protectedResourceFromMcpAuthRequest(e),r=this._requiredScopesFromMcpAuthRequest(e,t),o=new Ee;return this._pendingMcpAuthRequests.set(e.requestId,{serverName:e.serverName,resource:t,requiredScopes:r,deferred:o}),this._mcpCustomizations.applyOne({name:e.serverName,state:{kind:"authRequired",reason:this._mcpAuthRequiredReason(e.reason),resource:t,requiredScopes:r.length?[...r]:void 0,description:e.wwwAuthenticateParams?.error}}),this._logService.info(`[Copilot:${this.sessionId}] MCP server '${e.serverName}' requires authentication for ${t.resource}`),o.p.finally(()=>this._pendingMcpAuthRequests.delete(e.requestId))}_protectedResourceFromMcpAuthRequest(e){if(e.resourceMetadata)try{let r=JSON.parse(e.resourceMetadata);if(pP(r))return r;this._logService.warn(`[Copilot:${this.sessionId}] Ignoring invalid MCP protected-resource metadata for '${e.serverName}'`)}catch(r){this._logService.warn(`[Copilot:${this.sessionId}] Failed to parse MCP protected-resource metadata for '${e.serverName}'`,r)}let t=this._scopesFromChallenge(e.wwwAuthenticateParams?.scope);return{resource:e.serverUrl,resource_name:e.serverName,scopes_supported:t.length?t.slice():void 0}}_requiredScopesFromMcpAuthRequest(e,t){let r=this._scopesFromChallenge(e.wwwAuthenticateParams?.scope);return r.length?r:t.scopes_supported??[]}_scopesFromChallenge(e){return e?.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0)??[]}_mcpAuthRequiredReason(e){switch(e){case"refresh":case"reauth":return"expired";case"upscope":return"insufficientScope";default:return"required"}}_scopesSatisfy(e,t){if(t.length===0||e===void 0)return!0;let r=new Set(e);return t.every(o=>r.has(o))}_cancelPendingMcpAuthRequests(){for(let e of this._pendingMcpAuthRequests.values())e.deferred.complete({kind:"cancelled"});this._pendingMcpAuthRequests.clear()}async send(e,t,r,o,s){r&&this._currentTurn?.id!==r&&this.resetTurnState(r,s),this._logService.info(`[Copilot:${this.sessionId}] sendMessage called: "${e.substring(0,100)}${e.length>100?"...":""}" (${t?.length??0} attachments)`);let a=t1(e);if(a?.command==="compact"){try{let c=(await this._wrapper.session.rpc.history.compact()).contextWindow?.currentTokens;typeof c=="number"&&this._emitAction({type:"chat/usage",turnId:this._turnId,usage:{inputTokens:c,outputTokens:0,model:this._lastSeenModelId}}),this.emitInitialMarkdown(f(2208,null))}catch(d){if(Ur(d).toLowerCase().includes("nothing to compact")){this.emitInitialMarkdown(f(2208,null)),this._completeActiveTurn();return}throw this._logService.error(d,`[Copilot:${this.sessionId}] rpc.history.compact failed`),d}this._completeActiveTurn();return}if(a?.command==="plan")o="plan",e=a.rest;else if(a?.command==="rubber-duck")if(this._configurationService.getRootValue(qt,"rubberDuck")!==!0)e=a.rest;else{let d=a.rest;e=d?`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: ${d}`:'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.'}else if(a){let d=await this._resolveRuntimeSlashCommand(a.command);if(d&&d.kind!=="skill"){let c;try{c=await this._wrapper.session.rpc.commands.invoke({name:d.name,...a.rawRest.length>0?{input:a.rawRest}:{}})}catch(u){throw this._logService.error(u,`[Copilot:${this.sessionId}] rpc.commands.invoke(${a.command}) failed`),u}switch(c.kind){case"text":this._emitMarkdownDelta(c.markdown===!0?c.text:FS(c.text));break;case"completed":c.message&&this._emitMarkdownDelta(c.message);break;case"agent-prompt":{let u=FF(c.mode);u&&(o=u),e=c.prompt;break}case"select-subcommand":this._emitMarkdownDelta(f(2209,null,c.command,c.options.map(u=>u.name).join(", ")));break;default:this._logService.warn(`[Copilot:${this.sessionId}] Unhandled slash command result kind: ${c.kind}`);break}if(c.runtimeSettingsChanged===!0&&this._invalidateRuntimeSlashCommandCache(),c.kind!=="agent-prompt"){this._completeActiveTurn();return}}}let l=t?.length?(await Promise.all(t.map(d=>this._toSdkAttachment(d)))).filter(Gn):void 0;l?.length&&this._logService.trace(`[Copilot:${this.sessionId}] Attachments: ${JSON.stringify(l.map(d=>({type:d.type})))}`),await this.applyMode(o),await this._applyEffectiveSandboxConfig(),await this._wrapper.session.send({prompt:e,attachments:l?.length?l:void 0}),this._logService.info(`[Copilot:${this.sessionId}] session.send() returned`)}async hasRuntimeSlashCommand(e){try{return!!await this._resolveRuntimeSlashCommand(e)}catch(t){return this._logService.warn(`[Copilot:${this.sessionId}] rpc.commands.list failed`,t),!1}}async getRuntimeSlashCommands(e){try{let t=e?.maxWaitMs;return(await this._getRuntimeSlashCommandCatalog(t===void 0?void 0:Math.max(0,t))).commands}catch(t){return this._logService.warn(`[Copilot:${this.sessionId}] rpc.commands.list failed`,t),[]}}async _resolveRuntimeSlashCommand(e,t=void 0){let r=this._normalizeSlashCommandKey(e);if(!r)return;let o=await this._getRuntimeSlashCommandCatalog(t);return o.byName.get(r)??o.byAlias.get(r)}async _getRuntimeSlashCommandCatalog(e=void 0){let t=this._runtimeSlashCommandCache??={};if(t.value)return t.value;let r=this._refreshRuntimeSlashCommandCatalog(t);if(e===void 0)return r;let o=await YI(r,e);return o||(t.value?t.value:{commands:[],byName:new Map,byAlias:new Map})}_refreshRuntimeSlashCommandCatalog(e){if(e.inFlight)return e.inFlight;let t=this._wrapper.session.rpc.commands.list({includeBuiltins:!0,includeSkills:!0,includeClientCommands:!0}).then(r=>this._toRuntimeSlashCommandCatalog(r.commands));return e.inFlight=t,t.then(r=>{this._runtimeSlashCommandCache===e&&(e.value=r,e.inFlight=void 0)},()=>{this._runtimeSlashCommandCache===e&&(e.inFlight=void 0,e.value||(this._runtimeSlashCommandCache=void 0))}),t}_toRuntimeSlashCommandCatalog(e){let t=new Map,r=new Map,o=[];for(let s of e){let a=this._normalizeSlashCommandKey(s.name);if(!a)continue;let l=t.get(a);l||(l=s,t.set(a,l),o.push(l));for(let d of s.aliases??[]){let c=this._normalizeSlashCommandKey(d);!c||r.has(c)||r.set(c,l)}}return{commands:o,byName:t,byAlias:r}}_normalizeSlashCommandKey(e){let t=e.trim();return t?(t.charCodeAt(0)===47?t.slice(1):t).toLowerCase():void 0}_invalidateRuntimeSlashCommandCache(){this._runtimeSlashCommandCache&&(this._runtimeSlashCommandCache=void 0)}async _toSdkAttachment(e){if(rm(e)){let a=im(e);return a?{type:"blob",data:Zn(U.fromString(a)),mimeType:"text/plain",displayName:e.label}:void 0}if(e.type==="simple")return e.modelRepresentation?{type:"blob",data:Zn(U.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 t=v.parse(e.uri),r=t.scheme==="file"?t.fsPath:t.toString(),o=e.label??r;if(e.selection)try{let a=await this._readSelectedText(t,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 ${t.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,t){let o=(await this._fileService.readFile(e)).value.toString(),s=TI(o),a=this._getOffsetAt(s,t.start),l=this._getOffsetAt(s,t.end);return o.substring(a,Math.max(a,l))}_getOffsetAt(e,t){let r=Math.max(0,Math.min(t.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(t.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(t){this._logService.error(t,`[Copilot:${this.sessionId}] rpc.mode.set failed: mode=${e}`)}}_isAutopilotMode(){return this._configurationService.getEffectiveValue(this.sessionUri.toString(),Jt,"mode")==="autopilot"}_isAutoReplyEnabled(){return this._configurationService.getRootValue($t,My)===!0}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(t){this._logService.error(`[Copilot:${this.sessionId}] Steering message failed`,t)}finally{this._steeringMessagesInFlight.delete(e.id)}}}async getMessages(){return(await this._getMappedEvents()).turns}async getSubagentMessages(e){return(await this._getMappedEvents()).subagentTurnsByToolCallId.get(e)??[]}async getSubagentSessions(){let e=await this._getMappedEvents();if(e.subagentTurnsByToolCallId.size===0)return[];let t=this.sessionUri.toString(),r=[];for(let o of e.turns)for(let s of o.responseParts){if(s.kind!=="toolCall")continue;let a=s.toolCall,l=e.subagentTurnsByToolCallId.get(a.toolCallId);if(!l||l.length===0)continue;let d=a.content,c=d?N_({content:d}):void 0,u=ec(a).subagentDescription;r.push({resource:v.parse(qs(t,a.toolCallId)),toolCallId:a.toolCallId,title:Ry(u,c?.title),turns:l})}return r}_getMappedEvents(){if(!this._mappedEventsMemo){let e=this._computeMappedEvents();this._mappedEventsMemo=e,e.catch(()=>{this._mappedEventsMemo===e&&(this._mappedEventsMemo=void 0)})}return this._mappedEventsMemo}async _computeMappedEvents(){let e=await this._wrapper.session.getEvents(),t;try{t=this._databaseRef.object}catch{}return await p1(this.sessionUri,t,e,{workingDirectory:this._workingDirectory,model:this._launchPlan.kind==="create"?this._launchPlan.model:this._launchPlan.fallback.model})}_invalidateMappedEvents(){this._mappedEventsMemo=void 0}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,t,r){this._logService.info(`[Copilot:${this.sessionId}] Changing model to: ${e}`),this._lastSeenModelId=e,await this._wrapper.session.setModel(e,{reasoningEffort:t,contextTier:r})}async handleMcpRequest(e,t,r){let o=this._wrapper.session.rpc.mcp.apps;switch(t){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=Qe(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: ${t}`)}}async _handleSamplingCreateMessage(e,t){if(!t)throw new Error("sampling/createMessage missing params");let r=H(),o=H();this._pendingMcpSamplings.add(r);try{let s=await this._wrapper.session.rpc.mcp.executeSampling({requestId:r,serverName:e,mcpRequestId:o,request:t});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 t=e;this._logService.info(`[Copilot:${this.sessionId}] Selecting custom agent: ${t}`);try{await this._wrapper.session.rpc.agent.select({name:t})}catch(r){throw this._logService.error(r,`[Copilot:${this.sessionId}] rpc.agent.select failed: name=${t}`),r}}else{this._logService.info(`[Copilot:${this.sessionId}] Clearing custom agent selection`);try{await this._wrapper.session.rpc.agent.deselect()}catch(t){throw this._logService.error(t,`[Copilot:${this.sessionId}] rpc.agent.deselect failed`),t}}}async _handlePermissionRequest(e){this._logService.info(`[Copilot:${this.sessionId}] Permission request: kind=${e.kind}`);try{let t=e.toolCallId;if(!t)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"&&BF(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)&&!this._serverToolHost.requiresConfirmation(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"&&Kc(e.toolName);this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${t}`);let s=new Ee;if(this._pendingPermissions.set(t,s),o&&!e.requestSandboxBypass&&await this._isShellSandboxedByDefault())return this._pendingPermissions.get(t)===s?(this._pendingPermissions.delete(t),this._logService.info(`[Copilot:${this.sessionId}] Auto-approving sandboxed shell command for tool call ${t}`),{kind:"approve-once"}):{kind:"reject"};let{confirmationTitle:a,invocationMessage:l,toolInput:d,permissionKind:c,permissionPath:u}=a1(e,this._workingDirectory),p=await this._buildEditsForPermission(e,t);if(!this._pendingPermissions.has(t))return{kind:"reject"};let m=e.toolName??e.kind,h=this._activeToolCalls.get(t)?.parentToolCallId;this._onDidSessionProgress.fire({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:t,toolName:m,displayName:Dr(m),invocationMessage:l,toolInput:d,confirmationTitle:a,edits:p},permissionKind:c,permissionPath:u,requestSandboxBypass:e.requestSandboxBypass,parentToolCallId:h});let y=await s.p;return this._logService.info(`[Copilot:${this.sessionId}] Permission response: toolCallId=${t}, approved=${y}`),{kind:y?"approve-once":"reject"}}catch(t){throw this._logService.error(t,`[Copilot:${this.sessionId}] Failed to handle permission request: kind=${e.kind}, toolCallId=${e.toolCallId??"missing"}`),t}}_getInternalSessionResourcePath(e){let t;if(e.kind==="read"?t=typeof e.path=="string"?e.path:void 0:e.kind==="write"&&(t=typeof e.fileName=="string"?e.fileName:void 0),!t)return;let r=_n(v.file(WF(this._environmentService.userHome.fsPath))),o=_n(v.joinPath(r,this.sessionId));if(!rt.isEqualOrParent(o,r))return;let s=_n(v.file(t));return rt.isEqualOrParent(s,o)?t:void 0}_isSessionAttachmentPath(e){let t=_n(v.joinPath(this._sessionDataDir,Wp)),r=_n(v.file(e));return rt.isEqualOrParent(r,t)}async _isShellSandboxedByDefault(){return this._isCustomTerminalToolEnabled()?this._shellManager?this._shellManager.getOrCreateSandboxEngine().isEnabled():!1:this._computeSdkSandboxConfig()!==void 0}_isCustomTerminalToolEnabled(){return this._configurationService.getRootValue(qt,"enableCustomTerminalTool")===!0}_computeSdkSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(Cr,"sandbox");return qc(this._platform,e)}_isBypassApprovals(){return this._configurationService.getRootValue($t,Rd)===!0||this._isAutopilotMode()?!0:this._configurationService.getEffectiveValue(this.sessionUri.toString(),Jt,"autoApprove")==="autoApprove"}async _applyEffectiveSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(Cr,"sandbox"),t=qc(this._platform,e),r=t&&!this._isBypassApprovals()?t:{enabled:!1};try{await this._wrapper.session.rpc.options.update({sandboxConfig:r})}catch(o){this._logService.warn(`[Copilot:${this.sessionId}] Failed to update sandbox config for request`,o)}}async _buildEditsForPermission(e,t){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=v.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=g1(this.sessionUri.toString(),t,r);try{await this._fileService.writeFile(d,U.fromString(o))}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] Failed to write pending edit content for ${r}`,p);return}if(!this._pendingPermissions.has(t)){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(t,d);let c=typeof e.diff=="string"?zF(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,t){let r=this._pendingPermissions.get(e);return r?(this._pendingPermissions.delete(e),this._deletePendingEditContent(e),r.complete(t),!0):!1}async _requestUnsandboxedCommandConfirmation(e){let t=new Ee;this._pendingPermissions.set(e.toolCallId,t);let r=Dr(e.toolName),o=e.blockedDomains?.length?e.blockedDomains.join(", "):void 0,s=o?f(2206,null,o):f(2207,null),a=e.reason?f(2205,null,e.reason):o?f(2203,null,o):f(2204,null),l=this._activeToolCalls.get(e.toolCallId)?.parentToolCallId;return this._onDidSessionProgress.fire({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:e.toolCallId,toolName:e.toolName,displayName:r,invocationMessage:a,toolInput:e.command,confirmationTitle:s},parentToolCallId:l}),t.p}async _handleUserInputRequest(e,t){if(this._isAutopilotMode()||this._isAutoReplyEnabled())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=H(),a=H();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${s}, question="${o}"`);let l=new Ee;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:"chat/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._isAutopilotMode())return{action:"cancel"};let r=e.message.substring(0,100);try{let o=H();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,y])=>HF(h,y,a.has(h))):void 0,d=new Ee;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:"chat/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,y]of Object.entries(s.properties)){let S=$F(y,p[h]);S!==void 0&&(m[h]=S)}return{action:"accept",content:m}}catch(o){throw this._logService.error(o,`[Copilot:${this.sessionId}] Failed to handle elicitation request: message="${r}"`),o}}respondToUserInputRequest(e,t,r){let o=this._pendingPlanReviews.get(e);if(o)return this._pendingPlanReviews.delete(e),o.deferred.complete(this._resolveExitPlanMode(o,t,r)),!0;let s=this._pendingElicitations.get(e);if(s)return this._pendingElicitations.delete(e),s.deferred.complete({response:t,answers:r}),!0;let a=this._pendingUserInputs.get(e);return a?(this._pendingUserInputs.delete(e),a.deferred.complete({response:t,answers:r}),!0):!1}_resolveExitPlanMode(e,t,r){if(t!=="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?(this._syncAhpModeFromExitPlanAction(d),{approved:!0,selectedAction:d,...d==="autopilot"||d==="autopilot_fleet"?{autoApproveEdits:!0}:{}}):{approved:!1}}_syncAhpModeFromExitPlanAction(e){switch(e){case"autopilot":case"autopilot_fleet":this._syncAhpConfigFromSdkMode("autopilot");break;case"interactive":this._syncAhpConfigFromSdkMode("interactive");break}}async _handlePreToolUse(e){try{if(pl(e.toolName,y1(e))){let t=this._getEditFilePaths(e.toolArgs);await Promise.all(t.map(r=>this._editTracker.trackEditStart(r)))}}catch(t){throw this._logService.error(t,`[Copilot:${this.sessionId}] Failed in onPreToolUse: tool=${e.toolName}`),t}}async _handlePostToolUse(e){try{if(pl(e.toolName,y1(e))){let t=this._getEditFilePaths(e.toolArgs);await Promise.all(t.map(r=>this._editTracker.completeEdit(r)))}}catch(t){throw this._logService.error(t,`[Copilot:${this.sessionId}] Failed in onPostToolUse: tool=${e.toolName}`),t}}_subscribeToEvents(){let e=this._wrapper,t=this.sessionId;this._register(e.onSystemNotification(r=>{let o=ym(r);if(!o){this._logService.trace(`[Copilot:${t}] Ignoring system.notification kind=${r.data.kind.type}`);return}if(this._logService.info(`[Copilot:${t}] System notification received: kind=${r.data.kind.type}`),this._turnId){this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"systemNotification",content:o.messageText}});return}if(!o.startsTurn){this._logService.trace(`[Copilot:${t}] Ignoring passive system.notification kind=${r.data.kind.type} without an active turn`);return}let s=H();this.resetTurnState(s),this._emitAction({type:"chat/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;this._currentTurn?.markRunning();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:${t}] 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:${t}] Full message received: ${r.data.content.length} chars`),r.agentId||this._telemetryReporter.assistantMessageReceived(this.sessionUri.toString(),r.data.serviceRequestId,this._appliedSnapshot.tools),!r.data.content||this._shouldDropUnmappedSubagentEvent(r,"assistant.message"))return;let o=this._parentToolCallIdForSubagentEvent(r),s=o??"";if(this._currentTurn?.markdownPartIds.has(s))return;let a=H();this._currentTurn?.markdownPartIds.set(s,a),this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:a,content:r.data.content}},o)})),this._register(e.onToolStart(r=>{if(bm(r.data.toolName)){this._logService.trace(`[Copilot:${t}] Tool started (hidden): ${r.data.toolName}`);return}this._logService.info(`[Copilot:${t}] Tool started: ${r.data.toolName}`);let o=r.data.arguments!==void 0?uo(r.data.arguments):void 0,s;if(o)try{s=JSON.parse(o)}catch{}os(r.data.toolName,s,this._workingDirectory)&&(o=uo(s));let a=Dr(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,mcpServerName:r.data.mcpServerName,meta:void 0}),fl(r.data.toolName)){let b=l??"";this._currentTurn?.markdownPartIds.delete(b),this._currentTurn?.reasoningPartIds.delete(b);return}let d=_m(r.data.toolName),c=d==="subagent"?Tm(s):void 0,u,p=this._clientToolNames.has(r.data.toolName),m=p?this._activeClientToolSet.ownerOf(r.data.toolName,this._currentTurn?.senderClientId):void 0;if(m)u={kind:"client",clientId:m};else if(r.data.mcpServerName){let b=this._mcpCustomizations.customizationIdForServer(r.data.mcpServerName);b!==void 0&&(u={kind:"mcp",customizationId:b})}this._currentTurn?.markdownPartIds.delete(l??""),this._currentTurn?.reasoningPartIds.delete(l??"");let h={toolKind:d,language:d==="terminal"?wm(r.data.toolName):void 0};c?.description&&(h.subagentDescription=c.description),c?.agentName&&(h.subagentAgentName=c.agentName),o!==void 0&&(h.toolArguments=o),r.data.mcpServerName&&(h.mcpServerName=r.data.mcpServerName),r.data.mcpToolName&&(h.mcpToolName=r.data.mcpToolName);let y=this._activeToolCalls.get(r.data.toolCallId);if(y&&(y.meta=h),this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:r.data.toolCallId,toolName:r.data.toolName,displayName:a,intention:Cm(r.data.toolName,s),contributor:u,_meta:Qt(h)},l),p&&!u){this._logService.warn(`[Copilot:${t}] Client tool '${r.data.toolName}' started with no connected client; failing it immediately.`),this._activeToolCalls.delete(r.data.toolCallId),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:r.data.toolCallId,invocationMessage:mi(r.data.toolName,a,s),toolInput:Jc(r.data.toolName,s,o),confirmed:"not-needed"},l),this._emitAction({type:"chat/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"&&!o1(r.data.toolName)||this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:r.data.toolCallId,invocationMessage:mi(r.data.toolName,a,s),toolInput:Jc(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:${t}] 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(fl(o.toolName)){let h=jc(o.parameters,l);h&&this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:H(),content:h}});return}let d=[...o.content];l!==void 0&&d.push({type:"text",text:l}),ob(d,r.data.result?.contents);let c=Ve(o.parameters?.command)?o.parameters.command:void 0,u=pl(o.toolName,c)?this._getEditFilePaths(o.parameters):[];for(let h of u)try{let y=await this._editTracker.takeCompletedEdit(this._turnId,r.data.toolCallId,h,o.toolName,o.parameters,this._lastSeenModelId);y&&d.push(y)}catch(y){this._logService.warn(`[Copilot:${t}] Failed to take completed edit`,y)}if(Kc(o.toolName)&&this._shellManager){let h=this._shellManager.getTerminalUriForToolCall(r.data.toolCallId);h&&!d.some(y=>y.type==="terminal"&&y.resource===h)&&d.push({type:"terminal",resource:h,title:o.displayName})}let p=r.data.toolDescription?._meta?.ui?.resourceUri,m=o.meta;if(p){let h={resourceUri:p};if(o.mcpServerName){let y=this._mcpCustomizations.channelForServer(o.mcpServerName);y!==void 0&&(h.channel=y)}m={...o.meta??{},ui:h}}this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:r.data.toolCallId,result:{success:r.data.success,pastTenseMessage:Gc(o.toolName,a,o.parameters,r.data.success,r.data.success?l:void 0),content:d.length>0?d:void 0,error:r.data.error},_meta:m?Qt(m):void 0},s)})),this._register(e.onIdle(r=>{this._logService.info(`[Copilot:${t}] Session idle`),this._hasActivity&&(this._hasActivity=!1,this._emitAction({type:"session/activityChanged",activity:void 0}));let o=this._currentTurn;if(o){if(r.data.aborted){o.isRunning?(this._logService.trace(`[Copilot:${t}] Idle from abort; tearing down running turn ${o.id}`),o.markAborted(),this._currentTurn=void 0):this._logService.trace(`[Copilot:${t}] Idle from abort; leaving ${o.state} turn ${o.id} open`);return}this._completeActiveTurn()}})),this._register(e.onSkillInvoked(r=>{if(this._logService.info(`[Copilot:${t}] Skill invoked: ${r.data.name} (${r.data.path})`),this._shouldDropUnmappedSubagentEvent(r,"skill.invoked"))return;let o=this._parentToolCallIdForSubagentEvent(r),s=Im(r.data,r.id);this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:s.toolCallId,toolName:s.toolName,displayName:s.displayName},o),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:s.toolCallId,invocationMessage:s.invocationMessage,confirmed:"not-needed"},o),this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:s.toolCallId,result:{success:!0,pastTenseMessage:s.pastTenseMessage}},o)})),this._register(e.onSubagentStarted(r=>{r.agentId&&this._parentToolCallIdsByAgentId.set(r.agentId,r.data.toolCallId),this._logService.info(`[Copilot:${t}] Subagent started: toolCallId=${r.data.toolCallId}, agent=${r.data.agentName}`);let o=this._activeToolCalls.get(r.data.toolCallId);this._onDidSessionProgress.fire({kind:"subagent_started",chat:this._chatChannelUri,toolCallId:r.data.toolCallId,agentName:r.data.agentName,agentDisplayName:r.data.agentDisplayName,agentDescription:r.data.agentDescription,taskDescription:o?.meta?.subagentDescription,parentToolCallId:o?.parentToolCallId})})),this._register(e.onSessionError(r=>{this._logService.error(`[Copilot:${t}] Session error: ${r.data.errorType} - ${r.data.message}`);let o=ox(r.data)??ix(r.data.message);this._emitAction({type:"chat/error",turnId:this._turnId,error:{errorType:r.data.errorType,message:pc(r.data.message),stack:r.data.stack,...o?{_meta:o}:{}}})})),this._register(e.onUsage(r=>{let o=this._parentToolCallIdForSubagentEvent(r),s=r.data.copilotUsage,a=VF(r.data.quotaSnapshots),l=this._currentTurn;typeof r.data.model=="string"&&r.data.model&&(this._lastSeenModelId=r.data.model);let d=c=>{let u={};if(typeof r.data.cost=="number"&&(u.cost=r.data.cost),l&&typeof s?.totalNanoAiu=="number"){let p=(l.copilotUsageTotalNanoAiuByScope.get(c)??0)+s.totalNanoAiu;l.copilotUsageTotalNanoAiuByScope.set(c,p),u.copilotUsage={...s,totalNanoAiu:p}}return a&&(u.quotaSnapshots=a),{inputTokens:r.data.inputTokens,outputTokens:r.data.outputTokens,model:r.data.model,cacheReadTokens:r.data.cacheReadTokens,...Object.keys(u).length>0?{_meta:u}:{}}};this._emitAction({type:"chat/usage",turnId:this._turnId,usage:d("")}),o&&this._emitAction({type:"chat/usage",turnId:this._turnId,usage:d(o)},o)})),this._register(e.onReasoningDelta(r=>{this._logService.trace(`[Copilot:${t}] 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=>{if(r.agentId){this._logService.trace(`[Copilot:${t}] Ignoring subagent session.mode_changed: agentId=${r.agentId}, ${r.data.previousMode} -> ${r.data.newMode}`);return}this._logService.info(`[Copilot:${t}] 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._invalidateRuntimeSlashCommandCache(),this._fireMcpToolsListChanged()})),this._register(e.onCommandsChanged(()=>{this._invalidateRuntimeSlashCommandCache()})),this._seedMcpServersFromRpc()}_seedMcpServersFromRpc(){let e=this._wrapper.session.rpc?.mcp;e&&e.list().then(t=>{this._store.isDisposed||this._applyMcpServerList(t.servers)},t=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to seed MCP server inventory`,t)})}_applyMcpServerList(e){let t=e.map(r=>this._toSdkMcpServer(r.name,r.status,r.error)).filter(Gn);this._mcpCustomizations.applyAll(t)}_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,t,r){let o=this._translateSdkMcpStatus(t,r);if(o)return{name:e,state:o}}_translateSdkMcpStatus(e,t){switch(e){case"connected":return{kind:"ready"};case"failed":return{kind:"error",error:{errorType:"mcp-server-failed",message:t??"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 t=this.sessionUri.toString(),r={};switch(e){case"plan":r.mode="plan";break;case"autopilot":r.mode="autopilot";break;case"interactive":r.mode="interactive";break}this._configurationService.updateSessionConfig(t,r)}async _handleExitPlanModeRequest(e,t){let r=H(),o=H();this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request: rpcId=${r}, actions=[${e.actions.join(",")}], recommended=${e.recommendedAction}`);let s=null;try{s=(await this._wrapper.session.rpc.plan.read()).path??null}catch(u){this._logService.warn(`[Copilot:${this.sessionId}] rpc.plan.read failed for exit_plan_mode: ${u instanceof Error?u.message:String(u)}`)}let a=e.actions.map(u=>{let p=UF(u);return{id:u,label:p?.label??u,description:p?.description,recommended:u===e.recommendedAction}}),l=a.map(u=>({id:u.id,label:u.label,...u.description?{description:u.description}:{},...u.recommended?{default:!0}:{},...u.id==="autopilot"||u.id==="autopilot_fleet"?{permissionLevel:"autopilot"}:{}})),d={id:r,planReview:{title:f(2202,null),content:e.summary||f(2198,null),actions:l,canProvideFeedback:!0,answerQuestionId:o,...s?{planUri:v.file(s).toString()}:{}},questions:[{kind:"single-select",id:o,title:f(2202,null),message:f(2201,null),required:!0,options:a,allowFreeformInput:!0}]},c=new Ee;this._pendingPlanReviews.set(r,{actions:e.actions,recommendedAction:e.recommendedAction,questionId:o,deferred:c}),this._onDidSessionProgress.fire({kind:"action",resource:this._chatChannelUri,action:{type:"chat/inputRequested",request:d}});try{return await c.p}catch(u){return this._logService.error(u,`[Copilot:${this.sessionId}] exitPlanMode.request handler failed: rpcId=${r}`),{approved:!1}}}_subscribeForMemoInvalidation(){let e=this._wrapper,t=()=>this._invalidateMappedEvents();this._register(e.onUserMessage(t)),this._register(e.onTurnStart(t)),this._register(e.onMessage(t)),this._register(e.onToolStart(t)),this._register(e.onToolComplete(t)),this._register(e.onSubagentStarted(t)),this._register(e.onSubagentCompleted(t)),this._register(e.onSubagentFailed(t)),this._register(e.onTurnEnd(t)),this._register(e.onSessionCompactionComplete(t)),this._register(e.onSessionTruncation(t)),this._register(e.onSessionSnapshotRewind(t))}_subscribeForLogging(){let e=this._wrapper,t=this.sessionId;this._register(e.onUnhandledEvent(r=>{this._logService.trace(`[Copilot:${t}] Unhandled SDK event: ${ld(r)}`)})),this._register(e.onSessionStart(r=>{this._logService.trace(`[Copilot:${t}] Session started: model=${r.data.selectedModel??"default"}, producer=${r.data.producer}`)})),this._register(e.onSessionResume(r=>{this._logService.trace(`[Copilot:${t}] 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:${t}] [${r.data.infoType}]: ${r.data.message}`,a=new al(o);r.data.infoType==="mcp"?this._logService.info(s,a):this._logService.trace(s,a)})),this._register(e.onSessionWarning(r=>{this._logService.warn(`[Copilot:${t}] ${r.data.message}`,new al({warningType:r.data.warningType}))})),this._register(e.onSessionModelChange(r=>{this._logService.trace(`[Copilot:${t}] Model changed: ${r.data.previousModel??"(none)"} -> ${r.data.newModel}`)})),this._register(e.onSessionHandoff(r=>{this._logService.trace(`[Copilot:${t}] Session handoff: sourceType=${r.data.sourceType}, remoteSessionId=${r.data.remoteSessionId??"(none)"}`)})),this._register(e.onSessionTruncation(r=>{this._logService.trace(`[Copilot:${t}] Session truncation: removed ${r.data.tokensRemovedDuringTruncation} tokens, ${r.data.messagesRemovedDuringTruncation} messages`)})),this._register(e.onSessionSnapshotRewind(r=>{this._logService.trace(`[Copilot:${t}] Snapshot rewind: upTo=${r.data.upToEventId}, eventsRemoved=${r.data.eventsRemoved}`)})),this._register(e.onSessionShutdown(r=>{this._logService.trace(`[Copilot:${t}] Session shutdown: type=${r.data.shutdownType}, apiDuration=${r.data.totalApiDurationMs}ms`)})),this._register(e.onSessionUsageInfo(r=>{this._logService.trace(`[Copilot:${t}] Usage info: ${r.data.currentTokens}/${r.data.tokenLimit} tokens, ${r.data.messagesLength} messages`)})),this._register(e.onSessionCompactionStart(()=>{this._logService.trace(`[Copilot:${t}] Compaction started`)})),this._register(e.onSessionCompactionComplete(r=>{this._logService.trace(`[Copilot:${t}] Compaction complete: success=${r.data.success}, tokensRemoved=${r.data.tokensRemoved??"?"}`)})),this._register(e.onUserMessage(r=>{this._logService.trace(`[Copilot:${t}] User message: ${r.data.content.length} chars, ${r.data.attachments?.length??0} attachments`)})),this._register(e.onPendingMessagesModified(()=>{this._logService.trace(`[Copilot:${t}] Pending messages modified`)})),this._register(e.onTurnStart(r=>{this._currentTurn?.markRunning(),this._logService.trace(`[Copilot:${t}] Turn started: ${r.data.turnId}`)})),this._register(e.onIntent(r=>{this._logService.trace(`[Copilot:${t}] Intent: ${r.data.intent}`);let o=r.data.intent||void 0;o===void 0&&!this._hasActivity||(this._hasActivity=o!==void 0,this._emitAction({type:"session/activityChanged",activity:o}))})),this._register(e.onReasoning(r=>{this._logService.trace(`[Copilot:${t}] Reasoning: ${r.data.content.length} chars`)})),this._register(e.onTurnEnd(r=>{this._logService.trace(`[Copilot:${t}] Turn ended: ${r.data.turnId}`)})),this._register(e.onAbort(r=>{this._logService.trace(`[Copilot:${t}] Aborted: ${r.data.reason}`)})),this._register(e.onToolUserRequested(r=>{this._logService.trace(`[Copilot:${t}] Tool user-requested: ${r.data.toolName} (${r.data.toolCallId})`)})),this._register(e.onToolPartialResult(r=>{this._logService.trace(`[Copilot:${t}] Tool partial result: ${r.data.toolCallId} (${r.data.partialOutput.length} chars)`)})),this._register(e.onToolProgress(r=>{this._logService.trace(`[Copilot:${t}] Tool progress: ${r.data.toolCallId} - ${r.data.progressMessage}`)})),this._register(e.onSkillInvoked(r=>{this._logService.trace(`[Copilot:${t}] Skill invoked: ${r.data.name} (${r.data.path})`)})),this._register(e.onSubagentStarted(r=>{this._logService.trace(`[Copilot:${t}] Subagent started: ${r.data.agentName} (${r.data.agentDisplayName})`)})),this._register(e.onSubagentCompleted(r=>{r.agentId&&this._parentToolCallIdsByAgentId.delete(r.agentId),this._logService.trace(`[Copilot:${t}] Subagent completed: ${r.data.agentName}`),this._onDidSessionProgress.fire({kind:"subagent_completed",chat:this._chatChannelUri,toolCallId:r.data.toolCallId})})),this._register(e.onSubagentFailed(r=>{r.agentId&&this._parentToolCallIdsByAgentId.delete(r.agentId),this._logService.error(`[Copilot:${t}] Subagent failed: ${r.data.agentName} - ${r.data.error}`),this._onDidSessionProgress.fire({kind:"subagent_completed",chat:this._chatChannelUri,toolCallId:r.data.toolCallId})})),this._register(e.onSubagentSelected(r=>{this._logService.trace(`[Copilot:${t}] Subagent selected: ${r.data.agentName}`)})),this._register(e.onHookStart(r=>{this._logService.trace(`[Copilot:${t}] Hook started: ${r.data.hookType} (${r.data.hookInvocationId})`)})),this._register(e.onHookEnd(r=>{this._logService.trace(`[Copilot:${t}] Hook ended: ${r.data.hookType} (${r.data.hookInvocationId}), success=${r.data.success}`)})),this._register(e.onSystemMessage(r=>{this._logService.trace(`[Copilot:${t}] 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,t){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`),t?await this._databaseRef.object.deleteTurnsAfter(t):await this._databaseRef.object.deleteAllTurns()}async remapTurnIds(e){await this._databaseRef.object.remapTurnIds(e)}_denyPendingPermissions(){for(let[e,t]of this._pendingPermissions)this._deletePendingEditContent(e),t.complete(!1);this._pendingPermissions.clear()}_deletePendingEditContent(e){let t=this._pendingEditContentUris.get(e);t&&(this._pendingEditContentUris.delete(e),this._fileService.del(t).catch(r=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to delete pending edit content: ${t.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 t of e)this._wrapper.session.rpc.mcp.cancelSamplingExecution({requestId:t}).catch(()=>{})}_cancelPendingClientToolCalls(){this._pendingClientToolCalls.denyAll({textResultForLlm:"Tool call cancelled: session ended",resultType:"failure",error:"Session ended"})}};gl=w([C(1,Ie),C(2,D),C(3,Je),C(4,xe),C(5,Rt),C(6,ze),C(7,Hn)],gl);function zF(i){let n=0,e=0;for(let t of i.split(`
`))t.startsWith("+++")||t.startsWith("---")||(t.startsWith("+")?n++:t.startsWith("-")&&e++);if(!(n===0&&e===0))return{added:n,removed:e}}function VF(i){if(!i||typeof i!="object")return;let n={},e=!1;for(let[t,r]of Object.entries(i)){if(!r||typeof r!="object")continue;let o=r,s=o.resetDate,a=typeof s=="string"?s:s instanceof Date?s.toISOString():void 0;n[t]={isUnlimitedEntitlement:typeof o.isUnlimitedEntitlement=="boolean"?o.isUnlimitedEntitlement:void 0,entitlementRequests:typeof o.entitlementRequests=="number"?o.entitlementRequests:void 0,usedRequests:typeof o.usedRequests=="number"?o.usedRequests:void 0,remainingPercentage:typeof o.remainingPercentage=="number"?o.remainingPercentage:void 0,overage:typeof o.overage=="number"?o.overage:void 0,overageAllowedWithExhaustedQuota:typeof o.overageAllowedWithExhaustedQuota=="boolean"?o.overageAllowedWithExhaustedQuota:void 0,resetDate:a},e=!0}return e?n:void 0}async function jF(i,n){if(!i||i.scheme!==ie.file)return;let e=await n.getRepositoryRoot(i);if(!e)return;let t=(await n.getWorktreeRoots(i))[0]??e;if(t)return{uri:t,displayName:Te(t.fsPath)||t.toString()}}function KF(i){let n=i.includes("://")?v.parse(i):v.parse(`https://github.com/${i}`),e=Te(n.path)||i.split("/").filter(Boolean).pop()||i,t=e.endsWith(".git")?e.slice(0,-4):e;return{uri:n,displayName:t}}async function ar(i,n){let e=typeof i?.cwd=="string"?v.file(i.cwd):typeof i?.gitRoot=="string"?v.file(i.gitRoot):void 0,t=await jF(e,n);if(t)return t;if(i?.repository)return KF(i.repository)}function v1(i){let n={};for(let[e,t]of Object.entries(i))t!==void 0&&(n[e]=t);return Object.keys(n).length>0?n:void 0}function C1(i,n){if(i.length!==n.length)return!1;for(let e=0;e<i.length;e++){let t=i[e],r=n[e];if(t.type!==r.type||t.uri.toString()!==r.uri.toString()||!JF(t.files,r.files))return!1}return!0}function GF(i,n){let e=On(i.type,n.type);return e!==0?e:On(i.uri.toString(),n.uri.toString())}function JF(i,n){if(i.length!==n.length)return!1;for(let e=0;e<i.length;e++){let t=i[e],r=n[e];if(t.uri.toString()!==r.uri.toString()||t.etag!==r.etag)return!1}return!0}function Qc(i,n){return On(i.uri.toString(),n.uri.toString())}function YF(i,n){let e=On(i.uri,n.uri);return e!==0?e:On(i.contents,n.contents)}var QF=5,XF=8;var ZF=".md",e4=".instructions.md",t4=".json",n4="SKILL.md",r4="README.md",S1={workspace:[{path:[".github","agents"],type:"agent",name:".github"},{path:[".agents","agents"],type:"agent",name:".agents"},{path:[".claude","agents"],type:"agent",name:".claude"},{path:[".github","skills"],recursive:!0,type:"skill",name:".github"},{path:[".agents","skills"],recursive:!0,type:"skill",name:".agents"},{path:[".claude","skills"],recursive:!0,type:"skill",name:".claude"},{path:[".github","instructions"],recursive:!0,type:"instruction",name:".github"},{path:[".github","hooks"],recursive:!0,type:"hook",name:".github"}],user:[{path:[".copilot","agents"],type:"agent",name:"~/.copilot"},{path:[".agents","skills"],recursive:!0,type:"skill",name:"~/.agents"},{path:[".copilot","skills"],recursive:!0,type:"skill",name:"~/.copilot"},{path:[".copilot","instructions"],recursive:!0,type:"instruction",name:"~/.copilot"},{path:[".copilot","hooks"],recursive:!0,type:"hook",name:"~/.copilot"}]},b1={workspace:[{path:[".github"],filenames:["copilot-instructions.md"],type:"agentInstruction"},{path:[],filenames:["AGENTS.md","CLAUDE.md","GEMINI.md"],type:"agentInstruction"},{path:[".claude"],filenames:["CLAUDE.md"],type:"agentInstruction"},{path:[".github","copilot"],filenames:["settings.json","settings.local.json"],type:"hook"},{path:[".claude"],filenames:["settings.json","settings.local.json"],type:"hook"}],user:[{path:[".copilot"],filenames:["copilot-instructions.md"],type:"agentInstruction"}]};function hn(i){if(i.isCancellationRequested)throw new Y}function ab(i,n,e,t){let r=i.get(n);r?e&&!r.recursive&&(r={recursive:!0,resourcesToWatch:r.resourcesToWatch},i.set(n,r)):(r={recursive:e,resourcesToWatch:new pr},i.set(n,r)),r.resourcesToWatch.add(t)}var ml=class extends T{constructor(e,t,r,o){super();this._workingDirectory=e;this._userHome=t;this._fileService=r;this._logService=o;this._onDidChange=this._register(new P);this.onDidChange=this._onDidChange.event;this._watchers=new We;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 discover(e,t){hn(t);let r={projectPaths:[this._workingDirectory.fsPath]};try{let[o,s,a]=await Promise.all([this.discoverAgents(r,e,t),this.discoverRules(r,e,t),this.discoverSkills(r,e,t)]);hn(t);let l=[];return this.toDirectoryCustomizations("agent",o,l),this.toDirectoryCustomizations("rule",s,l),this.toDirectoryCustomizations("skill",a,l),l.sort(YF)}catch(o){return this._logService.error(`[SessionCustomizationDiscovery] Error during discovery: ${o instanceof Error?o.message:String(o)}`),[]}}async discoverAgents(e,t,r){let o=[],s=await zu(t.rpc.agents.discover(e),r);for(let a of s.agents)if(a.path){let l=v.file(a.path);o.push({type:"agent",uri:l.toString(),id:a.id,name:a.name,description:a.description,_meta:v1({userInvocable:a.userInvocable})})}return o}async discoverRules(e,t,r){let o=[],s=await zu(t.rpc.instructions.discover(e),r);for(let a of s.sources){let l;Ft(a.sourcePath)?l=v.file(a.sourcePath):l=te(this._workingDirectory,a.sourcePath),o.push({type:"rule",uri:l.toString(),id:a.id,name:a.label,description:a.description,globs:a.applyTo,alwaysApply:!1})}return o}async discoverSkills(e,t,r){let o=[],s=await zu(t.rpc.skills.discover(e),r);for(let a of s.skills)if(a.path){let l=v.file(a.path);o.push({type:"skill",uri:l.toString(),id:a.path,name:a.name,description:a.description})}return o}toDirectoryCustomizations(e,t,r){let o=new We;for(let s of t){if(s.type!==e)continue;let a=v.parse(s.uri),l=In(a),d=o.get(l);d||(d={uri:l,children:[]},o.set(l,d)),d.children.push(s)}for(let{uri:s,children:a}of o.values())a.sort((l,d)=>On(l.uri,d.uri)),r.push({type:"directory",id:Ot(s.toString()),uri:s.toString(),name:Te(s.path),enabled:!0,contents:e,writable:!0,load:{kind:"loaded"},children:a})}async scan(e){hn(e);let t=new We,r=new pr,o=[];return await Promise.all([...S1.workspace.map(s=>this._scanRoot(this._workingDirectory,s,r,o,t,e)),...S1.user.map(s=>this._scanRoot(this._userHome,s,r,o,t,e)),this._scanFixedDiscoveryFiles(this._workingDirectory,b1.workspace,r,o,t,e),this._scanFixedDiscoveryFiles(this._userHome,b1.user,r,o,t,e)]),hn(e),this._reconcileWatchers(t),o.sort(GF)}async _watchAncestors(e,t,r,o){let s=e;for(let a of t){let l=s,d=te(l,a);if(!r.has(l)){hn(o);try{if(!(await this._fileService.resolve(l)).isDirectory)return!1}catch{return!1}}ab(r,l,!1,d),s=d}return!0}_reconcileWatchers(e){for(let[t,r]of this._watchers.entries()){let o=e.get(t);(!o||o.recursive!==r.recursive)&&(r.disposable.dispose(),this._watchers.delete(t))}for(let[t,r]of e.entries()){let o=this._watchers.get(t);if(o){o.resourcesToWatch.clear();for(let s of r.resourcesToWatch)o.resourcesToWatch.add(s);continue}try{let s=this._fileService.watch(t,{recursive:r.recursive,excludes:[]});this._watchers.set(t,{recursive:r.recursive,resourcesToWatch:r.resourcesToWatch,disposable:s})}catch(s){this._logService.warn(`[SessionCustomizationDiscovery] Failed to watch '${t.toString()}': ${s instanceof Error?s.message:String(s)}`)}}}_disposeAllWatchers(){for(let e of this._watchers.values())e.disposable.dispose();this._watchers.clear()}async _scanFixedDiscoveryFiles(e,t,r,o,s,a){let l=new Map;await Promise.all(t.map(async d=>{if(hn(a),!await this._watchAncestors(e,d.path,s,a))return;let c=te(e,...d.path),u;try{u=await this._fileService.resolve(c,{resolveMetadata:!0})}catch{return}if(!(!u.isDirectory||!u.children)){for(let p of d.filenames)ab(s,c,!1,te(c,p));for(let p of u.children)if(hn(a),p.isFile&&d.filenames.includes(p.name)){let m=te(c,p.name);if(!r.has(m)){r.add(m);let h=l.get(d.type)??[];h.push({uri:m,etag:p.etag}),l.set(d.type,h)}}}}));for(let[d,c]of l.entries())c.length>0&&o.push({uri:e,type:d,files:c.sort(Qc),name:"",writable:!1})}async _scanRoot(e,t,r,o,s,a){hn(a);let l=te(e,...t.path),d,c=[];try{d=await this._fileService.resolve(l,{resolveMetadata:!0}),c=d.children??[]}catch{}if(await this._watchAncestors(e,t.path,s,a),ab(s,l,t.recursive??!1,l),t.type==="skill"){let u=[];await Promise.all(c.map(async p=>{if(hn(a),p.isDirectory){let m=te(p.resource,n4);try{let h=await this._fileService.resolve(m,{resolveMetadata:!0});h.isFile&&!r.has(m)&&(r.add(m),u.push({uri:m,etag:h.etag}))}catch{}}})),o.push({uri:l,type:t.type,files:u.sort(Qc),name:t.name,writable:!0})}else if(t.type==="agent"){let u=[];for(let p of c)if(hn(a),p.isFile){let m=p.name;m.endsWith(ZF)&&m!==r4&&!r.has(p.resource)&&(r.add(p.resource),u.push({uri:p.resource,etag:p.etag}))}o.push({uri:l,type:t.type,files:u.sort(Qc),name:t.name,writable:!0})}else if(t.type==="instruction"){let u=[],p=async(m,h)=>{hn(a);for(let y of m.children??[])if(hn(a),y.isFile)y.name.toLowerCase().endsWith(e4)&&!r.has(y.resource)&&(r.add(y.resource),u.push({uri:y.resource,etag:y.etag}));else if(y.isDirectory&&h<QF){let S;try{S=await this._fileService.resolve(y.resource,{resolveMetadata:!0})}catch{}S&&await p(S,h+1)}};d&&await p(d,0),o.push({uri:l,type:t.type,files:u.sort(Qc),name:t.name,writable:!0})}else if(t.type==="hook"){let u=[],p=async(m,h)=>{hn(a);for(let y of m.children??[])if(hn(a),y.isFile)y.name.toLowerCase().endsWith(t4)&&!r.has(y.resource)&&(r.add(y.resource),u.push({uri:y.resource,etag:y.etag}));else if(y.isDirectory&&h<XF){let S;try{S=await this._fileService.resolve(y.resource,{resolveMetadata:!0})}catch{}S&&await p(S,h+1)}};d&&await p(d,0),o.push({uri:l,type:t.type,files:u.sort(Qc),name:t.name,writable:!0})}else this._logService.warn(`[SessionCustomizationDiscovery] Unrecognized root type '${t.type}' for root '${l.toString()}'`)}};ml=w([C(2,xe),C(3,D)],ml);var s4=300,a4="https://api.githubcopilot.com",l4=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"],d4=["HTTP_PROXY","HTTPS_PROXY"];function c4(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"}}async function I1(i){try{return await zt.access(i),!0}catch{return!1}}function u4(){return process.platform!=="linux"?!1:!process.report?.getReport()?.header?.glibcVersionRuntime}function p4(){let i=`${process.platform}-${process.arch}`;if(process.platform!=="linux")return[i];let n=[`linux-${process.arch}`,`linuxmusl-${process.arch}`];return u4()?n.reverse():n}async function f4(i){let n=[];for(let t of p4()){let r=v.joinPath(i,"@github",`copilot-${t}`,"index.js").fsPath;if(n.push(r),await I1(r))return r}let e=v.joinPath(i,"@github","copilot","index.js").fsPath;if(n.push(e),await I1(e))return e;throw new Error(`Unable to resolve @github/copilot CLI path. Tried: ${n.join(", ")}`)}function g4(i){return v.joinPath(i,"..",`${Te(i.fsPath)}.worktrees`)}function m4(i){return(i.startsWith(Nc)?i.substring(Nc.length):i).replace(/\//g,"-")}function w1(i,n,e){if(!Kr(i,n))return;let t=Gr(n,i);if(t!==void 0)return t.length===0?e:te(e,t)}function h4(i,n,e){let t=new Map;for(let[r,o]of i){let s=w1(v.parse(r),n,e);t.set(s?s.toString():r,o)}return t}function _1(i){return f(2191,null,it(i))+`

`}function y4(i,n){if(i.length===0)return i;let e=i.slice(),t=e[0],r=t.responseParts[0];if(r?.kind==="markdown"){let o=t.responseParts.slice();o[0]={...r,content:n+r.content},e[0]={...t,responseParts:o}}else{let o=[{kind:"markdown",id:H(),content:n},...t.responseParts];e[0]={...t,responseParts:o}}return e}var ss=class extends rl{},Pe=class extends T{constructor(e,t,r,o,s,a,l,d,c,u,p,m,h,y,S){super();this._logService=e;this._instantiationService=t;this._sessionDataService=r;this._gitService=o;this._configurationService=s;this._otelService=a;this._branchNameGenerator=l;this._checkpointService=c;this._reviewService=u;this._environmentService=p;this._byokBridgeRegistry=m;this._telemetryService=h;this._copilotApiService=y;this._proxyResolver=S;this.id="copilotcli";this._onDidSessionProgress=this._register(new P);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidSpawnChat=this._register(new P);this.onDidSpawnChat=this._onDidSpawnChat.event;this._onDidMaterializeSession=this._register(new P);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new P);this.onMcpNotification=this._onMcpNotification.event;this._models=nn(this,[]);this.models=this._models;this._capiModels=[];this._byokModels=[];this._freeLongContextModels=new Set;this._modelRefreshMaxAttempts=5;this._modelRefreshBaseDelayMs=1e3;this._modelRefreshMaxDelayMs=3e4;this._modelRefreshRetry=this._register(new At);this._restrictedTelemetryEnabled=!1;this._onDidChangeRestrictedTelemetry=this._register(new P);this.onDidChangeRestrictedTelemetry=this._onDidChangeRestrictedTelemetry.event;this._sessions=this._register(new Re);this._chatBackings=new Map;this._onDidChangeChatData=this._register(new P);this.onDidChangeChatData=this._onDidChangeChatData.event;this._mcpNotificationSubs=this._register(new Re);this._resumingSessions=new Map;this._provisionalSessions=new Map;this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._sessionSequencer=new at;this._activeClients=new We;this._lastSessionSyncEnabled=this._isSessionSyncEnabled();this._lastRubberDuckEnabled=this._isRubberDuckEnabled();this.chats={createChat:(e,t)=>this._createChat(e,t),fork:(e,t,r)=>this._createChat(e,{...r,fork:t}),disposeChat:e=>{let{session:t,chat:r}=this._resolveChatTarget(e);return this._disposeChat(t,r)},sendMessage:(e,t,r,o,s)=>this._sendMessage(e,t,r,o,s),abort:e=>this._abortSession(e),changeModel:(e,t)=>this._changeModel(e,t),changeAgent:(e,t)=>this._changeAgent(e,t),getMessages:e=>this.getSessionMessages(e)};this._plugins=this._register(this._instantiationService.createInstance(Xc)),this._sessionLauncher=this._instantiationService.createInstance(ul),this.onDidCustomizationsChange=this._plugins.onDidChange,this._register(this._onDidSessionProgress.event(b=>this._emitSpawnedChatForSubagentSignal(b))),this._register(d.registerProvider(new vm(this.id,{isRubberDuckEnabled:()=>this._isRubberDuckEnabled(),getRuntimeSlashCommands:async(b,I)=>this._findAnySession(b)?.getRuntimeSlashCommands(I)??[],getSessionCustomizations:b=>this.getSessionCustomizations(L.uri(this.id,b))},s4))),this._register(this._configurationService.onDidRootConfigChange(()=>{this._restartClientIfStartupConfigChanged().catch(b=>this._logService.error("[Copilot] Failed to restart client after config change",b))})),this._register(this._byokBridgeRegistry.onDidChangeModels(()=>{this._logService.info("[Copilot] BYOK bridge changed; refreshing models"),this._refreshByokModels()}))}static{this._BRANCH_COMPLETION_LIMIT=25}setServerToolHost(e){this._serverToolHost=e}get restrictedTelemetryEnabled(){return this._restrictedTelemetryEnabled}_emitSpawnedChatForSubagentSignal(e){let t=Oo.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_isSessionSyncEnabled(){return this._configurationService.getRootValue($t,wd)===!0}_isRubberDuckEnabled(){return this._configurationService.getRootValue(qt,"rubberDuck")===!0}async _restartClientIfStartupConfigChanged(){let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled();if(this._lastSessionSyncEnabled===e&&this._lastRubberDuckEnabled===t)return;let r=[this._lastSessionSyncEnabled!==e?`sessionSync=${e}`:void 0,this._lastRubberDuckEnabled!==t?`rubberDuck=${t}`:void 0].filter(o=>o!==void 0).join(", ");this._lastSessionSyncEnabled=e,this._lastRubberDuckEnabled=t,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 i4(e)}getDescriptor(){return{provider:"copilotcli",displayName:"Copilot",description:f(2189,null),capabilities:{multipleChats:{fork:!0}}}}getProtectedResources(){return[mt,Ht]}getCustomizations(){return this._plugins.getConfiguredHostCustomizations()}async getSessionCustomizations(e){let t=await this._getSessionCustomizationDirectory(e),o=await this._getOrCreateActiveClient(e,t).pluginController.getCustomizationsSettled(),s=L.id(e),l=this._findAnySession(s)?.topLevelMcpCustomizations()??[];return l.length===0?o:[...o,...l]}async handleMcpRequest(e,t,r,o){let s=L.id(e),a=this._findAnySession(s);if(!a)throw new Error(`Method not found: no active session ${s}`);return a.handleMcpRequest(t,r,o)}async _getSessionCustomizationDirectory(e){let t=L.id(e),r=this._provisionalSessions.get(t);if(r)return r.workingDirectory;let o=this._findAnySession(t),s=o?void 0:await this._readSessionMetadata(e);return o?.customizationDirectory??s?.workingDirectory??s?.customizationDirectory}async authenticate(e,t){if(e===Ht.resource)return!0;if(e!==mt.resource)return!1;let r=this._githubToken!==t;return this._githubToken=t,this._updateRestrictedTelemetry(t),this._logService.info(`[Copilot] Auth token ${r?"updated":"unchanged"}`),r&&(await this._restartClientIfProxyChanged(),this._refreshModels()),!0}async handleAuthenticationToken(e){let t=!1;for(let[,r]of this._sessions)for(let o of r.allChatSessions()){let s=await o.resolveMcpAuthentication(e);t||=s}return t}_updateRestrictedTelemetry(e){this._applyRestrictedTelemetry(!1,void 0,void 0),e&&this._resolveRestrictedTelemetry(e)}async _resolveRestrictedTelemetry(e){try{let t=await this._copilotApiService.resolveRestrictedTelemetryContext(e);if(this._githubToken!==e)return;this._applyRestrictedTelemetry(t.restrictedTelemetryEnabled,t.trackingId,t.telemetryEndpoint?`${t.telemetryEndpoint}/telemetry`:void 0)}catch(t){this._logService.debug(`[Copilot] Restricted telemetry resolution failed: ${t instanceof Error?t.message:String(t)}`)}}_applyRestrictedTelemetry(e,t,r){e!==this._restrictedTelemetryEnabled&&(this._restrictedTelemetryEnabled=e,this._logService.info(`[Copilot] Enhanced (restricted) telemetry ${e?"enabled for this account":"disabled"}`),this._onDidChangeRestrictedTelemetry.fire()),eS(this._telemetryService)&&(this._telemetryService.setRestrictedTelemetryEnabled(e),this._telemetryService.setCopilotTrackingId(t),this._telemetryService.setRestrictedTelemetryEndpoint(r))}async _refreshModels(e=0){if(this._modelRefreshRetry.clear(),this._shutdownPromise)return;let t=this._githubToken;if(!t){this._capiModels=[],this._publishModels();return}try{let r=await this._listModels(t);this._githubToken===t&&(this._capiModels=r,this._publishModels())}catch(r){if(this._githubToken!==t||this._shutdownPromise)return;if(e+1<this._modelRefreshMaxAttempts){let o=this._modelRefreshBackoff(e);this._logService.warn(`[Copilot] Failed to refresh models (attempt ${e+1}), retrying in ${o}ms`,r),this._modelRefreshRetry.value=Kt(()=>{this._refreshModels(e+1)},o);return}this._logService.error(r,"[Copilot] Failed to refresh models"),this._publishModels()}}_publishModels(){this._models.set([...this._capiModels,...this._byokModels],void 0)}_refreshByokModels(){this._shutdownPromise||(this._byokModels=this._byokBridgeRegistry.getModels().map(e=>({provider:this.id,id:`${e.vendor}/${e.id}`,name:e.name??e.id,maxContextWindow:e.maxContextWindowTokens,supportsVision:e.supportsVision??!1})),this._logService.trace(`[Copilot] Found ${this._byokModels.length} BYOK models${this._byokModels.length?": "+this._byokModels.map(e=>e.name).join(", "):""}`),this._publishModels())}_modelRefreshBackoff(e){let t=Math.min(this._modelRefreshMaxDelayMs,this._modelRefreshBaseDelayMs*2**e);return Math.round(t/2+Math.random()*(t/2))}async _stopClient(){let e=this._client;this._client=void 0,this._clientStarting=void 0,await e?.stop(),await this._sessionLauncher.disposeByokProxyHandle()}_enablePlanModeOnClient(e){let t=e.connection;if(!t){this._logService.warn("[Copilot] Could not enable plan mode: client.connection is null");return}if(typeof t.sendRequest!="function"){this._logService.warn(`[Copilot] Could not enable plan mode: client.connection.sendRequest is ${typeof t.sendRequest}`);return}if(typeof t.onRequest!="function"){this._logService.warn(`[Copilot] Could not enable plan mode: client.connection.onRequest is ${typeof t.onRequest}`);return}let r=t.sendRequest.bind(t);t.sendRequest=(o,s)=>(o==="session.create"||o==="session.resume")&&s&&typeof s=="object"?r(o,{...s,requestExitPlanMode:!0}):r(o,s)}async _ensureClient(){if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled(),r=(async()=>{this._logService.info("[Copilot] Starting CopilotClient...");let o=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete o.NODE_OPTIONS,delete o.VSCODE_INSPECTOR_OPTIONS,delete o.VSCODE_ESM_ENTRYPOINT,delete o.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let y of Object.keys(o))y!=="ELECTRON_RUN_AS_NODE"&&y!=="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE"&&(y.startsWith("VSCODE_")||y.startsWith("ELECTRON_"))&&delete o[y];if(o.COPILOT_CLI_RUN_AS_NODE="1",o.USE_BUILTIN_RIPGREP="false",o.COPILOT_MCP_APPS="true",await this._configureProxyEnv(o),process.platform==="linux"){let y=o.COPILOT_CLI_ENABLED_FEATURE_FLAGS,S=new Set((y??"").split(",").map(b=>b.trim()).filter(Boolean));S.add("SHELL_SPAWN_BACKEND"),o.COPILOT_CLI_ENABLED_FEATURE_FLAGS=[...S].join(",")}o.GITHUB_COPILOT_INTEGRATION_ID=fS,this._logService.info(`[Copilot] Set CLI env: GITHUB_COPILOT_INTEGRATION_ID=${fS}`),this._isRubberDuckEnabled()?o.RUBBER_DUCK_AGENT="true":delete o.RUBBER_DUCK_AGENT;let s=v.joinPath(Dt.asFileUri(""),"..","node_modules"),a=await f4(s);o.MXC_BIN_DIR=v.joinPath(s,"@microsoft","mxc-sdk","bin").fsPath;let l=await Ha(),d=le(l),c=Object.keys(o).find(y=>y.toUpperCase()==="PATH")??"PATH",u=o[c];o[c]=u?`${u}${ws}${d}`:d,this._logService.info(`[Copilot] Resolved CLI path: ${a}`);let p=await this._otelService.getSdkTelemetryConfig(),m={useLoggedInUser:!1,connection:o4.forStdio({path:a}),env:o,telemetry:p,logLevel:c4(this._logService.getLevel()),enableRemoteSessions:this._isSessionSyncEnabled()},h=this._createCopilotClient(m);if(await h.start(),this._isSessionSyncEnabled()!==e||this._isRubberDuckEnabled()!==t)throw await h.stop(),new Error("Copilot startup config changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._enablePlanModeOnClient(h),this._client=h,this._clientStarting=void 0,h})();return this._clientStarting=r,r.catch(()=>{this._clientStarting=void 0}),r}_createThinkingLevelConfigSchemaProperty(e,t){if(e?.length)return{type:"string",title:f(2188,null),description:f(2187,null),default:t,enum:[...e],enumLabels:e.map(ns),enumDescriptions:e.map(r=>rs(r)??"")}}_createContextSizeConfigSchemaProperty(e){let t=e?.tokenPrices,r=t?.contextMax,o=t?.longContext?.contextMax;if(!(!r||!o||r>=o))return BS(e)?{type:"number",title:f(2186,null),description:f(2184,null),default:r,enum:[r,o],enumLabels:[Hg(r),Hg(o)],enumDescriptions:[f(2183,null),f(2185,null)]}:{type:"number",title:f(2186,null),description:f(2184,null),default:o,enum:[o],enumLabels:[Hg(o)],enumDescriptions:[f(2185,null)]}}_longContextWindowFor(e){if(!e)return;let r=this._models.get().find(o=>o.id===e)?.configSchema?.properties?.[gm]?.enum?.filter(o=>typeof o=="number");return r&&r.length>0?Math.max(...r):void 0}_isFreeLongContext(e){return!!e&&this._freeLongContextModels.has(e)}_createModelPricingMeta(e){let t=e?.billing,r=typeof e?.modelPickerPriceCategory=="string"?e.modelPickerPriceCategory:void 0;return tl(t,r)}_createModelConfigSchema(e){let t={},r=this._createThinkingLevelConfigSchemaProperty(e.supportedReasoningEfforts,e.defaultReasoningEffort);r&&(t[tb]=r);let o=this._createContextSizeConfigSchemaProperty(e.billing);if(o&&(t[gm]=o),Object.keys(t).length!==0)return{type:"object",properties:t}}_serializeModelSelection(e){return JSON.stringify(e)}_parseModelSelection(e){if(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.id=="string"){let r={id:t.id};if(t.config&&typeof t.config=="object"){let o={};for(let[s,a]of Object.entries(t.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 t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.uri=="string")return{uri:t.uri}}catch{}}async _resolveAgentName(e,t,r){for(let l of t.plugins){let d=l.agents.find(c=>c.uri.toString()===r.uri);if(d)return d.name}let o=await this.getSessionCustomizations(e),a=cP(o).find(l=>l.uri.toString()===r.uri);if(a)return a.name}async listSessions(){this._logService.info("[Copilot] Listing sessions...");let t=await(await this._ensureClient()).listSessions(),r=new Ps(4),o=new Map,a=(await Promise.all(t.map(async l=>{let d=L.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"?v.file(l.context.workingDirectory):void 0);return{session:d,startTime:l.startTime.getTime(),modifiedTime:l.modifiedTime.getTime(),project:u,summary:l.summary,workingDirectory:m,customizationDirectory:c.customizationDirectory}}))).filter(l=>l!==void 0);return this._logService.info(`[Copilot] Found ${a.length} sessions`),a}async getSessionMetadata(e){let t=L.id(e),r=await this._readStoredSessionMetadata(e);if(!r)return;let s=await(await this._ensureClient()).getSessionMetadata(t);if(!s)return;let a=r?.project;if(r&&!r.resolved){let d=new Ps(1);a=await this._resolveSessionProject(s?.context,d,new Map),this._storeSessionProjectResolution(e,a)}let l=r?.workingDirectory??(typeof s?.context?.workingDirectory=="string"?v.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,workingDirectory:l,customizationDirectory:r?.customizationDirectory}}async _listModels(e){this._logService.info("[Copilot] Listing models...");let t=await this._ensureClient(),{models:r}=await t.rpc.models.list({gitHubToken:e});this._freeLongContextModels.clear();let o=r.map(s=>{let a=this._createModelConfigSchema(s),l=s.billing?.tokenPrices;return l?.contextMax&&l.longContext?.contextMax&&l.longContext.contextMax>l.contextMax&&!BS(s.billing)&&this._freeLongContextModels.add(s.id),{provider:this.id,id:s.id,name:s.name,maxContextWindow:s.capabilities?.limits?.max_context_window_tokens,maxOutputTokens:s.capabilities?.limits?.max_output_tokens,maxPromptTokens:s.capabilities?.limits?.max_prompt_tokens,supportsVision:!!s.capabilities?.supports?.vision,configSchema:a,policyState:s.policy?.state,_meta:this._createModelPricingMeta(s)}});return this._logService.info(`[Copilot] Found ${o.length} models: ${o.map(s=>s.name).join(", ")}`),o}async _resolveCreateWorkingDirectory(e,t,r){let o=e.workingDirectory??this._provisionalSessions.get(t)?.workingDirectory;if(o)return o;if(r){let l=this._workspacelessScratchDir(t);return await zt.mkdir(l.fsPath,{recursive:!0}),l}let s=await zt.mkdtemp(j(T1.tmpdir(),"agent-host-session-")),a=v.file(s);return this._logService.trace(`[Copilot] No workingDirectory provided, defaulting to temp directory: ${a.fsPath}`),a}_workspacelessScratchDir(e){return qS(this._environmentService.userHome,e)}async _ensureWorkspacelessScratchDir(e,t){try{await zt.mkdir(e.fsPath,{recursive:!0}),this._logService.trace(`[Copilot:${t}] Workspace-less scratch directory ready: ${e.fsPath}`)}catch(r){this._logService.warn(`[Copilot:${t}] Failed to ensure workspace-less scratch directory '${e.fsPath}': ${r instanceof Error?r.message:String(r)}`)}}async _cleanupWorkspacelessScratchDir(e,t){try{await zt.rm(e.fsPath,{recursive:!0,force:!0}),this._logService.trace(`[Copilot:${t}] Removed workspace-less scratch directory: ${e.fsPath}`)}catch(r){this._logService.warn(`[Copilot:${t}] Failed to remove workspace-less scratch directory '${e.fsPath}': ${r instanceof Error?r.message:String(r)}`)}}_resolveChatTarget(e){let t=He(e);if(!t)throw new Error(`Copilot chat operation requires an AHP chat URI: ${e.toString()}`);return{session:v.parse(t.session),chat:e}}_getChatContext(e){let t=He(e)?e:v.parse(be(e)),r=v.parse(fe(t)),o=L.id(r),s=t.toString(),a=this._sessions.get(o)?.resolveChat(s);return{session:r,sessionId:o,chatKey:s,target:a?.chatSession,isPeerChat:a?!a.isDefault:s!==be(r)}}_findAnySession(e){return this._sessions.get(e)?.defaultChat}_findPeerChat(e,t){return this._sessions.get(L.id(e))?.getPeerChat(t.toString())}_ensureEntry(e){let t=this._sessions.get(e);return t||(t=new ss,this._sessions.set(e,t)),t}async createSession(e){let t=e??{};this._logService.info(`[Copilot] Creating session... ${t.model?`model=${t.model.id}`:""}`);let r=t.session?L.id(t.session):H(),o=!t.fork&&!t.workingDirectory,s=await this._resolveCreateWorkingDirectory(t,r,o),a=await this._ensureClient();if(t.fork){let u=L.id(t.fork.session);return this._sessionSequencer.queue(u,async()=>{this._logService.info(`[Copilot] Forking session ${u} at turnId=${t.fork.turnId}`);let m=await(this._findAnySession(u)??await this._resumeSession(u)).getNextTurnEventId(t.fork.turnId),y=(await a.rpc.sessions.fork({sessionId:u,...m?{toEventId:m}:{}})).sessionId,S=this._sessionDataService.getSessionDataDirById(y),b=v.joinPath(S,ea);try{let A=await this._sessionDataService.tryOpenDatabase(t.fork.session);if(A)try{await zt.mkdir(S.fsPath,{recursive:!0}),await zt.rm(b.fsPath,{force:!0}),await A.object.vacuumInto(b.fsPath)}finally{A.dispose()}}catch(A){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${A instanceof Error?A.message:String(A)}`)}let I=await this._resumeSession(y);t.fork.turnIdMapping&&await I.remapTurnIds(t.fork.turnIdMapping);let _=I.sessionUri;this._logService.info(`[Copilot] Forked session created: ${_.toString()}`);try{await this._reviewService.copyReviewedRef(t.fork.session.toString(),_.toString(),s)}catch(A){this._logService.warn(`[Copilot] Failed to copy reviewed ref for fork: ${A instanceof Error?A.message:String(A)}`)}let R=await ar({cwd:s.fsPath},this._gitService);return await this._storeSessionMetadata(_,t.model,s,s,R,!0),t.agent!==void 0&&await this._storeSessionAgentMetadata(_,t.agent),{session:_,workingDirectory:s,...R?{project:R}:{}}})}let l=L.uri(this.id,r);if(this._findAnySession(r)){this._logService.info(`[Copilot] createSession is a no-op: session already materialized: ${l.toString()}`);let u=await ar({cwd:s.fsPath},this._gitService);return{session:l,workingDirectory:s,...u?{project:u}:{}}}let d=this._provisionalSessions.has(r);if(t.activeClient){let u=this._getOrCreateActiveClient(l,s),p=t.activeClient;u.toolSet.set(p.clientId,p.tools),u.getOrCreateHandle(p.clientId,p.displayName),p.customizations!==void 0&&await u.pluginController.sync(p.clientId,p.customizations,{quiet:!0})}let c=await ar({cwd:s.fsPath},this._gitService);return d||this._provisionalSessions.set(r,{sessionId:r,sessionUri:l,workingDirectory:s,model:t.model,agent:t.agent,project:c,workspaceless:o}),this._logService.info(`[Copilot] Session created (provisional): ${l.toString()}`),{session:l,workingDirectory:s,provisional:!0,...c?{project:c}:{}}}async _materializeProvisional(e,t){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=await this._resolveSessionWorkingDirectory(l,e,t),c=d??r.workingDirectory,u=this._getOrCreateActiveClient(s,c);u.pluginController.reanchor(c);let p=await u.snapshot(),m=this._instantiationService.createInstance(gi,s,d),h,y;try{let b=await this._resolveAgentWhenMaterializing(r,p,d);y=b?.agent;let I={kind:"create",client:o,sessionId:e,workingDirectory:d,resolvedAgentName:b?.name,snapshot:p,activeClientToolSet:u.toolSet,shellManager:m,githubToken:this._githubToken,model:r.model,longContextWindow:this._longContextWindowFor(r.model?.id),freeLongContext:this._isFreeLongContext(r.model?.id),workspaceless:r.workspaceless};h=this._createAgentSession(I,c,u),await h.initializeSession(),this._registerInitializedSession(e,h)}catch(b){throw h?.dispose(),await this._removeCreatedWorktree(e),b}let S=await ar({cwd:d?.fsPath},this._gitService);return this._provisionalSessions.delete(e),await this._storeSessionMetadata(s,r.model,d,c,S,!0),y!==void 0&&await this._storeSessionAgentMetadata(s,y),this._checkpointService.captureBaseline(s,d).catch(b=>{this._logService.warn(`[Copilot:${e}] Baseline checkpoint capture failed: ${b instanceof Error?b.message:String(b)}`)}),this._logService.info(`[Copilot] Session materialized: ${s.toString()}`),this._onDidMaterializeSession.fire({session:s,workingDirectory:d,project:S}),h}async _resolveAgentWhenMaterializing(e,t,r){let o=e.agent;if(!o)return;let s=this._getAlternativeAgentForWorktree(e,r),[a,l]=await Promise.all([this._resolveAgentName(e.sessionUri,t,o),s?this._resolveAgentName(e.sessionUri,t,s):Promise.resolve(void 0)]);if(a)return{agent:o,name:a};if(l&&s)return this._logService.info(`[Copilot] Agent file ${o.uri} is in the original repo; using worktree agent ${s?.uri}`),{agent:s,name:l}}_getAlternativeAgentForWorktree(e,t){let r=e.agent;if(!r||!e.workingDirectory||!t||gr(e.workingDirectory,t))return;let o=v.parse(r.uri),s=w1(o,e.workingDirectory,t);return s?{uri:s.toString()}:void 0}async resolveSessionConfig(e){let t=e.workingDirectory?await this._getGitInfo(e.workingDirectory):void 0,r=we({type:"string",title:f(2177,null),description:f(2182,null),enum:t?["folder","worktree"]:["folder"],enumLabels:t?[f(2178,null),f(2180,null)]:[f(2178,null)],enumDescriptions:t?[f(2179,null),f(2181,null)]:[f(2179,null)],default:t?"worktree":"folder",readOnly:!t,sessionMutable:!1}),o=t?"worktree":"folder",s=r.validate(e.config?.isolation)?e.config.isolation:o,a,l;if(t){let u=s==="folder";l=s==="worktree"?t.defaultBranch:t.currentBranch,a=we({type:"string",title:f(2175,null),description:f(2176,null),enum:[l],enumLabels:[l],default:l,enumDynamic:!u,readOnly:u,sessionMutable:!1})}let d=pn({isolation:r,...Jt.definition,...a?{branch:a}:{}}),c=d.validateOrDefault(uT(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}))}}getOrCreateActiveClient(e,t){let r=this._getOrCreateActiveClient(e,void 0);return r.pluginController.directory||this._getSessionCustomizationDirectory(e).then(o=>r.pluginController.setDirectory(o),()=>{}),r.getOrCreateHandle(t.clientId,t.displayName)}removeActiveClient(e,t){let r=L.id(e);this._logService.info(`[Copilot:${r}] removeActiveClient: clientId=${t}`),this._activeClients.get(e)?.removeClient(t)}onClientToolCallComplete(e,t,r,o){let s=L.id(e);if(Ue(t)){let a=this._findAnySession(s);if(!a){this._logService.warn(`[Copilot:${s}] Dropping client tool completion for missing default chat: chat=${t.toString()}, toolCallId=${r}, success=${o.success}`);return}this._logService.info(`[Copilot:${s}] Routing client tool completion to default chat: chat=${t.toString()}, toolCallId=${r}, success=${o.success}`),a.handleClientToolCallComplete(r,o)}else{let a=this._findPeerChat(e,t);if(!a){this._logService.warn(`[Copilot:${s}] Dropping client tool completion for missing peer chat: chat=${t.toString()}, toolCallId=${r}, success=${o.success}`);return}this._logService.info(`[Copilot:${s}] Routing client tool completion to peer chat: chat=${t.toString()}, toolCallId=${r}, success=${o.success}`),a.handleClientToolCallComplete(r,o)}}setCustomizationEnabled(e,t){for(let r of this._activeClients.values())r.pluginController.setEnabled(e,t)}async _sendMessage(e,t,r,o,s){let a=this._getChatContext(e);if(a.isPeerChat){let l=await this._ensureChatSession(a.session,e);if(!l)throw new Error(`[Copilot] sendMessage for unknown chat: ${e.toString()}`);o&&l.resetTurnState(o,s),await l.send(t,r,o,this._resolveSdkMode(a.session),s);return}await this._sessionSequencer.queue(a.sessionId,async()=>{await this._activeClients.get(a.session)?.pluginController.retryFailedClientSyncIfNeeded();let l;this._provisionalSessions.has(a.sessionId)?l=await this._materializeProvisional(a.sessionId,t):l=this._getChatContext(e).target;let d=this._activeClients.get(a.session),c=!!l;this._logService.info(`[Copilot:${a.sessionId}] sendMessage: cachedEntry=${c}, hasActiveClient=${!!d}, activeClientId=${d?"(set)":"(none)"}`),l&&d&&await d.requiresRestart(l.appliedSnapshot)&&(this._logService.info(`[Copilot:${a.sessionId}] Session config changed (requiresRestart=true), refreshing session. clients=[${[...d.toolSet.clientIds()].join(", ")||"(none)"}]`),this._sessions.get(a.sessionId)?.clearDefaultChat(),l=void 0),l||this._logService.info(`[Copilot:${a.sessionId}] No cached entry${c?" (was evicted by requiresRestart)":""}, calling _resumeSession`),l??=await this._resumeSession(a.sessionId),o&&l.resetTurnState(o,s);let u=this._pendingFirstTurnAnnouncements.get(a.sessionId);u!==void 0&&(this._pendingFirstTurnAnnouncements.delete(a.sessionId),l.emitInitialMarkdown(u));try{let p=this._resolveSdkMode(a.session);await l.send(t,r,o,p,s)}catch(p){let m=p?.code,h=p instanceof Error?p.message:String(p);throw this._logService.error(`[Copilot:${a.sessionId}] entry.send() failed: code=${m}, message=${h}, hadCachedEntry=${c}, errorType=${p?.constructor?.name}`),p}})}_resolveSdkMode(e){let t=e.toString();switch(this._configurationService.getEffectiveValue(t,Jt,"mode")){case"plan":return"plan";case"autopilot":return"autopilot";case"interactive":return"interactive";default:return}}setPendingMessages(e,t,r){let o=L.id(e),s=this._findAnySession(o);if(!s){this._logService.warn(`[Copilot:${o}] setPendingMessages: session not found`);return}t&&s.sendSteering(t)}async getSessionMessages(e){let t=gt(e);if(t){let c=t.parentSession,u;for(;u=gt(c);)c=u.parentSession;let p=L.id(c),m=this._findAnySession(p)??await this._resumeSession(p).catch(h=>{this._logService.warn(`[Copilot:${p}] Failed to resume root for subagent restore`,h)});return m?m.getSubagentMessages(t.toolCallId):[]}let r=He(e)?e:v.parse(be(e)),o=this._getChatContext(r);if(o.isPeerChat){let c=await this._ensureChatSession(o.session,r);return c?c.getMessages():[]}let s=o.sessionId;if(this._provisionalSessions.has(s))return[];let a=o.target??await this._resumeSession(s).catch(c=>{this._logService.warn(`[Copilot:${s}] Failed to resume session for message lookup`,c)});if(!a)return[];let l=await a.getMessages(),d=await this._readWorktreeMetadata(o.session).catch(c=>{this._logService.warn(`[Copilot:${s}] Failed to read worktree branch metadata`,c)});return d?.branchName?y4(l,_1(d.branchName)):l}async getSubagentSessions(e){if(He(e)&&!Ue(e))return[];if(gt(e))return[];let r=L.id(e);if(this._provisionalSessions.has(r))return[];let o=this._findAnySession(r)??await this._resumeSession(r).catch(s=>{this._logService.warn(`[Copilot:${r}] Failed to resume session for subagent lookup`,s)});return o?o.getSubagentSessions():[]}async disposeSession(e){let t=L.id(e);await this._sessionSequencer.queue(t,async()=>{let r=this._provisionalSessions.get(t),o=r?r.workspaceless===!0:(await this._readSessionMetadata(e).catch(()=>{}))?.workspaceless===!0;this._provisionalSessions.has(t)||await(await this._ensureClient()).deleteSession(t),await this._destroyAndDisposeSession(t),o&&await this._cleanupWorkspacelessScratchDir(this._workspacelessScratchDir(t),t)})}async onArchivedChanged(e,t){let r=L.id(e);await this._sessionSequencer.queue(r,async()=>{t?await this._cleanupWorktreeOnArchive(e,r):await this._recreateWorktreeOnUnarchive(e,r)})}async _cleanupWorktreeOnArchive(e,t){let r=await this._readWorktreeMetadata(e).catch(()=>{});if(!r?.worktreePath||!r.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=r;try{await zt.access(s.fsPath)}catch{this._createdWorktrees.delete(t);return}if(!await this._gitService.branchExists(a,o).catch(()=>!1)){this._logService.info(`[Copilot:${t}] Skipping worktree cleanup: branch '${o}' is missing`);return}if(await this._gitService.hasUncommittedChanges(s).catch(()=>!0)){this._logService.info(`[Copilot:${t}] Skipping worktree cleanup: '${s.fsPath}' has uncommitted changes`);return}try{await this._gitService.removeWorktree(a,s),this._logService.info(`[Copilot:${t}] Removed worktree '${s.fsPath}' on archive`)}catch(c){this._logService.warn(`[Copilot:${t}] Failed to remove worktree '${s.fsPath}' on archive: ${c instanceof Error?c.message:String(c)}`)}finally{this._createdWorktrees.delete(t)}}async _recreateWorktreeOnUnarchive(e,t){let r=await this._readWorktreeMetadata(e).catch(()=>{});if(!r?.worktreePath||!r.repositoryRoot)return;let{branchName:o,worktreePath:s,repositoryRoot:a}=r;try{await zt.access(s.fsPath);return}catch{}if(!await this._gitService.branchExists(a,o).catch(()=>!1)){this._logService.info(`[Copilot:${t}] Skipping worktree recreation: branch '${o}' is missing`);return}try{await zt.mkdir(v.joinPath(s,"..").fsPath,{recursive:!0}),await this._gitService.addExistingWorktree(a,s,o),this._createdWorktrees.set(t,{repositoryRoot:a,worktree:s}),this._logService.info(`[Copilot:${t}] Recreated worktree '${s.fsPath}' on unarchive`)}catch(d){this._logService.warn(`[Copilot:${t}] Failed to recreate worktree '${s.fsPath}' on unarchive: ${d instanceof Error?d.message:String(d)}`)}}async _abortSession(e){let t=this._getChatContext(e);if(t.isPeerChat){await t.target?.abort();return}await this._sessionSequencer.queue(t.sessionId,async()=>{await this._getChatContext(e).target?.abort()})}async _createChat(e,t){if(Ue(e))return;let r=He(e);if(!r)throw new Error(`[Copilot] createChat: malformed chat URI ${e.toString()}`);let o=v.parse(r.session),s=e.toString();if(this._sessions.get(L.id(o))?.hasPeerChat(s)){let d=this._chatBackings.get(s);return d?{providerData:Er(d),backingSession:L.uri(this.id,d.sdkSessionId)}:void 0}let a=L.id(o),l;return await this._sessionSequencer.queue(a,async()=>{if(this._sessions.get(a)?.hasPeerChat(s)){let R=this._chatBackings.get(s);l=R?{providerData:Er(R),backingSession:L.uri(this.id,R.sdkSessionId)}:void 0;return}let d=t?.model,u=this._findAnySession(a)?.workingDirectory??this._provisionalSessions.get(a)?.workingDirectory,p=await this._ensureClient(),m=H(),h=this._getOrCreateActiveClient(o,u),y=await h.snapshot(),S=this._instantiationService.createInstance(gi,e,u),b,I;if(t?.fork){if(!u)throw new Error(`[Copilot] createChat fork: missing working directory for session ${o.toString()}`);let R=await this._resolveChatEntry(o,t.fork.source);if(!R)throw new Error(`[Copilot] createChat fork: source chat ${t.fork.source.toString()} not found`);I=await this._forkSdkChat(p,R,t.fork.turnId,this._sessionDataService.getSessionDataDir(e)),b={kind:"resume",client:p,sessionId:I,workingDirectory:u,resolvedAgentName:void 0,snapshot:y,activeClientToolSet:h.toolSet,shellManager:S,githubToken:this._githubToken,fallback:{model:d,longContextWindow:this._longContextWindowFor(d?.id),freeLongContext:this._isFreeLongContext(d?.id)}}}else I=m,b={kind:"create",client:p,sessionId:m,workingDirectory:u,resolvedAgentName:void 0,snapshot:y,activeClientToolSet:h.toolSet,shellManager:S,githubToken:this._githubToken,model:d,longContextWindow:this._longContextWindowFor(d?.id),freeLongContext:this._isFreeLongContext(d?.id)};let _;try{_=this._createAgentSession(b,u,h,e),await _.initializeSession(),t?.fork?.turnIdMapping&&await _.remapTurnIds(t.fork.turnIdMapping),this._ensureEntry(a).registerPeerChat(s,new ss(_));let R={sdkSessionId:I,...d?{model:d}:{}};this._chatBackings.set(s,R),l={providerData:Er(R),backingSession:L.uri(this.id,I)},this._logService.info(`[Copilot] Created additional chat ${s} in session ${o.toString()}${t?.fork?" (forked)":""}`)}catch(R){throw _?.dispose(),R}}),l}async _resolveChatEntry(e,t){let r=L.id(e);return Ue(t)||gr(t,e)?this._findAnySession(r)??await this._resumeSession(r).catch(()=>{}):this._ensureChatSession(e,t)}async _forkSdkChat(e,t,r,o){let s=await t.getNextTurnEventId(r),l=(await e.rpc.sessions.fork({sessionId:t.sessionId,...s?{toEventId:s}:{}})).sessionId,d=v.joinPath(o,ea);try{let c=await this._sessionDataService.tryOpenDatabase(t.sessionUri);if(c)try{await zt.mkdir(o.fsPath,{recursive:!0}),await zt.rm(d.fsPath,{force:!0}),await c.object.vacuumInto(d.fsPath)}finally{c.dispose()}}catch(c){this._logService.warn(`[Copilot] Failed to copy session database for chat fork: ${c instanceof Error?c.message:String(c)}`)}return l}async _disposeChat(e,t){if(Ue(t))return;let r=t.toString(),o=this._findPeerChat(e,t)?.sessionId??this._chatBackings.get(r)?.sdkSessionId;if(!o){let s=He(t);s&&(o=(await this._readPersistedChats(e)).get(s.chatId)?.sdkSessionId)}if(this._chatBackings.delete(r),this._sessions.get(L.id(e))?.disposePeerChat(r),o)try{await(await this._ensureClient()).deleteSession(o)}catch(s){this._logService.warn(`[Copilot] Failed to delete SDK session for chat ${r}: ${s instanceof Error?s.message:String(s)}`)}}async materializeChat(e,t){if(Ue(e))return;let r=He(e);if(!r)return;let o=e.toString(),s;if(t!==void 0){if(s=Jg(t),!s){this._logService.warn(`[Copilot] materializeChat: dropping corrupt providerData for ${o}`);return}}else if(s=(await this._readPersistedChats(v.parse(r.session))).get(r.chatId),!s)return;this._chatBackings.set(o,s)}async listLegacyChats(e){let t=await this._readPersistedChats(e),r=[];for(let[o,s]of t)r.push({uri:v.parse(Ty(e,o)),providerData:Er(s)});return r}async _resolveChatBacking(e,t){let r=t.toString(),o=this._chatBackings.get(r);if(o)return o;let s=He(t);if(!s)return;let l=(await this._readPersistedChats(e)).get(s.chatId);return l&&this._chatBackings.set(r,l),l}async _ensureChatSession(e,t){let r=t.toString(),o=this._findPeerChat(e,t);if(o)return o;if(!He(t))return;let a=L.id(e);return this._sessionSequencer.queue(a,async()=>{let l=this._findPeerChat(e,t);if(l)return l;let d=await this._resolveChatBacking(e,t);if(!d)return;let u=(this._findAnySession(a)??await this._resumeSession(a).catch(()=>{}))?.workingDirectory??this._provisionalSessions.get(a)?.workingDirectory;if(!u){this._logService.warn(`[Copilot] Cannot resume chat ${r}: missing working directory`);return}let p=await this._ensureClient(),m=this._getOrCreateActiveClient(e,u),h=await m.snapshot(),y=this._instantiationService.createInstance(gi,t,u),S={kind:"resume",client:p,sessionId:d.sdkSessionId,workingDirectory:u,resolvedAgentName:void 0,snapshot:h,activeClientToolSet:m.toolSet,shellManager:y,githubToken:this._githubToken,fallback:{model:d.model,longContextWindow:this._longContextWindowFor(d.model?.id),freeLongContext:this._isFreeLongContext(d.model?.id)}},b;try{return b=this._createAgentSession(S,u,m,t),await b.initializeSession(),this._ensureEntry(a).registerPeerChat(r,new ss(b)),this._logService.info(`[Copilot] Resumed additional chat ${r} in session ${e.toString()}`),b}catch(I){b?.dispose(),this._logService.warn(`[Copilot] Failed to resume additional chat ${r}: ${I instanceof Error?I.message:String(I)}`);return}})}async truncateSession(e,t,r){let o=L.id(e);if(this._provisionalSessions.has(o))return;let s=!Ue(r);await this._sessionSequencer.queue(o,async()=>{this._logService.info(`[Copilot:${o}] Truncating ${s?`peer chat ${r.toString()}`:"session"}${t!==void 0?` at turnId=${t}`:" (all turns)"}`);let a=s?await this._resolveChatEntry(e,r):this._findAnySession(o)??await this._resumeSession(o);if(!a){this._logService.info(`[Copilot:${o}] No chat entry resolved for truncation; nothing to truncate`);return}let l;t?l=await a.getNextTurnEventId(t):l=await a.getFirstTurnEventId(),l?await a.truncateAtEventId(l,t):this._logService.info(`[Copilot:${o}] No event ID found for truncation, nothing to truncate`),this._logService.info(`[Copilot:${o}] Session truncated`)})}async _changeModel(e,t){let r=this._longContextWindowFor(t.id),o=this._isFreeLongContext(t.id),s=this._getChatContext(e);if(s.isPeerChat){await s.target?.setModel(t.id,mm(t),hm(t,r,o));let d=this._chatBackings.get(s.chatKey);if(d){let c={sdkSessionId:d.sdkSessionId,model:t};this._chatBackings.set(s.chatKey,c),this._onDidChangeChatData.fire({chat:e,providerData:Er(c)})}return}let a=this._provisionalSessions.get(s.sessionId);if(a){a.model=t;return}let l=s.target;l&&await l.setModel(t.id,mm(t),hm(t,r,o)),await this._storeSessionMetadata(s.session,t,void 0,void 0,void 0)}async _changeAgent(e,t){let r=this._getChatContext(e);if(r.isPeerChat){if(r.target){let a=t?await this._resolveAgentName(r.session,r.target.appliedSnapshot,t):void 0;await r.target.setAgent(a)}return}let o=this._provisionalSessions.get(r.sessionId);if(o){o.agent=t;return}let s=r.target;if(s){let a=t?await this._resolveAgentName(r.session,s.appliedSnapshot,t):void 0;await s.setAgent(a)}await this._storeSessionAgentMetadata(r.session,t)}async shutdown(){return this._shutdownPromise??=(async()=>{this._modelRefreshRetry.clear(),this._logService.info("[Copilot] Shutting down...");let e=new Set([...this._sessions.keys(),...this._createdWorktrees.keys()]);for(let t of e)await this._sessionSequencer.queue(t,()=>this._destroyAndDisposeSession(t));await this._client?.stop(),this._client=void 0,await this._sessionLauncher.disposeByokProxyHandle()})(),this._shutdownPromise}respondToPermissionRequest(e,t){for(let r of this._sessions.values())for(let o of r.allChatSessions())if(o.respondToPermissionRequest(e,t))return}respondToUserInputRequest(e,t,r){for(let o of this._sessions.values())for(let s of o.allChatSessions())if(s.respondToUserInputRequest(e,t,r))return}hasSession(e){let t=L.id(e);return this._sessions.has(t)||this._provisionalSessions.has(t)}async _configureProxyEnv(e){let t=await this._resolveProxyForSdk(e);if(this._appliedProxy=t,t){for(let r of d4)e[r]=t;this._logService.info("[Copilot] Resolved CAPI proxy and forwarded HTTP_PROXY/HTTPS_PROXY to Copilot SDK")}}async _resolveProxyForSdk(e=process.env){if(l4.some(r=>e[r])){this._logService.debug("[Copilot] Proxy env var already set; leaving Copilot SDK proxy configuration to the environment");return}let t=e.VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE||a4;if(this._githubToken)try{let r=await this._copilotApiService.resolveApiEndpoint(this._githubToken);r&&(t=r)}catch(r){this._logService.debug(`[Copilot] CAPI endpoint discovery for proxy resolution failed; using ${t}: ${r instanceof Error?r.message:String(r)}`)}try{return await this._proxyResolver.resolveProxy(t)}catch(r){this._logService.warn(`[Copilot] Failed to resolve CAPI proxy for ${t}: ${r instanceof Error?r.message:String(r)}`);return}}async _restartClientIfProxyChanged(){if(!this._client&&!this._clientStarting)return;let e=this._appliedProxy,t=await this._resolveProxyForSdk();if(t!==e){if(this._clientStarting)try{await this._clientStarting}catch{}this._client&&(this._logService.info(`[Copilot] CAPI proxy changed after token update (${e??"(none)"} -> ${t??"(none)"}); restarting CopilotClient`),this._sessions.clearAndDisposeAll(),this._mcpNotificationSubs.clearAndDisposeAll(),await this._stopClient())}}_disposeChildChats(e){let t=this._sessions.get(e);if(t)for(let r of t.peerChatKeys())t.disposePeerChat(r);for(let r of[...this._chatBackings.keys()]){let o=He(v.parse(r));o&&L.id(o.session)===e&&this._chatBackings.delete(r)}}_getOrCreateActiveClient(e,t){let r=this._activeClients.get(e);if(r)t&&r.pluginController.setDirectory(t);else{let o=this._plugins.createSessionController(t);r=this._instantiationService.createInstance(Zc,e,o,this._onDidSessionProgress),this._activeClients.set(e,r)}return r}_createAgentSession(e,t,r,o){let s=o??L.uri(this.id,e.sessionId),a=o??v.parse(be(s)),l=this._instantiationService.createInstance(gl,{sessionUri:s,chatChannelUri:a,rawSessionId:e.sessionId,onDidSessionProgress:this._onDidSessionProgress,sessionLauncher:this._sessionLauncher,launchPlan:e,shellManager:e.shellManager,workingDirectory:e.workingDirectory,customizationDirectory:t,clientSnapshot:e.snapshot,activeClientToolSet:e.activeClientToolSet,resolveMcpChildId:d=>Dg(r.pluginController.getCustomizations(),d),serverToolHost:this._serverToolHost});return this._mcpNotificationSubs.set(e.sessionId,_u(l.onMcpNotification(d=>this._onMcpNotification.fire(d)),Wn(d=>r.pluginController.mcpServerStates.set(l.mcpServerStates.read(d),void 0)))),l}_registerInitializedSession(e,t){if(this._shutdownPromise)throw t.dispose(),new Y;let r=be(t.sessionUri.toString()),o=this._sessions.get(e);o||(o=new ss,this._sessions.set(e,o)),o.setDefaultChat(r,new ss(t))}async _destroyAndDisposeSession(e){this._disposeChildChats(e);let t=this._provisionalSessions.get(e);if(t){this._provisionalSessions.delete(e),this._sessions.deleteAndDispose(e),this._activeClients.get(t.sessionUri)?.dispose(),this._activeClients.delete(t.sessionUri);return}let r=this._findAnySession(e),o=L.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 t=this._resumingSessions.get(e);if(t)return t;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 t=await this._ensureClient(),r=L.uri(this.id,e),o=await this._readSessionMetadata(r),s=await t.getSessionMetadata(e).catch(y=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,y)}),a=o.workingDirectory??(typeof s?.context?.workingDirectory=="string"?v.file(s.context.workingDirectory):void 0);if(!a)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);o.workspaceless&&await this._ensureWorkspacelessScratchDir(a,e);let l=a,d=this._getOrCreateActiveClient(r,l);d.pluginController.reanchor(l);let c=await d.snapshot(),u=this._instantiationService.createInstance(gi,r,a),p=o.agent?await this._resolveAgentName(r,c,o.agent):void 0,m={kind:"resume",client:t,sessionId:e,workingDirectory:a,resolvedAgentName:p,snapshot:c,activeClientToolSet:d.toolSet,shellManager:u,githubToken:this._githubToken,workspaceless:o.workspaceless,fallback:{model:o.model,longContextWindow:this._longContextWindowFor(o.model?.id),freeLongContext:this._isFreeLongContext(o.model?.id)}},h=this._createAgentSession(m,l,d);try{await h.initializeSession()}catch(y){throw h.dispose(),y}return this._registerInitializedSession(e,h),h}async _getGitInfo(e){let t=await this._gitService.getRepositoryRoot(e);if(!t||!await this._gitService.revParse(t,"HEAD").catch(()=>{}))return;let o=await this._gitService.getCurrentBranch(t)??"HEAD",s=await this._gitService.getDefaultBranch(t)??o;return{currentBranch:o,defaultBranch:s}}async _getBranches(e,t){return this._gitService.getBranches(e,{query:t,limit:Pe._BRANCH_COMPLETION_LIMIT})}async _resolveSessionWorkingDirectory(e,t,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=g4(o),a=await this._branchNameGenerator.generateBranchName({sessionId:t,message:r,githubToken:this._githubToken,branchExists:u=>this._gitService.branchExists(o,u).catch(()=>!0)}),l=v.joinPath(s,m4(a));await zt.mkdir(s.fsPath,{recursive:!0});let d=typeof e.config.branch=="string"?e.config.branch:void 0;await this._gitService.addWorktree(o,l,a,d),this._createdWorktrees.set(t,{repositoryRoot:o,worktree:l}),this._pendingFirstTurnAnnouncements.set(t,_1(a));let c=L.uri(this.id,t);try{await this._writeWorktreeMetadata(c,{branchName:a,baseBranch:d,worktreePath:l,repositoryRoot:o})}catch(u){this._logService.warn(`[Copilot:${t}] Failed to persist worktree branch metadata: ${u instanceof Error?u.message:String(u)}`)}return l}async _removeCreatedWorktree(e){let t=this._createdWorktrees.get(e);if(t)try{await this._gitService.removeWorktree(t.repositoryRoot,t.worktree)}catch(r){this._logService.warn(`[Copilot:${e}] Failed to remove worktree '${t.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"}static{this._META_CHATS="copilot.chats"}async _readPersistedChats(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(!t)return new Map;try{let r=await t.object.getMetadata(Pe._META_CHATS);if(!r)return new Map;let o=JSON.parse(r),s=new Map;for(let[a,l]of Object.entries(o)){if(!l||typeof l!="object")continue;let{sdkSessionId:d,model:c}=l;typeof d!="string"||!d||s.set(a,{sdkSessionId:d,...c?{model:c}:{}})}return s}catch(r){return this._logService.warn(`[Copilot] Failed to read persisted chats for ${e.toString()}: ${r instanceof Error?r.message:String(r)}`),new Map}finally{t.dispose()}}async _writeWorktreeMetadata(e,t){let r=this._sessionDataService.openDatabase(e);try{let o=[r.object.setMetadata(Pe._META_WORKTREE_BRANCH,t.branchName),r.object.setMetadata(Pe._META_WORKTREE_PATH,t.worktreePath.toString()),r.object.setMetadata(Pe._META_WORKTREE_REPOSITORY_ROOT,t.repositoryRoot.toString())];t.baseBranch&&o.push(r.object.setMetadata(ca,t.baseBranch)),await Promise.all(o)}finally{r.dispose()}}async _readWorktreeMetadata(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(t)try{let[r,o,s]=await Promise.all([t.object.getMetadata(Pe._META_WORKTREE_BRANCH),t.object.getMetadata(Pe._META_WORKTREE_PATH),t.object.getMetadata(Pe._META_WORKTREE_REPOSITORY_ROOT)]);if(!r)return;let a=o?v.parse(o):void 0,l=s?v.parse(s):void 0;return{branchName:r,worktreePath:a,repositoryRoot:l}}finally{t.dispose()}}async _storeSessionMetadata(e,t,r,o,s,a=s!==void 0){let l=this._sessionDataService.openDatabase(e),d=l.object;try{let c=[];t&&c.push(d.setMetadata(Pe._META_MODEL,this._serializeModelSelection(t))),r&&c.push(d.setMetadata(Pe._META_CWD,r.toString())),o&&c.push(d.setMetadata(Pe._META_CUSTOMIZATION_DIRECTORY,o.toString())),a&&c.push(d.setMetadata(Pe._META_PROJECT_RESOLVED,"true")),s&&(c.push(d.setMetadata(Pe._META_PROJECT_URI,s.uri.toString())),c.push(d.setMetadata(Pe._META_PROJECT_DISPLAY_NAME,s.displayName))),await Promise.all(c)}finally{l.dispose()}}async _readSessionMetadata(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(!t)return{};try{let[r,o,s,a,l]=await Promise.all([t.object.getMetadata(Pe._META_MODEL),t.object.getMetadata(Pe._META_AGENT),t.object.getMetadata(Pe._META_CWD),t.object.getMetadata(Pe._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(Fn)]);return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(o),workingDirectory:s?v.parse(s):void 0,customizationDirectory:a?v.parse(a):void 0,workspaceless:l==="true"}}finally{t.dispose()}}async _readStoredSessionMetadata(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(t)try{let[r,o,s,a,l,d,c,u]=await Promise.all([t.object.getMetadata(Pe._META_MODEL),t.object.getMetadata(Pe._META_AGENT),t.object.getMetadata(Pe._META_CWD),t.object.getMetadata(Pe._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(Pe._META_PROJECT_RESOLVED),t.object.getMetadata(Pe._META_PROJECT_URI),t.object.getMetadata(Pe._META_PROJECT_DISPLAY_NAME),t.object.getMetadata(Fn)]),p=s?v.parse(s):void 0,m=d&&c?{uri:v.parse(d),displayName:c}:void 0;return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(o),workingDirectory:p,customizationDirectory:a?v.parse(a):void 0,project:m,resolved:l==="true"||m!==void 0,workspaceless:u==="true"}}finally{t.dispose()}}async _storeSessionAgentMetadata(e,t){let r=this._sessionDataService.openDatabase(e);try{await r.object.setMetadata(Pe._META_AGENT,t?this._serializeAgentSelection(t):"")}finally{r.dispose()}}async _storeSessionProjectResolution(e,t){await this._storeSessionMetadata(e,void 0,void 0,void 0,t,!0)}_resolveSessionProject(e,t,r){let o=this._projectContextKey(e);if(!o)return Promise.resolve(void 0);let s=r.get(o);return s||(s=t.queue(()=>ar(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())}};Pe=w([C(0,D),C(1,Ie),C(2,Je),C(3,Ye),C(4,ze),C(5,Yg),C(6,em),C(7,Jf),C(8,_r),C(9,to),C(10,Rt),C(11,ao),C(12,Hn),C(13,It),C(14,Qg)],Pe);var v4=100,lb=class extends T{constructor(e,t,r,o,s){super();this._onDidRefresh=r;this._logService=o;this._refreshDelayer=this._register(new Po(v4));this._refreshPromise=null;this._pendingRefreshNotify=!1;this._customizations=[];this._discovery=this._register(s.createInstance(ml,e,t)),this._fileService=s.invokeFunction(a=>a.get(xe)),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 t=this._pendingRefreshNotify;this._pendingRefreshNotify=!1;let r=this._refreshPromise=Mi(async o=>{await this._refresh(o)&&t&&this._onDidRefresh()});return r.then(()=>{this._refreshPromise===r&&(this._refreshPromise=null)},o=>{if(this._refreshPromise===r&&(this._refreshPromise=null),!(o instanceof Y))throw o})})}async _refresh(e){try{let t=await this._discovery.scan(e);if(e.isCancellationRequested||this._directories&&C1(this._directories,t))return!1;let r=await S4(t,this._fileService);return e.isCancellationRequested?!1:(this._customizations=r,this._directories=t,!0)}catch(t){if(e.isCancellationRequested)return!1;this._logService.warn(`[Copilot:SessionDiscoveredEntry] Discovery/bundle failed: ${t instanceof Error?t.message:String(t)}`);let r=this._customizations.length>0||this._directories!==void 0;return this._customizations=[],this._directories=void 0,r}}};function S4(i,n){return Promise.all(i.map(async e=>{let t=e.uri.toString();return{type:"directory",id:Ot(t),uri:t,name:e.name,enabled:!0,contents:b4(e.type),writable:e.writable,load:{kind:"loaded"},children:await Promise.all(e.files.map(r=>C4(r.uri,e.type,n)))}}))}function b4(i){switch(i){case"agent":return"agent";case"skill":return"skill";case"instruction":case"agentInstruction":return"rule";case"hook":return"hook"}}async function C4(i,n,e){let t=i.toString(),r=Ot(t);if(n==="agent"){let o=await Lc(i,e),s={type:"agent",id:r,uri:t,name:o.name,description:o.description};return o.userInvocable!==void 0&&(s._meta={userInvocable:o.userInvocable}),s}if(n==="skill"){let o=await WS(i,e);return{type:"skill",id:r,uri:t,name:o.name,description:o.description}}if(n==="instruction"){let o=await Vg(i,e);return{type:"rule",id:r,uri:t,name:o.name,description:o.description,globs:o.globs,alwaysApply:o.alwaysApply}}return n==="hook"?{type:"hook",id:r,uri:t,name:pe(i)}:{type:"rule",alwaysApply:!0,id:r,uri:t,name:pe(i)}}function I4(i){if(i.length===0)return;let n=[],e=[],t=[];for(let r of i)for(let o of r.children??[]){if(o.type==="agent"){n.push({uri:v.parse(o.uri),name:o.name,description:o.description,customization:o});continue}if(o.type==="skill"){e.push({uri:v.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;t.push({uri:v.parse(o.uri),name:o.name,description:o.description,customization:o})}}if(!(n.length===0&&e.length===0&&t.length===0))return{hooks:[],mcpServers:[],skills:e,agents:n,instructions:t}}var Xc=class extends T{constructor(e,t,r,o,s,a){super();this.pluginManager=e;this.logService=t;this.fileService=r;this._configurationService=o;this.instantiationService=s;this._environmentService=a;this._onDidChange=this._register(new P);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 this._environmentService.userHome}createSessionController(e){return new db(this,e)}_applyHostCustomizations(){let t=(this._configurationService.getRootValue(qt,"customizations")??[]).map(gw);if(Fe(t,this._lastAppliedRefs))return;this._lastAppliedRefs=t;let r=++this._hostRevision;this._hostCustomizations=t.map(o=>({customization:{...o,load:{kind:"loading"}}})),this._onDidChange.fire(),this._hostSync=Promise.all(t.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 t=v.parse(e.uri),r=await this.tryParsePlugin(t);return r?{customization:{...e,load:{kind:"loaded"},children:YS([r])},pluginDir:t,plugin:r}:{customization:{...e,load:{kind:"error",message:f(2190,null)}}}}async resolveSyncedCustomization(e,t,r){let o={...e.customization,clientId:t};if(!e.pluginDir)return{customization:o,input:r};let s=await this.tryParsePlugin(e.pluginDir);return s?{customization:{...o,children:YS([s])},pluginDir:e.pluginDir,plugin:s,input:r}:{customization:{...o,load:{kind:"error",message:f(2190,null)}},input:r}}async tryParsePlugin(e){try{return await jg(e,this.fileService,void 0,this.getUserHome())}catch(t){this.logService.warn(`[Copilot:PluginController] Error parsing plugin '${e.toString()}': ${t instanceof Error?t.message:String(t)}`);return}}};Xc=w([C(0,nl),C(1,D),C(2,xe),C(3,ze),C(4,Ie),C(5,Rt)],Xc);var db=class extends T{constructor(e,t){super();this._parent=e;this._directory=t;this._onDidPublish=this._register(new P);this.onDidPublish=this._onDidPublish.event;this._enablement=new Map;this.mcpServerStates=nn(this,new Map);this._clients=new Map;this._sessionDiscovered=this._register(new At)}get directory(){return this._directory}setDirectory(e){this._directory||!e||(this._directory=e)}reanchor(e){if(this._directory&&gr(this._directory,e))return;let t=this._directory;this._directory=e,this._sessionDiscovered.clear(),t&&this._migrateEnablement(t,e)}_migrateEnablement(e,t){let r=h4(this._enablement,e,t);this._enablement.clear();for(let[o,s]of r)this._enablement.set(o,s)}getCustomizations(){let e=[...this._parent.hostCustomizations().map(o=>this._projectForPublish(o.customization)),...this._flattenClientCustomizations().map(o=>this._projectForPublish(o.customization))],r=this._discoveredEntry()?.currentCustomizations()??[];for(let o of r)e.push(this._projectForPublish(o));return e}_flattenClientCustomizations(){let e=new Set,t=[];for(let r of this._clients.values())for(let o of r.customizations)e.has(o.customization.uri)||(e.add(o.customization.uri),t.push(o));return t}async getCustomizationsSettled(){let e=this._discoveredEntry();return await Promise.all([this._parent.hostSync().catch(t=>this._parent.logService.warn("[Copilot:SessionPluginController] Host customization update failed",t)),...[...this._clients.values()].map(t=>t.sync.catch(r=>this._parent.logService.warn("[Copilot:SessionPluginController] Client customization sync failed",r))),e?.whenSettled()]),this.getCustomizations()}async getAppliedPlugins(){let e=this._discoveredEntry(),[t]=await Promise.all([this._parent.hostSync().catch(a=>(this._parent.logService.warn("[Copilot:SessionPluginController] Host customization update failed",a),this._parent.hostCustomizations())),...[...this._clients.values()].map(a=>a.sync.catch(l=>(this._parent.logService.warn("[Copilot:SessionPluginController] Client customization sync failed",l),a.customizations))),e?.whenSettled()]),r=e?.currentCustomizations()??[],o=r.some(a=>this._isEnabled(a))?I4(r):void 0,s=o?[o]:[];return[...t.filter(a=>!!a.plugin&&this._isEnabled(a.customization)).map(a=>({...a.plugin,pluginDir:a.pluginDir})),...this._flattenClientCustomizations().filter(a=>!!a.plugin&&this._isEnabled(a.customization)).map(a=>({...a.plugin,pluginDir:a.pluginDir})),...s]}setEnabled(e,t){this._enablement.get(e)!==t&&this._enablement.set(e,t)}sync(e,t,r){let o=r?.quiet===!0,s=this._clients.get(e);if(!s)s={revision:0,customizations:[],sync:Promise.resolve([]),inputs:[]},this._clients.set(e,s);else if(Fe(s.inputs,t))return s.sync.then(p=>p.map(m=>({customization:this._projectForPublish(m.customization),...m.pluginDir?{pluginDir:m.pluginDir}:{}})));let a=++s.revision;s.inputs=t,s.customizations=t.map(p=>({customization:{...p,clientId:e,load:{kind:"loading"}},input:p})),o||this._onDidPublish.fire({type:"session/customizationsChanged",customizations:[...this.getCustomizations()]});let l=new Map;for(let p of s.customizations){let m=this._projectForPublish(p.customization);l.set(m.uri,m)}let d=p=>{let m=this._projectForPublish(p.customization);Fe(l.get(m.uri),m)||(l.set(m.uri,m),o||this._onDidPublish.fire({type:"session/customizationUpdated",customization:m}))},c=s.sync;return(s.sync=c.catch(p=>{this._parent.logService.warn("[Copilot:SessionPluginController] Previous customization sync failed",p)}).then(async()=>{let p=new Map(t.map(y=>[y.uri,y])),m=await this._parent.pluginManager.syncCustomizations(e,t,y=>{a===s.revision&&d({customization:{...y,clientId:e},input:p.get(y.uri)})}),h=await Promise.all(m.map(y=>this._parent.resolveSyncedCustomization(y,e,p.get(y.customization.uri))));if(a===s.revision){s.customizations=h;for(let y of h)d(y)}return h})).then(p=>p.map(m=>({customization:this._overlayMcpState(this._applyEnablement(m.customization)),...m.pluginDir?{pluginDir:m.pluginDir}:{}})))}removeClient(e){let t=this._clients.get(e);t&&(t.revision++,this._clients.delete(e),this._onDidPublish.fire({type:"session/customizationsChanged",customizations:[...this.getCustomizations()]}))}clientInputs(e){return this._clients.get(e)?.inputs??[]}async retryFailedClientSyncIfNeeded(){await Promise.all([...this._clients.values()].map(e=>e.sync.catch(()=>{})));for(let[e,t]of[...this._clients]){let r=t.customizations.filter(s=>s.customization.load?.kind==="error"&&s.input!==void 0);if(r.length===0)continue;let o=r.map(s=>s.input);this._parent.logService.info(`[Copilot:SessionPluginController] Retrying ${o.length} previously-failed client customization(s) for ${e}`),await this.sync(e,o).catch(s=>{this._parent.logService.warn("[Copilot:SessionPluginController] Retried client customization sync failed",s)})}}_discoveredEntry(){if(this._directory)return this._sessionDiscovered.value||(this._sessionDiscovered.value=new lb(this._directory,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 t=this._isEnabled(e);return e.enabled===t?e:{...e,enabled:t}}_projectForPublish(e){return this._overlayMcpState(this._applyEnablement(e))}_overlayMcpState(e){let t=this.mcpServerStates.get();if(t.size===0)return e;if(e.type==="mcpServer"){let a=t.get(e.id);return a?{...e,state:a.state,channel:a.channel}:e}let r=e.children;if(!r||r.length===0)return e;let o=!1,s=r.map(a=>{if(a.type!=="mcpServer")return a;let l=t.get(a.id);return l?(o=!0,{...a,state:l.state,channel:l.channel}):a});return o?{...e,children:s}:e}},cb=class{constructor(n,e,t){this._owner=n;this.clientId=e;this.displayName=t}get tools(){return this._owner.toolSet.get(this.clientId)}set tools(n){this._owner.toolSet.set(this.clientId,n)}get customizations(){return this._owner.pluginController.clientInputs(this.clientId)}set customizations(n){this._owner.pluginController.sync(this.clientId,[...n]).catch(()=>{})}},Zc=class extends T{constructor(e,t,r,o){super();this._sessionUri=e;this._configurationService=o;this.toolSet=new Pn;this._handles=new Map;this.pluginController=this._register(t),this._register(this.pluginController.onDidPublish(s=>{r.fire({kind:"action",resource:this._sessionUri,action:s})}))}getOrCreateHandle(e,t){let r=this._handles.get(e);return r||(r=new cb(this,e,t),this._handles.set(e,r)),r}removeClient(e){this._handles.delete(e),this.toolSet.delete(e),this.pluginController.removeClient(e)}async snapshot(){return{tools:this.toolSet.merged(),plugins:await this.pluginController.getAppliedPlugins(),mcpServers:this._getMcpServers()}}_getMcpServers(){let e=this._configurationService.getRootValue($t,Ly)??{};return structuredClone(e)}async requiresRestart(e){let t=await this.pluginController.getAppliedPlugins();return!BP(e.plugins,t)||!Fe(e.mcpServers,this._getMcpServers())?!0:!this.toolSet.structuralEquals(e.tools)}};Zc=w([C(3,ze)],Zc);function as(i){switch(i){case"default":case"acceptEdits":case"bypassPermissions":case"plan":case"auto":return i;default:return}}var R1="thinkingLevel";function ub(i){if(i!==void 0)return i==="max"?"xhigh":i}function eu(i){let n=i?.config?.[R1];switch(n){case"low":case"medium":case"high":case"xhigh":case"max":return n;default:return}}var _4=["low","medium","high","xhigh","max"];function pb(i){return _4.includes(i)}function fb(i){if(i.length===0)return;let n=i.includes("high")?"high":void 0;return{type:"object",properties:{[R1]:{type:"string",title:f(1956,null),description:f(1955,null),enum:[...i],enumLabels:i.map(ns),enumDescriptions:i.map(e=>rs(e)??""),...n!==void 0?{default:n}:{}}}}}import{pathToFileURL as k1}from"url";import*as A1 from"fs";import*as E1 from"tar";import{familySync as T4,MUSL as w4}from"detect-libc";var Rm,x1=!1;function P1(){return x1||(Oe?Rm=T4()===w4?"musl":"glibc":Rm=void 0,x1=!0),Rm}var R4=new Set(["linux","darwin","win32"]),x4=new Set(["x64","arm64"]);function gb(i,n={platform:process.platform,arch:process.arch,libc:P1()}){if(!(!R4.has(n.platform)||!x4.has(n.arch)))return n.platform==="linux"&&i.hasSeparateMuslLinuxPackage&&n.libc==="musl"?`linux-${n.arch}-musl`:`${n.platform}-${n.arch}`}var yl=$("agentSdkDownloader"),P4=3e4,A4=250;function E4(i){if(typeof i!="string"||!/^\d+$/.test(i))return;let n=parseInt(i,10);return n>0?n:void 0}var hl=class extends T{constructor(e,t,r,o,s){super();this._environmentService=e;this._productService=t;this._requestService=r;this._fileService=o;this._logService=s;this._onDidDownloadProgress=this._register(new P);this.onDidDownloadProgress=this._onDidDownloadProgress.event;this._pendingDownloads=new Map;this._failureLatch=new Map}isAvailable(e){return process.env[e.devOverrideEnvVar]?!0:!!this._productService.agentSdks?.[e.id]&&gb(e)!==void 0}async isSdkResolvableWithoutDownload(e){if(process.env[e.devOverrideEnvVar])return!0;let t=this._productService.agentSdks?.[e.id];if(!t)return!1;let r=gb(e);if(!r)return!1;let o=v.joinPath(v.file(this._cacheDir(e.id,t.version,r)),".complete");return this._fileService.exists(o)}async loadSdkRoot(e,t){let r=process.env[e.devOverrideEnvVar];if(r)return this._logService.info(`[AgentSdkDownloader] ${e.id}: using dev override at ${r}`),r;let o=this._failureLatch.get(e.id);if(o&&o.expiresAt>Date.now())throw o.error;try{let s=await this._resolveOrDownload(e,t);return this._failureLatch.delete(e.id),s}catch(s){if(t.isCancellationRequested)throw s;let a=s instanceof Error?s:new Error(String(s));throw this._failureLatch.set(e.id,{error:a,expiresAt:Date.now()+P4}),a}}async _resolveOrDownload(e,t){let r=this._productService.agentSdks?.[e.id];if(!r)throw new Error(`Cannot load ${e.id} SDK: no \`product.agentSdks.${e.id}\` configured and no ${e.devOverrideEnvVar} dev override set.`);let o=gb(e);if(!o)throw new Error(`Cannot load ${e.id} SDK: no SDK target for this host (${process.platform}/${process.arch}). Set ${e.devOverrideEnvVar} to a local SDK root to bypass.`);let s=II(r.urlTemplate,{sdkTarget:o}),a=/{[^}]+}/.exec(s);if(a)throw new Error(`Cannot load ${e.id} SDK: \`product.agentSdks.${e.id}.urlTemplate\` contains an unknown placeholder ${a[0]} \u2014 only {sdkTarget} is substituted. Template: ${r.urlTemplate}`);let l=this._cacheDir(e.id,r.version,o),d=v.joinPath(v.file(l),".complete");if(await this._fileService.exists(d))return l;let c=this._pendingDownloads.get(l);return c||(c=this._download(e,s,l,d,t).finally(()=>{this._pendingDownloads.delete(l)}),this._pendingDownloads.set(l,c)),c}_cacheDir(e,t,r){return j(this._environmentService.userDataPath,"agent-host","sdk-cache",e,t,r)}async _download(e,t,r,o,s){this._logService.info(`[AgentSdkDownloader] ${e.id}: downloading from ${t}`);let a=Date.now(),l=le(r);await this._fileService.createFolder(v.file(l));let d=`${r}.tmp.${process.pid}`,c=v.file(d);await this._delIgnoringMissing(c),await this._fileService.createFolder(c);let u=H(),p=0,m;this._fireProgress(e,u,"started",0,void 0);try{let h=j(d,"sdk.tgz");await this._fetch(t,h,s,(S,b)=>{p=S,m=b,this._fireProgress(e,u,"progress",S,b)}),await this._extractTarGz(h,d),await this._fileService.del(v.file(h)),await this._fileService.writeFile(v.joinPath(c,".complete"),U.fromString(""));try{await this._fileService.move(c,v.file(r))}catch(S){if(await this._handleRenameLoser(S,o,c))return this._logService.info(`[AgentSdkDownloader] ${e.id}: lost rename race, using existing cache`),this._fireProgress(e,u,"completed",p,m),r;throw S}let y=Math.round((Date.now()-a)/1e3);return this._logService.info(`[AgentSdkDownloader] ${e.id}: downloaded in ${y}s`),this._fireProgress(e,u,"completed",m??p,m),r}catch(h){if(await this._delIgnoringMissing(c),s.isCancellationRequested)throw this._fireProgress(e,u,"failed",p,m,"cancelled"),new Y;let y=h instanceof Error?h.message:String(h);throw this._fireProgress(e,u,"failed",p,m,y),new Error(`Failed to download ${e.id} SDK from ${t} (cache target: ${r}). Set ${e.devOverrideEnvVar} to a local SDK root to bypass. Cause: ${y}`)}}_fireProgress(e,t,r,o,s,a){this._onDidDownloadProgress.fire({downloadId:t,packageId:e.id,displayName:e.displayName,phase:r,receivedBytes:o,totalBytes:s,...a!==void 0?{error:a}:{}})}async _handleRenameLoser(e,t,r){return!(e instanceof lt)||e.fileOperationResult!==4||!await this._fileService.exists(t)?!1:(await this._delIgnoringMissing(r),!0)}async _fetch(e,t,r,o){if(r.isCancellationRequested)throw new Y;let s=await this._requestService.request({url:e,type:"GET",callSite:"agentSdkDownloader"},r);if(r.isCancellationRequested)throw s.stream.destroy(),new Y;let a=s.res.statusCode??0;if(a<200||a>=300)throw s.stream.destroy(),new Error(`HTTP ${a} fetching ${e}`);let l=E4(s.res.headers["content-length"]);await new Promise((d,c)=>{let u=A1.createWriteStream(t),p=!1,m=0,h=0,y=_=>{if(!o)return;let R=Date.now();!_&&R-h<A4||(h=R,o(m,l))},S=()=>{p||(p=!0,I.dispose(),d())},b=_=>{p||(p=!0,I.dispose(),s.stream.destroy(),u.destroy(),c(_))},I=r.onCancellationRequested(()=>b(new Y));u.on("error",b),u.on("finish",S),u.on("drain",()=>s.stream.resume()),s.stream.on("data",_=>{m+=_.byteLength,y(!1),u.write(_.buffer)||s.stream.pause()}),s.stream.on("end",()=>{y(!0),u.end()}),s.stream.on("error",b)})}async _extractTarGz(e,t){await E1.x({file:e,cwd:t})}async _delIgnoringMissing(e){try{await this._fileService.del(e,{recursive:!0})}catch(t){if(ii(t)!==1)throw t}}};hl=w([C(0,Rt),C(1,Ct),C(2,_a),C(3,xe),C(4,D)],hl);var vl={id:"claude",displayName:"Claude",devOverrideEnvVar:up,hasSeparateMuslLinuxPackage:!0},bl=$("claudeAgentSdkService"),Sl=class{constructor(n,e){this._logService=n;this._downloader=e;this._firstLoadFailureLogged=!1}async listSessions(){return(await this._getSdk()).listSessions(void 0)}async canLoadWithoutDownload(){return process.env[up]||!this._downloader.isAvailable(vl)?!0:this._downloader.isSdkResolvableWithoutDownload(vl)}async getSessionInfo(n){return(await this._getSdk()).getSessionInfo(n)}async startup(n){return(await this._getSdk()).startup(n)}async query(n){return(await this._getSdk()).query(n)}async getSessionMessages(n,e){return(await this._getSdk()).getSessionMessages(n,e)}async listSubagents(n,e){return(await this._getSdk()).listSubagents(n,e)}async getSubagentMessages(n,e,t){return(await this._getSdk()).getSubagentMessages(n,e,t)}async forkSession(n,e){return(await this._getSdk()).forkSession(n,e)}async deleteSession(n,e){return(await this._getSdk()).deleteSession(n,e)}async createSdkMcpServer(n){return(await this._getSdk()).createSdkMcpServer(n)}async tool(n,e,t,r){return(await this._getSdk()).tool(n,e,t,r)}async _getSdk(){if(this._sdkModule)return this._sdkModule;try{return this._sdkModule=await this._loadSdk(),this._sdkModule}catch(n){throw this._firstLoadFailureLogged||(this._firstLoadFailureLogged=!0,this._logService.error("[Claude] Failed to load @anthropic-ai/claude-agent-sdk",n)),n}}async _loadSdk(){let n=process.env[up];if(n){let e=j(n,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(k1(e).href)}if(this._downloader.isAvailable(vl)){let e=await this._downloader.loadSdkRoot(vl,Ae.None),t=j(e,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(k1(t).href)}return import("@anthropic-ai/claude-agent-sdk")}};Sl=w([C(0,D),C(1,yl)],Sl);import{tmpdir as U4}from"os";import{z as Ut}from"zod";function Pm(i){if(!i||i.type!=="object"||!i.properties)return{};let n=new Set(i.required??[]),e={};for(let[t,r]of Object.entries(i.properties)){let o;try{o=xm(r)}catch{o=Ut.any()}n.has(t)||(o=o.optional()),e[t]=o}return e}function xm(i){if(!i||typeof i!="object")return Ut.any();let n;if(Array.isArray(i.enum)&&i.enum.length>0){let e=i.enum.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null);e.length===0?n=Ut.any():e.length===1?n=Ut.literal(e[0]):n=Ut.union(e.map(t=>Ut.literal(t)))}else if(Array.isArray(i.oneOf)&&i.oneOf.length>0)n=D1(i.oneOf);else if(Array.isArray(i.anyOf)&&i.anyOf.length>0)n=D1(i.anyOf);else switch(Array.isArray(i.type)?i.type[0]:i.type){case"string":n=Ut.string();break;case"number":n=Ut.number();break;case"integer":n=Ut.number().int();break;case"boolean":n=Ut.boolean();break;case"array":n=Ut.array(i.items?xm(i.items):Ut.any());break;case"object":{let t={},r=new Set(i.required??[]);for(let[o,s]of Object.entries(i.properties??{})){let a;try{a=xm(s)}catch{a=Ut.any()}r.has(o)||(a=a.optional()),t[o]=a}n=Ut.object(t);break}case"null":n=Ut.null();break;default:n=Ut.any()}return i.nullable&&(n=n.nullable()),i.description&&(n=n.describe(i.description)),i.default!==void 0&&(n=n.default(i.default)),n}function D1(i){let n=i.map(e=>{try{return xm(e)}catch{return Ut.any()}});return n.length===1?n[0]:Ut.union(n)}var M1="claudecode/toolUseId";async function O1(i,n,e){let t=await Promise.all(i.map(r=>e.tool(r.name,r.description??"",Pm(r.inputSchema),async(o,s)=>{let a=k4(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["${M1}"]).`}],isError:!0}:n(a)})));return e.createSdkMcpServer({name:mb,tools:t})}function k4(i){if(!i||typeof i!="object")return;let n=i._meta;if(!n||typeof n!="object")return;let e=n[M1];return typeof e=="string"?e:void 0}var mb="client";function Cl(i){let n=`mcp__${mb}__`;return i.startsWith(n)?i.slice(n.length):i}function L1(i){return i.startsWith(`mcp__${mb}__`)}var D4=new Map([["opus",new Set(["1m"])]]),hb=new Map;function ru(i){if(i!==void 0)return ls(i)?.toSdkModelId()??i}function ls(i){let n=i.toLowerCase();if(hb.has(n))return hb.get(n);let e=O4(n);return hb.set(n,e),e}var M4=/^(?<base>.*)-(?<date>\d{8})$/;function O4(i){let n="",e=i,t=M4.exec(i);t?.groups&&(e=t.groups.base,n=t.groups.date);let r=e.match(/^claude-(?<name>\w+)-(?<major>\d+)-(?<minor>\d+)(?:-(?<mod>.+))?$/);if(r?.groups)return nu(r.groups.name,r.groups.major,r.groups.minor,tu(r.groups.mod,n));let o=e.match(/^claude-(?<major>\d+)-(?<minor>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(o?.groups)return nu(o.groups.name,o.groups.major,o.groups.minor,tu(o.groups.mod,n));let s=e.match(/^claude-(?<name>\w+)-(?<major>\d+)\.(?<minor>\d+)(?:-(?<mod>.+))?$/);if(s?.groups)return nu(s.groups.name,s.groups.major,s.groups.minor,tu(s.groups.mod,n));let a=e.match(/^claude-(?<name>\w+)-(?<major>\d+)(?:-(?<mod>.+))?$/);if(a?.groups)return nu(a.groups.name,a.groups.major,void 0,tu(a.groups.mod,n));let l=e.match(/^claude-(?<major>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(l?.groups)return nu(l.groups.name,l.groups.major,void 0,tu(l.groups.mod,n));let d=e.match(/^(?<name>\w+)$/);if(d?.groups)return L4(d.groups.name)}function tu(i,n){return i&&n?`${i}-${n}`:i||n}function N1(i,n,e,t,r){let o=e!==void 0?`claude-${i}-${n}${t}${e}`:`claude-${i}-${n}`;return r?`${o}-${r}`:o}function L4(i){return{name:i,version:"",modifiers:"",toSdkModelId:()=>i,toEndpointModelId:()=>i}}function nu(i,n,e,t){let r=e!==void 0?`${n}.${e}`:n,o=N4(i,t);return{name:i,version:r,modifiers:t,toSdkModelId:()=>N1(i,n,e,"-",o),toEndpointModelId:()=>N1(i,n,e,".",o)}}function N4(i,n){if(!n)return"";let e=D4.get(i);if(!e)return"";if(e.has(n))return n;let t=n.split("-")[0];return e.has(t)?t:""}async function yb(i,n,e,t){let r=n.kind==="proxy",o=H1(r),s=await Ha(),a={...n.kind==="proxy"?{ANTHROPIC_BASE_URL:n.handle.baseUrl,ANTHROPIC_AUTH_TOKEN:`${n.handle.nonce}.${i.sessionId}`}:{},CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",USE_BUILTIN_RIPGREP:"0",PATH:`${le(s)}${ws}${process.env.PATH??""}`};return{cwd:i.workingDirectory.fsPath,executable:process.execPath,env:o,abortController:i.abortController,allowDangerouslySkipPermissions:!0,canUseTool:i.canUseTool,onElicitation:async l=>(t(l.message??""),{action:"cancel"}),disallowedTools:["WebSearch"],includePartialMessages:!0,forwardSubagentText:!0,enableFileCheckpointing:!0,model:ru(i.model?.id),effort:eu(i.model),permissionMode:i.permissionMode,...i.isResume?{resume:i.sessionId,...i.resumeSessionAt?{resumeSessionAt:i.resumeSessionAt}:{}}:{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(l=>({type:"local",path:l.fsPath}))}:{},...i.agent?{agent:i.agent}:{},settingSources:["user","project","local"],settings:{env:a},systemPrompt:{type:"preset",preset:"claude_code"},stderr:e}}async function U1(i,n,e){let t=i.consume();return t.length===0?void 0:{client:await O1(t,o=>n.register(o),e)}}function F1(){return{cwd:U4(),executable:process.execPath,env:H1(!1),abortController:new AbortController,systemPrompt:{type:"preset",preset:"claude_code"},settings:{env:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}}}function H1(i=!0){let n=i?{ELECTRON_RUN_AS_NODE:"1",NODE_OPTIONS:void 0,ANTHROPIC_API_KEY:void 0}:{...process.env,ELECTRON_RUN_AS_NODE:"1",NODE_OPTIONS:void 0};for(let e of Object.keys(process.env))e!=="ELECTRON_RUN_AS_NODE"&&(e.startsWith("VSCODE_")||e.startsWith("ELECTRON_"))&&(n[e]=void 0);return n}var ou={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}},iu="mcp__";function Am(i){let n=ou[i];return n?n.permissionKind:i.startsWith(iu)?"mcp":"custom-tool"}function vn(i){let n=or(i,void 0)?.displayName;if(n!==void 0)return n;switch(i){case"Bash":return f(2056,null);case"BashOutput":return f(2057,null);case"KillBash":return f(2062,null);case"Read":return f(2068,null);case"Glob":return f(2060,null);case"Grep":return f(2061,null);case"LS":return f(2063,null);case"NotebookRead":return f(2067,null);case"Write":return f(2072,null);case"Edit":return f(2058,null);case"MultiEdit":return f(2065,null);case"NotebookEdit":return f(2066,null);case"TodoWrite":return f(2070,null);case"WebFetch":return f(2071,null);case"Task":case"Agent":return f(2069,null);case"ExitPlanMode":return f(2059,null);case"AskUserQuestion":return f(2055,null)}return i.startsWith(iu)?f(2064,null,i.slice(iu.length)):i}function Or(i,n){let e=ou[i];if(!e?.pathField||typeof n!="object"||n===null)return;let t=n[e.pathField];return typeof t=="string"?t:void 0}function $1(i){return ou[i]?.isFileEdit===!0}var W1=new Set(Object.entries(ou).filter(([,i])=>i.interactive).map(([i])=>i));function q1(i){switch(Am(i)){case"shell":return f(2052,null);case"write":return f(2054,null);case"read":return f(2051,null);case"url":return f(2053,null);case"mcp":{let n=i.startsWith(iu)?i.slice(iu.length).split("__")[0]:void 0;return n?f(2050,null,n):f(2049,null)}default:return f(2049,null)}}function hi(i){let n=vb(i);return n?Qt(n):void 0}function vb(i){let n=ou[i];if(n?.toolKind)return{toolKind:n.toolKind}}function yn(i){return{markdown:i}}function Il(i){let n=v.file(i);return`[${es(pe(n))}](${n})`}function Mr(i,n){if(i===null||typeof i!="object")return;let e=i[n];return typeof e=="string"&&e.length>0?e:void 0}function B1(i){let n=Mr(i,"command");return n?n.split(`
`)[0]:void 0}function yi(i,n,e){let t=or(i,e)?.invocationMessage;if(t!==void 0)return t;switch(i){case"Bash":{let r=B1(e);return r?yn(f(2093,null,it(Yn(r,80)))):f(2092,null)}case"BashOutput":return f(2094,null);case"KillBash":return f(2101,null);case"Read":case"NotebookRead":{let r=Or(i,e);return r?yn(f(2105,null,Il(r))):f(2104,null)}case"LS":{let r=Or(i,e);return r?yn(f(2103,null,Il(r))):f(2102,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let r=Or(i,e);return r?yn(f(2096,null,Il(r))):f(2095,null)}case"TodoWrite":return f(2106,null);case"Grep":{let r=Mr(e,"pattern");return r?yn(f(2100,null,it(Yn(r,80)))):f(2099,null)}case"Glob":{let r=Mr(e,"pattern");return r?yn(f(2098,null,it(Yn(r,80)))):f(2097,null)}case"WebFetch":{let r=Mr(e,"url");return r?yn(f(2107,null,`[${es(Yn(r,80))}](${r})`)):f(2108,null)}case"Task":case"Agent":{let r=Mr(e,"description");return r||n}default:return n}}function Em(i,n,e,t,r){if(!t)return f(2078,null,n);let o=or(i,e,{text:r,success:t})?.pastTenseMessage;if(o!==void 0)return o;switch(i){case"Bash":{let s=B1(e);return s?yn(f(2074,null,it(Yn(s,80)))):f(2073,null)}case"BashOutput":return f(2075,null);case"KillBash":return f(2083,null);case"Read":case"NotebookRead":{let s=Or(i,e);return s?yn(f(2087,null,Il(s))):f(2086,null)}case"LS":{let s=Or(i,e);return s?yn(f(2085,null,Il(s))):f(2084,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let s=Or(i,e);return s?yn(f(2077,null,Il(s))):f(2076,null)}case"TodoWrite":return f(2089,null);case"Grep":{let s=Mr(e,"pattern");return s?yn(f(2082,null,it(Yn(s,80)))):f(2081,null)}case"Glob":{let s=Mr(e,"pattern");return s?yn(f(2080,null,it(Yn(s,80)))):f(2079,null)}case"WebFetch":{let s=Mr(e,"url");return s?yn(f(2090,null,`[${es(Yn(s,80))}](${s})`)):f(2091,null)}case"Task":case"Agent":return f(2088,null);default:return n}}function po(i,n){if(n!==void 0){if(i==="Bash"||i==="BashOutput"||i==="KillBash"){let e=Mr(n,"command");if(e)return e}if(i==="Grep"||i==="Glob"){let e=Mr(n,"pattern");if(e)return e}try{return JSON.stringify(n,null,2)}catch{return}}}function su(i,n,e){let t=new Sb(n,e);for(let r of i){let o=V1(r);o!==void 0&&t.consume(o)}return t.finish()}function km(i,n){let e=!1,t;for(let r of i){let o=V1(r);if(o!==void 0)if(o.kind==="user-text"){if(e)break;o.uuid===n&&(e=!0)}else o.kind==="assistant"&&e&&(t=o.uuid)}if(e)return t??n}function V1(i){switch(i.type){case"user":return F4(i);case"assistant":return H4(i);case"system":return $4(i);default:return}}function F4(i){let n=q4(i.message);if(n===void 0||G4(n))return;if(typeof n=="string")return{kind:"user-text",uuid:i.uuid,text:n};let e=n.filter(t=>t.type==="text");if(e.length===0){let t=n.filter(r=>r.type==="tool_result");return t.length>0?{kind:"user-tool-results",uuid:i.uuid,results:t}:void 0}return{kind:"user-text",uuid:i.uuid,text:e.map(t=>t.text).join(`
`)}}function H4(i){let n=B4(i.message);if(!(n===void 0||n.length===0))return{kind:"assistant",uuid:i.uuid,blocks:n,isInner:i.parent_tool_use_id!==null}}function $4(i){let n=z4(i.message);if(n===void 0||!W4.has(n))return;let e=V4(i.message)??`[${n}]`;return{kind:"system-notification",uuid:i.uuid,subtype:n,text:e}}var W4=new Set(["compact_boundary","notification"]),z1=/^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/,Sb=class{constructor(n,e){this._session=n;this._logService=e;this._turns=[];this._toolUses=new Map}consume(n){switch(n.kind){case"user-text":this._closeActive(),this._active={id:n.uuid,userText:n.text,responseParts:[],pendingToolUseIds:new Set,toolCallParts:new Map};return;case"user-tool-results":for(let e of n.results)this._attachToolResult(e);return;case"assistant":this._consumeAssistant(n);return;case"system-notification":if(this._active===void 0)return;this._active.responseParts.push({kind:"systemNotification",content:n.text});return}}finish(){return this._closeActive(),this._turns}_consumeAssistant(n){if(this._active===void 0){if(!n.isInner){this._logService.warn(`[claudeReplayMapper] assistant envelope ${n.uuid} arrived before any user message; dropping`);return}this._active={id:n.uuid,userText:"",responseParts:[],pendingToolUseIds:new Set,toolCallParts:new Map}}let e=0,t=0;for(let r of n.blocks)r.type==="text"&&typeof r.text=="string"?this._active.responseParts.push({kind:"markdown",id:`${this._active.id}#${n.uuid}#text-${e++}`,content:r.text}):r.type==="thinking"&&typeof r.thinking=="string"?this._active.responseParts.push({kind:"reasoning",id:`${this._active.id}#${n.uuid}#thinking-${t++}`,content:r.thinking}):r.type==="tool_use"&&typeof r.id=="string"&&typeof r.name=="string"&&this._openToolUse(r.id,Cl(r.name),r.input)}_openToolUse(n,e,t){if(this._active===void 0)return;let r=vn(e),o=t!==null&&typeof t=="object"?t:void 0,s=hi(e),a={status:"cancelled",toolCallId:n,toolName:e,displayName:r,invocationMessage:yi(e,r,o),toolInput:o!==void 0?po(e,o):typeof t=="string"?t:t!==void 0?K4(t):void 0,reason:"skipped",...s?{_meta:s}:{}},l={kind:"toolCall",toolCall:a};this._active.responseParts.push(l),this._active.toolCallParts.set(n,l),this._active.pendingToolUseIds.add(n),this._toolUses.set(n,{turnId:this._active.id,parsedInput:o})}_attachToolResult(n){let e=this._toolUses.get(n.tool_use_id);if(e===void 0){this._logService.warn(`[claudeReplayMapper] tool_result for unknown tool_use_id ${n.tool_use_id}`);return}let t=e.turnId,r=this._findToolCallPart(t,n.tool_use_id);if(r===void 0)return;let o=n.is_error,s=r.toolCall,a=ec(s).toolKind==="subagent",l=j4(n.content)??[],d=l.filter(u=>u.type==="text").map(u=>u.text).join(`
`);a&&l.push({type:"subagent",resource:qs(this._session.toString(),s.toolCallId),title:s.displayName});let c={status:"completed",toolCallId:s.toolCallId,toolName:s.toolName,displayName:s.displayName,invocationMessage:s.invocationMessage??s.displayName,toolInput:s.status==="streaming"?void 0:s.toolInput,confirmed:"not-needed",success:!o,pastTenseMessage:Em(s.toolName,s.displayName,e.parsedInput,!o,d),content:l.length>0?l:void 0,...s._meta?{_meta:s._meta}:{}};r.toolCall=c,this._active?.id===t&&this._active.pendingToolUseIds.delete(n.tool_use_id)}_findToolCallPart(n,e){if(this._active&&this._active.id===n)return this._active.toolCallParts.get(e);for(let t=this._turns.length-1;t>=0;t--)if(this._turns[t].id===n){for(let r of this._turns[t].responseParts)if(r.kind==="toolCall"&&r.toolCall.toolCallId===e)return r;return}}_closeActive(){if(this._active===void 0)return;let n=this._active,e=n.pendingToolUseIds.size===0?"complete":"cancelled",t={id:n.id,message:{text:n.userText,origin:{kind:"user"}},responseParts:n.responseParts,usage:void 0,state:e};this._turns.push(t),this._active=void 0}};function q4(i){if(i===null||typeof i!="object")return;let n=i.content;if(typeof n=="string")return n.length>0?n:void 0;if(!Array.isArray(n)||n.length===0)return;let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let r=t;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 B4(i){if(i===null||typeof i!="object")return;let n=i.content;if(!Array.isArray(n))return;let e=[];for(let t of n){if(t===null||typeof t!="object")continue;let r=t;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 z4(i){if(i===null||typeof i!="object")return;let n=i.subtype;return typeof n=="string"?n:void 0}function V4(i){if(i===null||typeof i!="object")return;let n=i;if(typeof n.text=="string")return n.text;if(typeof n.message=="string")return n.message}function j4(i){if(typeof i=="string")return i.length>0?[{type:"text",text:i}]:void 0;if(!Array.isArray(i))return;let n=[];for(let e of i){if(e===null||typeof e!="object")continue;let t=e;t.type==="text"&&typeof t.text=="string"&&n.push({type:"text",text:t.text})}return n.length>0?n:void 0}function K4(i){try{return JSON.stringify(i)}catch{return}}function G4(i){if(typeof i=="string")return z1.test(i);let n=i.find(e=>e.type==="text");return n!==void 0&&z1.test(n.text)}var bb=class{validateOrThrow(n){let e=this.validate(n);if(e.error)throw new Error(e.error.message);return e.content}},_l=class extends bb{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}}},J4=new _l("string");function j1(){return J4}var nwe=new _l("number");var rwe=new _l("boolean");var Y4=new _l("object");function K1(){return Y4}var au=new Set(["Task","Agent"]),Q4=/^\s*agentId:\s+([a-z0-9]+)\b/im,Cb=class{constructor(n){this.toolUseId=n;this.background=!1;this._announced=!1;this._completed=!1}get agentId(){return this._agentId}setAgentId(n){this._agentId===void 0&&(this._agentId=n)}markAnnounced(){return this._announced?!1:(this._announced=!0,!0)}markCompleted(){return this._completed?!1:(this._completed=!0,!0)}},Dm=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,t){let r=this._spawns.get(e);return r||(r=new Cb(e),this._spawns.set(e,r)),t?.agentId!==void 0&&r.setAgentId(t.agentId),t?.subagentType!==void 0&&r.subagentType===void 0&&(r.subagentType=t.subagentType),t?.description!==void 0&&r.description===void 0&&(r.description=t.description),r}getSpawn(e){return this._spawns.get(e)}removeSpawn(e){this._spawns.delete(e),this._evictInnerEdgesFor(e)}noteInnerTool(e,t){this._innerToParent.set(e,t)}getParentSpawn(e){let t=this._innerToParent.get(e);return t!==void 0?this._spawns.get(t):void 0}drainForegroundSpawns(){let e=[];for(let t of this._spawns.values())t.background||e.push(t);for(let t of e)this._spawns.delete(t.toolUseId),this._evictInnerEdgesFor(t.toolUseId);return e}primeFromTranscript(e){for(let[t,r]of Ib(e))this.recordSpawn(t,{agentId:r})}_evictInnerEdgesFor(e){for(let[t,r]of this._innerToParent)r===e&&this._innerToParent.delete(t)}};function Ib(i){let n=new Map;for(let e of i)for(let t of e.responseParts){let r=X4(t);r&&n.set(r.toolCallId,r.agentId)}return n}function X4(i){if(i.kind!=="toolCall")return;let n=i.toolCall;if(!au.has(n.toolName)||n.status!=="completed"&&n.status!=="pending-result-confirmation")return;let e=n.content;if(e)for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type!=="text")continue;let o=Q4.exec(r.text);if(o)return{toolCallId:n.toolCallId,agentId:o[1]}}}var _b=class{constructor(n,e){this._sdk=n;this._logService=e;this.name="text_suffix"}async lookup(n,e){let t=await G1(this._sdk,this._logService,e,"TextSuffix");if(t)return Ib(t).get(n)}};async function G1(i,n,e,t){if(e.parentTranscript)return e.parentTranscript;try{let r=await i.getSessionMessages(e.parentSessionId,{includeSystemMessages:!0});return su(r,e.parentUri,n)}catch(r){n.warn(`[claudeSubagentResolver] ${t}: parent transcript fetch failed: ${r}`);return}}function J1(i){let n=j1().validate(i);return n.error?void 0:n.content}function Tb(i){let n=K1().validate(i);if(!(n.error||n.content===null||Array.isArray(n.content)))return n.content}var wb=class{constructor(n,e){this._sdk=n;this._logService=e;this.name="prompt_match"}async lookup(n,e){let t=await this._loadParentPrompt(n,e);if(!t)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=e5(s);if(a!==void 0&&a===t)return o}}async _loadParentPrompt(n,e){let t=await G1(this._sdk,this._logService,e,"PromptMatch");if(t)return Z4(t,n)}};function Z4(i,n){for(let e of i)for(let t of e.responseParts){if(t.kind!=="toolCall")continue;let r=t.toolCall;if(r.toolCallId!==n)continue;if(!au.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=Tb(s);return a?J1(a.prompt):void 0}}function e5(i){for(let n of i){if(n.type!=="user")continue;let e=Tb(n.message);if(!e)continue;let t=e.content;if(typeof t=="string")return t;if(Array.isArray(t))for(let r of t){let o=Tb(r);if(!o||o.type!=="text")continue;let s=J1(o.text);if(s!==void 0)return s}}}var Rb=class{constructor(){this.name="native"}async lookup(){}};async function t5(i,n,e){let t=e.cacheGet(i);if(t)return t;for(let r of e.strategies){if(n.token.isCancellationRequested)return;let o=await r.lookup(i,n);if(o)return e.cacheSet(i,o),o}}function n5(i,n){return[new _b(i,n),new wb(i,n),new Rb]}async function Y1(i,n,e,t,r){let o=gt(i);if(!o)throw new Error(`getSubagentTranscript: not a subagent URI: ${i.toString()}`);let{parentSession:s,toolCallId:a}=o,l=L.id(s),d=await t5(a,{parentUri:s,parentSessionId:l,token:r},{strategies:n5(e,t),cacheGet:u=>n.getSpawn(u)?.agentId,cacheSet:(u,p)=>{n.recordSpawn(u,{agentId:p})}});if(!d)return[];let c;try{c=await e.getSubagentMessages(l,d)}catch(u){return t.warn(`[getSubagentTranscript] getSubagentMessages(${d}) failed: ${u}`),[]}return su(c,i,t)}var Mm="host";function Q1(i){return i.map(n=>`mcp__${Mm}__${n}`)}async function X1(i,n,e){let t=await Promise.all(i.definitions.map(r=>e.tool(r.name,r.description??"",Pm(r.inputSchema),async o=>{try{return{content:[{type:"text",text:i.executeTool(n,r.name,o)}]}}catch(s){return{content:[{type:"text",text:s instanceof Error?s.message:String(s)}],isError:!0}}})));return e.createSdkMcpServer({name:Mm,tools:t})}var r5="claude-client";function Z1(i,n){let r={content:(i.content??[]).map((o,s)=>i5(o,n,s))};return i.structuredContent!==void 0&&(r.structuredContent=i.structuredContent),(!i.success||i.error)&&(r.isError=!0),r}function i5(i,n,e){switch(i.type){case"text":return{type:"text",text:i.text};case"embeddedResource":return o5(i,n,e);default:{console.warn(`[Claude] convertToolCallResult: unsupported tool-result block kind '${i.type}'; degrading to text`);let t;try{t=JSON.stringify(i)}catch{t=`[unserializable ${i.type} block]`}return{type:"text",text:t}}}}function o5(i,n,e){return i.contentType.startsWith("image/")?{type:"image",data:i.data,mimeType:i.contentType}:{type:"resource",resource:{uri:`${r5}://${encodeURIComponent(n)}/${e}`,mimeType:i.contentType,blob:i.data}}}function fo(i,n){return as(i.getSessionConfigValues(n.toString())?.permissionMode)}var xb=class{constructor(){this._toolSet=new Pn;this._merged=Ho({owner:this,equalsFn:(n,e)=>Xg(n,e)},[]);this.merged=this._merged}setTools(n,e){this._toolSet.set(n,e),this._merged.set(this._toolSet.merged(),void 0)}getTools(n){return this._toolSet.get(n)}removeClient(n){this._toolSet.delete(n)&&this._merged.set(this._toolSet.merged(),void 0)}ownerOf(n,e){return this._toolSet.ownerOf(n,e)}},Om=class extends T{constructor(){super();this.model=new xb;this._dirty=!1;this._ignoreNextFire=!0;this._lastAppliedTools=[];this._register(Wn(e=>{let t=this.model.merged.read(e);if(this._ignoreNextFire){this._ignoreNextFire=!1,this._lastAppliedTools=t;return}Xg(t,this._lastAppliedTools)||(this._dirty=!0)}))}get hasDifference(){return this._dirty}consume(){let e=this.model.merged.get();return this._dirty=!1,this._lastAppliedTools=e,e}markDirty(){this._dirty=!0}};var s5={synced:[],enablement:new Map},Pb=class{constructor(){this._byClient=new Map;this._state=Ho({owner:this,equalsFn:a5},s5);this.state=this._state;this.enabledPluginPaths=Ed({owner:this,equalsFn:(n,e)=>bn(n,e,(t,r)=>t.toString()===r.toString())},n=>{let e=this._state.read(n),t=[];for(let r of e.synced)r.pluginDir&&e.enablement.get(r.customization.id)!==!1&&t.push(r.pluginDir);return t})}_mergedSynced(){let n=new Set,e=[];for(let t of this._byClient.values())for(let r of t)n.has(r.customization.id)||(n.add(r.customization.id),e.push(r));return e}setSyncedCustomizations(n,e){this._byClient.set(n,e);let t=this._state.get();this._state.set({synced:this._mergedSynced(),enablement:t.enablement},void 0)}removeClient(n){if(!this._byClient.delete(n))return;let e=this._state.get();this._state.set({synced:this._mergedSynced(),enablement:e.enablement},void 0)}setEnabled(n,e){let t=this._state.get(),r=t.enablement.get(n);if(r===e||e&&r===void 0)return;let o=new Map(t.enablement);e?o.delete(n):o.set(n,!1),this._state.set({synced:t.synced,enablement:o},void 0)}},Lm=class extends T{constructor(){super();this.model=new Pb;this._dirty=!1;this._ignoreNextFire=!0;this.onDidChange=ee.fromObservableLight(this.model.state);this._register(Wn(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 a5(i,n){return l5(i.synced,n.synced)&&c5(i.enablement,n.enablement)}function l5(i,n){if(i.length!==n.length)return!1;for(let e=0;e<i.length;e++){let t=i[e].customization,r=n[e].customization;if(t.id!==r.id||t.uri!==r.uri||t.nonce!==r.nonce||t.name!==r.name||t.enabled!==r.enabled||t.load?.kind!==r.load?.kind||tA(t.load)!==tA(r.load)||!d5(t.children,r.children)||i[e].pluginDir?.toString()!==n[e].pluginDir?.toString())return!1}return!0}function tA(i){return i&&i.message?i.message:void 0}function d5(i,n){if(i===n)return!0;if(!i||!n||i.length!==n.length)return!1;for(let e=0;e<i.length;e++)if(i[e].id!==n[e].id||i[e].name!==n[e].name)return!1;return!0}function c5(i,n){if(i.size!==n.size)return!1;for(let[e,t]of i)if(n.get(e)!==t)return!1;return!0}function u5(i,n){let e=[];return i&&(e.push(v.joinPath(i,".claude","settings.json")),e.push(v.joinPath(i,".mcp.json"))),e.push(v.joinPath(n,".claude","settings.json")),e}function p5(i,n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(Object.hasOwn(e,"mcpServers")){let t=e.mcpServers;return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}return i.path.endsWith(".mcp.json")?e:void 0}async function nA(i,n,e){let t=new Set,r=[];for(let o of u5(i,n)){let s=await pi(o,e),a=p5(o,s);if(a)for(let[l,d]of Object.entries(a))!d||typeof d!="object"||Array.isArray(d)||t.has(l)||(t.add(l),r.push(Oc(o,l)))}return r.sort((o,s)=>o.name.localeCompare(s.name)),r}function Ab(i){switch(i){case"connected":return{kind:"ready"};case"disabled":return{kind:"stopped"};default:return{kind:"starting"}}}function Eb(i,n){let e=[v.joinPath(n,".claude","CLAUDE.md")];return i&&e.push(v.joinPath(i,"CLAUDE.md"),v.joinPath(i,".claude","CLAUDE.md"),v.joinPath(i,"CLAUDE.local.md")),e}var f5=32;async function rA(i,n,e=new Set,t=0){let r=i.toString();if(t>f5||e.has(r))return[];e.add(r);let o;try{o=await n.resolve(i)}catch{return[]}if(!o.isDirectory||!o.children)return[];let s=[];for(let a of o.children)a.isDirectory?s.push(...await rA(a.resource,n,e,t+1)):a.isFile&&a.resource.path.toLowerCase().endsWith(".md")&&s.push(a.resource);return s.sort((a,l)=>a.path.localeCompare(l.path))}async function iA(i,n,e){let t=[];for(let o of Eb(i,n))if(await ts(o,e)){let s=o.toString(),a=pe(o),l={type:"rule",id:Ot(s),uri:s,name:a,alwaysApply:!0};t.push({uri:o,name:a,customization:l})}let r=i?[i,n]:[n];for(let o of r){let s=await rA(v.joinPath(o,".claude","rules"),e);for(let a of s){let l=await Vg(a,e),d=a.toString(),c=!!l.globs?.length,u={type:"rule",id:Ot(d),uri:d,name:l.name,...l.description?{description:l.description}:{},...c?{globs:l.globs}:{},alwaysApply:!c};t.push({uri:a,name:l.name,...l.description?{description:l.description}:{},customization:u})}}return t}var oA="agent-builtin",g5=[{name:"init",description:()=>f(2112,null)},{name:"review",description:()=>f(2115,null)},{name:"security-review",description:()=>f(2117,null)},{name:"code-review",description:()=>f(2110,null)},{name:"simplify",description:()=>f(2118,null)},{name:"verify",description:()=>f(2120,null)},{name:"run",description:()=>f(2116,null)},{name:"loop",description:()=>f(2114,null)},{name:"claude-api",description:()=>f(2109,null)},{name:"fewer-permission-prompts",description:()=>f(2111,null)},{name:"update-config",description:()=>f(2119,null)},{name:"keybindings-help",description:()=>f(2113,null)},{name:"write-a-skill",description:()=>f(2121,null)}],sA=[{name:"claude",description:()=>f(2122,null)},{name:"claude-code-guide",description:()=>f(2123,null)},{name:"Explore",description:()=>f(2124,null)},{name:"general-purpose",description:()=>f(2125,null)},{name:"Plan",description:()=>f(2126,null)}];function aA(i){if(i.length===0)return;let n=i.map(t=>{let r=v.from({scheme:oA,path:`/skill/${encodeURIComponent(t.name)}`}).toString();return{type:"skill",id:Ot(r),uri:r,name:t.name,description:t.description}}),e=v.from({scheme:oA,path:"/skills"}).toString();return{type:"directory",id:Ot(e),uri:e,name:"builtin",enabled:!0,contents:"skill",writable:!1,load:{kind:"loaded"},children:n}}function lA(i){return aA(g5.filter(n=>!i.has(n.name)).map(n=>({name:n.name,description:n.description()})))}function dA(i,n){let e=new Set,t=[];for(let r of i)n.has(r.name)||e.has(r.name)||(e.add(r.name),t.push({name:r.name,description:r.description}));return aA(t)}var kb="general-purpose",pA="claude-internal";function Nm(i,n,e,t){let r=v.joinPath(i,".claude",n).toString();return{type:"directory",id:Ot(r),uri:r,name:n,enabled:!0,contents:e,writable:!0,load:{kind:"loaded"},children:[...t]}}function m5(i){let n=i.root.toString(),e=[],t=new Set,r=o=>{t.has(o.id)||(t.add(o.id),e.push(o))};for(let o of i.parsed.agents)r(o.customization);for(let o of i.parsed.skills)r(o.customization);for(let o of i.parsed.instructions)r(o.customization);for(let o of i.parsed.hooks)r(o.customization);for(let o of i.parsed.mcpServers)r(o.customization);return{type:"plugin",id:Ot(n),uri:n,name:i.id,enabled:!0,load:{kind:"loaded"},children:e}}function cA(i,n){return n&&i.scheme===n.scheme&&Kr(i,n)?"workspace":"user"}function uA(i,n,e,t,r,o){let s=new Map([["workspace",{agents:[],skills:[],rules:[],hooks:[]}],["user",{agents:[],skills:[],rules:[],hooks:[]}]]);for(let d of i){let c=s.get(cA(d.uri,r));d.customization.type==="agent"?c.agents.push(d.customization):d.customization.type==="skill"?c.skills.push(d.customization):c.rules.push(d.customization)}for(let d of e)s.get(cA(v.parse(d.uri),r)).hooks.push(d);let a=[],l=[["workspace",r],["user",o]];for(let[d,c]of l){if(!c)continue;let u=s.get(d);u.agents.length>0&&a.push(Nm(c,"agents","agent",u.agents)),u.skills.length>0&&a.push(Nm(c,"skills","skill",u.skills)),u.rules.length>0&&a.push(Nm(c,"rules","rule",u.rules)),u.hooks.length>0&&a.push(Nm(c,"hooks","hook",u.hooks))}for(let d of t)a.push(m5(d));return a.push(...n),a}function Db(i,n){return v.from({scheme:pA,path:`/${i}/${encodeURIComponent(n)}`})}async function Mb(i,n,e,t){if(!i)return;let r=v.parse(i.uri);if(r.scheme===pA){let a=r.path.split("/").pop()??"",l=a?decodeURIComponent(a):"";if(!l){e.warn(`[Claude:${t}] resolveClaudeAgentName: could not extract agent name from URI '${i.uri}'`);return}return l}try{let a=await Lc(r,n);if(a.name)return a.name}catch(a){e.warn(`[Claude:${t}] resolveClaudeAgentName: failed to parse agent file '${i.uri}', falling back to basename`,a)}let s=(r.path.split("/").pop()??"").replace(/\.md$/i,"");if(!s){e.warn(`[Claude:${t}] resolveClaudeAgentName: could not extract agent name from URI '${i.uri}'`);return}return s}function fA(i,n,e,t,r,o,s){let a=[],l=new Set,d=new Set,c=new Set;if(s)for(let A of t){let X=s.plugins.find(x=>x.source===A.id||v.file(x.path).fsPath===A.root.fsPath);if(!X)continue;a.push(A);let E=X.name,z=(x,B)=>{x.add(B),E&&x.add(`${E}:${B}`)};for(let x of A.parsed.agents)z(l,x.name);for(let x of A.parsed.skills)z(d,x.name);for(let x of A.parsed.mcpServers)z(c,x.name)}else a.push(...t);let u=new Set(i.filter(A=>A.customization.type==="skill").map(A=>A.name)),p=s?dA(s.commands.filter(A=>!d.has(A.name)),u):lA(u),m=A=>p?[...A,p]:A;if(!s){let A=new Set(i.filter(E=>E.customization.type==="agent").map(E=>E.name)),X=sA.filter(E=>E.name!==kb&&!A.has(E.name)).map(E=>el({uri:Db("agent",E.name),name:E.name,description:E.description()}));return m(uA([...i,...X],n,e,t,r,o))}let h=new Set(s.agents.map(A=>A.name)),y=new Set(s.commands.map(A=>A.name)),S=new Map(s.mcpServers.map(A=>[A.name,A])),b=new Set,I=[];for(let A of i)if(A.customization.type==="agent"){if(A.name===kb)continue;h.has(A.name)&&(I.push(A),b.add(A.name))}else A.customization.type==="skill"?y.has(A.name)&&I.push(A):I.push(A);for(let A of s.agents)A.name===kb||b.has(A.name)||l.has(A.name)||I.push(el({uri:Db("agent",A.name),name:A.name,...A.description?{description:A.description}:{}}));let _=new Set,R=[];for(let A of n){let X=S.get(A.name);X&&(_.add(A.name),R.push({...A,state:Ab(X.status)}))}for(let[A,X]of S)_.has(A)||c.has(A)||R.push({...Oc(Db("mcp",A),A),state:Ab(X.status)});return m(uA(I,R,e,a,r,o))}var Um=class i extends T{static{this.DEBOUNCE_MS=300}constructor(n,e,t,r,o=i.DEBOUNCE_MS){super();let s=[],a=(d,c)=>{try{this._register(t.watch(d,{recursive:c,excludes:[]}))}catch(u){r.warn(`[ClaudeCustomizationWatcher] failed to watch '${d.toString()}': ${u instanceof Error?u.message:String(u)}`)}};if(n){let d=v.joinPath(n,".claude");a(d,!0),s.push(d),a(n,!1),s.push(v.joinPath(n,".mcp.json"))}let l=v.joinPath(e,".claude");a(l,!0),s.push(l),s.push(...Eb(n,e)),this.onDidChange=ee.signal(ee.debounce(ee.filter(t.onDidFilesChange,d=>s.some(c=>d.affects(c)),this._store),(d,c)=>c,o,void 0,void 0,void 0,this._store))}};function h5(i){let n=v.joinPath(i,".claude");return{agents:v.joinPath(n,"agents"),skills:v.joinPath(n,"skills"),commands:v.joinPath(n,"commands")}}function Ob(i,n){for(let e of n)i.has(e.name)||i.set(e.name,e)}async function y5(i,n){let e=await Promise.all(i.map(async t=>{let r=In(t.uri),o=await Dc(r,n);return n.exists(v.joinPath(r,o.manifestPath))}));return i.filter((t,r)=>!e[r])}async function gA(i,n,e){let t=i?[i,n]:[n],r=new Map,o=new Map;for(let s of t){let{agents:a,skills:l,commands:d}=h5(s),[c,u,p]=await Promise.all([zg([a],e),$S(l,[l],e),zg([d],e)]);Ob(r,c.map(el));let m=await y5(u,e);Ob(o,m.map(Kg)),Ob(o,p.map(Kg))}return[...r.values(),...o.values()]}function v5(i,n){let e=[];return i&&(e.push(v.joinPath(i,".claude","settings.json")),e.push(v.joinPath(i,".claude","settings.local.json"))),e.push(v.joinPath(n,".claude","settings.json")),e}async function mA(i,n,e){let t=[],r=new pr;for(let o of v5(i,n)){if(r.has(o))continue;r.add(o);let s=await pi(o,e);if(s===void 0)continue;let a=Bg(o,s,i,n);a.length>0&&t.push(a[0].customization)}return t}var S5="skills-dir";function b5(i,n){let e=[v.joinPath(n,".claude","settings.json")];return i&&(e.push(v.joinPath(i,".claude","settings.json")),e.push(v.joinPath(i,".claude","settings.local.json"))),e}async function C5(i,n,e){let t=new Map,r=new pr;for(let o of b5(i,n)){if(r.has(o))continue;r.add(o);let s=await pi(o,e);if(!s||typeof s!="object"||Array.isArray(s))continue;let a=s.enabledPlugins;if(!(!a||typeof a!="object"||Array.isArray(a)))for(let[l,d]of Object.entries(a))t.set(l,d!==!1)}return[...t].filter(([,o])=>o).map(([o])=>o)}function I5(i){let n=i.lastIndexOf("@");if(n<=0||n===i.length-1)return;let e=i.slice(0,n),t=i.slice(n+1),r=o=>o.includes("/")||o.includes("\\")||o.includes("..");if(!(r(e)||r(t)))return{plugin:e,marketplace:t}}async function Lb(i,n){let e=await Dc(i,n);return n.exists(v.joinPath(i,e.manifestPath))}async function _5(i,n,e,t){let r=[];n&&r.push(v.joinPath(n,".claude","skills",i)),r.push(v.joinPath(e,".claude","skills",i));for(let o of r)if(await Lb(o,t))return o}async function T5(i,n,e,t){let r=v.joinPath(e,".claude","plugins","cache",n,i);if(await Lb(r,t))return r;let o;try{o=await t.resolve(r)}catch{return}if(!o.isDirectory||!o.children)return;let s;for(let a of o.children){if(!a.isDirectory||!await Lb(a.resource,t))continue;let l=a.mtime??0;(!s||l>s.mtime||l===s.mtime&&a.name.localeCompare(s.name,void 0,{numeric:!0})>0)&&(s={uri:a.resource,mtime:l,name:a.name})}return s?.uri}async function hA(i,n,e,t){let r=await C5(i,n,e),o=[],s=new pr;for(let a of r){let l=I5(a);if(!l){t.warn(`[claudeNativePluginScan] skipping malformed plugin id '${a}'`);continue}let d=l.marketplace===S5?await _5(l.plugin,i,n,e):await T5(l.plugin,l.marketplace,n,e);if(!d){t.warn(`[claudeNativePluginScan] could not resolve an on-disk root for enabled plugin '${a}'`);continue}if(!s.has(d)){s.add(d);try{let c=await jg(d,e,i,n,d);o.push({id:a,root:d,parsed:c})}catch(c){t.warn(`[claudeNativePluginScan] failed to parse plugin '${a}' at '${d.toString()}': ${c instanceof Error?c.message:String(c)}`)}}}return o.sort((a,l)=>a.id.localeCompare(l.id)),o}function Fm(i,n){let e=[{type:"text",text:i}];if(!n?.length)return e;let t=[],r=[],o=[];for(let s of n){if(rm(s)){let l=im(s);l&&o.push(l);continue}if(s.type==="simple"){s.modelRepresentation&&r.push(s.modelRepresentation);continue}if(s.type!=="resource")continue;let a=v.parse(s.uri);if(s.displayKind==="selection"){let l=s.selection?`:${s.selection.range.start.line+1}`:"";t.push(`- ${yA(a)}${l}`)}else t.push(`- ${yA(a)}`)}return o.length>0&&e.push({type:"text",text:o.join(`

`)}),r.length>0&&e.push({type:"text",text:r.join(`

`)}),t.length===0||e.push({type:"text",text:`<system-reminder>
The user provided the following references:
`+t.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 yA(i){return i.scheme==="file"?i.fsPath:i.toString()}var Tl=class extends T{constructor(e,t,r,o){super();this._sessionId=e;this._getAbortSignal=t;this._onSteeringYielded=r;this._logService=o;this._toYield=[];this._yielded=[];this._popped=[];this._pendingPromptDeferred=new Ee;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 Ee}}})}}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 t of this._popped)t.deferred.isSettled||t.deferred.complete();this._popped=[]}else this._popped.push(e);return e}}failAll(e){let t=r=>{for(let o of r)o.deferred.isSettled||o.deferred.error(e)};t(this._toYield),t(this._yielded),t(this._popped),this._toYield=[],this._yielded=[],this._popped=[]}notifyAborted(){this._pendingPromptDeferred.complete()}resetForRebind(){this._pendingPromptDeferred=new Ee}};Tl=w([C(3,D)],Tl);var wl=class extends T{constructor(e,t,r,o){super();this._logService=r;this._editToolPaths=new Map;this._register(t),this._editTracker=o.createInstance(zi,e,t.object)}observeAssistant(e){let t=e.message.content;if(!Array.isArray(t))return;let r=typeof e.message.model=="string"?e.message.model:void 0;for(let o of t){if(o.type!=="tool_use"||!$1(o.name))continue;let s=Or(o.name,o.input);s&&(this._editToolPaths.set(o.id,{filePath:s,toolName:o.name,toolInput:o.input,modelId:r}),this._editTracker.trackEditStart(s).catch(a=>this._logService.warn(`[ClaudeFileEditObserver] trackEditStart failed for ${s}: ${a}`)))}}async observeUser(e,t,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.filePath);let l=await this._editTracker.takeCompletedEdit(t,s.tool_use_id,a.filePath,a.toolName,a.toolInput,a.modelId);l&&r.cacheFileEdit(s.tool_use_id,l)}catch(l){this._logService.warn(`[ClaudeFileEditObserver] file edit tracking failed for ${a.filePath}: ${l}`)}}}}};wl=w([C(2,D),C(3,Ie)],wl);var Nb=au;function Hm(i,n,e,t){if(!e)return i;let r=i.map(a=>a.kind==="action"?{...a,parentToolCallId:e}:a.kind==="pending_confirmation"?{...a,parentToolCallId:e}:a),o=t.getSpawn(e);return!o||!o.markAnnounced()?r:[{kind:"subagent_started",chat:n,toolCallId:e,agentName:o.subagentType??"subagent",agentDisplayName:o.subagentType??"Subagent",agentDescription:o.description,taskDescription:o.description,parentToolCallId:t.getParentSpawn(e)?.toolUseId},...r]}function vA(i,n,e){let t=i.subtype;if(t==="task_started"){let r=i.tool_use_id,o=r?e.getSpawn(r):void 0;return o&&(o.background=!0),[]}if(t==="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",chat:n,toolCallId:a}]}return[]}function SA(i,n,e,t){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?w5(i.input):void 0;t.recordSpawn(i.id,{subagentType:s,description:o});let l={...vb(i.name)};return l.toolKind||(l.toolKind="subagent"),o&&(l.subagentDescription=o),s&&(l.subagentAgentName=s),{kind:"action",resource:n,action:{type:"chat/toolCallReady",turnId:e,toolCallId:i.id,invocationMessage:yi(i.name,vn(i.name),i.input),...a!==void 0?{toolInput:a}:{},confirmed:"not-needed",_meta:Qt(l)}}}function bA(i,n,e,t,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",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"markdown",id:`${e}#${s}#${l}`,content:d.text}}});continue}if(d.type==="thinking"){a.push({kind:"action",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"reasoning",id:`${e}#${s}#${l}`,content:d.thinking}}});continue}if(d.type==="tool_use"){let c=Cl(d.name);t.startToolBlock(l,d.id,c,e),t.toolCalls.seedParsedInput(d.id,d.input),o.noteInnerTool(d.id,r);let u=vn(c),p=hi(c),m=po(c,d.input);a.push({kind:"action",resource:n,action:{type:"chat/toolCallStart",turnId:e,toolCallId:d.id,toolName:c,displayName:u,...p?{_meta:p}:{}}}),a.push({kind:"action",resource:n,action:{type:"chat/toolCallReady",turnId:e,toolCallId:d.id,invocationMessage:yi(c,u,d.input),...m!==void 0?{toolInput:m}:{},confirmed:"not-needed"}});continue}}return a}function w5(i){try{return JSON.stringify(i)}catch{return}}var Ub="User declined",Fb="The user declined the plan, maybe ask why?",$m="The user cancelled the question";function CA(i){switch(i){case Ub:case Fb:return"denied";case $m:return"cancelled";default:return}}var Wm=class{constructor(){this._entries=new Map}begin(n,e,t){this._entries.set(n,{toolName:e,turnId:t,inputBuffer:"",info:void 0})}appendInputDelta(n,e){let t=this._entries.get(n);t&&(t.inputBuffer+=e)}finalize(n){let e=this._entries.get(n);if(!e)return;let t;if(e.inputBuffer.length>0)try{let o=JSON.parse(e.inputBuffer);o!==null&&typeof o=="object"&&(t=o)}catch{}let r=e.inputBuffer.length>0?e.inputBuffer:void 0;this._writeInfo(e,t,r),e.inputBuffer=""}seedParsedInput(n,e){let t=this._entries.get(n);if(!t)return;let r=e!==null&&typeof e=="object"?e:void 0;this._writeInfo(t,r)}_writeInfo(n,e,t){let r=vn(n.toolName);n.info={toolName:n.toolName,displayName:r,parsedInput:e,invocationMessage:yi(n.toolName,r,e),toolInput:po(n.toolName,e)??t}}lookup(n){let e=this._entries.get(n);if(e)return{turnId:e.turnId,toolName:e.toolName,info:e.info}}complete(n){this._entries.delete(n)}clearPending(n){if(this._entries.size!==0){for(let[e,t]of this._entries)n.warn(`[claudeToolCallRegistry] turn ${t.turnId} ended with pending tool_use ${e} (${t.toolName}); dropping cross-message state`);this._entries.clear()}}};var Bm=class{constructor(){this._activeToolBlocks=new Map;this.toolCalls=new Wm;this._completedFileEdits=new Map}resetMessage(n){this._activeToolBlocks.clear(),this._currentMessageId=n}getCurrentMessageId(){return this._currentMessageId}startToolBlock(n,e,t,r){this._activeToolBlocks.set(n,{toolUseId:e,toolName:t}),this.toolCalls.begin(e,t,r)}getActiveToolBlock(n){return this._activeToolBlocks.get(n)}endToolBlock(n){this._activeToolBlocks.delete(n)}appendToolBlockInputDelta(n,e){let t=this._activeToolBlocks.get(n);t&&this.toolCalls.appendInputDelta(t.toolUseId,e)}finalizeToolBlock(n){let e=this._activeToolBlocks.get(n);e&&this.toolCalls.finalize(e.toolUseId)}lookupToolCall(n){let e=this.toolCalls.lookup(n);return e?{turnId:e.turnId,toolName:e.toolName}:void 0}completeToolCall(n){this.toolCalls.complete(n)}cacheFileEdit(n,e){this._completedFileEdits.set(n,e)}takeFileEdit(n){let e=this._completedFileEdits.get(n);return e&&this._completedFileEdits.delete(n),e}clearPendingToolCalls(n){this.toolCalls.clearPending(n)}};function IA(i,n,e,t,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 Hm(D5(i.event,n,e,t,r,i.parent_tool_use_id,o,s),n,i.parent_tool_use_id,o);case"result":return E5(i,n,e,t,r,o);case"assistant":return Hm(R5(i,n,e,t,i.parent_tool_use_id,o),n,i.parent_tool_use_id,o);case"user":return Hm(x5(i,n,t,r,o),n,i.parent_tool_use_id,o);default:return i.type==="system"?vA(i,n,o):[]}}function R5(i,n,e,t,r,o){if(r===null){let s=[];for(let a of i.message.content)a.type!=="tool_use"||!Nb.has(a.name)||s.push(SA(a,n,e,o));return s}return bA(i,n,e,t,r,o)}function x5(i,n,e,t,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){t.warn(`[claudeMapSessionEvents] tool_result for unknown tool_use_id ${a.tool_use_id}`);continue}let d=a.is_error===!0,c=P5(a.content)??[],u=e.takeFileEdit(a.tool_use_id);u&&c.push(u);let p=e.toolCalls.lookup(a.tool_use_id)?.info,m=c.filter(b=>b.type==="text").map(b=>b.text).join(`
`),h=p?Em(p.toolName,p.displayName,p.parsedInput,!d,m):`${vn(l.toolName)} finished`,y=d?CA(m):void 0;s.push({kind:"action",resource:n,action:{type:"chat/toolCallComplete",turnId:l.turnId,toolCallId:a.tool_use_id,result:{success:!d,pastTenseMessage:h,content:c.length>0?c:void 0,...y?{error:{message:m,code:y}}:{}}}}),e.completeToolCall(a.tool_use_id);let S=r.getSpawn(a.tool_use_id);S&&!S.background&&S.markCompleted()&&(s.push({kind:"subagent_completed",chat:n,toolCallId:a.tool_use_id}),r.removeSpawn(a.tool_use_id))}return s}function P5(i){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return;let n=[];for(let e of i)A5(e)&&n.push({type:"text",text:e.text});return n.length>0?n:void 0}function A5(i){if(i===null||typeof i!="object")return!1;let n=i;return n.type==="text"&&typeof n.text=="string"}function E5(i,n,e,t,r,o){let s=[];if(i.subtype==="success"){let l=Object.keys(i.modelUsage)[0];s.push({kind:"action",resource:n,action:{type:"chat/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=k5(i);a!==void 0&&s.push({kind:"action",resource:n,action:{type:"chat/error",turnId:e,error:{errorType:i.subtype,...Ea(a)}}}),t.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 k5(i){if(i.subtype==="success")return i.is_error?i.result:void 0;if(i.subtype==="error_during_execution")return i.errors?.join(`
`)}function D5(i,n,e,t,r,o,s,a){switch(i.type){case"message_start":return t.resetMessage(i.message.id),[];case"content_block_start":{let l=i.content_block;if(l.type==="text")return[{kind:"action",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"markdown",id:qm(e,t,i.index,r),content:""}}}];if(l.type==="thinking")return[{kind:"action",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"reasoning",id:qm(e,t,i.index,r),content:""}}}];if(l.type==="tool_use"){let d=Cl(l.name),c=L1(l.name);t.startToolBlock(i.index,l.id,d,e);let u=!c&&Nb.has(d);o===null?u&&s.recordSpawn(l.id):s.noteInnerTool(l.id,o);let p=hi(d),m=c?a?.(d):void 0;return[{kind:"action",resource:n,action:{type:"chat/toolCallStart",turnId:e,toolCallId:l.id,toolName:d,displayName:vn(d),...m?{contributor:{kind:"client",clientId:m}}:{},...p?{_meta:p}:{}}}]}return[]}case"content_block_delta":{if(i.delta.type==="text_delta")return[{kind:"action",resource:n,action:{type:"chat/delta",turnId:e,partId:qm(e,t,i.index,r),content:i.delta.text}}];if(i.delta.type==="thinking_delta")return[{kind:"action",resource:n,action:{type:"chat/reasoning",turnId:e,partId:qm(e,t,i.index,r),content:i.delta.thinking}}];if(i.delta.type==="input_json_delta"){let l=t.getActiveToolBlock(i.index);return l?(t.appendToolBlockInputDelta(i.index,i.delta.partial_json),[{kind:"action",resource:n,action:{type:"chat/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=t.getActiveToolBlock(i.index);if(t.finalizeToolBlock(i.index),t.endToolBlock(i.index),!l)return[];let c=t.toolCalls.lookup(l.toolUseId)?.info;if(!c)return[];let u=hi(l.toolName);return[{kind:"action",resource:n,action:{type:"chat/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 qm(i,n,e,t){let r=n.getCurrentMessageId();return r===void 0?(t.warn(`[claudeMapSessionEvents] content block at index ${e} arrived before message_start; using turn-scoped id`),`${i}#${e}`):`${i}#${r}#${e}`}var Rl=class extends T{constructor(e,t,r,o,s=void 0,a,l){super();this._chatChannelUri=t;this._subagents=o;this._logService=l;this._onDidProduceSignal=this._register(new P);this.onDidProduceSignal=this._onDidProduceSignal.event;this._mapperState=new Bm;this._clientToolOwner=s,this._editObserver=this._register(a.createInstance(wl,e.toString(),r))}setClientToolOwner(e){this._clientToolOwner=e}async handle(e,t){if(e.type==="assistant"?this._editObserver.observeAssistant(e):e.type==="user"&&t!==void 0&&await this._editObserver.observeUser(e,t,this._mapperState),t!==void 0)try{let r=IA(e,this._chatChannelUri,t,this._mapperState,this._logService,this._subagents,this._clientToolOwner);for(let o of r)this._onDidProduceSignal.fire(o)}catch(r){this._logService.warn(`[ClaudeSdkMessageRouter] mapper threw, skipping message: ${r}`)}}};Rl=w([C(5,Ie),C(6,D)],Rl);var xl=class extends T{constructor(e,t,r,o,s,a,l,d=void 0,c,u){super();this.sessionId=e;this.sessionUri=t;this.chatChannelUri=r;this._logService=u;this._isResumed=!1;this._initPlugins=[];this._needsRebind=!1;this._consumerLoopRunning=!1;this._onDidProduceSignal=this._register(new P);this.onDidProduceSignal=this._onDidProduceSignal.event;this._warm=o,this._abortController=s,this._wireAbortHandler(s),this._queue=this._register(c.createInstance(Tl,e,()=>this._abortController.signal,p=>this._onDidProduceSignal.fire({kind:"steering_consumed",chat:this.chatChannelUri,id:p}))),this._router=this._register(c.createInstance(Rl,t,r,a,l,d)),this._register(this._router.onDidProduceSignal(p=>this._onDidProduceSignal.fire(p))),this._register(M(()=>this._abortController.abort())),this._register(M(()=>{Promise.resolve(this._warm[Symbol.asyncDispose]()).catch(p=>this._logService.warn(`[ClaudeSdkPipeline] WarmQuery dispose failed: ${p}`))}))}async reloadPlugins(){await(await this._ensureQueryBound()).reloadPlugins()}async snapshotResolvedCustomizations(){let e=await this._ensureQueryBound(),[t,r,o]=await Promise.all([e.supportedCommands(),e.supportedAgents(),e.mcpServerStatus()]);return{commands:t,agents:r,mcpServers:o,plugins:this._initPlugins}}async _ensureQueryBound(){return this._needsRebind&&await this._rebindQuery("recover"),this._query||(this._bindWarmQuery(),await this._replayCurrentConfig()),this._query}_bindWarmQuery(){let e=this._warm.query(this._queue.iterable);return this._query=e,e}get isResumed(){return this._isResumed}get isAborted(){return this._abortController.signal.aborted}async shutdownAndWait(){this._abortController.abort();try{await this._warm[Symbol.asyncDispose](),await this._query?.return(void 0)}catch(e){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] shutdownAndWait: teardown failed`,e)}}rebindForRestart(){return this._rebindQuery("restart")}setClientToolOwner(e){this._router.setClientToolOwner(e)}attachRematerializer(e){this._rematerializer=e}seedCurrentConfig(e,t,r){this._currentModel=e,this._currentEffort=t,this._currentPermissionMode=r,this._appliedModel=e,this._appliedEffort=t,this._appliedPermissionMode=r}async setModel(e){if(this._currentModel=e,this._query&&!this._needsRebind&&e!==this._appliedModel)try{await this._query.setModel(e),this._appliedModel=e}catch(t){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] setModel failed: ${t}`)}}async setEffort(e){if(this._currentEffort=e,this._query&&!this._needsRebind&&e!==this._appliedEffort)try{await this._query.applyFlagSettings({effortLevel:e??null}),this._appliedEffort=e}catch(t){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] setEffort failed: ${t}`)}}async send(e,t){if(this._needsRebind&&await this._rebindQuery("recover"),this._abortController.signal.aborted)throw new Y;this._query||(this._bindWarmQuery(),await this._replayCurrentConfig()),this._ensureConsumerLoop();let r={sdkMessage:e,sdkUuid:typeof e.uuid=="string"?e.uuid:t,turnId:t,deferred:new Ee};return this._queue.push(r)}injectSteering(e,t){if(this._abortController.signal.aborted){this._logService.warn(`[Claude:${this.sessionId}] injectSteering: dropped (controller aborted) id=${t}`);return}let r=this._queue.peekParent();if(!r){this._logService.warn(`[Claude:${this.sessionId}] injectSteering: dropped (no in-flight turn) id=${t}`);return}let o=typeof e.uuid=="string"?e.uuid:t;this._queue.push({sdkMessage:e,sdkUuid:o,turnId:r.turnId,deferred:new Ee,steeringPendingId:t}).catch(()=>{}),this._logService.info(`[Claude:${this.sessionId}] injectSteering: enqueued id=${t} sdkUuid=${o}`)}abort(){this._abortController.signal.aborted||(this._abortController.abort(),this._queue.failAll(new Y),this._needsRebind=!0)}async setPermissionMode(e){this._currentPermissionMode=e,this._query&&!this._needsRebind&&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._runConsumerLoop())}_runConsumerLoop(){let e=this._query;this._processMessages().catch(t=>this._logService.error(`[ClaudeSdkPipeline:${this.sessionId}] _processMessages crashed: ${t}`)).finally(()=>{!this._store.isDisposed&&this._query&&this._query!==e?this._runConsumerLoop():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 t=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 Y;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(t[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] previous WarmQuery dispose failed during aborted rebind: ${s}`)),this._queue.failAll(new Y),this._needsRebind=!0,new Y;Promise.resolve(t[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._bindWarmQuery(),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 t of e){if(this._abortController.signal.aborted)throw new Y;t.type==="system"&&t.subtype==="init"&&(this._initPlugins=t.plugins??[],this._isResumed||(this._isResumed=!0));let r=this._queue.peekParent()?.turnId;try{await this._router.handle(t,r)}catch(o){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] router threw, skipping: ${o}`)}if(t.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",resource:this.chatChannelUri,action:{type:"chat/turnComplete",turnId:o.turnId}})}}if(this._abortController.signal.aborted)throw new Y;if(this._query!==e)return;throw new Error("Claude SDK stream ended without a result message")}catch(t){let r=t instanceof Error?t:new Error(String(t));if(this._query===e&&(this._queue.failAll(r),this._needsRebind=!0),!Kn(r))throw r}}};xl=w([C(8,Ie),C(9,D)],xl);function M5(i,n,e){return fo(i,n)??e}var lr=class extends T{constructor(e,t,r,o,s,a,l,d,c,u,p,m,h,y,S,b,I,_,R,A){super();this.sessionId=e;this.sessionUri=t;this.chatChannelUri=r;this.workingDirectory=o;this._pendingClientToolCalls=u;this._permissionModeFallback=m;this._metadataStore=h;this._instantiationService=y;this._configurationService=S;this._sdkService=b;this._sessionDataService=I;this._logService=_;this._fileService=R;this._environmentService=A;this.subagents=this._register(new Dm);this._pendingPermissions=new xt;this._pendingUserInputs=new xt;this.clientCustomizationsDiff=this._register(new Lm);this._onDidSessionProgress=this._register(new P);this.onDidSessionProgress=this._onDidSessionProgress.event;this._currentTurnNanoAiu=0;this._transportKind="proxy";this._onDidCustomizationsChange=this._register(new P);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._lastCustomizations=[];this._chatChannelUri=r,this.project=s,this._provisionalModel=a,this._provisionalAgent=l,this.provisionalConfig=d,this.abortController=c,this.toolDiff=this._register(p),this._register(this.clientCustomizationsDiff.onDidChange(()=>this._onDidCustomizationsChange.fire()));let X=this._register(new Um(this.workingDirectory,this._environmentService.userHome,this._fileService,this._logService));this._register(X.onDidChange(()=>this._onDidCustomizationsChange.fire()))}get _storageUri(){return Ue(this._chatChannelUri)?this.sessionUri:this._chatChannelUri}get pendingClientToolCalls(){return this._pendingClientToolCalls}get permissionModeFallback(){return this._permissionModeFallback}static createProvisional(e,t,r,o,s,a,l,d,c,u,p,m){return m.createInstance(lr,e,t,r,o,s,a,l,d,new AbortController,c,new Om,u,p)}recordTurnCredits(e){Number.isFinite(e)&&e>0&&(this._currentTurnNanoAiu+=e)}_enrichSignalWithCredits(e){if(this._transportKind!=="proxy"||e.kind!=="action"||e.action.type!=="chat/usage"||this._currentTurnNanoAiu<=0)return e;let t=e.action.usage;return{...e,action:{...e.action,usage:{...t,_meta:{...t._meta,copilotUsage:{totalNanoAiu:this._currentTurnNanoAiu}}}}}}_enrichSignalWithMcpContributor(e){if(e.kind!=="action"||e.action.type!=="chat/toolCallStart"||e.action.contributor!==void 0)return e;let t=e.action.toolName;if(!t.startsWith("mcp__"))return e;let r=t.split("__")[1],o=r?Dg(this._lastCustomizations,r):void 0;return o===void 0?e:{...e,action:{...e.action,contributor:{kind:"mcp",customizationId:o}}}}async truncateToTurn(e,t){await this._withDatabase(r=>r.deleteTurnsAfter(e)),this._pendingResumeSessionAt=t}async pruneAllTurns(){await this._withDatabase(e=>e.deleteAllTurns())}async _withDatabase(e){let t=this._sessionDataService.openDatabase(this._storageUri);try{await e(t.object)}finally{t.dispose()}}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`);this._transportKind=e.transport.kind;let t=fo(this._configurationService,this._storageUri)??this._permissionModeFallback,{mcpServers:r,allowedTools:o}=await this._buildStartupToolWiring(e.serverToolHost),s=await Mb(this._provisionalAgent,this._fileService,this._logService,this.sessionId),a=await yb({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:this.abortController,permissionMode:t,canUseTool:e.canUseTool,isResume:e.isResume,resumeSessionAt:this._pendingResumeSessionAt,mcpServers:r,allowedTools:o,plugins:this.clientCustomizationsDiff.consume(),agent:s},e.transport,u=>this._logService.error(`[Claude SDK stderr] ${u}`),u=>this._logService.info(`[Claude] declining elicitation from MCP server (Phase 7 stub): ${u}`));this._logService.info(`[Claude] session ${this.sessionId}: enableFileCheckpointing=${a.enableFileCheckpointing} isResume=${e.isResume}`);let l=await this._sdkService.startup({options:a});if(this.abortController.signal.aborted)throw await l[Symbol.asyncDispose](),new Y;let d=this._sessionDataService.openDatabase(this._storageUri),c;try{c=this._register(this._instantiationService.createInstance(xl,this.sessionId,this.sessionUri,this._chatChannelUri,l,this.abortController,d,this.subagents,u=>this.toolDiff.model.ownerOf(u)))}catch(u){throw d.dispose(),await l[Symbol.asyncDispose](),u}if(this._register(c.onDidProduceSignal(u=>this._onDidSessionProgress.fire(this._enrichSignalWithMcpContributor(this._enrichSignalWithCredits(u))))),this._pipeline=c,this._pendingResumeSessionAt=void 0,c.seedCurrentConfig(ru(this._provisionalModel?.id),ub(eu(this._provisionalModel)),t),!e.isResume)try{await this._metadataStore.write(this._storageUri,{customizationDirectory:this.workingDirectory,model:this._provisionalModel,permissionMode:t,transport:e.transport.kind})}catch(u){throw this._logService.error("[Claude] Failed to persist customization directory; aborting materialize",u),u}if(this.abortController.signal.aborted)throw new Y;c.attachRematerializer(async u=>{let p=fo(this._configurationService,this._storageUri)??this._permissionModeFallback;try{let{mcpServers:m,allowedTools:h}=await this._buildStartupToolWiring(e.serverToolHost),y=await Mb(this._provisionalAgent,this._fileService,this._logService,this.sessionId),S=new AbortController,b=await yb({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:S,permissionMode:p,canUseTool:e.canUseTool,isResume:!0,resumeSessionAt:this._pendingResumeSessionAt,mcpServers:m,allowedTools:h,plugins:this.clientCustomizationsDiff.consume(),agent:y},e.transport,_=>this._logService.error(`[Claude SDK stderr] ${_}`),_=>this._logService.info(`[Claude] declining elicitation from MCP server (Phase 7 stub): ${_}`));this._logService.info(`[Claude] session ${this.sessionId}: resume rebuild agent=${b.agent??"(none)"}`);let I=await this._sdkService.startup({options:b});return this._pendingResumeSessionAt=void 0,{warm:I,abortController:S}}catch(m){throw this.toolDiff.markDirty(),this.clientCustomizationsDiff.markDirty(),m}}),e.serverToolHost?.advertise(this._storageUri.toString()),this._onDidCustomizationsChange.fire()}async _buildStartupToolWiring(e){let t=await U1(this.toolDiff,this._pendingClientToolCalls,this._sdkService),r=e?await X1(e,this._storageUri.toString(),this._sdkService):void 0,o=!t&&!r?void 0:{...t??{},...r?{[Mm]:r}:{}},s=e?e.toolNames.filter(a=>!e.requiresConfirmation(a)):void 0;return{mcpServers:o,allowedTools:s?Q1(s):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}async shutdownLiveQuery(){await this._pipeline?.shutdownAndWait()}seedBijectiveState(e){this._requirePipeline().seedCurrentConfig(e.model,e.effort,e.permissionMode)}attachRematerializer(e){this._requirePipeline().attachRematerializer(e)}async send(e,t){let r=this._requirePipeline();return this._currentTurnNanoAiu=0,this.toolDiff.hasDifference||this.clientCustomizationsDiff.hasDifference||this._pendingResumeSessionAt!==void 0?await this._rebindForSyncedState():await r.setPermissionMode(M5(this._configurationService,this._storageUri,this._permissionModeFallback)),r.send(e,t)}async _rebindForSyncedState(){this._pendingClientToolCalls.rejectAll(new Y),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 t=eu(e),r=ub(t);t==="max"&&this._logService.warn(`[Claude:${this.sessionId}] setModel: 'max' effort clamped to 'xhigh' (Copilot CAPI has no 'max' model yet)`),await this._pipeline.setModel(ru(e.id)),await this._pipeline.setEffort(r)}await this._metadataStore.write(this._storageUri,{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._storageUri,{agent:e??null}))}injectSteering(e){let t=this._requirePipeline();if(t.isAborted)return;let o={type:"user",message:{role:"user",content:Fm(e.message.text,e.message.attachments)},session_id:this.sessionId,parent_tool_use_id:null,priority:"now",uuid:e.id};t.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",chat:this._chatChannelUri,state:e.state,permissionKind:e.permissionKind,...e.permissionPath!==void 0?{permissionPath:e.permissionPath}:{},...e.parentToolCallId!==void 0?{parentToolCallId:e.parentToolCallId}:{}})})}respondToPermissionRequest(e,t){return this._pendingPermissions.respond(e,t)}requestUserInput(e,t){return!this._pipeline||this._pipeline.isAborted?Promise.resolve({response:"cancel"}):this._pendingUserInputs.registerAndFire(e.id,()=>{this._onDidSessionProgress.fire({kind:"action",resource:this._chatChannelUri,action:{type:"chat/inputRequested",request:e},...t!==void 0?{parentToolCallId:t}:{}})})}respondToUserInputRequest(e,t,r){return this._pendingUserInputs.respond(e,{response:t,answers:r})}setClientTools(e,t){this.toolDiff.model.setTools(e,t)}getClientTools(e){return this.toolDiff.model.getTools(e)}removeClientTools(e){this.toolDiff.model.removeClient(e)}removeClientCustomizations(e){this.clientCustomizationsDiff.model.removeClient(e)}completeClientToolCall(e,t){let r=Z1(t,e);return this._pendingClientToolCalls.respond(e,r)}async rebindForClientTools(){await this._rebindForSyncedState()}adoptClientCustomizations(e,t){this.clientCustomizationsDiff.model.setSyncedCustomizations(e,t)}setClientCustomizationEnabled(e,t){this.clientCustomizationsDiff.model.setEnabled(e,t)}getClientCustomizations(){return this.clientCustomizationsDiff.model.state.get().synced}async getSessionCustomizations(){let{synced:e,enablement:t}=this.clientCustomizationsDiff.model.state.get(),r=this._environmentService.userHome,[o,s,a,l,d]=await Promise.all([gA(this.workingDirectory,r,this._fileService),iA(this.workingDirectory,r,this._fileService),nA(this.workingDirectory,r,this._fileService),mA(this.workingDirectory,r,this._fileService),hA(this.workingDirectory,r,this._fileService,this._logService)]),c;if(this._pipeline)try{c=await this._pipeline.snapshotResolvedCustomizations()}catch(m){this._logService.warn(`[Claude:${this.sessionId}] snapshotResolvedCustomizations failed`,m)}let u=fA([...o,...s],a,l,d,this.workingDirectory,r,c),p=e.map(m=>({...m.customization,enabled:t.get(m.customization.id)??m.customization.enabled}));return p.push(...u),this._lastCustomizations=p,p}dispose(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._pendingClientToolCalls.rejectAll(new Y),super.dispose()}};lr=w([C(13,Ie),C(14,ze),C(15,bl),C(16,Je),C(17,D),C(18,xe),C(19,Rt)],lr);function _A(i,n){let e=typeof i.plan=="string"?i.plan:"";return{status:"pending-confirmation",toolCallId:n,toolName:"ExitPlanMode",displayName:vn("ExitPlanMode"),invocationMessage:{markdown:e},toolInput:JSON.stringify(i),confirmationTitle:f(2048,null),options:[{id:"approve",label:f(2046,null),kind:"approve"},{id:"deny",label:f(2047,null),kind:"deny"}]}}function TA(i){let n=i;if(n.questions?.length)return{questions:n.questions}}function wA(i,n){return i||`q-${n}`}function RA(i){return i.questions.map((n,e)=>{let t=n.options.map(o=>({id:o.label,label:o.label,...o.description!==void 0?{description:o.description}:{}})),r=wA(n.header,e);return n.multiSelect?{id:r,kind:"multi-select",title:n.header,message:n.question,options:t,allowFreeformInput:n.allowFreeformInput??!1}:{id:r,kind:"single-select",title:n.header,message:n.question,options:t,allowFreeformInput:n.allowFreeformInput??!1}})}function xA(i,n){let e={};for(let t=0;t<i.questions.length;t++){let r=i.questions[t],o=n[wA(r.header,t)];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 PA(i,n,e,t,r){let o=i.getSession(n);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 O5(i,o,e,t,r)}finally{r.signal.removeEventListener("abort",s)}}async function O5(i,n,e,t,r){if(W1.has(e))return L5(i,n,e,t,r);let o=Am(e),s=vn(e),a=r.blockedPath??Or(e,t),l=po(e,t),d=hi(e),c={status:"pending-confirmation",toolCallId:r.toolUseID,toolName:e,displayName:s,invocationMessage:yi(e,s,t),toolInput:l,confirmationTitle:q1(e),...d?{_meta:d}:{}},u=Hb(n,r);return await n.requestPermission({toolUseID:r.toolUseID,state:c,permissionKind:o,...a!==void 0?{permissionPath:a}:{},...u!==void 0?{parentToolCallId:u}:{}})?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:Ub}}function Hb(i,n){if(!n.agentID)return;let e=i.subagents.getParentSpawn(n.toolUseID);if(e)return e.setAgentId(n.agentID),e.toolUseId}function L5(i,n,e,t,r){switch(e){case"ExitPlanMode":return N5(i,n,t,r);case"AskUserQuestion":return U5(i,n,t,r);default:return Promise.resolve({behavior:"deny",message:`Unsupported interactive tool: ${e}`})}}async function N5(i,n,e,t){let r=t.toolUseID,o=Hb(n,t);return await n.requestPermission({toolUseID:r,state:_A(e,r),permissionKind:Am("ExitPlanMode"),...o!==void 0?{parentToolCallId:o}:{}})?(i.configurationService.updateSessionConfig(n.sessionUri.toString(),{permissionMode:"acceptEdits"}),{behavior:"allow",updatedInput:e}):{behavior:"deny",message:Fb}}async function U5(i,n,e,t){let r=t.toolUseID,o=TA(e);if(!o)return{behavior:"deny",message:"AskUserQuestion called without questions"};let s=Hb(n,t),a=await n.requestUserInput({id:r,questions:RA(o)},s);if(a.response!=="accept"||!a.answers)return{behavior:"deny",message:$m};let l=xA(o,a.answers);return Object.keys(l).length===0?{behavior:"deny",message:$m}:{behavior:"allow",updatedInput:{...e,answers:l}}}import{once as H5}from"events";var F5=["interleaved-thinking","context-management","advanced-tool-use"];function AA(i){let n=i.split(",").map(e=>e.trim()).filter(e=>e&&F5.some(t=>e.startsWith(t+"-")));return n.length>0?n.join(","):void 0}function $b(i,n){return{type:"error",error:{type:i,message:n},request_id:null}}function jn(i,n,e,t){i.writeHead(n,{"Content-Type":"application/json"}),i.end(JSON.stringify($b(e,t)))}function EA(i,n,e){i.writeHead(n,{"Content-Type":"application/json"}),i.end(JSON.stringify(e))}function kA(i){return`event: error
data: ${JSON.stringify(i)}

`}var Vm=$("claudeProxyService"),$5=new Set(["anthropic"]),W5="/v1/messages",Pl="ClaudeProxyService",DA="vscode_claude_code";function Wb(i){let n=i?.copilot_usage?.total_nano_aiu;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}var Al=class extends lo{constructor(e,t){super(Pl,e);this._copilotApiService=t;this._onDidReportCredits=new P;this.onDidReportCredits=this._onDidReportCredits.event}createState(e){return{githubToken:e}}async start(e){let{runtime:t,release:r}=await this.acquire(e);return t.state.githubToken=e,{baseUrl:t.baseUrl,nonce:t.nonce,dispose:r}}dispose(){super.dispose(),this._onDidReportCredits.dispose()}writeInternalError(e){jn(e,500,"api_error","Internal proxy error")}_reportCredits(e,t){e===void 0||t===void 0||(this._logService.trace(`[${Pl}] credits: session=${e} totalNanoAiu=${t}`),this._onDidReportCredits.fire({sessionId:e,totalNanoAiu:t}))}async handleRequest(e,t,r){let o=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${Pl}] ${o} ${s}`),o==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=om(e.headers,r.nonce);if(!a.valid){jn(t,401,"authentication_error","Invalid authentication");return}if(o==="GET"&&s==="/v1/models"){await this._handleModels(e,t,r);return}if(o==="POST"&&s==="/v1/messages"){await this._handleMessages(e,t,r,a.sessionId);return}if(o==="POST"&&s==="/v1/messages/count_tokens"){jn(t,501,"api_error","count_tokens not supported by CAPI");return}jn(t,404,"not_found_error",`No route for ${o} ${s}`)}async _handleModels(e,t,r){let o=MA(e.headers),s;try{s=await this._copilotApiService.models(r.state.githubToken,{headers:o,suppressIntegrationId:!0})}catch(d){this._writeUpstreamErrorResponse(t,d);return}let a=[];for(let d of s){if(!q5(d))continue;let c=ls(d.id),u=c?c.toSdkModelId():d.id;a.push({id:u,type:"model",display_name:d.name||u,created_at:"1970-01-01T00:00:00Z",capabilities:null,max_input_tokens:null,max_tokens:null})}let l={data:a,has_more:!1,first_id:a.length>0?a[0].id:null,last_id:a.length>0?a[a.length-1].id:null};t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(l))}async _handleMessages(e,t,r,o){let s;try{s=await ll(e)}catch(S){jn(t,400,"invalid_request_error",`Failed to read request body: ${zm(S)}`);return}let a;try{a=JSON.parse(s)}catch{jn(t,400,"invalid_request_error","Request body is not valid JSON");return}if(!a||typeof a!="object"){jn(t,400,"invalid_request_error","Request body must be a JSON object");return}let l=a,d=l.model;if(typeof d!="string"||d.length===0){jn(t,400,"invalid_request_error","Missing required field: model");return}if(!Array.isArray(l.messages)){jn(t,400,"invalid_request_error","Missing required field: messages");return}let c=ls(d);if(!c){jn(t,404,"not_found_error",`Unknown model: ${d}`);return}let u=c.toEndpointModelId();l.model=u;let p=l.stream===!0,m=MA(e.headers),h={ac:new AbortController,res:t,clientGone:!1};r.inFlight.add(h);let y=()=>{h.clientGone=!0,h.ac.abort()};t.on("close",y);try{p?await this._streamMessages(l,m,t,h,r,d,o):await this._sendNonStreamingMessage(l,m,t,h,r,d,o)}finally{t.removeListener("close",y),r.inFlight.delete(h)}}async _sendNonStreamingMessage(e,t,r,o,s,a,l){let d={headers:t,signal:o.ac.signal,suppressIntegrationId:!0},c;try{c=await this._copilotApiService.messages(s.state.githubToken,e,d)}catch(m){if(o.ac.signal.aborted){!o.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,m,!0);return}this._reportCredits(l,Wb(c));let u=LA(c.model,this._logService)??a,p={...c,model:u};r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify(p))}async _streamMessages(e,t,r,o,s,a,l){let d={headers:t,signal:o.ac.signal,suppressIntegrationId:!0},c;try{c=this._copilotApiService.messages(s.state.githubToken,e,d)}catch(h){if(o.ac.signal.aborted){!o.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,h,!0);return}let u;try{u=await c.next()}catch(h){if(o.ac.signal.aborted){!o.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,h,!0);return}r.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushHeaders(),V5(r);let p=async h=>{let y=B5(h,this._logService),S=`event: ${y.type}
data: ${JSON.stringify(y)}

`;if(!r.write(S))try{await H5(r,"drain",{signal:o.ac.signal})}catch{return!1}return!0},m;try{if(!u.done&&(m=Wb(u.value)??m,!await p(u.value)))return;for(;;){let h;try{h=await c.next()}catch(S){if(o.ac.signal.aborted){!o.clientGone&&!r.writableEnded&&r.destroy();return}let b=S instanceof ir?OA(S):$b("api_error",zm(S));if(!r.writableEnded){try{r.write(kA(b))}catch{}try{r.end()}catch{}}return}if(h.done)break;if(m=Wb(h.value)??m,!await p(h.value))return}r.writableEnded||r.end(),this._reportCredits(l,m)}catch(h){if(this._logService.warn(`[${Pl}] stream loop unexpected error: ${zm(h)}`),!r.writableEnded)try{r.end()}catch{}}}_writeUpstreamErrorResponse(e,t,r=!1){if(e.headersSent){if(this._logService.warn(`[${Pl}] cannot write upstream error after headers sent: ${zm(t)}`),!e.writableEnded)try{e.end()}catch{}return}if(t instanceof ir){let o=t.status===uc?502:t.status;EA(e,o,r?OA(t):t.envelope);return}jn(e,502,"api_error",t instanceof Error?t.message:String(t))}};Al=w([C(0,D),C(1,It)],Al);function q5(i){return $5.has(i.vendor.toLowerCase())?Array.isArray(i.supported_endpoints)&&i.supported_endpoints.includes(W5):!1}function LA(i,n){let e=ls(i);if(!e){n.warn(`[${Pl}] outbound model ID could not be parsed for SDK rewrite: ${i}`);return}return e.toSdkModelId()}function B5(i,n){if(i.type!=="message_start")return i;let e=LA(i.message.model,n);return e===void 0||e===i.message.model?i:{...i,message:{...i.message,model:e}}}function MA(i){let n={},e=i["anthropic-version"];typeof e=="string"&&e.length>0&&(n["anthropic-version"]=e);let t=i["anthropic-beta"];if(typeof t=="string"&&t.length>0){let o=AA(t);o!==void 0&&(n["anthropic-beta"]=o)}let r=i["user-agent"];return typeof r=="string"&&r.length>0&&(n["User-Agent"]=z5(r)),n}function z5(i){let n=i.indexOf("/");return n===-1?`${DA}/${i}`:`${DA}${i.substring(n)}`}function V5(i){let n=i.socket;if(n&&typeof n.setNoDelay=="function")try{n.setNoDelay(!0)}catch{}}function zm(i){return i instanceof Error?i.message:String(i)}function OA(i){let n=ug(cg(i));return{...i.envelope,error:{...i.envelope.error,message:`${i.envelope.error.message} ${n}`}}}var Vt=class{constructor(n,e){this._provider=n;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"}static{this.KEY_TRANSPORT="claude.transport"}async write(n,e){let t=this._sessionDataService.openDatabase(n),r=t.object;try{let o=[];e.customizationDirectory&&o.push(r.setMetadata(Vt.KEY_CUSTOMIZATION_DIRECTORY,e.customizationDirectory.toString())),e.model&&o.push(r.setMetadata(Vt.KEY_MODEL,K5(e.model))),e.permissionMode&&o.push(r.setMetadata(Vt.KEY_PERMISSION_MODE,e.permissionMode)),e.agent!==void 0&&o.push(r.setMetadata(Vt.KEY_AGENT,e.agent===null?"":JSON.stringify({uri:e.agent.uri}))),e.transport&&o.push(r.setMetadata(Vt.KEY_TRANSPORT,e.transport)),await Promise.all(o)}finally{t.dispose()}}async read(n){let e=await this._sessionDataService.tryOpenDatabase(n);if(!e)return{};try{let[t,r,o,s,a]=await Promise.all([e.object.getMetadata(Vt.KEY_CUSTOMIZATION_DIRECTORY),e.object.getMetadata(Vt.KEY_MODEL),e.object.getMetadata(Vt.KEY_PERMISSION_MODE),e.object.getMetadata(Vt.KEY_AGENT),e.object.getMetadata(Vt.KEY_TRANSPORT)]);return{customizationDirectory:t?v.parse(t):void 0,model:G5(r),permissionMode:as(o),agent:j5(s),transport:a==="proxy"||a==="native"?a:void 0}}finally{e.dispose()}}project(n,e){return{session:L.uri(this._provider,n.sessionId),startTime:n.createdAt??n.lastModified,modifiedTime:n.lastModified,summary:n.customTitle??n.summary,workingDirectory:n.cwd?v.file(n.cwd):void 0,customizationDirectory:e.customizationDirectory}}};Vt=w([C(1,Je)],Vt);function j5(i){if(i)try{let n=JSON.parse(i);if(n&&typeof n=="object"&&typeof n.uri=="string")return{uri:n.uri}}catch{}}function K5(i){return JSON.stringify(i)}function G5(i){if(i){try{let n=JSON.parse(i);if(n&&typeof n=="object"&&typeof n.id=="string"){let e={id:n.id};if(n.config&&typeof n.config=="object"){let t={};for(let[r,o]of Object.entries(n.config))typeof o=="string"&&(t[r]=o);Object.keys(t).length>0&&(e.config=t)}return e}}catch{}return{id:i}}}var J5="vscode_claude_code";function Y5(i){return i.vendor==="Anthropic"&&!!i.supported_endpoints?.includes("/v1/messages")&&!!i.model_picker_enabled&&!!i.capabilities?.supports?.tool_calls&&ls(i.id)!==void 0}function Q5(i,n){let e=i.capabilities?.supports,t=(e?.reasoning_effort??[]).filter(pb),r=fb(t),o=i.policy?.state,s=Gg(i.billing),a=typeof i.model_picker_price_category=="string"?i.model_picker_price_category:void 0;return{provider:n,id:i.id,name:i.name,maxContextWindow:i.capabilities?.limits?.max_context_window_tokens,maxOutputTokens:i.capabilities?.limits?.max_output_tokens,maxPromptTokens:i.capabilities?.limits?.max_prompt_tokens,supportsVision:!!e?.vision,...r?{configSchema:r}:{},...o?{policyState:o}:{},_meta:tl(s,a)}}function X5(i,n){let e=(i.supportedEffortLevels??[]).filter(pb),t=fb(e);return{provider:n,id:i.value,name:i.displayName,supportsVision:!1,...t?{configSchema:t}:{}}}var qb=class{constructor(n,e,t,r,o){this.clientId=n;this.displayName=e;this._getTools=t;this._setTools=r;this._syncCustomizations=o;this._customizations=[]}get tools(){return this._getTools()}set tools(n){this._setTools(n)}get customizations(){return this._customizations}set customizations(n){this._customizations=n,this._syncCustomizations(n)}},El=class extends T{constructor(e,t,r,o,s,a,l,d,c,u){super();this._logService=e;this._copilotApiService=t;this._claudeProxyService=r;this._sdkService=o;this._gitService=s;this._configurationService=a;this._instantiationService=l;this._pluginManager=d;this._productService=c;this._environmentService=u;this.id=Q_;this._onDidSessionProgress=this._register(new P);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new P);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._onDidRequireAuth=this._register(new P);this.onDidRequireAuth=this._onDidRequireAuth.event;this._models=nn(this,[]);this.models=this._models;this._transportMode="proxy";this._sessions=this._register(new Re);this._chatBackings=new Map;this._onDidChangeChatData=this._register(new P);this.onDidChangeChatData=this._onDidChangeChatData.event;this._onDidSpawnChat=this._register(new P);this.onDidSpawnChat=this._onDidSpawnChat.event;this._activeClientHandles=new Map;this._onDidMaterializeSession=this._register(new P);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._disposeSequencer=new at;this._sessionSequencer=new at;this.chats={createChat:(e,t)=>this._createChat(e,t),fork:(e,t,r)=>this._createChat(e,{...r,fork:t}),disposeChat:e=>{let{session:t,chat:r}=this._resolveChatTarget(e);return this._disposeChat(t,r)},sendMessage:(e,t,r,o,s)=>this._sendMessage(e,t,r,o,s),abort:e=>this._abortSession(e),changeModel:(e,t)=>this._changeModel(e,t),changeAgent:(e,t)=>this._changeAgent(e,t),getMessages:e=>this.getSessionMessages(e)};this._metadataStore=l.createInstance(Vt,this.id),this._register(this._claudeProxyService.onDidReportCredits(p=>{this._findSessionBySdkId(p.sessionId)?.recordTurnCredits(p.totalNanoAiu)})),this._transportMode=this._resolveTransportMode(),this._register(this._configurationService.onDidRootConfigChange(()=>{let p=this._resolveTransportMode();p!==this._transportMode&&(this._transportMode=p,this._refreshModels(),p==="proxy"&&!this._proxyHandle&&this._onDidRequireAuth.fire({resource:mt.resource,reason:"required"}))})),this._transportMode==="native"&&queueMicrotask(()=>{this._refreshModels()})}_findAnySession(e){return this._sessions.get(e)?.defaultChat}_findChat(e,t){let r=this._sessions.get(L.id(e));if(r)return r.getChat((t??v.parse(be(e))).toString())}_getChatContext(e){let t=He(e)?e:v.parse(be(e)),r=v.parse(fe(t)),o=L.id(r),s=t.toString(),a=this._sessions.get(o)?.resolveChat(s);return{session:r,sessionId:o,chatKey:s,target:a?.chatSession,isPeerChat:a?!a.isDefault:s!==be(r)}}_findSessionBySdkId(e){for(let t of this._sessions.values())for(let r of t.allChatSessions())if(r.sessionId===e)return r}_wireEntry(e){let t=new jm(e);return t.addDisposable(e.onDidSessionProgress(r=>{this._onDidSessionProgress.fire(r),this._emitSpawnedChatEvents(r)})),t.addDisposable(e.onDidCustomizationsChange(()=>this._onDidCustomizationsChange.fire())),t}_seedSessionEntry(e,t,r){let o=new jm;return o.setDefaultChat(be(t),this._wireEntry(r)),this._sessions.set(e,o),o}_emitSpawnedChatEvents(e){let t=Oo.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_resolveTransportMode(){return this._configurationService.getRootValue(qt,"claudeUseCopilotProxy")??!0?"proxy":"native"}getDescriptor(){return{provider:this.id,displayName:f(2045,null),description:f(2044,null),capabilities:{multipleChats:{fork:!0}}}}getProtectedResources(){return this._transportMode!=="proxy"?[Ht]:[mt,Ht]}_ensureAuthenticated(){if(this._transportMode!=="proxy")return{kind:"native"};let e=this._proxyHandle;if(!e)throw new k(tr,"Authentication is required to use Claude",this.getProtectedResources());return{kind:"proxy",handle:e}}async authenticate(e,t){if(e===Ht.resource)return!0;if(e!==mt.resource)return!1;if(this._transportMode!=="proxy")return this._githubToken=t,!0;if(!(this._githubToken!==t)&&this._proxyHandle)return this._logService.info("[Claude] Auth token unchanged"),!0;let o=await this._claudeProxyService.start(t),s=this._proxyHandle;return this._proxyHandle=o,this._githubToken=t,this._logService.info("[Claude] Auth token updated"),s?.dispose(),this._refreshModels(),!0}_isProxyEnabled(){return this._transportMode==="proxy"}async _refreshModels(){let e=this._isProxyEnabled(),t=this._githubToken;if(e&&!t){this._models.set([],void 0);return}try{let r=e?await this._fetchProxyModels(t):await this._fetchNativeModels();if(this._isProxyEnabled()!==e||e&&this._githubToken!==t)return;this._logService.info(`[Claude] Models refreshed. Count: ${r.length}, ${r.map(o=>o.name).join(", ")}`),this._models.set(r,void 0)}catch(r){this._logService.error(r,"[Claude] Failed to refresh models"),this._isProxyEnabled()===e&&(!e||this._githubToken===t)&&this._models.set([],void 0)}}async _fetchNativeModels(){let e={[Symbol.asyncIterator]:()=>({next:()=>new Promise(()=>{})})},t=F1(),r=await this._sdkService.query({prompt:e,options:t});try{return(await r.supportedModels()).map(s=>X5(s,this.id))}finally{r.close(),t.abortController?.abort()}}async _fetchProxyModels(e){let t=`${J5}/${this._productService.version}`;return(await this._copilotApiService.models(e,{headers:{"User-Agent":t},suppressIntegrationId:!0})).filter(Y5).sort((o,s)=>Number(s.is_chat_default)-Number(o.is_chat_default)).map(o=>Q5(o,this.id))}async createSession(e={}){if(this._ensureAuthenticated(),e.fork)return this._forkSession(e,e.fork);let t=e.session?L.id(e.session):H(),r=L.uri(this.id,t),o=this._findAnySession(t);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 dP(this._environmentService.userHome,t),a=e.workingDirectory?await ar({cwd:e.workingDirectory.fsPath},this._gitService):void 0,l=this._resolvePermissionMode(e.config),d=lr.createProvisional(t,r,v.parse(be(r)),s,a,e.model,e.agent,e.config,new xt,l,this._metadataStore,this._instantiationService);return this._seedSessionEntry(t,r,d),{session:r,workingDirectory:s,provisional:!0,...a?{project:a}:{}}}async truncateSession(e,t){let r=L.id(e);await this._sessionSequencer.queue(r,async()=>{let o=this._findAnySession(r);if(o&&!o.isPipelineReady){this._logService.info(`[Claude:${r}] truncateSession on a provisional session \u2014 nothing to truncate`);return}if(t===void 0){await this._removeAllTurns(e,r,o);return}let s=await this._sdkService.getSessionMessages(r,{includeSystemMessages:!0}),a=km(s,t);if(a===void 0)throw new Error(`Cannot truncate session ${r}: turn ${t} not found in transcript`);await(o??await this._resumeSession(r,e)).truncateToTurn(t,a),this._logService.info(`[Claude:${r}] truncateSession kept [0..${t}] (anchor=${a})`)})}async _removeAllTurns(e,t,r){let o=r?void 0:await this._sdkService.getSessionInfo(t),s=r?.workingDirectory??(o?.cwd?v.file(o.cwd):void 0);if(!s)throw new Error(`Cannot clear session ${t}: workingDirectory missing (SDK cwd absent and no live session)`);let a={};try{a=await this._metadataStore.read(e)}catch(l){this._logService.warn(`[Claude:${t}] overlay read failed during remove-all; continuing with defaults`,l)}await r?.shutdownLiveQuery(),this._sessions.deleteAndDispose(t),await this._sdkService.deleteSession(t),await this.createSession({session:e,workingDirectory:s,...a.model?{model:a.model}:{},...a.agent?{agent:a.agent}:{},...a.permissionMode?{config:{permissionMode:a.permissionMode}}:{}}),await this._findAnySession(t)?.pruneAllTurns(),this._logService.info(`[Claude:${t}] truncateSession removed all turns (deleteSession + fresh same-id)`)}_resolveChatTarget(e){let t=He(e);if(!t)throw new Error(`Claude chat operation requires an AHP chat URI: ${e.toString()}`);return{session:v.parse(t.session),chat:e}}async _forkSession(e,t){if(Qr(t.session))throw new Error("Cannot fork a subagent session");let r=L.id(t.session),o=this._findAnySession(r);if(o&&!o.isPipelineReady)throw new Error("Cannot fork a provisional/never-sent session");return this._sessionSequencer.queue(r,async()=>{let s=await this._sdkService.getSessionMessages(r,{includeSystemMessages:!0}),a=km(s,t.turnId);if(a===void 0)throw new Error(`Cannot fork session ${r}: turn ${t.turnId} not found in transcript`);let{sessionId:l}=await this._sdkService.forkSession(r,{upToMessageId:a}),d=L.uri(this.id,l),c={};try{c=await this._metadataStore.read(t.session)}catch(b){this._logService.warn(`[Claude] fork: source overlay read failed for ${r}; continuing with defaults`,b)}let u=e.model??c.model,p=e.agent??c.agent,m=as(e.config?.permissionMode)??c.permissionMode;await this._metadataStore.write(d,{...u?{model:u}:{},...m?{permissionMode:m}:{},...p?{agent:p}:{}});let h=await this._sdkService.getSessionInfo(l),y=h?.cwd?v.file(h.cwd):e.workingDirectory;if(!y)throw new Error(`Cannot fork session ${r}: forked session ${l} has no working directory (SDK cwd missing and none supplied)`);let S;try{S=await ar({cwd:y.fsPath},this._gitService)}catch(b){this._logService.warn(`[Claude] fork: project resolution failed for ${l}; continuing without project`,b)}return{session:d,workingDirectory:y,...S?{project:S}:{}}})}_makeCanUseTool(e){return(t,r,o)=>PA({getSession:s=>this._findSessionBySdkId(s),configurationService:this._configurationService},e,t,r,o)}async _materializeProvisional(e){let t=this._findAnySession(e);if(!t)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let r=this._ensureAuthenticated(),o=this._makeCanUseTool(e);try{await t.materialize({transport:r,canUseTool:o,isResume:!1,serverToolHost:this._serverToolHost})}catch(s){throw this._sessions.deleteAndDispose(e),s}return this._onDidMaterializeSession.fire({session:t.sessionUri,workingDirectory:t.workingDirectory,project:t.project}),t}async _resumeSession(e,t){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?v.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(t)}catch(p){this._logService.warn(`[Claude:${e}] overlay read failed during resume; continuing with defaults`,p)}let l=fo(this._configurationService,t)??a.permissionMode??"default",d;try{d=await ar({cwd:s.fsPath},this._gitService)}catch(p){this._logService.warn(`[Claude:${e}] project resolution failed during resume; continuing without project`,p)}let c=lr.createProvisional(e,t,v.parse(be(t)),s,d,a.model,a.agent,void 0,new xt,l,this._metadataStore,this._instantiationService);this._seedSessionEntry(e,t,c);let u=this._makeCanUseTool(e);try{await c.materialize({transport:r,canUseTool:u,isResume:!0,serverToolHost:this._serverToolHost})}catch(p){throw this._sessions.deleteAndDispose(e),p}return this._onDidMaterializeSession.fire({session:t,workingDirectory:s,project:d}),c}_resolvePermissionMode(e){return as(e?.permissionMode)??"default"}disposeSession(e){let t=L.id(e);return this._disposeSequencer.queue(t,async()=>{await this._teardownEntry(t),this._pruneActiveClientHandles(t)})}async _teardownEntry(e){let t=this._sessions.get(e);if(!t)return;let r=t.defaultChat;r&&!r.isPipelineReady&&r.abortController.abort(),await Promise.all(t.peerChatKeys().map(o=>this._sessionSequencer.queue(o,async()=>{let s=t.getPeerChat(o);s&&(s.isPipelineReady?s.abort():s.abortController.abort()),t.disposePeerChat(o)}))),this._sessions.deleteAndDispose(e);for(let o of[...this._chatBackings.keys()]){let s=He(v.parse(o));s&&L.id(v.parse(s.session))===e&&this._chatBackings.delete(o)}}async _createChat(e,t){if(this._ensureAuthenticated(),Ue(e))return;let r=He(e);if(!r)throw new Error(`[Claude] createChat: malformed chat URI ${e.toString()}`);let o=v.parse(r.session),s=e.toString(),a=L.id(o),l;return await this._sessionSequencer.queue(a,async()=>{let d=this._chatBackings.get(s);if(d){l={providerData:Er(d),backingSession:L.uri(this.id,d.sdkSessionId)};return}let c=await this._resolveParentSession(o,a),u=t?.model??c.model,p;t?.fork&&(p=await this._forkChat(o,t.fork)),p??=H();let m={sdkSessionId:p,...u?{model:u}:{}};this._chatBackings.set(s,m),l={providerData:Er(m),backingSession:L.uri(this.id,p)},await this._metadataStore.write(e,{...u?{model:u}:{},...c.agent?{agent:c.agent}:{},...c.permissionMode?{permissionMode:c.permissionMode}:{}}),this._logService.info(`[Claude] Created additional chat ${e.toString()} in session ${o.toString()}${t?.fork?" (forked)":""}`)}),l}async _disposeChat(e,t){if(Ue(t))return;let r=t.toString(),o=L.id(e);await this._sessionSequencer.queue(r,async()=>{let s=this._sessions.get(o),a=s?.getPeerChat(r);a&&(a.isPipelineReady?a.abort():a.abortController.abort(),s.disposePeerChat(r)),this._chatBackings.delete(r)})}async _resolveParentSession(e,t){let r=this._findAnySession(t),o=r?.workingDirectory,s=r?.project;if(!o){let d=await this._sdkService.getSessionInfo(t);o=d?.cwd?v.file(d.cwd):void 0}if(!o)throw new Error(`[Claude] createChat: cannot resolve working directory for parent session ${e.toString()}`);if(!s)try{s=await ar({cwd:o.fsPath},this._gitService)}catch(d){this._logService.warn(`[Claude] createChat: project resolution failed for ${e.toString()}; continuing without project`,d)}let a={};try{a=await this._metadataStore.read(e)}catch(d){this._logService.warn(`[Claude] createChat: parent overlay read failed for ${e.toString()}; continuing with defaults`,d)}let l=fo(this._configurationService,e)??a.permissionMode??"default";return{workingDirectory:o,project:s,model:a.model,agent:a.agent,permissionMode:l}}async _forkChat(e,t){let r=await this._resolveChatSdkId(e,t.source);if(!r){this._logService.warn(`[Claude] createChat fork: source ${t.source.toString()} has no SDK chat; creating fresh chat`);return}let o=await this._sdkService.getSessionMessages(r,{includeSystemMessages:!0}),s=km(o,t.turnId);if(s===void 0){this._logService.warn(`[Claude] createChat fork: turn ${t.turnId} not found in source ${r}; creating fresh chat`);return}let{sessionId:a}=await this._sdkService.forkSession(r,{upToMessageId:s});return a}async _resolveChatSdkId(e,t){if(Ue(t)||t.toString()===e.toString())return L.id(e);let r=this._findChat(e,t)?.sessionId;return r||this._resolveChatBacking(t)?.sdkSessionId}_resolveChatBacking(e){return this._chatBackings.get(e.toString())}_ensureSessionEntry(e){let t=L.id(e);return this._sessionSequencer.queue(t,async()=>{let r=this._sessions.get(t);if(r)return r;let o=await this._resolveParentSession(e,t),s=lr.createProvisional(t,e,v.parse(be(e)),o.workingDirectory,o.project,o.model,o.agent,void 0,new xt,o.permissionMode,this._metadataStore,this._instantiationService);return this._seedSessionEntry(t,e,s)})}async _materializeChatLocked(e,t){let r=t.toString(),o=await this._ensureSessionEntry(e),s=o.getPeerChat(r);if(s?.isPipelineReady)return s;let a=s??await this._buildProvisionalChat(e,t,o),l=await this._sdkService.getSessionInfo(a.sessionId),d=this._ensureAuthenticated(),c=this._makeCanUseTool(a.sessionId);try{await a.materialize({transport:d,canUseTool:c,isResume:!!l,serverToolHost:this._serverToolHost})}catch(u){throw o.disposePeerChat(r),u}return a}async _buildProvisionalChat(e,t,r){let o=this._resolveChatBacking(t);if(!o)throw new Error(`[Claude] no backing chat for chat ${t.toString()}`);let s=await this._resolveParentSession(e,L.id(e)),a={};try{a=await this._metadataStore.read(t)}catch(u){this._logService.warn(`[Claude] chat overlay read failed for ${t.toString()}; continuing with defaults`,u)}let l=fo(this._configurationService,t)??a.permissionMode??s.permissionMode,d=a.model??o.model,c=lr.createProvisional(o.sdkSessionId,e,t,s.workingDirectory,s.project,d,a.agent??s.agent,void 0,new xt,l,this._metadataStore,this._instantiationService);return r.registerPeerChat(t.toString(),this._wireEntry(c)),c}async _updateChatBackingModel(e,t){let r=this._resolveChatBacking(e);if(!r)return;let o={sdkSessionId:r.sdkSessionId,model:t};this._chatBackings.set(e.toString(),o),this._onDidChangeChatData.fire({chat:e,providerData:Er(o)})}async materializeChat(e,t){if(Ue(e)||!He(e)||t===void 0)return;let o=Jg(t);if(!o){this._logService.warn(`[Claude] materializeChat: dropping corrupt providerData for ${e.toString()}`);return}this._chatBackings.set(e.toString(),o)}getSessionForTesting(e){let t=this._sessions.get(L.id(e))?.defaultChat;return t?.isPipelineReady?t:void 0}async getSessionMessages(e){if(Qr(e)){let d=gt(e),c=d?this._sessions.get(L.id(d.parentSession))?.defaultChat:void 0;if(!c)return this._logService.warn(`[Claude] getSessionMessages: parent session not found for subagent ${e.toString()} (registry unavailable)`),[];try{return await Y1(e,c.subagents,this._sdkService,this._logService,Ae.None)}catch(u){return this._logService.warn(`[Claude] getSubagentTranscript threw for ${e.toString()}`,u),[]}}let t=He(e)?e:v.parse(be(e)),r=He(t);if(!r)return[];let o=v.parse(r.session),s=L.id(o),a=this._getChatContext(t);if(a.isPeerChat){let d=await this._resolveChatSdkId(o,t);return d?this._reconstructTurns(d,t,a.target):[]}let l=a.target;return l&&!l.isPipelineReady?[]:this._reconstructTurns(s,o,l)}async _reconstructTurns(e,t,r){let o;try{o=await this._sdkService.getSessionMessages(e,{includeSystemMessages:!0})}catch(a){return this._logService.warn(`[Claude] getSessionMessages SDK fetch failed for ${e}`,a),[]}let s;try{s=su(o,t,this._logService)}catch(a){return this._logService.warn(`[Claude] replay mapper threw for ${e}`,a),[]}try{r?.subagents.primeFromTranscript(s)}catch(a){this._logService.warn(`[Claude] primeFromTranscript threw for ${e}`,a)}return s}async listSessions(){let e;try{if(!await this._sdkService.canLoadWithoutDownload())return this._logService.info("[Claude] SDK not downloaded yet; deferring session list until a session triggers the download"),[];e=await this._sdkService.listSessions()}catch(t){return this._logService.warn("[Claude] SDK listSessions failed; surfacing empty list",t),[]}return Promise.all(e.map(async t=>{try{let r=L.uri(this.id,t.sessionId),o=await this._metadataStore.read(r);return this._metadataStore.project(t,o)}catch(r){this._logService.warn(`[Claude] Overlay read failed for session ${t.sessionId}`,r)}return this._metadataStore.project(t,{})}))}async getSessionMetadata(e){let t=L.id(e),r=await this._sdkService.getSessionInfo(t);if(!r)return;let o={};try{o=await this._metadataStore.read(e)}catch(s){this._logService.warn(`[Claude] Overlay read failed for session ${t}`,s)}return this._metadataStore.project(r,o)}resolveSessionConfig(e){let t=pn({permissionMode:we({type:"string",title:f(2032,null),description:f(2043,null),enum:["default","acceptEdits","plan","auto","bypassPermissions"],enumLabels:[f(2039,null),f(2033,null),f(2041,null),f(2035,null),f(2037,null)],enumDescriptions:[f(2040,null),f(2034,null),f(2042,null),f(2036,null),f(2038,null)],default:"default",sessionMutable:!0}),permissions:Jt.definition.permissions}),r=t.validateOrDefault(e.config,{permissionMode:"default"});return Promise.resolve({schema:t.toProtocol(),values:r})}sessionConfigCompletions(e){return Promise.resolve({items:[]})}shutdown(){return this._shutdownPromise??=(async()=>{for(let t of this._sessions.values())for(let r of t.allChatSessions())r.isPipelineReady||r.abortController.abort();let e=[...this._sessions.keys()];await Promise.all(e.map(t=>this._disposeSequencer.queue(t,async()=>{await this._teardownEntry(t),this._pruneActiveClientHandles(t)})))})()}async _sendMessage(e,t,r,o,s){let a=o??H(),l=this._getChatContext(e);return l.isPeerChat?this._sessionSequencer.queue(l.chatKey,async()=>{let d=await this._materializeChatLocked(l.session,e);await d.send(this._buildSdkPrompt(d.sessionId,t,r,a),a)}):this._sessionSequencer.queue(l.sessionId,async()=>{let d=this._getChatContext(e).target,c;d?.isPipelineReady?c=d:d?c=await this._materializeProvisional(l.sessionId):c=await this._resumeSession(l.sessionId,l.session),await c.send(this._buildSdkPrompt(l.sessionId,t,r,a),a)})}_buildSdkPrompt(e,t,r,o){return{type:"user",message:{role:"user",content:Fm(t,r)},session_id:e,parent_tool_use_id:null,uuid:o}}respondToPermissionRequest(e,t){for(let r of this._allLiveSessions())if(r.respondToPermissionRequest(e,t))return}respondToUserInputRequest(e,t,r){for(let o of this._allLiveSessions())if(o.respondToUserInputRequest(e,t,r))return}_allLiveSessions(){let e=[];for(let t of this._sessions.values())e.push(...t.allChatSessions());return e}async _abortSession(e){let t=this._getChatContext(e).target;if(t){if(!t.isPipelineReady){t.abortController.abort();return}t.abort()}}setPendingMessages(e,t,r,o){let s=!!o&&!Ue(o),a=this._findChat(e,o);if(this._logService.info(`[Claude] setPendingMessages for ${(o??e).toString()}: steering=${t?.id??"none"} queued=${r.length}`),!a){this._logService.warn(`[Claude] setPendingMessages: ${s?"chat":"session"} not found for ${(o??e).toString()}`);return}t&&a.injectSteering(t)}async _changeModel(e,t){let r=this._getChatContext(e),o=r.isPeerChat?r.chatKey:r.sessionId;await this._sessionSequencer.queue(o,async()=>{let s=this._getChatContext(e),a=s.target;a?await a.setModel(t):s.isPeerChat?await this._metadataStore.write(e,{model:t}):await this._metadataStore.write(s.session,{model:t}),s.isPeerChat&&await this._updateChatBackingModel(e,t)})}async _changeAgent(e,t){let r=this._getChatContext(e),o=r.isPeerChat?r.chatKey:r.sessionId;await this._sessionSequencer.queue(o,async()=>{let s=this._getChatContext(e),a=s.target;a?await a.setAgent(t):await this._metadataStore.write(s.isPeerChat?e:s.session,{agent:t??null})})}setServerToolHost(e){this._serverToolHost=e}getOrCreateActiveClient(e,t){let r=L.id(e),o=`${r}\0${t.clientId}`,s=this._activeClientHandles.get(o);return s||(s=new qb(t.clientId,t.displayName,()=>this._findAnySession(r)?.getClientTools(t.clientId)??[],a=>{this._logService.info(`[Claude:${r}] active client ${t.clientId} tools=[${a.map(l=>l.name).join(", ")||"(none)"}]`),this._findAnySession(r)?.setClientTools(t.clientId,a)},a=>{this.syncClientCustomizations(e,t.clientId,[...a])}),this._activeClientHandles.set(o,s)),s}removeActiveClient(e,t){let r=L.id(e);this._activeClientHandles.delete(`${r}\0${t}`),this._findAnySession(r)?.removeClientTools(t),this._sessionSequencer.queue(r,async()=>{this._findAnySession(r)?.removeClientCustomizations(t)}).catch(()=>{})}_pruneActiveClientHandles(e){let t=`${e}\0`;for(let r of[...this._activeClientHandles.keys()])r.startsWith(t)&&this._activeClientHandles.delete(r)}onClientToolCallComplete(e,t,r,o){let s=e,a;for(;a=gt(s);)s=a.parentSession;let l=L.id(s);this._sessions.get(l)?.defaultChat?.completeClientToolCall(r,o)}async syncClientCustomizations(e,t,r){let o=L.id(e),s=this._findAnySession(o);return s?this._sessionSequencer.queue(o,async()=>{let a=await this._pluginManager.syncCustomizations(t,r,l=>this._fireCustomizationUpdated(e,{customization:l}));return s.adoptClientCustomizations(t,a),a}):(this._logService.warn(`[Claude:${o}] syncClientCustomizations: session not found`),[])}_fireCustomizationUpdated(e,t){this._onDidSessionProgress.fire({kind:"action",resource:e,action:{type:"session/customizationUpdated",customization:t.customization}})}setCustomizationEnabled(e,t){for(let r of this._sessions.values())r.defaultChat.setClientCustomizationEnabled(e,t)}getCustomizations(){return[]}async getSessionCustomizations(e){let t=this._findAnySession(L.id(e));return t?await t.getSessionCustomizations():[]}dispose(){for(let e of this._sessions.values())for(let t of e.allChatSessions())t.isPipelineReady||t.abortController.abort();super.dispose(),this._proxyHandle?.dispose(),this._proxyHandle=void 0,this._githubToken=void 0,this._models.set([],void 0)}};El=w([C(0,D),C(1,It),C(2,Vm),C(3,bl),C(4,Ye),C(5,ze),C(6,Ie),C(7,nl),C(8,Ct),C(9,Rt)],El);var jm=class extends rl{get defaultChat(){return super.defaultChat}};import{spawn as h7}from"child_process";import*as mo from"fs";function NA(i,n){switch(i){case"ready":return{kind:"ready"};case"starting":return{kind:"starting"};case"failed":return{kind:"error",error:{errorType:"mcp-server-failed",message:n??"MCP server failed to start"}};case"cancelled":return{kind:"stopped"};default:return{kind:"stopped"}}}function Z5(i){let n=[];for(let e of Object.keys(i)){let t=i[e];t&&n.push(t)}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}function e7(i){return{state:{kind:"ready"},tools:Z5(i.tools),resources:i.resources,resourceTemplates:i.resourceTemplates}}function UA(i){let n=new Map;for(let e of i)n.set(e.name,e7(e));return n}function Bb(i){let n=[];for(let[e,t]of i)n.push({name:e,state:t.state});return n}function FA(i,n){switch(i){case"tools/list":return{handled:!0,result:{tools:n.tools}};case"resources/list":return{handled:!0,result:{resources:n.resources}};case"resources/templates/list":return{handled:!0,result:{resourceTemplates:n.resourceTemplates}};default:return{handled:!1}}}function HA(i,n){let e=(i?.tools??[]).map(r=>r.name).sort(),t=(n?.tools??[]).map(r=>r.name).sort();return e.length!==t.length?!0:e.some((r,o)=>r!==t[o])}function WA(i,n){if(n.mode==="url"){let r={id:i,message:n.message};return n.url&&(r.url=n.url),r}let e=new Set(n.requestedSchema.required??[]),t=[];for(let[r,o]of Object.entries(n.requestedSchema.properties))o&&t.push(t7(r,o,e.has(r)));return t.length>0?{id:i,message:n.message,questions:t}:{id:i,message:n.message}}function qA(i,n,e){if(n==="decline")return{action:"decline",content:null,_meta:null};if(n!=="accept")return{action:"cancel",content:null,_meta:null};if(i.mode==="url")return{action:"accept",content:null,_meta:null};let t={};for(let[r,o]of Object.entries(i.requestedSchema.properties)){if(!o)continue;let s=n7(e?.[r]);s!==void 0&&(t[r]=s)}return{action:"accept",content:t,_meta:null}}function BA(){return{action:"decline",content:null,_meta:null}}function zA(){return{action:"cancel",content:null,_meta:null}}function t7(i,n,e){let t={id:i,title:n.title,message:n.description??n.title??i,required:e};switch(n.type){case"boolean":return{...t,kind:"boolean",defaultValue:n.default};case"number":case"integer":return{...t,kind:n.type==="integer"?"integer":"number",min:n.minimum,max:n.maximum,defaultValue:n.default};case"array":return{...t,kind:"multi-select",options:me(n.items,{anyOf:!0})?n.items.anyOf.map(r=>({id:r.const,label:r.title||r.const})):n.items.enum.map(r=>({id:r,label:r})),min:$A(n.minItems),max:$A(n.maxItems)};case"string":if(me(n,{oneOf:!0}))return{...t,kind:"single-select",options:n.oneOf.map(r=>({id:r.const,label:r.title||r.const}))};if(me(n,{enum:!0})){let r=n.enumNames;return{...t,kind:"single-select",options:n.enum.map((o,s)=>({id:o,label:r?.[s]||o}))}}return{...t,kind:"text",format:n.format,min:n.minLength,max:n.maxLength,defaultValue:n.default}}}function n7(i){if(!i||i.state==="skipped")return;let{value:n}=i;switch(n.kind){case"text":return n.value;case"number":return n.value;case"boolean":return n.value;case"selected":return n.value;case"selected-many":return n.value}}function $A(i){return i==null?void 0:Number(i)}var go=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r;this.name="JsonRpcError"}},r7=2e3,Km=class extends T{constructor(e,t,r=r7){super();this._transport=e;this._onLog=t;this._graceKillMs=r;this._onExit=this._register(new P);this.onExit=this._onExit.event;this._onTransportError=this._register(new P);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=t=>{let r=typeof t=="string"?t:t.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),M(()=>this._transport.stdout.off("data",e))}_dispatch(e){let t=me(e,{id:!0}),r=me(e,{method:!0});if(t&&!r&&(me(e,{result:!0})||me(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),me(e,{error:!0})&&e.error?s.reject(new go(e.error.code,e.error.message,e.error.data)):s.resolve(e.result);return}if(r&&t&&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 t=this._requestHandlers.get(e.method);if(!t){this._writeMessage({id:e.id,error:{code:-32601,message:`Method not found: ${e.method}`}});return}try{let r=await t(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 t=this._notificationHandlers.get(e.method);if(!t){this._log("warn",`dropping unhandled notification: ${e.method}`);return}try{t(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(t){return this._onTransportError.fire(t instanceof Error?t:new Error(String(t))),!1}}_handleExit(e){if(this._exited)return;this._exited=!0;let t=`codex app-server exited (code=${e.code}, signal=${e.signal})`;for(let[r,o]of this._pending)o.reject(new go(-32603,`${t}; request id=${r} (${o.method}) aborted`));this._pending.clear(),this._onExit.fire(e)}request(e,t){if(this._disposed)return Promise.reject(new Y);if(this._exited)return Promise.reject(new go(-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:t})||(this._pending.delete(r),s(new go(-32603,"write failed; transport closed")))})}notify(e,t){let r={method:e};t!==void 0&&(r.params=t),this._writeMessage(r)}onNotification(e,t){return this._notificationHandlers.set(e,t),M(()=>{this._notificationHandlers.get(e)===t&&this._notificationHandlers.delete(e)})}onRequest(e,t){let r=async o=>await t(o);return this._requestHandlers.set(e,r),M(()=>{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 Y);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,t){this._onLog?.(e,t)}};function VA(i){if(!i.stdin||!i.stdout)throw new Error("Child process has no stdio pair");return{stdin:i.stdin,stdout:i.stdout,kill:n=>i.kill(n),onExit:ee.fromNodeEventEmitter(i,"exit",(n,e)=>({code:n,signal:e})),onExitOnce:n=>i.once("exit",(e,t)=>n({code:e,signal:t}))}}import*as Dl from"fs";var Gm=$("codexProxyService"),Xt="CodexProxyService",jA="vscode_codex",i7="VSCODE_CODEX_PROXY_DUMP_DIR",o7=0;function s7(){return String(++o7).padStart(4,"0")}function a7(){let i=process.env[i7];if(i)try{return Dl.mkdirSync(i,{recursive:!0}),i}catch{return}}function lu(i,n,e,t){i.headersSent||i.writableEnded||(i.writeHead(n,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:{type:e,message:t}})))}var kl=class extends lo{constructor(e,t){super(Xt,e);this._copilotApiService=t}createState(e){return{githubToken:e}}async start(e){let{runtime:t,release:r}=await this.acquire(e);t.state.githubToken=e;let o=!1;return{baseUrl:t.baseUrl,nonce:t.nonce,setToken:s=>{o||(t.state.githubToken=s)},dispose:()=>{o||(o=!0,r())}}}async handleRequest(e,t,r){let o=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname,a=Object.keys(e.headers).join(", ");if(this._logService.info(`[${Xt}] >>> ${o} ${s} (headers: ${a})`),o==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let l=e.headers.authorization,d=`Bearer ${r.nonce}`;if(typeof l!="string"||l!==d){lu(t,401,"authentication_error","Invalid authentication");return}if(o==="POST"&&(s==="/v1/responses"||s==="/responses"||s==="//responses")){await this._handleResponses(e,t,r);return}lu(t,404,"not_found_error",`No route for ${o} ${s}`)}async _handleResponses(e,t,r){let o;try{o=await ll(e)}catch(p){lu(t,400,"invalid_request_error",`Failed to read request body: ${p instanceof Error?p.message:String(p)}`);return}let s=a7(),a=s?s7():void 0;if(s&&a){let p=j(s,`req-${a}-${Date.now()}.json`);try{Dl.writeFileSync(p,o),this._logService.info(`[${Xt}] dumped request body to ${p}`)}catch(m){this._logService.warn(`[${Xt}] failed to dump request body: ${m instanceof Error?m.message:String(m)}`)}}try{let p=JSON.parse(o);if(this._logService.info(`[${Xt}] >>> /responses body: model=${p.model??"<none>"}, previous_response_id=${p.previous_response_id??"<none>"}, stream=${p.stream??"<none>"}, input_items=${Array.isArray(p.input)?p.input.length:"<not-array>"}`),Array.isArray(p.input))for(let h=0;h<p.input.length;h++){let y=p.input[h],S=y?.type??"<none>",b=y&&typeof y=="object"?Object.keys(y).join(","):typeof y,I="";if(S==="message"){let _=y?.content?.[0]?.text??"";I=`role=${y?.role??"?"} chars=${_.length}`}else if(S==="function_call")I=`name=${y?.name??"?"} call_id=${y?.call_id??"?"}`;else if(S==="function_call_output"){let _=y?.output??"";I=`call_id=${y?.call_id??"?"} output_chars=${typeof _=="string"?_.length:0}`}else if(S==="reasoning"){let _=y?.summary??y?.content??"";I=`summary_chars=${typeof _=="string"?_.length:JSON.stringify(_).length} encrypted=${typeof y?.encrypted_content=="string"}`}else I=JSON.stringify(y).slice(0,120);this._logService.info(`[${Xt}]   input[${h}] type=${S} keys=[${b}] ${I}`)}let m=Object.keys(p).filter(h=>h!=="input").sort();this._logService.info(`[${Xt}]   top-level keys (excl. input)=[${m.join(", ")}]`);for(let h of m){if(h==="instructions"||h==="tools"){let b=p[h],I=typeof b=="string"?b.length:JSON.stringify(b).length;this._logService.info(`[${Xt}]     ${h}=<${I} chars elided>`);continue}let y=p[h],S=typeof y=="object"?JSON.stringify(y).slice(0,300):String(y);this._logService.info(`[${Xt}]     ${h}=${S}`)}}catch{this._logService.info(`[${Xt}] >>> /responses body (unparseable): ${o.slice(0,200)}`)}let l={ac:new AbortController,res:t,clientGone:!1};r.inFlight.add(l);let d=()=>{l.clientGone=!0,l.ac.abort()};t.on("close",d);let c=r.state.githubToken,u=l7(e.headers);try{this._logService.info(`[${Xt}] forwarding to CAPI responses...`);let p=await this._copilotApiService.responses(c,o,{headers:u,signal:l.ac.signal,suppressIntegrationId:!0}),m=p.headers.get("content-type")??"application/json",h=[...p.headers.entries()].map(([_,R])=>`${_}: ${R}`).join(", ");if(this._logService.info(`[${Xt}] <<< CAPI response: status=${p.status}, contentType=${m}, headers=[${h}]`),t.writeHead(p.status,{"Content-Type":m}),!p.body){t.end();return}let y=p.body.getReader(),S=s&&a?Dl.createWriteStream(j(s,`res-${a}-${Date.now()}.txt`)):void 0,b="",I={};try{for(;;){let{done:_,value:R}=await y.read();if(_||l.clientGone)break;if(R&&R.byteLength>0){let A=Buffer.from(R);t.write(A),S&&S.write(A),b+=A.toString("utf8");let X;for(;(X=b.indexOf(`
`))>=0;){let E=b.slice(0,X).trimEnd();if(b=b.slice(X+1),E.startsWith("event:")){let z=E.slice(6).trim();I[z]=(I[z]??0)+1}}}}}finally{try{y.releaseLock()}catch{}S?.end()}if(Object.keys(I).length){let _=Object.entries(I).map(([R,A])=>`${R}=${A}`).join(", ");this._logService.info(`[${Xt}] <<< SSE event counts: ${_}`)}t.end()}catch(p){if(l.clientGone){this._logService.info(`[${Xt}] client disconnected during upstream call`);return}if(p instanceof ir){this._logService.error(`[${Xt}] CAPI error: status=${p.status}, message=${p.message}`);let m=ug(cg(p));lu(t,p.status,"api_error",`${p.message} ${m}`);return}this._logService.error(`[${Xt}] upstream error: ${p instanceof Error?p.message:String(p)}`),lu(t,502,"api_error",p instanceof Error?p.message:String(p))}finally{t.removeListener("close",d),r.inFlight.delete(l)}}};kl=w([C(0,D),C(1,It)],kl);function l7(i){let n={},e=i["user-agent"];return typeof e=="string"&&e.length>0&&(n["User-Agent"]=d7(e)),n}function d7(i){let n=i.indexOf("/");return n===-1?`${jA}/${i}`:`${jA}${i.substring(n)}`}function zb(i=new Set,n=new Pn){return{itemToPartId:new Map,itemToToolCall:new Map,itemToReasoningPartId:new Map,currentTurnId:void 0,clientToolSet:n,serverToolNames:i,mcpCustomizationIds:new Map,declinedToolCalls:new Set}}function Vb(i){i.itemToPartId.clear(),i.itemToToolCall.clear(),i.itemToReasoningPartId.clear(),i.declinedToolCalls.clear()}function jb(i){let n=[];for(let e of i)e.type==="text"&&n.push(e.text);return n.join(`

`)}function Kb(i,n,e){return`${i}:${n}:${e}`}function Gb(i,n,e){let t=i.itemToReasoningPartId.get(e);if(t)return{partId:t,actions:[]};let r=H();return i.itemToReasoningPartId.set(e,r),{partId:r,actions:[{type:"chat/responsePart",turnId:n,part:{kind:"reasoning",id:r,content:""}}]}}function JA(i,n){return n?.type==="search"?n.queries?.join(", ")??n.query??i:n?.type==="openPage"?n.url??i:n?.type==="findInPage"&&[n.pattern,n.url].filter(Boolean).join(" in ")||i}function YA(i){return i.map(n=>`${n.kind.type==="update"&&n.kind.move_path?`rename from ${n.kind.move_path}`:n.kind.type}: ${n.path}`).join(`
`)}function Jb(i){return i.map(n=>`${YA([n])}
${n.diff}`.trim()).join(`

`)}function KA(i){return typeof i=="string"?i:JSON.stringify(i,null,2)}function GA(i){return JSON.stringify(i,null,2)}function QA(i){return i?.map(n=>n.type==="inputText"?n.text:n.imageUrl).join(`
`)??""}function c7(i,n){if(n)return n;if(!i)return"";let e=i.content.map(KA).join(`
`),t=i.structuredContent!==null?KA(i.structuredContent):"";return[e,t].filter(Boolean).join(`
`)}function XA(i,n,e){i.currentTurnId=n.turn.id,Vb(i);let t=e,r=n.turn.items?.[0];if(r&&r.type==="userMessage"){let o=jb(r.content);o.length>0&&(t=o)}return[{type:"chat/turnStarted",turnId:n.turn.id,message:{text:t,origin:{kind:"user"}}}]}function ZA(i,n){return Gb(i,n.turnId,Kb(n.itemId,"summary",n.summaryIndex)).actions}function eE(i,n){let e=Gb(i,n.turnId,Kb(n.itemId,"summary",n.summaryIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function tE(i,n){let e=Gb(i,n.turnId,Kb(n.itemId,"text",n.contentIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function u7(i,n){for(let e of[...i.itemToReasoningPartId.keys()])e.startsWith(`${n}:`)&&i.itemToReasoningPartId.delete(e)}function nE(i){let n=i.tokenUsage.last;return[{type:"chat/usage",turnId:i.turnId,usage:{inputTokens:n.inputTokens,outputTokens:n.outputTokens,cacheReadTokens:n.cachedInputTokens,_meta:{reasoningOutputTokens:n.reasoningOutputTokens,modelContextWindow:i.tokenUsage.modelContextWindow}}}]}function rE(i,n){if(n.item.type==="agentMessage"){let e=H();return i.itemToPartId.set(n.item.id,e),[{type:"chat/responsePart",turnId:n.turnId,part:{kind:"markdown",id:e,content:n.item.text??""}}]}if(n.item.type==="commandExecution"){let e=H();i.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"shell",output:""});let t=n.item.command??"";return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"shell",displayName:"Run shell command",_meta:Qt({toolKind:"terminal"})},{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:t},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:t,toolInput:t,confirmed:"not-needed",_meta:Qt({toolKind:"terminal"})}]}if(n.item.type==="webSearch"){let e=H();i.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"web_search",output:""});let t=JA(n.item.query,n.item.action);return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"web_search",displayName:"Web search",_meta:Qt({toolKind:"search"})},{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:t},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:t,toolInput:t,confirmed:"not-needed",_meta:Qt({toolKind:"search"})}]}if(n.item.type==="fileChange"){let e=H(),t=Jb(n.item.changes);i.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"file_edit",output:t});let r=YA(n.item.changes)||"Apply file changes";return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"file_edit",displayName:"Apply file changes"},{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:r},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:r,toolInput:r,confirmed:"not-needed"},...t?[{type:"chat/toolCallContentChanged",turnId:n.turnId,toolCallId:e,content:[{type:"text",text:t}]}]:[]]}if(n.item.type==="mcpToolCall"){let e=H(),t=`${n.item.server}.${n.item.tool}`,r=GA(n.item.arguments),o=i.mcpCustomizationIds.get(n.item.server);return i.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:t,output:""}),[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:t,displayName:n.item.tool,...o?{contributor:{kind:"mcp",customizationId:o}}:{}},{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:r},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:`Calling ${t}`,toolInput:r,confirmed:"not-needed"}]}if(n.item.type==="dynamicToolCall"){let e=H(),t=n.item.namespace?`${n.item.namespace}.${n.item.tool}`:n.item.tool,r=GA(n.item.arguments),o=QA(n.item.contentItems),a=n.item.namespace===null&&i.serverToolNames.has(n.item.tool)?void 0:i.clientToolSet.ownerOf(n.item.tool),l=or(n.item.tool,n.item.arguments);return i.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:t,output:o}),[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:t,displayName:l?.displayName??n.item.tool,...a?{contributor:{kind:"client",clientId:a}}:{}},{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:r},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:l?.invocationMessage??`Calling ${t}`,toolInput:r,confirmed:"not-needed"},...o?[{type:"chat/toolCallContentChanged",turnId:n.turnId,toolCallId:e,content:[{type:"text",text:o}]}]:[]]}return[]}function iE(i,n){let e=i.itemToToolCall.get(n.itemId);return e?(e.output+=n.delta,[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function oE(i,n){let e=i.itemToToolCall.get(n.itemId);return e?(e.output=Jb(n.changes),[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:e.output?[{type:"text",text:e.output}]:[]}]):[]}function sE(i,n){let e=i.itemToToolCall.get(n.itemId);return e?(e.output+=n.delta,[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function aE(i,n){let e=i.itemToToolCall.get(n.itemId);return e?(e.output=[e.output,n.message].filter(Boolean).join(`
`),[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:[{type:"text",text:e.output}]}]):[]}function lE(i,n){let e=i.itemToPartId.get(n.itemId);return e?[{type:"chat/delta",turnId:n.turnId,partId:e,content:n.delta}]:[]}function dE(i,n){if(n.item.type==="agentMessage")return i.itemToPartId.delete(n.item.id),[];if(n.item.type==="reasoning")return u7(i,n.item.id),[];let e=i.itemToToolCall.get(n.item.id);if(!e)return[];i.itemToToolCall.delete(n.item.id);let t=i.declinedToolCalls.delete(e.toolCallId);if(n.item.type==="commandExecution"){let r=n.item.status==="completed"&&(n.item.exitCode===0||n.item.exitCode===null),o=n.item.aggregatedOutput??e.output,s=n.item.command??"",a=n.item.exitCode,l=r?`Ran \`${s}\``:a!==null?`Ran \`${s}\` (exit ${a})`:`Ran \`${s}\` (failed)`;return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:r,pastTenseMessage:l,content:o?[{type:"text",text:o}]:void 0,error:r?void 0:{message:a!==null?`Exit code ${a}`:"Command failed",...t?{code:"denied"}:{}}}}]}if(n.item.type==="webSearch"){let r=JA(n.item.query,n.item.action);return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:!0,pastTenseMessage:`Searched ${r}`}}]}if(n.item.type==="fileChange"){let r=Jb(n.item.changes)||e.output,o=n.item.status==="completed",s=r?[{type:"text",text:r}]:void 0,a={success:o,pastTenseMessage:o?"Applied file changes":"Failed to apply file changes",content:s,...o?{}:{error:{message:`Patch ${n.item.status}`,...t?{code:"denied"}:{}}}};return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:a}]}if(n.item.type==="mcpToolCall"){let r=n.item.status==="completed"&&!n.item.error,o=c7(n.item.result,n.item.error?.message)||e.output,s=o?[{type:"text",text:o}]:void 0;return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:r,pastTenseMessage:r?`Called ${e.toolName}`:`Failed to call ${e.toolName}`,content:s,...r?{}:{error:{message:n.item.error?.message??`MCP tool ${n.item.status}`,...t?{code:"denied"}:{}}}}}]}if(n.item.type==="dynamicToolCall"){let r=n.item.success===!0||n.item.status==="completed",o=QA(n.item.contentItems)||e.output,s=o?[{type:"text",text:o}]:void 0,a=r?or(e.toolName,n.item.arguments,{text:o,success:r})?.pastTenseMessage:void 0;return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:r,pastTenseMessage:a??(r?`Called ${e.toolName}`:`Failed to call ${e.toolName}`),content:s,...r?{}:{error:{message:`Dynamic tool ${n.item.status}`,...t?{code:"denied"}:{}}}}}]}return[]}function cE(i,n){i.currentTurnId=void 0,i.itemToPartId.clear(),i.itemToReasoningPartId.clear();let e=[...i.itemToToolCall.values()];i.itemToToolCall.clear();let t=n.turn.id,r=n.turn.status,o=e.map(s=>({type:"chat/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"&&n.turn.error){let s=n.turn.error.message??"Codex turn failed";return[...o,{type:"chat/error",turnId:t,error:{errorType:"CodexError",...Ea(s)}},{type:"chat/turnComplete",turnId:t}]}return r==="interrupted"?[...o,{type:"chat/turnCancelled",turnId:t}]:[...o,{type:"chat/turnComplete",turnId:t}]}function uE(i){switch(i){case"completed":return"complete";case"interrupted":return"cancelled";case"failed":return"error";default:return"complete"}}import*as pE from"crypto";import*as fE from"fs";import*as gE from"os";var p7=[];function Yb(i,n){let e=[],t=[],r=[i];if(n&&n.length>0)for(let s of n)switch(s.type){case"resource":{let a=v.parse(s.uri);a.scheme==="file"?r.push(`@${a.fsPath}`):r.push(a.toString());break}case"embeddedResource":{if(s.contentType.startsWith("image/")){let a=f7(s.contentType),l=j(gE.tmpdir(),`codex-img-${pE.randomBytes(8).toString("hex")}${a}`);try{fE.writeFileSync(l,Buffer.from(s.data,"base64")),e.push(l),t.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 t.unshift({type:"text",text:o,text_elements:p7}),{input:t,cleanupPaths:e}}function f7(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 mE(i,n){return{id:i,questions:n.map(e=>e.options&&e.options.length>0?{kind:"single-select",id:e.id,title:e.header,message:e.question,required:!0,options:e.options.map(t=>({id:t.label,label:t.label,description:t.description||void 0})),allowFreeformInput:e.isOther}:{kind:"text",id:e.id,title:e.header,message:e.question,required:!0})}}function hE(i,n,e){let t={};for(let r of i)t[r.id]={answers:g7(e?.[r.id],n)};return{answers:t}}function Qb(i){let n={};for(let e of i)n[e.id]={answers:[]};return{answers:n}}function g7(i,n){if(n!=="accept"||!i||i.state==="skipped")return[];let{value:e}=i;switch(e.kind){case"text":return[e.value];case"number":case"boolean":return[String(e.value)];case"selected":return[e.value,...e.freeformValues??[]];case"selected-many":return[...e.value,...e.freeformValues??[]]}}function yE(i){let n=[];for(let e of i.turns??[]){let t=m7(e);t&&n.push(t)}return n}function m7(i){let n="",e=[];for(let t of i.items??[])if(t.type==="userMessage"){let r=[];for(let o of t.content)o.type==="text"&&r.push(o.text);r.length>0&&(n=r.join(`

`))}else t.type==="agentMessage"&&t.text&&t.text.length>0&&e.push({kind:"markdown",id:H(),content:t.text});if(!(!n&&e.length===0))return{id:i.id,message:{text:n,origin:{kind:"user"}},responseParts:e,usage:void 0,state:uE(i.status)}}var kn=class{constructor(n,e){this._sessionDataService=n;this._logService=e}static{this.KEY_THREAD_ID="codex.threadId"}static{this.KEY_CWD="codex.cwd"}static{this.KEY_MODEL="codex.model"}async write(n,e){try{let t=this._sessionDataService.openDatabase(n),r=t.object;try{let o=[];e.threadId!==void 0&&o.push(r.setMetadata(kn.KEY_THREAD_ID,e.threadId)),e.cwd!==void 0&&o.push(r.setMetadata(kn.KEY_CWD,e.cwd.toString())),e.modelId!==void 0&&o.push(r.setMetadata(kn.KEY_MODEL,e.modelId)),await Promise.all(o)}finally{t.dispose()}}catch(t){this._logService.warn(`[Codex] metadata write failed for ${n.toString()}: ${t instanceof Error?t.message:String(t)}`)}}async read(n){try{let e=await this._sessionDataService.tryOpenDatabase(n);if(!e)return{};try{let[t,r,o]=await Promise.all([e.object.getMetadata(kn.KEY_THREAD_ID),e.object.getMetadata(kn.KEY_CWD),e.object.getMetadata(kn.KEY_MODEL)]);return{threadId:t??void 0,cwd:r?v.parse(r):void 0,modelId:o??void 0}}finally{e.dispose()}}catch(e){return this._logService.warn(`[Codex] metadata read failed for ${n.toString()}: ${e instanceof Error?e.message:String(e)}`),{}}}};kn=w([C(0,Je),C(1,D)],kn);function Xb(i){switch(i){case"never":case"on-request":case"on-failure":case"untrusted":return i;default:return}}function Zb(i){switch(i){case"read-only":case"workspace-write":case"danger-full-access":return i;default:return}}function vE(i){if(Array.isArray(i))return i.filter(n=>typeof n=="string"&&n.length>0)}function SE(i){return typeof i=="boolean"?i:void 0}function bE(i){switch(i){case"disabled":case"cached":case"live":return i;default:return}}function eC(i){switch(i){case"none":case"minimal":case"low":case"medium":case"high":case"xhigh":return i;default:return}}function CE(i){switch(i){case"none":case"friendly":case"pragmatic":return i;default:return}}function IE(i){switch(i){case"auto":case"concise":case"detailed":case"none":return i;default:return}}function _E(i){return i==="plan"?"plan":"default"}var y7={name:"vscode_agent_host",title:"VS Code Agent Host",version:"0.1.0"},TE="thinkingLevel",v7="vscode_codex",Ol=["minimal","low","medium","high"],S7={serverTools:{listChanged:!0},serverResources:{}},wE="mcp_tool_call_approval_",b7="Allow",C7="__codex_mcp_decline__",I7="/responses",vi=pn({"codex.approvalPolicy":we({type:"string",title:f(2132,null),description:f(2141,null),enum:["never","on-request","on-failure","untrusted"],enumLabels:[f(2133,null),f(2137,null),f(2135,null),f(2139,null)],enumDescriptions:[f(2134,null),f(2138,null),f(2136,null),f(2140,null)],default:"on-request",sessionMutable:!0}),"codex.sandboxMode":we({type:"string",title:f(2160,null),description:f(2167,null),enum:["read-only","workspace-write","danger-full-access"],enumLabels:[f(2163,null),f(2165,null),f(2161,null)],enumDescriptions:[f(2164,null),f(2166,null),f(2162,null)],default:"workspace-write",sessionMutable:!0}),"codex.webSearchMode":we({type:"string",title:f(2168,null),description:f(2172,null),enum:["disabled","cached","live"],enumLabels:[f(2170,null),f(2169,null),f(2171,null)],default:"disabled",sessionMutable:!1}),"codex.modelReasoningEffort":we({type:"string",title:f(2142,null),description:f(2143,null),enum:[...Ol],enumLabels:Ol.map(ns),enumDescriptions:Ol.map(i=>rs(i)??""),default:"medium",sessionMutable:!0}),mode:Jt.definition.mode,"codex.personality":we({type:"string",title:f(2146,null),description:f(2153,null),enum:["none","friendly","pragmatic"],enumLabels:[f(2149,null),f(2147,null),f(2151,null)],enumDescriptions:[f(2150,null),f(2148,null),f(2152,null)],default:"none",sessionMutable:!0}),"codex.reasoningSummary":we({type:"string",title:f(2154,null),description:f(2159,null),enum:["auto","concise","detailed","none"],enumLabels:[f(2155,null),f(2156,null),f(2157,null),f(2158,null)],default:"auto",sessionMutable:!0}),"codex.additionalDirectories":we({type:"array",title:f(2129,null),description:f(2131,null),items:{type:"string",title:f(2130,null)},enumDynamic:!0,default:[],sessionMutable:!0}),"codex.networkAccessEnabled":we({type:"boolean",title:f(2144,null),description:f(2145,null),default:!1,sessionMutable:!0}),permissions:Jt.definition.permissions}),xE=pn({mode:vi.definition.mode,"codex.approvalPolicy":vi.definition["codex.approvalPolicy"],"codex.sandboxMode":vi.definition["codex.sandboxMode"],"codex.webSearchMode":vi.definition["codex.webSearchMode"],"codex.personality":vi.definition["codex.personality"],"codex.reasoningSummary":vi.definition["codex.reasoningSummary"],permissions:Jt.definition.permissions}),_7=pn({...xE.definition,"codex.networkAccessEnabled":vi.definition["codex.networkAccessEnabled"]}),dr={"codex.approvalPolicy":"on-request","codex.sandboxMode":"workspace-write","codex.webSearchMode":"disabled","codex.modelReasoningEffort":"medium","codex.additionalDirectories":[],"codex.networkAccessEnabled":!1,mode:"interactive","codex.personality":"none","codex.reasoningSummary":"auto"},T7=6e4,ds={id:"codex",displayName:"Codex",devOverrideEnvVar:K_,hasSeparateMuslLinuxPackage:!1};function w7(i){let n=[];for(let e of i.content??[])e.type==="text"&&n.push({type:"inputText",text:e.text});if(n.length===0){let e=typeof i.pastTenseMessage=="string"&&i.pastTenseMessage.length>0?i.pastTenseMessage:i.success?"Tool completed with no output.":"Tool failed with no output.";n.push({type:"inputText",text:e})}return{contentItems:n,success:i.success}}function RE(i){return!i||i.length===0?"":i.map(n=>`${n.name}\0${n.description??""}\0${JSON.stringify(n.inputSchema??null)}`).sort().join("")}var tC=class{constructor(n,e,t,r){this._getSession=n;this.clientId=e;this.displayName=t;this._onToolsSet=r}get tools(){return this._getSession()?.clientToolSet.get(this.clientId)??[]}set tools(n){this._getSession()?.clientToolSet.set(this.clientId,n),this._onToolsSet(n)}get customizations(){return[]}set customizations(n){}};function R7(i){switch(i){case"accept":case"acceptForSession":case"decline":case"cancel":return i;default:return"decline"}}var Ml=class extends T{constructor(e,t,r,o,s,a,l){super();this._logService=e;this._copilotApiService=t;this._codexProxyService=r;this._configurationService=o;this._agentSdkDownloader=s;this._productService=a;this.id="codex";this._onDidSessionProgress=this._register(new P);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new P);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new P);this.onMcpNotification=this._onMcpNotification.event;this._models=nn(this,[]);this.models=this._models;this._sessions=new Map;this._sessionIdByThreadId=new Map;this._mcpInventory=new Map;this._connection={kind:"idle"};this.chats={createChat:(e,t)=>{throw new Error("Codex agent does not support multiple chats")},fork:(e,t,r)=>{throw new Error("Codex agent does not support chat forking")},disposeChat:e=>Promise.resolve(),sendMessage:(e,t,r,o,s)=>this._sendMessage(e,t,r,o),abort:e=>this._abort(e),changeModel:(e,t)=>this._changeModel(e,t),changeAgent:(e,t)=>Promise.resolve(),getMessages:e=>this.getSessionMessages(e)};this._metadataStore=l.createInstance(kn)}getProtectedResources(){return[mt,Ht]}async authenticate(e,t){if(e===Ht.resource)return!0;if(e!==mt.resource)return!1;let r=this._githubToken!==t;return this._githubToken=t,r&&this._connection.kind==="ready"?(this._connection.proxyHandle.setToken(t),this._queueModelRefresh(t)):r&&this._queueModelRefresh(t),this._logService.info("[Codex] Auth token updated"),!0}_queueModelRefresh(e){let t=this._refreshModels(e).finally(()=>{this._modelsRefreshPromise===t&&(this._modelsRefreshPromise=void 0)});this._modelsRefreshPromise=t,this._modelsRefreshPromise}_ensureAuthenticated(){let e=this._githubToken;if(!e)throw new k(tr,"Authentication is required to use Codex",this.getProtectedResources());return e}_defaultModel(){let t=this._models.get()[0];return t?{id:t.id}:void 0}_supportedModelOrUndefined(e){return e&&this._models.get().some(t=>t.id===e.id)?e:(e&&this._logService.warn(`[Codex] Ignoring unknown model '${e.id}'`),this._defaultModel())}async _resolveModel(e){this._models.get().length===0&&this._modelsRefreshPromise&&await this._modelsRefreshPromise;let t=this._supportedModelOrUndefined(e.model);if(t)return e.model=t,t;throw new Error("Codex has no available models.")}_createReasoningEffortConfigSchema(){return{type:"object",properties:{[TE]:{type:"string",title:f(2128,null),description:f(2127,null),default:"medium",enum:[...Ol],enumLabels:Ol.map(ns),enumDescriptions:Ol.map(e=>rs(e)??"")}}}}_getReasoningEffort(e){let t=eC(e.model?.config?.[TE]);if(t)return t;let r=this._configurationService.getSessionConfigValues(e.sessionUri.toString());return eC(r?.["codex.modelReasoningEffort"])??dr["codex.modelReasoningEffort"]}_readSessionConfig(e){return vi.validateOrDefault(this._configurationService.getSessionConfigValues(e.sessionUri.toString()),dr)}_sandboxPolicy(e,t){let r=Zb(t["codex.sandboxMode"])??dr["codex.sandboxMode"];if(r==="danger-full-access")return{type:"dangerFullAccess"};let o=SE(t["codex.networkAccessEnabled"])??dr["codex.networkAccessEnabled"];return r==="read-only"?{type:"readOnly",networkAccess:!1}:{type:"workspaceWrite",writableRoots:[...e.workingDirectory?[e.workingDirectory.fsPath]:[],...vE(t["codex.additionalDirectories"])??[]],networkAccess:o,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}_turnStartOptions(e,t){let r=this._readSessionConfig(e),o=Xb(r["codex.approvalPolicy"])??dr["codex.approvalPolicy"],s=this._sandboxPolicy(e,r),a=s.type==="workspaceWrite"?s.writableRoots:void 0,l=this._getReasoningEffort(e),d=CE(r["codex.personality"])??dr["codex.personality"],c=IE(r["codex.reasoningSummary"])??dr["codex.reasoningSummary"],p={mode:_E(r.mode),settings:{model:t,reasoning_effort:l??null,developer_instructions:null}};return{approvalPolicy:o,sandboxPolicy:s,effort:l,personality:d,summary:c,collaborationMode:p,...a?{runtimeWorkspaceRoots:a}:{}}}async _refreshModels(e){try{let t=`${v7}/${this._productService.version}`,r=await this._copilotApiService.models(e,{headers:{"User-Agent":t},suppressIntegrationId:!0});if(this._githubToken!==e)return;let o=this._createReasoningEffortConfigSchema(),s=r.filter(a=>a.supported_endpoints?.includes(I7)).sort((a,l)=>Number(l.is_chat_default)-Number(a.is_chat_default)).map(a=>({provider:this.id,id:a.id,name:a.name??a.id,maxContextWindow:a.capabilities?.limits?.max_context_window_tokens,maxOutputTokens:a.capabilities?.limits?.max_output_tokens,maxPromptTokens:a.capabilities?.limits?.max_prompt_tokens,supportsVision:!!a.capabilities?.supports?.vision,configSchema:o,policyState:a.policy?.state,_meta:tl(Gg(a.billing),typeof a.model_picker_price_category=="string"?a.model_picker_price_category:void 0)}));this._models.set(s,void 0)}catch(t){this._logService.warn(`[Codex] Failed to refresh models: ${t instanceof Error?t.message:String(t)}`),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(),t=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:t},t}async _resolveSdkRoot(){if(this._agentSdkDownloader.isAvailable(ds))return this._agentSdkDownloader.loadSdkRoot(ds,Ae.None);let e=await E7();return e?(this._logService.info(`[Codex] resolving SDK from repo node_modules (dev fallback): ${e}`),e):this._agentSdkDownloader.loadSdkRoot(ds,Ae.None)}async _startConnection(e){let t=await this._resolveSdkRoot(),r=P7(process.platform,process.arch);if(!r)throw new Error(`Codex: unsupported platform ${process.platform}-${process.arch}`);let o=A7(r);if(!o)throw new Error(`Codex: no binary triple known for sdkTarget '${r}'`);let s=process.platform==="win32"?"codex.exe":"codex",a=j(t,"node_modules",`@openai/codex-${r}`,"vendor",o,"bin",s);try{mo.accessSync(a,mo.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[G_];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","features.tool_call_mcp_elicitation=false","features.image_generation=false"],p=x7(process.env[J_]),m=["app-server",...u.flatMap(b=>["-c",b]),...p];this._logService.info(`[Codex] spawning ${a} ${m.join(" ")}`);let h=h7(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 y=VA(h),S=new Km(y,(b,I)=>{this._logService.info(`[CodexClient ${b}] ${I}`)});S.onExit(b=>{this._logService.warn(`[Codex] app-server exited code=${b.code} signal=${b.signal}`),this._handleConnectionLost()}),S.onTransportError(b=>{this._logService.error(`[Codex] transport error: ${b.message}`),this._handleConnectionLost()});try{await S.request("initialize",{clientInfo:y7,capabilities:{experimentalApi:!0,requestAttestation:!1,optOutNotificationMethods:null}}),S.notify("initialized",void 0),c&&await S.request("account/login/start",{type:"apiKey",apiKey:l.nonce}),this._logAccountSnapshot(S)}catch(b){S.dispose(),l.dispose();try{h.kill("SIGKILL")}catch{}throw b}return this._registerIgnoredNotifications(S),this._register(S.onNotification("turn/started",b=>this._dispatchByThread(b.threadId,I=>this._handleTurnStartedNotification(I,b)))),this._register(S.onNotification("item/started",b=>this._dispatchByThread(b.threadId,I=>this._handleItemStarted(I,b)))),this._register(S.onNotification("item/agentMessage/delta",b=>this._dispatchByThread(b.threadId,I=>lE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/commandExecution/outputDelta",b=>this._dispatchByThread(b.threadId,I=>iE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/fileChange/patchUpdated",b=>this._dispatchByThread(b.threadId,I=>oE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/fileChange/outputDelta",b=>this._dispatchByThread(b.threadId,I=>sE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/mcpToolCall/progress",b=>this._dispatchByThread(b.threadId,I=>aE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/summaryPartAdded",b=>this._dispatchByThread(b.threadId,I=>ZA(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/summaryTextDelta",b=>this._dispatchByThread(b.threadId,I=>eE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/textDelta",b=>this._dispatchByThread(b.threadId,I=>tE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("thread/tokenUsage/updated",b=>this._dispatchByThread(b.threadId,I=>nE(this._withHostTurnId(I,b))))),this._register(S.onNotification("item/completed",b=>this._dispatchByThread(b.threadId,I=>dE(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("turn/completed",b=>this._dispatchByThread(b.threadId,I=>this._handleTurnCompletedNotification(I,b)))),this._register(S.onNotification("mcpServer/startupStatus/updated",b=>this._handleMcpStartupStatus(S,b.name,b.status,b.error))),this._register(S.onRequest("item/commandExecution/requestApproval",b=>this._handleCommandApprovalRequestRpc(b))),this._register(S.onRequest("item/fileChange/requestApproval",b=>this._handleFileChangeApprovalRequestRpc(b))),this._register(S.onRequest("item/permissions/requestApproval",b=>this._handlePermissionsApprovalRequestRpc(b))),this._register(S.onRequest("item/tool/call",b=>this._handleDynamicToolCallRpc(b))),this._register(S.onRequest("item/tool/requestUserInput",b=>this._handleUserInputRequestRpc(b))),this._register(S.onRequest("mcpServer/elicitation/request",b=>this._handleElicitationRequestRpc(b))),this._refreshMcpInventory(S),{client:S,proxyHandle:l,child:h}}_buildDynamicTools(e){let t=this._serverToolHost?.definitions??[],r=e.clientToolSet.merged(),o=new Set,s=[];for(let a of[...t,...r])o.has(a.name)||(o.add(a.name),s.push(a));if(s.length!==0)return s.map(a=>({name:a.name,description:a.description??"",inputSchema:a.inputSchema??{type:"object"}}))}async _handleDynamicToolCallRpc(e){let t=this._sessionIdByThreadId.get(e.threadId),r=t?this._sessions.get(t):void 0;if(!r)return{result:this._toolFailure(`Codex tool call for unknown thread ${e.threadId}`)};let o=this._serverToolHost;if(o&&e.namespace===null&&o.toolNames.includes(e.tool))try{return{result:{contentItems:[{type:"inputText",text:o.executeTool(r.sessionUri.toString(),e.tool,e.arguments)}],success:!0}}}catch(a){return{result:this._toolFailure(`Server tool ${e.tool} failed: ${a instanceof Error?a.message:String(a)}`)}}let s=r.mapState.itemToToolCall.get(e.callId)?.toolCallId;if(s===void 0)return{result:this._toolFailure(`No pending client tool call for ${e.tool} (callId ${e.callId})`)};if(r.clientToolSet.size===0)return{result:this._toolFailure(`No client available to run ${e.tool}`)};try{let a=await r.pendingClientToolCalls.register(s);return{result:w7(a)}}catch(a){return a instanceof Y?{result:this._toolFailure(`Client tool ${e.tool} was cancelled`)}:{result:this._toolFailure(`Client tool ${e.tool} failed: ${a instanceof Error?a.message:String(a)}`)}}}_toolFailure(e){return this._logService.warn(`[Codex] dynamic tool call failed: ${e}`),{contentItems:[{type:"inputText",text:e}],success:!1}}async _handleUserInputRequestRpc(e){let t=this._sessionIdByThreadId.get(e.threadId),r=t?this._sessions.get(t):void 0;if(!r)return{result:Qb(e.questions)};let o=e.questions.length===1&&e.questions[0].id.startsWith(wE)?e.questions[0]:void 0;if(o){let l=o.id.slice(wE.length),d=r.mapState.itemToToolCall.get(l);if(d)return this._handleMcpToolApprovalViaCard(r,o,d)}let s=H(),a=mE(s,e.questions);try{let l=await r.pendingUserInputs.registerAndFire(s,()=>{this._fire(r.sessionUri,{type:"chat/inputRequested",request:a})});return{result:hE(e.questions,l.response,l.answers)}}catch{return{result:Qb(e.questions)}}}async _handleMcpToolApprovalViaCard(e,t,r){let o=t.question||t.header||"Run MCP tool",s;try{s=await e.pendingCommandApprovals.registerAndFire(r.toolCallId,()=>{this._fire(e.sessionUri,{type:"chat/toolCallReady",turnId:r.turnId,toolCallId:r.toolCallId,invocationMessage:o,toolInput:o,confirmationTitle:o})})}catch{s="decline"}let l=s==="accept"||s==="acceptForSession"?b7:C7;return{result:{answers:{[t.id]:{answers:[l]}}}}}async _handleElicitationRequestRpc(e){let t=this._sessionIdByThreadId.get(e.threadId),r=t?this._sessions.get(t):void 0;if(this._logService.info(`[Codex] elicitation request threadId=${e.threadId} mode=${e.mode} server=${e.serverName} session=${r?r.sessionId:"NONE"}`),!r)return this._logService.warn(`[Codex] elicitation request for unknown threadId=${e.threadId}; declining`),{result:BA()};let o=H(),s=WA(o,e);try{let a=await r.pendingUserInputs.registerAndFire(o,()=>{this._fire(r.sessionUri,{type:"chat/inputRequested",request:s})});return this._logService.info(`[Codex] elicitation resolved requestId=${o} response=${a.response}`),{result:qA(e,a.response,a.answers)}}catch(a){return this._logService.info(`[Codex] elicitation cancelled requestId=${o}: ${a instanceof Error?a.message:String(a)}`),{result:zA()}}}_hostTurnId(e,t){return e.hostTurnIdByAppTurnId.get(t)??t}_withHostTurnId(e,t){let r=this._hostTurnId(e,t.turnId);return r===t.turnId?t:{...t,turnId:r}}_withHostTurn(e,t){let r=t.turn.id,o=e.currentTurnId??this._hostTurnId(e,r);return e.hostTurnIdByAppTurnId.set(r,o),e.currentAppTurnId=r,o===r?t:{...t,turn:{...t.turn,id:o}}}_handleTurnStartedNotification(e,t){return XA(e.mapState,this._withHostTurn(e,t),e.lastPromptText),[]}_handleTurnCompletedNotification(e,t){let r=t.turn.id,o=this._hostTurnId(e,r),s=cE(e.mapState,this._withHostTurn(e,t));return e.codexTurnIdByHostTurnId.set(o,r),(e.currentAppTurnId===r||e.currentTurnId===o)&&(e.currentTurnId=void 0,e.currentAppTurnId=void 0),e.hostTurnIdByAppTurnId.delete(r),this._drainPendingSteering(e),s}_handleItemStarted(e,t){return t.item.type==="userMessage"?this._handleSteeredUserMessage(e,t.item.content):rE(e.mapState,this._withHostTurnId(e,t))}_handleSteeredUserMessage(e,t){let r=jb(t),o=this._takeMatchingPendingSteering(e,r);return o?this._beginSteeringTurn(e,o):[]}_takeMatchingPendingSteering(e,t){for(let[r,o]of e.pendingSteeringFlips)if(o.message.text===t)return e.pendingSteeringFlips.delete(r),o}_beginSteeringTurn(e,t){let r=[],o=e.currentAppTurnId,s=e.currentTurnId??(o?this._hostTurnId(e,o):void 0);s&&r.push({type:"chat/turnComplete",turnId:s});let a=H();return o&&e.hostTurnIdByAppTurnId.set(o,a),e.currentTurnId=a,Vb(e.mapState),r.push({type:"chat/turnStarted",turnId:a,message:t.message,queuedMessageId:t.id}),r}_drainPendingSteering(e){if(e.pendingSteeringFlips.size===0)return;let t=[...e.pendingSteeringFlips.keys()];e.pendingSteeringFlips.clear();for(let r of t)this._fireSteeringConsumed(e,r)}_fireSteeringConsumed(e,t){this._onDidSessionProgress.fire({kind:"steering_consumed",chat:v.parse(be(e.sessionUri)),id:t})}_registerIgnoredNotifications(e){let t=["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 t)this._register(e.onNotification(r,()=>{}))}async _logAccountSnapshot(e){try{let t=await e.request("account/read",{refreshToken:!1}),r=t.account?.type??"none",o=t.account?.type==="chatgpt"?t.account.planType:void 0;this._logService.info(`[Codex] account/read accountType=${r} requiresOpenaiAuth=${t.requiresOpenaiAuth}${o?` planType=${o}`:""}`)}catch(t){this._logService.warn(`[Codex] account/read failed: ${t instanceof Error?t.message:String(t)}`)}}_dispatchByThread(e,t){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=t(o);for(let a of s)this._fire(o.sessionUri,a)}async _handleCommandApprovalRequestRpc(e){return{result:{decision:await this._handleCommandApprovalRequest(e)}}}async _handleCommandApprovalRequest(e){let t=this._sessionIdByThreadId.get(e.threadId),r=t?this._sessions.get(t):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:${t}] 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:"chat/toolCallReady",turnId:o.turnId,toolCallId:o.toolCallId,invocationMessage:s,toolInput:s,confirmationTitle:a})});return l==="acceptForSession"&&s&&r.acceptedForSession.add(s),l}async _handleFileChangeApprovalRequestRpc(e){let t=await this._requestItemApproval(e.threadId,e.itemId,e.reason??"Apply file changes");return{result:{decision:R7(t)}}}async _handlePermissionsApprovalRequestRpc(e){let t=await this._requestItemApproval(e.threadId,e.itemId,e.reason??"Grant elevated permissions");return{result:{permissions:t==="accept"||t==="acceptForSession"?{network:e.permissions.network??void 0,fileSystem:e.permissions.fileSystem??void 0}:{},scope:t==="acceptForSession"?"session":"turn"}}}async _requestItemApproval(e,t,r){let o=this._sessionIdByThreadId.get(e),s=o?this._sessions.get(o):void 0;if(!s)return this._logService.warn(`[Codex] approval request for unknown threadId=${e}; declining`),"decline";let a=s.mapState.itemToToolCall.get(t);return a?s.pendingCommandApprovals.registerAndFire(a.toolCallId,()=>{this._fire(s.sessionUri,{type:"chat/toolCallReady",turnId:a.turnId,toolCallId:a.toolCallId,invocationMessage:r,toolInput:r,confirmationTitle:r})}):(this._logService.warn(`[Codex:${o}] approval request for unknown itemId=${t}; declining`),"decline")}_handleConnectionLost(){let e=this._connection;if(e.kind==="ready"){this._connection={kind:"idle"};for(let t of this._sessions.values()){t.pendingCommandApprovals.denyAll("decline"),t.pendingClientToolCalls.rejectAll(new Y),t.pendingUserInputs.rejectAll(new Y),this._drainPendingSteering(t);let r=t.currentTurnId,o=t.currentAppTurnId;t.currentTurnId=void 0,t.currentAppTurnId=void 0,o&&t.hostTurnIdByAppTurnId.delete(o),r&&(this._fire(t.sessionUri,{type:"chat/error",turnId:r,error:{errorType:"CodexDisconnected",message:"Codex app-server disconnected; session must restart."}}),this._fire(t.sessionUri,{type:"chat/turnComplete",turnId:r}))}try{e.client.dispose()}catch(t){this._logService.error(`[Codex] Failed to dispose app-server client after connection lost: ${t instanceof Error?t.message:String(t)}`)}try{e.proxyHandle.dispose()}catch(t){this._logService.error(`[Codex] Failed to dispose proxy handle after connection lost: ${t instanceof Error?t.message:String(t)}`)}}}getDescriptor(){return{provider:this.id,displayName:f(2174,null),description:f(2173,null)}}_sessionUriFromChat(e){let t=He(e);return t?v.parse(t.session):e}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 t=this._supportedModelOrUndefined(e.model),r=e.session?L.id(e.session):H(),o=e.session??L.uri(this.id,r),s=this._sessions.get(r);if(s)return s.model=t??s.model,{session:o,workingDirectory:s.workingDirectory??e.workingDirectory,provisional:s.threadId===void 0};let a=new Pn,l={sessionId:r,threadId:void 0,sessionUri:o,workingDirectory:e.workingDirectory,mapState:zb(new Set(this._serverToolHost?.toolNames??[]),a),pendingCommandApprovals:new xt,acceptedForSession:new Set,pendingSteeringFlips:new Map,clientToolSet:a,pendingClientToolCalls:new xt,pendingUserInputs:new xt,materializedToolsSig:void 0,firstTurnSent:!1,model:t,currentTurnId:void 0,currentAppTurnId:void 0,hostTurnIdByAppTurnId:new Map,codexTurnIdByHostTurnId:new Map,needsResume:!1,lastPromptText:"",disposed:!1,materializePromise:void 0,materializedEventFired:!1,prewarmTimer:void 0,prewarmClaimed:!1,serverToolsAdvertised:!1,mcpController:void 0};return this._sessions.set(r,l),this._schedulePrewarm(l),{session:o,workingDirectory:e.workingDirectory,provisional:!0}}async _materializeIfNeeded(e,t=!0){if(!e.disposed){if(e.threadId!==void 0){t&&this._fireMaterialized(e);return}if(e.materializePromise){await e.materializePromise,t&&this._fireMaterialized(e);return}e.materializePromise=this._materialize(e).finally(()=>{e.materializePromise=void 0}),await e.materializePromise,t&&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 t=await this._ensureConnection(),r=this._readSessionConfig(e),o=await this._resolveModel(e),a=(await t.client.request("thread/start",{cwd:e.workingDirectory.fsPath,model:o.id,approvalPolicy:Xb(r["codex.approvalPolicy"])??dr["codex.approvalPolicy"],sandbox:Zb(r["codex.sandboxMode"])??dr["codex.sandboxMode"],config:{web_search:bE(r["codex.webSearchMode"])??dr["codex.webSearchMode"]},dynamicTools:this._buildDynamicTools(e)})).thread.id;if(e.disposed){try{await t.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,e.materializedToolsSig=RE(e.clientToolSet.merged()),this._logService.info(`[Codex DEBUG] materialized session=${e.sessionUri.toString()} threadId=${e.threadId}`),this._sessionIdByThreadId.set(e.threadId,e.sessionId),!e.serverToolsAdvertised&&this._serverToolHost&&(e.serverToolsAdvertised=!0,this._serverToolHost.advertise(e.sessionUri.toString()))}async _restartThreadWithCurrentTools(e){let t=this._connection,r=e.threadId;if(this._logService.info(`[Codex:${e.sessionId}] restarting thread ${r} to apply client tools [${e.clientToolSet.merged().map(o=>o.name).join(", ")||"(none)"}]`),t.kind==="ready"&&r!==void 0){this._sessionIdByThreadId.delete(r);try{await t.client.request("thread/unsubscribe",{threadId:r})}catch(o){this._logService.info(`[Codex:${r}] thread/unsubscribe during tool restart failed: ${o instanceof Error?o.message:String(o)}`)}}e.threadId=void 0,e.materializePromise=void 0,await this._materializeIfNeeded(e)}_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&&(async()=>{if(!await this._agentSdkDownloader.isSdkResolvableWithoutDownload(ds)){this._logService.info(`[Codex] SDK not downloaded yet; skipping prewarm for session=${e.sessionUri.toString()} until a message triggers the download`);return}if(await this._materializeIfNeeded(e,!1),e.prewarmClaimed||e.threadId===void 0)return;this._logService.info(`[Codex] prewarm ready session=${e.sessionUri.toString()} threadId=${e.threadId}`);let t=setTimeout(()=>{this._expirePrewarm(e)},T7);e.prewarmTimer=t})().catch(t=>{this._logService.warn(`[Codex] prewarm failed session=${e.sessionUri.toString()}: ${t instanceof Error?t.message:String(t)}`)})}async _expirePrewarm(e){if(e.disposed||e.prewarmClaimed||e.threadId===void 0)return;let t=e.threadId;e.threadId=void 0,this._sessionIdByThreadId.delete(t);try{await(await this._ensureConnection()).client.request("thread/unsubscribe",{threadId:t}),this._logService.info(`[Codex] prewarm TTL eviction session=${e.sessionUri.toString()} threadId=${t}`)}catch(r){this._logService.warn(`[Codex] prewarm TTL eviction failed session=${e.sessionUri.toString()} threadId=${t}: ${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,t,r,o){let s=this._sessionUriFromChat(e);this._logService.info(`[Codex DEBUG] sendMessage session=${s.toString()} prompt=${JSON.stringify(t).slice(0,60)}`);let a=L.id(s),l=this._sessions.get(a);if(!l)throw new Error(`Codex session not found: ${s.toString()}`);let d=await this._ensureConnection(),c=o??H();try{this._claimPrewarm(l),await this._materializeIfNeeded(l),this._persistMaterializedSession(l)}catch(h){let y=h instanceof Error?h.message:String(h);this._logService.error(`[Codex:${a}] materialize failed: ${y}`),this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexMaterializeFailed",message:y}}),this._fire(s,{type:"chat/turnComplete",turnId:c});return}if(!l.firstTurnSent&&!l.needsResume&&RE(l.clientToolSet.merged())!==l.materializedToolsSig)try{await this._restartThreadWithCurrentTools(l),this._persistMaterializedSession(l)}catch(h){let y=h instanceof Error?h.message:String(h);this._logService.error(`[Codex:${a}] tool re-materialize failed: ${y}`),this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexMaterializeFailed",message:y}}),this._fire(s,{type:"chat/turnComplete",turnId:c});return}let u=l.threadId;if(l.needsResume)try{await d.client.request("thread/resume",{threadId:u}),l.needsResume=!1}catch(h){this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexResumeFailed",message:h instanceof Error?h.message:String(h)}}),this._fire(s,{type:"chat/turnComplete",turnId:c});return}let{input:p,cleanupPaths:m}=Yb(t,r);l.lastPromptText=t,l.currentTurnId=c;try{let h=await this._resolveModel(l),y=this._turnStartOptions(l,h.id);await d.client.request("turn/start",{threadId:u,input:p.slice(),model:h.id,...y}),l.firstTurnSent=!0}catch(h){if(h instanceof Y){this._fire(s,{type:"chat/turnCancelled",turnId:c});return}let y=h instanceof Error?h.message:String(h);this._logService.error(`[Codex:${a}] turn/start error: ${y}`),this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexTurnError",...Ea(y)}}),this._fire(s,{type:"chat/turnComplete",turnId:c})}finally{m.length>0&&setTimeout(()=>{for(let h of m)try{mo.unlinkSync(h)}catch{}},3e4)}}setPendingMessages(e,t,r){if(!t)return;let o=L.id(e),s=this._sessions.get(o);if(!s||s.pendingSteeringFlips.has(t.id))return;let a=s.currentAppTurnId,l=this._connection,d=t.message.text,c=d.length>0||(t.message.attachments?.length??0)>0;if(!a||l.kind!=="ready"||s.threadId===void 0||!c){this._fireSteeringConsumed(s,t.id);return}let{input:u}=Yb(d,t.message.attachments),p=s.threadId;s.pendingSteeringFlips.set(t.id,t),l.client.request("turn/steer",{threadId:p,input:u.slice(),expectedTurnId:a}).catch(m=>{if(s.pendingSteeringFlips.delete(t.id)&&this._fireSteeringConsumed(s,t.id),m instanceof go){this._logService.info(`[Codex:${o}] turn/steer skipped: ${m.message}`);return}this._logService.warn(`[Codex:${o}] turn/steer failed: ${m instanceof Error?m.message:String(m)}`)})}async _abort(e){let t=this._sessionUriFromChat(e),r=L.id(t),o=this._sessions.get(r);if(!o||(this._drainPendingSteering(o),!o.currentAppTurnId||o.threadId===void 0))return;let s=o.threadId,a=this._connection;if(a.kind==="ready")try{await a.client.request("turn/interrupt",{threadId:s,turnId:o.currentAppTurnId})}catch(l){this._logService.warn(`[Codex:${r}] turn/interrupt failed: ${l instanceof Error?l.message:String(l)}`)}}async disposeSession(e){this._logService.info(`[Codex DEBUG] disposeSession session=${e.toString()}`);let t=L.id(e),r=this._sessions.get(t);if(!r)return;r.disposed=!0,this._claimPrewarm(r),this._sessions.delete(t),r.mcpController?.dispose(),r.threadId!==void 0&&this._sessionIdByThreadId.delete(r.threadId),r.pendingCommandApprovals.denyAll("decline"),r.pendingClientToolCalls.rejectAll(new Y),r.pendingUserInputs.rejectAll(new Y),this._drainPendingSteering(r);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,t){let r=this._sessionUriFromChat(e),o=this._sessions.get(L.id(r));if(o){let s=this._supportedModelOrUndefined(t);s&&(o.model=s)}}async truncateSession(e,t){let r=await this._readSession(e);if(!r)return;let o=r.thread.turns??[];if(o.length===0)return;let s;if(t===void 0)s=o.length;else{let l=this._sessions.get(L.id(e))?.codexTurnIdByHostTurnId.get(t)??t,d=o.findIndex(c=>c.id===l);if(d===-1){this._logService.warn(`[Codex] truncateSession: turnId ${t} not found in thread ${r.thread.id}; skipping`);return}s=o.length-(d+1)}if(!(s<=0))try{await(await this._ensureConnection()).client.request("thread/rollback",{threadId:r.thread.id,numTurns:s})}catch(a){this._logService.warn(`[Codex:${r.thread.id}] thread/rollback failed: ${a instanceof Error?a.message:String(a)}`)}}async onArchivedChanged(e,t){let r=await this._resolveThreadId(e);if(r===void 0)return;let o=this._connection;if(o.kind==="ready")try{t?await o.client.request("thread/archive",{threadId:r}):await o.client.request("thread/unarchive",{threadId:r})}catch(s){this._logService.warn(`[Codex:${r}] thread/${t?"archive":"unarchive"} failed: ${s instanceof Error?s.message:String(s)}`)}}async _resolveThreadId(e){let t=this._sessions.get(L.id(e));return t?.threadId!==void 0?t.threadId:(await this._metadataStore.read(e)).threadId}respondToPermissionRequest(e,t){for(let r of this._sessions.values())if(r.pendingCommandApprovals.respond(e,t?"accept":"decline")){t||r.mapState.declinedToolCalls.add(e);return}this._logService.info(`[Codex] respondToPermissionRequest: unknown requestId=${e}`)}respondToUserInputRequest(e,t,r){for(let o of this._sessions.values())if(o.pendingUserInputs.respond(e,{response:t,answers:r}))return;this._logService.info(`[Codex] respondToUserInputRequest: unknown requestId=${e}`)}getSessionMessages(e){return this._readSession(this._sessionUriFromChat(e)).then(t=>t?yE(t.thread):[])}async getSessionMetadata(e){let t=L.id(e),r=await this._readSession(e);if(r){if(!this._sessions.has(t)){let o=r.thread.cwd?v.file(r.thread.cwd):void 0,s=r.thread.id,a=new Pn;this._sessions.set(t,{sessionId:t,threadId:s,sessionUri:e,workingDirectory:o,mapState:zb(new Set(this._serverToolHost?.toolNames??[]),a),pendingCommandApprovals:new xt,acceptedForSession:new Set,pendingSteeringFlips:new Map,clientToolSet:a,pendingClientToolCalls:new xt,pendingUserInputs:new xt,materializedToolsSig:void 0,firstTurnSent:!0,model:void 0,currentTurnId:void 0,currentAppTurnId:void 0,hostTurnIdByAppTurnId:new Map,codexTurnIdByHostTurnId:new Map,needsResume:!0,lastPromptText:"",disposed:!1,materializePromise:void 0,materializedEventFired:!0,prewarmTimer:void 0,prewarmClaimed:!0,serverToolsAdvertised:!1,mcpController:void 0}),this._sessionIdByThreadId.set(s,t);let l=this._sessions.get(t);l&&!l.serverToolsAdvertised&&this._serverToolHost&&(l.serverToolsAdvertised=!0,this._serverToolHost.advertise(l.sessionUri.toString()))}return this._threadToMetadata(r.thread,e)}}async _readSession(e){let t=L.id(e),o=this._sessions.get(t)?.threadId;o===void 0&&(o=(await this._metadataStore.read(e)).threadId??t);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[];if(!await this._agentSdkDownloader.isSdkResolvableWithoutDownload(ds))return this._logService.info("[Codex] SDK not downloaded yet; deferring thread/list until a session triggers the download"),[];try{let t=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 t.data.map(o=>this._threadToMetadata(o,r.get(o.id)??L.uri(this.id,o.id)))}catch(e){return this._logService.warn(`[Codex] thread/list failed: ${e instanceof Error?e.message:String(e)}`),[]}}_threadToMetadata(e,t){return{session:t,startTime:(e.createdAt??0)*1e3,modifiedTime:(e.updatedAt??e.createdAt??0)*1e3,summary:e.name??e.preview??void 0,workingDirectory:e.cwd?v.file(e.cwd):void 0}}setServerToolHost(e){this._serverToolHost=e}getOrCreateActiveClient(e,t){let r=L.id(e);return new tC(()=>this._sessions.get(r),t.clientId,t.displayName,o=>this._logService.info(`[Codex:${r}] active client ${t.clientId} tools=[${o.map(s=>s.name).join(", ")||"(none)"}]`))}removeActiveClient(e,t){let r=L.id(e);this._sessions.get(r)?.clientToolSet.delete(t)}onClientToolCallComplete(e,t,r,o){let s=L.id(e);this._sessions.get(s)?.pendingClientToolCalls.respondOrBuffer(r,o)}setCustomizationEnabled(e,t){}async getSessionCustomizations(e){let t=this._sessions.get(L.id(e));if(!t)return[];let r=this._getOrCreateMcpController(t);return r.applyAll(Bb(this._mcpInventory)),this._refreshMcpCustomizationIds(t,r),r.topLevelCustomizations()}async handleMcpRequest(e,t,r,o){let s=L.id(e),a=this._sessions.get(s);if(!a)throw new Error(`Method not found: no active session ${s}`);let l=this._mcpInventory.get(t);if(!l)throw new Error(`Method not found: unknown MCP server '${t}'`);let d=FA(r,l);if(d.handled)return d.result;switch(r){case"tools/call":{let c=o&&typeof o.name=="string"?o.name:void 0;if(!c)throw new Error("tools/call missing 'name' parameter");let u=await this._ensureThreadId(a);return(await this._ensureConnection()).client.request("mcpServer/tool/call",{threadId:u,server:t,tool:c,arguments:o?o.arguments:void 0})}case"resources/read":{let c=o&&typeof o.uri=="string"?o.uri:void 0;if(!c)throw new Error("resources/read missing 'uri' parameter");let u=await this._ensureThreadId(a);return(await this._ensureConnection()).client.request("mcpServer/resource/read",{threadId:u,server:t,uri:c})}default:throw new Error(`Method not found: ${r}`)}}_getOrCreateMcpController(e){return e.mcpController||(e.mcpController=new Wa({providerId:this.id,sessionId:e.sessionId,resolveChildId:()=>{},emit:t=>this._fire(e.sessionUri,t),capabilities:S7})),e.mcpController}_applyMcpInventoryToSessions(){let e=Bb(this._mcpInventory);for(let t of this._sessions.values()){if(t.disposed)continue;let r=this._getOrCreateMcpController(t);r.applyAll(e),this._refreshMcpCustomizationIds(t,r)}}_refreshMcpCustomizationIds(e,t){let r=e.mapState.mcpCustomizationIds;r.clear();for(let o of this._mcpInventory.keys()){let s=t.customizationIdForServer(o);s!==void 0&&r.set(o,s)}}async _refreshMcpInventory(e){let t=[];try{let s=null;do{let a=await e.request("mcpServerStatus/list",{cursor:s,detail:"full"});t=t.concat(a.data),s=a.nextCursor}while(s)}catch(s){this._logService.warn(`[Codex] Failed to list MCP servers: ${s instanceof Error?s.message:String(s)}`);return}if(this._connection.kind==="ready"&&this._connection.client!==e)return;let r=UA(t),o=[];for(let[s,a]of r){let l=this._mcpInventory.get(s);l&&HA(l,a)&&o.push(s)}this._mcpInventory.clear();for(let[s,a]of r)this._mcpInventory.set(s,a);this._applyMcpInventoryToSessions();for(let s of o)this._fireMcpToolsListChanged(s)}_handleMcpStartupStatus(e,t,r,o){if(!(this._connection.kind==="ready"&&this._connection.client!==e)){if(r==="ready"){this._refreshMcpInventory(e);return}if(r==="cancelled")this._mcpInventory.delete(t);else{let s=this._mcpInventory.get(t);this._mcpInventory.set(t,{state:NA(r,o),tools:s?.tools??[],resources:s?.resources??[],resourceTemplates:s?.resourceTemplates??[]})}this._applyMcpInventoryToSessions()}}_fireMcpToolsListChanged(e){for(let t of this._sessions.values()){let r=t.mcpController?.channelForServer(e);r&&this._onMcpNotification.fire({channel:r,method:"notifications/tools/list_changed"})}}async _ensureThreadId(e){if(await this._materializeIfNeeded(e,!1),e.threadId===void 0)throw new Error(`Cannot run MCP tool: codex session ${e.sessionId} is not materialized`);return e.threadId}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"),e.pendingClientToolCalls.rejectAll(new Y),e.pendingUserInputs.rejectAll(new Y),e.mcpController?.dispose();this._sessions.clear(),this._sessionIdByThreadId.clear(),this._mcpInventory.clear()}resolveSessionConfig(e){let t=vi.validateOrDefault(e.config,dr),r=t["codex.sandboxMode"]==="workspace-write",o=r?_7.toProtocol():xE.toProtocol(),s={mode:t.mode,"codex.approvalPolicy":t["codex.approvalPolicy"],"codex.sandboxMode":t["codex.sandboxMode"],"codex.webSearchMode":t["codex.webSearchMode"],"codex.personality":t["codex.personality"],"codex.reasoningSummary":t["codex.reasoningSummary"]};return r&&(s["codex.networkAccessEnabled"]=t["codex.networkAccessEnabled"]),Promise.resolve({values:s,schema:o})}async sessionConfigCompletions(e){if(e.property!=="codex.additionalDirectories")return{items:[]};let t=e.query?.trim();if(!t)return{items:[]};let r=e.workingDirectory?.fsPath,o=Ft(t)?t:Mn(r??process.cwd(),t),s=t.endsWith(Le)?o:le(o),a=t.endsWith(Le)?"":Te(o).toLowerCase();try{return{items:(await mo.promises.readdir(s,{withFileTypes:!0})).filter(d=>d.isDirectory()&&d.name.toLowerCase().startsWith(a)).slice(0,50).map(d=>{let c=j(s,d.name);return{value:c,label:d.name,description:c}})}}catch{return{items:[]}}}_fire(e,t){this._onDidSessionProgress.fire({kind:"action",resource:rr(t)?v.parse(be(e)):e,action:t})}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"),e.pendingClientToolCalls.rejectAll(new Y),e.pendingUserInputs.rejectAll(new Y),e.mcpController?.dispose();this._sessions.clear(),this._sessionIdByThreadId.clear(),this._mcpInventory.clear(),super.dispose()}};Ml=w([C(0,D),C(1,It),C(2,Gm),C(3,ze),C(4,yl),C(5,Ct),C(6,Ie)],Ml);function x7(i){if(!i)return[];try{let n=JSON.parse(i);return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}catch{return[]}}function P7(i,n){if(!(i!=="linux"&&i!=="darwin"&&i!=="win32"||n!=="x64"&&n!=="arm64"))return`${i}-${n}`}function A7(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}}async function E7(i=k7){try{let n=await i();return le(le(le(le(n))))}catch{return}}async function k7(){let{createRequire:i}=await import("node:module");return i(import.meta.url).resolve("@openai/codex/package.json")}import{mkdir as Y7}from"fs/promises";var D7=/^[0-9a-fA-F]+$/,M7="00000000000000000000000000000000",PE="0000000000000000";function AE(i){if(!i||!Array.isArray(i.resourceSpans))return{spans:[],rejected:0,errors:[]};let n=[],e=[],t=0;for(let r of i.resourceSpans){if(!r)continue;let o=U7(r.resource?.attributes);for(let s of r.scopeSpans??[])if(s)for(let a of s.spans??[])try{let l=O7(a,o);l?n.push(l):t++}catch(l){t++,e.push(l instanceof Error?l.message:String(l))}}return{spans:n,rejected:t,errors:e}}function O7(i,n){if(!i)return;let e=(i.traceId??"").toLowerCase(),t=(i.spanId??"").toLowerCase();if(!nC(e,32)||e===M7)throw new Error(`invalid traceId: ${i.traceId}`);if(!nC(t,16)||t===PE)throw new Error(`invalid spanId: ${i.spanId}`);let r;if(i.parentSpanId){let c=i.parentSpanId.toLowerCase();nC(c,16)&&c!==PE&&(r=c)}let o=iC(i.startTimeUnixNano),s=iC(i.endTimeUnixNano);if(o===void 0||s===void 0)throw new Error("missing span time bounds");let a={...n};for(let c of i.attributes??[])oC(a,c);let l=[];for(let c of i.events??[]){let u=L7(c);u&&l.push(u)}let d=N7(i.status?.code,i.status?.message);return{name:i.name??"",traceId:e,spanId:t,parentSpanId:r,startTime:o,endTime:s,status:d,attributes:a,events:l}}function L7(i){if(!i)return;let n=iC(i.timeUnixNano);if(n===void 0)return;let e={};for(let t of i.attributes??[])oC(e,t);return{name:i.name??"",timestamp:n,attributes:Object.keys(e).length>0?e:void 0}}function N7(i,n){switch(i){case 1:return{code:1,message:n};case 2:return{code:2,message:n};case 0:default:return{code:0,message:n}}}function U7(i){let n={};if(!i)return n;for(let e of i)oC(n,e);return n}function oC(i,n){if(!n||typeof n.key!="string"||n.key.length===0)return;let e=rC(n.value);e!==void 0&&(i[n.key]=e)}function rC(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 n=typeof i.intValue=="string"?Number(i.intValue):i.intValue;return Number.isFinite(n)?n:void 0}if(typeof i.doubleValue=="number")return i.doubleValue;if(i.arrayValue?.values){let n=i.arrayValue.values.map(rC);return n.every(e=>typeof e=="string")?n:JSON.stringify(n)}if(i.kvlistValue?.values){let n={};for(let e of i.kvlistValue.values)e&&typeof e.key=="string"&&(n[e.key]=rC(e.value));return JSON.stringify(n)}if(typeof i.bytesValue=="string")return i.bytesValue}}function iC(i){if(i===void 0||i===""||i==="0")return;let n=i.length<=6?"0":i.slice(0,-6),e=Number(n);return Number.isFinite(e)?e:void 0}function nC(i,n){return i.length===n&&D7.test(i)}var F7="/v1/traces",H7=64*1024*1024;async function EE(i,n,e={}){let t=e.maxBodyBytes??H7,o=(await import("http")).createServer();o.on("request",(c,u)=>{$7(c,u,i,n,t).catch(p=>{if(n.error(`[agentHost-otel] receiver: unhandled error: ${p instanceof Error?p.message:String(p)}`),!u.headersSent)ho(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}`;n.info(`[agentHost-otel] receiver listening on ${l}`);let d=M(()=>{o.closeAllConnections(),o.close(c=>{c&&n.warn(`[agentHost-otel] receiver close error: ${c.message}`)})});return Object.assign(d,{baseUrl:l,port:a})}async function $7(i,n,e,t,r){if((i.url??"").split("?",1)[0]!==F7){ho(n,404,"not found");return}if(i.method!=="POST"){n.setHeader("allow","POST"),ho(n,405,"method not allowed");return}let a=(i.headers["content-type"]??"").toString().toLowerCase();if(!a.includes("application/json")){ho(n,415,"unsupported content-type; this receiver only accepts application/json");return}let l=(i.headers["content-encoding"]??"").toString().toLowerCase();if(l&&l!=="identity"){ho(n,415,`unsupported content-encoding: ${l}`);return}let d;try{d=await W7(i,r)}catch(m){m instanceof Jm?ho(n,413,"payload too large"):ho(n,400,"failed to read body");return}if(e.onForward)try{e.onForward(d,a)}catch(m){t.warn(`[agentHost-otel] forward callback threw: ${m instanceof Error?m.message:String(m)}`)}let c;try{c=JSON.parse(d.toString("utf8"))}catch(m){ho(n,400,`invalid json: ${m instanceof Error?m.message:String(m)}`);return}let u=AE(c);try{e.onSpans(u)}catch(m){t.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)}}:{};n.statusCode=200,n.setHeader("content-type","application/json"),n.end(JSON.stringify(p))}var Jm=class extends Error{};function W7(i,n){return new Promise((e,t)=>{let r=[],o=0,s=c=>{if(o+=c.length,o>n){d(),t(new Jm(`body exceeds ${n} bytes`));return}r.push(c)},a=()=>{d(),e(Buffer.concat(r))},l=c=>{d(),t(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 ho(i,n,e){i.statusCode=n,i.setHeader("content-type","text/plain; charset=utf-8"),i.end(e)}import{URL as kE}from"url";import{promises as q7}from"fs";function B7(i){try{let n=new kE(i);return n.pathname===""||n.pathname==="/"?(n.pathname="/v1/traces",n.toString()):i}catch{return i}}var Ym=class extends T{constructor(e,t){super();this._options=e;this._logService=t;this._queue=new ki;this._disposed=!1;this._resolvedEndpoint=B7(e.endpoint),this._register(M(()=>{this._disposed=!0}))}forwardRaw(e,t){this._disposed||this._queue.queue(()=>this._sendOnce(e,t))}async flush(){try{await this._queue.queue(()=>Promise.resolve())}catch{}}async _sendOnce(e,t){try{let r=new kE(this._resolvedEndpoint),o=r.protocol==="https:",s=o?await import("https"):await import("http"),a={"content-type":t,"content-length":String(e.length),...this._options.headers??{}};await z7(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 z7(i,n,e){return new Promise((t,r)=>{let o=i.request({host:n.host,port:n.port,path:n.path,method:n.method,headers:n.headers,timeout:n.timeoutMs}),s=a=>{o.destroy(),r(a)};o.on("error",s),o.on("timeout",()=>s(new Error(`request timeout after ${n.timeoutMs}ms`))),o.on("response",a=>{a.resume(),a.on("end",()=>{let l=a.statusCode??0;l>=200&&l<300?t():r(new Error(`upstream returned HTTP ${l}`))}),a.on("error",s)}),o.end(e)})}var Qm=class extends T{constructor(e,t){super();this._options=e;this._logService=t;this._queue=new ki;this._disposed=!1;this._register(M(()=>{this._disposed=!0}))}forwardSpans(e){if(this._disposed||e.spans.length===0)return;let t=e.spans.map(r=>JSON.stringify(r)).join(`
`)+`
`;this._queue.queue(()=>this._append(t))}async flush(){try{await this._queue.queue(()=>Promise.resolve())}catch{}}async _append(e){try{await q7.appendFile(this._options.filePath,e,{encoding:"utf8"})}catch(t){this._logService.warn(`[agentHost-otel] file forward to ${this._options.filePath} failed: ${t instanceof Error?t.message:String(t)}`)}}},Xm=class extends T{constructor(e){super();this._logService=e;this._disposed=!1;this._register(M(()=>{this._disposed=!0}))}forwardSpans(e){if(!this._disposed)for(let t of e.spans)this._logService.info(`[agentHost-otel] span ${V7(t)}`)}async flush(){}};function V7(i){let n=Math.max(0,i.endTime-i.startTime),e=i.attributes["gen_ai.operation.name"],t=i.attributes["gen_ai.request.model"]??i.attributes["gen_ai.response.model"],r=[e&&`op=${e}`,t&&`model=${t}`].filter(Boolean).join(" ");return`${i.name} (${n}ms) trace=${i.traceId} span=${i.spanId}${r?" "+r:""}`}var Zm=class extends T{constructor(n){super(),this._children=n;for(let e of n)this._register(e)}forwardRaw(n,e){for(let t of this._children)t.forwardRaw?.(n,e)}forwardSpans(n){for(let e of this._children)e.forwardSpans?.(n)}async flush(){await Promise.all(this._children.map(n=>n.flush()))}};import{mkdirSync as j7}from"fs";import{createRequire as K7}from"module";var Sn={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"},du={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 G7=K7(import.meta.url);function J7(){return G7("node:sqlite")}var DE=1,ME=10080*60*1e3,OE=100,on={operation_name:Sn.OPERATION_NAME,provider_name:Sn.PROVIDER_NAME,agent_name:Sn.AGENT_NAME,conversation_id:Sn.CONVERSATION_ID,request_model:Sn.REQUEST_MODEL,response_model:Sn.RESPONSE_MODEL,input_tokens:Sn.USAGE_INPUT_TOKENS,output_tokens:Sn.USAGE_OUTPUT_TOKENS,cached_tokens:Sn.USAGE_CACHE_READ_INPUT_TOKENS,reasoning_tokens:Sn.USAGE_REASONING_TOKENS,tool_name:Sn.TOOL_NAME,tool_call_id:Sn.TOOL_CALL_ID,tool_type:Sn.TOOL_TYPE,chat_session_id:du.CHAT_SESSION_ID,turn_index:du.TURN_INDEX,ttft_ms:du.TIME_TO_FIRST_TOKEN},W0e=$("otelSqliteStore"),eh=class{constructor(n){this._db=null;this._insertSpanStmt=null;this._insertAttrStmt=null;this._insertEventStmt=null;this._beginTx=null;this._commitTx=null;this._rollbackTx=null;this._dbPath=n}get dbPath(){return this._dbPath}insertSpan(n){this._ensureDb();try{this._beginTx.run(),this._insertSpanStmt.run(n.spanId,n.traceId,n.parentSpanId??null,n.name,n.startTime,n.endTime,n.status.code,n.status.message??null,this._attr(n,on.operation_name),this._attr(n,on.provider_name),this._attr(n,on.agent_name),this._attr(n,on.conversation_id),this._attr(n,on.request_model),this._attr(n,on.response_model),this._attr(n,on.input_tokens),this._attr(n,on.output_tokens),this._attr(n,on.cached_tokens),this._attr(n,on.reasoning_tokens),this._attr(n,on.tool_name),this._attr(n,on.tool_call_id),this._attr(n,on.tool_type),this._attr(n,on.chat_session_id),this._attr(n,on.turn_index),this._ttftMs(n));for(let[e,t]of Object.entries(n.attributes)){let r=Array.isArray(t)?JSON.stringify(t):String(t);this._insertAttrStmt.run(n.spanId,e,r)}for(let e of n.events){let t=e.attributes?JSON.stringify(e.attributes):null;this._insertEventStmt.run(n.spanId,e.name,e.timestamp,t)}this._commitTx.run()}catch(e){try{this._rollbackTx.run()}catch{}throw e}}getSpansByTraceId(n){return this._ensureDb().prepare("SELECT * FROM spans WHERE trace_id = ? ORDER BY start_time_ms").all(n)}getSpansByConversationId(n){return this._ensureDb().prepare("SELECT * FROM spans WHERE conversation_id = ? OR chat_session_id = ? ORDER BY start_time_ms").all(n,n)}getSpanAttributes(n){return this._ensureDb().prepare("SELECT key, value FROM span_attributes WHERE span_id = ?").all(n)}getSpanAttribute(n,e){return this._ensureDb().prepare("SELECT value FROM span_attributes WHERE span_id = ? AND key = ?").get(n,e)?.value??null}getSpanEvents(n){return this._ensureDb().prepare("SELECT * FROM span_events WHERE span_id = ? ORDER BY timestamp_ms").all(n)}getTraceIds(n){let e=this._ensureDb();return n?e.prepare("SELECT DISTINCT trace_id FROM spans WHERE conversation_id = ? OR chat_session_id = ?").all(n,n).map(r=>r.trace_id):e.prepare("SELECT DISTINCT trace_id FROM spans").all().map(t=>t.trace_id)}getSessions(n){let e=n?"SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?":"SELECT * FROM sessions ORDER BY started_at DESC";return n?this._ensureDb().prepare(e).all(n):this._ensureDb().prepare(e).all()}getSessionsSince(n){return this._ensureDb().prepare("SELECT * FROM sessions WHERE started_at >= ? ORDER BY started_at DESC").all(n)}cleanup(n=ME){let e=Date.now()-n,t=this._ensureDb().prepare("DELETE FROM spans WHERE start_time_ms < ?").run(e);return Number(t.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(n,e){let t=n.attributes[e];return t===void 0?null:Array.isArray(t)?JSON.stringify(t):typeof t=="boolean"?t?1:0:t}_ttftMs(n){let e=this._attr(n,du.TIME_TO_FIRST_TOKEN);if(e!==null)return e;let t=n.attributes["gen_ai.response.time_to_first_chunk"]??n.attributes["github.copilot.time_to_first_chunk"];if(t===void 0)return null;let r=typeof t=="number"?t:parseFloat(String(t));return isNaN(r)?null:Math.round(r*1e3)}_ensureDb(){if(this._db)return this._db;this._dbPath!==":memory:"&&j7(le(this._dbPath),{recursive:!0});let{DatabaseSync:n}=J7(),e=new n(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(t){throw e.close(),this._db=null,t}return this._db}_prepareStatements(n){this._insertSpanStmt=n.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=n.prepare("INSERT OR REPLACE INTO span_attributes (span_id, key, value) VALUES (?, ?, ?)"),this._insertEventStmt=n.prepare("INSERT INTO span_events (span_id, name, timestamp_ms, attributes) VALUES (?, ?, ?, ?)"),this._beginTx=n.prepare("BEGIN"),this._commitTx=n.prepare("COMMIT"),this._rollbackTx=n.prepare("ROLLBACK")}_ensureSchema(){let n=this._db;((()=>{try{return n.prepare("SELECT version FROM schema_version LIMIT 1").get()}catch{return}})()?.version??0)>=DE||n.exec(`
			CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
			INSERT OR REPLACE INTO schema_version (version) VALUES (${DE});

			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(n){let e=Date.now()-ME;n.prepare("DELETE FROM spans WHERE start_time_ms < ?").run(e);let t=n.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(OE);t?.cutoff_ms&&n.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(t.cutoff_ms,OE)}};var Q7=Y_;function sC(i){if(!i)return!1;let n=i.trim().toLowerCase();return n==="true"||n==="1"||n==="yes"||n==="on"}function X7(i){if(!i)return;let n={};for(let e of i.split(",")){let t=e.indexOf("=");if(t<=0)continue;let r=e.slice(0,t).trim(),o=e.slice(t+1).trim();r&&(n[r]=o)}return Object.keys(n).length?n:void 0}function Z7(i){let n=sC(i.COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED),e=i.OTEL_EXPORTER_OTLP_ENDPOINT??i.COPILOT_OTEL_ENDPOINT,t=i.COPILOT_OTEL_FILE_EXPORTER_PATH,o=sC(i.COPILOT_OTEL_ENABLED)||n||!!e||!!t,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:t&&(l="file"),(a==="grpc"||a==="http/grpc")&&(l="otlp-grpc"),{enabled:o,dbSpanExporter:n,exporterType:l,otlpEndpoint:e,filePath:t,sourceName:i.COPILOT_OTEL_SOURCE_NAME,captureContent:i.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT===void 0?void 0:sC(i.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT),headers:X7(i.OTEL_EXPORTER_OTLP_HEADERS)}}var Ll=class extends T{constructor(e,t){super();this._logService=e;this._config=Z7(process.env),this._spansDbPath=j(t.userDataPath,Q7)}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?v.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 Y7(le(this._spansDbPath),{recursive:!0});let e=new eh(this._spansDbPath);this._register(M(()=>e.close())),this._forwarder=this._buildOutboundForwarder();let t=await EE({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=t,this._register(t),this._forwarder&&this._register(this._forwarder),this._logService.info(`[agentHost.otel] loopback receiver at ${t.baseUrl}, db ${this._spansDbPath}`)}_buildOutboundForwarder(){let e=[];switch(this._config.exporterType){case"otlp-http":case"otlp-grpc":this._config.otlpEndpoint&&e.push(new Ym({endpoint:this._config.otlpEndpoint,headers:this._config.headers},this._logService));break;case"file":this._config.filePath&&e.push(new Qm({filePath:this._config.filePath},this._logService));break;case"console":e.push(new Xm(this._logService));break}if(e.length)return e.length===1?e[0]:new Zm(e)}};Ll=w([C(0,D),C(1,Rt)],Ll);var th=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}},LE=class i extends T{constructor(e,t){super();this._send=e;this._handlers=t;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,t=Ae.None,r){if(this._store.isDisposed)return Promise.reject(new Y);let o=this._nextRequestId++,s=new Ee,a=new Ze;this._pendingRequests.set(o,{promise:s,cts:a});let l=t.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 t=await this._handleMessage(e);return t?[t]:[]}cancelPendingRequest(e){let t=this._pendingRequests.get(e);t&&(this._pendingRequests.delete(e),t.cts.cancel(),t.promise.cancel(),t.cts.dispose(!0))}cancelAllRequests(){for(let[e,t]of this._pendingRequests)this._pendingRequests.delete(e),t.cts.cancel(),t.promise.cancel(),t.cts.dispose(!0)}async _handleMessage(e){if(aC(e)){me(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(e9(e))return this._handleRequest(e);t9(e)&&this._handlers.handleNotification?.(e)}_handleResult(e){let t=this._pendingRequests.get(e.id);t&&(this._pendingRequests.delete(e.id),t.promise.complete(e.result),t.cts.dispose(!0))}_handleError(e){if(e.id===void 0)return;let t=this._pendingRequests.get(e.id);t&&(this._pendingRequests.delete(e.id),t.promise.error(new th(e.error.code,e.error.message,e.error.data)),t.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 t=new Ze;this._register(M(()=>t.dispose(!0)));try{let r=this._handlers.handleRequest(e,t.token),o=n9(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 th?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{t.dispose(!0)}}dispose(){this.cancelAllRequests(),super.dispose()}static createParseError(e,t){return{jsonrpc:"2.0",error:{code:i.ParseError,message:e,data:t}}}};function e9(i){return"method"in i&&"id"in i&&(typeof i.id=="string"||typeof i.id=="number")}function aC(i){return me(i,{id:!0,result:!0})||me(i,{id:!0,error:!0})}function t9(i){return me(i,{method:!0})&&!me(i,{id:!0})}function n9(i){return typeof i=="object"&&i!==null&&"then"in i&&typeof i.then=="function"}function NE(i,n){if(Mo(i.channel)){for(let e of n)if(Mo(e))return!0;return!1}for(let e of n)if(e===i.channel)return!0;return!1}var Nl="0.5.1",Dke=Object.freeze(["0.5.1","0.5.0"]);function UE(i){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);if(!n)throw new Error(`Invalid protocol version: ${i}`);return[Number(n[1]),Number(n[2]),Number(n[3])]}function lC(i,n){let[e,t,r]=UE(i),[o,s,a]=UE(n);return e-o||t-s||r-a}var Mke={"root/agentsChanged":"0.1.0","root/activeSessionsChanged":"0.1.0","session/ready":"0.1.0","session/creationFailed":"0.1.0","session/chatAdded":"0.4.0","session/chatRemoved":"0.4.0","session/chatUpdated":"0.4.0","session/defaultChatChanged":"0.4.0","session/titleChanged":"0.1.0","session/serverToolsChanged":"0.1.0","session/activeClientSet":"0.5.0","session/activeClientRemoved":"0.5.0","session/inputNeededSet":"0.5.1","session/inputNeededRemoved":"0.5.1","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/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","chat/turnStarted":"0.4.0","chat/delta":"0.4.0","chat/responsePart":"0.4.0","chat/toolCallStart":"0.4.0","chat/toolCallDelta":"0.4.0","chat/toolCallReady":"0.4.0","chat/toolCallConfirmed":"0.4.0","chat/toolCallComplete":"0.4.0","chat/toolCallResultConfirmed":"0.4.0","chat/toolCallContentChanged":"0.4.0","chat/turnComplete":"0.4.0","chat/turnCancelled":"0.4.0","chat/error":"0.4.0","chat/activityChanged":"0.5.0","chat/usage":"0.4.0","chat/reasoning":"0.4.0","chat/pendingMessageSet":"0.4.0","chat/pendingMessageRemoved":"0.4.0","chat/queuedMessagesReordered":"0.4.0","chat/draftChanged":"0.5.0","chat/inputRequested":"0.4.0","chat/inputAnswerChanged":"0.4.0","chat/inputCompleted":"0.4.0","chat/truncated":"0.4.0","changeset/statusChanged":"0.2.0","changeset/fileSet":"0.2.0","changeset/fileRemoved":"0.2.0","changeset/contentChanged":"0.4.0","changeset/operationsChanged":"0.2.0","changeset/operationStatusChanged":"0.3.0","changeset/cleared":"0.2.0","annotations/set":"0.4.0","annotations/updated":"0.4.0","annotations/removed":"0.4.0","annotations/entrySet":"0.4.0","annotations/entryRemoved":"0.4.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 FE(i){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])]}function r9(i,n){let e=FE(i),t=FE(n);return!e||!t||e[0]!==t[0]||e[0]===0&&e[1]!==t[1]?!1:lC(i,n)<=0}function HE(i,n){let e;for(let t of i)r9(t,n)&&(e===void 0||lC(t,e)>0)&&(e=t);return e}var dC="_vscodeUpgrade";var $E="VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";function nh(){let i=process.env[$E];return i&&i.length>0?i:void 0}async function WE(i=nh()){let n=await import("http");return i?new Promise((e,t)=>{let r=n.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}`;t(new Error(`Agent host upgrade request failed: ${c}`))}}),o.on("error",t)});r.once("error",t),r.end()}):Promise.reject(new Error(`Cannot request upgrade: ${$E} is not set.`))}function qE(i,n){if(i!=="resourceRead"||!i9(n))return!1;let e=n.uri;if(typeof e!="string")return!1;try{return v.parse(e).scheme===ie.file}catch{return!1}}function i9(i){return typeof i=="object"&&i!==null&&me(i,{uri:!0})}var o9=1e3,BE=3e4;function s9(i){return i==="streaming"||i==="running"||i==="pending-confirmation"}function cs(i,n){return{jsonrpc:"2.0",id:i,result:n}}function cu(i,n,e,t){return{jsonrpc:"2.0",id:i,error:{code:n,message:e,...t!==void 0?{data:t}:{}}}}function us(i,n){if(n instanceof k)return cu(i,n.code,n.message,n.data);let e=n instanceof Error?n.stack??n.message:String(n);return cu(i,Lo,e)}function a9(i,n,e){return!(e instanceof k)||e.code!==ye.NotFound||!qE(i,n)}function zE(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function l9(i){if(!zE(i))return;let n=i.channel;if(!(typeof n!="string"||!n.startsWith("mcp://")))return n}function rh(i){if(i.toLowerCase().startsWith(`${gP}:`)){let n=yP(i);return n?{kind:"otlp-logs",uri:vP(n),level:n}:void 0}return O_(i)?{kind:"resource-watch",uri:i}:{kind:"state",uri:i}}var ps=class extends T{constructor(e,t,r,o,s,a){super();this._agentService=e;this._stateManager=t;this._server=r;this._config=o;this._clientFileSystemProvider=s;this._logService=a;this._clients=new Map;this._replayBuffer=[];this._onDidChangeConnectionCount=this._register(new P);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,t)=>{let r=rh(t.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 ${t.channel}: no OTLP emitter configured.`),{});if(r.kind==="resource-watch"){let o=this._agentService.onResourceWatchSubscribed(r.uri);if(!o)throw new k(ut,`Resource watch not found: ${t.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(v.parse(t.channel),e.clientId);return e.subscriptions.set(r.uri,r),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),{snapshot:o}}catch(o){throw o instanceof k?o:new k(ut,`Resource not found: ${t.channel}`)}},createSession:async(e,t)=>{let r,o;if(t.fork){let s=this._stateManager.getSessionState(t.fork.session);if(!s)throw new k(ut,`Fork source session not found: ${t.fork.session}`);let a=s.turns.findIndex(l=>l.id===t.fork.turnId);if(a<0)throw new k(ut,`Fork turn ID ${t.fork.turnId} not found in session ${t.fork.session}`);o={session:v.parse(t.fork.session),turnIndex:a,turnId:t.fork.turnId}}if(t.activeClient&&t.activeClient.clientId!==e.clientId)throw new k(ne.InvalidParams,"createSession.activeClient.clientId must match the connection's clientId");try{r=await this._agentService.createSession({provider:t.provider,workingDirectory:t.workingDirectory?v.parse(t.workingDirectory):void 0,session:v.parse(t.channel),fork:o,config:t.config,activeClient:t.activeClient,progressToken:t.progressToken})}catch(s){throw s instanceof k?s:new k(iT,s instanceof Error?s.message:String(s))}return r.toString()!==v.parse(t.channel).toString()&&this._logService.warn(`[ProtocolServer] createSession: provider returned URI ${r.toString()} but client requested ${t.channel}`),null},disposeSession:async(e,t)=>(await this._agentService.disposeSession(v.parse(t.channel)),null),createChat:async(e,t)=>{let r=this._stateManager.getSessionState(t.channel);if(!r)throw new k(ut,`Session not found: ${t.channel}`);let o=r.defaultChat??be(t.channel);return v.parse(t.chat).toString()===v.parse(o).toString()||await this._agentService.createChat(v.parse(t.channel),v.parse(t.chat),{...t.source?{fork:{source:v.parse(t.source.chat),turnId:t.source.turnId}}:{}}),null},disposeChat:async(e,t)=>{let r=v.parse(t.channel),o=He(r);return o&&await this._agentService.disposeChat(v.parse(o.session),r),null},resourceWrite:async(e,t)=>this._agentService.resourceWrite(t),listSessions:async()=>({items:(await this._agentService.listSessions()).map(r=>{let o=L.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:new Date(r.startTime).toISOString(),modifiedAt:new Date(r.modifiedTime).toISOString(),...r.project?{project:{uri:r.project.uri.toString(),displayName:r.project.displayName}}:{},workingDirectory:r.workingDirectory?.toString(),changes:r.changes}})}),resolveSessionConfig:async(e,t)=>this._agentService.resolveSessionConfig({provider:t.provider,workingDirectory:t.workingDirectory?v.parse(t.workingDirectory):void 0,config:t.config}),sessionConfigCompletions:async(e,t)=>this._agentService.sessionConfigCompletions({provider:t.provider,workingDirectory:t.workingDirectory?v.parse(t.workingDirectory):void 0,config:t.config,property:t.property,query:t.query}),completions:async(e,t)=>this._agentService.completions(t),fetchTurns:async(e,t)=>{let r=this._stateManager.getSessionState(t.channel);if(!r)throw new k(ut,`Session not found: ${t.channel}`);let o=r.turns,s=Math.min(t.limit??50,100),a=o.length;if(t.before){let d=o.findIndex(c=>c.id===t.before);d!==-1&&(a=d)}let l=Math.max(0,a-s);return{turns:o.slice(l,a),hasMore:l>0}},resourceList:async(e,t)=>this._agentService.resourceList(v.parse(t.uri)),resourceRead:async(e,t)=>this._agentService.resourceRead(v.parse(t.uri)),resourceCopy:async(e,t)=>this._agentService.resourceCopy(t),resourceDelete:async(e,t)=>this._agentService.resourceDelete(t),resourceMove:async(e,t)=>this._agentService.resourceMove(t),resourceResolve:async(e,t)=>this._agentService.resourceResolve(t),resourceMkdir:async(e,t)=>this._agentService.resourceMkdir(t),createResourceWatch:async(e,t)=>this._agentService.createResourceWatch(t),resourceRequest:async(e,t)=>({}),authenticate:async(e,t)=>{if(!(await this._agentService.authenticate(t)).authenticated)throw new k(tr,`Authentication failed for resource: ${t.resource}`);return{}},createTerminal:async(e,t)=>(await this._agentService.createTerminal(t),null),disposeTerminal:async(e,t)=>(await this._agentService.disposeTerminal(v.parse(t.channel)),null),invokeChangesetOperation:async(e,t)=>this._agentService.invokeChangesetOperation(t)};this._reverseRequestId=0;this._pendingReverseRequests=new Map;this._register(this._server.onConnection(l=>{this._handleNewConnection(l)})),this._register(this._stateManager.onDidEmitEnvelope(l=>{if(this._replayBuffer.push(l),this._replayBuffer.length>o9&&this._replayBuffer.shift(),this._broadcastAction(l),l.action.type==="chat/toolCallStart"||l.action.type==="chat/toolCallReady"){if(!ce(l.channel))throw new Error(`[ProtocolServer] Chat tool-call action emitted on non-chat channel: ${l.channel}`);this._checkOrphanedClientToolCalls(fe(l.channel),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 t=new G,r;t.add(e.onMessage(o=>{if(sT(o)){if(this._logService.trace(`[ProtocolServer] request: method=${o.method} id=${o.id}`),o.method==="ping"){e.send(cs(o.id,null));return}if(!r&&o.method==="initialize"){try{let s=this._handleInitialize(o.params,e,t);r=s.client,e.send(cs(o.id,s.response))}catch(s){e.send(us(o.id,s))}return}if(!r&&o.method==="reconnect"){let s;try{let a=this._handleReconnect(o.params,e,t);r=a.client,s=a.responsePromise}catch(a){e.send(us(o.id,a));return}s.then(a=>e.send(cs(o.id,a)),a=>e.send(us(o.id,a)));return}if(o.method===dC){this._handleVscodeUpgrade(o.id,e);return}if(!r)return;this._handleRequest(r,o.method,o.params,o.id)}else if(aT(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;(Vd(s)||rr(s)||Vp(s)||s.type==="root/configChanged")&&this._agentService.dispatchAction(a,s,r.clientId,o.params.clientSeq)}break}else if(aC(o)){let s=this._pendingReverseRequests.get(o.id);s&&s.client===r&&(this._pendingReverseRequests.delete(o.id),me(o,{error:!0})?s.reject(new k(o.error?.code??-32e3,o.error?.message??"Reverse RPC error",o.error?.data)):s.resolve(o.result))}})),t.add(e.onClose(()=>{let o=r?this._clients.get(r.clientId):void 0;if(r&&o?.state==="active"){let s=o.connections.indexOf(r);if(s!==-1){let a=r.subscriptions.size;o.connections.splice(s,1),this._releaseClientSubscriptions(r,o),this._rejectPendingReverseRequestsForConnection(r),o.connections.length===0&&(this._logService.info(`[ProtocolServer] Client disconnected: ${r.clientId}, subscriptions=${a}`),this._clients.set(r.clientId,{state:"grace",lastSeenAt:Date.now(),disconnectTimeouts:new Re}),this._handleClientDisconnected(r.clientId),this._onDidChangeConnectionCount.fire(this._connectedClientCount))}}t.dispose()})),t.add(e)}_handleInitialize(e,t,r){let o=Array.isArray(e.protocolVersions)?e.protocolVersions:[];this._logService.info(`[ProtocolServer] Initialize: clientId=${e.clientId}, protocolVersions=[${o.join(", ")}]`);let s=HE(o,Nl);if(!s){let d={supportedVersions:[`^${Nl}`],_meta:nh()?{vscodeUpgradeMethod:dC}:void 0};throw new k(oT,`Client offered protocol versions [${o.join(", ")}], none of which are compatible with this server's version ${Nl} (server accepts ^${Nl}).`,d)}let a={clientId:e.clientId,protocolVersion:s,transport:t,subscriptions:new Map,disposables:r};this._attachConnection(e.clientId,a),this._registerClientFileSystemAuthority(e.clientId,r);let l=[];if(e.initialSubscriptions)for(let d of e.initialSubscriptions){let c=this._addInitialSubscription(a,d.toString());c&&l.push(c)}return{client:a,response:{protocolVersion:s,serverSeq:this._stateManager.serverSeq,snapshots:l,defaultDirectory:this._config.defaultDirectory,completionTriggerCharacters:this._config.completionTriggerCharacters,telemetry:this._config.otlpLogEmitter?{logs:fP}:void 0}}}_addInitialSubscription(e,t){let r=rh(t);if(!r)return;if(r.kind==="otlp-logs"){if(!this._config.otlpLogEmitter){this._logService.warn(`[ProtocolServer] Ignoring OTLP initialSubscription ${t}: no OTLP emitter configured.`);return}e.subscriptions.set(r.uri,r);return}let o=this._stateManager.getSnapshot(t);if(o)return e.subscriptions.set(r.uri,r),this._agentService.addSubscriber(v.parse(r.uri),e.clientId),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),o}_handleVscodeUpgrade(e,t){let r=nh();if(!r){t.send(cu(e,ne.MethodNotFound,"No upgrade supervisor is available for this agent host."));return}WE(r).then(o=>t.send(cs(e,o)),o=>{this._logService.warn(`[ProtocolServer] vscodeUpgrade signal failed: ${o instanceof Error?o.message:String(o)}`),t.send(us(e,o))})}_handleReconnect(e,t,r){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let o={clientId:e.clientId,protocolVersion:Nl,transport:t,subscriptions:new Map,disposables:r};this._attachConnection(e.clientId,o),this._registerClientFileSystemAuthority(e.clientId,r);let s=this._replayBuffer.length>0?this._replayBuffer[0].serverSeq:this._stateManager.serverSeq,a=e.lastSeenServerSeq>=s,l=this._restoreReconnectSubscriptions(o,e,a);return{client:o,responsePromise:l}}_registerClientFileSystemAuthority(e,t){t.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,t,r){let o=[],s=await Promise.all(t.subscriptions.map(async a=>{let l=a.toString(),d=rh(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(v.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(this._reconcileActiveClientsAfterReconnect(e),r){let a=[];for(let l of this._replayBuffer)l.serverSeq>t.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)}}_reconcileActiveClientsAfterReconnect(e){let t=this._clients.get(e.clientId),r=new Set;for(let o of t?.state==="active"?t.connections:[e])for(let s of o.subscriptions.values())s.kind==="state"&&r.add(s.uri);for(let o of this._stateManager.getSessionUris()){let s=this._stateManager.getSessionState(o);if(s&&this._isActiveClient(s,e.clientId))for(let a of s.chats)!r.has(o)&&!r.has(a.resource)&&this._releaseActiveClientForSession(o,e.clientId,a.resource)}}_handleClientDisconnected(e){for(let t of this._stateManager.getSessionUris()){let r=this._stateManager.getSessionState(t),o=r?this._isActiveClient(r,e):!1,s=r?this._hasPendingClientToolCall(r,e):!1;if(o||s)for(let a of r?.chats??[])this._startClientToolCallDisconnectTimeout(e,t,a.resource)}}_isActiveClient(e,t){return e.activeClients.some(r=>r.clientId===t)}_removeActiveClient(e,t){let r=this._stateManager.getSessionState(e);r&&this._isActiveClient(r,t)&&this._stateManager.dispatchServerAction(e,{type:"session/activeClientRemoved",clientId:t})}_releaseActiveClientForSession(e,t,r){this._clearClientToolCallDisconnectTimeout(t,r),this._completeDisconnectedClientToolCalls(t,e,r),this._removeActiveClient(e,t)}*_pendingClientToolCalls(e){let t=e?.activeTurn;if(t)for(let r of t.responseParts){if(r.kind!=="toolCall")continue;let o=r.toolCall,s=o.contributor;s?.kind==="client"&&s9(o.status)&&(yield{toolCall:o,clientId:s.clientId})}}_hasPendingClientToolCall(e,t){for(let r of this._pendingClientToolCalls(e))if(r.clientId===t)return!0;return!1}_hasReplacementActiveClientTool(e,t,r){return e.activeClients.some(o=>o.clientId!==t&&o.tools.some(s=>s.name===r))}_startClientToolCallDisconnectTimeout(e,t,r){let o=this._ensureGraceRecord(e);if(!o)return;o.disconnectTimeouts.deleteAndDispose(r);let s=Date.now()-o.lastSeenAt,a=Math.max(0,BE-s);o.disconnectTimeouts.set(r,Kt(()=>{this._releaseActiveClientForSession(t,e,r)},a))}_checkOrphanedClientToolCalls(e,t){let r=this._stateManager.getSessionState(t),o=new Set;for(let{clientId:s}of this._pendingClientToolCalls(r))this._clients.get(s)?.state!=="active"&&o.add(s);for(let s of o)this._startClientToolCallDisconnectTimeout(s,e,t)}_attachConnection(e,t){let r=this._clients.get(e);r?.state==="active"?r.connections.push(t):(r?.disconnectTimeouts.dispose(),this._clients.set(e,{state:"active",connections:[t]})),this._pruneClientRecords(),this._onDidChangeConnectionCount.fire(this._connectedClientCount)}_ensureGraceRecord(e){let t=this._clients.get(e);if(t?.state==="active")return;if(t)return t;let r={state:"grace",lastSeenAt:Date.now(),disconnectTimeouts:new Re};return this._clients.set(e,r),r}_getActiveClient(e){return this._getActiveClientFromRecord(this._clients.get(e))}_getActiveClientFromRecord(e){if(e?.state==="active")return e.connections[e.connections.length-1]}_releaseClientSubscriptions(e,t){for(let r of e.subscriptions.values())if(r.kind==="state"){if(this._hasSubscriptionInOtherConnection(t,e,r.uri))continue;this._agentService.unsubscribe(v.parse(r.uri),e.clientId)}else r.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(r.uri);e.subscriptions.clear()}_hasSubscriptionInOtherConnection(e,t,r){if(e.state!=="active")return!1;for(let o of e.connections)if(o!==t&&o.subscriptions.has(r))return!0;return!1}get _connectedClientCount(){let e=0;for(let t of this._clients.values())t.state==="active"&&e++;return e}_pruneClientRecords(){let e=Date.now()-BE*10;for(let[t,r]of this._clients)r.state==="grace"&&r.disconnectTimeouts.size===0&&r.lastSeenAt<e&&this._clients.delete(t)}_clearClientToolCallDisconnectTimeout(e,t){let r=this._clients.get(e);r?.state==="grace"&&r.disconnectTimeouts.deleteAndDispose(t)}_completeDisconnectedClientToolCalls(e,t,r){let o=this._stateManager.getSessionState(r),s=o?.activeTurn;if(!(!o||!s))for(let{toolCall:a,clientId:l}of this._pendingClientToolCalls(o)){if(l!==e)continue;let d=this._hasReplacementActiveClientTool(o,e,a.toolName);a.status==="streaming"&&this._stateManager.dispatchServerAction(r,{type:"chat/toolCallReady",turnId:s.id,toolCallId:a.toolCallId,invocationMessage:a.invocationMessage??a.displayName,confirmed:"not-needed"}),this._stateManager.dispatchServerAction(r,{type:"chat/toolCallComplete",turnId:s.id,toolCallId:a.toolCallId,result:{success:!1,pastTenseMessage:`${a.displayName} failed`,...d?{content:[{type:"text",text:`The client that was running ${a.displayName} disconnected, but another active client now provides ${a.displayName}. You may try calling the tool again.`}]}:{},error:{message:`Client ${e} disconnected before completing ${a.displayName}`}}})}}_sendReverseRequest(e,t,r){let o=this._getActiveClient(e);if(!o)return Promise.reject(new Error(`Client ${e} is not connected`));let s=++this._reverseRequestId;return new Promise((a,l)=>{this._pendingReverseRequests.set(s,{client:o,resolve:a,reject:l});let d={jsonrpc:"2.0",id:s,method:t,params:r};o.transport.send(d)})}_rejectPendingReverseRequestsForConnection(e){for(let[t,r]of this._pendingReverseRequests)r.client===e&&(this._pendingReverseRequests.delete(t),r.reject(new Error(`Client ${e.clientId} disconnected`)))}_handleRequest(e,t,r,o){let s=this._requestHandlers.hasOwnProperty(t)?this._requestHandlers[t]:void 0;if(s){s(e,r).then(d=>{this._logService.trace(`[ProtocolServer] Request '${t}' id=${o} succeeded`),e.transport.send(cs(o,d??null))}).catch(d=>{a9(t,r,d)&&this._logService.error(`[ProtocolServer] Request '${t}' failed`,d),e.transport.send(us(o,d))});return}let a=this._handleExtensionRequest(t,r);if(a){a.then(d=>{e.transport.send(cs(o,d??null))}).catch(d=>{this._logService.error(`[ProtocolServer] Extension request '${t}' failed`,d),e.transport.send(us(o,d))});return}let l=l9(r);if(l!==void 0){let d=zE(r)?r:void 0;this._agentService.handleMcpRequest(l,t,d).then(c=>{e.transport.send(cs(o,c??null))}).catch(c=>{if(c instanceof Error&&c.message.startsWith("Method not found")){e.transport.send(cu(o,ne.MethodNotFound,c.message));return}this._logService.error(`[ProtocolServer] mcp:// request '${t}' on ${l} failed`,c),e.transport.send(us(o,c))});return}e.transport.send(cu(o,Lo,`Unknown method: ${t}`))}_handleExtensionRequest(e,t){if(e==="shutdown")return this._agentService.shutdown()}_broadcastAction(e){this._logService.trace(`[ProtocolServer] Broadcasting action: ${e.action.type}`);let t={jsonrpc:"2.0",method:"action",params:e};for(let r of this._clients.values()){let o=this._getActiveClientFromRecord(r);o&&this._isRelevantToClient(o,e)&&o.transport.send(t)}}_broadcastNotification(e){let{type:t,...r}=e,o={jsonrpc:"2.0",method:t,params:r};for(let s of this._clients.values())this._getActiveClientFromRecord(s)?.transport.send(o)}_broadcastMcpNotification(e){let t={...e.params??{},channel:e.channel},r={jsonrpc:"2.0",method:e.method,params:t};for(let o of this._clients.values())this._getActiveClientFromRecord(o)?.transport.send(r)}_removeSubscription(e,t){let r=rh(t);if(!r)return;let o=e.subscriptions.get(r.uri);if(o)if(e.subscriptions.delete(r.uri),o.kind==="state"){let s=this._clients.get(e.clientId);if(s&&this._hasSubscriptionInOtherConnection(s,e,o.uri))return;if(this._agentService.unsubscribe(v.parse(o.uri),e.clientId),ce(o.uri))this._releaseActiveClientForSession(fe(o.uri),e.clientId,o.uri);else{let a=this._stateManager.getSessionState(o.uri);for(let l of a?.chats??[])this._releaseActiveClientForSession(o.uri,e.clientId,l.resource)}}else o.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(o.uri)}_broadcastOtlpLog(e){let t=hP(e);for(let r of this._clients.values()){let o=this._getActiveClientFromRecord(r);if(o)for(let s of o.subscriptions.values()){if(s.kind!=="otlp-logs"||e.severityNumber<mP(s.level))continue;let a={jsonrpc:"2.0",method:"otlp/exportLogs",params:{channel:s.uri,payload:t}};o.transport.send(a)}}}_isRelevantToClient(e,t){let r=e.subscriptions.get(t.channel);return r?.kind==="state"||r?.kind==="resource-watch"?!0:Mo(t.channel)?NE(t,this._stateAndResourceWatchUris(e)):!1}*_stateAndResourceWatchUris(e){for(let t of e.subscriptions.values())(t.kind==="state"||t.kind==="resource-watch")&&(yield t.uri)}dispose(){for(let e of this._clients.values())if(e.state==="active")for(let t of[...e.connections])t.disposables.dispose();else 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()}};ps=w([C(5,D)],ps);var d9="ahp",c9=75*1024*1024,u9=5,p9=1024*1024,f9=1024*1024,g9=16*1024,Ul=class extends T{constructor(e,t,r){super();this._options=e;this._fileService=t;this._logService=r;this._currentSize=0;this._segment=0;this._queue=Promise.resolve();this._pending=[];this._drainScheduled=!1;this._directory=te(this._options.logsHome,d9);let o=v9(this._options.connectionId).slice(0,64);this._baseName=`ahp-${y9(new Date)}-${o}.jsonl`,this._maxFileSizeBytes=this._options.maxFileSizeBytes??c9,this._maxFiles=this._options.maxFiles??u9,this._currentFile=te(this._directory,this._baseName)}get resource(){return this._currentFile}log(e,t,r){let o={ts:new Date().toISOString(),dir:t,connectionId:this._options.connectionId,transport:this._options.transport,...typeof r=="number"?{byteLength:r}:{}},s={...e,_ahpLog:o},a=m9(s);a.length>f9&&(o.truncated=!0,a=h9(s,g9));let l=`${a}
`;this._pending.push(U.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 t=[],r=0,o=async()=>{if(t.length===0)return;let s=t.length===1?t[0]:U.concat(t,r);await this._fileService.writeFile(this._currentFile,s,{append:!0}),this._currentSize+=s.byteLength,t=[],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>p9&&await o(),t.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(t=>{this._logService.trace("[AHPLog] Failed to delete old transport log",t)}),this._currentFile=this._resourceForSegment(this._segment),this._currentSize=await this._getFileSize(this._currentFile)}_resourceForSegment(e){if(e===0)return te(this._directory,this._baseName);let t=this._baseName.slice(0,-6);return te(this._directory,`${t}.${e}.jsonl`)}async _getFileSize(e){try{return(await this._fileService.resolve(e)).size??0}catch{return 0}}};Ul=w([C(1,xe),C(2,D)],Ul);function cC(i){return U.fromString(i).byteLength}function m9(i){return JSON.stringify(i,VE)}function h9(i,n){return JSON.stringify(i,function(e,t){let r=VE.call(this,e,t);return typeof r=="string"&&r.length>n?`${r.slice(0,n)}\u2026[${r.length-n} more chars elided]`:r})}function VE(i,n){return n&&typeof n=="object"&&n.$mid===1&&UI(n)?v.revive(n).toString():n}function y9(i){return i.toISOString().replace(/[:.]/g,"-")}function v9(i){return i.replace(/[\\/:\*\?"<>\|\s]+/g,"-").replace(/^-+|-+$/g,"")||"connection"}var uC=class extends T{constructor(e,t,r){super();this._ws=e;this._WebSocket=t;this._ahpLogger=r;this._onMessage=this._register(new P);this.onMessage=this._onMessage.event;this._onClose=this._register(new P);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",cC(s)),this._onMessage.fire(a)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:rT,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 t=JSON.stringify(e);this._ahpLogger?.log(e,"s2c",cC(t)),this._ws.send(t)}}dispose(){this._ws.close(),super.dispose()}},uu=class i extends T{constructor(e,t,r,o,s,a){super();this._logService=t;this._ahpLogOptions=r;this._connectionCount=0;this._onConnection=this._register(new P);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[ly];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(),y=!h||typeof h=="string"?`${d}:${l.port}`:`${h.address}:${h.port}`;this._logService.info(`[WebSocketProtocol] Server listening on ${y}`),p()}),u.once("error",m)})}this._wss.on("connection",u=>{this._logService.trace("[WebSocketProtocol] New client connection");let p=new uC(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,t,r){let[o,s,a]=await Promise.all([import("ws"),import("http"),import("url")]);return new i(e,t,r,o,s,a)}_createAhpLogger(){if(this._ahpLogOptions)return this._ahpLogOptions.instantiationService.createInstance(Ul,{logsHome:this._ahpLogOptions.logsHome,connectionId:`agent-host-${++this._connectionCount}-${H()}`,transport:"websocket"})}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};import{homedir as w9,tmpdir as R9}from"os";var jE=/^([^.]+\..+)[:=](.+)$/,ve=class{constructor(n,e,t){this._args=n;this.paths=e;this.productService=t}get appRoot(){return le(Dt.asFileUri("").fsPath)}get userHome(){return v.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return v.file(j(this.userDataPath,"User"))}get tmpDir(){return v.file(this.paths.tmpDir)}get cacheHome(){return v.file(this.userDataPath)}get stateResource(){return te(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:ie.vscodeUserData})}get userDataSyncHome(){return te(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let n=hx(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=j(this.userDataPath,"logs",n)}return v.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return te(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return te(this.appSettingsHome,"History")}get keyboardLayoutResource(){return te(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let n=Xe.VSCODE_PORTABLE;return n?v.file(j(n,"argv.json")):te(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return v.file(j(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let n=this.args["builtin-extensions-dir"];return n?Mn(n):cn(j(Dt.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let n=this.args["extensions-download-dir"];return n?v.file(Mn(n)):v.file(j(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let n=this.args["extensions-dir"];if(n)return Mn(n);let e=Xe.VSCODE_EXTENSIONS;if(e)return e;let t=Xe.VSCODE_PORTABLE;return t?j(t,"extensions"):te(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get appSharedDataHome(){let n=this.args["shared-data-dir"];if(n)return v.file(Mn(n));let e=Xe.VSCODE_PORTABLE;return e?v.file(j(e,"shared-data")):te(this.userHome,this.productService.sharedDataFolderName)}get extensionDevelopmentLocationURI(){let n=this.args.extensionDevelopmentPath;if(Array.isArray(n))return n.map(e=>/^[^:/?#]+?:\/\//.test(e)?v.parse(e):v.file(cn(e)))}get extensionDevelopmentKind(){return this.args.extensionDevelopmentKind?.map(n=>n==="ui"||n==="workspace"||n==="web"?n:"workspace")}get extensionTestsLocationURI(){let n=this.args.extensionTestsPath;if(n)return/^[^:/?#]+?:\/\//.test(n)?v.parse(n):v.file(cn(n))}get disableExtensions(){if(this.args["disable-extensions"])return!0;let n=this.args["disable-extension"];if(n){if(typeof n=="string")return[n];if(Array.isArray(n)&&n.length>0)return n}return!1}get skipBuiltinExtensions(){let n=Xe.VSCODE_SKIP_BUILTIN_EXTENSIONS;return n?n.split(",").map(e=>e.trim()).filter(e=>e):[]}get debugExtensionHost(){return S9(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!Xe.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(n=>!jE.test(n))}get extensionLogLevel(){let n=[];for(let e of this.args.log||[]){let t=jE.exec(e);t?.[1]&&t[2]&&n.push([t[1],t[2]])}return n.length?n:void 0}get serviceMachineIdResource(){return te(v.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 n=Xe.VSCODE_PORTABLE;return n?v.file(j(n,"policy.json")):te(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return te(this.appSettingsHome,"agent-sessions.code-workspace")}get editSessionId(){return this.args.editSessionId}get exportPolicyData(){return this.args["export-policy-data"]}get exportDefaultKeybindings(){return this.args["export-default-keybindings"]}get continueOn(){return this.args.continueOn}set continueOn(n){this.args.continueOn=n}get args(){return this._args}};w([Se],ve.prototype,"appRoot",1),w([Se],ve.prototype,"userHome",1),w([Se],ve.prototype,"userDataPath",1),w([Se],ve.prototype,"appSettingsHome",1),w([Se],ve.prototype,"tmpDir",1),w([Se],ve.prototype,"cacheHome",1),w([Se],ve.prototype,"stateResource",1),w([Se],ve.prototype,"userRoamingDataHome",1),w([Se],ve.prototype,"userDataSyncHome",1),w([Se],ve.prototype,"sync",1),w([Se],ve.prototype,"workspaceStorageHome",1),w([Se],ve.prototype,"localHistoryHome",1),w([Se],ve.prototype,"keyboardLayoutResource",1),w([Se],ve.prototype,"argvResource",1),w([Se],ve.prototype,"isExtensionDevelopment",1),w([Se],ve.prototype,"untitledWorkspacesHome",1),w([Se],ve.prototype,"builtinExtensionsPath",1),w([Se],ve.prototype,"extensionsDownloadLocation",1),w([Se],ve.prototype,"extensionsPath",1),w([Se],ve.prototype,"appSharedDataHome",1),w([Se],ve.prototype,"extensionDevelopmentLocationURI",1),w([Se],ve.prototype,"extensionDevelopmentKind",1),w([Se],ve.prototype,"extensionTestsLocationURI",1),w([Se],ve.prototype,"debugExtensionHost",1),w([Se],ve.prototype,"logLevel",1),w([Se],ve.prototype,"extensionLogLevel",1),w([Se],ve.prototype,"serviceMachineIdResource",1),w([Se],ve.prototype,"disableTelemetry",1),w([Se],ve.prototype,"disableExperiments",1),w([Se],ve.prototype,"disableWorkspaceTrust",1),w([Se],ve.prototype,"useInMemorySecretStorage",1),w([Se],ve.prototype,"policyFile",1),w([Se],ve.prototype,"agentSessionsWorkspace",1);function S9(i,n){return KE(i["inspect-extensions"],i["inspect-brk-extensions"],5870,n,i.debugId,i.extensionEnvironment)}function KE(i,n,e,t,r,o){let a=Number(n||i)||(t?null:e),l=a?!!n:!1,d;if(o)try{d=JSON.parse(o)}catch{}return{port:a,break:l,debugId:r,env:d}}import{homedir as GE}from"os";import{resolve as b9,isAbsolute as C9,join as Fl}from"path";var I9=process.env.VSCODE_CWD||process.cwd();function JE(i,n){let e=_9(i,n),t=[e];return C9(e)||t.unshift(I9),b9(...t)}function _9(i,n){process.env.VSCODE_DEV&&(n="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return Fl(e,"user-data");let t=process.env.VSCODE_APPDATA;if(t)return Fl(t,n);let r=i["user-data-dir"];return r||T9(n)}function T9(i){let n;switch(process.platform){case"win32":if(n=process.env.APPDATA,!n){let e=process.env.USERPROFILE;if(typeof e!="string")throw new Error("Windows: Unexpected undefined %USERPROFILE% environment variable");n=Fl(e,"AppData","Roaming")}break;case"darwin":n=Fl(GE(),"Library","Application Support");break;case"linux":n=process.env.XDG_CONFIG_HOME||Fl(GE(),".config");break;default:throw new Error("Platform not supported")}return Fl(n,i)}var ih=class extends ve{constructor(n,e){let t=w9();super(n,{homeDir:t,tmpDir:R9(),userDataDir:JE(n,e.nameShort)},e)}};import x9 from"minimist";var YDe={o:f(2461,null),e:f(2445,null),t:f(2475,null),m:f(2456,null)};var pC={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:f(2465,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:f(2432,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:f(2427,null)},maximize:{type:"boolean",cat:"o",description:f(2431,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2468,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2459,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2464,null)},help:{type:"boolean",alias:"h",description:f(2447,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:f(2433,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:f(2433,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:f(2433,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:f(2437,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:f(2457,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:f(2426,null)},remove:{type:"boolean",cat:"o",args:"folder",description:f(2466,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:f(2446,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2458,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2467,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:f(2429,null)},wait:{type:"boolean",cat:"o",alias:"w",description:f(2485,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:f(2453,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:f(2482,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2464,null)},help:{type:"boolean",cat:"o",alias:"h",description:f(2447,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:f(2434,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:f(2444,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"shared-data-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:f(2452,null)},"agent-plugins-dir":{type:"string"},"agents-user-data-dir":{type:"string"},"agents-extensions-dir":{type:"string"},"show-versions":{type:"boolean",cat:"e",description:f(2469,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:f(2430,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:f(2451,null)},"pre-release":{type:"boolean",cat:"e",description:f(2450,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:f(2477,null)},"update-extensions":{type:"boolean",cat:"e",description:f(2480,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:f(2443,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:f(2428,null)},version:{type:"boolean",cat:"t",alias:"v",description:f(2484,null)},verbose:{type:"boolean",cat:"t",global:!0,description:f(2483,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:f(2455,null)},status:{type:"boolean",alias:"s",cat:"t",description:f(2470,null)},"prof-startup":{type:"boolean",cat:"t",description:f(2463,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:f(2440,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:f(2439,null)},sync:{type:"string",cat:"t",description:f(2476,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:f(2449,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:f(2448,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:f(2442,null)},"disable-gpu":{type:"boolean",cat:"t",description:f(2441,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:f(2438,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:f(2454,null)},telemetry:{type:"boolean",cat:"t",description:f(2473,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:f(2474,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[]"}},P9={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function oh(i,n,e=P9){let t=i.find((p,m)=>p.length>0&&p[0]!=="-"&&n.hasOwnProperty(p)&&n[p].type==="subcommand"),r={},o=["_"],s=[],a={},l;for(let p in n){let m=n[p];m.type==="subcommand"?p===t&&(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&&t){let p=a;for(let S in l.options)p[S]=l.options[S];let m=i.filter(S=>S!==t),h=e.getSubcommandReporter?e.getSubcommandReporter(t):void 0,y=oh(m,p,h);return{[t]:y,_:[]}}let d=x9(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 n){let m=n[p];if(m.type==="subcommand")continue;m.alias&&delete u[m.alias];let h=u[p];if(m.deprecates)for(let y of m.deprecates)u.hasOwnProperty(y)&&(h||(h=u[y],h&&e.onDeprecatedOption(y,m.deprecationMessage||f(2436,null,p))),delete u[y]);if(typeof h<"u"){if(m.type==="string[]"){if(Array.isArray(h)||(h=[h]),!m.allowEmptyValue){let y=h.filter(S=>S.length>0);y.length!==h.length&&(e.onEmptyValue(p),h=y.length>0?y: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 sh=class extends T{constructor(n,e=[]){super(),this.logger=new Hp([n,...e]),this._register(n.onDidChangeLogLevel(t=>this.setLevel(t)))}get onDidChangeLogLevel(){return this.logger.onDidChangeLogLevel}setLevel(n){this.logger.setLevel(n)}getLevel(){return this.logger.getLevel()}trace(n,...e){this.logger.trace(n,...e)}debug(n,...e){this.logger.debug(n,...e)}info(n,...e){this.logger.info(n,...e)}warn(n,...e){this.logger.warn(n,...e)}error(n,...e){this.logger.error(n,...e)}flush(){this.logger.flush()}};async function A9(i,n,e,t,r){try{let o=await import("@vscode/spdlog");o.setFlushOn(0);let s=await o.createAsyncRotatingLogger(i,n,e,t);return r?s.clearFormatters():s.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v"),s}catch(o){console.error(o)}return null}function YE(i,n,e){switch(n){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 ${n}`)}}function QE(i,n){switch(n){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 ${n}`)}}var ah=class extends Vo{constructor(e,t,r,o,s){super();this.buffer=[];this.setLevel(s),this._loggerCreationPromise=this._createSpdLogLogger(e,t,r,o),this._register(this.onDidChangeLogLevel(a=>{this._logger&&QE(this._logger,a)}))}async _createSpdLogLogger(e,t,r,o){let s=r?6:1,a=30/s*Pp.MB,l=await A9(e,t,a,s,o);if(l){this._logger=l,QE(this._logger,this.getLevel());for(let{level:d,message:c}of this.buffer)YE(this._logger,d,c);this.buffer=[]}}log(e,t){this._logger?YE(this._logger,e,t):this.getLevel()<=e&&this.buffer.push({level:e,message:t})}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 lh=class extends zd{doCreateLogger(n,e,t){return new ah(H(),n.fsPath,!t?.donotRotate,!!t?.donotUseFormatters,e)}};var dh=class{constructor(n,e){this.loggerService=n;this.getUriTransformer=e}listen(n,e){let t=this.getUriTransformer(n);switch(e){case"onDidChangeLoggers":return ee.map(this.loggerService.onDidChangeLoggers,r=>({added:[...r.added].map(o=>this.transformLogger(o,t)),removed:[...r.removed].map(o=>this.transformLogger(o,t))}));case"onDidChangeVisibility":return ee.map(this.loggerService.onDidChangeVisibility,r=>[t.transformOutgoingURI(r[0]),r[1]]);case"onDidChangeLogLevel":return ee.map(this.loggerService.onDidChangeLogLevel,r=>lv(r)?r:[t.transformOutgoingURI(r[0]),r[1]])}throw new Error(`Event not found: ${e}`)}async call(n,e,t){let r=this.getUriTransformer(n);switch(e){case"setLogLevel":return lv(t[0])?this.loggerService.setLogLevel(t[0]):this.loggerService.setLogLevel(v.revive(r.transformIncoming(t[0][0])),t[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(o=>this.transformLogger(o,r)))}throw new Error(`Call not found: ${e}`)}transformLogger(n,e){return{...n,resource:e.transformOutgoingURI(n.resource)}}};var XE=new class{transformIncoming(i){return i}transformOutgoing(i){return i}transformOutgoingURI(i){return i}transformOutgoingScheme(i){return i}};function fC(i){let n=[];typeof i=="number"&&n.push("code/timeOrigin",i);function e(o,s){n.push(o,s?.startTime??Date.now())}function t(){let o=[];for(let s=0;s<n.length;s+=2)o.push({name:n[s],startTime:n[s+1]});return o}function r(o){if(typeof o>"u"){let s=n.length>=2&&n[0]==="code/timeOrigin",a=s?n[1]:void 0;n.length=0,s&&n.push("code/timeOrigin",a)}else for(let s=n.length-2;s>=0;s-=2)n[s]===o&&n.splice(s,2)}return{mark:e,getMarks:t,clearMarks:r}}function E9(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?fC():{mark(i,n){performance.mark(i,n)},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 n=[{name:"code/timeOrigin",startTime:Math.round(i)}];for(let e of performance.getEntriesByType("mark"))n.push({name:e.name,startTime:Math.round(i+e.startTime)});return n}};if(typeof process=="object"){let i=performance?.timeOrigin;return fC(i)}else return console.trace("perf-util loaded in UNKNOWN environment"),fC()}function k9(i){return i.MonacoPerformanceMarks||(i.MonacoPerformanceMarks=E9()),i.MonacoPerformanceMarks}var gC=k9(globalThis),ZE=gC.mark,OMe=gC.clearMarks,LMe=gC.getMarks;async function ch(i,n,e,t,r,o){let s;try{await D9(i,n,e,t,r,o)}catch(a){s=a}finally{s&&r.errorTransformer&&(s=r.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function D9(i,n,e,t,r,o){mC(o);let s=await i.open(n,{create:!1});try{mC(o);let a=0,l=0,d=r&&typeof r.length=="number"?r.length:void 0,c=U.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(t(c)),c=U.alloc(Math.min(r.bufferSize,typeof d=="number"?d:r.bufferSize)),p=0);while(l>0&&(typeof d!="number"||d>0)&&mC(o)&&M9(a,r));if(p>0){let m=p;typeof d=="number"&&(m=Math.min(p,d)),e.write(t(c.slice(0,m)))}}catch(a){throw ri(a)}finally{await i.close(s)}}function mC(i){if(i.isCancellationRequested)throw hu();return!0}function M9(i,n){if(typeof n?.limits?.size=="number"&&i>n.limits.size)throw De(f(2644,null),"EntryTooLarge");return!0}var yo=class extends T{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new P);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new P);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new P);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new P);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new P);this._onDidUncorrelatedFilesChange=this._register(new P);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new P);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new As)}registerProvider(e,t){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);ZE(`code/registerFilesystem/${e}`);let r=new G;return this.provider.set(e,t),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:t}),r.add(t.onDidChangeFile(o=>{let s=new xp(o,!this.isPathCaseSensitive(t));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof t.onDidWatchError=="function"&&r.add(t.onDidWatchError(o=>this._onDidWatchError.fire(new Error(o)))),r.add(t.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:t,scheme:e}))),M(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:t}),this.provider.delete(e),jt(r)})}getProvider(e){return this.provider.get(e)}async activateProvider(e){let t=[];this._onWillActivateFileSystemProvider.fire({scheme:e,join(r){t.push(r)}}),!this.provider.has(e)&&await Xn.settled(t)}async canHandleResource(e){return await this.activateProvider(e.scheme),this.hasProvider(e)}hasProvider(e){return this.provider.has(e.scheme)}hasCapability(e,t){let r=this.provider.get(e.scheme);return!!(r&&r.capabilities&t)}listCapabilities(){return ys.map(this.provider,([e,t])=>({scheme:e,capabilities:t.capabilities}))}async withProvider(e){if(!VI(e))throw new lt(f(2633,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let t=this.provider.get(e.scheme);if(!t){let r=new ur;throw r.message=f(2635,null,e.toString()),r}return t}async withReadProvider(e){let t=await this.withProvider(e);if(ni(t)||Rn(t)||Ap(t))return t;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 t=await this.withProvider(e);if(ni(t)||Rn(t))return t;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,t){try{return await this.doResolveFile(e,t)}catch(r){throw fn(r)==="EntryNotFound"?new lt(f(2630,null,this.resourceForError(e)),1):ri(r)}}async doResolveFile(e,t){let r=await this.withProvider(e),o=this.isPathCaseSensitive(r),s=t?.resolveTo,a=t?.resolveSingleChildDescendants,l=t?.resolveMetadata,d=await r.stat(e),c;return this.toFileStat(r,e,d,void 0,!!l,(u,p)=>(c||(c=Sr.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,t,r,o,s,a){let{providerExtUri:l}=this.getExtUri(e),d={resource:t,name:l.basename(t),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:ev({mtime:r.mtime,size:r.size}),children:void 0};if(d.isDirectory&&a(d,o)){try{let c=await e.readdir(t),u=await Xn.settled(c.map(async([p,m])=>{try{let h=l.joinPath(t,p),y=s?await e.stat(h):{type:m};return await this.toFileStat(e,h,y,c.length,s,a)}catch(h){return this.logService.trace(h),null}}));d.children=Ci(u)}catch(c){this.logService.trace(c),d.children=[]}return d}return d}async resolveAll(e){return Xn.settled(e.map(async t=>{try{return{stat:await this.doResolveFile(t.resource,t.options),success:!0}}catch(r){return this.logService.trace(r),{stat:void 0,success:!1}}}))}async stat(e){let t=await this.withProvider(e),r=await t.stat(e);return this.toFileStat(t,e,r,void 0,!0,()=>!1)}async realpath(e){let t=await this.withProvider(e);if(FT(t)){let r=await t.realpath(e);return e.with({path:r})}}async exists(e){let t=await this.withProvider(e);try{return!!await t.stat(e)}catch{return!1}}async canCreateFile(e,t){try{await this.doValidateCreateFile(e,t)}catch(r){return r}return!0}async doValidateCreateFile(e,t){if(!t?.overwrite&&await this.exists(e))throw new lt(f(2626,null,this.resourceForError(e)),3,t)}async createFile(e,t=U.fromString(""),r){await this.doValidateCreateFile(e,r);let o=await this.writeFile(e,t);return this._onDidRunOperation.fire(new ei(e,0,o)),o}async writeFile(e,t,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(o),a=r;if(Zy(o)&&!a?.atomic){let l=o.enforceAtomicWriteFile?.(e);l&&(a={...r,atomic:l})}try{let{stat:l,buffer:d}=await this.validateWriteFile(o,e,t,a);l||await this.mkdirp(o,s.dirname(e)),d||(d=await this.peekBufferForWriting(o,t)),!ni(o)||Rn(o)&&d instanceof U||Rn(o)&&Zy(o)&&a?.atomic?await this.doWriteUnbuffered(o,e,a,d):await this.doWriteBuffered(o,e,a,d instanceof U?o_(d):d),this._onDidRunOperation.fire(new ei(e,4))}catch(l){throw new lt(f(2625,null,this.resourceForError(e),ri(l).toString()),ii(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,t){let r;if(Rn(e)&&!(t instanceof U))if(td(t)){let o=await e_(t,3);o.ended?r=U.concat(o.buffer):r=o}else r=ZI(t,o=>U.concat(o),3);else r=t;return r}async validateWriteFile(e,t,r,o){let s=!!o?.unlock;if(s&&!(e.capabilities&8192))throw new Error(f(2643,null,this.resourceForError(t)));if(o?.append&&!NT(e))throw new lt(f(2622,null,this.resourceForError(t)),6);if(!!o?.atomic){if(!(e.capabilities&32768))throw new Error(f(2641,null,this.resourceForError(t)));if(!(e.capabilities&2))throw new Error(f(2642,null,this.resourceForError(t)));if(s)throw new Error(f(2640,null,this.resourceForError(t)))}let l;try{l=await e.stat(t)}catch{return Object.create(null)}if((l.type&2)!==0)throw new lt(f(2628,null,this.resourceForError(t)),0,o);this.throwIfFileIsReadonly(t,l);let d;if(typeof o?.mtime=="number"&&typeof o.etag=="string"&&o.etag!==kp&&typeof l.mtime=="number"&&typeof l.size=="number"&&o.mtime<l.mtime&&o.etag!==ev({mtime:o.mtime,size:l.size})){if(d=await this.peekBufferForWriting(e,r),d instanceof U&&d.byteLength===l.size)try{let{value:c}=await this.readFile(t,{limits:{size:l.size}});if(d.equals(c))return{stat:l,buffer:d}}catch{}throw new lt(f(2629,null),3,o)}return{stat:l,buffer:d}}async readFile(e,t,r){let o=await this.withReadProvider(e);return t?.atomic?this.doReadFileAtomic(o,e,t,r):this.doReadFile(o,e,t,r)}async doReadFileAtomic(e,t,r,o){return new Promise((s,a)=>{this.writeQueue.queueFor(t,async()=>{try{let l=await this.doReadFile(e,t,r,o);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,t,r,o){let s=await this.doReadFileStream(e,t,{...r,preferUnbuffered:!0},o);return{...s,value:await Oi(s.value)}}async readFileStream(e,t,r){let o=await this.withReadProvider(e);return this.doReadFileStream(o,e,t,r)}async doReadFileStream(e,t,r,o){let s=new Ze(o),a=r;Ep(e)&&e.enforceAtomicReadFile?.(t)&&(a={...r,atomic:!0});let l=this.validateReadFile(t,a).then(c=>c,c=>{throw s.dispose(!0),c}),d;try{return typeof a?.etag=="string"&&a.etag!==kp&&await l,a?.atomic&&Ep(e)||!(ni(e)||Ap(e))||Rn(e)&&a?.preferUnbuffered?d=this.readFileUnbuffered(e,t,a):Ap(e)?d=this.readFileStreamed(e,t,s.token,a):d=this.readFileBuffered(e,t,s.token,a),d.on("end",()=>s.dispose()),d.on("error",()=>s.dispose()),{...await l,value:d}}catch(c){throw d&&await ju(d),this.restoreReadError(c,t,a)}}restoreReadError(e,t,r){let o=f(2623,null,this.resourceForError(t),ri(e).toString());return e instanceof Qs?new Qs(o,e.stat,r):e instanceof Ys?new Ys(o,e.fileOperationResult,e.size,e.options):new lt(o,ii(e),r)}readFileStreamed(e,t,r,o=Object.create(null)){let s=e.readFileStream(t,o,r);return Gu(s,{data:a=>a instanceof U?a:U.wrap(a),error:a=>this.restoreReadError(a,t,o)},a=>U.concat(a))}readFileBuffered(e,t,r,o=Object.create(null)){let s=l_();return ch(e,t,s,a=>a,{...o,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,t,o)},r),s}readFileUnbuffered(e,t,r){let o=Jr(s=>U.concat(s));return(async()=>{try{let s;r?.atomic&&Ep(e)?s=await e.readFile(t,{atomic:!0}):s=await e.readFile(t),typeof r?.position=="number"&&(s=s.slice(r.position)),typeof r?.length=="number"&&(s=s.slice(0,r.length)),this.validateReadFileLimits(t,s.byteLength,r),o.end(U.wrap(s))}catch(s){o.error(s),o.end()}})(),o}async validateReadFile(e,t){let r=await this.resolve(e,{resolveMetadata:!0});if(r.isDirectory)throw new lt(f(2627,null,this.resourceForError(e)),0,t);if(typeof t?.etag=="string"&&t.etag!==kp&&t.etag===r.etag)throw new Qs(f(2631,null),r,t);return this.validateReadFileLimits(e,r.size,t),r}validateReadFileLimits(e,t,r){if(typeof r?.limits?.size=="number"&&t>r.limits.size)throw new Ys(f(2632,null,this.resourceForError(e)),7,t,r)}async canMove(e,t,r){return this.doCanMoveCopy(e,t,"move",r)}async canCopy(e,t,r){return this.doCanMoveCopy(e,t,"copy",r)}async doCanMoveCopy(e,t,r,o){if(e.toString()!==t.toString())try{let s=r==="move"?this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e):await this.withReadProvider(e),a=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t);await this.doValidateMoveCopy(s,e,a,t,r,o)}catch(s){return s}return!0}async move(e,t,r){let o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(o,e,s,t,"move",!!r),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ei(e,a==="move"?2:3,l)),l}async copy(e,t,r){let o=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(o,e,s,t,"copy",!!r),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ei(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,t,r,o,s,a){if(t.toString()===o.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:d}=await this.doValidateMoveCopy(e,t,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&&Xy(e))await e.copy(t,o,{overwrite:a});else{let c=await this.resolve(t);c.isDirectory?await this.doCopyFolder(e,c,r,o):await this.doCopyFile(e,t,r,o)}return s}else return e===r?(await e.rename(t,o,{overwrite:a}),s):(await this.doMoveCopy(e,t,r,o,"copy",a),await this.del(t,{recursive:!0}),"copy")}async doCopyFile(e,t,r,o){if(ni(e)&&ni(r))return this.doPipeBuffered(e,t,r,o);if(ni(e)&&Rn(r))return this.doPipeBufferedToUnbuffered(e,t,r,o);if(Rn(e)&&ni(r))return this.doPipeUnbufferedToBuffered(e,t,r,o);if(Rn(e)&&Rn(r))return this.doPipeUnbuffered(e,t,r,o)}async doCopyFolder(e,t,r,o){await r.mkdir(o),Array.isArray(t.children)&&await Xn.settled(t.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,t,r,o,s,a){let l=!1;if(e===r){let{providerExtUri:c,isPathCaseSensitive:u}=this.getExtUri(e);if(u||(l=c.isEqual(t,o)),l&&s==="copy")throw new Error(f(2636,null,this.resourceForError(t),this.resourceForError(o)));if(!l&&c.isEqualOrParent(o,t))throw new Error(f(2637,null,this.resourceForError(t),this.resourceForError(o)))}let d=await this.exists(o);if(d&&!l){if(!a)throw new lt(f(2638,null,this.resourceForError(t),this.resourceForError(o)),4);if(e===r){let{providerExtUri:c}=this.getExtUri(e);if(c.isEqualOrParent(t,o))throw new Error(f(2639,null,this.resourceForError(t),this.resourceForError(o)))}}return{exists:d,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let t=this.isPathCaseSensitive(e);return{providerExtUri:t?ge:cy,isPathCaseSensitive:t}}isPathCaseSensitive(e){return!!(e.capabilities&1024)}async createFolder(e){let t=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e);await this.mkdirp(t,e);let r=await this.resolve(e,{resolveMetadata:!0});return this._onDidRunOperation.fire(new ei(e,0,r)),r}async mkdirp(e,t){let r=[],{providerExtUri:o}=this.getExtUri(e);for(;!o.isEqual(t,o.dirname(t));)try{if(((await e.stat(t)).type&2)===0)throw new Error(f(2634,null,this.resourceForError(t)));break}catch(s){if(fn(s)!=="EntryNotFound")throw s;r.push(o.basename(t)),t=o.dirname(t)}for(let s=r.length-1;s>=0;s--){t=o.joinPath(t,r[s]);try{await e.mkdir(t)}catch(a){if(fn(a)!=="EntryExists")throw a}}}async canDelete(e,t){try{await this.doValidateDelete(e,t)}catch(r){return r}return!0}async doValidateDelete(e,t){let r=this.throwIfFileSystemIsReadonly(await this.withProvider(e),e),o=!!t?.useTrash;if(o&&!(r.capabilities&4096))throw new Error(f(2621,null,this.resourceForError(e)));let s=t?.atomic;if(s&&!(r.capabilities&65536))throw new Error(f(2617,null,this.resourceForError(e)));if(o&&s)throw new Error(f(2620,null,this.resourceForError(e)));let a;try{a=await r.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new lt(f(2619,null,this.resourceForError(e)),1);if(!!!t?.recursive){let d=await this.resolve(e);if(d.isDirectory&&Array.isArray(d.children)&&d.children.length>0)throw new Error(f(2618,null,this.resourceForError(e)))}return r}async del(e,t){let r=await this.doValidateDelete(e,t),o=t;if(HT(r)&&!o?.atomic){let d=r.enforceAtomicDelete?.(e);d&&(o={...t,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 ei(e,1))}async cloneFile(e,t){let r=await this.withProvider(e),o=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t);if(!(r===o&&this.getExtUri(r).providerExtUri.isEqual(e,t)))return r===o&&UT(r)?r.cloneFile(e,t):(await this.mkdirp(o,this.getExtUri(o).providerExtUri.dirname(t)),r===o&&Xy(r)?this.writeQueue.queueFor(e,()=>r.copy(e,t,{overwrite:!0}),this.getExtUri(r).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(r,e,o,t),this.getExtUri(r).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,t){return this.watch(e,{...t,correlationId:yo.WATCHER_CORRELATION_IDS++})}watch(e,t={recursive:!1,excludes:[]}){let r=new G,o=!1,s=()=>{o=!0};r.add(M(()=>s())),(async()=>{try{let l=await this.doWatch(e,t);o?jt(l):s=()=>jt(l)}catch(l){this.logService.error(l)}})();let a=t.correlationId;if(typeof a=="number"){let l=r.add(new P);return r.add(this.internalOnDidFilesChange.event(c=>{c.correlates(a)&&l.fire(c)})),{onDidChange:l.event,dispose:()=>r.dispose()}}return r}async doWatch(e,t){let r=await this.withProvider(e),o=br([this.getExtUri(r).providerExtUri.getComparisonKey(e),t]),s=this.activeWatchers.get(o);return s||(s={count:0,disposable:r.watch(e,t)},this.activeWatchers.set(o,s)),s.count+=1,M(()=>{s&&(s.count--,s.count===0&&(jt(s.disposable),this.activeWatchers.delete(o)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)jt(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,t,r,o){return this.writeQueue.queueFor(t,async()=>{let s=await e.open(t,{create:!0,unlock:r?.unlock??!1,append:r?.append??!1});try{td(o)||Vu(o)?await this.doWriteStreamBufferedQueued(e,s,o):await this.doWriteReadableBufferedQueued(e,s,o)}catch(a){throw ri(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,t,r){let o=0,s;if(Vu(r)){if(r.buffer.length>0){let a=U.concat(r.buffer);await this.doWriteBuffer(e,t,a,a.byteLength,o,0),o+=a.byteLength}if(r.ended)return;s=r.stream}else s=r;return new Promise((a,l)=>{Ku(s,{onData:async d=>{s.pause();try{await this.doWriteBuffer(e,t,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,t,r){let o=0,s;for(;(s=r.read())!==null;)await this.doWriteBuffer(e,t,s,s.byteLength,o,0),o+=s.byteLength}async doWriteBuffer(e,t,r,o,s,a){let l=0;for(;l<o;){let d=await e.write(t,s+l,r.buffer,a+l,o-l);l+=d}}async doWriteUnbuffered(e,t,r,o){return this.writeQueue.queueFor(t,()=>this.doWriteUnbufferedQueued(e,t,r,o),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,t,r,o){let s;o instanceof U?s=o:td(o)?s=await Oi(o):Vu(o)?s=await s_(o):s=i_(o),await e.writeFile(t,s.buffer,{create:!0,overwrite:!0,unlock:r?.unlock??!1,atomic:r?.atomic??!1,append:r?.append??!1})}async doPipeBuffered(e,t,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeBufferedQueued(e,t,r,o),this.getExtUri(r).providerExtUri)}async doPipeBufferedQueued(e,t,r,o){let s,a;try{s=await e.open(t,{create:!1}),a=await r.open(o,{create:!0,unlock:!1});let l=U.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 ri(l)}finally{await Xn.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?r.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,t,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedQueued(e,t,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedQueued(e,t,r,o){return r.writeFile(o,await e.readFile(t),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,t,r,o){return this.writeQueue.queueFor(o,()=>this.doPipeUnbufferedToBufferedQueued(e,t,r,o),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,t,r,o){let s=await r.open(o,{create:!0,unlock:!1});try{let a=await e.readFile(t);await this.doWriteBuffer(r,s,U.wrap(a),a.byteLength,0,0)}catch(a){throw ri(a)}finally{await r.close(s)}}async doPipeBufferedToUnbuffered(e,t,r,o){let s=await Oi(this.readFileBuffered(e,t,Ae.None));await this.doWriteUnbuffered(r,o,void 0,s)}throwIfFileSystemIsReadonly(e,t){if(e.capabilities&2048)throw new lt(f(2624,null,this.resourceForError(t)),6);return e}throwIfFileIsReadonly(e,t){if((t.permissions??0)&1)throw new lt(f(2624,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===ie.file?e.fsPath:e.toString(!0)}};yo=w([C(0,D)],yo);import{constants as SC,promises as fs}from"fs";function gh(i){return typeof i.correlationId=="number"}function e0(i){return i.recursive===!0}var uh=class i extends T{constructor(e,t,r,o){super();this.onFileChanges=e;this.onLogMessage=t;this.verboseLogging=r;this.options=o;this.watcherDisposables=this._register(new At);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new G;this.watcherDisposables.value=e,this.watcher=this.createWatcher(e),this.watcher.setVerboseLogging(this.verboseLogging),e.add(this.watcher.onDidChangeFile(t=>this.onFileChanges(t))),e.add(this.watcher.onDidLogMessage(t=>this.onLogMessage(t))),e.add(this.watcher.onDidError(t=>this.onError(t.error,t.request)))}onError(e,t){this.canRestart(e,t)?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,t){return!(!this.options.restartOnError||t||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()}},ph=class extends uh{constructor(n,e,t){super(n,e,t,{type:"node.js",restartOnError:!1})}},fh=class extends uh{constructor(n,e,t){super(n,e,t,{type:"universal",restartOnError:!0})}};function yC(i){return i.map(n=>({type:n.type,resource:v.revive(n.resource),cId:n.cId}))}function t0(i){let n=new hC;for(let e of i)n.processEvent(e);return n.coalesce()}function O9(i,n){return typeof n=="string"&&!n.startsWith(Pa)&&!Ft(n)?{base:i,pattern:n}:n}function vC(i,n,e){let t=[];for(let r of n)t.push(Qi(O9(i,r),{ignoreCase:e}));return t}var hC=class{constructor(){this.coalesced=new Set;this.mapPathToChange=new Map}toKey(n){return Oe?n.resource.fsPath:n.resource.fsPath.toLowerCase()}processEvent(n){let e=this.mapPathToChange.get(this.toKey(n)),t=!1;if(e){let r=e.type,o=n.type;e.resource.fsPath!==n.resource.fsPath&&(n.type===2||n.type===1)?t=!0:r===1&&o===2?(this.mapPathToChange.delete(this.toKey(n)),this.coalesced.delete(e)):r===2&&o===1?e.type=0:r===1&&o===0||(e.type=o)}else t=!0;t&&(this.coalesced.add(n),this.mapPathToChange.set(this.toKey(n),n))}coalesce(){let n=[],e=[];return Array.from(this.coalesced).filter(t=>t.type!==2?(n.push(t),!1):!0).sort((t,r)=>t.resource.fsPath.length-r.resource.fsPath.length).filter(t=>e.some(r=>$T(t.resource.fsPath,r,!Oe))?!1:(e.push(t.resource.fsPath),!0)).concat(n)}};function n0(i,n){if(typeof n=="number")switch(i.type){case 1:return(n&4)===0;case 2:return(n&8)===0;case 0:return(n&2)===0}return!1}function r0(i){if(typeof i=="number"){let n=[];return i&4&&n.push("Added"),i&8&&n.push("Deleted"),i&2&&n.push("Updated"),n.length===0?"<all>":`[${n.join(", ")}]`}return"<none>"}var mh=class extends T{constructor(e,t){super();this.logService=e;this.options=t;this._onDidChangeFile=this._register(new P);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new P);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new Ao(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new Ao(this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)))}watch(e,t){return t.recursive||this.options?.watcher?.forceUniversal?this.watchUniversal(e,t):this.watchNonRecursive(e,t)}getRefreshWatchersDelay(e){return e>200?500:0}watchUniversal(e,t){let r=this.toWatchRequest(e,t),o=Dh(this.universalWatchRequests,r);return this.refreshUniversalWatchers(),M(()=>{o(),this.refreshUniversalWatchers()})}toWatchRequest(e,t){let r={path:this.toWatchPath(e),excludes:t.excludes,includes:t.includes,recursive:t.recursive,filter:t.filter,correlationId:t.correlationId};if(e0(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=>st(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(yC(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,t){let r={path:this.toWatchPath(e),excludes:t.excludes,includes:t.includes,recursive:!1,filter:t.filter,correlationId:t.correlationId},o=Dh(this.nonRecursiveWatchRequests,r);return this.refreshNonRecursiveWatchers(),M(()=>{o(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>st(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(yC(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 cn(e.fsPath)}toWatchPath(e){let t=this.toFilePath(e);return DI(t)}};var hh=class extends fh{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){let e=n.add(new tp(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 n.add(e.onDidProcessExit(({code:t,signal:r})=>this.onError(`terminated by itself with code ${t}, signal: ${r} (ETERM)`))),Ns.toService(c_(e.getChannel("watcher")))}};import{watchFile as L9,unwatchFile as N9}from"fs";var yh=class extends T{constructor(){super();this._onDidChangeFile=this._register(new P);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new P);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new P);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new Re);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new Ao(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new Ee;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 gh(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:br(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new Ee;try{this.correlatedWatchRequests.clear(),this.nonCorrelatedWatchRequests.clear();for(let t of e)this.isCorrelated(t)?this.correlatedWatchRequests.set(t.correlationId,t):this.nonCorrelatedWatchRequests.set(this.computeId(t),t);for(let[t]of this.suspendedWatchRequests)!this.nonCorrelatedWatchRequests.has(t)&&!this.correlatedWatchRequests.has(t)&&(this.suspendedWatchRequests.deleteAndDispose(t),this.suspendedWatchRequestsWithPolling.delete(t));return await this.updateWatchers(!1)}finally{this.joinWatch.complete()}}updateWatchers(e){let t=[];for(let[r,o]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(r)||t.push(o);return this.updateWatchersDelayer.trigger(()=>this.doWatch(t),e?this.getUpdateWatchersDelay():0).catch(r=>st(r))}getUpdateWatchersDelay(){return 800}isSuspended(e){let t=this.computeId(e);return this.suspendedWatchRequestsWithPolling.has(t)?"polling":this.suspendedWatchRequests.has(t)}async suspendWatchRequest(e){if(this.suspendedWatchRequests.has(e.id))return;let t=new G;this.suspendedWatchRequests.set(e.id,t),await this.joinWatch.p,!t.isDisposed&&(this.monitorSuspendedWatchRequest(e,t),this.updateWatchers(!0))}resumeWatchRequest(e){this.suspendedWatchRequests.deleteAndDispose(e.id),this.suspendedWatchRequestsWithPolling.delete(e.id),this.updateWatchers(!1)}monitorSuspendedWatchRequest(e,t){this.doMonitorWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher to monitor ${e.path}`),this.suspendedWatchRequestsWithPolling.delete(e.id)):(this.doMonitorWithNodeJS(e,t),this.suspendedWatchRequestsWithPolling.add(e.id))}doMonitorWithExistingWatcher(e,t){let r=this.recursiveWatcher?.subscribe(e.path,(o,s)=>{t.isDisposed||(o?this.monitorSuspendedWatchRequest(e,t):s?.type===1&&this.onMonitoredPathAdded(e))});return r?(t.add(r),!0):!1}doMonitorWithNodeJS(e,t){let r=!1,o=(s,a)=>{if(t.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{L9(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})`)}t.add(M(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{N9(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 t={resource:v.file(e.path),type:1,cId:e.correlationId};this._onDidChangeFile.fire([t]),this.traceEvent(t,e),this.resumeWatchRequest(e)}isPathNotFound(e){return e.ctimeMs===0&&e.ino===0}async stop(){this.suspendedWatchRequests.clearAndDisposeAll(),this.suspendedWatchRequestsWithPolling.clear()}traceEvent(e,t){if(this.verboseLogging){let r=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(r,t)}}traceWithCorrelation(e,t){this.verboseLogging&&this.trace(`${e}${typeof t.correlationId=="number"?` <${t.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: ${r0(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as U9,promises as F9}from"fs";var vh=class i extends T{constructor(e,t,r,o,s,a){super();this.request=e;this.recursiveWatcher=t;this.onDidFilesChange=r;this.onDidWatchFail=o;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new Es({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new Wu(e=>this.handleFileChanges(e),i.FILE_CHANGES_HANDLER_DELAY));this.cts=new Ze;this.realPath=new qe(async()=>{let e=this.request.path;try{e=await Ne.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=!Oe;this.excludes=vC(this.request.path,this.request.excludes,l),this.includes=this.request.includes?vC(this.request.path,this.request.includes,l):void 0,this.filter=gh(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 F9.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;await Fh(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 t=new G;return this.doWatchWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher for ${this.request.path}`),this._isReusingRecursiveWatcher=!0):(this._isReusingRecursiveWatcher=!1,await this.doWatchWithNodeJS(e,t)),t}doWatchWithExistingWatcher(e,t){if(e)return!1;let r=v.file(this.request.path),o=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{t.isDisposed||(s?await Fh(this.doWatch(e),t):a&&(typeof a.cId=="number"||typeof this.request.correlationId=="number")&&this.onFileChange({resource:r,type:a.type,cId:this.request.correlationId},!0))});return o?(t.add(o),!0):!1}async doWatchWithNodeJS(e,t){let r=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(dt&&Vr(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 Ze(this.cts.token);t.add(M(()=>o.dispose(!0)));let s=new G;t.add(s);try{let a=v.file(this.request.path),l=Te(r),d=U9(r);s.add(M(()=>{d.removeAllListeners(),d.close()})),this.trace(`Started watching: '${r}'`);let c=new Set;if(e)try{for(let p of await Ne.readdir(r))c.add(p)}catch(p){this.error(p)}if(o.token.isCancellationRequested)return;let u=new Map;s.add(M(()=>{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(),dt&&(h=dd(h))),!(!h||p!=="change"&&p!=="rename"))if(e)if(p==="rename"){u.get(h)?.dispose();let y=setTimeout(async()=>{if(u.delete(h),xs(h,l,!Oe)&&!await Ne.exists(r)){this.onWatchedPathDeleted(a);return}if(o.token.isCancellationRequested)return;let S=await this.existsChildStrictCase(j(r,h));if(o.token.isCancellationRequested)return;let b;S?c.has(h)?b=0:(b=1,c.add(h)):(c.delete(h),b=2),this.onFileChange({resource:te(a,h),type:b,cId:this.request.correlationId})},i.FILE_DELETE_HANDLER_DELAY);u.set(h,M(()=>clearTimeout(y)))}else{let y;c.has(h)?y=0:(y=1,c.add(h)),this.onFileChange({resource:te(a,h),type:y,cId:this.request.correlationId})}else if(p==="rename"||!xs(h,l,!Oe)){let y=setTimeout(async()=>{let S=await Ne.exists(r);o.token.isCancellationRequested||(S?(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(M(()=>clearTimeout(y)))}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,t=!1){this.cts.token.isCancellationRequested||(this.verboseLogging&&this.traceWithCorrelation(`${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`),!t&&this.excludes.some(r=>r(e.resource.fsPath))?this.verboseLogging&&this.traceWithCorrelation(` >> ignored (excluded) ${e.resource.fsPath}`):!t&&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 t=t0(e),r=[];for(let s of t){if(n0(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(Oe)return Ne.exists(e);try{let t=Te(e);return(await Ne.readdir(le(e))).some(o=>o===t)}catch(t){return this.trace(t),!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 Sh=class extends yh{constructor(e){super();this.recursiveWatcher=e;this.onDidError=ee.None;this._watchers=new Map;this.worker=this._register(new At)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let t=[],r=new Set(Array.from(this.watchers));for(let o of e){let s=this._watchers.get(this.requestToWatcherKey(o));s&&uS(s.request.excludes,o.excludes)&&uS(s.request.includes,o.includes)?r.delete(s):t.push(o)}t.length&&this.trace(`Request to start watching: ${t.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(t)}createWatchWorker(){return this.worker.value=new Es({maxWorkChunkSize:100,throttleDelay:100,maxBufferedWork:Number.MAX_VALUE},e=>{for(let t of e)this.startWatching(t)}),this.worker.value}requestToWatcherKey(e){return typeof e.correlationId=="number"?e.correlationId:this.pathToWatcherKey(e.path)}pathToWatcherKey(e){return Oe?e:e.toLowerCase()}startWatching(e){let t=new vh(e,this.recursiveWatcher,o=>this._onDidChangeFile.fire(o),()=>this._onDidWatchFail.fire(e),o=>this._onDidLogMessage.fire(o),this.verboseLogging),r={request:e,instance:t};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 t=new Map;for(let r of e){let o=t.get(r.correlationId);o||(o=new Map,t.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(t.values()).flatMap(r=>Array.from(r.values()))}async setVerboseLogging(e){super.setVerboseLogging(e);for(let t of this.watchers)t.instance.setVerboseLogging(e)}trace(e,t){this.verboseLogging&&this._onDidLogMessage.fire({type:"trace",message:this.toMessage(e,t)})}warn(e){this._onDidLogMessage.fire({type:"warn",message:this.toMessage(e)})}toMessage(e,t){return t?`[File Watcher (node.js)] ${e} (${this.requestToString(t.request)})`:`[File Watcher (node.js)] ${e}`}};var bh=class extends ph{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){return n.add(new Sh(void 0))}};var Ch=class i extends mh{constructor(){super(...arguments);this.onDidChangeCapabilities=ee.None;this.resourceLocks=new We(e=>rt.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,Oe&&(this._capabilities|=1024)),this._capabilities}async stat(e){try{let{stat:t,symbolicLink:r}=await en.stat(this.toFilePath(e)),o;return(t.mode&128)===0&&(o=2),(t.mode&SC.S_IXUSR||t.mode&SC.S_IXGRP||t.mode&SC.S_IXOTH)&&(o=(o??0)|4),{type:this.toType(t,r),ctime:t.birthtime.getTime(),mtime:t.mtime.getTime(),size:t.size,permissions:o}}catch(t){throw this.toFileSystemProviderError(t)}}async statIgnoreError(e){try{return await this.stat(e)}catch{return}}async realpath(e){let t=this.toFilePath(e);return Ne.realpath(t)}async readdir(e){try{let t=await Ne.readdir(this.toFilePath(e),{withFileTypes:!0}),r=[];return await Promise.all(t.map(async o=>{try{let s;o.isSymbolicLink()?s=(await this.stat(te(e,o.name))).type:s=this.toType(o),r.push([o.name,s])}catch(s){this.logService.trace(s)}})),r}catch(t){throw this.toFileSystemProviderError(t)}}toType(e,t){let r;return t?.dangling?r=0:e.isFile()?r=1:e.isDirectory()?r=2:r=0,t&&(r|=64),r}async createResourceLock(e){let t=this.toFilePath(e);this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - request to acquire resource lock (${t})`);let r;for(;r=this.resourceLocks.get(e);)this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - waiting for resource lock to be released (${t})`),await r.wait();let o=new Hu;return this.resourceLocks.set(e,o),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${t})`),M(()=>{this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${t})`),this.resourceLocks.get(e)===o&&(this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock removed from resource-lock map (${t})`),this.resourceLocks.delete(e)),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock barrier open() (${t})`),o.open()})}async readFile(e,t){let r;try{t?.atomic&&(this.traceLock(`[Disk FileSystemProvider]: atomic read operation started (${this.toFilePath(e)})`),r=await this.createResourceLock(e));let o=this.toFilePath(e);return await fs.readFile(o)}catch(o){throw this.toFileSystemProviderError(o)}finally{r?.dispose()}}traceLock(e){i.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,t,r){let o=Jr(s=>U.concat(s.map(a=>U.wrap(a))).buffer);return ch(this,e,o,s=>s.buffer,{...t,bufferSize:256*1024},r),o}async writeFile(e,t,r){return r?.atomic!==!1&&r?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,te(In(e),`${pe(e)}${r.atomic.postfix}`),t,r):this.doWriteFile(e,t,r)}async canWriteFileAtomic(e){try{let t=this.toFilePath(e),{symbolicLink:r}=await en.stat(t);if(r)return!1}catch{}return!0}async doWriteFileAtomic(e,t,r,o){let s=new G;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(t)),await this.doWriteFile(t,r,{...o,create:!0,overwrite:!0},!0);try{await this.rename(t,e,{overwrite:!0})}catch(a){try{await this.delete(t,{recursive:!1,useTrash:!1,atomic:!1})}catch{}throw a}}finally{s.dispose()}}async doWriteFile(e,t,r,o){let s;try{let a=this.toFilePath(e);if(!r.create||!r.overwrite){if(await Ne.exists(a)){if(!r.overwrite)throw De(f(2647,null),"EntryExists")}else if(!r.create)throw De(f(2650,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:r.append,unlock:r.unlock},o),await this.write(s,0,t,0,t.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,t,r){let o=this.toFilePath(e),s;ti(t)&&!r&&(s=await this.createResourceLock(e));let a;try{if(ti(t)&&t.unlock)try{let{stat:l}=await en.stat(o);l.mode&128||await fs.chmod(o,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(Q&&ti(t)&&!t.append)try{a=await Ne.open(o,"r+"),await Ne.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await Ne.close(a)}catch(d){this.logService.trace(d)}a=void 0}}typeof a!="number"&&(a=await Ne.open(o,ti(t)?t.append?"a":"w":"r"))}catch(l){throw s?.dispose(),ti(t)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),ti(t)&&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 t=this.mapHandleToLock.get(e);try{if(this.mapHandleToPos.delete(e),this.writeHandles.delete(e)&&i.canFlush)try{await Ne.fdatasync(e)}catch(r){i.configureFlushOnWrite(!1),this.logService.error(r)}return await Ne.close(e)}catch(r){throw this.toFileSystemProviderError(r)}finally{t&&(this.mapHandleToLock.get(e)===t&&(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}`),t.dispose())}}async read(e,t,r,o,s){let a=this.normalizePos(e,t),l=null;try{l=(await Ne.read(e,r,o,s,a)).bytesRead}catch(d){throw this.toFileSystemProviderError(d)}finally{this.updatePos(e,a,l)}return l}normalizePos(e,t){return t===this.mapHandleToPos.get(e)?null:t}updatePos(e,t,r){let o=this.mapHandleToPos.get(e);typeof o=="number"&&(typeof t=="number"||(typeof r=="number"?this.mapHandleToPos.set(e,o+r):this.mapHandleToPos.delete(e)))}async write(e,t,r,o,s){return QI(()=>this.doWrite(e,t,r,o,s),100,3)}async doWrite(e,t,r,o,s){let a=this.normalizePos(e,t),l=null;try{l=(await Ne.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 fs.mkdir(this.toFilePath(e))}catch(t){throw this.toFileSystemProviderError(t)}}async delete(e,t){try{let r=this.toFilePath(e);if(t.recursive){let o;t?.atomic!==!1&&t.atomic.postfix&&(o=j(le(r),`${Te(r)}${t.atomic.postfix}`)),await Ne.rm(r,1,o)}else try{await fs.unlink(r)}catch(o){if(o.code==="EPERM"||o.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await en.stat(r);s=a.isDirectory()&&!l}catch{}if(s)await fs.rmdir(r);else throw o}else throw o}}catch(r){throw this.toFileSystemProviderError(r)}}async rename(e,t,r){let o=this.toFilePath(e),s=this.toFilePath(t);if(o!==s)try{await this.validateMoveCopy(e,t,"move",r.overwrite),await Ne.rename(o,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2651,null,Te(o),Te(le(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,t,r){let o=this.toFilePath(e),s=this.toFilePath(t);if(o!==s)try{await this.validateMoveCopy(e,t,"copy",r.overwrite),await Ne.copy(o,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2645,null,Te(o),Te(le(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,t,r,o){let s=this.toFilePath(e),a=this.toFilePath(t),l=!1;if(this.capabilities&1024||(l=xs(s,a,!0)),l){if(r==="copy")throw De(f(2646,null),"EntryExists");if(r==="move")return}let c=await this.statIgnoreError(e);if(!c)throw De(f(2649,null),"EntryNotFound");let u=await this.statIgnoreError(t);if(u){if(!o)throw De(f(2648,null),"EntryExists");(c.type&1)!==0&&(u.type&1)!==0||await this.delete(t,{recursive:!0,useTrash:!1,atomic:!1})}}async cloneFile(e,t){return this.doCloneFile(e,t,!1)}async doCloneFile(e,t,r){let o=this.toFilePath(e),s=this.toFilePath(t),a=!!(this.capabilities&1024);if(xs(o,s,!a))return;let l=new G;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(t)),r&&await fs.mkdir(le(s),{recursive:!0}),await fs.copyFile(o,s)}catch(d){if(d.code==="ENOENT"&&!r)return this.doCloneFile(e,t,!0);throw this.toFileSystemProviderError(d)}finally{l.dispose()}}createUniversalWatcher(e,t,r){return new hh(o=>e(o),o=>t(o),r)}createNonRecursiveWatcher(e,t,r){return new bh(o=>e(o),o=>t(o),r)}toFileSystemProviderError(e){if(e instanceof Js)return e;let t=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":t=`${e.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`,r="Unknown";break;default:r="Unknown"}return De(t,r)}async toFileSystemProviderWriteError(e,t){let r=this.toFileSystemProviderError(t);if(e&&r.code==="NoPermissions")try{let{stat:o}=await en.stat(this.toFilePath(e));o.mode&128||(r=De(t,"EntryWriteLocked"))}catch(o){this.logService.trace(o)}return r}};import{parse as a0}from"url";import{spawn as H9}from"child_process";import mNe from"assert";function bC(i){return i.VSCODE_CLI==="1"}var CC;async function i0(i,n,e,t){return e["force-disable-user-env"]?(n.trace("resolveShellEnv(): skipped (--force-disable-user-env)"),{}):Q?(n.trace("resolveShellEnv(): skipped (Windows)"),{}):bC(t)&&!e["force-user-env"]?(n.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)"),{}):(bC(t)?n.trace("resolveShellEnv(): running (--force-user-env)"):n.trace("resolveShellEnv(): running (macOS/Linux)"),CC||(CC=Xn.withAsyncBody(async(r,o)=>{let s=new Ze,a=1e4,l=i.getValue("application.shellEnvironmentResolutionTimeout");typeof l=="number"&&(a=tP(l,1,120)*1e3);let d=setTimeout(()=>{s.dispose(!0),o(new Error(f(2778,null)))},a);try{r(await $9(n,s.token))}catch(c){!Kn(c)&&!s.token.isCancellationRequested?o(new Error(f(2776,null,ke(c)))):r({})}finally{clearTimeout(d),s.dispose()}})),CC)}async function $9(i,n){let e=process.env.ELECTRON_RUN_AS_NODE;i.trace("getUnixShellEnvironment#runAsNode",e);let t=process.env.ELECTRON_NO_ATTACH_CONSOLE;i.trace("getUnixShellEnvironment#noAttach",t);let r=H().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 Kp(Et,s);return i.trace("getUnixShellEnvironment#shell",a),new Promise((l,d)=>{if(n.isCancellationRequested)return d(new Y);let c=Te(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=H9(a,[...p,u],{detached:!0,stdio:["ignore","pipe","pipe"],env:s});n.onCancellationRequested(()=>(h.kill(),d(new Y))),h.on("error",b=>{i.error("getUnixShellEnvironment#errorChildProcess",ke(b)),d(b)});let y=[];h.stdout.on("data",b=>y.push(b));let S=[];h.stderr.on("data",b=>S.push(b)),h.on("close",(b,I)=>{let _=Buffer.concat(y).toString("utf8");i.trace("getUnixShellEnvironment#raw",_);let R=Buffer.concat(S).toString("utf8");if(R.trim()&&i.trace("getUnixShellEnvironment#stderr",R),b||I)return d(new Error(f(2777,null,b,I)));let A=o.exec(_),X=A?A[1]:"{}";try{let E=JSON.parse(X);e?E.ELECTRON_RUN_AS_NODE=e:delete E.ELECTRON_RUN_AS_NODE,t?E.ELECTRON_NO_ATTACH_CONSOLE=t: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",ke(E)),d(E)}})})}import{parse as o0}from"url";function W9(i,n){return i.protocol==="http:"?n.HTTP_PROXY||n.http_proxy||null:i.protocol==="https:"&&(n.HTTPS_PROXY||n.https_proxy||n.HTTP_PROXY||n.http_proxy)||null}async function s0(i,n,e={}){let t=o0(i),r=e.proxyUrl||W9(t,n);if(!r)return null;let o=o0(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:bu(e.strictSSL)?e.strictSSL:!0,keepAlive:!0};if(t.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 q9}from"zlib";var B9=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),z9=/^(GET|HEAD|OPTIONS)$/i;function V9(i){if(i instanceof Error){let n=i.code;return!!n&&B9.has(n)}return!1}var Hl=class extends Ff{constructor(e,t,r,o){super(o);this.machine=e;this.configurationService=t;this.environmentService=r;this.configure(),this._register(t.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,t){let{proxyUrl:r,strictSSL:o}=this,s;try{s=await i0(this.configurationService,this.logService,this.environmentService.args,process.env)}catch(d){this.shellEnvErrorLogged||(this.shellEnvErrorLogged=!0,this.logService.error("resolving shell environment failed",Ur(d)))}let a={...process.env,...s},l=e.agent?e.agent:await s0(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,()=>l0(e,t))}async resolveProxy(e){}async lookupAuthorization(e){}async lookupKerberosAuthorization(e){try{let t=this.getConfigValue("http.proxyKerberosServicePrincipal");return"Negotiate "+await j9(e,t,this.logService,"RequestService#lookupKerberosAuthorization")}catch(t){this.logService.debug("RequestService#lookupKerberosAuthorization Kerberos authentication failed",t);return}}async loadCertificates(){return(await import("@vscode/proxy-agent")).loadSystemCertificates({loadSystemCertificatesFromNode:()=>this.getConfigValue("http.systemCertificatesNode",Ta),log:this.logService})}getConfigValue(e,t){if(this.machine==="remote")return this.configurationService.getValue(e);let r=this.configurationService.inspect(e);return r.userLocalValue??r.defaultValue??t}};Hl=w([C(1,Hi),C(2,Rt),C(3,D)],Hl);async function j9(i,n,e,t){let r=await import("kerberos"),o=r.default||r,s=new URL(i),a=n||(process.platform==="win32"?`HTTP/${s.hostname}`:`HTTP@${s.hostname}`);return e.debug(`${t} Kerberos authentication lookup`,`proxyURL:${s}`,`spn:${a}`),(await o.initializeClient(a)).step("")}async function K9(i){return(a0(i.url).protocol==="https:"?await import("https"):await import("http")).request}async function l0(i,n){let t,r=z9.test(i.type||"GET");for(let o=1;o<=3;o++)try{return await G9(i,n)}catch(s){if(t=s,s instanceof Y||!r||!V9(s)||o===3)throw s;await Tn(100*o,n)}throw t}async function G9(i,n){return Xn.withAsyncBody(async(e,t)=>{let r=a0(i.url),o=i.getRawRequest?i.getRawRequest(i):await K9(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:bu(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=So(i.followRedirects)?i.followRedirects:3;if(d.statusCode&&d.statusCode>=300&&d.statusCode<400&&c>0&&d.headers.location)l0({...i,url:d.headers.location,followRedirects:c-1},n).then(e,t);else{let u=d;!i.isChromiumNetwork&&d.headers["content-encoding"]==="gzip"&&(u=d.pipe(q9())),e({res:d,stream:a_(u)})}});if(a.on("error",t),i.timeout)if(i.isChromiumNetwork){let d=setTimeout(()=>{a.abort(),t(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=n.onCancellationRequested(()=>{l.dispose(),a.abort(),t(new Y)});a.on("response",()=>l.dispose()),a.on("error",()=>l.dispose())})}async function d0(i,n,e,t,r){let o=new Ji;i.set(Lf,o);let s=te(e.userRoamingDataHome,"settings.json"),a=r.add(new Ia(s,n,o,t));await a.initialize(),i.set(Hi,a),i.set(_a,r.add(new Hl("local",a,e,t)))}import*as f0 from"fs";var c0=[{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"},{version:6,sql:`CREATE TABLE IF NOT EXISTS chat_drafts (
			chat_uri TEXT PRIMARY KEY NOT NULL,
			draft    TEXT NOT NULL
		)`},{version:7,sql:`CREATE TABLE IF NOT EXISTS reviewed_files (
			uri   TEXT NOT NULL,
			nonce TEXT NOT NULL,
			PRIMARY KEY (uri, nonce)
		)`},{version:8,sql:`CREATE TABLE IF NOT EXISTS local_turns (
			turn_id        TEXT PRIMARY KEY NOT NULL,
			chat_uri       TEXT NOT NULL,
			anchor_turn_id TEXT,
			seq            INTEGER NOT NULL,
			payload        TEXT NOT NULL
		)`}];function cr(i,n){return new Promise((e,t)=>{i.exec(n,r=>r?t(r):e())})}function ot(i,n,e){return new Promise((t,r)=>{i.run(n,e,function(o){if(o)return r(o);t({changes:this.changes,lastID:this.lastID})})})}function Lr(i,n,e){return new Promise((t,r)=>{i.get(n,e,(o,s)=>{if(o)return r(o);t(s)})})}function Si(i,n,e){return new Promise((t,r)=>{i.all(n,e,(o,s)=>{if(o)return r(o);t(s)})})}function IC(i){return new Promise((n,e)=>{i.close(t=>t?e(t):n())})}function J9(i){return new Promise((n,e)=>{import("@vscode/sqlite3").then(t=>{let r=new t.default.Database(i,o=>{if(o)return e(o);n(r)})},e)})}async function Y9(i,n){await cr(i,"PRAGMA foreign_keys = ON");let t=(await Lr(i,"PRAGMA user_version",[]))?.user_version??0,r=n.filter(o=>o.version>t).sort((o,s)=>o.version-s.version);if(r.length!==0){await cr(i,"BEGIN TRANSACTION");try{for(let o of r)await cr(i,o.sql),await cr(i,`PRAGMA user_version = ${o.version}`);await cr(i,"COMMIT")}catch(o){throw await cr(i,"ROLLBACK"),o}}}var Ih=class i{constructor(n,e=c0){this._path=n;this._migrations=e;this._fileEditSequencer=new at;this._metadataSequencer=new at;this._pendingWrites=new Set}static async open(n,e=c0){let t=new i(n,e);return await t._ensureDb(),t}_ensureDb(){return this._closed?Promise.reject(new Error("SessionDatabase has been disposed")):(this._dbPromise||(this._dbPromise=(async()=>{await f0.promises.mkdir(le(this._path),{recursive:!0});let n=await J9(this._path);try{await Y9(n,this._migrations)}catch(e){throw await IC(n),this._dbPromise=void 0,e}if(this._closed)throw await IC(n),new Error("SessionDatabase has been disposed");return n})()),this._dbPromise)}async getAllTables(){let n=await this._ensureDb();return(await Si(n,"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",[])).map(t=>t.name)}createTurn(n){return this._track(async()=>{let e=await this._ensureDb();await ot(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n])})}deleteTurn(n){return this._track(async()=>{let e=await this._ensureDb();await ot(e,"DELETE FROM turns WHERE id = ?",[n])})}setTurnEventId(n,e){return this._track(async()=>{let t=await this._ensureDb();await ot(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await ot(t,"UPDATE turns SET event_id = ? WHERE id = ? AND event_id IS NULL",[e,n])})}async getTurnEventId(n){let e=await this._ensureDb();return(await Lr(e,"SELECT event_id FROM turns WHERE id = ?",[n]))?.event_id??void 0}async getNextTurnEventId(n){let e=await this._ensureDb();return(await Lr(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`,[n]))?.event_id??void 0}async getFirstTurnEventId(){let n=await this._ensureDb();return(await Lr(n,"SELECT event_id FROM turns ORDER BY rowid LIMIT 1",[]))?.event_id??void 0}setTurnCheckpointRef(n,e){return this._track(async()=>{let t=await this._ensureDb();await ot(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await ot(t,"UPDATE turns SET checkpoint_ref = ? WHERE id = ?",[e,n])})}async getTurnCheckpointRef(n){let e=await this._ensureDb();return(await Lr(e,"SELECT checkpoint_ref FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1",[n]))?.checkpoint_ref??void 0}async getPreviousCheckpointRef(n){let e=await this._ensureDb();return(await Lr(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`,[n]))?.checkpoint_ref??void 0}async getAllCheckpointRefs(){let n=await this._ensureDb();return(await Si(n,"SELECT checkpoint_ref FROM turns WHERE checkpoint_ref IS NOT NULL ORDER BY rowid",[])).map(t=>t.checkpoint_ref)}truncateFromTurn(n){return this._track(async()=>{let e=await this._ensureDb();await ot(e,"DELETE FROM turns WHERE rowid >= (SELECT rowid FROM turns WHERE id = ?)",[n])})}deleteTurnsAfter(n){return this._track(async()=>{let e=await this._ensureDb();await ot(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[n])})}deleteAllTurns(){return this._track(async()=>{let n=await this._ensureDb();await cr(n,"DELETE FROM turns")})}insertLocalTurn(n){return this._track(async()=>{let e=await this._ensureDb();await ot(e,"INSERT OR REPLACE INTO local_turns (turn_id, chat_uri, anchor_turn_id, seq, payload) VALUES (?, ?, ?, ?, ?)",[n.turnId,n.chatUri,n.anchorTurnId??null,n.seq,n.payload])})}async getLocalTurns(){let n=await this._ensureDb();return(await Si(n,"SELECT turn_id, chat_uri, anchor_turn_id, seq, payload FROM local_turns ORDER BY seq",[])).map(t=>({turnId:t.turn_id,chatUri:t.chat_uri,anchorTurnId:t.anchor_turn_id??void 0,seq:t.seq,payload:t.payload}))}deleteLocalTurns(n){return this._track(async()=>{if(n.length===0)return;let e=await this._ensureDb(),t=n.map(()=>"?").join(",");await ot(e,`DELETE FROM local_turns WHERE turn_id IN (${t})`,[...n])})}storeFileEdit(n){return this._track(()=>this._fileEditSequencer.queue(n.filePath,async()=>{let e=await this._ensureDb();await ot(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n.turnId]),await ot(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 (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n.turnId,n.toolCallId,n.filePath,n.kind,n.originalPath??null,n.beforeContent?Buffer.from(n.beforeContent):null,n.afterContent?Buffer.from(n.afterContent):null,n.addedLines??null,n.removedLines??null])}))}async getFileEdits(n){if(n.length===0)return[];let e=await this._ensureDb(),t=n.map(()=>"?").join(",");return(await Si(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 (${t})
				ORDER BY rowid`,n)).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 n=await this._ensureDb();return(await Si(n,`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
				FROM file_edits
				ORDER BY rowid`,[])).map(t=>({turnId:t.turn_id,toolCallId:t.tool_call_id,filePath:t.file_path,kind:t.edit_type??"edit",originalPath:t.original_path??void 0,addedLines:t.added_lines??void 0,removedLines:t.removed_lines??void 0}))}async getFileEditsByTurn(n){let e=await this._ensureDb();return(await Si(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`,[n])).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(n,e){return this._fileEditSequencer.queue(e,async()=>{let t=await this._ensureDb(),r=await Lr(t,`SELECT before_content, after_content
					FROM file_edits
					WHERE tool_call_id = ? AND file_path = ?`,[n,e]);if(r)return{beforeContent:r.before_content?p0(r.before_content):void 0,afterContent:r.after_content?p0(r.after_content):void 0}})}async getMetadata(n){let e=await this._ensureDb();return(await Lr(e,"SELECT value FROM session_metadata WHERE key = ?",[n]))?.value}async getMetadataObject(n){let e=Object.keys(n),t={};if(e.length===0)return t;let r=await this._ensureDb(),o=e.map(()=>"?").join(","),s=await Si(r,`SELECT key, value FROM session_metadata WHERE key IN (${o})`,e);for(let a of e)t[a]=void 0;for(let a of s)t[a.key]=a.value;return t}setMetadata(n,e){return this._track(()=>this._metadataSequencer.queue(n,async()=>{let t=await this._ensureDb();await ot(t,"INSERT OR REPLACE INTO session_metadata (key, value) VALUES (?, ?)",[n,e])}))}setChatDraft(n,e){let t=n.toString();return this._track(async()=>{let r=await this._ensureDb();if(!e){await ot(r,"DELETE FROM chat_drafts WHERE chat_uri = ?",[t]);return}await ot(r,"INSERT OR REPLACE INTO chat_drafts (chat_uri, draft) VALUES (?, ?)",[t,JSON.stringify(e)])})}async getChatDraft(n){let e=await this._ensureDb(),t=await Lr(e,"SELECT draft FROM chat_drafts WHERE chat_uri = ?",[n.toString()]);if(typeof t?.draft=="string")try{return JSON.parse(t.draft)}catch{return}}markFileReviewed(n,e){return this._track(async()=>{let t=await this._ensureDb();await ot(t,"INSERT OR IGNORE INTO reviewed_files (uri, nonce) VALUES (?, ?)",[n.toString(),e])})}unmarkFileReviewed(n,e){return this._track(async()=>{let t=await this._ensureDb();await ot(t,"DELETE FROM reviewed_files WHERE uri = ? AND nonce = ?",[n.toString(),e])})}async getReviewedFiles(){let n=await this._ensureDb();return(await Si(n,"SELECT uri, nonce FROM reviewed_files ORDER BY rowid",[])).map(u0)}async getReviewedFilesForUri(n){let e=await this._ensureDb();return(await Si(e,"SELECT uri, nonce FROM reviewed_files WHERE uri = ? ORDER BY rowid",[n.toString()])).map(u0)}async isFileReviewed(n,e){let t=await this._ensureDb();return!!await Lr(t,"SELECT 1 FROM reviewed_files WHERE uri = ? AND nonce = ? LIMIT 1",[n.toString(),e])}remapTurnIds(n){return this._track(async()=>{let e=await this._ensureDb();await cr(e,"PRAGMA defer_foreign_keys = ON"),await cr(e,"BEGIN TRANSACTION");try{let t=[...n.keys()];if(t.length>0){let r=t.map(()=>"?").join(",");await ot(e,`DELETE FROM turns WHERE id NOT IN (${r})`,t)}for(let[r,o]of n)await ot(e,"UPDATE turns SET id = ? WHERE id = ?",[o,r]),await ot(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[o,r]);if(t.length>0){let r=t.map(()=>"?").join(",");await ot(e,`DELETE FROM local_turns WHERE turn_id NOT IN (${r})`,t)}for(let[r,o]of n)await ot(e,"UPDATE local_turns SET turn_id = ? WHERE turn_id = ?",[o,r]),await ot(e,"UPDATE local_turns SET anchor_turn_id = ? WHERE anchor_turn_id = ?",[o,r]);await cr(e,"COMMIT")}catch(t){throw await cr(e,"ROLLBACK"),t}})}async whenIdle(){for(;this._pendingWrites.size>0;)await Promise.allSettled([...this._pendingWrites])}async vacuumInto(n){let e=await this._ensureDb();await ot(e,"VACUUM INTO ?",[n])}_track(n){let e=n();this._pendingWrites.add(e);let t=()=>{this._pendingWrites.delete(e)};return e.then(t,t),e}async close(){await(this._closed??=this._dbPromise?.then(n=>IC(n)).catch(()=>{})||!0)}dispose(){this.close()}};function u0(i){return{uri:v.parse(i.uri),nonce:i.nonce}}function p0(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 _C=class extends Ss{constructor(e,t){super();this._getDbPath=e;this._logService=t;this.liveDatabases=new Set}createReferencedObject(e){let t=this._getDbPath(e);this._logService.trace(`[SessionDataService] Opening database: ${t}`);let r=new Ih(t);return this.liveDatabases.add(r),r}destroyReferencedObject(e,t){this.liveDatabases.delete(t),t.dispose()}},$l=class{constructor(n,e,t,r){this._fileService=e;this._logService=t;this._onWillDeleteSessionData=new P;this._basePath=v.joinPath(n,"agentSessionData"),this._databases=new _C(r??(o=>v.joinPath(this._basePath,o,ea).fsPath),this._logService)}get onWillDeleteSessionData(){return this._onWillDeleteSessionData.event}getSessionDataDir(n){return v.joinPath(this._basePath,this._sanitizedSessionKey(n))}getSessionDataDirById(n){let e=n.replace(/[^a-zA-Z0-9_.-]/g,"-");return v.joinPath(this._basePath,e)}_sanitizedSessionKey(n){return this._dataKey(n).replace(/[^a-zA-Z0-9_.-]/g,"-")}_dataKey(n){let e=L.id(n);return n.authority?`${n.authority}-${e}`:e}openDatabase(n){return this._databases.acquire(this._sanitizedSessionKey(n))}async tryOpenDatabase(n){let e=this._sanitizedSessionKey(n),t=v.joinPath(this._basePath,e,ea);if(await this._fileService.exists(t))return this._databases.acquire(e)}async deleteSessionData(n){let e=this.getSessionDataDir(n),t=[];try{this._onWillDeleteSessionData.fire({session:n,waitUntil:r=>{t.push(r)}})}catch(r){this._logService.warn(`[SessionDataService] onWillDeleteSessionData listener threw synchronously: ${e.toString()}`,r)}if(t.length>0){let r=await Promise.allSettled(t);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(n){try{if(!await this._fileService.exists(this._basePath))return;let t=await this._fileService.resolve(this._basePath);if(!t.children)return;let r=[];for(let o of t.children){if(!o.isDirectory)continue;let s=o.name;n.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 n=[...this._databases.liveDatabases];if(n.length===0||(await Promise.all(n.map(t=>t.whenIdle())),[...this._databases.liveDatabases].filter(t=>!n.includes(t)).length===0))return}}};$l=w([C(1,xe),C(2,D)],$l);import{execFile as Q9}from"child_process";var _h=class i{static async checkSandboxDependenciesWith(n,e=Oe,t=r=>i._probeBubblewrap(r)){if(!e)return;let[r,o]=await Promise.all([n("bwrap"),n("socat")]),s=r?await t(r):{usable:!1};return{bubblewrapInstalled:!!r,bubblewrapUsable:s.usable,bubblewrapError:s.error,socatInstalled:!!o}}checkSandboxDependencies(){return i.checkSandboxDependenciesWith(Zu)}static _probeBubblewrap(n){return new Promise(e=>{Q9(n,["--unshare-net","--dev-bind","/","/","echo","ok"],{encoding:"utf8",timeout:5e3},(t,r,o)=>{if(!t&&r.trim()==="ok"){e({usable:!0});return}let s=o.trim()||t?.message||`Unexpected output: ${r.trim()}`;e({usable:!1,error:s.slice(0,1e3)})})})}async getWindowsMxcFilesystemPolicy(){if(!Q)return;let{getAvailableToolsPolicy:n,getUserProfilePolicy:e,getTemporaryFilesPolicy:t}=await import("@microsoft/mxc-sdk"),r=n(process.env,{containerType:"processcontainer"}),o=e(),s=t(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(!Q)return;let n=[];for(let s of["SystemRoot","PATH","ComSpec","PATHEXT","PSModulePath"]){let a=Yr(process.env,s);typeof a=="string"&&a&&n.push(`${s}=${a}`)}let e=Yr(process.env,"USERPROFILE");typeof e=="string"&&e&&n.push(`USERPROFILE=${e}`);let t=Yr(process.env,"APPDATA");typeof t=="string"&&t&&n.push(`APPDATA=${t}`);let r=this._getLocalAppData();typeof r=="string"&&r&&n.push(`LOCALAPPDATA=${r}`);let o=await this._getPSHome();return o&&n.push(`PSHOME=${o}`),n}async buildWindowsMxcSandboxPayload(n,e,t,r,o="process"){if(!Q)return;let{buildSandboxPayload:s}=await import("@microsoft/mxc-sdk");return s(n,e,t,r,o)}async _getPSHome(){let n=Yr(process.env,"PSHOME");if(typeof n=="string"&&n)return n;let e=await Zu("pwsh")??await Zu("powershell");return e?he.dirname(e):void 0}_getLocalAppData(){let n=Yr(process.env,"LOCALAPPDATA");return typeof n=="string"&&n?n:void 0}};var Th=class extends wc{_decodeUri(n){return Kx(n)}_encodeUri(n,e){return qa(n,e)}};var g0="local";var pu=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"}},m0=$("agentHostResourceService");var h0="agentHostClientResource";function y0(i){return{resourceList:n=>i.call("resourceList",{uri:n.toString()}),resourceRead:n=>i.call("resourceRead",{uri:n.toString()}),resourceWrite:n=>i.call("resourceWrite",{...n,uri:n.uri.toString()}),resourceCopy:n=>i.call("resourceCopy",{...n,source:n.source.toString(),destination:n.destination.toString()}),resourceDelete:n=>i.call("resourceDelete",{...n,uri:n.uri.toString()}),resourceMove:n=>i.call("resourceMove",{...n,source:n.source.toString(),destination:n.destination.toString()}),resourceResolve:n=>i.call("resourceResolve",{...n,uri:n.uri.toString()}),resourceMkdir:n=>i.call("resourceMkdir",{...n,uri:n.uri.toString()}),resourceRequest:n=>i.call("resourceRequest",{...n,uri:n.uri.toString()})}}var wh=class{constructor(n,e){this._ahpLogger=n;this._resourceService=e}listen(n,e){throw new Error(`No event '${e}' on AgentHostClientResourceChannel`)}async call(n,e,t){let r={jsonrpc:"2.0",method:e,params:t};this._logReverseFrame(r,"s2c");try{let o=await this._call(n,e,t),s={jsonrpc:"2.0",method:e,result:o??null};return this._logReverseFrame(s,"c2s"),o}catch(o){let s=o instanceof pu?{jsonrpc:"2.0",method:e,error:{code:ye.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(n,e){this._ahpLogger?.log(n,e)}async _call(n,e,t){let r=t??{},o=g0;switch(e){case"resourceList":return{entries:(await this._resourceService.list(o,v.parse(r.uri))).entries};case"resourceRead":{let s=await this._resourceService.read(o,v.parse(r.uri));return{data:Zn(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 Y?new pu(void 0):s}}throw new Error(`Unknown command '${e}' on AgentHostClientResourceChannel`)}};wh=w([C(1,m0)],wh);var v0=$("agentHostByokLmHandler");var S0="agentHostClientByokLm";function b0(i){let n=new qe(()=>i.listen("onDidChangeModels"));return{chat:e=>i.call("chat",e),listModels:()=>i.call("listModels"),onDidChangeModels:(e,t,r)=>n.value(e,t,r)}}var Rh=class{constructor(n){this._handler=n}listen(n,e){if(e==="onDidChangeModels")return this._handler.onDidChangeModels??ee.None;throw new Error(`No event '${e}' on AgentHostClientByokLmChannel`)}async call(n,e,t){switch(e){case"chat":return await this._handler.chat(t,Ae.None);case"listModels":return await this._handler.listModels(Ae.None)}throw new Error(`Unknown command '${e}' on AgentHostClientByokLmChannel`)}};Rh=w([C(0,v0)],Rh);var C0="agentHostClientProxy";function I0(i){return{resolveProxy:n=>i.call("resolveProxy",{url:n})}}var xh=class{constructor(n){this._requestService=n}listen(n,e){throw new Error(`No event '${e}' on AgentHostClientProxyChannel`)}async call(n,e,t){if(e==="resolveProxy"){let{url:r}=t;return await this._requestService.resolveProxy(r)}throw new Error(`Unknown command '${e}' on AgentHostClientProxyChannel`)}};xh=w([C(0,_a)],xh);var X9=20,Wl=class{constructor(n,e,t,r=X9){this._fileService=e;this._logService=t;this._sequencer=new at;this._lru=[];this._cacheLoaded=!1;this._basePath=v.joinPath(n,"agentPlugins"),this._cachePath=v.joinPath(this._basePath,"cache.json"),this._maxPlugins=r}get basePath(){return this._basePath}async syncCustomizations(n,e,t){return await this._ensureCacheLoaded(),await Promise.all(e.map(o=>this._sequencer.queue(o.uri,async()=>{try{let s=await this._syncPlugin(n,o),a={...o,load:{kind:"loaded"}};return t?.(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 t?.(l),{customization:l}}})))}async _syncPlugin(n,e){let t=qa(v.parse(e.uri),n),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(t,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(n){return this._sanitize(n)}_keyForNonce(n){return n&&this._sanitize(n)||"default"}_sanitize(n){return n.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,128)}_dirFor(n,e){return v.joinPath(this._basePath,this._keyForUri(n),this._keyForNonce(e))}_pluginRootFor(n){return v.joinPath(this._basePath,this._keyForUri(n))}_findEntry(n,e){let t=e??"";return this._lru.find(r=>r.uri===n&&r.nonce===t)}_removeEntry(n,e){let t=this._findEntry(n,e);t&&this._removeEntryRef(t)}_removeEntryRef(n){let e=this._lru.indexOf(n);e!==-1&&this._lru.splice(e,1)}_touchLru(n,e){let t=this._findEntry(n,e);t&&(this._removeEntryRef(t),this._lru.push(t))}async _tryDeleteDir(n){try{return await this._fileService.del(n,{recursive:!0}),!0}catch(e){return this._logService.warn(`[AgentPluginManager] Failed to remove plugin dir ${n.toString()}`,e),!1}}async _cleanupStaleNonces(){for(let n of new Set(this._lru.map(e=>e.uri)))await this._cleanupStaleNoncesFor(n)}async _cleanupStaleNoncesFor(n){let t=this._lru.filter(r=>r.uri===n).slice(0,-1);for(let r of t)this._logService.info(`[AgentPluginManager] Evicting stale nonce for plugin: ${n}`),await this._tryDeleteDir(this._dirFor(r.uri,r.nonce))&&this._removeEntryRef(r)}async _evictIfNeeded(){let n=0;for(;this._lru.length>this._maxPlugins&&n<this._lru.length;){let e=this._lru[n];this._logService.info(`[AgentPluginManager] Evicting plugin: ${e.uri}`),await this._tryDeleteDir(this._dirFor(e.uri,e.nonce))?(this._lru.splice(n,1),this._lru.some(t=>t.uri===e.uri)||await this._tryDeleteDir(this._pluginRootFor(e.uri))):n++}}async _ensureCacheLoaded(){if(!this._cacheLoaded){this._cacheLoaded=!0;try{if(!await this._fileService.exists(this._cachePath))return;let n=await this._fileService.readFile(this._cachePath),e=JSON.parse(n.value.toString());if(!Array.isArray(e))return;for(let t of e)typeof t.uri=="string"&&typeof t.nonce=="string"&&this._lru.push({uri:t.uri,nonce:t.nonce});this._logService.trace(`[AgentPluginManager] Loaded ${e.length} cache entries from disk`)}catch(n){this._logService.warn("[AgentPluginManager] Failed to load cache from disk",n)}await this._cleanupStaleNonces(),await this._persistCache()}}async _persistCache(){try{let n=this._lru.map(e=>({uri:e.uri,nonce:e.nonce}));await this._fileService.createFolder(this._basePath),await this._fileService.writeFile(this._cachePath,U.fromString(JSON.stringify(n)))}catch(n){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",n)}}};Wl=w([C(1,xe),C(2,D)],Wl);import*as Ph from"child_process";var ql=class{constructor(n,e,t){this._fileService=n;this._environmentService=e;this._logService=t;this._repositoryRoots=new sn(100);this._repositoryRootSequencer=new at}async getCurrentBranch(n){return(await this._runGit(n,["branch","--show-current"]))?.trim()||(await this._runGit(n,["rev-parse","--short","HEAD"]))?.trim()||void 0}async getDefaultBranch(n){let e=(await this._runGit(n,["symbolic-ref","refs/remotes/origin/HEAD"]))?.trim();if(e){if(!e.startsWith("refs/remotes/origin/"))return e;let t=e.substring(20);return await this._runGit(n,["show-ref","--verify","--quiet",`refs/remotes/origin/${t}`])!==void 0?`origin/${t}`:await this._runGit(n,["show-ref","--verify","--quiet",`refs/heads/${t}`])!==void 0?t:void 0}}async getBranches(n,e){let t=["for-each-ref","--format=%(refname:short)","--sort=-committerdate"];t.push("refs/heads");let r=await this._runGit(n,t);if(!r)return[];let o=r.split(/\r?\n/g).map(s=>s.trim()).filter(s=>s.length>0);return Yw(o,e)}async getRepositoryRoot(n){let e=n.toString();return this._repositoryRootSequencer.queue(e,async()=>{let t=this._repositoryRoots.get(e);if(t)return t;try{let r=(await this._runGit(n,["rev-parse","--show-toplevel"]))?.trim();return r&&(t=v.file(r),this._repositoryRoots.set(e,t)),t}catch{}})}async getWorktreeRoots(n){let e=await this._runGit(n,["worktree","list","--porcelain"]);return e?e.split(/\r?\n/g).filter(t=>t.startsWith("worktree ")).map(t=>v.file(t.substring(9))):[]}async addWorktree(n,e,t,r){let o=await this._resolveRemoteTrackingBranch(n,r)??r;await this._runGit(n,["-c","checkout.workers=0","worktree","add","--no-track","-b",t,e.fsPath,o],{timeout:18e4,throwOnError:!0})}async addExistingWorktree(n,e,t){await this._runGit(n,["-c","checkout.workers=0","worktree","add",e.fsPath,t],{timeout:18e4,throwOnError:!0})}async removeWorktree(n,e){await this._runGit(n,["worktree","remove","--force",e.fsPath],{timeout:6e4,throwOnError:!0})}async branchExists(n,e){return await this._runGit(n,["show-ref","--verify","--quiet",`refs/heads/${e}`])!==void 0}async hasUncommittedChanges(n){let e=await this._runGit(n,["status","--porcelain"]);return!!e&&e.trim().length>0}async commitAll(n,e){await this._runGit(n,["add","-A","--",":/"],{throwOnError:!0}),await this._runGit(n,["commit","--no-verify","--no-gpg-sign","-m",e],{timeout:6e4,throwOnError:!0})}async restore(n,e,t){let r=["restore"];t?.staged&&r.push("--staged"),t?.ref&&r.push("--source",t.ref),e.length===0&&(e=["."]),await this._runGit(n,[...r,"--",...e],{throwOnError:!0})}async hasUpstream(n,e){let t=await this._runGit(n,["rev-parse","--abbrev-ref",`${e}@{upstream}`]);return t!==void 0&&t.trim().length>0}async pull(n,e){let t=["pull"];e?.rebase&&t.push("-r"),(e?.remote||e?.ref)&&(t.push(e.remote??"origin"),e.ref&&t.push(e.ref)),await this._runGit(n,t,{timeout:18e4,throwOnError:!0})}async push(n,e){let t=["push"];e?.setUpstream&&t.push("--set-upstream"),(e?.remote||e?.ref)&&(t.push(e.remote??"origin"),e.ref&&t.push(e.ref)),await this._runGit(n,t,{timeout:18e4,throwOnError:!0})}async computeSessionFileDiffs(n,e){let t=await this.getRepositoryRoot(n);if(!t)return;let r=await this._resolveBranchMergeBaseCommit(t,e.baseBranch),o=await this._runGit(t,["status","--porcelain=v1","-z","--untracked-files=all"]);if(o===void 0)return;let s=t8(o).length>0,a;if(!s)a=await this._runGit(t,["diff","--raw","--numstat","--diff-filter=ADMR","-z",r,"--"]);else{let l=TC(o);a=await this._runWithTempIndex(t,r,l)}if(a!==void 0)return _0(a,t,e.sessionUri,r)}async resolveBranchBaselineCommit(n,e){let t=await this.getRepositoryRoot(n);if(t)return this._resolveBranchMergeBaseCommit(t,e)}async _resolveBranchMergeBaseCommit(n,e){let t;if(e){let r=await this._resolveRemoteTrackingBranch(n,e)??e;t=(await this._runGit(n,["merge-base","HEAD",r]))?.trim()}return t||(t=(await this._runGit(n,["rev-parse","HEAD"]))?.trim()),t??Jo}async _runWithTempIndex(n,e,t){let r=v.joinPath(this._environmentService.tmpDir,`agent-host-git-diff-${H()}`);await this._fileService.createFolder(r);let s={GIT_INDEX_FILE:v.joinPath(r,"index").fsPath};s.COMMAND_HOOK_LOCK="1";try{return await this._runGit(n,["read-tree","HEAD"],{env:s})===void 0&&await this._runGit(n,["read-tree",Jo],{env:s}),await this._stageChangedPaths(n,r,t,s)?await this._runGit(n,["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(n,e,t,r){if(t.length===0)return!0;let o=v.joinPath(e,"pathspec");return await this._fileService.writeFile(o,U.fromString(t.join("\0")+"\0")),this._logService.debug(`[agentHostGitService] Staging ${t.length} changed path(s) into temp index`),await this._runGit(n,["add","-A",`--pathspec-from-file=${o.fsPath}`,"--pathspec-file-nul"],{env:{...r,GIT_LITERAL_PATHSPECS:"1"}})!==void 0}async _resolveRemoteTrackingBranch(n,e){let t=`origin/${e}`;return await this._runGit(n,["show-ref","--verify","--quiet",`refs/remotes/${t}`])!==void 0?t:void 0}async showBlob(n,e,t){if(await this.getRepositoryRoot(n))return new Promise(o=>{Ph.execFile("git",["show",`${e}:${t}`],{cwd:n.fsPath,timeout:5e3,encoding:"buffer",maxBuffer:32*1024*1024},(s,a)=>{if(s){o(void 0);return}o(U.wrap(a))})})}async getSessionGitState(n){return this._computeSessionGitState(n)}async captureWorkingTreeAsTree(n){let e=await this.getRepositoryRoot(n);if(!e)return;let t=await this._runGit(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(t===void 0)return;let r=TC(t),o=v.joinPath(this._environmentService.tmpDir,`agent-host-checkpoint-${H()}`);await this._fileService.createFolder(o);let a={GIT_INDEX_FILE:v.joinPath(o,"index").fsPath,COMMAND_HOOK_LOCK:"1"};try{return await this._runGit(e,["read-tree","HEAD"],{env:a})===void 0&&await this._runGit(e,["read-tree",Jo],{env:a}),await this._stageChangedPaths(e,o,r,a)&&(await this._runGit(e,["write-tree"],{env:a}))?.trim()||void 0}finally{try{await this._fileService.del(o,{recursive:!0,useTrash:!1})}catch{}}}async commitTree(n,e,t,r){let o=["commit-tree",e];return t&&o.push("-p",t),o.push("-m",r),(await this._runGit(n,o,{throwOnError:!0}))?.trim()||void 0}async updateRef(n,e,t){await this._runGit(n,["update-ref",e,t],{throwOnError:!0})}async deleteRefs(n,e){if(e.length===0)return;let t=e.map(r=>`delete ${r}\0\0`).join("");await new Promise(r=>{Ph.execFile("git",["update-ref","--stdin","-z"],{cwd:n.fsPath,timeout:1e4},()=>{r()}).stdin?.end(t)})}async revParse(n,e){return(await this._runGit(n,["rev-parse","--verify","--quiet",e]))?.trim()||void 0}async overlayPathIntoTree(n,e,t,r){let o=v.joinPath(this._environmentService.tmpDir,`agent-host-review-overlay-${H()}`);await this._fileService.createFolder(o);let a={GIT_INDEX_FILE:v.joinPath(o,"index").fsPath,COMMAND_HOOK_LOCK:"1"};try{if(await this._runGit(n,["read-tree",e],{env:a,throwOnError:!1})===void 0)return;let d=await this._runGit(n,["ls-tree","-z",r,"--",t],{env:a}),c=n8(d);if(c){if(await this._runGit(n,["update-index","--add","--cacheinfo",`${c.mode},${c.oid},${t}`],{env:a,throwOnError:!1})===void 0)return}else if(await this._runGit(n,["update-index","--force-remove","--",t],{env:a,throwOnError:!1})===void 0)return;return(await this._runGit(n,["write-tree"],{env:a}))?.trim()}finally{try{await this._fileService.del(o,{recursive:!0,useTrash:!1})}catch{}}}async diffTreePaths(n,e,t){let r=await this._runGit(n,["diff","--name-only","--no-renames","-z",e,t,"--"]);if(r!==void 0)return r.split("\0").filter(Boolean)}async computeFileDiffsBetweenRefs(n,e){let t=await this.getRepositoryRoot(n);if(t)try{let r=await this._runGit(t,["diff","--raw","--numstat","--diff-filter=ADMR","-z",e.fromRef,e.toRef,"--"]);return r===void 0?void 0:_0(r,t,e.sessionUri,e.fromRef,e.toRef)}catch(r){this._logService.warn(`[AgentHostGitService][computeFileDiffsBetweenRefs] Failed to compute file diffs ${t.toString()}, ${e.fromRef}, ${e.toRef}: ${r}`);return}}async _computeSessionGitState(n){let e=await this.getRepositoryRoot(n);if(!e)return;let[t,r,o]=await Promise.all([this._runGit(e,["status","-b","--porcelain=v2"]),this._runGit(e,["remote","-v"]),this._runGit(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])]),s=r8(t),a=i8(r),l=a8(o),d=o8(r),c=s.outgoingChanges;if(c===void 0&&l&&s.branchName&&s.branchName!==l){let p=await this._runGit(e,["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 l8(u)}_runGit(n,e,t){return this._logService.trace(`[agentHostGitService] > git ${e.join(" ")}`),new Promise((r,o)=>{let s=t?.env?{...process.env,...t.env}:void 0,a=t?.timeout??5e3,l=!1,d=Ph.execFile("git",[...e],{cwd:n.fsPath,env:s,maxBuffer:t?.maxBuffer??32*1024*1024},(u,p,m)=>{if(u){if(m&&this._logService.warn(`[agentHostGitService] > git ${e.join(" ")} failed; full stderr:
${m}`),t?.throwOnError){o(new Error(Z9(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))})}};ql=w([C(0,xe),C(1,Rt),C(2,D)],ql);function Z9(i,n,e,t,r){let o=i[0]??"(unknown)",s;e?s=`git ${o} timed out after ${n}ms`:t.killed&&t.signal?s=`git ${o} killed by ${t.signal}`:typeof t.code=="number"?s=`git ${o} exited with code ${t.code}`:s=t.message;let a=e8(r);return a?`${s}: ${a}`:s}function e8(i){if(!i)return"";let n=i.split(/[\r\n]+/g).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)return"";let e=200,r=n.find(o=>/\bgit-lfs\b/i.test(o)&&/(command not found|not recognized|no such file)/i.test(o))??n[n.length-1];return r.length>e?`${r.slice(0,e-1)}\u2026`:r}function t8(i){return TC(i,n=>n==="??")}function TC(i,n=()=>!0){if(!i)return[];let e=[],t=new Set,r=s=>{s&&!t.has(s)&&(t.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(n(l)){if(r(d),c){let u=o[++s];u&&r(u)}}else c&&s++}return e}function n8(i){if(!i)return;let n=i.split("\0")[0];if(!n)return;let e=n.indexOf("	"),t=(e===-1?n:n.substring(0,e)).split(" ");if(!(t.length<3))return{mode:t[0],oid:t[2]}}function _0(i,n,e,t,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?v.joinPath(n,d.oldPath):void 0,p=d.newPath?v.joinPath(n,d.newPath):void 0,m=d.kind!=="create"&&d.oldPath&&u?{uri:u.toString(),content:{uri:xv(e,t,d.oldPath,u.path)}}:void 0,h=d.kind!=="delete"&&d.newPath&&p?{uri:p.toString(),content:r!==void 0?{uri:xv(e,r,d.newPath,p.path)}:{uri:p.toString()}}:void 0,y={added:c?.added??0,removed:c?.removed??0};return{...m?{before:m}:{},...h?{after:h}:{},diff:y}})}function r8(i){if(!i)return{};let n,e,t,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();n=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&&(t=Number(l[1]),r=Number(l[2]))}else a.startsWith("#")||o++}return{branchName:n,upstreamBranchName:e,outgoingChanges:t,incomingChanges:r,uncommittedChanges:o}}function i8(i){if(i!==void 0)return i.trim()?/github\.com[:\/]/i.test(i):!1}function o8(i){if(!i)return;let n=[];for(let t of i.split(/\r?\n/)){let r=t.trim();if(!r)continue;let o=/^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(r);o&&n.push({name:o[1],url:o[2]})}if(n.length===0)return;let e=[...n.filter(t=>t.name==="origin"),...n.filter(t=>t.name!=="origin")];for(let{url:t}of e){let r=s8(t);if(r)return r}}function s8(i){let n=/^[^@\s]+@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(i);if(n)return{owner:n[1],repo:n[2]};if(n=/^[a-z+]+:\/\/(?:[^@\/\s]+@)?github\.com(?::\d+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(i),n)return{owner:n[1],repo:n[2]}}function a8(i){let n=i?.trim();if(!n)return;let e="refs/remotes/origin/";return n.startsWith(e)?n.substring(e.length):n}function l8(i){let n={};for(let[e,t]of Object.entries(i))t!==void 0&&(n[e]=t);return n}d8().catch(i=>{console.error(i),process.exit(1)});async function d8(){let i;np(process)?i=new ud:i=new ep("agentHost");let n=new G,e={_serviceBrand:void 0,...gn},t=new ih(oh(process.argv,pC),e),r=new lh(XT(t),t.logsHome);i.registerChannel("agentHostLogger",new dh(r,()=>XE));let o=r.createLogger("agenthost",{name:f(1996,null)}),s=n.add(new tm),a=n.add(new nm(s)),l=new sh(o,[a]);!t.isBuilt&&YT&&n.add(QT(l)),l.info("Agent Host process started successfully");let d=n.add(new yo(l));n.add(d.registerProvider(ie.file,n.add(new Ch(l)))),n.add(m1(d));let c=new $l(v.file(t.userDataPath),d,l),u=te(t.appSettingsHome,"globalStorage","agent-host-config.json"),p=await OR({environmentService:t,productService:e,fileService:d,loggerService:r,logService:l,disposables:n}),m,h,y,S,b,I=pp(process.env[j_],!1);try{let x=new Wi;x.set(Rt,t),x.set(D,l),x.set(xe,d),x.set(Je,c),x.set(Ct,e),x.set(Hn,p),await d0(x,d,t,l,n),h=new Xs(x);let B=n.add(h.createInstance(xr));x.set(Oa,B),x.set(cm,h.createInstance(dm)),x.set(lm,new _h);let K=h.createInstance(ql);x.set(Ye,K);let N=n.add(h.createInstance(Da));x.set(_r,N);let V=n.add(h.createInstance(hl));x.set(yl,V),y=V.onDidDownloadProgress;let de=h.createInstance(Xi,void 0);x.set(It,de),x.set(em,h.createInstance(sl));let F=n.add(h.createInstance(Al));x.set(Vm,F);let O=h.createInstance(Sl);x.set(bl,O);let W=n.add(h.createInstance(kl));x.set(Gm,W),S=new Zg,x.set(ao,S),b=h.createInstance(il),x.set(Qg,b);let q=n.add(h.createInstance(cl));x.set(am,q);let J=n.add(h.createInstance(Ll));x.set(Yg,J),m=new Ng(l,d,c,e,K,N,u,p,B,void 0),x.set(yr,m);let Z=new Wl(v.file(t.userDataPath),d,l);x.set(nl,Z);let ae=n.add(new Zi(l));if(x.set(rf,ae),x.set(lf,h.createInstance(sa)),x.set(Ir,m.terminalManager),x.set(ze,m.configurationService),x.set(Jf,m.completionsService),m.registerProvider(h.createInstance(Pe)),pp(process.env[z_],!0)&&(!t.isBuilt||V.isAvailable(vl))&&m.registerProvider(h.createInstance(El)),!t.isBuilt||V.isAvailable(ds)){let ft=m.configurationService,Me=!1,yt=()=>{if(Me)return;let vt=pp(process.env[V_],!1),Pt=ft.getRootValue($t,ky)===!0;(vt||Pt)&&(Me=!0,m.registerProvider(h.createInstance(Ml)))};yt(),n.add(ft.onDidRootConfigChange(()=>yt()))}}catch(x){throw l.error("Failed to create AgentService",x),x}y&&n.add(y(x=>m.emitDownloadProgress(x.packageId,x.displayName,x.receivedBytes,x.totalBytes,x.phase==="completed"||x.phase==="failed")));let _=Ns.fromService(m,n);i.registerChannel("agentHost",_);let R=n.add(new Th);if(n.add(d.registerProvider(LS,R)),i instanceof ud){let x=new Map,B=K=>{if(x.has(K))return;let N=K.ctx;if(typeof N!="string"||!N)return;let V=new G,de=W=>i.getChannel(W,q=>q.ctx===N),F=y0(de(h0));V.add(R.registerAuthority(N,F));let O=I0(de(C0));if(V.add(b.register(N,O)),I&&S){let W=b0(de(S0));V.add(S.register(N,W))}x.set(K,V)};n.add(i.onDidAddConnection(B)),n.add(i.onDidRemoveConnection(K=>{let N=x.get(K);N&&(N.dispose(),x.delete(K))}));for(let K of i.connections)B(K)}let A=n.add(new P),X,E={onDidChangeConnectionCount:A.event,async startWebSocketServer(){if(X)return X;let x=Q?`\\\\.\\pipe\\vscode-agent-host-${H().replace(/-/g,"")}`:j(gu.tmpdir(),`vscode-agent-host-${H().replace(/-/g,"")}.sock`),B=n.add(await uu.create({socketPath:x},l,{instantiationService:h,logsHome:t.logsHome})),K=n.add(new ps(m,m.stateManager,B,{defaultDirectory:v.file(gu.homedir()).toString(),completionTriggerCharacters:m.completionTriggerCharacters,otlpLogEmitter:s},R,l));return n.add(K.onDidChangeConnectionCount(N=>A.fire(N))),l.info(`[AgentHost] Dynamic WebSocket server listening on ${x}`),X={socketPath:x},X},async getInspectInfo(x){let B=fu.url();if(!B&&x){try{fu.open(0,"127.0.0.1",!1)}catch(K){l.error("[AgentHost] Failed to open inspector",K);return}B=fu.url()}if(B)try{let K=new URL(B);if(K.protocol!=="ws:"){l.warn(`[AgentHost] Unexpected inspector URL: ${B}`);return}let N=Number(K.port),V=K.pathname.replace(/^\/+/,"");if(!Number.isInteger(N)||!V){l.warn(`[AgentHost] Unexpected inspector URL: ${B}`);return}let de=K.hostname==="0.0.0.0"?"127.0.0.1":K.hostname==="::"?"::1":K.hostname,F=de.includes(":")?`[${de}]`:de;return{host:de,port:N,devtoolsUrl:`devtools://devtools/bundled/js_app.html?v8only=true&ws=${F}:${K.port}/${V}`}}catch{l.warn(`[AgentHost] Unexpected inspector URL: ${B}`);return}}},z=Ns.fromService(E,n);i.registerChannel("agentHostConnectionTracker",z),c8(m,R,h,t.logsHome,l,s,n,x=>A.fire(x)).catch(x=>{l.error("Failed to start WebSocket server",x)}),process.once("exit",()=>{m.dispose(),l.dispose(),n.dispose()})}async function c8(i,n,e,t,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 uu.create(d?{socketPath:d,connectionTokenValidate:c?y=>y===c:void 0}:{port:parseInt(l,10),host:u,connectionTokenValidate:c?y=>y===c:void 0},r,{instantiationService:e,logsHome:t})),m=s.add(new ps(i,i.stateManager,p,{defaultDirectory:v.file(gu.homedir()).toString(),completionTriggerCharacters:i.completionTriggerCharacters,otlpLogEmitter:o},n,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}`)}
