/*!--------------------------------------------------------
 * 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 uD=Object.defineProperty;var pD=Object.getOwnPropertyDescriptor;var R=(o,n,e,t)=>{for(var r=t>1?void 0:t?pD(n,e):n,i=o.length-1,s;i>=0;i--)(s=o[i])&&(r=(t?s(n,e,r):s(r))||r);return t&&r&&uD(n,e,r),r},C=(o,n)=>(e,t)=>n(e,t,o);function fD(o,n,e=0,t=o.length){let r=e,i=t;for(;r<i;){let s=Math.floor((r+i)/2);n(o[s])?r=s+1:i=s}return r-1}var _I=class o{constructor(n){this._array=n;this._findLastMonotonousLastIdx=0}static{this.assertInvariants=!1}findLastMonotonous(n){if(o.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=fD(this._array,n,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var yy=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(n){setTimeout(()=>{throw n.stack?Cr.isErrorNoTelemetry(n)?new Cr(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)}},vy=new yy;function Mo(o){vy.onUnexpectedError(o)}function st(o){Cn(o)||vy.onUnexpectedError(o)}function wI(o){Cn(o)||vy.onUnexpectedExternalError(o)}var Fu="Canceled";function Cn(o){return o instanceof K?!0:o instanceof Error&&o.name===Fu&&o.message===Fu}var K=class extends Error{constructor(){super(Fu),this.name=this.message}},TI=class o extends Error{static{this._name="PendingMigrationError"}static is(n){return n instanceof o||n instanceof Error&&n.name===o._name}constructor(n){super(n),this.name=o._name}};function Hu(){let o=new Error(Fu);return o.name=o.message,o}function Sy(o){return o?new Error(`Illegal argument: ${o}`):new Error("Illegal argument")}function $u(o){return o?new Error(`Illegal state: ${o}`):new Error("Illegal state")}function Zn(o){return o?o.message?o.message:o.stack?o.stack.split(`
`)[0]:String(o):"Error"}var Cr=class o extends Error{constructor(n){super(n),this.name="CodeExpectedError"}static fromError(n){if(n instanceof o)return n;let e=new o;return e.message=n.message,e.stack=n.stack,e}static isErrorNoTelemetry(n){return n.name==="CodeExpectedError"}},We=class o extends Error{constructor(n){super(n||"An unexpected bug occurred."),Object.setPrototypeOf(this,o.prototype)}};function In(o,n,e=(t,r)=>t===r){if(o===n)return!0;if(!o||!n||o.length!==n.length)return!1;for(let t=0,r=o.length;t<r;t++)if(!e(o[t],n[t]))return!1;return!0}function Oo(o){return o.filter(n=>!!n)}function Jr(o,n=e=>e){let e=new Set;return o.filter(t=>{let r=n(t);return e.has(r)?!1:(e.add(r),!0)})}function by(o,n){return o.push(n),()=>gD(o,n)}function gD(o,n){let e=o.indexOf(n);if(e>-1)return o.splice(e,1),n}function Cy(o,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=o.length-1;t>0;t-=1){let r=Math.floor(e()*(t+1)),i=o[t];o[t]=o[r],o[r]=i}}function PI(o){return o[Math.floor(Math.random()*o.length)]}var AI;(a=>{function o(l){return l<0}a.isLessThan=o;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})(AI||={});function EI(o,n){return(e,t)=>n(o(e),o(t))}var kI=(o,n)=>o-n;var xI=class o{constructor(n){this.iterate=n}static{this.empty=new o(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 o(e=>this.iterate(t=>n(t)?e(t):!0))}map(n){return new o(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||AI.isGreaterThan(n(r,e)))&&(t=!1,e=r),!0)),e}};function LI(o,n){let e=Object.create(null);for(let t of o){let r=n(t),i=e[r];i||(i=e[r]=[]),i.push(t)}return e}var MI,OI,DI=class{constructor(n,e){this.toKey=e;this._map=new Map;this[MI]="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))}[(OI=Symbol.iterator,MI=Symbol.toStringTag,OI)](){return this.values()}};function Ps(o,n){let e=this,t=!1,r;return function(){if(t)return r;if(t=!0,n)try{r=o.apply(e,arguments)}finally{n()}else r=o.apply(e,arguments);return r}}var _y=class{constructor(n,e){this.uri=n;this.value=e}};function mD(o){return Array.isArray(o)}var NI,qe=class o{constructor(n,e){this[NI]="ResourceMap";if(n instanceof o)this.map=new Map(n.map),this.toKey=e??o.defaultToKey;else if(mD(n)){this.map=new Map,this.toKey=e??o.defaultToKey;for(let[t,r]of n)this.set(t,r)}else this.map=new Map,this.toKey=n??o.defaultToKey}static{this.defaultToKey=n=>n.toString()}set(n,e){return this.map.set(this.toKey(n),new _y(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]}*[(NI=Symbol.toStringTag,Symbol.iterator)](){for(let[,n]of this.map)yield[n.uri,n.value]}},UI,Ir=class{constructor(n,e){this[UI]="ResourceSet";!n||typeof n=="function"?this._map=new qe(n):(this._map=new qe(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()}[(UI=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var FI,ld=class{constructor(){this[FI]="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 i={value:t.key,done:!1};return t=t.next,i}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 i={value:t.value,done:!1};return t=t.next,i}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 i={value:[t.key,t.value],done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return r}[(FI=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)}},Ty=class extends ld{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))}},an=class extends Ty{constructor(n,e=1){super(n,e)}trim(n){this.trimOld(n)}set(n,e){return super.set(n,e),this.checkTrim(),this}};var Wu=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 dd=class{constructor(){this._data=new Map}set(n,...e){let t=this._data;for(let r=0;r<e.length-1;r++){let i=t.get(e[r]);i===void 0&&(i=new Map,t.set(e[r],i)),t=i}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 i=0;i<n.length-1;i++){let s=t.get(n[i]);if(s===void 0)return!1;t=s,e.push(t)}let r=t.delete(n[n.length-1]);for(let i=n.length-2;r&&i>=0;i--)e[i+1].size===0&&e[i].delete(n[i]);return r}deleteAll(...n){if(n.length===0){let i=this._data.size>0;return this._data.clear(),i}let e=[this._data],t=this._data;for(let i=0;i<n.length-1;i++){let s=t.get(n[i]);if(s===void 0)return!1;t=s,e.push(t)}let r=t.delete(n[n.length-1]);for(let i=n.length-2;r&&i>=0;i--)e[i+1].size===0&&e[i].delete(n[i]);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[i,s]of e)r+=`${"  ".repeat(t)}${i}: `,s instanceof Map?r+=`
`+n(s,t+1):r+=`${s}
`;return r};return n(this._data,0)}};function qu(o,n){if(!o)throw new Error(n?`Assertion failed (${n})`:"Assertion Failed")}function cd(o,n="unexpected state"){if(!o)throw typeof n=="string"?new We(`Assertion Failed: ${n}`):n}function ud(o){if(!o()){debugger;o(),st(new We("Assertion Failed"))}}function Ve(o){return typeof o=="string"}function Qe(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof RegExp)&&!(o instanceof Date)}function HI(o){let n=Object.getPrototypeOf(Uint8Array);return typeof o=="object"&&o instanceof n}function xi(o){return typeof o=="number"&&!isNaN(o)}function $I(o){return!!o&&typeof o[Symbol.iterator]=="function"}function Bu(o){return o===!0||o===!1}function As(o){return typeof o>"u"}function _r(o){return!er(o)}function er(o){return As(o)||o===null}function WI(o,n){if(!o)throw new Error(n?`Unexpected type, expected '${n}'`:"Unexpected type")}var yD=Object.prototype.hasOwnProperty;function zu(o){if(!Qe(o))return!1;for(let n in o)if(yD.call(o,n))return!1;return!0}function pd(o){return typeof o=="function"}function he(o,n){for(let e in n)if(!(e in o))return!1;return!0}var ks;(X=>{function o(k){return!!k&&typeof k=="object"&&typeof k[Symbol.iterator]=="function"}X.is=o;let n=Object.freeze([]);function e(){return n}X.empty=e;function*t(k){yield k}X.single=t;function r(k){return o(k)?k:t(k)}X.wrap=r;function i(k){return k??n}X.from=i;function*s(k){for(let x=k.length-1;x>=0;x--)yield k[x]}X.reverse=s;function a(k){return!k||k[Symbol.iterator]().next().done===!0}X.isEmpty=a;function l(k){return k[Symbol.iterator]().next().value}X.first=l;function d(k,x){let E=0;for(let H of k)if(x(H,E++))return!0;return!1}X.some=d;function c(k,x){let E=0;for(let H of k)if(!x(H,E++))return!1;return!0}X.every=c;function u(k,x){for(let E of k)if(x(E))return E}X.find=u;function*p(k,x){for(let E of k)x(E)&&(yield E)}X.filter=p;function*m(k,x){let E=0;for(let H of k)yield x(H,E++)}X.map=m;function*v(k,x){let E=0;for(let H of k)yield*x(H,E++)}X.flatMap=v;function*y(...k){for(let x of k)$I(x)?yield*x:yield x}X.concat=y;function S(k,x,E){let H=E;for(let G of k)H=x(H,G);return H}X.reduce=S;function b(k){let x=0;for(let E of k)x++;return x}X.length=b;function*I(k,x,E=k.length){for(x<-k.length&&(x=0),x<0&&(x+=k.length),E<0?E+=k.length:E>k.length&&(E=k.length);x<E;x++)yield k[x]}X.slice=I;function _(k,x=Number.POSITIVE_INFINITY){let E=[];if(x===0)return[E,k];let H=k[Symbol.iterator]();for(let G=0;G<x;G++){let q=H.next();if(q.done)return[E,X.empty()];E.push(q.value)}return[E,{[Symbol.iterator](){return H}}]}X.consume=_;async function T(k){let x=[];for await(let E of k)x.push(E);return x}X.asyncToArray=T;async function P(k){let x=[];for await(let E of k)x=x.concat(E);return x}X.asyncToArrayFlat=P})(ks||={});var vD=!1,Ds=null;var qI=class o{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:o.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 i=new Wu;for(let l of t){let d=r(l);for(let c=0;c<=d.length;c++)i.add(d.slice(0,c).join(`
`),l)}t.sort(EI(l=>l.idx,kI));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 ${i.get(d.slice(0,u+1).join(`
`)).size}/${t.length} leaks) at ${p}`;let v=i.get(d.slice(0,u).join(`
`)),y=LI([...v].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 SD(o){Ds=o}if(vD){let o="__is_disposable_tracked__";SD(new class{trackDisposable(n){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{n[o]||console.log(e)},3e3)}setParent(n,e){if(n&&n!==w.None)try{n[o]=!0}catch{}}markAsDisposed(n){if(n&&n!==w.None)try{n[o]=!0}catch{}}markAsSingleton(n){}})}function Lo(o){return Ds?.trackDisposable(o),o}function No(o){Ds?.markAsDisposed(o)}function Pi(o,n){Ds?.setParent(o,n)}function bD(o,n){if(Ds)for(let e of o)Ds.setParent(e,n)}function Os(o){return typeof o=="object"&&o!==null&&typeof o.dispose=="function"&&o.dispose.length===0}function Gt(o){if(ks.is(o)){let n=[];for(let e of o)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(o)?[]:o}else if(o)return o.dispose(),o}function Vu(...o){let n=N(()=>Gt(o));return bD(o,n),n}var wy=class{constructor(n){this._isDisposed=!1,this._fn=n,Lo(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,No(this),this._fn()}}};function N(o){return new wy(o)}var Y=class o{constructor(){this._toDispose=new Set;this._isDisposed=!1;Lo(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(No(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Gt(this._toDispose)}finally{this._toDispose.clear()}}add(n){if(!n||n===w.None)return n;if(n===this)throw new Error("Cannot register a disposable on itself!");return Pi(n,this),this._isDisposed?o.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)&&Pi(n,null)}assertNotDisposed(){this._isDisposed&&st(new We("Object disposed"))}},w=class{constructor(){this._store=new Y;Lo(this),Pi(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){No(this),this._store.dispose()}_register(n){if(n===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(n)}},Dt=class{constructor(){this._isDisposed=!1;Lo(this)}get value(){return this._isDisposed?void 0:this._value}set value(n){this._isDisposed||n===this._value||(this._value?.dispose(),n&&Pi(n,this),this._value=n)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,No(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let n=this._value;return this._value=void 0,n&&Pi(n,null),n}};var Ms=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,i=Ps(()=>{--t.counter===0&&(this.destroyReferencedObject(n,t.object),this.references.delete(n))});return t.counter++,{object:r,dispose:i}}};var we=class{constructor(n=new Map){this._isDisposed=!1;this._store=n,Lo(this)}dispose(){No(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{Gt(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),Pi(e,this)}deleteAndDispose(n){this._store.get(n)?.dispose(),this._store.delete(n)}deleteAndLeak(n){let e=this._store.get(n);return e&&Pi(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 Ry(o,n){return o.then(e=>(n.isDisposed?e.dispose():n.add(e),e))}var fd=class extends we{constructor(){super(new qe)}};var Ge=class o{static{this.Undefined=new o(void 0)}constructor(n){this.element=n,this.next=o.Undefined,this.prev=o.Undefined}},gd=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 i=this._last;this._last=t,t.prev=i,i.next=t}else{let i=this._first;this._first=t,t.next=i,i.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 CD(){return globalThis._VSCODE_NLS_MESSAGES}function xy(){return globalThis._VSCODE_NLS_LANGUAGE}var ID=xy()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function BI(o,n){let e;return n.length===0?e=o:e=o.replace(/\{(\d+)\}/g,(t,r)=>{let i=r[0],s=n[i],a=t;return typeof s=="string"?a=s:(typeof s=="number"||typeof s=="boolean"||s===void 0||s===null)&&(a=String(s)),a}),ID&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function f(o,n,...e){return BI(typeof o=="number"?_D(o,n):n,e)}function _D(o,n){let e=CD()?.[o];if(typeof e!="string"){if(typeof n=="string")return n;throw new Error(`!!! NLS MISSING: ${o} !!!`)}return e}var Fo="en",hd=!1,yd=!1,md=!1,VI=!1,jI=!1,Py=!1,KI=!1,GI=!1,TD=!1,wD=!1,Ku,Gu=Fo,zI=Fo,RD,Yr,Qr=globalThis,ln;typeof Qr.vscode<"u"&&typeof Qr.vscode.process<"u"?ln=Qr.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(ln=process);var JI=typeof ln?.versions?.electron=="string",xD=JI&&ln?.type==="renderer";if(typeof ln=="object"){hd=ln.platform==="win32",yd=ln.platform==="darwin",md=ln.platform==="linux",VI=md&&!!ln.env.SNAP&&!!ln.env.SNAP_REVISION,KI=JI,TD=!!ln.env.CI||!!ln.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!ln.env.GITHUB_WORKSPACE,Ku=Fo,Gu=Fo;let o=ln.env.VSCODE_NLS_CONFIG;if(o)try{let n=JSON.parse(o);Ku=n.userLocale,zI=n.osLocale,Gu=n.resolvedLanguage||Fo,RD=n.languagePack?.translationsConfigFile}catch{}jI=!0}else typeof navigator=="object"&&!xD?(Yr=navigator.userAgent,hd=Yr.indexOf("Windows")>=0,yd=Yr.indexOf("Macintosh")>=0,GI=(Yr.indexOf("Macintosh")>=0||Yr.indexOf("iPad")>=0||Yr.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,md=Yr.indexOf("Linux")>=0,wD=Yr?.indexOf("Mobi")>=0,Py=!0,Gu=xy()||Fo,Ku=navigator.language.toLowerCase(),zI=Ku):console.error("Unable to resolve platform.");function YI(o){switch(o){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var Ju=0;yd?Ju=1:hd?Ju=3:md&&(Ju=2);var Q=hd,dt=yd,Oe=md,QI=VI,XI=jI,ZI=KI,Nn=Py,Ay=Py&&typeof Qr.importScripts=="function",e_=Ay?Qr.origin:void 0;var Ey=Ju,Ln=Yr,Uo=Gu,PD;(t=>{function o(){return Uo}t.value=o;function n(){return Uo.length===2?Uo==="en":Uo.length>=3?Uo[0]==="e"&&Uo[1]==="n"&&Uo[2]==="-":!1}t.isDefaultVariant=n;function e(){return Uo==="en"}t.isDefault=e})(PD||={});var AD=typeof Qr.postMessage=="function"&&!Qr.importScripts,t_=(()=>{if(AD){let o=[];Qr.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let t=0,r=o.length;t<r;t++){let i=o[t];if(i.id===e.data.vscodeScheduleAsyncWork){o.splice(t,1),i.callback();return}}});let n=0;return e=>{let t=++n;o.push({id:t,callback:e}),Qr.postMessage({vscodeScheduleAsyncWork:t},"*")}}return o=>setTimeout(o)})();var Mt=yd||GI?2:hd?1:3;var ky=!!(Ln&&Ln.indexOf("Chrome")>=0),n_=!!(Ln&&Ln.indexOf("Firefox")>=0),r_=!!(!ky&&Ln&&Ln.indexOf("Safari")>=0),o_=!!(Ln&&Ln.indexOf("Edg/")>=0),j3=!!(Ln&&Ln.indexOf("Android")>=0),i_=!!(Ln&&Ln.indexOf("Electron")>=0);var Ai,Dy=globalThis.vscode;if(typeof Dy<"u"&&typeof Dy.process<"u"){let o=Dy.process;Ai={get platform(){return o.platform},get arch(){return o.arch},get env(){return o.env},cwd(){return o.cwd()}}}else typeof process<"u"&&typeof process?.versions?.node=="string"?Ai={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:Ai={get platform(){return Q?"win32":dt?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var Ei=Ai.cwd,Xe=Ai.env,Ls=Ai.platform,s_=Ai.arch;var ED=globalThis.performance.now.bind(globalThis.performance),Un=class o{static create(n){return new o(n)}constructor(n){this._now=n===!1?Date.now:ED,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 a_=!1,kD=!1,DD=100,l_=6e4;function d_(){return!!Xe.VSCODE_DEV}var ee;(ge=>{ge.None=()=>w.None;function n($){if(kD){let{onDidAddListener:U}=$,B=Us.create(),z=0;$.onDidAddListener=()=>{++z===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),B.print()),U?.()}}}function e($,U,B){return m($,()=>{},0,void 0,U??!0,void 0,B)}ge.defer=e;function t($){return(U,B=null,z)=>{let J=!1,Z;return Z=$(le=>{if(!J)return Z?Z.dispose():J=!0,U.call(B,le)},null,z),J&&Z.dispose(),Z}}ge.once=t;function r($,U){return ge.once(ge.filter($,U))}ge.onceIf=r;function i($,U,B){return u((z,J=null,Z)=>$(le=>z.call(J,U(le)),null,Z),B)}ge.map=i;function s($,U,B){return u((z,J=null,Z)=>$(le=>{U(le),z.call(J,le)},null,Z),B)}ge.forEach=s;function a($,U,B){return u((z,J=null,Z)=>$(le=>U(le)&&z.call(J,le),null,Z),B)}ge.filter=a;function l($){return $}ge.signal=l;function d(...$){return(U,B=null,z)=>{let J=Vu(...$.map(Z=>Z(le=>U.call(B,le))));return p(J,z)}}ge.any=d;function c($,U,B,z){let J=B;return i($,Z=>(J=U(J,Z),J),z)}ge.reduce=c;function u($,U){let B,z={onWillAddFirstListener(){B=$(J.fire,J)},onDidRemoveLastListener(){B?.dispose()}};U||n(z);let J=new A(z);return U?.add(J),J.event}function p($,U){return U instanceof Array?U.push($):U&&U.add($),$}function m($,U,B=100,z=!1,J=!1,Z,le){let It,$e,At,yt=0,Et,On={leakWarningThreshold:Z,onWillAddFirstListener(){It=$(Uu=>{yt++,$e=U($e,Uu),z&&!At&&(Gr.fire($e),$e=void 0),Et=()=>{let II=$e;$e=void 0,At=void 0,(!z||yt>1)&&Gr.fire(II),yt=0},typeof B=="number"?(At&&clearTimeout(At),At=setTimeout(Et,B)):At===void 0&&(At=null,queueMicrotask(Et))})},onWillRemoveListener(){J&&yt>0&&Et?.()},onDidRemoveLastListener(){Et=void 0,It.dispose()}};le||n(On);let Gr=new A(On);return le?.add(Gr),Gr.event}ge.debounce=m;function v($,U=0,B,z){return ge.debounce($,(J,Z)=>J?(J.push(Z),J):[Z],U,void 0,B??!0,void 0,z)}ge.accumulate=v;function y($,U,B=100,z=!0,J=!0,Z,le){let It,$e,At,yt=0,Et={leakWarningThreshold:Z,onWillAddFirstListener(){It=$(Gr=>{yt++,$e=U($e,Gr),At===void 0&&(z&&(On.fire($e),$e=void 0,yt=0),typeof B=="number"?At=setTimeout(()=>{J&&yt>0&&On.fire($e),$e=void 0,At=void 0,yt=0},B):(At=0,queueMicrotask(()=>{J&&yt>0&&On.fire($e),$e=void 0,At=void 0,yt=0})))})},onDidRemoveLastListener(){It.dispose()}};le||n(Et);let On=new A(Et);return le?.add(On),On.event}ge.throttle=y;function S($,U=(z,J)=>z===J,B){let z=!0,J;return a($,Z=>{let le=z||!U(Z,J);return z=!1,J=Z,le},B)}ge.latch=S;function b($,U,B){return[ge.filter($,U,B),ge.filter($,z=>!U(z),B)]}ge.split=b;function I($,U,B=!1,z=[],J){let Z=z.slice(),le;d_()&&(le={stack:Us.create(),timerId:setTimeout(()=>{Z&&Z.length>0&&le&&!le.warned&&(le.warned=!0,console.warn(`[Event.buffer][${U}] potential LEAK detected: ${Z.length} events buffered for ${l_/1e3}s without being consumed. Buffered here:`),le.stack.print())},l_),warned:!1},J&&J.add(N(()=>clearTimeout(le.timerId))));let It=()=>{le&&clearTimeout(le.timerId)},$e=$(Et=>{Z?(Z.push(Et),d_()&&le&&!le.warned&&Z.length>=DD&&(le.warned=!0,console.warn(`[Event.buffer][${U}] potential LEAK detected: ${Z.length} events buffered without being consumed. Buffered here:`),le.stack.print())):yt.fire(Et)});J&&J.add($e);let At=()=>{Z?.forEach(Et=>yt.fire(Et)),Z=null,It()},yt=new A({onWillAddFirstListener(){$e||($e=$(Et=>yt.fire(Et)),J&&J.add($e))},onDidAddFirstListener(){Z&&(B?setTimeout(At):At())},onDidRemoveLastListener(){$e&&$e.dispose(),$e=null,It()}});return J&&J.add(yt),yt.event}ge.buffer=I;function _($,U){return(z,J,Z)=>{let le=U(new P);return $(function(It){let $e=le.evaluate(It);$e!==T&&z.call(J,$e)},void 0,Z)}}ge.chain=_;let T=Symbol("HaltChainable");class P{constructor(){this.steps=[]}map(U){return this.steps.push(U),this}forEach(U){return this.steps.push(B=>(U(B),B)),this}filter(U){return this.steps.push(B=>U(B)?B:T),this}reduce(U,B){let z=B;return this.steps.push(J=>(z=U(z,J),z)),this}latch(U=(B,z)=>B===z){let B=!0,z;return this.steps.push(J=>{let Z=B||!U(J,z);return B=!1,z=J,Z?J:T}),this}evaluate(U){for(let B of this.steps)if(U=B(U),U===T)break;return U}}function X($,U,B=z=>z){let z=(...It)=>le.fire(B(...It)),J=()=>$.on(U,z),Z=()=>$.removeListener(U,z),le=new A({onWillAddFirstListener:J,onDidRemoveLastListener:Z});return le.event}ge.fromNodeEventEmitter=X;function k($,U,B=z=>z){let z=(...It)=>le.fire(B(...It)),J=()=>$.addEventListener(U,z),Z=()=>$.removeEventListener(U,z),le=new A({onWillAddFirstListener:J,onDidRemoveLastListener:Z});return le.event}ge.fromDOMEventEmitter=k;function x($,U){let B,z,J=new Promise(Z=>{z=t($)(Z),Fy(z,U),B=()=>{u_(z,U)}});return J.cancel=B,U&&J.finally(()=>u_(z,U)),J}ge.toPromise=x;function E($,U){return $(B=>U.fire(B))}ge.forward=E;function H($,U,B){return U(B),$(z=>U(z))}ge.runAndSubscribe=H;class G{constructor(U,B){this._observable=U;this._counter=0;this._hasChanged=!1;let z={onWillAddFirstListener:()=>{U.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{U.removeObserver(this)}};B||n(z),this.emitter=new A(z),B&&B.add(this.emitter)}beginUpdate(U){this._counter++}handlePossibleChange(U){}handleChange(U,B){this._hasChanged=!0}endUpdate(U){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function q($,U){return new G($,U).emitter.event}ge.fromObservable=q;function V($){return(U,B,z)=>{let J=0,Z=!1,le={beginUpdate(){J++},endUpdate(){J--,J===0&&($.reportChanges(),Z&&(Z=!1,U.call(B)))},handlePossibleChange(){},handleChange(){Z=!0}};$.addObserver(le),$.reportChanges();let It={dispose(){$.removeObserver(le)}};return Fy(It,z),It}}ge.fromObservableLight=V})(ee||={});var Oy=class o{constructor(n){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${n}_${o._idPool++}`,o.all.add(this)}static{this.all=new Set}static{this._idPool=0}start(n){this._stopWatch=new Un,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}}},c_=-1;var Ly=class o{constructor(n,e,t=(o._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[i,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(i);let d=s/e>.3?"dominated":"popular",c=new Yu(d,l,i,e,a);this._errorHandler(c)}return()=>{let i=this._stacks.get(n.value)||0;this._stacks.set(n.value,i-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}},Us=class o{constructor(n){this.value=n}static create(){let n=new Error;return new o(n.stack??"")}print(){console.warn(this.value.split(`
`).slice(2).join(`
`))}},Yu=class o extends Error{constructor(n,e,t,r,i){super(i?`[${i}] 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 o||n instanceof Error&&typeof n.kind=="string"&&typeof n.listenerCount=="number"}},Ny=class extends Yu{constructor(n,e,t,r,i){super(n,e,t,r,i),this.name="ListenerRefusalError"}},MD=0,Ns=class{constructor(n){this.value=n;this.id=MD++}},OD=2,LD=(o,n)=>{if(o instanceof Ns)n(o);else for(let e=0;e<o.length;e++){let t=o[e];t&&n(t)}},A=class{constructor(n){this._size=0;this._options=n,this._leakageMon=c_>0||this._options?.leakWarningThreshold?new Ly(n?.onListenerError??st,this._options?.leakWarningThreshold??c_,this._options?.leakWarningName):void 0,this._perfMon=this._options?._profName?new Oy(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(a_){let n=this._listeners;queueMicrotask(()=>{LD(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 Ny(c,`${l}. HINT: Stack shows most frequent listener (${d[1]}-times)`,d[0],this._size,this._options?.leakWarningName);return(this._options?.onListenerError||st)(u),w.None}if(this._disposed)return w.None;e&&(n=n.bind(e));let r=new Ns(n),i,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Us.create(),i=this._leakageMon.check(r.stack,this._size+1)),a_&&(r.stack=s??Us.create()),this._listeners?this._listeners instanceof Ns?(this._deliveryQueue??=new Uy,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=N(()=>{i?.(),this._removeListener(r)});return Fy(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*OD<=e.length){let i=0;for(let s=0;s<e.length;s++)e[s]?e[i++]=e[s]:r&&i<this._deliveryQueue.end&&(this._deliveryQueue.end--,i<this._deliveryQueue.i&&this._deliveryQueue.i--);e.length=i}}_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 Ns)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 Uy=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 Qu=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new A({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),N(Ps(()=>{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 vd=class{constructor(){this.listening=!1;this.inputEvent=ee.None;this.inputEventListener=w.None;this.emitter=new A({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 Fy(o,n){n instanceof Y?n.add(o):Array.isArray(n)&&n.push(o)}function u_(o,n){if(n instanceof Y)n.delete(o);else if(Array.isArray(n)){let e=n.indexOf(o);e!==-1&&n.splice(e,1)}o.dispose()}var p_=Object.freeze(function(o,n){let e=setTimeout(o.bind(n),0);return{dispose(){clearTimeout(e)}}}),Re;(t=>{function o(r){return r===t.None||r===t.Cancelled||r instanceof Fs?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}t.isCancellationToken=o,t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ee.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:p_})})(Re||={});var Fs=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?p_:(this._emitter||(this._emitter=new A),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 Fs),this._token}cancel(){this._token?this._token instanceof Fs&&this._token.cancel():this._token=Re.Cancelled}dispose(n=!1){n&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof Fs&&this._token.dispose():this._token=Re.None}};var ND=65,UD=97,FD=90,HD=122,ki=46,Ot=47,dn=92,Xr=58,$D=63,Xu=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 i=n.indexOf(".")!==-1?"property":"argument",s=`The "${n}" ${i} ${r} of type ${e}`;s+=`. Received type ${typeof t}`,super(s),this.code="ERR_INVALID_ARG_TYPE"}};function WD(o,n){if(o===null||typeof o!="object")throw new Xu(n,"Object",o)}function ct(o,n){if(typeof o!="string")throw new Xu(n,"string",o)}var cn=Ls==="win32";function ue(o){return o===Ot||o===dn}function Hy(o){return o===Ot}function Zr(o){return o>=ND&&o<=FD||o>=UD&&o<=HD}function Zu(o,n,e,t){let r="",i=0,s=-1,a=0,l=0;for(let d=0;d<=o.length;++d){if(d<o.length)l=o.charCodeAt(d);else{if(t(l))break;l=Ot}if(t(l)){if(!(s===d-1||a===1))if(a===2){if(r.length<2||i!==2||r.charCodeAt(r.length-1)!==ki||r.charCodeAt(r.length-2)!==ki){if(r.length>2){let c=r.lastIndexOf(e);c===-1?(r="",i=0):(r=r.slice(0,c),i=r.length-1-r.lastIndexOf(e)),s=d,a=0;continue}else if(r.length!==0){r="",i=0,s=d,a=0;continue}}n&&(r+=r.length>0?`${e}..`:"..",i=2)}else r.length>0?r+=`${e}${o.slice(s+1,d)}`:r=o.slice(s+1,d),i=d-s-1;s=d,a=0}else l===ki&&a!==-1?++a:a=-1}return r}function qD(o){return o?`${o[0]==="."?"":"."}${o}`:""}function f_(o,n){WD(n,"pathObject");let e=n.dir||n.root,t=n.base||`${n.name||""}${qD(n.ext)}`;return e?e===n.root?`${e}${t}`:`${e}${o}${t}`:t}var ye={resolve(...o){let n="",e="",t=!1;for(let r=o.length-1;r>=-1;r--){let i;if(r>=0){if(i=o[r],ct(i,`paths[${r}]`),i.length===0)continue}else n.length===0?i=Ei():(i=Xe[`=${n}`]||Ei(),(i===void 0||i.slice(0,2).toLowerCase()!==n.toLowerCase()&&i.charCodeAt(2)===dn)&&(i=`${n}\\`));let s=i.length,a=0,l="",d=!1,c=i.charCodeAt(0);if(s===1)ue(c)&&(a=1,d=!0);else if(ue(c))if(d=!0,ue(i.charCodeAt(1))){let u=2,p=u;for(;u<s&&!ue(i.charCodeAt(u));)u++;if(u<s&&u!==p){let m=i.slice(p,u);for(p=u;u<s&&ue(i.charCodeAt(u));)u++;if(u<s&&u!==p){for(p=u;u<s&&!ue(i.charCodeAt(u));)u++;(u===s||u!==p)&&(l=`\\\\${m}\\${i.slice(p,u)}`,a=u)}}}else a=1;else Zr(c)&&i.charCodeAt(1)===Xr&&(l=i.slice(0,2),a=2,s>2&&ue(i.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=`${i.slice(a)}\\${e}`,t=d,d&&n.length>0)break}return e=Zu(e,!t,"\\",ue),t?`${n}\\${e}`:`${n}${e}`||"."},normalize(o){ct(o,"path");let n=o.length;if(n===0)return".";let e=0,t,r=!1,i=o.charCodeAt(0);if(n===1)return Hy(i)?"\\":o;if(ue(i))if(r=!0,ue(o.charCodeAt(1))){let a=2,l=a;for(;a<n&&!ue(o.charCodeAt(a));)a++;if(a<n&&a!==l){let d=o.slice(l,a);for(l=a;a<n&&ue(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!ue(o.charCodeAt(a));)a++;if(a===n)return`\\\\${d}\\${o.slice(l)}\\`;a!==l&&(t=`\\\\${d}\\${o.slice(l,a)}`,e=a)}}}else e=1;else Zr(i)&&o.charCodeAt(1)===Xr&&(t=o.slice(0,2),e=2,n>2&&ue(o.charCodeAt(2))&&(r=!0,e=3));let s=e<n?Zu(o.slice(e),!r,"\\",ue):"";if(s.length===0&&!r&&(s="."),s.length>0&&ue(o.charCodeAt(n-1))&&(s+="\\"),!r&&t===void 0&&o.includes(":")){if(s.length>=2&&Zr(s.charCodeAt(0))&&s.charCodeAt(1)===Xr)return`.\\${s}`;let a=o.indexOf(":");do if(a===n-1||ue(o.charCodeAt(a+1)))return`.\\${s}`;while((a=o.indexOf(":",a+1))!==-1)}return t===void 0?r?`\\${s}`:s:r?`${t}\\${s}`:`${t}${s}`},isAbsolute(o){ct(o,"path");let n=o.length;if(n===0)return!1;let e=o.charCodeAt(0);return ue(e)||n>2&&Zr(e)&&o.charCodeAt(1)===Xr&&ue(o.charCodeAt(2))},join(...o){if(o.length===0)return".";let n,e;for(let i=0;i<o.length;++i){let s=o[i];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 i=e.length;i>1&&ue(e.charCodeAt(1))&&(++r,i>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 ye.normalize(n)},relative(o,n){if(ct(o,"from"),ct(n,"to"),o===n)return"";let e=ye.resolve(o),t=ye.resolve(n);if(e===t||(o=e.toLowerCase(),n=t.toLowerCase(),o===n))return"";if(e.length!==o.length||t.length!==n.length){let v=e.split("\\"),y=t.split("\\");v[v.length-1]===""&&v.pop(),y[y.length-1]===""&&y.pop();let S=v.length,b=y.length,I=S<b?S:b,_;for(_=0;_<I&&v[_].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<o.length&&o.charCodeAt(r)===dn;)r++;let i=o.length;for(;i-1>r&&o.charCodeAt(i-1)===dn;)i--;let s=i-r,a=0;for(;a<n.length&&n.charCodeAt(a)===dn;)a++;let l=n.length;for(;l-1>a&&n.charCodeAt(l-1)===dn;)l--;let d=l-a,c=s<d?s:d,u=-1,p=0;for(;p<c;p++){let v=o.charCodeAt(r+p);if(v!==n.charCodeAt(a+p))break;v===dn&&(u=p)}if(p!==c){if(u===-1)return t}else{if(d>c){if(n.charCodeAt(a+p)===dn)return t.slice(a+p+1);if(p===2)return t.slice(a+p)}s>c&&(o.charCodeAt(r+p)===dn?u=p:p===2&&(u=3)),u===-1&&(u=0)}let m="";for(p=r+u+1;p<=i;++p)(p===i||o.charCodeAt(p)===dn)&&(m+=m.length===0?"..":"\\..");return a+=u,m.length>0?`${m}${t.slice(a,l)}`:(t.charCodeAt(a)===dn&&++a,t.slice(a,l))},toNamespacedPath(o){if(typeof o!="string"||o.length===0)return o;let n=ye.resolve(o);if(n.length<=2)return o;if(n.charCodeAt(0)===dn){if(n.charCodeAt(1)===dn){let e=n.charCodeAt(2);if(e!==$D&&e!==ki)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(Zr(n.charCodeAt(0))&&n.charCodeAt(1)===Xr&&n.charCodeAt(2)===dn)return`\\\\?\\${n}`;return n},dirname(o){ct(o,"path");let n=o.length;if(n===0)return".";let e=-1,t=0,r=o.charCodeAt(0);if(n===1)return ue(r)?o:".";if(ue(r)){if(e=t=1,ue(o.charCodeAt(1))){let a=2,l=a;for(;a<n&&!ue(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&ue(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!ue(o.charCodeAt(a));)a++;if(a===n)return o;a!==l&&(e=t=a+1)}}}}else Zr(r)&&o.charCodeAt(1)===Xr&&(e=n>2&&ue(o.charCodeAt(2))?3:2,t=e);let i=-1,s=!0;for(let a=n-1;a>=t;--a)if(ue(o.charCodeAt(a))){if(!s){i=a;break}}else s=!1;if(i===-1){if(e===-1)return".";i=e}return o.slice(0,i)},basename(o,n){n!==void 0&&ct(n,"suffix"),ct(o,"path");let e=0,t=-1,r=!0,i;if(o.length>=2&&Zr(o.charCodeAt(0))&&o.charCodeAt(1)===Xr&&(e=2),n!==void 0&&n.length>0&&n.length<=o.length){if(n===o)return"";let s=n.length-1,a=-1;for(i=o.length-1;i>=e;--i){let l=o.charCodeAt(i);if(ue(l)){if(!r){e=i+1;break}}else a===-1&&(r=!1,a=i+1),s>=0&&(l===n.charCodeAt(s)?--s===-1&&(t=i):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=o.length),o.slice(e,t)}for(i=o.length-1;i>=e;--i)if(ue(o.charCodeAt(i))){if(!r){e=i+1;break}}else t===-1&&(r=!1,t=i+1);return t===-1?"":o.slice(e,t)},extname(o){ct(o,"path");let n=0,e=-1,t=0,r=-1,i=!0,s=0;o.length>=2&&o.charCodeAt(1)===Xr&&Zr(o.charCodeAt(0))&&(n=t=2);for(let a=o.length-1;a>=n;--a){let l=o.charCodeAt(a);if(ue(l)){if(!i){t=a+1;break}continue}r===-1&&(i=!1,r=a+1),l===ki?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?"":o.slice(e,r)},format:f_.bind(null,"\\"),parse(o){ct(o,"path");let n={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return n;let e=o.length,t=0,r=o.charCodeAt(0);if(e===1)return ue(r)?(n.root=n.dir=o,n):(n.base=n.name=o,n);if(ue(r)){if(t=1,ue(o.charCodeAt(1))){let u=2,p=u;for(;u<e&&!ue(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&ue(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&!ue(o.charCodeAt(u));)u++;u===e?t=u:u!==p&&(t=u+1)}}}}else if(Zr(r)&&o.charCodeAt(1)===Xr){if(e<=2)return n.root=n.dir=o,n;if(t=2,ue(o.charCodeAt(2))){if(e===3)return n.root=n.dir=o,n;t=3}}t>0&&(n.root=o.slice(0,t));let i=-1,s=t,a=-1,l=!0,d=o.length-1,c=0;for(;d>=t;--d){if(r=o.charCodeAt(d),ue(r)){if(!l){s=d+1;break}continue}a===-1&&(l=!1,a=d+1),r===ki?i===-1?i=d:c!==1&&(c=1):i!==-1&&(c=-1)}return a!==-1&&(i===-1||c===0||c===1&&i===a-1&&i===s+1?n.base=n.name=o.slice(s,a):(n.name=o.slice(s,i),n.base=o.slice(s,a),n.ext=o.slice(i,a))),s>0&&s!==t?n.dir=o.slice(0,s-1):n.dir=n.root,n},sep:"\\",delimiter:";",win32:null,posix:null},BD=(()=>{if(cn){let o=/\\/g;return()=>{let n=Ei().replace(o,"/");return n.slice(n.indexOf("/"))}}return()=>Ei()})(),re={resolve(...o){let n="",e=!1;for(let t=o.length-1;t>=0&&!e;t--){let r=o[t];ct(r,`paths[${t}]`),r.length!==0&&(n=`${r}/${n}`,e=r.charCodeAt(0)===Ot)}if(!e){let t=BD();n=`${t}/${n}`,e=t.charCodeAt(0)===Ot}return n=Zu(n,!e,"/",Hy),e?`/${n}`:n.length>0?n:"."},normalize(o){if(ct(o,"path"),o.length===0)return".";let n=o.charCodeAt(0)===Ot,e=o.charCodeAt(o.length-1)===Ot;return o=Zu(o,!n,"/",Hy),o.length===0?n?"/":e?"./":".":(e&&(o+="/"),n?`/${o}`:o)},isAbsolute(o){return ct(o,"path"),o.length>0&&o.charCodeAt(0)===Ot},join(...o){if(o.length===0)return".";let n=[];for(let e=0;e<o.length;++e){let t=o[e];ct(t,"path"),t.length>0&&n.push(t)}return n.length===0?".":re.normalize(n.join("/"))},relative(o,n){if(ct(o,"from"),ct(n,"to"),o===n||(o=re.resolve(o),n=re.resolve(n),o===n))return"";let e=1,t=o.length,r=t-e,i=1,s=n.length-i,a=r<s?r:s,l=-1,d=0;for(;d<a;d++){let u=o.charCodeAt(e+d);if(u!==n.charCodeAt(i+d))break;u===Ot&&(l=d)}if(d===a)if(s>a){if(n.charCodeAt(i+d)===Ot)return n.slice(i+d+1);if(d===0)return n.slice(i+d)}else r>a&&(o.charCodeAt(e+d)===Ot?l=d:d===0&&(l=0));let c="";for(d=e+l+1;d<=t;++d)(d===t||o.charCodeAt(d)===Ot)&&(c+=c.length===0?"..":"/..");return`${c}${n.slice(i+l)}`},toNamespacedPath(o){return o},dirname(o){if(ct(o,"path"),o.length===0)return".";let n=o.charCodeAt(0)===Ot,e=-1,t=!0;for(let r=o.length-1;r>=1;--r)if(o.charCodeAt(r)===Ot){if(!t){e=r;break}}else t=!1;return e===-1?n?"/":".":n&&e===1?"//":o.slice(0,e)},basename(o,n){n!==void 0&&ct(n,"suffix"),ct(o,"path");let e=0,t=-1,r=!0,i;if(n!==void 0&&n.length>0&&n.length<=o.length){if(n===o)return"";let s=n.length-1,a=-1;for(i=o.length-1;i>=0;--i){let l=o.charCodeAt(i);if(l===Ot){if(!r){e=i+1;break}}else a===-1&&(r=!1,a=i+1),s>=0&&(l===n.charCodeAt(s)?--s===-1&&(t=i):(s=-1,t=a))}return e===t?t=a:t===-1&&(t=o.length),o.slice(e,t)}for(i=o.length-1;i>=0;--i)if(o.charCodeAt(i)===Ot){if(!r){e=i+1;break}}else t===-1&&(r=!1,t=i+1);return t===-1?"":o.slice(e,t)},extname(o){ct(o,"path");let n=-1,e=0,t=-1,r=!0,i=0;for(let s=o.length-1;s>=0;--s){let a=o[s];if(a==="/"){if(!r){e=s+1;break}continue}t===-1&&(r=!1,t=s+1),a==="."?n===-1?n=s:i!==1&&(i=1):n!==-1&&(i=-1)}return n===-1||t===-1||i===0||i===1&&n===t-1&&n===e+1?"":o.slice(n,t)},format:f_.bind(null,"/"),parse(o){ct(o,"path");let n={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return n;let e=o.charCodeAt(0)===Ot,t;e?(n.root="/",t=1):t=0;let r=-1,i=0,s=-1,a=!0,l=o.length-1,d=0;for(;l>=t;--l){let c=o.charCodeAt(l);if(c===Ot){if(!a){i=l+1;break}continue}s===-1&&(a=!1,s=l+1),c===ki?r===-1?r=l:d!==1&&(d=1):r!==-1&&(d=-1)}if(s!==-1){let c=i===0&&e?1:i;r===-1||d===0||d===1&&r===s-1&&r===i+1?n.base=n.name=o.slice(c,s):(n.name=o.slice(c,r),n.base=o.slice(c,s),n.ext=o.slice(r,s))}return i>0?n.dir=o.slice(0,i-1):e&&(n.dir="/"),n},sep:"/",delimiter:":",win32:null,posix:null};re.win32=ye.win32=ye;re.posix=ye.posix=re;var un=cn?ye.normalize:re.normalize,Wt=cn?ye.isAbsolute:re.isAbsolute,j=cn?ye.join:re.join,Fn=cn?ye.resolve:re.resolve,ep=cn?ye.relative:re.relative,oe=cn?ye.dirname:re.dirname,Te=cn?ye.basename:re.basename,Di=cn?ye.extname:re.extname,u$=cn?ye.format:re.format,g_=cn?ye.parse:re.parse,p$=cn?ye.toNamespacedPath:re.toNamespacedPath,Le=cn?ye.sep:re.sep,Hs=cn?ye.delimiter:re.delimiter;function zD(o){return o}var tp=class{constructor(n,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof n=="function"?(this._fn=n,this._computeKey=zD):(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 Be=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 S_(o){return!o||typeof o!="string"?!0:o.trim().length===0}var VD=/{(\d+)}/g;function Mi(o,...n){return n.length===0?o:o.replace(VD,function(e,t){let r=parseInt(t,10);return isNaN(r)||r<0||r>=n.length?e:n[r]})}var jD=/{([^}]+)}/g;function b_(o,n){return Object.keys(n).length===0?o:o.replace(jD,(e,t)=>n[t]??e)}function _n(o){return o.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function tr(o,n,e=ZD){return o.length<=n?o:`${o.substr(0,n)}${e}`}function $y(o,n){if(!o||!n)return o;let e=n.length,t=0;if(e===1){let r=n.charCodeAt(0);for(;t<o.length&&o.charCodeAt(t)===r;)t++}else for(;o.startsWith(n,t);)t+=e;return o.substring(t)}function $s(o,n){if(!o||!n)return o;let e=n.length,t=o.length;if(e===1){let i=t,s=n.charCodeAt(0);for(;i>0&&o.charCodeAt(i-1)===s;)i--;return o.substring(0,i)}let r=t;for(;r>0&&o.endsWith(n,r);)r-=e;return o.substring(0,r)}function C_(o){return o.source==="^"||o.source==="^$"||o.source==="$"||o.source==="^\\s*$"?!1:!!(o.exec("")&&o.lastIndex===0)}function I_(o){let n=[],e=o.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 Hn(o,n){return o<n?-1:o>n?1:0}function np(o,n,e=0,t=o.length,r=0,i=n.length){for(;e<t&&r<i;e++,r++){let l=o.charCodeAt(e),d=n.charCodeAt(r);if(l<d)return-1;if(l>d)return 1}let s=t-e,a=i-r;return s<a?-1:s>a?1:0}function Wy(o,n){return Oi(o,n,0,o.length,0,n.length)}function Oi(o,n,e=0,t=o.length,r=0,i=n.length){for(;e<t&&r<i;e++,r++){let l=o.charCodeAt(e),d=n.charCodeAt(r);if(l===d)continue;if(l>=128||d>=128)return np(o.toLowerCase(),n.toLowerCase(),e,t,r,i);m_(l)&&(l-=32),m_(d)&&(d-=32);let c=l-d;if(c!==0)return c}let s=t-e,a=i-r;return s<a?-1:s>a?1:0}function m_(o){return o>=97&&o<=122}function qy(o){return o>=65&&o<=90}function no(o,n){return o.length===n.length&&Oi(o,n)===0}function $o(o,n){let e=n.length;return e<=o.length&&Oi(o,n,0,e)===0}function __(o,n){let e=o.length,t=e-n.length;return t>=0&&Oi(o,n,t,e)===0}function T_(o){return 55296<=o&&o<=56319}function By(o){return 56320<=o&&o<=57343}function w_(o,n){return(o-55296<<10)+(n-56320)+65536}var KD=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,GD=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,JD=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,YD=new RegExp("(?:"+[KD.source,GD.source,JD.source].join("|")+")","g");function R_(o){return o&&(o=o.replace(YD,"")),o}var _$=String.fromCharCode(65279);function QD(o){return!!(o&&o.length>0&&o.charCodeAt(0)===65279)}function x_(o){return QD(o)?o.substr(1):o}var h_=class o{static{this._INSTANCE=null}static getInstance(){return o._INSTANCE||(o._INSTANCE=new o),o._INSTANCE}constructor(){this._data=XD()}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 XD(){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 y_=class o{constructor(n){this.confusableDictionary=n}static{this.ambiguousCharacterData=new Be(()=>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 tp(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[v,y]of p)m.set(v,y);return m}function i(u,p){if(!u)return p;let m=new Map;for(let[v,y]of u)p.has(v)&&m.set(v,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=i(l,p)}let d=t(s._common),c=r(d,l);return new o(c)})}static getInstance(n){return o.cache.get(Array.from(n).join(","))}static{this._locales=new Be(()=>Object.keys(o.ambiguousCharacterData.value).filter(n=>!n.startsWith("_")))}static getLocales(){return o._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())}},v_=class o{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(o.getRawData())].flat())),this._data}static isInvisibleCharacter(n){return o.getData().has(n)}static containsInvisibleCharacter(n){for(let e=0;e<n.length;e++){let t=n.codePointAt(e);if(typeof t=="number"&&(o.isInvisibleCharacter(t)||t===32))return!0}return!1}static get codePoints(){return o.getData()}},ZD="\u2026";function Wo(o){return o===47||o===92}function rp(o){return o.replace(/[\\/]/g,re.sep)}function P_(o){return o.indexOf("/")===-1&&(o=rp(o)),/^[a-zA-Z]:(\/|$)/.test(o)&&(o="/"+o),o}function Vy(o,n=re.sep){if(!o)return"";let e=o.length,t=o.charCodeAt(0);if(Wo(t)){if(Wo(o.charCodeAt(1))&&!Wo(o.charCodeAt(2))){let i=3,s=i;for(;i<e&&!Wo(o.charCodeAt(i));i++);if(s!==i&&!Wo(o.charCodeAt(i+1))){for(i+=1;i<e;i++)if(Wo(o.charCodeAt(i)))return o.slice(0,i+1).replace(/[\\/]/g,n)}}return n}else if(A_(t)&&o.charCodeAt(1)===58)return Wo(o.charCodeAt(2))?o.slice(0,2)+n:o.slice(0,2);let r=o.indexOf("://");if(r!==-1){for(r+=3;r<e;r++)if(Wo(o.charCodeAt(r)))return o.slice(0,r+1)}return""}function Ws(o,n,e){let t=o===n;return!e||t?t:!o||!n?!1:no(o,n)}function ro(o,n,e,t=!1){let r=t?re.sep:Le;if(o===n)return!0;if(!o||!n||((o.indexOf("..")>=0||n.indexOf("..")>=0)&&(o=t?re.normalize(o):un(o),n=t?re.normalize(n):un(n)),n.length>o.length))return!1;if(e){if(!$o(o,n))return!1;if(n.length===o.length)return!0;let s=n.length;return n.charAt(n.length-1)===r&&s--,o.charAt(s)===r}return n.charAt(n.length-1)!==r&&(n+=r),o.indexOf(n)===0}function A_(o){return o>=65&&o<=90||o>=97&&o<=122}function E_(o){return Q?(o=$s(o,Le),o.endsWith(":")&&(o+=Le)):(o=$s(o,Le),o||(o=Le)),o}function jy(o){let n=un(o);return Q?o.length>3?!1:k_(n)&&(o.length===2||n.charCodeAt(2)===92):n===re.sep}function k_(o,n=Q){return n?A_(o.charCodeAt(0))&&o.charCodeAt(1)===58:!1}var eM="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",tM="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function D_(o,n,e=8){let t="";for(let i=0;i<e;i++){let s;i===0&&Q&&!n&&(e===3||e===4)?s=tM:s=eM,t+=s.charAt(Math.floor(Math.random()*s.length))}let r;return n?r=`${n}-${t}`:r=t,o?j(o,r):r}var rM=/^\w[\w\d+.-]*$/,oM=/^\//,iM=/^\/\//;function sM(o,n){if(!o.scheme&&n)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${o.authority}", path: "${o.path}", query: "${o.query}", fragment: "${o.fragment}"}`);if(o.scheme&&!rM.test(o.scheme)){let e=[...o.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:${o.scheme.length})`)}if(o.path){if(o.authority){if(!oM.test(o.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(iM.test(o.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function aM(o,n){return!o&&!n?"file":o}function lM(o,n){switch(o){case"https":case"http":case"file":n?n[0]!==nr&&(n=nr+n):n=nr;break}return n}var je="",nr="/",dM=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,h=class o{static isUri(n){return n instanceof o?!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,i,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=aM(n,s),this.authority=e||je,this.path=lM(this.scheme,t||je),this.query=r||je,this.fragment=i||je,sM(this,s))}get fsPath(){return Sd(this,!1)}with(n){if(!n)return this;let{scheme:e,authority:t,path:r,query:i,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),i===void 0?i=this.query:i===null&&(i=je),s===void 0?s=this.fragment:s===null&&(s=je),e===this.scheme&&t===this.authority&&r===this.path&&i===this.query&&s===this.fragment?this:new qo(e,t,r,i,s)}static parse(n,e=!1){let t=dM.exec(n);return t?new qo(t[2]||je,op(t[4]||je),op(t[5]||je),op(t[7]||je),op(t[9]||je),e):new qo(je,je,je,je,je)}static file(n){let e=je;if(Q&&(n=n.replace(/\\/g,nr)),n[0]===nr&&n[1]===nr){let t=n.indexOf(nr,2);t===-1?(e=n.substring(2),n=nr):(e=n.substring(2,t),n=n.substring(t)||nr)}return new qo("file",e,n,je,je)}static from(n,e){return new qo(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=o.file(ye.join(Sd(n,!0),...e)).path:t=re.join(n.path,...e),n.with({path:t})}toString(n=!1){return Ky(this,n)}toJSON(){return this}static revive(n){if(n){if(n instanceof o)return n;{let e=new qo(n);return e._formatted=n.external??null,e._fsPath=n._sep===N_?n.fsPath??null:null,e}}else return n}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};function L_(o){return!o||typeof o!="object"?!1:typeof o.scheme=="string"&&(typeof o.authority=="string"||typeof o.authority>"u")&&(typeof o.path=="string"||typeof o.path>"u")&&(typeof o.query=="string"||typeof o.query>"u")&&(typeof o.fragment=="string"||typeof o.fragment>"u")}var N_=Q?1:void 0,qo=class extends h{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=Sd(this,!1)),this._fsPath}toString(e=!1){return e?Ky(this,!0):(this._formatted||(this._formatted=Ky(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=N_),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}},U_={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 M_(o,n,e){let t,r=-1;for(let i=0;i<o.length;i++){let s=o.charCodeAt(i);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(o.substring(r,i)),r=-1),t!==void 0&&(t+=o.charAt(i));else{t===void 0&&(t=o.substr(0,i));let a=U_[s];a!==void 0?(r!==-1&&(t+=encodeURIComponent(o.substring(r,i)),r=-1),t+=a):r===-1&&(r=i)}}return r!==-1&&(t+=encodeURIComponent(o.substring(r))),t!==void 0?t:o}function cM(o){let n;for(let e=0;e<o.length;e++){let t=o.charCodeAt(e);t===35||t===63?(n===void 0&&(n=o.substr(0,e)),n+=U_[t]):n!==void 0&&(n+=o[e])}return n!==void 0?n:o}function Sd(o,n){let e;return o.authority&&o.path.length>1&&o.scheme==="file"?e=`//${o.authority}${o.path}`:o.path.charCodeAt(0)===47&&(o.path.charCodeAt(1)>=65&&o.path.charCodeAt(1)<=90||o.path.charCodeAt(1)>=97&&o.path.charCodeAt(1)<=122)&&o.path.charCodeAt(2)===58?n?e=o.path.substr(1):e=o.path[1].toLowerCase()+o.path.substr(2):e=o.path,Q&&(e=e.replace(/\//g,"\\")),e}function Ky(o,n){let e=n?cM:M_,t="",{scheme:r,authority:i,path:s,query:a,fragment:l}=o;if(r&&(t+=r,t+=":"),(i||r==="file")&&(t+=nr,t+=nr),i){let d=i.indexOf("@");if(d!==-1){let c=i.substr(0,d);i=i.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+="@"}i=i.toLowerCase(),d=i.lastIndexOf(":"),d===-1?t+=e(i,!1,!0):(t+=e(i.substr(0,d),!1,!0),t+=i.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:M_(l,!1,!1)),t}function F_(o){try{return decodeURIComponent(o)}catch{return o.length>3?o.substr(0,3)+F_(o.substr(3)):o}}var O_=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function op(o){return o.match(O_)?o.replace(O_,n=>F_(n)):o}var ne;(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"))(ne||={});var Qy="tkn",Jy=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??"/",pM(n))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return re.join(this._serverRootPath,ne.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 wI(a),n}let e=n.authority,t=this._hosts[e];t&&t.indexOf(":")!==-1&&t.indexOf("[")===-1&&(t=`[${t}]`);let r=this._ports[e],i=this._connectionTokens[e],s=`path=${encodeURIComponent(n.path)}`;return typeof i=="string"&&(s+=`&${Qy}=${encodeURIComponent(i)}`),h.from({scheme:Nn?this._preferredWebSchema:ne.vscodeRemoteResource,authority:`${t}:${r}`,path:Nn?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},uM=new Jy;function pM(o){return`${o.quality??"oss"}-${o.commit??"dev"}`}var ip="vs/../../node_modules",H_="vs/../../node_modules.asar",$_="vs/../../node_modules.asar.unpacked",Xy="vscode-app",Yy=class o{static{this.FALLBACK_AUTHORITY=Xy}asBrowserUri(n){let e=this.toUri(n);return this.uriToBrowserUri(e)}uriToBrowserUri(n){return n.scheme===ne.vscodeRemote?uM.rewrite(n):n.scheme===ne.file&&(XI||e_===`${ne.vscodeFileResource}://${o.FALLBACK_AUTHORITY}`)?n.with({scheme:ne.vscodeFileResource,authority:n.authority||o.FALLBACK_AUTHORITY,query:null,fragment:null}):n}asFileUri(n){let e=this.toUri(n);return this.uriToFileUri(e)}uriToFileUri(n){return n.scheme===ne.vscodeFileResource?n.with({scheme:ne.file,authority:n.authority!==o.FALLBACK_AUTHORITY?n.authority:null,query:null,fragment:null}):n}toUri(n){if(h.isUri(n))return n;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return h.joinPath(h.parse(e,!0),n);let t=j(e,n);return h.file(t)}throw new Error("Cannot determine URI for module id!")}},Lt=new Yy,N$=Object.freeze({"Cache-Control":"no-cache, no-store"}),U$=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),fM;(i=>{let o=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"}]]);i.CoopAndCoep=Object.freeze(o.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:h.isUri(s)&&(a=new URL(s.toString(!0)).searchParams);let l=a?.get(e);if(l)return o.get(l)}i.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}i.addSearchParam=r})(fM||={});function oo(o){return Sd(o,!0)}var Li=class{constructor(n){this._ignorePathCasing=n}compare(n,e,t=!1){return n===e?0:Hn(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===ne.file)return ro(oo(n),oo(e),this._ignorePathCasing(n))&&n.query===e.query&&(t||n.fragment===e.fragment);if(W_(n.authority,e.authority))return ro(n.path,e.path,this._ignorePathCasing(n),!0)&&n.query===e.query&&(t||n.fragment===e.fragment)}return!1}joinPath(n,...e){return h.joinPath(n,...e)}basenameOrAuthority(n){return ve(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===ne.file?e=h.file(oe(oo(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===ne.file?e=h.file(un(oo(n))).path:e=re.normalize(n.path),n.with({path:e})}relativePath(n,e){if(n.scheme!==e.scheme||!W_(n.authority,e.authority))return;if(n.scheme===ne.file){let i=ep(oo(n),oo(e));return Q?rp(i):i}let t=n.path||"/",r=e.path||"/";if(this._ignorePathCasing(n)){let i=0;for(let s=Math.min(t.length,r.length);i<s&&!(t.charCodeAt(i)!==r.charCodeAt(i)&&t.charAt(i).toLowerCase()!==r.charAt(i).toLowerCase());i++);t=r.substr(0,i)+t.substr(i)}return re.relative(t,r)}resolvePath(n,e){if(n.scheme===ne.file){let t=h.file(Fn(oo(n),e));return n.with({authority:t.authority,path:t.path})}return e=P_(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&&no(n,e)}hasTrailingPathSeparator(n,e=Le){if(n.scheme===ne.file){let t=oo(n);return t.length>Vy(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 q_(n,e)?n.with({path:n.path.substr(0,n.path.length-1)}):n}addTrailingPathSeparator(n,e=Le){let t=!1;if(n.scheme===ne.file){let r=oo(n);t=r!==void 0&&r.length===Vy(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&&!q_(n,e)?n.with({path:n.path+"/"}):n}},me=new Li(()=>!1),nt=new Li(o=>o.scheme===ne.file?!Oe:!0),Zy=new Li(o=>!0),Tr=me.isEqual.bind(me),io=me.isEqualOrParent.bind(me),z$=me.getComparisonKey.bind(me),V$=me.basenameOrAuthority.bind(me),ve=me.basename.bind(me),bd=me.extname.bind(me),Tn=me.dirname.bind(me),te=me.joinPath.bind(me),wn=me.normalizePath.bind(me),so=me.relativePath.bind(me),j$=me.resolvePath.bind(me),B_=me.isAbsolutePath.bind(me),W_=me.isEqualAuthority.bind(me),q_=me.hasTrailingPathSeparator.bind(me),K$=me.removeTrailingPathSeparator.bind(me),G$=me.addTrailingPathSeparator.bind(me);var gM;(i=>{i.META_DATA_LABEL="label",i.META_DATA_DESCRIPTION="description",i.META_DATA_SIZE="size",i.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(i.META_DATA_MIME,d),a}i.parseMetaData=r})(gM||={});var z_=Symbol("MicrotaskDelay");function fp(o){return!!o&&typeof o.then=="function"}function jo(o){let n=new Ze,e=o(n.token),t=!1,r=new Promise((i,s)=>{let a=n.token.onCancellationRequested(()=>{t=!0,a.dispose(),s(new K)});Promise.resolve(e).then(l=>{a.dispose(),n.dispose(),t?Os(l)&&l.dispose():i(l)},l=>{a.dispose(),n.dispose(),s(l)})});return new class{cancel(){n.cancel(),n.dispose()}then(i,s){return r.then(i,s)}catch(i){return this.then(void 0,i)}finally(i){return r.finally(i)}}}function gp(o,n){return new Promise((e,t)=>{let r=n.onCancellationRequested(()=>{r.dispose(),t(new K)});o.then(e,t).finally(()=>r.dispose())})}function K_(o){let n=-1,e=o.map((r,i)=>r.then(s=>(n=i,s))),t=Promise.race(e);return t.cancel=()=>{o.forEach((r,i)=>{i!==n&&r.cancel&&r.cancel()})},t.finally(()=>{t.cancel()}),t}function G_(o,n,e){let t,r=setTimeout(()=>{t?.(void 0),e?.()},n);return Promise.race([o.finally(()=>clearTimeout(r)),new Promise(i=>t=i)])}var ap=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 lp=class{constructor(){this.throttlers=new Map}queue(n,e){let t=this.throttlers.get(n);return t||(t={throttler:new ap,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()}},hM=(o,n)=>{let e=!0,t=setTimeout(()=>{e=!1,n()},o);return{isTriggered:()=>e,dispose:()=>{clearTimeout(t),e=!1}}},yM=o=>{let n=!0;return queueMicrotask(()=>{n&&(n=!1,o())}),{isTriggered:()=>n,dispose:()=>{n=!1}}},Ni=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,i)=>{this.doResolve=r,this.doReject=i}).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===z_?yM(t):hM(e,t),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&(this.doReject?.(new K),this.completionPromise=null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}},Ui=class{constructor(n){this.delayer=new Ni(n),this.throttler=new ap}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()}},dp=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 Zt(o,n){return n?new Promise((e,t)=>{let r=setTimeout(()=>{i.dispose(),e()},o),i=n.onCancellationRequested(()=>{clearTimeout(r),i.dispose(),t(new K)})}):jo(e=>Zt(o,e))}function qt(o,n=0,e){let t=setTimeout(()=>{o(),e&&r.dispose()},n),r=N(()=>{clearTimeout(t),e?.delete(r)});return e?.add(r),r}var lW=2**31-1;var Bo=class{constructor(n){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=n,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new A}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()}},zo=class extends Bo{constructor(){super(1)}};var qs=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=me){let t=e.getComparisonKey(n);return this.queues.get(t)?.size??0}queueFor(n,e,t=me){let r=t.getComparisonKey(n),i=this.queues.get(r);if(!i){i=new zo;let s=this.drainListenerCount++,a=ee.once(i.onDrained)(()=>{i?.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 we),this.drainListeners.set(s,a),this.queues.set(r,i)}return i.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 cp=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 We("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 We("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===void 0&&(this._token=setTimeout(()=>{this._token=void 0,n()},e))}};var Vo=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 up=class extends Vo{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()}},Bs=class extends w{constructor(e,t){super();this.options=e;this.handler=t;this.pendingWork=[];this.throttler=this._register(new Dt);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 Vo(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},vM,sp;(function(){let o=globalThis;typeof o.requestIdleCallback!="function"||typeof o.cancelIdleCallback!="function"?sp=(n,e,t)=>{t_(()=>{if(r)return;let i=Date.now()+15;e(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,i-Date.now())}}))});let r=!1;return{dispose(){r||(r=!0)}}}:sp=(n,e,t)=>{let r=n.requestIdleCallback(e,typeof t=="number"?{timeout:t}:void 0),i=!1;return{dispose(){i||(i=!0,n.cancelIdleCallback(r))}}},vM=(n,e)=>sp(globalThis,n,e)})();var ev=class{constructor(n,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(t){this._error=t}finally{this._didRun=!0}},this._handle=sp(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}},pp=class extends ev{constructor(n){super(globalThis,n)}};async function J_(o,n,e){let t;for(let r=0;r<e;r++)try{return await o()}catch(i){t=i,await Zt(n)}throw t}var Ee=class o{static fromPromise(n){let e=new o;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 K)}},rr;(e=>{async function o(t){let r,i=await Promise.all(t.map(s=>s.then(a=>a,a=>{r||(r=a)})));if(typeof r<"u")throw r;return i}e.settled=o;function n(t){return new Promise(async(r,i)=>{try{await t(r,i)}catch(s){i(s)}})}e.withAsyncBody=n})(rr||={});var V_=class o{static fromArray(n){return new o(e=>{e.emitMany(n)})}static fromPromise(n){return new o(async e=>{e.emitMany(await n)})}static fromPromisesResolveOrder(n){return new o(async e=>{await Promise.all(n.map(async t=>e.emitOne(await t)))})}static merge(n){return new o(async e=>{await Promise.all(n.map(async t=>{for await(let r of t)e.emitOne(r)}))})}static{this.EMPTY=o.fromArray([])}constructor(n,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new A,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 o(async t=>{for await(let r of n)t.emitOne(e(r))})}map(n){return o.map(this,n)}static filter(n,e){return new o(async t=>{for await(let r of n)e(r)&&t.emitOne(r)})}filter(n){return o.filter(this,n)}static coalesce(n){return o.filter(n,e=>!!e)}coalesce(){return o.coalesce(this)}static async toPromise(n){let e=[];for await(let t of n)e.push(t);return e}toPromise(){return o.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 tv=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 We("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}}},j_=class o{constructor(n,e){this._onReturn=e;this._producerConsumer=new tv;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 i of r)this._producerConsumer.produce({ok:!0,value:{done:!1,value:i}})},reject:r=>this._finishError(r)});if(!this._producerConsumer.hasFinalValue)try{await t,this._finishOk()}catch(r){this._finishError(r)}})}static fromArray(n){return new o(e=>{e.emitMany(n)})}static fromPromise(n){return new o(async e=>{e.emitMany(await n)})}static fromPromisesResolveOrder(n){return new o(async e=>{await Promise.all(n.map(async t=>e.emitOne(await t)))})}static merge(n){return new o(async e=>{await Promise.all(n.map(async t=>{for await(let r of t)e.emitOne(r)}))})}static{this.EMPTY=o.fromArray([])}static map(n,e){return new o(async t=>{for await(let r of n)t.emitOne(e(r))})}static tee(n){let e,t,r=new Ee,i=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 o(async l=>(e=l,i(),r.p)),a=new o(async l=>(t=l,i(),r.p));return[s,a]}map(n){return o.map(this,n)}static coalesce(n){return o.filter(n,e=>!!e)}coalesce(){return o.coalesce(this)}static filter(n,e){return new o(async t=>{for await(let r of n)e(r)&&t.emitOne(r)})}filter(n){return o.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 Cd(o){let n=o;return n?[n.on,n.pause,n.resume,n.destroy].every(e=>typeof e=="function"):!1}function mp(o){let n=o;return n?Cd(n.stream)&&Array.isArray(n.buffer)&&typeof n.ended=="boolean":!1}function ao(o,n){return new nv(o,n)}var nv=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 Y_(o,n){let e=[],t;for(;(t=o.read())!==null;)e.push(t);return n(e)}function Q_(o,n,e){let t=[],r;for(;(r=o.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 i=r;return r=void 0,i}return o.read()}}}function hp(o,n){return new Promise((e,t)=>{let r=[];yp(o,{onData:i=>{n&&r.push(i)},onError:i=>{n?t(i):e(void 0)},onEnd:()=>{e(n?n(r):void 0)}})})}function yp(o,n,e){o.on("error",t=>{e?.isCancellationRequested||n.onError(t)}),o.on("end",()=>{e?.isCancellationRequested||n.onEnd()}),o.on("data",t=>{e?.isCancellationRequested||n.onData(t)})}function X_(o,n){return new Promise((e,t)=>{let r=new Y,i=[],s=d=>{if(i.push(d),i.length>n)return r.dispose(),o.pause(),e({stream:o,buffer:i,ended:!1})},a=d=>(r.dispose(),t(d)),l=()=>(r.dispose(),e({stream:o,buffer:i,ended:!0}));r.add(N(()=>o.removeListener("error",a))),o.on("error",a),r.add(N(()=>o.removeListener("end",l))),o.on("end",l),r.add(N(()=>o.removeListener("data",s))),o.on("data",s)})}function Z_(o){let n=!1;return{read:()=>n?null:(n=!0,o)}}function vp(o,n,e){let t=ao(e);return yp(o,{onData:r=>t.write(n.data(r)),onError:r=>t.error(n.error?n.error(r):r),onEnd:()=>t.end()}),t}var Id=typeof Buffer<"u",bM=new Be(()=>new Uint8Array(256)),rv,ov,F=class o{static alloc(n){return Id?new o(Buffer.allocUnsafe(n)):new o(new Uint8Array(n))}static wrap(n){return Id&&!Buffer.isBuffer(n)&&(n=Buffer.from(n.buffer,n.byteOffset,n.byteLength)),new o(n)}static fromString(n,e){return!(e?.dontUseNodeBuffer||!1)&&Id?new o(Buffer.from(n)):(rv||(rv=new TextEncoder),new o(rv.encode(n)))}static fromByteArray(n){let e=o.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 i=0,s=n.length;i<s;i++)e+=n[i].byteLength}let t=o.alloc(e),r=0;for(let i=0,s=n.length;i<s;i++){let a=n[i];t.set(a,r),r+=a.byteLength}return t}static isNativeBuffer(n){return Id&&Buffer.isBuffer(n)}constructor(n){this.buffer=n,this.byteLength=this.buffer.byteLength}clone(){let n=o.alloc(this.byteLength);return n.set(this),n}toString(){return Id?this.buffer.toString():(ov||(ov=new TextDecoder(void 0,{ignoreBOM:!0})),ov.decode(this.buffer))}slice(n,e){return new o(this.buffer.subarray(n,e))}set(n,e){if(n instanceof o)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 IM(this.buffer,n)}writeUInt32BE(n,e){_M(this.buffer,n,e)}readUInt32LE(n){return TM(this.buffer,n)}writeUInt32LE(n,e){wM(this.buffer,n,e)}readUInt8(n){return RM(this.buffer,n)}writeUInt8(n,e){xM(this.buffer,n,e)}indexOf(n,e=0){return CM(this.buffer,n instanceof o?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 CM(o,n,e=0){let t=n.byteLength,r=o.byteLength;if(t===0)return 0;if(t===1)return o.indexOf(n[0],e);if(t>r-e)return-1;let i=bM.value;i.fill(n.length);for(let d=0;d<n.length;d++)i[n[d]]=n.length-d-1;let s=e+n.length-1,a=s,l=-1;for(;s<r;)if(o[s]===n[a]){if(a===0){l=s;break}s--,a--}else s+=Math.max(n.length-a,i[o[s]]),a=n.length-1;return l}function IM(o,n){return o[n]*2**24+o[n+1]*2**16+o[n+2]*2**8+o[n+3]}function _M(o,n,e){o[e+3]=n,n=n>>>8,o[e+2]=n,n=n>>>8,o[e+1]=n,n=n>>>8,o[e]=n}function TM(o,n){return o[n+0]<<0>>>0|o[n+1]<<8>>>0|o[n+2]<<16>>>0|o[n+3]<<24>>>0}function wM(o,n,e){o[e+0]=n&255,n=n>>>8,o[e+1]=n&255,n=n>>>8,o[e+2]=n&255,n=n>>>8,o[e+3]=n&255}function RM(o,n){return o[n]}function xM(o,n,e){o[e]=n}function nT(o){return Y_(o,n=>F.concat(n))}function rT(o){return Z_(o)}function wr(o){return hp(o,n=>F.concat(n))}async function oT(o){return o.ended?F.concat(o.buffer):F.concat([...o.buffer,await wr(o.stream)])}function iT(o){return vp(o,{data:n=>typeof n=="string"?F.fromString(n):F.wrap(n)},n=>F.concat(n))}function _d(o){return ao(n=>F.concat(n),o)}function pn(o){let n=0,e=0,t=0,r=new Uint8Array(Math.floor(o.length/4*3)),i=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<o.length;a++){let l=o.charCodeAt(a);if(l>=65&&l<=90)i(l-65);else if(l>=97&&l<=122)i(l-97+26);else if(l>=48&&l<=57)i(l-48+52);else if(l===43||l===45)i(62);else if(l===47||l===95)i(63);else{if(l===61)break;throw new SyntaxError(`Unexpected base64 character ${o[a]}`)}}let s=t;for(;e>0;)i(0);return F.wrap(r).slice(0,s)}var PM="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",AM="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function or({buffer:o},n=!0,e=!1){let t=e?AM:PM,r="",i=o.byteLength%3,s=0;for(;s<o.byteLength-i;s+=3){let a=o[s+0],l=o[s+1],d=o[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(i===1){let a=o[s+0];r+=t[a>>>2],r+=t[a<<4&63],n&&(r+="==")}else if(i===2){let a=o[s+0],l=o[s+1];r+=t[a>>>2],r+=t[(a<<4|l>>>4)&63],r+=t[l<<2&63],n&&(r+="=")}return r}var eT="0123456789abcdef";function Ko({buffer:o}){let n="";for(let e=0;e<o.length;e++){let t=o[e];n+=eT[t>>>4],n+=eT[t&15]}return n}function iv(o){if(o.length%2!==0)throw new SyntaxError("Hex string must have an even length");let n=new Uint8Array(o.length>>1);for(let e=0;e<o.length;)n[e>>1]=tT(o,e++)<<4|tT(o,e++);return F.wrap(n)}function tT(o,n){let e=o.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 Ce(o,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 i=`$memoize$${n}`;e[t]=function(...s){return this.hasOwnProperty(i)||Object.defineProperty(this,i,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,s)}),this[i]}}function Td(o,n=0){if(!o||n>200)return o;if(typeof o=="object"){switch(o.$mid){case 1:return h.revive(o);case 2:return new RegExp(o.source,o.flags);case 17:return new Date(o.source)}if(o instanceof F||o instanceof Uint8Array)return o;if(Array.isArray(o))for(let e=0;e<o.length;++e)o[e]=Td(o[e],n+1);else for(let e in o)Object.hasOwnProperty.call(o,e)&&(o[e]=Td(o[e],n+1))}return o}function js(o){switch(o){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function Sp(o){switch(o){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function zs(o){let n=0;for(let e=0;;e+=7){let t=o.read(1);if(n|=(t.buffer[0]&127)<<e,!(t.buffer[0]&128))return n}}var EM=Go(0);function Vs(o,n){if(n===0){o.write(EM);return}let e=0;for(let r=n;r!==0;r=r>>>7)e++;let t=F.alloc(e);for(let r=0;n!==0;r++)t.buffer[r]=n&127,n=n>>>7,n>0&&(t.buffer[r]|=128);o.write(t)}var wd=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}},bp=class{constructor(){this.buffers=[]}get buffer(){return F.concat(this.buffers)}write(n){this.buffers.push(n)}dispose(){this.buffers.length=0}};function Go(o){let n=F.alloc(1);return n.writeUInt8(o,0),n}var Fi={Undefined:Go(0),String:Go(1),Buffer:Go(2),VSBuffer:Go(3),Array:Go(4),Object:Go(5),Uint:Go(6)};function Rd(o,n){if(typeof n>"u")o.write(Fi.Undefined);else if(typeof n=="string"){let e=F.fromString(n);o.write(Fi.String),Vs(o,e.byteLength),o.write(e)}else if(F.isNativeBuffer(n)){let e=F.wrap(n);o.write(Fi.Buffer),Vs(o,e.byteLength),o.write(e)}else if(n instanceof F)o.write(Fi.VSBuffer),Vs(o,n.byteLength),o.write(n);else if(Array.isArray(n)){o.write(Fi.Array),Vs(o,n.length);for(let e of n)Rd(o,e)}else if(typeof n=="number"&&(n|0)===n)o.write(Fi.Uint),Vs(o,n);else{let e=F.fromString(JSON.stringify(n));o.write(Fi.Object),Vs(o,e.byteLength),o.write(e)}}function Gs(o){switch(o.read(1).readUInt8(0)){case 0:return;case 1:return o.read(zs(o)).toString();case 2:return o.read(zs(o)).buffer;case 3:return o.read(zs(o));case 4:{let e=zs(o),t=[];for(let r=0;r<e;r++)t.push(Gs(o));return t}case 5:return JSON.parse(o.read(zs(o)).toString());case 6:return zs(o)}}var xd=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(i=>this.onRawMessage(i)),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,Sp(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,Sp(n.type),n.data);return}}}send(n,e=void 0){let t=new bp;try{return Rd(t,n),Rd(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 wd(n),t=Gs(e),r=Gs(e),i=t[0];switch(i){case 100:return this.logger?.logIncoming(n.byteLength,t[1],1,`${js(i)}: ${t[2]}.${t[3]}`,r),this.onPromise({type:i,id:t[1],channelName:t[2],name:t[3],arg:r});case 102:return this.logger?.logIncoming(n.byteLength,t[1],1,`${js(i)}: ${t[2]}.${t[3]}`,r),this.onEventListen({type:i,id:t[1],channelName:t[2],name:t[3],arg:r});case 101:return this.logger?.logIncoming(n.byteLength,t[1],1,`${js(i)}`),this.disposeActiveRequest({type:i,id:t[1]});case 103:return this.logger?.logIncoming(n.byteLength,t[1],1,`${js(i)}`),this.disposeActiveRequest({type:i,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 i=n.id;r.then(a=>{this.sendResponse({id:i,data:a,type:201})},a=>{a instanceof Error?this.sendResponse({id:i,data:{message:a.message,name:a.name,stack:a.stack?a.stack.split(`
`):void 0},type:202}):this.sendResponse({id:i,data:a,type:203})}).finally(()=>{s.dispose(),this.activeRequests.delete(n.id)});let s=N(()=>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,i=e.listen(this.ctx,n.name,n.arg)(s=>this.sendResponse({id:t,data:s,type:204}));this.activeRequests.set(n.id,i)}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),Gt(this.activeRequests.values()),this.activeRequests.clear()}};var Ks=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 A;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,i){return e.isDisposed?Promise.reject(new K):e.requestPromise(n,t,r,i)},listen(t,r){return e.isDisposed?ee.None:e.requestEvent(n,t,r)}}}requestPromise(n,e,t,r=Re.None){let i=this.lastRequestId++,a={id:i,type:100,channelName:n,name:e,arg:t};if(r.isCancellationRequested)return Promise.reject(new K);let l,d;return new Promise((u,p)=>{if(r.isCancellationRequested)return p(new K);let m=()=>{let S=b=>{switch(b.type){case 201:this.handlers.delete(i),u(b.data);break;case 202:{this.handlers.delete(i);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(i),p(b.data);break}};this.handlers.set(i,S);try{this.sendRequest(a)}catch(b){this.handlers.delete(i),p(b)}},v=null;this.state===1?m():(v=jo(S=>this.whenInitialized()),v.then(()=>{v=null,m()}));let y=()=>{v?(v.cancel(),v=null):this.sendRequest({id:i,type:101}),p(new K)};l=r.onCancellationRequested(y),d={dispose:Ps(()=>{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 A({onWillAddFirstListener:()=>{let d=u=>l.fire(u.data);this.handlers.set(r,d);let c=()=>{this.activeRequests.add(l),this.sendRequest(s)};this.state===1?c():(a=jo(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)}});return 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,`${js(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,js(n.type));return}}}send(n,e=void 0){let t=new bp;try{return Rd(t,n),Rd(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 wd(n),t=Gs(e),r=Gs(e),i=t[0];switch(i){case 200:return this.logger?.logIncoming(n.byteLength,0,0,Sp(i)),this.onResponse({type:t[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(n.byteLength,t[1],0,Sp(i),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),Gt(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};R([Ce],Ks.prototype,"onDidInitializePromise",1);var Cp=class{constructor(n,e,t){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new A;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new A;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new Y;this.disposables.add(n(({protocol:r,onDidClientDisconnect:i})=>{let s=ee.once(r.onMessage),a=new Y,l=s(d=>{let c=new wd(d),u=Gs(c),p=new xd(r,u,e,t),m=new Ks(r,e);this.channels.forEach((y,S)=>p.registerChannel(S,y));let v={channelServer:p,channelClient:m,ctx:u};this._connections.add(v),this._onDidAddConnection.fire(v),a.add(i(()=>{p.dispose(),m.dispose(),this._connections.delete(v),this._onDidRemoveConnection.fire(v),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,i,s){let a;if(pd(e)){let d=PI(t.connections.filter(e));a=d?Promise.resolve(d):ee.toPromise(ee.filter(t.onDidAddConnection,e))}else a=e.routeCall(t,r,i);let l=a.then(d=>d.channelClient.getChannel(n));return sT(l).call(r,i,s)},listen(r,i){if(pd(e))return t.getMulticastEvent(n,e,r,i);let s=e.routeEvent(t,r,i).then(a=>a.channelClient.getChannel(n));return sT(s).listen(r,i)}}}getMulticastEvent(n,e,t,r){let i=this,s,a=new A({onWillAddFirstListener:()=>{s=new Y;let l=new Qu,d=new Map,c=p=>{let v=p.channelClient.getChannel(n).listen(t,r),y=l.add(v);d.set(p,y)},u=p=>{let m=d.get(p);m&&(m.dispose(),d.delete(p))};i.connections.filter(e).forEach(c),ee.filter(i.onDidAddConnection,e)(c,void 0,s),i.onDidRemoveConnection(u,void 0,s),l.event(a.fire,a,s),s.add(l)},onDidRemoveLastListener:()=>{s?.dispose(),s=void 0}});return i.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 sT(o){return{call(n,e,t){return o.then(r=>r.call(n,e,t))},listen(n,e){let t=new vd;return o.then(r=>t.input=r.listen(n,e)),t.event}}}function aT(o){let n=!1;return{call(e,t,r){return n?o.call(e,t,r):Zt(0).then(()=>n=!0).then(()=>o.call(e,t,r))},listen(e,t){if(n)return o.listen(e,t);let r=new vd;return Zt(0).then(()=>n=!0).then(()=>r.input=o.listen(e,t)),r.event}}}var Js;(r=>{function o(i,s,a){let l=i,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 v=c.get(p);if(v)return v;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 Cr(`Event not found: ${p}`)}call(u,p,m){let v=l[p];if(typeof v=="function"){if(!d&&Array.isArray(m))for(let S=0;S<m.length;S++)m[S]=Td(m[S]);let y=v.apply(l,m);return y instanceof Promise||(y=Promise.resolve(y)),y}throw new Cr(`Method not found: ${p}`)}}}r.fromService=o;function n(i,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 i.listen(d,c)}:e(d)?i.listen(d):async function(...c){let u;s&&!er(s.context)?u=[s.context,...c]:u=c;let p=await i.call(d,u);return a?p:Td(p)};throw new Cr(`Property not found: ${String(d)}`)}})}r.toService=n;function e(i){return i[0]==="o"&&i[1]==="n"&&qy(i.charCodeAt(2))}function t(i){return/^onDynamic/.test(i)&&qy(i.charCodeAt(9))}})(Js||={});import{fork as oO}from"child_process";function lT(o){let n=o;return n&&typeof n.type=="string"&&typeof n.severity=="string"}function kM(o){let n=[],e;try{let t=JSON.parse(o.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",o.arguments)}return{args:n,stack:e}}function DM(o){if(!o)return o;let n=o.indexOf(`
`);return n===-1?o:o.substring(0,n)}function dT(o,n){let{args:e,stack:t}=kM(o),r=typeof e[0]=="string"&&e.length===1,i=DM(t);i&&(i=`(${i.trim()})`);let s=[];if(typeof e[0]=="string"?i&&r?s=[`%c[${n}] %c${e[0]} %c${i}`,Ys("blue"),Ys(""),Ys("grey")]:s=[`%c[${n}] %c${e[0]}`,Ys("blue"),Ys(""),...e.slice(1)]:s=[`%c[${n}]%`,Ys("blue"),...e],i&&!r&&s.push(i),typeof console[o.severity]!="function")throw new Error("Unknown console method");console[o.severity].apply(console,s)}function Ys(o){return`color: ${o}`}function $n(o){if(!o||typeof o!="object"||o instanceof RegExp)return o;let n=Array.isArray(o)?[]:{};return Object.entries(o).forEach(([e,t])=>{n[e]=t&&typeof t=="object"?$n(t):t}),n}function cT(o){if(!o||typeof o!="object")return o;let n=[o];for(;n.length>0;){let e=n.shift();Object.freeze(e);for(let t in e)if(uT.call(e,t)){let r=e[t];typeof r=="object"&&!Object.isFrozen(r)&&!HI(r)&&n.push(r)}}return o}var uT=Object.prototype.hasOwnProperty;function Pd(o,n){return sv(o,n,new Set)}function sv(o,n,e){if(er(o))return o;let t=n(o);if(typeof t<"u")return t;if(Array.isArray(o)){let r=[];for(let i of o)r.push(sv(i,n,e));return r}if(Qe(o)){if(e.has(o))throw new Error("Cannot clone recursive data-structure");e.add(o);let r={};for(let i in o)uT.call(o,i)&&(r[i]=sv(o[i],n,e));return e.delete(o),r}return o}function Qs(o,n,e=!0){return Qe(o)?(Qe(n)&&Object.keys(n).forEach(t=>{t in o?e&&(Qe(o[t])&&Qe(n[t])?Qs(o[t],n[t],e):o[t]=n[t]):o[t]=n[t]}),o):n}function Ne(o,n){if(o===n)return!0;if(o==null||n===null||n===void 0||typeof o!=typeof n||typeof o!="object"||Array.isArray(o)!==Array.isArray(n))return!1;let e,t;if(Array.isArray(o)){if(o.length!==n.length)return!1;for(e=0;e<o.length;e++)if(!Ne(o[e],n[e]))return!1}else{let r=[];for(t in o)r.push(t);r.sort();let i=[];for(t in n)i.push(t);if(i.sort(),!Ne(r,i))return!1;for(e=0;e<r.length;e++)if(!Ne(o[r[e]],n[r[e]]))return!1}return!0}function Ad(o){let n=new Set;return JSON.stringify(o,(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 lo(o,n){let e=n.toLowerCase(),t=Object.keys(o).find(r=>r.toLowerCase()===e);return t?o[t]:o[n]}import*as tO from"child_process";import{promises as IT}from"fs";function pT(o){o&&(delete o.DEBUG,delete o.NODE_OPTIONS,Oe&&delete o.LD_PRELOAD)}import*as ie from"fs";import{tmpdir as HM}from"os";import{promisify as kd}from"util";var OM=new an(1e4);function Ed(o){return fT(o,"NFC",OM)}var LM=new an(1e4);function NM(o){return fT(o,"NFD",LM)}var UM=/[^\u0000-\u0080]/;function fT(o,n,e){if(!o)return o;let t=e.get(o);if(t)return t;let r;return UM.test(o)?r=o.normalize(n):r=o,e.set(o,r),r}var FM=(function(){let o=new an(1e4),n=/[\u0300-\u036f]/g;return function(e){let t=o.get(e);if(t)return t;let r=NM(e).replace(n,""),i=(r.length===e.length?r:e).toLowerCase();return o.set(e,i),i}})();async function hT(o,n=0,e){if(jy(o))throw new Error("rimraf - will refuse to recursively delete root");return n===0?av(o):$M(o,e)}async function $M(o,n=D_(HM())){try{try{await ie.promises.rename(o,n)}catch(e){return e.code==="ENOENT"?void 0:av(o)}av(n).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function av(o){return ie.promises.rm(o,{recursive:!0,force:!0,maxRetries:3})}async function Ip(o,n){try{return await gT(o,n)}catch(e){if(e.code==="ENOENT"&&Q&&jy(o))try{return await gT(`${o}.`,n)}catch{}throw e}}async function gT(o,n){return qM(await(n?WM(o):ie.promises.readdir(o)))}async function WM(o){try{return await ie.promises.readdir(o,{withFileTypes:!0})}catch(t){t.code!=="ENOENT"&&console.warn("[node.js fs] readdir with filetypes failed with error: ",t)}let n=[],e=await Ip(o);for(let t of e){let r=!1,i=!1,s=!1;try{let a=await ie.promises.lstat(j(o,t));r=a.isFile(),i=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:()=>i,isSymbolicLink:()=>s})}return n}function qM(o){return o.map(n=>typeof n=="string"?dt?Ed(n):n:(n.name=dt?Ed(n.name):n.name,n))}async function BM(o){let n=await Ip(o),e=[];for(let t of n)await en.existsDirectory(j(o,t))&&e.push(t);return e}var en;(t=>{async function o(r){let i;try{if(i=await ie.promises.lstat(r),!i.isSymbolicLink())return{stat:i}}catch{}try{return{stat:await ie.promises.stat(r),symbolicLink:i?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&i)return{stat:i,symbolicLink:{dangling:!0}};if(Q&&s.code==="EACCES")try{return{stat:await ie.promises.stat(await ie.promises.readlink(r)),symbolicLink:{dangling:!1}}}catch(a){if(a.code==="ENOENT"&&i)return{stat:i,symbolicLink:{dangling:!0}};throw a}throw s}}t.stat=o;async function n(r){try{let{stat:i,symbolicLink:s}=await t.stat(r);return i.isFile()&&s?.dangling!==!0}catch{}return!1}t.existsFile=n;async function e(r){try{let{stat:i,symbolicLink:s}=await t.stat(r);return i.isDirectory()&&s?.dangling!==!0}catch{}return!1}t.existsDirectory=e})(en||={});var zM=new qs;function VM(o,n,e){return zM.queueFor(h.file(o),()=>{let t=GM(e);return new Promise((r,i)=>KM(o,n,t,s=>s?i(s):r()))},nt)}var yT=!0;function jM(o){yT=o}function KM(o,n,e,t){if(!yT)return ie.writeFile(o,n,{mode:e.mode,flag:e.flag},t);ie.open(o,e.flag,e.mode,(r,i)=>{if(r)return t(r);ie.writeFile(i,n,s=>{if(s)return ie.close(i,()=>t(s));ie.fdatasync(i,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),jM(!1)),ie.close(i,l=>t(l))))})})}function GM(o){return o?{mode:typeof o.mode=="number"?o.mode:438,flag:typeof o.flag=="string"?o.flag:"w"}:{mode:438,flag:"w"}}async function JM(o,n,e=6e4){if(o!==n)try{Q&&typeof e=="number"?await vT(o,n,Date.now(),e):await ie.promises.rename(o,n)}catch(t){if(o.toLowerCase()!==n.toLowerCase()&&t.code==="EXDEV"||o.endsWith("."))await ST(o,n,{preserveSymlinks:!1}),await hT(o,1);else throw t}}async function vT(o,n,e,t,r=0){try{return await ie.promises.rename(o,n)}catch(i){if(i.code!=="EACCES"&&i.code!=="EPERM"&&i.code!=="EBUSY")throw i;if(Date.now()-e>=t)throw console.error(`[node.js fs] rename failed after ${r} retries with error: ${i}`),i;if(r===0){let s=!1;try{let{stat:a}=await en.stat(n);a.isFile()||(s=!0)}catch{}if(s)throw i}return await Zt(Math.min(100,r*10)),vT(o,n,e,t,r+1)}}async function ST(o,n,e){return bT(o,n,{root:{source:o,target:n},options:e,handledSourcePaths:new Set})}var mT=511;async function bT(o,n,e){if(e.handledSourcePaths.has(o))return;e.handledSourcePaths.add(o);let{stat:t,symbolicLink:r}=await en.stat(o);if(r){if(e.options.preserveSymlinks)try{return await XM(o,n,e)}catch{}if(r.dangling)return}return t.isDirectory()?YM(o,n,t.mode&mT,e):QM(o,n,t.mode&mT)}async function YM(o,n,e,t){await ie.promises.mkdir(n,{recursive:!0,mode:e});let r=await Ip(o);for(let i of r)await bT(j(o,i),j(n,i),t)}async function QM(o,n,e){await ie.promises.copyFile(o,n),await ie.promises.chmod(n,e)}async function XM(o,n,e){let t=await ie.promises.readlink(o);ro(t,e.root.source,!Oe)&&(t=j(e.root.target,t.substr(e.root.source.length+1))),await ie.promises.symlink(t,n)}async function ZM(o){try{return await kd(ie.realpath)(o)}catch{let n=eO(o);return await ie.promises.access(n,ie.constants.R_OK),n}}function eO(o){return $s(un(o),Le)}var Ue=new class{get read(){return(o,n,e,t,r)=>new Promise((i,s)=>{ie.read(o,n,e,t,r,(a,l,d)=>a?s(a):i({bytesRead:l,buffer:d}))})}get write(){return(o,n,e,t,r)=>new Promise((i,s)=>{ie.write(o,n,e,t,r,(a,l,d)=>a?s(a):i({bytesWritten:l,buffer:d}))})}get fdatasync(){return kd(ie.fdatasync)}get open(){return kd(ie.open)}get close(){return kd(ie.close)}get ftruncate(){return kd(ie.ftruncate)}async exists(o){try{return await ie.promises.access(o),!0}catch{return!1}}get readdir(){return Ip}get readDirsInDir(){return BM}get writeFile(){return VM}get rm(){return hT}get rename(){return JM}get copy(){return ST}get realpath(){return ZM}};function _T(o=Xe){return o.comspec||"cmd.exe"}function TT(o){let n=[],e=!1,t=function(r){if(e){n.push(r);return}(!o.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 nO(o){if(await Ue.exists(o)){let n;try{n=await IT.stat(o)}catch(e){e.message.startsWith("EACCES")&&(n=await IT.lstat(o))}return n?!n.isDirectory():!1}return!1}async function _p(o,n,e,t=Xe,r=nO){if(Wt(o))return await r(o)?o:void 0;if(n===void 0&&(n=Ei()),oe(o)!=="."){let l=j(n,o);return await r(l)?l:void 0}let s=lo(t,"PATH");if(e===void 0&&Ve(s)&&(e=s.split(Hs)),e===void 0||e.length===0){let l=j(n,o);return await r(l)?l:void 0}for(let l of e){let d;if(Wt(l)?d=j(l,o):d=j(n,l,o),Q){let u=(lo(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,o);return await r(a)?a:void 0}var Tp=class extends xd{constructor(n){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:ee.fromNodeEventEmitter(process,"message",e=>F.wrap(Buffer.from(e,"base64")))},n),process.once("disconnect",()=>this.dispose())}},wp=class{constructor(n,e){this.modulePath=n;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new A;this.onDidProcessExit=this._onDidProcessExit.event;let t=e.timeout||6e4;this.disposeDelayer=new Ni(t),this.child=null,this._client=null}getChannel(n){let e=this;return{call(t,r,i){return e.requestPromise(n,t,r,i)},listen(t,r){return e.requestEvent(n,t,r)}}}requestPromise(n,e,t,r=Re.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(r.isCancellationRequested)return Promise.reject(Hu());this.disposeDelayer.cancel();let i=this.getCachedChannel(n),s=jo(d=>i.call(e,t,d)),a=r.onCancellationRequested(()=>s.cancel()),l=N(()=>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,i=new A({onWillAddFirstListener:()=>{r=this.getCachedChannel(n).listen(e,t)(i.fire,i),this.activeRequests.add(r)},onDidRemoveLastListener:()=>{this.activeRequests.delete(r),r.dispose(),this.activeRequests.size===0&&this.disposeDelayer&&this.disposeDelayer.trigger(()=>this.disposeClient())}});return i.event}get client(){if(!this._client){let n=this.options.args||[],e=Object.create(null);e.env={...$n(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-"))),pT(e.env),this.child=oO(this.modulePath,n,e);let t=new A,i=ee.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(lT(u)){dT(u,`IPC Library: ${this.options.serverName}`);return}t.fire(F.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?TT(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 Ks(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),i.dispose(),this.activeRequests.forEach(m=>Gt(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 Rp(o){return!!o.parentPort}var lv=class{constructor(n){this.port=n;this.onMessage=ee.fromNodeEventEmitter(this.port,"message",e=>e.data?F.wrap(e.data):F.alloc(0)),n.start()}send(n){this.port.postMessage(n.buffer)}disconnect(){this.port.close()}},Dd=class o extends Cp{static getOnDidClientConnect(n){WI(Rp(process),"Electron Utility Process");let e=new A;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 lv(t),onDidClientDisconnect:ee.fromNodeEventEmitter(t,"close")}))}constructor(n){super(o.getOnDidClientConnect(n))}};var iO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function wT(o){return iO.test(o)}var O=(function(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let o=new Uint8Array(16),n=[];for(let e=0;e<256;e++)n.push(e.toString(16).padStart(2,"0"));return function(){crypto.getRandomValues(o),o[6]=o[6]&15|64,o[8]=o[8]&63|128;let t=0,r="";return r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r+="-",r+=n[o[t++]],r+=n[o[t++]],r+="-",r+=n[o[t++]],r+=n[o[t++]],r+="-",r+=n[o[t++]],r+=n[o[t++]],r+="-",r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r+=n[o[t++]],r}})();import*as Nu from"os";import*as Lu from"inspector";var ir;(r=>{r.serviceIds=new Map,r.DI_TARGET="$di$target",r.DI_DEPENDENCIES="$di$dependencies";function t(i){return i[r.DI_DEPENDENCIES]||[]}r.getServiceDependencies=t})(ir||={});var xe=W("instantiationService");function aO(o,n,e){n[ir.DI_TARGET]===n?n[ir.DI_DEPENDENCIES].push({id:o,index:e}):(n[ir.DI_DEPENDENCIES]=[{id:o,index:e}],n[ir.DI_TARGET]=n)}function W(o){if(ir.serviceIds.has(o))return ir.serviceIds.get(o);let n=function(e,t,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");aO(n,e,r)};return n.toString=()=>o,ir.serviceIds.set(o,n),n}var Ke="ahp-root://",lO="ahp-root",cv="ahp-resource-watch";function DT(o){let n={root:o.root};o.recursive&&(n.recursive=!0),o.excludes&&o.excludes.items.length>0&&(n.excludes=[...o.excludes.items]),o.includes&&o.includes.items.length>0&&(n.includes=[...o.includes.items]);let e=or(F.fromString(JSON.stringify(n)),!1,!0);return`${cv}://r/${e}`}function MT(o){let n;try{n=h.parse(o)}catch{return}if(n.scheme!==cv)return;let e=n.path.replace(/^\//,"");if(e)try{let t=JSON.parse(pn(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 OT(o){try{return h.parse(o).scheme===cv}catch{return!1}}function qi(o){if(o===Ke)return!0;try{return h.parse(o).scheme===lO}catch{return!1}}function Nt(o,n){return n?`${o.replace(/#/g,"%23")}#range=${n.start.line}:${n.start.character}-${n.end.line}:${n.end.character}`:o}function LT(o){if(!o.content||o.content.length===0)return[];let n=[];for(let e of o.content)he(e,{type:!0})&&e.type==="fileEdit"&&n.push(e);return n}function NT(o){if(!(!o.content||o.content.length===0)){for(let n of o.content)if(he(n,{type:!0})&&n.type==="subagent")return n}}var dO="subagent",cO=`/${dO}/`,uO=/^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;function UT(o){return typeof o=="string"?h.parse(o):o}function FT(o){let n=UT(o),e=n.path.endsWith("/")?n.path.slice(0,-1):n.path;return{parent:n,path:`${e}${cO}`}}function na(o,n){let{parent:e,path:t}=FT(o);return e.with({path:`${t}${n}`}).toString()}function ut(o){let n=UT(o),e=uO.exec(n.path);if(e?.groups)return{parentSession:n.with({path:e.groups.parentPath}),toolCallId:e.groups.toolCallId}}function lr(o){return ut(o)!==void 0}function HT(o){let{parent:n,path:e}=FT(o);return n.with({path:e}).toString()}function $T(){return{agents:[],activeSessions:0}}function uv(o){let n={provider:o.provider,title:o.title,status:o.status,lifecycle:"creating",activeClients:[],chats:[],defaultChat:void 0};return o.activity!==void 0&&(n.activity=o.activity),o.project!==void 0&&(n.project=o.project),o.workingDirectory!==void 0&&(n.workingDirectory=o.workingDirectory),o.annotations!==void 0&&(n.annotations=o.annotations),o._meta!==void 0&&(n._meta=o._meta),n}function Ap(o){return{resource:o.resource,title:o.title,status:o.status,activity:o.activity,modifiedAt:o.modifiedAt,origin:o.origin,interactivity:o.interactivity,workingDirectory:o.workingDirectory,turns:[],activeTurn:void 0}}function Ep(o,n){let e={resource:n,title:o.title,status:o.status,modifiedAt:o.modifiedAt,origin:{kind:"user"}};return o.activity!==void 0&&(e.activity=o.activity),e}function WT(o){let n={resource:o.resource,title:o.title,status:o.status,modifiedAt:o.modifiedAt};return o.activity!==void 0&&(n.activity=o.activity),o.origin!==void 0&&(n.origin=o.origin),o.interactivity!==void 0&&(n.interactivity=o.interactivity),o.workingDirectory!==void 0&&(n.workingDirectory=o.workingDirectory),n}function pO(o,n){return o==="hidden"?"hidden":n?"read-only":o??"full"}function qT(o,n){return pO(o,n)==="read-only"}var $d="ahp-chat",BT="default";function Jo(o,n){let e=typeof o=="string"?o:o.toString(),t=or(F.fromString(e),!1,!0);return`${$d}://${n}/${t}`}function pe(o){return Jo(o,BT)}var xp="subagent";function Wd(o){let n=typeof o=="string"?h.parse(o):o;return n.scheme===$d&&n.authority===xp}function ra(o,n){let e=typeof o=="string"?o:o.toString(),t=or(F.fromString(e),!1,!0);return`${$d}://${xp}/${t}/${encodeURIComponent(n)}`}function ke(o){let n;try{n=typeof o=="string"?h.parse(o):o}catch{return}if(n.scheme!==$d||!n.authority)return;let e=n.path.replace(/^\//,"");if(e)try{if(n.authority===xp){let[t,...r]=e.split("/"),i=r.join("/");return!t||!i?void 0:{session:pn(t).toString(),chatId:`${xp}/${decodeURIComponent(i)}`}}return{session:pn(e).toString(),chatId:n.authority}}catch{return}}function oa(o){return ke(o)?.session}function fe(o){let n=oa(o);if(n===void 0)throw new Error(`Malformed AHP chat URI: ${typeof o=="string"?o:o.toString()}`);return n}function Fe(o){return ke(o)?.chatId===BT}function de(o){try{return h.parse(o).scheme===$d}catch{return!1}}function zT(o,n){return{...o,workingDirectory:n?.workingDirectory??o.workingDirectory,turns:n?.turns??[],activeTurn:n?.activeTurn,steeringMessage:n?.steeringMessage,queuedMessages:n?.queuedMessages,inputRequests:n?.inputRequests,draft:n?.draft}}var Md="git",Od="github";function St(o){let n=o?.[Md];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 kp(o,n){let e={...o};return n!==void 0?e[Md]=n:delete e[Md],Object.keys(e).length>0?e:void 0}function dr(o){let n=o?.[Od];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(o,n){let e={...o};return n!==void 0?e[Od]=n:delete e[Od],Object.keys(e).length>0?e:void 0}var VT="agentHost/sessionSpawnDepth";function jT(o){let n=o?.[VT];return typeof n=="number"&&Number.isFinite(n)?n:0}function KT(o,n){return{...o,[VT]:n}}var dv="workspaceless",Wn="agentHost.workspaceless",qn="isArchived",xr="isDone";function pv(o){return o?.[dv]===!0}function Mp(o,n){let e={...o};return n?e[dv]=!0:delete e[dv],Object.keys(e).length>0?e:void 0}var RT="hostBuild";function GT(o){return{version:o.version,commit:o.commit,date:o.date,quality:o.quality}}function JT(o,n){let e={...o};return n!==void 0?e[RT]=n:delete e[RT],Object.keys(e).length>0?e:void 0}var Op="VSCODE_AGENT_HOST_CLAUDE_SDK_ROOT",YT="VSCODE_AGENT_HOST_CLAUDE_AGENT_ENABLED",QT="VSCODE_AGENT_HOST_CODEX_AGENT_ENABLED",XT="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",ZT="VSCODE_AGENT_HOST_SESSION_RELEASE_GRACE_MS";function Lp(o,n){if(o===void 0||o==="")return n;let e=o.trim().toLowerCase();return e==="false"||e==="0"?!1:e==="true"||e==="1"?!0:n}var ew="VSCODE_AGENT_HOST_CODEX_SDK_ROOT",tw="CODEX_HOME",nw="VSCODE_AGENT_HOST_CODEX_APP_SERVER_ARGS";var rw="agent-host/otel/agent-host-traces.db",VB=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 ow="claude",iw="codex";var fO=60;function fv(o,n){let e=o?.trim();return e?tr(e,fO):n?.trim()||"Subagent"}var Bi;(n=>{function o(e){if(e.kind!=="subagent_started")return;let t;try{t=fe(e.chat)}catch{return}return{session:h.parse(t),chat:h.parse(ra(t,e.toolCallId)),parent:{chat:e.chat,toolCallId:e.toolCallId},title:fv(e.taskDescription,e.agentDisplayName)}}n.toSpawnEvent=o})(Bi||={});var D;(t=>{function o(r,i){return h.from({scheme:r,path:`/${i}`})}t.uri=o;function n(r){return(typeof r=="string"?h.parse(r):r).path.substring(1)}t.id=n;function e(r){return(typeof r=="string"?h.parse(r):r).scheme||void 0}t.provider=e})(D||={});var Pr=W("agentService"),jB=W("agentHostService");function Jt(o,n){return o===n}function gO(){return(o,n)=>o===n}function gv(o,n,e){return In(o,n,e??Jt)}function mO(o){return(n,e)=>In(n,e,o??Jt)}function Yo(o,n){if(o===n)return!0;if(Array.isArray(o)&&Array.isArray(n)){if(o.length!==n.length)return!1;for(let e=0;e<o.length;e++)if(!Yo(o[e],n[e]))return!1;return!0}if(o&&typeof o=="object"&&n&&typeof n=="object"&&Object.getPrototypeOf(o)===Object.prototype&&Object.getPrototypeOf(n)===Object.prototype){let e=o,t=n,r=Object.keys(e),i=Object.keys(t),s=new Set(i);if(r.length!==i.length)return!1;for(let a of r)if(!s.has(a)||!Yo(e[a],t[a]))return!1;return!0}return!1}function hO(){return(o,n)=>Yo(o,n)}function yO(o,n){return JSON.stringify(o)===JSON.stringify(n)}function vO(){return(o,n)=>JSON.stringify(o)===JSON.stringify(n)}function SO(){return(o,n)=>o.equals(n)}function bO(o,n,e){return o==null||n===void 0||n===null?n===o:e(o,n)}function CO(o){return(n,e)=>n==null||e===void 0||e===null?e===n:o(n,e)}var IO;(u=>(u.strict=Jt,u.strictC=gO,u.array=gv,u.arrayC=mO,u.structural=Yo,u.structuralC=hO,u.jsonStringify=yO,u.jsonStringifyC=vO,u.thisC=SO,u.ifDefined=bO,u.ifDefinedC=CO))(IO||={});var Bn=W("configurationService");function Np(o){let n=o;return n&&typeof n=="object"&&(!n.overrideIdentifier||typeof n.overrideIdentifier=="string")&&(!n.resource||n.resource instanceof h)}function sw(o){let n=o;return n&&typeof n=="object"&&(!n.overrideIdentifiers||Array.isArray(n.overrideIdentifiers))&&!n.overrideIdentifier&&(!n.resource||n.resource instanceof h)}function Up(o,n){let e=Object.create(null);for(let t in o)mv(e,t,o[t],n);return e}function mv(o,n,e,t){let r=n.split("."),i=r.pop(),s=o;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[i]=e}catch{t(`Ignoring ${n} as ${r.join(".")} is ${JSON.stringify(s)}`)}else t(`Ignoring ${n} as ${r.join(".")} is ${JSON.stringify(s)}`)}function aw(o,n){let e=n.split(".");lw(o,e)}function lw(o,n){if(!o)return;let e=o,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)&&(lw(r,n),Object.keys(r).length===0&&delete e[t])}}function qd(o,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("."),i=t(o,r);return typeof i>"u"?e:i}function dw(o){return o.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}var zn=W("telemetryService");var tz=W("customEndpointTelemetryService");var cw="telemetry",ia="telemetry.telemetryLevel",Fp="telemetry.enableCrashReporter",Bd="telemetry.enableTelemetry";var ae={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603},Se={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010,Conflict:-32011};var uw=-32700,zi=-32603,_t=-32001,pw=-32002;var fw=-32005;var cr=-32007;function gw(o){return"method"in o&&"id"in o}function mw(o){return"method"in o&&!("id"in o)}var L=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}};function ce(o){let n=yv(o);return{protocol:o,validate:r=>{try{return n(r,""),!0}catch{return!1}},assertValid:(r,i="")=>n(r,i)}}function nn(o){return{definition:o,toProtocol(){let n={};for(let e of Object.keys(o))n[e]=o[e].protocol;return{type:"object",properties:n}},values(n){let e=n;for(let t of Object.keys(o)){let r=e[t];if(r===void 0)continue;o[t].assertValid(r,t)}return{...e}},validate(n,e){let t=o[n];return t?t.validate(e):!1},assertValid(n,e){let t=o[n];if(!t)throw new L(ae.InvalidParams,`Unknown schema key '${n}'`);t.assertValid(e,n)},validateOrDefault(n,e){let t={},r=n??{};for(let i of Object.keys(o)){let s=o[i],a=r[i];a!==void 0&&s.validate(a)?t[i]=a:Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t}}}function yv(o){if(o.type==="object"&&o.properties){let n={};for(let t of Object.keys(o.properties))n[t]=yv(o.properties[t]);let e=new Set(o.required??[]);return(t,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw Vi(r,"object",t);let i=t;for(let s of Object.keys(n)){let a=AO(r,s);if(i[s]===void 0){if(e.has(s))throw new L(ae.InvalidParams,`Missing required property at '${a}'`);continue}n[s](i[s],a)}}}if(o.type==="array"&&o.items){let n=yv(o.items);return(e,t)=>{if(!Array.isArray(e))throw Vi(t,"array",e);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`)}}return PO(o)}function PO(o){let n=o.enumDynamic===!0;return(e,t)=>{switch(o.type){case"string":if(typeof e!="string")throw Vi(t,"string",e);break;case"number":if(typeof e!="number")throw Vi(t,"number",e);break;case"boolean":if(typeof e!="boolean")throw Vi(t,"boolean",e);break;case"array":if(!Array.isArray(e))throw Vi(t,"array",e);break;case"object":if(typeof e!="object"||e===null||Array.isArray(e))throw Vi(t,"object",e);break}if(o.enum&&!n&&!o.enum.includes(e))throw new L(ae.InvalidParams,`Invalid value at '${t||"<root>"}': ${yw(e)} is not one of [${o.enum.map(r=>JSON.stringify(r)).join(", ")}]`)}}function Vi(o,n,e){return new L(ae.InvalidParams,`Invalid value at '${o||"<root>"}': expected ${n}, got ${yw(e)}`)}function AO(o,n){return o?`${o}.${n}`:n}function yw(o){try{return JSON.stringify(o)}catch{return String(o)}}var vw=ce({type:"object",title:f(1911,null),description:f(1915,null),properties:{allow:{type:"array",title:f(1912,null),items:{type:"string",title:f(1914,null)}},deny:{type:"array",title:f(1913,null),items:{type:"string",title:f(1914,null)}}},default:{allow:[],deny:[]},sessionMutable:!0}),Yt=nn({autoApprove:ce({type:"string",title:f(1897,null),description:f(1902,null),enum:["default","autoApprove"],enumLabels:[f(1900,null),f(1898,null)],enumDescriptions:[f(1901,null),f(1899,null)],default:"default",sessionMutable:!0}),permissions:vw,mode:ce({type:"string",title:f(1903,null),description:f(1910,null),enum:["interactive","plan","autopilot"],enumLabels:[f(1906,null),f(1908,null),f(1904,null)],enumDescriptions:[f(1907,null),f(1909,null),f(1905,null)],default:"interactive",sessionMutable:!0})});function Sw(o){if(!o||o.autoApprove!=="autopilot")return o;let n={...o};return n.mode!=="plan"&&(n.mode="autopilot"),n.autoApprove="default",n}var zd="telemetryLevel",Vd="sessionSyncEnabled",vv="codexAgentEnabled",Sv="terminalAutoApproveEnabled";var jd="globalAutoApproveEnabled";var bv="autoReplyEnabled";var Cv="preferLongContextEnabled";var Iv="terminalAutoApproveRules";var _v="mcpServers";function bw(o){switch(o){case 0:return"off";case 1:return"crash";case 2:return"error";case 3:return"all"}}function Cw(o){switch(o){case"off":return 0;case"crash":return 1;case"error":return 2;case"all":return 3;default:return}}var EO={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)}},kO={"<serverName>":{type:"object",title:f(1877,null),description:f(1876,null),properties:EO}},Ut=nn({permissions:vw,[zd]:ce({type:"string",title:f(1892,null),description:f(1891,null),enum:["all","error","crash","off"],default:"all"}),[Vd]:ce({type:"boolean",title:f(1890,null),description:f(1889,null),default:!1}),[vv]:ce({type:"boolean",title:f(1865,null),description:f(1864,null),default:!1}),[Sv]:ce({type:"boolean",title:f(1894,null),description:f(1893,null),default:!0}),[jd]:ce({type:"boolean",title:f(1867,null),description:f(1866,null),default:!1}),[bv]:ce({type:"boolean",title:f(1863,null),description:f(1862,null),default:!1}),[Cv]:ce({type:"boolean",title:f(1888,null),description:f(1887,null),default:!1}),[Iv]:ce({type:"object",title:f(1896,null),description:f(1895,null),default:{}}),[_v]:ce({type:"object",title:f(1882,null),description:f(1875,null),properties:kO,default:{}})});function Tv(o,n){return n&&(o.stack||o.stacktrace)?f(116,null,_w(o),Iw(o.stack)||Iw(o.stacktrace)):_w(o)}function Iw(o){return Array.isArray(o)?o.join(`
`):o}function _w(o){return o.code==="ERR_UNC_HOST_NOT_ALLOWED"?`${o.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`:typeof o.code=="string"&&typeof o.errno=="number"&&typeof o.syscall=="string"?f(115,null,o.message):o.message||f(113,null)}function De(o=null,n=!1){if(!o)return f(113,null);if(Array.isArray(o)){let e=Oo(o),t=De(e[0],n);return e.length>1?f(114,null,t,e.length):t}if(Ve(o))return o;if(o.detail){let e=o.detail;if(e.error)return Tv(e.error,n);if(e.exception)return Tv(e.exception,n)}return o.stack?Tv(o,n):o.message?o.message:f(113,null)}var Cz=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 wv={".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 $p(o){let n=Di(o),e=wv[n.toLowerCase()];return Array.isArray(e)?e[0]:e}function Tw(o){for(let n in wv){let e=wv[n];if(Array.isArray(e)?e.includes(o):e===o)return n}}var Tt=class{constructor(n,e,t){this.owner=n;this.debugNameSource=e;this.referenceFn=t}getDebugName(n){return Pw(n,this)}},ww=new Map,Rv=new WeakMap;function Pw(o,n){let e=Rv.get(o);if(e)return e;let t=DO(o,n);if(t){let r=ww.get(t)??0;r++,ww.set(t,r);let i=r===1?t:`${t}#${r}`;return Rv.set(o,i),i}}function DO(o,n){let e=Rv.get(o);if(e)return e;let t=n.owner?OO(n.owner)+".":"",r,i=n.debugNameSource;if(i!==void 0)if(typeof i=="function"){if(r=i(),r!==void 0)return t+r}else return t+i;let s=n.referenceFn;if(s!==void 0&&(r=Kd(s),r!==void 0))return t+r;if(n.owner!==void 0){let a=MO(n.owner,o);if(a!==void 0)return t+a}}function MO(o,n){for(let e in o)if(o[e]===n)return e}var Rw=new Map,xw=new WeakMap;function OO(o){let n=xw.get(o);if(n)return n;let e=xv(o)??"Object",t=Rw.get(e)??0;t++,Rw.set(e,t);let r=t===1?e:`${e}#${t}`;return xw.set(o,r),r}function xv(o){let n=o.constructor;if(n)return n.name==="Object"?void 0:n.name}function Kd(o){let n=o.toString(),t=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(n);return(t?t[1]:void 0)?.trim()}function Pv(o){let n=new Error("BugIndicatingErrorRecovery: "+o);st(n),console.error("recovered from an error that indicates a bug",n)}var Ki;function Gd(o){Ki?Ki instanceof Wp?Ki.loggers.push(o):Ki=new Wp([Ki,o]):Ki=o}function ze(){return Ki}var Av;function Aw(o){Av=o}function Ew(o){Av&&Av(o)}var Wp=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 ur(o,n){let e=new Qo(o,n);try{o(e)}finally{e.finish()}}function Ev(o,n,e){o?n(o):ur(n,e)}var Qo=class{constructor(n,e){this._fn=n;this._getDebugName=e;this._updatingObservers=[];ze()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():Kd(this._fn)}updateObserver(n,e){if(!this._updatingObservers){Pv("Transaction already finished!"),ur(t=>{t.updateObserver(n,e)});return}this._updatingObservers.push({observer:n,observable:e}),n.beginUpdate(e)}finish(){let n=this._updatingObservers;if(!n){Pv("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,ze()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var pt;(t=>{let o=!1;function n(){o=!0}t.enable=n;function e(){if(!o)return;let r=Error,i=r.stackTraceLimit;r.stackTraceLimit=3;let s=new Error().stack;return r.stackTraceLimit=i,kv.fromStack(s,2)}t.ofCaller=e})(pt||={});var kv=class o{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=LO(t[e+1]);if(r)return new o(r.fileName,r.line,r.column,r.id)}};function LO(o){let n=o.match(/\((.*):(\d+):(\d+)\)/);if(n)return{fileName:n[1],line:parseInt(n[2]),column:parseInt(n[3]),id:o};let e=o.match(/at ([^\(\)]*):(\d+):(\d+)/);if(e)return{fileName:e[1],line:parseInt(e[2]),column:parseInt(e[3]),id:o}}var Dv;function kw(o){Dv=o}var Dw;function Mw(o){Dw=o}var Ow;function Lw(o){Ow=o}var Mv;function Nw(o){Mv=o}var qp=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,i=e===void 0?n:e;return Dv({owner:r,debugName:()=>{let s=Kd(i);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(i.toString());if(l)return`${this.debugName}.${l[2]}`;if(!r)return`${this.debugName} (mapped)`},debugReferenceFn:i},s=>i(this.read(s),s),t)}flatten(){return Dv({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},n=>this.read(n).read(n))}recomputeInitiallyAndOnChange(n,e){return n.add(Dw(this,e)),this}keepObserved(n){return n.add(Ow(this)),this}get debugValue(){return this.get()}get debug(){return new Ov(this)}},Ov=class{constructor(n){this.observable=n}getDependencyGraph(){return Mv(this.observable,{type:"dependencies"})}getObserverGraph(){return Mv(this.observable,{type:"observers"})}},Vn=class extends qp{constructor(e){super();this._observers=new Set;ze()?.handleObservableCreated(this,e)}addObserver(e){let t=this._observers.size;this._observers.add(e),t===0&&this.onFirstObserverAdded(),t!==this._observers.size&&ze()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let t=this._observers.delete(e);t&&this._observers.size===0&&this.onLastObserverRemoved(),t&&ze()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!ze();return Ew(this),e||ze()?.handleObservableCreated(this,pt.ofCaller()),this}debugGetObservers(){return this._observers}};function rn(o,n,e=pt.ofCaller()){let t;return typeof o=="string"?t=new Tt(void 0,o,void 0):t=new Tt(o,void 0,void 0),new Ar(t,n,Jt,e)}var Ar=class extends Vn{constructor(e,t,r,i){super(i);this._debugNameData=e;this._equalityComparator=r;this._value=t,ze()?.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 i;t||(t=i=new Qo(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),ze()?.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{i&&i.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 Vn{constructor(e,t,r,i){super(i);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){ze()?.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{ze()?.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 i;t||(t=i=new Qo(()=>{},()=>`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{i&&i.finish()}}toString(){return`${this.debugName}: ${this._value}`}_setValue(e){this._value=e}};function Gi(o,n,e=pt.ofCaller()){return o.lazy?new Bp(new Tt(o.owner,o.debugName,void 0),n,o.equalsFn??Jt,e):new Ar(new Tt(o.owner,o.debugName,void 0),n,o.equalsFn??Jt,e)}function NO(o){switch(o){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var co=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),ze()?.handleAutorunCreated(this,r),this._run(),Lo(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(),ze()?.handleAutorunDisposed(this),No(this)}}_run(){let n=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=n,this._state=3;try{if(!this._disposed){ze()?.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){Mo(r)}finally{this._isRunning=!1,t!==void 0&&t.dispose()}}}finally{this._disposed||ze()?.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--}ud(()=>this._updateCount>=0)}handlePossibleChange(n){this._state===3&&this._isDependency(n)&&(this._checkIterations(),this._state=1)}handleChange(n,e){if(this._isDependency(n)){ze()?.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){Mo(t)}}}_isDependency(n){return this._dependencies.has(n)&&!this._dependenciesToBeRemoved.has(n)}_ensureNoRunning(){if(!this._isRunning)throw new We("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 We("Cannot access store after dispose");return this._store===void 0&&(this._store=new Y),this._store}get delayedStore(){if(this._ensureNoRunning(),this._disposed)throw new We("Cannot access store after dispose");return this._delayedStore===void 0&&(this._delayedStore=new Y),this._delayedStore}debugGetState(){return{isRunning:this._isRunning,updateCount:this._updateCount,dependencies:this._dependencies,state:this._state,stateStr:NO(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(Mo(new We(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function jn(o,n=pt.ofCaller()){return new co(new Tt(void 0,void 0,o),o,void 0,n)}function UO(o){switch(o){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var wt=class extends Vn{constructor(e,t,r,i=void 0,s,a){super(a);this._debugNameData=e;this._computeFn=t;this._changeTracker=r;this._handleLastObserverRemoved=i;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,ze()?.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 i=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||i&&!this._equalityComparator(s,this._value),ze()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:i})}catch(r){Mo(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 We("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 i of r)i.endUpdate(this)}}ud(()=>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){ze()?.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){Mo(s)}let i=this._state===3;if(r&&(this._state===1||i)&&(this._state=2,i))for(let s of this._observers)s.handlePossibleChange(this)}}_ensureReaderValid(){if(!this._isReaderValid)throw new We("The reader object cannot be used outside its compute function!")}readObservable(e){this._ensureReaderValid(),e.addObserver(this);let 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 Y),this._store}get delayedStore(){return this._ensureReaderValid(),this._delayedStore===void 0&&(this._delayedStore=new Y),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:UO(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 i=this._observers;t.updateObserver(this,this);for(let s of i)s.handleChange(this,r)}};function Jd(o,n,e=pt.ofCaller()){return n!==void 0?new wt(new Tt(o,void 0,n),n,void 0,void 0,Jt,e):new wt(new Tt(void 0,void 0,o),o,void 0,void 0,Jt,e)}function Yd(o,n,e=pt.ofCaller()){return new wt(new Tt(o.owner,o.debugName,o.debugReferenceFn),n,void 0,o.onLastObserverRemoved,o.equalsFn??Jt,e)}kw(Yd);function Ji(...o){let n,e,t,r;return o.length===2?[e,t]=o:[n,e,t,r]=o,new Kn(new Tt(n,void 0,t),e,t,()=>Kn.globalTransaction,Jt,r??pt.ofCaller())}var Kn=class extends Vn{constructor(e,t,r,i,s,a){super(a);this._debugNameData=e;this.event=t;this._getValue=r;this._getTransaction=i;this._equalityComparator=s;this._hasValue=!1;this.handleEvent=e=>{let t=this._getValue(e),r=this._value,i=!this._hasValue||!this._equalityComparator(r,t),s=!1;i&&(this._value=t,this._hasValue&&(s=!0,Ev(this._getTransaction(),a=>{ze()?.handleObservableUpdated(this,{oldValue:r,newValue:t,change:void 0,didChange:i,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||ze()?.handleObservableUpdated(this,{oldValue:r,newValue:t,change:void 0,didChange:i,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=Kn;function n(t,r){let i=!1;Kn.globalTransaction===void 0&&(Kn.globalTransaction=t,i=!0);try{r()}finally{i&&(Kn.globalTransaction=void 0)}}e.batchEventsGlobally=n})(Ji||={});function Uw(o){let n=new zp(!1,void 0);return o.addObserver(n),N(()=>{o.removeObserver(n)})}Lw(Uw);function Fw(o,n){let e=new zp(!0,n);o.addObserver(e);try{e.beginUpdate(o)}finally{e.endUpdate(o)}return N(()=>{o.removeObserver(e)})}Mw(Fw);var zp=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 Vp;function Hw(o){Vp||(Vp=new Qd,Gd(Vp)),Vp.addFilteredObj(o)}var Qd=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 BO([sa(jO("|  ",this.indentation)),n])}formatInfo(n){return n.hadValue?n.didChange?[sa(" "),Gn(Rn(n.oldValue,70),{color:"red",strikeThrough:!0}),sa(" "),Gn(Rn(n.newValue,60),{color:"green"})]:[sa(" (unchanged)")]:[sa(" "),Gn(Rn(n.newValue,60),{color:"green"}),sa(" (initial)")]}handleObservableCreated(n){if(n instanceof wt){let e=n;if(this.changedObservablesSets.set(e,new Set),!1){let r=[];e.__debugUpdating=r;let i=e.beginUpdate;e.beginUpdate=a=>(r.push(a),i.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 wt){this._handleDerivedRecomputed(n,e);return}console.log(...this.textToConsoleArgs([aa("observable value changed"),Gn(n.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(n){if(n.size!==0)return Gn(" (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([aa("derived recomputed"),Gn(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([aa("derived cleared"),Gn(n.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(n,e){this._isIncluded(n)&&console.log(...this.textToConsoleArgs([aa("observable from event triggered"),Gn(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([aa("autorun"),Gn(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([aa("transaction"),Gn(e,{color:"BlueViolet"}),{data:[{fn:n._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function BO(o){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(o);let i=[t,...n];return i.push(...e),i}function sa(o){return Gn(o,{color:"black"})}function aa(o){return Gn(KO(`${o}: `,10),{color:"black",bold:!0})}function Gn(o,n={color:"black"}){function e(r){return Object.entries(r).reduce((i,[s,a])=>`${i}${s}:${a};`,"")}let t={color:n.color};return n.strikeThrough&&(t["text-decoration"]="line-through"),n.bold&&(t["font-weight"]="bold"),{text:o,style:e(t)}}function Rn(o,n){switch(typeof o){case"number":return""+o;case"string":return o.length+2<=n?`"${o}"`:`"${o.substr(0,n-7)}"+...`;case"boolean":return o?"true":"false";case"undefined":return"undefined";case"object":return o===null?"null":Array.isArray(o)?zO(o,n):VO(o,n);case"symbol":return o.toString();case"function":return`[[Function${o.name?" "+o.name:""}]]`;default:return""+o}}function zO(o,n){let e="[ ",t=!0;for(let r of o){if(t||(e+=", "),e.length-5>n){e+="...";break}t=!1,e+=`${Rn(r,n-e.length)}`}return e+=" ]",e}function VO(o,n){if(typeof o.toString=="function"&&o.toString!==Object.prototype.toString){let i=o.toString();return i.length<=n?i:i.substring(0,n-3)+"..."}let e=xv(o),t=e?e+"(":"{ ",r=!0;for(let[i,s]of Object.entries(o)){if(r||(t+=", "),t.length-5>n){t+="...";break}r=!1,t+=`${i}: ${Rn(s,n-t.length)}`}return t+=e?")":" }",t}function jO(o,n){let e="";for(let t=1;t<=n;t++)e+=o;return e}function KO(o,n){for(;o.length<n;)o+=" ";return o}var jp=class o{constructor(n,e){this._channelFactory=n;this._getHandler=e;this._channel=this._channelFactory({handleNotification:i=>{let s=i,a=this._getHandler().notifications[s[0]];if(!a)throw new Error(`Unknown notification "${s[0]}"!`);a(...s[1])},handleRequest:i=>{let s=i;try{return{type:"result",value:this._getHandler().requests[s[0]](...s[1])}}catch(a){return{type:"error",value:a}}}});let t=new Proxy({},{get:(i,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:(i,s)=>(...a)=>{this._channel.sendNotification([s,a])}});this.api={notifications:r,requests:t}}static createHost(n,e){return new o(n,e)}static createClient(n,e){return new o(n,e)}};function $w(o,n){let e=globalThis,t=[],r,{channel:i,handler:s}=GO({sendNotification:l=>{r?r.sendNotification(l):t.push(l)}}),a;return(e.$$debugValueEditor_debugChannels??(e.$$debugValueEditor_debugChannels={}))[o]=l=>{a=n(),r=l;for(let d of t)l.sendNotification(d);return t=[],s},jp.createClient(i,()=>{if(!a)throw new Error("Not supported");return a})}function GO(o){let n;return{channel:t=>(n=t,{sendNotification:r=>{o.sendNotification(r)},sendRequest:r=>{throw new Error("not supported")}}),handler:{handleRequest:t=>t.type==="notification"?n?.handleNotification(t.data):n?.handleRequest(t.data)}}}var Kp=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 Lv(o,n){for(let e in n)o[e]&&typeof o[e]=="object"&&n[e]&&typeof n[e]=="object"?Lv(o[e],n[e]):o[e]=n[e]}function Nv(o,n){for(let e in n)n[e]===null?delete o[e]:o[e]&&typeof o[e]=="object"&&n[e]&&typeof n[e]=="object"?Nv(o[e],n[e]):o[e]=n[e]}var Gp=class o{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=$w("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(_r)}),getDerivedInfo:n=>{let e=this._aliveInstances.get(n);return{dependencies:[...e.debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(_r),observers:[...e.debugGetObservers()].map(t=>this._formatObserver(t)).filter(_r)}},getAutorunInfo:n=>({dependencies:[...this._aliveInstances.get(n).debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(_r)}),getTransactionState:()=>this.getTransactionState(),setValue:(n,e)=>{let t=this._aliveInstances.get(n);if(t instanceof wt)t.debugSetValue(e);else if(t instanceof Ar)t.debugSetValue(e);else if(t instanceof Kn)t.debugSetValue(e);else throw new We("Observable is not supported");let r=[...t.debugGetObservers()];for(let i of r)i.beginUpdate(t);for(let i of r)i.handleChange(t,void 0);for(let i of r)i.endUpdate(t)},getValue:n=>{let e=this._aliveInstances.get(n);if(e instanceof wt)return Rn(e.debugGetState().value,200);if(e instanceof Ar)return Rn(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 We("Observable is not supported")},rerun:n=>{let e=this._aliveInstances.get(n);if(e instanceof wt)e.debugRecompute();else if(e instanceof co)e.debugRerun();else throw new We("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new Kp;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 o._instance===void 0&&(o._instance=new o),o._instance}getTransactionState(){let n=[],e=[...this._activeTransactions];if(e.length===0)return;let t=e.flatMap(i=>i.debugGetUpdatingObservers()??[]).map(i=>i.observer),r=new Set;for(;t.length>0;){let i=t.shift();if(r.has(i))continue;r.add(i);let s=this._getInfo(i,a=>{r.has(a)||t.push(a)});s&&n.push(s)}return{names:e.map(i=>i.getDebugName()??"tx"),affected:n}}_getObservableInfo(n){let e=this._instanceInfos.get(n);if(!e){st(new We("No info found"));return}return e}_getAutorunInfo(n){let e=this._instanceInfos.get(n);if(!e){st(new We("No info found"));return}return e}_getInfo(n,e){if(n instanceof wt){let t=[...n.debugGetObservers()];for(let l of t)e(l);let r=this._getObservableInfo(n);if(!r)return;let i=n.debugGetState(),s={name:n.debugName,instanceId:r.instanceId,updateCount:i.updateCount},a=[...r.changedObservables].map(l=>this._instanceInfos.get(l)?.instanceId).filter(_r);if(i.isComputing)return{...s,type:"observable/derived",state:"updating",changedDependencies:a,initialComputation:!1};switch(i.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 co){let t=this._getAutorunInfo(n);if(!t)return;let r={name:n.debugName,instanceId:t.instanceId,updateCount:t.updateCount},i=[...t.changedObservables].map(s=>this._instanceInfos.get(s).instanceId);if(n.debugGetState().isRunning)return{...r,type:"autorun",state:"updating",changedDependencies:i};switch(n.debugGetState().state){case 3:return{...r,type:"autorun",state:"upToDate"};case 2:return{...r,type:"autorun",state:"stale",changedDependencies:i};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 wt)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){Nv(this._fullState,n),this._pendingChanges===null?this._pendingChanges=n:Lv(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 wt?"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 wt){this._handleDerivedRecomputed(n,e);return}let t=this._getObservableInfo(n);t&&e.didChange&&(t.lastValue=Rn(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=Rn(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 Ww(o,n){let e=n?.debugNamePostProcessor??(i=>i),t=Yi.from(o,e);if(!t)return"";let r=new Set;return n.type==="observers"?Bw(t,0,r,n).trim():qw(t,0,r,n).trim()}function qw(o,n,e,t){let r="		".repeat(n),i=[];if(e.has(o.sourceObj))return i.push(`${r}* ${o.type} ${o.name} (already listed)`),i.join(`
`);if(e.add(o.sourceObj),i.push(`${r}* ${o.type} ${o.name}:`),i.push(`${r}  value: ${Rn(o.value,50)}`),i.push(`${r}  state: ${o.state}`),o.dependencies.length>0){i.push(`${r}  dependencies:`);for(let a of o.dependencies){let l=Yi.from(a,t.debugNamePostProcessor??(d=>d))??Yi.unknown(a);i.push(qw(l,n+1,e,t))}}return i.join(`
`)}function Bw(o,n,e,t){let r="		".repeat(n),i=[];if(e.has(o.sourceObj))return i.push(`${r}* ${o.type} ${o.name} (already listed)`),i.join(`
`);if(e.add(o.sourceObj),i.push(`${r}* ${o.type} ${o.name}:`),i.push(`${r}  value: ${Rn(o.value,50)}`),i.push(`${r}  state: ${o.state}`),o.observers.length>0){i.push(`${r}  observers:`);for(let a of o.observers){let l=Yi.from(a,t.debugNamePostProcessor??(d=>d))??Yi.unknown(a);i.push(Bw(l,n+1,e,t))}}return i.join(`
`)}var Yi=class o{constructor(n,e,t,r,i,s,a){this.sourceObj=n;this.name=e;this.type=t;this.value=r;this.state=i;this.dependencies=s;this.observers=a}static from(n,e){if(n instanceof co){let t=n.debugGetState();return new o(n,e(n.debugName),"autorun",void 0,t.stateStr,Array.from(t.dependencies),[])}else if(n instanceof wt){let t=n.debugGetState();return new o(n,e(n.debugName),"derived",t.value,t.stateStr,Array.from(t.dependencies),Array.from(n.debugGetObservers()))}else if(n instanceof Ar){let t=n.debugGetState();return new o(n,e(n.debugName),"observableValue",t.value,"upToDate",[],Array.from(n.debugGetObservers()))}else if(n instanceof Kn){let t=n.debugGetState();return new o(n,e(n.debugName),"fromEvent",t.value,t.hasValue?"upToDate":"initial",[],Array.from(n.debugGetObservers()))}}static unknown(n){return new o(n,"(unknown)","unknown",void 0,"unknown",[],[])}};Nw(Ww);Aw(Hw);var JO=!1;JO&&Gd(new Qd);Xe&&Xe.VSCODE_DEV_DEBUG_OBSERVABLES&&Gd(Gp.getInstance());var Uv=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]}},Fv=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?np(n,this._value,0,n.length,this._from,this._to):Oi(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},Jp=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?np(n,this._value,0,n.length,this._from,this._to):Oi(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var Hv=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 Jp(!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 Wy(n,this._value.scheme);if(this._states[this._stateIdx]===2)return Wy(n,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(n);if(this._states[this._stateIdx]===4)return Hn(n,this._value.query);if(this._states[this._stateIdx]===5)return Hn(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}},uo=class o{static{this.Val=Symbol("undefined_placeholder")}static wrap(n){return n===void 0?o.Val:n}static unwrap(n){return n===o.Val?void 0:n}},la=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 Er=class o{static forUris(n=()=>!1,e=()=>!1){return new o(new Hv(n,e))}static forPaths(n=!1){return new o(new Jp(void 0,!n))}static forStrings(){return new o(new Uv)}static forConfigKeys(){return new o(new Fv)}constructor(n){this._iter=n}clear(){this._root=void 0}fill(n,e){if(e){let t=e.slice(0);Cy(t);for(let r of t)this.set(r,n)}else{let t=n.slice(0);Cy(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 la,this._root.segment=t.value());let i=[];for(r=this._root;;){let a=t.cmp(r.segment);if(a>0)r.left||(r.left=new la,r.left.segment=t.value()),i.push([-1,r]),r=r.left;else if(a<0)r.right||(r.right=new la,r.right.segment=t.value()),i.push([1,r]),r=r.right;else if(t.hasNext())t.next(),r.mid||(r.mid=new la,r.mid.segment=t.value()),i.push([0,r]),r=r.mid;else break}let s=uo.unwrap(r.value);r.value=uo.wrap(e),r.key=n;for(let a=i.length-1;a>=0;a--){let l=i[a][1];l.updateHeight();let d=l.balanceFactor();if(d<-1||d>1){let c=i[a][0],u=i[a+1][0];if(c===1&&u===1)i[a][1]=l.rotateLeft();else if(c===-1&&u===-1)i[a][1]=l.rotateRight();else if(c===1&&u===-1)l.right=i[a+1][1]=i[a+1][1].rotateRight(),i[a][1]=l.rotateLeft();else if(c===-1&&u===1)l.left=i[a+1][1]=i[a+1][1].rotateLeft(),i[a][1]=l.rotateRight();else throw new Error;if(a>0)switch(i[a-1][0]){case-1:i[a-1][1].left=i[a][1];break;case 1:i[a-1][1].right=i[a][1];break;case 0:i[a-1][1].mid=i[a][1];break}else this._root=i[0][1]}}return s}get(n){return uo.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=[],i=this._root;for(;i;){let s=t.cmp(i.segment);if(s>0)r.push([-1,i]),i=i.left;else if(s<0)r.push([1,i]),i=i.right;else if(t.hasNext())t.next(),r.push([0,i]),i=i.mid;else break}if(i){if(e?(i.left=void 0,i.mid=void 0,i.right=void 0,i.height=1):(i.key=void 0,i.value=void 0),!i.mid&&!i.value)if(i.left&&i.right){let s=[[1,i]],a=this._min(i.right,s);if(a.key){i.key=a.key,i.value=a.value,i.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:cd(!1);case 1:cd(!1)}}else i.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=i.left??i.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 i=e.cmp(t.segment);if(i>0)t=t.left;else if(i<0)t=t.right;else if(e.hasNext())e.next(),r=uo.unwrap(t.value)||r,t=t.mid;else break}return t&&uo.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 i=t.cmp(r.segment);if(i>0)r=r.left;else if(i<0)r=r.right;else if(t.hasNext())t.next(),r=r.mid;else return r.mid?this._entries(r.mid):e?uo.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,uo.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 Pe=W("fileService");function fo(o){return o.create===!0}function xn(o){return!!(o.capabilities&2)}function zw(o){return!!(o.capabilities&524288)}function $v(o){return!!(o.capabilities&8)}function Vw(o){return!!(o.capabilities&131072)}function jw(o){return!!(o.capabilities&262144)}function go(o){return!!(o.capabilities&4)}function Xp(o){return!!(o.capabilities&16)}function Zp(o){return xn(o)?!!(o.capabilities&16384):!1}function Wv(o){return xn(o)?!!(o.capabilities&32768):!1}function Kw(o){return!!(o.capabilities&65536)}var da=class o extends Error{constructor(e,t){super(e);this.code=t}static create(e,t){let r=new o(e.toString(),t);return YO(r,t),r}};function Me(o,n){return da.create(o,n)}function mo(o){return o||Me(f(2661,null),"Unknown")}function YO(o,n){return o.name=n?`${n} (FileSystemError)`:"FileSystemError",o}function fn(o){if(!o)return"Unknown";if(o instanceof da)return o.code;let n=/^(.+) \(FileSystemError\)$/.exec(o.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 ho(o){if(o instanceof lt)return o.fileOperationResult;switch(fn(o)){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 po=class{constructor(n,e,t){this.resource=n;this.operation=e;this.target=t}isOperation(n){return this.operation===n}};var Yp=class o{constructor(n,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new Be(()=>{let n=Er.forUris(()=>this.ignorePathCasing);return n.fill(this.rawAdded.map(e=>[e,!0])),n});this.updated=new Be(()=>{let n=Er.forUris(()=>this.ignorePathCasing);return n.fill(this.rawUpdated.map(e=>[e,!0])),n});this.deleted=new Be(()=>{let n=Er.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!==o.MIXED_CORRELATION&&(typeof t.cId=="number"?this.correlationId===void 0?this.correlationId=t.cId:this.correlationId!==t.cId&&(this.correlationId=o.MIXED_CORRELATION):this.correlationId!==void 0&&(this.correlationId=o.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 Gw(o,n,e){return!o||!n||o===n||n.length>o.length?!1:(n.charAt(n.length-1)!==Le&&(n+=Le),e?$o(o,n):o.indexOf(n)===0)}var lt=class extends Error{constructor(e,t,r){super(e);this.fileOperationResult=t;this.options=r}},ca=class extends lt{constructor(e,t,r,i){super(e,t,i);this.fileOperationResult=t;this.size=r}},ua=class extends lt{constructor(e,t,r){super(e,2,r);this.stat=t}};var ef="";function qv(o){if(!(typeof o.size!="number"||typeof o.mtime!="number"))return o.mtime.toString(29)+o.size.toString(31)}var Qp=class o{static{this.KB=1024}static{this.MB=o.KB*o.KB}static{this.GB=o.MB*o.KB}static{this.TB=o.GB*o.KB}static formatSize(n){return xi(n)||(n=0),n<o.KB?f(2656,null,n.toFixed(0)):n<o.MB?f(2658,null,(n/o.KB).toFixed(2)):n<o.GB?f(2659,null,(n/o.MB).toFixed(2)):n<o.TB?f(2657,null,(n/o.GB).toFixed(2)):f(2660,null,(n/o.TB).toFixed(2))}};var Jn=class{constructor(n,e=[],t=!1){this.ctor=n,this.staticArguments=e,this.supportsDelayedInstantiation=t}};var Bv=class{constructor(n,e){this.key=n;this.data=e;this.incoming=new Map;this.outgoing=new Map}},Xd=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 Bv(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 i=this._findCycle(r,e);if(i)return i;e.delete(t)}}};var Xo=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 QO=!1,tf=class extends Error{constructor(n){super("cyclic dependency between services"),this.message=n.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${n.toString()}`}},pa=class o{constructor(n=new Xo,e=!1,t,r=QO){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(xe,this),this._globalGraph=r?t?._globalGraph??new Xd(i=>i):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,Gt(this._children),this._children.clear();for(let n of this._servicesToMaybeDispose)Os(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 o{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=Zd.traceInvocation(this._enableTracing,n),r=!1;try{return n({get:s=>{if(r)throw $u("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 Jn?(t=Zd.traceCreation(this._enableTracing,n.ctor),r=this._createInstance(n.ctor,n.staticArguments.concat(e),t)):(t=Zd.traceCreation(this._enableTracing,n),r=this._createInstance(n,e,t)),t.stop(),r}_createInstance(n,e=[],t){let r=ir.getServiceDependencies(n).sort((a,l)=>a.index-l.index),i=[];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),i.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(i))}_setCreatedServiceInstance(n,e){if(this._services.get(n)instanceof Jn)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 Jn?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 Xd(l=>l.id.toString()),i=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),i++>1e3)throw new tf(r);for(let d of ir.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 Jn){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 tf(r);break}for(let{data:d}of l){if(this._getServiceInstanceOrDescriptor(d.id)instanceof Jn){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,i){if(this._services.get(n)instanceof Jn)return this._createServiceInstance(n,e,t,r,i,this._servicesToMaybeDispose);if(this._parent)return this._parent._createServiceInstanceWithOwner(n,e,t,r,i);throw new Error(`illegalState - creating UNKNOWN service instance ${e.name}`)}_createServiceInstance(n,e,t=[],r,i,s){if(r){let a=new o(void 0,this._strict,this,this._enableTracing);a._globalGraphImplicitDependency=String(n);let l=new Map,d=new pp(()=>{let c=a._createInstance(e,t,i);for(let[u,p]of l){let m=c[u];if(typeof m=="function")for(let v of p)v.disposable=m.apply(c,v.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 v=l.get(u);return v||(v=new gd,l.set(u,v)),(S,b,I)=>{if(d.isInitialized)return d.value[u](S,b,I);{let _={listener:[S,b,I],disposable:void 0},T=v.push(_);return N(()=>{T(),_.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,i);return s.add(a),a}}_throwIfStrict(n,e){if(e&&console.warn(n),this._strict)throw new Error(n)}};var Zd=class o{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 o{constructor(){super(0,null)}stop(){}branch(){return this}}}static traceInvocation(n,e){return n?new o(2,e.name||new Error().stack.split(`
`).slice(3,4).join(`
`)):o._None}static traceCreation(n,e){return n?new o(1,e.name):o._None}static{this._totals=0}branch(n,e){let t=new o(3,n.toString());return this._dep.push([n,e,t]),t}stop(){let n=Date.now()-this._start;o._totals+=n;let e=!1;function t(i,s){let a=[],l=new Array(i+1).join("	");for(let[d,c,u]of s._dep)if(c&&u){e=!0,a.push(`${l}CREATES -> ${d}`);let p=t(i+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 ${o._totals.toFixed(2)}ms)`];(n>2||e)&&o.all.add(r.join(`
`))}};function gn(o){return Vv(o,0)}function Vv(o,n){switch(typeof o){case"object":return o===null?yo(349,n):Array.isArray(o)?ZO(o,n):eL(o,n);case"string":return Yw(o,n);case"boolean":return XO(o,n);case"number":return yo(o,n);case"undefined":return yo(937,n);default:return yo(617,n)}}function yo(o,n){return(n<<5)-n+o|0}function XO(o,n){return yo(o?433:863,n)}function Yw(o,n){n=yo(149417,n);for(let e=0,t=o.length;e<t;e++)n=yo(o.charCodeAt(e),n);return n}function ZO(o,n){return n=yo(104579,n),o.reduce((e,t)=>Vv(t,e),n)}function eL(o,n){return n=yo(181387,n),Object.keys(o).sort().reduce((e,t)=>(e=Yw(t,e),Vv(o[t],e)),n)}function zv(o,n,e=32){let t=e-n,r=~((1<<t)-1);return(o<<n|(r&o)>>>t)>>>0}function ec(o,n=32){return o instanceof ArrayBuffer?Ko(F.wrap(new Uint8Array(o))):(o>>>0).toString(16).padStart(n/4,"0")}var Jw=class o{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,i=this._leftoverHighSurrogate,s,a;for(i!==0?(s=i,a=-1,i=0):(s=n.charCodeAt(0),a=0);;){let l=s;if(T_(s))if(a+1<e){let d=n.charCodeAt(a+1);By(d)?(a++,l=w_(s,d)):l=65533}else{i=s;break}else By(s)&&(l=65533);if(r=this._push(t,r,l),a++,a<e)s=n.charCodeAt(a);else break}this._buffLen=r,this._leftoverHighSurrogate=i}_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()),ec(this._h0)+ec(this._h1)+ec(this._h2)+ec(this._h3)+ec(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=o._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,zv(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,i=this._h2,s=this._h3,a=this._h4,l,d,c;for(let u=0;u<80;u++)u<20?(l=r&i|~r&s,d=1518500249):u<40?(l=r^i^s,d=1859775393):u<60?(l=r&i|r&s|i&s,d=2400959708):(l=r^i^s,d=3395469782),c=zv(t,5)+l+a+d+n.getUint32(u*4,!1)&4294967295,a=s,s=i,i=zv(r,30),r=t,t=c;this._h0=this._h0+t&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+i&4294967295,this._h3=this._h3+s&4294967295,this._h4=this._h4+a&4294967295}};function jv(...o){switch(o.length){case 1:return f(2462,null,o[0]);case 2:return f(2463,null,o[0],o[1]);case 3:return f(2464,null,o[0],o[1],o[2]);default:return}}var tL=f(2461,null),nL=f(2460,null),Zo=class o{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 $u(`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(jv("==","=~"));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(jv("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(jv("||"));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=o._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(tL);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(nL);return}let i=this._input.charCodeAt(n);if(e)e=!1;else if(i===47&&!t){n++;break}else i===91?t=!0:i===92?e=!0:i===93&&(t=!1);n++}for(;n<this._input.length&&o._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 kt=new Map;kt.set("false",!1);kt.set("true",!0);kt.set("isMac",dt);kt.set("isLinux",Oe);kt.set("isWindows",Q);kt.set("isWeb",Nn);kt.set("isMacNative",dt&&!Nn);kt.set("isEdge",o_);kt.set("isFirefox",n_);kt.set("isChrome",ky);kt.set("isSafari",r_);var rL=Object.prototype.hasOwnProperty;var oL={regexParsingWithErrorRecovery:!0},iL=f(2441,null),sL=f(2442,null),aL=f(2444,null),Qw=f(2440,null),lL=f(2447,null),dL=f(2448,null),cL=f(2445,null),uL=f(2446,null),Kv=class o{constructor(n=oL){this._config=n;this._scanner=new Zo;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:iL,offset:0,lexeme:"",additionalInfo:sL});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?dL:void 0;throw this._parsingErrors.push({message:lL,offset:t.offset,lexeme:Zo.getLexeme(t),additionalInfo:r}),o._parseError}return e}catch(e){if(e!==o._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]:Ft.or(...n)}_and(){let n=[this._term()];for(;this._matchOne(15);){let e=this._term();n.push(e)}return n.length===1?n[0]:Ft.and(...n)}_term(){if(this._matchOne(2)){let n=this._peek();switch(n.type){case 11:return this._advance(),zt.INSTANCE;case 12:return this._advance(),Qt.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,Qw),e?.negate()}case 17:return this._advance(),Xi.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(),Ft.true();case 12:return this._advance(),Ft.false();case 0:{this._advance();let e=this._expr();return this._consume(1,Qw),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 i=r.lexeme,s=i.lastIndexOf("/"),a=s===i.length-1?void 0:this._removeFlagsGY(i.substring(s+1)),l;try{l=new RegExp(i.substring(1,s),a)}catch{throw this._errExpectedButGot("REGEX",r)}return ac.create(e,l)}switch(r.type){case 10:case 19:{let i=[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;i.push(Zo.getLexeme(s)),this._advance(),s=this._peek()}let l=i.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 Ft.regex(e,u)}case 18:{let i=r.lexeme;this._advance();let s=null;if(!S_(i)){let a=i.indexOf("/"),l=i.lastIndexOf("/");if(a!==l&&a>=0){let d=i.slice(a+1,l),c=i[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 ac.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,aL);let r=this._value();return Ft.notIn(e,r)}switch(this._peek().type){case 3:{this._advance();let r=this._value();if(this._previous().type===18)return Ft.equals(e,r);switch(r){case"true":return Ft.has(e);case"false":return Ft.not(e);default:return Ft.equals(e,r)}}case 4:{this._advance();let r=this._value();if(this._previous().type===18)return Ft.notEquals(e,r);switch(r){case"true":return Ft.not(e);case"false":return Ft.has(e);default:return Ft.notEquals(e,r)}}case 5:return this._advance(),ic.create(e,this._value());case 6:return this._advance(),sc.create(e,this._value());case 7:return this._advance(),fa.create(e,this._value());case 8:return this._advance(),oc.create(e,this._value());case 13:return this._advance(),Ft.in(e,this._value());default:return Ft.has(e)}}case 20:throw this._parsingErrors.push({message:cL,offset:n.offset,lexeme:"",additionalInfo:uL}),o._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(2443,null,n,Zo.getLexeme(e)),i=e.offset,s=Zo.getLexeme(e);return this._parsingErrors.push({message:r,offset:i,lexeme:s,additionalInfo:t}),o._parseError}_check(n){return this._peek().type===n}_peek(){return this._tokens[this._current]}_isAtEnd(){return this._peek().type===20}},Ft=class{static false(){return zt.INSTANCE}static true(){return Qt.INSTANCE}static has(n){return Qi.create(n)}static equals(n,e){return nc.create(n,e)}static notEquals(n,e){return rc.create(n,e)}static regex(n,e){return ac.create(n,e)}static in(n,e){return nf.create(n,e)}static notIn(n,e){return rf.create(n,e)}static not(n){return Xi.create(n)}static and(...n){return of.create(n,null,!0)}static or(...n){return lc.create(n,null,!0)}static greater(n,e){return fa.create(n,e)}static greaterEquals(n,e){return oc.create(n,e)}static smaller(n,e){return ic.create(n,e)}static smallerEquals(n,e){return sc.create(n,e)}static{this._parser=new Kv({regexParsingWithErrorRecovery:!1})}static deserialize(n){return n==null?void 0:this._parser.parse(n)}};function tc(o,n){return o.cmp(n)}var zt=class o{constructor(){this.type=0}static{this.INSTANCE=new o}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 Qt.INSTANCE}},Qt=class o{constructor(){this.type=1}static{this.INSTANCE=new o}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 zt.INSTANCE}},Qi=class o{constructor(n,e){this.key=n;this.negated=e;this.type=2}static create(n,e=null){let t=kt.get(n);return typeof t=="boolean"?t?Qt.INSTANCE:zt.INSTANCE:new o(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:eR(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=kt.get(this.key);return typeof n=="boolean"?n?Qt.INSTANCE:zt.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=Xi.create(this.key,this)),this.negated}},nc=class o{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?Qi.create(n,t):Xi.create(n,t);let r=kt.get(n);return typeof r=="boolean"?e===(r?"true":"false")?Qt.INSTANCE:zt.INSTANCE:new o(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=kt.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?Qt.INSTANCE:zt.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=rc.create(this.key,this.value,this)),this.negated}},nf=class o{constructor(n,e){this.key=n;this.valueKey=e;this.type=10;this.negated=null}static create(n,e){return new o(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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(i=>typeof i=="string"&&i.toLowerCase()===r)}return!1}if(typeof t=="string"&&typeof e=="object"&&e!==null){if(rL.call(e,t))return!0;if(Q&&t.startsWith("file:///")){let r=t.toLowerCase();return Object.keys(e).some(i=>i.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=rf.create(this.key,this.valueKey)),this.negated}},rf=class o{constructor(n,e){this.key=n;this.valueKey=e;this.type=11;this._negated=nf.create(n,e)}static create(n,e){return new o(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}},rc=class o{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?Xi.create(n,t):Qi.create(n,t);let r=kt.get(n);return typeof r=="boolean"?e===(r?"true":"false")?zt.INSTANCE:Qt.INSTANCE:new o(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=kt.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?zt.INSTANCE:Qt.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=nc.create(this.key,this.value,this)),this.negated}},Xi=class o{constructor(n,e){this.key=n;this.negated=e;this.type=3}static create(n,e=null){let t=kt.get(n);return typeof t=="boolean"?t?zt.INSTANCE:Qt.INSTANCE:new o(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:eR(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=kt.get(this.key);return typeof n=="boolean"?n?zt.INSTANCE:Qt.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=Qi.create(this.key,this)),this.negated}};function af(o,n){if(typeof o=="string"){let e=parseFloat(o);isNaN(e)||(o=e)}return typeof o=="string"||typeof o=="number"?n(o):zt.INSTANCE}var fa=class o{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=12}static create(n,e,t=null){return af(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=sc.create(this.key,this.value,this)),this.negated}},oc=class o{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=13}static create(n,e,t=null){return af(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=ic.create(this.key,this.value,this)),this.negated}},ic=class o{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=14}static create(n,e,t=null){return af(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=oc.create(this.key,this.value,this)),this.negated}},sc=class o{constructor(n,e,t){this.key=n;this.value=e;this.negated=t;this.type=15}static create(n,e,t=null){return af(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Zi(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=fa.create(this.key,this.value,this)),this.negated}},ac=class o{constructor(n,e){this.key=n;this.regexp=e;this.type=7;this.negated=null}static create(n,e){return new o(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=Gv.create(this)),this.negated}},Gv=class o{constructor(n){this._actual=n;this.type=8}static create(n){return new o(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 o(this._actual.map(n))}negate(){return this._actual}};function Zw(o){let n=null;for(let e=0,t=o.length;e<t;e++){let r=o[e].substituteConstants();if(o[e]!==r&&n===null){n=[];for(let i=0;i<e;i++)n[i]=o[i]}n!==null&&(n[e]=r)}return n===null?o:n}var of=class o{constructor(n,e){this.expr=n;this.negated=e;this.type=6}static create(n,e,t){return o._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=tc(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=Zw(this.expr);return n===this.expr?this:o.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=[],i=!1;for(let s of n)if(s){if(s.type===1){i=!0;continue}if(s.type===0)return zt.INSTANCE;if(s.type===6){r.push(...s.expr);continue}r.push(s)}if(r.length===0&&i)return Qt.INSTANCE;if(r.length!==0){if(r.length===1)return r[0];r.sort(tc);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=lc.create(s.expr.map(c=>o.create([c,a],null,t)),null,l);d&&(r.push(d),r.sort(tc))}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 zt.INSTANCE;if(r.length===1)return r[0]}return new o(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 o(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=lc.create(n,this,!0)}return this.negated}},lc=class o{constructor(n,e){this.expr=n;this.negated=e;this.type=9}static create(n,e,t){return o._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=tc(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=Zw(this.expr);return n===this.expr?this:o.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=[],i=!1;if(n){for(let s=0,a=n.length;s<a;s++){let l=n[s];if(l){if(l.type===0){i=!0;continue}if(l.type===1)return Qt.INSTANCE;if(l.type===9){r=r.concat(l.expr);continue}r.push(l)}}if(r.length===0&&i)return zt.INSTANCE;r.sort(tc)}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 Qt.INSTANCE;if(r.length===1)return r[0]}return new o(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 o(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 i of Xw(e))for(let s of Xw(t))r.push(of.create([i,s],null,!1));n.unshift(o.create(r,null,!1))}this.negated=o.create(n,this,!0)}return this.negated}},sf=class o extends Qi{static{this._info=[]}static all(){return o._info.values()}constructor(n,e,t){super(n,null),this._defaultValue=e,typeof t=="object"?o._info.push({...t,key:n}):t!==!0&&o._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 nc.create(this.key,n)}notEqualsTo(n){return rc.create(this.key,n)}greater(n){return fa.create(this.key,n)}},dY=W("contextKeyService");function eR(o,n){return o<n?-1:o>n?1:0}function Zi(o,n,e,t){return o<e?-1:o>e?1:n<t?-1:n>t?1:0}function Xw(o){return o.type===9?o.expr:[o]}var M=W("logService"),nR=W("loggerService");function Yv(o){return xi(o)}var rR=3;function pL(o,n){return o!==0&&o<=n}function fL(o,n,e){switch(n){case 1:o.trace(e);break;case 2:o.debug(e);break;case 3:o.info(e);break;case 4:o.warn(e);break;case 5:o.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${n}`)}}var oR=!1,tR=!1,gL=!1;function dc(o,n){switch(o){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 iR(o){let n={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn},e=(r,i,s)=>{if(!gL){tR=!0;try{fL(o,i,vo(s))}catch{}finally{tR=!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 dc("debug",t.debug),dc("error",t.error),dc("info",t.info),dc("log",t.log),dc("warn",t.warn),N(()=>{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 vo(o,n=!1){let e="";for(let t=0;t<o.length;t++){let r=o[t];if(r instanceof Error&&(r=De(r,n)),typeof r=="object")try{r=JSON.stringify(r)}catch{}e+=(t>0?" ":"")+r}return e}var lf=class extends w{constructor(){super(...arguments);this.level=rR;this._onDidChangeLogLevel=this._register(new A)}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 pL(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},es=class extends lf{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...t){this.canLog(1)&&this.log(1,vo([e,...t],!0))}debug(e,...t){this.canLog(2)&&this.log(2,vo([e,...t]))}info(e,...t){this.canLog(3)&&this.log(3,vo([e,...t]))}warn(e,...t){this.canLog(4)&&this.log(4,vo([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,vo(r))}else this.log(5,vo([e,...t]))}flush(){}};var df=class extends lf{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()}},cc=class extends w{constructor(e,t,r){super();this.logLevel=e;this.logsHome=t;this._loggers=new qe;this._onDidChangeLoggers=this._register(new A);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new A);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new A);this.onDidChangeVisibility=this._onDidChangeVisibility.event;if(r)for(let i of r)this._loggers.set(i.resource,{logger:void 0,info:i})}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),i=Ve(e)?e:t?.id??gn(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:i}));let l={logger:s,info:{resource:r,id:i,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(h.isUri(e)){let r=e,i=t,s=this._loggers.get(r);s&&i!==s.info.logLevel&&(s.info.logLevel=i===this.logLevel?void 0:i,s.logger?.setLevel(i),this._loggers.set(s.info.resource,s),this._onDidChangeLogLevel.fire([r,i]))}else{this.logLevel=e;for(let[r,i]of this._loggers.entries())this._loggers.get(r)?.info.logLevel===void 0&&i.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()}},Jv=class{constructor(){this.onDidChangeLogLevel=new A().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(){}},cf=class extends Jv{};function sR(o){if(o.verbose)return 1;if(typeof o.logLevel=="string"){let n=hL(o.logLevel.toLowerCase());if(n!==void 0)return n}return rR}function mL(o){switch(o){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 hL(o){switch(o){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 wY=new sf("logLevel",mL(3));var rt=W("sessionDataService"),ga="session.db",uf="attachments";var pR="branch",fR="uncommitted",gR="session",pf="turn/",mR="{turnId}",ff="compare/",hR="{originalTurnId}",yR="{modifiedTurnId}",yL=()=>f(1948,null),aR=()=>f(1952,null),lR=()=>f(1951,null),vL=()=>f(1956,null),SL=()=>f(1955,null),dR=()=>f(1954,null),cR=()=>f(1953,null),bL=()=>f(1950,null),CL=()=>f(1949,null);function IL(o){let{baseBranchName:n,branchName:e,upstreamBranchName:t}=o;return n&&e?`${e} \u2192 ${n}`:t&&e?`${e} \u2192 ${t}`:e}var So="/changeset/";function Co(o){return`${o}${So}${pR}`}function bo(o){return`${o}${So}${gR}`}function ei(o){return`${o}${So}${fR}`}function uR(o){return`${o}${So}${pf}${mR}`}function gf(o,n){if(!n||n.includes("/"))throw new Error(`buildTurnChangesetUri: turnId must be non-empty and not contain '/' (got ${JSON.stringify(n)})`);return`${o}${So}${pf}${n}`}function _L(o){return`${o}${So}${ff}${hR}/${yR}`}function vR(o,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`${o}${So}${ff}${n}/${e}`}function Je(o){let n=o.lastIndexOf(So);if(n<0)return;let e=o.slice(n+So.length);if(!e)return;let t=o.slice(0,n);if(e===pR)return{sessionUri:t,changesetId:e,kind:"branch"};if(e===fR)return{sessionUri:t,changesetId:e,kind:"uncommitted"};if(e===gR)return{sessionUri:t,changesetId:e,kind:"session"};if(e.startsWith(pf)){let r=e.slice(pf.length);return!r||r.includes("/")||r===mR?void 0:{sessionUri:t,changesetId:e,kind:"turn",turnId:r}}if(e.startsWith(ff)){let i=e.slice(ff.length).split("/");if(i.length!==2)return;let[s,a]=i;return!s||!a||s===hR||a===yR?void 0:{sessionUri:t,changesetId:e,kind:"compare-turns",originalTurnId:s,modifiedTurnId:a}}if(!e.includes("/"))return{sessionUri:t,changesetId:e,kind:"unknown"}}function SR(o,n){return n?[{label:yL(),description:n?IL(n):void 0,uriTemplate:Co(o),changeKind:"branch",capabilities:{review:{}}},{label:vL(),description:SL(),uriTemplate:ei(o),changeKind:"uncommitted"},{label:aR(),description:lR(),uriTemplate:bo(o),changeKind:"session"},{label:dR(),description:cR(),uriTemplate:uR(o),changeKind:"turn"},{label:bL(),description:CL(),uriTemplate:_L(o),changeKind:"compare-turns"}]:[{label:aR(),description:lR(),uriTemplate:bo(o),changeKind:"session"},{label:dR(),description:cR(),uriTemplate:uR(o),changeKind:"turn"}]}function CR(o){return o.type.startsWith("root/")}function uc(o){return o.type.startsWith("session/")}function pr(o){return o.type.startsWith("chat/")}function mf(o){return o.type.startsWith("terminal/")}function Qv(o){return o.type.startsWith("changeset/")}function Xv(o){return o.type.startsWith("annotations/")}var ft=W("productService");import*as pc from"fs";var fr=nn({customizations:ce({type:"array",title:f(1846,null),description:f(1842,null),default:[],items:{type:"object",title:f(1845,null),properties:{uri:{type:"string",title:f(1847,null)},displayName:{type:"string",title:f(1844,null)},description:{type:"string",title:f(1843,null)}},required:["uri","displayName"]}}),defaultShell:ce({type:"string",title:f(1849,null),description:f(1848,null)}),claudeUseCopilotProxy:ce({type:"boolean",title:f(1841,null),description:f(1840,null),default:!0}),githubEnterpriseUri:ce({type:"string",title:f(1851,null),description:f(1850,null)})}),IR={customizations:[]};function _R(o){return{type:"plugin",id:Nt(o.uri),uri:o.uri,name:o.displayName,enabled:!0}}var mn=nn({enableCustomTerminalTool:ce({type:"boolean",title:f(1960,null),description:f(1959,null),default:!1}),rubberDuck:ce({type:"boolean",title:f(1972,null),description:f(1971,null),default:!1}),opus48Prompt:ce({type:"boolean",title:f(1968,null),description:f(1967,null),default:!1}),reasoningEffortOverride:ce({type:"string",title:f(1970,null),description:f(1969,null),default:""}),modelCapabilityOverrides:ce({type:"object",title:f(1966,null),description:f(1961,null),additionalProperties:{type:"object",title:f(1963,null),description:f(1962,null),properties:{family:{type:"string",title:f(1965,null),description:f(1964,null)}}},default:{}})});function TL(o,n){let e=o?.[n]?.family;return typeof e=="string"&&e.length>0?e:void 0}function TR(o,n){if(!o)return;let e=TL(n,o.id);return e?{...o,id:e}:o}function Zv(o){return o===!0?"on":o===!1?"off":o}function eS(o){return o!==void 0&&Zv(o)!=="off"}var kr=nn({sandbox:ce({type:"object",title:f(1997,null),properties:{enabled:{type:"string",title:f(1994,null),enum:["off","on","allowNetwork"]},"enabled.windows":{type:"string",title:f(1998,null),enum:["off","on","allowNetwork"]},allowNetwork:{type:"boolean",title:f(1990,null)},allowUnsandboxedCommands:{type:"boolean",title:f(1991,null)},"fileSystem.linux":{type:"object",title:f(1995,null)},"fileSystem.mac":{type:"object",title:f(1996,null)},"fileSystem.windows":{type:"object",title:f(1999,null)},"advanced.runtime":{type:"object",title:f(1987,null)},allowedNetworkDomains:{type:"array",title:f(1989,null),items:{type:"string",title:f(1988,null)}},deniedNetworkDomains:{type:"array",title:f(1993,null),items:{type:"string",title:f(1992,null)}}}})}),RR={"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 He=W("agentConfigurationService"),ma=class extends w{constructor(e,t,r){super();this._stateManager=e;this._logService=t;this._rootConfigResource=r;this._rootConfigWrite=Promise.resolve();this._onDidRootConfigChange=this._register(new A);this.onDidRootConfigChange=this._onDidRootConfigChange.event;let i=this._stateManager.rootState.config,s=fr.toProtocol(),a=kr.toProtocol(),l=mn.toProtocol();this._stateManager.rootState.config={schema:{type:"object",properties:{...i?.schema.properties,...s.properties,...a.properties,...l.properties}},values:{...i?.values,...this._loadPersistedRootConfig()}},this._register(this._stateManager.onDidEmitEnvelope(d=>{d.action.type==="root/configChanged"&&this._onDidRootConfigChange.fire()}))}getEffectiveValue(e,t,r){for(let i of this._effectiveChain(e)){let s=i[r];if(s!==void 0)try{return t.assertValid(r,s),s}catch(a){let l=a instanceof L?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=ut(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 i=this._stateManager.rootState.config?.values?.[t];if(i!==void 0)try{return e.assertValid(t,i),i}catch(s){let a=s instanceof L?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(i=>{this._logService.warn("[AgentConfigurationService] Previous host config write failed",i)}).then(async()=>{await pc.promises.mkdir(oe(r.fsPath),{recursive:!0}),await pc.promises.writeFile(r.fsPath,`${t}
`,"utf8")}).catch(i=>{this._logService.error(`[AgentConfigurationService] Failed to persist host config to ${r.fsPath}`,i)})}async whenIdle(){await this._rootConfigWrite}*_effectiveChain(e){let t=this._stateManager.getSessionState(e)?.config?.values;t&&(yield t);let r=ut(e);if(r){let s=this._stateManager.getSessionState(r.parentSession.toString())?.config?.values;s&&(yield s)}let i=this._stateManager.rootState.config?.values;i&&(yield i)}_loadPersistedRootConfig(){let e=IR;if(!this._rootConfigResource)return{...e};try{let t=pc.readFileSync(this._rootConfigResource.fsPath,"utf8"),r=JSON.parse(t);return{...fr.validateOrDefault(r,e),...kr.validateOrDefault(r,{}),...mn.validateOrDefault(r,{})}}catch(t){return(t&&typeof t=="object"&&he(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}}}};ma=R([C(1,M)],ma);import*as rs from"fs";import{userInfo as LL}from"os";import*as tS from"os";var xR=/^\d+$/,xL=/^Microsoft.PowerShell_.*/,PL=/^Microsoft.PowerShellPreview_.*/;var fc;switch(process.arch){case"ia32":fc=1;break;case"arm":case"arm64":fc=2;break;default:fc=0;break}var ha;process.env.PROCESSOR_ARCHITEW6432?ha=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?ha=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?ha=1:ha=0;var ts=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 AL({useAlternateBitness:o=!1}={}){return o?fc===0?process.env["ProgramFiles(x86)"]||null:ha===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function yf({useAlternateBitness:o=!1,findPreview:n=!1}={}){let e=AL({useAlternateBitness:o});if(!e)return null;let t=j(e,"PowerShell");if(!await en.existsDirectory(t))return null;let r=-1,i=null;for(let l of await Ue.readdir(t)){let d=-1;if(n){let u=l.indexOf("-");if(u<0)continue;let p=l.substring(0,u);if(!xR.test(p)||l.substring(u+1)!=="preview")continue;d=parseInt(p,10)}else{if(!xR.test(l))continue;d=parseInt(l,10)}if(d<=r)continue;let c=j(t,l,"pwsh.exe");await en.existsFile(c)&&(i=c,r=d)}if(!i)return null;let s=e.includes("x86")?" (x86)":"",a=n?" Preview":"";return new ts(i,`PowerShell${a}${s}`,!0)}async function PR({findPreview:o}={}){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}=o?{pwshMsixDirRegex:PL,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:xL,pwshMsixName:"PowerShell (Store)"};for(let r of await Ue.readdir(n))if(e.test(r)){let i=j(n,r,"pwsh.exe");return new ts(i,t)}return null}function EL(){let o=j(tS.homedir(),".dotnet","tools","pwsh.exe");return new ts(o,".NET Core PowerShell Global Tool")}function kL(){let o=j(tS.homedir(),"scoop","apps"),n=j(o,"pwsh","current","pwsh.exe");return new ts(n,"PowerShell (Scoop)")}function DL(){let o=j(process.env.windir,fc===1&&ha!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new ts(o,"Windows PowerShell",!0)}async function*ML(){let o=await yf();o&&(yield o),o=await yf({useAlternateBitness:!0}),o&&(yield o),o=await PR(),o&&(yield o),o=EL(),o&&(yield o),o=await yf({findPreview:!0}),o&&(yield o),o=await PR({findPreview:!0}),o&&(yield o),o=await yf({useAlternateBitness:!0,findPreview:!0}),o&&(yield o),o=await kL(),o&&(yield o),o=DL(),o&&(yield o)}async function*OL(){for await(let o of ML())await o.exists()&&(yield o)}async function AR(){for await(let o of OL())return o;return null}async function vf(o,n){return o===1?Q?UL():_T(n):NL(o,n)}var nS=null;function NL(o,n){if(Oe&&o===2||dt&&o===3)return"/bin/bash";if(!nS){let e;if(Q)e="/bin/bash";else{if(e=n.SHELL,!e)try{e=LL().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}nS=e}return nS}var rS=null;async function UL(){return rS||(rS=(await AR()).exePath),rS}import*as ya from"os";var oS=class{constructor(){this.data=new Map}add(n,e){qu(Ve(n)),qu(Qe(e)),qu(!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=>{pd(n.dispose)&&n.dispose()}),this.data.clear()}},Ht=new oS;var MQ=W("ptyService");var HL={Backend:"workbench.contributions.terminal.processBackend"},iS=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()??""}};Ht.add(HL.Backend,new iS);var OQ=W("localPtyService"),LQ=W("terminalLogService");function $L(o){return new Map(o)}function WL(o){return new Map(o??[])}function ER(o){return new Map(o.map(n=>[n[0],{map:$L(n[1]),descriptionMap:WL(n[2])}]))}var BL=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),zL=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,VL="ms-python.vscode-python-envs",Sf=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(),i=r.next();for(;!i.done;){let s=i.value[1],a=i.value[0];if(this.blockPythonActivationVar(a,t)){i=r.next();continue}let l=this.map.get(a);if(l||(l=[],this.map.set(a,l)),l.length>0&&l[0].type===1){i=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),i=r.next()}})}async applyToProcessEnvironment(n,e,t){let r;Q&&(r={},Object.keys(n).forEach(i=>r[i.toLowerCase()]=i));for(let[i,s]of this.getVariableMap(e)){let a=Q&&r[i.toLowerCase()]||i;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_${BL.get(l.type)}`;n[c]=(n[c]?n[c]+":":"")+i+"="+this._encodeColons(d)}}}}}_encodeColons(n){return n.replaceAll(":","\\x3a")}blockPythonActivationVar(n,e){return!!(zL.test(n)&&VL!==e)}diff(n,e){let t=new Map,r=new Map,i=new Map;if(n.getVariableMap(e).forEach((s,a)=>{let l=this.getVariableMap(e).get(a),d=DR(s,l);d&&t.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=DR(s,l);d&&i.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=jL(s,l);d&&r.set(a,d)}),!(t.size===0&&r.size===0&&i.size===0))return{added:t,changed:r,removed:i}}getVariableMap(n){let e=new Map;for(let t of this.map.values()){let r=t.filter(i=>kR(i,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(i=>kR(i,n,!0));for(let i of r)e.set(i.extensionIdentifier,i.description)}return e}populateDescriptionMap(n,e){if(!n.descriptionMap)return;let t=n.descriptionMap.entries(),r=t.next();for(;!r.done;){let i=r.value[1],s=r.value[0],a=this.descriptionMap.get(s);a||(a=[],this.descriptionMap.set(s,a));let l={extensionIdentifier:e,scope:i.scope,description:i.description};l.scope||delete l.scope,a.push(l),r=t.next()}}};function kR(o,n,e=!1){return o.scope?!!(o.scope.workspaceFolder&&n?.workspaceFolder&&o.scope.workspaceFolder.index===n.workspaceFolder.index):e?n===o.scope:!0}function DR(o,n){if(!n)return o;let e=new Set;n.forEach(r=>e.add(r.extensionIdentifier));let t=[];return o.forEach(r=>{e.has(r.extensionIdentifier)||t.push(r)}),t.length===0?void 0:t}function jL(o,n){if(!n)return;let e=new Map;n.forEach(r=>e.set(r.extensionIdentifier,r));let t=[];return o.forEach(r=>{let i=e.get(r.extensionIdentifier);i&&(r.type!==i.type||r.value!==i.value||r.scope?.workspaceFolder?.index!==i.scope?.workspaceFolder?.index)&&t.push(i)}),t.length===0?void 0:t}import{chmod as OR,realpathSync as JL,mkdirSync as YL}from"fs";import{promisify as LR}from"util";import*as bf from"os";var gc;async function KL(){if(gc)return;if(!Q){gc={release:bf.release(),buildNumber:0};return}let o,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&&(o=parseInt(r,10),isNaN(o)&&(o=void 0));let i=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",t,"CurrentMajorVersionNumber"),s=e.GetDWORDRegKey("HKEY_LOCAL_MACHINE",t,"CurrentMinorVersionNumber");i!==void 0&&s!==void 0&&r!==void 0&&(n=`${i}.${s}.${r}`)}catch{}finally{gc={release:n||bf.release(),buildNumber:o||GL()}}}async function MR(){return gc||await KL(),gc.buildNumber}function GL(){let o=/(\d+)\.(\d+)\.(\d+)/g.exec(bf.release());return o&&o.length===4?parseInt(o[3],10):0}async function HR(o,n,e,t,r,i=!1){if(!n.shellIntegration.enabled)return{type:"failure",reason:"injectionSettingDisabled"};if(!o.executable)return{type:"failure",reason:"noExecutable"};if(o.isFeatureTerminal&&!o.forceShellIntegration)return{type:"failure",reason:"featureTerminal"};if(o.ignoreShellIntegration)return{type:"failure",reason:"ignoreShellIntegrationFlag"};let s=Q?await MR():0;if(Q&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=o.args,l=Ls==="win32"?Te(o.executable).toLowerCase():Te(o.executable),d=oe(Lt.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(o.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||FR(a)?u=et.get("windows-pwsh"):UR(a)&&(u=et.get("windows-pwsh-login")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d,""),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"}):l==="bash.exe"?(!a||a.length===0?u=et.get("bash"):_f(a)&&(p.VSCODE_SHELL_LOGIN="1",Cf(n,p,l),u=et.get("bash")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"}):(t.warn(`Shell integration cannot be enabled for executable "${o.executable}" and args`,o.args),{type:"failure",reason:"unsupportedShell"});switch(l){case"bash":return!a||a.length===0?u=et.get("bash"):_f(a)&&(p.VSCODE_SHELL_LOGIN="1",Cf(n,p,l),u=et.get("bash")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"fish":return!a||a.length===0?u=et.get("fish"):_f(a)?u=et.get("fish-login"):(a===et.get("fish")||a===et.get("fish-login"))&&(u=a),u?(Cf(n,p,l),u=[...u],u[u.length-1]=Mi(u[u.length-1],d),{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||FR(a)?u=et.get("pwsh"):UR(a)&&(u=et.get("pwsh-login")),u?(u=[...u],u[u.length-1]=Mi(u[u.length-1],d,""),p.VSCODE_STABLE=r.quality==="stable"?"1":"0",{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"zsh":{if(!a||a.length===0?u=et.get("zsh"):_f(a)?(u=et.get("zsh-login"),Cf(n,p,l)):(a===et.get("zsh")||a===et.get("zsh-login"))&&(u=a),!u)return{type:"failure",reason:"unsupportedArgs"};u=[...u],u[u.length-1]=Mi(u[u.length-1],d);let v;try{v=ya.userInfo().username}catch{v="unknown"}let y=JL(ya.tmpdir()),S=j(y,`${v}-${r.applicationName}-zsh`);if(!i)try{await LR(OR)(S,960)}catch(_){if(_.message.includes("ENOENT")){try{YL(S)}catch(T){return t.error(`Failed to create zdotdir at ${S}: ${T}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await LR(OR)(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??ya.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 "${o.executable}" and args`,o.args),{type:"failure",reason:"unsupportedShell"}}function Cf(o,n,e){if((dt||e==="fish")&&o.environmentVariableCollections){let t=ER(o.environmentVariableCollections),i=new Sf(t).getVariableMap({workspaceFolder:o.workspaceFolder}).get("PATH"),s=[];if(i)for(let a of i)a.type===3&&s.push(a.value);s.length>0&&(n.VSCODE_PATH_PREFIX=s.join(""))}}var et=new Map;et.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);et.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);et.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);et.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);et.set("zsh",["-i"]);et.set("zsh-login",["-il"]);et.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);et.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);et.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var If=["-login","-l"],NR=["--login","-l"],QL=["-i","--interactive"],Tf=["-nol","-nologo"];function UR(o){return Ve(o)?If.includes(o.toLowerCase()):o.length===1&&If.includes(o[0].toLowerCase())||o.length===2&&(If.includes(o[0].toLowerCase())||If.includes(o[1].toLowerCase()))&&(Tf.includes(o[0].toLowerCase())||Tf.includes(o[1].toLowerCase()))}function FR(o){return Ve(o)?Tf.includes(o.toLowerCase()):o.length===0||o?.length===1&&Tf.includes(o[0].toLowerCase())}function _f(o){return Ve(o)||(o=o.filter(n=>!QL.includes(n.toLowerCase()))),Ve(o)&&NR.includes(o.toLowerCase())||!Ve(o)&&o.length===1&&NR.includes(o[0].toLowerCase())}import XL from"@xterm/headless";var{Terminal:ZL}=XL,wf=class extends w{constructor(e){super();this._onResponseData=this._register(new A);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 ZL(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 Rf(o){return Mt===1?/^zsh(?:\.exe)?$/i.test(ye.basename(o)):/^zsh$/.test(re.basename(o))}function $R(o){return o.indexOf("\\")===-1?o:o.replaceAll(/\\(\\|x([0-9a-f]{2}))/gi,(n,e,t)=>t?String.fromCharCode(parseInt(t,16)):e)}function eN(o){let n=o.indexOf(";");if((n===-1?o.length:n)!==1)return;let e=o[0],t=n===-1?"":o.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(";"),i=$R(r===-1?t:t.substring(0,r)),s=r===-1?void 0:t.substring(r+1);return{type:4,commandLine:i,nonce:s}}case"P":{let r=$R(t),i=r.indexOf("=");return i===-1?void 0:{type:5,key:r.substring(0,i),value:r.substring(i+1)}}default:return}}var lS="\x1B",sS=lS+"]",aS="\x07",WR=lS+"\\",xf=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(n){let e=[];if(!this._inOsc&&n.indexOf(sS)===-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}},WR);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 i=n.indexOf(sS,r);if(i===-1){t+=n.substring(r),r=n.length;continue}t+=n.substring(r,i),r=i+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(aS,e),r=n.indexOf(lS,e);return t!==-1&&(r===-1||t<r)?(this._pendingOsc+=n.substring(e,t),{nextIndex:t+1,complete:!0,terminator:aS}):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:WR}:{nextIndex:r,complete:!0}):(this._pendingOsc+=n.substring(e),{nextIndex:n.length,complete:!1})}_handleOscPayload(n,e,t,r=aS){if(n.startsWith("633;")){let i=n.substring(4),s=eN(i);s&&e.push(s)}else t&&t.append(t.value+sS+n+r)}};var tN=1e4,nN=0,dS="\x1B[6n",cS="\x1B[?6n",rN=["\x1B[?6","\x1B[?","\x1B[6","\x1B[","\x1B"],Dr=W("agentHostTerminalManager");function oN(o,n){if(!n.pendingData&&!o.includes(dS)&&!o.includes(cS)&&!qR(o))return o;let e=n.pendingData+o,t=qR(e),r=t?e.substring(0,e.length-t.length):e;return n.pendingData=t,!r.includes(dS)&&!r.includes(cS)?r:r.replaceAll(cS,"").replaceAll(dS,"")}function qR(o){for(let n of rN)if(o.endsWith(n))return n;return""}function iN(o,n){return n.forceBracketedPasteMode&&(o=`\x1B[200~${o}\x1B[201~`),o=o.replace(/\r?\n/g,"\r"),n.shouldExecute&&!o.endsWith("\r")&&(o+="\r"),o}var uS;async function sN(){return uS||(uS=await import("node-pty")),uS}var va=class extends w{constructor(e,t,r,i){super();this._stateManager=e;this._logService=t;this._productService=r;this._configurationService=i;this._terminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(s=>{let a=s.action;if(!mf(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 i=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=${i}, cols=${s}, rows=${a}`);let c=O(),u={...process.env};t?.preventShellHistory&&(u.VSCODE_PREVENT_SHELL_HISTORY="1"),e.claim?.kind==="session"&&Rf(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&&g_(l).name.match(/(zsh|bash)/)&&(p=["--login"]);let m=await HR({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),v;if(m.type==="injection"){if(this._logService.info(`[TerminalManager] Shell integration injected for ${r}`),m.envMixin)for(let[G,q]of Object.entries(m.envMixin))q!==void 0&&(u[G]=q);if(m.newArgs&&(p=m.newArgs),m.filesToCopy)for(let G of m.filesToCopy)try{await rs.promises.mkdir(oe(G.dest),{recursive:!0}),await rs.promises.copyFile(G.source,G.dest)}catch{}v={parser:new xf,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:i,env:u,cols:s,rows:a}),S=new Y,b=e.claim??{kind:"client",clientId:""},I=S.add(new A),_=S.add(new A),T=S.add(new A),P=S.add(new A),X=S.add(new wf({cols:s,rows:a,scrollback:nN,logService:this._logService})),k={uri:r,store:S,pty:y,onDataEmitter:I,onExitEmitter:_,onClaimChangedEmitter:T,onCommandFinishedEmitter:P,title:e.name??l,cwd:i,cols:s,rows:a,content:[],contentSize:0,claim:b,commandTracker:v,headlessTerminal:X,terminalQueryFilterState:{pendingData:""}};this._terminals.set(r,k),S.add(X.onResponseData(G=>{this._logService.debug(`[TerminalManager] Writing headless terminal response for ${r}: ${JSON.stringify(G)}`);try{y.write(G)}catch(q){this._logService.debug(`[TerminalManager] Failed to write headless terminal response for ${r}: ${q instanceof Error?q.message:String(q)}`)}})),S.add(N(()=>{try{y.kill()}catch{}}));let x=new Ee,E=y.onData(G=>{k.headlessTerminal?.writePtyData(G),this._handlePtyData(k,G),x.complete()});S.add(N(()=>E.dispose()));let H=y.onExit(G=>{k.exitCode=G.exitCode,k.onExitEmitter.fire(G.exitCode),x.complete(),this._stateManager.dispatchServerAction(r,{type:"terminal/exited",exitCode:G.exitCode}),this._broadcastTerminalList()});if(S.add(N(()=>H.dispose())),!Q){let G=setInterval(()=>{let q=y.process;q&&q!==k.title&&(k.title=q,this._stateManager.dispatchServerAction(r,{type:"terminal/titleChanged",title:q}),this._broadcastTerminalList())},200);S.add(N(()=>clearInterval(G)))}await K_([x.p,Zt(tN)]),this._broadcastTerminalList()}async _spawnPty(e,t,r){return(await sN()).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 i=this._terminals.get(e),s=!1;r.bracketedPasteMode&&(await i?.headlessTerminal?.whenPtyDataFlushed(),s=!!i?.headlessTerminal?.isBracketedPasteMode()),this.writeInput(e,iN(t,{shouldExecute:r.shouldExecute,forceBracketedPasteMode:s}))}onData(e,t){let r=this._terminals.get(e);return r?r.onDataEmitter.event(t):N(()=>{})}onExit(e,t){let r=this._terminals.get(e);return r?r.onExitEmitter.event(t):N(()=>{})}onClaimChanged(e,t){let r=this._terminals.get(e);return r?r.onClaimChangedEmitter.event(t):N(()=>{})}onCommandFinished(e,t){let r=this._terminals.get(e);return r?r.onCommandFinishedEmitter.event(t):N(()=>{})}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 i=this._terminals.get(e);i&&i.exitCode===void 0&&(i.cols=t,i.rows=r,i.pty.resize(t,r),i.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,i;if(r){let s=r.parser.parse(t);i=s.cleanedData;for(let a of s.events)this._handleOsc633Event(e,r,a)}else i=t;i=oN(i,e.terminalQueryFilterState),i.length>0&&this._appendToContent(e,i),this._trimContent(e),i.length>0&&(e.onDataEmitter.fire(i),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/data",data:i}))}_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 i=`cmd-${++t.commandCounter}`,s=t.pendingCommandLine??"",a=Date.now();t.pendingCommandLine=void 0,t.activeCommandId=i,t.activeCommandTimestamp=a,e.content.push({type:"command",commandId:i,commandLine:s,output:"",timestamp:a,isComplete:!1}),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandExecuted",commandId:i,commandLine:s,timestamp:a});break}case 3:{let i=t.activeCommandId;if(!i)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===i){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:i,exitCode:r.exitCode,command:a,output:l}),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/commandFinished",commandId:i,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 i=e.content.shift();e.contentSize-=this._getContentPartSize(i)}if(e.contentSize>8e4&&e.content.length>0){let i=e.content[0],s=e.contentSize-8e4;i.type==="command"?i.output=i.output.slice(s):i.value=i.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(fr,"defaultShell");if(e)try{return await rs.promises.access(e,rs.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 vf(Mt,process.env)}async _resolveCwd(e,t){let r=e;if(e){let s=h.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 rs.promises.stat(r)).isDirectory())return r}catch{}let i=process.env.HOME||process.env.USERPROFILE||process.cwd();return this._logService.warn(`[TerminalManager] cwd '${r}' is not accessible, falling back to ${i}`),i}_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()}};va=R([C(1,M),C(2,ft),C(3,He)],va);var Pf=W("diffComputeService"),BR=5e3;function zR(o,n,e){switch(o){case"Write":return Af(n,"content");case"Edit":return Af(n,"new_string");case"MultiEdit":return aN(n,"new_string");case"create":return Af(n,"file_text");case"edit":case"str_replace":case"insert":return Af(n,"new_str");case"str_replace_editor":return lN(n);case"apply_patch":case"git_apply_patch":return cN(n,e);default:return[]}}function Af(o,n){if(typeof o!="object"||o===null)return[];let e=o[n];return typeof e=="string"?[e]:[]}function aN(o,n){if(typeof o!="object"||o===null)return[];let e=o.edits;if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="object"&&r!==null){let i=r[n];typeof i=="string"&&t.push(i)}return t}function lN(o){if(typeof o!="object"||o===null)return[];let n=o;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 dN=[/^\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 cN(o,n){let e;if(typeof o=="string")e=o;else if(typeof o=="object"&&o!==null){let l=o;typeof l.input=="string"?e=l.input:typeof l.patch=="string"&&(e=l.patch)}if(!e)return[];let t=new Map,r=[],i;for(let l of e.split(`
`)){let d=!1;for(let c of dN){let u=c.exec(l);if(u&&u[1]){i=u[1],t.has(i)||(t.set(i,[]),r.push(i)),d=!0;break}}d||!i||l.startsWith("+")&&!l.startsWith("+++")&&t.get(i).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 Ef(o,n){if(o.length<4||n.length<4)return o===n?1:0;let t=new Map;for(let a=0;a<=o.length-4;a++){let l=o.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=o.length-4+1+n.length-4+1,i=0;for(let a of t.values())i+=Math.abs(a);return(r-i)/r}function uN(o,n){let e=new Set;for(let t=0;t<=o.length-n;t++)e.add(o.substring(t,t+n));return e}function pN(o,n,e){let t=o.length-e+1,r=0;for(let i=0;i<t;i++)n.has(o.substring(i,i+e))&&r++;return r/t}function fN(o,n){if(o.length===0)return 0;let e=4,t=n.length>=e?uN(n,e):void 0,r=0,i=0;for(let s of o){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=pN(s,t,e):l=0,i+=l*a,r+=a}return i/r}function VR(o,n,e){let t=Ef(n,o);if(t===1)return 1;let r=Ef(e,o);return 1-Math.max(r-t,0)/(1-t)}function jR(o,n,e){return{fourGram:Ef(e,n),noRevert:VR(o,n,e)}}function KR(o,n,e,t){return{fourGram:e.length===0?Ef(t,n):fN(e,t),noRevert:VR(o,n,t)}}var Df=W("editSurvivalReporterFactory");var fS=[0,5e3,3e4,12e4,3e5,6e5,9e5],gS=class extends w{constructor(e,t,r,i){super();this._params=e;this._fileService=t;this._logService=r;this._telemetryService=i;this._startTime=Date.now();this._samplesTaken=0;this._scheduleNext()}_scheduleNext(){if(this._samplesTaken>=fS.length){this.dispose();return}let e=Date.now()-this._startTime,t=Math.max(0,fS[this._samplesTaken]-e);this._register(new cp).setIfNotSet(()=>this._takeSample(),t)}async _takeSample(){let e=this._samplesTaken++,t=fS[e];try{let r,i=!1;try{r=(await this._fileService.readFile(h.file(this._params.filePath))).value.toString()}catch(u){if(ho(u)===1)i=!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=i?{fourGram:0,noRevert:0}:a?KR(this._params.beforeText,this._params.afterText,s,r):jR(this._params.beforeText,this._params.afterText,r),c=de(this._params.sessionUri)?fe(this._params.sessionUri):this._params.sessionUri;if(this._telemetryService.publicLog2("agentHost.trackEditSurvival",{provider:D.provider(c)??"unknown",modelId:this._params.modelId??"",toolName:this._params.toolName??"",agentSessionId:D.id(c),turnId:this._params.turnId,toolCallId:this._params.toolCallId,fileExtension:Di(this._params.filePath),survivalRateFourGram:d.fourGram,survivalRateNoRevert:d.noRevert,scoringMode:a?"chunked":"whole-file",aiChunkCount:s.length,aiCharCount:l,timeDelayMs:t,didFileGetDeleted:i?1:0,isCreate:this._params.isCreate?1:0,beforeTextLength:this._params.beforeText.length,afterTextLength:this._params.afterText.length,currentTextLength:i?0:r.length}),i){this.dispose();return}}catch(r){this._logService.warn(`[EditSurvivalReporter] sample failed for ${this._params.filePath}: ${r}`)}this._scheduleNext()}},gN=5*1024*1024,Sa=class{constructor(n,e,t){this._fileService=n;this._logService=e;this._telemetryService=t}launch(n){return Di(n.filePath).toLowerCase()===".ipynb"?{dispose(){}}:Math.max(n.beforeText.length,n.afterText.length)>gN?{dispose(){}}:new gS(n,this._fileService,this._logService,this._telemetryService)}};Sa=R([C(0,Pe),C(1,M),C(2,zn)],Sa);var JR="session-db";function ni(o,n,e,t){return h.from({scheme:JR,authority:Ko(F.fromString(o)).toString(),path:`/${encodeURIComponent(n)}/${Ko(F.fromString(e))}/${t}/${Te(e)}`}).toString()}function YR(o){let n=h.parse(o);if(n.scheme!==JR)return;let[,e,t,r]=n.path.split("/");if(!(!e||!t||r!=="before"&&r!=="after"))try{return{sessionUri:iv(n.authority).toString(),toolCallId:decodeURIComponent(e),filePath:iv(t).toString(),part:r}}catch{return}}var ti=class{constructor(n,e,t,r,i,s){this._sessionUri=n;this._db=e;this._fileService=t;this._logService=r;this._diffComputeService=i;this._editSurvivalReporterFactory=s;this._pendingEdits=new Map;this._completedEdits=new Map}async trackEditStart(n){let e=this._readFileWithExistence(n),t={beforeContent:F.fromString(""),beforeExisted:!1,snapshotDone:e.then(({content:r,existed:i})=>{t.beforeContent=r,t.beforeExisted=i})};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,i,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,v;try{let y=await this._diffComputeService.computeDiffCounts(c,u);m=y.added,v=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:v})}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:zR(r,i,t)}),{type:"fileEdit",before:{uri:h.file(t).toString(),content:{uri:ni(this._sessionUri,e,t,"before")}},after:{uri:h.file(t).toString(),content:{uri:ni(this._sessionUri,e,t,"after")}},diff:m!==void 0?{added:m,removed:v}:void 0}}async _readFile(n){try{return(await this._fileService.readFile(h.file(n))).value}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),F.fromString("")}}async _readFileWithExistence(n){try{return{content:(await this._fileService.readFile(h.file(n))).value,existed:!0}}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),{content:F.fromString(""),existed:!1}}}};ti=R([C(2,Pe),C(3,M),C(4,Pf),C(5,Df)],ti);var QR="git-blob";function mS(o,n,e,t){return h.from({scheme:QR,path:t,query:JSON.stringify({sessionUri:o,sha:n,repoRelativePath:e})}).toString()}function XR(o){let n;try{n=h.parse(o)}catch{return}if(!(n.scheme!==QR||!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 mN={"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/mcpServerStartRequested":!0,"session/mcpServerStopRequested":!0,"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,"chat/turnsLoaded":!1,"changeset/statusChanged":!1,"changeset/fileSet":!1,"changeset/fileRemoved":!1,"changeset/filesReviewChanged":!0,"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 Pn(o,n){let e=`Unhandled action type: ${JSON.stringify(o)}`;(n??console.warn)(e)}function mc(o,n,e){switch(n.type){case"root/agentsChanged":return{...o,agents:n.agents};case"root/activeSessionsChanged":return{...o,activeSessions:n.activeSessions};case"root/terminalsChanged":return{...o,terminals:n.terminals};case"root/configChanged":return o.config?{...o,config:{...o.config,values:n.replace?{...n.config}:{...o.config.values,...n.config}}}:o;default:return Pn(n,e),o}}var hN=31;function ZR(o,n,e){return e?o|n:o&~n}function ex(o,n){return n.length>0?o&~hN|24:o&-17}function hS(o,n,e){let t=o.customizations;if(!t)return o;let r=t.findIndex(a=>a.id===n);if(r>=0){let a=t[r];if(a.type!=="mcpServer")return o;let l=t.slice();return l[r]=e(a),{...o,customizations:l}}let i=!1,s=t.map(a=>{if(a.type==="mcpServer")return a;let l=a.children;if(!l)return a;let d=l.findIndex(p=>p.id===n);if(d<0)return a;let c=l[d];if(c.type!=="mcpServer")return a;i=!0;let u=l.slice();return u[d]=e(c),{...a,children:u}});return i?{...o,customizations:s}:o}function hc(o,n,e){switch(n.type){case"session/ready":return{...o,lifecycle:"ready"};case"session/creationFailed":return{...o,lifecycle:"creationFailed",creationError:n.error};case"session/chatAdded":{let t=o.chats,r=t.findIndex(s=>s.resource===n.summary.resource);if(r<0)return{...o,chats:[...t,n.summary]};let i=t.slice();return i[r]=n.summary,{...o,chats:i}}case"session/chatRemoved":{let t=o.chats,r=t.findIndex(a=>a.resource===n.chat);if(r<0)return o;let i=t.slice();i.splice(r,1);let s={...o,chats:i};return o.defaultChat===n.chat&&delete s.defaultChat,s}case"session/chatUpdated":{let t=o.chats,r=t.findIndex(l=>l.resource===n.chat);if(r<0)return o;let{resource:i,...s}=n.changes,a=t.slice();return a[r]={...t[r],...s},{...o,chats:a}}case"session/defaultChatChanged":return{...o,defaultChat:n.defaultChat};case"session/titleChanged":return{...o,title:n.title};case"session/isReadChanged":return{...o,status:ZR(o.status,32,n.isRead)};case"session/isArchivedChanged":return{...o,status:ZR(o.status,64,n.isArchived)};case"session/activityChanged":return{...o,activity:n.activity};case"session/changesetsChanged":{let{changesets:t,...r}=o;return n.changesets?{...r,changesets:n.changesets}:r}case"session/configChanged":return o.config?{...o,config:{...o.config,values:n.replace?{...n.config}:{...o.config.values,...n.config}}}:o;case"session/metaChanged":return{...o,_meta:n._meta};case"session/serverToolsChanged":return{...o,serverTools:n.tools};case"session/activeClientSet":{let t=o.activeClients,r=t.findIndex(s=>s.clientId===n.activeClient.clientId);if(r<0)return{...o,activeClients:[...t,n.activeClient]};let i=t.slice();return i[r]=n.activeClient,{...o,activeClients:i}}case"session/activeClientRemoved":{let t=o.activeClients,r=t.findIndex(s=>s.clientId===n.clientId);if(r<0)return o;let i=t.slice();return i.splice(r,1),{...o,activeClients:i}}case"session/inputNeededSet":{let t=o.inputNeeded??[],r=t.findIndex(s=>s.id===n.request.id),i=r<0?[...t,n.request]:t.slice();return r>=0&&(i[r]=n.request),{...o,inputNeeded:i,status:ex(o.status,i)}}case"session/inputNeededRemoved":{let t=o.inputNeeded;if(!t)return o;let r=t.findIndex(a=>a.id===n.id);if(r<0)return o;let i=t.slice();i.splice(r,1);let s={...o,status:ex(o.status,i)};return i.length>0?s.inputNeeded=i:delete s.inputNeeded,s}case"session/customizationsChanged":return{...o,customizations:n.customizations};case"session/customizationToggled":{let t=o.customizations;if(!t)return o;let r=t.findIndex(i=>i.id===n.id);if(r>=0){let i=t.slice();return i[r]={...t[r],enabled:n.enabled},{...o,customizations:i}}for(let i=0;i<t.length;i++){let s=t[i];if(s.type==="mcpServer")continue;let a=s.children;if(!a)continue;let l=a.findIndex(u=>u.id===n.id);if(l<0)continue;let d=a.slice();d[l]={...a[l],enabled:n.enabled};let c=t.slice();return c[i]={...s,children:d},{...o,customizations:c}}return o}case"session/customizationUpdated":{let t=o.customizations??[],r=t.findIndex(s=>s.id===n.customization.id);if(r<0)return{...o,customizations:[...t,n.customization]};let i=[...t];return i[r]=n.customization,{...o,customizations:i}}case"session/customizationRemoved":{let t=o.customizations;if(!t)return o;let r=t.findIndex(a=>a.id===n.id);if(r>=0){let a=t.slice();return a.splice(r,1),{...o,customizations:a}}let i=!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;i=!0;let c=l.slice();return c.splice(d,1),{...a,children:c}});return i?{...o,customizations:s}:o}case"session/mcpServerStateChanged":return hS(o,n.id,t=>({...t,state:n.state,channel:n.channel}));case"session/mcpServerStartRequested":return hS(o,n.id,t=>({...t,state:{kind:"starting"},channel:void 0}));case"session/mcpServerStopRequested":return hS(o,n.id,t=>({...t,state:{kind:"stopped"},channel:void 0}));default:return Pn(n,e),o}}function nx(o){return{toolCallId:o.toolCallId,toolName:o.toolName,displayName:o.displayName,intention:o.intention,contributor:o.contributor,_meta:o._meta}}function Mf(o,n){return{...nx(o),_meta:n??o._meta}}function yN(o,n){if(!(!n||!o))return o.find(e=>e.id===n)}function vN(o){return o.activeTurn?o.activeTurn.responseParts.some(n=>n.kind==="toolCall"&&(n.toolCall.status==="pending-confirmation"||n.toolCall.status==="pending-result-confirmation")):!1}var SN=31;function rx(o,n,e){return e?o|n:o&~n}function Ia(o,n){let e;return n?e=n:(o.inputRequests?.length??0)>0||vN(o)?e=24:o.activeTurn?e=8:e=1,o.status&~SN|e}function Of(o){let n=Ia(o);return n===o.status?o:{...o,status:n}}function yS(o,n,e,t,r){if(!o.activeTurn||o.activeTurn.id!==n)return o;let i=o.activeTurn,s=i.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",...nx(c),invocationMessage:c.status==="streaming"?c.invocationMessage??"":c.invocationMessage,toolInput:c.status==="streaming"?void 0:c.toolInput,reason:"skipped"}}}),a={id:i.id,message:i.message,responseParts:s,usage:i.usage,state:e,error:r},l={...o,turns:[...o.turns,a],activeTurn:void 0,modifiedAt:new Date(Date.now()).toISOString()};return delete l.inputRequests,{...l,status:Ia(l,t)}}function bN(o,n){let e=o.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 i={...o,inputRequests:r};return{...i,status:rx(Ia(i),32,!1),modifiedAt:new Date(Date.now()).toISOString()}}function Ca(o,n,e,t){let r=o.activeTurn;if(!r||r.id!==n)return o;let i=!1,s=r.responseParts.map(a=>{if(a.kind==="toolCall"&&a.toolCall.toolCallId===e){let l=t(a.toolCall);return l===a.toolCall?a:(i=!0,{...a,toolCall:l})}return a});return i?{...o,activeTurn:{...r,responseParts:s}}:o}function tx(o,n,e,t){let r=o.activeTurn;if(!r||r.id!==n)return o;let i=!1,s=r.responseParts.map(a=>!i&&(a.kind==="toolCall"?a.toolCall.toolCallId:"id"in a?a.id:void 0)===e?(i=!0,t(a)):a);return i?{...o,activeTurn:{...r,responseParts:s}}:o}function yc(o,n,e){switch(n.type){case"chat/turnStarted":{let t={...o,activeTurn:{id:n.turnId,message:n.message,responseParts:[],usage:void 0}};if(t={...t,status:rx(Ia(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(i=>i.id!==n.queuedMessageId);t={...t,queuedMessages:r.length>0?r:void 0}}return t}case"chat/delta":return tx(o,n.turnId,n.partId,t=>t.kind==="markdown"?{...t,content:t.content+n.content}:t);case"chat/responsePart":return!o.activeTurn||o.activeTurn.id!==n.turnId?o:{...o,activeTurn:{...o.activeTurn,responseParts:[...o.activeTurn.responseParts,n.part]}};case"chat/turnComplete":return yS(o,n.turnId,"complete");case"chat/turnCancelled":return yS(o,n.turnId,"cancelled");case"chat/error":return yS(o,n.turnId,"error",2,n.error);case"chat/activityChanged":return{...o,activity:n.activity};case"chat/toolCallStart":return!o.activeTurn||o.activeTurn.id!==n.turnId?o:{...o,activeTurn:{...o.activeTurn,responseParts:[...o.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 Ca(o,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 Of(Ca(o,n.turnId,n.toolCallId,t=>{if(t.status!=="streaming"&&t.status!=="running")return t;let r=Mf(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 Of(Ca(o,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-confirmation")return t;let r=Mf(t,n._meta),i=yN(t.options,n.selectedOptionId);return n.approved?{status:"running",...r,invocationMessage:t.invocationMessage,toolInput:n.editedToolInput??t.toolInput,confirmed:n.confirmed,...i?{selectedOption:i}:{}}:{status:"cancelled",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,reason:n.reason,reasonMessage:n.reasonMessage,userSuggestion:n.userSuggestion,...i?{selectedOption:i}:{}}}));case"chat/toolCallComplete":return Of(Ca(o,n.turnId,n.toolCallId,t=>{if(t.status!=="running"&&t.status!=="pending-confirmation")return t;let r=Mf(t,n._meta),i=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:i,...s?{selectedOption:s}:{},...n.result}:{status:"completed",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:i,...s?{selectedOption:s}:{},...n.result}}));case"chat/toolCallResultConfirmed":return Of(Ca(o,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-result-confirmation")return t;let r=Mf(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 Ca(o,n.turnId,n.toolCallId,t=>t.status!=="running"?t:{...t,...n._meta!==void 0?{_meta:n._meta}:{},content:n.content});case"chat/usage":return!o.activeTurn||o.activeTurn.id!==n.turnId?o:{...o,activeTurn:{...o.activeTurn,usage:n.usage}};case"chat/reasoning":return tx(o,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 i=o.turns.findIndex(s=>s.id===n.turnId);if(i<0)return o;t=o.turns.slice(0,i+1)}let r={...o,turns:t,activeTurn:void 0,modifiedAt:new Date(Date.now()).toISOString()};return delete r.inputRequests,n.turnId===void 0&&delete r.turnsNextCursor,{...r,status:Ia(r)}}case"chat/turnsLoaded":{let t=new Set(o.turns.map(i=>i.id)),r=n.turns.filter(i=>!t.has(i.id));return{...o,turns:[...r,...o.turns],turnsNextCursor:n.turnsNextCursor}}case"chat/inputRequested":return bN(o,n.request);case"chat/inputAnswerChanged":{let t=o.inputRequests,r=t?.findIndex(l=>l.id===n.requestId)??-1;if(!t||r<0)return o;let i=t[r],s={...i.answers??{}};n.answer===void 0?delete s[n.questionId]:s[n.questionId]=n.answer;let a=[...t];return a[r]={...i,answers:Object.keys(s).length>0?s:void 0},{...o,inputRequests:a,modifiedAt:new Date(Date.now()).toISOString()}}case"chat/inputCompleted":{let t=o.inputRequests,r=t?.findIndex(l=>l.id===n.requestId)??-1;if(!t||r<0)return o;let i=t[r],s=t.filter(l=>l.id!==n.requestId),a={...o};if(s.length>0?a.inputRequests=s:delete a.inputRequests,a.activeTurn){let l={...i.answers??{},...n.answers??{}},d={kind:"inputRequest",request:{...i,answers:Object.keys(l).length>0?l:void 0},response:n.response};a.activeTurn={...a.activeTurn,responseParts:[...a.activeTurn.responseParts,d]}}return{...a,status:Ia(a),modifiedAt:new Date(Date.now()).toISOString()}}case"chat/pendingMessageSet":{let t={id:n.id,message:n.message};if(n.kind==="steering")return{...o,steeringMessage:t};let r=o.queuedMessages??[],i=r.findIndex(s=>s.id===n.id);if(i>=0){let s=[...r];return s[i]=t,{...o,queuedMessages:s}}return{...o,queuedMessages:[...r,t]}}case"chat/pendingMessageRemoved":{if(n.kind==="steering")return!o.steeringMessage||o.steeringMessage.id!==n.id?o:{...o,steeringMessage:void 0};let t=o.queuedMessages;if(!t)return o;let r=t.filter(i=>i.id!==n.id);return r.length===t.length?o:{...o,queuedMessages:r.length>0?r:void 0}}case"chat/queuedMessagesReordered":{let t=o.queuedMessages;if(!t)return o;let r=new Map(t.map(a=>[a.id,a])),i=new Set,s=n.order.filter(a=>r.has(a)&&!i.has(a)?(i.add(a),!0):!1).map(a=>r.get(a));for(let a of t)i.has(a.id)||s.push(a);return{...o,queuedMessages:s}}case"chat/draftChanged":return{...o,draft:n.draft};default:return Pn(n,e),o}}function vc(o,n,e){switch(n.type){case"changeset/statusChanged":{if(n.status==="error")return{...o,status:n.status,error:n.error};let{error:t,...r}=o;return{...r,status:n.status}}case"changeset/fileSet":{let t=o.files.findIndex(i=>i.id===n.file.id);if(t<0)return{...o,files:[...o.files,n.file]};let r=[...o.files];return r[t]=n.file,{...o,files:r}}case"changeset/fileRemoved":{let t=o.files.findIndex(i=>i.id===n.fileId);if(t<0)return o;let r=[...o.files];return r.splice(t,1),{...o,files:r}}case"changeset/filesReviewChanged":{let t=!1,r=new Set(n.files),i=o.files.map(s=>!r.has(s.id)||s.reviewed===n.reviewed?s:(t=!0,{...s,reviewed:n.reviewed}));return t?{...o,files:i}:o}case"changeset/contentChanged":{let t=n.operations===void 0?{...o,files:n.files}:{...o,files:n.files,operations:n.operations};if(n.error===void 0){let{error:r,...i}=t;return i}return{...t,error:n.error}}case"changeset/operationsChanged":{if(n.operations===void 0){let{operations:t,...r}=o;return r}return{...o,operations:n.operations}}case"changeset/operationStatusChanged":{if(o.operations===void 0)return o;let t=o.operations.findIndex(a=>a.id===n.operationId);if(t<0)return o;let r=o.operations[t],i;if(n.status==="error")i={...r,status:n.status,error:n.error};else{let{error:a,...l}=r;i={...l,status:n.status}}let s=[...o.operations];return s[t]=i,{...o,operations:s}}case"changeset/cleared":return o.files.length===0?o:{...o,files:[]};default:return Pn(n,e),o}}function Sc(o,n,e){switch(n.type){case"annotations/set":{let t=o.annotations.findIndex(i=>i.id===n.annotation.id);if(t<0)return{...o,annotations:[...o.annotations,n.annotation]};let r=[...o.annotations];return r[t]=n.annotation,{...o,annotations:r}}case"annotations/updated":{let t=o.annotations.findIndex(a=>a.id===n.annotationId);if(t<0)return o;let i={...o.annotations[t]};n.turnId!==void 0&&(i.turnId=n.turnId),n.resource!==void 0&&(i.resource=n.resource),n.range!==void 0&&(i.range=n.range),n.resolved!==void 0&&(i.resolved=n.resolved);let s=[...o.annotations];return s[t]=i,{...o,annotations:s}}case"annotations/removed":{let t=o.annotations.findIndex(i=>i.id===n.annotationId);if(t<0)return o;let r=[...o.annotations];return r.splice(t,1),{...o,annotations:r}}case"annotations/entrySet":{let t=o.annotations.findIndex(l=>l.id===n.annotationId);if(t<0)return o;let r=o.annotations[t],i=r.entries.findIndex(l=>l.id===n.entry.id),s;i<0?s=[...r.entries,n.entry]:(s=[...r.entries],s[i]=n.entry);let a=[...o.annotations];return a[t]={...r,entries:s},{...o,annotations:a}}case"annotations/entryRemoved":{let t=o.annotations.findIndex(l=>l.id===n.annotationId);if(t<0)return o;let r=o.annotations[t],i=r.entries.findIndex(l=>l.id===n.entryId);if(i<0)return o;let s=[...r.entries];s.splice(i,1);let a=[...o.annotations];return a[t]={...r,entries:s},{...o,annotations:a}}default:return Pn(n,e),o}}function _N(o){return o==="terminal"||o==="subagent"||o==="search"}function TN(o){if(!o||typeof o!="object"||Array.isArray(o))return;let n=o;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 bc(o){let n=o._meta;if(!n)return{};let e={};_N(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=TN(n.ui);return t&&(e.ui=t),e}function Rt(o){let n={};for(let[e,t]of Object.entries(o))t!==void 0&&(n[e]=t);return Object.keys(n).length>0?n:void 0}var vS="/annotations";function Lf(o){return`${o}${vS}`}function wN(o){if(!o.endsWith(vS))return;let n=o.slice(0,o.length-vS.length);if(n)return{sessionUri:n}}function ox(o){return wN(o)!==void 0}var RN=500,Nf=class{constructor(n={}){this._states=new Map;this._lru=new ld;this._softLimit=Math.max(0,n.softLimit??RN),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 SS=class extends w{constructor(e,t){super();this._getSummary=e;this._emit=t;this._lastNotified=new Map;this._dirty=new Set;this._scheduler=this._register(new Vo(()=>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 i={};t.title!==r.title&&(i.title=t.title),t.status!==r.status&&(i.status=t.status),t.activity!==r.activity&&(i.activity=t.activity),t.modifiedAt!==r.modifiedAt&&(i.modifiedAt=t.modifiedAt),t.project!==r.project&&(i.project=t.project),t.changes!==r.changes&&(i.changes=t.changes),t.workingDirectory!==r.workingDirectory&&(i.workingDirectory=t.workingDirectory),t._meta!==r._meta&&(i._meta=t._meta),this._lastNotified.set(e,t),Object.keys(i).length>0&&this._emit(e,i)}},_a=class extends w{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 A);this.onDidEmitEnvelope=this._onDidEmitEnvelope.event;this._onDidEmitNotification=this._register(new A);this.onDidEmitNotification=this._onDidEmitNotification.event;this._onDidChangeSessionActiveTurn=this._register(new A);this.onDidChangeSessionActiveTurn=this._onDidChangeSessionActiveTurn.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._changesets=new Nf(t.changesetStateRetention),this._rootState=$T(),this._rootState={...this._rootState,config:{schema:Ut.toProtocol(),values:Ut.validateOrDefault({},{permissions:{allow:[],deny:[]},[zd]:bw(3)})},_meta:JT(this._rootState._meta,t.hostBuildInfo)},this._summaryNotifier=this._register(new SS(r=>{let i=this._sessionStates.get(r);return i?this._toSummary(r,i):void 0},(r,i)=>this._onDidEmitNotification.fire({type:"root/sessionSummaryChanged",channel:Ke,session:r,changes:i})))}get hasActiveSessions(){return this._sessionsWithActiveTurn.size>0}hasActiveTurn(e){return this._sessionsWithActiveTurn.has(e)}get rootState(){return this._rootState}getSessionState(e){let t=de(e),r=t?oa(e):e;if(r===void 0)return;let i=this._sessionStates.get(r);if(!i)return;let s=t?e:pe(r);return zT(i.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,i={resource:e,provider:r.provider,title:r.title,status:r.status,createdAt:t.createdAt,modifiedAt:t.modifiedAt};return r.activity!==void 0&&(i.activity=r.activity),r.project!==void 0&&(i.project=r.project),r.workingDirectory!==void 0&&(i.workingDirectory=r.workingDirectory),r.annotations!==void 0&&(i.annotations=r.annotations),t.changes!==void 0&&(i.changes=t.changes),r._meta!==void 0&&(i._meta=r._meta),i}_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(pe(e))}getChatState(e){return this._chatStates.get(e)}getChatProviderData(e){return this._chatProviderData.get(e)}seedDefaultChatTurns(e,t){let r=this._chatStates.get(pe(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 i=this._chatStates.get(pe(t));r.state.lifecycle==="creating"&&!i?.activeTurn&&(i?.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(qi(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(de(e)){let i=this._chatStates.get(e);return i?{resource:e,state:i,fromSeq:this._serverSeq}:void 0}if(ox(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,i=this._sessionStates.get(r);if(i)return this._logService.warn(`[AgentHostStateManager] Session already exists: ${r}`),i.state;let s=uv(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(),i=this._sessionStates.get(r);if(!i){this._logService.warn(`[AgentHostStateManager] markSessionPersisted: unknown session ${r}`);return}if(this._summaryNotifier.isAnnounced(r))return;i.state={...i.state,project:t.project,workingDirectory:t.workingDirectory},i.modifiedAt=t.modifiedAt,i.changes=t.changes;let s=this._toSummary(r,i);this._summaryNotifier.announce(r,s),this._onDidEmitNotification.fire({type:"root/sessionAdded",channel:Ke,summary:s})}restoreSession(e,t,r){let i=e.resource,s=this._sessionStates.get(i);if(s)return this._logService.warn(`[AgentHostStateManager] Session already exists (restore): ${i}`),s.state;let a={...uv(e),lifecycle:"ready"};return this._sessionStates.set(i,this._newEntry(a,e)),this._ensureDefaultChat(i,e,t,r?.draft,r?.defaultChatTitle),this._summaryNotifier.announce(i,e),this._logService.trace(`[AgentHostStateManager] Restored session: ${i} (${t.length} turns)`),a}_ensureDefaultChat(e,t,r,i,s){let a=pe(e),l={...Ep(t,a),title:s??""};this._chatStates.set(a,{...Ap(l),turns:r??[],draft:i});let d=this._sessionStates.get(e);d&&(d.state.chats=[l],d.state.defaultChat=a)}addChat(e,t,r){let i=this._sessionStates.get(e);if(!i){this._logService.warn(`[AgentHostStateManager] addChat for unknown session: ${e}`);return}let s=i.state,a=s.chats.find(u=>u.resource===t);if(a)return a;let l=s.defaultChat??pe(e),d=s.chats.find(u=>u.resource===l);d&&!d.title&&s.title&&this.updateChatTitle(e,l,s.title);let c={...Ep(this._toSummary(e,i),t),title:r?.title??"",status:1,origin:r?.origin,interactivity:r?.interactivity};return this._chatStates.set(t,{...Ap(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 i=this._sessionStates.get(e);if(!i){this._logService.warn(`[AgentHostStateManager] restoreChat for unknown session: ${e}`);return}let s=i.state;if(s.chats.some(l=>l.resource===t))return;let a={...Ep(this._toSummary(e,i),t),title:r.title??"",status:1};this._chatStates.set(t,{...Ap(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 i=r.state;if(t===i.defaultChat||Fe(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 i=this._chatStates.get(t);i&&this._chatStates.set(t,{...i,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(pe(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}Yo(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 i=r.state;if(gv(i.changesets??[],t??[],Yo))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 i=Je(r);i&&i.sessionUri===e&&t.push(r)}for(let r of t)this.disposeChangeset(r)}disposeSessionAnnotations(e){this._annotations.delete(Lf(e))}getActiveTurnId(e){let t=de(e)?e:pe(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 i;if(CR(t)){if(t.type==="root/configChanged"&&this._rootState.config){let a=this._rootState.config.values,l=t.config;if(t.replace?Ne(a,l):Ne({...a,...l},a))return this._rootState}this._rootState=mc(this._rootState,t,this._log),i=this._rootState}if(uc(t)){let a=t,l=e,d=this._sessionStates.get(l);if(d){let c=hc(d.state,a,this._log),u=!this._summaryFieldsEqual(d.state,c);d.state=c,u&&this._summaryNotifier.markDirty(l),i=c}else de(l)||this._logService.warn(`[AgentHostStateManager] Action for unknown session: ${l}, type=${t.type}`)}if(pr(t)){if(!de(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=yc(d,a,this._log);this._chatStates.set(e,c),this._onChatStateChanged(l,e,d,c),i=c}else this._logService.warn(`[AgentHostStateManager] Action for unknown chat: ${e}, type=${t.type}`)}if(Qv(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=vc(d,a,this._log);c!==d&&this._changesets.set(l,c),i=c}if(Xv(t)){let a=t,l=e,d=this._annotations.get(l)??{annotations:[]},c=Sc(d,a,this._log);c!==d&&this._annotations.set(l,c),i=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),i}_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,i){let s=!!r.activeTurn,a=!!i.activeTurn;if(s!==a)if(a){let _=this._sessionsWithActiveTurn.get(e),T=!!_?.size;_||(_=new Set,this._sessionsWithActiveTurn.set(e,_)),_.add(t),T||(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=WT(i),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),v=m.status!==void 0?this._mergeSessionStatus(d.status,m.status):d.status,y=v!==d.status,S=m.activity!==d.activity;l.state={...d,chats:p,...y?{status:v}: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,i=(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=i.status&r,a=i,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})}};_a=R([C(0,M)],_a);var Ta="agentHost.diffBaseBranch";function Uf(o,n){return o??n}var os="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ye=W("agentHostGitService");function ix(o){return o==="main"?0:o==="master"?1:2}function sx(o,n){let e=n?.query?.toLowerCase(),t=e?o.filter(r=>r.toLowerCase().includes(e)):[...o];return t.sort((r,i)=>ix(r)-ix(i)),n?.limit?t.slice(0,n.limit):t}var wa="agentHost.changeset.branch",Cc="agentHost.changeset.session",Ra="diffs",is="agentHost.changes",Ff={[wa]:!0,[Cc]:!0,[is]:!0,[Ra]:!0},xa=W("agentHostChangesetService");var Mr=W("agentHostCheckpointService"),ss="checkpoint.baseRef";function bS(o,n){return`refs/agents/${o}/checkpoints/turn/${n}`}var ax={_serviceBrand:void 0,captureBaseline:async()=>{},captureTurnCheckpoint:async()=>{},getTurnCheckpointPair:async()=>{},getBaselineCheckpointRef:async()=>{},disposeSessionData:async()=>{}};function CS(o){let n=[];for(let e of o)if(e.kind==="markdown"){let t=e.content.trim();t&&n.push(t)}return n.join(`

`)}function Hf(o,n){let e=[];for(let i of o){let s=i.message.text.trim(),a=CS(i.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?$f(t,n.maxChars):t;return`${n.framing??""}${r}`}function $f(o,n){if(o.length<=n)return o;let e=`
...
`;if(n<=e.length)return o.slice(0,n);let t=n-e.length,r=Math.ceil(t/2),i=t-r;return`${o.slice(0,r)}${e}${o.slice(o.length-i)}`}var lx=200,IS=2e4,Pa=class extends w{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 i=t.trim().replace(/\s+/g," ").slice(0,lx);if(i.length===0)return;if(!!r&&de(r)&&!Fe(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(i),this._generateTitleSoon(r,t,!1,i,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(i),this._generateTitleSoon(e,t,!1,i,l,()=>this._stateManager.getSessionState(e)?.title===this._lastAppliedTitle.get(e),d=>this._persistSessionFlag(e,"customTitle",d))}refineTitleFromFirstTurn(e,t){if(!!t&&de(t)&&!Fe(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,v=>this._stateManager.updateChatTitle(e,t,v));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 i=this._stateManager.getSessionState(e);if(!i||i.turns.length!==1)return;let s=this._lastAppliedTitle.get(e);if(s===void 0||i.title!==s)return;let a=this._buildFirstTurnContext(i.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,i,s){let a=this._buildConversationContext(r,s);if(!a)return;if(!!t&&de(t)&&!Fe(t)){let c=t;this._lastAppliedTitle.set(c,i);let u=p=>this._applyTitle(c,p,m=>this._stateManager.updateChatTitle(e,c,m));this._generateTitleSoon(c,a,!0,i,u,()=>this._stateManager.getChatState(c)?.title===this._lastAppliedTitle.get(c),p=>this._persistSessionFlag(e,`customChatTitle:${c}`,p));return}this._lastAppliedTitle.set(e,i);let d=c=>this._applyTitle(e,c,u=>this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:u}));this._generateTitleSoon(e,a,!0,i,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,i,s,a,l){this._cancelTitleGeneration(e);let d=new Ze;this._titleGenerationCancellationSources.set(e,d),this._generateTitle(e,t,r,i,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,i,s,a,l,d){let c=await this._generateTitleFromPrompt(t,r,d);d.isCancellationRequested||!c||a()&&(c!==i&&s(c),l(c))}async _generateTitleFromPrompt(e,t,r){if(r.isCancellationRequested)return;let i=this._options.getGitHubCopilotToken?.(),s=this._options.copilotApiService;if(!i||!s)return;let a=new AbortController,l=r.onCancellationRequested(()=>a.abort());try{let d=await s.utilityChatCompletion(i,{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(i=>i.trim()).find(i=>i.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,lx)}_buildFirstTurnContext(e){let t=CS(e.responseParts);if(!t)return;let r=Math.floor(IS/2),i=e.message.text.trim();i.length>r&&(i=$f(i,r));let s=`User request:
${i}`,a=`

Agent response:
`,l=Math.max(0,IS-s.length-a.length),d=t.length>l?$f(t,l):t;return d?`${s}${a}${d}`:s}_buildConversationContext(e,t){let r=t?.trim(),i=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 Hf(e,{maxChars:IS,framing:i})}_persistSessionFlag(e,t,r){let i=this._options.sessionDataService.openDatabase(h.parse(e));i.object.setMetadata(t,r).catch(s=>{this._logService.warn(`[AgentHostSessionTitleController] Failed to persist ${t}`,s)}).finally(()=>{i.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()}};Pa=R([C(2,M)],Pa);var xN="7d7048df-6dd0-4048-bb23-b716c1461f8f",PN="3fdd7f28-937a-48c8-9a21-ba337db23bd1",dx="https://copilot-telemetry.githubusercontent.com/telemetry",AN="copilot-chat",Ic=8192,EN=50;function Tc(o){let n={...o};for(let e in o){let t=o[e],r=t?.length??0;if(r>Ic){let i=0,s=0;for(;r>0&&s<EN;){s+=1;let a=e;s>1&&(a=e+"_"+(s<10?"0":"")+s);let l=i+Ic;r<Ic&&(l=i+r),n[a]=t.slice(i,l),r-=Ic,i+=Ic}}}return n}var Wf=class{constructor(n,e,t=dx,r,i=globalThis.fetch){this._logService=e;this._endpointUrl=t;this._internalSink=r;this._fetchFn=i;this._restrictedTelemetryEnabled=!1;this._commonProps={client_machineid:_c(n["common.machineId"]),client_deviceid:_c(n["common.devDeviceId"]),client_sessionid:_c(n.sessionID),common_os:_c(n["common.nodePlatform"])??process.platform,editor_version:_c(n.version)}}sendGHTelemetryEvent(n,e,t){this._post(xN,n,e,t)}sendEnhancedGHTelemetryEvent(n,e,t){this._restrictedTelemetryEnabled&&this._post(PN,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||dx}setRestrictedTelemetryEnabled(n){this._restrictedTelemetryEnabled=n}_post(n,e,t,r){let i=e.includes("/")?e:`${AN}/${e}`,s={ver:1,name:`Microsoft.ApplicationInsights.${n.replace(/-/g,"")}.Event`,time:new Date().toISOString(),sampleRate:100,seq:"",iKey:n,tags:{"ai.operation.id":O()},data:{baseType:"EventData",baseData:{name:i,properties:{unique_id:O(),...this._commonProps,...t},measurements:r??{}}}};if(this._logService.trace(`[ahp-restricted] emit ${i} (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] ${i} rejected: HTTP ${a.status}`)}).catch(a=>{this._logService.warn(`[ahp-restricted] ${i} POST failed: ${a instanceof Error?a.message:String(a)}`)})}};function _c(o){return typeof o=="string"?o:o===void 0?void 0:String(o)}var Aa=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,i){let s=i?.length??0,a=t?.activeClients??[],l=de(e)?fe(e):e;this._telemetryService.publicLog2("agentHost.userMessageSent",{provider:n,agentSessionId:D.id(l),source:r,isSubagentSession:lr(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",Tc({headerRequestId:e,conversationId:D.id(n),messagesJson:JSON.stringify(t)}))}userMessageText(n,e,t){let r=this._restricted;if(!r||!e)return;let i=Tc({source:"user",conversationId:D.id(n),turnIndex:String(t),messageText:e}),s={messageCharLen:e.length};r.sendEnhancedGHTelemetryEvent("conversation.messageText",i,s),r.sendInternalMSFTTelemetryEvent("conversation.messageText",i,s)}modelMessageText(n,e,t,r){let i=this._restricted;if(!i||!e)return;let s=Tc({source:"model",conversationId:D.id(n),turnIndex:String(t),...r?{headerRequestId:r}:{},messageText:e}),a={messageCharLen:e.length};i.sendEnhancedGHTelemetryEvent("conversation.messageText",s,a),i.sendInternalMSFTTelemetryEvent("conversation.messageText",s,a)}toolCallDetails(n){let e=this._restricted;if(!e||n.availableTools.length===0)return;let t=de(n.session)?fe(n.session):n.session,r=Tc({conversationId:D.id(t),requestId:n.turnId,messageId:n.turnId,responseType:n.responseType,...n.model?{model:n.model}:{},toolCounts:JSON.stringify(n.toolCounts),availableTools:JSON.stringify(n.availableTools)}),i={numRequests:n.numRequests,availableToolCount:n.availableTools.length,totalToolCalls:n.totalToolCalls,parallelToolCallRounds:n.parallelToolCallRounds,parallelToolCallsTotal:n.parallelToolCallsTotal};e.sendEnhancedGHTelemetryEvent("toolCallDetailsExternal",r,i),e.sendInternalMSFTTelemetryEvent("toolCallDetailsInternal",r,i)}skillContentRead(n){let e=this._restricted;if(!e||!n.name)return;let t=n.content?String(gn(n.content)):"",r=n.source??"",i=n.pluginName?n.pluginVersion??"":"",s={skillName:n.name,skillPath:n.path,skillExtensionId:n.pluginName??"",skillExtensionVersion:i,skillStorage:r,skillContentHash:t};e.sendGHTelemetryEvent("skillContentRead",{skillNameHash:String(gn(n.name)),skillExtensionIdHash:n.pluginName?String(gn(n.pluginName)):"",skillExtensionVersion:i,skillStorage:r,skillContentHash:t}),e.sendEnhancedGHTelemetryEvent("skillContentRead",s),e.sendInternalMSFTTelemetryEvent("skillContentRead",s)}turnCompleted(n){let e=de(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.turnCompleted",{provider:n.provider,agentSessionId:D.id(e),timeToFirstProgress:n.timeToFirstProgress,totalTime:n.totalTime,result:n.result,model:n.model,permissionLevel:n.permissionLevel})}toolInvoked(n){let e=de(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=de(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.toolCallStalled",{provider:n.provider,agentSessionId:D.id(e),isSubagentSession:Wd(n.session)||lr(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,stalledTimeMs:n.stalledTimeMs})}stalledToolCallCompleted(n){let e=de(n.session)?fe(n.session):n.session;this._telemetryService.publicLog2("agentHost.stalledToolCallCompleted",{provider:n.provider,agentSessionId:D.id(e),isSubagentSession:Wd(n.session)||lr(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,result:n.result,totalTimeMs:n.totalTimeMs,timeAfterStallMs:n.timeAfterStallMs})}};var kN=300*1e3;function DN(o){if(o.success)return"success";let n=o.error?.code;return n==="rejected"||n==="denied"||n==="cancelled"?"userCancelled":"error"}function cx(o){if(!o)return"agentHost";let n=o.kind;switch(n){case"mcp":return"mcp";case"client":return"client";default:return n}}var qf=class extends w{constructor(e){super();this._reporter=e;this._toolCalls=new Map;this._toolCallStallTimers=this._register(new we);this._stalledToolCalls=new Map}toolCallStarted(e,t,r,i,s){this._toolCalls.set(this._key(t,r),{stopWatch:Un.create(!0),provider:e,session:t,toolId:i,toolSourceKind:cx(s)})}toolCallCompleted(e,t,r){let i=this._key(e,t),s=this._toolCalls.get(i);if(!s)return;this._toolCalls.delete(i);let a=DN(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(i);d&&(this._stalledToolCalls.delete(i),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 i=this._key(t,r.id),s=this._key(t,r.toolCall.toolCallId);if(this._toolCallStallTimers.has(i)||this._stalledToolCalls.has(s))return;let a=Un.create(!0);this._toolCallStallTimers.set(i,qt(()=>{let l=a.elapsed();this._stalledToolCalls.set(s,{blockerKind:r.kind,completionStopWatch:Un.create(!0)}),this._reporter.toolCallStalled({provider:e,session:t,blockerKind:r.kind,toolId:r.toolCall.toolName,toolSourceKind:cx(r.toolCall.contributor),stalledTimeMs:l})},kN))}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 sU,release as aU}from"os";import{networkInterfaces as NN}from"os";import{networkInterfaces as MN}from"os";var ON=new Set(["00:00:00:00:00:00","ff:ff:ff:ff:ff:ff","ac:de:48:00:11:22"]);function LN(o){let n=o.replace(/\-/g,":").toLowerCase();return!ON.has(n)}function ux(){let o=MN();for(let n in o){let e=o[n];if(e){for(let{mac:t}of e)if(LN(t))return t}}throw new Error("Unable to retrieve mac address (unexpected format)")}var Hte=new class{_isVirtualMachineMacAddress(o){return this._virtualMachineOUIs||(this._virtualMachineOUIs=Er.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(o)}value(){if(this._value===void 0){let o=0,n=0,e=NN();for(let t in e){let r=e[t];if(r)for(let{mac:i,internal:s}of r)s||(n+=1,this._isVirtualMachineMacAddress(i.toUpperCase())&&(o+=1))}this._value=n>0?o/n:0}return this._value}},_S;async function Bf(o){return _S||(_S=(async()=>await UN(o)||O())()),_S}async function UN(o){try{let n=await import("crypto"),e=ux();return n.createHash("sha256").update(e,"utf8").digest("hex")}catch(n){o(n);return}}var FN="Software\\Microsoft\\SQMClient";async function px(o){if(Q){let n=await import("@vscode/windows-registry");try{return n.GetStringRegKey("HKEY_LOCAL_MACHINE",FN,"MachineId")||""}catch(e){return o(e),""}}return""}async function zf(o){try{let e=await(await import("@vscode/deviceid")).getDeviceId();return x_(e)}catch(n){return o(n),O()}}var jf;(n=>n.DEFAULT={allowTrailingComma:!0})(jf||={});function wS(o,n=!1){let e=0,t=o.length,r="",i=0,s=16,a=0;function l(y){let S=0,b=0;for(;S<y;){let I=o.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="",i=0,s=16,a=0}function c(){let y=e;if(o.charCodeAt(e)===48)e++;else for(e++;e<o.length&&Ea(o.charCodeAt(e));)e++;if(e<o.length&&o.charCodeAt(e)===46)if(e++,e<o.length&&Ea(o.charCodeAt(e)))for(e++;e<o.length&&Ea(o.charCodeAt(e));)e++;else return a=3,o.substring(y,e);let S=e;if(e<o.length&&(o.charCodeAt(e)===69||o.charCodeAt(e)===101))if(e++,(e<o.length&&o.charCodeAt(e)===43||o.charCodeAt(e)===45)&&e++,e<o.length&&Ea(o.charCodeAt(e))){for(e++;e<o.length&&Ea(o.charCodeAt(e));)e++;S=e}else a=3;return o.substring(y,S)}function u(){let y="",S=e;for(;;){if(e>=t){y+=o.substring(S,e),a=2;break}let b=o.charCodeAt(e);if(b===34){y+=o.substring(S,e),e++;break}if(b===92){if(y+=o.substring(S,e),e++,e>=t){a=2;break}switch(o.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(Vf(b)){y+=o.substring(S,e),a=2;break}else a=6;e++}return y}function p(){if(r="",a=0,i=e,e>=t)return i=t,s=17;let y=o.charCodeAt(e);if(TS(y)){do e++,r+=String.fromCharCode(y),y=o.charCodeAt(e);while(TS(y));return s=15}if(Vf(y))return e++,r+=String.fromCharCode(y),y===13&&o.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(o.charCodeAt(e+1)===47){for(e+=2;e<t&&!Vf(o.charCodeAt(e));)e++;return r=o.substring(S,e),s=12}if(o.charCodeAt(e+1)===42){e+=2;let b=t-1,I=!1;for(;e<b;){if(o.charCodeAt(e)===42&&o.charCodeAt(e+1)===47){e+=2,I=!0;break}e++}return I||(e++,a=1),r=o.substring(S,e),s=13}return r+=String.fromCharCode(y),e++,s=16}case 45:if(r+=String.fromCharCode(y),e++,e===t||!Ea(o.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=o.charCodeAt(e);if(i!==e){switch(r=o.substring(i,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(TS(y)||Vf(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 v(){let y;do y=p();while(y>=12&&y<=15);return y}return{setPosition:d,getPosition:()=>e,scan:n?v:p,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>e-i,getTokenError:()=>a}}function TS(o){return o===32||o===9||o===11||o===12||o===160||o===5760||o>=8192&&o<=8203||o===8239||o===8287||o===12288||o===65279}function Vf(o){return o===10||o===13||o===8232||o===8233}function Ea(o){return o>=48&&o<=57}function Kf(o,n=[],e=jf.DEFAULT){let t=null,r=[],i=[];function s(l){Array.isArray(r)?r.push(l):t!==null&&(r[t]=l)}return ka(o,{onObjectBegin:()=>{let l={};s(l),i.push(r),r=l,t=null},onObjectProperty:l=>{t=l},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let l=[];s(l),i.push(r),r=l,t=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:s,onError:(l,d,c)=>{n.push({error:l,offset:d,length:c})}},e),r[0]}function fx(o,n=[],e=jf.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 i(l){return t.children.push(l),l}ka(o,{onObjectBegin:l=>{t=i({type:"object",offset:l,length:-1,parent:t,children:[]})},onObjectProperty:(l,d,c)=>{t=i({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=i({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)=>{i({type:HN(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 RS(o,n){if(!o)return;let e=o;for(let t of n)if(typeof t=="string"){if(e.type!=="object"||!Array.isArray(e.children))return;let r=!1;for(let i of e.children)if(Array.isArray(i.children)&&i.children[0].value===t){e=i.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 ka(o,n,e=jf.DEFAULT){let t=wS(o,!1);function r(E){return E?()=>E(t.getTokenOffset(),t.getTokenLength()):()=>!0}function i(E){return E?H=>E(H,t.getTokenOffset(),t.getTokenLength()):()=>!0}let s=r(n.onObjectBegin),a=i(n.onObjectProperty),l=r(n.onObjectEnd),d=r(n.onArrayBegin),c=r(n.onArrayEnd),u=i(n.onLiteralValue),p=i(n.onSeparator),m=r(n.onComment),v=i(n.onError),y=e&&e.disallowComments,S=e&&e.allowTrailingComma;function b(){for(;;){let E=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(E){case 12:case 13:y?I(10):m();break;case 16:I(1);break;case 15:case 14:break;default:return E}}}function I(E,H=[],G=[]){if(v(E),H.length+G.length>0){let q=t.getToken();for(;q!==17;){if(H.indexOf(q)!==-1){b();break}else if(G.indexOf(q)!==-1)break;q=b()}}}function _(E){let H=t.getTokenValue();return E?u(H):a(H),b(),!0}function T(){switch(t.getToken()){case 11:{let E=0;try{E=JSON.parse(t.getTokenValue()),typeof E!="number"&&(I(2),E=0)}catch{I(2)}u(E);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return b(),!0}function P(){return t.getToken()!==10?(I(3,[],[2,5]),!1):(_(!1),t.getToken()===6?(p(":"),b(),x()||I(4,[],[2,5])):I(5,[],[2,5]),!0)}function X(){s(),b();let E=!1;for(;t.getToken()!==2&&t.getToken()!==17;){if(t.getToken()===5){if(E||I(4,[],[]),p(","),b(),t.getToken()===2&&S)break}else E&&I(6,[],[]);P()||I(4,[],[2,5]),E=!0}return l(),t.getToken()!==2?I(7,[2],[]):b(),!0}function k(){d(),b();let E=!1;for(;t.getToken()!==4&&t.getToken()!==17;){if(t.getToken()===5){if(E||I(4,[],[]),p(","),b(),t.getToken()===4&&S)break}else E&&I(6,[],[]);x()||I(4,[],[4,5]),E=!0}return c(),t.getToken()!==4?I(8,[4],[]):b(),!0}function x(){switch(t.getToken()){case 3:return k();case 1:return X();case 10:return _(!0);default:return T()}}return b(),t.getToken()===17?e.allowEmptyContent?!0:(I(4,[],[]),!1):x()?(t.getToken()!==17&&I(9,[],[]),!0):(I(4,[],[]),!1)}function HN(o){switch(typeof o){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(o){if(Array.isArray(o))return"array"}else return"null";return"object"}default:return"null"}}function mx(o,n,e){let t,r,i,s,a;if(n){for(s=n.offset,a=s+n.length,i=s;i>0&&!wc(o,i-1);)i--;let _=a;for(;_<o.length&&!wc(o,_);)_++;r=o.substring(i,_),t=$N(r,e)}else r=o,t=0,i=0,s=0,a=o.length;let l=WN(e,o),d=!1,c=0,u;e.insertSpaces?u=xS(" ",e.tabSize||4):u="	";let p=wS(r,!1),m=!1;function v(){return l+xS(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(_,T,P){!m&&T<a&&P>s&&o.substring(T,P)!==_&&S.push({offset:T,length:P-T,content:_})}let I=y();if(I!==17){let _=p.getTokenOffset()+i,T=xS(u,t);b(T,i,_)}for(;I!==17;){let _=p.getTokenOffset()+p.getTokenLength()+i,T=y(),P="";for(;!d&&(T===12||T===13);){let k=p.getTokenOffset()+i;b(" ",_,k),_=p.getTokenOffset()+p.getTokenLength()+i,P=T===12?v():"",T=y()}if(T===2)I!==1&&(c--,P=v());else if(T===4)I!==3&&(c--,P=v());else{switch(I){case 3:case 1:c++,P=v();break;case 5:case 12:P=v();break;case 13:d?P=v():P=" ";break;case 6:P=" ";break;case 10:if(T===6){P="";break}case 7:case 8:case 9:case 11:case 2:case 4:T===12||T===13?P=" ":T!==5&&T!==17&&(m=!0);break;case 16:m=!0;break}d&&(T===12||T===13)&&(P=v())}let X=p.getTokenOffset()+i;b(P,_,X),I=T}return S}function xS(o,n){let e="";for(let t=0;t<n;t++)e+=o;return e}function $N(o,n){let e=0,t=0,r=n.tabSize||4;for(;e<o.length;){let i=o.charAt(e);if(i===" ")t++;else if(i==="	")t+=r;else break;e++}return Math.floor(t/r)}function WN(o,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 o&&o.eol||`
`}function wc(o,n){return`\r
`.indexOf(o.charAt(n))!==-1}function hx(o,n,e,t,r){let i=n.slice(),a=fx(o,[]),l,d;for(;i.length>0&&(d=i.pop(),l=RS(a,i),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=RS(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 v=l.children[u-1];p=v.offset+v.length}else p=l.offset+1,l.children.length>1&&(m=l.children[1].offset);return Da(o,{offset:p,length:m-p,content:""},t)}else return Da(o,{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(v=>v.children[0].value)):l.children.length,m;if(p>0){let v=l.children[p-1];m={offset:v.offset+v.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 Da(o,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 Da(o,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],v=m.offset+m.length,y=l.offset+l.length;p={offset:v,length:y-2-v,content:""}}else p={offset:u.offset,length:l.children[c+1].offset-u.offset,content:""};return Da(o,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?[]:Da(o,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},t)}function Da(o,n,e){let t=PS(o,n),r=n.offset,i=n.offset+n.content.length;if(n.length===0||n.content.length===0){for(;r>0&&!wc(t,r-1);)r--;for(;i<t.length&&!wc(t,i);)i++}let s=mx(t,{offset:r,length:i-r},e);for(let l=s.length-1;l>=0;l--){let d=s[l];t=PS(t,d),r=Math.min(r,d.offset),i=Math.max(i,d.offset+d.length),i+=d.content.length-d.length}let a=o.length-(t.length-i)-r;return[{offset:r,length:a,content:t.substring(r,i)}]}function PS(o,n){return o.substring(0,n.offset)+n.content+o.substring(n.offset+n.length)}function yx(o,n){let e=n.slice(0).sort((r,i)=>{let s=r.offset-i.offset;return s===0?r.length-i.length:s}),t=o.length;for(let r=e.length-1;r>=0;r--){let i=e[r];if(i.offset+i.length<=t)o=PS(o,i);else throw new Error("Overlapping edit");t=i.offset}return o}function vx(o){let n=!1,e=new Map,t=new Map;if(qN(o,c=>{if(o===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(o);let i="$defs";for(;o.hasOwnProperty(i);)i+="_";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:`#/${i}/${m.id}`}}return p})}let l=a(o),d=[];for(let c=0;c<s.length;c++)d.push(`"_${c}":${a(s[c])}`);return d.length?`${l.substring(0,l.length-1)},"${i}":{${d.join(",")}}}`:l}function Ma(o){return typeof o=="object"&&o!==null}function qN(o,n){if(!o||typeof o!="object")return;let e=(...l)=>{for(let d of l)Ma(d)&&s.push(d)},t=(...l)=>{for(let d of l)if(Ma(d))for(let c in d){let u=d[c];Ma(u)&&s.push(u)}},r=(...l)=>{for(let d of l)if(Array.isArray(d))for(let c of d)Ma(c)&&s.push(c)},i=l=>{if(Array.isArray(l))for(let d of l)Ma(d)&&s.push(d);else Ma(l)&&s.push(l)},s=[o],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),i(a.items)),a=s.pop()}var ES={JSONContribution:"base.contributions.json"};function Sx(o){return o.length>0&&o.charAt(o.length-1)==="#"?o.substring(0,o.length-1):o}var AS=class extends w{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new A);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new A);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,t,r){let i=Sx(e);this.schemasById[i]=t,this._onDidChangeSchema.fire(e),r&&r.add(N(()=>{delete this.schemasById[i],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,t){let r=Sx(e);return this.schemaAssociations[r]||(this.schemaAssociations[r]=[]),this.schemaAssociations[r].includes(t)||(this.schemaAssociations[r].push(t),this._onDidChangeSchemaAssociations.fire()),N(()=>{let i=this.schemaAssociations[r];if(i){let s=i.indexOf(t);s!==-1&&(i.splice(s,1),i.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?vx(t):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},BN=new AS;Ht.add(ES.JSONContribution,BN);var Vt,kS=globalThis.vscode;if(typeof kS<"u"&&typeof kS.context<"u"){let o=kS.context.configuration();if(o)Vt=o.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(Vt=globalThis._VSCODE_PRODUCT_JSON,Xe.VSCODE_DEV&&Object.assign(Vt,{nameShort:`${Vt.nameShort} Dev`,nameLong:`${Vt.nameLong} Dev`,dataFolderName:`${Vt.dataFolderName}-dev`,serverDataFolderName:Vt.serverDataFolderName?`${Vt.serverDataFolderName}-dev`:void 0}),!Vt.version){let o=globalThis._VSCODE_PACKAGE_JSON;Object.assign(Vt,{version:o.version})}Object.assign(Vt,{extensionsGallery:Xe.EXTENSIONS_GALLERY?JSON.parse(Xe.EXTENSIONS_GALLERY):Vt.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||Vt.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else Vt={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.129.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.129.0",commit:"77baee7fe06f7031d45e6acf903c9b4b329e10c4",date:"2026-07-15T00:08:44Z"},Object.keys(Vt).length===0&&Object.assign(Vt,{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 Xt=Vt;var Yn={Configuration:"base.contributions.configuration"};function zN(o,n){return o===n?!0:!o||!n?!1:typeof o=="string"||typeof n=="string"?o===n:o.id===n.id}var Gf={properties:{},patternProperties:{}},Jf={properties:{},patternProperties:{}},Yf={properties:{},patternProperties:{}},Qf={properties:{},patternProperties:{}},Xf={properties:{},patternProperties:{}},Zf={properties:{},patternProperties:{}},Rc={properties:{},patternProperties:{}},as="vscode://schemas/settings/resourceLanguage";var eg=Ht.as(ES.JSONContribution),DS=class extends w{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new A);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new A);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:f(2436,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={},eg.registerSchema(as,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),eg.registerSchema(as,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}deregisterConfigurations(e){let t=new Set;this.doDeregisterConfigurations(e,t),eg.registerSchema(as,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),eg.registerSchema(as,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:i,source:s}of e)for(let a in i){t.add(a);let l=this.configurationDefaultsOverrides.get(a)??this.configurationDefaultsOverrides.set(a,{configurationDefaultOverrides:[]}).get(a),d=i[a];if(l.configurationDefaultOverrides.push({value:d,source:s}),Or.test(a)){let c=this.mergeDefaultConfigurationsForOverrideIdentifier(a,d,s,l.configurationDefaultOverrideValue);if(!c)continue;l.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(a,c,s),r.push(...Oa(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 i=this.registeredConfigurationDefaults.indexOf(r);i!==-1&&this.registeredConfigurationDefaults.splice(i,1)}for(let{overrides:r,source:i}of e)for(let s in r){let a=this.configurationDefaultsOverrides.get(s);if(!a)continue;let l=a.configurationDefaultOverrides.findIndex(d=>i?zN(d.source,i):d.value===r[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),Or.test(s)){let d;for(let c of a.configurationDefaultOverrides)d=this.mergeDefaultConfigurationsForOverrideIdentifier(s,c.value,c.source,d);d&&!zu(d.value)?(a.configurationDefaultOverrideValue=d,this.updateDefaultOverrideProperty(s,d,i)):(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 i={section:{id:this.defaultLanguageConfigurationOverridesNode.id,title:this.defaultLanguageConfigurationOverridesNode.title,order:this.defaultLanguageConfigurationOverridesNode.order,extensionInfo:this.defaultLanguageConfigurationOverridesNode.extensionInfo},type:"object",default:t.value,description:f(2435,null,dw(e)),$ref:as,defaultDefaultValue:t.value,source:r,defaultValueSource:r};this.configurationProperties[e]=i,this.defaultLanguageConfigurationOverridesNode.properties[e]=i}mergeDefaultConfigurationsForOverrideIdentifier(e,t,r,i){let s=i?.value||{},a=i?.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)&&(As(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,i){let s=this.configurationProperties[e],a=i?.value??s?.defaultDefaultValue,l=r;if(Qe(t)&&(s!==void 0&&s.type==="object"||s===void 0&&(As(a)||Qe(a)))){if(l=i?.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(i=>{this.validateAndRegisterProperties(i,t,i.extensionInfo,i.restrictedProperties,void 0,r),this.configurationContributors.push(i),this.registerJSONConfiguration(i)})}doDeregisterConfigurations(e,t){let r=i=>{if(i.properties)for(let s in i.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,i.properties[s])}i.allOf?.forEach(s=>r(s))};for(let i of e){r(i);let s=this.configurationContributors.indexOf(i);s!==-1&&this.configurationContributors.splice(s,1)}}validateAndRegisterProperties(e,t=!0,r,i,s=4,a){s=er(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&&jN(c,u,r?.id)){delete l[c];continue}u.source=r,u.defaultDefaultValue=l[c].default,this.updatePropertyDefaultValue(c,u),Or.test(c)?u.scope=void 0:(u.scope=er(u.scope)?s:u.scope,u.restricted=er(u.restricted)?!!i?.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,v=l[c].policyReference?.name;p?(this.excludedConfigurationProperties[c]=l[c],m&&(this.policyConfigurations.set(m,c),a.add(c)),v&&(this.addPolicyReferenceConfiguration(v,c),a.add(c)),delete l[c]):(a.add(c),m&&this.policyConfigurations.set(m,c),v&&this.addPolicyReferenceConfiguration(v,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,i,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 i=r.properties;if(i)for(let a in i)this.updateSchema(a,i[a]);r.allOf?.forEach(t)};t(e)}updateSchema(e,t){switch(Gf.properties[e]=t,t.scope){case 1:Jf.properties[e]=t;break;case 2:Qf.properties[e]=t;break;case 3:Yf.properties[e]=t;break;case 7:Xf.properties[e]=t;break;case 4:Zf.properties[e]=t;break;case 5:Rc.properties[e]=t;break;case 6:Rc.properties[e]=t,this.resourceLanguageSettingsSchema.properties[e]=t;break}}removeFromSchema(e,t){switch(delete Gf.properties[e],t.scope){case 1:delete Jf.properties[e];break;case 2:delete Qf.properties[e];break;case 3:delete Yf.properties[e];break;case 7:delete Xf.properties[e];break;case 4:delete Zf.properties[e];break;case 5:case 6:delete Rc.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let t=`[${e}]`,r={type:"object",description:f(2437,null),errorMessage:f(2438,null),$ref:as};this.updatePropertyDefaultValue(t,r),Gf.properties[t]=r,Jf.properties[t]=r,Yf.properties[t]=r,Qf.properties[t]=r,Xf.properties[t]=r,Zf.properties[t]=r,Rc.properties[t]=r}}registerOverridePropertyPatternKey(){let e={type:"object",description:f(2437,null),errorMessage:f(2438,null),$ref:as};Gf.patternProperties[ri]=e,Jf.patternProperties[ri]=e,Yf.patternProperties[ri]=e,Qf.patternProperties[ri]=e,Xf.patternProperties[ri]=e,Zf.patternProperties[ri]=e,Rc.patternProperties[ri]=e,this._onDidSchemaChange.fire()}updatePropertyDefaultValue(e,t){let r=this.configurationDefaultsOverrides.get(e)?.configurationDefaultOverrideValue,i,s;r&&(!t.disallowConfigurationDefault||!r.source)&&(i=r.value,s=r.source),As(i)&&(i=t.defaultDefaultValue,s=void 0),As(i)&&(i=VN(t.type)),t.default=i,t.defaultValueSource=s}},Cx="\\[([^\\]]+)\\]",bx=new RegExp(Cx,"g"),ri=`^(${Cx})+$`,Or=new RegExp(ri);function Oa(o){let n=[];if(Or.test(o)){let e=bx.exec(o);for(;e?.length;){let t=e[1].trim();t&&n.push(t),e=bx.exec(o)}}return Jr(n)}function Ix(o){return o.reduce((n,e)=>`${n}[${e}]`,"")}function VN(o){switch(Array.isArray(o)?o[0]:o){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}var tg=new DS;Ht.add(Yn.Configuration,tg);function jN(o,n,e){return o.trim()?Or.test(o)?f(2434,null,o):tg.getConfigurationProperties()[o]!==void 0&&(!e||!KN.has(e.toLowerCase()))?f(2432,null,o):n.policy&&n.policyReference?f(2430,null,o):n.policy?.name&&tg.getPolicyConfigurations().get(n.policy?.name)!==void 0?f(2431,null,o,n.policy?.name,tg.getPolicyConfigurations().get(n.policy?.name)):null:f(2433,null)}var KN=new Set(Xt.defaultChatAgent?[Xt.defaultChatAgent.extensionId,Xt.defaultChatAgent.chatExtensionId].map(o=>o.toLowerCase()):[]);function xc(o){return Object.isFrozen(o)?o:cT(o)}var tt=class o{constructor(n,e,t,r,i){this._contents=n;this._keys=e;this._overrides=t;this._raw=r;this.logService=i;this.overrideConfigurations=new Map}static createEmptyModel(n){return new o({},[],[],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 o)return e;let t=new ng("",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 o)))return this._raw}isEmpty(){return this._keys.length===0&&Object.keys(this._contents).length===0&&this._overrides.length===0}getValue(n){return n?qd(this.contents,n):this.contents}inspect(n,e){let t=this;return{get value(){return xc(t.rawConfiguration.getValue(n))},get override(){return e?xc(t.rawConfiguration.getOverrideValue(n,e)):void 0},get merged(){return xc(e?t.rawConfiguration.override(e).getValue(n):t.rawConfiguration.getValue(n))},get overrides(){let r=[];for(let{contents:i,identifiers:s,keys:a}of t.rawConfiguration.overrides){let l=new o(i,a,[],void 0,t.logService).getValue(n);l!==void 0&&r.push({identifiers:s,value:l})}return r.length?xc(r):void 0}}}getOverrideValue(n,e){let t=this.getContentsForOverrideIdentifer(e);return t?n?qd(t,n):t:void 0}getKeysForOverrideIdentifier(n){let e=[];for(let t of this.overrides)t.identifiers.includes(n)&&e.push(...t.keys);return Jr(e)}getAllOverrideIdentifiers(){let n=[];for(let e of this.overrides)n.push(...e.identifiers);return Jr(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=$n(this.contents),t=$n(this.overrides),r=[...this.keys],i=this._raw?Array.isArray(this._raw)?[...this._raw]:[this._raw]:[this];for(let s of n)if(i.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=>In(d.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=Jr(l.keys)):t.push($n(a))}for(let a of s.keys)r.indexOf(a)===-1&&r.push(a)}return new o(e,r,t,!i.length||i.every(s=>s instanceof o)?void 0:i,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 Jr([...Object.keys(this.contents),...Object.keys(e)])){let i=this.contents[r],s=e[r];s&&(typeof i=="object"&&typeof s=="object"?(i=$n(i),this.mergeContents(i,s)):i=s),t[r]=i}return new o(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]=$n(e[t])}}getContentsForOverrideIdentifer(n){let e=null,t=null,r=i=>{i&&(t?this.mergeContents(t,i):t=$n(i))};for(let i of this.overrides)i.identifiers.length===1&&i.identifiers[0]===n?e=i.contents:i.identifiers.includes(n)&&r(i.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),aw(this.contents,n),Or.test(n)&&this.overrides.splice(this.overrides.findIndex(t=>In(t.identifiers,Oa(n))),1))}updateValue(n,e,t){if(mv(this.contents,n,e,r=>this.logService.error(r)),t=t||this.keys.indexOf(n)===-1,t&&this.keys.push(n),Or.test(n)){let r=this.contents[n],i=Oa(n),s={identifiers:i,keys:Object.keys(r),contents:Up(r,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>In(l.identifiers,i));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},ng=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||tt.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(n,e){if(!er(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:i,restricted:s,hasExcludedProperties:a}=this.doParseRaw(n,e);this._configurationModel=new tt(t,r,i,a?[n]:void 0,this.logService),this._restrictedConfigurations=s||[]}doParseContent(n){let e={},t=null,r=[],i=[],s=[];function a(d){Array.isArray(r)?r.push(d):t!==null&&(r[t]=d)}let l={onObjectBegin:()=>{let d={};a(d),i.push(r),r=d,t=null},onObjectProperty:d=>{t=d},onObjectEnd:()=>{r=i.pop()},onArrayBegin:()=>{let d=[];a(d),i.push(r),r=d,t=null},onArrayEnd:()=>{r=i.pop()},onLiteralValue:a,onError:(d,c,u)=>{s.push({error:d,offset:c,length:u})}};if(n)try{ka(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=Ht.as(Yn.Configuration),r=t.getConfigurationProperties(),i=t.getExcludedConfigurationProperties(),s=this.filter(n,r,i,!0,e);n=s.raw;let a=Up(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,i){let s=!1;if(!i?.scopes&&!i?.skipRestricted&&!i?.skipUnregistered&&!i?.exclude?.length)return{raw:n,restricted:[],hasExcludedProperties:s};let a={},l=[];for(let d in n)if(Or.test(d)&&r){let c=this.filter(n[d],e,t,!1,i);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,i)?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 i=e??t[n],s=i?typeof i.scope<"u"?i.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(Or.test(r)){let i={},s=n[r];for(let a in s)i[a]=s[a];t.push({identifiers:Oa(r),keys:Object.keys(i),contents:Up(i,e)})}return t}},rg=class extends w{constructor(e,t,r,i,s){super();this.userSettingsResource=e;this.parseOptions=t;this.fileService=i;this.logService=s;this._onDidChange=this._register(new A);this.onDidChange=this._onDidChange.event;this.parser=new ng(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 tt.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},MS=class{constructor(n,e,t,r,i,s,a,l,d,c,u,p,m){this.key=n;this.overrides=e;this._value=t;this.overrideIdentifiers=r;this.defaultConfiguration=i;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 xc(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)}},La=class o{constructor(n,e,t,r,i,s,a,l,d,c){this._defaultConfiguration=n;this._policyConfiguration=e;this._applicationConfiguration=t;this._localUserConfiguration=r;this._remoteUserConfiguration=i;this._workspaceConfiguration=s;this._folderConfigurations=a;this._memoryConfiguration=l;this._memoryConfigurationByResource=d;this.logService=c;this._workspaceConsolidatedConfiguration=null;this._foldersConsolidatedConfigurations=new qe;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=tt.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),i=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 MS(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,i||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:i,removed:s}=oi(this._defaultConfiguration,n);e=[...r,...i,...s]}for(let r of e)for(let i of Oa(r)){let s=this._defaultConfiguration.getKeysForOverrideIdentifier(i),a=n.getKeysForOverrideIdentifier(i),l=[...a.filter(d=>s.indexOf(d)===-1),...s.filter(d=>a.indexOf(d)===-1),...s.filter(d=>!Ne(this._defaultConfiguration.override(i).getValue(d),n.override(i).getValue(d)))];t.push([i,l])}return this.updateDefaultConfiguration(n),{keys:e,overrides:t}}compareAndUpdatePolicyConfiguration(n){let{added:e,updated:t,removed:r}=oi(this._policyConfiguration,n),i=[...e,...t,...r];return i.length&&this.updatePolicyConfiguration(n),{keys:i,overrides:[]}}compareAndUpdateApplicationConfiguration(n){let{added:e,updated:t,removed:r,overrides:i}=oi(this.applicationConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateApplicationConfiguration(n),{keys:s,overrides:i}}compareAndUpdateLocalUserConfiguration(n){let{added:e,updated:t,removed:r,overrides:i}=oi(this.localUserConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateLocalUserConfiguration(n),{keys:s,overrides:i}}compareAndUpdateRemoteUserConfiguration(n){let{added:e,updated:t,removed:r,overrides:i}=oi(this.remoteUserConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateRemoteUserConfiguration(n),{keys:s,overrides:i}}compareAndUpdateWorkspaceConfiguration(n){let{added:e,updated:t,removed:r,overrides:i}=oi(this.workspaceConfiguration,n),s=[...e,...t,...r];return s.length&&this.updateWorkspaceConfiguration(n),{keys:s,overrides:i}}compareAndUpdateFolderConfiguration(n,e){let t=this.folderConfigurations.get(n),{added:r,updated:i,removed:s,overrides:a}=oi(t,e),l=[...r,...i,...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:i,overrides:s}=oi(e,void 0);return{keys:[...t,...r,...i],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 tt(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 i of this._policyConfiguration.keys)r.setValue(i,this._policyConfiguration.getValue(i))}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 i=this._memoryConfigurationByResource.get(n);i&&(t=t.merge(i))}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:i}=this._folderConfigurations.get(e);return n.push([e,{contents:t,overrides:r,keys:i}]),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),i=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(h.revive(u[0]),this.parseConfigurationModel(u[1],e)),c),new qe);return new o(t,r,i,s,a,l,d,tt.createEmptyModel(e),new qe,e)}static parseConfigurationModel(n,e){return new tt(n.contents,n.keys,n.overrides,n.raw,e)}};var og=class{constructor(n,e,t,r,i){this.change=n;this.previous=e;this.currentConfiguraiton=t;this.currentWorkspace=r;this.logService=i;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=La.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 i=r+t.length;if(i>=this._affectsConfigStr.length)return!1;let s=this._affectsConfigStr.charCodeAt(i);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!Ne(a,l)}return!0}};function oi(o,n){let{added:e,removed:t,updated:r}=_x(n?.rawConfiguration,o?.rawConfiguration),i=[],s=o?.getAllOverrideIdentifiers()||[],a=n?.getAllOverrideIdentifiers()||[];if(n){let l=a.filter(d=>!s.includes(d));for(let d of l)i.push([d,n.getKeysForOverrideIdentifier(d)])}if(o){let l=s.filter(d=>!a.includes(d));for(let d of l)i.push([d,o.getKeysForOverrideIdentifier(d)])}if(n&&o){for(let l of s)if(a.includes(l)){let d=_x({contents:o.getOverrideValue(void 0,l)||{},keys:o.getKeysForOverrideIdentifier(l)},{contents:n.getOverrideValue(void 0,l)||{},keys:n.getKeysForOverrideIdentifier(l)});i.push([l,[...d.added,...d.removed,...d.updated]])}}return{added:e,removed:t,updated:r,overrides:i}}function _x(o,n){let e=o?n?o.keys.filter(i=>n.keys.indexOf(i)===-1):[...o.keys]:[],t=n?o?n.keys.filter(i=>o.keys.indexOf(i)===-1):[...n.keys]:[],r=[];if(o&&n){for(let i of n.keys)if(o.keys.indexOf(i)!==-1){let s=qd(n.contents,i),a=qd(o.contents,i);Ne(s,a)||r.push(i)}}return{added:e,removed:t,updated:r}}var ig=W("policy");var ii=class{constructor(){this.onDidChange=ee.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var sg=class extends w{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new A);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=tt.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(Ht.as(Yn.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,Ht.as(Yn.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=tt.createEmptyModel(this.logService);let e=Ht.as(Yn.Configuration).getConfigurationProperties();this.updateConfigurationModel(Object.keys(e),e)}updateConfigurationModel(e,t){let r=this.getConfigurationDefaultOverrides();for(let i of e){let s=r[i],a=t[i];s!==void 0?this._configurationModel.setValue(i,s):a?this._configurationModel.setValue(i,this.getDefaultValue(i,a)):this._configurationModel.removeValue(i)}}getDefaultValue(e,t){return $n(t.default)}},ag=class{constructor(){this.onDidChangeConfiguration=ee.None;this.configurationModel=tt.createEmptyModel(new cf)}async initialize(){return this.configurationModel}},Na=class extends w{constructor(e,t,r){super();this.defaultConfiguration=e;this.policyService=t;this.logService=r;this._onDidChangeConfiguration=this._register(new A);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._submittedPolicyDefinitions=new Map;this._policyNameByKey=new Map;this._configurationModel=tt.createEmptyModel(this.logService),this.configurationRegistry=Ht.as(Yn.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 i=(Array.isArray(e)?e:[e]).filter(s=>s==="string"||s==="number"||s==="array"||s==="object"||s==="boolean");if(i.length===0){this.logService.warn(`PolicyConfiguration#updatePolicyDefinitions - policy '${t}' has unsupported type '${e}'`);return}return i.includes("number")?"number":i.includes("boolean")?"boolean":"string"}async updatePolicyDefinitions(e){this.logService.trace("PolicyConfiguration#updatePolicyDefinitions",e);let t=[],r=new Set,i=this.configurationRegistry.getConfigurationProperties(),s=this.configurationRegistry.getExcludedConfigurationProperties();for(let l of e){let d=i[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 zu(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(),i=this.configurationRegistry.getPolicyConfigurations().get(e);if(i!==void 0){let a=t[i]??r[i];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(),i=[];for(let s of e){let a=t.get(s);a&&i.push(a);let l=r.get(s);l&&i.push(...l)}this.update(i,!0)}update(e,t){this.logService.trace("PolicyConfiguration#update",e);let r=this.configurationRegistry.getConfigurationProperties(),i=this.configurationRegistry.getExcludedConfigurationProperties(),s=[],a=this._configurationModel.isEmpty();for(let l of e){let d=r[l]??i[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}:`,Zn(m));continue}(a?u!==void 0:!Ne(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=tt.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,i=[],s=[],a=[];function l(c){if(Array.isArray(i))i.push(c);else if(r!==null){if(i[r]!==void 0)throw new Error(`Duplicate property found: ${r}`);i[r]=c}}if(e&&(ka(e,{onObjectBegin:()=>{let c={};l(c),s.push(i),i=c,r=null},onObjectProperty:c=>{r=c},onObjectEnd:()=>{i=s.pop()},onArrayBegin:()=>{let c=[];l(c),s.push(i),i=c,r=null},onArrayEnd:()=>{i=s.pop()},onLiteralValue:l,onError:(c,u,p)=>{a.push({error:c,offset:u,length:p})}}),t=i[0]||t),a.length>0)throw new Error(a.map(c=>Zn(c.error)).join(`
`));return t}};Na=R([C(1,ig),C(2,M)],Na);var Ua=class extends w{constructor(e,t,r,i){super();this.settingsResource=e;this.logService=i;this._onDidChangeConfiguration=this._register(new A);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new sg(i)),this.policyConfiguration=r instanceof ii?new ag:this._register(new Na(this.defaultConfiguration,r,i)),this.userConfiguration=this._register(new rg(this.settingsResource,{},nt,t,i)),this.configuration=new La(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,tt.createEmptyModel(i),tt.createEmptyModel(i),tt.createEmptyModel(i),tt.createEmptyModel(i),new qe,tt.createEmptyModel(i),new qe,i),this.configurationEditing=new OS(e,t,this),this.reloadConfigurationScheduler=this._register(new Vo(()=>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 La(e,t,tt.createEmptyModel(this.logService),r,tt.createEmptyModel(this.logService),tt.createEmptyModel(this.logService),new qe,tt.createEmptyModel(this.logService),new qe,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,t){let r=typeof e=="string"?e:void 0,i=Np(e)?e:Np(t)?t:{};return this.configuration.getValue(r,i,void 0)}async updateValue(e,t,r,i,s){let a=sw(r)?r:Np(r)?{resource:r.resource,overrideIdentifiers:r.overrideIdentifier?[r.overrideIdentifier]:void 0}:void 0,l=a?i:r;if(l!==void 0&&l!==3&&l!==2)throw new Error(`Unable to write ${e} to target ${l}.`);a?.overrideIdentifiers&&(a.overrideIdentifiers=Jr(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(Ne(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=>In([...m.identifiers].sort(),u));p&&(a.overrideIdentifiers=p.identifiers)}let c=a?.overrideIdentifiers?.length?[Ix(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(),i=this.configuration.compareAndUpdateDefaultConfiguration(e,t);this.trigger(i,r,7)}onDidPolicyConfigurationChange(e){let t=this.configuration.toData(),r=this.configuration.compareAndUpdatePolicyConfiguration(e);this.trigger(r,t,7)}trigger(e,t,r){let i=new og(e,{data:t},this.configuration,void 0,this.logService);i.source=r,this._onDidChangeConfiguration.fire(i)}},OS=class{constructor(n,e,t){this.settingsResource=n;this.fileService=e;this.configurationService=t;this.queue=new zo}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(Kf(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 i=this.getEdits(t,n,e);t=yx(t,i),await this.fileService.writeFile(this.settingsResource,F.fromString(t))}getEdits(n,e,t){let{tabSize:r,insertSpaces:i,eol:s}=this.formattingOptions;if(!e.length){let a=JSON.stringify(t,null,i?" ".repeat(r):"	");return[{content:a,length:a.length,offset:0}]}return hx(n,e,t,{tabSize:r,insertSpaces:i,eol:s})}get formattingOptions(){if(!this._formattingOptions){let n=Mt===3||Mt===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 si=W("requestService"),dg="NO_FETCH_TELEMETRY",NS=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}},lg=class extends w{constructor(e){super();this.logService=e;this.counter=0;this._onDidCompleteRequest=this._register(new A);this.onDidCompleteRequest=this._onDidCompleteRequest.event}async logAndRequest(e,t){let r=`#${++this.counter}: ${e.url}`;this.logService.trace(`${r} - begin`,e.type,new NS(e.headers??{}));let i=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()-i,statusCode:s.res.statusCode}),s}catch(s){throw this.logService.error(`${r} - error`,e.type,Zn(s)),s}}};var Fa=!1,LS=[],wx,Rx;function JN(o=!0,n=!0){if(wx===o&&Rx===n)return;wx=o,Rx=n;let e=Ht.as(Yn.Configuration),t=LS;LS=[{id:"http",order:15,title:f(2804,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:n,markdownDescription:f(2819,null),restricted:!0}}},{id:"http",order:15,title:f(2804,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:f(2802,null),restricted:!0}}},{id:"http",order:15,title:f(2804,null),type:"object",scope:o?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:f(2807,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:f(2815,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:f(2809,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:f(2806,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:f(2808,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[f(2812,null),f(2813,null),f(2811,null),f(2814,null)],default:"override",markdownDescription:f(2810,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:f(2816,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:Fa,markdownDescription:f(2817,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:f(2818,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2803,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.webSocketAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2820,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:f(2805,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:LS,remove:t})}JN();var FS=class{constructor(n,e,t){this.id=n;this.dependencies=e;this.callback=t}};var HS=class o{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 o}_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 FS(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(`${ne.vscodeFileResource}://${Xy}`))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=O();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=[],i=[];if(Array.isArray(e.dependencies))for(let s of e.dependencies)s==="exports"?r.push(t):i.push(s);if(i.length>0)throw new Error(`Cannot resolve dependencies for script ${n}. The dependencies are: ${i.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 i=()=>{r.removeEventListener("load",s),r.removeEventListener("error",a)},s=l=>{i(),e(this._defineCalls.pop())},a=l=>{i(),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("module")).default,t=e.createRequire(import.meta.url),r=t("fs"),i=t("vm"),s=h.parse(n).fsPath,a=r.readFileSync(s).toString(),l=e.wrap(a.replace(/^#!.*/,""));return new i.Script(l).runInThisContext().apply(),this._defineCalls.pop()}catch(e){throw e}}},US=new Map;async function $S(o,n,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let t=n?`${o}/${n}`:o;if(US.has(t))return US.get(t);let r;if(/^\w[\w\d+.-]*:\/\//.test(t))r=t;else{let l=`${e&&(ZI||Ay&&i_)?H_:ip}/${t}`;r=Lt.asBrowserUri(l).toString(!0)}let i=HS.INSTANCE.load(r);return US.set(t,i),i}function YN(o){if(Ey===2&&/^penguin(\.|$)/i.test(o))return"chromebook"}function xx(o,n,e,t,r,i,s,a,l,d,c){let u=Object.create(null);u["common.machineId"]=i,u["common.sqmId"]=s,u["common.devDeviceId"]=a,u.sessionID=O()+Date.now(),u.commitHash=t,u.version=r,u["common.releaseDate"]=d,u["common.platformVersion"]=(o||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=YI(Ey),u["common.nodePlatform"]=Ls,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}}),QI&&(u["common.snap"]="true");let v=YN(n);return v&&(u["common.platformDetail"]=v),u}function Px(o){let n=Xe.USERDNSDOMAIN;if(!n)return!1;let e=n.toLowerCase();return o.some(t=>e===t)}var Pc=class{constructor(n){this.value=n;this.isTrustedTelemetryValue=!0}},WS=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(){}},cg=new WS;var qS="telemetry",Ex={id:qS,name:f(2844,null)};function kx(o,n){return!n.isBuilt&&!n.disableTelemetry?!0:!(n.disableTelemetry||!o.enableTelemetry)}function ug(o,n){return n.extensionTestsLocationURI?!0:!(n.isBuilt||n.disableTelemetry||o.enableTelemetry&&o.aiConfig?.ariaKey)}function Dx(o){let n=o.getValue(ia),e=o.getValue(Fp);if(o.getValue(Bd)===!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 pg(o){let n={},e={},t={};Mx(o,t);for(let r in t){r=r.length>150?r.substr(r.length-149):r;let i=t[r];typeof i=="number"?e[r]=i:typeof i=="boolean"?e[r]=i?1:0:typeof i=="string"?(i.length>8192&&console.warn(`Telemetry property: ${r} has been trimmed to 8192, the original length is ${i.length}`),n[r]=i.substring(0,8191)):typeof i<"u"&&i!==null&&(n[r]=String(i))}return{properties:n,measurements:e}}function Mx(o,n,e=0,t){if(!o||typeof o!="object"&&typeof o!="function")return;let r=o;for(let i of Object.getOwnPropertyNames(r)){let s=r[i],a=t?t+i:i;Array.isArray(s)?n[a]=Ad(s):s instanceof Date?n[a]=s.toISOString():Qe(s)?e<2?Mx(s,n,e+1,a+"."):n[a]=Ad(s):n[a]=s}}function Ox(o,n){let e=o.msftInternalDomains||[],t=n.getValue("telemetry.internalTesting");return Px(e)||t}function Lx(o){return[o.appRoot,o.extensionsPath,o.userHome.fsPath,o.tmpDir.fsPath,o.userDataPath]}function QN(o,n){if(!o||!o.includes("/")&&!o.includes("\\"))return o;let e=o,t=[];for(let l of n)for(;;){let d=l.exec(o);if(!d)break;t.push([d.index,l.lastIndex])}let r=/(?:^|[\\\/])((node_modules|node_modules\.asar)[\\\/].*)$/,i=/^(.*?)((?:\.vscode(?:-[a-z]+)*|resources[\\\/]app)[\\\/]extensions[\\\/].*)$/i,s=/(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w\-\._@]+(\\\\|\\|\/))+[\w\-\._@]*/g,a=0;for(e="";;){let l=s.exec(o);if(!l)break;if(!t.some(([c,u])=>l.index<u&&c<s.lastIndex)){let c=i.exec(l[0]);if(c)e+=o.substring(a,l.index)+"<REDACTED: user-file-path>/"+c[2];else{let u=r.exec(l[0]);u?e+=o.substring(a,l.index)+"<REDACTED: user-file-path>/"+u[1]:e+=o.substring(a,l.index)+"<REDACTED: user-file-path>"}a=s.lastIndex}}return a<o.length&&(e+=o.substr(a)),e}var Nx=[{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 Ax(o,n=o){for(let e of Nx)if(e.regex.test(n))return`<REDACTED: ${e.label}>`;return o}function XN(o){if(!o)return o;let n=!1;for(let t of Nx)if(t.regex.test(o)){n=!0;break}if(!n)return o;if(!o.includes(`
`))return Ax(o);let e=o.split(`
`);for(let t=0;t<e.length;t++){let r=t<e.length-1?e[t]+`
`:e[t];e[t]=Ax(e[t],r)}return e.join(`
`)}function Ux(o,n){return o?Pd(o,e=>{if(e instanceof Pc||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let t=e.replaceAll("%20"," ");t=QN(t,n);for(let r of n)t=t.replace(r,"");return t=XN(t),t}}):{}}var Fx="https://mobile.events.data.microsoft.com/OneCollector/1.0",ZN="https://mobile.events.data.microsoft.com/ping";async function eU(o,n,e){let t=Nn?await $S("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),r=Nn?await $S("@microsoft/1ds-post-js","bundle/ms.post.min.js"):await import("@microsoft/1ds-post-js"),i=new t.AppInsightsCore,s=new r.PostChannel,a={instrumentationKey:o,endpointUrl:Fx,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 i.initialize(a,[]),i.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)}),i}var fg=class{constructor(n,e,t,r,i){this._isInternalTelemetry=n;this._eventPrefix=e;this._defaultData=t;this._xhrOverride=i;this.endPointUrl=Fx;this.endPointHealthUrl=ZN;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=eU(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=Qs(e,this._defaultData);let t=pg(e),r=this._eventPrefix+"/"+n;try{this._withAIClient(i=>{i.pluginVersionString=t?.properties.version??"Unknown",i.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 tU(o,n){let e=await n.request(o,Re.None),t=(await wr(e.stream)).toString(),r=e.res.statusCode??200;return{headers:e.res.headers,statusCode:r,responseData:t}}async function nU(o){let n=await import("https"),e={method:o.type,headers:o.headers};return new Promise((r,i)=>{let s=n.request(o.url??"",e,a=>{a.on("data",function(l){r({headers:a.headers,statusCode:a.statusCode??200,responseData:l.toString()})}),a.on("error",function(l){i(l)})});s.write(o.data,a=>{a&&i(a)}),s.end()})}async function rU(o,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:dg};try{let i=o?await tU(r,o):await nU(r);e(i.statusCode,i.headers,i.responseData)}catch{e(0,{})}}var gg=class extends fg{constructor(n,e,t,r,i){let s={sendPOST:(a,l)=>{rU(n,a,l)}};super(e,t,r,i,s)}};var Ac=W("environmentService"),bt=Ac;var Ha=class extends w{constructor(e,t,r,i,s){super();this.prefix=e;let a=t?"remoteTelemetry":qS,l=r.getLogger(a);if(l)this.logger=this._register(l);else{let c=ug(s,i)?" (Not Sent)":"";this.logger=this._register(r.createLogger(a,{name:f(2824,null,c),group:Ex,hidden:!0}))}}flush(){return Promise.resolve()}log(e,t){this.logger.trace(`${this.prefix}telemetry/${e}`,pg(t))}};Ha=R([C(2,nR),C(3,Ac),C(4,ft)],Ha);var iie={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 Io=class{constructor(n,e,t){this._configurationService=e;this._productService=t;this._experimentProperties={};this._pendingEvents=[];this._isExperimentPropertySet=!1;this._disposables=new Y;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(_n(r),"gi")),r.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(_n(r.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(r=>{(r.affectsConfiguration(ia)||r.affectsConfiguration(Bd)||r.affectsConfiguration(Fp))&&this._updateTelemetryLevel()})),n.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),Io.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 Pc(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=Dx(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<Io.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:n,eventLevel:e,data:t});return}this._doLog(n,e,t)}}_doLog(n,e,t){t=Qs(t,this._experimentProperties),t=Ux(t,this._cleanupPatterns),t=Qs(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)}};Io=R([C(1,Bn),C(2,ft)],Io);function oU(){let o=f(2841,null,Xt.nameLong),n=Xt.privacyStatementUrl?f(2827,null,"https://aka.ms/vscode-telemetry",Xt.privacyStatementUrl):f(2828,null,"https://aka.ms/vscode-telemetry"),e=Nn?"":f(2833,null),t=f(2826,null),r=f(2831,null),i=f(2842,null),s=f(2840,null),a=`
|       | ${t} | ${r} | ${i} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,l=f(2836,null);return`
${o} ${n} ${e}

&nbsp;

${s}
${a}

&nbsp;

${l}
`}var iU=Ht.as(Yn.Configuration);iU.registerConfiguration({id:cw,order:1,type:"object",title:f(2843,null),properties:{[ia]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[f(2835,null),f(2837,null),f(2834,null),f(2838,null)],markdownDescription:oU(),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(2839,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:f(2835,null)},{key:"telemetry.telemetryLevel.error",value:f(2837,null)},{key:"telemetry.telemetryLevel.crash",value:f(2834,null)},{key:"telemetry.telemetryLevel.off",value:f(2838,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:f(2832,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:f(2832,null)}}}},[Bd]:{type:"boolean",markdownDescription:Xt.privacyStatementUrl?f(2830,null,Xt.nameLong,Xt.privacyStatementUrl):f(2829,null,Xt.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:f(2825,null,`\`#${ia}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var Hx="VSCODE_AGENT_HOST_MACHINE_ID",$x="VSCODE_AGENT_HOST_SQM_ID",Wx="VSCODE_AGENT_HOST_DEV_DEVICE_ID";var mg=class extends w{constructor(e,t){super();this._delegate=e;this._restricted=t;this._telemetryLevel=3;this._restrictedTelemetryEnabled=!1;Os(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 hg(o,n){let e=n?.[zd],t=Cw(e);!BS(o)||t===void 0||o.updateTelemetryLevel(t)}function BS(o){return typeof o.updateTelemetryLevel=="function"}async function qx(o){let{environmentService:n,productService:e,fileService:t,loggerService:r,logService:i,disposables:s}=o;if(o.disableTelemetry||!r||!kx(e,n))return s.add(new mg(cg));let a=s.add(new Ua(te(n.appSettingsHome,"settings.json"),t,new ii,i));await a.initialize();let l=[s.add(new Ha("",!1,r,n,e))],d=Ox(e,a);if(!ug(e,n)&&e.aiConfig?.ariaKey){let S=new gg(o.requestService,d,"monacoworkbench",null,e.aiConfig.ariaKey);s.add(N(()=>{S.flush()})),l.push(S)}let[c,u,p]=await Promise.all([process.env[Hx]||Bf(S=>i.error(S)),process.env[$x]||px(S=>i.error(S)),process.env[Wx]||zf(S=>i.error(S))]),m=xx(aU(),sU(),process.arch,e.commit,e.version,c,u,p,d,e.date),v=new Io({appenders:l,sendErrorTelemetry:!0,commonProperties:m,piiPaths:Lx(n)},a,e),y=new Wf(m,i,void 0,void 0,o.fetchFn);return s.add(new mg(v,y))}var yg=class{constructor(n){this._reporter=n;this._turnTimings=new Map}turnStarted(n,e,t,r,i){let s=this._key(e,t);this._turnTimings.set(s,{stopWatch:Un.create(!1),provider:n,session:e,model:r,permissionLevel:i,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),i=this._turnTimings.get(r);i&&(this._turnTimings.delete(r),this._reporter.turnCompleted({provider:i.provider,session:i.session,timeToFirstProgress:i.firstProgressMs,totalTime:i.stopWatch.elapsed(),result:t,model:i.model,permissionLevel:i.permissionLevel}))}_key(n,e){return`${n}\0${e}`}};function vg(o,n,e,t,r){let i=o.openDatabase(h.parse(e));i.object.setMetadata(t,r).catch(s=>{n.warn(`[AgentHost] Failed to persist session metadata '${t}'`,s)}).finally(()=>{i.dispose()})}var zS=class{constructor(){this._ctors=[]}register(n){this._ctors.push(n)}createAll(n){return this._ctors.map(e=>new e(n))}},Ec=new zS,$a=class extends w{constructor(e,t,r,i,s,a){super();this._stateManager=e;this._localTurns=t;this._notifyTurnConsumable=r;this._logService=i;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)=>vg(this._sessionDataService,this._logService,d,c,u)};this._commands=Ec.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(i){this._logService.error(`[AgentHostLocalCommands] Command '${e.name}' failed: ${i instanceof Error?i.message:String(i)}`,i)}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,i=de(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(i,r,lU(s[a]),l)}};$a=R([C(3,M),C(4,Dr),C(5,rt)],$a);function lU(o){let n=o.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(i=>i.type!=="terminal");return r.length===t.content.length?e:{...e,toolCall:{...t,content:r}}});return{...o,responseParts:n}}function Sg(o){let n={command:o.command};return o.description!==void 0&&(n.description=o.description),o.argumentHint!==void 0&&(n.argumentHint=o.argumentHint),n}function Bx(o){let n={uri:o.uri};return o.name!==void 0&&(n.name=o.name),o.displayName!==void 0&&(n.displayName=o.displayName),o.description!==void 0&&(n.description=o.description),n}var bg=W("agentHostCompletions");var Wa=class extends w{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),N(()=>this._providers.delete(e))}async completions(e,t=Re.None){let r=[...this._providers].filter(a=>a.kinds.has(e.kind));if(r.length===0)return{items:[]};let i=await Promise.allSettled(r.map(a=>a.provideCompletionItems(e,t))),s=[];for(let a=0;a<i.length;a++){let l=i[a];l.status==="fulfilled"?s.push(...l.value):this._logService.error(l.reason,`[AgentHostCompletions] Provider failed for kind=${e.kind}`)}return{items:s}}};Wa=R([C(0,M)],Wa);function Cg(o,n){if(o.length===0||o.charCodeAt(0)!==47)return;let e=1;for(;e<o.length&&!VS(o.charCodeAt(e));)e++;if(n<0||n>e)return;let t=o.slice(0,e);return{token:t,typed:t.slice(1),rangeStart:0,rangeEnd:e}}function Ig(o,n){if(o.length===0||n<0||n>o.length)return;let e=n;for(;e>0&&!VS(o.charCodeAt(e-1));)e--;if(e>=o.length||o.charCodeAt(e)!==47)return;let t=e+1;for(;t<o.length&&!VS(o.charCodeAt(t));)t++;if(n>t)return;let r=o.slice(e,t);return{token:r,typed:r.slice(1),rangeStart:e,rangeEnd:t}}function VS(o){return o===32||o===9||o===10||o===13}var _g="rename";function zx(o){let n=/^\/rename(?:$|\s+([\s\S]*))/.exec(o);if(n)return(n[1]??"").trim()}var Tg=class{constructor(n){this._hasHistory=n;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){let t=Cg(n.text,n.offset);if(!t)return[];if(!this._hasHistory(n.channel))return[];let r=t.typed;return r.length>0&&!_g.startsWith(r)?[]:[{insertText:"/"+_g+" ",rangeStart:t.rangeStart,rangeEnd:t.rangeEnd,attachment:{type:"simple",label:"/"+_g,_meta:Sg({command:_g,description:f(2035,null)})}}]}};var GS=class extends w{constructor(e){super();this._context=e;this.name="rename";this.recordsLocalTurn=!0}tryHandle(e){let t=zx(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=>de(l)&&!Fe(l))(e)?e:void 0,a=de(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:O(),content:f(2370,null,r)}})}};Ec.register(GS);function Vx(o){if(!o.startsWith("!"))return;let n=o.slice(1).trim();return n.length>0?n:void 0}var jx=8e4,wg=12e4,JS="<<<COPILOT_SENTINEL_";function Rg(o){let n=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\"));switch(o.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 YS(o){return o==="powershell"?"":" "}function Kx(o){let n=o.replace(/\r\n|\r/g,`
`);return/(?<!\\)\n/.test(n)}function Gx(o){return dt||Kx(o)}function dU(){return O().replace(/-/g,"")}function cU(o,n){return n==="powershell"?`Write-Output "${JS}${o}_EXIT_$LASTEXITCODE>>>"`:`echo "${JS}${o}_EXIT_$?>>>"`}function uU(o,n){let e=`${JS}${n}_EXIT_`,t=o.lastIndexOf(e);for(;t!==-1;){let r=o.substring(0,t),i=o.substring(t+e.length),s=i.indexOf(">>>");if(s!==-1){let a=i.substring(0,s).trim();if(/^-?\d+$/.test(a))return{found:!0,exitCode:parseInt(a,10),outputBeforeSentinel:r}}t=o.lastIndexOf(e,t-1)}return{found:!1,exitCode:-1,outputBeforeSentinel:o}}function ai(o){let n=R_(o).trim();return n.length>jx&&(n=n.substring(n.length-jx)),n}function xg(o,n,e,t,r){return t.supportsCommandDetection(o.terminalUri)?pU(o,n,e,t,r):fU(o,n,e,t,r)}function Jx(o,n,e,t,r){n.createAltBufferPromise(o.terminalUri,t).then(()=>{e.info("[ShellCommand] Command entered alternate buffer"),r({status:"altBuffer",output:""})})}async function pU(o,n,e,t,r){let i=new Y,s=new Promise(a=>{let l=!1,d=u=>{l||(l=!0,i.dispose(),a(u))};i.add(t.onCommandFinished(o.terminalUri,u=>{let p=ai(u.output),m=u.exitCode??0;r.info(`[ShellCommand] Command completed (shell integration) with exit code ${m}`),d({status:"completed",exitCode:m,output:p})})),Jx(o,t,r,i,d),i.add(t.onExit(o.terminalUri,u=>{r.info(`[ShellCommand] Shell exited unexpectedly with code ${u}`);let p=t.getContent(o.terminalUri)??"";d({status:"shellExited",exitCode:u,output:ai(p)})})),i.add(t.onClaimChanged(o.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(o.terminalUri)??"";d({status:"timeout",output:ai(u)})},e);i.add(N(()=>clearTimeout(c)))});try{await t.sendText(o.terminalUri,`${YS(o.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:Gx(n)})}catch(a){throw i.dispose(),a}return s}async function fU(o,n,e,t,r){let i=dU(),s=cU(i,o.shellType),a=new Y,d=(t.getContent(o.terminalUri)??"").length,c=new Promise(u=>{let p=!1,m=S=>{p||(p=!0,a.dispose(),u(S))},v=()=>{let S=t.getContent(o.terminalUri)??"",b=Math.min(d,S.length),I=S.substring(b),_=uU(I,i);if(_.found){let T=ai(_.outputBeforeSentinel);r.info(`[ShellCommand] Command completed with exit code ${_.exitCode}`),m({status:"completed",exitCode:_.exitCode,output:T})}};a.add(t.onData(o.terminalUri,()=>{v()})),Jx(o,t,r,a,m),a.add(t.onExit(o.terminalUri,S=>{r.info(`[ShellCommand] Shell exited unexpectedly with code ${S}`);let I=(t.getContent(o.terminalUri)??"").substring(d);m({status:"shellExited",exitCode:S,output:ai(I)})})),a.add(t.onClaimChanged(o.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(o.terminalUri)??"").substring(d);m({status:"timeout",output:ai(b)})},e);a.add(N(()=>clearTimeout(y))),v()});try{await t.sendText(o.terminalUri,`${YS(o.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:Gx(n)}),await t.sendText(o.terminalUri,s,{shouldExecute:!0})}catch(u){throw a.dispose(),u}return c}var QS=class extends w{constructor(e){super();this._context=e;this.name="bang";this.recordsLocalTurn=!0;this._terminals=new Set;this._register(N(()=>{for(let t of this._terminals)this._context.terminalManager.disposeTerminal(t);this._terminals.clear()}))}tryHandle(e){let t=Vx(e.text);if(t!==void 0)return()=>this._run(e.turnChannel,e.turnId,t)}async _run(e,t,r){let i=this._context,s=de(e)?fe(e):e,a=O(),l=`agenthost-terminal://bang/${O()}`,d=f(2368,null),c=!1;try{let u=i.getState(s)?.workingDirectory,p=u?h.parse(u).fsPath:void 0,m=await i.terminalManager.getDefaultShell(),v=Rg(m);i.dispatch(e,{type:"chat/toolCallStart",turnId:t,toolCallId:a,toolName:"terminal",displayName:d,intention:r}),i.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 i.terminalManager.createTerminal(S,{shell:m,preventShellHistory:!0,nonInteractive:!0}),c=!0,this._terminals.add(l);let b={type:"terminal",resource:l,title:d};i.dispatch(e,{type:"chat/toolCallContentChanged",turnId:t,toolCallId:a,content:[b]});let I=await xg({terminalUri:l,shellType:v},r,wg,i.terminalManager,i.logService),{success:_,pastTenseMessage:T}=this._summarizeResult(I),P=[b];I.output&&P.push({type:"text",text:I.output}),i.dispatch(e,{type:"chat/toolCallComplete",turnId:t,toolCallId:a,result:{success:_,pastTenseMessage:T,content:P}})}catch(u){i.logService.error(`[BangLocalCommand] Command failed for session=${s}: ${u instanceof Error?u.message:String(u)}`,u),c&&(i.terminalManager.disposeTerminal(l),this._terminals.delete(l)),i.dispatch(e,{type:"chat/toolCallComplete",turnId:t,toolCallId:a,result:{success:!1,pastTenseMessage:f(2364,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(2366,null)}:{success:!1,pastTenseMessage:f(2363,null,t)}}case"timeout":return{success:!1,pastTenseMessage:f(2369,null)};case"shellExited":return{success:!1,pastTenseMessage:f(2367,null)};case"background":return{success:!0,pastTenseMessage:f(2362,null)};case"altBuffer":return{success:!0,pastTenseMessage:f(2365,null)}}}};Ec.register(QS);import{homedir as Mg}from"os";var qa="**",Yx="/",Pg="[/\\\\]",Ag="[^/\\\\]",gU=/\//g;function Qx(o,n){switch(o){case 0:return"";case 1:return`${Ag}*?`;default:return`(?:${Pg}|${Ag}+${Pg}${n?`|${Pg}${Ag}+`:""})*?`}}function Xx(o,n){if(!o)return[];let e=[],t=!1,r=!1,i="";for(let s of o){switch(s){case n:if(!t&&!r){e.push(i),i="";continue}break;case"{":t=!0;break;case"}":t=!1;break;case"[":r=!0;break;case"]":r=!1;break}i+=s}return i&&e.push(i),e}function rP(o){if(!o)return"";let n="",e=Xx(o,Yx);if(e.every(t=>t===qa))n=".*";else{let t=!1;e.forEach((r,i)=>{if(r===qa){if(t)return;n+=Qx(2,i===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===Yx?u="":u=_n(c),d+=u;continue}switch(c){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let p=`(?:${Xx(a,",").map(m=>rP(m)).join("|")})`;n+=p,s=!1,a="";break}case"]":{n+="["+d+"]",l=!1,d="";break}case"?":n+=Ag;continue;case"*":n+=Qx(1);continue;default:n+=_n(c)}}i<e.length-1&&(e[i+1]!==qa||i+2<e.length)&&(n+=Pg)}t=r===qa})}return n}var mU=/^\*\*\/\*\.[\w\.-]+$/,hU=/^\*\*\/([\w\.-]+)\/?$/,yU=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,vU=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,SU=/^\*\*((\/[\w\.-]+)+)\/?$/,bU=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,Zx=new an(1e4),eP=function(){return!1},Lr=function(){return null};function ZS(o,n){if(!o)return Lr;let e;typeof o!="string"?e=o.pattern:e=o,e=e.trim();let t=n.ignoreCase??!1,r={...n,equals:t?no:(l,d)=>l===d,endsWith:t?__:(l,d)=>l.endsWith(d),isEqualOrParent:(l,d)=>ro(l,d,n.ignoreCase??!Oe)},i=`${t?e.toLowerCase():e}_${!!n.trimForExclusions}_${t}`,s=Zx.get(i);if(s)return tP(s,o,r);let a;return mU.test(e)?s=CU(e.substring(4),e,r):(a=hU.exec(XS(e,r)))?s=IU(a[1],e,r):(n.trimForExclusions?vU:yU).test(e)?s=_U(e,r):(a=SU.exec(XS(e,r)))?s=nP(a[1].substring(1),e,!0,r):(a=bU.exec(XS(e,r)))?s=nP(a[1],e,!1,r):s=TU(e,r),Zx.set(i,s),tP(s,o,r)}function tP(o,n,e){if(typeof n=="string")return o;let t=function(r,i){return e.isEqualOrParent(r,n.base)?o($y(r.substring(n.base.length),Le),i):null};return t.allBasenames=o.allBasenames,t.allPaths=o.allPaths,t.basenames=o.basenames,t.patterns=o.patterns,t}function XS(o,n){return n.trimForExclusions&&o.endsWith("/**")?o.substring(0,o.length-2):o}function CU(o,n,e){return function(t,r){return typeof t=="string"&&e.endsWith(t,o)?n:null}}function IU(o,n,e){let t=`/${o}`,r=`\\${o}`,i=function(a,l){return typeof a!="string"?null:l?e.equals(l,o)?n:null:e.equals(a,o)||e.endsWith(a,t)||e.endsWith(a,r)?n:null},s=[o];return i.basenames=s,i.patterns=[n],i.allBasenames=s,i}function _U(o,n){let e=oP(o.slice(1,-1).split(",").map(a=>ZS(a,n)).filter(a=>a!==Lr),o),t=e.length;if(!t)return Lr;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 o;return null},i=e.find(a=>!!a.allBasenames);i&&(r.allBasenames=i.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function nP(o,n,e,t){let r=Le===re.sep,i=r?o:o.replace(gU,Le),s=Le+i,a=re.sep+o,l;return e?l=function(d,c){return typeof d=="string"&&(t.equals(d,i)||t.endsWith(d,s)||!r&&(t.equals(d,o)||t.endsWith(d,a)))?n:null}:l=function(d,c){return typeof d=="string"&&(t.equals(d,i)||!r&&t.equals(d,o))?n:null},l.allPaths=[(e?"*/":"./")+o],l}function TU(o,n){try{let e=new RegExp(`^${rP(o)}$`,n.ignoreCase?"i":void 0);return function(t){return e.lastIndex=0,typeof t=="string"&&e.test(t)?o:null}}catch{return Lr}}function Eg(o,n,e){return!o||typeof n!="string"?!1:Nr(o,e)(n)}function Nr(o,n={}){if(!o)return eP;if(typeof o=="string"||wU(o)){let e=ZS(o,n);if(e===Lr)return eP;let t=function(r,i){return!!e(r,i)};return e.allBasenames&&(t.allBasenames=e.allBasenames),e.allPaths&&(t.allPaths=e.allPaths),t}return RU(o,n)}function wU(o){let n=o;return n?typeof n.base=="string"&&typeof n.pattern=="string":!1}function RU(o,n){let e=oP(Object.getOwnPropertyNames(o).map(a=>xU(a,o[a],n)).filter(a=>a!==Lr)),t=e.length;if(!t)return Lr;if(!e.some(a=>!!a.requiresSiblings)){if(t===1)return e[0];let a=function(c,u){let p;for(let m=0,v=e.length;m<v;m++){let y=e[m](c,u);if(typeof y=="string")return y;fp(y)&&(p||(p=[]),p.push(y))}return p?(async()=>{for(let m of p){let v=await m;if(typeof v=="string")return v}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 v=e[p];v.requiresSiblings&&d&&(l||(l=Te(a)),c||(c=l.substring(0,l.length-Di(a).length)));let y=v(a,l,c,d);if(typeof y=="string")return y;fp(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},i=e.find(a=>!!a.allBasenames);i&&(r.allBasenames=i.allBasenames);let s=e.reduce((a,l)=>l.allPaths?a.concat(l.allPaths):a,[]);return s.length&&(r.allPaths=s),r}function xU(o,n,e){if(n===!1)return Lr;let t=ZS(o,e);if(t===Lr)return Lr;if(typeof n=="boolean")return t;if(n){let r=n.when;if(typeof r=="string"){let i=(s,a,l,d)=>{if(!d||!t(s,a))return null;let c=r.replace("$(basename)",()=>l),u=d(c);return fp(u)?u.then(p=>p?o:null):u?o:null};return i.requiresSiblings=!0,i}}return t}function oP(o,n){let e=o.filter(a=>!!a.basenames);if(e.length<2)return o;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 i=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};i.basenames=t,i.patterns=r,i.allBasenames=t;let s=o.filter(a=>!a.basenames);return s.push(i),s}function eb(o,n){return In(o,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 iP(o,n){return o.replace(/^~($|\/|\\)/,`${n}$1`)}import*as lP from"fs";function sP(){return!!process.versions.electron&&!!Xt.commit&&!process.env.VSCODE_DEV}function kg(){return sP()?$_:ip}function aP(){return sP()?"node_modules.asar.unpacked":"node_modules"}var PU=new Set(["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"]);function AU(o){let n=o.trim();return n.length===0?!1:((n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1)),/^&[0-9]+-?$/.test(n)?!0:PU.has(n))}function EU(o){if(!o.includes(">"))return{kind:"read"};let n=o.match(/(?:[0-9]+|&)?>>?\|?\s*(.+)$/);if(!n)return{kind:"unsafeWrite",dest:void 0};let e=n[1].trim();if(AU(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 tb=/(?!.*)/,kU=/^[A-Z_][A-Z0-9_]*=/i,Dg=class extends w{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 i=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,i.denyCommandLineRules))return"denied";let a=this._matchSubCommands(s.subCommands,i);if(a!=="denied"&&this._matchesRule(r,i.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 i of e){if(kU.test(i))return"denied";let s=this._matchSingleCommand(i,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"),i=r.captures(t.rootNode),s=[],a=[];for(let l of i)if(l.name==="command")s.push(l.node.text);else if(l.name==="file_redirect"){let d=EU(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=h.joinPath(Lt.asFileUri(kg()),"@vscode","tree-sitter-wasm","wasm"),r=h.joinPath(t,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return r}}),this._store.isDisposed)return;let i=new e.Parser;this._register(N(()=>{try{i.delete()}catch{}}));let s=h.joinPath(t,"tree-sitter-bash.wasm").fsPath,a=await lP.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=i,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(MU)),this._fallbackRules)}_compileRuleEntries(e){let t=[],r=[],i=[],s=[];for(let[a,l]of Object.entries(e)){let d=DU(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?i.push({regex:d}):t.push({regex:d}):l.matchCommandLine===!0?s.push({regex:d}):r.push({regex:d}))}return{allowRules:t,denyRules:r,allowCommandLineRules:i,denyCommandLineRules:s}}};function DU(o){let n=o.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 i=new RegExp(e,r||void 0);return C_(i)?tb:i}catch{return tb}}if(o==="")return tb;let t;if(o.includes("/")||o.includes("\\")){let r=o.replace(/[/\\]/g,"%%PATH_SEP%%");r=_n(r),r=r.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),t=`^(?:\\.[/\\\\])?${r}`}else t=_n(o);return new RegExp(`^${t}\\b`)}var MU={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 dP="allow-session",LU=[{id:dP,label:f(2372,null),kind:"approve",group:1},{id:"allow-once",label:f(2371,null),kind:"approve"},{id:"skip",label:f(2373,null),kind:"deny",group:2}],NU={"**/*":!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},UU=[Nr(Mg()+"/.*"),Nr(Mg()+"/.*/**")],FU=(Q?[process.env.APPDATA,process.env.LOCALAPPDATA]:dt?[Mg()+"/Library"]:[]).filter(_r);function HU(o,n=Q){if(o.includes("\0"))throw new Error(`Path contains null bytes: ${o}`);if(!n)return;if(o.indexOf(":",2)!==-1)throw new Error(`Path contains invalid characters (alternate data stream): ${o}`);let t=/[<>"|?*]/,r=o.length>2?o.substring(2):o;if(t.test(r))throw new Error(`Path contains invalid characters: ${o}`);if(o.startsWith("\\\\.")||o.startsWith("\\\\?"))throw new Error(`Path is a reserved device path: ${o}`);let i=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,s=o.split("\\");for(let a of s){if(a.length===0)continue;if(i.test(a))throw new Error(`Reserved device name in path: ${o}`);if(a.endsWith(".")||a.endsWith(" "))throw new Error(`Path contains invalid trailing characters: ${o}`);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): ${o}. Please use the full path.`)}}}async function $U(o){try{return await Ue.realpath(o)}catch(t){if(t.code!=="ENOENT")throw t}let n=[Te(o)],e=oe(o);for(;;){let t=oe(e);if(t===e)return o;try{let r=await Ue.realpath(e);return j(r,...n)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")throw r}n.unshift(Te(e)),e=t}}var Ba=class extends w{constructor(e,t,r){super();this._stateManager=e;this._configService=t;this._logService=r;this._commandAutoApprover=this._register(new Dg(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(Ut,Sv)===!1)return;let i=this._commandAutoApprover.shouldAutoApprove(e.toolInput,{autoApproveRules:this._configService.getRootValue(Ut,Iv),isWriteDestApproved:s=>this._isShellWriteDestApproved(s,r)});if(i==="approved")return this._logService.trace("[SessionPermissionManager] Auto-approving shell command"),"not-needed";i==="denied"&&this._logService.trace("[SessionPermissionManager] Shell command denied by rule");return}}}isGlobalAutoApproveEnabled(){return this._configService.getRootValue(Ut,jd)===!0}isSessionAutoApproveEnabled(e){return this._configService.getEffectiveValue(e,Yt,"autoApprove")==="autoApprove"}createToolReadyAction(e,t,r){let i=e.state;return i.confirmationTitle?{type:"chat/toolCallReady",turnId:r,toolCallId:i.toolCallId,invocationMessage:i.invocationMessage,toolInput:i.toolInput,confirmationTitle:i.confirmationTitle,edits:i.edits,editable:i.editable,...i._meta?{_meta:i._meta}:{},options:i.options?i.options.slice():LU.slice()}:{type:"chat/toolCallReady",turnId:r,toolCallId:i.toolCallId,invocationMessage:i.invocationMessage,toolInput:i.toolInput,confirmed:"not-needed",...i._meta?{_meta:i._meta}:{}}}handleToolCallConfirmed(e,t,r){if(!de(e))throw new Error(`Tool call confirmations must be handled on an AHP chat channel: ${e}`);let i=fe(e);if(r===dP){let s=this._getToolNameForToolCall(e,t);s&&this._addToolToSessionPermissions(i,s)}}_isPathInWorkingDirectory(e,t){if(!t)return!1;let r=h.parse(t);return nt.isEqualOrParent(wn(h.file(e)),r)}_isShellWriteDestApproved(e,t){let r=this._resolveShellRedirectPath(e,t);return r?this._checkWritePath(r,t):!1}_resolveShellRedirectPath(e,t){let r=iP(e.trim(),Mg());if(r){if(Wt(r))return r;if(t)return Fn(h.parse(t).fsPath,r)}}async _isEditAutoApproved(e,t){let r=await this._resolveWritePaths(e);return r!==void 0&&r.every(i=>this._checkWritePath(i,t))}async _resolveWritePaths(e){let t=[e];if(Wt(e))try{let r=await $U(e);r!==e&&t.push(r)}catch(r){let i=r.code;if(i==="EPERM"||i==="EACCES")return}return t}_checkWritePath(e,t){try{HU(e)}catch{return!1}return!this._isPathInWorkingDirectory(e,t)||this._isPlatformRestrictedPath(e,t)?!1:this._matchesEditAutoApprovePatterns(e)}_isPlatformRestrictedPath(e,t){if(UU.some(s=>s(e)))return!0;let r=h.file(e),i=t?h.parse(t):void 0;for(let s of FU){let a=h.file(s);if(nt.isEqualOrParent(r,a))return!(i&&nt.isEqualOrParent(i,a))}return!1}_matchesEditAutoApprovePatterns(e){let t=!0;for(let[r,i]of Object.entries(NU))i!==t&&Eg(r,e)&&(t=i);return t}_isToolAllowedByPermissions(e,t){let r=this._getToolNameForToolCall(e,t);if(!r)return!1;let s=this._configService.getEffectiveValue(e,Yt,"permissions")?.allow.includes(r)??!1;return s&&this._logService.trace(`[SessionPermissionManager] Auto-approving "${r}" via permissions`),s}_getToolNameForToolCall(e,t){let i=this._stateManager.getSessionState(e)?.activeTurn?.responseParts;if(i){for(let s of i)if(s.kind==="toolCall"&&s.toolCall.toolCallId===t)return s.toolCall.toolName}}_addToolToSessionPermissions(e,t){let r=this._configService.getEffectiveValue(e,Yt,"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}`))}};Ba=R([C(1,He),C(2,M)],Ba);import{CAPIClient as qU,RequestType as kc}from"@vscode/copilot-api";var Og={apiBaseUri:"https://api.github.com",graphQlUri:"https://api.github.com/graphql",oauthServer:"https://github.com/login/oauth",enterpriseHost:void 0};function cP(o){if(!o)return Og;let n;try{n=h.parse(o)}catch{return Og}let e=n.authority;if(!e||e==="github.com"||e==="www.github.com"||e==="api.github.com")return Og;let t=n.scheme||"https",r=/\.ghe\.com$/.test(e);return{apiBaseUri:r?`${t}://api.${e}`:`${t}://${e}/api/v3`,graphQlUri:r?`${t}://api.${e}/graphql`:`${t}://${e}/api/graphql`,oauthServer:`${t}://${e}/login/oauth`,enterpriseHost:e}}function uP(o){return{resource:o.apiBaseUri,resource_name:"GitHub Copilot",authorization_servers:[o.oauthServer],scopes_supported:["read:user","user:email"],required:!0}}function pP(o){return{resource:`${o.apiBaseUri}/repos`,resource_name:"GitHub Repository",authorization_servers:[o.oauthServer],scopes_supported:["repo"],required:!1}}var xt=W("agentHostGitHubEndpointService"),za=class extends w{constructor(e,t){super();this._configurationService=e;this._logService=t;this._onDidChange=this._register(new A);this.onDidChange=this._onDidChange.event;let r=this._resolve();this._endpoints=r.endpoints,this._enterpriseUri=r.enterpriseUri,this._register(this._configurationService.onDidRootConfigChange(()=>{let i=this._resolve();i.endpoints.apiBaseUri===this._endpoints.apiBaseUri&&i.endpoints.graphQlUri===this._endpoints.graphQlUri&&i.endpoints.oauthServer===this._endpoints.oauthServer||(this._logService.info(`[AgentHost] GitHub endpoints changed (api=${i.endpoints.apiBaseUri})`),this._endpoints=i.endpoints,this._enterpriseUri=i.enterpriseUri,this._onDidChange.fire())}))}_resolve(){let e=this._configurationService.getRootValue(fr,"githubEnterpriseUri");return{endpoints:cP(e),enterpriseUri:e||void 0}}getApiBaseUri(){return this._endpoints.apiBaseUri}getGraphQlUri(){return this._endpoints.graphQlUri}getEnterpriseHost(){return this._endpoints.enterpriseHost}getEnterpriseUri(){return this._enterpriseUri}getCopilotResource(){return uP(this._endpoints)}getRepoResource(){return pP(this._endpoints)}};za=R([C(0,He),C(1,M)],za);var nb="code-oss";function fP(o){let n=new Map;if(!o)return n;let e=o.indexOf(":"),t=e===-1?o:o.substring(0,e);for(let r of t.split(";")){let i=r.indexOf("=");i<=0||n.set(r.substring(0,i),r.substring(i+1))}return n}var Dc=520,BU=300,gP=1800,mP="2025-04-01",zU="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE";function VU(o){let n;try{n=new URL(o).hostname}catch{return!1}let e=n.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}var jU=300,KU="gpt-4o-mini",GU=.1,JU=1,YU="conversation-background",gr=class extends Error{constructor(e,t,r){super(r??t.error.message);this.status=e;this.envelope=t;this.name="CopilotApiError"}};function Lg(o,n,e,t="CAPI request failed"){let r;if(e)try{let i=JSON.parse(e);if(i&&typeof i=="object"&&i.type==="error"){let s=i.error;s&&typeof s=="object"&&typeof s.type=="string"&&typeof s.message=="string"&&(r=i)}}catch{}return r||(r={type:"error",error:{type:"api_error",message:e||`${o} ${n}`},request_id:null}),new gr(o,r,`${t}: ${o} ${n} \u2014 ${r.error.message}`)}var Pt=W("copilotApiService"),li=class{constructor(n,e,t,r){this._logService=e;this._productService=t;this._gitHubEndpointService=r;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:kc.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),i=O(),s="<unknown>";try{s=JSON.parse(e).model??"<none>"}catch{}this._logService.info(`[CopilotApiService] POST responses: requestId=${i}, model=${s}`);let a=await r.makeRequest({method:"POST",headers:{...t?.headers,"Content-Type":"application/json",Authorization:`Bearer ${n}`,"X-Request-Id":i,"OpenAI-Intent":"conversation"},suppressIntegrationId:t?.suppressIntegrationId,body:e,signal:t?.signal},{type:kc.ChatResponses});if(this._logService.info(`[CopilotApiService] responses status=${a.status}, requestId=${i}`),!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),i=await this._getCopilotToken(n),s=await this._resolveUtilityModelId(n,KU),a=O();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??GU,top_p:JU}),d=await r.makeRequest({method:"POST",headers:{...t?.headers,"Content-Type":"application/json",Authorization:`Bearer ${i}`,"X-Request-Id":a,"OpenAI-Intent":YU},body:l,signal:t?.signal},{type:kc.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([Bf(i=>this._logService.warn("[CopilotApiService] getMachineId failed",i)),zf(i=>this._logService.warn("[CopilotApiService] getDevDeviceId failed",i))]),t={name:"agent-host",sessionId:O(),machineId:n,deviceId:e,vscodeVersion:this._productService.version,version:this._productService.version,buildType:this._productService.quality==="stable"?"prod":"dev"},r=`${this._gitHubEndpointService.getApiBaseUri()}/copilot_internal/user`;return{extensionInfo:t,userUrl:r}}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 i=await this._getClientForToken(n),s=O();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 i.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:kc.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=fP(await this._getCopilotToken(n)),t=e.get("rt")==="1",r=e.get("tid"),i=t?(await this._getEntryForToken(n)).telemetryEndpoint:void 0;return{restrictedTelemetryEnabled:t,trackingId:r,telemetryEndpoint:i}}async resolveApiEndpoint(n){return(await this._getEntryForToken(n)).apiEndpoint}async resolveUserLogin(n){return(await this._getEntryForToken(n)).login}_getEntryForToken(n){let e=Date.now()/1e3,t=this._clientsByToken.get(n);if(t)return t.then(i=>i.expiresAt-e>BU?i:(this._clientsByToken.delete(n),this._getEntryForToken(n))).catch(i=>{throw this._clientsByToken.delete(n),i});let r=this._buildClientForToken(n).catch(i=>{throw this._clientsByToken.delete(n),i});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,i=new qU(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[zU];if(s){if(VU(s))return this._logService.info(`[CopilotApiService] Using CAPI URL override ${s}; skipping endpoint discovery`),i.updateDomains({endpoints:{api:s,proxy:s},sku:""},void 0),{capiClient:i,expiresAt:Date.now()/1e3+gP,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":mP}});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 i.updateDomains({endpoints:l.endpoints??{},sku:l.access_type_sku??""},this._gitHubEndpointService.getEnterpriseUri()),this._logService.debug("[CopilotApiService] CAPI endpoint discovered, api=",l.endpoints?.api),{capiClient:i,expiresAt:Date.now()/1e3+gP,login:l.login,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(i=>i.expiresAt-e>jU?i.token:(this._copilotTokensByGithub.get(n)===t&&this._copilotTokensByGithub.delete(n),this._getCopilotToken(n))).catch(i=>{throw this._copilotTokensByGithub.get(n)===t&&this._copilotTokensByGithub.delete(n),i});let r=this._buildCopilotToken(n).catch(i=>{throw this._copilotTokensByGithub.get(n)===r&&this._copilotTokensByGithub.delete(n),i});return this._copilotTokensByGithub.set(n,r),r.then(i=>i.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":mP}},{type:kc.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 i=Date.now()/1e3,s=typeof r.refresh_in=="number"?r.refresh_in:void 0,a=Math.max(s!==void 0?i+s:r.expires_at,i+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,i=r?.modelIdsByFamily.get(e);if(i)return i;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:i,value:s}=await e.read();if(i)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 i=this._parseDataLine(r);if(i!==void 0&&(yield i,i.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 i=t.type;if(typeof i=="string"){if(i==="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 gr(Dc,a)}if(QU.has(i))return t}}};li=R([C(1,M),C(2,ft),C(3,xt)],li);var QU=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);var Ng="VSCODE_PROXY_ERROR:",XU=8*1024,ZU=/^[A-Za-z0-9+/]+={0,2}$/;function hP(o){switch(o){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 Ug(o){let n=o.status===Dc?502:o.status,e=typeof o.envelope.request_id=="string"?o.envelope.request_id:"",t=e2(o.envelope.error.message)??{code:o.envelope.error.type,message:o.envelope.error.message};return{fetchError:{type:hP(n),reason:t.message??o.envelope.error.message,requestId:e,capiError:t}}}function e2(o){let n;try{n=JSON.parse(o)}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 Fg(o){return`${Ng}${Buffer.from(JSON.stringify(o)).toString("base64")}`}function t2(o,n){switch(o){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?hP(n):void 0}function n2(o){let n=t2(o.errorType,o.statusCode);if(!n)return;let e=o.errorCode??(n==="quotaExceeded"?"quota_exceeded":void 0),t=e||o.message?{code:e,message:o.message}:void 0;return{fetchError:{type:n,reason:o.message,requestId:o.providerCallId??"",serverRequestId:o.serviceRequestId,...t&&{capiError:t}}}}function Hg(o){if(!o)return;let n=o.indexOf(Ng);if(n===-1)return;let e=n+Ng.length,t=o.slice(e).search(/[\s"']/),r=t===-1?o.slice(e):o.slice(e,e+t);if(!(r.length===0||r.length>XU||!ZU.test(r)))try{let i=JSON.parse(Buffer.from(r,"base64").toString());return i&&typeof i=="object"&&i.fetchError&&typeof i.fetchError.type=="string"?i:void 0}catch{return}}function Mc(o){let n=o.indexOf(Ng);return n===-1?o:o.slice(0,n).trim()||o.slice(0,n)}function Oc(o){return{chatError:o}}function yP(o){let n=Hg(o);return n?Oc(n):void 0}function vP(o){let n=n2(o);return n?Oc(n):void 0}function Va(o){let n=Hg(o);return n?{message:Mc(o),_meta:Oc(n)}:{message:o}}var ja=class extends w{constructor(e,t,r,i,s,a,l){super();this._stateManager=e;this._options=t;this._logService=i;this._changesets=s;this._telemetryService=a;this._checkpointService=l;this._toolCallAgents=new Map;this._lastAgentInfos=[];this._subagentChats=new dd;this._pendingSubagentSignals=new dd;this._telemetryReporter=new Aa(this._telemetryService),this._turnTracker=new yg(this._telemetryReporter),this._toolCallTracker=this._register(new qf(this._telemetryReporter)),this._permissionManager=this._register(r.createInstance(Ba,this._stateManager)),this._localCommands=this._register(r.createInstance($a,this._stateManager,this._options.localTurns,d=>this._tryConsumeNextQueuedMessage(d))),this._titleController=this._register(r.createInstance(Pa,this._stateManager,{sessionDataService:this._options.sessionDataService,getGitHubCopilotToken:this._options.getGitHubCopilotToken,copilotApiService:this._options.copilotApiService})),this._register(jn(d=>{let c=this._options.agents.read(d);this._publishAgentInfos(c,d)})),this._register(this._stateManager.onDidEmitEnvelope(d=>{if(de(d.channel)&&pr(d.action)&&this._syncSessionInputNeededForChatAction(d.channel,d.action),!d.origin&&d.action.type==="chat/toolCallComplete"){let c=d.action;if(!de(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(i=>{let s=i.getDescriptor(),a=i.getProtectedResources(),l=t?i.models.read(t):i.models.get(),d=i.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}});Ne(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(h.parse(t)),i=this._stateManager.getSessionState(t)?.customizations;i&&Ne(i,r)||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 i=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:i,kind:"toolConfirmation",chat:e,turnId:t,toolCall:a}):this._removeSessionInputNeeded(e,i);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 i=this._stateManager.getSessionState(e),a=(i?.activeTurn?.id===t?i.activeTurn:i?.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),i=this._stateManager.getSessionState(r)?.inputNeeded?.find(s=>s.id===t.id);if(!(i&&Ne(i,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(i=>i.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 Y;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(),i=t.parentToolCallId;if(i){let a=this._subagentChats.get(r,i);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}/${i}`);let l=this._pendingSubagentSignals.get(r,i);l||(l=[],this._pendingSubagentSignals.set(l,r,i)),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,i){if(e.kind==="pending_confirmation"){i&&this._handleToolReady(e,t,r,i).catch(l=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",l)});return}if(e.kind!=="action")return;let s=e.action;he(s,{turnId:!0})&&s.turnId!==r&&(s={...s,turnId:r}),s.type==="chat/toolCallStart"&&i&&(this._toolCallAgents.set(`${t}:${s.toolCallId}`,i.id),this._toolCallTracker.toolCallStarted(i.id,t,s.toolCallId,s.toolName,s.contributor));let a=de(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=>he(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),LT(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=de(e)?fe(e):e;t!==void 0?this._checkpointService.captureTurnCheckpoint(h.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 i=de(e)&&!Fe(e)?e:void 0;this._titleController.refineTitleFromFirstTurn(r,i)}_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:i,agent:s}of r)this._handleAgentSignal(s,i)}}_handleSubagentStarted(e,t,r,i,s,a){let l=fe(e),d=ra(l,t);if(this._subagentChats.get(e,t))return;this._logService.info(`[AgentSideEffects] Starting subagent turn: ${d} (parent=${e}, toolCallId=${t})`);let c=O();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),v=this._getRunningToolCallContent(m,p,t);this._stateManager.dispatchServerAction(u,{type:"chat/toolCallContentChanged",turnId:p,toolCallId:t,content:[...v,{type:"subagent",resource:d,title:i,agentName:r,description:s}]})}}_getRunningToolCallContent(e,t,r){if(!e?.activeTurn||e.activeTurn.id!==t)return[];for(let i of e.activeTurn.responseParts)if(i.kind==="toolCall"&&i.toolCall.toolCallId===r&&i.toolCall.status==="running")return i.toolCall.content?[...i.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 i=this._stateManager.getActiveTurnId(r.chatUri);i&&this._stateManager.dispatchServerAction(r.chatUri,{type:"chat/turnComplete",turnId:i}),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(!Wd(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,i,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=${i.success}`),l.onClientToolCallComplete(h.parse(e),h.parse(a),r,i)}async _handleToolReady(e,t,r,i){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}`,i.id),u={...e,state:{...e.state,_meta:{...d?._meta,...e.state._meta,...Rt({autoApproveBySetting:!0})}}}):a!==void 0?(this._toolCallAgents.delete(`${t}:${e.state.toolCallId}`),i.respondToPermissionRequest(e.state.toolCallId,!0),u={...e,state:{...e.state,confirmationTitle:void 0}}):u.state.confirmationTitle&&this._toolCallAgents.set(`${t}:${e.state.toolCallId}`,i.id),this._stateManager.dispatchServerAction(t,this._permissionManager.createToolReadyAction(u,t,r))}handleAction(e,t,r){let i=de(e)?e:void 0,s=i?fe(i):e;switch(t.type){case"chat/turnStarted":{if(!i)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,i);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(!i)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(!i)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(!i)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=h.parse(e);a.chats.abort(l).catch(d=>{this._logService.error("[AgentSideEffects] abort failed",d)})}break}case"session/titleChanged":{if(i){this._stateManager.updateChatTitle(s,i,t.title),this._persistSessionFlag(s,`customChatTitle:${i}`,t.title);break}this._persistSessionFlag(e,"customTitle",t.title);break}case"chat/pendingMessageSet":case"chat/pendingMessageRemoved":case"chat/queuedMessagesReordered":{if(!i)throw new Error(`${t.type} must be handled on an AHP chat channel: ${e}`);this._syncPendingMessages(e);break}case"chat/truncated":{if(!i)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(i,t.turnId):t.turnId;a?.truncateSession?.(h.parse(s),l,h.parse(i)).catch(u=>{this._logService.error("[AgentSideEffects] truncateSession failed",u)});let d=new Set((this._stateManager.getChatState(i)?.turns??[]).map(u=>u.id)),c=this._options.localTurns.getLocalTurnIds(i).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(h.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(h.parse(e),t.clientId);break}case"root/configChanged":{hg(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/mcpServerStartRequested":{this._options.getAgent(s)?.startMcpServer?.(h.parse(s),t.id).catch(l=>{this._logService.warn(`[AgentSideEffects] startMcpServer failed for ${s}`,l)});break}case"session/mcpServerStopRequested":{this._options.getAgent(s)?.stopMcpServer?.(h.parse(s),t.id).catch(l=>{this._logService.warn(`[AgentSideEffects] stopMcpServer failed for ${s}`,l)});break}case"session/isReadChanged":{this._persistSessionFlag(e,"isRead",t.isRead?"true":"");break}case"session/isArchivedChanged":{this._persistSessionFlag(e,qn,t.isArchived?"true":""),this._options.getAgent(e)?.onArchivedChanged?.(h.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(!i)break;this._notifyClientToolCallComplete(s,i,t.toolCallId,t.result,"client-dispatch");break}}}cancelSessionTitleGeneration(e){this._titleController.cancelTitleGeneration(e)}generateForkedTitle(e,t,r,i,s){this._titleController.generateForkedTitle(e,t,r,i,s)}_persistSessionFlag(e,t,r){vg(this._options.sessionDataService,this._logService,e,t,r)}_persistChatDraft(e,t){if(!de(e))return;let r=ke(e);if(!r)return;let i=h.parse(r.session),s=this._options.sessionDataService.openDatabase(i);s.object.setChatDraft(h.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?.(h.parse(t),r.steeringMessage,[],Fe(e)?void 0:h.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 i=r.queuedMessages[0],s=O();if(this._stateManager.dispatchServerAction(e,{type:"chat/turnStarted",turnId:s,message:i.message,queuedMessageId:i.id}),this._localCommands.tryHandle({turnChannel:e,turnId:s,text:i.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=i.message.attachments,d=this._stateManager.getSessionState(e);this._telemetryReporter.userMessageSent(a.id,e,d,"queued",l);let{model:c,permissionLevel:u}=this._getTurnTelemetryContext(d,i.message.model?.id);this._turnTracker.turnStarted(a.id,e,s,c,u),this._sendTurnMessage({agent:a,sessionChannel:t,turnChannel:e,chat:e,message:i.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,sessionChannel:r,turnChannel:i,chat:s,message:a,turnId:l,senderClientId:d}=e,c=this._stateManager.getChatState(s),p=((this._stateManager.getSessionSummary(e.sessionChannel)?.status??0)&64)===64;if(qT(c?.interactivity,p)){this._logService.warn(`[AgentSideEffects] Rejecting turn on read-only chat=${s} (archived=${p}), turnId=${l}`),this._stateManager.dispatchServerAction(i,{type:"chat/error",turnId:l,error:p?{errorType:"archived",message:"This session is archived and read-only. Restore the session to continue the conversation."}:{errorType:"readOnly",message:"This chat is read-only."}}),this._turnTracker.turnCompleted(i,l,"error"),this._toolCallTracker.clearSession(i);return}let m=h.parse(s),v=[];a.model&&v.push(t.chats.changeModel(m,a.model).catch(y=>{this._logService.error("[AgentSideEffects] changeModel failed",y)})),v.push(t.chats.changeAgent(m,a.agent).catch(y=>{this._logService.error("[AgentSideEffects] changeAgent failed",y)})),await Promise.all(v);try{await t.chats.sendMessage(m,a.text,a.attachments,l,d)}catch(y){let S=y?.code;this._logService.error(`[AgentSideEffects] sendMessage failed for session=${i}: code=${S}, message=${y instanceof Error?y.message:String(y)}, type=${y?.constructor?.name}`,y),this._stateManager.dispatchServerAction(i,{type:"chat/error",turnId:l,error:SP(y)}),this._turnTracker.turnCompleted(i,l,"error"),this._toolCallTracker.clearSession(i),this._failSessionCreationIfStillCreating(r,y)}}_failSessionCreationIfStillCreating(e,t){if(this._stateManager.getSessionState(e)?.lifecycle!=="creating")return;this._stateManager.dispatchServerAction(e,{type:"session/creationFailed",error:SP(t)});let i=this._stateManager.getSessionSummary(e);i&&this._stateManager.markSessionPersisted(e,i)}dispose(){this._toolCallAgents.clear(),this._toolCallTracker.clear(),super.dispose()}};ja=R([C(2,xe),C(3,M),C(4,xa),C(5,zn),C(6,Mr)],ja);function SP(o){let n=String(o),e=Hg(o instanceof Error?o.message:n);return e?{errorType:"sendFailed",message:Mc(n),_meta:Oc(e)}:{errorType:"sendFailed",message:n}}var $g=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 i=(this._seqBySession.get(n)??0)+1;this._noteInMemory(n,e,t.id,r,i);let s={turnId:t.id,chatUri:e,anchorTurnId:r,seq:i,payload:JSON.stringify(t)},a;try{a=this._sessionDataService.openDatabase(h.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,i){this._noteInMemory(n,e,t,r,i)}deleteLocals(n,e){if(e.length===0)return;let t=new Set(e);for(let i of this._byChat.values())for(let s of t)i.delete(s);let r;try{r=this._sessionDataService.openDatabase(h.parse(n))}catch(i){this._logService.warn(`[AgentHostLocalTurns] Failed to open database to delete local turns for ${n}`,i);return}r.object.deleteLocalTurns(e).catch(i=>{this._logService.warn(`[AgentHostLocalTurns] Failed to delete local turns for ${n}`,i)}).finally(()=>r.dispose())}forgetChat(n){this._byChat.delete(n)}async _load(n){let e=this._sessionDataService.tryOpenDatabase?.(h.parse(n));if(!e)return[];try{let t=await e;if(!t)return[];try{let r=await t.object.getLocalTurns();for(let i of r)this._noteInMemory(n,i.chatUri,i.turnId,i.anchorTurnId,i.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,i){let s=this._byChat.get(e);s||(s=new Map,this._byChat.set(e,s)),s.set(t,{anchorTurnId:r,seq:i}),this._seqBySession.set(n,Math.max(this._seqBySession.get(n)??0,i))}};var Wg=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 Lc="vscode.agentFeedback",bP="viewUnreviewedComments",CP="addComment";function r2(o){return o==="user"||o==="codeReview"||o==="prReview"}function o2(o){return o==="created"||o==="accepted"||o==="submitted"||o==="resolved"}function IP(o){let e=o._meta?.[Lc];if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(!r2(t.kind)||!o2(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 Ur=CP,ib="listComments",Bg="deleteComments",Uc="resolveComments",Fc=bP,wP=new Set(["prReview","codeReview"]),i2=new Set([Fc]);function s2(o){return i2.has(o)}var a2={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"]},l2={type:"object",properties:{}},d2={type:"object",properties:{}},c2={type:"object",properties:{commentIds:{type:"array",items:{type:"string"},description:"Comment IDs to delete."}},required:["commentIds"]},u2={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:Ur,title:"Add Comment (Agent Feedback)",description:"Add a comment to a file range.",inputSchema:a2,annotations:{readOnlyHint:!1}},{name:ib,title:"List Comments (Agent Feedback)",description:"List comments for this session.",inputSchema:l2,annotations:{readOnlyHint:!0}},{name:Bg,title:"Delete Comments (Agent Feedback)",description:"Delete comments for this session.",inputSchema:c2,annotations:{readOnlyHint:!1,destructiveHint:!0}},{name:Uc,title:"Resolve Comments (Agent Feedback)",description:"Mark comments for this session as resolved or unresolved.",inputSchema:u2,annotations:{readOnlyHint:!1}},{name:Fc,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:d2,annotations:{readOnlyHint:!0}}];function ob(o,n,e){if(typeof o!="string"||o.length===0)throw new Error(`Invalid ${e} input: ${n} must be a non-empty string.`);return o}function qg(o,n,e){if(typeof o!="number"||!Number.isInteger(o)||o<1)throw new Error(`Invalid ${e} input: ${n} must be a positive integer.`);return o}function f2(o){let n=o??{},e=ob(n.resourceUri,"resourceUri",Ur),t=ob(n.text,"text",Ur);if(!n.range||typeof n.range!="object"||Array.isArray(n.range))throw new Error(`Invalid ${Ur} input: range must be an object.`);let r=n.range;return{resourceUri:e,text:t,range:{startLineNumber:qg(r.startLineNumber,"range.startLineNumber",Ur),startColumn:qg(r.startColumn,"range.startColumn",Ur),endLineNumber:qg(r.endLineNumber,"range.endLineNumber",Ur),endColumn:qg(r.endColumn,"range.endColumn",Ur)}}}function _P(o,n){if(!Array.isArray(o)||o.length===0)throw new Error(`Invalid ${n} input: commentIds must be a non-empty string array.`);let e=[];for(let t of o)e.push(ob(t,"commentIds[]",n));return[...new Set(e)]}function g2(o){if(o===void 0)return!0;if(typeof o!="boolean")throw new Error(`Invalid ${Uc} input: resolved must be a boolean.`);return o}function m2(o){return{start:{line:o.startLineNumber-1,character:o.startColumn-1},end:{line:o.endLineNumber-1,character:o.endColumn-1}}}function h2(o){return o?{startLineNumber:o.start.line+1,startColumn:o.start.character+1,endLineNumber:o.end.line+1,endColumn:o.end.character+1}:{startLineNumber:1,startColumn:1,endLineNumber:1,endColumn:1}}function TP(o){return typeof o=="string"?o:o.markdown}function ls(o){return IP(o)}function Nc(o){let n=o.entries??[],e=ls(o),t=n.slice(1).map(r=>TP(r.text));return{id:o.id,resourceUri:o.resource,range:h2(o.range),text:n.length?TP(n[0].text):"",kind:e?.kind??"user",resolved:o.resolved,...t.length?{replies:t}:{}}}function rb(o){return o.annotations.filter(n=>{let e=ls(n);return!e||!n.entries?.length?!1:(n.resolved?"resolved":e.state??"accepted")!=="created"})}function y2(o){return o.annotations.filter(n=>{let e=ls(n);return!e||!n.entries?.length?!1:wP.has(e.kind)&&e.pendingAgentReveal===!0})}function v2(o){let n=ls(o);if(!n)return o;let e={...n,pendingAgentReveal:void 0};return{...o,_meta:{...o._meta,[Lc]:e}}}function S2(o){return o.annotations.filter(n=>{let e=ls(n);return!e||!n.entries?.length?!1:wP.has(e.kind)&&!n.resolved&&(e.state??"accepted")==="created"})}function b2(o){let n=S2(o);if(!n.length)return;let e=0,t=0;for(let a of n){let l=ls(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 i=r.join(" and ");return`There ${n.length===1?"is":"are"} ${i} which the user has not reviewed yet. If the user wants you to tackle them, call the \`${Fc}\` tool to view them.`}function C2(o,n,e,t){switch(e){case Ur:{let{resourceUri:r,range:i,text:s}=f2(t),a=O(),l={kind:"codeReview",state:"created",sessionResource:n},d={id:a,turnId:"",resource:r,range:m2(i),resolved:!1,entries:[{id:`${a}:0`,text:s}],_meta:{[Lc]:l}};return{actions:[{type:"annotations/set",annotation:d}],result:"Comment added."}}case ib:{let r={comments:rb(o).map(Nc)},i=b2(o);return i&&(r.note=i),{actions:[],result:JSON.stringify(r,void 0,2)}}case Fc:{let r=y2(o),i=r.map(Nc);return{actions:r.map(a=>({type:"annotations/set",annotation:v2(a)})),result:JSON.stringify({comments:i},void 0,2)}}case Bg:{let r=_P(t?.commentIds,Bg),i=rb(o),s=new Map(i.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=i.filter(u=>!l.includes(u.id)).map(Nc);return{actions:a,result:JSON.stringify({deletedCommentIds:l,notFoundCommentIds:d,remainingComments:c},void 0,2)}}case Uc:{let r=t??{},i=_P(r.commentIds,Uc),s=g2(r.resolved),a=rb(o),l=new Map(a.map(m=>[m.id,m])),d=[],c=[],u=[];for(let m of i){let v=l.get(m);if(!v){u.push(m);continue}let y=ls(v),S={...y,kind:y?.kind??"user",state:s?"resolved":"submitted",sessionResource:y?.sessionResource??n},b={...v,resolved:s,_meta:{...v._meta,[Lc]:S}};d.push({type:"annotations/set",annotation:b}),c.push(m)}let p=a.map(m=>c.includes(m.id)?Nc({...m,resolved:s}):Nc(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 I2(o){if(o)try{let n=JSON.parse(o);return Array.isArray(n.comments)?n.comments.length:void 0}catch{return}}function _2(o,n,e){switch(o){case Ur:return{displayName:f(2386,null),invocationMessage:f(2381,null),pastTenseMessage:f(2374,null)};case ib:{let t,r=e?I2(e.text):void 0;return r===void 0?t=f(2376,null):r===1?t=f(2378,null):t=f(2377,null,r),{displayName:f(2388,null),invocationMessage:f(2383,null),pastTenseMessage:t}}case Bg:return{displayName:f(2387,null),invocationMessage:f(2382,null),pastTenseMessage:f(2375,null)};case Uc:return{displayName:f(2389,null),invocationMessage:f(2384,null),pastTenseMessage:f(2379,null)};case Fc:return{displayName:f(2390,null),invocationMessage:f(2385,null),pastTenseMessage:f(2380,null)};default:return}}var RP={definitions:p2,requiresConfirmation(o){return s2(o)},getDisplay(o,n,e){return _2(o,n,e)},execute(o,n,e,t){let r=ke(n)?.session??n,i=Lf(r),a=o.getSnapshot(i)?.state??{annotations:[]},l=C2(a,r,e,t);for(let d of l.actions)o.dispatchServerAction(i,d);return l.result}};var sb="agent-host-session",xP="create_session",PP="create_chat",AP="send_message";function ds(o,n){let e=D.provider(o),t=D.id(o);if(!e)throw new Error(`Cannot build open-session link: missing provider in ${o.toString()}`);let r=h.from({scheme:sb,authority:e,path:`/${t}`}).toString();return n?`${r}?chat=${encodeURIComponent(n)}`:r}function ab(o){let n=typeof o=="string"?h.parse(o):o;if(n.scheme!==sb||!n.authority)return;let e=n.path.replace(/^\//,"");if(e)return D.uri(n.authority,e)}function lb(o){let n=typeof o=="string"?h.parse(o):o;if(n.scheme!==sb)return;let e=/(?:^|&)chat=([^&]+)/.exec(n.query);return e?decodeURIComponent(e[1]):void 0}var An="list_sessions",ub="get_current_session",_o=xP,Fr=PP,di=AP,cs="get_session_context",us="delete_session",EP=3,kP=25,DP=25,MP=50,T2=new Set([_o,Fr,di,us]);function w2(o){return T2.has(o)}var db=["idle","inProgress","inputNeeded","error","archived"],R2={type:"object",properties:{session:{type:"string",description:"Return only the session with this URI or `agent-host-session://` link (a direct lookup that ignores the other filters). Use this to fetch one known session's metadata."},status:{type:"array",items:{type:"string",enum:[...db]},description:"Only return sessions whose status matches one of these (e.g. `inputNeeded` for sessions awaiting a reply, `inProgress` for running ones). Omit to return every status."},workspace:{type:"string",description:"Only return sessions whose working directory is this folder \u2014 an absolute path or a workspace URI."},withChanges:{type:"boolean",description:"When true, only return sessions that have pending worktree changes."},unread:{type:"boolean",description:"When true, only return sessions with updates the user has not seen yet."},withPullRequest:{type:"boolean",description:"When true, only return sessions that have a linked GitHub pull request."},includeArchived:{type:"boolean",description:"Whether to include archived sessions. Defaults to false; set true to also return archived sessions."},createdAfter:{type:"string",description:"Only return sessions created at or after this time (ISO-8601 timestamp, e.g. `2025-01-31T00:00:00Z`)."},createdBefore:{type:"string",description:"Only return sessions created at or before this time (ISO-8601 timestamp)."}}},x2={type:"object",properties:{workspace:{type:"string",description:"Absolute folder path, workspace URI, or a working directory from an existing session."},prompt:{type:"string",description:"Initial prompt to send to the new session."},model:{type:"string",description:"Optional model ID or display name."}},required:["workspace","prompt"]},P2={type:"object",properties:{}},A2={type:"object",properties:{session:{type:"string",description:"Optional session to add the chat to: a session URI from `list_sessions` or an `agent-host-session://` link. Defaults to the current session when omitted."},prompt:{type:"string",description:"Initial prompt to send to the new chat."},title:{type:"string",description:"Optional title for the new chat."},model:{type:"string",description:"Optional model ID or display name. Defaults to the session's model."}},required:["prompt"]},E2={type:"object",properties:{session:{type:"string",description:"The session to delete: a session URI from `list_sessions` or an `agent-host-session://` link (e.g. from `create_session`)."}},required:["session"]},k2={type:"object",properties:{session:{type:"string",description:"The session or chat to message: a session URI from `list_sessions`, or an `agent-host-session://` link (from `create_session`/`create_chat`; a `create_chat` link targets that specific chat)."},message:{type:"string",description:"The message to send."}},required:["session","message"]},cb=["summary","digest","full"],D2={type:"object",properties:{session:{type:"string",description:"The session or chat to read: a session URI from `list_sessions`, or an `agent-host-session://` link (a `create_chat` link targets that specific chat)."},detail:{type:"string",enum:[...cb],description:"How much conversation detail to return. `summary` (default): status and a short per-turn gist (the message plus a compact snippet of the reply). `digest`: adds the full assistant reply text and tool-call names. `full`: adds tool-call inputs. Higher levels return more tokens."},transcriptLimit:{type:"number",description:"Maximum number of most-recent turns to include. Defaults to 10; capped at 50."}},required:["session"]},M2=[{name:An,title:"List Sessions",description:"List sessions and their compact metadata (status, activity, working directory, project, worktree changes, git/GitHub info, timestamps). Pass `session` to fetch a single known session by URI. By default archived sessions are omitted. Optionally filter by `status`, `workspace`, `withChanges`, `unread`, `withPullRequest`, `includeArchived`, `createdAfter`, or `createdBefore`.",inputSchema:R2,annotations:{readOnlyHint:!0}},{name:ub,title:"Get Current Session",description:"Get metadata and the open link for the session this conversation is running in. Use this to reference the current session (for example before adding a chat to it).",inputSchema:P2,annotations:{readOnlyHint:!0}},{name:_o,title:"Create Session",description:'Create a session in a workspace and start it with an initial prompt. The UI shows a "Session Created" confirmation with a button to open it, so reply with a single short sentence confirming the session was created and do NOT print the session URL or tell the user to click a button.',inputSchema:x2,annotations:{readOnlyHint:!1}},{name:Fr,title:"Create Chat",description:'Add a new chat to an existing session and start it with an initial prompt. Omit `session` to add the chat to the current session; otherwise pass a session URI from `list_sessions`. Optionally pass a `model` to use for the chat (defaults to the session\'s model). The UI shows a "Chat Created" confirmation with a button to open the session, so reply with a single short sentence and do NOT print the session URL or tell the user to click a button.',inputSchema:A2,annotations:{readOnlyHint:!1}},{name:di,title:"Send Message",description:"Send a message to an existing session or chat, starting a new turn there. Provide a session URI from `list_sessions` or an `agent-host-session://` link (a `create_chat` link targets that specific chat). The message is delivered asynchronously \u2014 this tool does not wait for or return the reply. The UI shows a confirmation with a button to open the target, so reply with a single short sentence and do NOT print the URL or tell the user to click a button.",inputSchema:k2,annotations:{readOnlyHint:!1}},{name:cs,title:"Get Session Context",description:'Read the recent conversation of an existing session or chat: a compacted transcript of its turns (messages, replies, and tool calls). Use this to see what a session you created is doing, or to gather context before sending it a message. Returns a compacted summary by default (`detail: "summary"`); request `digest` or `full` for more detail. For session metadata (status, working directory, changes, \u2026) use `list_sessions` with the `session` argument.',inputSchema:D2,annotations:{readOnlyHint:!0}},{name:us,title:"Delete Session",description:"Permanently delete a session (identified by a session URI from `list_sessions`), including its stored data. This cannot be undone. Refuses to delete the current session.",inputSchema:E2,annotations:{readOnlyHint:!1,destructiveHint:!0}}];function zg(o){let n=ke(o)??void 0;return h.parse(n?.session??o)}function ps(o,n,e){if(typeof o!="string"||o.length===0)throw new Error(`Invalid ${e} input: ${n} must be a non-empty string.`);return o}function Ka(o,n,e){if(o!==void 0){if(typeof o!="string"||o.length===0)throw new Error(`Invalid ${e} input: ${n} must be a non-empty string.`);return o}}function LP(o){if(/^(\/|[a-zA-Z]:[\\/]|\\\\)/.test(o))return h.file(o);try{let n=h.parse(o,!0);return n.scheme?n:void 0}catch{return}}function O2(o,n){let e=n.find(r=>r.workingDirectory?.toString()===o||r.workingDirectory?.fsPath===o);if(e?.workingDirectory)return e.workingDirectory;let t=LP(o);if(!t)throw new Error(`Invalid ${_o} input: workspace must match a known session workingDirectory, an absolute path, or a valid URI string.`);return t}function NP(o,n){if(o===void 0)return;let e=n.find(t=>t.id===o||t.name===o);if(!e)throw new Error(`Invalid ${_o} input: model must match an available model id or name.`);return e}function L2(o,n,e){let t=o??{},r=ps(t.workspace,"workspace",_o),i=ps(t.prompt,"prompt",_o),s=Ka(t.model,"model",_o);return{workspace:O2(r,n),prompt:i,model:NP(s,e)}}function UP(o){let n=[];return(o&24)===24?n.push("inputNeeded"):o&8?n.push("inProgress"):o&1&&n.push("idle"),o&2&&n.push("error"),o&64&&n.push("archived"),n.join(",")||"unknown"}function Vg(o,n,e){if(o!==void 0){if(typeof o!="boolean")throw new Error(`Invalid ${e} input: ${n} must be a boolean.`);return o}}function OP(o,n,e){if(o===void 0)return;if(typeof o!="string")throw new Error(`Invalid ${e} input: ${n} must be an ISO-8601 timestamp string.`);let t=Date.parse(o);if(Number.isNaN(t))throw new Error(`Invalid ${e} input: ${n} must be a valid ISO-8601 timestamp (e.g. 2025-01-31T00:00:00Z).`);return t}function N2(o){let n=o??{},e;if(n.status!==void 0){if(!Array.isArray(n.status)||n.status.some(r=>typeof r!="string"))throw new Error(`Invalid ${An} input: status must be an array of status names.`);let t=n.status.filter(r=>!db.includes(r));if(t.length>0)throw new Error(`Invalid ${An} input: unknown status value(s) ${t.join(", ")}. Valid values: ${db.join(", ")}.`);e=new Set(n.status)}return{session:Ka(n.session,"session",An),status:e,workspace:Ka(n.workspace,"workspace",An),withChanges:Vg(n.withChanges,"withChanges",An),unread:Vg(n.unread,"unread",An),withPullRequest:Vg(n.withPullRequest,"withPullRequest",An),includeArchived:Vg(n.includeArchived,"includeArchived",An),createdAfter:OP(n.createdAfter,"createdAfter",An),createdBefore:OP(n.createdBefore,"createdBefore",An)}}function U2(o){let n=o.changes;return!!n&&((n.files??0)>0||(n.additions??0)>0||(n.deletions??0)>0)}function F2(o){return o.isArchived===!0||o.status!==void 0&&(o.status&64)!==0}function H2(o,n){let e=o.workingDirectory;if(!e)return!1;if(e.toString()===n||e.fsPath===n)return!0;let t=LP(n);return!!t&&t.toString()===e.toString()}function $2(o,n){if(n.session!==void 0){let e=ab(n.session)?.toString()??n.session;return o.filter(t=>t.session.toString()===e)}return o.filter(e=>!(n.status&&!(e.status!==void 0?UP(e.status).split(","):[]).some(r=>n.status.has(r))||n.workspace!==void 0&&!H2(e,n.workspace)||n.withChanges&&!U2(e)||n.unread&&e.isRead!==!1||n.withPullRequest&&!dr(e._meta)?.pullRequestUrl||n.includeArchived!==!0&&F2(e)||n.createdAfter!==void 0&&e.startTime<n.createdAfter||n.createdBefore!==void 0&&e.startTime>n.createdBefore))}function W2(o){let n=St(o._meta);if(!n)return;let e={};return n.branchName!==void 0&&(e.branch=n.branchName),n.baseBranchName!==void 0&&(e.baseBranch=n.baseBranchName),n.upstreamBranchName!==void 0&&(e.upstreamBranch=n.upstreamBranchName),n.outgoingChanges!==void 0&&(e.ahead=n.outgoingChanges),n.incomingChanges!==void 0&&(e.behind=n.incomingChanges),n.uncommittedChanges!==void 0&&(e.uncommittedChanges=n.uncommittedChanges),Object.keys(e).length>0?e:void 0}function q2(o){let n=dr(o._meta);if(!n)return;let e={};return n.owner!==void 0&&(e.owner=n.owner),n.repo!==void 0&&(e.repo=n.repo),n.pullRequestUrl!==void 0&&(e.pullRequestUrl=n.pullRequestUrl),Object.keys(e).length>0?e:void 0}function FP(o){let n=W2(o),e=q2(o);return{session:o.session.toString(),...o.summary!==void 0?{title:o.summary}:{},...o.status!==void 0?{status:UP(o.status)}:{},...o.activity!==void 0?{activity:o.activity}:{},...o.workingDirectory!==void 0?{workingDirectory:o.workingDirectory.toString()}:{},...o.project!==void 0?{project:o.project.displayName}:{},...o.isRead===!1?{unread:!0}:{},...o.startTime>0?{createdAt:new Date(o.startTime).toISOString()}:{},...o.modifiedTime>0?{modifiedAt:new Date(o.modifiedTime).toISOString()}:{},...o.changes!==void 0?{changes:o.changes}:{},...o.changesets!==void 0?{changesets:o.changesets.map(t=>({label:t.label,changeKind:t.changeKind,uriTemplate:t.uriTemplate,...t.description!==void 0?{description:t.description}:{}}))}:{},...n!==void 0?{git:n}:{},...e!==void 0?{github:e}:{}}}function B2(o){return JSON.stringify({sessions:o.map(FP)})}async function z2(o,n,e){let t=e?o.getSessionSpawnDepth(e):0;if(t>=EP)throw new Error(`Refusing to create a session: recursion limit reached (max spawn depth ${EP}). This session was itself created ${t} level(s) deep.`);let r=await o.listSessions(),i=L2(n,r,o.getModels()),s={workingDirectory:i.workspace,...i.model!==void 0?{provider:i.model.provider,model:{id:i.model.id}}:{}},a=await o.createSession(s);o.setSessionSpawnDepth(a,t+1);let l=h.parse(pe(a));return await o.startPrompt(a,l,i.prompt),{session:a.toString(),chat:l.toString(),openLink:ds(a)}}function V2(o){return`Session created (${o.openLink}). Reply with one short sentence confirming the session was created; do not print the URL or mention a button.`}function jg(o,n){let t=ab(o)?.toString()??o;return n.find(i=>i.session.toString()===t)?.session}function j2(o,n){let e=jg(o,n);if(!e)throw new Error(`Invalid ${Fr} input: session must match the URI of a known session (see list_sessions).`);return e}function K2(o,n,e,t){let r=o??{},i=ps(r.prompt,"prompt",Fr),s=Ka(r.title,"title",Fr),a=Ka(r.model,"model",Fr),l=NP(a,e),d=Ka(r.session,"session",Fr),c;if(d!==void 0)c=j2(d,n);else if(t)c=t;else throw new Error(`Invalid ${Fr} input: no session provided and the current session could not be determined.`);return{session:c,prompt:i,...s!==void 0?{title:s}:{},...l!==void 0?{model:l}:{}}}async function G2(o,n,e){let t=await o.listSessions(),r=K2(n,t,o.getModels(),e),i=O(),s=h.parse(Jo(r.session.toString(),i));return await o.createChat(r.session,s,{title:r.title,model:r.model}),await o.startPrompt(r.session,s,r.prompt),{session:r.session.toString(),chat:s.toString(),openLink:ds(r.session,i)}}function J2(o){return`Chat created (${o.openLink}). Reply with one short sentence confirming the chat was created; do not print the URL or mention a button.`}function Y2(o,n){let e=o??{},t=ps(e.message,"message",di),r=ps(e.session,"session",di),i=jg(r,n);if(!i)throw new Error(`Invalid ${di} input: session must match the URI of a known session (see list_sessions).`);let s=lb(r),a=h.parse(s?Jo(i.toString(),s):pe(i.toString()));return{session:i,chat:a,message:t,...s!==void 0?{chatId:s}:{}}}async function Q2(o,n,e){let t=await o.listSessions(),{session:r,chat:i,chatId:s,message:a}=Y2(n,t);if(e&&i.toString()===h.parse(e).toString())throw new Error(`Invalid ${di} input: refusing to send a message to the current chat.`);return await o.startPrompt(r,i,a),X2(ds(r,s))}function X2(o){return`Message sent (${o}). Reply with one short sentence confirming the message was sent; do not print the URL or mention a button.`}var Z2=10,eF=50,tF={summary:{user:160,assistant:140,toolInput:0},digest:{user:300,assistant:800,toolInput:0},full:{user:1e3,assistant:2e3,toolInput:200}};function nF(o,n){let e=o??{},t=ps(e.session,"session",cs),r=jg(t,n);if(!r)throw new Error(`Invalid ${cs} input: session must match the URI of a known session (see list_sessions).`);let i="summary";if(e.detail!==void 0){if(typeof e.detail!="string"||!cb.includes(e.detail))throw new Error(`Invalid ${cs} input: detail must be one of ${cb.join(", ")}.`);i=e.detail}let s=Z2;if(e.transcriptLimit!==void 0){if(typeof e.transcriptLimit!="number"||!Number.isFinite(e.transcriptLimit)||e.transcriptLimit<1)throw new Error(`Invalid ${cs} input: transcriptLimit must be a positive number.`);s=Math.min(Math.floor(e.transcriptLimit),eF)}let a=lb(t);return{session:r,detail:i,transcriptLimit:s,...a!==void 0?{chatId:a}:{}}}function rF(o,n){let e=o.trim();return e.length<=n?{text:e,truncated:!1}:{text:`${e.slice(0,Math.max(0,n-1))}\u2026`,truncated:!0}}function oF(o){return o.filter(n=>n.kind==="toolCall").map(n=>n.toolCall)}function iF(o){return o.filter(n=>n.kind==="markdown").map(n=>n.content).join("").trim()}function sF(o){return o.status==="streaming"?void 0:o.toolInput}function aF(o){switch(o){case"complete":return"complete";case"cancelled":return"cancelled";case"error":return"error";default:return"inProgress"}}function lF(o,n,e,t,r){let i=tF[t],s=!1,a=(m,v)=>{if(v<=0||!m)return;let y=rF(m,v);return s=s||y.truncated,y.text||void 0},l=e.turns.map(m=>({message:m.message,parts:m.responseParts,state:m.state}));e.activeTurn&&l.push({message:e.activeTurn.message,parts:e.activeTurn.responseParts,state:"inProgress"}),l.length>r&&(s=!0);let d=Math.max(0,l.length-r),u=l.slice(d).map((m,v)=>{let y=a(m.message.text,i.user),S=a(iF(m.parts),i.assistant),b=oF(m.parts),I;return t!=="summary"&&b.length>0&&(I=b.map(_=>{if(i.toolInput>0){let T=a(sF(_)??"",i.toolInput);return T!==void 0?{name:_.toolName,input:T}:{name:_.toolName}}return _.toolName})),{turn:d+v+1,state:aF(m.state),...y!==void 0?{user:y}:{},...S!==void 0?{assistant:S}:{},...I?{toolCalls:I}:{}}}),p={session:o.toString(),openLink:ds(o,n),detail:t,transcript:u,hasMoreHistory:e.hasMoreHistory,truncated:s};return JSON.stringify(p)}async function dF(o,n){let e=await o.listSessions(),{session:t,chatId:r,detail:i,transcriptLimit:s}=nF(n,e),a=o.getChatContext(t,r);return a?lF(t,r,a,i,s):JSON.stringify({session:t.toString(),openLink:ds(t,r),detail:i,transcript:[],hasMoreHistory:!1,truncated:!1})}function cF(o,n){let e=n.find(t=>t.session.toString()===o.toString());return JSON.stringify({session:o.toString(),openLink:ds(o),...e?FP(e):{}})}function uF(o){if(o)try{let n=JSON.parse(o);return Array.isArray(n.sessions)?n.sessions.length:void 0}catch{return}}function pF(o,n,e){let r=ps((o??{}).session,"session",us),i=jg(r,n);if(!i)throw new Error(`Invalid ${us} input: session must match the URI of a known session (see list_sessions).`);if(e&&i.toString()===e.toString())throw new Error(`Invalid ${us} input: refusing to delete the current session.`);return i}async function fF(o,n,e){let t=await o.listSessions(),r=pF(n,t,e);return await o.deleteSession(r),`Deleted session ${r.toString()}. Reply with one short sentence confirming the session was deleted.`}function gF(o,n,e){switch(o){case An:{let t,r=e?uF(e.text):void 0;return r===void 0?t=f(2396,null):r===1?t=f(2398,null):t=f(2397,null,r),{displayName:f(2412,null),invocationMessage:f(2405,null),pastTenseMessage:t}}case _o:return{displayName:f(2408,null),invocationMessage:f(2401,null),pastTenseMessage:f(2392,null)};case Fr:return{displayName:f(2407,null),invocationMessage:f(2400,null),pastTenseMessage:f(2391,null)};case di:return{displayName:f(2413,null),invocationMessage:f(2406,null),pastTenseMessage:f(2399,null)};case cs:return{displayName:f(2411,null),invocationMessage:f(2404,null),pastTenseMessage:f(2395,null)};case ub:return{displayName:f(2410,null),invocationMessage:f(2403,null),pastTenseMessage:f(2394,null)};case us:return{displayName:f(2409,null),invocationMessage:f(2402,null),pastTenseMessage:f(2393,null)};default:return}}function HP(o){let n=0,e=0,t=0;return{definitions:M2,requiresConfirmation(i){return w2(i)},getDisplay(i,s,a){return gF(i,s,a)},async execute(i,s,a,l){if(!o)throw new Error(`Session server tool "${a}" cannot run: the group was built without a session accessor.`);switch(a){case An:return B2($2(await o.listSessions(),N2(l)));case ub:return cF(zg(s),await o.listSessions());case _o:{if(n>=kP)throw new Error(`Refusing to create more than ${kP} sessions from server tools in this process.`);let d=await z2(o,l,zg(s));return n++,V2(d)}case Fr:{if(e>=DP)throw new Error(`Refusing to create more than ${DP} chats from server tools in this process.`);let d=await G2(o,l,zg(s));return e++,J2(d)}case di:{if(t>=MP)throw new Error(`Refusing to send more than ${MP} messages from server tools in this process.`);let d=await Q2(o,l,s);return t++,d}case cs:return dF(o,l);case us:return fF(o,l,zg(s));default:throw new Error(`Unknown session server tool: ${a}`)}}}}function pb(o){return[RP,HP(o)]}var mF=pb();function hF(o,n){return o===n||o.endsWith(`__${n}`)}function mr(o,n,e){for(let t of mF)if(t.getDisplay){for(let r of t.definitions)if(hF(o,r.name))return t.getDisplay(r.name,n,e)}}import{Worker as yF}from"worker_threads";var ci=class extends w{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,t,r=BR){let i=this._ensureWorker(),s=this._nextId++;return new Promise((a,l)=>{this._pending.set(s,{resolve:a,reject:l});try{i.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=Lt.asFileUri("vs/platform/agentHost/node/diffWorkerMain.js").fsPath,t=new yF(e,{name:"Diff compute worker"});t.on("message",r=>{let i=this._pending.get(r.id);if(i)if(this._pending.delete(r.id),r.err){let s=new Error(r.err.message);r.err.stack&&(s.stack=r.err.stack),i.reject(s)}else i.resolve(r.res)}),t.on("error",r=>{this._logService.error("[DiffComputeService] Worker error",r);for(let[,i]of this._pending)i.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()}};ci=R([C(0,M)],ci);function $P(o){return o.after?.uri??o.before?.uri}function fb(o,n,e,t,r){let i=e.firstKind!=="create",s=e.lastKind!=="delete";return{...i?{before:{uri:h.file(e.firstFilePath).toString(),content:{uri:ni(o,e.firstToolCallId,e.firstFilePath,"before")}}}:{},...s?{after:{uri:h.file(e.terminalPath).toString(),content:{uri:ni(n,e.lastToolCallId,e.lastFilePath,"after")}}}:{},diff:{added:t,removed:r}}}async function WP(o,n,e,t){if(!t)return gb([{sessionUri:o,db:n}],e);let r,i=!1,s=await n.getFileEditsByTurn(t.changedTurnId);if(s.length===0)return[...t.previousDiffs];let a=new Set(t.previousDiffs.map($P));if(s.some(y=>y.kind==="rename"||a.has(h.file(y.filePath).toString()))?r=await n.getAllFileEdits():(r=s,i=!0),r.length===0)return[];let d=new Map,c=new Map,u=i?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=i?void 0:new Map(t.previousDiffs.map(y=>[$P(y),y])),m=[],v=[];for(let[y,S]of c){if(u&&!u.has(y)){let b=h.file(S.terminalPath).toString(),I=p.get(b);I&&m.push(I);continue}v.push((async()=>{let b;if(S.firstKind==="create")b="";else{let T=await n.readFileEditContent(S.firstToolCallId,S.firstFilePath);b=T?.beforeContent?new TextDecoder().decode(T.beforeContent):""}let I;if(S.lastKind==="delete")I="";else{let T=await n.readFileEditContent(S.lastToolCallId,S.lastFilePath);I=T?.afterContent?new TextDecoder().decode(T.afterContent):""}if(b===I)return;let _=await e.computeDiffCounts(b,I);m.push(fb(o,o,S,_.added,_.removed))})())}return await Promise.allSettled(v),i&&m.push(...t.previousDiffs),m}async function gb(o,n){let e=await Promise.all(o.map(l=>l.db.getAllFileEdits())),t=new Map,r=new Map,i=0;for(let l=0;l<e.length;l++)for(let d of e[l]){i++;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(i===0)return[];let s=[],a=[];for(let l of r.values())a.push((async()=>{let d=o[l.firstSourceIdx],c=o[l.lastSourceIdx],u;if(l.firstKind==="create")u="";else{let v=await d.db.readFileEditContent(l.firstToolCallId,l.firstFilePath);u=v?.beforeContent?new TextDecoder().decode(v.beforeContent):""}let p;if(l.lastKind==="delete")p="";else{let v=await c.db.readFileEditContent(l.lastToolCallId,l.lastFilePath);p=v?.afterContent?new TextDecoder().decode(v.afterContent):""}if(u===p)return;let m=await n.computeDiffCounts(u,p);s.push(fb(d.sessionUri,c.sessionUri,l,m.added,m.removed))})());return await Promise.allSettled(a),s}async function qP(o,n,e,t){let r=await n.getFileEditsByTurn(t);if(r.length===0)return[];let i=new Map,s=new Map;for(let d of r){let c;d.kind==="rename"&&d.originalPath?(c=i.get(d.originalPath)??d.originalPath,i.set(d.filePath,c),i.delete(d.originalPath)):(c=i.get(d.filePath)??d.filePath,i.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(fb(o,o,d,p.added,p.removed))})());return await Promise.allSettled(l),a}var Hc="checkpoint.workingDir",Ga=class extends w{constructor(e,t,r){super();this._sessionDataService=e;this._gitService=t;this._logService=r;this._sequencer=new at;this._register(this._sessionDataService.onWillDeleteSessionData(i=>{i.waitUntil(this.disposeSessionData(i.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 i=await r.object.getMetadata(ss);if(i)return i;let s=this._sanitizedSessionId(e),a=bS(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(ss,a),await r.object.setMetadata(Hc,t.toString()),this._logService.trace(`[AgentHostCheckpoint] Captured baseline for ${e.toString()} at ${a}`),a):void 0}catch(i){this._logService.warn(`[AgentHostCheckpoint] Failed to capture baseline for ${e.toString()}`,i);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[i,s,a,l]=await Promise.all([r.object.getMetadata(ss),r.object.getMetadata(Hc),r.object.getTurnCheckpointRef(t),r.object.getPreviousCheckpointRef(t)]);if(a)return a;if(!i||!s)return;let d=h.parse(s),c=await this._gitService.getRepositoryRoot(d);if(!c)return;let u=l??i,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 v=await this._gitService.revParse(c,`${p}^{tree}`);if(v&&v===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=bS(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(i){this._logService.warn(`[AgentHostCheckpoint] Failed to capture turn checkpoint for ${e.toString()}/${t}`,i);return}finally{r.dispose()}}async getTurnCheckpointPair(e,t){let r=this._sessionDataService.openDatabase(e);try{let[i,s,a]=await Promise.all([r.object.getTurnCheckpointRef(t),r.object.getPreviousCheckpointRef(t),r.object.getMetadata(ss)]);if(!i)return;let l=s??a;return l?{parent:l,current:i}:void 0}finally{r.dispose()}}async getBaselineCheckpointRef(e){let t=this._sessionDataService.openDatabase(e);try{return await t.object.getMetadata(ss)}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,i,s]=await Promise.all([t.object.getMetadata(Hc),t.object.getMetadata(ss),t.object.getAllCheckpointRefs()]);if(!r)return;let a=h.parse(r),l=await this._gitService.getRepositoryRoot(a);if(!l)return;let d=new Set;i&&d.add(i);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 i=await this._gitService.captureWorkingTreeAsTree(e);if(!i)return;let s=await this._gitService.getRepositoryRoot(e);if(!s)return;let a=await this._gitService.commitTree(s,i,t,r);if(a)return{commitOid:a}}async _nextTurnNumber(e){let t=await e.getAllCheckpointRefs(),r=0;for(let i of t){let s=i.lastIndexOf("/"),a=s>=0?i.substring(s+1):i,l=parseInt(a,10);Number.isFinite(l)&&l>r&&(r=l)}return r+1}_sanitizedSessionId(e){return D.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};Ga=R([C(0,rt),C(1,Ye),C(2,M)],Ga);var ui=W("agentHostChangesetSubscriptionService");var Ja=W("agentHostChangesetOperationService");var Ya=W("agentHostReviewService");function $c(o){return`refs/agents/${o}/reviewed`}function Kg(o,n){return n==="branch"?Co(o):bo(o)}function vF(o){return o==="branch"?wa:Cc}function hb(o){if(!o)return;let n=0,e=0;for(let t of o)n+=t.diff?.added??0,e+=t.diff?.removed??0;return{additions:n,deletions:e,files:o.length}}function SF(o){let n=o?.status==="ready"?o.files.map(e=>e.edit):void 0;return hb(n)}function bF(o){return hb(o)}function mb(o,n,e,t){if(o)try{return JSON.parse(o)}catch(r){t.warn(`[AgentHostChangesetService] Failed to parse persisted ${e} diffs for ${n}: ${De(r)}`);return}}var To=class extends w{constructor(e,t,r,i,s,a,l,d,c){super();this._stateManager=e;this._logService=t;this._sessionDataService=r;this._gitService=i;this._checkpointService=s;this._configurationService=a;this._changesetOperationService=l;this._changesetSubscriptions=d;this._reviewService=c;this._diffComputationSequencer=new at;this._debouncedDiffTimers=this._register(new we);this._perTurnDebouncedDiffTimers=this._register(new we);this._activeStaticComputes=new Set;this._pendingMaterialization=new Set;this._diffComputeService=this._register(new ci(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(Co(e)),this._stateManager.registerChangeset(ei(e)),this._stateManager.registerChangeset(bo(e))}restoreStaticChangeset(e,t,r){let i=this._stateManager.registerChangeset(Kg(e,t));this._publishChangesetDiffs(e,i,r)}parsePersistedStaticChangesets(e,t){let r=mb(t.branchRaw,e,"branch",this._logService),i=mb(t.sessionRaw,e,"session",this._logService)??mb(t.legacyRaw,e,"session (legacy)",this._logService);return{branch:r,session:i}}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,is,JSON.stringify(t))}getListMetadataKeys(e){if(!(this._stateManager.getSessionSummary(e)?.changes||this._stateManager.getChangesetState(bo(e))?.status==="ready"))return Ff}computeListEntryChanges(e,t){if(this._stateManager.getSessionState(e))return;let r=t[is];if(r!==void 0)try{return JSON.parse(r)}catch{return}let i=this._stateManager.getChangesetState(Co(e)),s=SF(i);if(s)return this.persistChangesSummary(e,s),s;let a=t[wa],l=t[Ra];if(a===void 0&&l===void 0)return;let d=this.parsePersistedStaticChangesets(e,{branchRaw:a,legacyRaw:l}),c=bF(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 i=this._stateManager.getChangesetState(Kg(e,t));i&&i.files.length>0||this.restoreStaticChangeset(e,t,r)}refreshChangesetCatalog(e){let t=this._stateManager.getSessionState(e);if(t?.lifecycle!=="ready")return;let r=St(t?._meta),i=SR(e,r);this._stateManager.setSessionChangesets(e,i)}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 i=Je(r);switch(i?.kind){case"branch":this.refreshBranchChangeset(e);break;case"session":this.refreshSessionChangeset(e);break;case"uncommitted":this.computeUncommittedChangeset(e);break;case"turn":i.turnId!==void 0&&this.computeTurnChangeset(e,i.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(gf(e,t)),i;try{i=this._sessionDataService.openDatabase(h.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,i.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{i.dispose()}return r}async computeCompareTurnsChangeset(e,t,r){let i=this._stateManager.registerChangeset(vR(e,t,r)),s;try{s=this._sessionDataService.openDatabase(h.parse(e))}catch(a){return this._logService.warn(`[AgentHostChangesetService] Failed to open session database for compare-turns diff: ${e}`,a),this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}}),i}try{let a=h.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(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:`No checkpoint available for ${p}; compare requires git-backed sessions.`}}),i}if(l===d.current)return this._publishChangesetDiffs(e,i,[]),i;let c=await this._resolveWorkingDirectory(s.object);if(!c)return this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:"No working directory recorded for session; compare requires git-backed sessions."}}),i;let u=await this._gitService.computeFileDiffsBetweenRefs(c,{sessionUri:e,fromRef:l,toRef:d.current});if(u===void 0)return this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:`Failed to compute compare-turns diff from git (${l}..${d.current}).`}}),i;this._publishChangesetDiffs(e,i,u)}catch(a){this._logService.warn(`[AgentHostChangesetService] Failed to compute compare-turns diffs for ${e}/${t}/${r}`,a),this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}})}finally{s.dispose()}return i}async computeUncommittedChangeset(e){let t=this._stateManager.registerChangeset(ei(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 i=await this._computeUncommittedDiffs(e);if(i===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,i)}catch(i){this._logService.warn(`[AgentHostChangesetService] Failed to compute uncommitted diffs for ${e}`,i),this._stateManager.dispatchServerAction(t,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:i instanceof Error?i.message:String(i)}})}return t}async _computeUncommittedDiffs(e){let t=this._stateManager.getSessionState(e)?.workingDirectory;if(!t)return;let r;try{r=h.parse(t)}catch{return}return this._gitService.computeSessionFileDiffs(r,{sessionUri:e})}async _computeTurnDiffsPreferCheckpoint(e,t,r){let i=await this._checkpointService.getTurnCheckpointPair(h.parse(e),r);if(i&&i.parent!==i.current){let s=await this._resolveWorkingDirectory(t);if(s){let a=await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:e,fromRef:i.parent,toRef:i.current});if(a)return a}}else if(i&&i.parent===i.current)return[];return qP(e,t,this._diffComputeService,r)}async _resolveWorkingDirectory(e){let t=await e.getMetadata(Hc);return t?h.parse(t):void 0}onToolCallEditsApplied(e,t){this._scheduleDebouncedDiffComputation(e,t),this._hasSubscription(e,gf(e,t))&&this._scheduleDebouncedTurnDiffComputation(e,t)}onTurnComplete(e,t){this._cancelDebouncedDiffComputation(e),t!==void 0&&(this._cancelDebouncedTurnDiffComputation(e,t),this._hasSubscription(e,gf(e,t))&&this._scheduleTurnRecompute(e,t)),this._hasSubscription(e,ei(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,qt(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._scheduleStaticRecompute(e,"branch",t),this._scheduleStaticRecompute(e,"session",t)},To._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_scheduleDebouncedTurnDiffComputation(e,t){let r=`${e}\0${t}`;this._perTurnDebouncedDiffTimers.set(r,qt(()=>{this._perTurnDebouncedDiffTimers.deleteAndDispose(r),this._scheduleTurnRecompute(e,t)},To._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,i){this._diffComputationSequencer.queue(`${e}\0${t}`,()=>this._doComputeStaticChangeset(e,t,r,i))}_markStaticChangesetComputing(e,t){let r=Kg(e,t);this._stateManager.registerChangeset(r);let i=this._stateManager.getChangesetState(r)?.status;return i!=="computing"&&this._stateManager.dispatchServerAction(r,{type:"changeset/statusChanged",status:"computing"}),i}async _doComputeStaticChangeset(e,t,r,i){let s=Kg(e,t);this._activeStaticComputes.add(s);let a=i??this._stateManager.getChangesetState(s)?.status,l;try{l=this._sessionDataService.openDatabase(h.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 gb(p,this._diffComputeService)}else{let p;if(r){let m=this._readPreviousChangesetDiffs(s);m&&(p={changedTurnId:r,previousDiffs:[...m]})}d=await WP(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,vF(t),JSON.stringify(d)),t==="branch"){this._persistSessionFlag(e,Ra,JSON.stringify(d));let u=hb(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,i){let s=this._changesetOperationService.getOperations(e,t),a=[];for(let d of r){let c=d.after?.uri??d.before?.uri;if(c)if(i){let u=so(i.repoRoot,h.parse(c));a.push({id:c,edit:d,reviewed:u?i.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 i of t)if(!Fe(i.resource))try{let s=this._sessionDataService.openDatabase(h.parse(i.resource));r.push({sessionUri:i.resource,ref:s})}catch(s){this._logService.warn(`[AgentHostChangesetService] Failed to open peer chat database for session changes: ${i.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 i,s="";for(let a of r){let d=(Fe(a.resource)?t.turns:this._stateManager.getChatState(a.resource)?.turns)?.at(-1)?.id;d&&a.modifiedAt>=s&&(s=a.modifiedAt,i=d)}return i}async _tryComputeGitDiffs(e,t,r){let i=this._stateManager.getSessionState(e)?.workingDirectory;if(!i)return;let s;try{s=h.parse(i)}catch{return}if(r==="session"){let l=this._latestTurnIdAcrossChats(e);if(!l)return;let d=h.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(Ta),i=St(this._stateManager.getSessionState(e)?._meta)?.baseBranchName;return!r&&i&&this._logService.debug(`[AgentHostChangesetService] Using _meta.git base branch fallback for Branch Changes in ${e}: ${i}`),Uf(r,i)}async _computeReviewedInfo(e,t){let r=this._stateManager.getSessionState(e)?.workingDirectory;if(!r)return;let i;try{i=h.parse(r)}catch{return}let s=await this._gitService.getRepositoryRoot(i);if(!s)return;let a=await this._resolveBranchBaseBranch(e,t),l=await this._reviewService.getReviewedPaths(e,i,a);return{repoRoot:s,paths:l}}_persistSessionFlag(e,t,r){let i=this._sessionDataService.openDatabase(h.parse(e));i.object.setMetadata(t,r).catch(s=>{this._logService.warn(`[AgentHostChangesetService] Failed to persist ${t}`,s)}).finally(()=>{i.dispose()})}};To=R([C(1,M),C(2,rt),C(3,Ye),C(4,Mr),C(5,He),C(6,Ja),C(7,ui),C(8,Ya)],To);var Qa=W("agentHostFileMonitorService"),yb=Object.freeze(["**/.git","**/.git/lfs/**","**/.git/logs/**","**/.git/objects/**","**/.git/subtree-cache/**","**/.git/**/*.lock","**/.git/**/FETCH_HEAD","**/.git/**/fsmonitor--daemon/**","**/*.watchman-cookie-*"]);function CF(o){return[...o].sort()}function IF(o){let n=Object.create(null);for(let e of o)n[e]=!0;return Nr(n)}var Hr=class extends w{constructor(e,t){super();this._fileService=e;this._logService=t;this._entries=this._register(new we);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 i=this._canonicalizeFolder(e),s=CF(r.excludes??yb),a=r.debounceMs??Hr._DEFAULT_DEBOUNCE_MS,l=this._key(i,s,a),d=this._entries.get(l);if(!d){try{d=this._createEntry(l,i,s,a)}catch(c){this._logService.warn(`[AgentHostFileMonitorService] Failed to watch ${i.toString()}`,c);return}this._entries.set(l,d)}return d.callbacks.add(t),N(()=>{let c=this._entries.get(l);c&&(c.callbacks.delete(t),c.callbacks.size===0&&this._entries.deleteAndDispose(l))})}_createEntry(e,t,r,i){let s=new Y;try{let a=s.add(new Dt),l=new Set,d=IF(r);return s.add(this._fileService.watch(t,{recursive:!0,excludes:[...r]})),{folder:t,callbacks:l,debounce:a,debounceMs:i,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=qt(()=>{r.debounce.clear();for(let i of[...r.callbacks])try{i()}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(nt.isEqualOrParent(r,e.folder)&&!this._isExcluded(e,r))return!0;return!1}_isExcluded(e,t){let r=nt.basename(t),i=nt.relativePath(e.folder,t);return i!==void 0&&this._matchesExclude(e,i,r)?!0:this._matchesExclude(e,t.path,r)}_matchesExclude(e,t,r){return typeof e.excludeMatcher(t,r)=="string"}_canonicalizeFolder(e){return nt.removeTrailingPathSeparator(nt.normalizePath(e))}_key(e,t,r){return`${nt.getComparisonKey(e)}\0${r}\0${t.join(`
`)}`}};Hr=R([C(0,Pe),C(1,M)],Hr);var pi="agentHost.git",fi="agentHost.github",Jg={[pi]:!0,[fi]:!0},$r=W("agentHostGitStateService");var vb=class extends Ms{constructor(e,t){super();this._create=e;this._destroy=t}createReferencedObject(e){return this._create(e),e}destroyReferencedObject(e){this._destroy(e)}},Xa=class extends w{constructor(e,t,r,i,s,a){super();this._stateManager=e;this._configurationService=t;this._fileMonitorService=r;this._gitService=i;this._gitStateService=s;this._logService=a;this._watchInterestReferences=this._register(new we);this._watchInterestCollection=new vb(e=>this._attachWatcherIfPossible(e),e=>this._destroyWatchInterest(e));this._pendingWatchInterest=new Set;this._sessionWorkingDirectory=new Map;this._sessionRoot=new Map;this._rootSessions=new Map;this._rootWatchAcquisitions=this._register(new we);this._rootUris=new Map;this._activeSessionRoots=new Map;this._rootActiveSessions=new Map;this._unresolvedActiveSessions=new Set;this._watchAttachmentSequencer=new 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(ei(e)),this.untrackSessionChanges(bo(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(Co(e))||this._watchInterestReferences.has(ei(e))||this._watchInterestReferences.has(bo(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=h.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 i=await this._gitService.getRepositoryRoot(r);if(this._shouldAttachSession(e)){if(!i){this._pendingWatchInterest.delete(e),this._releaseSessionRoot(e);return}this._pendingWatchInterest.delete(e),this._attachSessionToRoot(e,i,t)}})}_attachSessionToRoot(e,t,r){let i=t.toString();if(this._sessionRoot.get(e)===i){this._sessionWorkingDirectory.set(e,r),this._ensureRootWatcher(i,t);return}this._releaseSessionRoot(e);let s=this._rootSessions.get(i);s||(s=new Set,this._rootSessions.set(i,s),this._rootUris.set(i,t)),s.add(e),this._sessionRoot.set(e,i),this._sessionWorkingDirectory.set(e,r),this._ensureRootWatcher(i,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 i=h.parse(e);for(let s of r)this._gitStateService.refreshSessionGitState(s,i)}_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 i=this._fileMonitorService.acquire(t,()=>this._onRootChanged(e),{excludes:yb,debounceMs:750});if(!i){for(let s of r)this._pendingWatchInterest.add(s);return}this._rootWatchAcquisitions.set(e,i)}_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(),i=this._rootActiveSessions.get(r);i||(i=new Set,this._rootActiveSessions.set(r,i)),i.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=h.parse(t)}catch(i){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse active working directory URI for ${e}: ${t}`,i);return}return this._gitService.getRepositoryRoot(r)}_getActivityWorkingDirectory(e){let t=this._configurationService.getEffectiveWorkingDirectory(e);if(t)return t;let r=ut(e);if(r)return this._configurationService.getEffectiveWorkingDirectory(r.parentSession.toString())}};Xa=R([C(1,He),C(2,Qa),C(3,Ye),C(4,$r),C(5,M)],Xa);var Za=class extends w{constructor(e,t,r,i,s,a){super();this._stateManager=e;this._changesetOperationService=t;this._changesets=r;this._changesetSubscriptions=i;this._changesetFileMonitor=this._register(a.createInstance(Xa,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[wa],sessionRaw:t[Cc],legacyRaw:t[Ra]}),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=Je(t);if(!r&&!de(t)&&this._stateManager.getSessionState(t)){this._addSubscription(t,Co(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=Je(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(),i=Je(r);if(i){if(i.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);this._stateManager.getSessionState(i.sessionUri)||await t(h.parse(i.sessionUri))}}async tryHandleSubscribe(e,t){let r=e.toString(),i=Je(r);if(!i)return!1;if(i.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);return await this.restoreSessionIfChangesetSubscription(e,t),i.kind==="turn"&&i.turnId?await this._changesets.computeTurnChangeset(i.sessionUri,i.turnId):i.kind==="compare-turns"&&i.originalTurnId&&i.modifiedTurnId?await this._changesets.computeCompareTurnsChangeset(i.sessionUri,i.originalTurnId,i.modifiedTurnId):this._changesets.registerStaticChangesets(i.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)}};Za=R([C(1,Ja),C(2,xa),C(3,ui),C(4,$r),C(5,xe)],Za);var _F=60,TF=_F*60,Sb=TF*24,Rue=Sb*7,xue=Sb*30,Pue=Sb*365;function BP(o){return o.getFullYear()+"-"+String(o.getMonth()+1).padStart(2,"0")+"-"+String(o.getDate()).padStart(2,"0")+"T"+String(o.getHours()).padStart(2,"0")+":"+String(o.getMinutes()).padStart(2,"0")+":"+String(o.getSeconds()).padStart(2,"0")+"."+(o.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}var Yg={DateTimeFormat(o,n){return new Be(()=>{try{return new Intl.DateTimeFormat(o,n)}catch{return new Intl.DateTimeFormat(void 0,n)}})},Collator(o,n){return new Be(()=>{try{return new Intl.Collator(o,n)}catch{return new Intl.Collator(void 0,n)}})},Segmenter(o,n){return new Be(()=>{try{return new Intl.Segmenter(o,n)}catch{return new Intl.Segmenter(void 0,n)}})},Locale(o,n){return new Be(()=>{try{return new Intl.Locale(o,n)}catch{return new Intl.Locale(Fo,n)}})},NumberFormat(o,n){return new Be(()=>{try{return new Intl.NumberFormat(o,n)}catch{return new Intl.NumberFormat(void 0,n)}})}};var zP=new Be(()=>{let o=Yg.Collator(void 0,{numeric:!0,sensitivity:"base"}).value;return{collator:o,collatorIsNumeric:o.resolvedOptions().numeric}}),Mue=new Be(()=>({collator:Yg.Collator(void 0,{numeric:!0}).value})),Oue=new Be(()=>({collator:Yg.Collator(void 0,{numeric:!0,sensitivity:"accent"}).value}));function wF(o,n,e=!1){let t=o||"",r=n||"",i=zP.value.collator.compare(t,r);return zP.value.collatorIsNumeric&&i===0&&t!==r?t<r?-1:1:i}function Qg(o,n,e){let t=o.toLowerCase(),r=n.toLowerCase(),i=RF(o,n,e);if(i)return i;let s=t.endsWith(e),a=r.endsWith(e);if(s!==a)return s?-1:1;let l=wF(t,r);return l!==0?l:t.localeCompare(r)}function RF(o,n,e){let t=o.toLowerCase(),r=n.toLowerCase(),i=t.startsWith(e),s=r.startsWith(e);if(i!==s)return i?-1:1;if(i&&s){if(t.length<r.length)return-1;if(t.length>r.length)return 1}return 0}var Nue=new Uint32Array(10);var Uue=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),Fue=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),Hue=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]),$ue=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 jP(...o){return function(n,e){for(let t=0,r=o.length;t<r;t++){let i=o[t](n,e);if(i)return i}return null}}var Jue=KP.bind(void 0,!1),Zg=KP.bind(void 0,!0);function KP(o,n,e){if(!e||e.length<n.length)return null;let t;return o?t=$o(e,n):t=e.indexOf(n)===0,t?n.length>0?[{start:0,end:n.length}]:[]:null}function xF(o,n){if(o.length>n.length)return null;let e=n.toLowerCase().indexOf(o.toLowerCase());return e===-1?null:[{start:e,end:e+o.length}]}function PF(o,n){return o.length>n.length?null:bb(o.toLowerCase(),n.toLowerCase(),0,0)}function bb(o,n,e,t){if(e===o.length)return[];if(t===n.length)return null;if(o[e]===n[t]){let r=null;return(r=bb(o,n,e+1,t+1))?JP({start:t,end:t+1},r):null}return bb(o,n,e,t+1)}function Ib(o){return 97<=o&&o<=122}function el(o){return 65<=o&&o<=90}function _b(o){return 48<=o&&o<=57}function AF(o){return o===32||o===9||o===10||o===13}var EF=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(o=>EF.add(o.charCodeAt(0)));function GP(o){return Ib(o)||el(o)||_b(o)}function JP(o,n){return n.length===0?n=[o]:o.end===n[0].start?n[0].start=o.start:n.unshift(o),n}function YP(o,n){for(let e=n;e<o.length;e++){let t=o.charCodeAt(e);if(el(t)||_b(t)||e>0&&!GP(o.charCodeAt(e-1)))return e}return o.length}function Cb(o,n,e,t){if(e===o.length)return[];if(t===n.length)return null;if(o[e]!==n[t].toLowerCase())return null;{let r=null,i=t+1;for(r=Cb(o,n,e+1,t+1);!r&&(i=YP(n,i))<n.length;)r=Cb(o,n,e+1,i),i++;return r===null?null:JP({start:t,end:t+1},r)}}function kF(o){let n=0,e=0,t=0,r=0,i=0;for(let c=0;c<o.length;c++)i=o.charCodeAt(c),el(i)&&n++,Ib(i)&&e++,GP(i)&&t++,_b(i)&&r++;let s=n/o.length,a=e/o.length,l=t/o.length,d=r/o.length;return{upperPercent:s,lowerPercent:a,alphaPercent:l,numericPercent:d}}function DF(o){let{upperPercent:n,lowerPercent:e}=o;return e===0&&n>.6}function MF(o){let{upperPercent:n,lowerPercent:e,alphaPercent:t,numericPercent:r}=o;return e>.2&&n<.8&&t>.6&&r<.2}function OF(o){let n=0,e=0,t=0,r=0;for(let i=0;i<o.length;i++)t=o.charCodeAt(i),el(t)&&n++,Ib(t)&&e++,AF(t)&&r++;return(n===0||e===0)&&r===0?o.length<=30:n<=5}function QP(o,n){if(!n||(n=n.trim(),n.length===0)||!OF(o))return null;n.length>60&&(n=n.substring(0,60));let e=kF(n);if(!MF(e)){if(!DF(e))return null;n=n.toLowerCase()}let t=null,r=0;for(o=o.toLowerCase();r<n.length&&(t=Cb(o,n,0,r))===null;)r=YP(n,r+1);return t}var Yue=jP(Zg,QP,xF),Que=jP(Zg,QP,PF),Xue=new an(1e4);var Xg=128;function Tb(){let o=[],n=[];for(let e=0;e<=Xg;e++)n[e]=0;for(let e=0;e<=Xg;e++)o.push(n.slice(0));return o}function XP(o){let n=[];for(let e=0;e<=o;e++)n[e]=0;return n}var Zue=XP(2*Xg),epe=XP(2*Xg),tpe=Tb(),npe=Tb(),rpe=Tb();var LF;(e=>{e.Default=[-100,0];function n(t){return!t||t.length===2&&t[0]===-100&&t[1]===0}e.isDefault=n})(LF||={});var VP=class{constructor(n,e){this.firstMatchCanBeWeak=n;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};var tm=0,ZP=[tm,[]];function eA(o,n,e,t){if(!o||!n)return ZP;let r=o.length,i=n.length;if(r<i)return ZP;let s=o.toLowerCase();return NF(n,e,i,o,s,r,t)}function NF(o,n,e,t,r,i,s){let a=[],l=[];for(let p=0;p<e;p++){let m=p*i,v=m-i,y=p>0,S=o[p],b=n[p];for(let I=0;I<i;I++){let _=I>0,T=m+I,P=T-1,X=v+I-1,k=_?a[P]:0,x=y&&_?a[X]:0,E=y&&_?l[X]:0,H;!x&&y?H=0:H=UF(S,b,t,r,I,E),H&&x+H>=k&&(s||y||r.startsWith(n,I))?(l[T]=E+1,a[T]=x+H):(l[T]=tm,a[T]=k)}}let d=[],c=e-1,u=i-1;for(;c>=0&&u>=0;){let p=c*i+u;l[p]===tm||(d.push(u),c--),u--}return[a[e*i-1],d.reverse()]}function UF(o,n,e,t,r,i){let s=0;if(!FF(n,t[r]))return s;if(s+=1,i>0&&(s+=Math.min(i,3)*6+Math.max(0,i-3)*3),o===e[r]&&(s+=1),r===0)s+=8;else{let a=HF(e.charCodeAt(r-1));a?s+=a:el(e.charCodeAt(r))&&i===0&&(s+=2)}return s}function FF(o,n){return o===n?!0:o==="/"||o==="\\"?n==="/"||n==="\\":!1}function HF(o){switch(o){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 nm=Object.freeze({score:0}),em=1<<18,wb=1<<17,Rb=65536;function $F(o,n,e,t){let r=t.values?t.values:[t];return gn({[t.normalized]:{values:r.map(s=>({value:s.normalized,expectContiguousMatch:s.expectContiguousMatch})),label:o,description:n,allowNonContiguousMatches:e}})}function rm(o,n,e,t,r){if(!o||!n.normalized)return nm;let i=t.getItemLabel(o);if(!i)return nm;let s=t.getItemDescription(o),a=$F(i,s,e,n),l=r[a];if(l)return l;let d=WF(i,s,t.getItemPath(o),n,e);return r[a]=d,d}function WF(o,n,e,t,r){let i=!e||!t.containsPathSeparator;return e&&(Oe?t.pathNormalized===e:no(t.pathNormalized,e))?{score:em,labelMatch:[{start:0,end:o.length}],descriptionMatch:n?[{start:0,end:n.length}]:void 0}:t.values&&t.values.length>1?qF(o,n,e,t.values,i,r):sA(o,n,e,t,i,r)}function qF(o,n,e,t,r,i){let s=0,a=[],l=[];for(let d of t){let{score:c,labelMatch:u,descriptionMatch:p}=sA(o,n,e,d,r,i);if(c===tm)return nm;s+=c,u&&a.push(...u),p&&l.push(...p)}return{score:s,labelMatch:nA(a),descriptionMatch:nA(l)}}function sA(o,n,e,t,r,i){if(r||!n){let[s,a]=eA(o,t.normalized,t.normalizedLowercase,i&&!t.expectContiguousMatch);if(s){let l=Zg(t.normalized,o),d;if(l){d=wb;let c=Math.round(t.normalized.length/o.length*100);d+=c}else d=Rb;return{score:d+s,labelMatch:l||tA(a)}}}if(n){let s=n;e&&(s=`${n}${Le}`);let a=s.length,l=`${s}${o}`,[d,c]=eA(l,t.normalized,t.normalizedLowercase,i&&!t.expectContiguousMatch);if(d){let u=tA(c),p=[],m=[];return u.forEach(v=>{v.start<a&&v.end>a?(p.push({start:0,end:v.end-a}),m.push({start:v.start,end:a})):v.start>=a?p.push({start:v.start-a,end:v.end-a}):m.push(v)}),{score:d,labelMatch:p,descriptionMatch:m}}}return nm}function tA(o){let n=[];if(!o)return n;let e;for(let t of o)e&&e.end===t?e.end+=1:(e={start:t,end:t+1},n.push(e));return n}function nA(o){let n=o.sort((r,i)=>r.start-i.start),e=[],t;for(let r of n)!t||!BF(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 BF(o,n){return!(o.end<n.start||n.end<o.start)}function aA(o,n,e,t,r,i){let s=rm(o,e,t,r,i),a=rm(n,e,t,r,i),l=s.score,d=a.score;if((l===em||d===em)&&l!==d)return l===em?-1:1;if(l>Rb||d>Rb){if(l!==d)return l>d?-1:1;if(l<wb&&d<wb){let S=zF(s.labelMatch,a.labelMatch);if(S!==0)return S}let v=r.getItemLabel(o)||"",y=r.getItemLabel(n)||"";if(v.length!==y.length)return v.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=rA(o,s,r),m=rA(n,a,r);return p&&m&&p!==m?m>p?-1:1:VF(o,n,e,r)}function rA(o,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 i=e.getItemDescription(o);i&&(r+=i.length)}}else n.descriptionMatch?.length&&(r=n.descriptionMatch[n.descriptionMatch.length-1].end);return r-t}function zF(o,n){if(!o&&!n||!o?.length&&!n?.length)return 0;if(!n?.length)return-1;if(!o?.length)return 1;let e=o[0].start,r=o[o.length-1].end-e,i=n[0].start,a=n[n.length-1].end-i;return r===a?0:a<r?1:-1}function VF(o,n,e,t){let r=t.getItemLabel(o)||"",i=t.getItemLabel(n)||"",s=t.getItemDescription(o),a=t.getItemDescription(n),l=r.length+(s?s.length:0),d=i.length+(a?a.length:0);if(l!==d)return l-d;let c=t.getItemPath(o),u=t.getItemPath(n);return c&&u&&c.length!==u.length?c.length-u.length:r!==i?Qg(r,i,e.normalized):s&&a&&s!==a?Qg(s,a,e.normalized):c&&u&&c!==u?Qg(c,u,e.normalized):0}function oA(o){return o.startsWith('"')&&o.endsWith('"')}var jF=" ";function lA(o){typeof o!="string"&&(o="");let n=o.toLowerCase(),{pathNormalized:e,normalized:t,normalizedLowercase:r}=iA(o),i=e.indexOf(Le)>=0,s=oA(o),a,l=o.split(jF);if(l.length>1)for(let d of l){let c=oA(d),{pathNormalized:u,normalized:p,normalizedLowercase:m}=iA(d);p&&(a||(a=[]),a.push({original:d,originalLowercase:d.toLowerCase(),pathNormalized:u,normalized:p,normalizedLowercase:m,expectContiguousMatch:c}))}return{original:o,originalLowercase:n,pathNormalized:e,normalized:t,normalizedLowercase:r,values:a,containsPathSeparator:i,expectContiguousMatch:s}}function iA(o){let n;Q?n=o.replace(/\//g,Le):n=o.replace(/\\/g,Le);let e=n.replace(/[\*\u2026\s"]/g,"").replace(/(?<=.)#$/,"");return{pathNormalized:n,normalized:e,normalizedLowercase:e.toLowerCase()}}var dA=50;function KF(o,n){if(!(n<0||n>o.length))for(let e=n-1;e>=0;e--){let t=o.charCodeAt(e);if(t===32||t===9||t===10||t===13)return;if(o[e]==="@"||o[e]==="#"){if(e>0){let r=o.charCodeAt(e-1);if(!(r===32||r===9||r===10||r===13))return}return{token:o.slice(e+1,n),triggerChar:o[e],rangeStart:e,rangeEnd:n}}}}var xb=class{constructor(n){this._workingDirectory=n}getItemLabel(n){return ve(n)}getItemDescription(n){let e=so(this._workingDirectory,n);if(!e)return;let t=e.lastIndexOf("/");return t>0?e.slice(0,t):void 0}getItemPath(n){return so(this._workingDirectory,n)??n.fsPath}},om=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=h.parse(t);if(r.scheme!==ne.file)return[];let i=KF(n.text,n.offset);if(!i)return[];let s;try{s=await this._workspaceFiles.getFiles(r,e)}catch(u){if(Cn(u))return[];throw u}if(e.isCancellationRequested||s.length===0)return[];let a=new xb(r),l=lA(i.token),d=Object.create(null),c;if(!l.normalized)c=s.slice(0,dA);else{let u=s.filter(p=>rm(p,l,!0,a,d).score>0);u.sort((p,m)=>aA(p,m,l,!0,a,d)),c=u.slice(0,dA)}return c.map(u=>{let p=ve(u);return{insertText:i.triggerChar+p,rangeStart:i.rangeStart,rangeEnd:i.rangeEnd,attachment:{type:"resource",uri:u.toString(),label:p,displayKind:"document"}}})}};var Wc=class{constructor(n){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n}},gi=class{constructor(n){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n,this.entries=new Map}},tl=class extends w{constructor(){super(...arguments);this.memoryFdCounter=0;this.fdMemory=new Map;this._onDidChangeCapabilities=this._register(new A);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._capabilities=525318;this.root=new gi("");this._onDidChangeFile=this._register(new A);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((i,s)=>r.push([s,i.type])),r}async readFile(e){let t=this._lookupAsFile(e,!1).data;if(t)return t;throw Me("file not found","EntryNotFound")}readFileStream(e){let t=this._lookupAsFile(e,!1).data,r=ao(i=>F.concat(i.map(s=>F.wrap(s))).buffer);return r.end(t),r}async writeFile(e,t,r){let i=ve(e),s=this._lookupParentDirectory(e),a=s.entries.get(i);if(a instanceof gi)throw Me("file is directory","EntryIsADirectory");if(!a&&!r.create)throw Me("file not found","EntryNotFound");if(a&&r.create&&!r.overwrite)throw Me("file exists already","EntryExists");if(a||(a=new Wc(i),s.entries.set(i,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),i=fo(t),s=i&&!!t.append;if(r){if(r instanceof gi)throw Me("file is directory","EntryIsADirectory")}else{if(!i)throw Me("file not found","EntryNotFound");let l=ve(e),d=this._lookupParentDirectory(e);r=new Wc(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:i,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,i,s){let a=this.fdMemory.get(e);if(!a)throw Me("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=F.wrap(a.file.data).slice(t,t+s);return r.set(l.buffer,i),Promise.resolve(l.byteLength)}write(e,t,r,i,s){let a=this.fdMemory.get(e);if(!a)throw Me("No file with that descriptor open","Unavailable");let l=F.wrap(r).slice(i,i+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 Me("file exists already","EntryExists");let i=this._lookup(e,!1),s=this._lookupParentDirectory(e),a=this._lookupParentDirectory(t),l=ve(t);s.entries.delete(i.name),i.name=l,a.entries.set(l,i),this._fireSoon({type:2,resource:e},{type:1,resource:t})}async delete(e,t){let r=Tn(e),i=ve(e),s=this._lookupAsDirectory(r,!1);s.entries.delete(i)&&(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 Me("file exists already","EntryExists");let t=ve(e),r=Tn(e),i=this._lookupAsDirectory(r,!1),s=new gi(t);i.entries.set(s.name,s),i.mtime=Date.now(),i.size+=1,this._fireSoon({type:0,resource:r},{type:1,resource:e})}_lookup(e,t){let r=e.path.split("/"),i=this.root;for(let s of r){if(!s)continue;let a;if(i instanceof gi&&(a=i.entries.get(s)),!a){if(t)return;throw Me("file not found","EntryNotFound")}i=a}return i}_lookupAsDirectory(e,t){let r=this._lookup(e,t);if(r instanceof gi)return r;throw Me("file not a directory","EntryNotADirectory")}_lookupAsFile(e,t){let r=this._lookup(e,t);if(r instanceof Wc)return r;throw Me("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let t=Tn(e);return this._lookupAsDirectory(t,!1)}watch(e,t){return w.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 GF=[];function cA(o,n,e){n instanceof Jn||(n=new Jn(n,[],!!e)),GF.push([o,n])}var uA=W("labelService");var zc="vscode-agent-host",pA="_ah";function fA(o,n){if(n==="local"&&o.scheme===ne.file)return o;let e={scheme:o.scheme,...o.authority?{authority:o.authority}:{},...o.query?{query:o.query}:{}},t=new URLSearchParams;return t.set(pA,or(F.fromString(JSON.stringify(e)),!1,!0)),h.from({scheme:zc,authority:n,path:o.path||"/",query:t.toString(),fragment:o.fragment})}function gA(o){if(o.scheme!==zc)return o;let n,e=o.query?new URLSearchParams(o.query).get(pA):null;if(e)try{n=JSON.parse(pn(e).toString())}catch{n=void 0}return!n||typeof n.scheme!="string"?h.from({scheme:ne.file,path:o.path,fragment:o.fragment}):h.from({scheme:n.scheme,authority:n.authority||void 0,path:o.path,query:n.query||"",fragment:o.fragment})}var mA={scheme:zc,formatting:{label:"${path}",separator:"/"}};var Vc=class o extends w{constructor(e=o._DEFAULT_CONNECTION_GRACE_MS){super();this._connectionGraceMs=e;this.capabilities=263178;this._onDidChangeCapabilities=this._register(new A);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new A);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new A);this.onDidWatchError=this._onDidWatchError.event;this._authorities=new Map;this._onDidChangeConnection=this._register(new A)}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 Dt},this._authorities.set(e,r));let i=r;return this._onDidChangeConnection.fire(e),N(()=>{let s=i.connections.indexOf(t);if(s===-1)return;let a=s===i.connections.length-1;i.connections.splice(s,1),i.connections.length===0&&(i.expiry.value=qt(()=>this._expireAuthority(e,i),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 Y,i=r.add(new Dt),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;i.clear(),l=void 0;let v=m?.watchResource;if(!m||!v)return;d=!0;let y=m;try{let S=await v.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(T=>({resource:this._encodeUri(T.resource,e.authority),type:T.type}))));i.value=N(()=>{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 i=await this._getConnection(e.authority);try{let s=await this._resolve(i,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 i=await this._getConnection(e.authority);try{let s=await this._resolve(i,r);return this._encodeUri(h.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),i=await t.resourceRead(r);return i.encoding==="base64"?pn(i.data).buffer:F.fromString(i.data).buffer}catch(r){throw this._mapError(r,"EntryNotFound")}}async writeFile(e,t,r){let i=await this._getConnection(e.authority);try{let s=this._decodeUri(e);await i.resourceWrite({channel:Ke,uri:s.toString(),data:F.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 i=this._decodeUri(e);await r.resourceDelete({channel:Ke,uri:i.toString(),recursive:t.recursive})}catch(i){throw this._mapError(i,"NoPermissions")}}async rename(e,t,r){let i=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(t);await i.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 i=await this._getConnection(e.authority);try{let s=this._decodeUri(e),a=this._decodeUri(t);await i.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 Me(`Connection for ${e.authority} does not support resourceRequest`,"Unavailable");let i=this._decodeUri(e);try{await r.resourceRequest({channel:Ke,uri:i.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(Me(`No connection for authority: ${e}`,"Unavailable"));let r=t.connections.at(-1);return r?Promise.resolve(r):new Promise((i,s)=>{let a=()=>{let d=this._authorities.get(e);if(!d){l.dispose(),s(Me(`No connection for authority: ${e}`,"Unavailable"));return}let c=d.connections.at(-1);c&&(l.dispose(),i(c))},l=this._onDidChangeConnection.event(d=>{d===e&&a()});a()})}_mapError(e,t){return e instanceof L&&e.code===Se.PermissionDenied?Me(e.message,"NoPermissions"):Me(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 i=this._decodeUri(t);return(await r.resourceList(i)).entries}catch(i){throw this._mapError(i,"Unavailable")}}},im=class extends Vc{_decodeUri(n){return gA(n)}_encodeUri(n,e){return fA(n,e)}};var Kc="vscode-synced-customization",JF=W("agentHostFileSystemService"),jc=class extends w{constructor(e,t){super();this._fileService=e;this._syncedCustomizationProviderRegistered=!1;this._fsProvider=this._register(new im),this._register(e.registerProvider(zc,this._fsProvider)),this._register(t.registerFormatter(mA))}registerAuthority(e,t){return this._fsProvider.registerAuthority(e,t)}ensureSyncedCustomizationProvider(){if(!this._syncedCustomizationProviderRegistered){this._syncedCustomizationProviderRegistered=!0;let e=this._register(new tl);this._register(this._fileService.registerProvider(Kc,e))}}};jc=R([C(0,Pe),C(1,uA)],jc);cA(JF,jc,1);var sm=class extends w{constructor(e){super();this._getAgent=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(e,t){let r=Ig(e.text,e.offset);if(!r)return[];let i=typeof e.channel=="string"?h.parse(e.channel):e.channel,s=this._getAgent(i);if(!s)return[];let a=await this._getCandidates(s,i);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:Bx({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),i=[];for(let s of r)if(!(s.type==="mcpServer"||!s.enabled||!s.children))for(let a of s.children)a.type==="skill"&&i.push(this._toSlashCommandCandidate(s,a));return i}_toSlashCommandCandidate(e,t){let r=t.name;return e.type==="plugin"&&!YF(e)&&t.name!==e.name&&(r=`${e.name}:${t.name}`),{slashCommandName:r,name:t.name,description:t.description,uri:t.uri}}};function YF(o){return o.uri.startsWith(Kc+":")}import*as yA from"child_process";var QF=new Be(async()=>(await import("@vscode/ripgrep-universal")).rgPath.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"));function nl(){return QF.value}var XF=5e4,ZF=3e4,rl=class extends w{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!==ne.file)return[];let r=e.toString(),i=Date.now(),s=this._cache.get(r),a;if(s&&s.expiresAt>i)a=s.promise;else{a=this._enumerate(e);let l={promise:a,expiresAt:i+ZF};this._cache.set(r,l),a.catch(()=>{this._cache.get(r)===l&&this._cache.delete(r)})}if(t.isCancellationRequested)throw new K;return t===Re.None?a:new Promise((l,d)=>{let c=t.onCancellationRequested(()=>{c.dispose(),d(new K)});a.then(u=>{c.dispose(),l(u)},u=>{c.dispose(),d(u)})})}async _enumerate(e){let t=await nl();return new Promise(r=>{let i=e.fsPath,s=["--files","--hidden","--no-require-git","--follow","--no-config","--glob","!.git"],a;try{a=yA.spawn(t,s,{cwd:i})}catch(v){this._logService.warn(`[AgentHostWorkspaceFiles] Failed to spawn ripgrep: ${v}`),r([]);return}this._activeChildren.add(a);let l=[],d="",c=!1,u=!1,p=v=>{u||(u=!0,this._activeChildren.delete(a),r(v))};a.stdout.setEncoding("utf8"),a.stdout.on("data",v=>{if(c)return;d+=v;let y;for(;(y=d.indexOf(`
`))>=0;){let S=d.slice(0,y).replace(/\r$/,"");if(d=d.slice(y+1),!!S&&(l.push(h.joinPath(e,S)),l.length>=XF)){c=!0;try{a.kill()}catch{}break}}}),a.stderr.setEncoding("utf8");let m="";a.stderr.on("data",v=>{m+=v}),a.on("error",v=>{this._logService.warn(`[AgentHostWorkspaceFiles] ripgrep error: ${v}`),p([])}),a.on("close",()=>{if(!c&&d.length>0){let v=d.replace(/\r$/,"");v&&l.push(h.joinPath(e,v)),d=""}m&&this._logService.trace(`[AgentHostWorkspaceFiles] ripgrep stderr: ${m}`),p(l)})})}};rl=R([C(0,M)],rl);var vA={serverTools:{listChanged:!0},serverResources:{},sampling:{}},am={capabilities:vA};var ol=class extends w{constructor(e){super();this._options=e;this._live=rn(this,new Map);this.runtimeStates=Jd(this,t=>{let r=new Map;for(let i of this._live.read(t).values()){let s=i.topLevelId??this._options.resolveChildId(i.serverName);s!==void 0&&r.set(s,{state:i.state,channel:this._buildChannel(i.serverName,i.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)}serverNameForCustomizationId(e){for(let t of this._live.get().values())if((t.topLevelId??this._options.resolveChildId(t.serverName))===e)return t.serverName}stateForServer(e){return this._live.get().get(e)?.state}channelForServer(e){let t=this._live.get().get(e);if(!(!t||t.state.kind!=="ready"))return this._buildChannel(e,t.state)}applyAll(e){ur(t=>{let r=new Set;for(let i of e)r.add(i.name),this._applyOne(i,t);for(let i of[...this._live.get().keys()])r.has(i)||this._remove(i,t)})}applyOne(e){ur(t=>this._applyOne(e,t))}_applyOne(e,t){let r=this._live.get().get(e.name),i=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:i,topLevelId:void 0},t),this._options.emit({type:"session/mcpServerStateChanged",id:a,state:i,channel:this._buildChannel(e.name,i)});return}s=this._mintTopLevelId(e.name)}this._setLiveEntry(e.name,{serverName:e.name,state:i,topLevelId:s},t),this._options.emit({type:"session/customizationUpdated",customization:this._buildTopLevel(s,e.name,i)})}remove(e){ur(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 i=this._options.resolveChildId(e);i!==void 0&&this._options.emit({type:"session/mcpServerStateChanged",id:i,state:{kind:"stopped"}})}_setLiveEntry(e,t,r){let i=new Map(this._live.get());i.set(e,t),this._live.set(i,r)}_deleteLiveEntry(e,t){let r=this._live.get();if(!r.has(e))return;let i=new Map(r);i.delete(e),this._live.set(i,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 i=this._buildChannel(t,r),s=this._options.capabilities?{capabilities:this._options.capabilities}:am;return{type:"mcpServer",id:e,uri:this._mintTopLevelId(t),name:t,enabled:!0,state:r,channel:i,mcpApp:s}}};function lm(o,n){for(let e of o){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 Eb(o,n){for(let e of o){if(e.type==="mcpServer"){if(e.id===n)return e.name;continue}let t=e.children;if(t){for(let r of t)if(r.type==="mcpServer"&&r.id===n)return r.name}}}function SA(o){let n="mcp://";if(!o.startsWith(n))return;let e=o.slice(n.length),t=e.indexOf("/");if(t<=0)return;let r=e.slice(0,t),i=e.slice(t+1),s=i.indexOf("/");if(s<=0||s===i.length-1)return;let a,l;try{a=decodeURIComponent(i.slice(0,s)),l=decodeURIComponent(i.slice(s+1))}catch{return}if(!(!r||!a||!l))return{providerId:r,sessionId:a,serverName:l}}var kb="vscode-agent-client";function il(o,n){let e=o.authority||"-",t=o.path.length>0&&!o.path.startsWith("/"),r=t?`${o.scheme}!`:o.scheme,i=t?`/${o.path}`:o.path;return h.from({scheme:kb,authority:n,path:`/${r}/${e}${i}`,query:o.query||void 0,fragment:o.fragment||void 0})}function bA(o){let n=o.path,e=o.query||void 0,t=o.fragment||void 0,r=n.indexOf("/",1);if(r===-1)return h.from({scheme:"file",path:n,query:e,fragment:t});let i=n.substring(1,r),s=i.endsWith("!");s&&(i=i.substring(0,i.length-1));let a=n.indexOf("/",r+1);if(a===-1){let c=n.substring(r+1);return h.from({scheme:i,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)),h.from({scheme:i,authority:l||void 0,path:d,query:e,fragment:t})}var sl=class extends w{constructor(e,t,r){super();this._stateManager=e;this._gitStateService=t;this._changesetSubscriptions=r;this._handlerRegistrations=this._register(new we);this._changesetOperationHandlers=new Map;this._inFlightOperations=new Map;this._registry={registerChangesetOperationHandler:(i,s)=>this._registerChangesetOperationHandler(i,s),refreshSessionGitState:i=>this._gitStateService.refreshSessionGitState(i),onDidChangeOperations:i=>this.updateOperations(i)}}registerContribution(e){if(this._handlerRegistrations.has(e))throw new Error("Changeset operation contribution already registered");return this._handlerRegistrations.set(e,e.registerHandlers(this._registry)),N(()=>{this._handlerRegistrations.deleteAndDispose(e),e.dispose()})}getOperations(e,t,r,i){if(!r){let a=this._stateManager.getSessionState(e);if(r=St(a?._meta),!r)return[]}i||(i=dr(this._stateManager.getSessionState(e)?._meta));let s=Je(t);return s?this._getOperations({sessionKey:e,changesetUri:t,changesetKind:s.kind,gitState:r,gitHubState:i}):[]}_getOperations(e){let t=[];for(let r of this._handlerRegistrations.keys()){let i=r.getOperations(e);i&&t.push(...i)}return this._stateManager.hasActiveTurn(e.sessionKey)?t.map(r=>({...r,status:"disabled"})):t}updateOperations(e,t,r,i){if(!r){let a=this._stateManager.getSessionState(e);if(r=St(a?._meta),!r)return}if(!i){let a=this._stateManager.getSessionState(e);i=dr(a?._meta)}let s=t?[t]:this._changesetSubscriptions.getSessionSubscriptions(e);for(let a of s){let l=this.getOperations(e,a,r,i);this._stateManager.dispatchServerAction(a,{type:"changeset/operationsChanged",operations:[...l]})}}async invokeChangesetOperation(e){let t=this._stateManager.getChangesetState(e.channel);if(!t)throw new L(_t,`Changeset not found: ${e.channel}`);let r=t.operations?.find(l=>l.id===e.operationId);if(!r)throw new L(ae.InvalidParams,`Unknown operation '${e.operationId}' on changeset ${e.channel}`);if(r.status==="disabled")throw new L(ae.InvalidParams,`Operation '${e.operationId}' is disabled on changeset ${e.channel}`);let i=Je(e.channel);if(i&&this._stateManager.hasActiveTurn(i.sessionUri))throw new L(ae.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 L(ae.InvalidParams,`Operation '${e.operationId}' does not support scope '${s}' (allowed: ${r.scopes.join(", ")})`);let a=this._changesetOperationHandlers.get(e.operationId);if(!a)throw new L(ae.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)}`,i=this._inFlightOperations.get(r);if(i)return i;this._stateManager.dispatchServerAction(t.channel,{type:"changeset/operationStatusChanged",operationId:t.operationId,status:"running"});let s=e.invoke(t,Re.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:e4(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),N(()=>{this._changesetOperationHandlers.get(e)===t&&this._changesetOperationHandlers.delete(e)})}};sl=R([C(1,$r),C(2,ui)],sl);function e4(o){let n=De(o);return o instanceof Error?{errorType:o.name,message:n,stack:o.stack}:{errorType:"Error",message:n}}var ll=W("agentHostOctoKitService"),CA="2022-11-28",IA=500,t4=`mutation EnableAutoMerge($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
	enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
		pullRequest { id }
	}
}`,al=class{constructor(n,e,t){this._logService=e;this._endpoint=t;this.pullRequestSearchEtags=new an(100);this._fetch=n??globalThis.fetch}async createPullRequest(n,e,t,r,i,s,a,l,d){let c=await this._makeGHAPIRequest(`repos/${n}/${e}/pulls`,"POST",l,d,{title:t,body:r,head:i,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,i){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,i,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(t4,{pullRequestId:n,mergeMethod:e},t,r)}async _makeGHAPIRequest(n,e,t,r,i,s){let a=`${this._endpoint.getApiBaseUri()}/${n}`,l={Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":CA};s&&(l["If-None-Match"]=s),i&&(l["Content-Type"]="application/json");let d;try{d=await this._fetch(a,{method:e,headers:l,body:i?JSON.stringify(i):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=n4(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(()=>{}),v=this._formatErrorResponseBody(m);throw this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Status: ${d.status}${v?` - ${v}`:""}`),new Error(`GitHub API request failed: ${e} ${n} - ${d.status} ${d.statusText}${v?` - ${v}`:""}`)}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 i=this._endpoint.getGraphQlUri(),s={Accept:"application/json",Authorization:`Bearer ${t}`,"Content-Type":"application/json","X-GitHub-Api-Version":CA},a;try{a=await this._fetch(i,{method:"POST",headers:s,body:JSON.stringify({query:n,variables:e}),signal:r})}catch(d){throw r.aborted||this._logService.error(`[AgentHostOctoKit] POST ${i} - Network error`,d),d}if(!a.ok){let d=await a.text().catch(()=>{}),c=this._formatErrorResponseBody(d);throw this._logService.error(`[AgentHostOctoKit] POST ${i} - 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 ${i} - 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 ${i} - 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>IA?`${e.substring(0,IA)}...`:e}};al=R([C(1,M),C(2,xt)],al);function n4(o){if(o===void 0)return;let n=Array.isArray(o)?o[0]:o,e=parseInt(n,10);return isNaN(e)?void 0:e}var dl=class extends w{constructor(e,t,r,i,s,a,l){super();this._stateManager=e;this._gitService=t;this._octoKitService=r;this._agentService=i;this._gitHubEndpointService=s;this._logService=a;this._sessionDataService=l;this._onDidRefreshSessionGitState=this._register(new A);this.onDidRefreshSessionGitState=this._onDidRefreshSessionGitState.event;this._gitStateRefreshThrottler=this._register(new lp);this._gitStateRefreshCancellationTokenSource=new Ze;this._register(N(()=>this._gitStateRefreshCancellationTokenSource.dispose(!0)))}async attachSessionGitHubPullRequest(e){let t=this._stateManager.getSessionState(e);if(!t||t.lifecycle!=="ready")return;let r=dr(this._stateManager.getSessionState(e)?._meta);if(!r?.owner||!r?.repo||r?.pullRequestUrl)return;let i=St(t._meta);if(!(!i?.branchName||i.branchName===i.baseBranchName))try{let s=this._gitHubEndpointService.getRepoResource(),a=this._agentService.getAuthToken({resource:s.resource,scopes:s.scopes_supported});if(!a)return;let l=new AbortController().signal,d=await this._octoKitService.findPullRequestByHeadBranch(r.owner,r.repo,i.branchName,a,l);if(!d?.url)return;this.setSessionGitHubState(e,{owner:r.owner,repo:r.repo,pullRequestUrl:d.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 i=r?.workingDirectory;i&&(t=h.parse(i))}t&&await this._gitStateRefreshThrottler.queue(e,async()=>{try{this._logService.trace(`[AgentHostGitStateService][refreshSessionGitState] Refreshing git state for ${e}, ${t?.fsPath}`);let i=await this._gitService.getSessionGitState(t);if(i){let s=this._stateManager.getSessionState(e)?._meta;Ne(St(s),i)||(await this._setSessionGitState(e,i),i.githubOwner&&i.githubRepo&&await this.setSessionGitHubState(e,{owner:i.githubOwner,repo:i.githubRepo}))}this._onDidRefreshSessionGitState.fire(e),await Zt(5e3,this._gitStateRefreshCancellationTokenSource.token)}catch(i){if(Cn(i))return;this._logService.warn(`[AgentHostGitStateService][refreshSessionGitState] Failed to compute git state for ${e}:`,i)}})}}async setSessionGitHubState(e,t){let r=this._stateManager.getSessionState(e)?._meta,i=dr(r),s={...i??{},...t};if(Ne(i,s))return;let a=Dp(r,s);this._stateManager.setSessionMeta(e,a),await this._saveSessionState(e,fi,JSON.stringify(s))}async _setSessionGitState(e,t){let r=this._stateManager.getSessionState(e)?._meta,i=kp(r,t);this._stateManager.setSessionMeta(e,i),await this._saveSessionState(e,pi,JSON.stringify(t))}async _saveSessionState(e,t,r){if(this._stateManager.getSessionState(e)?.lifecycle==="creating")return;let s;try{s=this._sessionDataService.openDatabase(h.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()}}};dl=R([C(1,Ye),C(2,ll),C(3,Pr),C(4,xt),C(5,M),C(6,rt)],dl);var dm=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)),i=await Promise.allSettled(r.map(d=>d.authenticate(n.resource,n.token))),s=!1;for(let d=0;d<i.length;d++){let c=i[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),i;for(let s of this._tokens.values())s.resource!==n.resource||s.scopes.length===0||this._containsAll(s.scopes,r)&&(!i||s.scopes.length<i.scopes.length)&&(i=s);return i?i.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 r4=new Set,cm=class{constructor(){this._subscriptions=new Map}getSessionSubscriptions(n){return this._subscriptions.get(n)??r4}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 o4=2e4,mi=class{constructor(n,e,t,r,i,s,a){this._getSessionState=n;this._onCommitted=e;this._agentService=t;this._gitHubEndpointService=r;this._gitService=i;this._copilotApiService=s;this._logService=a}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=Je(n.channel);if(!r)throw new L(ae.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new L(_t,`Session not found: ${i}`);let a=s.workingDirectory;if(!a)throw new L(ae.InternalError,`Session has no working directory: ${i}`);let l=h.parse(a),d=St(s._meta);if(!d)throw new L(ae.InternalError,`Session's working directory is not a git repo: ${i}`);if(!await this._gitService.hasUncommittedChanges(l))return{message:{markdown:f(2006,null)}};this._throwIfCancelled(e);let u=this._gitHubEndpointService.getCopilotResource(),p=this._agentService.getAuthToken({resource:u.resource,scopes:u.scopes_supported});if(!p)throw new L(cr,f(2001,null),[u]);let m=await this._gitService.computeSessionFileDiffs(l,{sessionUri:i});if(!m||m.length===0)throw new L(ae.InternalError,f(2004,null));this._throwIfCancelled(e);let v;try{v=this._cleanCommitMessage(await this._copilotApiService.utilityChatCompletion(p,{messages:this._buildCommitMessagePrompt(l,d.branchName,m)},{signal:t}))}catch(y){throw this._throwIfCancelled(e),this._isAuthFailure(y)?new L(cr,f(2000,null),[u]):y}if(!v)throw new L(ae.InternalError,f(2005,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostCommitOperationHandler] Committing uncommitted changes for session ${i}`);try{await this._gitService.commitAll(l,v)}catch(y){throw this._throwIfCancelled(e),new L(ae.InternalError,`Failed to commit changes: ${y instanceof Error?y.message:String(y)}`)}try{await this._onCommitted(i)}catch(y){this._logService.warn(`[AgentHostCommitOperationHandler] Post-commit refresh failed for session ${i}: ${y instanceof Error?y.message:String(y)}`)}return{message:{markdown:f(2003,null,v.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: ${ve(n)}`,`Branch: ${e??"unknown"}`,"Changed files:",r].join(`
`)}]}_summarizeDiffsForPrompt(n){let e=[];for(let t of n){let r=t.before?.uri,i=t.after?.uri,s=i??r??"(unknown)",a="Edit";if(!r&&i?a="Create":r&&!i?a="Delete":r&&i&&r!==i&&(a="Rename"),e.push(`- ${a}: ${this._displayUri(s)} (+${t.diff?.added??0} -${t.diff?.removed??0})`),e.join(`
`).length>o4){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=h.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 gr)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 L(ae.InternalError,f(2002,null))}};mi=R([C(2,Pr),C(3,xt),C(4,Ye),C(5,Pt),C(6,M)],mi);var cl=class extends w{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new Y,r=s=>this._stateManager.getSessionState(s),i=this._instantiationService.createInstance(mi,r,s=>this._onCommitted(s));return t.add(e.registerChangesetOperationHandler(mi.OPERATION_COMMIT,i)),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:mi.OPERATION_COMMIT,label:f(2007,null),icon:"git-commit",group:"commit",scopes:["changeset"],status:"idle"}]}async _onCommitted(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};cl=R([C(1,xe)],cl);var Wr=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=Je(n.channel);if(!r||r.kind!=="uncommitted")throw new L(ae.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new L(_t,`Session not found: ${i}`);if(n.target?.kind!=="resource")throw new L(ae.InvalidParams,`Operation '${Wr.OPERATION_DISCARD_CHANGES}' requires a resource target.`);let a=s.workingDirectory;if(!a)throw new L(ae.InternalError,`Session has no working directory: ${i}`);let l=h.parse(a),d=h.parse(n.target.resource);this._logService.info(`[AgentHostDiscardChangesOperationHandler] Restoring '${d.fsPath}' for session ${i}`);try{await this._agentHostGitService.restore(l,[d.fsPath])}catch(c){throw this._throwIfCancelled(e),new L(ae.InternalError,`Failed to discard changes: ${c instanceof Error?c.message:String(c)}`)}return{message:{markdown:f(2009,null,ve(d))}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new L(ae.InternalError,f(2008,null))}};Wr=R([C(1,Ye),C(2,M)],Wr);var ul=class extends w{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){let t=new Y,r=s=>this._stateManager.getSessionState(s),i=this._instantiationService.createInstance(Wr,r);return t.add(e.registerChangesetOperationHandler(Wr.OPERATION_DISCARD_CHANGES,i)),t}getOperations({changesetKind:e,gitState:t}){return e!=="uncommitted"||(t?.uncommittedChanges??0)<=0?[]:[{id:Wr.OPERATION_DISCARD_CHANGES,label:f(2010,null),confirmation:f(2011,null),icon:"discard",scopes:["resource"],status:"idle"}]}};ul=R([C(1,xe)],ul);var i4=12e3,s4=4e3,on=class{constructor(n,e,t,r,i,s,a,l,d,c){this._draft=n;this._autoMergeMethod=e;this._getSessionState=t;this._onPullRequestCreated=r;this._agentService=i;this._gitService=s;this._octoKitService=a;this._gitHubEndpointService=l;this._copilotApiService=d;this._logService=c}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=Je(n.channel);if(!r)throw new L(ae.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new L(_t,`Session not found: ${i}`);let a=s.workingDirectory;if(!a)throw new L(ae.InternalError,`Session has no working directory: ${i}`);let l=dr(s._meta);if(!l?.owner||!l?.repo)throw new L(ae.InternalError,`Session's working directory is not a GitHub-backed git repo: ${i}`);let d=h.parse(a),c=St(s._meta),u=c?.branchName??await this._gitService.getCurrentBranch(d);if(!u)throw new L(ae.InternalError,`Could not determine current branch for ${d}`);let p=c?.baseBranchName??await this._gitService.getDefaultBranch(d);if(!p)throw new L(ae.InternalError,`Could not determine base branch for ${d}`);let m=p.startsWith("origin/")?p.substring(7):p,v=this._gitHubEndpointService.getRepoResource(),y=this._agentService.getAuthToken({resource:v.resource,scopes:v.scopes_supported});if(!y)throw new L(cr,f(2013,null),[v]);if(await this._gitService.hasUncommittedChanges(d)){this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Committing uncommitted changes for session ${i}`);try{await this._gitService.commitAll(d,this._formatCommitMessage(u))}catch(x){throw this._throwIfCancelled(e),new L(ae.InternalError,`Failed to commit changes before creating a pull request: ${x instanceof Error?x.message:String(x)}`)}}this._throwIfCancelled(e);let b=await this._gitService.computeSessionFileDiffs(d,{sessionUri:i,baseBranch:m});if(b===void 0)throw new L(ae.InternalError,f(2021,null));if(b!==void 0&&b.length===0)throw new L(ae.InternalError,f(2029,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Pushing branch ${u} for session ${i}`);let I=await this._gitService.hasUpstream(d,u);this._throwIfCancelled(e);try{await this._gitService.push(d,{ref:u,setUpstream:!I})}catch(x){throw this._throwIfCancelled(e),new L(ae.InternalError,`Failed to push branch '${u}': ${x instanceof Error?x.message:String(x)}`)}this._throwIfCancelled(e);let _=await this._octoKitService.findPullRequestByHeadBranch(l.owner,l.repo,u,y,t);if(_)return this._throwIfCancelled(e),await this._finalize(_,!0,i,l.owner,l.repo,y,t,e);this._throwIfCancelled(e);let T=await this._generateTitleAndDescription(s,u,m,b,t,e);this._throwIfCancelled(e);let P=T?.title??this._formatTitle(u),X=T?.description??this._formatBody(u,m);this._logService.info(`[AgentHostPullRequestOperationHandler] Creating ${this._draft?"draft ":""}PR ${l.owner}/${l.repo} ${u} -> ${m}`);let k;try{k=await this._octoKitService.createPullRequest(l.owner,l.repo,P,X,u,m,this._draft,y,t)}catch(x){this._throwIfCancelled(e);let E;try{E=await this._octoKitService.findPullRequestByHeadBranch(l.owner,l.repo,u,y,t)}catch{throw this._throwIfCancelled(e),x}if(E)return this._throwIfCancelled(e),await this._finalize(E,!0,i,l.owner,l.repo,y,t,e);throw x}return this._throwIfCancelled(e),await this._finalize(k,!1,i,l.owner,l.repo,y,t,e)}async _finalize(n,e,t,r,i,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}/${i}#${n.number}: ${d}`)}else d=f(2015,null),c="failed",this._logService.warn(`[AgentHostPullRequestOperationHandler] Cannot enable auto-merge for ${r}/${i}#${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 i;switch(this._autoMergeMethod){case"SQUASH":i=f(2017,null);break;case"REBASE":i=f(2016,null);break;default:i=f(2014,null);break}if(e)switch(t){case"enabled":return f(2027,null,n.number,n.url,i);case"failed":return f(2028,null,n.number,n.url,r??"");default:return f(2026,null,n.number,n.url)}switch(t){case"enabled":return f(2023,null,n.number,n.url,i);case"failed":return f(2024,null,n.number,n.url,r??"");default:return this._draft?f(2025,null,n.number,n.url):f(2022,null,n.number,n.url)}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new L(ae.InternalError,f(2019,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(2020,null,n)}_formatBody(n,e){return f(2018,null,n,e)}async _generateTitleAndDescription(n,e,t,r,i,s){let a=this._gitHubEndpointService.getCopilotResource(),l=this._agentService.getAuthToken({resource:a.resource,scopes:a.scopes_supported});if(!l)return;let d=Hf(n.turns,{maxChars:i4}),c=this._summarizeDiffsForPrompt(r);if(!(!d&&!c))try{let u=await this._copilotApiService.utilityChatCompletion(l,{messages:this._buildTitleAndDescriptionPrompt(e,t,d,c)},{signal:i});return this._throwIfCancelled(s),this._parseTitleAndDescription(u)}catch(u){if(s.isCancellationRequested)return;this._logService.warn(`[AgentHostPullRequestOperationHandler] Failed to generate PR title and description: ${u instanceof Error?u.message:String(u)}`);return}}_buildTitleAndDescriptionPrompt(n,e,t,r){let i=[`Branch: ${n}`,`Base branch: ${e}`];return r&&i.push(`Changed files:
${r}`),t&&i.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:i.join(`

`)}]}_summarizeDiffsForPrompt(n){let e=[],t=0;for(let r of n){let i=r.before?.uri,s=r.after?.uri,a=s??i??"(unknown)",l="Edit";!i&&s?l="Create":i&&!s?l="Delete":i&&s&&i!==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>s4){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=h.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(`
`),i=0;for(;i<r.length&&r[i].trim().length===0;)i++;if(i>=r.length)return;let s=r[i].trim().replace(/^#+\s*/,"").replace(/^title:\s*/i,"").trim().replace(/^"(?<inner>.+)"$/,(l,d)=>d).trim();if(!s)return;let a=r.slice(i+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}}};on=R([C(4,Pr),C(5,Ye),C(6,ll),C(7,xt),C(8,Pt),C(9,M)],on);var pl=class extends w{constructor(e,t,r){super();this._stateManager=e;this._instantiationService=t;this._gitStateService=r}registerHandlers(e){this._registry=e;let t=new Y,r=u=>this._stateManager.getSessionState(u),i=u=>this._onPullRequestCreated(u),s=this._instantiationService.createInstance(on,!1,void 0,r,i),a=this._instantiationService.createInstance(on,!0,void 0,r,i),l=this._instantiationService.createInstance(on,!1,"MERGE",r,i),d=this._instantiationService.createInstance(on,!1,"SQUASH",r,i),c=this._instantiationService.createInstance(on,!1,"REBASE",r,i);return t.add(e.registerChangesetOperationHandler(on.OPERATION_CREATE_PR,s)),t.add(e.registerChangesetOperationHandler(on.OPERATION_CREATE_DRAFT_PR,a)),t.add(e.registerChangesetOperationHandler(on.OPERATION_CREATE_PR_AUTO_MERGE,l)),t.add(e.registerChangesetOperationHandler(on.OPERATION_CREATE_PR_AUTO_SQUASH,d)),t.add(e.registerChangesetOperationHandler(on.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,i=e?.uncommittedChanges??0,s=r>0||i>0;if(!(!e?.hasGitHubRemote||!s))return[{id:"create-pr",label:f(2031,null),icon:"git-pull-request-create",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-merge",label:f(2032,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-squash",label:f(2034,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-rebase",label:f(2033,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-draft-pr",label:f(2030,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})}};pl=R([C(1,xe),C(2,$r)],pl);var hi=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=Je(n.channel);if(!t)throw new L(ae.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let r=t.sessionUri,i=this._getSessionState(r);if(!i)throw new L(_t,`Session not found: ${r}`);let s=i.workingDirectory;if(!s)throw new L(ae.InternalError,`Session has no working directory: ${r}`);let a=h.parse(s),d=St(i._meta)?.branchName??await this._gitService.getCurrentBranch(a);if(!d)throw new L(ae.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 L(ae.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(2037,null)}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new L(ae.InternalError,f(2036,null))}};hi=R([C(2,Ye),C(3,M)],hi);var fl=class extends w{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new Y,r=s=>this._stateManager.getSessionState(s),i=this._instantiationService.createInstance(hi,r,s=>this._onSynced(s));return t.add(e.registerChangesetOperationHandler(hi.OPERATION_SYNC,i)),t.add({dispose:()=>{this._registry=void 0}}),t}getOperations({gitState:e}){if(!(!e?.upstreamBranchName||(e?.outgoingChanges??0)===0))return[{id:hi.OPERATION_SYNC,label:f(2038,null,e.outgoingChanges),icon:"sync",group:"sync",scopes:["changeset"],status:"idle"}]}async _onSynced(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};fl=R([C(1,xe)],fl);var gl=class extends w{constructor(e,t,r,i){super();this._stateManager=e;this._gitService=t;this._sessionDataService=r;this._logService=i;this._sequencer=new at;this._register(this._sessionDataService.onWillDeleteSessionData(s=>{s.waitUntil(this.disposeSessionData(s.session.toString()))}))}async setReviewState(e,t,r){let i=Je(e);if(!i||i.kind!=="branch")throw new Error(`Not a branch changeset URI: ${e}`);let s=this._stateManager.getSessionState(i.sessionUri);if(!s)throw new Error(`Session not found: ${i.sessionUri}`);if(!s.workingDirectory)throw new Error(`Session has no working directory: ${i.sessionUri}`);let a=this._sessionDataService.openDatabase(h.parse(i.sessionUri)),l;try{l=await a.object.getMetadata(Ta)}finally{a.dispose()}let d=h.parse(s.workingDirectory),c=Uf(l,St(s._meta)?.baseBranchName);await this._sequencer.queue(i.sessionUri,async()=>{for(let u of t)await this._setReviewed(i.sessionUri,d,c,h.parse(u),r)})}markFileReviewed(e,t,r,i){return this._sequencer.queue(e,()=>this._setReviewed(e,t,r,i,!0))}markFileUnreviewed(e,t,r,i){return this._sequencer.queue(e,()=>this._setReviewed(e,t,r,i,!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 i=await this._gitService.getRepositoryRoot(r);if(!i)return;let s=$c(this._sanitizedSessionId(e)),a=await this._gitService.revParse(i,s);if(!a)return;let l=$c(this._sanitizedSessionId(t));await this._gitService.updateRef(i,l,a),this._logService.trace(`[AgentHostReview][_copyReviewedRef] Copied reviewed ref ${s} -> ${l} for fork`)}async _setReviewed(e,t,r,i,s){let a=await this._resolveContext(e,t,r);if(!a)return;let l=so(a.repoRoot,i);if(!l){this._logService.warn(`[AgentHostReview][_setReviewed] '${i.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 i=await this._resolveContext(e,t,r);if(!i?.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(i.repoRoot,i.baselineTree,s),this._gitService.diffTreePaths(i.repoRoot,i.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 i=await this._gitService.getRepositoryRoot(t);if(!i)return;let s=await this._gitService.resolveBranchBaselineCommit(t,r);if(!s)return;let a=s!==os?await this._gitService.revParse(i,`${s}^{tree}`):os;if(!a)return;let l=$c(this._sanitizedSessionId(e)),d=await this._gitService.revParse(i,l),c=d?await this._gitService.revParse(i,`${d}^{tree}`)??a:a;return{repoRoot:i,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(h.parse(t));if(r)try{let i=$c(this._sanitizedSessionId(e));await this._gitService.deleteRefs(r,[i]),this._logService.trace(`[AgentHostReview][_disposeSessionData] Deleted reviewed ref for ${e}`)}catch(i){this._logService.warn(`[AgentHostReview][_disposeSessionData] Failed to dispose reviewed ref for ${e}`,i)}}_sanitizedSessionId(e){return D.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};gl=R([C(1,Ye),C(2,rt),C(3,M)],gl);var a4=3e4,l4=3e4,d4=(()=>{let o=process.env[ZT],n=o!==void 0?parseInt(o,10):NaN;return Number.isFinite(n)&&n>=0?n:3e4})(),Db="peerChats",um="peerChatBacking",pm=class extends w{constructor(e,t,r,i,s,a=ax,l,d=cg,c,u,p){super();this._logService=e;this._fileService=t;this._sessionDataService=r;this._productService=i;this._gitService=s;this._checkpointService=a;this._rootConfigResource=l;this._telemetryService=d;this._onDidAction=this._register(new A);this.onDidAction=this._onDidAction.event;this._onDidNotification=this._register(new A);this.onDidNotification=this._onDidNotification.event;this._onMcpNotification=this._register(new A);this.onMcpNotification=this._onMcpNotification.event;this._providers=new Map;this._sessionToProvider=new Map;this._downloadProgressInterest=new Map;this._providerSubscriptions=this._register(new Y);this._peerChatCatalogWrites=new Map;this._agents=rn("agents",[]);this._skillCompletionProviderRegistered=!1;this._resourceSubscribers=new qe;this._restoreSessionInFlight=new Map;this._restoreSubagentInFlight=new Map;this._pendingSessionGc=this._register(new fd);this._pendingSessionRelease=this._register(new fd);this._resourceWatches=this._register(new we);this._clientDispatchQueues=new Map;this._logService.info("AgentService initialized"),this._authService=new dm(e),this._stateManager=this._register(new _a(e,{hostBuildInfo:GT(this._productService),changesetStateRetention:{canEvict:T=>this._changesets?this._isChangesetEvictable(T):!1}})),this._register(this._stateManager.onDidEmitEnvelope(T=>this._onDidAction.fire(T))),this._register(this._stateManager.onDidEmitNotification(T=>this._onDidNotification.fire(T)));let m=this._register(new ma(this._stateManager,this._logService,this._rootConfigResource));this._configurationService=m;let v=c??this._register(new Hr(this._fileService,this._logService));hg(this._telemetryService,this._stateManager.rootState.config?.values);let y=new Xo([M,this._logService],[Pr,this],[ft,this._productService],[He,m],[Qa,v],[Ye,this._gitService],[zn,this._telemetryService],[rt,this._sessionDataService]),S=this._register(new pa(y,!0));this._gitHubEndpointService=this._register(S.createInstance(za)),y.set(xt,this._gitHubEndpointService),this._register(this._gitHubEndpointService.onDidChange(()=>{this._stateManager.emitAuthRequired({resource:this._gitHubEndpointService.getCopilotResource().resource,reason:"required"})}));let b=S.createInstance(al,p);y.set(ll,b);let I=u??S.createInstance(li,p);y.set(Pt,I),this._gitStateService=this._register(S.createInstance(dl,this._stateManager)),y.set($r,this._gitStateService),y.set(Mr,this._checkpointService),this._changesetSubscriptions=S.createInstance(cm),y.set(ui,this._changesetSubscriptions),this._changesetOperationService=this._register(S.createInstance(sl,this._stateManager)),y.set(Ja,this._changesetOperationService),this._reviewService=this._register(S.createInstance(gl,this._stateManager)),y.set(Ya,this._reviewService),this._changesets=this._register(S.createInstance(To,this._stateManager)),y.set(xa,this._changesets),this._changesetCoordinator=this._register(S.createInstance(Za,this._stateManager)),this._register(this._stateManager.onDidChangeSessionActiveTurn(T=>this._changesetCoordinator.onSessionTurnActiveChanged(T.session,T.active))),this._register(this._changesetOperationService.registerContribution(S.createInstance(cl,this._stateManager))),this._register(this._changesetOperationService.registerContribution(S.createInstance(pl,this._stateManager))),this._register(this._changesetOperationService.registerContribution(S.createInstance(fl,this._stateManager))),this._register(this._changesetOperationService.registerContribution(S.createInstance(ul,this._stateManager))),this._completions=this._register(S.createInstance(Wa));let _=this._register(S.createInstance(rl));this._register(this._completions.registerProvider(new om(this._stateManager,_))),this._register(this._completions.registerProvider(new Tg(T=>(this._stateManager.getSessionState(T)?.turns.length??0)>0))),this._terminalManager=this._register(S.createInstance(va,this._stateManager)),y.set(Dr,this._terminalManager),this._localTurns=new $g(this._sessionDataService,this._logService),this._sideEffects=this._register(S.createInstance(ja,this._stateManager,{getAgent:T=>this._findProviderForSession(T),sessionDataService:this._sessionDataService,localTurns:this._localTurns,agents:this._agents,copilotApiService:I,getGitHubCopilotToken:()=>this.getAuthToken({resource:this._gitHubEndpointService.getCopilotResource().resource,scopes:this._gitHubEndpointService.getCopilotResource().scopes_supported}),onTurnComplete:async T=>{let P=this._stateManager.getSessionState(T)?.workingDirectory;this._gitStateService.refreshSessionGitState(T,P?h.parse(P):void 0),this._gitStateService.attachSessionGitHubPullRequest(T.toString())}})),this._serverToolHost=new Wg(this._stateManager,pb(this._createSessionServerToolAccessor()))}get stateManager(){return this._stateManager}get configurationService(){return this._configurationService}get gitHubEndpointService(){return this._gitHubEndpointService}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 sm(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 i=SA(e);if(!i)throw new Error(`Method not found: invalid mcp:// channel ${e}`);let s=this._providers.get(i.providerId);if(!s||!s.handleMcpRequest)throw new Error(`Method not found: no provider for mcp:// channel ${e}`);let a=D.uri(i.providerId,i.sessionId);return s.handleMcpRequest(a,i.serverName,t,r)}_createSessionServerToolAccessor(){return{listSessions:()=>this.listSessions(),createSession:e=>this.createSession(e),getModels:()=>{let e=[];for(let t of this._providers.values())e.push(...t.models.get());return e},startPrompt:(e,t,r)=>this._startSessionPrompt(e,t,r),createChat:(e,t,r)=>this.createChat(e,t,r?.title!==void 0||r?.model!==void 0?{...r.title!==void 0?{title:r.title}:{},...r.model!==void 0?{model:{id:r.model.id}}:{}}:void 0),deleteSession:e=>this.disposeSession(e),getChatContext:(e,t)=>this._getChatContext(e,t),getSessionSpawnDepth:e=>jT(this._stateManager.getSessionSummary(e.toString())?._meta),setSessionSpawnDepth:(e,t)=>this._stateManager.dispatchServerAction(e.toString(),{type:"session/metaChanged",_meta:KT(this._stateManager.getSessionSummary(e.toString())?._meta,t)})}}async _startSessionPrompt(e,t,r){let i={text:r,origin:{kind:"user"}},s={type:"chat/turnStarted",turnId:O(),message:i};this._stateManager.dispatchServerAction(t.toString(),s),this._sideEffects.handleAction(t.toString(),s)}_getChatContext(e,t){let r=t?this._stateManager.getChatState(Jo(e.toString(),t)):this._stateManager.getDefaultChatState(e.toString());if(r)return{turns:r.turns,...r.activeTurn?{activeTurn:{message:r.activeTurn.message,responseParts:r.activeTurn.responseParts}}:{},hasMoreHistory:!!r.turnsNextCursor}}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),v=m?{customTitle:!0,isRead:!0,[qn]:!0,[xr]:!0,[Wn]:!0,[um]:!0,...Jg,...m}:{customTitle:!0,isRead:!0,[qn]:!0,[xr]:!0,[Wn]:!0,[um]:!0,...Jg},y=await u.object.getMetadataObject(v);if(y[um])return;let S=c;if(y.customTitle&&(S={...S,summary:y.customTitle}),y.isRead!==void 0&&(S={...S,isRead:y.isRead==="true"}),y[qn]!==void 0?S={...S,isArchived:y[qn]==="true"}:y[xr]!==void 0&&(S={...S,isArchived:y[xr]==="true"}),y[pi])try{let b=JSON.parse(y[pi]);S={...S,_meta:kp(S._meta,b)}}catch(b){this._logService.warn(`[AgentService][listSessions] Failed to parse Git state for ${c.session}`,b)}if(y[fi])try{let b=JSON.parse(y[fi]);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[Wn]!==void 0&&(S={...S,_meta:Mp(S._meta,y[Wn]==="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:h.parse(u.project.uri),displayName:u.project.displayName}:c.project,workingDirectory:typeof u.workingDirectory=="string"?h.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)||lr(c.resource)||l.push({session:h.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"?h.parse(c.workingDirectory):void 0,...c.project?{project:{uri:h.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,O());let p=this._localTurns.resolveConcreteTurnId(pe(e.fork.session).toString(),e.fork.turnId);e={...e,fork:{...e.fork,turnIdMapping:u,...p!==void 0?{turnId:p}:{}}}}}if(e?.importConversation){let d=e.importConversation.turns.map(c=>({...c,id:O()}));e={...e,importConversation:{...e.importConversation,turns:d}}}this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,i]=await Promise.all([this._sideEffects.initialize(),this._createSession(r,e)]),s=i.session;if(this._logService.trace("[AgentService] createSession: initialization complete"),this._cancelPendingSessionGc(s),this._cancelPendingSessionRelease(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=pe(e.fork.session).toString(),u=pe(s).toString(),p=[];if(d&&e.fork.turnIdMapping){let I=d.turns.slice(0,e.fork.turnIndex+1),_=e.fork.turnIdMapping;p=I.map(T=>({...T,id:_.get(T.id)??O()})),this._persistForkedLocalTurns(s.toString(),c,u,I,p,_)}let m=f(2042,null),v=d?.title,y=v?v.startsWith(m)?v:`${m}${v}`:f(2041,null),S=this._buildInitialSummary(r,s,e,i,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,v)}else if(e?.importConversation){let d=[...e.importConversation.turns],c=this._buildImportedTitle(d),u=this._buildInitialSummary(r,s,e,i,c),p=this._stateManager.createSession(u);p.config=a,this._stateManager.seedDefaultChatTurns(u.resource,d),p.activeClients=e.activeClient?[e.activeClient]:[],l&&l.length>0&&(p.customizations=[...l]),d.length>0&&this._sideEffects.generateForkedTitle(u.resource,void 0,d,c)}else{let d=this._buildInitialSummary(r,s,e,i,""),c=this._stateManager.createSession(d,{emitNotification:!i.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&&!i.provisional&&this._persistConfigValues(s,a.values),this._changesetCoordinator.onSessionCreated(s.toString()),!i.provisional){this._persistWorkspaceless(s,pv(this._stateManager.getSessionSummary(s.toString())?._meta)),this._stateManager.dispatchServerAction(s.toString(),{type:"session/ready"});let d=i.workingDirectory??e?.workingDirectory;this._gitStateService.refreshSessionGitState(s.toString(),d)}return s}async createChat(e,t,r){let i=e.toString(),s=this._findProviderForSession(e);if(!s)throw new Error(`[AgentService] createChat: no provider for session ${i}`);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(),v=this._stateManager.getChatState(m),y=v??this._stateManager.getDefaultChatState(m),S=v?m:pe(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),T=new Map;for(let k of _)T.set(k.id,O());a=_.map(k=>({...k,id:T.get(k.id)??O()})),this._persistForkedLocalTurns(i,S,t.toString(),_,a,T);let P=f(2042,null);d=y?.title||this._stateManager.getSessionState(i)?.title,l=d?d.startsWith(P)?d:`${P}${d}`:f(2040,null);let X=this._localTurns.resolveConcreteTurnId(S,r.fork.turnId);c={...r,fork:{...r.fork,turnIdMapping:T,...X!==void 0?{turnId:X}:{}}}}}let u=await this._createChat(s,t,c),p=u?.providerData;this._stateManager.addChat(i,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(i,t.toString(),a,l,d)}async disposeChat(e,t){let r=e.toString(),i=this._findProviderForSession(e);this._stateManager.removeChat(r,t.toString()),this._removePersistedPeerChat(e,t),i&&await this._disposeChat(i,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 i=await this._localTurns.loadForChat(e,t);if(i.length===0)return[...r];let s=new Set(r.map(c=>c.id)),a=new Map,l=[];for(let c of i){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,i,s,a){for(let l=0;l<i.length;l++){let d=i[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 i=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,i):e.chats.createChat(t,i)}async _disposeChat(e,t){await e.chats.disposeChat(t)}_buildImportedTitle(e){let t=e.find(i=>i.message?.text?.trim())?.message.text.trim();if(!t)return f(2043,null);let r=60;return t.length>r?`${t.slice(0,r)}...`:t}_buildInitialSummary(e,t,r,i,s){let a=new Date().toISOString();return{resource:t.toString(),provider:e.id,title:s,status:1,createdAt:a,modifiedAt:a,...i.project?{project:{uri:i.project.uri.toString(),displayName:i.project.displayName}}:{},workingDirectory:(i.workingDirectory??r?.workingDirectory)?.toString(),...r&&!r.fork&&!r.workingDirectory?{_meta:Mp(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 i=this._stateManager.getSessionSummary(t);if(!i){this._logService.warn(`[AgentService] onDidMaterializeSession missing summary for session: ${t}`);return}let s={...i,...e.project?{project:{uri:e.project.uri.toString(),displayName:e.project.displayName}}:{},workingDirectory:e.workingDirectory?.toString()??i.workingDirectory,modifiedAt:new Date().toISOString()},a=r.config?.values;a&&Object.keys(a).length>0&&this._persistConfigValues(e.session,a),this._persistWorkspaceless(e.session,pv(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,i,s){let a=this._downloadProgressInterest.get(e);if(!a||a.size===0)return;let l=s?r:i,d=f(2039,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(i){this._logService.warn(`[AgentService] Failed to open session database to persist workspaceless for ${e.toString()}: ${De(i)}`);return}r.object.setMetadata(Wn,t?"true":"false").catch(i=>{this._logService.warn(`[AgentService] Failed to persist workspaceless for ${e.toString()}: ${De(i)}`)}).finally(()=>{r.dispose()})}_persistConfigValues(e,t){let r;try{r=this._sessionDataService.openDatabase(e)}catch(i){this._logService.warn(`[AgentService] Failed to open session database to persist configValues for ${e.toString()}: ${De(i)}`);return}r.object.setMetadata("configValues",JSON.stringify(t)).catch(i=>{this._logService.warn(`[AgentService] Failed to persist configValues for ${e.toString()}: ${De(i)}`)}).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 i=this._terminalManager.getTerminalState(r);if(i)return{resource:r,state:i,fromSeq:this._stateManager.serverSeq};let s=this._stateManager.getSnapshot(r),a=Je(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=oa(r);if(d!==void 0){if(!this._stateManager.getSessionState(d)){let c=h.parse(d),u=ut(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=ut(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(!de(r)&&l&&St(l._meta)===void 0){let d=l.workingDirectory?h.parse(l.workingDirectory):void 0;this._gitStateService.refreshSessionGitState(r,d)}return s}catch(i){throw this.unsubscribe(e,t),i}}addSubscriber(e,t){let r=this._resourceSubscribers.get(e),i=!r||r.size===0;r||(r=new Set,this._resourceSubscribers.set(e,r)),r.add(t),this._cancelPendingSessionGc(e),this._cancelPendingSessionRelease(e),i&&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._pendingSessionRelease.set(e,qt(()=>{this._pendingSessionRelease.deleteAndDispose(e),this._maybeEvictIdleSession(e)},d4))))}_cancelPendingSessionRelease(e){this._pendingSessionRelease.deleteAndDispose(e)}_maybeScheduleSessionGc(e){if(ut(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,qt(()=>{this._pendingSessionGc.deleteAndDispose(e),this._runSessionGc(e).catch(i=>{this._logService.error(i,`[AgentService] GC failed for ${t}`)})},a4)),!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){let t=e.toString();if(this._resourceSubscribers.has(e))return;let r=e;{let d;for(;d=ut(r);)r=d.parentSession}if(this._resourceSubscribers.has(r))return;for(let d of this._resourceSubscribers.keys())if(this._isSubagentDescendantOf(d,r))return;let i=r.toString();if(this._restoreSessionInFlight.has(i))return;let s=this._stateManager.getSessionState(i);if(!s||s.activeTurn!==void 0)return;this._logService.info(`[AgentService] Evicting idle session: ${i} (triggered by unsubscribe of ${t})`);let a=HT(r);for(let d of this._stateManager.getSessionUrisWithPrefix(a))this._stateManager.removeSession(d);this._stateManager.removeSession(i),this._findProviderForSession(r)?.releaseSession?.(r).catch(d=>{this._logService.error(d,`[AgentService] Failed to release idle session ${i}`)})}_isChangesetEvictable(e){let t=h.parse(e);if(this._resourceSubscribers.has(t))return!1;let r=Je(e);if(!r)return!1;let i=h.parse(r.sessionUri);if(this._resourceSubscribers.has(i))return!1;for(let s of this._resourceSubscribers.keys())if(this._isSubagentDescendantOf(s,i))return!1;return!this._changesets.isStaticChangesetComputeActive(e)}_isSubagentDescendantOf(e,t){let r=ut(e);for(;r;){if(Tr(r.parentSession,t))return!0;r=ut(r.parentSession)}return!1}dispatchAction(e,t,r,i){this._logService.trace(`[AgentService] dispatchAction: type=${t.type}, clientId=${r}, clientSeq=${i}`,t);let s=de(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,i);return}let d=(l??Promise.resolve()).then(async()=>{let c=this._needsAsyncRewrite(a,t)?await this._rewriteUserMessageAttachments(a,t,r):t;if(c.type==="changeset/filesReviewChanged"){await this._reviewService.setReviewState(e,c.files,c.reviewed);let u=Je(e);if(!u)throw new Error(`Invalid changeset URI: ${e}`);this._changesets.refreshBranchChangeset(u.sessionUri)}this._dispatchActionNow(e,a,c,r,i)}).catch(c=>{this._logService.error(`[AgentService] async dispatchAction failed: ${De(c)}`)});this._clientDispatchQueues.set(r,d.finally(()=>{this._clientDispatchQueues.get(r)===d&&this._clientDispatchQueues.delete(r)}))}_dispatchActionNow(e,t,r,i,s){let a={clientId:i,clientSeq:s};this._stateManager.dispatchClientAction(e,r,a),r.type==="root/configChanged"&&this._configurationService.persistRootConfig(),this._sideEffects.handleAction(e,r,i)}_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(i=>this._isRewritableAttachment(i,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(h.parse(e)),uf)}async _rewriteUserMessageAttachments(e,t,r){let i=t.message.attachments;if(!i?.length)return t;let s=this._attachmentsRoot(e),a=s.toString(),l=await Promise.all(i.map(d=>this._rewriteSingleAttachment(d,s,a,r)));return{...t,message:{...t.message,attachments:l}}}async _rewriteSingleAttachment(e,t,r,i){try{if(e.type==="embeddedResource"){let s=pn(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=h.parse(e.uri);if(s.scheme===ne.file&&await this._fileExistsSafe(s))return e;let a=await this._readClientResource(s,i),l=this._attachmentBasename(e.label,$p(s.path));return this._writeAndRewrite(e,a,l,t)}}catch(s){this._logService.warn(`[AgentService] Failed to rewrite attachment '${e.label}': ${De(s)}`)}return e}async _fileExistsSafe(e){try{return await this._fileService.exists(e)}catch{return!1}}async _readClientResource(e,t){let r=t?il(e,t):e;try{return(await this._fileService.readFile(r)).value.buffer}catch(i){if(r!==e)try{return(await this._fileService.readFile(e)).value.buffer}catch{}throw i}}async _writeAndRewrite(e,t,r,i){let s=O(),a=te(i,s,r);await this._fileService.writeFile(a,F.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(bd(h.file(r)))return r;let i=t?Tw(t):void 0;return i?`${r}${i}`:r}async resourceList(e){let t;try{t=await this._fileService.resolve(e)}catch{throw new L(Se.NotFound,`Directory not found: ${e.toString()}`)}if(!t.isDirectory)throw new L(Se.NotFound,`Not a directory: ${e.toString()}`);return{entries:(t.children??[]).map(i=>({name:i.name,type:i.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 i=this._doRestoreSession(e,t);this._restoreSessionInFlight.set(t,i);try{await i}finally{this._restoreSessionInFlight.get(t)===i&&this._restoreSessionInFlight.delete(t)}}async _doRestoreSession(e,t){if(this._stateManager.getSessionState(t))return;let r=this._findProviderForSession(e);if(!r)throw new L(_t,`No agent for session: ${t}`);let i=await this._getSessionMetadataForRestore(r,e);if(!i)throw new L(_t,`Session not found on backend: ${t}`);let s=h.parse(pe(t)),a;try{a=await this._getChatMessages(r,s)}catch(E){if(E instanceof L)throw E;let H=E instanceof Error?E.message:String(E);throw new L(zi,`Failed to restore session ${t}: ${H}`)}let l=i.summary??"Session",d,c,u,p,m,v,y,S=this._sessionDataService.tryOpenDatabase?.(e);if(S)try{let E=await S;if(E)try{let H=await E.object.getMetadataObject({customTitle:!0,isRead:!0,[qn]:!0,[xr]:!0,configValues:!0,[Wn]:!0,...Jg,...Ff});if(H.customTitle&&(l=H.customTitle),H.isRead!==void 0&&(d=H.isRead==="true"),H[qn]!==void 0?c=H[qn]==="true":H[xr]!==void 0&&(c=H[xr]==="true"),v=H,v[is])try{p=JSON.parse(v[is])}catch(G){this._logService.warn(`[AgentService] Failed to parse changes summary for ${t}: ${De(G)}`)}if(m=H,m[pi])try{let G=JSON.parse(m[pi]);y={[Md]:G}}catch(G){this._logService.warn(`[AgentService] Failed to parse Git state for ${t}: ${De(G)}`)}if(m[fi])try{let G=JSON.parse(m[fi]);y={...y||{},[Od]:G}}catch(G){this._logService.warn(`[AgentService] Failed to parse GitHub state for ${t}: ${De(G)}`)}if(H[Wn]!==void 0&&(y=Mp(y,H[Wn]==="true")),H.configValues)try{u=JSON.parse(H.configValues)}catch(G){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${t}: ${De(G)}`)}}finally{E.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(i.startTime).toISOString(),modifiedAt:new Date(i.modifiedTime).toISOString(),...i.project?{project:{uri:i.project.uri.toString(),displayName:i.project.displayName}}:{},changes:i.changes??p,workingDirectory:i.workingDirectory?.toString(),_meta:y||i._meta?{...i._meta??{},...y??{}}:void 0},[_,T]=await Promise.all([this._getChatDraft(e,s),this._readPersistedChatTitle(e,s)]),P=await this._interleaveLocalTurns(t,s.toString(),a);this._stateManager.restoreSession(I,P,{draft:_,defaultChatTitle:T});let X=[];X.push((async()=>{if(r.getSubagentSessions)try{let E=await r.getSubagentSessions(e);for(let H of E)this._registerRestoredSubagent(H,I,t)}catch(E){this._logService.warn(`[AgentService] restoreSession failed to eagerly register subagents session=${t}`,E)}})()),X.push(this._restorePeerChats(r,e)),this._changesetCoordinator.onSessionRestored(t,v??{}),i._meta&&this._stateManager.setSessionMeta(t,i._meta);let[k,x]=await Promise.all([this._resolveCreatedSessionConfig(r,{workingDirectory:i.workingDirectory,config:u}),r.getSessionCustomizations?r.getSessionCustomizations(e).catch(E=>{this._logService.error("[AgentService] restoreSession: failed to resolve session customizations",E)}):Promise.resolve(void 0),...X]);k&&this._stateManager.setSessionConfig(t,k),x&&x.length>0&&this._stateManager.setSessionCustomizations(t,x),this._logService.info(`[AgentService] Restored session ${t} with ${a.length} turns`),this._gitStateService.refreshSessionGitState(t,i.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 i=r.map(s=>({uri:s.uri.toString(),...s.providerData!==void 0?{providerData:s.providerData}:{}}));await this._restorePeerChatsFromCatalog(e,t,i),await this._enqueuePeerChatCatalogWrite(t,()=>[...i])}async _restorePeerChatsFromCatalog(e,t,r){let i=await Promise.all(r.map(async s=>{let a;try{a=h.parse(s.uri)}catch(p){this._logService.warn(`[AgentService] Skipping malformed persisted peer chat URI '${s.uri}': ${De(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}: ${De(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()}: ${De(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 i){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=oa(e.chat);if(t===void 0){this._logService.warn(`[AgentService] onDidChangeChatData for malformed chat URI: ${e.chat.toString()}`);return}this._persistPeerChat(h.parse(t),e.chat,e.providerData)}_sequenceSpawnedChat(e){let t=Bi.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(Db);if(r===void 0)return;let i=JSON.parse(r);if(!Array.isArray(i)){this._logService.warn(`[AgentService] Ignoring malformed peer-chat catalog for ${e.toString()}`);return}return i.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()}: ${De(r)}`);return}finally{t.dispose()}}_markPeerChatBacking(e,t){let r;try{r=this._sessionDataService.openDatabase(e)}catch(i){this._logService.warn(`[AgentService] Failed to open backing session database to mark peer-chat backing for ${e.toString()}: ${De(i)}`);return}r.object.setMetadata(um,t.toString()).catch(i=>{this._logService.warn(`[AgentService] Failed to mark peer-chat backing for ${e.toString()}: ${De(i)}`)}).finally(()=>{r.dispose()})}_persistPeerChat(e,t,r){let i=t.toString();return this._enqueuePeerChatCatalogWrite(e,s=>{let a=s.filter(l=>l.uri!==i);return a.push({uri:i,...r!==void 0?{providerData:r}:{}}),a})}_removePersistedPeerChat(e,t){let r=t.toString();return this._enqueuePeerChatCatalogWrite(e,i=>i.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 i=[];try{let a=await r.object.getMetadata(Db);if(a!==void 0){let l=JSON.parse(a);Array.isArray(l)&&(i=l.filter(d=>typeof d?.uri=="string"))}}catch(a){this._logService.warn(`[AgentService] Replacing malformed peer-chat catalog for ${e.toString()}: ${De(a)}`)}let s=t(i);await r.object.setMetadata(Db,JSON.stringify(s))}catch(i){this._logService.warn(`[AgentService] Failed to persist peer-chat catalog for ${e.toString()}: ${De(i)}`)}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(i){if(i instanceof L)throw i;try{return await this._getSessionMetadataFromCatalog(e,t)}catch(s){if(s instanceof L){let a=i instanceof Error?i.message:String(i);throw new L(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(),i;try{i=await e.listSessions()}catch(s){if(s instanceof L)throw s;let a=s instanceof Error?s.message:String(s);throw new L(zi,`Failed to list sessions for ${r}: ${a}`)}return i.find(s=>s.session.toString()===r)}async resourceRead(e){let t=YR(e.toString());if(t)return this._fetchSessionDbContent(t);let r=XR(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(i){let s=i instanceof Error?i:new Error(String(i)),a=ho(s);throw a===1?new L(Se.NotFound,`Content not found: ${e.toString()}`):a===6?new L(Se.PermissionDenied,`Permission denied: ${e.toString()}`):new L(zi,`Failed to read content: ${e.toString()}: ${De(s)}`)}}async resourceWrite(e){let t=typeof e.uri=="string"?h.parse(e.uri):h.revive(e.uri),r;e.encoding==="base64"?r=pn(e.data):r=F.fromString(e.data);let i=e.mode??"truncate",s=e.position??0;try{return e.ifMatch!==void 0||i!=="truncate"||s!==0?await this._resourceWriteWithMode(t,r,i,s,e):e.createOnly?await this._fileService.createFile(t,r,{overwrite:!1}):await this._fileService.writeFile(t,r),{}}catch(a){if(a instanceof L)throw a;if(a instanceof lt&&a.fileOperationResult===3)throw new L(Se.Conflict,`ifMatch precondition failed for: ${t.toString()}`);let l=fn(a);throw l==="EntryExists"?new L(Se.AlreadyExists,`File already exists: ${t.toString()}`):l==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Failed to write file: ${t.toString()}`)}}async _resourceWriteWithMode(e,t,r,i,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 L(Se.Conflict,`ifMatch precondition failed for: ${e.toString()}`);let d=a??F.alloc(0),c;switch(r){case"append":{let u=d.byteLength,p=Math.max(0,u-i);c=F.concat([d.slice(0,p),t,d.slice(p,u)]);break}case"insert":{let u=Math.min(i,d.byteLength);c=F.concat([d.slice(0,u),t,d.slice(u,d.byteLength)]);break}case"truncate":default:{let u=Math.min(i,d.byteLength);c=F.concat([d.slice(0,u),t]);break}}await this._fileService.writeFile(e,c,{etag:l})}async resourceCopy(e){let t=h.parse(e.source),r=h.parse(e.destination);try{return await this._fileService.copy(t,r,!e.failIfExists),{}}catch(i){let s=fn(i);throw s==="EntryExists"?new L(Se.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Source not found: ${t.toString()}`)}}async resourceDelete(e){let t=h.parse(e.uri);try{return await this._fileService.del(t,{recursive:e.recursive}),{}}catch(r){throw fn(r)==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMove(e){let t=h.parse(e.source),r=h.parse(e.destination);try{return await this._fileService.move(t,r,!e.failIfExists),{}}catch(i){let s=fn(i);throw s==="EntryExists"?new L(Se.AlreadyExists,`Destination already exists: ${r.toString()}`):s==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Source not found: ${t.toString()}`)}}async resourceResolve(e){let t=typeof e.uri=="string"?h.parse(e.uri):h.revive(e.uri);try{let r=await this._fileService.stat(t),i;return r.isSymbolicLink&&e.followSymlinks===!1?i="symlink":r.isDirectory?i="directory":i="file",{uri:t.toString(),type:i,...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 L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMkdir(e){let t=typeof e.uri=="string"?h.parse(e.uri):h.revive(e.uri);try{let r=await this._fileService.stat(t).catch(()=>{});if(r&&!r.isDirectory)throw new L(Se.AlreadyExists,`Path exists and is not a directory: ${t.toString()}`);return await this._fileService.createFolder(t),{}}catch(r){throw r instanceof L?r:fn(r)==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Failed to create directory: ${t.toString()}`)}}async createResourceWatch(e){let t=typeof e.uri=="string"?h.parse(e.uri):h.revive(e.uri);try{await this._fileService.stat(t)}catch(i){throw fn(i)==="NoPermissions"?new L(Se.PermissionDenied,`Permission denied: ${t.toString()}`):new L(Se.NotFound,`Resource not found: ${t.toString()}`)}return{channel:DT({root:t.toString(),recursive:e.recursive===!0,excludes:e.excludes,includes:e.includes})}}onResourceWatchSubscribed(e){let t=MT(e);if(!t)return;let r=this._resourceWatches.get(e);if(r)return r.subscribers++,r.pendingGc&&r.pendingGc.clear(),r.descriptor;let i=new Y;try{let s=h.parse(t.root),a={recursive:t.recursive,excludes:t.excludes?.items??[],includes:t.includes?.items};if(t.recursive)i.add(this._fileService.watch(s,a)),i.add(this._fileService.onDidFilesChange(l=>{let d=u4(l,s);d.length>0&&this._dispatchResourceWatchChanges(e,d)}));else{let l=this._fileService.createWatcher(s,{...a,recursive:!1});i.add(l),i.add(l.onDidChange(d=>{this._dispatchResourceWatchChanges(e,c4(d))}))}}catch(s){i.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:i,pendingGc:i.add(new Dt),dispose:()=>i.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=qt(()=>{let r=this._resourceWatches.get(e);!r||r.subscribers>0||this._resourceWatches.deleteAndDispose(e)},l4)),!0):!1}_dispatchResourceWatchChanges(e,t){if(t.length===0)return;let r=t.map(i=>({uri:i.resource.toString(),type:i.type===1?"added":i.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()}setNetworkDiagnosticsService(e){this._networkDiagnostics=e}async getNetworkDiagnosticsInfo(){if(!this._networkDiagnostics)throw new Error("Network diagnostics unavailable: service not wired");let e=[...this._providers.values()],t=await Promise.all(e.map(async a=>{try{return await a.getNetworkDiagnosticsEndpoints?.()??[]}catch(l){return this._logService.warn(`[AgentService] Failed to resolve network diagnostics endpoints for ${a.id}: ${l instanceof Error?l.message:String(l)}`),[]}})),r=await Promise.all(e.map(async a=>{try{return await a.getNetworkDiagnosticsAccount?.()}catch(l){this._logService.warn(`[AgentService] Failed to resolve network diagnostics account for ${a.id}: ${l instanceof Error?l.message:String(l)}`);return}})),i=[],s=new Set;for(let a of t.flat()){let l;try{l=new URL(a.url).toString()}catch{l=a.url}s.has(l)||(s.add(l),i.push(a))}return this._networkDiagnostics.getInfo(i,r.find(a=>!!a))}async diagnosticsFetch(e){if(!this._networkDiagnostics)throw new Error("Network diagnostics unavailable: service not wired");return this._networkDiagnostics.fetch(e)}async _fetchSessionDbContent(e){let t=h.parse(e.sessionUri),r=this._sessionDataService.openDatabase(t);try{let i=await r.object.readFileEditContent(e.toolCallId,e.filePath);if(!i)throw new L(Se.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?i.beforeContent:i.afterContent;if(!s)throw new L(Se.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 L(Se.NotFound,`git service unavailable for: ${e.repoRelativePath}`);let t=this._stateManager.getSessionState(e.sessionUri)?.workingDirectory;if(!t)throw new L(Se.NotFound,`Session has no working directory for git-blob URI: ${e.sessionUri}`);let r=await this._gitService.showBlob(h.parse(t),e.sha,e.repoRelativePath);if(!r)throw new L(Se.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 i=this._doRestoreSubagentSession(e,t);this._restoreSubagentInFlight.set(e,i);try{await i}finally{this._restoreSubagentInFlight.get(e)===i&&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 i=this._stateManager.getSessionState(r);if(!i)return;let s=[...i.turns];i.activeTurn&&s.push(i.activeTurn);let a;for(let m of s){for(let v of m.responseParts)if(v.kind==="toolCall"){let y=v.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,h.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,...i?.project?{project:i.project}:{}},p),this._logService.info(`[AgentService] Restored subagent session: ${e} with ${l.length} turn(s)`)}_registerRestoredSubagent(e,t,r){let i=e.resource.toString();if(this._stateManager.getSessionState(i))return;let s=new Date().toISOString();this._stateManager.restoreSession({resource:i,provider:"subagent",title:e.title,status:1,createdAt:s,modifiedAt:s,...t.project?{project:t.project}:{}},[...e.turns]);let a=ra(r,e.toolCallId);this._stateManager.addChat(r,a,{title:e.title,turns:[...e.turns],origin:{kind:"tool",chat:pe(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 i=D.provider(e);if(i)return this._providers.get(i);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 c4(o){let n=[];for(let e of o.rawAdded)n.push({resource:e,type:1});for(let e of o.rawUpdated)n.push({resource:e,type:0});for(let e of o.rawDeleted)n.push({resource:e,type:2});return n}function u4(o,n){let e=[],t=(r,i)=>{io(r,n)&&e.push({resource:r,type:i})};for(let r of o.rawAdded)t(r,1);for(let r of o.rawUpdated)t(r,0);for(let r of o.rawDeleted)t(r,2);return e}import{CopilotClient as W7,RuntimeConnection as q7}from"@github/copilot-sdk";import*as ht from"fs/promises";import*as nh from"os";var _A=Object.create(null);function g(o,n){if(Ve(n)){let e=_A[n];if(e===void 0)throw new Error(`${o} references an unknown codicon: ${n}`);n=e}return _A[o]=n,{id:o}}var TA={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 p4={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)},fm={...TA,...p4};var wA;(n=>{function o(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}n.isThemeColor=o})(wA||={});var Gc;(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 i(I){let _=r.exec(I.id);if(!_)return i(fm.error);let[,T,P]=_,X=["codicon","codicon-"+T];return P&&X.push("codicon-modifier-"+P.substring(1)),X}b.asClassNameArray=i;function s(I){return i(I).join(" ")}b.asClassName=s;function a(I){return"."+i(I).join(".")}b.asCSSSelector=a;function l(I){return!!I&&typeof I=="object"&&typeof I.id=="string"&&(typeof I.color>"u"||wA.isThemeColor(I.color))}b.isThemeIcon=l;let d=new RegExp(`^\\$\\((${b.iconNameExpression}(?:${b.iconModifierExpression})?)\\)$`);function c(I){let _=d.exec(I);if(!_)return;let[,T]=_;return{id:T}}b.fromString=c;function u(I){return{id:I}}b.fromId=u;function p(I,_){let T=I.id,P=T.lastIndexOf("~");return P!==-1&&(T=T.substring(0,P)),_&&(T=`${T}~${_}`),{id:T}}b.modify=p;function m(I){let _=I.id.lastIndexOf("~");if(_!==-1)return I.id.substring(_+1)}b.getModifier=m;function v(I,_){return I.id===_.id&&I.color?.id===_.color?.id}b.isEqual=v;function y(I){return I?.id===fm.file.id}b.isFile=y;function S(I){return I?.id===fm.folder.id}b.isFolder=S})(Gc||={});var Mb=new RegExp(`\\$\\(${Gc.iconNameExpression}(?:${Gc.iconModifierExpression})?\\)`,"g"),f4=new RegExp(`(\\\\)?${Mb.source}`,"g");function RA(o){return o.replace(f4,(n,e)=>e?n:`\\${n}`)}var eSe=new RegExp(`\\\\${Mb.source}`,"g");var tSe=new RegExp(`(\\s)?(\\\\)?${Mb.source}(\\s)?`,"g");var nSe=new RegExp(`\\$\\(${Gc.iconNameCharacter}+\\)`,"g");var gm=class o{static lift(n){let e=new o(n.value,n);return e.uris=n.uris,e.baseUri=n.baseUri?h.revive(n.baseUri):void 0,e}constructor(n="",e=!1){if(this.value=n,typeof this.value!="string")throw Sy("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+=Ob(this.supportThemeIcons?RA(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+=`
${g4(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(_n(e),"g");return n.replace(t,(r,i)=>n.charAt(i-1)!=="\\"?`\\${r}`:r)}};function Ob(o){return o.replace(/[\\`*_{}[\]()#+!~]/g,"\\$&").replace(/^([ \t]*)-/gm,"$1\\-")}function fs(o){return o.replace(/[\\\]]/g,"\\$&")}function g4(o,n){let e=o.match(/^`+/gm)?.reduce((r,i)=>r.length>i.length?r:i).length??0,t=e>=3?e+1:3;return[`${"`".repeat(t)}${n}`,o,`${"`".repeat(t)}`].join(`
`)}function ot(o){let n=Math.max(0,...(o.match(/`+/g)??[]).map(i=>i.length)),e="`".repeat(n+1),r=o.startsWith("`")||o.endsWith("`")?` ${o} `:o;return`${e}${r}${e}`}function xA(o,n,e){return Math.min(Math.max(o,n),e)}function mm(o){if(o>=1e6){let n=o/1e6,e=Math.floor(n*10)/10;return e%1===0?`${e.toFixed(0)}M`:`${e.toFixed(1)}M`}else{if(o>9e5)return"1M";if(o>=1e3)return`${Math.round(o/1e3)}K`}return o.toString()}function m4(o,n=[],e={}){let r=new hm(o).scan();return new ym(r,o,n,e).parse()}function ml(o,n=[],e={}){let t=new hm(o).scan();if(t.length===0||t[0].type!==11)return new Jc(void 0,o);if(!t.slice(1).some(l=>l.type===11))return new Jc(void 0,o);let i=new ym(t,o,n,e).parse(),s=t[t.length-1],a=s.type===13?o.substring(s.startOffset):"";return new Jc(i,a)}var Jc=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"?h4(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 h4(o,n=0){let e=m4(`[${o}]`),t=n-1,r=[];if(e&&e.type==="sequence")for(let i of e.items)i.type==="scalar"&&r.push({...i,startOffset:i.startOffset+t,endOffset:i.endOffset+t});else r.push({type:"scalar",value:o,rawValue:o,startOffset:n,endOffset:o.length+n,format:"none"});return r}function Ct(o,n,e,t){return{type:o,startOffset:n,endOffset:e,rawValue:t?.rawValue??"",value:t?.value??"",format:t?.format??"none",indent:t?.indent??0}}var hm=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(Ct(13,this.pos,this.pos)),this.tokens}scanLine(){if(this.seenBlockColon=!1,this.peekChar()===`
`){this.tokens.push(Ct(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(Ct(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(Ct(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(Ct(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],i=this.input[this.pos+2],s=this.input[this.pos+3],a=s===void 0||s===" "||s==="	"||s===`
`||s==="\r";if(t==="-"&&r==="-"&&i==="-"&&a){this.tokens.push(Ct(11,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline(),this.seenDocumentStart++;return}if(t==="."&&r==="."&&i==="."&&a){this.tokens.push(Ct(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(Ct(4,this.pos,this.pos+1)),this.pos++;else if(n==="}"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Ct(5,this.pos,this.pos+1)),this.pos++;else if(n==="[")this.flowDepth++,this.tokens.push(Ct(6,this.pos,this.pos+1)),this.pos++;else if(n==="]"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Ct(7,this.pos,this.pos+1)),this.pos++;else if(n===","&&this.flowDepth>0)this.tokens.push(Ct(3,this.pos,this.pos+1)),this.pos++;else if(n==="-"&&this.isBlockDash())this.tokens.push(Ct(2,this.pos,this.pos+1)),this.pos++;else if(n===":"&&this.isBlockColon())this.tokens.push(Ct(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(Ct(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(Ct(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 i=this.input.substring(e,this.pos);this.tokens.push(Ct(0,e,this.pos,{rawValue:i,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(Ct(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 i=this.getParentBlockIndent(e),s=t>0?i+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],T=_===void 0||_===" "||_==="	"||_===`
`||_==="\r";if(S==="-"&&b==="-"&&I==="-"&&T||S==="."&&b==="."&&I==="."&&T){this.pos=p;break}}if(s===0){if(m<=i){this.pos=p;break}s=m}if(m<s){this.pos=p;break}let v=p+s;for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;let y=this.input.substring(v,this.pos);a.push(y),l=0,this.consumeNewline()}let d;if(n==="|")d=a.join(`
`);else{d="";let p=!1,m=!1,v=!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,v=!0):m?((p||b)&&v?d+=`
`+S:d+=S,p=b,m=!1,v=!0):b||p?(d+=`
`+S,p=b,v=!0):(d+=" "+S,p=!1,v=!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(Ct(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 i=this.tokens[r];if(!(i.type===8||i.type===10||i.type===9))return this.getColumnAt(i.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(Ct(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(Ct(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]}},ym=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 i=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=i;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=i;break}if(this.peek(1).type===1){this.pos=i;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=[],i=new Set;if(e){let a=this.parseMappingEntry(n);a&&(i.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&&i.has(l.key.value)&&this.emitError(f(143,null,l.key.value),l.key.startOffset,l.key.endOffset,"duplicate-key"),i.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 i=this.parseMappingValue(n,r);return{key:t,value:i}}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 i=this.currentIndent();return i===n&&this.peekPastIndent().type===2?this.parseValue(n)??this.makeEmptyScalar(e.endOffset):i<=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,i=!0;for(;this.currentToken().type!==13&&(this.skipNewlinesAndComments(),this.currentToken().type!==13);){let s;if(i&&this.currentToken().type===2?s=this.currentToken().startOffset-this.getLineStart(this.currentToken().startOffset):s=this.currentIndent(),i=!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 i=t.startOffset-this.getLineStart(t.startOffset);return this.parseBlockSequence(i)}if(t.type===0){if(this.peek(1).type===1){let i=t.startOffset-this.getLineStart(t.startOffset);return this.parseBlockMapping(i,!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 i;this.currentToken().type===1?(this.advance(),this.skipFlowWhitespace(),i=this.parseFlowValue()):i=this.makeEmptyScalar(r.endOffset),e.push({key:r,value:i}),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,i=this.pos;for(;i<this.tokens.length;){let a=this.tokens[i];if(a.type===8)r=!0,i++;else if(a.type===9||a.type===10)i++;else break}if(!r||i>=this.tokens.length)break;let s=this.tokens[i];if(s.type===0&&s.format==="none")this.pos=i+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 v4;(n=>{function o(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&&Tr(e.cwd,t.cwd)&&Ne(e.env,t.env)&&e.timeout===t.timeout&&Tr(e.sourceUri,t.sourceUri)}n.isEquals=o})(v4||={});var S4={format:0,manifestPath:"plugin.json",hookConfigPath:"hooks.json",pluginRootTokens:["${PLUGIN_ROOT}","${CLAUDE_PLUGIN_ROOT}"],pluginRootEnvVars:["PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"],parseHooks(o,n,e,t,r){return Sm(o,n,t,r)}},b4={format:1,manifestPath:".claude-plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootTokens:["${PLUGIN_ROOT}","${CLAUDE_PLUGIN_ROOT}"],pluginRootEnvVars:["PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"],parseHooks(o,n,e,t,r){return DA(o,n,e,t,r,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},C4={format:2,manifestPath:".plugin/plugin.json",hookConfigPath:"hooks/hooks.json",pluginRootTokens:["${PLUGIN_ROOT}","${CLAUDE_PLUGIN_ROOT}"],pluginRootEnvVars:["PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"],parseHooks(o,n,e,t,r){return DA(o,n,e,t,r,"${PLUGIN_ROOT}","PLUGIN_ROOT")}};async function Xc(o,n){return await gs(te(o,".plugin","plugin.json"),n)?C4:o.path.split("/").includes(".claude")||await gs(te(o,".claude-plugin","plugin.json"),n)?b4:S4}function Zc(o,n){let e=Nt(o.toString());return n?`${e.replace(/#/g,"%23")}#${n}`:e}function I4(o){let n=o.uri.toString();return{type:"agent",id:Zc(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function _4(o){let n=o.uri.toString();return{type:"skill",id:Zc(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function T4(o){let n=o.uri.toString();return{type:"rule",id:Zc(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function w4(o){return{type:"hook",id:Zc(o),uri:o.toString(),name:ve(o)}}function eu(o,n){return{type:"mcpServer",id:Zc(o,`mcp=${encodeURIComponent(n)}`),uri:o.toString(),name:n,enabled:!0,state:{kind:"starting"},mcpApp:am}}var Lb={paths:[],exclusive:!1};function Yc(o){if(o==null)return Lb;if(typeof o=="string"){let n=o.trim();return n?{paths:[n],exclusive:!1}:Lb}if(Array.isArray(o))return{paths:o.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0),exclusive:!1};if(typeof o=="object"){let n=o;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 Lb}function Qc(o,n,e,t){let r=t&&io(o,t)?t:o,i=[];e.exclusive||i.push(te(o,n));for(let s of e.paths){let a=wn(te(o,s));io(a,r)&&i.push(a)}return i}function R4(o){if(!o||typeof o!="object"||Array.isArray(o))return;let n=o;return Object.hasOwn(n,"mcpServers")?n.mcpServers:n}function x4(o){if(!o||typeof o!="object")return;let n=o,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,i=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:i,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 P4=/[\s&|<>()^;!`"']/;function A4(o,n,e){if(!o.includes(e))return o;if(!P4.test(n))return o.replaceAll(e,n);let t=_n(e),r=new RegExp(`(["']?)`+t+"([\\w./\\\\~:-]*)","g");return o.replace(r,(i,s,a)=>{let l=n+a;return s?s+l:'"'+l.replace(/"/g,'\\"')+'"'})}function E4(o,n,e,t){let r=a=>e.reduce((l,d)=>l.replaceAll(d,n),a),i=o.configuration,s;if(i.type==="stdio"){let a={...i};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));for(let l of t)a.env[l]=n;a.envFile&&(a.envFile=r(a.envFile)),s=a}else{let a={...i};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:o.name,configuration:s,uri:o.uri,customization:o.customization}}var k4=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function D4(o){return Pd(o,n=>{if(h.isUri(n))return n;if(typeof n=="string"){let e=n.replace(k4,"${env:$1}");return e!==n?e:void 0}})}var M4={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 O4(o){if(o.type!==void 0&&o.type!=="command")return;let n=typeof o.command=="string"&&o.command.length>0,e=typeof o.bash=="string"&&o.bash.length>0,t=typeof o.powershell=="string"&&o.powershell.length>0,r=typeof o.windows=="string"&&o.windows.length>0,i=typeof o.linux=="string"&&o.linux.length>0,s=typeof o.osx=="string"&&o.osx.length>0;if(!n&&!e&&!t&&!r&&!i&&!s)return;let a=r?o.windows:t?o.powershell:void 0,l=i?o.linux:e?o.bash:void 0,d=s?o.osx:e?o.bash:void 0,c=typeof o.timeout=="number"?o.timeout:typeof o.timeoutSec=="number"?o.timeoutSec:void 0;return{...n&&{command:o.command},...a&&{windows:a},...l&&{linux:l},...d&&{osx:d},...typeof o.env=="object"&&o.env!==null&&{env:o.env},...c!==void 0&&{timeout:c}}}function PA(o,n,e){let t=O4(o);if(!t)return;let r,i=typeof o.cwd=="string"?o.cwd:void 0;return i?i.startsWith("~/")?r=h.joinPath(e,i.substring(2)):Wt(i)?r=h.file(i):n&&(r=te(n,i)):r=n,{...t,cwd:r}}function L4(o,n,e){if(!o||typeof o!="object")return[];let t=o,r=[],i=t.hooks;if(i!==void 0&&Array.isArray(i))for(let s of i){if(!s||typeof s!="object")continue;let a=PA(s,n,e);a&&r.push(a)}else{let s=PA(t,n,e);s&&r.push(s)}return r}function Sm(o,n,e,t){if(!n||typeof n!="object")return[];let r=n;if(r.disableAllHooks===!0)return[];let i=r.hooks;if(!i||typeof i!="object")return[];let s=i,a=[],l=w4(o);for(let d of Object.keys(s)){let c=M4[d];if(!c)continue;let u=s[d];if(!Array.isArray(u))continue;let p=[];for(let m of u)p.push(...L4(m,e,t));p.length>0&&a.push({type:c,commands:p,uri:o,originalId:d,customization:l})}return a}function DA(o,n,e,t,r,i,s){let a=e.fsPath,l=n,d=u=>{for(let p of["command","windows","linux","osx"])typeof u[p]=="string"&&(u[p]=A4(u[p],a,i));(!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 v of m.hooks)d(v);else d(m)}return Sm(o,Pd(n,u=>typeof u=="string"?u.replaceAll(i,e.fsPath):void 0),t,r)}async function wo(o,n){try{let e=await n.readFile(o);return Kf(e.value.toString())}catch{return}}async function gs(o,n){try{return await n.resolve(o),!0}catch{return!1}}var vm=".md",AA=".mdc",EA=".instructions.md";async function Nb(o,n,e){let t=new Set,r=[],i=async(s,a)=>{let l;try{let d=await Ub(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=h.joinPath(s,"SKILL.md");if(await gs(a,e)){await i(ve(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=h.joinPath(d.resource,"SKILL.md");await gs(c,e)&&await i(ve(d.resource),c)}))})),r.length===0){let s=h.joinPath(o,"SKILL.md");await gs(s,e)&&await i(ve(o),s)}return r.sort((s,a)=>s.name.localeCompare(a.name)),r}async function N4(o,n){let e=new Set,t=[],r=(i,s)=>{e.has(i)||(e.add(i),t.push({uri:s,name:i}))};for(let i of o){let s;try{s=await n.resolve(i)}catch{continue}if(s.isFile&&bd(i).toLowerCase()===vm){r(ve(i).slice(0,-vm.length),i);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||bd(a.resource).toLowerCase()!==vm||r(ve(a.resource).slice(0,-vm.length),a.resource)}return t.sort((i,s)=>i.name.localeCompare(s.name)),t}function kA(o){let n=ve(o),e=n.toLowerCase();if(e.endsWith(AA))return n.slice(0,-AA.length);if(e.endsWith(EA))return n.slice(0,-EA.length)}async function U4(o,n){let e=new Set,t=[],r=(i,s)=>{e.has(i)||(e.add(i),t.push({uri:s,name:i}))};for(let i of o){let s;try{s=await n.resolve(i)}catch{continue}if(s.isFile){let a=kA(i);a&&r(a,i);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children){if(!a.isFile)continue;let l=kA(a.resource);l&&r(l,a.resource)}}return t.sort((i,s)=>i.name.localeCompare(s.name)),t}async function bm(o,n){let e=await N4(o,n);if(e.length===0)return e;let t=await Promise.all(e.map(async s=>{try{let{name:a,description:l}=await tu(s.uri,n);return{uri:s.uri,name:a||s.name,...l?{description:l}:{}}}catch{return s}})),r=new Set,i=[];for(let s of t)r.has(s.name)||(r.add(s.name),i.push(s));return i.sort((s,a)=>s.name.localeCompare(a.name)),i}async function tu(o,n){let e=ve(o).replace(/(\.agent)?\.md$/i,"");try{let t=await n.readFile(o),r=ml(t.value.toString()),i=r?.getStringValue("name")?.trim()||e,s=r?.getStringValue("description")?.trim(),a=r?.getBooleanValue("user-invocable");return{name:i,description:s,userInvocable:a}}catch{return{name:e}}}async function Ub(o,n){try{let e=await n.readFile(o),t=ml(e.value.toString()),r=t?.getStringValue("name")?.trim()||ve(Tn(o)),i=t?.getStringValue("description")?.trim(),s=t?.getBooleanValue("user-invocable");return{name:r,description:i,userInvokable:s}}catch{return{name:ve(Tn(o))}}}async function Cm(o,n){let e=ve(o).replace(/(\.instructions)?\.md$/i,"");try{let t=await n.readFile(o),r=ml(t.value.toString()),i=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:i,description:s,globs:a,alwaysApply:l}}catch{return{name:e}}}async function F4(o,n,e,t,r,i){for(let s of n){let a=await wo(s,t);if(a)return e.parseHooks(s,a,o,r,i)}return[]}async function H4(o,n,e,t){let r=new Map;for(let i of o){let s=await wo(i,t);for(let a of MA(i,s,n,e))r.has(a.name)||r.set(a.name,a)}return[...r.values()].sort((i,s)=>i.name.localeCompare(s.name))}function MA(o,n,e,t){let r=R4(n);if(!r)return[];let i=[];for(let[s,a]of Object.entries(r)){let l=x4(a);if(!l)continue;let d={name:s,configuration:l,uri:o,customization:eu(o,s)};d=E4(d,e,t.pluginRootTokens,t.pluginRootEnvVars),d.configuration.type==="stdio"&&d.configuration.cwd===void 0&&(d={...d,configuration:{...d.configuration,cwd:e}}),d=D4(d),i.push(d)}return i}async function Im(o,n,e,t,r){let i=await Xc(o,n),s=await wo(te(o,i.manifestPath),n),a=s&&typeof s=="object"?s:void 0,l=Qc(o,i.hookConfigPath,Yc(a?.hooks),r),d=Qc(o,".mcp.json",Yc(a?.mcpServers),r),c=Qc(o,"skills",Yc(a?.skills),r),u=Qc(o,"agents",Yc(a?.agents),r),p=Qc(o,"rules",Yc(a?.rules),r),m=[],v=a?.mcpServers;v&&typeof v=="object"&&!Array.isArray(v)&&!he(v,{paths:!0})&&(m=MA(te(o,i.manifestPath),{mcpServers:v},o.fsPath,i));let y=[],S=a?.hooks;if(S&&typeof S=="object"&&!Array.isArray(S)&&!he(S,{paths:!0})){let X=te(o,i.manifestPath);y=i.parseHooks(X,{hooks:S},o,e,t)}let[b,I,_,T,P]=await Promise.all([y.length>0?Promise.resolve(y):F4(o,l,i,n,e,t),m.length>0?Promise.resolve(m):H4(d,o.fsPath,i,n),Nb(o,c,n),bm(u,n),U4(p,n)]);return{hooks:b,mcpServers:I,skills:_.map(_m),agents:T.map(hl),instructions:P.map($4)}}function hl(o){return{...o,customization:I4(o)}}function _m(o){return{...o,customization:_4(o)}}function $4(o){return{...o,customization:T4(o)}}import*as OA from"fs/promises";function Fb(o,n){return te(o,".copilot","chats",n)}async function LA(o,n){let e=Fb(o,n);return await OA.mkdir(e.fsPath,{recursive:!0}),e}function W4(o){let n=Object.entries(o).filter(([,e])=>e!==void 0);return n.length>0?Object.fromEntries(n):void 0}function Tm(o){if(!o||typeof o!="object")return;let n=o,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,i=n.tokenPrices??n.token_prices,s;if(i&&typeof i=="object"){let a=i.default,l=a&&typeof a=="object",d=gt(i.inputPrice)??gt(l?a.input_price:void 0),c=gt(i.cachePrice)??gt(l?a.cache_price:void 0),u=gt(i.cacheWritePrice)??gt(l?a.cache_write_price:void 0),p=gt(i.outputPrice)??gt(l?a.output_price:void 0),m=gt(i.contextMax)??gt(l?a.context_max:void 0),v=i.longContext??i.long_context,y;v&&typeof v=="object"&&(y={inputPrice:gt(v.inputPrice)??gt(v.input_price),cachePrice:gt(v.cachePrice)??gt(v.cache_price),cacheWritePrice:gt(v.cacheWritePrice)??gt(v.cache_write_price),outputPrice:gt(v.outputPrice)??gt(v.output_price),contextMax:gt(v.contextMax)??gt(v.context_max)}),s={inputPrice:d,cachePrice:c,cacheWritePrice:u,outputPrice:p,contextMax:m,longContext:y}}return{multiplier:e,priceCategory:t,discountPercent:r,promo:q4(n),tokenPrices:s}}function gt(o){return typeof o=="number"?o:void 0}function q4(o){let n=o.promo;if(!n||typeof n!="object")return;let e=typeof n.id=="string"?n.id:void 0,t=gt(n.discountPercent)??gt(n.discount_percent),r=typeof n.endsAt=="string"?n.endsAt:typeof n.ends_at=="string"?n.ends_at:void 0,i=typeof n.message=="string"?n.message:void 0;if(e&&typeof t=="number"&&r&&i)return{id:e,discountPercent:t,endsAt:r,message:i}}function yl(o,n){let e=o?.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 W4({multiplierNumeric:typeof o?.multiplier=="number"?o.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 o?.priceCategory=="string"?o.priceCategory:void 0),discountPercent:typeof o?.discountPercent=="number"?o.discountPercent:void 0,promo:o?.promo})}function Hb(o){let n=o?.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 B4="byokModelIdentifier";function NA(o){return o!==void 0?{[B4]:o}:void 0}var vl=W("agentPluginManager");function qr(o){return JSON.stringify(o)}function wm(o){try{let n=JSON.parse(o);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 Sl=class extends w{constructor(e){super();this._chats=this._register(new we);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 ms(o){switch(o){case"none":return f(1983,null);case"minimal":return f(1981,null);case"low":return f(1975,null);case"medium":return f(1979,null);case"high":return f(1973,null);case"xhigh":return f(1985,null);case"max":return f(1977,null);default:return o.charAt(0).toUpperCase()+o.slice(1)}}function hs(o){switch(o){case"none":return f(1984,null);case"minimal":return f(1982,null);case"low":return f(1976,null);case"medium":return f(1980,null);case"high":return f(1974,null);case"xhigh":return f(1986,null);case"max":return f(1978,null);default:return}}var Rm=W("agentHostOTelService");import{LogLevel as ys,createFetchPatch as z4,createProxyResolver as V4,loadSystemCertificates as j4}from"@vscode/proxy-agent";var yi=W("agentHostProxyResolver"),bl=class{constructor(n,e){this._configurationService=n;this._logService=e;this._connections=new Map}register(n,e){return this._connections.set(n,e),N(()=>{this._connections.get(n)===e&&this._connections.delete(n)})}resolveProxy(n){return this._getProxyResolver().resolveProxyURL(n)}fetch(n,e){if(!this._fetch){let t=this._getProxyResolver();this._fetch=z4(this._proxyAgentParams,globalThis.fetch,t.resolveProxyURL)}return this._fetch(n,e)}_getProxyResolver(){if(!this._proxyResolver){let n=i=>this._configurationService.getValue(i),e=()=>n("http.experimental.systemCertificatesV2")??!1,t=()=>!!n("http.systemCertificates"),r={resolveProxy:i=>this._hostResolveProxy(i),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")??Fa,loadAdditionalCertificates:async()=>j4({loadSystemCertificatesFromNode:()=>n("http.systemCertificatesNode")??Fa,log:this._logService}),log:this._logService,getLogLevel:()=>{switch(this._logService.getLevel()){case 1:return ys.Trace;case 2:return ys.Debug;case 3:return ys.Info;case 4:return ys.Warning;case 5:return ys.Error;case 0:return ys.Off;default:return ys.Info}},proxyResolveTelemetry:()=>{},isUseHostProxyEnabled:()=>this._connections.size>0,getNetworkInterfaceCheckInterval:()=>(n("http.experimental.networkInterfaceCheckInterval")??300)*1e3,env:process.env};this._proxyAgentParams=r,this._proxyResolver=V4(r)}return this._proxyResolver}async _hostResolveProxy(n){for(let e of this._connections.values())try{return await e.resolveProxy(n)}catch{}}};bl=R([C(0,Bn),C(1,M)],bl);function xm(o,n){let e=o??[],t=n??[];if(e.length!==t.length)return!1;let r=new Map;for(let i of e)r.set(i.name,i);for(let i of t){let s=r.get(i.name);if(!s||s.description!==i.description||!Ne(s.inputSchema,i.inputSchema))return!1}return!0}var hn=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(i=>i.name===n))return t}structuralEquals(n){return xm(this.merged(),n)}};var vi=W("byokLmBridgeRegistry"),Pm=class{constructor(){this._entries=new Map;this._changeListeners=new Set}onDidChangeModels(n){return this._changeListeners.add(n),N(()=>{this._changeListeners.delete(n)})}_notifyChanged(){for(let n of[...this._changeListeners])n()}register(n,e){this._entries.get(n)?.store.dispose();let t=new Y,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),N(()=>{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||!K4(e.models,t))&&(e.models=t,this._notifyChanged())}};function K4(o,n){return o.length!==n.length?!1:o.every((e,t)=>{let r=n[t];return e.vendor===r.vendor&&e.id===r.id&&e.name===r.name&&e.modelIdentifier===r.modelIdentifier&&e.maxContextWindowTokens===r.maxContextWindowTokens&&e.supportsVision===r.supportsVision})}var Am="agents/",G4=8,UA=48,J4=8,Em=W("copilotBranchNameGenerator"),Cl=class{constructor(n,e){this._copilotApiService=n;this._logService=e}async generateBranchName(n){let e=await this._generateBranchNameHint(n)??Q4(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=Y4(r).slice(0,UA).replace(/-+$/g,""),r.length<J4){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){let t=`${n.branchPrefix??""}${Am}`;if(!e)return`${t}${n.sessionId}`;let r=`${t}${e}`;return n.branchExists&&await n.branchExists(r)?`${r}-${n.sessionId.substring(0,G4)}`:r}};Cl=R([C(0,Pt),C(1,M)],Cl);function Y4(o){let n=o.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 Q4(o){let e=o.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").split("-").filter(t=>t.length>0).slice(0,8).join("-").slice(0,UA).replace(/-+$/g,"");return e.length>0?e:void 0}var X4=1,Z4="vscode-copilot-migration";function e5(o,n){let e=[],t=null,r=(n.startTime??new Date).getTime(),i=()=>new Date(r++).toISOString(),s=l=>{e.push(l),t=l.id},a=l=>{let d;if(l.toolInput)try{let p=JSON.parse(l.toolInput);p&&typeof p=="object"&&(d=p)}catch{}let c=l.content?.find(p=>p.type==="subagent");c&&s({id:O(),parentId:t,timestamp:i(),type:"subagent.started",data:{toolCallId:l.toolCallId,agentName:c.agentName??c.title,agentDisplayName:c.title,agentDescription:c.description??""}}),s({id:O(),parentId:t,timestamp:i(),type:"tool.execution_start",data:{toolCallId:l.toolCallId,toolName:l.toolName,...d?{arguments:d}:{}}});let u=t5(l.content);s({id:O(),parentId:t,timestamp:i(),type:"tool.execution_complete",data:{toolCallId:l.toolCallId,success:l.success,...l.success?{result:{content:u}}:{},...l.error?{error:{message:l.error.message,...l.error.code?{code:l.error.code}:{}}}:{}}})};s({id:O(),parentId:t,timestamp:i(),type:"session.start",data:{sessionId:n.sessionId,copilotVersion:n.copilotVersion??"0.0.0",producer:Z4,startTime:i(),version:n.schemaVersion??X4,...n.model?{selectedModel:n.model}:{},...n.workingDirectory?{context:{cwd:n.workingDirectory}}:{}}});for(let l of o){s({id:wT(l.id)?l.id:O(),parentId:t,timestamp:i(),type:"user.message",data:{content:l.message.text,source:"user"}});let d="",c="",u=()=>{!d&&!c||(s({id:O(),parentId:t,timestamp:i(),type:"assistant.message",data:{content:d,messageId:O(),...c?{reasoningText:c}:{},...n.model?{model:n.model}:{}}}),d="",c="")};for(let p of l.responseParts)p.kind==="markdown"?(c&&u(),d+=p.content):p.kind==="reasoning"?(d&&u(),c+=p.content):p.kind==="toolCall"&&p.toolCall.status==="completed"&&(u(),a(p.toolCall));u(),l.state==="cancelled"&&s({id:O(),parentId:t,timestamp:i(),type:"abort",data:{reason:"user_initiated"}})}return e}function t5(o){if(!o)return"";let n="";for(let e of o)e.type==="text"&&(n+=e.text);return n}function n5(o){return o.length===0?"":o.map(n=>JSON.stringify(n)).join(`
`)+`
`}function FA(o,n){return n5(e5(o,n))}var $b="/.well-known",Sbe=`${$b}/oauth-protected-resource`,bbe=`${$b}/oauth-authorization-server`,Cbe=`${$b}/openid-configuration`;function HA(o){if(typeof o!="object"||o===null)return!1;let n=o;return!(!n.resource||n.scopes_supported!==void 0&&!Array.isArray(n.scopes_supported))}function r5(o,n){let e=o.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 i=t;return i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),{directory:i,command:r}}}function Ss(o,n,e){if(!e||!n)return!1;let t=o==="bash",r=o==="powershell";if(!t&&!r)return!1;let i=n.command;if(typeof i!="string")return!1;let s=r5(i,r);return!s||!o5(s.directory,e)?!1:(n.command=s.command,!0)}function o5(o,n){if(!o)return!1;let e=a=>a.replace(/[\\/]+$/,""),t=e(o),r=e(n.fsPath);if(!t||!r)return!1;let i,s;try{i=h.file(t),s=h.file(r)}catch{return!1}return nt.isEqual(i,s)}var $A="ahp-otlp://logs/{level}",WA="ahp-otlp",i5=["trace","debug","info","warn","error","fatal"];function qA(o){switch(o){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 s5(o){let n=o.toLowerCase();return i5.includes(n)?n:void 0}function a5(o){switch(o){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 Il=class{constructor(n){this.attributes=n}toJSON(){return this.attributes}},km=class extends w{constructor(){super(...arguments);this._onDidLog=this._register(new A);this.onDidLog=this._onDidLog.event}emit(e){this._onDidLog.fire(e)}},Dm=class extends es{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,i=!1){let s,a=r.findIndex(c=>c instanceof Il);a!==-1&&(s=r[a].attributes,r=r.slice(0,a).concat(r.slice(a+1)));let{severityNumber:l,severityText:d}=a5(e);this._emitter.emit({timeUnixNano:u5(Date.now()),severityNumber:l,severityText:d,body:vo([t,...r],i),...s?{attributes:s}:void 0})}};function BA(o){return l5([o])}function l5(o){return{resourceLogs:[{resource:{attributes:[]},scopeLogs:[{scope:{name:"vscode.agentHost"},logRecords:o.map(n=>({timeUnixNano:n.timeUnixNano,observedTimeUnixNano:n.timeUnixNano,severityNumber:n.severityNumber,severityText:n.severityText,body:{stringValue:n.body},...n.attributes?{attributes:d5(n.attributes)}:void 0}))}]}]}}function d5(o){return Object.entries(o).map(([n,e])=>({key:n,value:c5(e)}))}function c5(o){switch(typeof o){case"boolean":return{boolValue:o};case"number":return Number.isInteger(o)?{intValue:String(o)}:{doubleValue:o};default:return{stringValue:o}}}function u5(o){return`${o}000000`}function zA(o){let n=/^ahp-otlp:\/\/logs\/([^/?#]+)/i.exec(o);if(n)return s5(n[1])}function VA(o){return`ahp-otlp://logs/${o}`}var p5="agentFeedback";function Mm(o){return o.type==="annotations"&&o.displayKind===p5}function Om(o){let n=o.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 Wb=Object.freeze({valid:!1,sessionId:void 0});function Lm(o,n){let e=o.authorization;if(typeof e!="string"||!e.startsWith("Bearer "))return Wb;let t=e.slice(7),r=t.indexOf(".");if(r===-1)return Wb;let i=t.slice(0,r),s=t.slice(r+1);return i!==n||s.length===0?Wb:{valid:!0,sessionId:s}}function f5(){let o=new Uint8Array(32);crypto.getRandomValues(o);let n="";for(let e=0;e<o.length;e++)n+=o[e].toString(16).padStart(2,"0");return n}function _l(o){return new Promise((n,e)=>{let t=[];o.on("data",r=>t.push(Buffer.isBuffer(r)?r:Buffer.from(r))),o.on("end",()=>n(Buffer.concat(t).toString("utf8"))),o.on("error",e)})}var Si=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=f5(),t=new Set,i=(await import("http")).createServer();await new Promise((d,c)=>{let u=p=>c(p);i.once("error",u),i.listen(0,"127.0.0.1",()=>{i.removeListener("error",u),d()})});let s=i.address();if(!s||typeof s=="string")throw i.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:i,baseUrl:a,nonce:e,inFlight:t,refcount:0,state:this.createState(n)};return i.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 Tl=class extends Error{};function g5(o){if(typeof o=="string")return o;if(Array.isArray(o)){let n="";for(let e of o)e&&e.type==="text"&&typeof e.text=="string"&&(n+=e.text);return n}return""}function m5(o){switch(o){case"system":case"developer":return"system";case"assistant":return"assistant";case"tool":case"function":return"tool";default:return"user"}}function h5(o){if(!o||o.length===0)return;let n=[];for(let e=0;e<o.length;e++){let t=o[e],r=t.function?.name;if(!r)throw new Tl(`tool_calls[${e}].function.name is required`);n.push({id:t.id??`call_${e}`,name:r,argumentsJson:t.function?.arguments??"{}"})}return n}function y5(o){if(!o||o.length===0)return;let n=[];for(let e of o){let t=e.function;t?.name&&n.push({name:t.name,description:t.description,parametersSchema:t.parameters})}return n.length?n:void 0}function jA(o,n){let e=typeof n.model=="string"?n.model:"";if(!e)throw new Tl('Request is missing the "model" field');let r=(Array.isArray(n.messages)?n.messages:[]).map(s=>({role:m5(s.role),content:g5(s.content),toolCalls:h5(s.tool_calls),toolCallId:s.tool_call_id})),i={};return typeof n.temperature=="number"&&(i.temperature=n.temperature),typeof n.top_p=="number"&&(i.top_p=n.top_p),typeof n.max_tokens=="number"&&(i.max_tokens=n.max_tokens),{vendor:o,modelId:e,messages:r,tools:y5(n.tools),modelOptions:Object.keys(i).length?i:void 0}}var qb=0;function v5(){return qb=(qb+1)%Number.MAX_SAFE_INTEGER,`chatcmpl-byok-${Date.now().toString(36)}-${qb.toString(36)}`}function Nm(o){return`data: ${JSON.stringify(o)}

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

`),i}function GA(o,n="api_error"){return JSON.stringify({error:{message:o,type:n}})}var Um=W("byokLmProxyService"),JA="ByokLmProxyService",Bb="/v/",YA="/chat/completions",wl=class extends Si{constructor(e,t){super(JA,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:i=>`${e.baseUrl}${Bb}${encodeURIComponent(i)}`,dispose:()=>{r||(r=!0,t())}}}writeInternalError(e){this._writeJsonError(e,500,"Internal proxy error")}async handleRequest(e,t,r){let i=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${JA}] ${i} ${s}`),i==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=Lm(e.headers,r.nonce);if(!a.valid||!a.sessionId){this._writeJsonError(t,401,"Invalid authentication","authentication_error");return}let l=this._parseVendorFromChatPath(s);if(i==="POST"&&l!==void 0){await this._handleChatCompletions(e,t,r,l);return}this._writeJsonError(t,404,`No route for ${i} ${s}`,"not_found_error")}_parseVendorFromChatPath(e){if(!e.startsWith(Bb)||!e.endsWith(YA))return;let t=e.slice(Bb.length,e.length-YA.length);if(!t)return;let r;try{r=decodeURIComponent(t)}catch{return}if(!(!r||r.includes("/")))return r}async _handleChatCompletions(e,t,r,i){let s;try{let u=await _l(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=jA(i,s)}catch(u){let p=u instanceof Tl?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 KA(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,i="api_error"){e.headersSent||e.writableEnded||(e.writeHead(t,{"Content-Type":"application/json"}),e.end(GA(r,i)))}};wl=R([C(0,M),C(1,vi)],wl);var Rl=class extends w{constructor(e){super();this.session=e;this._handledEventTypes=new Set;this._onUnhandledEvent=this._register(new A);this.onUnhandledEvent=this._onUnhandledEvent.event;let t=e.on(r=>{this._handledEventTypes.has(r.type)||this._onUnhandledEvent.fire(r)});this._register(N(t)),this._register(N(()=>{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 onPermissionRequested(){return this._onPermissionRequested??=this._sdkEvent("permission.requested")}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 A({onDidAddFirstListener:()=>this._handledEventTypes.add(e),onDidRemoveLastListener:()=>this._handledEventTypes.delete(e)})),r=this.session.on(e,i=>t.fire(i));return this._register(N(r)),t.event}};var Fm=W("sandboxHelperService");import{createHash as A5}from"crypto";var S5=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"]),b5=new Set(["ai","cloud","com","dev","io","me","net","org","tech"]);function nu(o,n=!1){if(!o)return;let e=o.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 i=t.startsWith("*."),s=i?t.slice(2):t;if(s&&/^[a-z0-9.-]+$/.test(s)){if(!n){let a=s.slice(s.lastIndexOf(".")+1);if(S5.has(a)||!b5.has(a))return}return i?`*.${s}`:s}}function C5(o){let n=o.trim();if(n==="*"||!n.includes("://"))return n;try{return h.parse(n).authority}catch{return n}}function zb(o,n){let e=nu(C5(n),n.includes("://"));if(!e)return!1;if(e==="*")return!0;if(e.startsWith("*.")){let t=e.slice(2);return o===t||o.endsWith(`.${t}`)}return o===e}var $m=W("windowsMxcTerminalSandboxRuntime"),Hm=class{constructor(){this._configVersion="0.6.0-alpha"}getExecutablePath(n,e,t){let r=t==="arm64"?"arm64":"x64";return ye.join(n,e,"@microsoft","mxc-sdk","bin",r,"wxc-exec.exe")}getRuntimeReadPaths(n,e){let t=[];return n&&t.push(n),e&&t.push(e,ye.dirname(e)),[...new Set(t)]}async createConfig(n,e){let t=this.toWindowsPath(n.tempDir),i=`${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&&ye.isAbsolute(n.shell)?[ye.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(i,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 Wm(o,n,e){if(!n.keywords.includes(o.keyword.toLowerCase())||n.condition&&(!e||!n.condition(e)))return!1;if(n.subcommands){let t=I5(o.args,n.optionsWithValue);if(t===void 0||!n.subcommands.includes(t))return!1}return n.when?.(o)??!0}function I5(o,n){for(let e=0;e<o.length;e++){let t=o[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 _5=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 XA(o,n){if(n===1)return[];switch(o){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 QA(o,n){let e=new Set;for(let r of n)for(let i of T5)Wm(r,i,{os:o})&&e.add(i.value);let t=[...e].flatMap(r=>XA(r,o));return[...new Set(t)]}var T5=[{keywords:["gpg","gpg2"],value:"gnupg"},{keywords:["git"],value:"gnupg"}];function qm(o,n,e=[]){if(n.length===0)return QA(o,e);let t=new Set;for(let i of n){let s=_5.get(i.toLowerCase());s&&t.add(s)}let r=[...t].flatMap(i=>XA(i,o));return[...new Set([...r,...QA(o,e)])]}var w5=[{keywords:["node","npm","npx","pnpm","yarn","corepack","bun","deno","nvm","volta","fnm","asdf","mise"],value:"node"},{keywords:["git"],value:"gnupg",condition:({os:o})=>o!==1}],R5=new Set(["git","gh","gpg","gpg2"]);function x5(o,n){switch(o){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 ru(o,n){let e=new Set;for(let r of n)for(let i of w5)Wm(r,i,{os:o})&&P5(i.value,n)&&e.add(i.value);let t={};for(let r of e)eE(t,x5(r,o));return t}function P5(o,n){switch(o){case"gnupg":return n.every(e=>R5.has(e.keyword.toLowerCase()));case"node":return!0}}function eE(o,n){for(let[e,t]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(o,e)){o[e]=t;continue}let r=o[e];if(Array.isArray(r)&&Array.isArray(t)){o[e]=[...new Set([...r,...t])];continue}ZA(r)&&ZA(t)&&eE(r,t)}}function ZA(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}var hCe=W("terminalSandboxService");var En=class extends w{constructor(e,t,r,i){super();this._host=e;this._fileService=t;this._logService=r;this._windowsMxcRuntime=i;this._sandboxSettingsId=O();this._runtimeResolved=!1;this._runAsNode=!1;this._needsForceUpdateConfigFile=!0;this._commandAllowListKeywords=[];this._commandAllowListCommandDetails=[];this._commandAllowNetwork=!1;this._os=Mt;this._defaultWritePaths=[];this._fileSystemPathExtUri=new Li(()=>this._os===1);this._buildSandboxPayload=(e,t,r,i,s)=>this._host.buildWindowsMxcSandboxPayload(e,t,r,i,s);this._pathJoin=(...e)=>(this._os===1?ye: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,i,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),v=this._normalizeCommandDetails(s??[]),y=this._normalizeCommandKeywords(v.map(x=>x.keyword)),S=qm(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),b=qm(this._os,y,v),I=ru(this._os,this._commandAllowListCommandDetails),_=ru(this._os,v);if((this._commandAllowListKeywords.length===0||this._needsForceUpdateConfigFile||!this._areStringArraysEqual(this._commandAllowListKeywords,y)||!this._areStringArraysEqual(S,b)||!this._areObjectsEqual(I,_)||this._commandCwd?.toString()!==i?.toString()||this._commandAllowNetwork!==m||this._os===1&&(this._commandLine!==e||this._commandShell!==r))&&(this._commandAllowListKeywords=y,this._commandAllowListCommandDetails=v,this._commandCwd=i,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 P=p?{blockedDomains:u.blockedDomains,deniedDomains:u.deniedDomains}:void 0;if(this._os===1){if(!this._mxcPath)throw new Error("MXC executable path not resolved");return{command:this._windowsMxcRuntime.wrapCommand(this._mxcPath,this._sandboxConfigPath),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}if(!this._execPath)throw new Error("Executable path not set to run sandbox commands");if(!this._srtPath)throw new Error("Sandbox runtime path not resolved");if(!this._rgPath)throw new Error("Ripgrep path not resolved");let X=this._getSandboxCommandWithPreservedCwd(e,i),k=`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 x=`ELECTRON_RUN_AS_NODE=1 ${k}`;return{command:this._wrapSandboxRuntimeCommandForLaunch(x,i),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}return{command:this._wrapSandboxRuntimeCommandForLaunch(k,i),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:m&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...P}}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 i=await this.getMissingSandboxDependencies();return i.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:i}}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 i=this._tempDir?this._getUriPath(h.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`)):void 0,s=await this._getFileSystemAccessPaths(i),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:i}=this.getResolvedNetworkDomains(),s=new Set,a=new Set;for(let l of t){if(i.some(d=>zb(l,d))){s.add(l),a.add(l);continue}r.some(d=>zb(l,d))||s.add(l)}return{blockedDomains:[...s],deniedDomains:[...a]}}_extractDomains(e){let t=new Set,r;for(En._urlRegex.lastIndex=0;(r=En._urlRegex.exec(e))!==null;){let i=this._extractDomainFromUrl(r[0]);i&&t.add(i)}for(En._sshRemoteRegex.lastIndex=0;(r=En._sshRemoteRegex.exec(e))!==null;){let i=nu(r[1],!0);i&&t.add(i)}for(En._hostRegex.lastIndex=0;(r=En._hostRegex.exec(e))!==null;){let i=nu(r[1]);i&&t.add(i)}return[...t]}_extractDomainFromUrl(e){try{let t=h.parse(e).authority;return nu(t,!0)}catch{return}}_normalizeCommandKeywords(e){return[...new Set(e.map(t=>t.toLowerCase()))].sort()}_normalizeCommandDetails(e){let t=new Set,r=[];for(let i of e){let s={keyword:i.keyword.toLowerCase(),args:[...i.args]},a=JSON.stringify(s);t.has(a)||(t.add(a),r.push(s))}return r.sort((i,s)=>i.keyword.localeCompare(s.keyword)||i.args.join("\0").localeCompare(s.args.join("\0")))}_areStringArraysEqual(e,t){return e.length===t.length&&e.every((r,i)=>r===t[i])}_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 eS(r)}let t=this._getSandboxConfiguredEnabledValue();return eS(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=e.nativeModulesDir??"node_modules",r=this._os===1?"win32":this._os===2?"darwin":"linux",i=this._os===1?"rg.exe":"rg";this._rgPath=this._pathJoin(this._appRoot,t,"@vscode","ripgrep-universal","bin",`${r}-${s_}`,i),this._mxcPath=this._windowsMxcRuntime.getExecutablePath(this._appRoot,t,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")??{}:{},i=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=ru(this._os,this._commandAllowListCommandDetails),d=this._getCommandRuntimeFileSystemPaths(l,"allowRead"),c=this._getCommandRuntimeFileSystemPaths(l,"allowWrite"),u=h.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`),p=this._getUriPath(u),m=[],v=[],y=[],S;if(this._os===1){let I=await this._getWindowsMxcFilesystemPolicy(),_=await this._getWindowsMxcEnvironment();m=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(i.allowWrite),...I.readwritePaths]),v=await this._resolveFileSystemPaths([...i.allowRead??[],...I.readonlyPaths]),y=await this._resolveFileSystemPaths(i.denyRead??[]),this._windowsMxcEnvironment=_}else this._os===2?(m=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,c))).filter(I=>I!==p),v=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),v=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:v,allowWritePaths:m,denyReadPaths:y,env:this._windowsMxcEnvironment??[]},this._buildSandboxPayload):{network:e?{allowedDomains:[],deniedDomains:[],enabled:!1}:this.getResolvedNetworkDomains(),filesystem:{denyRead:y,allowRead:v,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,F.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")??{}:{},i=this._os===1?this._getSettingValue("chat.agent.sandbox.fileSystem.windows")??{}:{},s=ru(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(i.allowWrite),...m.readwritePaths]),c=await this._resolveFileSystemPaths([...i.allowRead??[],...m.readonlyPaths]),u=await this._resolveFileSystemPaths(i.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 i=await this._resolveFileSystemPath(t);return e==="write"?this._os===1&&this._matchesAnyFileSystemPath(i,r.denyReadPaths)||this._matchesAnyFileSystemPath(i,r.denyWritePaths??[])?!1:this._matchesAnyFileSystemPath(i,r.allowWritePaths):this._matchesAnyFileSystemPath(i,[...r.allowReadPaths,...r.allowWritePaths])?!0:!this._matchesAnyFileSystemPath(i,r.denyReadPaths)}_matchesAnyFileSystemPath(e,t){return e.some(r=>t.some(i=>this._matchesFileSystemPath(r,i)))}_matchesFileSystemPath(e,t){let r=this._normalizeFileSystemAccessPath(e),i=this._normalizeFileSystemAccessPath(t,!0),s=this._os===1;return this._containsGlobPattern(i)?Eg(i,r,{ignoreCase:s}):this._fileSystemPathExtUri.isEqualOrParent(this._toFileSystemAccessUri(r),this._toFileSystemAccessUri(i))}_toFileSystemAccessUri(e){return h.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 i=r[t];return Array.isArray(i)?i.filter(s=>typeof s=="string"):[]}_mergeAdditionalSandboxConfigProperties(e,t){for(let[r,i]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(e,r)){e[r]=i;continue}let s=e[r];this._isObjectForSandboxConfigMerge(s)&&this._isObjectForSandboxConfigMerge(i)&&this._mergeAdditionalSandboxConfigProperties(s,i)}}_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?ye: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(i=>this._getUriPath(i));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??[],...qm(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),...r,...this._getSandboxRuntimeReadPaths(),...await this._getWorkspaceStorageReadPaths(),...t])]}async _resolveFileSystemPaths(e){let t=await Promise.all((e??[]).map(i=>this._resolveFileSystemPath(i))),r=new Set;return t.flat().filter(i=>{let s=this._getFileSystemPathComparisonKey(i);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)),i=r?this._getUriPath(r):void 0;return i&&i!==t?[t,i]:[t]}catch{return[t]}}_isAbsoluteFileSystemPath(e){return(this._os===1?ye: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})??h.file(e)}_toWindowsFileSystemResource(e){let t=e.replace(/\\/g,"/");if(/^\/\/[^/]/.test(t)){let r=t.indexOf("/",2);return r===-1?h.from({scheme:"file",authority:t.slice(2),path:"/"}):h.from({scheme:"file",authority:t.slice(2,r),path:t.slice(r)||"/"})}return/^[a-zA-Z]:($|\/)/.test(t)?h.from({scheme:"file",path:`/${t[0].toLowerCase()}${t.slice(1)}`}):/^\/[a-zA-Z]:($|\/)/.test(t)?h.from({scheme:"file",path:`/${t[1].toLowerCase()}${t.slice(2)}`}):h.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?ye.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":Zv(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)}};En=R([C(1,Pe),C(2,M),C(3,$m)],En);var E5="tmp",Vb=class{constructor(n,e,t,r,i,s){this._sessionId=n;this._workingDirectory=e;this._environmentService=t;this._productService=r;this._agentConfigurationService=i;this.onDidChangeRoots=ee.None;this._sandboxHelper=s,this.onDidChangeSandboxSettings=this._agentConfigurationService.onDidRootConfigChange}async getOS(){return Mt}async getRuntimeInfo(){let n=oe(Lt.asFileUri("").path),e=!!process.versions.electron,t=aP();return{appRoot:n,execPath:process.execPath,runAsNode:e,nativeModulesDir:t}}async getUserHome(){return this._environmentService.userHome}async getSandboxTempDir(){let n=this._environmentService.userHome;if(!n)return;let e=h.joinPath(n,this._productService.dataFolderName,E5),r=`agenthost_${A5("sha256").update(this._sessionId).digest("hex").substring(0,16)}`;return h.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,i){return this._sandboxHelper.buildWindowsMxcSandboxPayload(n,e,t,r,i)}getSandboxSetting(n){let e=RR[n];return e===void 0?void 0:this._agentConfigurationService.getRootValue(kr,"sandbox")?.[e]}};function nE(o,n,e,t,r,i,s){let a=new Vb(i,s,n,e,t,r);return o.createInstance(En,a)}var k5="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.",xo=class extends w{constructor(e,t,r,i,s,a,l,d,c){super();this._sessionUri=e;this.workingDirectory=t;this._terminalManager=r;this._logService=i;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 A);this.onDidAssociateTerminal=this._onDidAssociateTerminal.event;this._register(N(()=>{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()??O(),t=nE(this._instantiationService,this._environmentService,this._productService,this._agentConfigurationService,this._sandboxHelper,e,this.workingDirectory);this._register(t),this._register(N(()=>{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,i){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=O(),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:i??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 Y,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 i=r.shellType==="bash"?"Bash":"PowerShell";this._onDidAssociateTerminal.fire({toolCallId:e,terminalUri:r.terminalUri,displayName:i})}}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}};xo=R([C(2,Dr),C(3,M),C(4,xe),C(5,Ac),C(6,ft),C(7,He),C(8,Fm)],xo);function Ro(o){return{textResultForLlm:o,resultType:"success"}}function kn(o,n){return{textResultForLlm:o,resultType:"failure",error:n}}function ou(o,n){return{toolResult:o,keepShellBusy:n?.keepShellBusy}}function D5(o,n){switch(o.status){case"completed":{let e=o.exitCode??0,t=`Exit code: ${e}
${o.output}`;return ou(e===0?Ro(t):kn(t))}case"shellExited":return ou(kn(`Shell exited with code ${o.exitCode}
${o.output}`));case"timeout":return ou(kn(`Command timed out after ${Math.round(n/1e3)}s. Partial output:
${o.output}`,"timeout"));case"background":return ou(Ro("The user chose to continue this command in the background. The terminal is still running."),{keepShellBusy:!0});case"altBuffer":return ou(kn(k5,"alternateBuffer"),{keepShellBusy:!0})}}async function M5(o,n,e,t,r){let i=D5(await xg(o,n,e,t,r),e);return{...i,toolResult:{...i.toolResult,textResultForLlm:`Shell ID: ${o.id}
${i.toolResult.textResultForLlm}`}}}async function rE(o,n,e,t){let r=await o.getResolvedExecutable(),i=Rg(r),s=o.getOrCreateSandboxEngine(),a=await s.isEnabled(),l=a?s.getResolvedNetworkDomains():void 0,d={name:i,description:i==="bash"?Rf(r)?U5(a,l):N5(a,l):L5(i,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??wg,T=await o.getOrCreateShell(i,I.toolCallId,I.toolCallId),P=!0;try{let X=b.command;if(a){if(b.requestUnsandboxedExecution&&!s.areUnsandboxedCommandsAllowed())return kn("Unsandboxed execution is disabled by the chat.agent.sandbox.allowUnsandboxedCommands setting.","unsandboxed_disabled");let x=async H=>{if(!t){let q=H?.join(", ")??"(unknown)";return kn(`Command requires approval to run outside the sandbox. Blocked domains: ${q}. 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:H})},E=await s.wrapCommand(b.command,b.requestUnsandboxedExecution,r,T.object.shellType==="bash"?o.workingDirectory:void 0);if(b.requestUnsandboxedExecution&&!E.isSandboxWrapped){let H=await x(E.blockedDomains);if(typeof H!="boolean")return H;if(!H){let G=E.blockedDomains?.join(", ")??"(none)";return kn(`User declined to run command outside the sandbox. Blocked domains: ${G}.`,"sandbox_blocked")}}if(E.requiresUnsandboxConfirmation){let H=await x(E.blockedDomains);if(typeof H!="boolean")return H;if(!H){let G=E.blockedDomains?.join(", ")??"(unknown)";return kn(`User declined to run command outside the sandbox. Blocked domains: ${G}.`,"sandbox_blocked")}E=await s.wrapCommand(b.command,!0,r,T.object.shellType==="bash"?o.workingDirectory:void 0)}X=E.command}let k=await M5(T.object,X,_,n,e);return k.keepShellBusy&&(P=!1,o.holdShellUntilCommandFinishes(T.object)),k.toolResult}finally{P&&T.dispose()}}},c={name:`read_${i}`,description:`Read the latest output from a running ${i} 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=o.listShells(),_=b.shell_id?o.getShell(b.shell_id):I[I.length-1];if(!_)return kn("No active shell found.","no_shell");let T=n.getContent(_.terminalUri);return Ro(T?ai(T):"(no output)")}},u={name:`write_${i}`,description:`Send input to a running ${i} 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=o.listShells(),_=I[I.length-1];return _?(await n.sendText(_.terminalUri,b.command,{shouldExecute:!1}),Ro("Input sent to shell.")):kn("No active shell found.","no_shell")}},p={name:i==="bash"?"bash_shutdown":`${i}_shutdown`,description:`Stop a ${i} 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 o.shutdownShell(b.shell_id)?Ro("Shell stopped."):kn("Shell not found.","not_found");let I=o.listShells(),_=I[I.length-1];return _?(o.shutdownShell(_.id),Ro("Shell stopped.")):kn("No active shell to stop.","no_shell")}},m={name:`list_${i}`,description:`List active ${i} shell instances.`,parameters:{type:"object",properties:{}},overridesBuiltInTool:!0,skipPermission:!0,handler:()=>{let b=o.listShells();if(b.length===0)return Ro("No active shells.");let I=b.map(_=>{let T=n.getExitCode(_.terminalUri),P=T!==void 0?`exited (${T})`:"running";return`- ${_.id}: ${_.shellType} [${P}]`});return Ro(I.join(`
`))}},v=i==="bash"?"powershell":"bash",y=`This tool is disabled because the configured shell is ${r}. Use the \`${i}\` tool instead.`;return[d,c,u,p,m,{name:v,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:()=>kn(y,"wrong_shell")}]}function O5(o){return o.endsWith("System32\\WindowsPowerShell\\v1.0\\powershell.exe")}function L5(o,n,e,t){let r=O5(n),i=[`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_${o} to send commands or input to a terminal session.`];return e&&i.push(...oE(t)),i.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_${o}. Never send multiple answers in a single send.`,`- After each send, call read_${o} to read the next prompt before sending the next answer.`,"- Continue one prompt at a time until the command finishes."),i.join(`
`)}function oE(o){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(o){let e=new Set(o.deniedDomains),t=o.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(", ")}`),o.deniedDomains.length>0&&n.push(`- The following domains are explicitly blocked in the sandbox: ${o.deniedDomains.join(", ")}`)}return n}function iE(o,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_${o} to send commands or input to a terminal session.`];return n&&t.push(oE(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_${o}. Never send multiple answers in a single send.
- After each send, call read_${o} to read the next prompt before sending the next answer.
- Continue one prompt at a time until the command finishes.`),t.join("")}function N5(o,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.",iE("bash",o,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 U5(o,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.",iE("bash",o,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 F5}from"child_process";function lE(o){let n={};for(let e of o)n[e.name]=cE(e.name,e.configuration);return n}function dE(o){let n={};for(let[e,t]of Object.entries(o))H5(t)&&(n[e]=cE(e,t));return n}function H5(o){if(!o||typeof o!="object")return!1;let n=o;return n.type==="stdio"?typeof n.command=="string":n.type==="http"?typeof n.url=="string":!1}function cE(o,n){return n.type==="stdio"?{type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:$5(n.env)},...n.cwd&&{cwd:n.cwd}}:{type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}function $5(o){let n={};for(let[e,t]of Object.entries(o))t!==null&&(n[e]=String(t));return n}async function sE(o,n){let e=[];for(let t of o)try{let i=(await n.readFile(t.uri)).value.toString(),s=ml(i),a=s?.getStringValue("name")?.trim()||t.name,l=s?.getStringValue("description"),d=s?.getStringArrayValue("tools"),c=s?.body??i,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 uE(o,n,e){let t=o.filter(i=>!i.pluginDir||i.pluginDir.scheme!==ne.file),r=await sE(t.flatMap(i=>i.agents),e);if(n&&!r.some(i=>i.name===n)){let i=o.flatMap(s=>s.agents).filter(s=>s.name===n);for(let s of await sE(i,e))r.some(a=>a.name===s.name)||r.push(s)}return r}function jb(o){let n=new Map,e=t=>{n.has(t.id)||n.set(t.id,t)};for(let t of o){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 pE(o){return gE(o)}function fE(o){return gE(o)}function gE(o){let n=new Set,e=[];for(let t of o){let r=oe(t.uri.fsPath);n.has(r)||(n.add(r),e.push(r))}return e}function W5(o,n){return n===1&&o.windows?o.windows:n===2&&o.osx?o.osx:n===3&&o.linux?o.linux:o.command}function iu(o,n){let e=W5(o,Mt);if(!e)return Promise.resolve("");let t=(o.timeout??30)*1e3,r=o.cwd?.fsPath;return new Promise((i,s)=>{let a=Mt===1,c=F5(a?"cmd.exe":"/bin/sh",a?["/c",e]:["-c",e],{cwd:r,env:{...process.env,...o.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?i(u):s(new Error(`Hook command exited with code ${m}: ${p||u}`))})})}async function aE(o,n){if(!o)return;let e=JSON.stringify(n);for(let t of o)try{let r=await iu(t,e);if(r.trim())try{let i=JSON.parse(r);if(i&&typeof i=="object")return i}catch{}}catch{}}var q5={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function mE(o,n){let e=new Map;for(let c of o){let u=q5[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),aE(r,c)));let i=e.get("onPostToolUse");(i?.length||n)&&(t.onPostToolUse=async c=>(await n?.onPostToolUse(c),aE(i,c)));let s=e.get("onUserPromptSubmitted");s?.length&&(t.onUserPromptSubmitted=async c=>{let u=JSON.stringify(c);for(let p of s)try{await iu(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 iu(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 iu(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 iu(p,u)}catch{}}),t}function hE(o,n){let e=t=>JSON.stringify(t.map(r=>({hooks:r.hooks.map(i=>({type:i.type,commands:i.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(i=>({name:i.name,configuration:i.configuration})),skills:r.skills.map(i=>({uri:i.uri.toString(),name:i.name})),agents:r.agents.map(i=>({uri:i.uri.toString(),name:i.name})),instructions:r.instructions.map(i=>({uri:i.uri.toString(),name:i.name}))})));return e(o)===e(n)}var B5=!1;function su(o,n){if(!n||o==="win32"&&!B5)return;let e=o==="win32"&&n["enabled.windows"]!==void 0?n["enabled.windows"]:n.enabled;if(e!=="on"&&e!=="allowNetwork")return;let t=o==="win32"?n["fileSystem.windows"]:o==="darwin"?n["fileSystem.mac"]:n["fileSystem.linux"],r=t&&typeof t=="object"?t:{},i=new Set(r.denyRead??[]),s=new Set,a=new Set;for(let S of r.denyWrite??[])i.has(S)||s.add(S);for(let S of r.allowWrite??[])!i.has(S)&&!s.has(S)&&a.add(S);for(let S of r.allowRead??[])!i.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,v=!d&&c&&p?.length?[...p]:void 0,y=d||!!m||!!v;return{enabled:!0,allowBypass:!0,userPolicy:{filesystem:{...a.size?{readwritePaths:[...a]}:{},...s.size?{readonlyPaths:[...s]}:{},...i.size?{deniedPaths:[...i]}:{}},network:{allowOutbound:y,...y&&m?{allowedHosts:m}:{},...y&&v?{blockedHosts:v}:{}}}}}var Kb="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.",yE=["<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`).","- If a file path has spaces, wrap the target in angle brackets: [foo bar.ts](</path/to/foo bar.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(`
`),au={mode:"customize",sections:{identity:{action:"replace",content:Kb}}},Gb=["<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 vE(o){return{mode:"replace",content:o}}function SE(o){return{mode:"customize",sections:o}}function bE(o,n){if(o.mode==="replace")return o;let e=o.content;return{...o,content:e?`${e}

${n}`:n}}function CE(o){if(o.mode==="replace")return`mode=replace (content length ${o.content.length})`;if(o.mode==="customize"){let n=Object.entries(o.sections??{}).map(([t,r])=>{let i=r?.action;return`${t}:${typeof i=="function"?"transform":i}`}),e=o.content?` +content(length ${o.content.length})`:"";return`mode=customize sections=[${n.join(", ")}]${e}`}return`mode=append (content length ${o.content?.length??0})`}var lu={OpenBrowserPage:"openBrowserPage",ReadPage:"readPage",ScreenshotPage:"screenshotPage",NavigatePage:"navigatePage",ClickElement:"clickElement",TypeInPage:"typeInPage",HoverElement:"hoverElement",DragElement:"dragElement",HandleDialog:"handleDialog",RunPlaywrightCode:"runPlaywrightCode"},IE=Object.values(lu);var z5=IE.filter(o=>o!==lu.OpenBrowserPage),V5=o=>{if(!o(lu.OpenBrowserPage))return;let n=z5.find(o);if(n)return`Use the browser tools (${lu.OpenBrowserPage}, ${n}, etc.) when beneficial for front-end tasks, such as when visualizing or validating UI changes.`},_E=[V5];function j5(o,n=_E){let e=Oo(n.map(t=>t(o)));return e.length>0?e.join(`
`):void 0}function K5(o,n){if(!o)return{action:"append",content:`
${n}`};if(o.action==="remove"||typeof o.action=="function")return o;let e=o.content??"",t=e?`${e}
${n}`:n;switch(o.action){case"append":return{action:"append",content:`
${t}`};case"prepend":return{action:"prepend",content:`${t}
`};default:return{action:o.action,content:t}}}function TE(o,n,e=_E){let t=j5(o,e);return t===void 0?void 0:K5(n,t)}var Jb=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 bE(r,yE)}_resolveModelConfig(n,e){if(!n)return au;let t=this._getContributor(n);if(!t)return au;let r=new t,i=r.resolveFullSystemPrompt?.(n,e);if(i!==void 0)return vE(i);let s=r.resolveSectionOverrides?.(n,e);return s&&Object.keys(s).length>0?SE(s):au}_withUniversalSections(n,e){if(n.mode!=="customize")return n;let t=TE(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}

${Gb}`:Gb;return{...n,content:t}}},Bm=new Jb;function G5(){return{identity:{action:"replace",content:Kb},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 J5(o){return o.id.startsWith("claude-opus-4-8")||o.id.startsWith("claude-opus-4.8")}var Yb=class{static{this.familyPrefixes=[]}static matchesModel(n){return J5(n)}resolveSectionOverrides(n,e){return e.getSetting("opus48Prompt")===!0?G5():void 0}};Bm.registerPrompt(Yb);var Zb="thinkingLevel",jm="contextSize",Y5="contextTier",wE=["low","medium","high","xhigh"],Q5=["default","long_context"];function eC(o){return new Set(o.tools.map(n=>n.name))}function Xb(o){return wE.some(n=>n===o)}function X5(o){return Q5.some(n=>n===o)}function zm(o){if(typeof o!="object"||o===null)return;let n=Object.getOwnPropertyDescriptor(o,"code")?.value;return typeof n=="number"?n:void 0}function Vm(o){if(o instanceof Error)return o.message;if(typeof o=="object"&&o!==null){let n=Object.getOwnPropertyDescriptor(o,"message")?.value;if(typeof n=="string")return n}return String(o)}function Z5(o){if(zm(o)!==-32603)return!1;let n=Vm(o);return!/\b(corrupt|corrupted|invalid|validation|schema|must be|parse|malformed|unexpected token)\b/i.test(n)}function e7(o){return zm(o)===-32603&&/\bCustom agent '.+' not found\b/i.test(Vm(o))}function t7(o,n){if(Xb(n))return n;let e=o?.config?.[Zb];return Xb(e)?e:void 0}function Km(o,n,e,t){let r=n.getRootValue(mn,"reasoningEffortOverride"),i=r||void 0;return i!==void 0&&(Xb(i)?e.info(`[Copilot:${t}] Applying reasoning-effort override '${i}'`):e.warn(`[Copilot:${t}] Ignoring invalid reasoning-effort override '${i}'; expected one of [${wE.join(", ")}]`)),t7(o,i)}function Gm(o,n,e){let t=o?.config?.[Y5];if(X5(t))return t;let r=o?.config?.[jm];if(r===void 0)return e?"long_context":void 0;let i=Number(r);if(!(!Number.isFinite(i)||typeof n!="number"))return i>=n?"long_context":"default"}async function n7(o,n,e,t,r=!1){let i;try{let c=r?n.getModels():void 0;c&&c.length>0?i=[...c]:i=await n.listModels()}catch(c){return t.warn(`[Copilot:${o}] Failed to enumerate BYOK models from renderer bridges`,c),{}}if(i.length===0)return{};let s=new Set;i=i.filter(c=>{let u=`${c.vendor}/${c.id}`;return s.has(u)?!1:(s.add(u),!0)});let a;try{a=await e()}catch(c){return t.warn(`[Copilot:${o}] Failed to start BYOK loopback proxy`,c),{}}let l=[...new Set(i.map(c=>c.vendor))].map(c=>({name:c,type:"openai",wireApi:"completions",baseUrl:a.providerBaseUrl(c),bearerToken:`${a.nonce}.${o}`})),d=i.map(c=>({id:c.id,provider:c.vendor,...c.name!==void 0?{name:c.name}:{},...c.maxContextWindowTokens!==void 0?{maxContextWindowTokens:c.maxContextWindowTokens}:{}}));return t.info(`[Copilot:${o}] Wired ${d.length} BYOK model(s) across ${l.length} provider(s) via loopback proxy ${a.baseUrl}`),{providers:l,models:d}}var xl=class{constructor(n,e,t,r,i,s){this._configurationService=n;this._terminalManager=e;this._logService=t;this._fileService=r;this._byokLmProxyService=i;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);let i=n,s=t;try{let a=new Un;this._logService.trace(`[Copilot:${n.sessionId}] Calling SDK resumeSession...`);let l=await n.client.resumeSession(n.sessionId,t);return this._logService.trace(`[Copilot:${n.sessionId}] SDK resumeSession succeeded after ${a.elapsed()}ms`),await this._applySandboxConfig(l,r,n.sessionId),new Rl(l)}catch(a){let l=a,d=zm(l),c=Vm(l);if(this._logService.warn(`[Copilot:${n.sessionId}] SDK resumeSession failed: code=${d}, message=${c}`),n.resolvedAgentName&&e7(l)){i={...n,resolvedAgentName:void 0},s={...t,agent:void 0},this._logService.warn(`[Copilot:${n.sessionId}] Stored custom agent '${n.resolvedAgentName}' was not found; retrying resume without a custom agent`);try{let p=await i.client.resumeSession(i.sessionId,s);return await this._applySandboxConfig(p,r,n.sessionId),new Rl(p)}catch(p){l=p,this._logService.warn(`[Copilot:${n.sessionId}] SDK resumeSession without custom agent failed: code=${zm(p)}, message=${Vm(p)}`)}}if(!Z5(l))throw l;this._logService.warn(`[Copilot:${n.sessionId}] Resume failed (code=-32603), falling back to createSession with same ID`);let u=await this._createSession({...i,kind:"create",model:i.fallback.model,longContextWindow:i.fallback.longContextWindow,freeLongContext:i.fallback.freeLongContext},s,r);return this._logService.info(`[Copilot:${n.sessionId}] Fallback createSession succeeded`),u}}async _createSession(n,e,t){let r=await n.client.createSession({...e,sessionId:n.sessionId,streaming:!0,model:n.model?.id,reasoningEffort:Km(n.model,this._configurationService,this._logService,n.sessionId),contextTier:Gm(n.model,n.longContextWindow,n.freeLongContext),...n.resolvedAgentName?{agent:n.resolvedAgentName}:{},workingDirectory:n.workingDirectory?.fsPath});return await this._applySandboxConfig(r,t,n.sessionId),new Rl(r)}_computeSandboxConfig(){if(this._configurationService.getRootValue(mn,"enableCustomTerminalTool")!==!0)return su(process.platform,this._configurationService.getRootValue(kr,"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,e){return n7(n,this._byokLmBridgeRegistry,()=>(this._byokProxyHandle||(this._byokProxyHandle=this._byokLmProxyService.start()),this._byokProxyHandle),this._logService,e)}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,n.kind==="resume"),i=this._configurationService.getRootValue(mn,"enableCustomTerminalTool")===!0,s=[];if(i){if(!n.shellManager)throw new Error(`ShellManager is required to launch Copilot session '${n.sessionId}'`);s=await rE(n.shellManager,this._terminalManager,this._logService,S=>e.requestUnsandboxedCommandConfirmation(S))}let a=t.filter(S=>!S.pluginDir||S.pluginDir.scheme!==ne.file),l=await uE(t,n.resolvedAgentName,this._fileService),d=pE(a.flatMap(S=>S.skills)),c=fE(t.flatMap(S=>S.instructions)),u=n.kind==="create"?n.model:n.fallback.model,p=eC(n.snapshot),m={getSetting:S=>this._configurationService.getRootValue(mn,S),hasClientTool:S=>p.has(S),workspaceless:n.workspaceless===!0},v=TR(u,this._configurationService.getRootValue(mn,"modelCapabilityOverrides"));u&&v!==u&&this._logService.info(`[Copilot:${n.sessionId}] Model capability override: routing prompt for '${u.id}' as family '${v?.id}'`);let y=Bm.resolveSystemMessageConfig(v,m);return this._logService.info(`[Copilot:${n.sessionId}] Resolved system message: ${CE(y)}`),this._logService.getLevel()<=1&&this._logService.trace(`[Copilot:${n.sessionId}] System message config: ${JSON.stringify(y,(S,b)=>typeof b=="function"?"[transform fn]":b)}`),{...r,clientName:"vscode",enableMcpApps:!0,enableFileHooks:!0,enableConfigDiscovery:!0,onPermissionRequest:S=>e.handlePermissionRequest(S),onUserInputRequest:(S,b)=>e.handleUserInputRequest(S,b),onElicitationRequest:S=>e.handleElicitationRequest(S),onMcpAuthRequest:(S,b)=>e.handleMcpAuthRequest(S,b),hooks:mE(a.flatMap(S=>S.hooks),{onPreToolUse:S=>e.handlePreToolUse(S),onPostToolUse:S=>e.handlePostToolUse(S)}),mcpServers:{...dE(n.snapshot.mcpServers),...lE(a.flatMap(S=>S.mcpServers))},onExitPlanModeRequest:(S,b)=>e.handleExitPlanModeRequest(S,b),workingDirectory:n.workingDirectory?.fsPath,customAgents:l,agent:n.resolvedAgentName,skillDirectories:d,instructionDirectories:c,systemMessage:y,pluginDirectories:Oo(t.map(S=>S.pluginDir)).filter(S=>S.scheme===ne.file).map(S=>S.fsPath),tools:[...s,...e.createClientSdkTools(),...e.createServerSdkTools()],gitHubToken:n.githubToken,infiniteSessions:{enabled:!0},remoteSession:this._configurationService.getRootValue(Ut,Vd)===!0?"export":void 0,enableManagedSettings:!0}}};xl=R([C(0,He),C(1,Dr),C(2,M),C(3,Pe),C(4,Um),C(5,vi)],xl);var mt=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 K);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 Jm(o){let n=o.data,e=n.kind;if(r7(n.content))switch(e.type){case"shell_completed":case"shell_detached_completed":{let r=e.description;return{messageText:r?f(2244,null,r):f(2243,null),startsTurn:!0}}case"agent_completed":return{messageText:e.status==="failed"?f(2239,null,e.agentId):f(2238,null,e.agentId),startsTurn:!0};case"agent_idle":return{messageText:f(2240,null,e.agentId),startsTurn:!0};case"new_inbox_message":return{messageText:f(2242,null,e.senderName),startsTurn:!1};case"instruction_discovered":return{messageText:f(2241,null,e.description??e.sourcePath),startsTurn:!1};default:return}}function r7(o){let n=o.trim();return(/^<system_notification>\s*([\s\S]*?)\s*<\/system_notification>$/.exec(n)?.[1]??n).trim()}var RE=new Set(["agent","app","changelog","context","copy","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"]),o7=300;function xE(o){let n=/^\/([^\s/]+)(?:$|\s+([\s\S]*))/.exec(o);if(!n)return;let e=n[2]??"";return{command:n[1],rest:e.trim(),rawRest:e}}var Ym=class{constructor(n,e,t=o7){this.copilotcliId=n;this._sessionInfo=e;this._runtimeSlashCommandCompletionWaitMs=t;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){if(D.provider(n.channel)!==this.copilotcliId)return[];let t=Ig(n.text,n.offset),r=Cg(n.text,n.offset),i=r??t,s=!r&&!!t;if(!i)return[];let a=D.id(n.channel),l=i.typed;return await this._getRuntimeSlashCommandCompletionInfo(a,l,i,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 i of r.children)i.type==="skill"&&e.add(this._toSlashCommandCandidate(r,i));return e}_toSlashCommandCandidate(n,e){let t=e.name;return n.type==="plugin"&&!i7(n)&&e.name!==n.name&&(t=`${n.name}:${e.name}`),t}async _getRuntimeSlashCommandCompletionInfo(n,e,{rangeStart:t,rangeEnd:r},i){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||i&&p.kind!=="skill"||p.kind==="skill"&&a.has(p.name)||RE.has(p.name)||p.aliases?.some(y=>RE.has(y))||!d&&p.name==="rubber-duck"||e.length>0&&!p.name.toLowerCase().startsWith(l)&&!p.aliases?.some(y=>y.toLowerCase().startsWith(l)))continue;let m=[];(p.input?.hint||!p.input?.choices?.length)&&m.push({name:"",description:p.description,argumentHint:p.input?.hint}),p.input?.choices?.length&&m.push(...p.input.choices),Array.from(new Set([p.name].concat(p.aliases??[]))).filter(y=>!u.has(y)).forEach(y=>{m.forEach(S=>{let b=`/${y}${S.name?" "+S.name:""} `,I=S.description??p.description,_=S.argumentHint;u.add(y),c.push({insertText:b,rangeStart:t,rangeEnd:r,attachment:{type:"simple",label:b,_meta:Sg({command:p.name,...I!==void 0?{description:I}:{},..._!==void 0?{argumentHint:_}:{}})}})})})}return c.sort((p,m)=>p.insertText.localeCompare(m.insertText))}};function i7(o){return o.uri.startsWith(Kc+":")}function AE(o){if(!Array.isArray(o)||o.length!==2)return;let[n,e]=o;if(!(!Number.isInteger(n)||!Number.isInteger(e))&&!(n<0)&&!(e!==-1&&e<n))return{startLine:n,endLine:e}}function PE(o){let n=o?.agent_id;return typeof n=="string"&&n.length>0?n:void 0}var s7=[/^\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 tC(o){let n=typeof o=="string"?o:o?.input??o?.patch;if(typeof n!="string"||n.length===0)return[];let e=new Set,t=[];for(let r of n.split(`
`))for(let i of s7){let s=i.exec(r);if(s){let a=s[1];a&&!e.has(a)&&(e.add(a),t.push(a));break}}return t}var a7=new Set(["edit","str_replace","insert","create","apply_patch","git_apply_patch"]),l7=new Set(["edit","str_replace","insert","create"]);function Pl(o,n){return a7.has(o)?!0:o==="str_replace_editor"?n!==void 0&&l7.has(n):!1}function Qm(o){if(typeof o=="string"){try{o=JSON.parse(o)}catch{return tC(o)}if(typeof o=="string")return tC(o)}if(!o||typeof o!="object")return[];let n=o;if(typeof n.input=="string"||typeof n.patch=="string")return tC(n);let e=o;return typeof e.path=="string"?[e.path]:[]}var du=new Set(["bash","powershell"]),nC=new Set(["write_bash","write_powershell"]),EE=new Set(["read_bash","read_powershell"]),d7=new Set(["task"]),c7=new Set(["grep","rg","glob"]),u7=new Set(["report_intent","skill"]);function Xm(o){return u7.has(o)}function kE(o){return o==="list_agents"||o==="read_agent"||o==="write_agent"}function Al(o){return o==="task_complete"}function p7(o,n){if(n&&n.trim().length>0)return n;let e=o?.summary;return typeof e=="string"&&e.trim().length>0?e:void 0}function cu(o,n){let e=p7(o,n);if(e)return`

`+f(2318,null,e)}function uu(o){return du.has(o)}function pu(o,n){if(uu(o)&&typeof n?.description=="string"&&n.description.length>0)return n.description}function hr(o,n){return o.length>n?o.substring(0,n-3)+"...":o}function Br(o){let n=h.file(o);return`[${fs(ve(n))}](${n})`}function DE(o){return new gm().appendLink(o,hr(o,80)).value}function _e(o){return{markdown:o}}function yr(o){let n=mr(o,void 0)?.displayName;if(n!==void 0)return n;switch(o){case"str_replace_editor":case"edit":case"str_replace":case"insert":return f(2325,null);case"create":return f(2323,null);case"view":return f(2339,null);case"bash":case"powershell":return f(2347,null);case"read_bash":case"read_powershell":return f(2341,null);case"write_bash":return f(2360,null);case"write_powershell":return f(2361,null);case"stop_bash":case"stop_powershell":case"bash_shutdown":case"powershell_shutdown":return f(2351,null);case"list_bash":case"list_powershell":return f(2332,null);case"grep":case"rg":case"glob":return f(2345,null);case"search_code_subagent":return f(2346,null);case"apply_patch":return f(2319,null);case"git_apply_patch":return f(2337,null);case"codeql_checker":return f(2321,null);case"code_review":return f(2322,null);case"reply_to_comment":return f(2342,null);case"think":return f(2355,null);case"report_intent":return f(2343,null);case"report_progress":return f(2344,null);case"web_search":return f(2358,null);case"web_fetch":return f(2328,null);case"update_todo":return f(2357,null);case"show_file":return f(2348,null);case"fetch_copilot_cli_documentation":return f(2327,null);case"propose_work":return f(2338,null);case"task_complete":return f(2354,null);case"ask_user":return f(2320,null);case"skill":return f(2330,null);case"task":return f(2353,null);case"list_agents":return f(2331,null);case"read_agent":return f(2340,null);case"exit_plan_mode":return f(2326,null);case"sql":return f(2350,null);case"lsp":return f(2333,null);case"create_pull_request":return f(2324,null);case"gh-advisory-database":return f(2329,null);case"store_memory":return f(2352,null);case"parallel_validation":return f(2336,null);case"write_agent":return f(2359,null);case"mcp_reload":return f(2334,null);case"mcp_validate":return f(2335,null);case"tool_search_tool_regex":return f(2356,null);default:return o}}function Ao(o,n,e){let t=mr(o,e)?.invocationMessage;if(t!==void 0)return t;if(du.has(o)){let r=e;if(r?.command){let i=r.command.split(`
`)[0];return _e(f(2304,null,ot(hr(i,80))))}return f(2303,null,n)}if(nC.has(o)){let r=e;if(r?.command){let i=r.command.split(`
`)[0];return _e(f(2317,null,ot(hr(i,80))))}return f(2316,null)}if(EE.has(o))return f(2302,null);switch(o){case"view":{let r=e;if(r?.path){let i=Br(r.path),s=AE(r.view_range);return s?s.endLine===-1?_e(f(2311,null,i,s.startLine)):s.endLine!==s.startLine?_e(f(2313,null,i,s.startLine,s.endLine)):_e(f(2312,null,i,s.startLine)):_e(f(2310,null,i))}return f(2309,null)}case"edit":{let r=e;return r?.path?_e(f(2293,null,Br(r.path))):f(2292,null)}case"create":{let r=e;return r?.path?_e(f(2291,null,Br(r.path))):f(2290,null)}case"grep":{let r=e;return r?.pattern?_e(f(2298,null,ot(hr(r.pattern,80)))):f(2297,null)}case"rg":{let r=e;return r?.pattern?_e(f(2298,null,ot(hr(r.pattern,80)))):f(2297,null)}case"glob":{let r=e;return r?.pattern?_e(f(2296,null,ot(hr(r.pattern,80)))):f(2295,null)}case"apply_patch":case"git_apply_patch":{let r=Qm(e);return r.length===1?_e(f(2300,null,Br(r[0]))):r.length>1?_e(f(2301,null,r.map(Br).join(", "))):f(2299,null)}case"sql":return e?.description||f(2307,null);case"web_fetch":{let r=e;return r?.url?_e(f(2314,null,DE(r.url))):f(2315,null)}case"exit_plan_mode":return f(2294,null);case"task":return f(2308,null);case"list_agents":case"read_agent":case"write_agent":return fu(o,n,e,!0);default:return n}}function fu(o,n,e,t,r){if(!t)return f(2261,null,n);let i=mr(o,e,{text:r,success:t})?.pastTenseMessage;if(i!==void 0)return i;if(du.has(o)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return _e(f(2274,null,ot(hr(a,80))))}return f(2273,null,n)}if(nC.has(o)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return _e(f(2289,null,ot(hr(a,80))))}return f(2288,null)}if(EE.has(o))return f(2272,null);switch(o){case"view":{let s=e;if(s?.path){let a=Br(s.path),l=AE(s.view_range);return l?l.endLine===-1?_e(f(2281,null,a,l.startLine)):l.endLine!==l.startLine?_e(f(2283,null,a,l.startLine,l.endLine)):_e(f(2282,null,a,l.startLine)):_e(f(2280,null,a))}return f(2279,null)}case"edit":{let s=e;return s?.path?_e(f(2259,null,Br(s.path))):f(2258,null)}case"create":{let s=e;return s?.path?_e(f(2257,null,Br(s.path))):f(2256,null)}case"grep":{let s=e;return s?.pattern?_e(f(2265,null,ot(hr(s.pattern,80)))):f(2264,null)}case"rg":{let s=e;return s?.pattern?_e(f(2265,null,ot(hr(s.pattern,80)))):f(2264,null)}case"glob":{let s=e;return s?.pattern?_e(f(2263,null,ot(hr(s.pattern,80)))):f(2262,null)}case"apply_patch":case"git_apply_patch":{let s=Qm(e);return s.length===1?_e(f(2268,null,Br(s[0]))):s.length>1?_e(f(2269,null,s.map(Br).join(", "))):f(2267,null)}case"sql":return e?.description||f(2277,null);case"web_fetch":{let s=e;return s?.url?_e(f(2284,null,DE(s.url))):f(2285,null)}case"exit_plan_mode":return f(2260,null);case"task":return f(2278,null);case"list_agents":return f(2266,null);case"read_agent":{let s=PE(e);return s?_e(f(2270,null,ot(s))):f(2271,null)}case"write_agent":{let s=PE(e);return s?_e(f(2286,null,ot(s))):f(2287,null)}default:return n}}function f7(o,n){if(o)return`synth-skill-${o}`;let e=n.path??n.name;return`synth-skill-${gn(e).toString(16)}`}function Zm(o,n){let e=f7(n,o),t=f(2349,null),r=fs(o.name),i=o.path?`[${r}](${h.file(o.path)})`:void 0,s=i?_e(f(2305,null,i)):f(2306,null,o.name),a=i?_e(f(2275,null,i)):f(2276,null,o.name);return{toolCallId:e,toolName:"skill",displayName:t,invocationMessage:s,pastTenseMessage:a}}function gu(o,n,e){if(!(!n&&!e)){if(du.has(o)||nC.has(o)){let t=n,r=t?.command??t?.args;return typeof r=="string"?r:typeof r=="object"&&r!==null&&he(r,{command:!0})?r.command:e}switch(o){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 mu(o){if(du.has(o))return"terminal";if(d7.has(o))return"subagent";if(c7.has(o))return"search"}function eh(o){if(!o)return{};let n=typeof o.agent_type=="string"&&o.agent_type.length>0?o.agent_type:void 0,e=typeof o.description=="string"&&o.description.length>0?o.description:void 0;return{agentName:n,description:e}}function th(o){switch(o){case"powershell":case"write_powershell":case"read_powershell":return"powershell";default:return"shellscript"}}function Po(o){try{return JSON.stringify(o)}catch{return}}function bi(o){return typeof o=="string"?o:void 0}function ME(o,n,e){let t=bi(o.path)??bi(o.fileName),r=bi(o.fullCommandText),i=bi(o.intention),s=bi(o.serverName),a=bi(o.toolName),l=o.requestSandboxBypass?f(2251,null):f(2252,null);switch(o.kind){case"shell":{let d=r?{command:r}:void 0;Ss("bash",d,n);let c=typeof d?.command=="string"?d.command:r;return{confirmationTitle:l,invocationMessage:i??Ao("bash",yr("bash"),c?{command:c}:void 0),toolInput:c,permissionKind:"shell",permissionPath:t}}case"custom-tool":{let d=typeof o.args=="object"&&o.args!==null?o.args:void 0,c=bi(o.toolName);if(d&&c&&uu(c)&&typeof d.command=="string"){Ss(c,d,n);let u=d.command;return{confirmationTitle:l,invocationMessage:Ao(c,yr(c),{command:u}),toolInput:u,permissionKind:"shell",permissionPath:t}}return{confirmationTitle:f(2247,null),invocationMessage:_e(f(2246,null,ot(a??o.kind))),toolInput:Po(d||o),permissionKind:o.kind,permissionPath:t}}case"write":{let d=e?"create":"edit";return{confirmationTitle:e?f(2245,null):f(2255,null),invocationMessage:Ao(d,yr(d),t?{path:t}:void 0),toolInput:Po(t?{path:t}:o)??void 0,permissionKind:"write",permissionPath:t}}case"mcp":{let d=a??f(2248,null);return{confirmationTitle:s?f(2249,null,s):f(2247,null),invocationMessage:s?`${s}: ${d}`:d,toolInput:Po({serverName:s,toolName:a})??void 0,permissionKind:"mcp",permissionPath:t}}case"read":return{confirmationTitle:f(2250,null),invocationMessage:Ao("view",yr("view"),t?{path:t}:void 0),permissionKind:"read",permissionPath:t};case"url":{let d=bi(o.url),c=d?URL.canParse(d)?new URL(d).href:d:void 0;return{confirmationTitle:f(2254,null),invocationMessage:_e(f(2253,null)),toolInput:c?JSON.stringify({url:c}):void 0,permissionKind:"url"}}default:return{confirmationTitle:f(2247,null),invocationMessage:_e(f(2246,null,ot(a??o.kind))),toolInput:Po(o)??void 0,permissionKind:o.kind,permissionPath:t}}}function OE(o){try{return JSON.stringify(o)}catch{return}}function g7(o){if(o.type!=="user.message")return!1;let n=o.data.source;return!!n&&n.toLowerCase()!=="user"}function rC(o,n){for(let e of n??[])e.type==="shell_exit"&&o.push({type:"terminalComplete",exitCode:e.exitCode,...e.cwd!==void 0?{cwd:h.file(e.cwd).toString()}:{},...e.outputPreview!==void 0?{preview:e.outputPreview}:{},...e.outputTruncated!==void 0?{truncated:e.outputTruncated}:{}})}function hu(o,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:o,message:t,responseParts:[],pendingTools:new Map}}function LE(o,n,e,t){if(Xm(o))return;let r=n!==void 0?OE(n):void 0,i;if(r)try{i=JSON.parse(r)}catch{}let a=(Ss(o,i,t)?OE(i):void 0)??r,l=mu(o),d=l==="subagent"?eh(i):void 0,c=yr(o);return{toolName:o,displayName:c,invocationMessage:Ao(o,c,i),toolInput:gu(o,i,a),toolKind:l,language:l==="terminal"?th(o):void 0,intention:pu(o,i),subagentAgentName:d?.agentName,subagentDescription:d?.description,parameters:i,parentToolCallId:e}}function NE(o,n){return{id:o.id,message:o.message,responseParts:o.responseParts,usage:void 0,state:n}}async function FE(o,n,e,t=void 0){let r=t instanceof h?t:t?.workingDirectory,i=t instanceof h?void 0:t?.model,s=t instanceof h?void 0:t?.agent,a=new Map,l=[],d=new Map,c=new Map,u=(q,V)=>(q?c.get(q):void 0)??V;for(let q of e)if(q.type==="subagent.started"&&q.agentId&&c.set(q.agentId,q.data.toolCallId),q.type==="tool.execution_complete"&&d.set(q.data.toolCallId,q.data),q.type==="tool.execution_start"){let V=q.data,ge=u(q.agentId,V.parentToolCallId),$=LE(V.toolName,V.arguments,ge,r);if(!$)continue;a.set(V.toolCallId,$);let U=Ve($.parameters?.command)?$.parameters.command:void 0;Pl(V.toolName,U)&&l.push(V.toolCallId)}let p;if(n&&l.length>0)try{let q=await n.getFileEdits(l);if(q.length>0){p=new Map;for(let V of q){let ge=p.get(V.toolCallId);ge||(ge=[],p.set(V.toolCallId,ge)),ge.push(V)}}}catch{}let m=o.toString(),v=[],y=new Map,S=new Map,b=new Map,I=new Map,_,T="cancelled",P=!1,X=!1,k=()=>{_&&(v.push(NE(_,T)),_=void 0,T="cancelled",P=!1)},x=q=>{let V=y.get(q);if(!V){S.delete(q);return}y.delete(q);let ge=S.get(q)??"complete";if(S.delete(q),V.responseParts.length===0)return;let $=b.get(q)??[];$.push(NE(V,ge)),b.set(q,$)},E=q=>{let V=y.get(q);return V||(V=hu(O(),""),y.set(q,V),S.has(q)||S.set(q,"complete")),V},H=q=>q?E(q):_;for(let q of e)switch(q.type){case"assistant.turn_start":q.agentId||(X=!0);break;case"assistant.turn_end":q.agentId||(X=!1);break;case"session.model_change":{i={id:q.data.newModel};break}case"subagent.deselected":{q.agentId||(s=void 0);break}case"user.message":{if(g7(q))continue;let V=q.data,ge=V.interactionId??"",$=V.content??"",U=m7(V.attachments),B=u(q.agentId,void 0);if(B){let z=E(B);$&&z.responseParts.push({kind:"markdown",id:O(),content:$}),U?.length&&(z.message={...z.message,attachments:U})}else{k();let z=q.id??ge;_=hu(z,$,{attachments:U,model:i,agent:s})}break}case"assistant.message":{let V=q.data,ge=V.messageId??V.interactionId??"",$=V.content??"",U=V.reasoningText,B=!!V.toolRequests&&V.toolRequests.length>0,z=u(q.agentId,V.parentToolCallId);if(!$&&!U&&!B){!z&&_&&!P&&(T="complete");break}let J=q.id??ge,Z=H(z)??(_=hu(J,""));U&&Z.responseParts.push({kind:"reasoning",id:O(),content:U}),$&&Z.responseParts.push({kind:"markdown",id:O(),content:$}),!z&&Z===_&&!P&&(T=B?"cancelled":"complete"),V.toolRequests?.length&&G(Z,V.toolRequests,z);break}case"system.notification":{let V=Jm(q);if(!V)break;X&&_?_.responseParts.push({kind:"systemNotification",content:V.messageText}):V.startsTurn&&(k(),_=hu(q.id,V.messageText,{origin:"systemNotification"}));break}case"subagent.started":{let V=q.data;I.set(V.toolCallId,{agentName:V.agentName,agentDisplayName:V.agentDisplayName,agentDescription:V.agentDescription});break}case"tool.execution_start":{!u(q.agentId,q.data.parentToolCallId)&&_&&(T="cancelled");break}case"tool.execution_complete":{let V=q.data,ge=a.get(V.toolCallId);if(!ge)continue;a.delete(V.toolCallId);let $=u(q.agentId,V.parentToolCallId);if(Al(ge.toolName)){let z=H($);if(!z)continue;let J=cu(ge.parameters,V.error?.message??V.result?.content);J&&z.responseParts.push({kind:"markdown",id:O(),content:J}),!$&&V.success&&z===_&&!P&&(T="complete");continue}let U=H($);if(!U)continue;let B=UE(V,ge,m,p,I.get(V.toolCallId));U.responseParts.push(B),!$&&I.has(V.toolCallId)&&x(V.toolCallId);break}case"skill.invoked":{let V=Zm(q.data,q.id),ge=u(q.agentId,void 0),$=H(ge)??(_=hu(O(),""));!ge&&$===_&&(T="cancelled"),$.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(q.agentId,void 0);V?S.set(V,"cancelled"):(X=!1,_&&(T="cancelled",P=!0));break}default:break}k();for(let q of[...y.keys()])x(q);return{turns:v,subagentTurnsByToolCallId:b};function G(q,V,ge){for(let $ of V){let U=d.get($.toolCallId);if(U&&a.has($.toolCallId))continue;let B=a.get($.toolCallId)??LE($.name,$.arguments,ge,r);if(B){if(Al(B.toolName)){let z=cu(B.parameters,U?.error?.message??U?.result?.content);z&&q.responseParts.push({kind:"markdown",id:O(),content:z}),!ge&&U?.success&&q===_&&!P&&(T="complete");continue}q.responseParts.push(UE(U??{toolCallId:$.toolCallId,success:!0},B,m,p,I.get($.toolCallId)))}}}}function m7(o){if(!o?.length)return;let n=[];for(let e of o){let t=h7(e);t&&n.push(t)}return n.length>0?n:void 0}function h7(o){switch(o.type){case"file":return{type:"resource",uri:h.file(o.path).toString(),label:o.displayName||Te(o.path),displayKind:$p(o.path)?.startsWith("image/")?"image":"document"};case"directory":return{type:"resource",uri:h.file(o.path).toString(),label:o.displayName||Te(o.path),displayKind:"directory"};case"selection":return{type:"resource",uri:h.file(o.filePath).toString(),label:o.displayName,displayKind:"selection",selection:{range:o.selection}};case"blob":{if(typeof o.data!="string")return;if(o.mimeType.startsWith("text/plain"))return{type:"simple",label:o.displayName??"attachment",modelRepresentation:pn(o.data??"").toString()};let n=o.mimeType.startsWith("image/")?"image":void 0;return{type:"embeddedResource",label:o.displayName??"attachment",data:o.data??"",contentType:o.mimeType,displayKind:n}}default:return}}function UE(o,n,e,t,r){let i=o.error?.message??o.result?.content,s=[];i!==void 0&&s.push({type:"text",text:i}),rC(s,o.result?.contents);let a=t?.get(o.toolCallId);if(a)for(let d of a){let c=d.kind==="rename"&&d.originalPath?h.file(d.originalPath).toString():h.file(d.filePath).toString(),u=h.file(d.filePath).toString(),p=d.kind!=="create",m=d.kind!=="delete";s.push({type:"fileEdit",before:p?{uri:c,content:{uri:ni(e,d.toolCallId,d.filePath,"before")}}:void 0,after:m?{uri:u,content:{uri:ni(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:na(e,o.toolCallId),title:r.agentDisplayName,agentName:r.agentName,description:r.agentDescription});let l={status:"completed",toolCallId:o.toolCallId,toolName:n.toolName,displayName:n.displayName,intention:n.intention,invocationMessage:n.invocationMessage,toolInput:n.toolInput,success:o.success,pastTenseMessage:fu(n.toolName,n.displayName,n.parameters,o.success,o.success?i:void 0),content:s.length>0?s:void 0,error:o.error,confirmed:"not-needed",_meta:Rt({toolKind:n.toolKind,language:n.language,subagentDescription:n.subagentDescription,subagentAgentName:n.subagentAgentName})};return{kind:"toolCall",toolCall:l}}var HE="pending-edit-content";function $E(o,n,e){return h.from({scheme:HE,authority:Ko(F.fromString(o)).toString(),path:`/${encodeURIComponent(n)}/${Ko(F.fromString(e))}`})}function WE(o){let n=new tl,e=o.registerProvider(HE,n);return{dispose(){e.dispose(),n.dispose()}}}var Ci=class{constructor(n,e){this.listCommands=n;this._logService=e}async getSlashCommands(n){try{let e=n?.maxWaitMs;return(await this._getRuntimeSlashCommandCatalog(e===void 0?void 0:Math.max(0,e))).commands}catch(e){return this._logService.warn("[Copilot] rpc.commands.list failed",e),[]}}async resolveSlashCommand(n,e=void 0){let t=this._normalizeSlashCommandKey(n);if(!t)return;let r=await this._getRuntimeSlashCommandCatalog(e);return r.byName.get(t)??r.byAlias.get(t)}clearCache(){this._runtimeSlashCommandCache&&(this._runtimeSlashCommandCache=void 0)}async _getRuntimeSlashCommandCatalog(n=void 0){let e=this._runtimeSlashCommandCache??={};if(e.value)return e.value;let t=this._refreshRuntimeSlashCommandCatalog(e);if(n===void 0)return t;let r=await G_(t,n);return r||(e.value?e.value:{commands:[],byName:new Map,byAlias:new Map})}async _refreshRuntimeSlashCommandCatalog(n){if(n.inFlight)return n.inFlight;let e=this.listCommands().then(t=>this._toRuntimeSlashCommandCatalog(t));return n.inFlight=e,e.then(t=>{this._runtimeSlashCommandCache===n&&(n.value=t,n.inFlight=void 0)},()=>{this._runtimeSlashCommandCache===n&&(n.inFlight=void 0,n.value||(this._runtimeSlashCommandCache=void 0))}),e}_toRuntimeSlashCommandCatalog(n){let e=new Map,t=new Map,r=[];for(let i of n){let s=this._normalizeSlashCommandKey(i.name);if(!s)continue;let a=e.get(s);a||(a=i,e.set(s,a),r.push(a));for(let l of i.aliases??[]){let d=this._normalizeSlashCommandKey(l);!d||t.has(d)||t.set(d,a)}}return{commands:r,byName:e,byAlias:t}}_normalizeSlashCommandKey(n){let e=n.trim();return e?(e.charCodeAt(0)===47?e.slice(1):e).toLowerCase():void 0}};Ci=R([C(1,M)],Ci);var y7=".copilot",qE=j(y7,"session-state"),v7="<empty />";function S7(o){if(!o?.length)return v7;let n=o.some(t=>t.type==="image"),e=o.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 b7(o){switch(o){case"autopilot":return{label:f(2221,null),description:f(2220,null)};case"autopilot_fleet":return{label:f(2223,null),description:f(2222,null)};case"interactive":return{label:f(2228,null),description:f(2227,null)};case"exit_only":return{label:f(2225,null),description:f(2224,null)};default:return}}function BE(o){let n=Qe(o.toolArgs)?Reflect.get(o.toolArgs,"command"):void 0;return Ve(n)?n:void 0}function C7(o){switch(o){case"interactive":case"plan":case"autopilot":return o;default:return}}function I7(o,n,e){let t={id:o,title:n.title??o,message:n.description??n.title??o,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=he(n.items,{enum:!0})?n.items.enum.map(i=>({id:i,label:i})):n.items.anyOf.map(i=>({id:i.const,label:i.title}));return{...t,kind:"multi-select",options:r,min:n.minItems,max:n.maxItems}}case"string":{if(he(n,{enum:!0})){let r=n.enumNames,i=n.enum.map((s,a)=>({id:s,label:r?.[a]??s}));return{...t,kind:"single-select",options:i}}if(he(n,{oneOf:!0})){let r=n.oneOf.map(i=>({id:i.const,label:i.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 _7(o,n){if(!n||n.state==="skipped")return;let e=n.value;if(o.type==="boolean")return e.kind==="boolean"?e.value:e.kind==="text"?e.value==="true"?!0:e.value==="false"?!1:void 0:void 0;if(o.type==="number"||o.type==="integer"){if(e.kind==="number")return o.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)?o.type==="integer"?Math.trunc(t):t:void 0}return}if(o.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 T7(o){let n=process.env.XDG_STATE_HOME;return n?j(n,qE):j(o,qE)}var w7=/^(?:\d{10,}-copilot-tool-output-[a-z0-9]{6}|copilot-tool-output-\d{10,}-[a-z0-9]{6})\.txt$/i;function R7(o,n){let e=wn(h.file(o)),t=wn(h.file(n)),r=wn(h.joinPath(e,".."));if(!nt.isEqual(r,t))return!1;let i=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\")),s=i>=0?o.substring(i+1):o;return w7.test(s)}var oC=class{constructor(n,e,t){this.id=n;this.ordinal=e;this.senderClientId=t;this._state="pending";this.copilotUsageTotalNanoAiuByScope=new Map;this.markdownPartIds=new Map;this.reasoningPartIds=new Map;this.toolCounts=new Map;this.toolCallRounds=0;this.totalToolCalls=0;this.parallelToolCallRounds=0;this.parallelToolCallsTotal=0}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"}},El=class extends w{constructor(e,t,r,i,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._permissionRequestAgentIds=new Map;this._bufferedPendingConfirmations=new Map;this._deferredServerToolReady=new Map;this._pendingPermissions=new Map;this._pendingUserInputs=new Map;this._pendingElicitations=new Map;this._pendingPlanReviews=new Map;this._nextTurnOrdinal=0;this._steeringMessagesInFlight=new Set;this._pendingSteeringFlips=new Map;this._pendingClientToolCalls=new mt;this._pendingMcpAuthRequests=new Map;this._pendingEditContentUris=new Map;this._onMcpNotification=this._register(new A);this.onMcpNotification=this._onMcpNotification.event;this._pendingMcpSamplings=new Set;this._hasActivity=!1;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._slashCommandProvider=new Ci(()=>this._wrapper.session.rpc.commands.list({includeBuiltins:!0,includeSkills:!0,includeClientCommands:!0}).then(c=>c.commands),this._logService),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 Aa(this._telemetryService),this._appliedSnapshot=e.clientSnapshot??{tools:[],plugins:[],mcpServers:{}},this._clientToolNames=eC(this._appliedSnapshot),this._activeClientToolSet=e.activeClientToolSet??new hn,this._databaseRef=i.openDatabase(e.sessionUri),this._register(N(()=>this._databaseRef.dispose())),this._sessionDataDir=i.getSessionDataDir(e.sessionUri),this._editTracker=this._instantiationService.createInstance(ti,e.sessionUri.toString(),this._databaseRef.object),this._mcpCustomizations=this._register(new ol({providerId:this.sessionUri.scheme,sessionId:this.sessionId,resolveChildId:e.resolveMcpChildId,emit:c=>this._emitAction(c)})),this._register(N(()=>this._denyPendingPermissions())),this._register(N(()=>this._shellManager?.dispose())),this._register(N(()=>this._cancelPendingUserInputs())),this._register(N(()=>this._cancelPendingElicitations())),this._register(N(()=>this._cancelPendingPlanReviews())),this._register(N(()=>this._drainPendingSteeringFlips())),this._register(N(()=>this._cancelPendingMcpSamplings())),this._register(N(()=>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(N(()=>this._cancelPendingClientToolCalls())),this._register(N(()=>this._permissionRequestAgentIds.clear())),this._register(N(()=>this._bufferedPendingConfirmations.clear())),this._register(N(()=>this._deferredServerToolReady.clear()))}get workingDirectory(){return this._workingDirectory}get _turnId(){return this._currentTurn?.id??""}get _turnOrdinal(){return this._currentTurn?.ordinal??0}get hasActiveTurn(){return this._currentTurn!==void 0}get mcpServerStates(){return this._mcpCustomizations.runtimeStates}_emitAction(e,t){this._onDidSessionProgress.fire({kind:"action",resource:pr(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=O();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 oC(e,this._nextTurnOrdinal++,t)}_completeActiveTurn(){let e=this._currentTurn;e&&(e.markCompleted(),this._telemetryReporter.toolCallDetails({session:this.sessionUri.toString(),turnId:e.id,model:e.lastModel,responseType:"success",toolCounts:Object.fromEntries(e.toolCounts),availableTools:this._appliedSnapshot.tools.map(t=>t.name),numRequests:e.toolCallRounds,totalToolCalls:e.totalToolCalls,parallelToolCallRounds:e.parallelToolCallRounds,parallelToolCallsTotal:e.parallelToolCallsTotal}),this._emitAction({type:"chat/turnComplete",turnId:e.id}),this._currentTurn=void 0)}_getEditFilePaths(e){return Qm(e).map(t=>this._resolveEditFilePath(t))}_resolveEditFilePath(e){return Wt(e)||!this._workingDirectory||this._workingDirectory.scheme!==ne.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 i=t??"",s=r.markdownPartIds.get(i);if(!s){s=O(),r.markdownPartIds.set(i,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 i=t??"",s=r.reasoningPartIds.get(i);if(!s){s=O(),r.reasoningPartIds.set(i,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:i})=>{try{return await this._pendingClientToolCalls.register(i)}catch(s){throw this._logService.error(s,`[Copilot:${this.sessionId}] Failed in client tool handler: tool=${t.name}, toolCallId=${i}`),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:await e.executeTool(this._chatChannelUri.toString(),t.name,r),resultType:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return this._logService.error(i,`[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(`
`)??"",i=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:S7(i);t.success?this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:s,resultType:"success",binaryResultsForLlm:i?.length?i:void 0}):this._pendingClientToolCalls.respondOrBuffer(e,{textResultForLlm:r.trim()?r:t.error?.message||"Tool call failed",resultType:"failure",error:t.error?.message,binaryResultsForLlm:i?.length?i: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 K;this._wrapper=this._register(e),this._subscribeToEvents(),this._subscribeForLogging(),this._subscribeForMemoInvalidation(),this._subscribeForInstructionsCollectedTelemetry(),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,i]of this._pendingMcpAuthRequests)i.resource.resource!==e.resource||!this._scopesSatisfy(e.scopes,i.requiredScopes)||(this._pendingMcpAuthRequests.delete(r),i.deferred.complete({kind:"token",accessToken:e.token}),t=!0);return t}async _handleMcpAuthRequest(e){let t=this._protectedResourceFromMcpAuthRequest(e),r=this._requiredScopesFromMcpAuthRequest(e,t),i=new Ee;return this._pendingMcpAuthRequests.set(e.requestId,{serverName:e.serverName,resource:t,requiredScopes:r,deferred:i}),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}`),i.p.finally(()=>this._pendingMcpAuthRequests.delete(e.requestId))}_protectedResourceFromMcpAuthRequest(e){if(e.resourceMetadata)try{let r=JSON.parse(e.resourceMetadata);if(HA(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(i=>r.has(i))}_cancelPendingMcpAuthRequests(){for(let e of this._pendingMcpAuthRequests.values())e.deferred.complete({kind:"cancelled"});this._pendingMcpAuthRequests.clear()}async send(e,t,r,i,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=xE(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(2236,null))}catch(d){if(Zn(d).toLowerCase().includes("nothing to compact")){this.emitInitialMarkdown(f(2236,null)),this._completeActiveTurn();return}throw this._logService.error(d,`[Copilot:${this.sessionId}] rpc.history.compact failed`),d}this._completeActiveTurn();return}if(a?.command==="plan")i="plan",e=a.rest;else if(a?.command==="rubber-duck")if(this._configurationService.getRootValue(mn,"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._slashCommandProvider.resolveSlashCommand(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:Ob(c.text));break;case"completed":c.message&&this._emitMarkdownDelta(c.message);break;case"agent-prompt":{let u=C7(c.mode);u&&(i=u),e=c.prompt;break}case"select-subcommand":this._emitMarkdownDelta(f(2237,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._slashCommandProvider.clearCache(),c.kind!=="agent-prompt"){this._completeActiveTurn();return}}}let l=t?.length?(await Promise.all(t.map(d=>this._toSdkAttachment(d)))).filter(_r):void 0;l?.length&&this._logService.trace(`[Copilot:${this.sessionId}] Attachments: ${JSON.stringify(l.map(d=>({type:d.type})))}`),await this.applyMode(i),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._slashCommandProvider.resolveSlashCommand(e)}catch(t){return this._logService.warn(`[Copilot:${this.sessionId}] rpc.commands.list failed`,t),!1}}async getRuntimeSlashCommands(e){try{return await this._slashCommandProvider.getSlashCommands(e)}catch(t){return this._logService.warn(`[Copilot:${this.sessionId}] rpc.commands.list failed`,t),[]}}async _toSdkAttachment(e){if(Mm(e)){let a=Om(e);return a?{type:"blob",data:or(F.fromString(a)),mimeType:"text/plain",displayName:e.label}:void 0}if(e.type==="simple")return e.modelRepresentation?{type:"blob",data:or(F.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=h.parse(e.uri),r=t.scheme==="file"?t.fsPath:t.toString(),i=e.label??r;if(e.selection)try{let a=await this._readSelectedText(t,e.selection.range);return{type:"selection",filePath:r,displayName:i,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:i}}return e.displayKind==="selection"?{type:"file",path:r,displayName:i}:{type:e.displayKind==="directory"?"directory":"file",path:r,displayName:i}}async _readSelectedText(e,t){let i=(await this._fileService.readFile(e)).value.toString(),s=I_(i),a=this._getOffsetAt(s,t.start),l=this._getOffsetAt(s,t.end);return i.substring(a,Math.max(a,l))}_getOffsetAt(e,t){let r=Math.max(0,Math.min(t.line,e.length-1)),i=0;for(let a=0;a<r;a++)i+=e[a].length;let s=e[r].replace(/\r\n|\r|\n$/,"");return i+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(),Yt,"mode")==="autopilot"}_isAutoReplyEnabled(){return this._configurationService.getRootValue(Ut,bv)===!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 i of e.turns)for(let s of i.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?NT({content:d}):void 0,u=bc(a).subagentDescription;r.push({resource:h.parse(na(t,a.toolCallId)),toolCallId:a.toolCallId,title:fv(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 FE(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 i=this._wrapper.session.rpc.mcp.apps;switch(t){case"tools/list":return i.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 i.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 i.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 startMcpServer(e){let t=this._mcpCustomizations.serverNameForCustomizationId(e);if(!t){this._logService.warn(`[Copilot:${this.sessionId}] Cannot start unknown MCP server customization ${e}`);return}await this._wrapper.session.rpc.mcp.disable({serverName:t}),await this._wrapper.session.rpc.mcp.enable({serverName:t}),await this._wrapper.session.rpc.mcp.listTools({serverName:t}),this._seedMcpServersFromRpc()}async stopMcpServer(e){let t=this._mcpCustomizations.serverNameForCustomizationId(e);if(!t){this._logService.warn(`[Copilot:${this.sessionId}] Cannot stop unknown MCP server customization ${e}`);return}await this._wrapper.session.rpc.mcp.stopServer({serverName:t}),this._mcpCustomizations.applyOne({name:t,state:{kind:"stopped"}})}async _handleSamplingCreateMessage(e,t){if(!t)throw new Error("sampling/createMessage missing params");let r=O(),i=O();this._pendingMcpSamplings.add(r);try{let s=await this._wrapper.session.rpc.mcp.executeSampling({requestId:r,serverName:e,mcpRequestId:i,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}}}_firePendingConfirmation(e){this._deferredServerToolReady.delete(e.state.toolCallId),this._activeToolCalls.has(e.state.toolCallId)||this._bufferedPendingConfirmations.set(e.state.toolCallId,e),this._onDidSessionProgress.fire(e)}_emitDeferredServerToolReady(e){let t=this._deferredServerToolReady.get(e);t&&(this._deferredServerToolReady.delete(e),t())}_ensureClientToolCallStarted(e){let t=e.toolCallId,r=e.toolName;if(!t||!r||this._activeToolCalls.has(t)||!this._clientToolNames.has(r))return;let i=this._activeClientToolSet.ownerOf(r,this._currentTurn?.senderClientId);if(!i)return;let s=this._permissionRequestAgentIds.get(t),a=s?this._parentToolCallIdsByAgentId.get(s):void 0,l=e.args,d=l!==void 0?Po(l):void 0,c=yr(r),u={toolKind:mu(r)};d!==void 0&&(u.toolArguments=d),this._logService.info(`[Copilot:${this.sessionId}] Synthesizing tool start for client tool ahead of permission ready: ${r} (toolCallId=${t}, parentToolCallId=${a??"none"})`),this._activeToolCalls.set(t,{toolName:r,displayName:c,parameters:l,content:[],parentToolCallId:a,mcpServerName:void 0,meta:u}),this._currentTurn?.markdownPartIds.delete(a??""),this._currentTurn?.reasoningPartIds.delete(a??""),this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:t,toolName:r,displayName:c,intention:pu(r,l),contributor:{kind:"client",clientId:i},_meta:Rt(u)},a)}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"&&R7(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 i=e.kind==="shell"||e.kind==="custom-tool"&&typeof e.toolName=="string"&&uu(e.toolName);this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${t}`);let s=new Ee;if(this._pendingPermissions.set(t,s),i&&!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}`),this._emitDeferredServerToolReady(t),{kind:"approve-once"}):{kind:"reject"};let a=await this._buildEditsForPermission(e,t);if(!this._pendingPermissions.has(t))return{kind:"reject"};let l=a?.items.some(b=>!b.before&&!!b.after),{confirmationTitle:d,invocationMessage:c,toolInput:u,permissionKind:p,permissionPath:m}=ME(e,this._workingDirectory,l),v=e.toolName??e.kind;this._ensureClientToolCallStarted(e);let y=this._activeToolCalls.get(t)?.parentToolCallId;this._firePendingConfirmation({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:t,toolName:v,displayName:yr(v),invocationMessage:c,toolInput:u,confirmationTitle:d,edits:a},permissionKind:p,permissionPath:m,requestSandboxBypass:e.requestSandboxBypass,parentToolCallId:y});let S=await s.p;return this._logService.info(`[Copilot:${this.sessionId}] Permission response: toolCallId=${t}, approved=${S}`),{kind:S?"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=wn(h.file(T7(this._environmentService.userHome.fsPath))),i=wn(h.joinPath(r,this.sessionId));if(!nt.isEqualOrParent(i,r))return;let s=wn(h.file(t));return nt.isEqualOrParent(s,i)?t:void 0}_isSessionAttachmentPath(e){let t=wn(h.joinPath(this._sessionDataDir,uf)),r=wn(h.file(e));return nt.isEqualOrParent(r,t)}async _isShellSandboxedByDefault(){return this._isCustomTerminalToolEnabled()?this._shellManager?this._shellManager.getOrCreateSandboxEngine().isEnabled():!1:this._computeSdkSandboxConfig()!==void 0}_isCustomTerminalToolEnabled(){return this._configurationService.getRootValue(mn,"enableCustomTerminalTool")===!0}_computeSdkSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(kr,"sandbox");return su(this._platform,e)}_isBypassApprovals(){return this._configurationService.getRootValue(Ut,jd)===!0||this._isAutopilotMode()?!0:this._configurationService.getEffectiveValue(this.sessionUri.toString(),Yt,"autoApprove")==="autoApprove"}async _applyEffectiveSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(kr,"sandbox"),t=su(this._platform,e),r=t&&!this._isBypassApprovals()?t:{enabled:!1};try{await this._wrapper.session.rpc.options.update({sandboxConfig:r})}catch(i){this._logService.warn(`[Copilot:${this.sessionId}] Failed to update sandbox config for request`,i)}}async _buildEditsForPermission(e,t){if(e.kind!=="write")return;let r=typeof e.fileName=="string"?e.fileName:void 0,i=typeof e.newFileContents=="string"?e.newFileContents:void 0;if(!r||i===void 0)return;let s=h.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=$E(this.sessionUri.toString(),t,r);try{await this._fileService.writeFile(d,F.fromString(i))}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"?x7(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=yr(e.toolName),i=e.blockedDomains?.length?e.blockedDomains.join(", "):void 0,s=i?f(2234,null,i):f(2235,null),a=e.reason?f(2233,null,e.reason):i?f(2231,null,i):f(2232,null),l=this._activeToolCalls.get(e.toolCallId)?.parentToolCallId;return this._firePendingConfirmation({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 i=e.question.substring(0,100);try{let s=O(),a=O();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${s}, question="${i}"`);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="${i}"`),s}}async _handleElicitationRequest(e){if(this._isAutopilotMode())return{action:"cancel"};let r=e.message.substring(0,100);try{let i=O();this._logService.info(`[Copilot:${this.sessionId}] Elicitation request: requestId=${i}, 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(([v,y])=>I7(v,y,a.has(v))):void 0,d=new Ee;this._pendingElicitations.set(i,{deferred:d,schema:s});let c={id:i,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=${i}, response=${u.response}`),u.response==="decline")return{action:"decline"};if(u.response!=="accept")return{action:"cancel"};let p=u.answers??{};if(!s){let v=p.answer;return v&&v.state!=="skipped"&&v.value.kind==="text"?{action:"accept",content:{answer:v.value.value}}:{action:"accept"}}let m={};for(let[v,y]of Object.entries(s.properties)){let S=_7(y,p[v]);S!==void 0&&(m[v]=S)}return{action:"accept",content:m}}catch(i){throw this._logService.error(i,`[Copilot:${this.sessionId}] Failed to handle elicitation request: message="${r}"`),i}}respondToUserInputRequest(e,t,r){let i=this._pendingPlanReviews.get(e);if(i)return this._pendingPlanReviews.delete(e),i.deferred.complete(this._resolveExitPlanMode(i,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 i=r?.[e.questionId];if(!i||i.state==="skipped")return{approved:!1};let s=i.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,BE(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,BE(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(i=>{let s=Jm(i);if(!s){this._logService.trace(`[Copilot:${t}] Ignoring system.notification kind=${i.data.kind.type}`);return}if(this._logService.info(`[Copilot:${t}] System notification received: kind=${i.data.kind.type}`),this._turnId){this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"systemNotification",content:s.messageText}});return}if(!s.startsTurn){this._logService.trace(`[Copilot:${t}] Ignoring passive system.notification kind=${i.data.kind.type} without an active turn`);return}let a=O();this.resetTurnState(a),this._emitAction({type:"chat/turnStarted",turnId:a,message:{text:s.messageText,origin:{kind:"systemNotification"}}})})),this._register(e.onUserMessage(i=>{if(i.data.source&&i.data.source.toLowerCase()!=="user")return;this._currentTurn?.markRunning();let s=this._takeMatchingPendingSteering(i.data.content);s&&this._beginSteeringTurn(s),this._turnId&&this._databaseRef.object.setTurnEventId(this._turnId,i.id)})),this._register(e.onMessageDelta(i=>{this._logService.trace(`[Copilot:${t}] delta: ${i.data.deltaContent}`),!this._shouldDropUnmappedSubagentEvent(i,"assistant.message_delta")&&this._emitMarkdownDelta(i.data.deltaContent,this._parentToolCallIdForSubagentEvent(i))})),this._register(e.onMessage(i=>{if(this._logService.info(`[Copilot:${t}] Full message received: ${i.data.content.length} chars`),!i.agentId){this._telemetryReporter.assistantMessageReceived(this.sessionUri.toString(),i.data.serviceRequestId,this._appliedSnapshot.tools),this._telemetryReporter.modelMessageText(this.sessionUri.toString(),i.data.content,this._turnOrdinal,i.data.serviceRequestId);let d=this._currentTurn;if(d){d.toolCallRounds++,i.data.model&&(d.lastModel=i.data.model);let c=i.data.toolRequests;if(c?.length){d.totalToolCalls+=c.length,c.length>1&&(d.parallelToolCallRounds++,d.parallelToolCallsTotal+=c.length);for(let u of c)d.toolCounts.set(u.name,(d.toolCounts.get(u.name)??0)+1)}}}if(!i.data.content||this._shouldDropUnmappedSubagentEvent(i,"assistant.message"))return;let s=this._parentToolCallIdForSubagentEvent(i),a=s??"";if(this._currentTurn?.markdownPartIds.has(a))return;let l=O();this._currentTurn?.markdownPartIds.set(a,l),this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:l,content:i.data.content}},s)})),this._register(e.onPermissionRequested(i=>{let s=i.data.permissionRequest.toolCallId;s&&i.agentId&&this._permissionRequestAgentIds.set(s,i.agentId)})),this._register(e.onToolStart(i=>{if(Xm(i.data.toolName)){this._logService.trace(`[Copilot:${t}] Tool started (hidden): ${i.data.toolName}`);return}if(this._activeToolCalls.has(i.data.toolCallId)){this._logService.trace(`[Copilot:${t}] Tool start already emitted for ${i.data.toolCallId}; skipping duplicate.`);return}this._logService.info(`[Copilot:${t}] Tool started: ${i.data.toolName}`);let s=i.data.arguments!==void 0?Po(i.data.arguments):void 0,a;if(s)try{a=JSON.parse(s)}catch{}Ss(i.data.toolName,a,this._workingDirectory)&&(s=Po(a));let l=yr(i.data.toolName);if(this._shouldDropUnmappedSubagentEvent(i,"tool.execution_start"))return;let d=this._parentToolCallIdForSubagentEvent(i);if(this._activeToolCalls.set(i.data.toolCallId,{toolName:i.data.toolName,displayName:l,parameters:a,content:[],parentToolCallId:d,mcpServerName:i.data.mcpServerName,meta:void 0}),Al(i.data.toolName)){let P=d??"";this._currentTurn?.markdownPartIds.delete(P),this._currentTurn?.reasoningPartIds.delete(P);return}let c=mu(i.data.toolName),u=c==="subagent"?eh(a):void 0,p,m=this._clientToolNames.has(i.data.toolName),v=m?this._activeClientToolSet.ownerOf(i.data.toolName,this._currentTurn?.senderClientId):void 0;if(v)p={kind:"client",clientId:v};else if(i.data.mcpServerName){let P=this._mcpCustomizations.customizationIdForServer(i.data.mcpServerName);P!==void 0&&(p={kind:"mcp",customizationId:P})}this._currentTurn?.markdownPartIds.delete(d??""),this._currentTurn?.reasoningPartIds.delete(d??"");let y={toolKind:c,language:c==="terminal"?th(i.data.toolName):void 0};u?.description&&(y.subagentDescription=u.description),u?.agentName&&(y.subagentAgentName=u.agentName),s!==void 0&&(y.toolArguments=s),i.data.mcpServerName&&(y.mcpServerName=i.data.mcpServerName),i.data.mcpToolName&&(y.mcpToolName=i.data.mcpToolName);let S=i.data.toolDescription?._meta?.ui?.resourceUri;this._setToolCallUiMeta(y,S,i.data.mcpServerName);let b=this._activeToolCalls.get(i.data.toolCallId);if(b&&(b.meta=y),this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:i.data.toolCallId,toolName:i.data.toolName,displayName:l,intention:pu(i.data.toolName,a),contributor:p,_meta:Rt(y)},d),m&&!p){this._logService.warn(`[Copilot:${t}] Client tool '${i.data.toolName}' started with no connected client; failing it immediately.`),this._activeToolCalls.delete(i.data.toolCallId),this._bufferedPendingConfirmations.delete(i.data.toolCallId),this._deferredServerToolReady.delete(i.data.toolCallId),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:i.data.toolCallId,invocationMessage:Ao(i.data.toolName,l,a),toolInput:gu(i.data.toolName,a,s),confirmed:"not-needed"},d),this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:i.data.toolCallId,result:{success:!1,pastTenseMessage:`${l} failed`,error:{message:`No client was connected to run ${l}`}}},d),this._pendingClientToolCalls.respondOrBuffer(i.data.toolCallId,{textResultForLlm:`No client was connected to run ${l}.`,resultType:"failure",error:"No client connected"});return}if(p?.kind==="client"&&!kE(i.data.toolName))return;let _=()=>this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:i.data.toolCallId,invocationMessage:Ao(i.data.toolName,l,a),toolInput:gu(i.data.toolName,a,s),confirmed:"not-needed"},d),T=this._bufferedPendingConfirmations.get(i.data.toolCallId);if(T){this._bufferedPendingConfirmations.delete(i.data.toolCallId),this._deferredServerToolReady.delete(i.data.toolCallId),this._onDidSessionProgress.fire({...T,parentToolCallId:d});return}if(this._pendingPermissions.has(i.data.toolCallId)){this._deferredServerToolReady.set(i.data.toolCallId,_);return}_()})),this._register(e.onToolComplete(async i=>{let s=this._activeToolCalls.get(i.data.toolCallId);if(!s)return;let a=s.parentToolCallId??this._parentToolCallIdForSubagentEvent(i);if(!a&&i.agentId){this._logService.warn(`[Copilot:${this.sessionId}] Dropping tool.execution_complete for unknown subagent agentId=${i.agentId}`);return}this._logService.info(`[Copilot:${t}] Tool completed: ${i.data.toolCallId}`),this._activeToolCalls.delete(i.data.toolCallId),this._permissionRequestAgentIds.delete(i.data.toolCallId),this._bufferedPendingConfirmations.delete(i.data.toolCallId),this._deferredServerToolReady.delete(i.data.toolCallId);let l=s.displayName,d=i.data.error?.message??i.data.result?.content;if(Al(s.toolName)){let m=cu(s.parameters,d);m&&this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:O(),content:m}});return}let c=[...s.content];d!==void 0&&c.push({type:"text",text:d}),rC(c,i.data.result?.contents);let u=Ve(s.parameters?.command)?s.parameters.command:void 0,p=Pl(s.toolName,u)?this._getEditFilePaths(s.parameters):[];for(let m of p)try{let v=await this._editTracker.takeCompletedEdit(this._turnId,i.data.toolCallId,m,s.toolName,s.parameters,this._lastSeenModelId);v&&c.push(v)}catch(v){this._logService.warn(`[Copilot:${t}] Failed to take completed edit`,v)}if(uu(s.toolName)&&this._shellManager){let m=this._shellManager.getTerminalUriForToolCall(i.data.toolCallId);m&&!c.some(v=>v.type==="terminal"&&v.resource===m)&&c.push({type:"terminal",resource:m,title:s.displayName})}this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:i.data.toolCallId,result:{success:i.data.success,pastTenseMessage:fu(s.toolName,l,s.parameters,i.data.success,i.data.success?d:void 0),content:c.length>0?c:void 0,error:i.data.error},_meta:s.meta?Rt(s.meta):void 0},a)})),this._register(e.onIdle(i=>{this._logService.info(`[Copilot:${t}] Session idle`),this._hasActivity&&(this._hasActivity=!1,this._emitAction({type:"session/activityChanged",activity:void 0}));let s=this._currentTurn;if(s){if(i.data.aborted){s.isRunning?(this._logService.trace(`[Copilot:${t}] Idle from abort; tearing down running turn ${s.id}`),s.markAborted(),this._currentTurn=void 0):this._logService.trace(`[Copilot:${t}] Idle from abort; leaving ${s.state} turn ${s.id} open`);return}this._completeActiveTurn()}})),this._register(e.onSkillInvoked(i=>{if(this._logService.info(`[Copilot:${t}] Skill invoked: ${i.data.name} (${i.data.path})`),this._shouldDropUnmappedSubagentEvent(i,"skill.invoked"))return;i.agentId||this._telemetryReporter.skillContentRead({name:i.data.name,path:i.data.path,content:i.data.content,source:i.data.source,pluginName:i.data.pluginName,pluginVersion:i.data.pluginVersion});let s=this._parentToolCallIdForSubagentEvent(i),a=Zm(i.data,i.id);this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:a.toolCallId,toolName:a.toolName,displayName:a.displayName},s),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:a.toolCallId,invocationMessage:a.invocationMessage,confirmed:"not-needed"},s),this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:a.toolCallId,result:{success:!0,pastTenseMessage:a.pastTenseMessage}},s)})),this._register(e.onSubagentStarted(i=>{i.agentId&&this._parentToolCallIdsByAgentId.set(i.agentId,i.data.toolCallId),this._logService.info(`[Copilot:${t}] Subagent started: toolCallId=${i.data.toolCallId}, agent=${i.data.agentName}`);let s=this._activeToolCalls.get(i.data.toolCallId);this._onDidSessionProgress.fire({kind:"subagent_started",chat:this._chatChannelUri,toolCallId:i.data.toolCallId,agentName:i.data.agentName,agentDisplayName:i.data.agentDisplayName,agentDescription:i.data.agentDescription,taskDescription:s?.meta?.subagentDescription,parentToolCallId:s?.parentToolCallId})})),this._register(e.onSessionError(i=>{this._logService.error(`[Copilot:${t}] Session error: ${i.data.errorType} - ${i.data.message}`);let s=vP(i.data)??yP(i.data.message);this._emitAction({type:"chat/error",turnId:this._turnId,error:{errorType:i.data.errorType,message:Mc(i.data.message),stack:i.data.stack,...s?{_meta:s}:{}}})}));let r;this._register(e.onUsage(i=>{let s=this._parentToolCallIdForSubagentEvent(i),a=i.data.copilotUsage,l=P7(i.data.quotaSnapshots),d=this._currentTurn;typeof i.data.model=="string"&&i.data.model&&(this._lastSeenModelId=i.data.model);let c={inputTokens:i.data.inputTokens,outputTokens:i.data.outputTokens,model:i.data.model,cacheReadTokens:i.data.cacheReadTokens,...typeof i.data.cost=="number"?{cost:i.data.cost}:{}};!s&&d&&(d.parentContextUsage=c);let u=(v,y)=>{let S={};if(typeof y.cost=="number"&&(S.cost=y.cost),d&&typeof a?.totalNanoAiu=="number"){let b=(d.copilotUsageTotalNanoAiuByScope.get(v)??0)+a.totalNanoAiu;d.copilotUsageTotalNanoAiuByScope.set(v,b),S.copilotUsage={...a,totalNanoAiu:b}}return l&&(S.quotaSnapshots=l),{inputTokens:y.inputTokens,outputTokens:y.outputTokens,model:y.model,cacheReadTokens:y.cacheReadTokens,...Object.keys(S).length>0?{_meta:S}:{}}},p=s?d?.parentContextUsage??{}:c,m=u("",p);r=m,this._emitAction({type:"chat/usage",turnId:this._turnId,usage:m}),s&&this._emitAction({type:"chat/usage",turnId:this._turnId,usage:u(s,c)},s)})),this._register(e.onUsage(async i=>{if(this._parentToolCallIdForSubagentEvent(i))return;let s=this._turnId,a=r??{inputTokens:i.data.inputTokens,outputTokens:i.data.outputTokens,model:i.data.model,cacheReadTokens:i.data.cacheReadTokens};try{let d=(await this._wrapper.session.rpc.metadata.getContextAttribution())?.contextAttribution;if(!d||!s){this._logService.trace(`[Copilot:${t}] contextAttribution: null/empty (turnId=${s})`);return}if(s!==this._turnId||a!==r)return;this._logService.getLevel()<=1&&this._logService.trace(`[Copilot:${t}] contextAttribution: totalTokens=${d.totalTokens}, entries=${JSON.stringify(d.entries.map(u=>({kind:u.kind,id:u.id,label:u.label,tokens:u.tokens,parentId:u.parentId})))}`);let c={...a,_meta:{...a._meta??{},contextAttribution:d}};r=c,this._emitAction({type:"chat/usage",turnId:s,usage:c})}catch(l){this._logService.trace(`[Copilot:${t}] contextAttribution RPC failed: ${l?.message??l}`)}})),this._register(e.onReasoningDelta(i=>{this._logService.trace(`[Copilot:${t}] Reasoning delta: ${i.data.deltaContent.length} chars`),!this._shouldDropUnmappedSubagentEvent(i,"assistant.reasoning_delta")&&this._emitReasoningDelta(i.data.deltaContent,this._parentToolCallIdForSubagentEvent(i))})),this._register(e.onSessionModeChanged(i=>{if(i.agentId){this._logService.trace(`[Copilot:${t}] Ignoring subagent session.mode_changed: agentId=${i.agentId}, ${i.data.previousMode} -> ${i.data.newMode}`);return}this._logService.info(`[Copilot:${t}] session.mode_changed: ${i.data.previousMode} -> ${i.data.newMode}`);let s=i.data.newMode;s!=="interactive"&&s!=="plan"&&s!=="autopilot"||(this._lastAppliedMode=s,this._syncAhpConfigFromSdkMode(s))})),this._register(e.onMcpServersLoaded(i=>{this._applyMcpServerList(i.data.servers)})),this._register(e.onMcpServerStatusChanged(i=>{let s=this._toSdkMcpServer(i.data.serverName,i.data.status,i.data.error);if(!s){this._mcpCustomizations.remove(i.data.serverName);return}this._mcpCustomizations.applyOne(s)})),this._register(e.onToolsUpdated(()=>{this._slashCommandProvider.clearCache(),this._fireMcpToolsListChanged()})),this._register(e.onCommandsChanged(()=>{this._slashCommandProvider.clearCache()})),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));this._mcpCustomizations.applyAll(t)}_setToolCallUiMeta(e,t,r){if(!t)return;let i={resourceUri:t};if(r){let s=this._mcpCustomizations.channelForServer(r);s!==void 0&&(i.channel=s)}e.ui=i}_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){return{name:e,state:this._translateSdkMcpStatus(e,t,r)}}_translateSdkMcpStatus(e,t,r){switch(t){case"connected":return{kind:"ready"};case"failed":return{kind:"error",error:{errorType:"mcp-server-failed",message:r??"MCP server failed to start"}};case"pending":case"needs-auth":{let i=this._mcpCustomizations.stateForServer(e);return i?.kind==="authRequired"?i:{kind:"starting"}}case"disabled":case"not_configured":return{kind:"stopped"};default:return{kind:"stopped"}}}_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=O(),i=O();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=b7(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(2230,null),content:e.summary||f(2226,null),actions:l,canProvideFeedback:!0,answerQuestionId:i,...s?{planUri:h.file(s).toString()}:{}},questions:[{kind:"single-select",id:i,title:f(2230,null),message:f(2229,null),required:!0,options:a,allowFreeformInput:!0}]},c=new Ee;this._pendingPlanReviews.set(r,{actions:e.actions,recommendedAction:e.recommendedAction,questionId:i,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))}_subscribeForInstructionsCollectedTelemetry(){let e=this._wrapper,t=this.sessionId;this._register(e.onUserMessage(r=>{r.data.source&&r.data.source.toLowerCase()!=="user"||(async()=>{let i;try{i=(await e.session.rpc.instructions.getSources()).sources}catch(c){this._logService.trace(`[Copilot:${t}] Failed to fetch instruction sources for telemetry: ${Zn(c)}`);return}let s=0,a=0,l=0,d=0;for(let c of i){(c.type==="home"||c.type==="repo"||c.type==="model")&&s++,c.applyTo&&c.applyTo.length>0&&a++,(c.type==="child-instructions"||c.type==="nested-agents")&&l++;let u=Math.max(c.sourcePath.lastIndexOf("/"),c.sourcePath.lastIndexOf("\\"));(u>=0?c.sourcePath.slice(u+1):c.sourcePath)==="CLAUDE.md"&&d++}this._telemetryService.publicLog2("agentHost.instructionsCollected",{provider:this.sessionUri.scheme,agentSessionId:D.id(this.sessionUri),isSubagentSession:lr(this.sessionUri),totalInstructionsCount:i.length,agentInstructionsCount:s,applyingInstructionsCount:a,referencedInstructionsCount:l,claudeMdCount:d})})().catch(i=>{this._logService.trace(`[Copilot:${t}] instructionsCollected telemetry failed: ${Zn(i)}`)})}))}_subscribeForLogging(){let e=this._wrapper,t=this.sessionId;this._register(e.onUnhandledEvent(r=>{this._logService.trace(`[Copilot:${t}] Unhandled SDK event: ${Ad(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 i={infoType:r.data.infoType};r.data.tip&&(i.tip=r.data.tip);let s=`[Copilot:${t}] [${r.data.infoType}]: ${r.data.message}`,a=new Il(i);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 Il({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`),!r.agentId&&(!r.data.source||r.data.source.toLowerCase()==="user")&&this._telemetryReporter.userMessageText(this.sessionUri.toString(),r.data.content,this._turnOrdinal)})),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 i=r.data.intent||void 0;i===void 0&&!this._hasActivity||(this._hasActivity=i!==void 0,this._emitAction({type:"session/activityChanged",activity:i}))})),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"})}};El=R([C(1,xe),C(2,M),C(3,rt),C(4,Pe),C(5,bt),C(6,He),C(7,zn)],El);function x7(o){let n=0,e=0;for(let t of o.split(`
`))t.startsWith("+++")||t.startsWith("---")||(t.startsWith("+")?n++:t.startsWith("-")&&e++);if(!(n===0&&e===0))return{added:n,removed:e}}function P7(o){if(!o||typeof o!="object")return;let n={},e=!1;for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object")continue;let i=r,s=i.resetDate,a=typeof s=="string"?s:s instanceof Date?s.toISOString():void 0;n[t]={isUnlimitedEntitlement:typeof i.isUnlimitedEntitlement=="boolean"?i.isUnlimitedEntitlement:void 0,entitlementRequests:typeof i.entitlementRequests=="number"?i.entitlementRequests:void 0,usedRequests:typeof i.usedRequests=="number"?i.usedRequests:void 0,remainingPercentage:typeof i.remainingPercentage=="number"?i.remainingPercentage:void 0,overage:typeof i.overage=="number"?i.overage:void 0,overageAllowedWithExhaustedQuota:typeof i.overageAllowedWithExhaustedQuota=="boolean"?i.overageAllowedWithExhaustedQuota:void 0,resetDate:a},e=!0}return e?n:void 0}async function A7(o,n){if(!o||o.scheme!==ne.file)return;let e=await n.getRepositoryRoot(o);if(!e)return;let t=(await n.getWorktreeRoots(o))[0]??e;if(t)return{uri:t,displayName:Te(t.fsPath)||t.toString()}}function E7(o){let n=o.includes("://")?h.parse(o):h.parse(`https://github.com/${o}`),e=Te(n.path)||o.split("/").filter(Boolean).pop()||o,t=e.endsWith(".git")?e.slice(0,-4):e;return{uri:n,displayName:t}}async function Qn(o,n){let e=typeof o?.cwd=="string"?h.file(o.cwd):typeof o?.gitRoot=="string"?h.file(o.gitRoot):void 0,t=await A7(e,n);if(t)return t;if(o?.repository)return E7(o.repository)}function zE(o){let n={};for(let[e,t]of Object.entries(o))t!==void 0&&(n[e]=t);return Object.keys(n).length>0?n:void 0}function KE(o,n){if(o.length!==n.length)return!1;for(let e=0;e<o.length;e++){let t=o[e],r=n[e];if(t.type!==r.type||t.uri.toString()!==r.uri.toString()||!D7(t.files,r.files))return!1}return!0}function k7(o,n){let e=Hn(o.type,n.type);return e!==0?e:Hn(o.uri.toString(),n.uri.toString())}function D7(o,n){if(o.length!==n.length)return!1;for(let e=0;e<o.length;e++){let t=o[e],r=n[e];if(t.uri.toString()!==r.uri.toString()||t.etag!==r.etag)return!1}return!0}function yu(o,n){return Hn(o.uri.toString(),n.uri.toString())}function M7(o,n){let e=Hn(o.uri,n.uri);return e!==0?e:Hn(o.contents,n.contents)}var O7=5,L7=8;var N7=".md",U7=".instructions.md",F7=".json",H7="SKILL.md",$7="README.md",VE={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"}]},jE={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 yn(o){if(o.isCancellationRequested)throw new K}function iC(o,n,e,t){let r=o.get(n);r?e&&!r.recursive&&(r={recursive:!0,resourcesToWatch:r.resourcesToWatch},o.set(n,r)):(r={recursive:e,resourcesToWatch:new Ir},o.set(n,r)),r.resourcesToWatch.add(t)}var kl=class extends w{constructor(e,t,r,i){super();this._workingDirectory=e;this._userHome=t;this._fileService=r;this._logService=i;this._onDidChange=this._register(new A);this.onDidChange=this._onDidChange.event;this._watchers=new qe;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){yn(t);let r={projectPaths:[this._workingDirectory.fsPath]};try{let[i,s,a]=await Promise.all([this.discoverAgents(r,e,t),this.discoverRules(r,e,t),this.discoverSkills(r,e,t)]);yn(t);let l=[];return this.toDirectoryCustomizations("agent",i,l),this.toDirectoryCustomizations("rule",s,l),this.toDirectoryCustomizations("skill",a,l),l.sort(M7)}catch(i){return this._logService.error(`[SessionCustomizationDiscovery] Error during discovery: ${i instanceof Error?i.message:String(i)}`),[]}}async discoverAgents(e,t,r){let i=[],s=await gp(t.rpc.agents.discover(e),r);for(let a of s.agents)if(a.path){let l=h.file(a.path);i.push({type:"agent",uri:l.toString(),id:a.id,name:a.name,description:a.description,_meta:zE({userInvocable:a.userInvocable})})}return i}async discoverRules(e,t,r){let i=[],s=await gp(t.rpc.instructions.discover(e),r);for(let a of s.sources){let l;Wt(a.sourcePath)?l=h.file(a.sourcePath):l=te(this._workingDirectory,a.sourcePath),i.push({type:"rule",uri:l.toString(),id:a.id,name:a.label,description:a.description,globs:a.applyTo,alwaysApply:!1})}return i}async discoverSkills(e,t,r){let i=[],s=await gp(t.rpc.skills.discover(e),r);for(let a of s.skills)if(a.path){let l=h.file(a.path);i.push({type:"skill",uri:l.toString(),id:a.path,name:a.name,description:a.description})}return i}toDirectoryCustomizations(e,t,r){let i=new qe;for(let s of t){if(s.type!==e)continue;let a=h.parse(s.uri),l=Tn(a),d=i.get(l);d||(d={uri:l,children:[]},i.set(l,d)),d.children.push(s)}for(let{uri:s,children:a}of i.values())a.sort((l,d)=>Hn(l.uri,d.uri)),r.push({type:"directory",id:Nt(s.toString()),uri:s.toString(),name:Te(s.path),enabled:!0,contents:e,writable:!0,load:{kind:"loaded"},children:a})}async scan(e){yn(e);let t=new qe,r=new Ir,i=[];return await Promise.all([...VE.workspace.map(s=>this._scanRoot(this._workingDirectory,s,r,i,t,e)),...VE.user.map(s=>this._scanRoot(this._userHome,s,r,i,t,e)),this._scanFixedDiscoveryFiles(this._workingDirectory,jE.workspace,r,i,t,e),this._scanFixedDiscoveryFiles(this._userHome,jE.user,r,i,t,e)]),yn(e),this._reconcileWatchers(t),i.sort(k7)}async _watchAncestors(e,t,r,i){let s=e;for(let a of t){let l=s,d=te(l,a);if(!r.has(l)){yn(i);try{if(!(await this._fileService.resolve(l)).isDirectory)return!1}catch{return!1}}iC(r,l,!1,d),s=d}return!0}_reconcileWatchers(e){for(let[t,r]of this._watchers.entries()){let i=e.get(t);(!i||i.recursive!==r.recursive)&&(r.disposable.dispose(),this._watchers.delete(t))}for(let[t,r]of e.entries()){let i=this._watchers.get(t);if(i){i.resourcesToWatch.clear();for(let s of r.resourcesToWatch)i.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,i,s,a){let l=new Map;await Promise.all(t.map(async d=>{if(yn(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)iC(s,c,!1,te(c,p));for(let p of u.children)if(yn(a),p.isFile&&d.filenames.includes(p.name)){let m=te(c,p.name);if(!r.has(m)){r.add(m);let v=l.get(d.type)??[];v.push({uri:m,etag:p.etag}),l.set(d.type,v)}}}}));for(let[d,c]of l.entries())c.length>0&&i.push({uri:e,type:d,files:c.sort(yu),name:"",writable:!1})}async _scanRoot(e,t,r,i,s,a){yn(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),iC(s,l,t.recursive??!1,l),t.type==="skill"){let u=[];await Promise.all(c.map(async p=>{if(yn(a),p.isDirectory){let m=te(p.resource,H7);try{let v=await this._fileService.resolve(m,{resolveMetadata:!0});v.isFile&&!r.has(m)&&(r.add(m),u.push({uri:m,etag:v.etag}))}catch{}}})),i.push({uri:l,type:t.type,files:u.sort(yu),name:t.name,writable:!0})}else if(t.type==="agent"){let u=[];for(let p of c)if(yn(a),p.isFile){let m=p.name;m.endsWith(N7)&&m!==$7&&!r.has(p.resource)&&(r.add(p.resource),u.push({uri:p.resource,etag:p.etag}))}i.push({uri:l,type:t.type,files:u.sort(yu),name:t.name,writable:!0})}else if(t.type==="instruction"){let u=[],p=async(m,v)=>{yn(a);for(let y of m.children??[])if(yn(a),y.isFile)y.name.toLowerCase().endsWith(U7)&&!r.has(y.resource)&&(r.add(y.resource),u.push({uri:y.resource,etag:y.etag}));else if(y.isDirectory&&v<O7){let S;try{S=await this._fileService.resolve(y.resource,{resolveMetadata:!0})}catch{}S&&await p(S,v+1)}};d&&await p(d,0),i.push({uri:l,type:t.type,files:u.sort(yu),name:t.name,writable:!0})}else if(t.type==="hook"){let u=[],p=async(m,v)=>{yn(a);for(let y of m.children??[])if(yn(a),y.isFile)y.name.toLowerCase().endsWith(F7)&&!r.has(y.resource)&&(r.add(y.resource),u.push({uri:y.resource,etag:y.etag}));else if(y.isDirectory&&v<L7){let S;try{S=await this._fileService.resolve(y.resource,{resolveMetadata:!0})}catch{}S&&await p(S,v+1)}};d&&await p(d,0),i.push({uri:l,type:t.type,files:u.sort(yu),name:t.name,writable:!0})}else this._logService.warn(`[SessionCustomizationDiscovery] Unrecognized root type '${t.type}' for root '${l.toString()}'`)}};kl=R([C(2,Pe),C(3,M)],kl);var B7=300,GE="https://api.githubcopilot.com",z7=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"],V7=["HTTP_PROXY","HTTPS_PROXY"];function j7(o){switch(o){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 JE(o){try{return await ht.access(o),!0}catch{return!1}}function K7(){return process.platform!=="linux"?!1:!process.report?.getReport()?.header?.glibcVersionRuntime}function G7(){let o=`${process.platform}-${process.arch}`;if(process.platform!=="linux")return[o];let n=[`linux-${process.arch}`,`linuxmusl-${process.arch}`];return K7()?n.reverse():n}async function J7(o){let n=[];for(let t of G7()){let r=h.joinPath(o,"@github",`copilot-${t}`,"index.js").fsPath;if(n.push(r),await JE(r))return r}let e=h.joinPath(o,"@github","copilot","index.js").fsPath;if(n.push(e),await JE(e))return e;throw new Error(`Unable to resolve @github/copilot CLI path. Tried: ${n.join(", ")}`)}function Y7(o){return h.joinPath(o,"..",`${Te(o.fsPath)}.worktrees`)}var bu=class extends Error{constructor(e,t){super(t?f(2218,null,t):f(2217,null,e.fsPath));this.workingDirectory=e;this.reason=t;this.name="SessionWorkingDirectoryMissingError"}};function Q7(o,n=""){let e=o;return n&&e.startsWith(n)&&(e=e.substring(n.length)),e.startsWith(Am)&&(e=e.substring(Am.length)),e.replace(/\//g,"-")}function XE(o,n,e){if(!io(o,n))return;let t=so(n,o);if(t!==void 0)return t.length===0?e:te(e,t)}function X7(o,n,e){let t=new Map;for(let[r,i]of o){let s=XE(h.parse(r),n,e);t.set(s?s.toString():r,i)}return t}function YE(o){return f(2216,null,ot(o))+`

`}function Z7(o,n){if(o.length===0)return o;let e=o.slice(),t=e[0],r=t.responseParts[0];if(r?.kind==="markdown"){let i=t.responseParts.slice();i[0]={...r,content:n+r.content},e[0]={...t,responseParts:i}}else{let i=[{kind:"markdown",id:O(),content:n},...t.responseParts];e[0]={...t,responseParts:i}}return e}var bs=class extends Sl{},Ae=class extends w{constructor(e,t,r,i,s,a,l,d,c,u,p,m,v,y,S,b){super();this._logService=e;this._instantiationService=t;this._sessionDataService=r;this._gitService=i;this._configurationService=s;this._gitHubEndpointService=a;this._otelService=l;this._branchNameGenerator=d;this._checkpointService=u;this._reviewService=p;this._environmentService=m;this._byokBridgeRegistry=v;this._telemetryService=y;this._copilotApiService=S;this._proxyResolver=b;this.id="copilotcli";this._onDidSessionProgress=this._register(new A);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidSpawnChat=this._register(new A);this.onDidSpawnChat=this._onDidSpawnChat.event;this._onDidMaterializeSession=this._register(new A);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new A);this.onMcpNotification=this._onMcpNotification.event;this._models=rn(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 Dt);this._restrictedTelemetryEnabled=!1;this._onDidChangeRestrictedTelemetry=this._register(new A);this.onDidChangeRestrictedTelemetry=this._onDidChangeRestrictedTelemetry.event;this._sessions=this._register(new we);this._chatBackings=new Map;this._onDidChangeChatData=this._register(new A);this.onDidChangeChatData=this._onDidChangeChatData.event;this._mcpNotificationSubs=this._register(new we);this._resumingSessions=new Map;this._provisionalSessions=new Map;this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._sessionSequencer=new at;this._activeClients=new qe;this._lastSessionSyncEnabled=this._isSessionSyncEnabled();this._lastRubberDuckEnabled=this._isRubberDuckEnabled();this._lastEnterpriseHost=this._getEnterpriseHost();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,i,s)=>this._sendMessage(e,t,r,i,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(vu)),this._sessionLauncher=this._instantiationService.createInstance(xl),this._slashCommandProvider=new Ci(()=>this._ensureClient().then(I=>I.rpc.commands.list().then(_=>_.commands)),this._logService),this.onDidCustomizationsChange=this._plugins.onDidChange,this._register(this._onDidSessionProgress.event(I=>this._emitSpawnedChatForSubagentSignal(I))),this._register(c.registerProvider(new Ym(this.id,{isRubberDuckEnabled:()=>this._isRubberDuckEnabled(),getRuntimeSlashCommands:(I,_)=>this._getRuntimeSlashCommands(I,_),getSessionCustomizations:I=>this.getSessionCustomizations(D.uri(this.id,I))},B7))),this._register(this._configurationService.onDidRootConfigChange(()=>{this._restartClientIfStartupConfigChanged().catch(I=>this._logService.error("[Copilot] Failed to restart client after config change",I))})),this._register(this._byokBridgeRegistry.onDidChangeModels(()=>{this._logService.info("[Copilot] BYOK bridge changed; refreshing models"),this._refreshByokModels()})),this._register(this._gitHubEndpointService.onDidChange(()=>{this._restartClientIfStartupConfigChanged().catch(I=>this._logService.error("[Copilot] Failed to restart client after endpoint change",I))}))}static{this._BRANCH_COMPLETION_LIMIT=25}setServerToolHost(e){this._serverToolHost=e}get restrictedTelemetryEnabled(){return this._restrictedTelemetryEnabled}_emitSpawnedChatForSubagentSignal(e){let t=Bi.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_isSessionSyncEnabled(){return this._configurationService.getRootValue(Ut,Vd)===!0}_isRubberDuckEnabled(){return this._configurationService.getRootValue(mn,"rubberDuck")===!0}_getEnterpriseHost(){return this._gitHubEndpointService.getEnterpriseHost()}_isPreferLongContextEnabled(){return this._configurationService.getRootValue(Ut,Cv)===!0}async _restartClientIfStartupConfigChanged(){let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled(),r=this._getEnterpriseHost();if(this._lastSessionSyncEnabled===e&&this._lastRubberDuckEnabled===t&&this._lastEnterpriseHost===r)return;let i=[this._lastSessionSyncEnabled!==e?`sessionSync=${e}`:void 0,this._lastRubberDuckEnabled!==t?`rubberDuck=${t}`:void 0,this._lastEnterpriseHost!==r?`enterpriseHost=${r}`:void 0].filter(s=>s!==void 0).join(", ");this._lastSessionSyncEnabled=e,this._lastRubberDuckEnabled=t,this._lastEnterpriseHost=r,this._client&&(this._logService.info(`[Copilot] Startup config changed (${i}), restarting CopilotClient`),this._sessions.clearAndDisposeAll(),this._mcpNotificationSubs.clearAndDisposeAll(),await this._stopClient())}_createCopilotClient(e){return new W7(e)}getDescriptor(){return{provider:"copilotcli",displayName:"Copilot",description:f(2214,null),capabilities:{multipleChats:{fork:!0}}}}getProtectedResources(){return[this._gitHubEndpointService.getCopilotResource(),this._gitHubEndpointService.getRepoResource()]}async getNetworkDiagnosticsEndpoints(){let e=process.env.VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE||GE;if(this._githubToken)try{e=await this._copilotApiService.resolveApiEndpoint(this._githubToken)||e}catch(r){this._logService.debug(`[Copilot] CAPI endpoint discovery for network diagnostics failed; using ${e}: ${r instanceof Error?r.message:String(r)}`)}let t=new URL(e);return t.pathname=`${t.pathname.replace(/\/$/,"")}/_ping`,[{name:"GitHub API",url:this._gitHubEndpointService.getApiBaseUri()},{name:"Copilot API (CAPI)",url:t.toString()}]}async getNetworkDiagnosticsAccount(){return this._githubToken?this._copilotApiService.resolveUserLogin?.(this._githubToken):void 0}getCustomizations(){return this._plugins.getConfiguredHostCustomizations()}async getSessionCustomizations(e){let t=await this._getSessionCustomizationDirectory(e),i=await this._getOrCreateActiveClient(e,t).pluginController.getCustomizationsSettled(),s=D.id(e),l=this._findAnySession(s)?.topLevelMcpCustomizations()??[];return l.length===0?i:[...i,...l]}async handleMcpRequest(e,t,r,i){let s=D.id(e),a=this._findAnySession(s);if(!a)throw new Error(`Method not found: no active session ${s}`);return a.handleMcpRequest(t,r,i)}async startMcpServer(e,t){let r=D.id(e);await this._findAnySession(r)?.startMcpServer(t)}async stopMcpServer(e,t){let r=D.id(e);await this._findAnySession(r)?.stopMcpServer(t)}async _getSessionCustomizationDirectory(e){let t=D.id(e),r=this._provisionalSessions.get(t);if(r)return r.workingDirectory;let i=this._findAnySession(t),s=i?void 0:await this._readSessionMetadata(e);return i?.customizationDirectory??s?.workingDirectory??s?.customizationDirectory}async authenticate(e,t){if(e===this._gitHubEndpointService.getRepoResource().resource)return!0;if(e!==this._gitHubEndpointService.getCopilotResource().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 i of r.allChatSessions()){let s=await i.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()),BS(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 i=this._modelRefreshBackoff(e);this._logService.warn(`[Copilot] Failed to refresh models (attempt ${e+1}), retrying in ${i}ms`,r),this._modelRefreshRetry.value=qt(()=>{this._refreshModels(e+1)},i);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=>{let t=NA(e.modelIdentifier);return{provider:this.id,id:`${e.vendor}/${e.id}`,name:e.name??e.id,maxContextWindow:e.maxContextWindowTokens,supportsVision:e.supportsVision??!1,...t&&{_meta:t}}}),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=(i,s)=>(i==="session.create"||i==="session.resume")&&s&&typeof s=="object"?r(i,{...s,requestExitPlanMode:!0}):r(i,s)}async _ensureClient(){if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled(),r=this._getEnterpriseHost(),i=(async()=>{this._logService.info("[Copilot] Starting CopilotClient...");let s=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete s.NODE_OPTIONS,delete s.VSCODE_INSPECTOR_OPTIONS,delete s.VSCODE_ESM_ENTRYPOINT,delete s.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let b of Object.keys(s))b!=="ELECTRON_RUN_AS_NODE"&&b!=="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE"&&(b.startsWith("VSCODE_")||b.startsWith("ELECTRON_"))&&delete s[b];if(s.COPILOT_CLI_RUN_AS_NODE="1",s.USE_BUILTIN_RIPGREP="false",s.COPILOT_MCP_APPS="true",await this._configureProxyEnv(s),process.platform==="linux"){let b=s.COPILOT_CLI_ENABLED_FEATURE_FLAGS,I=new Set((b??"").split(",").map(_=>_.trim()).filter(Boolean));I.add("SHELL_SPAWN_BACKEND"),s.COPILOT_CLI_ENABLED_FEATURE_FLAGS=[...I].join(",")}s.GITHUB_COPILOT_INTEGRATION_ID=nb,this._logService.info(`[Copilot] Set CLI env: GITHUB_COPILOT_INTEGRATION_ID=${nb}`);let a=this._getEnterpriseHost();a&&(s.COPILOT_GH_HOST=a,this._logService.info(`[Copilot] Set CLI env: COPILOT_GH_HOST=${a}`)),this._isRubberDuckEnabled()?s.RUBBER_DUCK_AGENT="true":delete s.RUBBER_DUCK_AGENT;let l=Lt.asFileUri(kg()),d=await J7(l);s.MXC_BIN_DIR=h.joinPath(l,"@microsoft","mxc-sdk","bin").fsPath;let c=await nl(),u=oe(c),p=Object.keys(s).find(b=>b.toUpperCase()==="PATH")??"PATH",m=s[p];s[p]=m?`${m}${Hs}${u}`:u,this._logService.info(`[Copilot] Resolved CLI path: ${d}`);let v=await this._otelService.getSdkTelemetryConfig(),y={useLoggedInUser:!1,connection:q7.forStdio({path:d}),env:s,telemetry:v,logLevel:j7(this._logService.getLevel()),enableRemoteSessions:this._isSessionSyncEnabled()},S=this._createCopilotClient(y);if(await S.start(),this._isSessionSyncEnabled()!==e||this._isRubberDuckEnabled()!==t||this._getEnterpriseHost()!==r)throw await S.stop(),new Error("Copilot startup config changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._enablePlanModeOnClient(S),this._client=S,this._clientStarting=void 0,S})();return this._clientStarting=i,i.catch(()=>{this._clientStarting=void 0}),i}_createThinkingLevelConfigSchemaProperty(e,t){if(e?.length)return{type:"string",title:f(2213,null),description:f(2212,null),default:t,enum:[...e],enumLabels:e.map(ms),enumDescriptions:e.map(r=>hs(r)??"")}}_createContextSizeConfigSchemaProperty(e){let t=e?.tokenPrices,r=t?.contextMax,i=t?.longContext?.contextMax;if(!(!r||!i||r>=i))return this._isPreferLongContextEnabled()&&!Hb(e)?{type:"number",title:f(2211,null),description:f(2209,null),default:i,enum:[i],enumLabels:[mm(i)],enumDescriptions:[f(2210,null)]}:{type:"number",title:f(2211,null),description:f(2209,null),default:r,enum:[r,i],enumLabels:[mm(r),mm(i)],enumDescriptions:[f(2208,null),f(2210,null)]}}_longContextWindowFor(e){if(!e)return;let r=this._models.get().find(i=>i.id===e)?.configSchema?.properties?.[jm]?.enum?.filter(i=>typeof i=="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 yl(t,r)}_createModelConfigSchema(e){let t={},r=this._createThinkingLevelConfigSchemaProperty(e.supportedReasoningEfforts,e.defaultReasoningEffort);r&&(t[Zb]=r);let i=this._createContextSizeConfigSchemaProperty(e.billing);if(i&&(t[jm]=i),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 i={};for(let[s,a]of Object.entries(t.config))typeof a=="string"&&(i[s]=a);Object.keys(i).length>0&&(r.config=i)}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{}}_resolveAgentName(e,t){for(let r of e.plugins){let i=r.agents.find(s=>s.uri.toString()===t.uri);if(i)return i.name}}async listSessions(){this._logService.info("[Copilot] Listing sessions...");let t=await(await this._ensureClient()).listSessions(),r=new Bo(4),i=new Map,a=(await Promise.all(t.map(async l=>{let d=D.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,i),this._storeSessionProjectResolution(d,u));let m=c.workingDirectory??(typeof l.context?.workingDirectory=="string"?h.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=D.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 Bo(1);a=await this._resolveSessionProject(s?.context,d,new Map),this._storeSessionProjectResolution(e,a)}let l=r?.workingDirectory??(typeof s?.context?.workingDirectory=="string"?h.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 i=this._isPreferLongContextEnabled(),s=r.map(a=>{let l=this._createModelConfigSchema(a),d=a.billing?.tokenPrices,c=!!d?.contextMax&&!!d.longContext?.contextMax&&d.longContext.contextMax>d.contextMax;return i&&c&&!Hb(a.billing)&&this._freeLongContextModels.add(a.id),{provider:this.id,id:a.id,name:a.name,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:l,policyState:a.policy?.state,_meta:this._createModelPricingMeta(a)}});return this._logService.info(`[Copilot] Found ${s.length} models: ${s.map(a=>a.name).join(", ")}`),s}async _resolveCreateWorkingDirectory(e,t,r){let i=e.workingDirectory??this._provisionalSessions.get(t)?.workingDirectory;if(i)return i;if(r){let l=this._workspacelessScratchDir(t);return await ht.mkdir(l.fsPath,{recursive:!0}),l}let s=await ht.mkdtemp(j(nh.tmpdir(),"agent-host-session-")),a=h.file(s);return this._logService.trace(`[Copilot] No workingDirectory provided, defaulting to temp directory: ${a.fsPath}`),a}_workspacelessScratchDir(e){return Fb(this._environmentService.userHome,e)}async _ensureWorkspacelessScratchDir(e,t){try{await ht.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 ht.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=ke(e);if(!t)throw new Error(`Copilot chat operation requires an AHP chat URI: ${e.toString()}`);return{session:h.parse(t.session),chat:e}}_getChatContext(e){let t=ke(e)?e:h.parse(pe(e)),r=h.parse(fe(t)),i=D.id(r),s=t.toString(),a=this._sessions.get(i)?.resolveChat(s);return{session:r,sessionId:i,chatKey:s,target:a?.chatSession,isPeerChat:a?!a.isDefault:s!==pe(r)}}_findAnySession(e){return this._sessions.get(e)?.defaultChat}_getRuntimeSlashCommands(e,t){let r=this._findAnySession(e);return r?r.getRuntimeSlashCommands(t)??[]:this._slashCommandProvider.getSlashCommands(t)}_findPeerChat(e,t){return this._sessions.get(D.id(e))?.getPeerChat(t.toString())}_ensureEntry(e){let t=this._sessions.get(e);return t||(t=new bs,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?D.id(t.session):O(),i=!t.fork&&!t.workingDirectory,s=await this._resolveCreateWorkingDirectory(t,r,i),a=await this._ensureClient();if(t.fork){let u=D.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=h.joinPath(S,ga);try{let P=await this._sessionDataService.tryOpenDatabase(t.fork.session);if(P)try{await ht.mkdir(S.fsPath,{recursive:!0}),await ht.rm(b.fsPath,{force:!0}),await P.object.vacuumInto(b.fsPath)}finally{P.dispose()}}catch(P){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${P instanceof Error?P.message:String(P)}`)}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(P){this._logService.warn(`[Copilot] Failed to copy reviewed ref for fork: ${P instanceof Error?P.message:String(P)}`)}let T=await Qn({cwd:s.fsPath},this._gitService);return await this._storeSessionMetadata(_,t.model,s,s,T,!0),t.agent!==void 0&&await this._storeSessionAgentMetadata(_,t.agent),{session:_,workingDirectory:s,...T?{project:T}:{}}})}if(t.importConversation)return this._importConversation(t,r,s);let l=D.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 Qn({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 Qn({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:i}),this._logService.info(`[Copilot] Session created (provisional): ${l.toString()}`),{session:l,workingDirectory:s,provisional:!0,...c?{project:c}:{}}}_copilotConfigRoot(){return process.env.COPILOT_HOME||j(nh.homedir(),".copilot")}async _importConversation(e,t,r){let i=e.importConversation,s=D.uri(this.id,t);return this._sessionSequencer.queue(t,async()=>{this._logService.info(`[Copilot] Importing conversation into session ${t} (${i.turns.length} turns)`);let a=i.model??e.model,l=Qn({cwd:r.fsPath},this._gitService),d=j(this._copilotConfigRoot(),"session-state",t,"events.jsonl"),c=FA(i.turns,{sessionId:t,workingDirectory:r.fsPath,model:a?.id});await ht.mkdir(oe(d),{recursive:!0}),await ht.writeFile(d,c,"utf8");let u=await l;return await this._storeSessionMetadata(s,a,r,r,u),e.agent!==void 0&&await this._storeSessionAgentMetadata(s,e.agent),await this._resumeSession(t),this._logService.info(`[Copilot] Imported session created: ${s.toString()}`),{session:s,workingDirectory:r,...u?{project:u}:{}}})}async _materializeProvisional(e,t){let r=this._provisionalSessions.get(e);if(!r)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let i=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(xo,s,d),v,y;try{let b=await this._resolveAgentWhenMaterializing(r,p,d);y=b?.agent;let I={kind:"create",client:i,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};v=this._createAgentSession(I,c,u),await v.initializeSession(),this._registerInitializedSession(e,v)}catch(b){throw v?.dispose(),await this._removeCreatedWorktree(e),b}let S=await Qn({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}),v}async _resolveAgentWhenMaterializing(e,t,r){let i=e.agent;if(!i)return;let s=this._getAlternativeAgentForWorktree(e,r),a=this._resolveAgentName(t,i),l=s?this._resolveAgentName(t,s):void 0;if(a)return{agent:i,name:a};if(l&&s)return this._logService.info(`[Copilot] Agent file ${i.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||Tr(e.workingDirectory,t))return;let i=h.parse(r.uri),s=XE(i,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=ce({type:"string",title:f(2197,null),description:f(2202,null),enum:t?["folder","worktree"]:["folder"],enumLabels:t?[f(2198,null),f(2200,null)]:[f(2198,null)],enumDescriptions:t?[f(2199,null),f(2201,null)]:[f(2199,null)],default:t?"worktree":"folder",readOnly:!t,sessionMutable:!1}),i=t?"worktree":"folder",s=r.validate(e.config?.isolation)?e.config.isolation:i,a,l,d,c;if(t){let m=s==="folder";l=s==="worktree"?t.defaultBranch:t.currentBranch,a=ce({type:"string",title:f(2195,null),description:f(2196,null),enum:[l],enumLabels:[l],default:l,enumDynamic:!m,readOnly:m,sessionMutable:!1}),d=ce({type:"string",title:f(2203,null),description:f(2204,null),readOnly:!0,sessionMutable:!1}),c=ce({type:"array",title:f(2205,null),description:f(2206,null),items:{type:"string",title:f(2207,null)},readOnly:!0,sessionMutable:!1})}let u=nn({isolation:r,...Yt.definition,...a?{branch:a}:{},...d?{worktreeBranchPrefix:d}:{},...c?{worktreeIncludeFiles:c}:{}}),p=u.validateOrDefault(Sw(e.config),{isolation:s,autoApprove:"default",mode:"interactive",...l!==void 0?{branch:l}:{}});return{schema:u.toProtocol(),values:p}}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(i=>r.pluginController.setDirectory(i),()=>{}),r.getOrCreateHandle(t.clientId,t.displayName)}removeActiveClient(e,t){let r=D.id(e);this._logService.info(`[Copilot:${r}] removeActiveClient: clientId=${t}`),this._activeClients.get(e)?.removeClient(t)}onClientToolCallComplete(e,t,r,i){let s=D.id(e);if(Fe(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=${i.success}`);return}this._logService.info(`[Copilot:${s}] Routing client tool completion to default chat: chat=${t.toString()}, toolCallId=${r}, success=${i.success}`),a.handleClientToolCallComplete(r,i)}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=${i.success}`);return}this._logService.info(`[Copilot:${s}] Routing client tool completion to peer chat: chat=${t.toString()}, toolCallId=${r}, success=${i.success}`),a.handleClientToolCallComplete(r,i)}}setCustomizationEnabled(e,t){for(let r of this._activeClients.values())r.pluginController.setEnabled(e,t)}async _sendMessage(e,t,r,i,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()}`);i&&l.resetTurnState(i,s),await l.send(t,r,i,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),i&&l.resetTurnState(i,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,i,p,s)}catch(p){let m=p?.code,v=p instanceof Error?p.message:String(p);throw this._logService.error(`[Copilot:${a.sessionId}] entry.send() failed: code=${m}, message=${v}, hadCachedEntry=${c}, errorType=${p?.constructor?.name}`),p}})}_resolveSdkMode(e){let t=e.toString();switch(this._configurationService.getEffectiveValue(t,Yt,"mode")){case"plan":return"plan";case"autopilot":return"autopilot";case"interactive":return"interactive";default:return}}setPendingMessages(e,t,r){let i=D.id(e),s=this._findAnySession(i);if(!s){this._logService.warn(`[Copilot:${i}] setPendingMessages: session not found`);return}t&&s.sendSteering(t)}async getSessionMessages(e){let t=ut(e);if(t){let c=t.parentSession,u;for(;u=ut(c);)c=u.parentSession;let p=D.id(c),m=this._findAnySession(p)??await this._resumeSession(p).catch(v=>{this._logService.warn(`[Copilot:${p}] Failed to resume root for subagent restore`,v)});return m?m.getSubagentMessages(t.toolCallId):[]}let r=ke(e)?e:h.parse(pe(e)),i=this._getChatContext(r);if(i.isPeerChat){let c=await this._ensureChatSession(i.session,r);return c?c.getMessages():[]}let s=i.sessionId;if(this._provisionalSessions.has(s))return[];let a=i.target??await this._resumeSession(s).catch(c=>{if(c instanceof bu)throw 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(i.session).catch(c=>{this._logService.warn(`[Copilot:${s}] Failed to read worktree branch metadata`,c)});return d?.branchName?Z7(l,YE(d.branchName)):l}async getSubagentSessions(e){if(ke(e)&&!Fe(e))return[];if(ut(e))return[];let r=D.id(e);if(this._provisionalSessions.has(r))return[];let i=this._findAnySession(r)??await this._resumeSession(r).catch(s=>{this._logService.warn(`[Copilot:${r}] Failed to resume session for subagent lookup`,s)});return i?i.getSubagentSessions():[]}async disposeSession(e){let t=D.id(e);await this._sessionSequencer.queue(t,async()=>{let r=this._provisionalSessions.get(t),i=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),i&&await this._cleanupWorkspacelessScratchDir(this._workspacelessScratchDir(t),t)})}async releaseSession(e){let t=D.id(e);await this._sessionSequencer.queue(t,async()=>{if(this._provisionalSessions.has(t))return;let r=this._sessions.get(t);r&&(r.allChatSessions().some(i=>i.hasActiveTurn)||(this._logService.info(`[Copilot:${t}] Releasing idle session from memory (durable state preserved)`),await this._releaseSessionResources(t)))})}async onArchivedChanged(e,t){let r=D.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:i,worktreePath:s,repositoryRoot:a}=r;try{await ht.access(s.fsPath)}catch{this._createdWorktrees.delete(t);return}if(!await this._gitService.branchExists(a,i).catch(()=>!1)){this._logService.info(`[Copilot:${t}] Skipping worktree cleanup: branch '${i}' 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)){try{await ht.access(r.worktreePath.fsPath);return}catch{}await this._recreateWorktree(t,{branchName:r.branchName,worktreePath:r.worktreePath,repositoryRoot:r.repositoryRoot})}}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(Fe(e))return;let r=ke(e);if(!r)throw new Error(`[Copilot] createChat: malformed chat URI ${e.toString()}`);let i=h.parse(r.session),s=e.toString();if(this._sessions.get(D.id(i))?.hasPeerChat(s)){let d=this._chatBackings.get(s);return d?{providerData:qr(d),backingSession:D.uri(this.id,d.sdkSessionId)}:void 0}let a=D.id(i),l;return await this._sessionSequencer.queue(a,async()=>{if(this._sessions.get(a)?.hasPeerChat(s)){let T=this._chatBackings.get(s);l=T?{providerData:qr(T),backingSession:D.uri(this.id,T.sdkSessionId)}:void 0;return}let d=t?.model,u=this._findAnySession(a)?.workingDirectory??this._provisionalSessions.get(a)?.workingDirectory,p=await this._ensureClient(),m=O(),v=this._getOrCreateActiveClient(i,u),y=await v.snapshot(),S=this._instantiationService.createInstance(xo,e,u),b,I;if(t?.fork){if(!u)throw new Error(`[Copilot] createChat fork: missing working directory for session ${i.toString()}`);let T=await this._resolveChatEntry(i,t.fork.source);if(!T)throw new Error(`[Copilot] createChat fork: source chat ${t.fork.source.toString()} not found`);I=await this._forkSdkChat(p,T,t.fork.turnId,this._sessionDataService.getSessionDataDir(e)),b={kind:"resume",client:p,sessionId:I,workingDirectory:u,resolvedAgentName:void 0,snapshot:y,activeClientToolSet:v.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:v.toolSet,shellManager:S,githubToken:this._githubToken,model:d,longContextWindow:this._longContextWindowFor(d?.id),freeLongContext:this._isFreeLongContext(d?.id)};let _;try{_=this._createAgentSession(b,u,v,e),await _.initializeSession(),t?.fork?.turnIdMapping&&await _.remapTurnIds(t.fork.turnIdMapping),this._ensureEntry(a).registerPeerChat(s,new bs(_));let T={sdkSessionId:I,...d?{model:d}:{}};this._chatBackings.set(s,T),l={providerData:qr(T),backingSession:D.uri(this.id,I)},this._logService.info(`[Copilot] Created additional chat ${s} in session ${i.toString()}${t?.fork?" (forked)":""}`)}catch(T){throw _?.dispose(),T}}),l}async _resolveChatEntry(e,t){let r=D.id(e);return Fe(t)||Tr(t,e)?this._findAnySession(r)??await this._resumeSession(r).catch(()=>{}):this._ensureChatSession(e,t)}async _forkSdkChat(e,t,r,i){let s=await t.getNextTurnEventId(r),l=(await e.rpc.sessions.fork({sessionId:t.sessionId,...s?{toEventId:s}:{}})).sessionId,d=h.joinPath(i,ga);try{let c=await this._sessionDataService.tryOpenDatabase(t.sessionUri);if(c)try{await ht.mkdir(i.fsPath,{recursive:!0}),await ht.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(Fe(t))return;let r=t.toString(),i=this._findPeerChat(e,t)?.sessionId??this._chatBackings.get(r)?.sdkSessionId;if(!i){let s=ke(t);s&&(i=(await this._readPersistedChats(e)).get(s.chatId)?.sdkSessionId)}if(this._chatBackings.delete(r),this._sessions.get(D.id(e))?.disposePeerChat(r),i)try{await(await this._ensureClient()).deleteSession(i)}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(Fe(e))return;let r=ke(e);if(!r)return;let i=e.toString(),s;if(t!==void 0){if(s=wm(t),!s){this._logService.warn(`[Copilot] materializeChat: dropping corrupt providerData for ${i}`);return}}else if(s=(await this._readPersistedChats(h.parse(r.session))).get(r.chatId),!s)return;this._chatBackings.set(i,s)}async listLegacyChats(e){let t=await this._readPersistedChats(e),r=[];for(let[i,s]of t)r.push({uri:h.parse(Jo(e,i)),providerData:qr(s)});return r}async _resolveChatBacking(e,t){let r=t.toString(),i=this._chatBackings.get(r);if(i)return i;let s=ke(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(),i=this._findPeerChat(e,t);if(i)return i;if(!ke(t))return;let a=D.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),v=await m.snapshot(),y=this._instantiationService.createInstance(xo,t,u),S={kind:"resume",client:p,sessionId:d.sdkSessionId,workingDirectory:u,resolvedAgentName:void 0,snapshot:v,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 bs(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 i=D.id(e);if(this._provisionalSessions.has(i))return;let s=!Fe(r);await this._sessionSequencer.queue(i,async()=>{this._logService.info(`[Copilot:${i}] 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(i)??await this._resumeSession(i);if(!a){this._logService.info(`[Copilot:${i}] 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:${i}] No event ID found for truncation, nothing to truncate`),this._logService.info(`[Copilot:${i}] Session truncated`)})}async _changeModel(e,t){let r=this._longContextWindowFor(t.id),i=this._isFreeLongContext(t.id),s=this._getChatContext(e);if(s.isPeerChat){await s.target?.setModel(t.id,Km(t,this._configurationService,this._logService,s.sessionId),Gm(t,r,i));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:qr(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,Km(t,this._configurationService,this._logService,s.sessionId),Gm(t,r,i)),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?this._resolveAgentName(r.target.appliedSnapshot,t):void 0;await r.target.setAgent(a)}return}let i=this._provisionalSessions.get(r.sessionId);if(i){i.agent=t;return}let s=r.target;if(s){let a=t?this._resolveAgentName(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 i of r.allChatSessions())if(i.respondToPermissionRequest(e,t))return}respondToUserInputRequest(e,t,r){for(let i of this._sessions.values())for(let s of i.allChatSessions())if(s.respondToUserInputRequest(e,t,r))return}hasSession(e){let t=D.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 V7)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(z7.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||GE;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 i=ke(h.parse(r));i&&D.id(i.session)===e&&this._chatBackings.delete(r)}}_getOrCreateActiveClient(e,t){let r=this._activeClients.get(e);if(r)t&&r.pluginController.setDirectory(t);else{let i=this._plugins.createSessionController(t);r=this._instantiationService.createInstance(Su,e,i,this._onDidSessionProgress),this._activeClients.set(e,r)}return r}_createAgentSession(e,t,r,i){let s=i??D.uri(this.id,e.sessionId),a=i??h.parse(pe(s)),l=this._instantiationService.createInstance(El,{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=>lm(r.pluginController.getCustomizations(),d),serverToolHost:this._serverToolHost});return this._mcpNotificationSubs.set(e.sessionId,Vu(l.onMcpNotification(d=>this._onMcpNotification.fire(d)),jn(d=>r.pluginController.mcpServerStates.set(l.mcpServerStates.read(d),void 0)))),l}_registerInitializedSession(e,t){if(this._shutdownPromise)throw t.dispose(),new K;let r=pe(t.sessionUri.toString()),i=this._sessions.get(e);i||(i=new bs,this._sessions.set(e,i)),i.setDefaultChat(r,new bs(t))}async _destroyAndDisposeSession(e){await this._releaseSessionResources(e),await this._removeCreatedWorktree(e)}async _releaseSessionResources(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),i=D.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(i)?.dispose(),this._activeClients.delete(i)}_resumeSession(e){let t=this._resumingSessions.get(e);if(t)return t;let r=this._doResumeSession(e);this._resumingSessions.set(e,r);let i=()=>{this._resumingSessions.get(e)===r&&this._resumingSessions.delete(e)};return r.then(i,i),r}async _doResumeSession(e){this._logService.info(`[Copilot:${e}] _resumeSession called \u2014 session not in memory, resuming...`);let t=await this._ensureClient(),r=D.uri(this.id,e),i=await this._readSessionMetadata(r),s=await t.getSessionMetadata(e).catch(S=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,S)}),a=i.workingDirectory??(typeof s?.context?.workingDirectory=="string"?h.file(s.context.workingDirectory):void 0);if(!a)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);let l=a;i.workspaceless?await this._ensureWorkspacelessScratchDir(a,e):l=await this._ensureResumeWorkingDirectory(r,e,a);let d=l,c=this._getOrCreateActiveClient(r,d);c.pluginController.reanchor(d);let u=await c.snapshot(),p=this._instantiationService.createInstance(xo,r,l),m=i.agent?this._resolveAgentName(u,i.agent):void 0;i.agent&&!m&&this._logService.info(`[Copilot:${e}] Stored custom agent is not available in the current plugin snapshot; resuming without a custom agent`);let v={kind:"resume",client:t,sessionId:e,workingDirectory:l,resolvedAgentName:m,snapshot:u,activeClientToolSet:c.toolSet,shellManager:p,githubToken:this._githubToken,workspaceless:i.workspaceless,fallback:{model:i.model,longContextWindow:this._longContextWindowFor(i.model?.id),freeLongContext:this._isFreeLongContext(i.model?.id)}},y=this._createAgentSession(v,d,c);try{await y.initializeSession()}catch(S){throw y.dispose(),S}return this._registerInitializedSession(e,y),y}async _ensureResumeWorkingDirectory(e,t,r){if(r.scheme!==ne.file)return r;try{return await ht.access(r.fsPath),r}catch{}let i=await this._readWorktreeMetadata(e).catch(()=>{});if(await this._isSessionArchived(e)){if(i?.repositoryRoot)try{return await ht.access(i.repositoryRoot.fsPath),this._logService.info(`[Copilot:${t}] Archived session working directory '${r.fsPath}' is missing; resuming against repository root '${i.repositoryRoot.fsPath}' for history`),i.repositoryRoot}catch{}throw this._logService.warn(`[Copilot:${t}] Cannot resume archived session: working directory '${r.fsPath}' is missing and no usable repository-root fallback was found`),new bu(r)}let a;if(i?.worktreePath&&i.repositoryRoot){let l=await this._recreateWorktree(t,{branchName:i.branchName,worktreePath:i.worktreePath,repositoryRoot:i.repositoryRoot});if(l.ok)return this._logService.info(`[Copilot:${t}] Recreated missing worktree '${i.worktreePath.fsPath}' for a live session on resume`),i.worktreePath;a=l.reason}throw this._logService.warn(`[Copilot:${t}] Cannot resume: working directory '${r.fsPath}' is missing and its worktree could not be recreated${a?`: ${a}`:""}`),new bu(r,a)}async _isSessionArchived(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(!t)return!1;try{let[r,i]=await Promise.all([t.object.getMetadata(qn),t.object.getMetadata(xr)]);return r!==void 0?r==="true":i==="true"}finally{t.dispose()}}async _recreateWorktree(e,t){let{branchName:r,worktreePath:i,repositoryRoot:s}=t;if(!await this._gitService.branchExists(s,r).catch(()=>!1)){let l=f(2219,null,r);return this._logService.info(`[Copilot:${e}] Cannot recreate worktree: branch '${r}' is missing`),{ok:!1,reason:l}}try{return await ht.mkdir(h.joinPath(i,"..").fsPath,{recursive:!0}),await this._gitService.addExistingWorktree(s,i,r),this._createdWorktrees.set(e,{repositoryRoot:s,worktree:i}),this._logService.info(`[Copilot:${e}] Recreated worktree '${i.fsPath}'`),{ok:!0}}catch(l){let d=l instanceof Error?l.message:String(l);return this._logService.warn(`[Copilot:${e}] Failed to recreate worktree '${i.fsPath}': ${d}`),{ok:!1,reason:d}}}async _getGitInfo(e){let t=await this._gitService.getRepositoryRoot(e);if(!t||!await this._gitService.revParse(t,"HEAD").catch(()=>{}))return;let i=await this._gitService.getCurrentBranch(t)??"HEAD",s=await this._gitService.getDefaultBranch(t)??i;return{currentBranch:i,defaultBranch:s}}async _getBranches(e,t){return this._gitService.getBranches(e,{query:t,limit:Ae._BRANCH_COMPLETION_LIMIT})}async _resolveSessionWorkingDirectory(e,t,r){if(e?.config?.isolation!=="worktree"||!e.workingDirectory||typeof e.config.branch!="string")return e?.workingDirectory;let i=await this._gitService.getRepositoryRoot(e.workingDirectory);if(!i)return e.workingDirectory;let s=Y7(i),a=typeof e.config.worktreeBranchPrefix=="string"?e.config.worktreeBranchPrefix:void 0,l=await this._branchNameGenerator.generateBranchName({sessionId:t,message:r,githubToken:this._githubToken,branchPrefix:a,branchExists:m=>this._gitService.branchExists(i,m).catch(()=>!0)}),d=h.joinPath(s,Q7(l,a));await ht.mkdir(s.fsPath,{recursive:!0});let c=typeof e.config.branch=="string"?e.config.branch:void 0;await this._gitService.addWorktree(i,d,l,c);let u=Array.isArray(e.config.worktreeIncludeFiles)&&e.config.worktreeIncludeFiles.every(m=>typeof m=="string")?e.config.worktreeIncludeFiles:void 0;if(u?.length)try{await this._gitService.copyWorktreeIncludeFiles(i,d,u)}catch(m){this._logService.warn(`[Copilot:${t}] Failed to copy worktree include files: ${m instanceof Error?m.message:String(m)}`)}this._createdWorktrees.set(t,{repositoryRoot:i,worktree:d}),this._pendingFirstTurnAnnouncements.set(t,YE(l));let p=D.uri(this.id,t);try{await this._writeWorktreeMetadata(p,{branchName:l,baseBranch:c,worktreePath:d,repositoryRoot:i})}catch(m){this._logService.warn(`[Copilot:${t}] Failed to persist worktree branch metadata: ${m instanceof Error?m.message:String(m)}`)}return d}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(Ae._META_CHATS);if(!r)return new Map;let i=JSON.parse(r),s=new Map;for(let[a,l]of Object.entries(i)){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 i=[r.object.setMetadata(Ae._META_WORKTREE_BRANCH,t.branchName),r.object.setMetadata(Ae._META_WORKTREE_PATH,t.worktreePath.toString()),r.object.setMetadata(Ae._META_WORKTREE_REPOSITORY_ROOT,t.repositoryRoot.toString())];t.baseBranch&&i.push(r.object.setMetadata(Ta,t.baseBranch)),await Promise.all(i)}finally{r.dispose()}}async _readWorktreeMetadata(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(t)try{let[r,i,s]=await Promise.all([t.object.getMetadata(Ae._META_WORKTREE_BRANCH),t.object.getMetadata(Ae._META_WORKTREE_PATH),t.object.getMetadata(Ae._META_WORKTREE_REPOSITORY_ROOT)]);if(!r)return;let a=i?h.parse(i):void 0,l=s?h.parse(s):void 0;return{branchName:r,worktreePath:a,repositoryRoot:l}}finally{t.dispose()}}async _storeSessionMetadata(e,t,r,i,s,a=s!==void 0){let l=this._sessionDataService.openDatabase(e),d=l.object;try{let c=[];t&&c.push(d.setMetadata(Ae._META_MODEL,this._serializeModelSelection(t))),r&&c.push(d.setMetadata(Ae._META_CWD,r.toString())),i&&c.push(d.setMetadata(Ae._META_CUSTOMIZATION_DIRECTORY,i.toString())),a&&c.push(d.setMetadata(Ae._META_PROJECT_RESOLVED,"true")),s&&(c.push(d.setMetadata(Ae._META_PROJECT_URI,s.uri.toString())),c.push(d.setMetadata(Ae._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,i,s,a,l]=await Promise.all([t.object.getMetadata(Ae._META_MODEL),t.object.getMetadata(Ae._META_AGENT),t.object.getMetadata(Ae._META_CWD),t.object.getMetadata(Ae._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(Wn)]);return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(i),workingDirectory:s?h.parse(s):void 0,customizationDirectory:a?h.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,i,s,a,l,d,c,u]=await Promise.all([t.object.getMetadata(Ae._META_MODEL),t.object.getMetadata(Ae._META_AGENT),t.object.getMetadata(Ae._META_CWD),t.object.getMetadata(Ae._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(Ae._META_PROJECT_RESOLVED),t.object.getMetadata(Ae._META_PROJECT_URI),t.object.getMetadata(Ae._META_PROJECT_DISPLAY_NAME),t.object.getMetadata(Wn)]),p=s?h.parse(s):void 0,m=d&&c?{uri:h.parse(d),displayName:c}:void 0;return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(i),workingDirectory:p,customizationDirectory:a?h.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(Ae._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 i=this._projectContextKey(e);if(!i)return Promise.resolve(void 0);let s=r.get(i);return s||(s=t.queue(()=>Qn(e,this._gitService)),r.set(i,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())}};Ae=R([C(0,M),C(1,xe),C(2,rt),C(3,Ye),C(4,He),C(5,xt),C(6,Rm),C(7,Em),C(8,bg),C(9,Mr),C(10,Ya),C(11,bt),C(12,vi),C(13,zn),C(14,Pt),C(15,yi)],Ae);var QE=100,sC=class extends w{constructor(e,t,r,i,s){super();this._onDidRefresh=r;this._logService=i;this._refreshDelayer=this._register(new Ni(QE));this._refreshPromise=null;this._pendingRefreshNotify=!1;this._customizations=[];this._discovery=this._register(s.createInstance(kl,e,t)),this._fileService=s.invokeFunction(a=>a.get(Pe)),this._settled=this._queueRefresh(!1,0),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,t=QE){return this._refreshPromise?.cancel(),this._refreshPromise=null,this._pendingRefreshNotify=this._pendingRefreshNotify||e,this._refreshDelayer.trigger(()=>{let r=this._pendingRefreshNotify;this._pendingRefreshNotify=!1;let i=this._refreshPromise=jo(async s=>{await this._refresh(s)&&r&&this._onDidRefresh()});return i.then(()=>{this._refreshPromise===i&&(this._refreshPromise=null)},s=>{if(this._refreshPromise===i&&(this._refreshPromise=null),!(s instanceof K))throw s})},t)}async _refresh(e){try{let t=await this._discovery.scan(e);if(e.isCancellationRequested||this._directories&&KE(this._directories,t))return!1;let r=await e9(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 e9(o,n){return Promise.all(o.map(async e=>{let t=e.uri.toString();return{type:"directory",id:Nt(t),uri:t,name:e.name,enabled:!0,contents:t9(e.type),writable:e.writable,load:{kind:"loaded"},children:await Promise.all(e.files.map(r=>n9(r.uri,e.type,n)))}}))}function t9(o){switch(o){case"agent":return"agent";case"skill":return"skill";case"instruction":case"agentInstruction":return"rule";case"hook":return"hook"}}async function n9(o,n,e){let t=o.toString(),r=Nt(t);if(n==="agent"){let i=await tu(o,e),s={type:"agent",id:r,uri:t,name:i.name,description:i.description};return i.userInvocable!==void 0&&(s._meta={userInvocable:i.userInvocable}),s}if(n==="skill"){let i=await Ub(o,e);return{type:"skill",id:r,uri:t,name:i.name,description:i.description}}if(n==="instruction"){let i=await Cm(o,e);return{type:"rule",id:r,uri:t,name:i.name,description:i.description,globs:i.globs,alwaysApply:i.alwaysApply}}return n==="hook"?{type:"hook",id:r,uri:t,name:ve(o)}:{type:"rule",alwaysApply:!0,id:r,uri:t,name:ve(o)}}function r9(o){if(o.length===0)return;let n=[],e=[],t=[];for(let r of o)for(let i of r.children??[]){if(i.type==="agent"){n.push({uri:h.parse(i.uri),name:i.name,description:i.description,customization:i});continue}if(i.type==="skill"){e.push({uri:h.parse(i.uri),name:i.name,description:i.description,customization:i});continue}if(i.type==="rule"){if(i.alwaysApply&&i.name.match(/\.md$/i))continue;t.push({uri:h.parse(i.uri),name:i.name,description:i.description,customization:i})}}if(!(n.length===0&&e.length===0&&t.length===0))return{hooks:[],mcpServers:[],skills:e,agents:n,instructions:t}}var vu=class extends w{constructor(e,t,r,i,s,a){super();this.pluginManager=e;this.logService=t;this.fileService=r;this._configurationService=i;this.instantiationService=s;this._environmentService=a;this._onDidChange=this._register(new A);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 aC(this,e)}_applyHostCustomizations(){let t=(this._configurationService.getRootValue(fr,"customizations")??[]).map(_R);if(Ne(t,this._lastAppliedRefs))return;this._lastAppliedRefs=t;let r=++this._hostRevision;this._hostCustomizations=t.map(i=>({customization:{...i,load:{kind:"loading"}}})),this._onDidChange.fire(),this._hostSync=Promise.all(t.map(i=>this.resolveConfiguredCustomization(i))).then(i=>(r===this._hostRevision&&(this._hostCustomizations=i),i)).finally(()=>{r===this._hostRevision&&this._onDidChange.fire()})}async resolveConfiguredCustomization(e){let t=h.parse(e.uri),r=await this.tryParsePlugin(t);return r?{customization:{...e,load:{kind:"loaded"},children:jb([r])},pluginDir:t,plugin:r}:{customization:{...e,load:{kind:"error",message:f(2215,null)}}}}async resolveSyncedCustomization(e,t,r){let i={...e.customization,clientId:t};if(!e.pluginDir)return{customization:i,input:r};let s=await this.tryParsePlugin(e.pluginDir);return s?{customization:{...i,children:jb([s])},pluginDir:e.pluginDir,plugin:s,input:r}:{customization:{...i,load:{kind:"error",message:f(2215,null)}},input:r}}async tryParsePlugin(e){try{return await Im(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}}};vu=R([C(0,vl),C(1,M),C(2,Pe),C(3,He),C(4,xe),C(5,bt)],vu);var aC=class extends w{constructor(e,t){super();this._parent=e;this._directory=t;this._onDidPublish=this._register(new A);this.onDidPublish=this._onDidPublish.event;this._enablement=new Map;this.mcpServerStates=rn(this,new Map);this._clients=new Map;this._sessionDiscovered=this._register(new Dt)}get directory(){return this._directory}setDirectory(e){this._directory||!e||(this._directory=e)}reanchor(e){if(this._directory&&Tr(this._directory,e))return;let t=this._directory;this._directory=e,this._sessionDiscovered.clear(),t&&this._migrateEnablement(t,e)}_migrateEnablement(e,t){let r=X7(this._enablement,e,t);this._enablement.clear();for(let[i,s]of r)this._enablement.set(i,s)}getCustomizations(){let e=[...this._parent.hostCustomizations().map(i=>this._projectForPublish(i.customization)),...this._flattenClientCustomizations().map(i=>this._projectForPublish(i.customization))],r=this._discoveredEntry()?.currentCustomizations()??[];for(let i of r)e.push(this._projectForPublish(i));return e}_flattenClientCustomizations(){let e=new Set,t=[];for(let r of this._clients.values())for(let i of r.customizations)e.has(i.customization.uri)||(e.add(i.customization.uri),t.push(i));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()??[],i=r.some(a=>this._isEnabled(a))?r9(r):void 0,s=i?[i]:[];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 i=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(Ne(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})),i||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);Ne(l.get(m.uri),m)||(l.set(m.uri,m),i||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)})}),v=await Promise.all(m.map(y=>this._parent.resolveSyncedCustomization(y,e,p.get(y.customization.uri))));if(a===s.revision){s.customizations=v;for(let y of v)d(y)}return v})).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 i=r.map(s=>s.input);this._parent.logService.info(`[Copilot:SessionPluginController] Retrying ${i.length} previously-failed client customization(s) for ${e}`),await this.sync(e,i).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 sC(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!==!1}_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 i=!1,s=r.map(a=>{if(a.type!=="mcpServer")return a;let l=t.get(a.id);return l?(i=!0,{...a,state:l.state,channel:l.channel}):a});return i?{...e,children:s}:e}},lC=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(()=>{})}},Su=class extends w{constructor(e,t,r,i){super();this._sessionUri=e;this._configurationService=i;this.toolSet=new hn;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 lC(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(Ut,_v)??{};return structuredClone(e)}async requiresRestart(e){let t=await this.pluginController.getAppliedPlugins();return!hE(e.plugins,t)||!Ne(e.mcpServers,this._getMcpServers())?!0:!this.toolSet.structuralEquals(e.tools)}};Su=R([C(3,He)],Su);function Cs(o){switch(o){case"default":case"acceptEdits":case"bypassPermissions":case"plan":case"auto":return o;default:return}}var ZE="thinkingLevel";function dC(o){if(o!==void 0)return o==="max"?"xhigh":o}function Cu(o){let n=o?.config?.[ZE];switch(n){case"low":case"medium":case"high":case"xhigh":case"max":return n;default:return}}var o9=["low","medium","high","xhigh","max"];function cC(o){return o9.includes(o)}function uC(o){if(o.length===0)return;let n=o.includes("high")?"high":void 0;return{type:"object",properties:{[ZE]:{type:"string",title:f(1958,null),description:f(1957,null),enum:[...o],enumLabels:o.map(ms),enumDescriptions:o.map(e=>hs(e)??""),...n!==void 0?{default:n}:{}}}}}import{pathToFileURL as o1}from"url";import*as n1 from"fs";import*as r1 from"tar";import{familySync as i9,MUSL as s9}from"detect-libc";var rh,e1=!1;function t1(){return e1||(Oe?rh=i9()===s9?"musl":"glibc":rh=void 0,e1=!0),rh}var a9=new Set(["linux","darwin","win32"]),l9=new Set(["x64","arm64"]);function pC(o,n={platform:process.platform,arch:process.arch,libc:t1()}){if(!(!a9.has(n.platform)||!l9.has(n.arch)))return n.platform==="linux"&&o.hasSeparateMuslLinuxPackage&&n.libc==="musl"?`linux-${n.arch}-musl`:`${n.platform}-${n.arch}`}var Ml=W("agentSdkDownloader"),d9=3e4,c9=250;function u9(o){if(typeof o!="string"||!/^\d+$/.test(o))return;let n=parseInt(o,10);return n>0?n:void 0}var Dl=class extends w{constructor(e,t,r,i,s){super();this._environmentService=e;this._productService=t;this._requestService=r;this._fileService=i;this._logService=s;this._onDidDownloadProgress=this._register(new A);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]&&pC(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=pC(e);if(!r)return!1;let i=h.joinPath(h.file(this._cacheDir(e.id,t.version,r)),".complete");return this._fileService.exists(i)}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 i=this._failureLatch.get(e.id);if(i&&i.expiresAt>Date.now())throw i.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()+d9}),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 i=pC(e);if(!i)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=b_(r.urlTemplate,{sdkTarget:i}),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,i),d=h.joinPath(h.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,i,s){this._logService.info(`[AgentSdkDownloader] ${e.id}: downloading from ${t}`);let a=Date.now(),l=oe(r);await this._fileService.createFolder(h.file(l));let d=`${r}.tmp.${process.pid}`,c=h.file(d);await this._delIgnoringMissing(c),await this._fileService.createFolder(c);let u=O(),p=0,m;this._fireProgress(e,u,"started",0,void 0);try{let v=j(d,"sdk.tgz");await this._fetch(t,v,s,(S,b)=>{p=S,m=b,this._fireProgress(e,u,"progress",S,b)}),await this._extractTarGz(v,d),await this._fileService.del(h.file(v)),await this._fileService.writeFile(h.joinPath(c,".complete"),F.fromString(""));try{await this._fileService.move(c,h.file(r))}catch(S){if(await this._handleRenameLoser(S,i,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(v){if(await this._delIgnoringMissing(c),s.isCancellationRequested)throw this._fireProgress(e,u,"failed",p,m,"cancelled"),new K;let y=v instanceof Error?v.message:String(v);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,i,s,a){this._onDidDownloadProgress.fire({downloadId:t,packageId:e.id,displayName:e.displayName,phase:r,receivedBytes:i,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,i){if(r.isCancellationRequested)throw new K;let s=await this._requestService.request({url:e,type:"GET",callSite:"agentSdkDownloader"},r);if(r.isCancellationRequested)throw s.stream.destroy(),new K;let a=s.res.statusCode??0;if(a<200||a>=300)throw s.stream.destroy(),new Error(`HTTP ${a} fetching ${e}`);let l=u9(s.res.headers["content-length"]);await new Promise((d,c)=>{let u=n1.createWriteStream(t),p=!1,m=0,v=0,y=_=>{if(!i)return;let T=Date.now();!_&&T-v<c9||(v=T,i(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 K));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 r1.x({file:e,cwd:t})}async _delIgnoringMissing(e){try{await this._fileService.del(e,{recursive:!0})}catch(t){if(ho(t)!==1)throw t}}};Dl=R([C(0,bt),C(1,ft),C(2,si),C(3,Pe),C(4,M)],Dl);var Ol={id:"claude",displayName:"Claude",devOverrideEnvVar:Op,hasSeparateMuslLinuxPackage:!0},Nl=W("claudeAgentSdkService"),Ll=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[Op]||!this._downloader.isAvailable(Ol)?!0:this._downloader.isSdkResolvableWithoutDownload(Ol)}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[Op];if(n){let e=j(n,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(o1(e).href)}if(this._downloader.isAvailable(Ol)){let e=await this._downloader.loadSdkRoot(Ol,Re.None),t=j(e,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(o1(t).href)}return import("@anthropic-ai/claude-agent-sdk")}};Ll=R([C(0,M),C(1,Ml)],Ll);import{tmpdir as v9}from"os";import{z as $t}from"zod";function ih(o){if(!o||o.type!=="object"||!o.properties)return{};let n=new Set(o.required??[]),e={};for(let[t,r]of Object.entries(o.properties)){let i;try{i=oh(r)}catch{i=$t.any()}n.has(t)||(i=i.optional()),e[t]=i}return e}function oh(o){if(!o||typeof o!="object")return $t.any();let n;if(Array.isArray(o.enum)&&o.enum.length>0){let e=o.enum.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null);e.length===0?n=$t.any():e.length===1?n=$t.literal(e[0]):n=$t.union(e.map(t=>$t.literal(t)))}else if(Array.isArray(o.oneOf)&&o.oneOf.length>0)n=i1(o.oneOf);else if(Array.isArray(o.anyOf)&&o.anyOf.length>0)n=i1(o.anyOf);else switch(Array.isArray(o.type)?o.type[0]:o.type){case"string":n=$t.string();break;case"number":n=$t.number();break;case"integer":n=$t.number().int();break;case"boolean":n=$t.boolean();break;case"array":n=$t.array(o.items?oh(o.items):$t.any());break;case"object":{let t={},r=new Set(o.required??[]);for(let[i,s]of Object.entries(o.properties??{})){let a;try{a=oh(s)}catch{a=$t.any()}r.has(i)||(a=a.optional()),t[i]=a}n=$t.object(t);break}case"null":n=$t.null();break;default:n=$t.any()}return o.nullable&&(n=n.nullable()),o.description&&(n=n.describe(o.description)),o.default!==void 0&&(n=n.default(o.default)),n}function i1(o){let n=o.map(e=>{try{return oh(e)}catch{return $t.any()}});return n.length===1?n[0]:$t.union(n)}var s1="claudecode/toolUseId";async function a1(o,n,e){let t=await Promise.all(o.map(r=>e.tool(r.name,r.description??"",ih(r.inputSchema),async(i,s)=>{let a=p9(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["${s1}"]).`}],isError:!0}:n(a)})));return e.createSdkMcpServer({name:fC,tools:t})}function p9(o){if(!o||typeof o!="object")return;let n=o._meta;if(!n||typeof n!="object")return;let e=n[s1];return typeof e=="string"?e:void 0}var fC="client";function Ul(o){let n=`mcp__${fC}__`;return o.startsWith(n)?o.slice(n.length):o}function l1(o){return o.startsWith(`mcp__${fC}__`)}var f9=new Map([["opus",new Set(["1m"])]]),gC=new Map;function Tu(o){if(o!==void 0)return Is(o)?.toSdkModelId()??o}function Is(o){let n=o.toLowerCase();if(gC.has(n))return gC.get(n);let e=m9(n);return gC.set(n,e),e}var g9=/^(?<base>.*)-(?<date>\d{8})$/;function m9(o){let n="",e=o,t=g9.exec(o);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 _u(r.groups.name,r.groups.major,r.groups.minor,Iu(r.groups.mod,n));let i=e.match(/^claude-(?<major>\d+)-(?<minor>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(i?.groups)return _u(i.groups.name,i.groups.major,i.groups.minor,Iu(i.groups.mod,n));let s=e.match(/^claude-(?<name>\w+)-(?<major>\d+)\.(?<minor>\d+)(?:-(?<mod>.+))?$/);if(s?.groups)return _u(s.groups.name,s.groups.major,s.groups.minor,Iu(s.groups.mod,n));let a=e.match(/^claude-(?<name>\w+)-(?<major>\d+)(?:-(?<mod>.+))?$/);if(a?.groups)return _u(a.groups.name,a.groups.major,void 0,Iu(a.groups.mod,n));let l=e.match(/^claude-(?<major>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(l?.groups)return _u(l.groups.name,l.groups.major,void 0,Iu(l.groups.mod,n));let d=e.match(/^(?<name>\w+)$/);if(d?.groups)return h9(d.groups.name)}function Iu(o,n){return o&&n?`${o}-${n}`:o||n}function d1(o,n,e,t,r){let i=e!==void 0?`claude-${o}-${n}${t}${e}`:`claude-${o}-${n}`;return r?`${i}-${r}`:i}function h9(o){return{name:o,version:"",modifiers:"",toSdkModelId:()=>o,toEndpointModelId:()=>o}}function _u(o,n,e,t){let r=e!==void 0?`${n}.${e}`:n,i=y9(o,t);return{name:o,version:r,modifiers:t,toSdkModelId:()=>d1(o,n,e,"-",i),toEndpointModelId:()=>d1(o,n,e,".",i)}}function y9(o,n){if(!n)return"";let e=f9.get(o);if(!e)return"";if(e.has(n))return n;let t=n.split("-")[0];return e.has(t)?t:""}async function mC(o,n,e,t){let r=n.kind==="proxy",i=p1(r),s=await nl(),a={...n.kind==="proxy"?{ANTHROPIC_BASE_URL:n.handle.baseUrl,ANTHROPIC_AUTH_TOKEN:`${n.handle.nonce}.${o.sessionId}`}:{},CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",USE_BUILTIN_RIPGREP:"0",PATH:`${oe(s)}${Hs}${process.env.PATH??""}`};return{cwd:o.workingDirectory.fsPath,executable:process.execPath,env:i,abortController:o.abortController,allowDangerouslySkipPermissions:!0,canUseTool:o.canUseTool,onElicitation:async l=>(t(l.message??""),{action:"cancel"}),disallowedTools:["WebSearch"],includePartialMessages:!0,forwardSubagentText:!0,enableFileCheckpointing:!0,model:Tu(o.model?.id),effort:Cu(o.model),permissionMode:o.permissionMode,...o.isResume?{resume:o.sessionId,...o.resumeSessionAt?{resumeSessionAt:o.resumeSessionAt}:{}}:{sessionId:o.sessionId},...o.mcpServers?{mcpServers:o.mcpServers}:{},...o.allowedTools&&o.allowedTools.length>0?{allowedTools:[...o.allowedTools]}:{},...o.plugins&&o.plugins.length>0?{plugins:o.plugins.map(l=>({type:"local",path:l.fsPath}))}:{},...o.agent?{agent:o.agent}:{},settingSources:["user","project","local"],settings:{env:a},systemPrompt:{type:"preset",preset:"claude_code"},stderr:e}}async function c1(o,n,e){let t=o.consume();return t.length===0?void 0:{client:await a1(t,i=>n.register(i),e)}}function u1(){return{cwd:v9(),executable:process.execPath,env:p1(!1),abortController:new AbortController,systemPrompt:{type:"preset",preset:"claude_code"},settings:{env:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}}}function p1(o=!0){let n=o?{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 Ru={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}},wu="mcp__";function sh(o){let n=Ru[o];return n?n.permissionKind:o.startsWith(wu)?"mcp":"custom-tool"}function Sn(o){let n=mr(o,void 0)?.displayName;if(n!==void 0)return n;switch(o){case"Bash":return f(2068,null);case"BashOutput":return f(2069,null);case"KillBash":return f(2074,null);case"Read":return f(2080,null);case"Glob":return f(2072,null);case"Grep":return f(2073,null);case"LS":return f(2075,null);case"NotebookRead":return f(2079,null);case"Write":return f(2084,null);case"Edit":return f(2070,null);case"MultiEdit":return f(2077,null);case"NotebookEdit":return f(2078,null);case"TodoWrite":return f(2082,null);case"WebFetch":return f(2083,null);case"Task":case"Agent":return f(2081,null);case"ExitPlanMode":return f(2071,null);case"AskUserQuestion":return f(2067,null)}return o.startsWith(wu)?f(2076,null,o.slice(wu.length)):o}function Vr(o,n){let e=Ru[o];if(!e?.pathField||typeof n!="object"||n===null)return;let t=n[e.pathField];return typeof t=="string"?t:void 0}function f1(o){return Ru[o]?.isFileEdit===!0}var g1=new Set(Object.entries(Ru).filter(([,o])=>o.interactive).map(([o])=>o));function m1(o){switch(sh(o)){case"shell":return f(2064,null);case"write":return f(2066,null);case"read":return f(2063,null);case"url":return f(2065,null);case"mcp":{let n=o.startsWith(wu)?o.slice(wu.length).split("__")[0]:void 0;return n?f(2062,null,n):f(2061,null)}default:return f(2061,null)}}function Eo(o){let n=hC(o);return n?Rt(n):void 0}function hC(o){let n=Ru[o];if(n?.toolKind)return{toolKind:n.toolKind}}function vn(o){return{markdown:o}}function Fl(o){let n=h.file(o);return`[${fs(ve(n))}](${n})`}function zr(o,n){if(o===null||typeof o!="object")return;let e=o[n];return typeof e=="string"&&e.length>0?e:void 0}function h1(o){let n=zr(o,"command");return n?n.split(`
`)[0]:void 0}function ko(o,n,e){let t=mr(o,e)?.invocationMessage;if(t!==void 0)return t;switch(o){case"Bash":{let r=h1(e);return r?vn(f(2105,null,ot(tr(r,80)))):f(2104,null)}case"BashOutput":return f(2106,null);case"KillBash":return f(2113,null);case"Read":case"NotebookRead":{let r=Vr(o,e);return r?vn(f(2117,null,Fl(r))):f(2116,null)}case"LS":{let r=Vr(o,e);return r?vn(f(2115,null,Fl(r))):f(2114,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let r=Vr(o,e);return r?vn(f(2108,null,Fl(r))):f(2107,null)}case"TodoWrite":return f(2118,null);case"Grep":{let r=zr(e,"pattern");return r?vn(f(2112,null,ot(tr(r,80)))):f(2111,null)}case"Glob":{let r=zr(e,"pattern");return r?vn(f(2110,null,ot(tr(r,80)))):f(2109,null)}case"WebFetch":{let r=zr(e,"url");return r?vn(f(2119,null,`[${fs(tr(r,80))}](${r})`)):f(2120,null)}case"Task":case"Agent":{let r=zr(e,"description");return r||n}default:return n}}function ah(o,n,e,t,r){if(!t)return f(2090,null,n);let i=mr(o,e,{text:r,success:t})?.pastTenseMessage;if(i!==void 0)return i;switch(o){case"Bash":{let s=h1(e);return s?vn(f(2086,null,ot(tr(s,80)))):f(2085,null)}case"BashOutput":return f(2087,null);case"KillBash":return f(2095,null);case"Read":case"NotebookRead":{let s=Vr(o,e);return s?vn(f(2099,null,Fl(s))):f(2098,null)}case"LS":{let s=Vr(o,e);return s?vn(f(2097,null,Fl(s))):f(2096,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let s=Vr(o,e);return s?vn(f(2089,null,Fl(s))):f(2088,null)}case"TodoWrite":return f(2101,null);case"Grep":{let s=zr(e,"pattern");return s?vn(f(2094,null,ot(tr(s,80)))):f(2093,null)}case"Glob":{let s=zr(e,"pattern");return s?vn(f(2092,null,ot(tr(s,80)))):f(2091,null)}case"WebFetch":{let s=zr(e,"url");return s?vn(f(2102,null,`[${fs(tr(s,80))}](${s})`)):f(2103,null)}case"Task":case"Agent":return f(2100,null);default:return n}}function Ii(o,n){if(n!==void 0){if(o==="Bash"||o==="BashOutput"||o==="KillBash"){let e=zr(n,"command");if(e)return e}if(o==="Grep"||o==="Glob"){let e=zr(n,"pattern");if(e)return e}try{return JSON.stringify(n,null,2)}catch{return}}}function xu(o,n,e){let t=new yC(n,e);for(let r of o){let i=v1(r);i!==void 0&&t.consume(i)}return t.finish()}function lh(o,n){let e=!1,t;for(let r of o){let i=v1(r);if(i!==void 0)if(i.kind==="user-text"){if(e)break;i.uuid===n&&(e=!0)}else i.kind==="assistant"&&e&&(t=i.uuid)}if(e)return t??n}function v1(o){switch(o.type){case"user":return S9(o);case"assistant":return b9(o);case"system":return C9(o);default:return}}function S9(o){let n=_9(o.message);if(n===void 0||A9(n))return;if(typeof n=="string")return{kind:"user-text",uuid:o.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:o.uuid,results:t}:void 0}return{kind:"user-text",uuid:o.uuid,text:e.map(t=>t.text).join(`
`)}}function b9(o){let n=T9(o.message);if(!(n===void 0||n.length===0))return{kind:"assistant",uuid:o.uuid,blocks:n,isInner:o.parent_tool_use_id!==null}}function C9(o){let n=w9(o.message);if(n===void 0||!I9.has(n))return;let e=R9(o.message)??`[${n}]`;return{kind:"system-notification",uuid:o.uuid,subtype:n,text:e}}var I9=new Set(["compact_boundary","notification"]),y1=/^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/,yC=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,Ul(r.name),r.input)}_openToolUse(n,e,t){if(this._active===void 0)return;let r=Sn(e),i=t!==null&&typeof t=="object"?t:void 0,s=Eo(e),a={status:"cancelled",toolCallId:n,toolName:e,displayName:r,invocationMessage:ko(e,r,i),toolInput:i!==void 0?Ii(e,i):typeof t=="string"?t:t!==void 0?P9(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:i})}_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 i=n.is_error,s=r.toolCall,a=bc(s).toolKind==="subagent",l=x9(n.content)??[],d=l.filter(u=>u.type==="text").map(u=>u.text).join(`
`);a&&l.push({type:"subagent",resource:na(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:!i,pastTenseMessage:ah(s.toolName,s.displayName,e.parsedInput,!i,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 _9(o){if(o===null||typeof o!="object")return;let n=o.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 T9(o){if(o===null||typeof o!="object")return;let n=o.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 w9(o){if(o===null||typeof o!="object")return;let n=o.subtype;return typeof n=="string"?n:void 0}function R9(o){if(o===null||typeof o!="object")return;let n=o;if(typeof n.text=="string")return n.text;if(typeof n.message=="string")return n.message}function x9(o){if(typeof o=="string")return o.length>0?[{type:"text",text:o}]:void 0;if(!Array.isArray(o))return;let n=[];for(let e of o){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 P9(o){try{return JSON.stringify(o)}catch{return}}function A9(o){if(typeof o=="string")return y1.test(o);let n=o.find(e=>e.type==="text");return n!==void 0&&y1.test(n.text)}var vC=class{validateOrThrow(n){let e=this.validate(n);if(e.error)throw new Error(e.error.message);return e.content}},Hl=class extends vC{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}}},E9=new Hl("string");function S1(){return E9}var QPe=new Hl("number");var XPe=new Hl("boolean");var k9=new Hl("object");function b1(){return k9}var Pu=new Set(["Task","Agent"]),D9=/^\s*agentId:\s+([a-z0-9]+)\b/im,SC=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)}},dh=class extends w{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 SC(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 bC(e))this.recordSpawn(t,{agentId:r})}_evictInnerEdgesFor(e){for(let[t,r]of this._innerToParent)r===e&&this._innerToParent.delete(t)}};function bC(o){let n=new Map;for(let e of o)for(let t of e.responseParts){let r=M9(t);r&&n.set(r.toolCallId,r.agentId)}return n}function M9(o){if(o.kind!=="toolCall")return;let n=o.toolCall;if(!Pu.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 i=D9.exec(r.text);if(i)return{toolCallId:n.toolCallId,agentId:i[1]}}}var CC=class{constructor(n,e){this._sdk=n;this._logService=e;this.name="text_suffix"}async lookup(n,e){let t=await C1(this._sdk,this._logService,e,"TextSuffix");if(t)return bC(t).get(n)}};async function C1(o,n,e,t){if(e.parentTranscript)return e.parentTranscript;try{let r=await o.getSessionMessages(e.parentSessionId,{includeSystemMessages:!0});return xu(r,e.parentUri,n)}catch(r){n.warn(`[claudeSubagentResolver] ${t}: parent transcript fetch failed: ${r}`);return}}function I1(o){let n=S1().validate(o);return n.error?void 0:n.content}function IC(o){let n=b1().validate(o);if(!(n.error||n.content===null||Array.isArray(n.content)))return n.content}var _C=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(i){this._logService.warn(`[claudeSubagentResolver] PromptMatch: listSubagents failed: ${i}`);return}for(let i of r){if(e.token.isCancellationRequested)return;let s;try{s=await this._sdk.getSubagentMessages(e.parentSessionId,i)}catch(l){this._logService.warn(`[claudeSubagentResolver] PromptMatch: getSubagentMessages(${i}) failed: ${l}`);continue}let a=L9(s);if(a!==void 0&&a===t)return i}}async _loadParentPrompt(n,e){let t=await C1(this._sdk,this._logService,e,"PromptMatch");if(t)return O9(t,n)}};function O9(o,n){for(let e of o)for(let t of e.responseParts){if(t.kind!=="toolCall")continue;let r=t.toolCall;if(r.toolCallId!==n)continue;if(!Pu.has(r.toolName)||r.status==="streaming")return;let i=r.toolInput;if(typeof i!="string")return;let s;try{s=JSON.parse(i)}catch{return}let a=IC(s);return a?I1(a.prompt):void 0}}function L9(o){for(let n of o){if(n.type!=="user")continue;let e=IC(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 i=IC(r);if(!i||i.type!=="text")continue;let s=I1(i.text);if(s!==void 0)return s}}}var TC=class{constructor(){this.name="native"}async lookup(){}};async function N9(o,n,e){let t=e.cacheGet(o);if(t)return t;for(let r of e.strategies){if(n.token.isCancellationRequested)return;let i=await r.lookup(o,n);if(i)return e.cacheSet(o,i),i}}function U9(o,n){return[new CC(o,n),new _C(o,n),new TC]}async function _1(o,n,e,t,r){let i=ut(o);if(!i)throw new Error(`getSubagentTranscript: not a subagent URI: ${o.toString()}`);let{parentSession:s,toolCallId:a}=i,l=D.id(s),d=await N9(a,{parentUri:s,parentSessionId:l,token:r},{strategies:U9(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 xu(c,o,t)}var ch="host";function T1(o){return o.map(n=>`mcp__${ch}__${n}`)}async function w1(o,n,e){let t=await Promise.all(o.definitions.map(r=>e.tool(r.name,r.description??"",ih(r.inputSchema),async i=>{try{return{content:[{type:"text",text:await o.executeTool(n,r.name,i)}]}}catch(s){return{content:[{type:"text",text:s instanceof Error?s.message:String(s)}],isError:!0}}})));return e.createSdkMcpServer({name:ch,tools:t})}var F9="claude-client";function R1(o,n){let r={content:(o.content??[]).map((i,s)=>H9(i,n,s))};return o.structuredContent!==void 0&&(r.structuredContent=o.structuredContent),(!o.success||o.error)&&(r.isError=!0),r}function H9(o,n,e){switch(o.type){case"text":return{type:"text",text:o.text};case"embeddedResource":return $9(o,n,e);default:{console.warn(`[Claude] convertToolCallResult: unsupported tool-result block kind '${o.type}'; degrading to text`);let t;try{t=JSON.stringify(o)}catch{t=`[unserializable ${o.type} block]`}return{type:"text",text:t}}}}function $9(o,n,e){return o.contentType.startsWith("image/")?{type:"image",data:o.data,mimeType:o.contentType}:{type:"resource",resource:{uri:`${F9}://${encodeURIComponent(n)}/${e}`,mimeType:o.contentType,blob:o.data}}}function _i(o,n){return Cs(o.getSessionConfigValues(n.toString())?.permissionMode)}var wC=class{constructor(){this._toolSet=new hn;this._merged=Gi({owner:this,equalsFn:(n,e)=>xm(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)}},uh=class extends w{constructor(){super();this.model=new wC;this._dirty=!1;this._ignoreNextFire=!0;this._lastAppliedTools=[];this._register(jn(e=>{let t=this.model.merged.read(e);if(this._ignoreNextFire){this._ignoreNextFire=!1,this._lastAppliedTools=t;return}xm(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 W9={synced:[],enablement:new Map},RC=class{constructor(){this._byClient=new Map;this._state=Gi({owner:this,equalsFn:q9},W9);this.state=this._state;this.enabledPluginPaths=Yd({owner:this,equalsFn:(n,e)=>In(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 i=new Map(t.enablement);e?i.delete(n):i.set(n,!1),this._state.set({synced:t.synced,enablement:i},void 0)}},ph=class extends w{constructor(){super();this.model=new RC;this._dirty=!1;this._ignoreNextFire=!0;this.onDidChange=ee.fromObservableLight(this.model.state);this._register(jn(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 q9(o,n){return B9(o.synced,n.synced)&&V9(o.enablement,n.enablement)}function B9(o,n){if(o.length!==n.length)return!1;for(let e=0;e<o.length;e++){let t=o[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||P1(t.load)!==P1(r.load)||!z9(t.children,r.children)||o[e].pluginDir?.toString()!==n[e].pluginDir?.toString())return!1}return!0}function P1(o){return o&&o.message?o.message:void 0}function z9(o,n){if(o===n)return!0;if(!o||!n||o.length!==n.length)return!1;for(let e=0;e<o.length;e++)if(o[e].id!==n[e].id||o[e].name!==n[e].name)return!1;return!0}function V9(o,n){if(o.size!==n.size)return!1;for(let[e,t]of o)if(n.get(e)!==t)return!1;return!0}function j9(o,n){let e=[];return o&&(e.push(h.joinPath(o,".claude","settings.json")),e.push(h.joinPath(o,".mcp.json"))),e.push(h.joinPath(n,".claude","settings.json")),e}function K9(o,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 o.path.endsWith(".mcp.json")?e:void 0}async function A1(o,n,e){let t=new Set,r=[];for(let i of j9(o,n)){let s=await wo(i,e),a=K9(i,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(eu(i,l)))}return r.sort((i,s)=>i.name.localeCompare(s.name)),r}function xC(o){switch(o){case"connected":return{kind:"ready"};case"disabled":return{kind:"stopped"};default:return{kind:"starting"}}}function PC(o,n){let e=[h.joinPath(n,".claude","CLAUDE.md")];return o&&e.push(h.joinPath(o,"CLAUDE.md"),h.joinPath(o,".claude","CLAUDE.md"),h.joinPath(o,"CLAUDE.local.md")),e}var G9=32;async function E1(o,n,e=new Set,t=0){let r=o.toString();if(t>G9||e.has(r))return[];e.add(r);let i;try{i=await n.resolve(o)}catch{return[]}if(!i.isDirectory||!i.children)return[];let s=[];for(let a of i.children)a.isDirectory?s.push(...await E1(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 k1(o,n,e){let t=[];for(let i of PC(o,n))if(await gs(i,e)){let s=i.toString(),a=ve(i),l={type:"rule",id:Nt(s),uri:s,name:a,alwaysApply:!0};t.push({uri:i,name:a,customization:l})}let r=o?[o,n]:[n];for(let i of r){let s=await E1(h.joinPath(i,".claude","rules"),e);for(let a of s){let l=await Cm(a,e),d=a.toString(),c=!!l.globs?.length,u={type:"rule",id:Nt(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 D1="agent-builtin",J9=[{name:"init",description:()=>f(2124,null)},{name:"review",description:()=>f(2127,null)},{name:"security-review",description:()=>f(2129,null)},{name:"code-review",description:()=>f(2122,null)},{name:"simplify",description:()=>f(2130,null)},{name:"verify",description:()=>f(2132,null)},{name:"run",description:()=>f(2128,null)},{name:"loop",description:()=>f(2126,null)},{name:"claude-api",description:()=>f(2121,null)},{name:"fewer-permission-prompts",description:()=>f(2123,null)},{name:"update-config",description:()=>f(2131,null)},{name:"keybindings-help",description:()=>f(2125,null)},{name:"write-a-skill",description:()=>f(2133,null)}],M1=[{name:"claude",description:()=>f(2134,null)},{name:"claude-code-guide",description:()=>f(2135,null)},{name:"Explore",description:()=>f(2136,null)},{name:"general-purpose",description:()=>f(2137,null)},{name:"Plan",description:()=>f(2138,null)}];function O1(o){if(o.length===0)return;let n=o.map(t=>{let r=h.from({scheme:D1,path:`/skill/${encodeURIComponent(t.name)}`}).toString();return{type:"skill",id:Nt(r),uri:r,name:t.name,description:t.description}}),e=h.from({scheme:D1,path:"/skills"}).toString();return{type:"directory",id:Nt(e),uri:e,name:"builtin",enabled:!0,contents:"skill",writable:!1,load:{kind:"loaded"},children:n}}function L1(o){return O1(J9.filter(n=>!o.has(n.name)).map(n=>({name:n.name,description:n.description()})))}function N1(o,n){let e=new Set,t=[];for(let r of o)n.has(r.name)||e.has(r.name)||(e.add(r.name),t.push({name:r.name,description:r.description}));return O1(t)}var AC="general-purpose",H1="claude-internal";function fh(o,n,e,t){let r=h.joinPath(o,".claude",n).toString();return{type:"directory",id:Nt(r),uri:r,name:n,enabled:!0,contents:e,writable:!0,load:{kind:"loaded"},children:[...t]}}function Y9(o){let n=o.root.toString(),e=[],t=new Set,r=i=>{t.has(i.id)||(t.add(i.id),e.push(i))};for(let i of o.parsed.agents)r(i.customization);for(let i of o.parsed.skills)r(i.customization);for(let i of o.parsed.instructions)r(i.customization);for(let i of o.parsed.hooks)r(i.customization);for(let i of o.parsed.mcpServers)r(i.customization);return{type:"plugin",id:Nt(n),uri:n,name:o.id,enabled:!0,load:{kind:"loaded"},children:e}}function U1(o,n){return n&&o.scheme===n.scheme&&io(o,n)?"workspace":"user"}function F1(o,n,e,t,r,i){let s=new Map([["workspace",{agents:[],skills:[],rules:[],hooks:[]}],["user",{agents:[],skills:[],rules:[],hooks:[]}]]);for(let d of o){let c=s.get(U1(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(U1(h.parse(d.uri),r)).hooks.push(d);let a=[],l=[["workspace",r],["user",i]];for(let[d,c]of l){if(!c)continue;let u=s.get(d);u.agents.length>0&&a.push(fh(c,"agents","agent",u.agents)),u.skills.length>0&&a.push(fh(c,"skills","skill",u.skills)),u.rules.length>0&&a.push(fh(c,"rules","rule",u.rules)),u.hooks.length>0&&a.push(fh(c,"hooks","hook",u.hooks))}for(let d of t)a.push(Y9(d));return a.push(...n),a}function EC(o,n){return h.from({scheme:H1,path:`/${o}/${encodeURIComponent(n)}`})}async function kC(o,n,e,t){if(!o)return;let r=h.parse(o.uri);if(r.scheme===H1){let a=r.path.split("/").pop()??"",l=a?decodeURIComponent(a):"";if(!l){e.warn(`[Claude:${t}] resolveClaudeAgentName: could not extract agent name from URI '${o.uri}'`);return}return l}try{let a=await tu(r,n);if(a.name)return a.name}catch(a){e.warn(`[Claude:${t}] resolveClaudeAgentName: failed to parse agent file '${o.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 '${o.uri}'`);return}return s}function $1(o,n,e,t,r,i,s){let a=[],l=new Set,d=new Set,c=new Set;if(s)for(let P of t){let X=s.plugins.find(E=>E.source===P.id||h.file(E.path).fsPath===P.root.fsPath);if(!X)continue;a.push(P);let k=X.name,x=(E,H)=>{E.add(H),k&&E.add(`${k}:${H}`)};for(let E of P.parsed.agents)x(l,E.name);for(let E of P.parsed.skills)x(d,E.name);for(let E of P.parsed.mcpServers)x(c,E.name)}else a.push(...t);let u=new Set(o.filter(P=>P.customization.type==="skill").map(P=>P.name)),p=s?N1(s.commands.filter(P=>!d.has(P.name)),u):L1(u),m=P=>p?[...P,p]:P;if(!s){let P=new Set(o.filter(k=>k.customization.type==="agent").map(k=>k.name)),X=M1.filter(k=>k.name!==AC&&!P.has(k.name)).map(k=>hl({uri:EC("agent",k.name),name:k.name,description:k.description()}));return m(F1([...o,...X],n,e,t,r,i))}let v=new Set(s.agents.map(P=>P.name)),y=new Set(s.commands.map(P=>P.name)),S=new Map(s.mcpServers.map(P=>[P.name,P])),b=new Set,I=[];for(let P of o)if(P.customization.type==="agent"){if(P.name===AC)continue;v.has(P.name)&&(I.push(P),b.add(P.name))}else P.customization.type==="skill"?y.has(P.name)&&I.push(P):I.push(P);for(let P of s.agents)P.name===AC||b.has(P.name)||l.has(P.name)||I.push(hl({uri:EC("agent",P.name),name:P.name,...P.description?{description:P.description}:{}}));let _=new Set,T=[];for(let P of n){let X=S.get(P.name);X&&(_.add(P.name),T.push({...P,state:xC(X.status)}))}for(let[P,X]of S)_.has(P)||c.has(P)||T.push({...eu(EC("mcp",P),P),state:xC(X.status)});return m(F1(I,T,e,a,r,i))}var Q9=Object.freeze(["agents","skills","commands","rules","plugins","CLAUDE.md","settings.json","settings.local.json"]),gh=class o extends w{static{this.DEBOUNCE_MS=300}constructor(n,e,t,r,i=o.DEBOUNCE_MS){super();let s=[],a=(c,u)=>{try{this._register(t.watch(c,{recursive:u,excludes:[]}))}catch(p){r.warn(`[ClaudeCustomizationWatcher] failed to watch '${c.toString()}': ${p instanceof Error?p.message:String(p)}`)}},l=c=>{for(let u of Q9)s.push(h.joinPath(c,u))};if(n){let c=h.joinPath(n,".claude");a(c,!0),l(c),a(n,!1),s.push(h.joinPath(n,".mcp.json"))}let d=h.joinPath(e,".claude");a(d,!0),l(d),s.push(...PC(n,e)),this.onDidChange=ee.signal(ee.debounce(ee.filter(t.onDidFilesChange,c=>s.some(u=>c.affects(u)),this._store),(c,u)=>u,i,void 0,void 0,void 0,this._store))}};function X9(o){let n=h.joinPath(o,".claude");return{agents:h.joinPath(n,"agents"),skills:h.joinPath(n,"skills"),commands:h.joinPath(n,"commands")}}function DC(o,n){for(let e of n)o.has(e.name)||o.set(e.name,e)}async function Z9(o,n){let e=await Promise.all(o.map(async t=>{let r=Tn(t.uri),i=await Xc(r,n);return n.exists(h.joinPath(r,i.manifestPath))}));return o.filter((t,r)=>!e[r])}async function W1(o,n,e){let t=o?[o,n]:[n],r=new Map,i=new Map;for(let s of t){let{agents:a,skills:l,commands:d}=X9(s),[c,u,p]=await Promise.all([bm([a],e),Nb(l,[l],e),bm([d],e)]);DC(r,c.map(hl));let m=await Z9(u,e);DC(i,m.map(_m)),DC(i,p.map(_m))}return[...r.values(),...i.values()]}function e8(o,n){let e=[];return o&&(e.push(h.joinPath(o,".claude","settings.json")),e.push(h.joinPath(o,".claude","settings.local.json"))),e.push(h.joinPath(n,".claude","settings.json")),e}async function q1(o,n,e){let t=[],r=new Ir;for(let i of e8(o,n)){if(r.has(i))continue;r.add(i);let s=await wo(i,e);if(s===void 0)continue;let a=Sm(i,s,o,n);a.length>0&&t.push(a[0].customization)}return t}var t8="skills-dir";function n8(o,n){let e=[h.joinPath(n,".claude","settings.json")];return o&&(e.push(h.joinPath(o,".claude","settings.json")),e.push(h.joinPath(o,".claude","settings.local.json"))),e}async function r8(o,n,e){let t=new Map,r=new Ir;for(let i of n8(o,n)){if(r.has(i))continue;r.add(i);let s=await wo(i,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(([,i])=>i).map(([i])=>i)}function o8(o){let n=o.lastIndexOf("@");if(n<=0||n===o.length-1)return;let e=o.slice(0,n),t=o.slice(n+1),r=i=>i.includes("/")||i.includes("\\")||i.includes("..");if(!(r(e)||r(t)))return{plugin:e,marketplace:t}}async function MC(o,n){let e=await Xc(o,n);return n.exists(h.joinPath(o,e.manifestPath))}async function i8(o,n,e,t){let r=[];n&&r.push(h.joinPath(n,".claude","skills",o)),r.push(h.joinPath(e,".claude","skills",o));for(let i of r)if(await MC(i,t))return i}async function s8(o,n,e,t){let r=h.joinPath(e,".claude","plugins","cache",n,o);if(await MC(r,t))return r;let i;try{i=await t.resolve(r)}catch{return}if(!i.isDirectory||!i.children)return;let s;for(let a of i.children){if(!a.isDirectory||!await MC(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 B1(o,n,e,t){let r=await r8(o,n,e),i=[],s=new Ir;for(let a of r){let l=o8(a);if(!l){t.warn(`[claudeNativePluginScan] skipping malformed plugin id '${a}'`);continue}let d=l.marketplace===t8?await i8(l.plugin,o,n,e):await s8(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 Im(d,e,o,n,d);i.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 i.sort((a,l)=>a.id.localeCompare(l.id)),i}function mh(o,n){let e=[{type:"text",text:o}];if(!n?.length)return e;let t=[],r=[],i=[];for(let s of n){if(Mm(s)){let l=Om(s);l&&i.push(l);continue}if(s.type==="simple"){s.modelRepresentation&&r.push(s.modelRepresentation);continue}if(s.type!=="resource")continue;let a=h.parse(s.uri);if(s.displayKind==="selection"){let l=s.selection?`:${s.selection.range.start.line+1}`:"";t.push(`- ${z1(a)}${l}`)}else t.push(`- ${z1(a)}`)}return i.length>0&&e.push({type:"text",text:i.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 z1(o){return o.scheme==="file"?o.fsPath:o.toString()}var $l=class extends w{constructor(e,t,r,i){super();this._sessionId=e;this._getAbortSignal=t;this._onSteeringYielded=r;this._logService=i;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 i of r)i.deferred.isSettled||i.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}};$l=R([C(3,M)],$l);var Wl=class extends w{constructor(e,t,r,i){super();this._logService=r;this._editToolPaths=new Map;this._register(t),this._editTracker=i.createInstance(ti,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 i of t){if(i.type!=="tool_use"||!f1(i.name))continue;let s=Vr(i.name,i.input);s&&(this._editToolPaths.set(i.id,{filePath:s,toolName:i.name,toolInput:i.input,modelId:r}),this._editTracker.trackEditStart(s).catch(a=>this._logService.warn(`[ClaudeFileEditObserver] trackEditStart failed for ${s}: ${a}`)))}}async observeUser(e,t,r){let i=e.message.content;if(Array.isArray(i))for(let s of i){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=R([C(2,M),C(3,xe)],Wl);var OC=Pu;function hh(o,n,e,t){if(!e)return o;let r=o.map(a=>a.kind==="action"?{...a,parentToolCallId:e}:a.kind==="pending_confirmation"?{...a,parentToolCallId:e}:a),i=t.getSpawn(e);return!i||!i.markAnnounced()?r:[{kind:"subagent_started",chat:n,toolCallId:e,agentName:i.subagentType??"subagent",agentDisplayName:i.subagentType??"Subagent",agentDescription:i.description,taskDescription:i.description,parentToolCallId:t.getParentSpawn(e)?.toolUseId},...r]}function V1(o,n,e){let t=o.subtype;if(t==="task_started"){let r=o.tool_use_id,i=r?e.getSpawn(r):void 0;return i&&(i.background=!0),[]}if(t==="task_notification"){let r=o;if(!r.tool_use_id)return[];let i=r.status;if(i!=="completed"&&i!=="failed"&&i!=="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 j1(o,n,e,t){let r=o.input,i=typeof r?.description=="string"?r.description:void 0,s=typeof r?.subagent_type=="string"?r.subagent_type:void 0,a=o.input!==void 0?a8(o.input):void 0;t.recordSpawn(o.id,{subagentType:s,description:i});let l={...hC(o.name)};return l.toolKind||(l.toolKind="subagent"),i&&(l.subagentDescription=i),s&&(l.subagentAgentName=s),{kind:"action",resource:n,action:{type:"chat/toolCallReady",turnId:e,toolCallId:o.id,invocationMessage:ko(o.name,Sn(o.name),o.input),...a!==void 0?{toolInput:a}:{},confirmed:"not-needed",_meta:Rt(l)}}}function K1(o,n,e,t,r,i){let s=o.message.id,a=[];for(let l=0;l<o.message.content.length;l++){let d=o.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=Ul(d.name);t.startToolBlock(l,d.id,c,e),t.toolCalls.seedParsedInput(d.id,d.input),i.noteInnerTool(d.id,r);let u=Sn(c),p=Eo(c),m=Ii(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:ko(c,u,d.input),...m!==void 0?{toolInput:m}:{},confirmed:"not-needed"}});continue}}return a}function a8(o){try{return JSON.stringify(o)}catch{return}}var LC="User declined",NC="The user declined the plan, maybe ask why?",yh="The user cancelled the question";function G1(o){switch(o){case LC:case NC:return"denied";case yh:return"cancelled";default:return}}var vh=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 i=JSON.parse(e.inputBuffer);i!==null&&typeof i=="object"&&(t=i)}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=Sn(n.toolName);n.info={toolName:n.toolName,displayName:r,parsedInput:e,invocationMessage:ko(n.toolName,r,e),toolInput:Ii(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 bh=class{constructor(){this._activeToolBlocks=new Map;this.toolCalls=new vh;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 J1(o,n,e,t,r,i,s){if(r.getLevel()<=1)try{let a=JSON.stringify(o,(l,d)=>typeof d=="string"&&d.length>200?d.slice(0,200)+"\u2026":d);r.trace(`[claudeMapSessionEvents] SDK message type=${o.type}: ${a?.slice(0,2e3)??"<unserializable>"}`)}catch{r.trace(`[claudeMapSessionEvents] SDK message type=${o.type} (unserializable)`)}switch(o.type){case"stream_event":return hh(g8(o.event,n,e,t,r,o.parent_tool_use_id,i,s),n,o.parent_tool_use_id,i);case"result":return p8(o,n,e,t,r,i);case"assistant":return hh(l8(o,n,e,t,o.parent_tool_use_id,i),n,o.parent_tool_use_id,i);case"user":return hh(d8(o,n,t,r,i),n,o.parent_tool_use_id,i);default:return o.type==="system"?V1(o,n,i):[]}}function l8(o,n,e,t,r,i){if(r===null){let s=[];for(let a of o.message.content)a.type!=="tool_use"||!OC.has(a.name)||s.push(j1(a,n,e,i));return s}return K1(o,n,e,t,r,i)}function d8(o,n,e,t,r){let i=o.message.content;if(!Array.isArray(i))return[];let s=[];for(let a of i){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=c8(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(`
`),v=p?ah(p.toolName,p.displayName,p.parsedInput,!d,m):`${Sn(l.toolName)} finished`,y=d?G1(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:v,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 c8(o){if(typeof o=="string")return[{type:"text",text:o}];if(!Array.isArray(o))return;let n=[];for(let e of o)u8(e)&&n.push({type:"text",text:e.text});return n.length>0?n:void 0}function u8(o){if(o===null||typeof o!="object")return!1;let n=o;return n.type==="text"&&typeof n.text=="string"}function p8(o,n,e,t,r,i){let s=[];if(o.subtype==="success"){let l=Object.keys(o.modelUsage)[0];s.push({kind:"action",resource:n,action:{type:"chat/usage",turnId:e,usage:{inputTokens:o.usage.input_tokens,outputTokens:o.usage.output_tokens,cacheReadTokens:o.usage.cache_read_input_tokens,...l?{model:l}:{}}}})}let a=f8(o);a!==void 0&&s.push({kind:"action",resource:n,action:{type:"chat/error",turnId:e,error:{errorType:o.subtype,...Va(a)}}}),t.clearPendingToolCalls(r);for(let l of i.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 f8(o){if(o.subtype==="success")return o.is_error?o.result:void 0;if(o.subtype==="error_during_execution")return o.errors?.join(`
`)}function g8(o,n,e,t,r,i,s,a){switch(o.type){case"message_start":return t.resetMessage(o.message.id),[];case"content_block_start":{let l=o.content_block;if(l.type==="text")return[{kind:"action",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"markdown",id:Sh(e,t,o.index,r),content:""}}}];if(l.type==="thinking")return[{kind:"action",resource:n,action:{type:"chat/responsePart",turnId:e,part:{kind:"reasoning",id:Sh(e,t,o.index,r),content:""}}}];if(l.type==="tool_use"){let d=Ul(l.name),c=l1(l.name);t.startToolBlock(o.index,l.id,d,e);let u=!c&&OC.has(d);i===null?u&&s.recordSpawn(l.id):s.noteInnerTool(l.id,i);let p=Eo(d),m=c?a?.(d):void 0;return[{kind:"action",resource:n,action:{type:"chat/toolCallStart",turnId:e,toolCallId:l.id,toolName:d,displayName:Sn(d),...m?{contributor:{kind:"client",clientId:m}}:{},...p?{_meta:p}:{}}}]}return[]}case"content_block_delta":{if(o.delta.type==="text_delta")return[{kind:"action",resource:n,action:{type:"chat/delta",turnId:e,partId:Sh(e,t,o.index,r),content:o.delta.text}}];if(o.delta.type==="thinking_delta")return[{kind:"action",resource:n,action:{type:"chat/reasoning",turnId:e,partId:Sh(e,t,o.index,r),content:o.delta.thinking}}];if(o.delta.type==="input_json_delta"){let l=t.getActiveToolBlock(o.index);return l?(t.appendToolBlockInputDelta(o.index,o.delta.partial_json),[{kind:"action",resource:n,action:{type:"chat/toolCallDelta",turnId:e,toolCallId:l.toolUseId,content:o.delta.partial_json}}]):(r.warn(`[claudeMapSessionEvents] input_json_delta for unknown content-block index ${o.index}`),[])}return[]}case"content_block_stop":{let l=t.getActiveToolBlock(o.index);if(t.finalizeToolBlock(o.index),t.endToolBlock(o.index),!l)return[];let c=t.toolCalls.lookup(l.toolUseId)?.info;if(!c)return[];let u=Eo(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 Sh(o,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`),`${o}#${e}`):`${o}#${r}#${e}`}var ql=class extends w{constructor(e,t,r,i,s=void 0,a,l){super();this._chatChannelUri=t;this._subagents=i;this._logService=l;this._onDidProduceSignal=this._register(new A);this.onDidProduceSignal=this._onDidProduceSignal.event;this._mapperState=new bh;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=J1(e,this._chatChannelUri,t,this._mapperState,this._logService,this._subagents,this._clientToolOwner);for(let i of r)this._onDidProduceSignal.fire(i)}catch(r){this._logService.warn(`[ClaudeSdkMessageRouter] mapper threw, skipping message: ${r}`)}}};ql=R([C(5,xe),C(6,M)],ql);var Bl=class extends w{constructor(e,t,r,i,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 A);this.onDidProduceSignal=this._onDidProduceSignal.event;this._warm=i,this._abortController=s,this._wireAbortHandler(s),this._queue=this._register(c.createInstance($l,e,()=>this._abortController.signal,p=>this._onDidProduceSignal.fire({kind:"steering_consumed",chat:this.chatChannelUri,id:p}))),this._router=this._register(c.createInstance(ql,t,r,a,l,d)),this._register(this._router.onDidProduceSignal(p=>this._onDidProduceSignal.fire(p))),this._register(N(()=>this._abortController.abort())),this._register(N(()=>{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,i]=await Promise.all([e.supportedCommands(),e.supportedAgents(),e.mcpServerStatus()]);return{commands:t,agents:r,mcpServers:i,plugins:this._initPlugins}}async startMcpServer(e){let r=await this._ensureQueryBound();return r.toggleMcpServer&&r.reconnectMcpServer?(await r.toggleMcpServer(e,!0),await r.reconnectMcpServer(e),!0):!1}async stopMcpServer(e){let r=await this._ensureQueryBound();return r.toggleMcpServer?(await r.toggleMcpServer(e,!1),!0):!1}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}get hasActiveTurn(){return!this._queue.isEmpty}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 K;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 i=typeof e.uuid=="string"?e.uuid:t;this._queue.push({sdkMessage:e,sdkUuid:i,turnId:r.turnId,deferred:new Ee,steeringPendingId:t}).catch(()=>{}),this._logService.info(`[Claude:${this.sessionId}] injectSteering: enqueued id=${t} sdkUuid=${i}`)}abort(){this._abortController.signal.aborted||(this._abortController.abort(),this._queue.failAll(new K),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 i=await this._rematerializer(e);if(this._store.isDisposed)throw i.abortController.abort(),Promise.resolve(i.warm[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] rebind-after-dispose: warm dispose failed: ${s}`)),new K;if(r.signal.aborted)throw i.abortController.abort(),Promise.resolve(i.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 K),this._needsRebind=!0,new K;Promise.resolve(t[Symbol.asyncDispose]()).catch(s=>this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] previous WarmQuery dispose failed during rebind: ${s}`)),this._warm=i.warm,this._abortController=i.abortController,this._wireAbortHandler(i.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 K;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(i){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] router threw, skipping: ${i}`)}if(t.type==="result"){let i=this._queue.settleHead();this._logService.info(`[Claude:${this.sessionId}] result for sdkUuid=${i?.sdkUuid}`),i&&this._queue.isEmpty&&this._onDidProduceSignal.fire({kind:"action",resource:this.chatChannelUri,action:{type:"chat/turnComplete",turnId:i.turnId}})}}if(this._abortController.signal.aborted)throw new K;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),!Cn(r))throw r}}};Bl=R([C(8,xe),C(9,M)],Bl);function m8(o,n,e){return _i(o,n)??e}var vr=class extends w{constructor(e,t,r,i,s,a,l,d,c,u,p,m,v,y,S,b,I,_,T,P){super();this.sessionId=e;this.sessionUri=t;this.chatChannelUri=r;this.workingDirectory=i;this._pendingClientToolCalls=u;this._permissionModeFallback=m;this._metadataStore=v;this._instantiationService=y;this._configurationService=S;this._sdkService=b;this._sessionDataService=I;this._logService=_;this._fileService=T;this._environmentService=P;this.subagents=this._register(new dh);this._pendingPermissions=new mt;this._pendingUserInputs=new mt;this.clientCustomizationsDiff=this._register(new ph);this._onDidSessionProgress=this._register(new A);this.onDidSessionProgress=this._onDidSessionProgress.event;this._currentTurnNanoAiu=0;this._transportKind="proxy";this._onDidCustomizationsChange=this._register(new A);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 gh(this.workingDirectory,this._environmentService.userHome,this._fileService,this._logService));this._register(X.onDidChange(()=>this._onDidCustomizationsChange.fire()))}get _storageUri(){return Fe(this._chatChannelUri)?this.sessionUri:this._chatChannelUri}get pendingClientToolCalls(){return this._pendingClientToolCalls}get permissionModeFallback(){return this._permissionModeFallback}static createProvisional(e,t,r,i,s,a,l,d,c,u,p,m){return m.createInstance(vr,e,t,r,i,s,a,l,d,new AbortController,c,new uh,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],i=r?lm(this._lastCustomizations,r):void 0;return i===void 0?e:{...e,action:{...e.action,contributor:{kind:"mcp",customizationId:i}}}}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=_i(this._configurationService,this._storageUri)??this._permissionModeFallback,{mcpServers:r,allowedTools:i}=await this._buildStartupToolWiring(e.serverToolHost),s=await kC(this._provisionalAgent,this._fileService,this._logService,this.sessionId),a=await mC({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:i,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 K;let d=this._sessionDataService.openDatabase(this._storageUri),c;try{c=this._register(this._instantiationService.createInstance(Bl,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(Tu(this._provisionalModel?.id),dC(Cu(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 K;c.attachRematerializer(async u=>{let p=_i(this._configurationService,this._storageUri)??this._permissionModeFallback;try{let{mcpServers:m,allowedTools:v}=await this._buildStartupToolWiring(e.serverToolHost),y=await kC(this._provisionalAgent,this._fileService,this._logService,this.sessionId),S=new AbortController,b=await mC({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:S,permissionMode:p,canUseTool:e.canUseTool,isResume:!0,resumeSessionAt:this._pendingResumeSessionAt,mcpServers:m,allowedTools:v,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 c1(this.toolDiff,this._pendingClientToolCalls,this._sdkService),r=e?await w1(e,this._storageUri.toString(),this._sdkService):void 0,i=!t&&!r?void 0:{...t??{},...r?{[ch]:r}:{}},s=e?e.toolNames.filter(a=>!e.requiresConfirmation(a)):void 0;return{mcpServers:i,allowedTools:s?T1(s):void 0}}get isPipelineReady(){return this._pipeline!==void 0}get hasActiveTurn(){return this._pipeline?.hasActiveTurn??!1}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(m8(this._configurationService,this._storageUri,this._permissionModeFallback)),r.send(e,t)}async _rebindForSyncedState(){this._pendingClientToolCalls.rejectAll(new K),await this._requirePipeline().rebindForRestart(),this._onDidCustomizationsChange.fire()}abort(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._requirePipeline().abort()}async setModel(e){if(this._provisionalModel=e,this._pipeline){let t=Cu(e),r=dC(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(Tu(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 i={type:"user",message:{role:"user",content:mh(e.message.text,e.message.attachments)},session_id:this.sessionId,parent_tool_use_id:null,priority:"now",uuid:e.id};t.injectSteering(i,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=R1(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,[i,s,a,l,d]=await Promise.all([W1(this.workingDirectory,r,this._fileService),k1(this.workingDirectory,r,this._fileService),A1(this.workingDirectory,r,this._fileService),q1(this.workingDirectory,r,this._fileService),B1(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=$1([...i,...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}async startMcpServer(e){let t=await this._resolveMcpServerName(e);if(!t){this._logService.warn(`[Claude:${this.sessionId}] Cannot start unknown MCP server customization ${e}`);return}await this._requirePipeline().startMcpServer(t)||await this._rebindForSyncedState(),this._onDidCustomizationsChange.fire()}async stopMcpServer(e){let t=await this._resolveMcpServerName(e);if(!t){this._logService.warn(`[Claude:${this.sessionId}] Cannot stop unknown MCP server customization ${e}`);return}if(!await this._requirePipeline().stopMcpServer(t)){this._logService.warn(`[Claude:${this.sessionId}] MCP server stop is not supported by the current SDK`);return}this._onDidCustomizationsChange.fire()}async _resolveMcpServerName(e){return Eb(this._lastCustomizations,e)??Eb(await this.getSessionCustomizations(),e)}dispose(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._pendingClientToolCalls.rejectAll(new K),super.dispose()}};vr=R([C(13,xe),C(14,He),C(15,Nl),C(16,rt),C(17,M),C(18,Pe),C(19,bt)],vr);function Y1(o,n){let e=typeof o.plan=="string"?o.plan:"";return{status:"pending-confirmation",toolCallId:n,toolName:"ExitPlanMode",displayName:Sn("ExitPlanMode"),invocationMessage:{markdown:e},toolInput:JSON.stringify(o),confirmationTitle:f(2060,null),options:[{id:"approve",label:f(2058,null),kind:"approve"},{id:"deny",label:f(2059,null),kind:"deny"}]}}function Q1(o){let n=o;if(n.questions?.length)return{questions:n.questions}}function X1(o,n){return o||`q-${n}`}function Z1(o){return o.questions.map((n,e)=>{let t=n.options.map(i=>({id:i.label,label:i.label,...i.description!==void 0?{description:i.description}:{}})),r=X1(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 e0(o,n){let e={};for(let t=0;t<o.questions.length;t++){let r=o.questions[t],i=n[X1(r.header,t)];if(!i||i.state==="skipped")continue;let s=[],a=i.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 t0(o,n,e,t,r){let i=o.getSession(n);if(!i)return{behavior:"deny",message:"Session is no longer active"};if(r.signal.aborted)return{behavior:"deny",message:"SDK aborted the tool request"};let s=()=>{i.respondToPermissionRequest(r.toolUseID,!1),i.respondToUserInputRequest(r.toolUseID,"cancel")};r.signal.addEventListener("abort",s);try{return await h8(o,i,e,t,r)}finally{r.signal.removeEventListener("abort",s)}}async function h8(o,n,e,t,r){if(g1.has(e))return y8(o,n,e,t,r);let i=sh(e),s=Sn(e),a=r.blockedPath??Vr(e,t),l=Ii(e,t),d=Eo(e),c={status:"pending-confirmation",toolCallId:r.toolUseID,toolName:e,displayName:s,invocationMessage:ko(e,s,t),toolInput:l,confirmationTitle:m1(e),...d?{_meta:d}:{}},u=UC(n,r);return await n.requestPermission({toolUseID:r.toolUseID,state:c,permissionKind:i,...a!==void 0?{permissionPath:a}:{},...u!==void 0?{parentToolCallId:u}:{}})?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:LC}}function UC(o,n){if(!n.agentID)return;let e=o.subagents.getParentSpawn(n.toolUseID);if(e)return e.setAgentId(n.agentID),e.toolUseId}function y8(o,n,e,t,r){switch(e){case"ExitPlanMode":return v8(o,n,t,r);case"AskUserQuestion":return S8(o,n,t,r);default:return Promise.resolve({behavior:"deny",message:`Unsupported interactive tool: ${e}`})}}async function v8(o,n,e,t){let r=t.toolUseID,i=UC(n,t);return await n.requestPermission({toolUseID:r,state:Y1(e,r),permissionKind:sh("ExitPlanMode"),...i!==void 0?{parentToolCallId:i}:{}})?(o.configurationService.updateSessionConfig(n.sessionUri.toString(),{permissionMode:"acceptEdits"}),{behavior:"allow",updatedInput:e}):{behavior:"deny",message:NC}}async function S8(o,n,e,t){let r=t.toolUseID,i=Q1(e);if(!i)return{behavior:"deny",message:"AskUserQuestion called without questions"};let s=UC(n,t),a=await n.requestUserInput({id:r,questions:Z1(i)},s);if(a.response!=="accept"||!a.answers)return{behavior:"deny",message:yh};let l=e0(i,a.answers);return Object.keys(l).length===0?{behavior:"deny",message:yh}:{behavior:"allow",updatedInput:{...e,answers:l}}}import{once as C8}from"events";var b8=["interleaved-thinking","context-management","advanced-tool-use"];function n0(o){let n=o.split(",").map(e=>e.trim()).filter(e=>e&&b8.some(t=>e.startsWith(t+"-")));return n.length>0?n.join(","):void 0}function FC(o,n){return{type:"error",error:{type:o,message:n},request_id:null}}function Xn(o,n,e,t){o.writeHead(n,{"Content-Type":"application/json"}),o.end(JSON.stringify(FC(e,t)))}function r0(o,n,e){o.writeHead(n,{"Content-Type":"application/json"}),o.end(JSON.stringify(e))}function o0(o){return`event: error
data: ${JSON.stringify(o)}

`}var Ih=W("claudeProxyService"),I8=new Set(["anthropic"]),_8="/v1/messages",zl="ClaudeProxyService",i0="vscode_claude_code";function HC(o){let n=o?.copilot_usage?.total_nano_aiu;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}var Vl=class extends Si{constructor(e,t){super(zl,e);this._copilotApiService=t;this._onDidReportCredits=new A;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){Xn(e,500,"api_error","Internal proxy error")}_reportCredits(e,t){e===void 0||t===void 0||(this._logService.trace(`[${zl}] credits: session=${e} totalNanoAiu=${t}`),this._onDidReportCredits.fire({sessionId:e,totalNanoAiu:t}))}async handleRequest(e,t,r){let i=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname;if(this._logService.trace(`[${zl}] ${i} ${s}`),i==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=Lm(e.headers,r.nonce);if(!a.valid){Xn(t,401,"authentication_error","Invalid authentication");return}if(i==="GET"&&s==="/v1/models"){await this._handleModels(e,t,r);return}if(i==="POST"&&s==="/v1/messages"){await this._handleMessages(e,t,r,a.sessionId);return}if(i==="POST"&&s==="/v1/messages/count_tokens"){Xn(t,501,"api_error","count_tokens not supported by CAPI");return}Xn(t,404,"not_found_error",`No route for ${i} ${s}`)}async _handleModels(e,t,r){let i=s0(e.headers),s;try{s=await this._copilotApiService.models(r.state.githubToken,{headers:i,suppressIntegrationId:!0})}catch(d){this._writeUpstreamErrorResponse(t,d);return}let a=[];for(let d of s){if(!T8(d))continue;let c=Is(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,i){let s;try{s=await _l(e)}catch(S){Xn(t,400,"invalid_request_error",`Failed to read request body: ${Ch(S)}`);return}let a;try{a=JSON.parse(s)}catch{Xn(t,400,"invalid_request_error","Request body is not valid JSON");return}if(!a||typeof a!="object"){Xn(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){Xn(t,400,"invalid_request_error","Missing required field: model");return}if(!Array.isArray(l.messages)){Xn(t,400,"invalid_request_error","Missing required field: messages");return}let c=Is(d);if(!c){Xn(t,404,"not_found_error",`Unknown model: ${d}`);return}let u=c.toEndpointModelId();l.model=u;let p=l.stream===!0,m=s0(e.headers),v={ac:new AbortController,res:t,clientGone:!1};r.inFlight.add(v);let y=()=>{v.clientGone=!0,v.ac.abort()};t.on("close",y);try{p?await this._streamMessages(l,m,t,v,r,d,i):await this._sendNonStreamingMessage(l,m,t,v,r,d,i)}finally{t.removeListener("close",y),r.inFlight.delete(v)}}async _sendNonStreamingMessage(e,t,r,i,s,a,l){let d={headers:t,signal:i.ac.signal,suppressIntegrationId:!0},c;try{c=await this._copilotApiService.messages(s.state.githubToken,e,d)}catch(m){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,m,!0);return}this._reportCredits(l,HC(c));let u=l0(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,i,s,a,l){let d={headers:t,signal:i.ac.signal,suppressIntegrationId:!0},c;try{c=this._copilotApiService.messages(s.state.githubToken,e,d)}catch(v){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,v,!0);return}let u;try{u=await c.next()}catch(v){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,v,!0);return}r.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushHeaders(),x8(r);let p=async v=>{let y=w8(v,this._logService),S=`event: ${y.type}
data: ${JSON.stringify(y)}

`;if(!r.write(S))try{await C8(r,"drain",{signal:i.ac.signal})}catch{return!1}return!0},m;try{if(!u.done&&(m=HC(u.value)??m,!await p(u.value)))return;for(;;){let v;try{v=await c.next()}catch(S){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}let b=S instanceof gr?a0(S):FC("api_error",Ch(S));if(!r.writableEnded){try{r.write(o0(b))}catch{}try{r.end()}catch{}}return}if(v.done)break;if(m=HC(v.value)??m,!await p(v.value))return}r.writableEnded||r.end(),this._reportCredits(l,m)}catch(v){if(this._logService.warn(`[${zl}] stream loop unexpected error: ${Ch(v)}`),!r.writableEnded)try{r.end()}catch{}}}_writeUpstreamErrorResponse(e,t,r=!1){if(e.headersSent){if(this._logService.warn(`[${zl}] cannot write upstream error after headers sent: ${Ch(t)}`),!e.writableEnded)try{e.end()}catch{}return}if(t instanceof gr){let i=t.status===Dc?502:t.status;r0(e,i,r?a0(t):t.envelope);return}Xn(e,502,"api_error",t instanceof Error?t.message:String(t))}};Vl=R([C(0,M),C(1,Pt)],Vl);function T8(o){return I8.has(o.vendor.toLowerCase())?Array.isArray(o.supported_endpoints)&&o.supported_endpoints.includes(_8):!1}function l0(o,n){let e=Is(o);if(!e){n.warn(`[${zl}] outbound model ID could not be parsed for SDK rewrite: ${o}`);return}return e.toSdkModelId()}function w8(o,n){if(o.type!=="message_start")return o;let e=l0(o.message.model,n);return e===void 0||e===o.message.model?o:{...o,message:{...o.message,model:e}}}function s0(o){let n={},e=o["anthropic-version"];typeof e=="string"&&e.length>0&&(n["anthropic-version"]=e);let t=o["anthropic-beta"];if(typeof t=="string"&&t.length>0){let i=n0(t);i!==void 0&&(n["anthropic-beta"]=i)}let r=o["user-agent"];return typeof r=="string"&&r.length>0&&(n["User-Agent"]=R8(r)),n}function R8(o){let n=o.indexOf("/");return n===-1?`${i0}/${o}`:`${i0}${o.substring(n)}`}function x8(o){let n=o.socket;if(n&&typeof n.setNoDelay=="function")try{n.setNoDelay(!0)}catch{}}function Ch(o){return o instanceof Error?o.message:String(o)}function a0(o){let n=Fg(Ug(o));return{...o.envelope,error:{...o.envelope.error,message:`${o.envelope.error.message} ${n}`}}}var jt=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 i=[];e.customizationDirectory&&i.push(r.setMetadata(jt.KEY_CUSTOMIZATION_DIRECTORY,e.customizationDirectory.toString())),e.model&&i.push(r.setMetadata(jt.KEY_MODEL,A8(e.model))),e.permissionMode&&i.push(r.setMetadata(jt.KEY_PERMISSION_MODE,e.permissionMode)),e.agent!==void 0&&i.push(r.setMetadata(jt.KEY_AGENT,e.agent===null?"":JSON.stringify({uri:e.agent.uri}))),e.transport&&i.push(r.setMetadata(jt.KEY_TRANSPORT,e.transport)),await Promise.all(i)}finally{t.dispose()}}async read(n){let e=await this._sessionDataService.tryOpenDatabase(n);if(!e)return{};try{let[t,r,i,s,a]=await Promise.all([e.object.getMetadata(jt.KEY_CUSTOMIZATION_DIRECTORY),e.object.getMetadata(jt.KEY_MODEL),e.object.getMetadata(jt.KEY_PERMISSION_MODE),e.object.getMetadata(jt.KEY_AGENT),e.object.getMetadata(jt.KEY_TRANSPORT)]);return{customizationDirectory:t?h.parse(t):void 0,model:E8(r),permissionMode:Cs(i),agent:P8(s),transport:a==="proxy"||a==="native"?a:void 0}}finally{e.dispose()}}project(n,e){return{session:D.uri(this._provider,n.sessionId),startTime:n.createdAt??n.lastModified,modifiedTime:n.lastModified,summary:n.customTitle??n.summary,workingDirectory:n.cwd?h.file(n.cwd):void 0,customizationDirectory:e.customizationDirectory}}};jt=R([C(1,rt)],jt);function P8(o){if(o)try{let n=JSON.parse(o);if(n&&typeof n=="object"&&typeof n.uri=="string")return{uri:n.uri}}catch{}}function A8(o){return JSON.stringify(o)}function E8(o){if(o){try{let n=JSON.parse(o);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,i]of Object.entries(n.config))typeof i=="string"&&(t[r]=i);Object.keys(t).length>0&&(e.config=t)}return e}}catch{}return{id:o}}}var k8="vscode_claude_code";function D8(o){return o.vendor==="Anthropic"&&!!o.supported_endpoints?.includes("/v1/messages")&&!!o.model_picker_enabled&&!!o.capabilities?.supports?.tool_calls&&Is(o.id)!==void 0}function M8(o,n){let e=o.capabilities?.supports,t=(e?.reasoning_effort??[]).filter(cC),r=uC(t),i=o.policy?.state,s=Tm(o.billing),a=typeof o.model_picker_price_category=="string"?o.model_picker_price_category:void 0;return{provider:n,id:o.id,name:o.name,maxContextWindow:o.capabilities?.limits?.max_context_window_tokens,maxOutputTokens:o.capabilities?.limits?.max_output_tokens,maxPromptTokens:o.capabilities?.limits?.max_prompt_tokens,supportsVision:!!e?.vision,...r?{configSchema:r}:{},...i?{policyState:i}:{},_meta:yl(s,a)}}function O8(o,n){let e=(o.supportedEffortLevels??[]).filter(cC),t=uC(e);return{provider:n,id:o.value,name:o.displayName,supportsVision:!1,...t?{configSchema:t}:{}}}var $C=class{constructor(n,e,t,r,i){this.clientId=n;this.displayName=e;this._getTools=t;this._setTools=r;this._syncCustomizations=i;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)}},jl=class extends w{constructor(e,t,r,i,s,a,l,d,c,u,p){super();this._logService=e;this._copilotApiService=t;this._claudeProxyService=r;this._sdkService=i;this._gitService=s;this._configurationService=a;this._gitHubEndpointService=l;this._instantiationService=d;this._pluginManager=c;this._productService=u;this._environmentService=p;this.id=ow;this._onDidSessionProgress=this._register(new A);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new A);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._onDidRequireAuth=this._register(new A);this.onDidRequireAuth=this._onDidRequireAuth.event;this._models=rn(this,[]);this.models=this._models;this._transportMode="proxy";this._sessions=this._register(new we);this._chatBackings=new Map;this._onDidChangeChatData=this._register(new A);this.onDidChangeChatData=this._onDidChangeChatData.event;this._onDidSpawnChat=this._register(new A);this.onDidSpawnChat=this._onDidSpawnChat.event;this._activeClientHandles=new Map;this._onDidMaterializeSession=this._register(new A);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,i,s)=>this._sendMessage(e,t,r,i,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=d.createInstance(jt,this.id),this._register(this._claudeProxyService.onDidReportCredits(m=>{this._findSessionBySdkId(m.sessionId)?.recordTurnCredits(m.totalNanoAiu)})),this._transportMode=this._resolveTransportMode(),this._register(this._configurationService.onDidRootConfigChange(()=>{let m=this._resolveTransportMode();m!==this._transportMode&&(this._transportMode=m,this._refreshModels(),m==="proxy"&&!this._proxyHandle&&this._onDidRequireAuth.fire({resource:this._gitHubEndpointService.getCopilotResource().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(D.id(e));if(r)return r.getChat((t??h.parse(pe(e))).toString())}_getChatContext(e){let t=ke(e)?e:h.parse(pe(e)),r=h.parse(fe(t)),i=D.id(r),s=t.toString(),a=this._sessions.get(i)?.resolveChat(s);return{session:r,sessionId:i,chatKey:s,target:a?.chatSession,isPeerChat:a?!a.isDefault:s!==pe(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 _h(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 i=new _h;return i.setDefaultChat(pe(t),this._wireEntry(r)),this._sessions.set(e,i),i}_emitSpawnedChatEvents(e){let t=Bi.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_resolveTransportMode(){return this._configurationService.getRootValue(fr,"claudeUseCopilotProxy")??!0?"proxy":"native"}getDescriptor(){return{provider:this.id,displayName:f(2057,null),description:f(2056,null),capabilities:{multipleChats:{fork:!0}}}}getProtectedResources(){return this._transportMode!=="proxy"?[this._gitHubEndpointService.getRepoResource()]:[this._gitHubEndpointService.getCopilotResource(),this._gitHubEndpointService.getRepoResource()]}_ensureAuthenticated(){if(this._transportMode!=="proxy")return{kind:"native"};let e=this._proxyHandle;if(!e)throw new L(cr,"Authentication is required to use Claude",this.getProtectedResources());return{kind:"proxy",handle:e}}async authenticate(e,t){if(e===this._gitHubEndpointService.getRepoResource().resource)return!0;if(e!==this._gitHubEndpointService.getCopilotResource().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 i=await this._claudeProxyService.start(t),s=this._proxyHandle;return this._proxyHandle=i,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(i=>i.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=u1(),r=await this._sdkService.query({prompt:e,options:t});try{return(await r.supportedModels()).map(s=>O8(s,this.id))}finally{r.close(),t.abortController?.abort()}}async _fetchProxyModels(e){let t=`${k8}/${this._productService.version}`;return(await this._copilotApiService.models(e,{headers:{"User-Agent":t},suppressIntegrationId:!0})).filter(D8).sort((i,s)=>Number(s.is_chat_default)-Number(i.is_chat_default)).map(i=>M8(i,this.id))}async createSession(e={}){if(this._ensureAuthenticated(),e.fork)return this._forkSession(e,e.fork);let t=e.session?D.id(e.session):O(),r=D.uri(this.id,t),i=this._findAnySession(t);if(i)return await this._seedEagerActiveClient(r,e.activeClient),i.isPipelineReady?{session:r,workingDirectory:e.workingDirectory}:{session:i.sessionUri,workingDirectory:i.workingDirectory,provisional:!0,...i.project?{project:i.project}:{}};let s=e.workingDirectory??await LA(this._environmentService.userHome,t),a=e.workingDirectory?await Qn({cwd:e.workingDirectory.fsPath},this._gitService):void 0,l=this._resolvePermissionMode(e.config),d=vr.createProvisional(t,r,h.parse(pe(r)),s,a,e.model,e.agent,e.config,new mt,l,this._metadataStore,this._instantiationService);return this._seedSessionEntry(t,r,d),await this._seedEagerActiveClient(r,e.activeClient),{session:r,workingDirectory:s,provisional:!0,...a?{project:a}:{}}}async _seedEagerActiveClient(e,t){if(!t)return;let r=this.getOrCreateActiveClient(e,{clientId:t.clientId,displayName:t.displayName});r.tools=t.tools,t.customizations!==void 0&&await this.syncClientCustomizations(e,t.clientId,t.customizations,{quiet:!0})}async truncateSession(e,t){let r=D.id(e);await this._sessionSequencer.queue(r,async()=>{let i=this._findAnySession(r);if(i&&!i.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,i);return}let s=await this._sdkService.getSessionMessages(r,{includeSystemMessages:!0}),a=lh(s,t);if(a===void 0)throw new Error(`Cannot truncate session ${r}: turn ${t} not found in transcript`);await(i??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 i=r?void 0:await this._sdkService.getSessionInfo(t),s=r?.workingDirectory??(i?.cwd?h.file(i.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=ke(e);if(!t)throw new Error(`Claude chat operation requires an AHP chat URI: ${e.toString()}`);return{session:h.parse(t.session),chat:e}}async _forkSession(e,t){if(lr(t.session))throw new Error("Cannot fork a subagent session");let r=D.id(t.session),i=this._findAnySession(r);if(i&&!i.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=lh(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=D.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=Cs(e.config?.permissionMode)??c.permissionMode;await this._metadataStore.write(d,{...u?{model:u}:{},...m?{permissionMode:m}:{},...p?{agent:p}:{}});let v=await this._sdkService.getSessionInfo(l),y=v?.cwd?h.file(v.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 Qn({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,i)=>t0({getSession:s=>this._findSessionBySdkId(s),configurationService:this._configurationService},e,t,r,i)}async _materializeProvisional(e){let t=this._findAnySession(e);if(!t)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let r=this._ensureAuthenticated(),i=this._makeCanUseTool(e);try{await t.materialize({transport:r,canUseTool:i,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(),i=await this._sdkService.getSessionInfo(e);if(!i)throw new Error(`Cannot resume unknown session: ${e} (not present in SDK transcript store)`);let s=i.cwd?h.file(i.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=_i(this._configurationService,t)??a.permissionMode??"default",d;try{d=await Qn({cwd:s.fsPath},this._gitService)}catch(p){this._logService.warn(`[Claude:${e}] project resolution failed during resume; continuing without project`,p)}let c=vr.createProvisional(e,t,h.parse(pe(t)),s,d,a.model,a.agent,void 0,new mt,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 Cs(e?.permissionMode)??"default"}disposeSession(e){let t=D.id(e);return this._disposeSequencer.queue(t,async()=>{await this._teardownEntry(t),this._pruneActiveClientHandles(t)})}releaseSession(e){let t=D.id(e);return this._disposeSequencer.queue(t,async()=>{let r=this._sessions.get(t);r&&r.defaultChat?.isPipelineReady&&(r.allChatSessions().some(i=>i.hasActiveTurn)||(this._logService.info(`[Claude:${t}] Releasing idle session from memory (durable state preserved)`),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(i=>this._sessionSequencer.queue(i,async()=>{let s=t.getPeerChat(i);s&&(s.isPipelineReady?s.abort():s.abortController.abort()),t.disposePeerChat(i)}))),this._sessions.deleteAndDispose(e);for(let i of[...this._chatBackings.keys()]){let s=ke(h.parse(i));s&&D.id(h.parse(s.session))===e&&this._chatBackings.delete(i)}}async _createChat(e,t){if(this._ensureAuthenticated(),Fe(e))return;let r=ke(e);if(!r)throw new Error(`[Claude] createChat: malformed chat URI ${e.toString()}`);let i=h.parse(r.session),s=e.toString(),a=D.id(i),l;return await this._sessionSequencer.queue(a,async()=>{let d=this._chatBackings.get(s);if(d){l={providerData:qr(d),backingSession:D.uri(this.id,d.sdkSessionId)};return}let c=await this._resolveParentSession(i,a),u=t?.model??c.model,p;t?.fork&&(p=await this._forkChat(i,t.fork)),p??=O();let m={sdkSessionId:p,...u?{model:u}:{}};this._chatBackings.set(s,m),l={providerData:qr(m),backingSession:D.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 ${i.toString()}${t?.fork?" (forked)":""}`)}),l}async _disposeChat(e,t){if(Fe(t))return;let r=t.toString(),i=D.id(e);await this._sessionSequencer.queue(r,async()=>{let s=this._sessions.get(i),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),i=r?.workingDirectory,s=r?.project;if(!i){let d=await this._sdkService.getSessionInfo(t);i=d?.cwd?h.file(d.cwd):void 0}if(!i)throw new Error(`[Claude] createChat: cannot resolve working directory for parent session ${e.toString()}`);if(!s)try{s=await Qn({cwd:i.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=_i(this._configurationService,e)??a.permissionMode??"default";return{workingDirectory:i,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 i=await this._sdkService.getSessionMessages(r,{includeSystemMessages:!0}),s=lh(i,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(Fe(t)||t.toString()===e.toString())return D.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=D.id(e);return this._sessionSequencer.queue(t,async()=>{let r=this._sessions.get(t);if(r)return r;let i=await this._resolveParentSession(e,t),s=vr.createProvisional(t,e,h.parse(pe(e)),i.workingDirectory,i.project,i.model,i.agent,void 0,new mt,i.permissionMode,this._metadataStore,this._instantiationService);return this._seedSessionEntry(t,e,s)})}async _materializeChatLocked(e,t){let r=t.toString(),i=await this._ensureSessionEntry(e),s=i.getPeerChat(r);if(s?.isPipelineReady)return s;let a=s??await this._buildProvisionalChat(e,t,i),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 i.disposePeerChat(r),u}return a}async _buildProvisionalChat(e,t,r){let i=this._resolveChatBacking(t);if(!i)throw new Error(`[Claude] no backing chat for chat ${t.toString()}`);let s=await this._resolveParentSession(e,D.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=_i(this._configurationService,t)??a.permissionMode??s.permissionMode,d=a.model??i.model,c=vr.createProvisional(i.sdkSessionId,e,t,s.workingDirectory,s.project,d,a.agent??s.agent,void 0,new mt,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 i={sdkSessionId:r.sdkSessionId,model:t};this._chatBackings.set(e.toString(),i),this._onDidChangeChatData.fire({chat:e,providerData:qr(i)})}async materializeChat(e,t){if(Fe(e)||!ke(e)||t===void 0)return;let i=wm(t);if(!i){this._logService.warn(`[Claude] materializeChat: dropping corrupt providerData for ${e.toString()}`);return}this._chatBackings.set(e.toString(),i)}getSessionForTesting(e){let t=this._sessions.get(D.id(e))?.defaultChat;return t?.isPipelineReady?t:void 0}async getSessionMessages(e){if(!await this._sdkService.canLoadWithoutDownload())return this._logService.info("[Claude] SDK not downloaded yet; deferring session messages until a session triggers the download"),[];if(lr(e)){let d=ut(e),c=d?this._sessions.get(D.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 _1(e,c.subagents,this._sdkService,this._logService,Re.None)}catch(u){return this._logService.warn(`[Claude] getSubagentTranscript threw for ${e.toString()}`,u),[]}}let t=ke(e)?e:h.parse(pe(e)),r=ke(t);if(!r)return[];let i=h.parse(r.session),s=D.id(i),a=this._getChatContext(t);if(a.isPeerChat){let d=await this._resolveChatSdkId(i,t);return d?this._reconstructTurns(d,t,a.target):[]}let l=a.target;return l&&!l.isPipelineReady?[]:this._reconstructTurns(s,i,l)}async _reconstructTurns(e,t,r){let i;try{i=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=xu(i,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=D.uri(this.id,t.sessionId),i=await this._metadataStore.read(r);return this._metadataStore.project(t,i)}catch(r){this._logService.warn(`[Claude] Overlay read failed for session ${t.sessionId}`,r)}return this._metadataStore.project(t,{})}))}async getSessionMetadata(e){if(!await this._sdkService.canLoadWithoutDownload()){this._logService.info("[Claude] SDK not downloaded yet; deferring session metadata until a session triggers the download");return}let t=D.id(e),r=await this._sdkService.getSessionInfo(t);if(!r)return;let i={};try{i=await this._metadataStore.read(e)}catch(s){this._logService.warn(`[Claude] Overlay read failed for session ${t}`,s)}return this._metadataStore.project(r,i)}resolveSessionConfig(e){let t=nn({permissionMode:ce({type:"string",title:f(2044,null),description:f(2055,null),enum:["default","acceptEdits","plan","auto","bypassPermissions"],enumLabels:[f(2051,null),f(2045,null),f(2053,null),f(2047,null),f(2049,null)],enumDescriptions:[f(2052,null),f(2046,null),f(2054,null),f(2048,null),f(2050,null)],default:"default",sessionMutable:!0}),permissions:Yt.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,i,s){let a=i??O(),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,i){return{type:"user",message:{role:"user",content:mh(t,r)},session_id:e,parent_tool_use_id:null,uuid:i}}respondToPermissionRequest(e,t){for(let r of this._allLiveSessions())if(r.respondToPermissionRequest(e,t))return}respondToUserInputRequest(e,t,r){for(let i of this._allLiveSessions())if(i.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,i){let s=!!i&&!Fe(i),a=this._findChat(e,i);if(this._logService.info(`[Claude] setPendingMessages for ${(i??e).toString()}: steering=${t?.id??"none"} queued=${r.length}`),!a){this._logService.warn(`[Claude] setPendingMessages: ${s?"chat":"session"} not found for ${(i??e).toString()}`);return}t&&a.injectSteering(t)}async _changeModel(e,t){let r=this._getChatContext(e),i=r.isPeerChat?r.chatKey:r.sessionId;await this._sessionSequencer.queue(i,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),i=r.isPeerChat?r.chatKey:r.sessionId;await this._sessionSequencer.queue(i,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=D.id(e),i=`${r}\0${t.clientId}`,s=this._activeClientHandles.get(i);return s||(s=new $C(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(i,s)),s}removeActiveClient(e,t){let r=D.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,i){let s=e,a;for(;a=ut(s);)s=a.parentSession;let l=D.id(s);this._sessions.get(l)?.defaultChat?.completeClientToolCall(r,i)}async syncClientCustomizations(e,t,r,i){let s=D.id(e),a=this._findAnySession(s);return a?this._sessionSequencer.queue(s,async()=>{let l=await this._pluginManager.syncCustomizations(t,r,i?.quiet?void 0:d=>this._fireCustomizationUpdated(e,{customization:d}));return a.adoptClientCustomizations(t,l),l}):(this._logService.warn(`[Claude:${s}] 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(D.id(e));return t?await t.getSessionCustomizations():[]}async startMcpServer(e,t){await this._findAnySession(D.id(e))?.startMcpServer(t)}async stopMcpServer(e,t){await this._findAnySession(D.id(e))?.stopMcpServer(t)}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)}};jl=R([C(0,M),C(1,Pt),C(2,Ih),C(3,Nl),C(4,Ye),C(5,He),C(6,xt),C(7,xe),C(8,vl),C(9,ft),C(10,bt)],jl);var _h=class extends Sl{get defaultChat(){return super.defaultChat}};import{spawn as gH}from"child_process";import*as jr from"fs";import*as ak from"os";function d0(o,n){switch(o){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 L8(o){let n=[];for(let e of Object.keys(o)){let t=o[e];t&&n.push(t)}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}function N8(o){return{state:{kind:"ready"},tools:L8(o.tools),resources:o.resources,resourceTemplates:o.resourceTemplates}}function c0(o){let n=new Map;for(let e of o)n.set(e.name,N8(e));return n}function Th(o){let n=[];for(let[e,t]of o)n.push({name:e,state:t.state});return n}function u0(o,n){switch(o){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 p0(o,n){let e=(o?.tools??[]).map(r=>r.name).sort(),t=(n?.tools??[]).map(r=>r.name).sort();return e.length!==t.length?!0:e.some((r,i)=>r!==t[i])}function g0(o,n){if(n.mode==="url"){let r={id:o,message:n.message};return n.url&&(r.url=n.url),r}if(n.mode!=="form")return{id:o,message:n.message};let e=new Set(n.requestedSchema.required??[]),t=[];for(let[r,i]of Object.entries(n.requestedSchema.properties))i&&t.push(U8(r,i,e.has(r)));return t.length>0?{id:o,message:n.message,questions:t}:{id:o,message:n.message}}function m0(o,n,e){if(n==="decline")return{action:"decline",content:null,_meta:null};if(n!=="accept")return{action:"cancel",content:null,_meta:null};if(o.mode!=="form")return{action:"accept",content:null,_meta:null};let t={};for(let[r,i]of Object.entries(o.requestedSchema.properties)){if(!i)continue;let s=F8(e?.[r]);s!==void 0&&(t[r]=s)}return{action:"accept",content:t,_meta:null}}function h0(){return{action:"decline",content:null,_meta:null}}function y0(){return{action:"cancel",content:null,_meta:null}}function U8(o,n,e){let t={id:o,title:n.title,message:n.description??n.title??o,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:he(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:f0(n.minItems),max:f0(n.maxItems)};case"string":if(he(n,{oneOf:!0}))return{...t,kind:"single-select",options:n.oneOf.map(r=>({id:r.const,label:r.title||r.const}))};if(he(n,{enum:!0})){let r=n.enumNames;return{...t,kind:"single-select",options:n.enum.map((i,s)=>({id:i,label:r?.[s]||i}))}}return{...t,kind:"text",format:n.format,min:n.minLength,max:n.maxLength,defaultValue:n.default}}}function F8(o){if(!o||o.state==="skipped")return;let{value:n}=o;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 f0(o){return o==null?void 0:Number(o)}var Ti=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r;this.name="JsonRpcError"}},H8=2e3,wh=class extends w{constructor(e,t,r=H8){super();this._transport=e;this._onLog=t;this._graceKillMs=r;this._onExit=this._register(new A);this.onExit=this._onExit.event;this._onTransportError=this._register(new A);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(i=>this._handleExit(i))),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 i;for(;(i=this._buf.indexOf(`
`))>=0;){let s=this._buf.slice(0,i);this._buf=this._buf.slice(i+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),N(()=>this._transport.stdout.off("data",e))}_dispatch(e){let t=he(e,{id:!0}),r=he(e,{method:!0});if(t&&!r&&(he(e,{result:!0})||he(e,{error:!0}))){if(typeof e.id!="number"){this._log("warn",`unsolicited response id=${e.id}`);return}let i=e.id,s=this._pending.get(i);if(!s){this._log("warn",`unsolicited response id=${e.id}`);return}this._pending.delete(i),he(e,{error:!0})&&e.error?s.reject(new Ti(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 i=r instanceof Error?r.message:String(r);this._log("error",`handler for ${e.method} threw: ${i}`),this._writeMessage({id:e.id,error:{code:-32603,message:i}})}}_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,i]of this._pending)i.reject(new Ti(-32603,`${t}; request id=${r} (${i.method}) aborted`));this._pending.clear(),this._onExit.fire(e)}request(e,t){if(this._disposed)return Promise.reject(new K);if(this._exited)return Promise.reject(new Ti(-32603,"transport has exited"));let r=this._nextId++;return new Promise((i,s)=>{this._pending.set(r,{method:e,resolve:i,reject:s}),this._writeMessage({id:r,method:e,params:t})||(this._pending.delete(r),s(new Ti(-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),N(()=>{this._notificationHandlers.get(e)===t&&this._notificationHandlers.delete(e)})}onRequest(e,t){let r=async i=>await t(i);return this._requestHandlers.set(e,r),N(()=>{this._requestHandlers.get(e)===r&&this._requestHandlers.delete(e)})}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._pending.values())e.reject(new K);this._pending.clear();try{this._transport.stdin.end()}catch{}if(!this._exited){let e=setTimeout(()=>{try{this._transport.kill("SIGKILL")}catch{}},this._graceKillMs);this._transport.onExitOnce(()=>{clearTimeout(e)}),e.unref?.()}super.dispose()}}_log(e,t){this._onLog?.(e,t)}};function v0(o){if(!o.stdin||!o.stdout)throw new Error("Child process has no stdio pair");return{stdin:o.stdin,stdout:o.stdout,kill:n=>o.kill(n),onExit:ee.fromNodeEventEmitter(o,"exit",(n,e)=>({code:n,signal:e})),onExitOnce:n=>o.once("exit",(e,t)=>n({code:e,signal:t}))}}import*as Gl from"fs";var Rh=W("codexProxyService"),$8="codex-auto-review",Kt="CodexProxyService",S0="vscode_codex",W8="VSCODE_CODEX_PROXY_DUMP_DIR",q8=0;function B8(){return String(++q8).padStart(4,"0")}function z8(){let o=process.env[W8];if(o)try{return Gl.mkdirSync(o,{recursive:!0}),o}catch{return}}function Au(o,n,e,t){o.headersSent||o.writableEnded||(o.writeHead(n,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:{type:e,message:t}})))}var Kl=class extends Si{constructor(e,t){super(Kt,e);this._copilotApiService=t}createState(e){return{githubToken:e,lastPrimaryModel:void 0}}async start(e){let{runtime:t,release:r}=await this.acquire(e);t.state.githubToken=e;let i=!1;return{baseUrl:t.baseUrl,nonce:t.nonce,setToken:s=>{i||(t.state.githubToken=s)},dispose:()=>{i||(i=!0,r())}}}async handleRequest(e,t,r){let i=e.method??"GET",s=new URL(e.url??"/","http://127.0.0.1").pathname,a=Object.keys(e.headers).join(", ");if(this._logService.info(`[${Kt}] >>> ${i} ${s} (headers: ${a})`),i==="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){Au(t,401,"authentication_error","Invalid authentication");return}if(i==="POST"&&(s==="/v1/responses"||s==="/responses"||s==="//responses")){await this._handleResponses(e,t,r);return}Au(t,404,"not_found_error",`No route for ${i} ${s}`)}async _handleResponses(e,t,r){let i;try{i=await _l(e)}catch(m){Au(t,400,"invalid_request_error",`Failed to read request body: ${m instanceof Error?m.message:String(m)}`);return}let s=V8(i,r.state);s.remappedFrom&&this._logService.info(`[${Kt}] remapped unsupported reviewer model '${s.remappedFrom}' -> '${s.remappedTo}'`),i=s.body;let a=z8(),l=a?B8():void 0;if(a&&l){let m=j(a,`req-${l}-${Date.now()}.json`);try{Gl.writeFileSync(m,i),this._logService.info(`[${Kt}] dumped request body to ${m}`)}catch(v){this._logService.warn(`[${Kt}] failed to dump request body: ${v instanceof Error?v.message:String(v)}`)}}try{let m=JSON.parse(i);if(this._logService.info(`[${Kt}] >>> /responses body: model=${m.model??"<none>"}, previous_response_id=${m.previous_response_id??"<none>"}, stream=${m.stream??"<none>"}, input_items=${Array.isArray(m.input)?m.input.length:"<not-array>"}`),Array.isArray(m.input))for(let y=0;y<m.input.length;y++){let S=m.input[y],b=S?.type??"<none>",I=S&&typeof S=="object"?Object.keys(S).join(","):typeof S,_="";if(b==="message"){let T=S?.content?.[0]?.text??"";_=`role=${S?.role??"?"} chars=${T.length}`}else if(b==="function_call")_=`name=${S?.name??"?"} call_id=${S?.call_id??"?"}`;else if(b==="function_call_output"){let T=S?.output??"";_=`call_id=${S?.call_id??"?"} output_chars=${typeof T=="string"?T.length:0}`}else if(b==="reasoning"){let T=S?.summary??S?.content??"";_=`summary_chars=${typeof T=="string"?T.length:JSON.stringify(T).length} encrypted=${typeof S?.encrypted_content=="string"}`}else _=JSON.stringify(S).slice(0,120);this._logService.info(`[${Kt}]   input[${y}] type=${b} keys=[${I}] ${_}`)}let v=Object.keys(m).filter(y=>y!=="input").sort();this._logService.info(`[${Kt}]   top-level keys (excl. input)=[${v.join(", ")}]`);for(let y of v){if(y==="instructions"||y==="tools"){let I=m[y],_=typeof I=="string"?I.length:JSON.stringify(I).length;this._logService.info(`[${Kt}]     ${y}=<${_} chars elided>`);continue}let S=m[y],b=typeof S=="object"?JSON.stringify(S).slice(0,300):String(S);this._logService.info(`[${Kt}]     ${y}=${b}`)}}catch{this._logService.info(`[${Kt}] >>> /responses body (unparseable): ${i.slice(0,200)}`)}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);let u=r.state.githubToken,p=j8(e.headers);try{this._logService.info(`[${Kt}] forwarding to CAPI responses...`);let m=await this._copilotApiService.responses(u,i,{headers:p,signal:d.ac.signal,suppressIntegrationId:!0}),v=m.headers.get("content-type")??"application/json",y=[...m.headers.entries()].map(([T,P])=>`${T}: ${P}`).join(", ");if(this._logService.info(`[${Kt}] <<< CAPI response: status=${m.status}, contentType=${v}, headers=[${y}]`),t.writeHead(m.status,{"Content-Type":v}),!m.body){t.end();return}let S=m.body.getReader(),b=a&&l?Gl.createWriteStream(j(a,`res-${l}-${Date.now()}.txt`)):void 0,I="",_={};try{for(;;){let{done:T,value:P}=await S.read();if(T||d.clientGone)break;if(P&&P.byteLength>0){let X=Buffer.from(P);t.write(X),b&&b.write(X),I+=X.toString("utf8");let k;for(;(k=I.indexOf(`
`))>=0;){let x=I.slice(0,k).trimEnd();if(I=I.slice(k+1),x.startsWith("event:")){let E=x.slice(6).trim();_[E]=(_[E]??0)+1}}}}}finally{try{S.releaseLock()}catch{}b?.end()}if(Object.keys(_).length){let T=Object.entries(_).map(([P,X])=>`${P}=${X}`).join(", ");this._logService.info(`[${Kt}] <<< SSE event counts: ${T}`)}t.end()}catch(m){if(d.clientGone){this._logService.info(`[${Kt}] client disconnected during upstream call`);return}if(m instanceof gr){this._logService.error(`[${Kt}] CAPI error: status=${m.status}, message=${m.message}`);let v=Fg(Ug(m));Au(t,m.status,"api_error",`${m.message} ${v}`);return}this._logService.error(`[${Kt}] upstream error: ${m instanceof Error?m.message:String(m)}`),Au(t,502,"api_error",m instanceof Error?m.message:String(m))}finally{t.removeListener("close",c),r.inFlight.delete(d)}}};Kl=R([C(0,M),C(1,Pt)],Kl);function V8(o,n){let e;try{e=JSON.parse(o)}catch{return{body:o}}let t=typeof e.model=="string"?e.model:void 0;if(!t)return{body:o};if(t!==$8)return n.lastPrimaryModel=t,{body:o};let r=n.lastPrimaryModel;return r?(e.model=r,{body:JSON.stringify(e),remappedFrom:t,remappedTo:r}):{body:o}}function j8(o){let n={},e=o["user-agent"];return typeof e=="string"&&e.length>0&&(n["User-Agent"]=K8(e)),n}function K8(o){let n=o.indexOf("/");return n===-1?`${S0}/${o}`:`${S0}${o.substring(n)}`}function Sr(o){let n=/^\s*\S*sh(?:\.exe)?\s+-[a-z]*c\s+([\s\S]+)$/i.exec(o);return n?G8(n[1].trim()):o}function G8(o){return o.length>=2&&o[0]==="'"&&o[o.length-1]==="'"?o.slice(1,-1).replace(/'\\''/g,"'"):o.length>=2&&o[0]==='"'&&o[o.length-1]==='"'?o.slice(1,-1).replace(/\\(["\\$`])/g,"$1"):o}function Ph(o=new Set,n=new hn){return{itemToPartId:new Map,itemToToolCall:new Map,itemToReasoningPartId:new Map,currentTurnId:void 0,clientToolSet:n,serverToolNames:o,mcpCustomizationIds:new Map,declinedToolCalls:new Set,pendingPreflight:void 0}}function WC(o){o.itemToPartId.clear(),o.itemToToolCall.clear(),o.itemToReasoningPartId.clear(),o.declinedToolCalls.clear(),o.pendingPreflight=void 0}function xh(o){let n=o.pendingPreflight;return n?(o.pendingPreflight=void 0,n.completion):[]}function qC(o){let n=[];for(let e of o)e.type==="text"&&n.push(e.text);return n.join(`

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

`)}function b0(o){return typeof o=="string"?o:JSON.stringify(o,null,2)}function C0(o){return JSON.stringify(o,null,2)}function _0(o){return o?.map(n=>n.type==="inputText"?n.text:n.imageUrl).join(`
`)??""}function J8(o,n){if(n)return n;if(!o)return"";let e=o.content.map(b0).join(`
`),t=o.structuredContent!==null?b0(o.structuredContent):"";return[e,t].filter(Boolean).join(`
`)}function T0(o){switch(o){case"spawnAgent":return{displayName:"Spawn agent",present:"Spawning agent",past:"Spawned agent"};case"sendInput":return{displayName:"Send input to agent",present:"Sending input to agent",past:"Sent input to agent"};case"resumeAgent":return{displayName:"Resume agent",present:"Resuming agent",past:"Resumed agent"};case"wait":return{displayName:"Wait for agents",present:"Waiting for agents",past:"Finished waiting"};case"closeAgent":return{displayName:"Close agent",present:"Closing agent",past:"Closed agent"};default:return{displayName:o,present:o,past:o}}}function I0(o){switch(o.status){case"completed":return o.message?`Completed \u2014 ${o.message}`:"Completed";case"errored":return o.message?`Errored \u2014 ${o.message}`:"Errored";case"running":return o.message?`Running \u2014 ${o.message}`:"Running";case"interrupted":return o.message?`Interrupted \u2014 ${o.message}`:"Interrupted";case"pendingInit":return"Pending init";case"shutdown":return"Shutdown";case"notFound":return"Not found";default:return o.status}}function Y8(o,n){let e=new Set,t=[];for(let r of o){let i=n[r];i&&(t.push(i),e.add(r))}for(let r of Object.keys(n).sort()){if(e.has(r))continue;let i=n[r];i&&t.push(i)}return t.length===0?"":t.length===1?I0(t[0]):t.map((r,i)=>`Agent ${i+1}: ${I0(r)}`).join(`
`)}function w0(o,n,e){o.currentTurnId=n.turn.id,WC(o);let t=e,r=n.turn.items?.[0];if(r&&r.type==="userMessage"){let i=qC(r.content);i.length>0&&(t=i)}return[{type:"chat/turnStarted",turnId:n.turn.id,message:{text:t,origin:{kind:"user"}}}]}function R0(o,n){return zC(o,n.turnId,BC(n.itemId,"summary",n.summaryIndex)).actions}function x0(o,n){let e=zC(o,n.turnId,BC(n.itemId,"summary",n.summaryIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function P0(o,n){let e=zC(o,n.turnId,BC(n.itemId,"text",n.contentIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function Q8(o,n){for(let e of[...o.itemToReasoningPartId.keys()])e.startsWith(`${n}:`)&&o.itemToReasoningPartId.delete(e)}function A0(o){let n=o.tokenUsage.last;return[{type:"chat/usage",turnId:o.turnId,usage:{inputTokens:n.inputTokens,outputTokens:n.outputTokens,cacheReadTokens:n.cachedInputTokens,_meta:{reasoningOutputTokens:n.reasoningOutputTokens,modelContextWindow:o.tokenUsage.modelContextWindow}}}]}function E0(o,n){if(n.item.type==="commandExecution"){let r=o.pendingPreflight;if(r&&r.turnId===n.turnId&&r.command===Sr(n.item.command??""))return o.pendingPreflight=void 0,o.itemToToolCall.set(n.item.id,{toolCallId:r.toolCallId,turnId:n.turnId,toolName:"shell",output:""}),[]}let e=xh(o),t=X8(o,n);return e.length===0?t:[...e,...t]}function X8(o,n){if(n.item.type==="agentMessage"){let e=O();return o.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=O();o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"shell",output:""});let t=Sr(n.item.command??"");return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"shell",displayName:"Run shell command",_meta:Rt({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:Rt({toolKind:"terminal"})}]}if(n.item.type==="webSearch"){let e=O();o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"web_search",output:""});let t=Ah(n.item.query,n.item.action);return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"web_search",displayName:"Web search",_meta:Rt({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:Rt({toolKind:"search"})}]}if(n.item.type==="fileChange"){let e=O(),t=Eu(n.item.changes);o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"file_edit",output:t});let r=Eh(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=O(),t=`${n.item.server}.${n.item.tool}`,r=C0(n.item.arguments),i=o.mcpCustomizationIds.get(n.item.server);return o.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,...i?{contributor:{kind:"mcp",customizationId:i}}:{}},{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=O(),t=n.item.namespace?`${n.item.namespace}.${n.item.tool}`:n.item.tool,r=C0(n.item.arguments),i=_0(n.item.contentItems),a=n.item.namespace===null&&o.serverToolNames.has(n.item.tool)?void 0:o.clientToolSet.ownerOf(n.item.tool),l=mr(n.item.tool,n.item.arguments);return o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:t,output:i}),[{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"},...i?[{type:"chat/toolCallContentChanged",turnId:n.turnId,toolCallId:e,content:[{type:"text",text:i}]}]:[]]}if(n.item.type==="collabAgentToolCall"){let e=O(),t=T0(n.item.tool),r=`codex.${n.item.tool}`;if(o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:r,output:""}),n.item.tool==="spawnAgent")return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:r,displayName:t.displayName},{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:t.present,confirmed:"not-needed"}];let i=[];n.item.prompt&&i.push(n.item.prompt),n.item.model&&i.push(`Model: ${n.item.model}`);let s=i.join(`

`);return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:r,displayName:t.displayName},...s?[{type:"chat/toolCallDelta",turnId:n.turnId,toolCallId:e,content:s}]:[],{type:"chat/toolCallReady",turnId:n.turnId,toolCallId:e,invocationMessage:t.present,toolInput:s,confirmed:"not-needed"}]}return[]}function k0(o,n){let e=o.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 D0(o,n){let e=o.itemToToolCall.get(n.itemId);return e?(e.output=Eu(n.changes),[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:e.output?[{type:"text",text:e.output}]:[]}]):[]}function M0(o,n){let e=o.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 O0(o,n){let e=o.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 L0(o,n){let e=o.itemToPartId.get(n.itemId);return e?[{type:"chat/delta",turnId:n.turnId,partId:e,content:n.delta}]:[]}function VC(o,n){if(n.item.type==="agentMessage")return o.itemToPartId.delete(n.item.id),[];if(n.item.type==="reasoning")return Q8(o,n.item.id),[];let e=o.itemToToolCall.get(n.item.id);if(!e)return[];o.itemToToolCall.delete(n.item.id);let t=o.declinedToolCalls.delete(e.toolCallId);if(n.item.type==="commandExecution"){let r=n.item.status==="completed"&&(n.item.exitCode===0||n.item.exitCode===null),i=n.item.aggregatedOutput??e.output,s=Sr(n.item.command??""),a=n.item.exitCode,l=r?`Ran \`${s}\``:a!==null?`Ran \`${s}\` (exit ${a})`:`Ran \`${s}\` (failed)`,d=[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:r,pastTenseMessage:l,content:i?[{type:"text",text:i}]:void 0,error:r?void 0:{message:a!==null?`Exit code ${a}`:"Command failed",...t?{code:"denied"}:{}}}}];if(r&&!i&&!t){let c=xh(o);return o.pendingPreflight={toolCallId:e.toolCallId,turnId:e.turnId,command:s,completion:d},c}return[...xh(o),...d]}if(n.item.type==="webSearch"){let r=Ah(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=Eu(n.item.changes)||e.output,i=n.item.status==="completed",s=r?[{type:"text",text:r}]:void 0,a={success:i,pastTenseMessage:i?"Applied file changes":"Failed to apply file changes",content:s,...i?{}:{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,i=J8(n.item.result,n.item.error?.message)||e.output,s=i?[{type:"text",text:i}]: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",i=_0(n.item.contentItems)||e.output,s=i?[{type:"text",text:i}]:void 0,a=r?mr(e.toolName,n.item.arguments,{text:i,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"}:{}}}}}]}if(n.item.type==="collabAgentToolCall"){let r=T0(n.item.tool),i=n.item.status==="completed",s=Y8(n.item.receiverThreadIds,n.item.agentsStates)||e.output,a=s?[{type:"text",text:s}]:void 0;return[{type:"chat/toolCallComplete",turnId:e.turnId,toolCallId:e.toolCallId,result:{success:i,pastTenseMessage:i?r.past:`${r.displayName} failed`,content:a,...i?{}:{error:{message:`Collab agent ${n.item.status}`,...t?{code:"denied"}:{}}}}}]}return[]}function N0(o,n){o.currentTurnId=void 0,o.itemToPartId.clear(),o.itemToReasoningPartId.clear();let e=xh(o),t=[...o.itemToToolCall.values()];o.itemToToolCall.clear();let r=n.turn.id,i=n.turn.status,s=t.map(a=>({type:"chat/toolCallComplete",turnId:a.turnId,toolCallId:a.toolCallId,result:{success:!1,pastTenseMessage:`Stopped ${a.toolName}`,content:a.output?[{type:"text",text:a.output}]:void 0,error:{message:i==="interrupted"?"Turn interrupted before the tool completed":"Turn completed before the tool reported completion"}}}));if(i==="failed"&&n.turn.error){let a=n.turn.error.message??"Codex turn failed";return[...e,...s,{type:"chat/error",turnId:r,error:{errorType:"CodexError",...Va(a)}},{type:"chat/turnComplete",turnId:r}]}return i==="interrupted"?[...e,...s,{type:"chat/turnCancelled",turnId:r}]:[...e,...s,{type:"chat/turnComplete",turnId:r}]}function U0(o){switch(o){case"completed":return"complete";case"interrupted":return"cancelled";case"failed":return"error";default:return"complete"}}function F0(o,n,e){let t=o.length,r=o.findIndex(s=>s===n);if(r===-1&&(r=e),t>0&&(r<0||r>=t))return{resolved:!1};let i=t>0?Math.max(0,t-(r+1)):0;return{resolved:!0,keepThroughIndex:r,numTurnsToDrop:i}}function H0(o,n,e,t,r){if(!r||r.size===0)return[];let i=Math.min(e+1,o.length,n.length),s=[];for(let a=0;a<i;a++){let l=o[a],d=t?.get(l)??l,c=r.get(d)??d;s.push([c,n[a]])}return s}import*as $0 from"crypto";import*as W0 from"fs";import*as q0 from"os";var Z8=[];function jC(o,n){let e=[],t=[],r=[o];if(n&&n.length>0)for(let s of n)switch(s.type){case"resource":{let a=h.parse(s.uri);a.scheme==="file"?r.push(`@${a.fsPath}`):r.push(a.toString());break}case"embeddedResource":{if(s.contentType.startsWith("image/")){let a=eH(s.contentType),l=j(q0.tmpdir(),`codex-img-${$0.randomBytes(8).toString("hex")}${a}`);try{W0.writeFileSync(l,Buffer.from(s.data,"base64")),e.push(l),t.push({type:"localImage",path:l})}catch{}break}if(tH(s.contentType)){let a=nH(s);a&&r.push(a);break}break}case"simple":{let a=s.modelRepresentation;typeof a=="string"&&a.length>0&&r.push(a);break}}let i=r.filter(s=>s.length>0).join(`

`);return t.unshift({type:"text",text:i,text_elements:Z8}),{input:t,cleanupPaths:e}}function eH(o){switch(o.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 tH(o){let n=o.toLowerCase().split(";",1)[0].trim();return n.startsWith("text/")?!0:n==="application/json"||n==="application/xml"||n==="application/javascript"||n==="application/typescript"||n.endsWith("+json")||n.endsWith("+xml")}function nH(o){let n;try{n=Buffer.from(o.data,"base64").toString("utf8")}catch{return}if(n.length===0)return;let e=o.label||"attachment",t=o.selection?.range,r=t?` (lines ${t.start.line+1}-${t.end.line+1})`:"";return`${e}${r}:
\`\`\`
${n}
\`\`\``}function B0(o,n){return{id:o,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 z0(o,n,e){let t={};for(let r of o)t[r.id]={answers:rH(e?.[r.id],n)};return{answers:t}}function KC(o){let n={};for(let e of o)n[e.id]={answers:[]};return{answers:n}}function rH(o,n){if(n!=="accept"||!o||o.state==="skipped")return[];let{value:e}=o;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 V0(o){let n=[];for(let e of o.turns??[]){let t=oH(e);t&&n.push(t)}return n}function oH(o){let n="",e=[],t,r=()=>{t&&(e.push(GC(t.item,t.command)),t=void 0)};for(let i of o.items??[]){if(i.type==="commandExecution"){let s=Sr(i.command??"");if(t&&t.command===s){t=void 0,e.push(GC(i,s));continue}r();let a=i.status==="completed"&&(i.exitCode===0||i.exitCode===null),l=i.aggregatedOutput??"";if(a&&!l){t={command:s,item:i};continue}e.push(GC(i,s));continue}if(r(),i.type==="userMessage"){let s=[];for(let a of i.content)a.type==="text"&&s.push(a.text);s.length>0&&(n=s.join(`

`))}else i.type==="agentMessage"?i.text&&i.text.length>0&&e.push({kind:"markdown",id:O(),content:i.text}):i.type==="webSearch"?e.push(iH(i)):i.type==="fileChange"&&e.push(sH(i))}if(r(),!(!n&&e.length===0))return{id:o.id,message:{text:n,origin:{kind:"user"}},responseParts:e,usage:void 0,state:U0(o.status)}}function j0(o){return o?[{type:"text",text:o}]:void 0}function GC(o,n){let e=o.status==="completed"&&(o.exitCode===0||o.exitCode===null),t=o.aggregatedOutput??"",r=o.exitCode,i=e?`Ran \`${n}\``:r!==null?`Ran \`${n}\` (exit ${r})`:`Ran \`${n}\` (failed)`;return{kind:"toolCall",toolCall:{status:"completed",toolCallId:O(),toolName:"shell",displayName:"Run shell command",_meta:Rt({toolKind:"terminal"}),invocationMessage:n,toolInput:n,confirmed:"not-needed",success:e,pastTenseMessage:i,content:j0(t),error:e?void 0:{message:r!==null?`Exit code ${r}`:"Command failed"}}}}function iH(o){let n=Ah(o.query,o.action);return{kind:"toolCall",toolCall:{status:"completed",toolCallId:O(),toolName:"web_search",displayName:"Web search",_meta:Rt({toolKind:"search"}),invocationMessage:n,toolInput:n,confirmed:"not-needed",success:!0,pastTenseMessage:`Searched ${n}`}}}function sH(o){let n=o.status==="completed",e=Eh(o.changes)||"Apply file changes",t=Eu(o.changes);return{kind:"toolCall",toolCall:{status:"completed",toolCallId:O(),toolName:"file_edit",displayName:"Apply file changes",invocationMessage:e,confirmed:"not-needed",success:n,pastTenseMessage:n?"Applied file changes":"Failed to apply file changes",content:j0(t),error:n?void 0:{message:`Patch ${o.status}`}}}}var Dn=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 i=[];e.threadId!==void 0&&i.push(r.setMetadata(Dn.KEY_THREAD_ID,e.threadId)),e.cwd!==void 0&&i.push(r.setMetadata(Dn.KEY_CWD,e.cwd.toString())),e.modelId!==void 0&&i.push(r.setMetadata(Dn.KEY_MODEL,e.modelId)),await Promise.all(i)}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,i]=await Promise.all([e.object.getMetadata(Dn.KEY_THREAD_ID),e.object.getMetadata(Dn.KEY_CWD),e.object.getMetadata(Dn.KEY_MODEL)]);return{threadId:t??void 0,cwd:r?h.parse(r):void 0,modelId:i??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)}`),{}}}};Dn=R([C(0,rt),C(1,M)],Dn);var kh=["default","auto-review","full-access"],Jl="default";function Dh(o){switch(o){case"default":case"auto-review":case"full-access":return o;default:return}}function Mh(o){switch(o){case"auto-review":return{approvalPolicy:"on-request",sandboxMode:"workspace-write",approvalsReviewer:"auto_review"};case"full-access":return{approvalPolicy:"never",sandboxMode:"danger-full-access",approvalsReviewer:"user"};default:return{approvalPolicy:"on-request",sandboxMode:"workspace-write",approvalsReviewer:"user"}}}function JC(o){for(let n of kh){let e=Mh(n);if(e.approvalPolicy===o.approvalPolicy&&e.sandboxMode===o.sandboxMode&&e.approvalsReviewer===o.approvalsReviewer)return n}}function aH(o){switch(o){case"never":case"on-request":case"on-failure":case"untrusted":return o;default:return}}function lH(o){switch(o){case"read-only":case"workspace-write":case"danger-full-access":return o;default:return}}function Oh(o,n){let e=Dh(o?.["codex.permissionsPreset"]);return e?Mh(e):{approvalPolicy:aH(o?.["codex.approvalPolicy"])??n.approvalPolicy,sandboxMode:lH(o?.["codex.sandboxMode"])??n.sandboxMode,approvalsReviewer:"user"}}function Lh(o,n){let e=Dh(o?.["codex.permissionsPreset"]);if(e)return{"codex.permissionsPreset":e};let t=Oh(o,n),r=JC(t);return r?{"codex.permissionsPreset":r}:t.sandboxMode==="read-only"?{"codex.approvalPolicy":t.approvalPolicy,"codex.sandboxMode":t.sandboxMode}:{"codex.permissionsPreset":t.sandboxMode==="danger-full-access"?"full-access":Jl}}function G0(o){if(Array.isArray(o))return o.filter(n=>typeof n=="string"&&n.length>0)}function J0(o){return typeof o=="boolean"?o:void 0}function Y0(o){switch(o){case"disabled":case"cached":case"live":return o;default:return}}function YC(o){switch(o){case"none":case"minimal":case"low":case"medium":case"high":case"xhigh":return o;default:return}}function Q0(o){switch(o){case"none":case"friendly":case"pragmatic":return o;default:return}}function X0(o){switch(o){case"auto":case"concise":case"detailed":case"none":return o;default:return}}function Z0(o){return o==="plan"?"plan":"default"}function dH(o){switch(o){case"inProgress":return"in_progress";case"timedOut":return"timed_out";default:return o}}function ek(o){return o==="unifiedExec"?"unified_exec":o}function cH(o){switch(o){case"socks5Tcp":return"socks5_tcp";case"socks5Udp":return"socks5_udp";default:return o}}function uH(o){let n=o.fileSystem,e=null;if(n){let t={read:n.read,write:n.write};n.globScanMaxDepth!==void 0&&(t.glob_scan_max_depth=n.globScanMaxDepth),n.entries!==void 0&&(t.entries=n.entries),e=t}return{network:o.network,file_system:e}}function pH(o){switch(o.type){case"command":return{type:"command",source:ek(o.source),command:o.command,cwd:o.cwd};case"execve":return{type:"execve",source:ek(o.source),program:o.program,argv:o.argv,cwd:o.cwd};case"applyPatch":return{type:"apply_patch",cwd:o.cwd,files:o.files};case"networkAccess":return{type:"network_access",target:o.target,host:o.host,protocol:cH(o.protocol),port:o.port};case"mcpToolCall":return{type:"mcp_tool_call",server:o.server,tool_name:o.toolName,connector_id:o.connectorId,connector_name:o.connectorName,tool_title:o.toolTitle};case"requestPermissions":return{type:"request_permissions",reason:o.reason,permissions:uH(o.permissions)}}}function tk(o){let n={id:o.reviewId,turn_id:o.turnId,started_at_ms:o.startedAtMs,status:dH(o.review.status),action:pH(o.action)};return o.targetItemId!==null&&(n.target_item_id=o.targetItemId),o.completedAtMs!==null&&o.completedAtMs!==void 0&&(n.completed_at_ms=o.completedAtMs),o.review.riskLevel!==null&&(n.risk_level=o.review.riskLevel),o.review.userAuthorization!==null&&(n.user_authorization=o.review.userAuthorization),o.review.rationale!==null&&(n.rationale=o.review.rationale),o.decisionSource!==null&&o.decisionSource!==void 0&&(n.decision_source=o.decisionSource),n}function nk(o){switch(o.type){case"command":return{title:"Run command",detail:Sr(o.command),toolKind:"terminal"};case"execve":return{title:"Run program",detail:Sr([o.program,...o.argv].join(" ")),toolKind:"terminal"};case"applyPatch":return{title:"Apply file changes",detail:o.files.join(", ")};case"networkAccess":return{title:"Network access",detail:o.target||`${o.protocol}://${o.host}:${o.port}`,toolKind:"search"};case"mcpToolCall":return{title:"MCP tool call",detail:`${o.server}/${o.toolName}`};case"requestPermissions":return{title:"Elevated permissions",detail:o.reason??"Requested additional permissions"}}}function fH(o){let n=(o.match(/`+/g)??[]).reduce((r,i)=>Math.max(r,i.length),0),e="`".repeat(n+1),t=o.startsWith("`")||o.endsWith("`")?" ":"";return`${e}${t}${o}${t}${e}`}function rk(o,n){let e=o.detail?.trim(),t="**Auto-review denied**",r=[e?`\u26A0\uFE0F ${t} \u2014 ${o.title}: ${fH(e)}`:`\u26A0\uFE0F ${t} \u2014 ${o.title}`],i=n?.trim();return i&&r.push("",...i.split(`
`)),`

${r.map(a=>a?`> ${a}`:">").join(`
`)}
`}var mH={name:"vscode_agent_host",title:"VS Code Agent Host",version:"0.1.0"},ok="thinkingLevel",hH="vscode_codex",Ql=["minimal","low","medium","high"],yH={serverTools:{listChanged:!0},serverResources:{}},ik="mcp_tool_call_approval_",vH="Allow",SH="__codex_mcp_decline__",bH="/responses";function CH(){let o=Yt.definition.mode.protocol,n=(o.enum??[]).flatMap((e,t)=>e==="autopilot"?[]:[t]);return ce({...o,enum:n.map(e=>o.enum[e]),enumLabels:o.enumLabels&&n.map(e=>o.enumLabels[e]),enumDescriptions:o.enumDescriptions&&n.map(e=>o.enumDescriptions[e])})}var Nh=nn({"codex.permissionsPreset":ce({type:"string",title:f(2158,null),description:f(2165,null),enum:[...kh],enumLabels:[f(2161,null),f(2159,null),f(2163,null)],enumDescriptions:[f(2162,null),f(2160,null),f(2164,null)],default:Jl,sessionMutable:!0}),"codex.approvalPolicy":ce({type:"string",title:f(2144,null),description:f(2153,null),enum:["never","on-request","on-failure","untrusted"],enumLabels:[f(2145,null),f(2149,null),f(2147,null),f(2151,null)],enumDescriptions:[f(2146,null),f(2150,null),f(2148,null),f(2152,null)],default:"on-request",sessionMutable:!0}),"codex.sandboxMode":ce({type:"string",title:f(2180,null),description:f(2187,null),enum:["read-only","workspace-write","danger-full-access"],enumLabels:[f(2183,null),f(2185,null),f(2181,null)],enumDescriptions:[f(2184,null),f(2186,null),f(2182,null)],default:"workspace-write",sessionMutable:!0}),"codex.webSearchMode":ce({type:"string",title:f(2188,null),description:f(2192,null),enum:["disabled","cached","live"],enumLabels:[f(2190,null),f(2189,null),f(2191,null)],default:"disabled",sessionMutable:!1}),"codex.modelReasoningEffort":ce({type:"string",title:f(2154,null),description:f(2155,null),enum:[...Ql],enumLabels:Ql.map(ms),enumDescriptions:Ql.map(o=>hs(o)??""),default:"medium",sessionMutable:!0}),mode:CH(),"codex.personality":ce({type:"string",title:f(2166,null),description:f(2173,null),enum:["none","friendly","pragmatic"],enumLabels:[f(2169,null),f(2167,null),f(2171,null)],enumDescriptions:[f(2170,null),f(2168,null),f(2172,null)],default:"none",sessionMutable:!0}),"codex.reasoningSummary":ce({type:"string",title:f(2174,null),description:f(2179,null),enum:["auto","concise","detailed","none"],enumLabels:[f(2175,null),f(2176,null),f(2177,null),f(2178,null)],default:"auto",sessionMutable:!0}),"codex.additionalDirectories":ce({type:"array",title:f(2141,null),description:f(2143,null),items:{type:"string",title:f(2142,null)},enumDynamic:!0,default:[],sessionMutable:!0}),"codex.networkAccessEnabled":ce({type:"boolean",title:f(2156,null),description:f(2157,null),default:!1,sessionMutable:!0}),permissions:Yt.definition.permissions}),IH=nn({mode:Nh.definition.mode,"codex.permissionsPreset":Nh.definition["codex.permissionsPreset"],permissions:Yt.definition.permissions}),Mn={"codex.permissionsPreset":Jl,"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"},_H=6e4,_s={id:"codex",displayName:"Codex",devOverrideEnvVar:ew,hasSeparateMuslLinuxPackage:!1};function TH(o){let n=[];for(let e of o.content??[])e.type==="text"&&n.push({type:"inputText",text:e.text});if(n.length===0){let e=typeof o.pastTenseMessage=="string"&&o.pastTenseMessage.length>0?o.pastTenseMessage:o.success?"Tool completed with no output.":"Tool failed with no output.";n.push({type:"inputText",text:e})}return{contentItems:n,success:o.success}}function sk(o){return!o||o.length===0?"":o.map(n=>`${n.name}\0${n.description??""}\0${JSON.stringify(n.inputSchema??null)}`).sort().join("")}var QC=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 wH(o){switch(o){case"accept":case"acceptForSession":case"decline":case"cancel":return o;default:return"decline"}}var Yl=class extends w{constructor(e,t,r,i,s,a,l,d){super();this._logService=e;this._copilotApiService=t;this._codexProxyService=r;this._configurationService=i;this._gitHubEndpointService=s;this._agentSdkDownloader=a;this._productService=l;this.id=iw;this._onDidSessionProgress=this._register(new A);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new A);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new A);this.onMcpNotification=this._onMcpNotification.event;this._models=rn(this,[]);this.models=this._models;this._sessions=new Map;this._sessionIdByThreadId=new Map;this._subagentsByThreadId=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,i,s)=>this._sendMessage(e,t,r,i),abort:e=>this._abort(e),changeModel:(e,t)=>this._changeModel(e,t),changeAgent:(e,t)=>Promise.resolve(),getMessages:e=>this.getSessionMessages(e)};this._metadataStore=d.createInstance(Dn)}getProtectedResources(){return[this._gitHubEndpointService.getCopilotResource(),this._gitHubEndpointService.getRepoResource()]}async authenticate(e,t){if(e===this._gitHubEndpointService.getRepoResource().resource)return!0;if(e!==this._gitHubEndpointService.getCopilotResource().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 L(cr,"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:{[ok]:{type:"string",title:f(2140,null),description:f(2139,null),default:"medium",enum:[...Ql],enumLabels:Ql.map(ms),enumDescriptions:Ql.map(e=>hs(e)??"")}}}}_getReasoningEffort(e){let t=YC(e.model?.config?.[ok]);if(t)return t;let r=this._configurationService.getSessionConfigValues(e.sessionUri.toString());return YC(r?.["codex.modelReasoningEffort"])??Mn["codex.modelReasoningEffort"]}_readSessionConfig(e){return Nh.validateOrDefault(this._configurationService.getSessionConfigValues(e.sessionUri.toString()),Mn)}_resolveSessionPermissions(e){let t=this._configurationService.getSessionConfigValues(e.sessionUri.toString()),r={approvalPolicy:Mn["codex.approvalPolicy"],sandboxMode:Mn["codex.sandboxMode"]};return Oh(Lh(t,r),r)}_sandboxPolicy(e,t,r){if(r==="danger-full-access")return{type:"dangerFullAccess"};let i=J0(t["codex.networkAccessEnabled"])??Mn["codex.networkAccessEnabled"];return r==="read-only"?{type:"readOnly",networkAccess:!1}:{type:"workspaceWrite",writableRoots:[...e.workingDirectory?[e.workingDirectory.fsPath]:[],...G0(t["codex.additionalDirectories"])??[]],networkAccess:i,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}_turnStartOptions(e,t){let r=this._readSessionConfig(e),{approvalPolicy:i,sandboxMode:s,approvalsReviewer:a}=this._resolveSessionPermissions(e),l=this._sandboxPolicy(e,r,s),d=l.type==="workspaceWrite"?l.writableRoots:void 0,c=this._getReasoningEffort(e),u=Q0(r["codex.personality"])??Mn["codex.personality"],p=X0(r["codex.reasoningSummary"])??Mn["codex.reasoningSummary"],v={mode:Z0(r.mode),settings:{model:t,reasoning_effort:c??null,developer_instructions:null}};return{approvalPolicy:i,sandboxPolicy:l,approvalsReviewer:a,effort:c,personality:u,summary:p,collaborationMode:v,...d?{runtimeWorkspaceRoots:d}:{}}}async _refreshModels(e){try{let t=`${hH}/${this._productService.version}`,r=await this._copilotApiService.models(e,{headers:{"User-Agent":t},suppressIntegrationId:!0});if(this._githubToken!==e)return;let i=this._createReasoningEffortConfigSchema(),s=r.filter(a=>a.supported_endpoints?.includes(bH)).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:i,policyState:a.policy?.state,_meta:yl(Tm(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(_s))return this._agentSdkDownloader.loadSdkRoot(_s,Re.None);let e=await AH();return e?(this._logService.info(`[Codex] resolving SDK from repo node_modules (dev fallback): ${e}`),e):this._agentSdkDownloader.loadSdkRoot(_s,Re.None)}async _startConnection(e){let t=await this._resolveSdkRoot(),r=xH(process.platform,process.arch);if(!r)throw new Error(`Codex: unsupported platform ${process.platform}-${process.arch}`);let i=PH(r);if(!i)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",i,"bin",s);try{jr.accessSync(a,jr.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[tw];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=RH(process.env[nw]),m=["app-server",...u.flatMap(b=>["-c",b]),...p];this._logService.info(`[Codex] spawning ${a} ${m.join(" ")}`);let v=gH(a,m,{env:d,stdio:["pipe","pipe","pipe"]});v.stderr.setEncoding("utf8"),v.stderr.on("data",b=>this._logService.info(`[Codex stderr] ${String(b).trimEnd()}`));let y=v0(v),S=new wh(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:mH,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{v.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=>L0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/commandExecution/outputDelta",b=>this._dispatchByThread(b.threadId,I=>k0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/fileChange/patchUpdated",b=>this._dispatchByThread(b.threadId,I=>D0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/fileChange/outputDelta",b=>this._dispatchByThread(b.threadId,I=>M0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/mcpToolCall/progress",b=>this._dispatchByThread(b.threadId,I=>O0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/summaryPartAdded",b=>this._dispatchByThread(b.threadId,I=>R0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/summaryTextDelta",b=>this._dispatchByThread(b.threadId,I=>x0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("item/reasoning/textDelta",b=>this._dispatchByThread(b.threadId,I=>P0(I.mapState,this._withHostTurnId(I,b))))),this._register(S.onNotification("thread/tokenUsage/updated",b=>this._dispatchByThread(b.threadId,I=>A0(this._withHostTurnId(I,b))))),this._register(S.onNotification("item/completed",b=>this._dispatchItemCompleted(b))),this._register(S.onNotification("turn/completed",b=>this._dispatchTurnCompleted(b))),this._register(S.onNotification("guardianWarning",b=>this._dispatchByThread(b.threadId,I=>this._handleGuardianWarning(I,b)))),this._register(S.onNotification("item/autoApprovalReview/completed",b=>{this._handleGuardianReviewCompleted(S,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:v}}_buildDynamicTools(e){let t=this._serverToolHost?.definitions??[],r=e.clientToolSet.merged(),i=new Set,s=[];for(let a of[...t,...r])i.has(a.name)||(i.add(a.name),s.push(a));if(s.length!==0)return s.map(a=>({type:"function",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 i=this._serverToolHost;if(i&&e.namespace===null&&i.toolNames.includes(e.tool))try{return{result:{contentItems:[{type:"inputText",text:await i.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:TH(a)}}catch(a){return a instanceof K?{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:KC(e.questions)};let i=e.questions.length===1&&e.questions[0].id.startsWith(ik)?e.questions[0]:void 0;if(i){let l=i.id.slice(ik.length),d=r.mapState.itemToToolCall.get(l);if(d)return this._handleMcpToolApprovalViaCard(r,i,d)}let s=O(),a=B0(s,e.questions);try{let l=await r.pendingUserInputs.registerAndFire(s,()=>{this._fire(r.sessionUri,{type:"chat/inputRequested",request:a})});return{result:z0(e.questions,l.response,l.answers)}}catch{return{result:KC(e.questions)}}}async _handleMcpToolApprovalViaCard(e,t,r){let i=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:i,toolInput:i,confirmationTitle:i})})}catch{s="decline"}let l=s==="accept"||s==="acceptForSession"?vH:SH;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:h0()};let i=O(),s=g0(i,e);try{let a=await r.pendingUserInputs.registerAndFire(i,()=>{this._fire(r.sessionUri,{type:"chat/inputRequested",request:s})});return this._logService.info(`[Codex] elicitation resolved requestId=${i} response=${a.response}`),{result:m0(e,a.response,a.answers)}}catch(a){return this._logService.info(`[Codex] elicitation cancelled requestId=${i}: ${a instanceof Error?a.message:String(a)}`),{result:y0()}}}_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,i=e.currentTurnId??this._hostTurnId(e,r);return e.hostTurnIdByAppTurnId.set(r,i),e.currentAppTurnId=r,i===r?t:{...t,turn:{...t.turn,id:i}}}_handleTurnStartedNotification(e,t){return w0(e.mapState,this._withHostTurn(e,t),e.lastPromptText),[]}_handleTurnCompletedNotification(e,t){let r=t.turn.id,i=this._hostTurnId(e,r),s=N0(e.mapState,this._withHostTurn(e,t));if(e.codexTurnIdByHostTurnId.set(i,r),(e.currentAppTurnId===r||e.currentTurnId===i)&&(e.currentTurnId=void 0,e.currentAppTurnId=void 0),e.hostTurnIdByAppTurnId.delete(r),this._drainPendingSteering(e),e.pendingGuardianReviewCards.size>0)for(let a of[...e.pendingGuardianReviewCards])e.pendingCommandApprovals.respond(a,"cancel");return s}_handleItemStarted(e,t){return t.item.type==="userMessage"?this._handleSteeredUserMessage(e,t.item.content):E0(e.mapState,this._withHostTurnId(e,t))}_handleSteeredUserMessage(e,t){let r=qC(t),i=this._takeMatchingPendingSteering(e,r);return i?this._beginSteeringTurn(e,i):[]}_takeMatchingPendingSteering(e,t){for(let[r,i]of e.pendingSteeringFlips)if(i.message.text===t)return e.pendingSteeringFlips.delete(r),i}_beginSteeringTurn(e,t){let r=[],i=e.currentAppTurnId,s=e.currentTurnId??(i?this._hostTurnId(e,i):void 0);s&&r.push({type:"chat/turnComplete",turnId:s});let a=O();return i&&e.hostTurnIdByAppTurnId.set(i,a),e.currentTurnId=a,WC(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:h.parse(pe(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","item/autoApprovalReview/started"];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",i=t.account?.type==="chatgpt"?t.account.planType:void 0;this._logService.info(`[Codex] account/read accountType=${r} requiresOpenaiAuth=${t.requiresOpenaiAuth}${i?` planType=${i}`:""}`)}catch(t){this._logService.warn(`[Codex] account/read failed: ${t instanceof Error?t.message:String(t)}`)}}_dispatchByThread(e,t){let r=this._subagentsByThreadId.get(e);if(r){let l=t(r.session);for(let d of l)this._fireSubagent(r,d);return}let i=this._sessionIdByThreadId.get(e),s=i?this._sessions.get(i):void 0;if(!s){this._logService.trace(`[Codex] Ignoring notification for untracked threadId=${e}; likely unclaimed prewarm`);return}let a=t(s);for(let l of a)this._fire(s.sessionUri,l)}_dispatchItemCompleted(e){let t=this._subagentsByThreadId.get(e.threadId);if(t){let a=VC(t.session.mapState,this._withHostTurnId(t.session,e));for(let l of a)this._fireSubagent(t,l);return}let r=this._sessionIdByThreadId.get(e.threadId),i=r?this._sessions.get(r):void 0;if(!i){this._logService.trace(`[Codex] Ignoring item/completed for untracked threadId=${e.threadId}; likely unclaimed prewarm`);return}this._maybeRegisterSubagents(i,e);let s=VC(i.mapState,this._withHostTurnId(i,e));for(let a of s)this._fire(i.sessionUri,a)}_dispatchTurnCompleted(e){let t=this._subagentsByThreadId.get(e.threadId);if(t){let r=this._handleTurnCompletedNotification(t.session,e);for(let i of r)i.type!=="chat/turnComplete"&&this._fireSubagent(t,i);this._subagentsByThreadId.delete(e.threadId),t.session.pendingCommandApprovals.denyAll("decline"),this._onDidSessionProgress.fire({kind:"subagent_completed",chat:h.parse(pe(t.session.sessionUri)),toolCallId:t.toolCallId});return}this._dispatchByThread(e.threadId,r=>this._handleTurnCompletedNotification(r,e))}_maybeRegisterSubagents(e,t){let r=t.item;if(r.type!=="collabAgentToolCall"||r.tool!=="spawnAgent")return;let i=e.mapState.itemToToolCall.get(r.id);if(!i)return;let s=h.parse(pe(e.sessionUri)),a=r.model||void 0,l=r.prompt||void 0;for(let d of r.receiverThreadIds){if(this._subagentsByThreadId.has(d))continue;let c=this._createSubagentSession(e,d);this._subagentsByThreadId.set(d,{parentSessionId:e.sessionId,toolCallId:i.toolCallId,session:c}),this._onDidSessionProgress.fire({kind:"subagent_started",chat:s,toolCallId:i.toolCallId,agentName:a??"codex",agentDisplayName:a??"Subagent",taskDescription:l}),this._logService.trace(`[Codex:${e.sessionId}] subagent spawned thread=${d} toolCall=${i.toolCallId} model=${a??"(default)"}`)}}_createSubagentSession(e,t){let r=new hn;return{sessionId:e.sessionId,threadId:t,sessionUri:e.sessionUri,workingDirectory:e.workingDirectory,managedWorkingDirectory:void 0,mapState:Ph(new Set(this._serverToolHost?.toolNames??[]),r),pendingCommandApprovals:new mt,acceptedForSession:e.acceptedForSession,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:r,pendingClientToolCalls:new mt,pendingUserInputs:new mt,materializedToolsSig:void 0,firstTurnSent:!0,model:e.model,currentTurnId:void 0,currentAppTurnId:void 0,hostTurnIdByAppTurnId:new Map,codexTurnIdByHostTurnId:new Map,needsResume:!1,lastPromptText:"",disposed:!1,materializePromise:void 0,materializedEventFired:!0,prewarmTimer:void 0,prewarmClaimed:!0,serverToolsAdvertised:!0,mcpController:void 0}}_fireSubagent(e,t){this._onDidSessionProgress.fire({kind:"action",resource:h.parse(pe(e.session.sessionUri)),action:t,parentToolCallId:e.toolCallId})}async _handleCommandApprovalRequestRpc(e){return{result:{decision:await this._handleCommandApprovalRequest(e)}}}async _handleCommandApprovalRequest(e){let t=this._resolveApprovalTarget(e.threadId);if(!t)return this._logService.warn(`[Codex] commandExecution/requestApproval for unknown threadId=${e.threadId}; declining`),"decline";let r=t.session,i=r.mapState.itemToToolCall.get(e.itemId);if(!i)return this._logService.warn(`[Codex:${r.sessionId}] commandExecution/requestApproval for unknown itemId=${e.itemId}; declining`),"decline";let s=e.command??"",a=Sr(s);if(s&&r.acceptedForSession.has(s))return"acceptForSession";let l=e.reason??"Run shell command",d=await r.pendingCommandApprovals.registerAndFire(i.toolCallId,()=>{this._fireApproval(t,{type:"chat/toolCallReady",turnId:i.turnId,toolCallId:i.toolCallId,invocationMessage:a,toolInput:a,confirmationTitle:l})});return d==="acceptForSession"&&s&&r.acceptedForSession.add(s),d}async _handleFileChangeApprovalRequestRpc(e){let t=await this._requestItemApproval(e.threadId,e.itemId,e.reason??"Apply file changes");return{result:{decision:wH(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 i=this._resolveApprovalTarget(e);if(!i)return this._logService.warn(`[Codex] approval request for unknown threadId=${e}; declining`),"decline";let s=i.session,a=s.mapState.itemToToolCall.get(t);return a?s.pendingCommandApprovals.registerAndFire(a.toolCallId,()=>{this._fireApproval(i,{type:"chat/toolCallReady",turnId:a.turnId,toolCallId:a.toolCallId,invocationMessage:r,toolInput:r,confirmationTitle:r})}):(this._logService.warn(`[Codex:${s.sessionId}] approval request for unknown itemId=${t}; declining`),"decline")}_resolveApprovalTarget(e){let t=this._subagentsByThreadId.get(e);if(t)return{session:t.session,subagent:t};let r=this._sessionIdByThreadId.get(e),i=r?this._sessions.get(r):void 0;return i?{session:i}:void 0}_fireApproval(e,t){e.subagent?this._fireSubagent(e.subagent,t):this._fire(e.session.sessionUri,t)}_handleGuardianWarning(e,t){let r=e.currentTurnId;return r===void 0?(this._logService.trace(`[Codex:${e.sessionId}] guardianWarning without active turn; ignoring`),[]):[{type:"chat/responsePart",turnId:r,part:{kind:"systemNotification",content:t.message}}]}async _handleGuardianReviewCompleted(e,t){let r=this._sessionIdByThreadId.get(t.threadId),i=r?this._sessions.get(r):void 0;if(!i){this._logService.trace(`[Codex] autoApprovalReview/completed for unknown threadId=${t.threadId}; ignoring`);return}if(t.review.status!=="denied"||i.handledGuardianReviews.has(t.reviewId))return;let s=this._hostTurnId(i,t.turnId);if(i.currentTurnId!==s){this._logService.trace(`[Codex:${r}] autoApprovalReview/completed for non-current turn ${s} (current=${i.currentTurnId??"(none)"}); ignoring reviewId=${t.reviewId}`);return}i.handledGuardianReviews.add(t.reviewId);let a=nk(t.action);this._fire(i.sessionUri,{type:"chat/responsePart",turnId:s,part:{kind:"markdown",id:O(),content:rk(a,t.review.rationale)}});let l=O(),d=a.detail||a.title,c="Approve anyway";i.pendingGuardianReviewCards.add(l);let u;try{u=await i.pendingCommandApprovals.registerAndFire(l,()=>{this._fire(i.sessionUri,{type:"chat/toolCallStart",turnId:s,toolCallId:l,toolName:"auto_review_denied",displayName:a.title,intention:d}),this._fire(i.sessionUri,{type:"chat/toolCallReady",turnId:s,toolCallId:l,invocationMessage:d,confirmationTitle:c})})}catch(p){this._logService.trace(`[Codex:${r}] guardian approval cancelled for reviewId=${t.reviewId}: ${p instanceof Error?p.message:String(p)}`);return}finally{i.pendingGuardianReviewCards.delete(l)}if(!(u!=="accept"&&u!=="acceptForSession")){if(i.currentTurnId!==s){this._logService.trace(`[Codex:${r}] turn ended before guardian approval could be applied for reviewId=${t.reviewId}`);return}try{await e.request("thread/approveGuardianDeniedAction",{threadId:t.threadId,event:tk(t)}),this._fire(i.sessionUri,{type:"chat/toolCallComplete",turnId:s,toolCallId:l,result:{success:!0,pastTenseMessage:"Approved anyway"}})}catch(p){let m=p instanceof Error?p.message:String(p);this._logService.warn(`[Codex:${r}] approveGuardianDeniedAction failed for reviewId=${t.reviewId}: ${m}`),this._fire(i.sessionUri,{type:"chat/toolCallComplete",turnId:s,toolCallId:l,result:{success:!1,pastTenseMessage:"Approval failed",error:{message:m}}})}}}_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 K),t.pendingUserInputs.rejectAll(new K),this._drainPendingSteering(t);let r=t.currentTurnId,i=t.currentAppTurnId;t.currentTurnId=void 0,t.currentAppTurnId=void 0,i&&t.hostTurnIdByAppTurnId.delete(i),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(2194,null),description:f(2193,null)}}_sessionUriFromChat(e){let t=ke(e);return t?h.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)return this._forkSession(e,e.fork);let t=this._supportedModelOrUndefined(e.model),r=e.session?D.id(e.session):O(),i=e.session??D.uri(this.id,r),s=this._sessions.get(r);if(s)return s.model=t??s.model,{session:i,workingDirectory:s.workingDirectory??e.workingDirectory,provisional:s.threadId===void 0};let a=new hn,l={sessionId:r,threadId:void 0,sessionUri:i,workingDirectory:e.workingDirectory,managedWorkingDirectory:void 0,mapState:Ph(new Set(this._serverToolHost?.toolNames??[]),a),pendingCommandApprovals:new mt,acceptedForSession:new Set,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:a,pendingClientToolCalls:new mt,pendingUserInputs:new mt,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:i,workingDirectory:e.workingDirectory,provisional:!0}}_createResumedSessionEntry(e,t,r,i,s){let a=new hn;return{sessionId:e,threadId:t,sessionUri:r,workingDirectory:i,managedWorkingDirectory:void 0,mapState:Ph(new Set(this._serverToolHost?.toolNames??[]),a),pendingCommandApprovals:new mt,acceptedForSession:new Set,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:a,pendingClientToolCalls:new mt,pendingUserInputs:new mt,materializedToolsSig:void 0,firstTurnSent:!0,model:s,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}}async _forkSession(e,t){let r=await this._readSession(t.session);if(!r)throw new Error(`Cannot fork codex session ${t.session.toString()}: source thread could not be read`);let i=r.thread.id,s=r.thread.turns??[],a=this._sessions.get(D.id(t.session)),l=a?.codexTurnIdByHostTurnId.get(t.turnId)??t.turnId,d=F0(s.map(x=>x.id),l,t.turnIndex);if(!d.resolved)throw new Error(`Cannot fork codex session ${i}: unable to resolve fork boundary for turn ${t.turnId} (turnIndex=${t.turnIndex}, turns=${s.length})`);let{keepThroughIndex:c,numTurnsToDrop:u}=d,p=await this._ensureConnection(),m=this._supportedModelOrUndefined(e.model),v=this._configurationService.getSessionConfigValues(t.session.toString()),y={approvalPolicy:Mn["codex.approvalPolicy"],sandboxMode:Mn["codex.sandboxMode"]},{approvalPolicy:S,sandboxMode:b,approvalsReviewer:I}=Oh(Lh({...v,...e.config},y),y),_=await p.client.request("thread/fork",{threadId:i,...m?{model:m.id}:{},approvalPolicy:S,sandbox:b,approvalsReviewer:I}),T=_.thread.id;if(u>0)try{await p.client.request("thread/rollback",{threadId:T,numTurns:u})}catch(x){let E=x instanceof Error?x.message:String(x);this._logService.warn(`[Codex:${T}] fork rollback failed (numTurns=${u}); discarding fork: ${E}`);try{await p.client.request("thread/archive",{threadId:T})}catch(H){this._logService.warn(`[Codex:${T}] failed to archive orphaned fork after rollback failure: ${H instanceof Error?H.message:String(H)}`)}throw new Error(`Failed to fork codex session ${i}: could not roll back forked thread ${T} to the requested turn (${E})`)}let P=D.uri(this.id,T),X=_.cwd?h.file(_.cwd):r.thread.cwd?h.file(r.thread.cwd):e.workingDirectory,k=this._createResumedSessionEntry(T,T,P,X,m);if(this._sessions.set(T,k),this._sessionIdByThreadId.set(T,T),!k.serverToolsAdvertised&&this._serverToolHost&&(k.serverToolsAdvertised=!0,this._serverToolHost.advertise(k.sessionUri.toString())),this._persistMaterializedSession(k),t.turnIdMapping&&t.turnIdMapping.size>0)try{let E=(await this._readSession(P))?.thread.turns??[],H=H0(s.map(G=>G.id),E.map(G=>G.id),c,a?.hostTurnIdByAppTurnId,t.turnIdMapping);for(let[G,q]of H)k.codexTurnIdByHostTurnId.set(G,q)}catch(x){this._logService.warn(`[Codex:${T}] failed to seed forked turn-id map: ${x instanceof Error?x.message:String(x)}`)}return this._logService.info(`[Codex] forked session ${i} \u2192 ${T} (kept ${s.length-u}/${s.length} turns)`),{session:P,workingDirectory:X,provisional:!1}}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){let u=j(ak.tmpdir(),"vscode-agent-codex",e.sessionId);await jr.promises.mkdir(u,{recursive:!0}),e.workingDirectory=h.file(u),e.managedWorkingDirectory=e.workingDirectory,this._logService.info(`[Codex] no working directory supplied for session=${e.sessionUri.toString()}; using managed temp folder ${u}`)}let t=await this._ensureConnection(),r=this._readSessionConfig(e),i=await this._resolveModel(e),{approvalPolicy:s,sandboxMode:a,approvalsReviewer:l}=this._resolveSessionPermissions(e),c=(await t.client.request("thread/start",{cwd:e.workingDirectory.fsPath,model:i.id,approvalPolicy:s,sandbox:a,approvalsReviewer:l,config:{web_search:Y0(r["codex.webSearchMode"])??Mn["codex.webSearchMode"]},dynamicTools:this._buildDynamicTools(e)})).thread.id;if(e.disposed){try{await t.client.request("thread/unsubscribe",{threadId:c})}catch(u){this._logService.info(`[Codex:${c}] thread/unsubscribe after disposed prewarm failed: ${u instanceof Error?u.message:String(u)}`)}return}e.threadId=c,e.materializedToolsSig=sk(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(i=>i.name).join(", ")||"(none)"}]`),t.kind==="ready"&&r!==void 0){this._sessionIdByThreadId.delete(r);try{await t.client.request("thread/unsubscribe",{threadId:r})}catch(i){this._logService.info(`[Codex:${r}] thread/unsubscribe during tool restart failed: ${i instanceof Error?i.message:String(i)}`)}}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(_s)){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)},_H);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,i){let s=this._sessionUriFromChat(e);this._logService.info(`[Codex DEBUG] sendMessage session=${s.toString()} prompt=${JSON.stringify(t).slice(0,60)}`);let a=D.id(s),l=this._sessions.get(a);if(!l)throw new Error(`Codex session not found: ${s.toString()}`);let d=await this._ensureConnection(),c=i??O();try{this._claimPrewarm(l),await this._materializeIfNeeded(l),this._persistMaterializedSession(l)}catch(v){let y=v instanceof Error?v.message:String(v);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&&sk(l.clientToolSet.merged())!==l.materializedToolsSig)try{await this._restartThreadWithCurrentTools(l),this._persistMaterializedSession(l)}catch(v){let y=v instanceof Error?v.message:String(v);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(v){this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexResumeFailed",message:v instanceof Error?v.message:String(v)}}),this._fire(s,{type:"chat/turnComplete",turnId:c});return}let{input:p,cleanupPaths:m}=jC(t,r);l.lastPromptText=t,l.currentTurnId=c;try{let v=await this._resolveModel(l),y=this._turnStartOptions(l,v.id);await d.client.request("turn/start",{threadId:u,input:p.slice(),model:v.id,...y}),l.firstTurnSent=!0}catch(v){if(v instanceof K){this._fire(s,{type:"chat/turnCancelled",turnId:c});return}let y=v instanceof Error?v.message:String(v);this._logService.error(`[Codex:${a}] turn/start error: ${y}`),this._fire(s,{type:"chat/error",turnId:c,error:{errorType:"CodexTurnError",...Va(y)}}),this._fire(s,{type:"chat/turnComplete",turnId:c})}finally{m.length>0&&setTimeout(()=>{for(let v of m)try{jr.unlinkSync(v)}catch{}},3e4)}}setPendingMessages(e,t,r){if(!t)return;let i=D.id(e),s=this._sessions.get(i);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}=jC(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 Ti){this._logService.info(`[Codex:${i}] turn/steer skipped: ${m.message}`);return}this._logService.warn(`[Codex:${i}] turn/steer failed: ${m instanceof Error?m.message:String(m)}`)})}async _abort(e){let t=this._sessionUriFromChat(e),r=D.id(t),i=this._sessions.get(r);if(!i||(this._drainPendingSteering(i),!i.currentAppTurnId||i.threadId===void 0))return;let s=i.threadId,a=this._connection;if(a.kind==="ready")try{await a.client.request("turn/interrupt",{threadId:s,turnId:i.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=D.id(e),r=this._sessions.get(t);r&&await this._teardownSessionInMemory(r,t)}async releaseSession(e){let t=D.id(e),r=this._sessions.get(t);r&&r.threadId!==void 0&&r.currentTurnId===void 0&&(this._logService.info(`[Codex:${r.threadId}] Releasing idle session from memory (durable state preserved)`),await this._teardownSessionInMemory(r,t))}async _teardownSessionInMemory(e,t){if(e.disposed=!0,this._claimPrewarm(e),this._sessions.delete(t),e.mcpController?.dispose(),e.managedWorkingDirectory){let i=e.managedWorkingDirectory.fsPath;jr.promises.rm(i,{recursive:!0,force:!0}).catch(s=>{this._logService.info(`[Codex] failed to remove managed temp folder ${i}: ${s instanceof Error?s.message:String(s)}`)})}e.threadId!==void 0&&this._sessionIdByThreadId.delete(e.threadId),e.pendingCommandApprovals.denyAll("decline"),e.pendingClientToolCalls.rejectAll(new K),e.pendingUserInputs.rejectAll(new K),this._drainPendingSteering(e);for(let[i,s]of this._subagentsByThreadId)s.parentSessionId===t&&(s.session.pendingCommandApprovals.denyAll("decline"),this._subagentsByThreadId.delete(i));let r=this._connection;if(r.kind==="ready"&&e.threadId!==void 0){let i=e.threadId;try{await r.client.request("thread/unsubscribe",{threadId:i})}catch(s){this._logService.info(`[Codex:${i}] thread/unsubscribe failed: ${s instanceof Error?s.message:String(s)}`)}}}async _changeModel(e,t){let r=this._sessionUriFromChat(e),i=this._sessions.get(D.id(r));if(i){let s=this._supportedModelOrUndefined(t);s&&(i.model=s)}}async truncateSession(e,t){let r=await this._readSession(e);if(!r)return;let i=r.thread.turns??[];if(i.length===0)return;let s;if(t===void 0)s=i.length;else{let l=this._sessions.get(D.id(e))?.codexTurnIdByHostTurnId.get(t)??t,d=i.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=i.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 i=this._connection;if(i.kind==="ready")try{t?await i.client.request("thread/archive",{threadId:r}):await i.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(D.id(e));return t?.threadId!==void 0?t.threadId:(await this._metadataStore.read(e)).threadId}respondToPermissionRequest(e,t){let r=[...this._sessions.values(),...[...this._subagentsByThreadId.values()].map(i=>i.session)];for(let i of r)if(i.pendingCommandApprovals.respond(e,t?"accept":"decline")){t||i.mapState.declinedToolCalls.add(e);return}this._logService.info(`[Codex] respondToPermissionRequest: unknown requestId=${e}`)}respondToUserInputRequest(e,t,r){for(let i of this._sessions.values())if(i.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?V0(t.thread):[])}async getSessionMetadata(e){let t=D.id(e),r=await this._readSession(e);if(r){if(!this._sessions.has(t)){let i=r.thread.cwd?h.file(r.thread.cwd):void 0,s=r.thread.id;this._sessions.set(t,this._createResumedSessionEntry(t,s,e,i,void 0)),this._sessionIdByThreadId.set(s,t);let a=this._sessions.get(t);a&&!a.serverToolsAdvertised&&this._serverToolHost&&(a.serverToolsAdvertised=!0,this._serverToolHost.advertise(a.sessionUri.toString()))}return this._threadToMetadata(r.thread,e)}}async _readSession(e){let t=D.id(e),i=this._sessions.get(t)?.threadId;i===void 0&&(i=(await this._metadataStore.read(e)).threadId??t);try{return await(await this._ensureConnection()).client.request("thread/read",{threadId:i,includeTurns:!0})}catch(s){let a=s instanceof Error?s.message:String(s);/thread not loaded/i.test(a)?this._logService.info(`[Codex:${i}] thread/read: not loaded yet (will resume on first send)`):this._logService.warn(`[Codex:${i}] thread/read failed: ${a}`);return}}async listSessions(){if(!this._githubToken)return[];if(!await this._agentSdkDownloader.isSdkResolvableWithoutDownload(_s))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 i of this._sessions.values())i.threadId!==void 0&&r.set(i.threadId,i.sessionUri);return t.data.map(i=>this._threadToMetadata(i,r.get(i.id)??D.uri(this.id,i.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?h.file(e.cwd):void 0}}setServerToolHost(e){this._serverToolHost=e}getOrCreateActiveClient(e,t){let r=D.id(e);return new QC(()=>this._sessions.get(r),t.clientId,t.displayName,i=>this._logService.info(`[Codex:${r}] active client ${t.clientId} tools=[${i.map(s=>s.name).join(", ")||"(none)"}]`))}removeActiveClient(e,t){let r=D.id(e);this._sessions.get(r)?.clientToolSet.delete(t)}onClientToolCallComplete(e,t,r,i){let s=D.id(e);this._sessions.get(s)?.pendingClientToolCalls.respondOrBuffer(r,i)}setCustomizationEnabled(e,t){}async getSessionCustomizations(e){let t=this._sessions.get(D.id(e));if(!t)return[];let r=this._getOrCreateMcpController(t);return r.applyAll(Th(this._mcpInventory)),this._refreshMcpCustomizationIds(t,r),r.topLevelCustomizations()}async handleMcpRequest(e,t,r,i){let s=D.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=u0(r,l);if(d.handled)return d.result;switch(r){case"tools/call":{let c=i&&typeof i.name=="string"?i.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:i?i.arguments:void 0})}case"resources/read":{let c=i&&typeof i.uri=="string"?i.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}`)}}async startMcpServer(e,t){let r=this._sessions.get(D.id(e)),i=r?this._resolveMcpServerName(r,t):void 0;if(!r||!i){this._logService.warn(`[Codex] Cannot start unknown MCP server customization ${t}`);return}let s=await this._ensureConnection();await s.client.request("config/mcpServer/reload",void 0),await this._refreshMcpInventory(s.client)}async stopMcpServer(e,t){let r=this._sessions.get(D.id(e)),i=r?this._resolveMcpServerName(r,t):void 0;if(!r||!i){this._logService.warn(`[Codex] Cannot stop unknown MCP server customization ${t}`);return}}_resolveMcpServerName(e,t){let r=this._getOrCreateMcpController(e);return r.applyAll(Th(this._mcpInventory)),this._refreshMcpCustomizationIds(e,r),r.serverNameForCustomizationId(t)}_getOrCreateMcpController(e){return e.mcpController||(e.mcpController=new ol({providerId:this.id,sessionId:e.sessionId,resolveChildId:()=>{},emit:t=>this._fire(e.sessionUri,t),capabilities:yH})),e.mcpController}_applyMcpInventoryToSessions(){let e=Th(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 i of this._mcpInventory.keys()){let s=t.customizationIdForServer(i);s!==void 0&&r.set(i,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=c0(t),i=[];for(let[s,a]of r){let l=this._mcpInventory.get(s);l&&p0(l,a)&&i.push(s)}for(let[s,a]of this._mcpInventory)!r.has(s)&&a.state.kind!=="ready"&&r.set(s,a);this._mcpInventory.clear();for(let[s,a]of r)this._mcpInventory.set(s,a);this._applyMcpInventoryToSessions();for(let s of i)this._fireMcpToolsListChanged(s)}_handleMcpStartupStatus(e,t,r,i){if(this._connection.kind==="ready"&&this._connection.client!==e)return;if(r==="ready"){this._refreshMcpInventory(e);return}let s=this._mcpInventory.get(t);this._mcpInventory.set(t,{state:d0(r,i),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 K),e.pendingUserInputs.rejectAll(new K),e.mcpController?.dispose();this._sessions.clear(),this._sessionIdByThreadId.clear(),this._mcpInventory.clear()}resolveSessionConfig(e){let t=Nh.validateOrDefault(e.config,Mn),r=IH.toProtocol(),i={...e.config,mode:t.mode};return delete i["codex.permissionsPreset"],delete i["codex.approvalPolicy"],delete i["codex.sandboxMode"],Object.assign(i,Lh(e.config,{approvalPolicy:Mn["codex.approvalPolicy"],sandboxMode:Mn["codex.sandboxMode"]})),Promise.resolve({values:i,schema:r})}async sessionConfigCompletions(e){if(e.property!=="codex.additionalDirectories")return{items:[]};let t=e.query?.trim();if(!t)return{items:[]};let r=e.workingDirectory?.fsPath,i=Wt(t)?t:Fn(r??process.cwd(),t),s=t.endsWith(Le)?i:oe(i),a=t.endsWith(Le)?"":Te(i).toLowerCase();try{return{items:(await jr.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:pr(t)?h.parse(pe(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 K),e.pendingUserInputs.rejectAll(new K),e.mcpController?.dispose();for(let e of this._subagentsByThreadId.values())e.session.pendingCommandApprovals.denyAll("decline");this._subagentsByThreadId.clear(),this._sessions.clear(),this._sessionIdByThreadId.clear(),this._mcpInventory.clear(),super.dispose()}};Yl=R([C(0,M),C(1,Pt),C(2,Rh),C(3,He),C(4,xt),C(5,Ml),C(6,ft),C(7,xe)],Yl);function RH(o){if(!o)return[];try{let n=JSON.parse(o);return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}catch{return[]}}function xH(o,n){if(!(o!=="linux"&&o!=="darwin"&&o!=="win32"||n!=="x64"&&n!=="arm64"))return`${o}-${n}`}function PH(o){switch(o){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 AH(o=EH){try{let n=await o();return oe(oe(oe(oe(n))))}catch{return}}async function EH(){let{createRequire:o}=await import("node:module");return o(import.meta.url).resolve("@openai/codex/package.json")}import{lookup as kH}from"dns";var ck=W("networkDiagnosticsService"),uk=1e4,lk=64*1024,DH=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy","NO_PROXY","no_proxy"],MH=["http.proxy","http.proxyStrictSSL","http.proxySupport","http.noProxy"],Xl=class{constructor(n,e,t,r,i){this._requestService=n;this._proxyResolver=e;this._configurationService=t;this._productService=r;this._logService=i}async getInfo(n,e){let t={};for(let i of DH){let s=process.env[i];s&&(t[i]=s)}let r={};for(let i of MH){let s=this._configurationService.getValue(i);s===void 0||s===""||Array.isArray(s)&&s.length===0||(r[i]=Array.isArray(s)?s.join(", "):String(s))}return{version:this._productService.version,os:process.platform,arch:process.arch,account:e,proxySettings:r,proxyEnv:t,endpoints:n}}async fetch(n){let t=new URL(n).hostname,[r,i]=await Promise.all([dk(t,4),dk(t,6)]),s;try{s=await this._proxyResolver.resolveProxy(n)}catch(d){this._logService.debug(`[AgentHost] Network diagnostics: proxy resolution for ${n} failed: ${XC(d)}`)}let a={url:n,proxyUrl:s,dnsIpv4:r,dnsIpv6:i},l=Date.now();try{let d=await this._requestService.request({url:n,type:"GET",timeout:uk,callSite:dg},Re.None),c=(await wr(d.stream)).toString();return{...a,statusCode:d.res.statusCode,body:c.length>lk?c.slice(0,lk):c,durationMs:Date.now()-l}}catch(d){return{...a,error:XC(d),durationMs:Date.now()-l}}}};Xl=R([C(0,si),C(1,yi),C(2,Bn),C(3,ft),C(4,M)],Xl);function OH(o,n){return new Promise((e,t)=>{kH(o,{family:n},(r,i)=>r?t(r):e(i))})}async function dk(o,n){let e=Date.now();try{return{address:await LH(OH(o,n),uk),durationMs:Date.now()-e}}catch(t){return{durationMs:Date.now()-e,error:XC(t)}}}function LH(o,n){return new Promise((e,t)=>{let r=setTimeout(()=>t(new Error(`Timed out after ${n/1e3}s`)),n);o.then(i=>{clearTimeout(r),e(i)},i=>{clearTimeout(r),t(i)})})}function XC(o){return o instanceof Error?o.message:String(o)}import{mkdir as e6}from"fs/promises";var NH=/^[0-9a-fA-F]+$/,UH="00000000000000000000000000000000",pk="0000000000000000";function fk(o){if(!o||!Array.isArray(o.resourceSpans))return{spans:[],rejected:0,errors:[]};let n=[],e=[],t=0;for(let r of o.resourceSpans){if(!r)continue;let i=WH(r.resource?.attributes);for(let s of r.scopeSpans??[])if(s)for(let a of s.spans??[])try{let l=FH(a,i);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 FH(o,n){if(!o)return;let e=(o.traceId??"").toLowerCase(),t=(o.spanId??"").toLowerCase();if(!ZC(e,32)||e===UH)throw new Error(`invalid traceId: ${o.traceId}`);if(!ZC(t,16)||t===pk)throw new Error(`invalid spanId: ${o.spanId}`);let r;if(o.parentSpanId){let c=o.parentSpanId.toLowerCase();ZC(c,16)&&c!==pk&&(r=c)}let i=tI(o.startTimeUnixNano),s=tI(o.endTimeUnixNano);if(i===void 0||s===void 0)throw new Error("missing span time bounds");let a={...n};for(let c of o.attributes??[])nI(a,c);let l=[];for(let c of o.events??[]){let u=HH(c);u&&l.push(u)}let d=$H(o.status?.code,o.status?.message);return{name:o.name??"",traceId:e,spanId:t,parentSpanId:r,startTime:i,endTime:s,status:d,attributes:a,events:l}}function HH(o){if(!o)return;let n=tI(o.timeUnixNano);if(n===void 0)return;let e={};for(let t of o.attributes??[])nI(e,t);return{name:o.name??"",timestamp:n,attributes:Object.keys(e).length>0?e:void 0}}function $H(o,n){switch(o){case 1:return{code:1,message:n};case 2:return{code:2,message:n};case 0:default:return{code:0,message:n}}}function WH(o){let n={};if(!o)return n;for(let e of o)nI(n,e);return n}function nI(o,n){if(!n||typeof n.key!="string"||n.key.length===0)return;let e=eI(n.value);e!==void 0&&(o[n.key]=e)}function eI(o){if(o){if(typeof o.stringValue=="string")return o.stringValue;if(typeof o.boolValue=="boolean")return o.boolValue;if(o.intValue!==void 0){let n=typeof o.intValue=="string"?Number(o.intValue):o.intValue;return Number.isFinite(n)?n:void 0}if(typeof o.doubleValue=="number")return o.doubleValue;if(o.arrayValue?.values){let n=o.arrayValue.values.map(eI);return n.every(e=>typeof e=="string")?n:JSON.stringify(n)}if(o.kvlistValue?.values){let n={};for(let e of o.kvlistValue.values)e&&typeof e.key=="string"&&(n[e.key]=eI(e.value));return JSON.stringify(n)}if(typeof o.bytesValue=="string")return o.bytesValue}}function tI(o){if(o===void 0||o===""||o==="0")return;let n=o.length<=6?"0":o.slice(0,-6),e=Number(n);return Number.isFinite(e)?e:void 0}function ZC(o,n){return o.length===n&&NH.test(o)}var qH="/v1/traces",BH=64*1024*1024;async function gk(o,n,e={}){let t=e.maxBodyBytes??BH,i=(await import("http")).createServer();i.on("request",(c,u)=>{zH(c,u,o,n,t).catch(p=>{if(n.error(`[agentHost-otel] receiver: unhandled error: ${p instanceof Error?p.message:String(p)}`),!u.headersSent)wi(u,500,"internal error");else if(!u.writableEnded)try{u.end()}catch{}})}),await new Promise((c,u)=>{let p=m=>u(m);i.once("error",p),i.listen(0,"127.0.0.1",()=>{i.removeListener("error",p),c()})});let s=i.address();if(!s||typeof s=="string")throw i.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=N(()=>{i.closeAllConnections(),i.close(c=>{c&&n.warn(`[agentHost-otel] receiver close error: ${c.message}`)})});return Object.assign(d,{baseUrl:l,port:a})}async function zH(o,n,e,t,r){if((o.url??"").split("?",1)[0]!==qH){wi(n,404,"not found");return}if(o.method!=="POST"){n.setHeader("allow","POST"),wi(n,405,"method not allowed");return}let a=(o.headers["content-type"]??"").toString().toLowerCase();if(!a.includes("application/json")){wi(n,415,"unsupported content-type; this receiver only accepts application/json");return}let l=(o.headers["content-encoding"]??"").toString().toLowerCase();if(l&&l!=="identity"){wi(n,415,`unsupported content-encoding: ${l}`);return}let d;try{d=await VH(o,r)}catch(m){m instanceof Uh?wi(n,413,"payload too large"):wi(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){wi(n,400,`invalid json: ${m instanceof Error?m.message:String(m)}`);return}let u=fk(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 Uh=class extends Error{};function VH(o,n){return new Promise((e,t)=>{let r=[],i=0,s=c=>{if(i+=c.length,i>n){d(),t(new Uh(`body exceeds ${n} bytes`));return}r.push(c)},a=()=>{d(),e(Buffer.concat(r))},l=c=>{d(),t(c)},d=()=>{o.removeListener("data",s),o.removeListener("end",a),o.removeListener("error",l)};o.on("data",s),o.on("end",a),o.on("error",l)})}function wi(o,n,e){o.statusCode=n,o.setHeader("content-type","text/plain; charset=utf-8"),o.end(e)}import{URL as mk}from"url";import{promises as jH}from"fs";function KH(o){try{let n=new mk(o);return n.pathname===""||n.pathname==="/"?(n.pathname="/v1/traces",n.toString()):o}catch{return o}}var Fh=class extends w{constructor(e,t,r){super();this._options=e;this._logService=t;this._fetchFn=r;this._queue=new zo;this._disposed=!1;this._resolvedEndpoint=KH(e.endpoint),this._register(N(()=>{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{if(this._fetchFn){let l=await this._fetchFn(this._resolvedEndpoint,{method:"POST",headers:{"content-type":t,"content-length":String(e.length),...this._options.headers??{}},body:Uint8Array.from(e).buffer,signal:AbortSignal.timeout(this._options.timeoutMs??1e4)});if(await l.arrayBuffer(),!l.ok)throw new Error(`upstream returned HTTP ${l.status}`);return}let r=new mk(this._resolvedEndpoint),i=r.protocol==="https:",s=i?await import("https"):await import("http"),a={"content-type":t,"content-length":String(e.length),...this._options.headers??{}};await GH(s,{host:r.hostname,port:r.port?Number(r.port):i?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 GH(o,n,e){return new Promise((t,r)=>{let i=o.request({host:n.host,port:n.port,path:n.path,method:n.method,headers:n.headers,timeout:n.timeoutMs}),s=a=>{i.destroy(),r(a)};i.on("error",s),i.on("timeout",()=>s(new Error(`request timeout after ${n.timeoutMs}ms`))),i.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)}),i.end(e)})}var Hh=class extends w{constructor(e,t){super();this._options=e;this._logService=t;this._queue=new zo;this._disposed=!1;this._register(N(()=>{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 jH.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)}`)}}},$h=class extends w{constructor(e){super();this._logService=e;this._disposed=!1;this._register(N(()=>{this._disposed=!0}))}forwardSpans(e){if(!this._disposed)for(let t of e.spans)this._logService.info(`[agentHost-otel] span ${JH(t)}`)}async flush(){}};function JH(o){let n=Math.max(0,o.endTime-o.startTime),e=o.attributes["gen_ai.operation.name"],t=o.attributes["gen_ai.request.model"]??o.attributes["gen_ai.response.model"],r=[e&&`op=${e}`,t&&`model=${t}`].filter(Boolean).join(" ");return`${o.name} (${n}ms) trace=${o.traceId} span=${o.spanId}${r?" "+r:""}`}var Wh=class extends w{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 YH}from"fs";import{createRequire as QH}from"module";var bn={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"},ku={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 XH=QH(import.meta.url);function ZH(){return XH("node:sqlite")}var hk=1,yk=10080*60*1e3,vk=100,sn={operation_name:bn.OPERATION_NAME,provider_name:bn.PROVIDER_NAME,agent_name:bn.AGENT_NAME,conversation_id:bn.CONVERSATION_ID,request_model:bn.REQUEST_MODEL,response_model:bn.RESPONSE_MODEL,input_tokens:bn.USAGE_INPUT_TOKENS,output_tokens:bn.USAGE_OUTPUT_TOKENS,cached_tokens:bn.USAGE_CACHE_READ_INPUT_TOKENS,reasoning_tokens:bn.USAGE_REASONING_TOKENS,tool_name:bn.TOOL_NAME,tool_call_id:bn.TOOL_CALL_ID,tool_type:bn.TOOL_TYPE,chat_session_id:ku.CHAT_SESSION_ID,turn_index:ku.TURN_INDEX,ttft_ms:ku.TIME_TO_FIRST_TOKEN},lLe=W("otelSqliteStore"),qh=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,sn.operation_name),this._attr(n,sn.provider_name),this._attr(n,sn.agent_name),this._attr(n,sn.conversation_id),this._attr(n,sn.request_model),this._attr(n,sn.response_model),this._attr(n,sn.input_tokens),this._attr(n,sn.output_tokens),this._attr(n,sn.cached_tokens),this._attr(n,sn.reasoning_tokens),this._attr(n,sn.tool_name),this._attr(n,sn.tool_call_id),this._attr(n,sn.tool_type),this._attr(n,sn.chat_session_id),this._attr(n,sn.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=yk){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,ku.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:"&&YH(oe(this._dbPath),{recursive:!0});let{DatabaseSync:n}=ZH(),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)>=hk||n.exec(`
			CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
			INSERT OR REPLACE INTO schema_version (version) VALUES (${hk});

			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()-yk;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(vk);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,vk)}};var t6=rw;function rI(o){if(!o)return!1;let n=o.trim().toLowerCase();return n==="true"||n==="1"||n==="yes"||n==="on"}function n6(o){if(!o)return;let n={};for(let e of o.split(",")){let t=e.indexOf("=");if(t<=0)continue;let r=e.slice(0,t).trim(),i=e.slice(t+1).trim();r&&(n[r]=i)}return Object.keys(n).length?n:void 0}function r6(o){let n=rI(o.COPILOT_OTEL_DB_SPAN_EXPORTER_ENABLED),e=o.OTEL_EXPORTER_OTLP_ENDPOINT??o.COPILOT_OTEL_ENDPOINT,t=o.COPILOT_OTEL_FILE_EXPORTER_PATH,i=rI(o.COPILOT_OTEL_ENABLED)||n||!!e||!!t,s=(o.COPILOT_OTEL_EXPORTER_TYPE??"").trim().toLowerCase(),a=(o.OTEL_EXPORTER_OTLP_PROTOCOL??o.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:i,dbSpanExporter:n,exporterType:l,otlpEndpoint:e,filePath:t,sourceName:o.COPILOT_OTEL_SOURCE_NAME,captureContent:o.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT===void 0?void 0:rI(o.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT),headers:n6(o.OTEL_EXPORTER_OTLP_HEADERS)}}var Zl=class extends w{constructor(e,t,r){super();this._fetchFn=e;this._logService=t;this._config=r6(process.env),this._spansDbPath=j(r.userDataPath,t6)}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?h.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 e6(oe(this._spansDbPath),{recursive:!0});let e=new qh(this._spansDbPath);this._register(N(()=>e.close())),this._forwarder=this._buildOutboundForwarder();let t=await gk({onSpans:r=>{for(let i of r.spans)try{e.insertSpan(i)}catch(s){this._logService.warn("[agentHost.otel] failed to insert span",s)}this._forwarder?.forwardSpans?.(r)},onForward:this._forwarder?(r,i)=>{this._forwarder.forwardRaw?.(r,i)}: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 Fh({endpoint:this._config.otlpEndpoint,headers:this._config.headers},this._logService,this._fetchFn));break;case"file":this._config.filePath&&e.push(new Hh({filePath:this._config.filePath},this._logService));break;case"console":e.push(new $h(this._logService));break}if(e.length)return e.length===1?e[0]:new Wh(e)}};Zl=R([C(1,M),C(2,bt)],Zl);var Bh=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}},Sk=class o extends w{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=Re.None,r){if(this._store.isDisposed)return Promise.reject(new K);let i=this._nextRequestId++,s=new Ee,a=new Ze;this._pendingRequests.set(i,{promise:s,cts:a});let l=t.onCancellationRequested(()=>{s.isSettled||(this._pendingRequests.delete(i),a.cancel(),r?.(i),s.cancel()),l.dispose()});return this._send({jsonrpc:"2.0",id:i,...e}),s.p.finally(()=>{l.dispose(),this._pendingRequests.delete(i),a.dispose(!0)})}async handleMessage(e){if(Array.isArray(e)){let r=[];for(let i of e){let s=await this._handleMessage(i);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(oI(e)){he(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(o6(e))return this._handleRequest(e);i6(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 Bh(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:o.MethodNotFound,message:`Method not found: ${e.method}`}};return this._send(r),r}let t=new Ze;this._register(N(()=>t.dispose(!0)));try{let r=this._handlers.handleRequest(e,t.token),i=s6(r)?await r:r,s={jsonrpc:"2.0",id:e.id,result:i};return this._send(s),s}catch(r){let i;return r instanceof Bh?i={jsonrpc:"2.0",id:e.id,error:{code:r.code,message:r.message,data:r.data}}:i={jsonrpc:"2.0",id:e.id,error:{code:o.InternalError,message:r instanceof Error?r.message:"Internal error"}},this._send(i),i}finally{t.dispose(!0)}}dispose(){this.cancelAllRequests(),super.dispose()}static createParseError(e,t){return{jsonrpc:"2.0",error:{code:o.ParseError,message:e,data:t}}}};function o6(o){return"method"in o&&"id"in o&&(typeof o.id=="string"||typeof o.id=="number")}function oI(o){return he(o,{id:!0,result:!0})||he(o,{id:!0,error:!0})}function i6(o){return he(o,{method:!0})&&!he(o,{id:!0})}function s6(o){return typeof o=="object"&&o!==null&&"then"in o&&typeof o.then=="function"}function bk(o,n){if(qi(o.channel)){for(let e of n)if(qi(e))return!0;return!1}for(let e of n)if(e===o.channel)return!0;return!1}var ed="0.6.0",eNe=Object.freeze(["0.6.0","0.5.2","0.5.1"]);function Ck(o){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(o);if(!n)throw new Error(`Invalid protocol version: ${o}`);return[Number(n[1]),Number(n[2]),Number(n[3])]}function iI(o,n){let[e,t,r]=Ck(o),[i,s,a]=Ck(n);return e-i||t-s||r-a}var tNe={"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/mcpServerStartRequested":"0.5.2","session/mcpServerStopRequested":"0.5.2","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","chat/turnsLoaded":"0.5.1","changeset/statusChanged":"0.2.0","changeset/fileSet":"0.2.0","changeset/fileRemoved":"0.2.0","changeset/filesReviewChanged":"0.6.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 Ik(o){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(o);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])]}function a6(o,n){let e=Ik(o),t=Ik(n);return!e||!t||e[0]!==t[0]||e[0]===0&&e[1]!==t[1]?!1:iI(o,n)<=0}function _k(o,n){let e;for(let t of o)a6(t,n)&&(e===void 0||iI(t,e)>0)&&(e=t);return e}var sI="_vscodeUpgrade";var Tk="VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";function zh(){let o=process.env[Tk];return o&&o.length>0?o:void 0}async function wk(o=zh()){let n=await import("http");return o?new Promise((e,t)=>{let r=n.request({socketPath:o,method:"POST",path:"/upgrade",headers:{"content-length":"0"}},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>{let a=Buffer.concat(s).toString("utf8"),l=i.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}`))}}),i.on("error",t)});r.once("error",t),r.end()}):Promise.reject(new Error(`Cannot request upgrade: ${Tk} is not set.`))}function Rk(o,n){if(o!=="resourceRead"||!l6(n))return!1;let e=n.uri;if(typeof e!="string")return!1;try{return h.parse(e).scheme===ne.file}catch{return!1}}function l6(o){return typeof o=="object"&&o!==null&&he(o,{uri:!0})}var d6=1e3,xk=3e4;function c6(o){return o==="streaming"||o==="running"||o==="pending-confirmation"}function Ts(o,n){return{jsonrpc:"2.0",id:o,result:n}}function Du(o,n,e,t){return{jsonrpc:"2.0",id:o,error:{code:n,message:e,...t!==void 0?{data:t}:{}}}}function ws(o,n){if(n instanceof L)return Du(o,n.code,n.message,n.data);let e=n instanceof Error?n.stack??n.message:String(n);return Du(o,zi,e)}function u6(o,n,e){return!(e instanceof L)||e.code!==Se.NotFound||!Rk(o,n)}function Pk(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function p6(o){if(!Pk(o))return;let n=o.channel;if(!(typeof n!="string"||!n.startsWith("mcp://")))return n}function Vh(o){if(o.toLowerCase().startsWith(`${WA}:`)){let n=zA(o);return n?{kind:"otlp-logs",uri:VA(n),level:n}:void 0}return OT(o)?{kind:"resource-watch",uri:o}:{kind:"state",uri:o}}var Rs=class extends w{constructor(e,t,r,i,s,a){super();this._agentService=e;this._stateManager=t;this._server=r;this._config=i;this._clientFileSystemProvider=s;this._logService=a;this._clients=new Map;this._replayBuffer=[];this._onDidChangeConnectionCount=this._register(new A);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,t)=>{let r=Vh(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 i=this._agentService.onResourceWatchSubscribed(r.uri);if(!i)throw new L(_t,`Resource watch not found: ${t.channel}`);return e.subscriptions.set(r.uri,r),{snapshot:{resource:r.uri,state:i,fromSeq:this._stateManager.serverSeq}}}try{let i=await this._agentService.subscribe(h.parse(t.channel),e.clientId);return e.subscriptions.set(r.uri,r),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),{snapshot:i}}catch(i){throw i instanceof L?i:new L(_t,`Resource not found: ${t.channel}`)}},createSession:async(e,t)=>{let r,i;if(t.fork){let s=this._stateManager.getSessionState(t.fork.session);if(!s)throw new L(_t,`Fork source session not found: ${t.fork.session}`);let a=s.turns.findIndex(l=>l.id===t.fork.turnId);if(a<0)throw new L(_t,`Fork turn ID ${t.fork.turnId} not found in session ${t.fork.session}`);i={session:h.parse(t.fork.session),turnIndex:a,turnId:t.fork.turnId}}if(t.activeClient&&t.activeClient.clientId!==e.clientId)throw new L(ae.InvalidParams,"createSession.activeClient.clientId must match the connection's clientId");try{r=await this._agentService.createSession({provider:t.provider,workingDirectory:t.workingDirectory?h.parse(t.workingDirectory):void 0,session:h.parse(t.channel),fork:i,config:t.config,activeClient:t.activeClient,progressToken:t.progressToken})}catch(s){throw s instanceof L?s:new L(pw,s instanceof Error?s.message:String(s))}return r.toString()!==h.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(h.parse(t.channel)),null),createChat:async(e,t)=>{let r=this._stateManager.getSessionState(t.channel);if(!r)throw new L(_t,`Session not found: ${t.channel}`);let i=r.defaultChat??pe(t.channel);return h.parse(t.chat).toString()===h.parse(i).toString()||await this._agentService.createChat(h.parse(t.channel),h.parse(t.chat),{...t.source?{fork:{source:h.parse(t.source.chat),turnId:t.source.turnId}}:{}}),null},disposeChat:async(e,t)=>{let r=h.parse(t.channel),i=ke(r);return i&&await this._agentService.disposeChat(h.parse(i.session),r),null},resourceWrite:async(e,t)=>this._agentService.resourceWrite(t),listSessions:async()=>({items:(await this._agentService.listSessions()).map(r=>{let i=D.provider(r.session);if(!i)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:i,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?h.parse(t.workingDirectory):void 0,config:t.config}),sessionConfigCompletions:async(e,t)=>this._agentService.sessionConfigCompletions({provider:t.provider,workingDirectory:t.workingDirectory?h.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.getChatState(t.channel);if(!r)throw new L(_t,`Session not found: ${t.channel}`);if(t.cursor&&t.cursor!==r.turnsNextCursor)throw new L(ae.InvalidParams,"Unrecognized fetchTurns cursor");return this._stateManager.dispatchServerAction(t.channel,{type:"chat/turnsLoaded",turns:[]}),{}},resourceList:async(e,t)=>this._agentService.resourceList(h.parse(t.uri)),resourceRead:async(e,t)=>this._agentService.resourceRead(h.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 L(cr,`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(h.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>d6&&this._replayBuffer.shift(),this._broadcastAction(l),l.action.type==="chat/toolCallStart"||l.action.type==="chat/toolCallReady"){if(!de(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 Y,r;t.add(e.onMessage(i=>{if(gw(i)){if(this._logService.trace(`[ProtocolServer] request: method=${i.method} id=${i.id}`),i.method==="ping"){e.send(Ts(i.id,null));return}if(!r&&i.method==="initialize"){try{let s=this._handleInitialize(i.params,e,t);r=s.client,e.send(Ts(i.id,s.response))}catch(s){e.send(ws(i.id,s))}return}if(!r&&i.method==="reconnect"){let s;try{let a=this._handleReconnect(i.params,e,t);r=a.client,s=a.responsePromise}catch(a){e.send(ws(i.id,a));return}s.then(a=>e.send(Ts(i.id,a)),a=>e.send(ws(i.id,a)));return}if(i.method===sI){this._handleVscodeUpgrade(i.id,e);return}if(!r)return;this._handleRequest(r,i.method,i.params,i.id)}else if(mw(i))switch(this._logService.trace(`[ProtocolServer] notification: method=${i.method}`),i.method){case"unsubscribe":r&&this._removeSubscription(r,i.params.channel);break;case"dispatchAction":if(r){this._logService.trace(`[ProtocolServer] dispatchAction: ${JSON.stringify(i.params.action.type)}`);let s=i.params.action,a=i.params.channel;(uc(s)||pr(s)||mf(s)||s.type==="root/configChanged")&&this._agentService.dispatchAction(a,s,r.clientId,i.params.clientSeq)}break}else if(oI(i)){let s=this._pendingReverseRequests.get(i.id);s&&s.client===r&&(this._pendingReverseRequests.delete(i.id),he(i,{error:!0})?s.reject(new L(i.error?.code??-32e3,i.error?.message??"Reverse RPC error",i.error?.data)):s.resolve(i.result))}})),t.add(e.onClose(()=>{let i=r?this._clients.get(r.clientId):void 0;if(r&&i?.state==="active"){let s=i.connections.indexOf(r);if(s!==-1){let a=r.subscriptions.size;i.connections.splice(s,1),this._releaseClientSubscriptions(r,i),this._rejectPendingReverseRequestsForConnection(r),i.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 we}),this._handleClientDisconnected(r.clientId),this._onDidChangeConnectionCount.fire(this._connectedClientCount))}}t.dispose()})),t.add(e)}_handleInitialize(e,t,r){let i=Array.isArray(e.protocolVersions)?e.protocolVersions:[];this._logService.info(`[ProtocolServer] Initialize: clientId=${e.clientId}, protocolVersions=[${i.join(", ")}]`);let s=_k(i,ed);if(!s){let d={supportedVersions:[`^${ed}`],_meta:zh()?{vscodeUpgradeMethod:sI}:void 0};throw new L(fw,`Client offered protocol versions [${i.join(", ")}], none of which are compatible with this server's version ${ed} (server accepts ^${ed}).`,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,terminalCommandPrefix:this._config.terminalCommandPrefix,telemetry:this._config.otlpLogEmitter?{logs:$A}:void 0}}}_addInitialSubscription(e,t){let r=Vh(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 i=this._stateManager.getSnapshot(t);if(i)return e.subscriptions.set(r.uri,r),this._agentService.addSubscriber(h.parse(r.uri),e.clientId),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),i}_handleVscodeUpgrade(e,t){let r=zh();if(!r){t.send(Du(e,ae.MethodNotFound,"No upgrade supervisor is available for this agent host."));return}wk(r).then(i=>t.send(Ts(e,i)),i=>{this._logService.warn(`[ProtocolServer] vscodeUpgrade signal failed: ${i instanceof Error?i.message:String(i)}`),t.send(ws(e,i))})}_handleReconnect(e,t,r){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let i={clientId:e.clientId,protocolVersion:ed,transport:t,subscriptions:new Map,disposables:r};this._attachConnection(e.clientId,i),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(i,e,a);return{client:i,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 i=[],s=await Promise.all(t.subscriptions.map(async a=>{let l=a.toString(),d=Vh(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`),i.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(h.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)}`),i.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:i}}return{type:"snapshot",snapshots:s.filter(a=>a!==void 0)}}_reconcileActiveClientsAfterReconnect(e){let t=this._clients.get(e.clientId),r=new Set;for(let i of t?.state==="active"?t.connections:[e])for(let s of i.subscriptions.values())s.kind==="state"&&r.add(s.uri);for(let i of this._stateManager.getSessionUris()){let s=this._stateManager.getSessionState(i);if(s&&this._isActiveClient(s,e.clientId))for(let a of s.chats)!r.has(i)&&!r.has(a.resource)&&this._releaseActiveClientForSession(i,e.clientId,a.resource)}}_handleClientDisconnected(e){for(let t of this._stateManager.getSessionUris()){let r=this._stateManager.getSessionState(t),i=r?this._isActiveClient(r,e):!1,s=r?this._hasPendingClientToolCall(r,e):!1;if(i||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 i=r.toolCall,s=i.contributor;s?.kind==="client"&&c6(i.status)&&(yield{toolCall:i,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(i=>i.clientId!==t&&i.tools.some(s=>s.name===r))}_startClientToolCallDisconnectTimeout(e,t,r){let i=this._ensureGraceRecord(e);if(!i)return;i.disconnectTimeouts.deleteAndDispose(r);let s=Date.now()-i.lastSeenAt,a=Math.max(0,xk-s);i.disconnectTimeouts.set(r,qt(()=>{this._releaseActiveClientForSession(t,e,r)},a))}_checkOrphanedClientToolCalls(e,t){let r=this._stateManager.getSessionState(t),i=new Set;for(let{clientId:s}of this._pendingClientToolCalls(r))this._clients.get(s)?.state!=="active"&&i.add(s);for(let s of i)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 we};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(h.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 i of e.connections)if(i!==t&&i.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()-xk*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 i=this._stateManager.getSessionState(r),s=i?.activeTurn;if(!(!i||!s))for(let{toolCall:a,clientId:l}of this._pendingClientToolCalls(i)){if(l!==e)continue;let d=this._hasReplacementActiveClientTool(i,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 i=this._getActiveClient(e);if(!i)return Promise.reject(new Error(`Client ${e} is not connected`));let s=++this._reverseRequestId;return new Promise((a,l)=>{this._pendingReverseRequests.set(s,{client:i,resolve:a,reject:l});let d={jsonrpc:"2.0",id:s,method:t,params:r};i.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,i){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=${i} succeeded`),e.transport.send(Ts(i,d??null))}).catch(d=>{u6(t,r,d)&&this._logService.error(`[ProtocolServer] Request '${t}' failed`,d),e.transport.send(ws(i,d))});return}let a=this._handleExtensionRequest(t,r);if(a){a.then(d=>{e.transport.send(Ts(i,d??null))}).catch(d=>{this._logService.error(`[ProtocolServer] Extension request '${t}' failed`,d),e.transport.send(ws(i,d))});return}let l=p6(r);if(l!==void 0){let d=Pk(r)?r:void 0;this._agentService.handleMcpRequest(l,t,d).then(c=>{e.transport.send(Ts(i,c??null))}).catch(c=>{if(c instanceof Error&&c.message.startsWith("Method not found")){e.transport.send(Du(i,ae.MethodNotFound,c.message));return}this._logService.error(`[ProtocolServer] mcp:// request '${t}' on ${l} failed`,c),e.transport.send(ws(i,c))});return}e.transport.send(Du(i,zi,`Unknown method: ${t}`))}_handleExtensionRequest(e,t){switch(e){case"shutdown":return this._agentService.shutdown();case"getNetworkDiagnosticsInfo":return this._agentService.getNetworkDiagnosticsInfo();case"diagnosticsFetch":return this._agentService.diagnosticsFetch(t.url);default:return}}_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 i=this._getActiveClientFromRecord(r);i&&this._isRelevantToClient(i,e)&&i.transport.send(t)}}_broadcastNotification(e){let{type:t,...r}=e,i={jsonrpc:"2.0",method:t,params:r};for(let s of this._clients.values())this._getActiveClientFromRecord(s)?.transport.send(i)}_broadcastMcpNotification(e){let t={...e.params??{},channel:e.channel},r={jsonrpc:"2.0",method:e.method,params:t};for(let i of this._clients.values())this._getActiveClientFromRecord(i)?.transport.send(r)}_removeSubscription(e,t){let r=Vh(t);if(!r)return;let i=e.subscriptions.get(r.uri);if(i)if(e.subscriptions.delete(r.uri),i.kind==="state"){let s=this._clients.get(e.clientId);if(s&&this._hasSubscriptionInOtherConnection(s,e,i.uri))return;if(this._agentService.unsubscribe(h.parse(i.uri),e.clientId),de(i.uri))this._releaseActiveClientForSession(fe(i.uri),e.clientId,i.uri);else{let a=this._stateManager.getSessionState(i.uri);for(let l of a?.chats??[])this._releaseActiveClientForSession(i.uri,e.clientId,l.resource)}}else i.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(i.uri)}_broadcastOtlpLog(e){let t=BA(e);for(let r of this._clients.values()){let i=this._getActiveClientFromRecord(r);if(i)for(let s of i.subscriptions.values()){if(s.kind!=="otlp-logs"||e.severityNumber<qA(s.level))continue;let a={jsonrpc:"2.0",method:"otlp/exportLogs",params:{channel:s.uri,payload:t}};i.transport.send(a)}}}_isRelevantToClient(e,t){let r=e.subscriptions.get(t.channel);return r?.kind==="state"||r?.kind==="resource-watch"?!0:qi(t.channel)?bk(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()}};Rs=R([C(5,M)],Rs);var f6="ahp",g6=75*1024*1024,m6=5,h6=1024*1024,y6=1024*1024,v6=16*1024,td=class extends w{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,f6);let i=I6(this._options.connectionId).slice(0,64);this._baseName=`ahp-${C6(new Date)}-${i}.jsonl`,this._maxFileSizeBytes=this._options.maxFileSizeBytes??g6,this._maxFiles=this._options.maxFiles??m6,this._currentFile=te(this._directory,this._baseName)}get resource(){return this._currentFile}log(e,t,r){let i={ts:new Date().toISOString(),dir:t,connectionId:this._options.connectionId,transport:this._options.transport,...typeof r=="number"?{byteLength:r}:{}},s={...e,_ahpLog:i},a=S6(s);a.length>y6&&(i.truncated=!0,a=b6(s,v6));let l=`${a}
`;this._pending.push(F.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,i=async()=>{if(t.length===0)return;let s=t.length===1?t[0]:F.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 i(),await this._rotate()):r>0&&r+s.byteLength>h6&&await i(),t.push(s),r+=s.byteLength}await i()}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}}};td=R([C(1,Pe),C(2,M)],td);function aI(o){return F.fromString(o).byteLength}function S6(o){return JSON.stringify(o,Ak)}function b6(o,n){return JSON.stringify(o,function(e,t){let r=Ak.call(this,e,t);return typeof r=="string"&&r.length>n?`${r.slice(0,n)}\u2026[${r.length-n} more chars elided]`:r})}function Ak(o,n){return n&&typeof n=="object"&&n.$mid===1&&L_(n)?h.revive(n).toString():n}function C6(o){return o.toISOString().replace(/[:.]/g,"-")}function I6(o){return o.replace(/[\\/:\*\?"<>\|\s]+/g,"-").replace(/^-+|-+$/g,"")||"connection"}var lI=class extends w{constructor(e,t,r){super();this._ws=e;this._WebSocket=t;this._ahpLogger=r;this._onMessage=this._register(new A);this.onMessage=this._onMessage.event;this._onClose=this._register(new A);this.onClose=this._onClose.event;this._ahpLogger&&this._register(this._ahpLogger),this._ws.on("message",i=>{try{let s=typeof i=="string"?i:i.toString("utf-8"),a=JSON.parse(s);this._ahpLogger?.log(a,"c2s",aI(s)),this._onMessage.fire(a)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:uw,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",aI(t)),this._ws.send(t)}}dispose(){this._ws.close(),super.dispose()}},Mu=class o extends w{constructor(e,t,r,i,s,a){super();this._logService=t;this._ahpLogOptions=r;this._connectionCount=0;this._onConnection=this._register(new A);this.onConnection=this._onConnection.event;this._WebSocket=i.WebSocket;let l=typeof e=="number"?{port:e}:e,d=l.host??"127.0.0.1",c=l.connectionTokenValidate?(u,p)=>{let v=a.parse(u.req.url??"",!0).query[Qy];if(!l.connectionTokenValidate(v)){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 i.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 i.WebSocketServer({port:l.port,host:d,verifyClient:c});let u=this._wss;this.whenListening=new Promise((p,m)=>{u.once("listening",()=>{let v=u.address(),y=!v||typeof v=="string"?`${d}:${l.port}`:`${v.address}:${v.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 lI(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[i,s,a]=await Promise.all([import("ws"),import("http"),import("url")]);return new o(e,t,r,i,s,a)}_createAhpLogger(){if(this._ahpLogOptions)return this._ahpLogOptions.instantiationService.createInstance(td,{logsHome:this._ahpLogOptions.logsHome,connectionId:`agent-host-${++this._connectionCount}-${O()}`,transport:"websocket"})}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};import{homedir as A6,tmpdir as E6}from"os";var Ek=/^([^.]+\..+)[:=](.+)$/,be=class{constructor(n,e,t){this._args=n;this.paths=e;this.productService=t}get appRoot(){return oe(Lt.asFileUri("").fsPath)}get userHome(){return h.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return h.file(j(this.userDataPath,"User"))}get tmpDir(){return h.file(this.paths.tmpDir)}get cacheHome(){return h.file(this.userDataPath)}get stateResource(){return te(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:ne.vscodeUserData})}get userDataSyncHome(){return te(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let n=BP(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=j(this.userDataPath,"logs",n)}return h.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?h.file(j(n,"argv.json")):te(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return h.file(j(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let n=this.args["builtin-extensions-dir"];return n?Fn(n):un(j(Lt.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let n=this.args["extensions-download-dir"];return n?h.file(Fn(n)):h.file(j(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let n=this.args["extensions-dir"];if(n)return Fn(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 h.file(Fn(n));let e=Xe.VSCODE_PORTABLE;return e?h.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)?h.parse(e):h.file(un(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)?h.parse(n):h.file(un(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 _6(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=>!Ek.test(n))}get extensionLogLevel(){let n=[];for(let e of this.args.log||[]){let t=Ek.exec(e);t?.[1]&&t[2]&&n.push([t[1],t[2]])}return n.length?n:void 0}get serviceMachineIdResource(){return te(h.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?h.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}};R([Ce],be.prototype,"appRoot",1),R([Ce],be.prototype,"userHome",1),R([Ce],be.prototype,"userDataPath",1),R([Ce],be.prototype,"appSettingsHome",1),R([Ce],be.prototype,"tmpDir",1),R([Ce],be.prototype,"cacheHome",1),R([Ce],be.prototype,"stateResource",1),R([Ce],be.prototype,"userRoamingDataHome",1),R([Ce],be.prototype,"userDataSyncHome",1),R([Ce],be.prototype,"sync",1),R([Ce],be.prototype,"workspaceStorageHome",1),R([Ce],be.prototype,"localHistoryHome",1),R([Ce],be.prototype,"keyboardLayoutResource",1),R([Ce],be.prototype,"argvResource",1),R([Ce],be.prototype,"isExtensionDevelopment",1),R([Ce],be.prototype,"untitledWorkspacesHome",1),R([Ce],be.prototype,"builtinExtensionsPath",1),R([Ce],be.prototype,"extensionsDownloadLocation",1),R([Ce],be.prototype,"extensionsPath",1),R([Ce],be.prototype,"appSharedDataHome",1),R([Ce],be.prototype,"extensionDevelopmentLocationURI",1),R([Ce],be.prototype,"extensionDevelopmentKind",1),R([Ce],be.prototype,"extensionTestsLocationURI",1),R([Ce],be.prototype,"debugExtensionHost",1),R([Ce],be.prototype,"logLevel",1),R([Ce],be.prototype,"extensionLogLevel",1),R([Ce],be.prototype,"serviceMachineIdResource",1),R([Ce],be.prototype,"disableTelemetry",1),R([Ce],be.prototype,"disableExperiments",1),R([Ce],be.prototype,"disableWorkspaceTrust",1),R([Ce],be.prototype,"useInMemorySecretStorage",1),R([Ce],be.prototype,"policyFile",1),R([Ce],be.prototype,"agentSessionsWorkspace",1);function _6(o,n){return kk(o["inspect-extensions"],o["inspect-brk-extensions"],5870,n,o.debugId,o.extensionEnvironment)}function kk(o,n,e,t,r,i){let a=Number(n||o)||(t?null:e),l=a?!!n:!1,d;if(i)try{d=JSON.parse(i)}catch{}return{port:a,break:l,debugId:r,env:d}}import{homedir as Dk}from"os";import{resolve as T6,isAbsolute as w6,join as nd}from"path";var R6=process.env.VSCODE_CWD||process.cwd();function Mk(o,n){let e=x6(o,n),t=[e];return w6(e)||t.unshift(R6),T6(...t)}function x6(o,n){process.env.VSCODE_DEV&&(n="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return nd(e,"user-data");let t=process.env.VSCODE_APPDATA;if(t)return nd(t,n);let r=o["user-data-dir"];return r||P6(n)}function P6(o){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=nd(e,"AppData","Roaming")}break;case"darwin":n=nd(Dk(),"Library","Application Support");break;case"linux":n=process.env.XDG_CONFIG_HOME||nd(Dk(),".config");break;default:throw new Error("Platform not supported")}return nd(n,o)}var jh=class extends be{constructor(n,e){let t=A6();super(n,{homeDir:t,tmpDir:E6(),userDataDir:Mk(n,e.nameShort)},e)}};import k6 from"minimist";var vUe={o:f(2506,null),e:f(2490,null),t:f(2520,null),m:f(2501,null)};var dI={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:f(2510,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:f(2477,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:f(2472,null)},maximize:{type:"boolean",cat:"o",description:f(2476,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2513,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2504,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2509,null)},help:{type:"boolean",alias:"h",description:f(2492,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(2478,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(2478,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(2478,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(2482,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:f(2502,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:f(2471,null)},remove:{type:"boolean",cat:"o",args:"folder",description:f(2511,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:f(2491,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2503,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2512,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:f(2474,null)},wait:{type:"boolean",cat:"o",alias:"w",description:f(2530,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:f(2498,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:f(2527,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2509,null)},help:{type:"boolean",cat:"o",alias:"h",description:f(2492,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:f(2479,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:f(2489,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"shared-data-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:f(2497,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(2514,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:f(2475,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:f(2496,null)},"pre-release":{type:"boolean",cat:"e",description:f(2495,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:f(2522,null)},"update-extensions":{type:"boolean",cat:"e",description:f(2525,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:f(2488,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:f(2473,null)},version:{type:"boolean",cat:"t",alias:"v",description:f(2529,null)},verbose:{type:"boolean",cat:"t",global:!0,description:f(2528,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:f(2500,null)},status:{type:"boolean",alias:"s",cat:"t",description:f(2515,null)},"prof-startup":{type:"boolean",cat:"t",description:f(2508,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(2485,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:f(2484,null)},sync:{type:"string",cat:"t",description:f(2521,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:f(2494,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:f(2493,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:f(2487,null)},"disable-gpu":{type:"boolean",cat:"t",description:f(2486,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:f(2483,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:f(2499,null)},telemetry:{type:"boolean",cat:"t",description:f(2518,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(2519,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[]"}},D6={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function Kh(o,n,e=D6){let t=o.find((p,m)=>p.length>0&&p[0]!=="-"&&n.hasOwnProperty(p)&&n[p].type==="subcommand"),r={},i=["_"],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[]"?(i.push(p),m.deprecates&&i.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=o.filter(S=>S!==t),v=e.getSubcommandReporter?e.getSubcommandReporter(t):void 0,y=Kh(m,p,v);return{[t]:y,_:[]}}let d=k6(o,{string:i,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 v=u[p];if(m.deprecates)for(let y of m.deprecates)u.hasOwnProperty(y)&&(v||(v=u[y],v&&e.onDeprecatedOption(y,m.deprecationMessage||f(2481,null,p))),delete u[y]);if(typeof v<"u"){if(m.type==="string[]"){if(Array.isArray(v)||(v=[v]),!m.allowEmptyValue){let y=v.filter(S=>S.length>0);y.length!==v.length&&(e.onEmptyValue(p),v=y.length>0?y:void 0)}}else m.type==="string"&&(Array.isArray(v)?(v=v.pop(),e.onMultipleValues(p,v)):!v&&!m.allowEmptyValue&&(e.onEmptyValue(p),v=void 0));c[p]=v,m.deprecationMessage&&e.onDeprecatedOption(p,m.deprecationMessage)}delete u[p]}for(let p in u)e.onUnknownOption(p);return c}var Gh=class extends w{constructor(n,e=[]){super(),this.logger=new df([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 M6(o,n,e,t,r){try{let i=await import("@vscode/spdlog");i.setFlushOn(0);let s=await i.createAsyncRotatingLogger(o,n,e,t);return r?s.clearFormatters():s.setPattern("%Y-%m-%d %H:%M:%S.%e [%l] %v"),s}catch(i){console.error(i)}return null}function Ok(o,n,e){switch(n){case 1:o.trace(e);break;case 2:o.debug(e);break;case 3:o.info(e);break;case 4:o.warn(e);break;case 5:o.error(e);break;case 0:break;default:throw new Error(`Invalid log level ${n}`)}}function Lk(o,n){switch(n){case 1:o.setLevel(0);break;case 2:o.setLevel(1);break;case 3:o.setLevel(2);break;case 4:o.setLevel(3);break;case 5:o.setLevel(4);break;case 0:o.setLevel(6);break;default:throw new Error(`Invalid log level ${n}`)}}var Jh=class extends es{constructor(e,t,r,i,s){super();this.buffer=[];this.setLevel(s),this._loggerCreationPromise=this._createSpdLogLogger(e,t,r,i),this._register(this.onDidChangeLogLevel(a=>{this._logger&&Lk(this._logger,a)}))}async _createSpdLogLogger(e,t,r,i){let s=r?6:1,a=30/s*Qp.MB,l=await M6(e,t,a,s,i);if(l){this._logger=l,Lk(this._logger,this.getLevel());for(let{level:d,message:c}of this.buffer)Ok(this._logger,d,c);this.buffer=[]}}log(e,t){this._logger?Ok(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 Yh=class extends cc{doCreateLogger(n,e,t){return new Jh(O(),n.fsPath,!t?.donotRotate,!!t?.donotUseFormatters,e)}};var Qh=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(i=>this.transformLogger(i,t)),removed:[...r.removed].map(i=>this.transformLogger(i,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=>Yv(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 Yv(t[0])?this.loggerService.setLogLevel(t[0]):this.loggerService.setLogLevel(h.revive(r.transformIncoming(t[0][0])),t[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(i=>this.transformLogger(i,r)))}throw new Error(`Call not found: ${e}`)}transformLogger(n,e){return{...n,resource:e.transformOutgoingURI(n.resource)}}};var Nk=new class{transformIncoming(o){return o}transformOutgoing(o){return o}transformOutgoingURI(o){return o}transformOutgoingScheme(o){return o}};function cI(o){let n=[];typeof o=="number"&&n.push("code/timeOrigin",o);function e(i,s){n.push(i,s?.startTime??Date.now())}function t(){let i=[];for(let s=0;s<n.length;s+=2)i.push({name:n[s],startTime:n[s+1]});return i}function r(i){if(typeof i>"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]===i&&n.splice(s,2)}return{mark:e,getMarks:t,clearMarks:r}}function O6(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?cI():{mark(o,n){performance.mark(o,n)},clearMarks(o){performance.clearMarks(o)},getMarks(){let o=performance.timeOrigin;typeof o!="number"&&(o=(performance.timing.navigationStart||performance.timing.redirectStart||performance.timing.fetchStart)??0);let n=[{name:"code/timeOrigin",startTime:Math.round(o)}];for(let e of performance.getEntriesByType("mark"))n.push({name:e.name,startTime:Math.round(o+e.startTime)});return n}};if(typeof process=="object"){let o=performance?.timeOrigin;return cI(o)}else return console.trace("perf-util loaded in UNKNOWN environment"),cI()}function L6(o){return o.MonacoPerformanceMarks||(o.MonacoPerformanceMarks=O6()),o.MonacoPerformanceMarks}var uI=L6(globalThis),Uk=uI.mark,n2e=uI.clearMarks,r2e=uI.getMarks;async function Xh(o,n,e,t,r,i){let s;try{await N6(o,n,e,t,r,i)}catch(a){s=a}finally{s&&r.errorTransformer&&(s=r.errorTransformer(s)),typeof s<"u"&&e.error(s),e.end()}}async function N6(o,n,e,t,r,i){pI(i);let s=await o.open(n,{create:!1});try{pI(i);let a=0,l=0,d=r&&typeof r.length=="number"?r.length:void 0,c=F.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 o.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=F.alloc(Math.min(r.bufferSize,typeof d=="number"?d:r.bufferSize)),p=0);while(l>0&&(typeof d!="number"||d>0)&&pI(i)&&U6(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 mo(a)}finally{await o.close(s)}}function pI(o){if(o.isCancellationRequested)throw Hu();return!0}function U6(o,n){if(typeof n?.limits?.size=="number"&&o>n.limits.size)throw Me(f(2689,null),"EntryTooLarge");return!0}var Ri=class extends w{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new A);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new A);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new A);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new A);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new A);this._onDidUncorrelatedFilesChange=this._register(new A);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new A);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new qs)}registerProvider(e,t){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);Uk(`code/registerFilesystem/${e}`);let r=new Y;return this.provider.set(e,t),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:t}),r.add(t.onDidChangeFile(i=>{let s=new Yp(i,!this.isPathCaseSensitive(t));this.internalOnDidFilesChange.fire(s),s.hasCorrelation()||this._onDidUncorrelatedFilesChange.fire(s)})),typeof t.onDidWatchError=="function"&&r.add(t.onDidWatchError(i=>this._onDidWatchError.fire(new Error(i)))),r.add(t.onDidChangeCapabilities(()=>this._onDidChangeFileSystemProviderCapabilities.fire({provider:t,scheme:e}))),N(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:t}),this.provider.delete(e),Gt(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 rr.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 ks.map(this.provider,([e,t])=>({scheme:e,capabilities:t.capabilities}))}async withProvider(e){if(!B_(e))throw new lt(f(2678,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let t=this.provider.get(e.scheme);if(!t){let r=new Cr;throw r.message=f(2680,null,e.toString()),r}return t}async withReadProvider(e){let t=await this.withProvider(e);if(go(t)||xn(t)||Xp(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(go(t)||xn(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(2675,null,this.resourceForError(e)),1):mo(r)}}async doResolveFile(e,t){let r=await this.withProvider(e),i=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=Er.forUris(()=>!i),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,i,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:qv({mtime:r.mtime,size:r.size}),children:void 0};if(d.isDirectory&&a(d,i)){try{let c=await e.readdir(t),u=await rr.settled(c.map(async([p,m])=>{try{let v=l.joinPath(t,p),y=s?await e.stat(v):{type:m};return await this.toFileStat(e,v,y,c.length,s,a)}catch(v){return this.logService.trace(v),null}}));d.children=Oo(u)}catch(c){this.logService.trace(c),d.children=[]}return d}return d}async resolveAll(e){return rr.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(jw(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(2671,null,this.resourceForError(e)),3,t)}async createFile(e,t=F.fromString(""),r){await this.doValidateCreateFile(e,r);let i=await this.writeFile(e,t);return this._onDidRunOperation.fire(new po(e,0,i)),i}async writeFile(e,t,r){let i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),{providerExtUri:s}=this.getExtUri(i),a=r;if(Wv(i)&&!a?.atomic){let l=i.enforceAtomicWriteFile?.(e);l&&(a={...r,atomic:l})}try{let{stat:l,buffer:d}=await this.validateWriteFile(i,e,t,a);l||await this.mkdirp(i,s.dirname(e)),d||(d=await this.peekBufferForWriting(i,t)),!go(i)||xn(i)&&d instanceof F||xn(i)&&Wv(i)&&a?.atomic?await this.doWriteUnbuffered(i,e,a,d):await this.doWriteBuffered(i,e,a,d instanceof F?rT(d):d),this._onDidRunOperation.fire(new po(e,4))}catch(l){throw new lt(f(2670,null,this.resourceForError(e),mo(l).toString()),ho(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,t){let r;if(xn(e)&&!(t instanceof F))if(Cd(t)){let i=await X_(t,3);i.ended?r=F.concat(i.buffer):r=i}else r=Q_(t,i=>F.concat(i),3);else r=t;return r}async validateWriteFile(e,t,r,i){let s=!!i?.unlock;if(s&&!(e.capabilities&8192))throw new Error(f(2688,null,this.resourceForError(t)));if(i?.append&&!zw(e))throw new lt(f(2667,null,this.resourceForError(t)),6);if(!!i?.atomic){if(!(e.capabilities&32768))throw new Error(f(2686,null,this.resourceForError(t)));if(!(e.capabilities&2))throw new Error(f(2687,null,this.resourceForError(t)));if(s)throw new Error(f(2685,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(2673,null,this.resourceForError(t)),0,i);this.throwIfFileIsReadonly(t,l);let d;if(typeof i?.mtime=="number"&&typeof i.etag=="string"&&i.etag!==ef&&typeof l.mtime=="number"&&typeof l.size=="number"&&i.mtime<l.mtime&&i.etag!==qv({mtime:i.mtime,size:l.size})){if(d=await this.peekBufferForWriting(e,r),d instanceof F&&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(2674,null),3,i)}return{stat:l,buffer:d}}async readFile(e,t,r){let i=await this.withReadProvider(e);return t?.atomic?this.doReadFileAtomic(i,e,t,r):this.doReadFile(i,e,t,r)}async doReadFileAtomic(e,t,r,i){return new Promise((s,a)=>{this.writeQueue.queueFor(t,async()=>{try{let l=await this.doReadFile(e,t,r,i);s(l)}catch(l){a(l)}},this.getExtUri(e).providerExtUri)})}async doReadFile(e,t,r,i){let s=await this.doReadFileStream(e,t,{...r,preferUnbuffered:!0},i);return{...s,value:await wr(s.value)}}async readFileStream(e,t,r){let i=await this.withReadProvider(e);return this.doReadFileStream(i,e,t,r)}async doReadFileStream(e,t,r,i){let s=new Ze(i),a=r;Zp(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!==ef&&await l,a?.atomic&&Zp(e)||!(go(e)||Xp(e))||xn(e)&&a?.preferUnbuffered?d=this.readFileUnbuffered(e,t,a):Xp(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 hp(d),this.restoreReadError(c,t,a)}}restoreReadError(e,t,r){let i=f(2668,null,this.resourceForError(t),mo(e).toString());return e instanceof ua?new ua(i,e.stat,r):e instanceof ca?new ca(i,e.fileOperationResult,e.size,e.options):new lt(i,ho(e),r)}readFileStreamed(e,t,r,i=Object.create(null)){let s=e.readFileStream(t,i,r);return vp(s,{data:a=>a instanceof F?a:F.wrap(a),error:a=>this.restoreReadError(a,t,i)},a=>F.concat(a))}readFileBuffered(e,t,r,i=Object.create(null)){let s=_d();return Xh(e,t,s,a=>a,{...i,bufferSize:this.BUFFER_SIZE,errorTransformer:a=>this.restoreReadError(a,t,i)},r),s}readFileUnbuffered(e,t,r){let i=ao(s=>F.concat(s));return(async()=>{try{let s;r?.atomic&&Zp(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),i.end(F.wrap(s))}catch(s){i.error(s),i.end()}})(),i}async validateReadFile(e,t){let r=await this.resolve(e,{resolveMetadata:!0});if(r.isDirectory)throw new lt(f(2672,null,this.resourceForError(e)),0,t);if(typeof t?.etag=="string"&&t.etag!==ef&&t.etag===r.etag)throw new ua(f(2676,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 ca(f(2677,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,i){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,i)}catch(s){return s}return!0}async move(e,t,r){let i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(e),e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(i,e,s,t,"move",!!r),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new po(e,a==="move"?2:3,l)),l}async copy(e,t,r){let i=await this.withReadProvider(e),s=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t),a=await this.doMoveCopy(i,e,s,t,"copy",!!r),l=await this.resolve(t,{resolveMetadata:!0});return this._onDidRunOperation.fire(new po(e,a==="copy"?3:2,l)),l}async doMoveCopy(e,t,r,i,s,a){if(t.toString()===i.toString())return s;let{exists:l,isSameResourceWithDifferentPathCase:d}=await this.doValidateMoveCopy(e,t,r,i,s,a);if(l&&!d&&a&&await this.del(i,{recursive:!0}),await this.mkdirp(r,this.getExtUri(r).providerExtUri.dirname(i)),s==="copy"){if(e===r&&$v(e))await e.copy(t,i,{overwrite:a});else{let c=await this.resolve(t);c.isDirectory?await this.doCopyFolder(e,c,r,i):await this.doCopyFile(e,t,r,i)}return s}else return e===r?(await e.rename(t,i,{overwrite:a}),s):(await this.doMoveCopy(e,t,r,i,"copy",a),await this.del(t,{recursive:!0}),"copy")}async doCopyFile(e,t,r,i){if(go(e)&&go(r))return this.doPipeBuffered(e,t,r,i);if(go(e)&&xn(r))return this.doPipeBufferedToUnbuffered(e,t,r,i);if(xn(e)&&go(r))return this.doPipeUnbufferedToBuffered(e,t,r,i);if(xn(e)&&xn(r))return this.doPipeUnbuffered(e,t,r,i)}async doCopyFolder(e,t,r,i){await r.mkdir(i),Array.isArray(t.children)&&await rr.settled(t.children.map(async s=>{let a=this.getExtUri(r).providerExtUri.joinPath(i,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,i,s,a){let l=!1;if(e===r){let{providerExtUri:c,isPathCaseSensitive:u}=this.getExtUri(e);if(u||(l=c.isEqual(t,i)),l&&s==="copy")throw new Error(f(2681,null,this.resourceForError(t),this.resourceForError(i)));if(!l&&c.isEqualOrParent(i,t))throw new Error(f(2682,null,this.resourceForError(t),this.resourceForError(i)))}let d=await this.exists(i);if(d&&!l){if(!a)throw new lt(f(2683,null,this.resourceForError(t),this.resourceForError(i)),4);if(e===r){let{providerExtUri:c}=this.getExtUri(e);if(c.isEqualOrParent(t,i))throw new Error(f(2684,null,this.resourceForError(t),this.resourceForError(i)))}}return{exists:d,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let t=this.isPathCaseSensitive(e);return{providerExtUri:t?me:Zy,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 po(e,0,r)),r}async mkdirp(e,t){let r=[],{providerExtUri:i}=this.getExtUri(e);for(;!i.isEqual(t,i.dirname(t));)try{if(((await e.stat(t)).type&2)===0)throw new Error(f(2679,null,this.resourceForError(t)));break}catch(s){if(fn(s)!=="EntryNotFound")throw s;r.push(i.basename(t)),t=i.dirname(t)}for(let s=r.length-1;s>=0;s--){t=i.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),i=!!t?.useTrash;if(i&&!(r.capabilities&4096))throw new Error(f(2666,null,this.resourceForError(e)));let s=t?.atomic;if(s&&!(r.capabilities&65536))throw new Error(f(2662,null,this.resourceForError(e)));if(i&&s)throw new Error(f(2665,null,this.resourceForError(e)));let a;try{a=await r.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new lt(f(2664,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(2663,null,this.resourceForError(e)))}return r}async del(e,t){let r=await this.doValidateDelete(e,t),i=t;if(Kw(r)&&!i?.atomic){let d=r.enforceAtomicDelete?.(e);d&&(i={...t,atomic:d})}let s=!!i?.useTrash,a=!!i?.recursive,l=i?.atomic??!1;await r.delete(e,{recursive:a,useTrash:s,atomic:l}),this._onDidRunOperation.fire(new po(e,1))}async cloneFile(e,t){let r=await this.withProvider(e),i=this.throwIfFileSystemIsReadonly(await this.withWriteProvider(t),t);if(!(r===i&&this.getExtUri(r).providerExtUri.isEqual(e,t)))return r===i&&Vw(r)?r.cloneFile(e,t):(await this.mkdirp(i,this.getExtUri(i).providerExtUri.dirname(t)),r===i&&$v(r)?this.writeQueue.queueFor(e,()=>r.copy(e,t,{overwrite:!0}),this.getExtUri(r).providerExtUri):this.writeQueue.queueFor(e,()=>this.doCopyFile(r,e,i,t),this.getExtUri(r).providerExtUri))}static{this.WATCHER_CORRELATION_IDS=0}createWatcher(e,t){return this.watch(e,{...t,correlationId:Ri.WATCHER_CORRELATION_IDS++})}watch(e,t={recursive:!1,excludes:[]}){let r=new Y,i=!1,s=()=>{i=!0};r.add(N(()=>s())),(async()=>{try{let l=await this.doWatch(e,t);i?Gt(l):s=()=>Gt(l)}catch(l){this.logService.error(l)}})();let a=t.correlationId;if(typeof a=="number"){let l=r.add(new A);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),i=gn([this.getExtUri(r).providerExtUri.getComparisonKey(e),t]),s=this.activeWatchers.get(i);return s||(s={count:0,disposable:r.watch(e,t)},this.activeWatchers.set(i,s)),s.count+=1,N(()=>{s&&(s.count--,s.count===0&&(Gt(s.disposable),this.activeWatchers.delete(i)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)Gt(e.disposable);this.activeWatchers.clear()}async doWriteBuffered(e,t,r,i){return this.writeQueue.queueFor(t,async()=>{let s=await e.open(t,{create:!0,unlock:r?.unlock??!1,append:r?.append??!1});try{Cd(i)||mp(i)?await this.doWriteStreamBufferedQueued(e,s,i):await this.doWriteReadableBufferedQueued(e,s,i)}catch(a){throw mo(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,t,r){let i=0,s;if(mp(r)){if(r.buffer.length>0){let a=F.concat(r.buffer);await this.doWriteBuffer(e,t,a,a.byteLength,i,0),i+=a.byteLength}if(r.ended)return;s=r.stream}else s=r;return new Promise((a,l)=>{yp(s,{onData:async d=>{s.pause();try{await this.doWriteBuffer(e,t,d,d.byteLength,i,0)}catch(c){return l(c)}i+=d.byteLength,setTimeout(()=>s.resume())},onError:d=>l(d),onEnd:()=>a()})})}async doWriteReadableBufferedQueued(e,t,r){let i=0,s;for(;(s=r.read())!==null;)await this.doWriteBuffer(e,t,s,s.byteLength,i,0),i+=s.byteLength}async doWriteBuffer(e,t,r,i,s,a){let l=0;for(;l<i;){let d=await e.write(t,s+l,r.buffer,a+l,i-l);l+=d}}async doWriteUnbuffered(e,t,r,i){return this.writeQueue.queueFor(t,()=>this.doWriteUnbufferedQueued(e,t,r,i),this.getExtUri(e).providerExtUri)}async doWriteUnbufferedQueued(e,t,r,i){let s;i instanceof F?s=i:Cd(i)?s=await wr(i):mp(i)?s=await oT(i):s=nT(i),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,i){return this.writeQueue.queueFor(i,()=>this.doPipeBufferedQueued(e,t,r,i),this.getExtUri(r).providerExtUri)}async doPipeBufferedQueued(e,t,r,i){let s,a;try{s=await e.open(t,{create:!1}),a=await r.open(i,{create:!0,unlock:!1});let l=F.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 mo(l)}finally{await rr.settled([typeof s=="number"?e.close(s):Promise.resolve(),typeof a=="number"?r.close(a):Promise.resolve()])}}async doPipeUnbuffered(e,t,r,i){return this.writeQueue.queueFor(i,()=>this.doPipeUnbufferedQueued(e,t,r,i),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedQueued(e,t,r,i){return r.writeFile(i,await e.readFile(t),{create:!0,overwrite:!0,unlock:!1,atomic:!1})}async doPipeUnbufferedToBuffered(e,t,r,i){return this.writeQueue.queueFor(i,()=>this.doPipeUnbufferedToBufferedQueued(e,t,r,i),this.getExtUri(r).providerExtUri)}async doPipeUnbufferedToBufferedQueued(e,t,r,i){let s=await r.open(i,{create:!0,unlock:!1});try{let a=await e.readFile(t);await this.doWriteBuffer(r,s,F.wrap(a),a.byteLength,0,0)}catch(a){throw mo(a)}finally{await r.close(s)}}async doPipeBufferedToUnbuffered(e,t,r,i){let s=await wr(this.readFileBuffered(e,t,Re.None));await this.doWriteUnbuffered(r,i,void 0,s)}throwIfFileSystemIsReadonly(e,t){if(e.capabilities&2048)throw new lt(f(2669,null,this.resourceForError(t)),6);return e}throwIfFileIsReadonly(e,t){if((t.permissions??0)&1)throw new lt(f(2669,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===ne.file?e.fsPath:e.toString(!0)}};Ri=R([C(0,M)],Ri);import{constants as hI,promises as xs}from"fs";function ny(o){return typeof o.correlationId=="number"}function Fk(o){return o.recursive===!0}var Zh=class o extends w{constructor(e,t,r,i){super();this.onFileChanges=e;this.onLogMessage=t;this.verboseLogging=r;this.options=i;this.watcherDisposables=this._register(new Dt);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new Y;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<o.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()}},ey=class extends Zh{constructor(n,e,t){super(n,e,t,{type:"node.js",restartOnError:!1})}},ty=class extends Zh{constructor(n,e,t){super(n,e,t,{type:"universal",restartOnError:!0})}};function gI(o){return o.map(n=>({type:n.type,resource:h.revive(n.resource),cId:n.cId}))}function Hk(o){let n=new fI;for(let e of o)n.processEvent(e);return n.coalesce()}function F6(o,n){return typeof n=="string"&&!n.startsWith(qa)&&!Wt(n)?{base:o,pattern:n}:n}function mI(o,n,e){let t=[];for(let r of n)t.push(Nr(F6(o,r),{ignoreCase:e}));return t}var fI=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,i=n.type;e.resource.fsPath!==n.resource.fsPath&&(n.type===2||n.type===1)?t=!0:r===1&&i===2?(this.mapPathToChange.delete(this.toKey(n)),this.coalesced.delete(e)):r===2&&i===1?e.type=0:r===1&&i===0||(e.type=i)}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=>Gw(t.resource.fsPath,r,!Oe))?!1:(e.push(t.resource.fsPath),!0)).concat(n)}};function $k(o,n){if(typeof n=="number")switch(o.type){case 1:return(n&4)===0;case 2:return(n&8)===0;case 0:return(n&2)===0}return!1}function Wk(o){if(typeof o=="number"){let n=[];return o&4&&n.push("Added"),o&8&&n.push("Deleted"),o&2&&n.push("Updated"),n.length===0?"<all>":`[${n.join(", ")}]`}return"<none>"}var ry=class extends w{constructor(e,t){super();this.logService=e;this.options=t;this._onDidChangeFile=this._register(new A);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new A);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new Ui(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new Ui(this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)))}watch(e,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),i=by(this.universalWatchRequests,r);return this.refreshUniversalWatchers(),N(()=>{i(),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(Fk(r)){let i=this.options?.watcher?.recursive?.usePolling;i===!0?r.pollingInterval=this.options?.watcher?.recursive?.pollingInterval??5e3:Array.isArray(i)&&i.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(gI(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},i=by(this.nonRecursiveWatchRequests,r);return this.refreshNonRecursiveWatchers(),N(()=>{i(),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(gI(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 un(e.fsPath)}toWatchPath(e){let t=this.toFilePath(e);return E_(t)}};var oy=class extends ty{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){let e=n.add(new wp(Lt.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)`))),Js.toService(aT(e.getChannel("watcher")))}};import{watchFile as H6,unwatchFile as $6}from"fs";var iy=class extends w{constructor(){super();this._onDidChangeFile=this._register(new A);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new A);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new A);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new we);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new Ui(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 ny(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:gn(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,i]of[...this.nonCorrelatedWatchRequests,...this.correlatedWatchRequests])this.suspendedWatchRequests.has(r)||t.push(i);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 Y;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,(i,s)=>{t.isDisposed||(i?this.monitorSuspendedWatchRequest(e,t):s?.type===1&&this.onMonitoredPathAdded(e))});return r?(t.add(r),!0):!1}doMonitorWithNodeJS(e,t){let r=!1,i=(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{H6(e.path,{persistent:!1,interval:this.suspendedWatchRequestPollingInterval},i)}catch(s){this.warn(`fs.watchFile() failed with error ${s} on path ${e.path} (correlationId: ${e.correlationId})`)}t.add(N(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{$6(e.path,i)}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:h.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: ${Wk(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as W6,promises as q6}from"fs";var sy=class o extends w{constructor(e,t,r,i,s,a){super();this.request=e;this.recursiveWatcher=t;this.onDidFilesChange=r;this.onDidWatchFail=i;this.onLogMessage=s;this.verboseLogging=a;this.throttledFileChangesEmitter=this._register(new Bs({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new up(e=>this.handleFileChanges(e),o.FILE_CHANGES_HANDLER_DELAY));this.cts=new Ze;this.realPath=new Be(async()=>{let e=this.request.path;try{e=await Ue.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=mI(this.request.path,this.request.excludes,l),this.includes=this.request.includes?mI(this.request.path,this.request.includes,l):void 0,this.filter=ny(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 q6.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;await Ry(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 Y;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=h.file(this.request.path),i=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{t.isDisposed||(s?await Ry(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 i?(t.add(i),!0):!1}async doWatchWithNodeJS(e,t){let r=await this.realPath.value;if(this.cts.token.isCancellationRequested)return;if(dt&&ro(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 i=new Ze(this.cts.token);t.add(N(()=>i.dispose(!0)));let s=new Y;t.add(s);try{let a=h.file(this.request.path),l=Te(r),d=W6(r);s.add(N(()=>{d.removeAllListeners(),d.close()})),this.trace(`Started watching: '${r}'`);let c=new Set;if(e)try{for(let p of await Ue.readdir(r))c.add(p)}catch(p){this.error(p)}if(i.token.isCancellationRequested)return;let u=new Map;s.add(N(()=>{for(let[,p]of u)p.dispose();u.clear()})),d.on("error",(p,m)=>{i.token.isCancellationRequested||(this.error(`Failed to watch ${r} for changes using fs.watch() (${p}, ${m})`),this.notifyWatchFailed())}),d.on("change",(p,m)=>{if(i.token.isCancellationRequested)return;this.verboseLogging&&this.traceWithCorrelation(`[raw] ["${p}"] ${m}`);let v="";if(m&&(v=m.toString(),dt&&(v=Ed(v))),!(!v||p!=="change"&&p!=="rename"))if(e)if(p==="rename"){u.get(v)?.dispose();let y=setTimeout(async()=>{if(u.delete(v),Ws(v,l,!Oe)&&!await Ue.exists(r)){this.onWatchedPathDeleted(a);return}if(i.token.isCancellationRequested)return;let S=await this.existsChildStrictCase(j(r,v));if(i.token.isCancellationRequested)return;let b;S?c.has(v)?b=0:(b=1,c.add(v)):(c.delete(v),b=2),this.onFileChange({resource:te(a,v),type:b,cId:this.request.correlationId})},o.FILE_DELETE_HANDLER_DELAY);u.set(v,N(()=>clearTimeout(y)))}else{let y;c.has(v)?y=0:(y=1,c.add(v)),this.onFileChange({resource:te(a,v),type:y,cId:this.request.correlationId})}else if(p==="rename"||!Ws(v,l,!Oe)){let y=setTimeout(async()=>{let S=await Ue.exists(r);i.token.isCancellationRequested||(S?(this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0),s.add(await this.doWatch(!1))):this.onWatchedPathDeleted(a))},o.FILE_DELETE_HANDLER_DELAY);s.clear(),s.add(N(()=>clearTimeout(y)))}else this.onFileChange({resource:a,type:0,cId:this.request.correlationId},!0)})}catch(a){if(i.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=Hk(e),r=[];for(let s of t){if($k(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 Ue.exists(e);try{let t=Te(e);return(await Ue.readdir(oe(e))).some(i=>i===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 ay=class extends iy{constructor(e){super();this.recursiveWatcher=e;this.onDidError=ee.None;this._watchers=new Map;this.worker=this._register(new Dt)}get watchers(){return this._watchers.values()}async doWatch(e){e=this.removeDuplicateRequests(e);let t=[],r=new Set(Array.from(this.watchers));for(let i of e){let s=this._watchers.get(this.requestToWatcherKey(i));s&&eb(s.request.excludes,i.excludes)&&eb(s.request.includes,i.includes)?r.delete(s):t.push(i)}t.length&&this.trace(`Request to start watching: ${t.map(i=>this.requestToString(i)).join(",")}`),r.size&&this.trace(`Request to stop watching: ${Array.from(r).map(i=>this.requestToString(i.request)).join(",")}`),this.worker.clear();for(let i of r)this.stopWatching(i);this.createWatchWorker().work(t)}createWatchWorker(){return this.worker.value=new Bs({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 sy(e,this.recursiveWatcher,i=>this._onDidChangeFile.fire(i),()=>this._onDidWatchFail.fire(e),i=>this._onDidLogMessage.fire(i),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 i=t.get(r.correlationId);i||(i=new Map,t.set(r.correlationId,i));let s=this.pathToWatcherKey(r.path);i.has(s)&&this.trace(`ignoring a request for watching who's path is already watched: ${this.requestToString(r)}`),i.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 ly=class extends ey{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){return n.add(new ay(void 0))}};var dy=class o extends ry{constructor(){super(...arguments);this.onDidChangeCapabilities=ee.None;this.resourceLocks=new qe(e=>nt.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)),i;return(t.mode&128)===0&&(i=2),(t.mode&hI.S_IXUSR||t.mode&hI.S_IXGRP||t.mode&hI.S_IXOTH)&&(i=(i??0)|4),{type:this.toType(t,r),ctime:t.birthtime.getTime(),mtime:t.mtime.getTime(),size:t.size,permissions:i}}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 Ue.realpath(t)}async readdir(e){try{let t=await Ue.readdir(this.toFilePath(e),{withFileTypes:!0}),r=[];return await Promise.all(t.map(async i=>{try{let s;i.isSymbolicLink()?s=(await this.stat(te(e,i.name))).type:s=this.toType(i),r.push([i.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 i=new dp;return this.resourceLocks.set(e,i),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${t})`),N(()=>{this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - resource lock dispose() (${t})`),this.resourceLocks.get(e)===i&&(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})`),i.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 i=this.toFilePath(e);return await xs.readFile(i)}catch(i){throw this.toFileSystemProviderError(i)}finally{r?.dispose()}}traceLock(e){o.TRACE_LOG_RESOURCE_LOCKS&&this.logService.trace(e)}readFileStream(e,t,r){let i=ao(s=>F.concat(s.map(a=>F.wrap(a))).buffer);return Xh(this,e,i,s=>s.buffer,{...t,bufferSize:256*1024},r),i}async writeFile(e,t,r){return r?.atomic!==!1&&r?.atomic?.postfix&&await this.canWriteFileAtomic(e)?this.doWriteFileAtomic(e,te(Tn(e),`${ve(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,i){let s=new Y;try{s.add(await this.createResourceLock(e)),s.add(await this.createResourceLock(t)),await this.doWriteFile(t,r,{...i,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,i){let s;try{let a=this.toFilePath(e);if(!r.create||!r.overwrite){if(await Ue.exists(a)){if(!r.overwrite)throw Me(f(2692,null),"EntryExists")}else if(!r.create)throw Me(f(2695,null),"EntryNotFound")}s=await this.open(e,{create:!0,append:r.append,unlock:r.unlock},i),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){o.canFlush=e}async open(e,t,r){let i=this.toFilePath(e),s;fo(t)&&!r&&(s=await this.createResourceLock(e));let a;try{if(fo(t)&&t.unlock)try{let{stat:l}=await en.stat(i);l.mode&128||await xs.chmod(i,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(Q&&fo(t)&&!t.append)try{a=await Ue.open(i,"r+"),await Ue.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await Ue.close(a)}catch(d){this.logService.trace(d)}a=void 0}}typeof a!="number"&&(a=await Ue.open(i,fo(t)?t.append?"a":"w":"r"))}catch(l){throw s?.dispose(),fo(t)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),fo(t)&&this.writeHandles.set(a,e),s){let l=this.mapHandleToLock.get(a);this.traceLock(`[Disk FileSystemProvider]: open() - storing lock for handle ${a} (${i})`),this.mapHandleToLock.set(a,s),l&&(this.traceLock(`[Disk FileSystemProvider]: open() - disposing a previous lock that was still stored on same handle ${a} (${i})`),l.dispose())}return a}async close(e){let t=this.mapHandleToLock.get(e);try{if(this.mapHandleToPos.delete(e),this.writeHandles.delete(e)&&o.canFlush)try{await Ue.fdatasync(e)}catch(r){o.configureFlushOnWrite(!1),this.logService.error(r)}return await Ue.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,i,s){let a=this.normalizePos(e,t),l=null;try{l=(await Ue.read(e,r,i,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 i=this.mapHandleToPos.get(e);typeof i=="number"&&(typeof t=="number"||(typeof r=="number"?this.mapHandleToPos.set(e,i+r):this.mapHandleToPos.delete(e)))}async write(e,t,r,i,s){return J_(()=>this.doWrite(e,t,r,i,s),100,3)}async doWrite(e,t,r,i,s){let a=this.normalizePos(e,t),l=null;try{l=(await Ue.write(e,r,i,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 xs.mkdir(this.toFilePath(e))}catch(t){throw this.toFileSystemProviderError(t)}}async delete(e,t){try{let r=this.toFilePath(e);if(t.recursive){let i;t?.atomic!==!1&&t.atomic.postfix&&(i=j(oe(r),`${Te(r)}${t.atomic.postfix}`)),await Ue.rm(r,1,i)}else try{await xs.unlink(r)}catch(i){if(i.code==="EPERM"||i.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await en.stat(r);s=a.isDirectory()&&!l}catch{}if(s)await xs.rmdir(r);else throw i}else throw i}}catch(r){throw this.toFileSystemProviderError(r)}}async rename(e,t,r){let i=this.toFilePath(e),s=this.toFilePath(t);if(i!==s)try{await this.validateMoveCopy(e,t,"move",r.overwrite),await Ue.rename(i,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2696,null,Te(i),Te(oe(s)),a.toString()))),this.toFileSystemProviderError(a)}}async copy(e,t,r){let i=this.toFilePath(e),s=this.toFilePath(t);if(i!==s)try{await this.validateMoveCopy(e,t,"copy",r.overwrite),await Ue.copy(i,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2690,null,Te(i),Te(oe(s)),a.toString()))),this.toFileSystemProviderError(a)}}async validateMoveCopy(e,t,r,i){let s=this.toFilePath(e),a=this.toFilePath(t),l=!1;if(this.capabilities&1024||(l=Ws(s,a,!0)),l){if(r==="copy")throw Me(f(2691,null),"EntryExists");if(r==="move")return}let c=await this.statIgnoreError(e);if(!c)throw Me(f(2694,null),"EntryNotFound");let u=await this.statIgnoreError(t);if(u){if(!i)throw Me(f(2693,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 i=this.toFilePath(e),s=this.toFilePath(t),a=!!(this.capabilities&1024);if(Ws(i,s,!a))return;let l=new Y;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(t)),r&&await xs.mkdir(oe(s),{recursive:!0}),await xs.copyFile(i,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 oy(i=>e(i),i=>t(i),r)}createNonRecursiveWatcher(e,t,r){return new ly(i=>e(i),i=>t(i),r)}toFileSystemProviderError(e){if(e instanceof da)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 Me(t,r)}async toFileSystemProviderWriteError(e,t){let r=this.toFileSystemProviderError(t);if(e&&r.code==="NoPermissions")try{let{stat:i}=await en.stat(this.toFilePath(e));i.mode&128||(r=Me(t,"EntryWriteLocked"))}catch(i){this.logService.trace(i)}return r}};import{parse as Vk}from"url";import{spawn as B6}from"child_process";import U5e from"assert";function yI(o){return o.VSCODE_CLI==="1"}var vI;async function qk(o,n,e,t){return e["force-disable-user-env"]?(n.trace("resolveShellEnv(): skipped (--force-disable-user-env)"),{}):Q?(n.trace("resolveShellEnv(): skipped (Windows)"),{}):yI(t)&&!e["force-user-env"]?(n.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)"),{}):(yI(t)?n.trace("resolveShellEnv(): running (--force-user-env)"):n.trace("resolveShellEnv(): running (macOS/Linux)"),vI||(vI=rr.withAsyncBody(async(r,i)=>{let s=new Ze,a=1e4,l=o.getValue("application.shellEnvironmentResolutionTimeout");typeof l=="number"&&(a=xA(l,1,120)*1e3);let d=setTimeout(()=>{s.dispose(!0),i(new Error(f(2823,null)))},a);try{r(await z6(n,s.token))}catch(c){!Cn(c)&&!s.token.isCancellationRequested?i(new Error(f(2821,null,De(c)))):r({})}finally{clearTimeout(d),s.dispose()}})),vI)}async function z6(o,n){let e=process.env.ELECTRON_RUN_AS_NODE;o.trace("getUnixShellEnvironment#runAsNode",e);let t=process.env.ELECTRON_NO_ATTACH_CONSOLE;o.trace("getUnixShellEnvironment#noAttach",t);let r=O().replace(/-/g,"").substr(0,12),i=new RegExp(r+"({.*})"+r),s={...process.env,ELECTRON_RUN_AS_NODE:"1",ELECTRON_NO_ATTACH_CONSOLE:"1",VSCODE_RESOLVING_ENVIRONMENT:"1"};o.trace("getUnixShellEnvironment#env",s);let a=await vf(Mt,s);return o.trace("getUnixShellEnvironment#shell",a),new Promise((l,d)=>{if(n.isCancellationRequested)return d(new K);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"]),o.trace("getUnixShellEnvironment#spawn",JSON.stringify(p),u);let v=B6(a,[...p,u],{detached:!0,stdio:["ignore","pipe","pipe"],env:s});n.onCancellationRequested(()=>(v.kill(),d(new K))),v.on("error",b=>{o.error("getUnixShellEnvironment#errorChildProcess",De(b)),d(b)});let y=[];v.stdout.on("data",b=>y.push(b));let S=[];v.stderr.on("data",b=>S.push(b)),v.on("close",(b,I)=>{let _=Buffer.concat(y).toString("utf8");o.trace("getUnixShellEnvironment#raw",_);let T=Buffer.concat(S).toString("utf8");if(T.trim()&&o.trace("getUnixShellEnvironment#stderr",T),b||I)return d(new Error(f(2822,null,b,I)));let P=i.exec(_),X=P?P[1]:"{}";try{let k=JSON.parse(X);e?k.ELECTRON_RUN_AS_NODE=e:delete k.ELECTRON_RUN_AS_NODE,t?k.ELECTRON_NO_ATTACH_CONSOLE=t:delete k.ELECTRON_NO_ATTACH_CONSOLE,delete k.VSCODE_RESOLVING_ENVIRONMENT,delete k.XDG_RUNTIME_DIR,o.trace("getUnixShellEnvironment#result",k),l(k)}catch(k){o.error("getUnixShellEnvironment#errorCaught",De(k)),d(k)}})})}import{parse as Bk}from"url";function V6(o,n){return o.protocol==="http:"?n.HTTP_PROXY||n.http_proxy||null:o.protocol==="https:"&&(n.HTTPS_PROXY||n.https_proxy||n.HTTP_PROXY||n.http_proxy)||null}async function zk(o,n,e={}){let t=Bk(o),r=e.proxyUrl||V6(t,n);if(!r)return null;let i=Bk(r);if(!/^https?:$/.test(i.protocol||""))return null;let s={host:i.hostname||"",port:(i.port?+i.port:0)||(i.protocol==="https"?443:80),auth:i.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 j6}from"zlib";var K6=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),G6=/^(GET|HEAD|OPTIONS)$/i;function J6(o){if(o instanceof Error){let n=o.code;return!!n&&K6.has(n)}return!1}var rd=class extends lg{constructor(e,t,r,i){super(i);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:i}=this,s;try{s=await qk(this.configurationService,this.logService,this.environmentService.args,process.env)}catch(d){this.shellEnvErrorLogged||(this.shellEnvErrorLogged=!0,this.logService.error("resolving shell environment failed",Zn(d)))}let a={...process.env,...s},l=e.agent?e.agent:await zk(e.url||"",a,{proxyUrl:r,strictSSL:i});return e.agent=l,e.strictSSL=i,this.authorization&&(e.headers={...e.headers||{},"Proxy-Authorization":this.authorization}),this.logAndRequest(e,()=>jk(e,t))}async resolveProxy(e){}async lookupAuthorization(e){}async lookupKerberosAuthorization(e){try{let t=this.getConfigValue("http.proxyKerberosServicePrincipal");return"Negotiate "+await Y6(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",Fa),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}};rd=R([C(1,Bn),C(2,bt),C(3,M)],rd);async function Y6(o,n,e,t){let r=await import("kerberos"),i=r.default||r,s=new URL(o),a=n||(process.platform==="win32"?`HTTP/${s.hostname}`:`HTTP@${s.hostname}`);return e.debug(`${t} Kerberos authentication lookup`,`proxyURL:${s}`,`spn:${a}`),(await i.initializeClient(a)).step("")}async function Q6(o){return(Vk(o.url).protocol==="https:"?await import("https"):await import("http")).request}async function jk(o,n){let t,r=G6.test(o.type||"GET");for(let i=1;i<=3;i++)try{return await X6(o,n)}catch(s){if(t=s,s instanceof K||!r||!J6(s)||i===3)throw s;await Zt(100*i,n)}throw t}async function X6(o,n){return rr.withAsyncBody(async(e,t)=>{let r=Vk(o.url),i=o.getRawRequest?o.getRawRequest(o):await Q6(o),s={hostname:r.hostname,port:r.port?parseInt(r.port):r.protocol==="https:"?443:80,protocol:r.protocol,path:r.path,method:o.type||"GET",headers:o.headers,agent:o.agent,rejectUnauthorized:Bu(o.strictSSL)?o.strictSSL:!0};o.user&&o.password&&(s.auth=o.user+":"+o.password),o.disableCache&&(s.cache="no-store");let a=i(s,d=>{let c=xi(o.followRedirects)?o.followRedirects:3;if(d.statusCode&&d.statusCode>=300&&d.statusCode<400&&c>0&&d.headers.location)jk({...o,url:d.headers.location,followRedirects:c-1},n).then(e,t);else{let u=d;!o.isChromiumNetwork&&d.headers["content-encoding"]==="gzip"&&(u=d.pipe(j6())),e({res:d,stream:iT(u)})}});if(a.on("error",t),o.timeout)if(o.isChromiumNetwork){let d=setTimeout(()=>{a.abort(),t(new Error(`Request timeout after ${o.timeout}ms`))},o.timeout);a.on("response",()=>clearTimeout(d)),a.on("error",()=>clearTimeout(d)),a.on("abort",()=>clearTimeout(d))}else a.setTimeout(o.timeout);o.isChromiumNetwork&&a.removeHeader("Content-Length"),o.data&&typeof o.data=="string"&&a.write(o.data),a.end();let l=n.onCancellationRequested(()=>{l.dispose(),a.abort(),t(new K)});a.on("response",()=>l.dispose()),a.on("error",()=>l.dispose())})}var Z6=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),e3=/^(GET|HEAD|OPTIONS)$/i;function t3(o){if(o instanceof Error){let n=o.code;return!!n&&Z6.has(n)}return!1}var od=class extends rd{constructor(e,t,r,i){super("local",e,t,r);this._proxyResolver=i}request(e,t){return this.logAndRequest(e,()=>this._request(e,t))}resolveProxy(e){return this._proxyResolver.resolveProxy(e)}async _request(e,t){let i,s=e3.test(e.type||"GET");for(let a=1;a<=3;a++)try{return await this._requestAttempt(e,t)}catch(l){if(i=l,Cn(l)||!s||!t3(l)||a===3)throw l;await Zt(100*a,t)}throw i}async _requestAttempt(e,t){if(t.isCancellationRequested)throw new K;let r=new AbortController,i=t.onCancellationRequested(()=>r.abort()),s=e.timeout?AbortSignal.any([r.signal,AbortSignal.timeout(e.timeout)]):r.signal;try{let a=await this._proxyResolver.fetch(e.url||"",{method:e.type||"GET",headers:n3(e),body:e.data,signal:s,cache:e.disableCache?"no-store":void 0}),l=a.body?i3(a.body,r,i):o3(i);return{res:{statusCode:a.status,headers:r3(a)},stream:l}}catch(a){throw i.dispose(),a instanceof Error&&a.name==="AbortError"?new K:a instanceof Error&&a.name==="TimeoutError"?new Error(`Fetch timeout: ${e.timeout}ms`):a}}};od=R([C(0,Bn),C(1,bt),C(2,M),C(3,yi)],od);function n3(o){if(!o.headers&&!o.user&&!o.password&&!o.proxyAuthorization)return;let n=new Headers;for(let e in o.headers){let t=o.headers[e];if(typeof t=="string")n.set(e,t);else if(Array.isArray(t))for(let r of t)n.append(e,r)}return(o.user||o.password)&&n.set("Authorization",`Basic ${btoa(`${o.user||""}:${o.password||""}`)}`),o.proxyAuthorization&&n.set("Proxy-Authorization",o.proxyAuthorization),n}function r3(o){let n=Object.create(null);return o.headers.forEach((e,t)=>{n[t]=e}),n}function o3(o){let n=_d();return n.end(),o.dispose(),n}function i3(o,n,e){let t=o.getReader(),r=_d({highWaterMark:16}),i=r.destroy.bind(r);return r.destroy=()=>{n.abort(),t.cancel(),e.dispose(),i()},s3(t,r,e),r}async function s3(o,n,e){try{for(;;){let{done:t,value:r}=await o.read();if(t)break;await n.write(F.wrap(r))}n.end()}catch(t){n.error(t instanceof Error?t:new Error(String(t))),n.end()}finally{e.dispose()}}async function Kk(o,n,e,t,r){let i=new ii;o.set(ig,i);let s=te(e.userRoamingDataHome,"settings.json"),a=r.add(new Ua(s,n,i,t));await a.initialize(),o.set(Bn,a);let l=new bl(a,t);o.set(yi,l);let d=r.add(new od(a,e,t,l));return o.set(si,d),{proxyResolver:l,requestService:d}}import*as Qk from"fs";var Gk=[{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 br(o,n){return new Promise((e,t)=>{o.exec(n,r=>r?t(r):e())})}function it(o,n,e){return new Promise((t,r)=>{o.run(n,e,function(i){if(i)return r(i);t({changes:this.changes,lastID:this.lastID})})})}function Kr(o,n,e){return new Promise((t,r)=>{o.get(n,e,(i,s)=>{if(i)return r(i);t(s)})})}function Do(o,n,e){return new Promise((t,r)=>{o.all(n,e,(i,s)=>{if(i)return r(i);t(s)})})}function SI(o){return new Promise((n,e)=>{o.close(t=>t?e(t):n())})}function a3(o){return new Promise((n,e)=>{import("@vscode/sqlite3").then(t=>{let r=new t.default.Database(o,i=>{if(i)return e(i);n(r)})},e)})}async function l3(o,n){await br(o,"PRAGMA foreign_keys = ON");let t=(await Kr(o,"PRAGMA user_version",[]))?.user_version??0,r=n.filter(i=>i.version>t).sort((i,s)=>i.version-s.version);if(r.length!==0){await br(o,"BEGIN TRANSACTION");try{for(let i of r)await br(o,i.sql),await br(o,`PRAGMA user_version = ${i.version}`);await br(o,"COMMIT")}catch(i){throw await br(o,"ROLLBACK"),i}}}var cy=class o{constructor(n,e=Gk){this._path=n;this._migrations=e;this._fileEditSequencer=new at;this._metadataSequencer=new at;this._pendingWrites=new Set}static async open(n,e=Gk){let t=new o(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 Qk.promises.mkdir(oe(this._path),{recursive:!0});let n=await a3(this._path);try{await l3(n,this._migrations)}catch(e){throw await SI(n),this._dbPromise=void 0,e}if(this._closed)throw await SI(n),new Error("SessionDatabase has been disposed");return n})()),this._dbPromise)}async getAllTables(){let n=await this._ensureDb();return(await Do(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 it(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n])})}deleteTurn(n){return this._track(async()=>{let e=await this._ensureDb();await it(e,"DELETE FROM turns WHERE id = ?",[n])})}setTurnEventId(n,e){return this._track(async()=>{let t=await this._ensureDb();await it(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await it(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 Kr(e,"SELECT event_id FROM turns WHERE id = ?",[n]))?.event_id??void 0}async getNextTurnEventId(n){let e=await this._ensureDb();return(await Kr(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 Kr(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 it(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await it(t,"UPDATE turns SET checkpoint_ref = ? WHERE id = ?",[e,n])})}async getTurnCheckpointRef(n){let e=await this._ensureDb();return(await Kr(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 Kr(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 Do(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 it(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 it(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[n])})}deleteAllTurns(){return this._track(async()=>{let n=await this._ensureDb();await br(n,"DELETE FROM turns")})}insertLocalTurn(n){return this._track(async()=>{let e=await this._ensureDb();await it(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 Do(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 it(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 it(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n.turnId]),await it(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 Do(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(i=>({turnId:i.turn_id,toolCallId:i.tool_call_id,filePath:i.file_path,kind:i.edit_type??"edit",originalPath:i.original_path??void 0,addedLines:i.added_lines??void 0,removedLines:i.removed_lines??void 0}))}async getAllFileEdits(){let n=await this._ensureDb();return(await Do(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 Do(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 Kr(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?Yk(r.before_content):void 0,afterContent:r.after_content?Yk(r.after_content):void 0}})}async getMetadata(n){let e=await this._ensureDb();return(await Kr(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(),i=e.map(()=>"?").join(","),s=await Do(r,`SELECT key, value FROM session_metadata WHERE key IN (${i})`,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 it(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 it(r,"DELETE FROM chat_drafts WHERE chat_uri = ?",[t]);return}await it(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 Kr(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 it(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 it(t,"DELETE FROM reviewed_files WHERE uri = ? AND nonce = ?",[n.toString(),e])})}async getReviewedFiles(){let n=await this._ensureDb();return(await Do(n,"SELECT uri, nonce FROM reviewed_files ORDER BY rowid",[])).map(Jk)}async getReviewedFilesForUri(n){let e=await this._ensureDb();return(await Do(e,"SELECT uri, nonce FROM reviewed_files WHERE uri = ? ORDER BY rowid",[n.toString()])).map(Jk)}async isFileReviewed(n,e){let t=await this._ensureDb();return!!await Kr(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 br(e,"PRAGMA defer_foreign_keys = ON"),await br(e,"BEGIN TRANSACTION");try{let t=[...n.keys()];if(t.length>0){let r=t.map(()=>"?").join(",");await it(e,`DELETE FROM turns WHERE id NOT IN (${r})`,t)}for(let[r,i]of n)await it(e,"UPDATE turns SET id = ? WHERE id = ?",[i,r]),await it(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[i,r]);if(t.length>0){let r=t.map(()=>"?").join(",");await it(e,`DELETE FROM local_turns WHERE turn_id NOT IN (${r})`,t)}for(let[r,i]of n)await it(e,"UPDATE local_turns SET turn_id = ? WHERE turn_id = ?",[i,r]),await it(e,"UPDATE local_turns SET anchor_turn_id = ? WHERE anchor_turn_id = ?",[i,r]);await br(e,"COMMIT")}catch(t){throw await br(e,"ROLLBACK"),t}})}async whenIdle(){for(;this._pendingWrites.size>0;)await Promise.allSettled([...this._pendingWrites])}async vacuumInto(n){let e=await this._ensureDb();await it(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=>SI(n)).catch(()=>{})||!0)}dispose(){this.close()}};function Jk(o){return{uri:h.parse(o.uri),nonce:o.nonce}}function Yk(o){return o instanceof Buffer?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):o instanceof Uint8Array?o:typeof o=="string"?new TextEncoder().encode(o):new Uint8Array(0)}var bI=class extends Ms{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 cy(t);return this.liveDatabases.add(r),r}destroyReferencedObject(e,t){this.liveDatabases.delete(t),t.dispose()}},id=class{constructor(n,e,t,r){this._fileService=e;this._logService=t;this._onWillDeleteSessionData=new A;this._basePath=h.joinPath(n,"agentSessionData"),this._databases=new bI(r??(i=>h.joinPath(this._basePath,i,ga).fsPath),this._logService)}get onWillDeleteSessionData(){return this._onWillDeleteSessionData.event}getSessionDataDir(n){return h.joinPath(this._basePath,this._sanitizedSessionKey(n))}getSessionDataDirById(n){let e=n.replace(/[^a-zA-Z0-9_.-]/g,"-");return h.joinPath(this._basePath,e)}_sanitizedSessionKey(n){return this._dataKey(n).replace(/[^a-zA-Z0-9_.-]/g,"-")}_dataKey(n){let e=D.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=h.joinPath(this._basePath,e,ga);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 i of r)i.status==="rejected"&&this._logService.warn(`[SessionDataService] onWillDeleteSessionData waitUntil rejected: ${e.toString()}`,i.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 i of t.children){if(!i.isDirectory)continue;let s=i.name;n.has(s)||(this._logService.trace(`[SessionDataService] Cleaning up orphaned session data: ${s}`),r.push(this._fileService.del(i.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}}};id=R([C(1,Pe),C(2,M)],id);import{execFile as d3}from"child_process";var uy=class o{static async checkSandboxDependenciesWith(n,e=Oe,t=r=>o._probeBubblewrap(r)){if(!e)return;let[r,i]=await Promise.all([n("bwrap"),n("socat")]),s=r?await t(r):{usable:!1};return{bubblewrapInstalled:!!r,bubblewrapUsable:s.usable,bubblewrapError:s.error,socatInstalled:!!i}}checkSandboxDependencies(){return o.checkSandboxDependenciesWith(_p)}static _probeBubblewrap(n){return new Promise(e=>{d3(n,["--unshare-net","--dev-bind","/","/","echo","ok"],{encoding:"utf8",timeout:5e3},(t,r,i)=>{if(!t&&r.trim()==="ok"){e({usable:!0});return}let s=i.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"}),i=e(),s=t(process.env),a=await this._getPSHome();return{readonlyPaths:[...new Set([...r.readonlyPaths,...i.readonlyPaths,...s.readonlyPaths,...a?[a]:[]])],readwritePaths:[...new Set([...r.readwritePaths,...i.readwritePaths,...s.readwritePaths])]}}async getWindowsMxcEnvironment(){if(!Q)return;let n=[];for(let s of["SystemRoot","PATH","ComSpec","PATHEXT","PSModulePath"]){let a=lo(process.env,s);typeof a=="string"&&a&&n.push(`${s}=${a}`)}let e=lo(process.env,"USERPROFILE");typeof e=="string"&&e&&n.push(`USERPROFILE=${e}`);let t=lo(process.env,"APPDATA");typeof t=="string"&&t&&n.push(`APPDATA=${t}`);let r=this._getLocalAppData();typeof r=="string"&&r&&n.push(`LOCALAPPDATA=${r}`);let i=await this._getPSHome();return i&&n.push(`PSHOME=${i}`),n}async buildWindowsMxcSandboxPayload(n,e,t,r,i="process"){if(!Q)return;let{buildSandboxPayload:s}=await import("@microsoft/mxc-sdk");return s(n,e,t,r,i)}async _getPSHome(){let n=lo(process.env,"PSHOME");if(typeof n=="string"&&n)return n;let e=await _p("pwsh")??await _p("powershell");return e?ye.dirname(e):void 0}_getLocalAppData(){let n=lo(process.env,"LOCALAPPDATA");return typeof n=="string"&&n?n:void 0}};var py=class extends Vc{_decodeUri(n){return bA(n)}_encodeUri(n,e){return il(n,e)}};var Xk="local";var Ou=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"}},Zk=W("agentHostResourceService");var eD="agentHostClientResource";function tD(o){return{resourceList:n=>o.call("resourceList",{uri:n.toString()}),resourceRead:n=>o.call("resourceRead",{uri:n.toString()}),resourceWrite:n=>o.call("resourceWrite",{...n,uri:n.uri.toString()}),resourceCopy:n=>o.call("resourceCopy",{...n,source:n.source.toString(),destination:n.destination.toString()}),resourceDelete:n=>o.call("resourceDelete",{...n,uri:n.uri.toString()}),resourceMove:n=>o.call("resourceMove",{...n,source:n.source.toString(),destination:n.destination.toString()}),resourceResolve:n=>o.call("resourceResolve",{...n,uri:n.uri.toString()}),resourceMkdir:n=>o.call("resourceMkdir",{...n,uri:n.uri.toString()}),resourceRequest:n=>o.call("resourceRequest",{...n,uri:n.uri.toString()})}}var fy=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 i=await this._call(n,e,t),s={jsonrpc:"2.0",method:e,result:i??null};return this._logReverseFrame(s,"c2s"),i}catch(i){let s=i instanceof Ou?{jsonrpc:"2.0",method:e,error:{code:Se.PermissionDenied,message:i.message,data:i.request?{request:i.request}:void 0}}:{jsonrpc:"2.0",method:e,error:{code:-32603,message:i instanceof Error?i.message:String(i)}};throw this._logReverseFrame(s,"c2s"),i}}_logReverseFrame(n,e){this._ahpLogger?.log(n,e)}async _call(n,e,t){let r=t??{},i=Xk;switch(e){case"resourceList":return{entries:(await this._resourceService.list(i,h.parse(r.uri))).entries};case"resourceRead":{let s=await this._resourceService.read(i,h.parse(r.uri));return{data:or(s.bytes),encoding:"base64"}}case"resourceWrite":return await this._resourceService.write(i,r),{};case"resourceDelete":return await this._resourceService.del(i,r),{};case"resourceMove":return await this._resourceService.move(i,r),{};case"resourceCopy":return await this._resourceService.copy(i,r),{};case"resourceResolve":return this._resourceService.resolve(i,r);case"resourceMkdir":return await this._resourceService.mkdir(i,r),{};case"resourceRequest":try{return await this._resourceService.request(i,r),{}}catch(s){throw s instanceof K?new Ou(void 0):s}}throw new Error(`Unknown command '${e}' on AgentHostClientResourceChannel`)}};fy=R([C(1,Zk)],fy);var nD=W("agentHostByokLmHandler");var rD="agentHostClientByokLm";function oD(o){let n=new Be(()=>o.listen("onDidChangeModels"));return{chat:e=>o.call("chat",e),listModels:()=>o.call("listModels"),onDidChangeModels:(e,t,r)=>n.value(e,t,r)}}var gy=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,Re.None);case"listModels":return await this._handler.listModels(Re.None)}throw new Error(`Unknown command '${e}' on AgentHostClientByokLmChannel`)}};gy=R([C(0,nD)],gy);var iD="agentHostClientProxy";function sD(o){return{resolveProxy:n=>o.call("resolveProxy",{url:n})}}var my=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`)}};my=R([C(0,si)],my);var c3=20,sd=class{constructor(n,e,t,r=c3){this._fileService=e;this._logService=t;this._sequencer=new at;this._lru=[];this._cacheLoaded=!1;this._basePath=h.joinPath(n,"agentPlugins"),this._cachePath=h.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(i=>this._sequencer.queue(i.uri,async()=>{try{let s=await this._syncPlugin(n,i),a={...i,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 ${i.uri}: ${a}`);let l={...i,load:{kind:"error",message:a}};return t?.(l),{customization:l}}})))}async _syncPlugin(n,e){let t=il(h.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 h.joinPath(this._basePath,this._keyForUri(n),this._keyForNonce(e))}_pluginRootFor(n){return h.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,F.fromString(JSON.stringify(n)))}catch(n){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",n)}}};sd=R([C(1,Pe),C(2,M)],sd);import*as hy from"child_process";import*as dD from"fs/promises";import{cp as u3}from"@vscode/fs-copyfile";var ad=class{constructor(n,e,t){this._fileService=n;this._environmentService=e;this._logService=t;this._repositoryRoots=new an(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 i=r.split(/\r?\n/g).map(s=>s.trim()).filter(s=>s.length>0);return sx(i,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=h.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=>h.file(t.substring(9))):[]}async addWorktree(n,e,t,r){let i=await this._resolveRemoteTrackingBranch(n,r)??r;await this._runGit(n,["-c","checkout.workers=0","worktree","add","--no-track","-b",t,e.fsPath,i],{timeout:18e4,throwOnError:!0})}async copyWorktreeIncludeFiles(n,e,t){try{let r=await this._getWorktreeIncludePaths(n,t);if(r.length===0)return;let i=performance.now(),s=new Bo(15),l=(await Promise.allSettled(r.map(d=>s.queue(async()=>{let c=j(e.fsPath,ep(n.fsPath,d));await dD.mkdir(oe(c),{recursive:!0}),await u3(d,c,{force:!0,recursive:!0,verbatimSymlinks:!0})})))).filter(d=>d.status==="rejected");if(this._logService.info(`[AgentHostGitService][copyWorktreeIncludeFiles] Copied ${r.length-l.length}/${r.length} folder(s)/file(s) to worktree ${e.fsPath}. [${(performance.now()-i).toFixed(2)}ms]`),l.length>0){this._logService.warn(`[AgentHostGitService][copyWorktreeIncludeFiles] Failed to copy ${l.length} folder(s)/file(s) to worktree ${e.fsPath}.`);for(let d of l)this._logService.warn(`[AgentHostGitService][copyWorktreeIncludeFiles] ${d.reason}`)}}catch(r){this._logService.warn(`[AgentHostGitService][copyWorktreeIncludeFiles] Failed to copy folder(s)/file(s) to worktree ${e.fsPath}: ${r}`)}}async addExistingWorktree(n,e,t){await this._runGit(n,["-c","checkout.workers=0","worktree","add","-f",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","-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),i=await this._runGit(t,["status","--porcelain=v1","-z","--untracked-files=all"]);if(i===void 0)return;let s=g3(i).length>0,a;if(!s)a=await this._runGit(t,["diff","--raw","--numstat","--diff-filter=ADMR","-z",r,"--"]);else{let l=CI(i);a=await this._runWithTempIndex(t,r,l)}if(a!==void 0)return lD(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??os}async _runWithTempIndex(n,e,t){let r=h.joinPath(this._environmentService.tmpDir,`agent-host-git-diff-${O()}`);await this._fileService.createFolder(r);let s={GIT_INDEX_FILE:h.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",os],{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 i=h.joinPath(e,"pathspec");return await this._fileService.writeFile(i,F.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=${i.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 _getWorktreeIncludePaths(n,e){if(e.length===0)return[];let t=["ls-files","--others","--ignored","--exclude-standard","-z"],[r,i]=await Promise.all([this._runGit(n,t,{timeout:3e4}),this._runGit(n,[...t,"--directory","--no-empty-directory"],{timeout:3e4})]);if(!r)return[];let s=r.split("\0").filter(m=>m.length>0);if(s.length===0)return[];let a=e.map(m=>Nr(m)),l=new Set((i??"").split("\0").filter(m=>m.endsWith("/"))),d=[],c=new Set;for(let m of s)if(a.some(v=>v(m)))d.push(m);else if(l.size>0){let v=aD(m,l);v!==void 0&&c.add(v)}if(d.length===0)return[];let u=new Set;for(let m of l)c.has(m)||u.add(m);let p=[...u];for(let m of d)(u.size===0||aD(m,u)===void 0)&&p.push(m);return p.map(m=>j(n.fsPath,m))}async showBlob(n,e,t){if(await this.getRepositoryRoot(n))return new Promise(i=>{hy.execFile("git",["show",`${e}:${t}`],{cwd:n.fsPath,timeout:5e3,encoding:"buffer",maxBuffer:32*1024*1024},(s,a)=>{if(s){i(void 0);return}i(F.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=CI(t),i=h.joinPath(this._environmentService.tmpDir,`agent-host-checkpoint-${O()}`);await this._fileService.createFolder(i);let a={GIT_INDEX_FILE:h.joinPath(i,"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",os],{env:a}),await this._stageChangedPaths(e,i,r,a)&&(await this._runGit(e,["write-tree"],{env:a}))?.trim()||void 0}finally{try{await this._fileService.del(i,{recursive:!0,useTrash:!1})}catch{}}}async commitTree(n,e,t,r){let i=["commit-tree",e];return t&&i.push("-p",t),i.push("-m",r),(await this._runGit(n,i,{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=>{hy.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 i=h.joinPath(this._environmentService.tmpDir,`agent-host-review-overlay-${O()}`);await this._fileService.createFolder(i);let a={GIT_INDEX_FILE:h.joinPath(i,"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=m3(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(i,{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:lD(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,i]=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=h3(t),a=y3(r),l=b3(i),d=v3(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 C3(u)}_runGit(n,e,t){return this._logService.trace(`[agentHostGitService] > git ${e.join(" ")}`),new Promise((r,i)=>{let s=t?.env?{...process.env,...t.env}:void 0,a=t?.timeout??5e3,l=!1,d=hy.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){i(new Error(p3(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))})}};ad=R([C(0,Pe),C(1,bt),C(2,M)],ad);function aD(o,n){let e=o.indexOf("/");for(;e!==-1;){let t=o.slice(0,e+1);if(n.has(t))return t;e=o.indexOf("/",e+1)}}function p3(o,n,e,t,r){let i=o[0]??"(unknown)",s;e?s=`git ${i} timed out after ${n}ms`:t.killed&&t.signal?s=`git ${i} killed by ${t.signal}`:typeof t.code=="number"?s=`git ${i} exited with code ${t.code}`:s=t.message;let a=f3(r);return a?`${s}: ${a}`:s}function f3(o){if(!o)return"";let n=o.split(/[\r\n]+/g).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)return"";let e=200,r=n.find(i=>/\bgit-lfs\b/i.test(i)&&/(command not found|not recognized|no such file)/i.test(i))??n[n.length-1];return r.length>e?`${r.slice(0,e-1)}\u2026`:r}function g3(o){return CI(o,n=>n==="??")}function CI(o,n=()=>!0){if(!o)return[];let e=[],t=new Set,r=s=>{s&&!t.has(s)&&(t.add(s),e.push(s))},i=o.split("\0");for(let s=0;s<i.length;s++){let a=i[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=i[++s];u&&r(u)}}else c&&s++}return e}function m3(o){if(!o)return;let n=o.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 lD(o,n,e,t,r){let i=o.split("\0"),s=[],a=new Map,l=0;for(;l<i.length;){let d=i[l++];if(d)if(d.startsWith(":")){let u=d.split(" ")[4]??"",p=i[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=i[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 v=i[l++];m=i[l++]??v??""}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?h.joinPath(n,d.oldPath):void 0,p=d.newPath?h.joinPath(n,d.newPath):void 0,m=d.kind!=="create"&&d.oldPath&&u?{uri:u.toString(),content:{uri:mS(e,t,d.oldPath,u.path)}}:void 0,v=d.kind!=="delete"&&d.newPath&&p?{uri:p.toString(),content:r!==void 0?{uri:mS(e,r,d.newPath,p.path)}:{uri:p.toString()}}:void 0,y={added:c?.added??0,removed:c?.removed??0};return{...m?{before:m}:{},...v?{after:v}:{},diff:y}})}function h3(o){if(!o)return{};let n,e,t,r,i=0;for(let s of o.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("#")||i++}return{branchName:n,upstreamBranchName:e,outgoingChanges:t,incomingChanges:r,uncommittedChanges:i}}function y3(o){if(o!==void 0)return o.trim()?/github\.com[:\/]/i.test(o):!1}function v3(o){if(!o)return;let n=[];for(let t of o.split(/\r?\n/)){let r=t.trim();if(!r)continue;let i=/^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(r);i&&n.push({name:i[1],url:i[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=S3(t);if(r)return r}}function S3(o){let n=/^[^@\s]+@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(o);if(n)return{owner:n[1],repo:n[2]};if(n=/^[a-z+]+:\/\/(?:[^@\/\s]+@)?github\.com(?::\d+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i.exec(o),n)return{owner:n[1],repo:n[2]}}function b3(o){let n=o?.trim();if(!n)return;let e="refs/remotes/origin/";return n.startsWith(e)?n.substring(e.length):n}function C3(o){let n={};for(let[e,t]of Object.entries(o))t!==void 0&&(n[e]=t);return n}I3().catch(o=>{console.error(o),process.exit(1)});async function I3(){let o;Rp(process)?o=new Dd:o=new Tp("agentHost");let n=new Y,e={_serviceBrand:void 0,...Xt},t=new jh(Kh(process.argv,dI),e),r=new Yh(sR(t),t.logsHome);o.registerChannel("agentHostLogger",new Qh(r,()=>Nk));let i=r.createLogger("agenthost",{name:f(2012,null)}),s=n.add(new km),a=n.add(new Dm(s)),l=new Gh(i,[a]);!t.isBuilt&&oR&&n.add(iR(l)),l.info("Agent Host process started successfully");let d=n.add(new Ri(l));n.add(d.registerProvider(ne.file,n.add(new dy(l)))),n.add(WE(d));let c=new id(h.file(t.userDataPath),d,l),u=te(t.appSettingsHome,"globalStorage","agent-host-config.json"),p,m,v,y,S,b=Lp(process.env[XT],!0);try{let x=new Xo;x.set(bt,t),x.set(M,l),x.set(Pe,d),x.set(rt,c),x.set(ft,e);let E=await Kk(x,d,t,l,n);S=E.proxyResolver;let H=S.fetch.bind(S),G=await qx({environmentService:t,productService:e,fileService:d,loggerService:r,logService:l,disposables:n,fetchFn:H,requestService:E.requestService});x.set(zn,G),m=new pa(x);let q=n.add(m.createInstance(Hr));x.set(Qa,q),x.set($m,m.createInstance(Hm)),x.set(Fm,new uy);let V=m.createInstance(ad);x.set(Ye,V);let ge=n.add(m.createInstance(Ga));x.set(Mr,ge);let $=n.add(m.createInstance(Dl));x.set(Ml,$),v=$.onDidDownloadProgress;let U=m.createInstance(Ll);x.set(Nl,U),y=new Pm,x.set(vi,y);let B=n.add(m.createInstance(wl));x.set(Um,B);let z=n.add(m.createInstance(Zl,H));x.set(Rm,z),p=new pm(l,d,c,e,V,ge,u,G,q,void 0,H);let J=m.createInstance(Xl);x.set(ck,J),p.setNetworkDiagnosticsService(J),x.set(Pr,p);let Z=new sd(h.file(t.userDataPath),d,l);x.set(vl,Z);let le=n.add(new ci(l));x.set(Pf,le),x.set(Df,m.createInstance(Sa)),x.set(Dr,p.terminalManager),x.set(He,p.configurationService),x.set(xt,p.gitHubEndpointService),x.set(bg,p.completionsService);let It=m.createInstance(li,H);x.set(Pt,It),x.set(Em,m.createInstance(Cl));let $e=n.add(m.createInstance(Vl));x.set(Ih,$e);let At=n.add(m.createInstance(Kl));if(x.set(Rh,At),p.registerProvider(m.createInstance(Ae)),Lp(process.env[YT],!0)&&(!t.isBuilt||$.isAvailable(Ol))&&p.registerProvider(m.createInstance(jl)),!t.isBuilt||$.isAvailable(_s)){let yt=p.configurationService,Et=!1,On=()=>{if(Et)return;let Gr=Lp(process.env[QT],!1),Uu=yt.getRootValue(Ut,vv)===!0;(Gr||Uu)&&(Et=!0,p.registerProvider(m.createInstance(Yl)))};On(),n.add(yt.onDidRootConfigChange(()=>On()))}}catch(x){throw l.error("Failed to create AgentService",x),x}v&&n.add(v(x=>p.emitDownloadProgress(x.packageId,x.displayName,x.receivedBytes,x.totalBytes,x.phase==="completed"||x.phase==="failed")));let I=Js.fromService(p,n);o.registerChannel("agentHost",I);let _=n.add(new py);if(n.add(d.registerProvider(kb,_)),o instanceof Dd){let x=new Map,E=H=>{if(x.has(H))return;let G=H.ctx;if(typeof G!="string"||!G)return;let q=new Y,V=U=>o.getChannel(U,B=>B.ctx===G),ge=tD(V(eD));q.add(_.registerAuthority(G,ge));let $=sD(V(iD));if(q.add(S.register(G,$)),b&&y){let U=oD(V(rD));q.add(y.register(G,U))}x.set(H,q)};n.add(o.onDidAddConnection(E)),n.add(o.onDidRemoveConnection(H=>{let G=x.get(H);G&&(G.dispose(),x.delete(H))}));for(let H of o.connections)E(H)}let T=n.add(new A),P,X={onDidChangeConnectionCount:T.event,async startWebSocketServer(){if(P)return P;let x=Q?`\\\\.\\pipe\\vscode-agent-host-${O().replace(/-/g,"")}`:j(Nu.tmpdir(),`vscode-agent-host-${O().replace(/-/g,"")}.sock`),E=n.add(await Mu.create({socketPath:x},l,{instantiationService:m,logsHome:t.logsHome})),H=n.add(new Rs(p,p.stateManager,E,{defaultDirectory:h.file(Nu.homedir()).toString(),completionTriggerCharacters:p.completionTriggerCharacters,terminalCommandPrefix:"!",otlpLogEmitter:s},_,l));return n.add(H.onDidChangeConnectionCount(G=>T.fire(G))),l.info(`[AgentHost] Dynamic WebSocket server listening on ${x}`),P={socketPath:x},P},async getInspectInfo(x){let E=Lu.url();if(!E&&x){try{Lu.open(0,"127.0.0.1",!1)}catch(H){l.error("[AgentHost] Failed to open inspector",H);return}E=Lu.url()}if(E)try{let H=new URL(E);if(H.protocol!=="ws:"){l.warn(`[AgentHost] Unexpected inspector URL: ${E}`);return}let G=Number(H.port),q=H.pathname.replace(/^\/+/,"");if(!Number.isInteger(G)||!q){l.warn(`[AgentHost] Unexpected inspector URL: ${E}`);return}let V=H.hostname==="0.0.0.0"?"127.0.0.1":H.hostname==="::"?"::1":H.hostname,ge=V.includes(":")?`[${V}]`:V;return{host:V,port:G,devtoolsUrl:`devtools://devtools/bundled/js_app.html?v8only=true&ws=${ge}:${H.port}/${q}`}}catch{l.warn(`[AgentHost] Unexpected inspector URL: ${E}`);return}}},k=Js.fromService(X,n);o.registerChannel("agentHostConnectionTracker",k),_3(p,_,m,t.logsHome,l,s,n,x=>T.fire(x)).catch(x=>{l.error("Failed to start WebSocket server",x)}),process.once("exit",()=>{p.dispose(),l.dispose(),n.dispose()})}async function _3(o,n,e,t,r,i,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 Mu.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 Rs(o,o.stateManager,p,{defaultDirectory:h.file(Nu.homedir()).toString(),completionTriggerCharacters:o.completionTriggerCharacters,terminalCommandPrefix:"!",otlpLogEmitter:i},n,r));s.add(m.onDidChangeConnectionCount(a)),await p.whenListening;let v=d??`${u}:${p.boundPort??l}`;r.info(`[AgentHost] WebSocket server listening on ${v}`),console.log(`Agent host server listening on ${v}`)}
