/*!--------------------------------------------------------
 * 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 OL=Object.defineProperty;var LL=Object.getOwnPropertyDescriptor;var A=(o,n,e,t)=>{for(var r=t>1?void 0:t?LL(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&&OL(n,e,r),r},b=(o,n)=>(e,t)=>n(e,t,o);function NL(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 pT=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=NL(this._array,n,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=e+1,e===-1?void 0:this._array[e]}};var Dv=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(n){setTimeout(()=>{throw n.stack?Jn.isErrorNoTelemetry(n)?new Jn(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)}},ga=new Dv;function fT(o){ga.setUnexpectedErrorHandler(o)}function gT(o){if(!o||typeof o!="object")return!1;let n=o;return n.code==="EPIPE"&&n.syscall?.toUpperCase()==="WRITE"}function Yo(o){ga.onUnexpectedError(o)}function Ye(o){un(o)||ga.onUnexpectedError(o)}function mT(o){un(o)||ga.onUnexpectedExternalError(o)}function UL(o){return Object.hasOwn(o,"code")}function hT(o){if(!o||typeof o!="object"||!UL(o))return;let n=o.code;return typeof n=="string"||typeof n=="number"?String(n):void 0}var Fp="Canceled";function un(o){return o instanceof K?!0:o instanceof Error&&o.name===Fp&&o.message===Fp}var K=class extends Error{constructor(){super(Fp),this.name=this.message}},Hp=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 $p(){let o=new Error(Fp);return o.name=o.message,o}function Mv(o){return o?new Error(`Illegal argument: ${o}`):new Error("Illegal argument")}function Wp(o){return o?new Error(`Illegal state: ${o}`):new Error("Illegal state")}function In(o){return o?o.message?o.message:o.stack?o.stack.split(`
`)[0]:String(o):"Error"}var Jn=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"}},qe=class o extends Error{constructor(n){super(n||"An unexpected bug occurred."),Object.setPrototypeOf(this,o.prototype)}};function Nn(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 ST(o,n,e){return FL(o.length,t=>e(o[t],n))}function FL(o,n){let e=0,t=o-1;for(;e<=t;){let r=(e+t)/2|0,i=n(r);if(i<0)e=r+1;else if(i>0)t=r-1;else return r}return-(e+1)}function Qo(o){return o.filter(n=>!!n)}function uo(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 Ov(o,n){return o.push(n),()=>HL(o,n)}function HL(o,n){let e=o.indexOf(n);if(e>-1)return o.splice(e,1),n}function Lv(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 CT(o){return o[Math.floor(Math.random()*o.length)]}var IT;(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})(IT||={});function bT(o,n){return(e,t)=>n(o(e),o(t))}var _T=(o,n)=>o-n;var vT=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||IT.isGreaterThan(n(r,e)))&&(t=!1,e=r),!0)),e}};function xT(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 wT,RT,TT=class{constructor(n,e){this.toKey=e;this._map=new Map;this[wT]="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))}[(RT=Symbol.iterator,wT=Symbol.toStringTag,RT)](){return this.values()}};function ma(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 Uv=class{constructor(n,e){this.uri=n;this.value=e}};function $L(o){return Array.isArray(o)}var AT,Me=class o{constructor(n,e){this[AT]="ResourceMap";if(n instanceof o)this.map=new Map(n.map),this.toKey=e??o.defaultToKey;else if($L(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 Uv(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]}*[(AT=Symbol.toStringTag,Symbol.iterator)](){for(let[,n]of this.map)yield[n.uri,n.value]}},PT,pn=class{constructor(n,e){this[PT]="ResourceSet";!n||typeof n=="function"?this._map=new Me(n):(this._map=new Me(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()}[(PT=Symbol.toStringTag,Symbol.iterator)](){return this.keys()}};var ET,vc=class{constructor(){this[ET]="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}[(ET=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)}},Fv=class extends vc{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))}},bn=class extends Fv{constructor(n,e=1){super(n,e)}trim(n){this.trimOld(n)}set(n,e){return super.set(n,e),this.checkTrim(),this}};var qp=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 ha=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 Bp(o,n){if(!o)throw new Error(n?`Assertion failed (${n})`:"Assertion Failed")}function Sc(o,n="unexpected state"){if(!o)throw typeof n=="string"?new qe(`Assertion Failed: ${n}`):n}function Cc(o){if(!o()){debugger;o(),Ye(new qe("Assertion Failed"))}}function Be(o){return typeof o=="string"}function ze(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof RegExp)&&!(o instanceof Date)}function kT(o){let n=Object.getPrototypeOf(Uint8Array);return typeof o=="object"&&o instanceof n}function is(o){return typeof o=="number"&&!isNaN(o)}function DT(o){return!!o&&typeof o[Symbol.iterator]=="function"}function zp(o){return o===!0||o===!1}function ya(o){return typeof o>"u"}function Mr(o){return!hr(o)}function hr(o){return ya(o)||o===null}function MT(o,n){if(!o)throw new Error(n?`Unexpected type, expected '${n}'`:"Unexpected type")}var qL=Object.prototype.hasOwnProperty;function Vp(o){if(!ze(o))return!1;for(let n in o)if(qL.call(o,n))return!1;return!0}function Ic(o){return typeof o=="function"}function he(o,n){for(let e in n)if(!(e in o))return!1;return!0}var Sa;(W=>{function o(R){return!!R&&typeof R=="object"&&typeof R[Symbol.iterator]=="function"}W.is=o;let n=Object.freeze([]);function e(){return n}W.empty=e;function*t(R){yield R}W.single=t;function r(R){return o(R)?R:t(R)}W.wrap=r;function i(R){return R??n}W.from=i;function*s(R){for(let L=R.length-1;L>=0;L--)yield R[L]}W.reverse=s;function a(R){return!R||R[Symbol.iterator]().next().done===!0}W.isEmpty=a;function l(R){return R[Symbol.iterator]().next().value}W.first=l;function d(R,L){let D=0;for(let z of R)if(L(z,D++))return!0;return!1}W.some=d;function c(R,L){let D=0;for(let z of R)if(!L(z,D++))return!1;return!0}W.every=c;function u(R,L){for(let D of R)if(L(D))return D}W.find=u;function*p(R,L){for(let D of R)L(D)&&(yield D)}W.filter=p;function*g(R,L){let D=0;for(let z of R)yield L(z,D++)}W.map=g;function*h(R,L){let D=0;for(let z of R)yield*L(z,D++)}W.flatMap=h;function*y(...R){for(let L of R)DT(L)?yield*L:yield L}W.concat=y;function I(R,L,D){let z=D;for(let J of R)z=L(z,J);return z}W.reduce=I;function S(R){let L=0;for(let D of R)L++;return L}W.length=S;function*C(R,L,D=R.length){for(L<-R.length&&(L=0),L<0&&(L+=R.length),D<0?D+=R.length:D>R.length&&(D=R.length);L<D;L++)yield R[L]}W.slice=C;function _(R,L=Number.POSITIVE_INFINITY){let D=[];if(L===0)return[D,R];let z=R[Symbol.iterator]();for(let J=0;J<L;J++){let me=z.next();if(me.done)return[D,W.empty()];D.push(me.value)}return[D,{[Symbol.iterator](){return z}}]}W.consume=_;async function T(R){let L=[];for await(let D of R)L.push(D);return L}W.asyncToArray=T;async function w(R){let L=[];for await(let D of R)L=L.concat(D);return L}W.asyncToArrayFlat=w})(Sa||={});var BL=!1,Ca=null;var OT=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(g=>typeof g=="string"?g===u[0]:u[0].match(g));)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 qp;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(bT(l=>l.idx,_T));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 h=i.get(d.slice(0,u).join(`
`)),y=xT([...h].map(I=>r(I)[u]),I=>I);delete y[d[u]];for(let[I,S]of Object.entries(y))S&&c.unshift(`    - stacktraces of ${S.length} other leaks continue with ${I}`);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 zL(o){Ca=o}if(BL){let o="__is_disposable_tracked__";zL(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!==x.None)try{n[o]=!0}catch{}}markAsDisposed(n){if(n&&n!==x.None)try{n[o]=!0}catch{}}markAsSingleton(n){}})}function Xo(o){return Ca?.trackDisposable(o),o}function Zo(o){Ca?.markAsDisposed(o)}function ss(o,n){Ca?.setParent(o,n)}function VL(o,n){if(Ca)for(let e of o)Ca.setParent(e,n)}function ba(o){return typeof o=="object"&&o!==null&&typeof o.dispose=="function"&&o.dispose.length===0}function tn(o){if(Sa.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 jp(...o){let n=U(()=>tn(o));return VL(o,n),n}var Hv=class{constructor(n){this._isDisposed=!1,this._fn=n,Xo(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,Zo(this),this._fn()}}};function U(o){return new Hv(o)}var G=class o{constructor(){this._toDispose=new Set;this._isDisposed=!1;Xo(this)}static{this.DISABLE_DISPOSED_WARNING=!1}dispose(){this._isDisposed||(Zo(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{tn(this._toDispose)}finally{this._toDispose.clear()}}add(n){if(!n||n===x.None)return n;if(n===this)throw new Error("Cannot register a disposable on itself!");return ss(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)&&ss(n,null)}assertNotDisposed(){this._isDisposed&&Ye(new qe("Object disposed"))}},x=class{constructor(){this._store=new G;Xo(this),ss(this._store,this)}static{this.None=Object.freeze({dispose(){}})}dispose(){Zo(this),this._store.dispose()}_register(n){if(n===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(n)}},ht=class{constructor(){this._isDisposed=!1;Xo(this)}get value(){return this._isDisposed?void 0:this._value}set value(n){this._isDisposed||n===this._value||(this._value?.dispose(),n&&ss(n,this),this._value=n)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Zo(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let n=this._value;return this._value=void 0,n&&ss(n,null),n}};var Ia=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=ma(()=>{--t.counter===0&&(this.destroyReferencedObject(n,t.object),this.references.delete(n))});return t.counter++,{object:r,dispose:i}}};var Ee=class{constructor(n=new Map){this._isDisposed=!1;this._store=n,Xo(this)}dispose(){Zo(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{tn(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),ss(e,this)}deleteAndDispose(n){this._store.get(n)?.dispose(),this._store.delete(n)}deleteAndLeak(n){let e=this._store.get(n);return e&&ss(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 $v(o,n){return o.then(e=>(n.isDisposed?e.dispose():n.add(e),e))}var bc=class extends Ee{constructor(){super(new Me)}};var Qe=class o{static{this.Undefined=new o(void 0)}constructor(n){this.element=n,this.next=o.Undefined,this.prev=o.Undefined}},_c=class{constructor(){this._first=Qe.Undefined;this._last=Qe.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===Qe.Undefined}clear(){let n=this._first;for(;n!==Qe.Undefined;){let e=n.next;n.prev=Qe.Undefined,n.next=Qe.Undefined,n=e}this._first=Qe.Undefined,this._last=Qe.Undefined,this._size=0}unshift(n){return this._insert(n,!1)}push(n){return this._insert(n,!0)}_insert(n,e){let t=new Qe(n);if(this._first===Qe.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!==Qe.Undefined){let n=this._first.element;return this._remove(this._first),n}}pop(){if(this._last!==Qe.Undefined){let n=this._last.element;return this._remove(this._last),n}}peek(){if(this._last!==Qe.Undefined)return this._last.element}_remove(n){if(n.prev!==Qe.Undefined&&n.next!==Qe.Undefined){let e=n.prev;e.next=n.next,n.next.prev=e}else n.prev===Qe.Undefined&&n.next===Qe.Undefined?(this._first=Qe.Undefined,this._last=Qe.Undefined):n.next===Qe.Undefined?(this._last=this._last.prev,this._last.next=Qe.Undefined):n.prev===Qe.Undefined&&(this._first=this._first.next,this._first.prev=Qe.Undefined);this._size-=1}*[Symbol.iterator](){let n=this._first;for(;n!==Qe.Undefined;)yield n.element,n=n.next}};function jL(){return globalThis._VSCODE_NLS_MESSAGES}function Wv(){return globalThis._VSCODE_NLS_LANGUAGE}var KL=Wv()==="pseudo"||typeof document<"u"&&document.location&&typeof document.location.hash=="string"&&document.location.hash.indexOf("pseudo=true")>=0;function LT(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}),KL&&(e="\uFF3B"+e.replace(/[aouei]/g,"$&$&")+"\uFF3D"),e}function f(o,n,...e){return LT(typeof o=="number"?GL(o,n):n,e)}function GL(o,n){let e=jL()?.[o];if(typeof e!="string"){if(typeof n=="string")return n;throw new Error(`!!! NLS MISSING: ${o} !!!`)}return e}var ti="en",wc=!1,Rc=!1,Tc=!1,UT=!1,FT=!1,qv=!1,HT=!1,$T=!1,JL=!1,YL=!1,Gp,Jp=ti,NT=ti,QL,po,fo=globalThis,_n;typeof fo.vscode<"u"&&typeof fo.vscode.process<"u"?_n=fo.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(_n=process);var WT=typeof _n?.versions?.electron=="string",XL=WT&&_n?.type==="renderer";if(typeof _n=="object"){wc=_n.platform==="win32",Rc=_n.platform==="darwin",Tc=_n.platform==="linux",UT=Tc&&!!_n.env.SNAP&&!!_n.env.SNAP_REVISION,HT=WT,JL=!!_n.env.CI||!!_n.env.BUILD_ARTIFACTSTAGINGDIRECTORY||!!_n.env.GITHUB_WORKSPACE,Gp=ti,Jp=ti;let o=_n.env.VSCODE_NLS_CONFIG;if(o)try{let n=JSON.parse(o);Gp=n.userLocale,NT=n.osLocale,Jp=n.resolvedLanguage||ti,QL=n.languagePack?.translationsConfigFile}catch{}FT=!0}else typeof navigator=="object"&&!XL?(po=navigator.userAgent,wc=po.indexOf("Windows")>=0,Rc=po.indexOf("Macintosh")>=0,$T=(po.indexOf("Macintosh")>=0||po.indexOf("iPad")>=0||po.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Tc=po.indexOf("Linux")>=0,YL=po?.indexOf("Mobi")>=0,qv=!0,Jp=Wv()||ti,Gp=navigator.language.toLowerCase(),NT=Gp):console.error("Unable to resolve platform.");function qT(o){switch(o){case 0:return"Web";case 1:return"Mac";case 2:return"Linux";case 3:return"Windows"}}var Yp=0;Rc?Yp=1:wc?Yp=3:Tc&&(Yp=2);var X=wc,ft=Rc,Fe=Tc,BT=UT,zT=FT,VT=HT,Qn=qv,Bv=qv&&typeof fo.importScripts=="function",jT=Bv?fo.origin:void 0;var zv=Yp,Yn=po,ei=Jp,ZL;(t=>{function o(){return ei}t.value=o;function n(){return ei.length===2?ei==="en":ei.length>=3?ei[0]==="e"&&ei[1]==="n"&&ei[2]==="-":!1}t.isDefaultVariant=n;function e(){return ei==="en"}t.isDefault=e})(ZL||={});var eN=typeof fo.postMessage=="function"&&!fo.importScripts,KT=(()=>{if(eN){let o=[];fo.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}),fo.postMessage({vscodeScheduleAsyncWork:t},"*")}}return o=>setTimeout(o)})();var qt=Rc||$T?2:wc?1:3;var Vv=!!(Yn&&Yn.indexOf("Chrome")>=0),GT=!!(Yn&&Yn.indexOf("Firefox")>=0),JT=!!(!Vv&&Yn&&Yn.indexOf("Safari")>=0),YT=!!(Yn&&Yn.indexOf("Edg/")>=0),cV=!!(Yn&&Yn.indexOf("Android")>=0),QT=!!(Yn&&Yn.indexOf("Electron")>=0);var as,jv=globalThis.vscode;if(typeof jv<"u"&&typeof jv.process<"u"){let o=jv.process;as={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"?as={get platform(){return process.platform},get arch(){return process.arch},get env(){return process.env},cwd(){return process.env.VSCODE_CWD||process.cwd()}}:as={get platform(){return X?"win32":ft?"darwin":"linux"},get arch(){},get env(){return{}},cwd(){return"/"}};var ls=as.cwd,at=as.env,_a=as.platform,XT=as.arch;var tN=globalThis.performance.now.bind(globalThis.performance),lt=class o{static create(n){return new o(n)}constructor(n){this._now=n===!1?Date.now:tN,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 ZT=!1,nN=!1,rN=100,ew=6e4;function tw(){return!!at.VSCODE_DEV}var ee;(je=>{je.None=()=>x.None;function n(k){if(nN){let{onDidAddListener:P}=k,q=wa.create(),H=0;k.onDidAddListener=()=>{++H===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),q.print()),P?.()}}}function e(k,P,q){return g(k,()=>{},0,void 0,P??!0,void 0,q)}je.defer=e;function t(k){return(P,q=null,H)=>{let j=!1,Q;return Q=k(Z=>{if(!j)return Q?Q.dispose():j=!0,P.call(q,Z)},null,H),j&&Q.dispose(),Q}}je.once=t;function r(k,P){return je.once(je.filter(k,P))}je.onceIf=r;function i(k,P,q){return u((H,j=null,Q)=>k(Z=>H.call(j,P(Z)),null,Q),q)}je.map=i;function s(k,P,q){return u((H,j=null,Q)=>k(Z=>{P(Z),H.call(j,Z)},null,Q),q)}je.forEach=s;function a(k,P,q){return u((H,j=null,Q)=>k(Z=>P(Z)&&H.call(j,Z),null,Q),q)}je.filter=a;function l(k){return k}je.signal=l;function d(...k){return(P,q=null,H)=>{let j=jp(...k.map(Q=>Q(Z=>P.call(q,Z))));return p(j,H)}}je.any=d;function c(k,P,q,H){let j=q;return i(k,Q=>(j=P(j,Q),j),H)}je.reduce=c;function u(k,P){let q,H={onWillAddFirstListener(){q=k(j.fire,j)},onDidRemoveLastListener(){q?.dispose()}};P||n(H);let j=new E(H);return P?.add(j),j.event}function p(k,P){return P instanceof Array?P.push(k):P&&P.add(k),k}function g(k,P,q=100,H=!1,j=!1,Q,Z){let st,Pe,kt,xt=0,Lt,mr={leakWarningThreshold:Q,onWillAddFirstListener(){st=k(cT=>{xt++,Pe=P(Pe,cT),H&&!kt&&(co.fire(Pe),Pe=void 0),Lt=()=>{let uT=Pe;Pe=void 0,kt=void 0,(!H||xt>1)&&co.fire(uT),xt=0},typeof q=="number"?(kt&&clearTimeout(kt),kt=setTimeout(Lt,q)):kt===void 0&&(kt=null,queueMicrotask(Lt))})},onWillRemoveListener(){j&&xt>0&&Lt?.()},onDidRemoveLastListener(){Lt=void 0,st.dispose()}};Z||n(mr);let co=new E(mr);return Z?.add(co),co.event}je.debounce=g;function h(k,P=0,q,H){return je.debounce(k,(j,Q)=>j?(j.push(Q),j):[Q],P,void 0,q??!0,void 0,H)}je.accumulate=h;function y(k,P,q=100,H=!0,j=!0,Q,Z){let st,Pe,kt,xt=0,Lt={leakWarningThreshold:Q,onWillAddFirstListener(){st=k(co=>{xt++,Pe=P(Pe,co),kt===void 0&&(H&&(mr.fire(Pe),Pe=void 0,xt=0),typeof q=="number"?kt=setTimeout(()=>{j&&xt>0&&mr.fire(Pe),Pe=void 0,kt=void 0,xt=0},q):(kt=0,queueMicrotask(()=>{j&&xt>0&&mr.fire(Pe),Pe=void 0,kt=void 0,xt=0})))})},onDidRemoveLastListener(){st.dispose()}};Z||n(Lt);let mr=new E(Lt);return Z?.add(mr),mr.event}je.throttle=y;function I(k,P=(H,j)=>H===j,q){let H=!0,j;return a(k,Q=>{let Z=H||!P(Q,j);return H=!1,j=Q,Z},q)}je.latch=I;function S(k,P,q){return[je.filter(k,P,q),je.filter(k,H=>!P(H),q)]}je.split=S;function C(k,P,q=!1,H=[],j){let Q=H.slice(),Z;tw()&&(Z={stack:wa.create(),timerId:setTimeout(()=>{Q&&Q.length>0&&Z&&!Z.warned&&(Z.warned=!0,console.warn(`[Event.buffer][${P}] potential LEAK detected: ${Q.length} events buffered for ${ew/1e3}s without being consumed. Buffered here:`),Z.stack.print())},ew),warned:!1},j&&j.add(U(()=>clearTimeout(Z.timerId))));let st=()=>{Z&&clearTimeout(Z.timerId)},Pe=k(Lt=>{Q?(Q.push(Lt),tw()&&Z&&!Z.warned&&Q.length>=rN&&(Z.warned=!0,console.warn(`[Event.buffer][${P}] potential LEAK detected: ${Q.length} events buffered without being consumed. Buffered here:`),Z.stack.print())):xt.fire(Lt)});j&&j.add(Pe);let kt=()=>{Q?.forEach(Lt=>xt.fire(Lt)),Q=null,st()},xt=new E({onWillAddFirstListener(){Pe||(Pe=k(Lt=>xt.fire(Lt)),j&&j.add(Pe))},onDidAddFirstListener(){Q&&(q?setTimeout(kt):kt())},onDidRemoveLastListener(){Pe&&Pe.dispose(),Pe=null,st()}});return j&&j.add(xt),xt.event}je.buffer=C;function _(k,P){return(H,j,Q)=>{let Z=P(new w);return k(function(st){let Pe=Z.evaluate(st);Pe!==T&&H.call(j,Pe)},void 0,Q)}}je.chain=_;let T=Symbol("HaltChainable");class w{constructor(){this.steps=[]}map(P){return this.steps.push(P),this}forEach(P){return this.steps.push(q=>(P(q),q)),this}filter(P){return this.steps.push(q=>P(q)?q:T),this}reduce(P,q){let H=q;return this.steps.push(j=>(H=P(H,j),H)),this}latch(P=(q,H)=>q===H){let q=!0,H;return this.steps.push(j=>{let Q=q||!P(j,H);return q=!1,H=j,Q?j:T}),this}evaluate(P){for(let q of this.steps)if(P=q(P),P===T)break;return P}}function W(k,P,q=H=>H){let H=(...st)=>Z.fire(q(...st)),j=()=>k.on(P,H),Q=()=>k.removeListener(P,H),Z=new E({onWillAddFirstListener:j,onDidRemoveLastListener:Q});return Z.event}je.fromNodeEventEmitter=W;function R(k,P,q=H=>H){let H=(...st)=>Z.fire(q(...st)),j=()=>k.addEventListener(P,H),Q=()=>k.removeEventListener(P,H),Z=new E({onWillAddFirstListener:j,onDidRemoveLastListener:Q});return Z.event}je.fromDOMEventEmitter=R;function L(k,P){let q,H,j=new Promise(Q=>{H=t(k)(Q),Xv(H,P),q=()=>{rw(H,P)}});return j.cancel=q,P&&j.finally(()=>rw(H,P)),j}je.toPromise=L;function D(k,P){return k(q=>P.fire(q))}je.forward=D;function z(k,P,q){return P(q),k(H=>P(H))}je.runAndSubscribe=z;class J{constructor(P,q){this._observable=P;this._counter=0;this._hasChanged=!1;let H={onWillAddFirstListener:()=>{P.addObserver(this),this._observable.reportChanges()},onDidRemoveLastListener:()=>{P.removeObserver(this)}};q||n(H),this.emitter=new E(H),q&&q.add(this.emitter)}beginUpdate(P){this._counter++}handlePossibleChange(P){}handleChange(P,q){this._hasChanged=!0}endUpdate(P){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function me(k,P){return new J(k,P).emitter.event}je.fromObservable=me;function We(k){return(P,q,H)=>{let j=0,Q=!1,Z={beginUpdate(){j++},endUpdate(){j--,j===0&&(k.reportChanges(),Q&&(Q=!1,P.call(q)))},handlePossibleChange(){},handleChange(){Q=!0}};k.addObserver(Z),k.reportChanges();let st={dispose(){k.removeObserver(Z)}};return Xv(st,H),st}}je.fromObservableLight=We})(ee||={});var Gv=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 lt,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}}},nw=-1;var Jv=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 Ra(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}},wa=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(`
`))}},Ra=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"}},Yv=class extends Ra{constructor(n,e,t,r,i){super(n,e,t,r,i),this.name="ListenerRefusalError"}},oN=0,Ta=class{constructor(n){this.value=n;this.id=oN++}},iN=2,sN=(o,n)=>{if(o instanceof Ta)n(o);else for(let e=0;e<o.length;e++){let t=o[e];t&&n(t)}},E=class{constructor(n){this._size=0;this._options=n,this._leakageMon=nw>0||this._options?.leakWarningThreshold?new Jv(n?.onListenerError??Ye,this._options?.leakWarningThreshold??nw,this._options?.leakWarningName):void 0,this._perfMon=this._options?._profName?new Gv(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(ZT){let n=this._listeners;queueMicrotask(()=>{sN(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 Yv(c,`${l}. HINT: Stack shows most frequent listener (${d[1]}-times)`,d[0],this._size,this._options?.leakWarningName);return(this._options?.onListenerError||Ye)(u),x.None}if(this._disposed)return x.None;e&&(n=n.bind(e));let r=new Ta(n),i,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=wa.create(),i=this._leakageMon.check(r.stack,this._size+1)),ZT&&(r.stack=s??wa.create()),this._listeners?this._listeners instanceof Ta?(this._deliveryQueue??=new Qv,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=U(()=>{i?.(),this._removeListener(r)});return Xv(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*iN<=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||Ye;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 Ta)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 Qv=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 Qp=class{constructor(){this.hasListeners=!1;this.events=[];this.emitter=new E({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),U(ma(()=>{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 xc=class{constructor(){this.listening=!1;this.inputEvent=ee.None;this.inputEventListener=x.None;this.emitter=new E({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 Xv(o,n){n instanceof G?n.add(o):Array.isArray(n)&&n.push(o)}function rw(o,n){if(n instanceof G)n.delete(o);else if(Array.isArray(n)){let e=n.indexOf(o);e!==-1&&n.splice(e,1)}o.dispose()}var ow=Object.freeze(function(o,n){let e=setTimeout(o.bind(n),0);return{dispose(){clearTimeout(e)}}}),ke;(t=>{function o(r){return r===t.None||r===t.Cancelled||r instanceof xa?!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:ow})})(ke||={});var xa=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?ow:(this._emitter||(this._emitter=new E),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},dt=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 xa),this._token}cancel(){this._token?this._token instanceof xa&&this._token.cancel():this._token=ke.Cancelled}dispose(n=!1){n&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof xa&&this._token.dispose():this._token=ke.None}};var aN=65,lN=97,dN=90,cN=122,ds=46,Bt=47,Tn=92,mo=58,uN=63,Xp=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 pN(o,n){if(o===null||typeof o!="object")throw new Xp(n,"Object",o)}function Ct(o,n){if(typeof o!="string")throw new Xp(n,"string",o)}var wn=_a==="win32";function fe(o){return o===Bt||o===Tn}function Zv(o){return o===Bt}function ho(o){return o>=aN&&o<=dN||o>=lN&&o<=cN}function Zp(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=Bt}if(t(l)){if(!(s===d-1||a===1))if(a===2){if(r.length<2||i!==2||r.charCodeAt(r.length-1)!==ds||r.charCodeAt(r.length-2)!==ds){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===ds&&a!==-1?++a:a=-1}return r}function fN(o){return o?`${o[0]==="."?"":"."}${o}`:""}function iw(o,n){pN(n,"pathObject");let e=n.dir||n.root,t=n.base||`${n.name||""}${fN(n.ext)}`;return e?e===n.root?`${e}${t}`:`${e}${o}${t}`:t}var ve={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=ls():(i=at[`=${n}`]||ls(),(i===void 0||i.slice(0,2).toLowerCase()!==n.toLowerCase()&&i.charCodeAt(2)===Tn)&&(i=`${n}\\`));let s=i.length,a=0,l="",d=!1,c=i.charCodeAt(0);if(s===1)fe(c)&&(a=1,d=!0);else if(fe(c))if(d=!0,fe(i.charCodeAt(1))){let u=2,p=u;for(;u<s&&!fe(i.charCodeAt(u));)u++;if(u<s&&u!==p){let g=i.slice(p,u);for(p=u;u<s&&fe(i.charCodeAt(u));)u++;if(u<s&&u!==p){for(p=u;u<s&&!fe(i.charCodeAt(u));)u++;(u===s||u!==p)&&(l=`\\\\${g}\\${i.slice(p,u)}`,a=u)}}}else a=1;else ho(c)&&i.charCodeAt(1)===mo&&(l=i.slice(0,2),a=2,s>2&&fe(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=Zp(e,!t,"\\",fe),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 Zv(i)?"\\":o;if(fe(i))if(r=!0,fe(o.charCodeAt(1))){let a=2,l=a;for(;a<n&&!fe(o.charCodeAt(a));)a++;if(a<n&&a!==l){let d=o.slice(l,a);for(l=a;a<n&&fe(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!fe(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 ho(i)&&o.charCodeAt(1)===mo&&(t=o.slice(0,2),e=2,n>2&&fe(o.charCodeAt(2))&&(r=!0,e=3));let s=e<n?Zp(o.slice(e),!r,"\\",fe):"";if(s.length===0&&!r&&(s="."),s.length>0&&fe(o.charCodeAt(n-1))&&(s+="\\"),!r&&t===void 0&&o.includes(":")){if(s.length>=2&&ho(s.charCodeAt(0))&&s.charCodeAt(1)===mo)return`.\\${s}`;let a=o.indexOf(":");do if(a===n-1||fe(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 fe(e)||n>2&&ho(e)&&o.charCodeAt(1)===mo&&fe(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"&&fe(e.charCodeAt(0))){++r;let i=e.length;i>1&&fe(e.charCodeAt(1))&&(++r,i>2&&(fe(e.charCodeAt(2))?++r:t=!1))}if(t){for(;r<n.length&&fe(n.charCodeAt(r));)r++;r>=2&&(n=`\\${n.slice(r)}`)}return ve.normalize(n)},relative(o,n){if(Ct(o,"from"),Ct(n,"to"),o===n)return"";let e=ve.resolve(o),t=ve.resolve(n);if(e===t||(o=e.toLowerCase(),n=t.toLowerCase(),o===n))return"";if(e.length!==o.length||t.length!==n.length){let h=e.split("\\"),y=t.split("\\");h[h.length-1]===""&&h.pop(),y[y.length-1]===""&&y.pop();let I=h.length,S=y.length,C=I<S?I:S,_;for(_=0;_<C&&h[_].toLowerCase()===y[_].toLowerCase();_++);return _===0?t:_===C?S>C?y.slice(_).join("\\"):I>C?"..\\".repeat(I-1-_)+"..":"":"..\\".repeat(I-_)+y.slice(_).join("\\")}let r=0;for(;r<o.length&&o.charCodeAt(r)===Tn;)r++;let i=o.length;for(;i-1>r&&o.charCodeAt(i-1)===Tn;)i--;let s=i-r,a=0;for(;a<n.length&&n.charCodeAt(a)===Tn;)a++;let l=n.length;for(;l-1>a&&n.charCodeAt(l-1)===Tn;)l--;let d=l-a,c=s<d?s:d,u=-1,p=0;for(;p<c;p++){let h=o.charCodeAt(r+p);if(h!==n.charCodeAt(a+p))break;h===Tn&&(u=p)}if(p!==c){if(u===-1)return t}else{if(d>c){if(n.charCodeAt(a+p)===Tn)return t.slice(a+p+1);if(p===2)return t.slice(a+p)}s>c&&(o.charCodeAt(r+p)===Tn?u=p:p===2&&(u=3)),u===-1&&(u=0)}let g="";for(p=r+u+1;p<=i;++p)(p===i||o.charCodeAt(p)===Tn)&&(g+=g.length===0?"..":"\\..");return a+=u,g.length>0?`${g}${t.slice(a,l)}`:(t.charCodeAt(a)===Tn&&++a,t.slice(a,l))},toNamespacedPath(o){if(typeof o!="string"||o.length===0)return o;let n=ve.resolve(o);if(n.length<=2)return o;if(n.charCodeAt(0)===Tn){if(n.charCodeAt(1)===Tn){let e=n.charCodeAt(2);if(e!==uN&&e!==ds)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(ho(n.charCodeAt(0))&&n.charCodeAt(1)===mo&&n.charCodeAt(2)===Tn)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 fe(r)?o:".";if(fe(r)){if(e=t=1,fe(o.charCodeAt(1))){let a=2,l=a;for(;a<n&&!fe(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&fe(o.charCodeAt(a));)a++;if(a<n&&a!==l){for(l=a;a<n&&!fe(o.charCodeAt(a));)a++;if(a===n)return o;a!==l&&(e=t=a+1)}}}}else ho(r)&&o.charCodeAt(1)===mo&&(e=n>2&&fe(o.charCodeAt(2))?3:2,t=e);let i=-1,s=!0;for(let a=n-1;a>=t;--a)if(fe(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&&ho(o.charCodeAt(0))&&o.charCodeAt(1)===mo&&(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(fe(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(fe(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)===mo&&ho(o.charCodeAt(0))&&(n=t=2);for(let a=o.length-1;a>=n;--a){let l=o.charCodeAt(a);if(fe(l)){if(!i){t=a+1;break}continue}r===-1&&(i=!1,r=a+1),l===ds?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:iw.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 fe(r)?(n.root=n.dir=o,n):(n.base=n.name=o,n);if(fe(r)){if(t=1,fe(o.charCodeAt(1))){let u=2,p=u;for(;u<e&&!fe(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&fe(o.charCodeAt(u));)u++;if(u<e&&u!==p){for(p=u;u<e&&!fe(o.charCodeAt(u));)u++;u===e?t=u:u!==p&&(t=u+1)}}}}else if(ho(r)&&o.charCodeAt(1)===mo){if(e<=2)return n.root=n.dir=o,n;if(t=2,fe(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),fe(r)){if(!l){s=d+1;break}continue}a===-1&&(l=!1,a=d+1),r===ds?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},gN=(()=>{if(wn){let o=/\\/g;return()=>{let n=ls().replace(o,"/");return n.slice(n.indexOf("/"))}}return()=>ls()})(),ie={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)===Bt)}if(!e){let t=gN();n=`${t}/${n}`,e=t.charCodeAt(0)===Bt}return n=Zp(n,!e,"/",Zv),e?`/${n}`:n.length>0?n:"."},normalize(o){if(Ct(o,"path"),o.length===0)return".";let n=o.charCodeAt(0)===Bt,e=o.charCodeAt(o.length-1)===Bt;return o=Zp(o,!n,"/",Zv),o.length===0?n?"/":e?"./":".":(e&&(o+="/"),n?`/${o}`:o)},isAbsolute(o){return Ct(o,"path"),o.length>0&&o.charCodeAt(0)===Bt},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?".":ie.normalize(n.join("/"))},relative(o,n){if(Ct(o,"from"),Ct(n,"to"),o===n||(o=ie.resolve(o),n=ie.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===Bt&&(l=d)}if(d===a)if(s>a){if(n.charCodeAt(i+d)===Bt)return n.slice(i+d+1);if(d===0)return n.slice(i+d)}else r>a&&(o.charCodeAt(e+d)===Bt?l=d:d===0&&(l=0));let c="";for(d=e+l+1;d<=t;++d)(d===t||o.charCodeAt(d)===Bt)&&(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)===Bt,e=-1,t=!0;for(let r=o.length-1;r>=1;--r)if(o.charCodeAt(r)===Bt){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===Bt){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)===Bt){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:iw.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)===Bt,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===Bt){if(!a){i=l+1;break}continue}s===-1&&(a=!1,s=l+1),c===ds?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};ie.win32=ve.win32=ve;ie.posix=ve.posix=ie;var Rn=wn?ve.normalize:ie.normalize,nn=wn?ve.isAbsolute:ie.isAbsolute,V=wn?ve.join:ie.join,Xn=wn?ve.resolve:ie.resolve,ef=wn?ve.relative:ie.relative,te=wn?ve.dirname:ie.dirname,ue=wn?ve.basename:ie.basename,cs=wn?ve.extname:ie.extname,PV=wn?ve.format:ie.format,sw=wn?ve.parse:ie.parse,EV=wn?ve.toNamespacedPath:ie.toNamespacedPath,He=wn?ve.sep:ie.sep,Aa=wn?ve.delimiter:ie.delimiter;function mN(o){return o}var tf=class{constructor(n,e){this.lastCache=void 0;this.lastArgKey=void 0;typeof n=="function"?(this._fn=n,this._computeKey=mN):(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 Xe=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 uw(o){return!o||typeof o!="string"?!0:o.trim().length===0}var hN=/{(\d+)}/g;function us(o,...n){return n.length===0?o:o.replace(hN,function(e,t){let r=parseInt(t,10);return isNaN(r)||r<0||r>=n.length?e:n[r]})}var yN=/{([^}]+)}/g;function pw(o,n){return Object.keys(n).length===0?o:o.replace(yN,(e,t)=>n[t]??e)}function Un(o){return o.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function fn(o,n,e=TN){return o.length<=n?o:`${o.substr(0,n)}${e}`}function eS(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 Pa(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 fw(o){return o.source==="^"||o.source==="^$"||o.source==="$"||o.source==="^\\s*$"?!1:!!(o.exec("")&&o.lastIndex===0)}function gw(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 Fn(o,n){return o<n?-1:o>n?1:0}function nf(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 tS(o,n){return ps(o,n,0,o.length,0,n.length)}function ps(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 nf(o.toLowerCase(),n.toLowerCase(),e,t,r,i);aw(l)&&(l-=32),aw(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 aw(o){return o>=97&&o<=122}function nS(o){return o>=65&&o<=90}function So(o,n){return o.length===n.length&&ps(o,n)===0}function ni(o,n){let e=n.length;return e<=o.length&&ps(o,n,0,e)===0}function mw(o,n){let e=o.length,t=e-n.length;return t>=0&&ps(o,n,t,e)===0}function hw(o){return 55296<=o&&o<=56319}function rS(o){return 56320<=o&&o<=57343}function yw(o,n){return(o-55296<<10)+(n-56320)+65536}function vw(o){return o>=127462&&o<=127487||o===8986||o===8987||o===9200||o===9203||o>=9728&&o<=10175||o===11088||o===11093||o>=127744&&o<=128591||o>=128640&&o<=128764||o>=128992&&o<=129008||o>=129280&&o<=129535||o>=129648&&o<=129782}var vN=/(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/,SN=/(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/,CN=/\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/,IN=new RegExp("(?:"+[vN.source,SN.source,CN.source].join("|")+")","g");function Sw(o){return o&&(o=o.replace(IN,"")),o}var WV=String.fromCharCode(65279);function bN(o){return!!(o&&o.length>0&&o.charCodeAt(0)===65279)}function Cw(o){return bN(o)?o.substr(1):o}var lw=class o{static{this._INSTANCE=null}static getInstance(){return o._INSTANCE||(o._INSTANCE=new o),o._INSTANCE}constructor(){this._data=_N()}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 _N(){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 dw=class o{constructor(n){this.confusableDictionary=n}static{this.ambiguousCharacterData=new Xe(()=>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 tf(n=>{let e=n.split(",");function t(u){let p=new Map;for(let g=0;g<u.length;g+=2)p.set(u[g],u[g+1]);return p}function r(u,p){let g=new Map(u);for(let[h,y]of p)g.set(h,y);return g}function i(u,p){if(!u)return p;let g=new Map;for(let[h,y]of u)p.has(h)&&g.set(h,y);return g}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 Xe(()=>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())}},cw=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()}},TN="\u2026";function ri(o){return o===47||o===92}function rf(o){return o.replace(/[\\/]/g,ie.sep)}function Iw(o){return o.indexOf("/")===-1&&(o=rf(o)),/^[a-zA-Z]:(\/|$)/.test(o)&&(o="/"+o),o}function iS(o,n=ie.sep){if(!o)return"";let e=o.length,t=o.charCodeAt(0);if(ri(t)){if(ri(o.charCodeAt(1))&&!ri(o.charCodeAt(2))){let i=3,s=i;for(;i<e&&!ri(o.charCodeAt(i));i++);if(s!==i&&!ri(o.charCodeAt(i+1))){for(i+=1;i<e;i++)if(ri(o.charCodeAt(i)))return o.slice(0,i+1).replace(/[\\/]/g,n)}}return n}else if(bw(t)&&o.charCodeAt(1)===58)return ri(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(ri(o.charCodeAt(r)))return o.slice(0,r+1)}return""}function Ea(o,n,e){let t=o===n;return!e||t?t:!o||!n?!1:So(o,n)}function Co(o,n,e,t=!1){let r=t?ie.sep:He;if(o===n)return!0;if(!o||!n||((o.indexOf("..")>=0||n.indexOf("..")>=0)&&(o=t?ie.normalize(o):Rn(o),n=t?ie.normalize(n):Rn(n)),n.length>o.length))return!1;if(e){if(!ni(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 bw(o){return o>=65&&o<=90||o>=97&&o<=122}function _w(o){return X?(o=Pa(o,He),o.endsWith(":")&&(o+=He)):(o=Pa(o,He),o||(o=He)),o}function sS(o){let n=Rn(o);return X?o.length>3?!1:Tw(n)&&(o.length===2||n.charCodeAt(2)===92):n===ie.sep}function Tw(o,n=X){return n?bw(o.charCodeAt(0))&&o.charCodeAt(1)===58:!1}var wN="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",RN="BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789";function ww(o,n,e=8){let t="";for(let i=0;i<e;i++){let s;i===0&&X&&!n&&(e===3||e===4)?s=RN:s=wN,t+=s.charAt(Math.floor(Math.random()*s.length))}let r;return n?r=`${n}-${t}`:r=t,o?V(o,r):r}var AN=/^\w[\w\d+.-]*$/,PN=/^\//,EN=/^\/\//;function kN(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&&!AN.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(!PN.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(EN.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 DN(o,n){return!o&&!n?"file":o}function MN(o,n){switch(o){case"https":case"http":case"file":n?n[0]!==yr&&(n=yr+n):n=yr;break}return n}var Ke="",yr="/",ON=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,v=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||Ke,this.authority=n.authority||Ke,this.path=n.path||Ke,this.query=n.query||Ke,this.fragment=n.fragment||Ke):(this.scheme=DN(n,s),this.authority=e||Ke,this.path=MN(this.scheme,t||Ke),this.query=r||Ke,this.fragment=i||Ke,kN(this,s))}get fsPath(){return Ac(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=Ke),t===void 0?t=this.authority:t===null&&(t=Ke),r===void 0?r=this.path:r===null&&(r=Ke),i===void 0?i=this.query:i===null&&(i=Ke),s===void 0?s=this.fragment:s===null&&(s=Ke),e===this.scheme&&t===this.authority&&r===this.path&&i===this.query&&s===this.fragment?this:new oi(e,t,r,i,s)}static parse(n,e=!1){let t=ON.exec(n);return t?new oi(t[2]||Ke,of(t[4]||Ke),of(t[5]||Ke),of(t[7]||Ke),of(t[9]||Ke),e):new oi(Ke,Ke,Ke,Ke,Ke)}static file(n){let e=Ke;if(X&&(n=n.replace(/\\/g,yr)),n[0]===yr&&n[1]===yr){let t=n.indexOf(yr,2);t===-1?(e=n.substring(2),n=yr):(e=n.substring(2,t),n=n.substring(t)||yr)}return new oi("file",e,n,Ke,Ke)}static from(n,e){return new oi(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 X&&n.scheme==="file"?t=o.file(ve.join(Ac(n,!0),...e)).path:t=ie.join(n.path,...e),n.with({path:t})}toString(n=!1){return aS(this,n)}toJSON(){return this}static revive(n){if(n){if(n instanceof o)return n;{let e=new oi(n);return e._formatted=n.external??null,e._fsPath=n._sep===Pw?n.fsPath??null:null,e}}else return n}[Symbol.for("debug.description")](){return`URI(${this.toString()})`}};function Aw(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 Pw=X?1:void 0,oi=class extends v{constructor(){super(...arguments);this._formatted=null;this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=Ac(this,!1)),this._fsPath}toString(e=!1){return e?aS(this,!0):(this._formatted||(this._formatted=aS(this,!1)),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=Pw),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}},Ew={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 Rw(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=Ew[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 LN(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+=Ew[t]):n!==void 0&&(n+=o[e])}return n!==void 0?n:o}function Ac(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,X&&(e=e.replace(/\//g,"\\")),e}function aS(o,n){let e=n?LN:Rw,t="",{scheme:r,authority:i,path:s,query:a,fragment:l}=o;if(r&&(t+=r,t+=":"),(i||r==="file")&&(t+=yr,t+=yr),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:Rw(l,!1,!1)),t}function kw(o){try{return decodeURIComponent(o)}catch{return o.length>3?o.substr(0,3)+kw(o.substr(3)):o}}var xw=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function of(o){return o.match(xw)?o.replace(xw,n=>kw(n)):o}var ne;(le=>(le.inMemory="inmemory",le.vscode="vscode",le.internal="private",le.walkThrough="walkThrough",le.walkThroughSnippet="walkThroughSnippet",le.http="http",le.https="https",le.file="file",le.mailto="mailto",le.untitled="untitled",le.data="data",le.command="command",le.vscodeRemote="vscode-remote",le.vscodeRemoteResource="vscode-remote-resource",le.vscodeManagedRemoteResource="vscode-managed-remote-resource",le.vscodeUserData="vscode-userdata",le.vscodeCustomEditor="vscode-custom-editor",le.vscodeNotebookCell="vscode-notebook-cell",le.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",le.vscodeNotebookCellMetadataDiff="vscode-notebook-cell-metadata-diff",le.vscodeNotebookCellOutput="vscode-notebook-cell-output",le.vscodeNotebookCellOutputDiff="vscode-notebook-cell-output-diff",le.vscodeNotebookMetadata="vscode-notebook-metadata",le.vscodeInteractiveInput="vscode-interactive-input",le.vscodeSettings="vscode-settings",le.vscodeWorkspaceTrust="vscode-workspace-trust",le.vscodeTerminal="vscode-terminal",le.vscodeImageCarousel="vscode-image-carousel",le.vscodeChatCodeBlock="vscode-chat-code-block",le.vscodeChatCodeCompareBlock="vscode-chat-code-compare-block",le.vscodeChatEditor="vscode-chat-editor",le.vscodeChatInput="chatSessionInput",le.vscodeLocalChatSession="vscode-chat-session",le.webviewPanel="webview-panel",le.vscodeWebview="vscode-webview",le.vscodeBrowser="vscode-browser",le.extension="extension",le.vscodeFileResource="vscode-file",le.tmp="tmp",le.vsls="vsls",le.vscodeSourceControl="vscode-scm",le.commentsInput="comment",le.codeSetting="code-setting",le.outputChannel="output",le.accessibleView="accessible-view",le.chatEditingSnapshotScheme="chat-editing-snapshot-text-model",le.chatEditingModel="chat-editing-text-model",le.copilotPr="copilot-pr"))(ne||={});var uS="tkn",dS=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=ie.join(e??"/",UN(n))}getServerRootPath(){return this._serverRootPath}get _remoteResourcesPath(){return ie.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 mT(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+=`&${uS}=${encodeURIComponent(i)}`),v.from({scheme:Qn?this._preferredWebSchema:ne.vscodeRemoteResource,authority:`${t}:${r}`,path:Qn?(window.location.pathname+"/"+this._remoteResourcesPath).replace(/\/\/+/g,"/"):this._remoteResourcesPath,query:s})}},NN=new dS;function UN(o){return`${o.quality??"oss"}-${o.commit??"dev"}`}var sf="vs/../../node_modules",Dw="vs/../../node_modules.asar",Mw="vs/../../node_modules.asar.unpacked",pS="vscode-app",cS=class o{static{this.FALLBACK_AUTHORITY=pS}asBrowserUri(n){let e=this.toUri(n);return this.uriToBrowserUri(e)}uriToBrowserUri(n){return n.scheme===ne.vscodeRemote?NN.rewrite(n):n.scheme===ne.file&&(zT||jT===`${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(v.isUri(n))return n;if(globalThis._VSCODE_FILE_ROOT){let e=globalThis._VSCODE_FILE_ROOT;if(/^\w[\w\d+.-]*:\/\//.test(e))return v.joinPath(v.parse(e,!0),n);let t=V(e,n);return v.file(t)}throw new Error("Cannot determine URI for module id!")}},Nt=new cS,ej=Object.freeze({"Cache-Control":"no-cache, no-store"}),tj=Object.freeze({"Document-Policy":"include-js-call-stacks-in-crash-reports"}),FN;(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:v.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})(FN||={});function Io(o){return Ac(o,!0)}var fs=class{constructor(n){this._ignorePathCasing=n}compare(n,e,t=!1){return n===e?0:Fn(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 Co(Io(n),Io(e),this._ignorePathCasing(n))&&n.query===e.query&&(t||n.fragment===e.fragment);if(Ow(n.authority,e.authority))return Co(n.path,e.path,this._ignorePathCasing(n),!0)&&n.query===e.query&&(t||n.fragment===e.fragment)}return!1}joinPath(n,...e){return v.joinPath(n,...e)}basenameOrAuthority(n){return Se(n)||n.authority}basename(n,e){return ie.basename(n.path,e)}extname(n){return ie.extname(n.path)}dirname(n){if(n.path.length===0)return n;let e;return n.scheme===ne.file?e=v.file(te(Io(n))).path:(e=ie.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=v.file(Rn(Io(n))).path:e=ie.normalize(n.path),n.with({path:e})}relativePath(n,e){if(n.scheme!==e.scheme||!Ow(n.authority,e.authority))return;if(n.scheme===ne.file){let i=ef(Io(n),Io(e));return X?rf(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 ie.relative(t,r)}resolvePath(n,e){if(n.scheme===ne.file){let t=v.file(Xn(Io(n),e));return n.with({authority:t.authority,path:t.path})}return e=Iw(e),n.with({path:ie.resolve(n.path,e)})}isAbsolutePath(n){return!!n.path&&n.path[0]==="/"}isEqualAuthority(n,e){return n===e||n!==void 0&&e!==void 0&&So(n,e)}hasTrailingPathSeparator(n,e=He){if(n.scheme===ne.file){let t=Io(n);return t.length>iS(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=He){return Lw(n,e)?n.with({path:n.path.substr(0,n.path.length-1)}):n}addTrailingPathSeparator(n,e=He){let t=!1;if(n.scheme===ne.file){let r=Io(n);t=r!==void 0&&r.length===iS(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&&!Lw(n,e)?n.with({path:n.path+"/"}):n}},ye=new fs(()=>!1),re=new fs(o=>o.scheme===ne.file?!Fe:!0),fS=new fs(o=>!0),gn=ye.isEqual.bind(ye),Or=ye.isEqualOrParent.bind(ye),lj=ye.getComparisonKey.bind(ye),dj=ye.basenameOrAuthority.bind(ye),Se=ye.basename.bind(ye),Pc=ye.extname.bind(ye),Ut=ye.dirname.bind(ye),Y=ye.joinPath.bind(ye),rn=ye.normalizePath.bind(ye),Zn=ye.relativePath.bind(ye),cj=ye.resolvePath.bind(ye),Nw=ye.isAbsolutePath.bind(ye),Ow=ye.isEqualAuthority.bind(ye),Lw=ye.hasTrailingPathSeparator.bind(ye),uj=ye.removeTrailingPathSeparator.bind(ye),pj=ye.addTrailingPathSeparator.bind(ye);var HN;(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})(HN||={});var Uw=Symbol("MicrotaskDelay");function mf(o){return!!o&&typeof o.then=="function"}function li(o){let n=new dt,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?ba(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 hs(o,n){return new Promise((e,t)=>{let r=n.onCancellationRequested(()=>{r.dispose(),t(new K)});o.then(e,t).finally(()=>r.dispose())})}function $w(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 hf(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 ka=class{constructor(){this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null,this.cancellationTokenSource=new dt}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()}},lf=class{constructor(){this.current=Promise.resolve(null)}queue(n){return this.current=this.current.then(()=>n(),()=>n())}},df=class{constructor(){this.throttlers=new Map}queue(n,e){let t=this.throttlers.get(n);return t||(t={throttler:new ka,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()}},Ze=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()}},WN=(o,n)=>{let e=!0,t=setTimeout(()=>{e=!1,n()},o);return{isTriggered:()=>e,dispose:()=>{clearTimeout(t),e=!1}}},qN=o=>{let n=!0;return queueMicrotask(()=>{n&&(n=!1,o())}),{isTriggered:()=>n,dispose:()=>{n=!1}}},gs=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===Uw?qN(t):WN(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()}},ms=class{constructor(n){this.delayer=new gs(n),this.throttler=new ka}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()}},cf=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 mn(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)})}):li(e=>mn(o,e))}function Ft(o,n=0,e){let t=setTimeout(()=>{o(),e&&r.dispose()},n),r=U(()=>{clearTimeout(t),e?.delete(r)});return e?.add(r),r}var Rj=2**31-1;var Lr=class{constructor(n){this._size=0;this._isDisposed=!1;this.maxDegreeOfParalellism=n,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new E}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()}},ii=class extends Lr{constructor(){super(1)}};var si=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 be;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=ye){let t=e.getComparisonKey(n);return this.queues.get(t)?.size??0}queueFor(n,e,t=ye){let r=t.getComparisonKey(n),i=this.queues.get(r);if(!i){i=new ii;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 Ee),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 uf=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 qe("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 qe("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===void 0&&(this._token=setTimeout(()=>{this._token=void 0,n()},e))}},pf=class{constructor(){this.disposable=void 0;this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(n,e,t=globalThis){if(this.isDisposed)throw new qe("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=t.setInterval(()=>{n()},e);this.disposable=U(()=>{t.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},ai=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 ff=class extends ai{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()}},Da=class extends x{constructor(e,t){super();this.options=e;this.handler=t;this.pendingWork=[];this.throttler=this._register(new ht);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 ai(()=>{this.throttler.clear(),this.doWork()},e),this.throttler.value.schedule()}dispose(){super.dispose(),this.pendingWork.length=0,this.disposed=!0}},BN,af;(function(){let o=globalThis;typeof o.requestIdleCallback!="function"||typeof o.cancelIdleCallback!="function"?af=(n,e,t)=>{KT(()=>{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)}}}:af=(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))}}},BN=(n,e)=>af(globalThis,n,e)})();var gS=class{constructor(n,e){this._didRun=!1;this._executor=()=>{try{this._value=e()}catch(t){this._error=t}finally{this._didRun=!0}},this._handle=af(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}},gf=class extends gS{constructor(n){super(globalThis,n)}};async function Ww(o,n,e){let t;for(let r=0;r<e;r++)try{return await o()}catch(i){t=i,await mn(n)}throw t}var be=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)}},vr;(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})(vr||={});var Fw=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 E,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 mS=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 qe("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 be;return this._unsatisfiedConsumers.push(n),n.p}}},Hw=class o{constructor(n,e){this._onReturn=e;this._producerConsumer=new mS;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 be,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 Ec(o){let n=o;return n?[n.on,n.pause,n.resume,n.destroy].every(e=>typeof e=="function"):!1}function yf(o){let n=o;return n?Ec(n.stream)&&Array.isArray(n.buffer)&&typeof n.ended=="boolean":!1}function bo(o,n){return new hS(o,n)}var hS=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?Ye(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 qw(o,n){let e=[],t;for(;(t=o.read())!==null;)e.push(t);return n(e)}function Bw(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 vf(o,n){return new Promise((e,t)=>{let r=[];Sf(o,{onData:i=>{n&&r.push(i)},onError:i=>{n?t(i):e(void 0)},onEnd:()=>{e(n?n(r):void 0)}})})}function Sf(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 zw(o,n){return new Promise((e,t)=>{let r=new G,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(U(()=>o.removeListener("error",a))),o.on("error",a),r.add(U(()=>o.removeListener("end",l))),o.on("end",l),r.add(U(()=>o.removeListener("data",s))),o.on("data",s)})}function Vw(o){let n=!1;return{read:()=>n?null:(n=!0,o)}}function Cf(o,n,e){let t=bo(e);return Sf(o,{onData:r=>t.write(n.data(r)),onError:r=>t.error(n.error?n.error(r):r),onEnd:()=>t.end()}),t}var kc=typeof Buffer<"u",VN=new Xe(()=>new Uint8Array(256)),yS,vS,$=class o{static alloc(n){return kc?new o(Buffer.allocUnsafe(n)):new o(new Uint8Array(n))}static wrap(n){return kc&&!Buffer.isBuffer(n)&&(n=Buffer.from(n.buffer,n.byteOffset,n.byteLength)),new o(n)}static fromString(n,e){return!(e?.dontUseNodeBuffer||!1)&&kc?new o(Buffer.from(n)):(yS||(yS=new TextEncoder),new o(yS.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 kc&&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 kc?this.buffer.toString():(vS||(vS=new TextDecoder(void 0,{ignoreBOM:!0})),vS.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 KN(this.buffer,n)}writeUInt32BE(n,e){GN(this.buffer,n,e)}readUInt32LE(n){return JN(this.buffer,n)}writeUInt32LE(n,e){YN(this.buffer,n,e)}readUInt8(n){return QN(this.buffer,n)}writeUInt8(n,e){XN(this.buffer,n,e)}indexOf(n,e=0){return jN(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 jN(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=VN.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 KN(o,n){return o[n]*2**24+o[n+1]*2**16+o[n+2]*2**8+o[n+3]}function GN(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 JN(o,n){return o[n+0]<<0>>>0|o[n+1]<<8>>>0|o[n+2]<<16>>>0|o[n+3]<<24>>>0}function YN(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 QN(o,n){return o[n]}function XN(o,n,e){o[e]=n}function Gw(o){return qw(o,n=>$.concat(n))}function Jw(o){return Vw(o)}function Nr(o){return vf(o,n=>$.concat(n))}async function Yw(o){return o.ended?$.concat(o.buffer):$.concat([...o.buffer,await Nr(o.stream)])}function Qw(o){return Cf(o,{data:n=>typeof n=="string"?$.fromString(n):$.wrap(n)},n=>$.concat(n))}function Dc(o){return bo(n=>$.concat(n),o)}function xn(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 $.wrap(r).slice(0,s)}var ZN="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function _o({buffer:o},n=!0,e=!1){let t=e?eU:ZN,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 jw="0123456789abcdef";function di({buffer:o}){let n="";for(let e=0;e<o.length;e++){let t=o[e];n+=jw[t>>>4],n+=jw[t&15]}return n}function SS(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]=Kw(o,e++)<<4|Kw(o,e++);return $.wrap(n)}function Kw(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 _e(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 Mc(o,n=0){if(!o||n>200)return o;if(typeof o=="object"){switch(o.$mid){case 1:return v.revive(o);case 2:return new RegExp(o.source,o.flags);case 17:return new Date(o.source)}if(o instanceof $||o instanceof Uint8Array)return o;if(Array.isArray(o))for(let e=0;e<o.length;++e)o[e]=Mc(o[e],n+1);else for(let e in o)Object.hasOwnProperty.call(o,e)&&(o[e]=Mc(o[e],n+1))}return o}function La(o){switch(o){case 100:return"req";case 101:return"cancel";case 102:return"subscribe";case 103:return"unsubscribe"}}function If(o){switch(o){case 200:return"init";case 201:return"reply:";case 202:case 203:return"replyErr:";case 204:return"event:"}}function Ma(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 tU=ci(0);function Oa(o,n){if(n===0){o.write(tU);return}let e=0;for(let r=n;r!==0;r=r>>>7)e++;let t=$.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 Oc=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}},bf=class{constructor(){this.buffers=[]}get buffer(){return $.concat(this.buffers)}write(n){this.buffers.push(n)}dispose(){this.buffers.length=0}};function ci(o){let n=$.alloc(1);return n.writeUInt8(o,0),n}var ys={Undefined:ci(0),String:ci(1),Buffer:ci(2),VSBuffer:ci(3),Array:ci(4),Object:ci(5),Uint:ci(6)};function Lc(o,n){if(typeof n>"u")o.write(ys.Undefined);else if(typeof n=="string"){let e=$.fromString(n);o.write(ys.String),Oa(o,e.byteLength),o.write(e)}else if($.isNativeBuffer(n)){let e=$.wrap(n);o.write(ys.Buffer),Oa(o,e.byteLength),o.write(e)}else if(n instanceof $)o.write(ys.VSBuffer),Oa(o,n.byteLength),o.write(n);else if(Array.isArray(n)){o.write(ys.Array),Oa(o,n.length);for(let e of n)Lc(o,e)}else if(typeof n=="number"&&(n|0)===n)o.write(ys.Uint),Oa(o,n);else{let e=$.fromString(JSON.stringify(n));o.write(ys.Object),Oa(o,e.byteLength),o.write(e)}}function Ua(o){switch(o.read(1).readUInt8(0)){case 0:return;case 1:return o.read(Ma(o)).toString();case 2:return o.read(Ma(o)).buffer;case 3:return o.read(Ma(o));case 4:{let e=Ma(o),t=[];for(let r=0;r<e;r++)t.push(Ua(o));return t}case 5:return JSON.parse(o.read(Ma(o)).toString());case 6:return Ma(o)}}var Nc=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,If(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,If(n.type),n.data);return}}}send(n,e=void 0){let t=new bf;try{return Lc(t,n),Lc(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 Oc(n),t=Ua(e),r=Ua(e),i=t[0];switch(i){case 100:return this.logger?.logIncoming(n.byteLength,t[1],1,`${La(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,`${La(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,`${La(i)}`),this.disposeActiveRequest({type:i,id:t[1]});case 103:return this.logger?.logIncoming(n.byteLength,t[1],1,`${La(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 dt,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=U(()=>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),tn(this.activeRequests.values()),this.activeRequests.clear()}};var Na=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 E;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=ke.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 g=()=>{let I=S=>{switch(S.type){case 201:this.handlers.delete(i),u(S.data);break;case 202:{this.handlers.delete(i);let C=new Error(S.data.message);C.stack=Array.isArray(S.data.stack)?S.data.stack.join(`
`):S.data.stack,C.name=S.data.name,p(C);break}case 203:this.handlers.delete(i),p(S.data);break}};this.handlers.set(i,I);try{this.sendRequest(a)}catch(S){this.handlers.delete(i),p(S)}},h=null;this.state===1?g():(h=li(I=>this.whenInitialized()),h.then(()=>{h=null,g()}));let y=()=>{h?(h.cancel(),h=null):this.sendRequest({id:i,type:101}),p(new K)};l=r.onCancellationRequested(y),d={dispose:ma(()=>{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 E({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=li(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,`${La(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,La(n.type));return}}}send(n,e=void 0){let t=new bf;try{return Lc(t,n),Lc(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 Oc(n),t=Ua(e),r=Ua(e),i=t[0];switch(i){case 200:return this.logger?.logIncoming(n.byteLength,0,0,If(i)),this.onResponse({type:t[0]});case 201:case 202:case 204:case 203:return this.logger?.logIncoming(n.byteLength,t[1],0,If(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),tn(this.activeRequests.values()),this.activeRequests.clear(),this._onDidInitialize.dispose()}};A([_e],Na.prototype,"onDidInitializePromise",1);var _f=class{constructor(n,e,t){this.channels=new Map;this._connections=new Set;this._onDidAddConnection=new E;this.onDidAddConnection=this._onDidAddConnection.event;this._onDidRemoveConnection=new E;this.onDidRemoveConnection=this._onDidRemoveConnection.event;this.disposables=new G;this.disposables.add(n(({protocol:r,onDidClientDisconnect:i})=>{let s=ee.once(r.onMessage),a=new G,l=s(d=>{let c=new Oc(d),u=Ua(c),p=new Nc(r,u,e,t),g=new Na(r,e);this.channels.forEach((y,I)=>p.registerChannel(I,y));let h={channelServer:p,channelClient:g,ctx:u};this._connections.add(h),this._onDidAddConnection.fire(h),a.add(i(()=>{p.dispose(),g.dispose(),this._connections.delete(h),this._onDidRemoveConnection.fire(h),this.disposables.delete(a),a.dispose()}))});a.add(l),this.disposables.add(a)}))}get connections(){let n=[];return this._connections.forEach(e=>n.push(e)),n}getChannel(n,e){let t=this;return{call(r,i,s){let a;if(Ic(e)){let d=CT(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 Xw(l).call(r,i,s)},listen(r,i){if(Ic(e))return t.getMulticastEvent(n,e,r,i);let s=e.routeEvent(t,r,i).then(a=>a.channelClient.getChannel(n));return Xw(s).listen(r,i)}}}getMulticastEvent(n,e,t,r){let i=this,s,a=new E({onWillAddFirstListener:()=>{s=new G;let l=new Qp,d=new Map,c=p=>{let h=p.channelClient.getChannel(n).listen(t,r),y=l.add(h);d.set(p,y)},u=p=>{let g=d.get(p);g&&(g.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 Xw(o){return{call(n,e,t){return o.then(r=>r.call(n,e,t))},listen(n,e){let t=new xc;return o.then(r=>t.input=r.listen(n,e)),t.event}}}function Zw(o){let n=!1;return{call(e,t,r){return n?o.call(e,t,r):mn(0).then(()=>n=!0).then(()=>o.call(e,t,r))},listen(e,t){if(n)return o.listen(e,t);let r=new xc;return mn(0).then(()=>n=!0).then(()=>r.input=o.listen(e,t)),r.event}}}var vs;(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,g){let h=c.get(p);if(h)return h;let y=l[p];if(typeof y=="function"){if(t(p))return y.call(l,g);if(e(p))return c.set(p,ee.buffer(l[p],p,!0,void 0,s)),c.get(p)}throw new Jn(`Event not found: ${p}`)}call(u,p,g){let h=l[p];if(typeof h=="function"){if(!d&&Array.isArray(g))for(let I=0;I<g.length;I++)g[I]=Mc(g[I]);let y=h.apply(l,g);return y instanceof Promise||(y=Promise.resolve(y)),y}throw new Jn(`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&&!hr(s.context)?u=[s.context,...c]:u=c;let p=await i.call(d,u);return a?p:Mc(p)};throw new Jn(`Property not found: ${String(d)}`)}})}r.toService=n;function e(i){return i[0]==="o"&&i[1]==="n"&&nS(i.charCodeAt(2))}function t(i){return/^onDynamic/.test(i)&&nS(i.charCodeAt(9))}})(vs||={});import{fork as PU}from"child_process";function eR(o){let n=o;return n&&typeof n.type=="string"&&typeof n.severity=="string"}function nU(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 rU(o){if(!o)return o;let n=o.indexOf(`
`);return n===-1?o:o.substring(0,n)}function tR(o,n){let{args:e,stack:t}=nU(o),r=typeof e[0]=="string"&&e.length===1,i=rU(t);i&&(i=`(${i.trim()})`);let s=[];if(typeof e[0]=="string"?i&&r?s=[`%c[${n}] %c${e[0]} %c${i}`,Fa("blue"),Fa(""),Fa("grey")]:s=[`%c[${n}] %c${e[0]}`,Fa("blue"),Fa(""),...e.slice(1)]:s=[`%c[${n}]%`,Fa("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 Fa(o){return`color: ${o}`}function er(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"?er(t):t}),n}function nR(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(rR.call(e,t)){let r=e[t];typeof r=="object"&&!Object.isFrozen(r)&&!kT(r)&&n.push(r)}}return o}var rR=Object.prototype.hasOwnProperty;function Uc(o,n){return CS(o,n,new Set)}function CS(o,n,e){if(hr(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(CS(i,n,e));return r}if(ze(o)){if(e.has(o))throw new Error("Cannot clone recursive data-structure");e.add(o);let r={};for(let i in o)rR.call(o,i)&&(r[i]=CS(o[i],n,e));return e.delete(o),r}return o}function Ha(o,n,e=!0){return ze(o)?(ze(n)&&Object.keys(n).forEach(t=>{t in o?e&&(ze(o[t])&&ze(n[t])?Ha(o[t],n[t],e):o[t]=n[t]):o[t]=n[t]}),o):n}function Oe(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(!Oe(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(),!Oe(r,i))return!1;for(e=0;e<r.length;e++)if(!Oe(o[r[e]],n[r[e]]))return!1}return!0}function Ur(o){let n=new Set;return JSON.stringify(o,(e,t)=>{if(ze(t)||Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t)}return typeof t=="bigint"?`[BigInt ${t.toString()}]`:t})}function To(o,n){let e=n.toLowerCase(),t=Object.keys(o).find(r=>r.toLowerCase()===e);return t?o[t]:o[n]}import*as RU from"child_process";import{promises as gR}from"fs";function oR(o){o&&(delete o.DEBUG,delete o.NODE_OPTIONS,Fe&&delete o.LD_PRELOAD)}import*as se from"fs";import{tmpdir as cU}from"os";import{promisify as Hc}from"util";var iU=new bn(1e4);function Fc(o){return iR(o,"NFC",iU)}var sU=new bn(1e4);function aU(o){return iR(o,"NFD",sU)}var lU=/[^\u0000-\u0080]/;function iR(o,n,e){if(!o)return o;let t=e.get(o);if(t)return t;let r;return lU.test(o)?r=o.normalize(n):r=o,e.set(o,r),r}var dU=(function(){let o=new bn(1e4),n=/[\u0300-\u036f]/g;return function(e){let t=o.get(e);if(t)return t;let r=aU(e).replace(n,""),i=(r.length===e.length?r:e).toLowerCase();return o.set(e,i),i}})();async function lR(o,n=0,e){if(sS(o))throw new Error("rimraf - will refuse to recursively delete root");return n===0?IS(o):uU(o,e)}async function uU(o,n=ww(cU())){try{try{await se.promises.rename(o,n)}catch(e){return e.code==="ENOENT"?void 0:IS(o)}IS(n).catch(()=>{})}catch(e){if(e.code!=="ENOENT")throw e}}async function IS(o){return se.promises.rm(o,{recursive:!0,force:!0,maxRetries:3})}async function Tf(o,n){try{return await sR(o,n)}catch(e){if(e.code==="ENOENT"&&X&&sS(o))try{return await sR(`${o}.`,n)}catch{}throw e}}async function sR(o,n){return fU(await(n?pU(o):se.promises.readdir(o)))}async function pU(o){try{return await se.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 Tf(o);for(let t of e){let r=!1,i=!1,s=!1;try{let a=await se.promises.lstat(V(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 fU(o){return o.map(n=>typeof n=="string"?ft?Fc(n):n:(n.name=ft?Fc(n.name):n.name,n))}async function gU(o){let n=await Tf(o),e=[];for(let t of n)await hn.existsDirectory(V(o,t))&&e.push(t);return e}var hn;(t=>{async function o(r){let i;try{if(i=await se.promises.lstat(r),!i.isSymbolicLink())return{stat:i}}catch{}try{return{stat:await se.promises.stat(r),symbolicLink:i?.isSymbolicLink()?{dangling:!1}:void 0}}catch(s){if(s.code==="ENOENT"&&i)return{stat:i,symbolicLink:{dangling:!0}};if(X&&s.code==="EACCES")try{return{stat:await se.promises.stat(await se.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})(hn||={});var mU=new si;function hU(o,n,e){return mU.queueFor(v.file(o),()=>{let t=SU(e);return new Promise((r,i)=>vU(o,n,t,s=>s?i(s):r()))},re)}var dR=!0;function yU(o){dR=o}function vU(o,n,e,t){if(!dR)return se.writeFile(o,n,{mode:e.mode,flag:e.flag},t);se.open(o,e.flag,e.mode,(r,i)=>{if(r)return t(r);se.writeFile(i,n,s=>{if(s)return se.close(i,()=>t(s));se.fdatasync(i,a=>(a&&(console.warn("[node.js fs] fdatasync is now disabled for this session because it failed: ",a),yU(!1)),se.close(i,l=>t(l))))})})}function SU(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 CU(o,n,e=6e4){if(o!==n)try{X&&typeof e=="number"?await cR(o,n,Date.now(),e):await se.promises.rename(o,n)}catch(t){if(o.toLowerCase()!==n.toLowerCase()&&t.code==="EXDEV"||o.endsWith("."))await uR(o,n,{preserveSymlinks:!1}),await lR(o,1);else throw t}}async function cR(o,n,e,t,r=0){try{return await se.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 hn.stat(n);a.isFile()||(s=!0)}catch{}if(s)throw i}return await mn(Math.min(100,r*10)),cR(o,n,e,t,r+1)}}async function uR(o,n,e){return pR(o,n,{root:{source:o,target:n},options:e,handledSourcePaths:new Set})}var aR=511;async function pR(o,n,e){if(e.handledSourcePaths.has(o))return;e.handledSourcePaths.add(o);let{stat:t,symbolicLink:r}=await hn.stat(o);if(r){if(e.options.preserveSymlinks)try{return await _U(o,n,e)}catch{}if(r.dangling)return}return t.isDirectory()?IU(o,n,t.mode&aR,e):bU(o,n,t.mode&aR)}async function IU(o,n,e,t){await se.promises.mkdir(n,{recursive:!0,mode:e});let r=await Tf(o);for(let i of r)await pR(V(o,i),V(n,i),t)}async function bU(o,n,e){await se.promises.copyFile(o,n),await se.promises.chmod(n,e)}async function _U(o,n,e){let t=await se.promises.readlink(o);Co(t,e.root.source,!Fe)&&(t=V(e.root.target,t.substr(e.root.source.length+1))),await se.promises.symlink(t,n)}async function TU(o){try{return await Hc(se.realpath)(o)}catch{let n=wU(o);return await se.promises.access(n,se.constants.R_OK),n}}function wU(o){return Pa(Rn(o),He)}var Ge=new class{get read(){return(o,n,e,t,r)=>new Promise((i,s)=>{se.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)=>{se.write(o,n,e,t,r,(a,l,d)=>a?s(a):i({bytesWritten:l,buffer:d}))})}get fdatasync(){return Hc(se.fdatasync)}get open(){return Hc(se.open)}get close(){return Hc(se.close)}get ftruncate(){return Hc(se.ftruncate)}async exists(o){try{return await se.promises.access(o),!0}catch{return!1}}get readdir(){return Tf}get readDirsInDir(){return gU}get writeFile(){return hU}get rm(){return lR}get rename(){return CU}get copy(){return uR}get realpath(){return TU}};function mR(o=at){return o.comspec||"cmd.exe"}function hR(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))}})||X)&&(e=!0)};return{send:t}}async function xU(o){if(await Ge.exists(o)){let n;try{n=await gR.stat(o)}catch(e){e.message.startsWith("EACCES")&&(n=await gR.lstat(o))}return n?!n.isDirectory():!1}return!1}async function wf(o,n,e,t=at,r=xU){if(nn(o))return await r(o)?o:void 0;if(n===void 0&&(n=ls()),te(o)!=="."){let l=V(n,o);return await r(l)?l:void 0}let s=To(t,"PATH");if(e===void 0&&Be(s)&&(e=s.split(Aa)),e===void 0||e.length===0){let l=V(n,o);return await r(l)?l:void 0}for(let l of e){let d;if(nn(l)?d=V(l,o):d=V(n,l,o),X){let u=(To(t,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").map(async p=>{let g=d+p;return await r(g)?g:void 0});for(let p of u){let g=await p;if(g)return g}}if(await r(d))return d}let a=V(n,o);return await r(a)?a:void 0}var Rf=class extends Nc{constructor(n){super({send:e=>{try{process.send?.(e.buffer.toString("base64"))}catch{}},onMessage:ee.fromNodeEventEmitter(process,"message",e=>$.wrap(Buffer.from(e,"base64")))},n),process.once("disconnect",()=>this.dispose())}},xf=class{constructor(n,e){this.modulePath=n;this.options=e;this.activeRequests=new Set;this.channels=new Map;this._onDidProcessExit=new E;this.onDidProcessExit=this._onDidProcessExit.event;let t=e.timeout||6e4;this.disposeDelayer=new gs(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=ke.None){if(!this.disposeDelayer)return Promise.reject(new Error("disposed"));if(r.isCancellationRequested)return Promise.reject($p());this.disposeDelayer.cancel();let i=this.getCachedChannel(n),s=li(d=>i.call(e,t,d)),a=r.onCancellationRequested(()=>s.cancel()),l=U(()=>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 E({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={...er(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-"))),oR(e.env),this.child=PU(this.modulePath,n,e);let t=new E,i=ee.fromNodeEventEmitter(this.child,"message",u=>u)(u=>{if(eR(u)){tR(u,`IPC Library: ${this.options.serverName}`);return}t.fire($.wrap(Buffer.from(u,"base64")))}),s=this.options.useQueue?hR(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 Na(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(g=>tn(g)),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 Af(o){return!!o.parentPort}var bS=class{constructor(n){this.port=n;this.onMessage=ee.fromNodeEventEmitter(this.port,"message",e=>e.data?$.wrap(e.data):$.alloc(0)),n.start()}send(n){this.port.postMessage(n.buffer)}disconnect(){this.port.close()}},Ss=class o extends _f{static getOnDidClientConnect(n){MT(Af(process),"Electron Utility Process");let e=new E;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 bS(t),onDidClientDisconnect:ee.fromNodeEventEmitter(t,"close")}))}constructor(n){super(o.getOnDidClientConnect(n))}};var EU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yR(o){return EU.test(o)}var F=(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 yc from"os";import*as Up from"inspector";var Sr;(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})(Sr||={});var we=B("instantiationService");function DU(o,n,e){n[Sr.DI_TARGET]===n?n[Sr.DI_DEPENDENCIES].push({id:o,index:e}):(n[Sr.DI_DEPENDENCIES]=[{id:o,index:e}],n[Sr.DI_TARGET]=n)}function B(o){if(Sr.serviceIds.has(o))return Sr.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");DU(n,e,r)};return n.toString=()=>o,Sr.serviceIds.set(o,n),n}function MU(o){return o==="terminal"||o==="subagent"||o==="search"}function OU(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 LU(o){if(!Array.isArray(o))return;let n=[];for(let e of o){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.name!="string"||typeof t.description!="string")return;n.push({name:t.name,description:t.description})}return n}function An(o){let n=o._meta;if(!n)return{};let e={};MU(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),typeof n.subagentChatUri=="string"&&(e.subagentChatUri=n.subagentChatUri),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=LU(n.toolSearchCandidates);t&&(e.toolSearchCandidates=t);let r=OU(n.ui);return r&&(e.ui=r),e}function At(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 Je="ahp-root://",FU="ahp-root",TS="ahp-resource-watch";function wR(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=_o($.fromString(JSON.stringify(n)),!1,!0);return`${TS}://r/${e}`}function RR(o){let n;try{n=v.parse(o)}catch{return}if(n.scheme!==TS)return;let e=n.path.replace(/^\//,"");if(e)try{let t=JSON.parse(xn(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 xR(o){try{return v.parse(o).scheme===TS}catch{return!1}}function Is(o){if(o===Je)return!0;try{return v.parse(o).scheme===FU}catch{return!1}}function et(o,n){return n?`${o.replace(/#/g,"%23")}#range=${n.start.line}:${n.start.character}-${n.end.line}:${n.end.character}`:o}function AR(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 PR(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 HU="subagent",$U=`/${HU}/`,WU=/^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;function ER(o){return typeof o=="string"?v.parse(o):o}function kR(o){let n=ER(o),e=n.path.endsWith("/")?n.path.slice(0,-1):n.path;return{parent:n,path:`${e}${$U}`}}function ja(o,n){let{parent:e,path:t}=kR(o);return e.with({path:`${t}${n}`}).toString()}function It(o){let n=ER(o),e=WU.exec(n.path);if(e?.groups)return{parentSession:n.with({path:e.groups.parentPath}),toolCallId:e.groups.toolCallId}}function Ir(o){return It(o)!==void 0}function DR(o){let{parent:n,path:e}=kR(o);return n.with({path:e}).toString()}function MR(){return{agents:[],activeSessions:0}}function wS(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.workingDirectories!==void 0&&(n.workingDirectories=o.workingDirectories),o.annotations!==void 0&&(n.annotations=o.annotations),o._meta!==void 0&&(n._meta=o._meta),n}function kf(o){return{resource:o.resource,title:o.title,status:o.status,activity:o.activity,modifiedAt:o.modifiedAt,origin:o.origin,interactivity:o.interactivity,workingDirectories:o.workingDirectories,primaryWorkingDirectory:o.primaryWorkingDirectory,turns:[],activeTurn:void 0}}function Df(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}var qU=31;function BU(o){return!!o.activeTurn?.responseParts.some(n=>n.kind==="toolCall"&&n.toolCall.status==="pending-confirmation"&&An(n.toolCall).autoApproveBySetting===!0)}function zU(o){return!!o.activeTurn?.responseParts.some(n=>{if(n.kind==="inputRequest")return n.response===void 0;if(n.kind!=="toolCall")return!1;let e=n.toolCall.status;return e==="pending-result-confirmation"||e==="auth-required"?!0:e==="pending-confirmation"&&An(n.toolCall).autoApproveBySetting!==!0})}function VU(o){let n=o.status;return(n&24)!==24?n:BU(o)&&!zU(o)?n&~qU|8:n}function OR(o){let n={resource:o.resource,title:o.title,status:VU(o),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.workingDirectories!==void 0&&(n.workingDirectories=o.workingDirectories),o.primaryWorkingDirectory!==void 0&&(n.primaryWorkingDirectory=o.primaryWorkingDirectory),n}function jU(o,n){return o==="hidden"?"hidden":n?"read-only":o??"full"}function LR(o,n){return jU(o,n)==="read-only"}var Bc="ahp-chat",NR="default";function fi(o,n){let e=typeof o=="string"?o:o.toString(),t=_o($.fromString(e),!1,!0);return`${Bc}://${n}/${t}`}function pe(o){return fi(o,NR)}var Pf="subagent";function bs(o){let n=typeof o=="string"?v.parse(o):o;return n.scheme===Bc&&n.authority===Pf}function _s(o,n){let e=typeof o=="string"?o:o.toString(),t=_o($.fromString(e),!1,!0);return`${Bc}://${Pf}/${t}/${encodeURIComponent(n)}`}function Le(o){let n;try{n=typeof o=="string"?v.parse(o):o}catch{return}if(n.scheme!==Bc||!n.authority)return;let e=n.path.replace(/^\//,"");if(e)try{if(n.authority===Pf){let[t,...r]=e.split("/"),i=r.join("/");return!t||!i?void 0:{session:xn(t).toString(),chatId:`${Pf}/${decodeURIComponent(i)}`}}return{session:xn(e).toString(),chatId:n.authority}}catch{return}}function Ka(o){return Le(o)?.session}function ce(o){let n=Ka(o);if(n===void 0)throw new Error(`Malformed AHP chat URI: ${typeof o=="string"?o:o.toString()}`);return n}function Re(o){return Le(o)?.chatId===NR}function de(o){try{return v.parse(o).scheme===Bc}catch{return!1}}function UR(o,n){return{...o,workingDirectories:n?.workingDirectories??o.workingDirectories,primaryWorkingDirectory:n?.primaryWorkingDirectory,turns:n?.turns??[],activeTurn:n?.activeTurn,steeringMessage:n?.steeringMessage,queuedMessages:n?.queuedMessages,draft:n?.draft}}var $c="git",Wc="github",vR="vscode.promptCache";function FR(o,n){let e={...o};return n?e[vR]=n:delete e[vR],Object.keys(e).length>0?e:void 0}function bt(o){let n=o?.[$c];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 Mf(o,n){let e={...o};return n!==void 0?e[$c]=n:delete e[$c],Object.keys(e).length>0?e:void 0}function br(o){let n=o?.[Wc];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 Of(o,n){let e={...o};return n!==void 0?e[Wc]=n:delete e[Wc],Object.keys(e).length>0?e:void 0}var HR="agentHost/sessionSpawnDepth";function $R(o){let n=o?.[HR];return typeof n=="number"&&Number.isFinite(n)?n:0}function WR(o,n){return{...o,[HR]:n}}var _S="workspaceless",rr="agentHost.workspaceless",or="isArchived",Fr="isDone";function zc(o){return o?.[_S]===!0}function Lf(o,n){let e={...o};return n?e[_S]=!0:delete e[_S],Object.keys(e).length>0?e:void 0}var SR="hostBuild";function qR(o){return{version:o.version,commit:o.commit,date:o.date,quality:o.quality}}function BR(o,n){let e={...o};return n!==void 0?e[SR]=n:delete e[SR],Object.keys(e).length>0?e:void 0}var Nf="VSCODE_AGENT_HOST_CLAUDE_SDK_ROOT",zR="VSCODE_AGENT_HOST_CLAUDE_AGENT_ENABLED",VR="VSCODE_AGENT_HOST_CODEX_AGENT_ENABLED",jR="VSCODE_AGENT_HOST_BYOK_MODELS_ENABLED",KR="VSCODE_AGENT_HOST_SESSION_RELEASE_GRACE_MS";function Uf(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 GR="VSCODE_AGENT_HOST_CODEX_SDK_ROOT",JR="CODEX_HOME",YR="VSCODE_AGENT_HOST_CODEX_APP_SERVER_ARGS";var QR="agent-host/otel/agent-host-traces.db",pJ=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 XR="claude",Ff="codex";var KU=60;function RS(o,n){let e=o?.trim();return e?fn(e,KU):n?.trim()||"Subagent"}var Ts;(n=>{function o(e){if(e.kind!=="subagent_started")return;let t;try{t=ce(e.chat)}catch{return}return{session:v.parse(t),chat:v.parse(_s(t,e.toolCallId)),parent:{chat:e.chat,toolCallId:e.toolCallId},title:RS(e.taskDescription,e.agentDisplayName)}}n.toSpawnEvent=o})(Ts||={});var M;(t=>{function o(r,i){return v.from({scheme:r,path:`/${i}`})}t.uri=o;function n(r){return(typeof r=="string"?v.parse(r):r).path.substring(1)}t.id=n;function e(r){return(typeof r=="string"?v.parse(r):r).scheme||void 0}t.provider=e})(M||={});var Hr=B("agentService"),fJ=B("agentHostService");function sn(o,n){return o===n}function GU(){return(o,n)=>o===n}function xS(o,n,e){return Nn(o,n,e??sn)}function JU(o){return(n,e)=>Nn(n,e,o??sn)}function gi(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(!gi(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)||!gi(e[a],t[a]))return!1;return!0}return!1}function YU(){return(o,n)=>gi(o,n)}function QU(o,n){return JSON.stringify(o)===JSON.stringify(n)}function XU(){return(o,n)=>JSON.stringify(o)===JSON.stringify(n)}function ZU(){return(o,n)=>o.equals(n)}function e2(o,n,e){return o==null||n===void 0||n===null?n===o:e(o,n)}function t2(o){return(n,e)=>n==null||e===void 0||e===null?e===n:o(n,e)}var n2;(u=>(u.strict=sn,u.strictC=GU,u.array=xS,u.arrayC=JU,u.structural=gi,u.structuralC=YU,u.jsonStringify=QU,u.jsonStringifyC=XU,u.thisC=ZU,u.ifDefined=e2,u.ifDefinedC=t2))(n2||={});var ir=B("configurationService");function Hf(o){let n=o;return n&&typeof n=="object"&&(!n.overrideIdentifier||typeof n.overrideIdentifier=="string")&&(!n.resource||n.resource instanceof v)}function ZR(o){let n=o;return n&&typeof n=="object"&&(!n.overrideIdentifiers||Array.isArray(n.overrideIdentifiers))&&!n.overrideIdentifier&&(!n.resource||n.resource instanceof v)}function $f(o,n){let e=Object.create(null);for(let t in o)AS(e,t,o[t],n);return e}function AS(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 ex(o,n){let e=n.split(".");tx(o,e)}function tx(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)&&(tx(r,n),Object.keys(r).length===0&&delete e[t])}}function Vc(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 nx(o){return o.replace(/^\[/,"").replace(/]$/g,"").replace(/\]\[/g,", ")}var Pn=B("telemetryService");var bJ=B("customEndpointTelemetryService");var rx="telemetry",Ga="telemetry.telemetryLevel",Wf="telemetry.enableCrashReporter",jc="telemetry.enableTelemetry";var oe={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603},ge={SessionNotFound:-32001,ProviderNotFound:-32002,SessionAlreadyExists:-32003,TurnInProgress:-32004,UnsupportedProtocolVersion:-32005,ContentNotFound:-32006,AuthRequired:-32007,NotFound:-32008,PermissionDenied:-32009,AlreadyExists:-32010,Conflict:-32011};var qf=-32700,Ja=-32603,Dt=-32001,ix=-32002;var sx=-32005;var _r=-32007;function ax(o){return"method"in o&&"id"in o}function lx(o){return"method"in o&&!("id"in o)}var N=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}};function ae(o){let n=PS(o);return{protocol:o,validate:r=>{try{return n(r,""),!0}catch{return!1}},assertValid:(r,i="")=>n(r,i)}}function Hn(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 N(oe.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 PS(o){if(o.type==="object"&&o.properties){let n={};for(let t of Object.keys(o.properties))n[t]=PS(o.properties[t]);let e=new Set(o.required??[]);return(t,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw ws(r,"object",t);let i=t;for(let s of Object.keys(n)){let a=d2(r,s);if(i[s]===void 0){if(e.has(s))throw new N(oe.InvalidParams,`Missing required property at '${a}'`);continue}n[s](i[s],a)}}}if(o.type==="array"&&o.items){let n=PS(o.items);return(e,t)=>{if(!Array.isArray(e))throw ws(t,"array",e);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`)}}return l2(o)}function l2(o){let n=o.enumDynamic===!0;return(e,t)=>{switch(o.type){case"string":if(typeof e!="string")throw ws(t,"string",e);break;case"number":if(typeof e!="number")throw ws(t,"number",e);break;case"boolean":if(typeof e!="boolean")throw ws(t,"boolean",e);break;case"array":if(!Array.isArray(e))throw ws(t,"array",e);break;case"object":if(typeof e!="object"||e===null||Array.isArray(e))throw ws(t,"object",e);break}if(o.enum&&!n&&!o.enum.includes(e))throw new N(oe.InvalidParams,`Invalid value at '${t||"<root>"}': ${cx(e)} is not one of [${o.enum.map(r=>JSON.stringify(r)).join(", ")}]`)}}function ws(o,n,e){return new N(oe.InvalidParams,`Invalid value at '${o||"<root>"}': expected ${n}, got ${cx(e)}`)}function d2(o,n){return o?`${o}.${n}`:n}function cx(o){try{return JSON.stringify(o)}catch{return String(o)}}var ux=ae({type:"object",title:f(1923,null),description:f(1927,null),properties:{allow:{type:"array",title:f(1924,null),items:{type:"string",title:f(1926,null)}},deny:{type:"array",title:f(1925,null),items:{type:"string",title:f(1926,null)}}},default:{allow:[],deny:[]},sessionMutable:!0}),Pt=Hn({autoApprove:ae({type:"string",title:f(1907,null),description:f(1914,null),enum:["default","assisted","autoApprove"],enumLabels:[f(1912,null),f(1908,null),f(1910,null)],enumDescriptions:[f(1913,null),f(1909,null),f(1911,null)],default:"default",sessionMutable:!0}),permissions:ux,mode:ae({type:"string",title:f(1915,null),description:f(1922,null),enum:["interactive","plan","autopilot"],enumLabels:[f(1918,null),f(1920,null),f(1916,null)],enumDescriptions:[f(1919,null),f(1921,null),f(1917,null)],default:"interactive",sessionMutable:!0})});function px(o){if(!o||o.autoApprove!=="autopilot")return o;let n={...o};return n.mode!=="plan"&&(n.mode="autopilot"),n.autoApprove="default",n}var Kc="telemetryLevel",ES="disableRepoInfoTelemetry";var Gc="sessionSyncEnabled",kS="codexAgentEnabled",DS="terminalAutoApproveEnabled";var Ya="globalAutoApproveEnabled";var MS="autoReplyEnabled";var OS="preferLongContextEnabled";var LS="systemProxyEnabled",NS="terminalAutoApproveRules";var mi="mcpServers";function fx(o){switch(o){case 0:return"off";case 1:return"crash";case 2:return"error";case 3:return"all"}}function gx(o){switch(o){case"off":return 0;case"crash":return 1;case"error":return 2;case"all":return 3;default:return}}var c2={type:{type:"string",title:f(1892,null),description:f(1891,null),enum:["stdio","http"]},command:{type:"string",title:f(1880,null),description:f(1879,null)},args:{type:"array",title:f(1878,null),description:f(1877,null),items:{type:"string",title:f(1876,null)}},env:{type:"object",title:f(1887,null),description:f(1886,null)},cwd:{type:"string",title:f(1882,null),description:f(1881,null)},url:{type:"string",title:f(1894,null),description:f(1893,null)},headers:{type:"object",title:f(1889,null),description:f(1888,null)}},u2={"<serverName>":{type:"object",title:f(1885,null),description:f(1884,null),properties:c2}},tt=Hn({permissions:ux,[ES]:ae({type:"boolean",title:f(1873,null),description:f(1872,null),default:!1}),[Kc]:ae({type:"string",title:f(1902,null),description:f(1901,null),enum:["all","error","crash","off"],default:"all"}),[Gc]:ae({type:"boolean",title:f(1898,null),description:f(1897,null),default:!1}),[kS]:ae({type:"boolean",title:f(1871,null),description:f(1870,null),default:!1}),[DS]:ae({type:"boolean",title:f(1904,null),description:f(1903,null),default:!0}),[Ya]:ae({type:"boolean",title:f(1875,null),description:f(1874,null),default:!1}),[MS]:ae({type:"boolean",title:f(1869,null),description:f(1868,null),default:!1}),[OS]:ae({type:"boolean",title:f(1896,null),description:f(1895,null),default:!1}),[LS]:ae({type:"boolean",title:f(1900,null),description:f(1899,null),default:!0}),[NS]:ae({type:"object",title:f(1906,null),description:f(1905,null),default:{}}),[mi]:ae({type:"object",title:f(1890,null),description:f(1883,null),properties:u2,default:{}})});var Mt=class{constructor(n,e,t){this.owner=n;this.debugNameSource=e;this.referenceFn=t}getDebugName(n){return vx(n,this)}},mx=new Map,US=new WeakMap;function vx(o,n){let e=US.get(o);if(e)return e;let t=p2(o,n);if(t){let r=mx.get(t)??0;r++,mx.set(t,r);let i=r===1?t:`${t}#${r}`;return US.set(o,i),i}}function p2(o,n){let e=US.get(o);if(e)return e;let t=n.owner?g2(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=Jc(s),r!==void 0))return t+r;if(n.owner!==void 0){let a=f2(n.owner,o);if(a!==void 0)return t+a}}function f2(o,n){for(let e in o)if(o[e]===n)return e}var hx=new Map,yx=new WeakMap;function g2(o){let n=yx.get(o);if(n)return n;let e=FS(o)??"Object",t=hx.get(e)??0;t++,hx.set(e,t);let r=t===1?e:`${e}#${t}`;return yx.set(o,r),r}function FS(o){let n=o.constructor;if(n)return n.name==="Object"?void 0:n.name}function Jc(o){let n=o.toString(),t=/\/\*\*\s*@description\s*([^*]*)\*\//.exec(n);return(t?t[1]:void 0)?.trim()}function HS(o){let n=new Error("BugIndicatingErrorRecovery: "+o);Ye(n),console.error("recovered from an error that indicates a bug",n)}var Rs;function Yc(o){Rs?Rs instanceof zf?Rs.loggers.push(o):Rs=new zf([Rs,o]):Rs=o}function Ve(){return Rs}var $S;function Sx(o){$S=o}function Cx(o){$S&&$S(o)}var zf=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 sr(o,n){let e=new hi(o,n);try{o(e)}finally{e.finish()}}function WS(o,n,e){o?n(o):sr(n,e)}var hi=class{constructor(n,e){this._fn=n;this._getDebugName=e;this._updatingObservers=[];Ve()?.handleBeginTransaction(this)}getDebugName(){return this._getDebugName?this._getDebugName():Jc(this._fn)}updateObserver(n,e){if(!this._updatingObservers){HS("Transaction already finished!"),sr(t=>{t.updateObserver(n,e)});return}this._updatingObservers.push({observer:n,observable:e}),n.beginUpdate(e)}finish(){let n=this._updatingObservers;if(!n){HS("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,Ve()?.handleEndTransaction(this)}debugGetUpdatingObservers(){return this._updatingObservers}};var _t;(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,qS.fromStack(s,2)}t.ofCaller=e})(_t||={});var qS=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=m2(t[e+1]);if(r)return new o(r.fileName,r.line,r.column,r.id)}};function m2(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 BS;function Ix(o){BS=o}var bx;function _x(o){bx=o}var Tx;function wx(o){Tx=o}var zS;function Rx(o){zS=o}var Vf=class{get TChange(){return null}reportChanges(){this.get()}read(n){return n?n.readObservable(this):this.get()}map(n,e,t=_t.ofCaller()){let r=e===void 0?void 0:n,i=e===void 0?n:e;return BS({owner:r,debugName:()=>{let s=Jc(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 BS({owner:void 0,debugName:()=>`${this.debugName} (flattened)`},n=>this.read(n).read(n))}recomputeInitiallyAndOnChange(n,e){return n.add(bx(this,e)),this}keepObserved(n){return n.add(Tx(this)),this}get debugValue(){return this.get()}get debug(){return new VS(this)}},VS=class{constructor(n){this.observable=n}getDependencyGraph(){return zS(this.observable,{type:"dependencies"})}getObserverGraph(){return zS(this.observable,{type:"observers"})}},ar=class extends Vf{constructor(e){super();this._observers=new Set;Ve()?.handleObservableCreated(this,e)}addObserver(e){let t=this._observers.size;this._observers.add(e),t===0&&this.onFirstObserverAdded(),t!==this._observers.size&&Ve()?.handleOnListenerCountChanged(this,this._observers.size)}removeObserver(e){let t=this._observers.delete(e);t&&this._observers.size===0&&this.onLastObserverRemoved(),t&&Ve()?.handleOnListenerCountChanged(this,this._observers.size)}onFirstObserverAdded(){}onLastObserverRemoved(){}log(){let e=!!Ve();return Cx(this),e||Ve()?.handleObservableCreated(this,_t.ofCaller()),this}debugGetObservers(){return this._observers}};function yn(o,n,e=_t.ofCaller()){let t;return typeof o=="string"?t=new Mt(void 0,o,void 0):t=new Mt(o,void 0,void 0),new Wr(t,n,sn,e)}var Wr=class extends ar{constructor(e,t,r,i){super(i);this._debugNameData=e;this._equalityComparator=r;this._value=t,Ve()?.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 hi(()=>{},()=>`Setting ${this.debugName}`));try{let s=this._value;this._setValue(e),Ve()?.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 jf=class extends ar{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){Ve()?.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{Ve()?.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 hi(()=>{},()=>`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 xs(o,n,e=_t.ofCaller()){return o.lazy?new jf(new Mt(o.owner,o.debugName,void 0),n,o.equalsFn??sn,e):new Wr(new Mt(o.owner,o.debugName,void 0),n,o.equalsFn??sn,e)}function h2(o){switch(o){case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var xo=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),Ve()?.handleAutorunCreated(this,r),this._run(),Xo(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(),Ve()?.handleAutorunDisposed(this),Zo(this)}}_run(){let n=this._dependenciesToBeRemoved;this._dependenciesToBeRemoved=this._dependencies,this._dependencies=n,this._state=3;try{if(!this._disposed){Ve()?.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){Yo(r)}finally{this._isRunning=!1,t!==void 0&&t.dispose()}}}finally{this._disposed||Ve()?.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--}Cc(()=>this._updateCount>=0)}handlePossibleChange(n){this._state===3&&this._isDependency(n)&&(this._checkIterations(),this._state=1)}handleChange(n,e){if(this._isDependency(n)){Ve()?.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){Yo(t)}}}_isDependency(n){return this._dependencies.has(n)&&!this._dependenciesToBeRemoved.has(n)}_ensureNoRunning(){if(!this._isRunning)throw new qe("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 qe("Cannot access store after dispose");return this._store===void 0&&(this._store=new G),this._store}get delayedStore(){if(this._ensureNoRunning(),this._disposed)throw new qe("Cannot access store after dispose");return this._delayedStore===void 0&&(this._delayedStore=new G),this._delayedStore}debugGetState(){return{isRunning:this._isRunning,updateCount:this._updateCount,dependencies:this._dependencies,state:this._state,stateStr:h2(this._state)}}debugRerun(){this._isRunning?this._state=2:this._run()}_checkIterations(){return this._iteration>100?(Yo(new qe(`Autorun '${this.debugName}' is stuck in an infinite update loop.`)),!0):!1}};function En(o,n=_t.ofCaller()){return new xo(new Mt(void 0,void 0,o),o,void 0,n)}function y2(o){switch(o){case 0:return"initial";case 1:return"dependenciesMightHaveChanged";case 2:return"stale";case 3:return"upToDate";default:return"<unknown>"}}var Ot=class extends ar{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,Ve()?.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),Ve()?.handleObservableUpdated(this,{oldValue:s,newValue:this._value,change:void 0,didChange:e,hadValue:i})}catch(r){Yo(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 qe("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)}}Cc(()=>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){Ve()?.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){Yo(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 qe("The reader object cannot be used outside its compute function!")}readObservable(e){this._ensureReaderValid(),e.addObserver(this);let t=e.get();return this._dependencies.add(e),this._dependenciesToBeRemoved.delete(e),t}reportChange(e){this._ensureReaderValid(),this._didReportChange=!0;for(let t of this._observers)t.handleChange(this,e)}get store(){return this._ensureReaderValid(),this._store===void 0&&(this._store=new G),this._store}get delayedStore(){return this._ensureReaderValid(),this._delayedStore===void 0&&(this._delayedStore=new G),this._delayedStore}addObserver(e){let t=!this._observers.has(e)&&this._updateCount>0;super.addObserver(e),t&&(this._removedObserverToCallEndUpdateOn?.delete(e)||e.beginUpdate(this))}removeObserver(e){this._observers.has(e)&&this._updateCount>0&&(this._removedObserverToCallEndUpdateOn||(this._removedObserverToCallEndUpdateOn=new Set),this._removedObserverToCallEndUpdateOn.add(e)),super.removeObserver(e)}debugGetState(){return{state:this._state,stateStr:y2(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 Qc(o,n,e=_t.ofCaller()){return n!==void 0?new Ot(new Mt(o,void 0,n),n,void 0,void 0,sn,e):new Ot(new Mt(void 0,void 0,o),o,void 0,void 0,sn,e)}function jS(o,n,e=_t.ofCaller()){return new Ot(new Mt(o.owner,o.debugName,o.debugReferenceFn),n,void 0,o.onLastObserverRemoved,o.equalsFn??sn,e)}Ix(jS);function As(...o){let n,e,t,r;return o.length===2?[e,t]=o:[n,e,t,r]=o,new lr(new Mt(n,void 0,t),e,t,()=>lr.globalTransaction,sn,r??_t.ofCaller())}var lr=class extends ar{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,WS(this._getTransaction(),a=>{Ve()?.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||Ve()?.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=lr;function n(t,r){let i=!1;lr.globalTransaction===void 0&&(lr.globalTransaction=t,i=!0);try{r()}finally{i&&(lr.globalTransaction=void 0)}}e.batchEventsGlobally=n})(As||={});function xx(o){let n=new Kf(!1,void 0);return o.addObserver(n),U(()=>{o.removeObserver(n)})}wx(xx);function Ax(o,n){let e=new Kf(!0,n);o.addObserver(e);try{e.beginUpdate(o)}finally{e.endUpdate(o)}return U(()=>{o.removeObserver(e)})}_x(Ax);var Kf=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 Gf;function Px(o){Gf||(Gf=new Xc,Yc(Gf)),Gf.addFilteredObj(o)}var Xc=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 _2([Qa(R2("|  ",this.indentation)),n])}formatInfo(n){return n.hadValue?n.didChange?[Qa(" "),dr($n(n.oldValue,70),{color:"red",strikeThrough:!0}),Qa(" "),dr($n(n.newValue,60),{color:"green"})]:[Qa(" (unchanged)")]:[Qa(" "),dr($n(n.newValue,60),{color:"green"}),Qa(" (initial)")]}handleObservableCreated(n){if(n instanceof Ot){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 Ot){this._handleDerivedRecomputed(n,e);return}console.log(...this.textToConsoleArgs([Xa("observable value changed"),dr(n.debugName,{color:"BlueViolet"}),...this.formatInfo(e)]))}}formatChanges(n){if(n.size!==0)return dr(" (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([Xa("derived recomputed"),dr(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([Xa("derived cleared"),dr(n.debugName,{color:"BlueViolet"})]))}handleFromEventObservableTriggered(n,e){this._isIncluded(n)&&console.log(...this.textToConsoleArgs([Xa("observable from event triggered"),dr(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([Xa("autorun"),dr(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([Xa("transaction"),dr(e,{color:"BlueViolet"}),{data:[{fn:n._fn}]}])),this.indentation++}handleEndTransaction(){this.indentation--}};function _2(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 Qa(o){return dr(o,{color:"black"})}function Xa(o){return dr(x2(`${o}: `,10),{color:"black",bold:!0})}function dr(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 $n(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)?T2(o,n):w2(o,n);case"symbol":return o.toString();case"function":return`[[Function${o.name?" "+o.name:""}]]`;default:return""+o}}function T2(o,n){let e="[ ",t=!0;for(let r of o){if(t||(e+=", "),e.length-5>n){e+="...";break}t=!1,e+=`${$n(r,n-e.length)}`}return e+=" ]",e}function w2(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=FS(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}: ${$n(s,n-t.length)}`}return t+=e?")":" }",t}function R2(o,n){let e="";for(let t=1;t<=n;t++)e+=o;return e}function x2(o,n){for(;o.length<n;)o+=" ";return o}var Jf=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 Ex(o,n){let e=globalThis,t=[],r,{channel:i,handler:s}=A2({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},Jf.createClient(i,()=>{if(!a)throw new Error("Not supported");return a})}function A2(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 Yf=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 KS(o,n){for(let e in n)o[e]&&typeof o[e]=="object"&&n[e]&&typeof n[e]=="object"?KS(o[e],n[e]):o[e]=n[e]}function GS(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"?GS(o[e],n[e]):o[e]=n[e]}var Qf=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=Ex("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(Mr)}),getDerivedInfo:n=>{let e=this._aliveInstances.get(n);return{dependencies:[...e.debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(Mr),observers:[...e.debugGetObservers()].map(t=>this._formatObserver(t)).filter(Mr)}},getAutorunInfo:n=>({dependencies:[...this._aliveInstances.get(n).debugGetState().dependencies].map(t=>this._formatObservable(t)).filter(Mr)}),getTransactionState:()=>this.getTransactionState(),setValue:(n,e)=>{let t=this._aliveInstances.get(n);if(t instanceof Ot)t.debugSetValue(e);else if(t instanceof Wr)t.debugSetValue(e);else if(t instanceof lr)t.debugSetValue(e);else throw new qe("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 Ot)return $n(e.debugGetState().value,200);if(e instanceof Wr)return $n(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 qe("Observable is not supported")},rerun:n=>{let e=this._aliveInstances.get(n);if(e instanceof Ot)e.debugRecompute();else if(e instanceof xo)e.debugRerun();else throw new qe("Observable is not supported")}}}));this._pendingChanges=null;this._changeThrottler=new Yf;this._fullState={};this._flushUpdates=()=>{this._pendingChanges!==null&&(this._channel.api.notifications.handleChange(this._pendingChanges,!1),this._pendingChanges=null)};_t.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){Ye(new qe("No info found"));return}return e}_getAutorunInfo(n){let e=this._instanceInfos.get(n);if(!e){Ye(new qe("No info found"));return}return e}_getInfo(n,e){if(n instanceof Ot){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(Mr);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 xo){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 Ot)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){GS(this._fullState,n),this._pendingChanges===null?this._pendingChanges=n:KS(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 Ot?"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 Ot){this._handleDerivedRecomputed(n,e);return}let t=this._getObservableInfo(n);t&&e.didChange&&(t.lastValue=$n(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=$n(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 kx(o,n){let e=n?.debugNamePostProcessor??(i=>i),t=Ps.from(o,e);if(!t)return"";let r=new Set;return n.type==="observers"?Mx(t,0,r,n).trim():Dx(t,0,r,n).trim()}function Dx(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: ${$n(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=Ps.from(a,t.debugNamePostProcessor??(d=>d))??Ps.unknown(a);i.push(Dx(l,n+1,e,t))}}return i.join(`
`)}function Mx(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: ${$n(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=Ps.from(a,t.debugNamePostProcessor??(d=>d))??Ps.unknown(a);i.push(Mx(l,n+1,e,t))}}return i.join(`
`)}var Ps=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 xo){let t=n.debugGetState();return new o(n,e(n.debugName),"autorun",void 0,t.stateStr,Array.from(t.dependencies),[])}else if(n instanceof Ot){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 Wr){let t=n.debugGetState();return new o(n,e(n.debugName),"observableValue",t.value,"upToDate",[],Array.from(n.debugGetObservers()))}else if(n instanceof lr){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",[],[])}};Rx(kx);Sx(Px);var P2=!1;P2&&Yc(new Xc);at&&at.VSCODE_DEV_DEBUG_OBSERVABLES&&Yc(Qf.getInstance());function JS(o,n){return n&&(o.stack||o.stacktrace)?f(116,null,Lx(o),Ox(o.stack)||Ox(o.stacktrace)):Lx(o)}function Ox(o){return Array.isArray(o)?o.join(`
`):o}function Lx(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=Qo(o),t=De(e[0],n);return e.length>1?f(114,null,t,e.length):t}if(Be(o))return o;if(o.detail){let e=o.detail;if(e.error)return JS(e.error,n);if(e.exception)return JS(e.exception,n)}return o.stack?JS(o,n):o.message?o.message:f(113,null)}function kn(o){return QS(o,0)}function QS(o,n){switch(typeof o){case"object":return o===null?Ao(349,n):Array.isArray(o)?k2(o,n):D2(o,n);case"string":return Ux(o,n);case"boolean":return E2(o,n);case"number":return Ao(o,n);case"undefined":return Ao(937,n);default:return Ao(617,n)}}function Ao(o,n){return(n<<5)-n+o|0}function E2(o,n){return Ao(o?433:863,n)}function Ux(o,n){n=Ao(149417,n);for(let e=0,t=o.length;e<t;e++)n=Ao(o.charCodeAt(e),n);return n}function k2(o,n){return n=Ao(104579,n),o.reduce((e,t)=>QS(t,e),n)}function D2(o,n){return n=Ao(181387,n),Object.keys(o).sort().reduce((e,t)=>(e=Ux(t,e),QS(o[t],e)),n)}function YS(o,n,e=32){let t=e-n,r=~((1<<t)-1);return(o<<n|(r&o)>>>t)>>>0}function Zc(o,n=32){return o instanceof ArrayBuffer?di($.wrap(new Uint8Array(o))):(o>>>0).toString(16).padStart(n/4,"0")}var Nx=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(hw(s))if(a+1<e){let d=n.charCodeAt(a+1);rS(d)?(a++,l=yw(s,d)):l=65533}else{i=s;break}else rS(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()),Zc(this._h0)+Zc(this._h1)+Zc(this._h2)+Zc(this._h3)+Zc(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,YS(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=YS(t,5)+l+a+d+n.getUint32(u*4,!1)&4294967295,a=s,s=i,i=YS(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 XS(...o){switch(o.length){case 1:return f(2541,null,o[0]);case 2:return f(2542,null,o[0],o[1]);case 3:return f(2543,null,o[0],o[1],o[2]);default:return}}var M2=f(2540,null),O2=f(2539,null),yi=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 Wp(`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(XS("==","=~"));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(XS("&&"));break;case 124:this._match(124)?this._addToken(16):this._error(XS("||"));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(M2);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(O2);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 Ht=new Map;Ht.set("false",!1);Ht.set("true",!0);Ht.set("isMac",ft);Ht.set("isLinux",Fe);Ht.set("isWindows",X);Ht.set("isWeb",Qn);Ht.set("isMacNative",ft&&!Qn);Ht.set("isEdge",YT);Ht.set("isFirefox",GT);Ht.set("isChrome",Vv);Ht.set("isSafari",JT);var L2=Object.prototype.hasOwnProperty;var N2={regexParsingWithErrorRecovery:!0},U2=f(2520,null),F2=f(2521,null),H2=f(2523,null),Fx=f(2519,null),$2=f(2526,null),W2=f(2527,null),q2=f(2524,null),B2=f(2525,null),ZS=class o{constructor(n=N2){this._config=n;this._scanner=new yi;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:U2,offset:0,lexeme:"",additionalInfo:F2});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?W2:void 0;throw this._parsingErrors.push({message:$2,offset:t.offset,lexeme:yi.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]:zt.or(...n)}_and(){let n=[this._term()];for(;this._matchOne(15);){let e=this._term();n.push(e)}return n.length===1?n[0]:zt.and(...n)}_term(){if(this._matchOne(2)){let n=this._peek();switch(n.type){case 11:return this._advance(),Yt.INSTANCE;case 12:return this._advance(),an.INSTANCE;case 0:{this._advance();let e=this._expr();return this._consume(1,Fx),e?.negate()}case 17:return this._advance(),ks.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(),zt.true();case 12:return this._advance(),zt.false();case 0:{this._advance();let e=this._expr();return this._consume(1,Fx),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 su.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(yi.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 zt.regex(e,u)}case 18:{let i=r.lexeme;this._advance();let s=null;if(!uw(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 su.create(e,s)}default:throw this._errExpectedButGot("REGEX",this._peek())}}if(this._matchOne(14)){this._consume(13,H2);let r=this._value();return zt.notIn(e,r)}switch(this._peek().type){case 3:{this._advance();let r=this._value();if(this._previous().type===18)return zt.equals(e,r);switch(r){case"true":return zt.has(e);case"false":return zt.not(e);default:return zt.equals(e,r)}}case 4:{this._advance();let r=this._value();if(this._previous().type===18)return zt.notEquals(e,r);switch(r){case"true":return zt.not(e);case"false":return zt.has(e);default:return zt.notEquals(e,r)}}case 5:return this._advance(),ou.create(e,this._value());case 6:return this._advance(),iu.create(e,this._value());case 7:return this._advance(),Za.create(e,this._value());case 8:return this._advance(),ru.create(e,this._value());case 13:return this._advance(),zt.in(e,this._value());default:return zt.has(e)}}case 20:throw this._parsingErrors.push({message:q2,offset:n.offset,lexeme:"",additionalInfo:B2}),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(2522,null,n,yi.getLexeme(e)),i=e.offset,s=yi.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}},zt=class{static false(){return Yt.INSTANCE}static true(){return an.INSTANCE}static has(n){return Es.create(n)}static equals(n,e){return tu.create(n,e)}static notEquals(n,e){return nu.create(n,e)}static regex(n,e){return su.create(n,e)}static in(n,e){return Xf.create(n,e)}static notIn(n,e){return Zf.create(n,e)}static not(n){return ks.create(n)}static and(...n){return eg.create(n,null,!0)}static or(...n){return au.create(n,null,!0)}static greater(n,e){return Za.create(n,e)}static greaterEquals(n,e){return ru.create(n,e)}static smaller(n,e){return ou.create(n,e)}static smallerEquals(n,e){return iu.create(n,e)}static{this._parser=new ZS({regexParsingWithErrorRecovery:!1})}static deserialize(n){return n==null?void 0:this._parser.parse(n)}};function eu(o,n){return o.cmp(n)}var Yt=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 an.INSTANCE}},an=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 Yt.INSTANCE}},Es=class o{constructor(n,e){this.key=n;this.negated=e;this.type=2}static create(n,e=null){let t=Ht.get(n);return typeof t=="boolean"?t?an.INSTANCE:Yt.INSTANCE:new o(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:Wx(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=Ht.get(this.key);return typeof n=="boolean"?n?an.INSTANCE:Yt.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=ks.create(this.key,this)),this.negated}},tu=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?Es.create(n,t):ks.create(n,t);let r=Ht.get(n);return typeof r=="boolean"?e===(r?"true":"false")?an.INSTANCE:Yt.INSTANCE:new o(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=Ht.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?an.INSTANCE:Yt.INSTANCE}return this}evaluate(n){return n.getValue(this.key)==this.value}serialize(){return`${this.key} == '${this.value}'`}keys(){return[this.key]}map(n){return n.mapEquals(this.key,this.value)}negate(){return this.negated||(this.negated=nu.create(this.key,this.value,this)),this.negated}},Xf=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:Ds(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(X&&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(L2.call(e,t))return!0;if(X&&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=Zf.create(this.key,this.valueKey)),this.negated}},Zf=class o{constructor(n,e){this.key=n;this.valueKey=e;this.type=11;this._negated=Xf.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}},nu=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?ks.create(n,t):Es.create(n,t);let r=Ht.get(n);return typeof r=="boolean"?e===(r?"true":"false")?Yt.INSTANCE:an.INSTANCE:new o(n,e,t)}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=Ht.get(this.key);if(typeof n=="boolean"){let e=n?"true":"false";return this.value===e?Yt.INSTANCE:an.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=tu.create(this.key,this.value,this)),this.negated}},ks=class o{constructor(n,e){this.key=n;this.negated=e;this.type=3}static create(n,e=null){let t=Ht.get(n);return typeof t=="boolean"?t?Yt.INSTANCE:an.INSTANCE:new o(n,e)}cmp(n){return n.type!==this.type?this.type-n.type:Wx(this.key,n.key)}equals(n){return n.type===this.type?this.key===n.key:!1}substituteConstants(){let n=Ht.get(this.key);return typeof n=="boolean"?n?Yt.INSTANCE:an.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=Es.create(this.key,this)),this.negated}};function ng(o,n){if(typeof o=="string"){let e=parseFloat(o);isNaN(e)||(o=e)}return typeof o=="string"||typeof o=="number"?n(o):Yt.INSTANCE}var Za=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 ng(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=iu.create(this.key,this.value,this)),this.negated}},ru=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 ng(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=ou.create(this.key,this.value,this)),this.negated}},ou=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 ng(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=ru.create(this.key,this.value,this)),this.negated}},iu=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 ng(e,r=>new o(n,r,t))}cmp(n){return n.type!==this.type?this.type-n.type:Ds(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=Za.create(this.key,this.value,this)),this.negated}},su=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=eC.create(this)),this.negated}},eC=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 $x(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 eg=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=eu(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=$x(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 Yt.INSTANCE;if(s.type===6){r.push(...s.expr);continue}r.push(s)}if(r.length===0&&i)return an.INSTANCE;if(r.length!==0){if(r.length===1)return r[0];r.sort(eu);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=au.create(s.expr.map(c=>o.create([c,a],null,t)),null,l);d&&(r.push(d),r.sort(eu))}if(r.length===1)return r[0];if(t){for(let s=0;s<r.length;s++)for(let a=s+1;a<r.length;a++)if(r[s].negate().equals(r[a]))return Yt.INSTANCE;if(r.length===1)return r[0]}return new 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=au.create(n,this,!0)}return this.negated}},au=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=eu(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=$x(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 an.INSTANCE;if(l.type===9){r=r.concat(l.expr);continue}r.push(l)}}if(r.length===0&&i)return Yt.INSTANCE;r.sort(eu)}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 an.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 Hx(e))for(let s of Hx(t))r.push(eg.create([i,s],null,!1));n.unshift(o.create(r,null,!1))}this.negated=o.create(n,this,!0)}return this.negated}},tg=class o extends Es{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 tu.create(this.key,n)}notEqualsTo(n){return nu.create(this.key,n)}greater(n){return Za.create(this.key,n)}},Vee=B("contextKeyService");function Wx(o,n){return o<n?-1:o>n?1:0}function Ds(o,n,e,t){return o<e?-1:o>e?1:n<t?-1:n>t?1:0}function Hx(o){return o.type===9?o.expr:[o]}var O=B("logService"),Bx=B("loggerService");function nC(o){return is(o)}var zx=3;function z2(o,n){return o!==0&&o<=n}function V2(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 Vx=!1,qx=!1,j2=!1;function lu(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 jx(o){let n={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn},e=(r,i,s)=>{if(!j2){qx=!0;try{V2(o,i,Po(s))}catch{}finally{qx=!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 lu("debug",t.debug),lu("error",t.error),lu("info",t.info),lu("log",t.log),lu("warn",t.warn),U(()=>{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 Po(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 rg=class extends x{constructor(){super(...arguments);this.level=zx;this._onDidChangeLogLevel=this._register(new E)}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 z2(this.level,e)}canLog(e){return this._store.isDisposed?!1:this.checkLogLevel(e)}},Ms=class extends rg{constructor(e){super();this.logAlways=e}checkLogLevel(e){return this.logAlways||super.checkLogLevel(e)}trace(e,...t){this.canLog(1)&&this.log(1,Po([e,...t],!0))}debug(e,...t){this.canLog(2)&&this.log(2,Po([e,...t]))}info(e,...t){this.canLog(3)&&this.log(3,Po([e,...t]))}warn(e,...t){this.canLog(4)&&this.log(4,Po([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,Po(r))}else this.log(5,Po([e,...t]))}flush(){}};var og=class extends rg{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()}},du=class extends x{constructor(e,t,r){super();this.logLevel=e;this.logsHome=t;this._loggers=new Me;this._onDidChangeLoggers=this._register(new E);this.onDidChangeLoggers=this._onDidChangeLoggers.event;this._onDidChangeLogLevel=this._register(new E);this.onDidChangeLogLevel=this._onDidChangeLogLevel.event;this._onDidChangeVisibility=this._register(new E);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 Be(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=Be(e)?e:t?.id??kn(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 Be(e)?Y(this.logsHome,`${e.replace(/[\\/:\*\?"<>\|]/g,"")}.log`):e}setLogLevel(e,t){if(v.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()}},tC=class{constructor(){this.onDidChangeLogLevel=new E().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(){}},ig=class extends tC{};function Kx(o){if(o.verbose)return 1;if(typeof o.logLevel=="string"){let n=G2(o.logLevel.toLowerCase());if(n!==void 0)return n}return zx}function K2(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 G2(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 ate=new tg("logLevel",K2(3));var Gx=600*1e3,el=class extends x{constructor(e,t,r){super();this._logService=r;this._timer=this._register(new pf);this._agents=[];this._isTimerRunning=!1;this._register(En(i=>{if(this._agents=e.read(i),this._agents.length===0){this._timer.cancel(),this._isTimerRunning=!1;return}this._isTimerRunning||(this._timer.cancelAndSet(()=>this._refreshAll(this._agents),t),this._isTimerRunning=!0)}))}_refreshAll(e){for(let t of e){if(!t.refreshModels)continue;let r=t.getDescriptor().provider;this._logService.trace(`[AgentHost] Periodic model refresh for ${r}`),t.refreshModels().catch(i=>this._logService.error(i,`[AgentHost] Periodic model refresh failed for ${r}`))}}};el=A([b(2,O)],el);import{open as _9,unlink as T9}from"fs/promises";var yte=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 rC={".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 sg(o){let n=cs(o),e=rC[n.toLowerCase()];return Array.isArray(e)?e[0]:e}function Jx(o){for(let n in rC){let e=rC[n];if(Array.isArray(e)?e.includes(o):e===o)return n}}var oC=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]}},iC=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?nf(n,this._value,0,n.length,this._from,this._to):ps(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}},ag=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?nf(n,this._value,0,n.length,this._from,this._to):ps(n,this._value,0,n.length,this._from,this._to)}value(){return this._value.substring(this._from,this._to)}};var sC=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 ag(!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 tS(n,this._value.scheme);if(this._states[this._stateIdx]===2)return tS(n,this._value.authority);if(this._states[this._stateIdx]===3)return this._pathIterator.cmp(n);if(this._states[this._stateIdx]===4)return Fn(n,this._value.query);if(this._states[this._stateIdx]===5)return Fn(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}},Eo=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}},tl=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 qr=class o{static forUris(n=()=>!1,e=()=>!1){return new o(new sC(n,e))}static forPaths(n=!1){return new o(new ag(void 0,!n))}static forStrings(){return new o(new oC)}static forConfigKeys(){return new o(new iC)}constructor(n){this._iter=n}clear(){this._root=void 0}fill(n,e){if(e){let t=e.slice(0);Lv(t);for(let r of t)this.set(r,n)}else{let t=n.slice(0);Lv(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 tl,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 tl,r.left.segment=t.value()),i.push([-1,r]),r=r.left;else if(a<0)r.right||(r.right=new tl,r.right.segment=t.value()),i.push([1,r]),r=r.right;else if(t.hasNext())t.next(),r.mid||(r.mid=new tl,r.mid.segment=t.value()),i.push([0,r]),r=r.mid;else break}let s=Eo.unwrap(r.value);r.value=Eo.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 Eo.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:Sc(!1);case 1:Sc(!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=Eo.unwrap(t.value)||r,t=t.mid;else break}return t&&Eo.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?Eo.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,Eo.unwrap(n.value)]),n.mid&&this._dfsEntries(n.mid,e),n.right&&this._dfsEntries(n.right,e))}_isBalanced(){let n=e=>{if(!e)return!0;let t=e.balanceFactor();return t<-1||t>1?!1:n(e.left)&&n(e.right)};return n(this._root)}};var xe=B("fileService");function Do(o){return o.create===!0}function Wn(o){return!!(o.capabilities&2)}function Yx(o){return!!(o.capabilities&524288)}function aC(o){return!!(o.capabilities&8)}function Qx(o){return!!(o.capabilities&131072)}function Xx(o){return!!(o.capabilities&262144)}function Mo(o){return!!(o.capabilities&4)}function cg(o){return!!(o.capabilities&16)}function ug(o){return Wn(o)?!!(o.capabilities&16384):!1}function lC(o){return Wn(o)?!!(o.capabilities&32768):!1}function Zx(o){return!!(o.capabilities&65536)}var nl=class o extends Error{constructor(e,t){super(e);this.code=t}static create(e,t){let r=new o(e.toString(),t);return J2(r,t),r}};function Ne(o,n){return nl.create(o,n)}function Oo(o){return o||Ne(f(2740,null),"Unknown")}function J2(o,n){return o.name=n?`${n} (FileSystemError)`:"FileSystemError",o}function cu(o){if(!o)return"Unknown";if(o instanceof nl)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 Vt(o){if(o instanceof vt)return o.fileOperationResult;switch(cu(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 ko=class{constructor(n,e,t){this.resource=n;this.operation=e;this.target=t}isOperation(n){return this.operation===n}};var lg=class o{constructor(n,e){this.ignorePathCasing=e;this.correlationId=void 0;this.added=new Xe(()=>{let n=qr.forUris(()=>this.ignorePathCasing);return n.fill(this.rawAdded.map(e=>[e,!0])),n});this.updated=new Xe(()=>{let n=qr.forUris(()=>this.ignorePathCasing);return n.fill(this.rawUpdated.map(e=>[e,!0])),n});this.deleted=new Xe(()=>{let n=qr.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 eA(o,n,e){return!o||!n||o===n||n.length>o.length?!1:(n.charAt(n.length-1)!==He&&(n+=He),e?ni(o,n):o.indexOf(n)===0)}var vt=class extends Error{constructor(e,t,r){super(e);this.fileOperationResult=t;this.options=r}},rl=class extends vt{constructor(e,t,r,i){super(e,t,i);this.fileOperationResult=t;this.size=r}},ol=class extends vt{constructor(e,t,r){super(e,2,r);this.stat=t}};var pg="";function dC(o){if(!(typeof o.size!="number"||typeof o.mtime!="number"))return o.mtime.toString(29)+o.size.toString(31)}var dg=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 is(n)||(n=0),n<o.KB?f(2735,null,n.toFixed(0)):n<o.MB?f(2737,null,(n/o.KB).toFixed(2)):n<o.GB?f(2738,null,(n/o.MB).toFixed(2)):n<o.TB?f(2736,null,(n/o.GB).toFixed(2)):f(2739,null,(n/o.TB).toFixed(2))}};var cr=class{constructor(n,e=[],t=!1){this.ctor=n,this.staticArguments=e,this.supportsDelayedInstantiation=t}};var cC=class{constructor(n,e){this.key=n;this.data=e;this.incoming=new Map;this.outgoing=new Map}},uu=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 cC(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 vi=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 Y2=!1,fg=class extends Error{constructor(n){super("cyclic dependency between services"),this.message=n.findCycleSlow()??`UNABLE to detect cycle, dumping graph: 
${n.toString()}`}},il=class o{constructor(n=new vi,e=!1,t,r=Y2){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(we,this),this._globalGraph=r?t?._globalGraph??new uu(i=>i):void 0}dispose(){if(!this._isDisposed){this._isDisposed=!0,tn(this._children),this._children.clear();for(let n of this._servicesToMaybeDispose)ba(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=pu.traceInvocation(this._enableTracing,n),r=!1;try{return n({get:s=>{if(r)throw Wp("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 cr?(t=pu.traceCreation(this._enableTracing,n.ctor),r=this._createInstance(n.ctor,n.staticArguments.concat(e),t)):(t=pu.traceCreation(this._enableTracing,n),r=this._createInstance(n,e,t)),t.stop(),r}_createInstance(n,e=[],t){let r=Sr.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 cr)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 cr?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 uu(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 fg(r);for(let d of Sr.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 cr){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 fg(r);break}for(let{data:d}of l){if(this._getServiceInstanceOrDescriptor(d.id)instanceof cr){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 cr)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 gf(()=>{let c=a._createInstance(e,t,i);for(let[u,p]of l){let g=c[u];if(typeof g=="function")for(let h of p)h.disposable=g.apply(c,h.listener)}return l.clear(),s.add(c),c});return new Proxy(Object.create(null),{get(c,u){if(!d.isInitialized&&typeof u=="string"&&(u.startsWith("onDid")||u.startsWith("onWill"))){let h=l.get(u);return h||(h=new _c,l.set(u,h)),(I,S,C)=>{if(d.isInitialized)return d.value[u](I,S,C);{let _={listener:[I,S,C],disposable:void 0},T=h.push(_);return U(()=>{T(),_.disposable?.dispose()})}}}if(u in c)return c[u];let p=d.value,g=p[u];return typeof g!="function"||(g=g.bind(p),c[u]=g),g},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 pu=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(`
`))}};var nt=B("sessionDataService"),sl="session.db",gg="attachments";var lA="branch",dA="uncommitted",cA="session",mg="turn/",uA="{turnId}",hg="compare/",pA="{originalTurnId}",fA="{modifiedTurnId}",Q2=()=>f(1961,null),tA=()=>f(1965,null),nA=()=>f(1964,null),rA=()=>f(1969,null),oA=()=>f(1968,null),iA=()=>f(1967,null),sA=()=>f(1966,null),X2=()=>f(1963,null),Z2=()=>f(1962,null);function eF(o){let{baseBranchName:n,branchName:e,upstreamBranchName:t}=o;return n&&e?`${e} \u2192 ${n}`:t&&e?`${e} \u2192 ${t}`:e}var Lo="/changeset/";function Fo(o){return`${o}${Lo}${lA}`}function No(o){return`${o}${Lo}${cA}`}function Uo(o){return`${o}${Lo}${dA}`}function aA(o){return`${o}${Lo}${mg}${uA}`}function yg(o,n){if(!n||n.includes("/"))throw new Error(`buildTurnChangesetUri: turnId must be non-empty and not contain '/' (got ${JSON.stringify(n)})`);return`${o}${Lo}${mg}${n}`}function tF(o){return`${o}${Lo}${hg}${pA}/${fA}`}function gA(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}${Lo}${hg}${n}/${e}`}function rt(o){let n=o.lastIndexOf(Lo);if(n<0)return;let e=o.slice(n+Lo.length);if(!e)return;let t=o.slice(0,n);if(e===lA)return{sessionUri:t,changesetId:e,kind:"branch"};if(e===dA)return{sessionUri:t,changesetId:e,kind:"uncommitted"};if(e===cA)return{sessionUri:t,changesetId:e,kind:"session"};if(e.startsWith(mg)){let r=e.slice(mg.length);return!r||r.includes("/")||r===uA?void 0:{sessionUri:t,changesetId:e,kind:"turn",turnId:r}}if(e.startsWith(hg)){let i=e.slice(hg.length).split("/");if(i.length!==2)return;let[s,a]=i;return!s||!a||s===pA||a===fA?void 0:{sessionUri:t,changesetId:e,kind:"compare-turns",originalTurnId:s,modifiedTurnId:a}}if(!e.includes("/"))return{sessionUri:t,changesetId:e,kind:"unknown"}}function mA(o,n){if(!n||n.lifecycle==="creationFailed")return[];if(n.lifecycle==="creating")return zc(n._meta)?[]:[{label:rA(),description:oA(),uriTemplate:Uo(o),changeKind:"uncommitted"}];let e=bt(n._meta);return e?[{label:Q2(),description:e?eF(e):void 0,uriTemplate:Fo(o),changeKind:"branch",capabilities:{review:{}}},{label:rA(),description:oA(),uriTemplate:Uo(o),changeKind:"uncommitted"},{label:tA(),description:nA(),uriTemplate:No(o),changeKind:"session"},{label:iA(),description:sA(),uriTemplate:aA(o),changeKind:"turn"},{label:X2(),description:Z2(),uriTemplate:tF(o),changeKind:"compare-turns"}]:[{label:tA(),description:nA(),uriTemplate:No(o),changeKind:"session"},{label:iA(),description:sA(),uriTemplate:aA(o),changeKind:"turn"}]}function hA(o){return o.type.startsWith("root/")}function fu(o){return o.type.startsWith("session/")}function Tr(o){return o.type.startsWith("chat/")}function vg(o){return o.type.startsWith("terminal/")}function gu(o){return o.type.startsWith("changeset/")}function mu(o){return o.type.startsWith("annotations/")}var Tt=B("productService");function Os(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 Sg(o,n){let e=[];for(let i of o){let s=i.message.text.trim(),a=Os(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?Ls(t,n.maxChars):t;return`${n.framing??""}${r}`}function Ls(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 pC="<side-chat-context>",al="</side-chat-context>",fC="length=",nF="This is a side conversation. Prefer explanation over action; do not make changes or carry out work unless the user explicitly asks.",gC=2e4;function Cg(o,n){let e=[];for(let r of o){let i=yA(r.message.text,Os(r.responseParts));i&&e.push(i)}if(n){let r=yA(n.message.text,void 0);r&&e.push(r)}if(e.length===0)return;let t=e.join(`

---

`);return t.length>gC?Ls(t,gC):t}function vA(o){if(!o)return;let n=Os(o.responseParts);return n?Ls(n,gC):void 0}function SA(o,n,e){if(e?.id===n)return Cg(o,e);let t=o.findIndex(r=>r.id===n);return t===-1?void 0:Cg(o.slice(0,t+1))}function rF(o,n,e,t){let r=[nF];t&&r.push("","Selected text:","",t),e&&r.push("","Source conversation up to the branching point:","",e),n&&r.push("","The side chat was created while the source assistant was still responding.","The user-visible response had produced the following text at that moment:","",n);let i=r.join(`
`);return[pC,`${fC}${i.length}`,i,al,"",o].join(`
`)}function Ig(o,n,e){if(!e||n.length>e.inheritedTurnCount)return o;let t=n.find(s=>s.id===e.turnId),r=t?void 0:e.context,i=e.partialResponse;return i&&(t?Os(t.responseParts):"").includes(i)&&(i=void 0),rF(o,i,r,e.selection?.text)}function yA(o,n){let e=o.trim(),t=n?.trim();if(!(!e&&!t))return t?`User request:
${e}

Agent response:
${t}`:`User request:
${e}`}function bg(o,n){if(!n||o.length===0)return o;let e=o[0],t=e.message.text;if(!t.startsWith(pC))return o;let r=pC.length+1;if(t.slice(r).startsWith(fC)){let a=t.indexOf(`
`,r),l=a>0?Number.parseInt(t.slice(r+fC.length,a),10):Number.NaN;if(Number.isInteger(l)&&l>=0){let c=a+1+l;if(t.slice(c,c+al.length+1)===`
${al}`){let u=t.slice(c+al.length+1).trimStart();return[{...e,message:{...e.message,text:u}},...o.slice(1)]}}}let i=t.lastIndexOf(al);if(i<0)return o;let s=t.slice(i+al.length).trimStart();return[{...e,message:{...e.message,text:s}},...o.slice(1)]}function Br(o){return JSON.stringify(o)}function _g(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,i=n.sideChat,s=i?.selection&&typeof i.selection=="object"&&typeof i.selection.text=="string"&&(i.selection.responsePartId===void 0||typeof i.selection.responsePartId=="string")?{text:i.selection.text,...i.selection.responsePartId?{responsePartId:i.selection.responsePartId}:{}}:void 0,a=i&&typeof i.source=="string"&&typeof i.turnId=="string"&&(i.providerAnchorTurnId===void 0||typeof i.providerAnchorTurnId=="string")&&typeof i.inheritedTurnCount=="number"&&(i.partialResponse===void 0||typeof i.partialResponse=="string")&&(i.context===void 0||typeof i.context=="string")?{source:i.source,turnId:i.turnId,...s?{selection:s}:{},...i.providerAnchorTurnId?{providerAnchorTurnId:i.providerAnchorTurnId}:{},inheritedTurnCount:i.inheritedTurnCount,...i.partialResponse?{partialResponse:i.partialResponse}:{},...i.context?{context:i.context}:{}}:void 0;return{sdkSessionId:e,...r?{model:r}:{},...a?{sideChat:a}:{}}}catch{return}}var ll=class extends x{constructor(e){super();this._chats=this._register(new Ee);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}};import*as hu from"fs";var oF=["copilot","openai"];var iF=["scan","discover"],mC="scan",Dn=Hn({customizations:ae({type:"array",title:f(1852,null),description:f(1848,null),default:[],items:{type:"object",title:f(1851,null),properties:{uri:{type:"string",title:f(1853,null)},displayName:{type:"string",title:f(1850,null)},description:{type:"string",title:f(1849,null)}},required:["uri","displayName"]}}),defaultShell:ae({type:"string",title:f(1855,null),description:f(1854,null)}),claudeUseCopilotProxy:ae({type:"boolean",title:f(1845,null),description:f(1844,null),default:!0}),codexUsageSource:ae({type:"string",title:f(1847,null),description:f(1846,null),default:"copilot",enum:[...oF]}),sessionCustomizationDiscoveryMode:ae({type:"string",enum:[...iF],title:f(1859,null),description:f(1858,null),default:mC}),githubEnterpriseUri:ae({type:"string",title:f(1857,null),description:f(1856,null)})}),CA={customizations:[]};function IA(o){return{type:"plugin",id:et(o.uri),uri:o.uri,name:o.displayName,enabled:!0}}var bA="vscode.agentCustomizationSettings";function sF(o){if(!o||typeof o!="object")return!1;let n=o;return typeof n.key=="string"&&typeof n.group=="string"&&(n.kind===void 0||n.kind==="multiline")&&(n.saveLabel===void 0||typeof n.saveLabel=="string")}function aF(o){if(!o||typeof o!="object")return!1;let n=o;if(typeof n.provider!="string"||typeof n.title!="string"||typeof n.description!="string"||!Array.isArray(n.settings)||!n.settings.every(sF))return!1;let e=n.configurationFile;return e===void 0||!!e&&typeof e.resource=="string"&&typeof e.title=="string"&&typeof e.description=="string"&&typeof e.openLabel=="string"&&(e.documentationUrl===void 0||typeof e.documentationUrl=="string")&&(e.documentationLabel===void 0||typeof e.documentationLabel=="string")}function hC(o){let e=o?._meta?.[bA];return Array.isArray(e)?e.filter(aF):[]}function _A(o,n){return{...o?._meta,[bA]:n}}function yC(o){return new Set(hC(o).flatMap(n=>n.settings.map(e=>e.key)))}function TA(o,n){let e={...n},t=o?.config?.values;if(!t)return e;for(let r of yC(o))!Object.hasOwn(e,r)&&Object.hasOwn(t,r)&&(e[r]=t[r]);return e}var lF=["info","trace"],jt=Hn({enableCustomTerminalTool:ae({type:"boolean",title:f(1977,null),description:f(1976,null),default:!1}),copilotSdkLogLevel:ae({type:"string",title:f(1974,null),description:f(1972,null),enum:[...lF],enumLabels:[f(1973,null),f(1975,null)],default:"info"}),rubberDuck:ae({type:"boolean",title:f(1989,null),description:f(1988,null),default:!1}),opus48Prompt:ae({type:"boolean",title:f(1985,null),description:f(1984,null),default:!1}),toolSearchEnabled:ae({type:"boolean",title:f(1991,null),description:f(1990,null),default:!1}),reasoningEffortOverride:ae({type:"string",title:f(1987,null),description:f(1986,null),default:""}),modelCapabilityOverrides:ae({type:"object",title:f(1983,null),description:f(1978,null),additionalProperties:{type:"object",title:f(1980,null),description:f(1979,null),properties:{family:{type:"string",title:f(1982,null),description:f(1981,null)}}},default:{}})});function dF(o,n){let e=o?.[n]?.family;return typeof e=="string"&&e.length>0?e:void 0}function Tg(o,n){if(!o)return;let e=dF(n,o.id);return e?{...o,id:e}:o}function vC(o){return o===!0?"on":o===!1?"off":o}function SC(o){return o!==void 0&&vC(o)!=="off"}var zr=Hn({sandbox:ae({type:"object",title:f(2024,null),properties:{enabled:{type:"string",title:f(2021,null),enum:["off","on","allowNetwork"]},"enabled.windows":{type:"string",title:f(2025,null),enum:["off","on","allowNetwork"]},allowNetwork:{type:"boolean",title:f(2017,null)},allowUnsandboxedCommands:{type:"boolean",title:f(2018,null)},"fileSystem.linux":{type:"object",title:f(2022,null)},"fileSystem.mac":{type:"object",title:f(2023,null)},"fileSystem.windows":{type:"object",title:f(2026,null)},"advanced.runtime":{type:"object",title:f(2014,null)},allowedNetworkDomains:{type:"array",title:f(2016,null),items:{type:"string",title:f(2015,null)}},deniedNetworkDomains:{type:"array",title:f(2020,null),items:{type:"string",title:f(2019,null)}}}})}),RA={"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 Ue=B("agentConfigurationService"),dl=class extends x{constructor(e,t,r,i=[]){super();this._stateManager=e;this._logService=t;this._rootConfigResource=r;this._rootConfigWrite=Promise.resolve();this._onDidRootConfigChange=this._register(new E);this.onDidRootConfigChange=this._onDidRootConfigChange.event;this._onDidSessionConfigChange=this._register(new E);this.onDidSessionConfigChange=this._onDidSessionConfigChange.event;let s=this._stateManager.rootState.config,a=Dn.toProtocol(),l=zr.toProtocol(),d=jt.toProtocol();this._stateManager.rootState.config={schema:{type:"object",properties:{...s?.schema.properties,...a.properties,...l.properties,...d.properties}},values:{...s?.values,...this._loadPersistedRootConfig()}};for(let c of i)this.registerProviderConfiguration(c);this._register(this._stateManager.onDidEmitEnvelope(c=>{c.action.type==="root/configChanged"?this._onDidRootConfigChange.fire():c.action.type==="session/configChanged"&&this._onDidSessionConfigChange.fire({session:c.channel,config:c.action.config})}))}setWorktreeIsolation(e){this._worktree=e}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 N?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)?.workingDirectories?.[0];if(t!==void 0)return t;let r=It(e);if(r)return this._stateManager.getSessionState(r.parentSession.toString())?.workingDirectories?.[0]}isWorkingDirectoryPending(e){return this._worktree?.isWorkingDirectoryPending(M.id(e))??!1}async resolveWorkingDirectoryForResume(e,t){return this._worktree?.resolveWorkingDirectoryForResume(v.parse(e),M.id(e),t)??t}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 N?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(Je,{type:"root/configChanged",config:e,replace:t}),this.persistRootConfig()}persistRootConfig(){if(!this._rootConfigResource)return;let e={...this._stateManager.rootState.config?.values??{customizations:[]}};for(let i of yC(this._stateManager.rootState))delete e[i];let 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 hu.promises.mkdir(te(r.fsPath),{recursive:!0}),await hu.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}registerProviderConfiguration(e){let t=this._stateManager.rootState.config;if(!t)return;Object.assign(t.schema.properties,e.properties);for(let[i,s]of Object.entries(e.properties))t.values[i]===void 0&&s.default!==void 0&&(t.values[i]=s.default);let r=hC(this._stateManager.rootState).filter(i=>i.provider!==e.provider);this._stateManager.rootState._meta=_A(this._stateManager.rootState,[...r,{provider:e.provider,title:e.title,description:e.description,settings:e.settings,configurationFile:e.configurationFile}])}getRootConfigValues(){return this._stateManager.rootState.config?.values??{}}*_effectiveChain(e){let t=this._stateManager.getSessionState(e)?.config?.values;t&&(yield t);let r=It(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=CA;if(!this._rootConfigResource)return{...e};try{let t=hu.readFileSync(this._rootConfigResource.fsPath,"utf8"),r=JSON.parse(t);return{...Dn.validateOrDefault(r,e),...zr.validateOrDefault(r,{}),...jt.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}}}};dl=A([b(1,O)],dl);import*as Fs from"fs";import{userInfo as CF}from"os";import*as CC from"os";var xA=/^\d+$/,pF=/^Microsoft.PowerShell_.*/,fF=/^Microsoft.PowerShellPreview_.*/;var vu;switch(process.arch){case"ia32":vu=1;break;case"arm":case"arm64":vu=2;break;default:vu=0;break}var cl;process.env.PROCESSOR_ARCHITEW6432?cl=process.env.PROCESSOR_ARCHITEW6432==="ARM64"?2:0:process.env.PROCESSOR_ARCHITECTURE==="ARM64"?cl=2:process.env.PROCESSOR_ARCHITECTURE==="X86"?cl=1:cl=0;var Ns=class{constructor(n,e,t){this.exePath=n;this.displayName=e;this.knownToExist=t}async exists(){return this.knownToExist===void 0&&(this.knownToExist=await hn.existsFile(this.exePath)),this.knownToExist}};function gF({useAlternateBitness:o=!1}={}){return o?vu===0?process.env["ProgramFiles(x86)"]||null:cl===0&&process.env.ProgramW6432||null:process.env.ProgramFiles||null}async function wg({useAlternateBitness:o=!1,findPreview:n=!1}={}){let e=gF({useAlternateBitness:o});if(!e)return null;let t=V(e,"PowerShell");if(!await hn.existsDirectory(t))return null;let r=-1,i=null;for(let l of await Ge.readdir(t)){let d=-1;if(n){let u=l.indexOf("-");if(u<0)continue;let p=l.substring(0,u);if(!xA.test(p)||l.substring(u+1)!=="preview")continue;d=parseInt(p,10)}else{if(!xA.test(l))continue;d=parseInt(l,10)}if(d<=r)continue;let c=V(t,l,"pwsh.exe");await hn.existsFile(c)&&(i=c,r=d)}if(!i)return null;let s=e.includes("x86")?" (x86)":"",a=n?" Preview":"";return new Ns(i,`PowerShell${a}${s}`,!0)}async function AA({findPreview:o}={}){if(!process.env.LOCALAPPDATA)return null;let n=V(process.env.LOCALAPPDATA,"Microsoft","WindowsApps");if(!await hn.existsDirectory(n))return null;let{pwshMsixDirRegex:e,pwshMsixName:t}=o?{pwshMsixDirRegex:fF,pwshMsixName:"PowerShell Preview (Store)"}:{pwshMsixDirRegex:pF,pwshMsixName:"PowerShell (Store)"};for(let r of await Ge.readdir(n))if(e.test(r)){let i=V(n,r,"pwsh.exe");return new Ns(i,t)}return null}function mF(){let o=V(CC.homedir(),".dotnet","tools","pwsh.exe");return new Ns(o,".NET Core PowerShell Global Tool")}function hF(){let o=V(CC.homedir(),"scoop","apps"),n=V(o,"pwsh","current","pwsh.exe");return new Ns(n,"PowerShell (Scoop)")}function yF(){let o=V(process.env.windir,vu===1&&cl!==1?"SysNative":"System32","WindowsPowerShell","v1.0","powershell.exe");return new Ns(o,"Windows PowerShell",!0)}async function*vF(){let o=await wg();o&&(yield o),o=await wg({useAlternateBitness:!0}),o&&(yield o),o=await AA(),o&&(yield o),o=mF(),o&&(yield o),o=await wg({findPreview:!0}),o&&(yield o),o=await AA({findPreview:!0}),o&&(yield o),o=await wg({useAlternateBitness:!0,findPreview:!0}),o&&(yield o),o=await hF(),o&&(yield o),o=yF(),o&&(yield o)}async function*SF(){for await(let o of vF())await o.exists()&&(yield o)}async function PA(){for await(let o of SF())return o;return null}async function Rg(o,n){return o===1?X?bF():mR(n):IF(o,n)}var IC=null;function IF(o,n){if(Fe&&o===2||ft&&o===3)return"/bin/bash";if(!IC){let e;if(X)e="/bin/bash";else{if(e=n.SHELL,!e)try{e=CF().shell}catch{}e||(e="sh"),e==="/bin/false"&&(e="/bin/bash")}IC=e}return IC}var bC=null;async function bF(){return bC||(bC=(await PA()).exePath),bC}var Vr="AI_AGENT",jr="github_copilot_vscode_agent";import*as ul from"os";var _C=class{constructor(){this.data=new Map}add(n,e){Bp(Be(n)),Bp(ze(e)),Bp(!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=>{Ic(n.dispose)&&n.dispose()}),this.data.clear()}},Kt=new _C;var Sre=B("ptyService");var TF={Backend:"workbench.contributions.terminal.processBackend"},TC=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()??""}};Kt.add(TF.Backend,new TC);var Cre=B("localPtyService"),Ire=B("terminalLogService");function wF(o){return new Map(o)}function RF(o){return new Map(o??[])}function EA(o){return new Map(o.map(n=>[n[0],{map:wF(n[1]),descriptionMap:RF(n[2])}]))}var AF=new Map([[2,"APPEND"],[3,"PREPEND"],[1,"REPLACE"]]),PF=/^VSCODE_PYTHON_(PWSH|ZSH|BASH|FISH)_ACTIVATE/,EF="ms-python.vscode-python-envs",xg=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;X&&(r={},Object.keys(n).forEach(i=>r[i.toLowerCase()]=i));for(let[i,s]of this.getVariableMap(e)){let a=X&&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_${AF.get(l.type)}`;n[c]=(n[c]?n[c]+":":"")+i+"="+this._encodeColons(d)}}}}}_encodeColons(n){return n.replaceAll(":","\\x3a")}blockPythonActivationVar(n,e){return!!(PF.test(n)&&EF!==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=DA(s,l);d&&t.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=DA(s,l);d&&i.set(a,d)}),this.getVariableMap(e).forEach((s,a)=>{let l=n.getVariableMap(e).get(a),d=kF(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=>kA(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=>kA(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 kA(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 DA(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 kF(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 OA,realpathSync as OF,mkdirSync as LF}from"fs";import{promisify as LA}from"util";import*as Ag from"os";var Su;async function DF(){if(Su)return;if(!X){Su={release:Ag.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{Su={release:n||Ag.release(),buildNumber:o||MF()}}}async function MA(){return Su||await DF(),Su.buildNumber}function MF(){let o=/(\d+)\.(\d+)\.(\d+)/g.exec(Ag.release());return o&&o.length===4?parseInt(o[3],10):0}async function HA(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=X?await MA():0;if(X&&s<18309)return{type:"failure",reason:"unsupportedWindowsBuild"};let a=o.args,l=_a==="win32"?ue(o.executable).toLowerCase():ue(o.executable),d=te(Nt.asFileUri("").fsPath),c="injection",u,p={VSCODE_INJECTION:"1"};n.shellIntegration.nonce&&(p.VSCODE_NONCE=n.shellIntegration.nonce);let g=["PATH","VIRTUAL_ENV","HOME","SHELL","PWD"];if(o.shellIntegrationEnvironmentReporting&&(X?(n.windowsUseConptyDll||s>=22631&&l!=="bash.exe")&&(p.VSCODE_SHELL_ENV_REPORTING=g.join(",")):p.VSCODE_SHELL_ENV_REPORTING=g.join(",")),X)return l==="pwsh.exe"||l==="powershell.exe"?(p.VSCODE_A11Y_MODE=n.isScreenReaderOptimized?"1":"0",!a||FA(a)?u=ct.get("windows-pwsh"):UA(a)&&(u=ct.get("windows-pwsh-login")),u?(u=[...u],u[u.length-1]=us(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=ct.get("bash"):kg(a)&&(p.VSCODE_SHELL_LOGIN="1",Pg(n,p,l),u=ct.get("bash")),u?(u=[...u],u[u.length-1]=us(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=ct.get("bash"):kg(a)&&(p.VSCODE_SHELL_LOGIN="1",Pg(n,p,l),u=ct.get("bash")),u?(u=[...u],u[u.length-1]=us(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=ct.get("fish"):kg(a)?u=ct.get("fish-login"):(a===ct.get("fish")||a===ct.get("fish-login"))&&(u=a),u?(Pg(n,p,l),u=[...u],u[u.length-1]=us(u[u.length-1],d),{type:c,newArgs:u,envMixin:p}):{type:"failure",reason:"unsupportedArgs"};case"pwsh":return!a||FA(a)?u=ct.get("pwsh"):UA(a)&&(u=ct.get("pwsh-login")),u?(u=[...u],u[u.length-1]=us(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=ct.get("zsh"):kg(a)?(u=ct.get("zsh-login"),Pg(n,p,l)):(a===ct.get("zsh")||a===ct.get("zsh-login"))&&(u=a),!u)return{type:"failure",reason:"unsupportedArgs"};u=[...u],u[u.length-1]=us(u[u.length-1],d);let h;try{h=ul.userInfo().username}catch{h="unknown"}let y=OF(ul.tmpdir()),I=V(y,`${h}-${r.applicationName}-zsh`);if(!i)try{await LA(OA)(I,960)}catch(_){if(_.message.includes("ENOENT")){try{LF(I)}catch(T){return t.error(`Failed to create zdotdir at ${I}: ${T}`),{type:"failure",reason:"failedToCreateTmpDir"}}try{await LA(OA)(I,960)}catch{return t.error(`Failed to set sticky bit on ${I}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}}return t.error(`Failed to set sticky bit on ${I}: ${_}`),{type:"failure",reason:"failedToSetStickyBit"}}p.ZDOTDIR=I;let S=e?.ZDOTDIR??ul.homedir()??"~";p.USER_ZDOTDIR=S;let C=[];return C.push({source:V(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh"),dest:V(I,".zshrc")}),C.push({source:V(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-profile.zsh"),dest:V(I,".zprofile")}),C.push({source:V(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-env.zsh"),dest:V(I,".zshenv")}),C.push({source:V(d,"out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-login.zsh"),dest:V(I,".zlogin")}),{type:c,newArgs:u,envMixin:p,filesToCopy:C}}}return t.warn(`Shell integration cannot be enabled for executable "${o.executable}" and args`,o.args),{type:"failure",reason:"unsupportedShell"}}function Pg(o,n,e){if((ft||e==="fish")&&o.environmentVariableCollections){let t=EA(o.environmentVariableCollections),i=new xg(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 ct=new Map;ct.set("windows-pwsh",["-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);ct.set("windows-pwsh-login",["-l","-noexit","-command",'try { . "{0}\\out\\vs\\workbench\\contrib\\terminal\\common\\scripts\\shellIntegration.ps1" } catch {}{1}']);ct.set("pwsh",["-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"{1}']);ct.set("pwsh-login",["-l","-noexit","-command",'. "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1"']);ct.set("zsh",["-i"]);ct.set("zsh-login",["-il"]);ct.set("bash",["--init-file","{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh"]);ct.set("fish",["--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);ct.set("fish-login",["-l","--init-command",'source "{0}/out/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish"']);var Eg=["-login","-l"],NA=["--login","-l"],NF=["-i","--interactive"],Dg=["-nol","-nologo"];function UA(o){return Be(o)?Eg.includes(o.toLowerCase()):o.length===1&&Eg.includes(o[0].toLowerCase())||o.length===2&&(Eg.includes(o[0].toLowerCase())||Eg.includes(o[1].toLowerCase()))&&(Dg.includes(o[0].toLowerCase())||Dg.includes(o[1].toLowerCase()))}function FA(o){return Be(o)?Dg.includes(o.toLowerCase()):o.length===0||o?.length===1&&Dg.includes(o[0].toLowerCase())}function kg(o){return Be(o)||(o=o.filter(n=>!NF.includes(n.toLowerCase()))),Be(o)&&NA.includes(o.toLowerCase())||!Be(o)&&o.length===1&&NA.includes(o[0].toLowerCase())}import UF from"@xterm/headless";var{Terminal:FF}=UF,Mg=class extends x{constructor(e){super();this._onResponseData=this._register(new E);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 FF(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 be,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 Og(o){return qt===1?/^zsh(?:\.exe)?$/i.test(ve.basename(o)):/^zsh$/.test(ie.basename(o))}var HF={"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/workingDirectorySet":!0,"session/workingDirectoryRemoved":!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/toolCallAuthRequired":!1,"chat/toolCallAuthResolved":!1,"chat/turnComplete":!1,"chat/turnCancelled":!0,"chat/error":!1,"chat/activityChanged":!1,"chat/workingDirectorySet":!0,"chat/workingDirectoryRemoved":!0,"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 qn(o,n){let e=`Unhandled action type: ${JSON.stringify(o)}`;(n??console.warn)(e)}function Cu(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 qn(n,e),o}}var $F=31;function $A(o,n,e){return e?o|n:o&~n}function WA(o,n){return n.length>0?o&~$F|24:o&-17}function wC(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 Iu(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:$A(o.status,32,n.isRead)};case"session/isArchivedChanged":return{...o,status:$A(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/workingDirectorySet":{let t=o.workingDirectories??[];return t.includes(n.directory)?o:{...o,workingDirectories:[...t,n.directory]}}case"session/workingDirectoryRemoved":{let t=o.workingDirectories;if(!t)return o;let r=t.indexOf(n.directory);if(r<0)return o;let i=t.slice();return i.splice(r,1),{...o,workingDirectories: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:WA(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:WA(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 wC(o,n.id,t=>({...t,state:n.state,channel:n.channel}));case"session/mcpServerStartRequested":return wC(o,n.id,t=>({...t,state:{kind:"starting"},channel:void 0}));case"session/mcpServerStopRequested":return wC(o,n.id,t=>({...t,state:{kind:"stopped"},channel:void 0}));default:return qn(n,e),o}}function BA(o){return{toolCallId:o.toolCallId,toolName:o.toolName,displayName:o.displayName,intention:o.intention,contributor:o.contributor,_meta:o._meta}}function fl(o,n){return{...BA(o),_meta:n??o._meta}}function WF(o,n){if(!(!n||!o))return o.find(e=>e.id===n)}function qF(o){return o.activeTurn?o.activeTurn.responseParts.some(n=>n.kind==="toolCall"&&(n.toolCall.status==="pending-confirmation"||n.toolCall.status==="pending-result-confirmation"||n.toolCall.status==="auth-required")):!1}function BF(o){return o.activeTurn?.responseParts.some(n=>n.kind==="inputRequest"&&n.response===void 0)??!1}function xC(o,n){let e=o.findIndex(r=>r.kind==="inputRequest"&&r.response===void 0&&r.request.id===n);if(e<0)return;let t=o[e];return t.kind==="inputRequest"?{index:e,part:t}:void 0}var zF=31;function zA(o,n,e){return e?o|n:o&~n}function ml(o,n){let e;return n?e=n:BF(o)||qF(o)?e=24:o.activeTurn?e=8:e=1,o.status&~zF|e}function gl(o){let n=ml(o);return n===o.status?o:{...o,status:n}}function RC(o,n,e,t,r,i){if(!o.activeTurn||o.activeTurn.id!==n)return o;let s=o.activeTurn,a=s.responseParts.map(c=>{if(c.kind!=="toolCall")return c;let u=c.toolCall;return u.status==="completed"||u.status==="cancelled"?c:{kind:"toolCall",toolCall:{status:"cancelled",...BA(u),invocationMessage:u.status==="streaming"?u.invocationMessage??"":u.invocationMessage,toolInput:u.status==="streaming"?void 0:u.toolInput,reason:"skipped"}}}),l={id:s.id,startedAt:s.startedAt,duration:Math.max(0,t),message:s.message,responseParts:a,usage:s.usage,state:e,error:i},d={...o,turns:[...o.turns,l],activeTurn:void 0,modifiedAt:new Date(Date.now()).toISOString()};return{...d,status:ml(d,r)}}function VF(o,n){let e=o.activeTurn;if(!e)return o;let t=xC(e.responseParts,n.id),r=[...e.responseParts],i={kind:"inputRequest",request:n};t?(i.request={...n,answers:n.answers??t.part.request.answers},r[t.index]=i):r.push(i);let s={...o,activeTurn:{...e,responseParts:r}};return{...s,status:zA(ml(s),32,!1),modifiedAt:new Date(Date.now()).toISOString()}}function Si(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 qA(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 bu(o,n,e){switch(n.type){case"chat/turnStarted":{let t={...o,activeTurn:{id:n.turnId,startedAt:n.startedAt,message:n.message,responseParts:[],usage:void 0}};if(t={...t,status:zA(ml(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 qA(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 RC(o,n.turnId,"complete",n.duration);case"chat/turnCancelled":return RC(o,n.turnId,"cancelled",n.duration);case"chat/error":return RC(o,n.turnId,"error",n.duration,2,n.error);case"chat/activityChanged":return{...o,activity:n.activity};case"chat/workingDirectorySet":{let t=o.workingDirectories??[];return t.includes(n.directory)?o:{...o,workingDirectories:[...t,n.directory]}}case"chat/workingDirectoryRemoved":{let t=o.workingDirectories;if(!t)return o;let r=t.indexOf(n.directory);if(r<0)return o;let i=t.slice();return i.splice(r,1),{...o,workingDirectories:i}}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 Si(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 gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="streaming"&&t.status!=="running"&&t.status!=="pending-confirmation")return t;let r=fl(t,n._meta);if(n.confirmed)return{status:"running",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput,confirmed:n.confirmed};let i=t.status==="pending-confirmation"?t:void 0,s=n.options??i?.options;return{status:"pending-confirmation",...r,invocationMessage:n.invocationMessage,toolInput:n.toolInput??i?.toolInput,confirmationTitle:n.confirmationTitle??i?.confirmationTitle,riskAssessment:n.riskAssessment??i?.riskAssessment,edits:n.edits??i?.edits,editable:n.editable??i?.editable,...s?{options:s}:{}}}));case"chat/toolCallConfirmed":return gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-confirmation")return t;let r=fl(t,n._meta),i=WF(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 gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="running"&&t.status!=="pending-confirmation"&&t.status!=="auth-required"||t.status==="auth-required"&&n.result.success)return t;let r=fl(t,n._meta),i=t.status==="running"||t.status==="auth-required"?t.confirmed:"not-needed",s=t.status==="running"||t.status==="auth-required"?t.selectedOption:void 0,a=t.status==="auth-required"?t.content:void 0;return n.requiresResultConfirmation&&t.status!=="auth-required"?{status:"pending-result-confirmation",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:i,...s?{selectedOption:s}:{},...a?{content:a}:{},...n.result}:{status:"completed",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:i,...s?{selectedOption:s}:{},...a?{content:a}:{},...n.result}}));case"chat/toolCallResultConfirmed":return gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="pending-result-confirmation")return t;let r=fl(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 Si(o,n.turnId,n.toolCallId,t=>t.status!=="running"?t:{...t,...n._meta!==void 0?{_meta:n._meta}:{},content:n.content});case"chat/toolCallAuthRequired":return gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="running"||!t.contributor||t.contributor.kind!=="mcp")return t;let r=fl(t,n._meta);return{status:"auth-required",...r,contributor:t.contributor,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed,...t.selectedOption?{selectedOption:t.selectedOption}:{},...t.content?{content:t.content}:{},auth:n.auth}}));case"chat/toolCallAuthResolved":return gl(Si(o,n.turnId,n.toolCallId,t=>{if(t.status!=="auth-required")return t;let r=fl(t,n._meta);return{status:"running",...r,invocationMessage:t.invocationMessage,toolInput:t.toolInput,confirmed:t.confirmed,...t.selectedOption?{selectedOption:t.selectedOption}:{},...t.content?{content:t.content}:{}}}));case"chat/usage":return!o.activeTurn||o.activeTurn.id!==n.turnId?o:{...o,activeTurn:{...o.activeTurn,usage:n.usage}};case"chat/reasoning":return qA(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 n.turnId===void 0&&delete r.turnsNextCursor,{...r,status:ml(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 VF(o,n.request);case"chat/inputAnswerChanged":{let t=o.activeTurn,r=t?xC(t.responseParts,n.requestId):void 0;if(!t||!r)return o;let{index:i,part:s}=r,a=s.request,l={...a.answers??{}};n.answer===void 0?delete l[n.questionId]:l[n.questionId]=n.answer;let d=[...t.responseParts];return d[i]={...s,request:{...a,answers:Object.keys(l).length>0?l:void 0}},{...o,activeTurn:{...t,responseParts:d},modifiedAt:new Date(Date.now()).toISOString()}}case"chat/inputCompleted":{let t=o.activeTurn,r=t?xC(t.responseParts,n.requestId):void 0;if(!t||!r)return o;let{index:i,part:s}=r,a={...s.request.answers??{},...n.answers??{}},l=[...t.responseParts];l[i]={...s,request:{...s.request,answers:Object.keys(a).length>0?a:void 0},response:n.response};let d={...o,activeTurn:{...t,responseParts:l}};return{...d,status:ml(d),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 qn(n,e),o}}function _u(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 qn(n,e),o}}function Tu(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 qn(n,e),o}}var AC="/annotations";function Lg(o){return`${o}${AC}`}function GF(o){if(!o.endsWith(AC))return;let n=o.slice(0,o.length-AC.length);if(n)return{sessionUri:n}}function VA(o){return GF(o)!==void 0}var JF=500,Ng=class{constructor(n={}){this._states=new Map;this._lru=new vc;this._softLimit=Math.max(0,n.softLimit??JF),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 PC=class extends x{constructor(e,t){super();this._getSummary=e;this._emit=t;this._lastNotified=new Map;this._dirty=new Set;this._scheduler=this._register(new ai(()=>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.workingDirectories!==r.workingDirectories&&(i.workingDirectories=t.workingDirectories),t._meta!==r._meta&&(i._meta=t._meta),this._lastNotified.set(e,t),Object.keys(i).length>0&&this._emit(e,i)}},Ce=B("agentHostStateManager"),hl=class extends x{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 E);this.onDidEmitEnvelope=this._onDidEmitEnvelope.event;this._onDidEmitNotification=this._register(new E);this.onDidEmitNotification=this._onDidEmitNotification.event;this._onDidChangeSessionActiveTurn=this._register(new E);this.onDidChangeSessionActiveTurn=this._onDidChangeSessionActiveTurn.event;this._log=e=>this._logService.warn(`[AgentHostStateManager] ${e}`);this._changesets=new Ng(t.changesetStateRetention),this._rootState=MR(),this._rootState={...this._rootState,config:{schema:tt.toProtocol(),values:tt.validateOrDefault({},{permissions:{allow:[],deny:[]},[Kc]:fx(3)})},_meta:BR(this._rootState._meta,t.hostBuildInfo)},this._summaryNotifier=this._register(new PC(r=>{let i=this._sessionStates.get(r);return i?this._toSummary(r,i):void 0},(r,i)=>this._onDidEmitNotification.fire({type:"root/sessionSummaryChanged",channel:Je,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?Ka(e):e;if(r===void 0)return;let i=this._sessionStates.get(r);if(!i)return;let s=t?e:pe(r);return UR(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.workingDirectories!==void 0&&(i.workingDirectories=r.workingDirectories),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.workingDirectories===t.workingDirectories&&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(Is(e))return{resource:Je,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(VA(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=wS(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:Je,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,workingDirectories:t.workingDirectories},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:Je,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={...wS(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={...Df(t,a),title:s??""};this._chatStates.set(a,{...kf(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={...Df(this._toSummary(e,i),t),title:r?.title??"",status:1,origin:r?.origin,interactivity:r?.interactivity};return this._chatStates.set(t,{...kf(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={...Df(this._toSummary(e,i),t),title:r.title??"",status:1,origin:r.origin};this._chatStates.set(t,{...kf(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||Re(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(Je,{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:Je,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}gi(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(xS(i.changesets??[],t??[],gi))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=rt(r);i&&i.sessionUri===e&&t.push(r)}for(let r of t)this.disposeChangeset(r)}disposeSessionAnnotations(e){this._annotations.delete(Lg(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)}rejectClientAction(e,t,r,i){let s={channel:e,action:t,serverSeq:++this._serverSeq,origin:r,rejectionReason:i};this._logService.trace(`[AgentHostStateManager] Emitting rejection envelope: seq=${s.serverSeq}, channel=${s.channel}, type=${t.type}, origin=${r.clientId}:${r.clientSeq}, reason=${i}`),this._onDidEmitEnvelope.fire(s)}_applyAndEmit(e,t,r){let i;if(t.type==="root/configChanged"&&t.replace&&(t={...t,config:TA(this._rootState,t.config)}),hA(t)){if(t.type==="root/configChanged"&&this._rootState.config){let a=this._rootState.config.values,l=t.config;if(t.replace?Oe(a,l):Oe({...a,...l},a))return this._rootState}this._rootState=Cu(this._rootState,t,this._log),i=this._rootState}if(fu(t)){let a=t,l=e,d=this._sessionStates.get(l);if(d){let c=Iu(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(Tr(t)){if(!de(e))throw new Error(`[AgentHostStateManager] Chat action dispatched to non-chat channel: ${e}, type=${t.type}`);let a=t,l=ce(e),d=this._chatStates.get(e);if(d&&l!==void 0){let c=bu(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(gu(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=_u(d,a,this._log);c!==d&&this._changesets.set(l,c),i=c}if(mu(t)){let a=t,l=e,d=this._annotations.get(l)??{annotations:[]},c=Tu(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(Je,{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(Je,{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=OR(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 g=this._aggregateChatSummaries(p,d.defaultChat),h=g.status!==void 0?this._mergeSessionStatus(d.status,g.status):d.status,y=h!==d.status,I=g.activity!==d.activity;l.state={...d,chats:p,...y?{status:h}:void 0,...I?{activity:g.activity}:void 0};let S=g.modifiedAt!==void 0?new Date(g.modifiedAt).toISOString():void 0,C=S!==void 0&&S!==l.modifiedAt;C&&(l.modifiedAt=S),(y||I||C)&&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,g)=>Date.parse(g.modifiedAt)>Date.parse(p.modifiedAt)?g: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,g)=>Math.max(p,Date.parse(g.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:Je,...e})}emitAuthRequired(e){this._onDidEmitNotification.fire({type:"auth/required",channel:Je,...e})}};hl=A([b(0,O)],hl);function jA(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 YF(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=jA(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=jA(t),i=r.indexOf("=");return i===-1?void 0:{type:5,key:r.substring(0,i),value:r.substring(i+1)}}default:return}}var DC="\x1B",EC=DC+"]",kC="\x07",KA=DC+"\\",Ug=class{constructor(){this._pendingOsc="";this._inOsc=!1;this._pendingEscInOsc=!1}parse(n){let e=[],t="";for(let r of this.parseSegments(n))r.kind==="data"?t+=r.data:e.push(r.event);return{cleanedData:t,events:e}}parseSegments(n){let e=[],t="",r=l=>{t+=l},i=()=>{t.length>0&&(e.push({kind:"data",data:t}),t="")},s=l=>{i(),e.push({kind:"event",event:l})};if(!this._inOsc&&n.indexOf(EC)===-1)return r(n),i(),e;let a=0;for(;a<n.length;){if(this._inOsc){if(this._pendingEscInOsc){if(this._pendingEscInOsc=!1,n[a]==="\\"){a++,this._inOsc=!1;let p=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(p,s,r,KA);continue}this._inOsc=!1;let u=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(u,s,r);continue}let c=this._consumeOscBody(n,a);if(a=c.nextIndex,c.complete){this._inOsc=!1;let u=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(u,s,r,c.terminator)}else c.pendingEsc&&(this._pendingEscInOsc=!0);continue}let l=n.indexOf(EC,a);if(l===-1){r(n.substring(a)),a=n.length;continue}r(n.substring(a,l)),a=l+2,this._pendingOsc="",this._inOsc=!0;let d=this._consumeOscBody(n,a);if(a=d.nextIndex,d.complete){this._inOsc=!1;let c=this._pendingOsc;this._pendingOsc="",this._handleOscPayload(c,s,r,d.terminator)}else d.pendingEsc&&(this._pendingEscInOsc=!0)}return i(),e}_consumeOscBody(n,e){let t=n.indexOf(kC,e),r=n.indexOf(DC,e);return t!==-1&&(r===-1||t<r)?(this._pendingOsc+=n.substring(e,t),{nextIndex:t+1,complete:!0,terminator:kC}):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:KA}:{nextIndex:r,complete:!0}):(this._pendingOsc+=n.substring(e),{nextIndex:n.length,complete:!1})}_handleOscPayload(n,e,t,r=kC){if(n.startsWith("633;")){let i=n.substring(4),s=YF(i);s&&e(s)}else t(EC+n+r)}};var QF=1e4,XF=0,MC="\x1B[6n",OC="\x1B[?6n",ZF=["\x1B[?6","\x1B[?","\x1B[6","\x1B[","\x1B"],ur=B("agentHostTerminalManager");function e4(o,n){if(!n.pendingData&&!o.includes(MC)&&!o.includes(OC)&&!GA(o))return o;let e=n.pendingData+o,t=GA(e),r=t?e.substring(0,e.length-t.length):e;return n.pendingData=t,!r.includes(MC)&&!r.includes(OC)?r:r.replaceAll(OC,"").replaceAll(MC,"")}function GA(o){for(let n of ZF)if(o.endsWith(n))return n;return""}function t4(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 LC;async function n4(){return LC||(LC=await import("node-pty")),LC}var yl=class extends x{constructor(e,t,r,i){super();this._stateManager=e;this._logService=t;this._productService=r;this._configurationService=i;this._terminals=new Map;this._outputTerminals=new Map;this._register(this._stateManager.onDidEmitEnvelope(s=>{let a=s.action;if(!vg(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._outputTerminals.get(e);if(t)return{title:t.title,content:t.content,exitCode:t.exitCode,claim:t.claim,isPty:!1};let r=this._terminals.get(e);if(r)return{title:r.title,cwd:r.cwd,cols:r.cols,rows:r.rows,content:r.content,exitCode:r.exitCode,claim:r.claim,supportsCommandDetection:r.commandTracker?.detectionAvailableEmitted,isPty:!0}}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=X?"cmd":"xterm-256color";this._logService.info(`[TerminalManager] Creating terminal ${r}: shell=${l}, cwd=${i}, cols=${s}, rows=${a}`);let c=F(),u={...process.env};u[Vr]=jr,t?.preventShellHistory&&(u.VSCODE_PREVENT_SHELL_HISTORY="1"),e.claim?.kind==="session"&&Og(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=[];ft&&sw(l).name.match(/(zsh|bash)/)&&(p=["--login"]);let g=await HA({executable:l,args:p,forceShellIntegration:!0},{shellIntegration:{enabled:!0,suggestEnabled:!1,nonce:c},windowsUseConptyDll:!1,environmentVariableCollections:void 0,workspaceFolder:void 0,isScreenReaderOptimized:!1},void 0,this._logService,this._productService),h;if(g.type==="injection"){if(this._logService.info(`[TerminalManager] Shell integration injected for ${r}`),g.envMixin)for(let[J,me]of Object.entries(g.envMixin))me!==void 0&&(u[J]=me);if(g.newArgs&&(p=g.newArgs),g.filesToCopy)for(let J of g.filesToCopy)try{await Fs.promises.mkdir(te(J.dest),{recursive:!0}),await Fs.promises.copyFile(J.source,J.dest)}catch{}h={parser:new Ug,nonce:c,commandCounter:0,detectionAvailableEmitted:!1}}else this._logService.info(`[TerminalManager] Shell integration not available for ${r}: ${g.reason}`);let y=await this._spawnPty(l,p,{name:d,cwd:i,env:u,cols:s,rows:a}),I=new G,S=e.claim??{kind:"client",clientId:""},C=I.add(new E),_=I.add(new E),T=I.add(new E),w=I.add(new E),W=I.add(new Mg({cols:s,rows:a,scrollback:XF,logService:this._logService})),R={uri:r,store:I,pty:y,onDataEmitter:C,onExitEmitter:_,onClaimChangedEmitter:T,onCommandFinishedEmitter:w,title:e.name??l,cwd:i,cols:s,rows:a,content:[],contentSize:0,claim:S,commandTracker:h,headlessTerminal:W,terminalQueryFilterState:{pendingData:""}};this._terminals.set(r,R),I.add(W.onResponseData(J=>{this._logService.debug(`[TerminalManager] Writing headless terminal response for ${r}: ${JSON.stringify(J)}`);try{y.write(J)}catch(me){this._logService.debug(`[TerminalManager] Failed to write headless terminal response for ${r}: ${me instanceof Error?me.message:String(me)}`)}})),I.add(U(()=>{try{y.kill()}catch{}}));let L=new be,D=y.onData(J=>{R.headlessTerminal?.writePtyData(J),this._handlePtyData(R,J),L.complete()});I.add(U(()=>D.dispose()));let z=y.onExit(J=>{R.exitCode=J.exitCode,R.onExitEmitter.fire(J.exitCode),L.complete(),this._stateManager.dispatchServerAction(r,{type:"terminal/exited",exitCode:J.exitCode}),this._broadcastTerminalList()});if(I.add(U(()=>z.dispose())),!X){let J=setInterval(()=>{let me=y.process;me&&me!==R.title&&(R.title=me,this._stateManager.dispatchServerAction(r,{type:"terminal/titleChanged",title:me}),this._broadcastTerminalList())},200);I.add(U(()=>clearInterval(J)))}await $w([L.p,mn(QF)]),this._broadcastTerminalList()}async _spawnPty(e,t,r){return(await n4()).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,t4(t,{shouldExecute:r.shouldExecute,forceBracketedPasteMode:s}))}onData(e,t){let r=this._terminals.get(e);return r?r.onDataEmitter.event(t):U(()=>{})}onExit(e,t){let r=this._terminals.get(e);return r?r.onExitEmitter.event(t):U(()=>{})}onClaimChanged(e,t){let r=this._terminals.get(e);return r?r.onClaimChangedEmitter.event(t):U(()=>{})}onCommandFinished(e,t){let r=this._terminals.get(e);return r?r.onCommandFinishedEmitter.event(t):U(()=>{})}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=r?r.parser.parseSegments(t):t.length>0?[{kind:"data",data:t}]:[],s="",a=()=>{s.length!==0&&(e.onDataEmitter.fire(s),this._stateManager.dispatchServerAction(e.uri,{type:"terminal/data",data:s}),s="")};for(let l of i){if(l.kind==="event"){a(),this._handleOsc633Event(e,r,l.event);continue}let d=e4(l.data,e.terminalQueryFilterState);d.length>0&&(this._appendToContent(e,d),s+=d)}a(),this._trimContent(e)}_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}}}createOutputTerminal(e,t){if(this._terminals.has(e)||this._outputTerminals.has(e))throw new Error(`Terminal already exists: ${e}`);this._outputTerminals.set(e,{title:t.title,content:[],contentSize:0,claim:t.claim})}appendOutputTerminalData(e,t){let r=this._outputTerminals.get(e);!r||t.length===0||(this._appendToContent(r,t),this._trimContent(r),this._stateManager.dispatchServerAction(e,{type:"terminal/data",data:t}))}resetOutputTerminal(e){let t=this._outputTerminals.get(e);t&&(t.content=[],t.contentSize=0,this._stateManager.dispatchServerAction(e,{type:"terminal/cleared"}))}finalizeOutputTerminal(e,t){let r=this._outputTerminals.get(e);!r||r.exitCode!==void 0||t!==void 0&&(r.exitCode=t,this._stateManager.dispatchServerAction(e,{type:"terminal/exited",exitCode:t}))}disposeTerminal(e){if(this._outputTerminals.delete(e))return;let t=this._terminals.get(e);t&&(this._terminals.delete(e),t.store.dispose(),this._broadcastTerminalList())}async getDefaultShell(){let e=this._configurationService.getRootValue(Dn,"defaultShell");if(e)try{return await Fs.promises.access(e,Fs.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 Rg(qt,process.env)}async _resolveCwd(e,t){let r=e;if(e){let s=v.parse(e);s.scheme==="file"&&s.fsPath&&s.fsPath!=="/"?r=s.fsPath:this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${t}: ${e}`)}try{if(r&&(await Fs.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(Je,{type:"root/terminalsChanged",terminals:this.getTerminalInfos()})}dispose(){for(let e of this._terminals.values())e.store.dispose();this._terminals.clear(),super.dispose()}};yl=A([b(0,Ce),b(1,O),b(2,Tt),b(3,Ue)],yl);var Hg=B("diffComputeService"),JA=5e3;function YA(o,n,e){switch(o){case"Write":return $g(n,"content");case"Edit":return $g(n,"new_string");case"MultiEdit":return r4(n,"new_string");case"create":return $g(n,"file_text");case"edit":case"str_replace":case"insert":return $g(n,"new_str");case"str_replace_editor":return o4(n);case"apply_patch":case"git_apply_patch":return s4(n,e);default:return[]}}function $g(o,n){if(typeof o!="object"||o===null)return[];let e=o[n];return typeof e=="string"?[e]:[]}function r4(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 o4(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 i4=[/^\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 s4(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 i4){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 Wg(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 a4(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 l4(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 d4(o,n){if(o.length===0)return 0;let e=4,t=n.length>=e?a4(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=l4(s,t,e):l=0,i+=l*a,r+=a}return i/r}function QA(o,n,e){let t=Wg(n,o);if(t===1)return 1;let r=Wg(e,o);return 1-Math.max(r-t,0)/(1-t)}function XA(o,n,e){return{fourGram:Wg(e,n),noRevert:QA(o,n,e)}}function ZA(o,n,e,t){return{fourGram:e.length===0?Wg(t,n):d4(e,t),noRevert:QA(o,n,t)}}var Bg=B("editSurvivalReporterFactory");var NC=[0,5e3,3e4,12e4,3e5,6e5,9e5],UC=class extends x{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>=NC.length){this.dispose();return}let e=Date.now()-this._startTime,t=Math.max(0,NC[this._samplesTaken]-e);this._register(new uf).setIfNotSet(()=>this._takeSample(),t)}async _takeSample(){let e=this._samplesTaken++,t=NC[e];try{let r,i=!1;try{r=(await this._fileService.readFile(v.file(this._params.filePath))).value.toString()}catch(u){if(Vt(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?ZA(this._params.beforeText,this._params.afterText,s,r):XA(this._params.beforeText,this._params.afterText,r),c=de(this._params.sessionUri)?ce(this._params.sessionUri):this._params.sessionUri;if(this._telemetryService.publicLog2("agentHost.trackEditSurvival",{provider:M.provider(c)??"unknown",modelId:this._params.modelId??"",toolName:this._params.toolName??"",agentSessionId:M.id(c),turnId:this._params.turnId,toolCallId:this._params.toolCallId,fileExtension:cs(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()}},c4=5*1024*1024,vl=class{constructor(n,e,t){this._fileService=n;this._logService=e;this._telemetryService=t}launch(n){return cs(n.filePath).toLowerCase()===".ipynb"?{dispose(){}}:Math.max(n.beforeText.length,n.afterText.length)>c4?{dispose(){}}:new UC(n,this._fileService,this._logService,this._telemetryService)}};vl=A([b(0,xe),b(1,O),b(2,Pn)],vl);var tP="session-db";function Ii(o,n,e,t){return v.from({scheme:tP,authority:di($.fromString(o)).toString(),path:`/${encodeURIComponent(n)}/${di($.fromString(e))}/${t}/${ue(e)}`}).toString()}function nP(o){let n=v.parse(o);if(n.scheme!==tP)return;let[,e,t,r]=n.path.split("/");if(!(!e||!t||r!=="before"&&r!=="after"))try{return{sessionUri:SS(n.authority).toString(),toolCallId:decodeURIComponent(e),filePath:SS(t).toString(),part:r}}catch{return}}var Ci=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:$.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,g,h;try{let y=await this._diffComputeService.computeDiffCounts(c,u);g=y.added,h=p?0:y.removed}catch(y){this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${t}`,y)}try{await this._db.storeFileEdit({turnId:n,toolCallId:e,filePath:t,kind:p?"create":"edit",beforeContent:l,afterContent:d,addedLines:g,removedLines:h})}catch(y){this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${t}`,y)}return this._editSurvivalReporterFactory.launch({sessionUri:this._sessionUri,turnId:n,toolCallId:e,filePath:t,beforeText:c,afterText:u,isCreate:p,modelId:s,toolName:r,aiChunks:YA(r,i,t)}),{type:"fileEdit",before:{uri:v.file(t).toString(),content:{uri:Ii(this._sessionUri,e,t,"before")}},after:{uri:v.file(t).toString(),content:{uri:Ii(this._sessionUri,e,t,"after")}},diff:g!==void 0?{added:g,removed:h}:void 0}}async _readFile(n){try{return(await this._fileService.readFile(v.file(n))).value}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),$.fromString("")}}async _readFileWithExistence(n){try{return{content:(await this._fileService.readFile(v.file(n))).value,existed:!0}}catch(e){return this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${n}`,e),{content:$.fromString(""),existed:!1}}}};Ci=A([b(2,xe),b(3,O),b(4,Hg),b(5,Bg)],Ci);var rP="git-blob";function FC(o,n,e,t){return v.from({scheme:rP,path:t,query:JSON.stringify({sessionUri:o,sha:n,repoRelativePath:e})}).toString()}function oP(o){let n;try{n=v.parse(o)}catch{return}if(!(n.scheme!==rP||!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 bi="agentHost.diffBaseBranch";function zg(o,n){return o??n}var Hs="4b825dc642cb6eb9a060e54bf8d69288fbee4904",$e=B("agentHostGitService");function iP(o){return o==="main"?0:o==="master"?1:2}function sP(o,n){let e=n?.query?.toLowerCase(),t=e?o.filter(r=>r.toLowerCase().includes(e)):[...o];return t.sort((r,i)=>iP(r)-iP(i)),n?.limit?t.slice(0,n.limit):t}var Sl="agentHost.changeset.branch",wu="agentHost.changeset.session",Cl="diffs",$s="agentHost.changes",Vg={[Sl]:!0,[wu]:!0,[$s]:!0,[Cl]:!0},Il=B("agentHostChangesetService");var Kr=B("agentHostCheckpointService"),Ws="checkpoint.baseRef";function HC(o,n){return`refs/agents/${o}/checkpoints/turn/${n}`}var aP={_serviceBrand:void 0,captureBaseline:async()=>{},captureTurnCheckpoint:async()=>{},getTurnCheckpointPair:async()=>{},getBaselineCheckpointRef:async()=>{},disposeSessionData:async()=>{}};var lP="vscode-editor-window",dP="vscode-agents-window";var Zse=Object.freeze({name:lP,title:"VS Code"}),eae=Object.freeze({name:dP,title:"VS Code Agents Window"});function cP(o){switch(o?.name){case lP:return"editor_window";case dP:return"agents_window";default:return"unknown"}}var uP="byokModelIdentifier";function pP(o){return o!==void 0?{[uP]:o}:void 0}function fP(o){let n=o._meta;if(!n)return;let e=n[uP];return typeof e=="string"?e:void 0}var gP="The user referenced another chat in the same session. The transcript below is that chat up to the selected turn, provided as background context. Treat it as reference material that may or may not be relevant to the new question.";function u4(o,n){let e=o.findIndex(t=>t.id===n);if(e<0)throw new Error(`Chat attachment endTurn ${n} was not found in the retained transcript.`);return o.slice(0,e+1)}function p4(o){let n=[];for(let e of o){let t=e.message?.text?.trim();t&&n.push(`User: ${t}`);let r=e.responseParts.map(i=>i.kind==="markdown"?i.content:"").join("").trim();r&&n.push(`Assistant: ${r}`)}return n.join(`

`)}function mP(o,n){let e=u4(n,o.endTurn),t=p4(e),r=t?`${gP}

${t}`:gP;return{type:"simple",label:o.label,modelRepresentation:r,...o.range!==void 0?{range:o.range}:{}}}var hP=200,$C=2e4,bl=class extends x{constructor(e,t,r){super();this._stateManager=e;this._options=t;this._logService=r;this._titleGenerationCancellationSources=new Map;this._lastAppliedTitle=new Map;this._provisionalTitles=new Set}seedTitleFromFirstMessage(e,t,r){let i=this._normalizeTitle(t);if(!i)return;let s=this._additionalChatChannel(r),a=s??e,l=s?this._stateManager.getChatState(s):this._stateManager.getSessionState(e);if(!l||!this._canSeedFirstMessageTitle(a,l.turns.length,l.title))return;let d=this._provisionalTitles.has(a);this._provisionalTitles.delete(a),this._applySeedTitle(e,s,i),d&&this._persistSeedTitle(e,s,i),this._generateTitleSoon(a,t,!1,i,c=>this._applySeedTitle(e,s,c),()=>this._currentSeedTitle(e,s)===this._lastAppliedTitle.get(a),c=>this._persistSeedTitle(e,s,c))}seedProvisionalTitle(e,t,r){let i=this._normalizeTitle(t);if(!i)return;let s=this._additionalChatChannel(r),a=s??e,l=s?this._stateManager.getChatState(s):this._stateManager.getSessionState(e);!l||!this._canSeedProvisionalTitle(a,l.title)||(this._provisionalTitles.add(a),this._applySeedTitle(e,s,i),this._persistSeedTitle(e,s,i))}_normalizeTitle(e){return e.trim().replace(/\s+/g," ").slice(0,hP)}_additionalChatChannel(e){return e&&de(e)&&!Re(e)?e:void 0}_applySeedTitle(e,t,r){t?this._applyTitle(t,r,i=>this._stateManager.updateChatTitle(e,t,i)):this._applyTitle(e,r,i=>this._stateManager.dispatchServerAction(e,{type:"session/titleChanged",title:i}))}_persistSeedTitle(e,t,r){this._persistSessionFlag(e,t?`customChatTitle:${t}`:"customTitle",r)}_currentSeedTitle(e,t){return t?this._stateManager.getChatState(t)?.title:this._stateManager.getSessionState(e)?.title}_canSeedFirstMessageTitle(e,t,r){return t===0&&!r?!0:this._provisionalTitles.has(e)&&!!r&&r===this._lastAppliedTitle.get(e)}_canSeedProvisionalTitle(e,t){return t?this._provisionalTitles.has(e)&&t===this._lastAppliedTitle.get(e):!0}refineTitleFromFirstTurn(e,t){if(!!t&&de(t)&&!Re(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=g=>this._applyTitle(t,g,h=>this._stateManager.updateChatTitle(e,t,h));this._generateTitleSoon(t,u,!0,c,p,()=>this._stateManager.getChatState(t)?.title===this._lastAppliedTitle.get(t),g=>this._persistSessionFlag(e,`customChatTitle:${t}`,g));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)&&!Re(t)){let c=t;this._lastAppliedTitle.set(c,i);let u=p=>this._applyTitle(c,p,g=>this._stateManager.updateChatTitle(e,c,g));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 dt;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,hP)}_buildFirstTurnContext(e){let t=Os(e.responseParts);if(!t)return;let r=Math.floor($C/2),i=e.message.text.trim();i.length>r&&(i=Ls(i,r));let s=`User request:
${i}`,a=`

Agent response:
`,l=Math.max(0,$C-s.length-a.length),d=t.length>l?Ls(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 Sg(e,{maxChars:$C,framing:i})}_persistSessionFlag(e,t,r){let i=this._options.sessionDataService.openDatabase(v.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(),this._provisionalTitles.clear(),super.dispose()}};bl=A([b(2,O)],bl);function f4(o){if(zv===2&&/^penguin(\.|$)/i.test(o))return"chromebook"}function yP(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=F()+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"]=qT(zv),u["common.nodePlatform"]=_a,u["common.nodeArch"]=e,u["common.product"]=c||"desktop",l&&(u["common.msftInternal"]=l);let p=0,g=Date.now();Object.defineProperties(u,{timestamp:{get:()=>new Date,enumerable:!0},"common.timesincesessionstart":{get:()=>Date.now()-g,enumerable:!0},"common.sequence":{get:()=>p++,enumerable:!0}}),BT&&(u["common.snap"]="true");let h=f4(n);return h&&(u["common.platformDetail"]=h),u}function vP(o){let n=at.USERDNSDOMAIN;if(!n)return!1;let e=n.toLowerCase();return o.some(t=>e===t)}var qs=class{constructor(n){this.value=n;this.isTrustedTelemetryValue=!0}},WC=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(){}},jg=new WC;var qC="telemetry",CP={id:qC,name:f(2925,null)};function IP(o,n){return!n.isBuilt&&!n.disableTelemetry?!0:!(n.disableTelemetry||!o.enableTelemetry)}function Kg(o,n){return n.extensionTestsLocationURI?!0:!(n.isBuilt||n.disableTelemetry||o.enableTelemetry&&o.aiConfig?.ariaKey)}function bP(o){let n=o.getValue(Ga),e=o.getValue(Wf);if(o.getValue(jc)===!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 Gg(o){let n={},e={},t={};_P(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 _P(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]=Ur(s):s instanceof Date?n[a]=s.toISOString():ze(s)?e<2?_P(s,n,e+1,a+"."):n[a]=Ur(s):n[a]=s}}function TP(o,n){let e=o.msftInternalDomains||[],t=n.getValue("telemetry.internalTesting");return vP(e)||t}function wP(o){return[o.appRoot,o.extensionsPath,o.userHome.fsPath,o.tmpDir.fsPath,o.userDataPath]}function g4(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 RP=[{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 SP(o,n=o){for(let e of RP)if(e.regex.test(n))return`<REDACTED: ${e.label}>`;return o}function m4(o){if(!o)return o;let n=!1;for(let t of RP)if(t.regex.test(o)){n=!0;break}if(!n)return o;if(!o.includes(`
`))return SP(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]=SP(e[t],r)}return e.join(`
`)}function xP(o,n){return o?Uc(o,e=>{if(e instanceof qs||Object.hasOwnProperty.call(e,"isTrustedTelemetryValue"))return e.value;if(typeof e=="string"){let t=e.replaceAll("%20"," ");t=g4(t,n);for(let r of n)t=t.replace(r,"");return t=m4(t),t}}):{}}var h4="7d7048df-6dd0-4048-bb23-b716c1461f8f",AP="3fdd7f28-937a-48c8-9a21-ba337db23bd1",BC="https://copilot-telemetry.githubusercontent.com/telemetry",y4="copilot-chat",Ru=8192,v4=50;function Ho(o){let n={...o};for(let e in o){let t=o[e],r=t?.length??0;if(r>Ru){let i=0,s=0;for(;r>0&&s<v4;){s+=1;let a=e;s>1&&(a=e+"_"+(s<10?"0":"")+s);let l=i+Ru;r<Ru&&(l=i+r),n[a]=t.slice(i,l),r-=Ru,i+=Ru}}}return n}var Jg=class{constructor(n,e,t=BC,r,i=globalThis.fetch){this._logService=e;this._endpointUrl=t;this._internalSink=r;this._fetchFn=i;this._restrictedTelemetryEnabled=!1;this._internalTelemetryEnabled=!1;this._commonProps={client_machineid:xu(n["common.machineId"]),client_deviceid:xu(n["common.devDeviceId"]),client_sessionid:xu(n.sessionID),common_os:xu(n["common.nodePlatform"])??process.platform,editor_version:xu(n.version)}}sendGHTelemetryEvent(n,e,t){this._post(h4,n,e,t)}sendEnhancedGHTelemetryEvent(n,e,t){this._restrictedTelemetryEnabled&&this._post(AP,n,e,t)}sendEnhancedGHTelemetryEventForContext(n,e,t,r){n.restrictedTelemetryEnabled&&this._post(AP,e,t,r,{endpointUrl:n.telemetryEndpoint,trackingId:n.trackingId})}sendInternalMSFTTelemetryEvent(n,e,t){if(this._internalTelemetryEnabled){if(this._internalSink){this._internalSink.send(n,e,t);return}this._logService.trace(`[ahp-restricted] internal MSFT event (not sent, no internal key): ${n}`)}}sendInternalMSFTTelemetryEventForContext(n,e,t,r){if(n.isInternal){if(this._internalSink){this._internalSink.sendForContext(n,e,t,r);return}this._logService.trace(`[ahp-restricted] internal MSFT event (not sent, no internal key): ${e}`)}}setCopilotTrackingId(n){this._commonProps.copilot_trackingId=n||void 0}setRestrictedTelemetryEndpoint(n){this._endpointUrl=n||BC}setRestrictedTelemetryEnabled(n){this._restrictedTelemetryEnabled=n}setInternalTelemetryContext(n){this._internalTelemetryEnabled=n?.isInternal===!0,this._internalSink?.setContext(n)}_post(n,e,t,r,i){let s=e.includes("/")?e:`${y4}/${e}`,a=i?{...this._commonProps,copilot_trackingId:i.trackingId}:this._commonProps,l={ver:1,name:`Microsoft.ApplicationInsights.${n.replace(/-/g,"")}.Event`,time:new Date().toISOString(),sampleRate:100,seq:"",iKey:n,tags:{"ai.operation.id":F()},data:{baseType:"EventData",baseData:{name:s,properties:i?{unique_id:F(),...a,...t,copilot_trackingId:i.trackingId}:{unique_id:F(),...a,...t},measurements:r??{}}}};if(this._logService.trace(`[ahp-restricted] emit ${s} (iKey ${n.slice(0,8)})`),typeof this._fetchFn!="function"){this._logService.warn("[ahp-restricted] global fetch unavailable; telemetry not sent");return}this._fetchFn(i?.endpointUrl||(i?BC:this._endpointUrl),{method:"POST",headers:{"Content-Type":"application/x-json-stream"},body:JSON.stringify(l)}).then(d=>{d.ok||this._logService.warn(`[ahp-restricted] ${s} rejected: HTTP ${d.status}`)}).catch(d=>{this._logService.warn(`[ahp-restricted] ${s} POST failed: ${d instanceof Error?d.message:String(d)}`)})}};function xu(o){return typeof o=="string"?o:o===void 0?void 0:String(o)}var _l=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,s){let a=s?.length??0,l=r?.activeClients??[],d=de(t)?ce(t):t;this._telemetryService.publicLog2("agentHost.userMessageSent",{provider:n,initiatorClientType:e,agentSessionId:M.id(d),source:i,isSubagentSession:Ir(d),turnCount:r?.turns.length??0,...l.length>0?{activeClientId:l[0].clientId,activeClientToolCount:l.reduce((c,u)=>c+u.tools.length,0),activeClientCustomizationCount:l.reduce((c,u)=>c+(u.customizations?.length??0),0)}:{},attachmentCount:a})}assistantMessageReceived(n,e,t,r){let i=this._restricted;!i||!t||r.length===0||i.sendEnhancedGHTelemetryEvent("request.options.tools",Ho({headerRequestId:t,conversationId:M.id(n),initiatorClientType:e,messagesJson:JSON.stringify(r)}))}userMessageText(n,e,t,r){let i=this._restricted;if(!i||!t)return;let s=Ho({source:"user",conversationId:M.id(n),initiatorClientType:e,turnIndex:String(r),messageText:t}),a={messageCharLen:t.length};i.sendEnhancedGHTelemetryEvent("conversation.messageText",s,a),i.sendInternalMSFTTelemetryEvent("conversation.messageText",s,a)}modelMessageText(n,e,t,r,i){let s=this._restricted;if(!s||!t)return;let a=Ho({source:"model",conversationId:M.id(n),initiatorClientType:e,turnIndex:String(r),...i?{headerRequestId:i}:{},messageText:t}),l={messageCharLen:t.length};s.sendEnhancedGHTelemetryEvent("conversation.messageText",a,l),s.sendInternalMSFTTelemetryEvent("conversation.messageText",a,l)}toolCallDetails(n){let e=this._restricted;if(!e||n.availableTools.length===0)return;let t=de(n.session)?ce(n.session):n.session,r=Ho({conversationId:M.id(t),requestId:n.turnId,messageId:n.turnId,initiatorClientType:n.clientType,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(kn(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(kn(n.name)),skillExtensionIdHash:n.pluginName?String(kn(n.pluginName)):"",skillExtensionVersion:i,skillStorage:r,skillContentHash:t}),e.sendEnhancedGHTelemetryEvent("skillContentRead",s),e.sendInternalMSFTTelemetryEvent("skillContentRead",s)}reportRepoInfo(n,e){let t=this._restricted;if(!t)return;let r={remoteUrl:e.remoteUrl,repoId:e.repoId,repoType:e.repoType,headCommitHash:e.headCommitHash,headBranchName:e.headBranchName,fileRelativePaths:e.fileRelativePaths,diffsJSON:e.diffsJSON,result:e.result,isActiveRepository:e.isActiveRepository,location:e.location,telemetryMessageId:e.telemetryMessageId},i={workspaceFileCount:e.workspaceFileCount,changedFileCount:e.changedFileCount,diffSizeBytes:e.diffSizeBytes,repoIndex:0,repoCount:1},{headBranchName:s,fileRelativePaths:a,...l}=r;t.sendEnhancedGHTelemetryEventForContext(n,"request.repoInfo",Ho(r),i),t.sendInternalMSFTTelemetryEventForContext(n,"request.repoInfo",Ho(l),i)}turnCompleted(n){let e=de(n.session)?ce(n.session):n.session,t=n.model===void 0?void 0:n.modelTelemetryKind==="trusted"?new qs(n.model):n.modelTelemetryKind==="byok"?"byokModel":"unknown";this._telemetryService.publicLog2("agentHost.turnCompleted",{provider:n.provider,agentSessionId:M.id(e),turnId:n.turnId,timeToFirstProgress:n.timeToFirstProgress,totalTime:n.totalTime,result:n.result,model:t,modelSelectionKind:n.model===void 0?"default":n.model==="auto"?"auto":"explicit",permissionLevel:n.permissionLevel,errorType:n.failure?.error.errorType,failureStage:n.failure?.stage}),n.failure&&this._telemetryService.publicLogError2("agentHost.turnFailed",{provider:n.provider,agentSessionId:M.id(e),turnId:n.turnId,failureStage:n.failure.stage,errorType:n.failure.error.errorType,errorName:n.failure.errorName,errorCode:n.failure.errorCode,msg:n.failure.error.message,callstack:n.failure.errorStack??n.failure.error.stack})}toolInvoked(n){let e=de(n.session)?ce(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)?ce(n.session):n.session;this._telemetryService.publicLog2("agentHost.toolCallStalled",{provider:n.provider,agentSessionId:M.id(e),isSubagentSession:bs(n.session)||Ir(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,stalledTimeMs:n.stalledTimeMs})}stalledToolCallCompleted(n){let e=de(n.session)?ce(n.session):n.session;this._telemetryService.publicLog2("agentHost.stalledToolCallCompleted",{provider:n.provider,agentSessionId:M.id(e),isSubagentSession:bs(n.session)||Ir(e),blockerKind:n.blockerKind,toolId:n.toolId,toolSourceKind:n.toolSourceKind,result:n.result,totalTimeMs:n.totalTimeMs,timeAfterStallMs:n.timeAfterStallMs})}};var S4=300*1e3;function C4(o){if(o.success)return"success";let n=o.error?.code;return n==="rejected"||n==="denied"||n==="cancelled"?"userCancelled":"error"}function PP(o){if(!o)return"agentHost";let n=o.kind;switch(n){case"mcp":return"mcp";case"client":return"client";default:return n}}var Yg=class extends x{constructor(e){super();this._reporter=e;this._toolCalls=new Map;this._toolCallStallTimers=this._register(new Ee);this._stalledToolCalls=new Map}toolCallStarted(e,t,r,i,s){this._toolCalls.set(this._key(t,r),{stopWatch:lt.create(!0),provider:e,session:t,toolId:i,toolSourceKind:PP(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=C4(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=lt.create(!0);this._toolCallStallTimers.set(i,Ft(()=>{let l=a.elapsed();this._stalledToolCalls.set(s,{blockerKind:r.kind,completionStopWatch:lt.create(!0)}),this._reporter.toolCallStalled({provider:e,session:t,blockerKind:r.kind,toolId:r.toolCall.toolName,toolSourceKind:PP(r.toolCall.contributor),stalledTimeMs:l})},S4))}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 j4,release as K4}from"os";import{networkInterfaces as T4}from"os";import{networkInterfaces as I4}from"os";var b4=new Set(["00:00:00:00:00:00","ff:ff:ff:ff:ff:ff","ac:de:48:00:11:22"]);function _4(o){let n=o.replace(/\-/g,":").toLowerCase();return!b4.has(n)}function EP(){let o=I4();for(let n in o){let e=o[n];if(e){for(let{mac:t}of e)if(_4(t))return t}}throw new Error("Unable to retrieve mac address (unexpected format)")}var ele=new class{_isVirtualMachineMacAddress(o){return this._virtualMachineOUIs||(this._virtualMachineOUIs=qr.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=T4();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}},zC;async function Qg(o){return zC||(zC=(async()=>await w4(o)||F())()),zC}async function w4(o){try{let n=await import("crypto"),e=EP();return n.createHash("sha256").update(e,"utf8").digest("hex")}catch(n){o(n);return}}var R4="Software\\Microsoft\\SQMClient";async function kP(o){if(X){let n=await import("@vscode/windows-registry");try{return n.GetStringRegKey("HKEY_LOCAL_MACHINE",R4,"MachineId")||""}catch(e){return o(e),""}}return""}async function Xg(o){try{let e=await(await import("@vscode/deviceid")).getDeviceId();return Cw(e)}catch(n){return o(n),F()}}var em;(n=>n.DEFAULT={allowTrailingComma:!0})(em||={});function jC(o,n=!1){let e=0,t=o.length,r="",i=0,s=16,a=0;function l(y){let I=0,S=0;for(;I<y;){let C=o.charCodeAt(e);if(C>=48&&C<=57)S=S*16+C-48;else if(C>=65&&C<=70)S=S*16+C-65+10;else if(C>=97&&C<=102)S=S*16+C-97+10;else break;e++,I++}return I<y&&(S=-1),S}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&&Tl(o.charCodeAt(e));)e++;if(e<o.length&&o.charCodeAt(e)===46)if(e++,e<o.length&&Tl(o.charCodeAt(e)))for(e++;e<o.length&&Tl(o.charCodeAt(e));)e++;else return a=3,o.substring(y,e);let I=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&&Tl(o.charCodeAt(e))){for(e++;e<o.length&&Tl(o.charCodeAt(e));)e++;I=e}else a=3;return o.substring(y,I)}function u(){let y="",I=e;for(;;){if(e>=t){y+=o.substring(I,e),a=2;break}let S=o.charCodeAt(e);if(S===34){y+=o.substring(I,e),e++;break}if(S===92){if(y+=o.substring(I,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}I=e;continue}if(S>=0&&S<=31)if(Zg(S)){y+=o.substring(I,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(VC(y)){do e++,r+=String.fromCharCode(y),y=o.charCodeAt(e);while(VC(y));return s=15}if(Zg(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 I=e-1;if(o.charCodeAt(e+1)===47){for(e+=2;e<t&&!Zg(o.charCodeAt(e));)e++;return r=o.substring(I,e),s=12}if(o.charCodeAt(e+1)===42){e+=2;let S=t-1,C=!1;for(;e<S;){if(o.charCodeAt(e)===42&&o.charCodeAt(e+1)===47){e+=2,C=!0;break}e++}return C||(e++,a=1),r=o.substring(I,e),s=13}return r+=String.fromCharCode(y),e++,s=16}case 45:if(r+=String.fromCharCode(y),e++,e===t||!Tl(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&&g(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 g(y){if(VC(y)||Zg(y))return!1;switch(y){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function h(){let y;do y=p();while(y>=12&&y<=15);return y}return{setPosition:d,getPosition:()=>e,scan:n?h:p,getToken:()=>s,getTokenValue:()=>r,getTokenOffset:()=>i,getTokenLength:()=>e-i,getTokenError:()=>a}}function VC(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 Zg(o){return o===10||o===13||o===8232||o===8233}function Tl(o){return o>=48&&o<=57}function wl(o,n=[],e=em.DEFAULT){let t=null,r=[],i=[];function s(l){Array.isArray(r)?r.push(l):t!==null&&(r[t]=l)}return Rl(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 DP(o,n=[],e=em.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}Rl(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:x4(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 KC(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 Rl(o,n,e=em.DEFAULT){let t=jC(o,!1);function r(D){return D?()=>D(t.getTokenOffset(),t.getTokenLength()):()=>!0}function i(D){return D?z=>D(z,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),g=r(n.onComment),h=i(n.onError),y=e&&e.disallowComments,I=e&&e.allowTrailingComma;function S(){for(;;){let D=t.scan();switch(t.getTokenError()){case 4:C(14);break;case 5:C(15);break;case 3:C(13);break;case 1:y||C(11);break;case 2:C(12);break;case 6:C(16);break}switch(D){case 12:case 13:y?C(10):g();break;case 16:C(1);break;case 15:case 14:break;default:return D}}}function C(D,z=[],J=[]){if(h(D),z.length+J.length>0){let me=t.getToken();for(;me!==17;){if(z.indexOf(me)!==-1){S();break}else if(J.indexOf(me)!==-1)break;me=S()}}}function _(D){let z=t.getTokenValue();return D?u(z):a(z),S(),!0}function T(){switch(t.getToken()){case 11:{let D=0;try{D=JSON.parse(t.getTokenValue()),typeof D!="number"&&(C(2),D=0)}catch{C(2)}u(D);break}case 7:u(null);break;case 8:u(!0);break;case 9:u(!1);break;default:return!1}return S(),!0}function w(){return t.getToken()!==10?(C(3,[],[2,5]),!1):(_(!1),t.getToken()===6?(p(":"),S(),L()||C(4,[],[2,5])):C(5,[],[2,5]),!0)}function W(){s(),S();let D=!1;for(;t.getToken()!==2&&t.getToken()!==17;){if(t.getToken()===5){if(D||C(4,[],[]),p(","),S(),t.getToken()===2&&I)break}else D&&C(6,[],[]);w()||C(4,[],[2,5]),D=!0}return l(),t.getToken()!==2?C(7,[2],[]):S(),!0}function R(){d(),S();let D=!1;for(;t.getToken()!==4&&t.getToken()!==17;){if(t.getToken()===5){if(D||C(4,[],[]),p(","),S(),t.getToken()===4&&I)break}else D&&C(6,[],[]);L()||C(4,[],[4,5]),D=!0}return c(),t.getToken()!==4?C(8,[4],[]):S(),!0}function L(){switch(t.getToken()){case 3:return R();case 1:return W();case 10:return _(!0);default:return T()}}return S(),t.getToken()===17?e.allowEmptyContent?!0:(C(4,[],[]),!1):L()?(t.getToken()!==17&&C(9,[],[]),!0):(C(4,[],[]),!1)}function x4(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 OP(o,n,e){let t,r,i,s,a;if(n){for(s=n.offset,a=s+n.length,i=s;i>0&&!Au(o,i-1);)i--;let _=a;for(;_<o.length&&!Au(o,_);)_++;r=o.substring(i,_),t=A4(r,e)}else r=o,t=0,i=0,s=0,a=o.length;let l=P4(e,o),d=!1,c=0,u;e.insertSpaces?u=GC(" ",e.tabSize||4):u="	";let p=jC(r,!1),g=!1;function h(){return l+GC(u,t+c)}function y(){let _=p.scan();for(d=!1;_===15||_===14;)d=d||_===14,_=p.scan();return g=_===16||p.getTokenError()!==0,_}let I=[];function S(_,T,w){!g&&T<a&&w>s&&o.substring(T,w)!==_&&I.push({offset:T,length:w-T,content:_})}let C=y();if(C!==17){let _=p.getTokenOffset()+i,T=GC(u,t);S(T,i,_)}for(;C!==17;){let _=p.getTokenOffset()+p.getTokenLength()+i,T=y(),w="";for(;!d&&(T===12||T===13);){let R=p.getTokenOffset()+i;S(" ",_,R),_=p.getTokenOffset()+p.getTokenLength()+i,w=T===12?h():"",T=y()}if(T===2)C!==1&&(c--,w=h());else if(T===4)C!==3&&(c--,w=h());else{switch(C){case 3:case 1:c++,w=h();break;case 5:case 12:w=h();break;case 13:d?w=h():w=" ";break;case 6:w=" ";break;case 10:if(T===6){w="";break}case 7:case 8:case 9:case 11:case 2:case 4:T===12||T===13?w=" ":T!==5&&T!==17&&(g=!0);break;case 16:g=!0;break}d&&(T===12||T===13)&&(w=h())}let W=p.getTokenOffset()+i;S(w,_,W),C=T}return I}function GC(o,n){let e="";for(let t=0;t<n;t++)e+=o;return e}function A4(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 P4(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 Au(o,n){return`\r
`.indexOf(o.charAt(n))!==-1}function LP(o,n,e,t,r){let i=n.slice(),a=DP(o,[]),l,d;for(;i.length>0&&(d=i.pop(),l=KC(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=KC(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,g=c.parent.offset+c.parent.length;if(u>0){let h=l.children[u-1];p=h.offset+h.length}else p=l.offset+1,l.children.length>1&&(g=l.children[1].offset);return xl(o,{offset:p,length:g-p,content:""},t)}else return xl(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(h=>h.children[0].value)):l.children.length,g;if(p>0){let h=l.children[p-1];g={offset:h.offset+h.length,length:0,content:","+u}}else l.children.length===0?g={offset:l.offset+1,length:0,content:u}:g={offset:l.offset+1,length:0,content:u+","};return xl(o,g,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,g=l.children[p-1];u={offset:g.offset+g.length,length:0,content:","+c}}return xl(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 g=l.children[c-1],h=g.offset+g.length,y=l.offset+l.length;p={offset:h,length:y-2-h,content:""}}else p={offset:u.offset,length:l.children[c+1].offset-u.offset,content:""};return xl(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?[]:xl(o,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(e)},t)}function xl(o,n,e){let t=JC(o,n),r=n.offset,i=n.offset+n.content.length;if(n.length===0||n.content.length===0){for(;r>0&&!Au(t,r-1);)r--;for(;i<t.length&&!Au(t,i);)i++}let s=OP(t,{offset:r,length:i-r},e);for(let l=s.length-1;l>=0;l--){let d=s[l];t=JC(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 JC(o,n){return o.substring(0,n.offset)+n.content+o.substring(n.offset+n.length)}function NP(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=JC(o,i);else throw new Error("Overlapping edit");t=i.offset}return o}function UP(o){let n=!1,e=new Map,t=new Map;if(E4(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 g={schemas:[c]};return e.set(u,g),t.set(c,g),!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 g=t.get(p);if(g&&g.schemas.length>1)return g.id||(g.id=`_${s.length}`,s.push(g.schemas[0])),{$ref:`#/${i}/${g.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 Al(o){return typeof o=="object"&&o!==null}function E4(o,n){if(!o||typeof o!="object")return;let e=(...l)=>{for(let d of l)Al(d)&&s.push(d)},t=(...l)=>{for(let d of l)if(Al(d))for(let c in d){let u=d[c];Al(u)&&s.push(u)}},r=(...l)=>{for(let d of l)if(Array.isArray(d))for(let c of d)Al(c)&&s.push(c)},i=l=>{if(Array.isArray(l))for(let d of l)Al(d)&&s.push(d);else Al(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 QC={JSONContribution:"base.contributions.json"};function FP(o){return o.length>0&&o.charAt(o.length-1)==="#"?o.substring(0,o.length-1):o}var YC=class extends x{constructor(){super(...arguments);this.schemasById={};this.schemaAssociations={};this._onDidChangeSchema=this._register(new E);this.onDidChangeSchema=this._onDidChangeSchema.event;this._onDidChangeSchemaAssociations=this._register(new E);this.onDidChangeSchemaAssociations=this._onDidChangeSchemaAssociations.event}registerSchema(e,t,r){let i=FP(e);this.schemasById[i]=t,this._onDidChangeSchema.fire(e),r&&r.add(U(()=>{delete this.schemasById[i],this._onDidChangeSchema.fire(e)}))}registerSchemaAssociation(e,t){let r=FP(e);return this.schemaAssociations[r]||(this.schemaAssociations[r]=[]),this.schemaAssociations[r].includes(t)||(this.schemaAssociations[r].push(t),this._onDidChangeSchemaAssociations.fire()),U(()=>{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?UP(t):void 0}hasSchemaContent(e){return!!this.schemasById[e]}getSchemaAssociations(){return this.schemaAssociations}},k4=new YC;Kt.add(QC.JSONContribution,k4);var Qt,XC=globalThis.vscode;if(typeof XC<"u"&&typeof XC.context<"u"){let o=XC.context.configuration();if(o)Qt=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(Qt=globalThis._VSCODE_PRODUCT_JSON,at.VSCODE_DEV&&Object.assign(Qt,{nameShort:`${Qt.nameShort} Dev`,nameLong:`${Qt.nameLong} Dev`,dataFolderName:`${Qt.dataFolderName}-dev`,serverDataFolderName:Qt.serverDataFolderName?`${Qt.serverDataFolderName}-dev`:void 0}),!Qt.version){let o=globalThis._VSCODE_PACKAGE_JSON;Object.assign(Qt,{version:o.version})}Object.assign(Qt,{extensionsGallery:at.EXTENSIONS_GALLERY?JSON.parse(at.EXTENSIONS_GALLERY):Qt.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:at.CS_TELEMETRY_URL||Qt.telemetryEndpoint||"https://v1.telemetry.coder.com/track"})}else Qt={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.131.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.131.0",commit:"a3fc2899bd0fcd388253c0e79ce33b8acd48c688",date:"2026-07-28T06:40:51Z"},Object.keys(Qt).length===0&&Object.assign(Qt,{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 ln=Qt;var pr={Configuration:"base.contributions.configuration"};function D4(o,n){return o===n?!0:!o||!n?!1:typeof o=="string"||typeof n=="string"?o===n:o.id===n.id}var tm={properties:{},patternProperties:{}},nm={properties:{},patternProperties:{}},rm={properties:{},patternProperties:{}},om={properties:{},patternProperties:{}},im={properties:{},patternProperties:{}},sm={properties:{},patternProperties:{}},Pu={properties:{},patternProperties:{}},Bs="vscode://schemas/settings/resourceLanguage";var am=Kt.as(QC.JSONContribution),ZC=class extends x{constructor(){super();this.registeredConfigurationDefaults=[];this.overrideIdentifiers=new Set;this._onDidSchemaChange=this._register(new E);this.onDidSchemaChange=this._onDidSchemaChange.event;this._onDidUpdateConfiguration=this._register(new E);this.onDidUpdateConfiguration=this._onDidUpdateConfiguration.event;this.configurationDefaultsOverrides=new Map,this.defaultLanguageConfigurationOverridesNode={id:"defaultOverrides",title:f(2515,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={},am.registerSchema(Bs,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),am.registerSchema(Bs,this.resourceLanguageSettingsSchema),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire({properties:r})}deregisterConfigurations(e){let t=new Set;this.doDeregisterConfigurations(e,t),am.registerSchema(Bs,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),am.registerSchema(Bs,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}),Gr.test(a)){let c=this.mergeDefaultConfigurationsForOverrideIdentifier(a,d,s,l.configurationDefaultOverrideValue);if(!c)continue;l.configurationDefaultOverrideValue=c,this.updateDefaultOverrideProperty(a,c,s),r.push(...Pl(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?D4(d.source,i):d.value===r[s]);if(l!==-1){if(a.configurationDefaultOverrides.splice(l,1),a.configurationDefaultOverrides.length===0&&this.configurationDefaultsOverrides.delete(s),Gr.test(s)){let d;for(let c of a.configurationDefaultOverrides)d=this.mergeDefaultConfigurationsForOverrideIdentifier(s,c.value,c.source,d);d&&!Vp(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(2514,null,nx(e)),$ref:Bs,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(ze(d)&&(ya(s[l])||ze(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(ze(t)&&(s!==void 0&&s.type==="object"||s===void 0&&(ya(a)||ze(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={...ze(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=hr(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&&O4(c,u,r?.id)){delete l[c];continue}u.source=r,u.defaultDefaultValue=l[c].default,this.updatePropertyDefaultValue(c,u),Gr.test(c)?u.scope=void 0:(u.scope=hr(u.scope)?s:u.scope,u.restricted=hr(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,g=l[c].policy?.name,h=l[c].policyReference?.name;p?(this.excludedConfigurationProperties[c]=l[c],g&&(this.policyConfigurations.set(g,c),a.add(c)),h&&(this.addPolicyReferenceConfiguration(h,c),a.add(c)),delete l[c]):(a.add(c),g&&this.policyConfigurations.set(g,c),h&&this.addPolicyReferenceConfiguration(h,c),this.configurationProperties[c]=l[c],!l[c].deprecationMessage&&l[c].markdownDeprecationMessage&&(l[c].deprecationMessage=l[c].markdownDeprecationMessage))}let d=e.allOf;if(d)for(let c of d)this.validateAndRegisterProperties(c,t,r,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(tm.properties[e]=t,t.scope){case 1:nm.properties[e]=t;break;case 2:om.properties[e]=t;break;case 3:rm.properties[e]=t;break;case 7:im.properties[e]=t;break;case 4:sm.properties[e]=t;break;case 5:Pu.properties[e]=t;break;case 6:Pu.properties[e]=t,this.resourceLanguageSettingsSchema.properties[e]=t;break}}removeFromSchema(e,t){switch(delete tm.properties[e],t.scope){case 1:delete nm.properties[e];break;case 2:delete om.properties[e];break;case 3:delete rm.properties[e];break;case 7:delete im.properties[e];break;case 4:delete sm.properties[e];break;case 5:case 6:delete Pu.properties[e],delete this.resourceLanguageSettingsSchema.properties[e];break}}updateOverridePropertyPatternKey(){for(let e of this.overrideIdentifiers.values()){let t=`[${e}]`,r={type:"object",description:f(2516,null),errorMessage:f(2517,null),$ref:Bs};this.updatePropertyDefaultValue(t,r),tm.properties[t]=r,nm.properties[t]=r,rm.properties[t]=r,om.properties[t]=r,im.properties[t]=r,sm.properties[t]=r,Pu.properties[t]=r}}registerOverridePropertyPatternKey(){let e={type:"object",description:f(2516,null),errorMessage:f(2517,null),$ref:Bs};tm.patternProperties[_i]=e,nm.patternProperties[_i]=e,rm.patternProperties[_i]=e,om.patternProperties[_i]=e,im.patternProperties[_i]=e,sm.patternProperties[_i]=e,Pu.patternProperties[_i]=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),ya(i)&&(i=t.defaultDefaultValue,s=void 0),ya(i)&&(i=M4(t.type)),t.default=i,t.defaultValueSource=s}},$P="\\[([^\\]]+)\\]",HP=new RegExp($P,"g"),_i=`^(${$P})+$`,Gr=new RegExp(_i);function Pl(o){let n=[];if(Gr.test(o)){let e=HP.exec(o);for(;e?.length;){let t=e[1].trim();t&&n.push(t),e=HP.exec(o)}}return uo(n)}function WP(o){return o.reduce((n,e)=>`${n}[${e}]`,"")}function M4(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 lm=new ZC;Kt.add(pr.Configuration,lm);function O4(o,n,e){return o.trim()?Gr.test(o)?f(2513,null,o):lm.getConfigurationProperties()[o]!==void 0&&(!e||!L4.has(e.toLowerCase()))?f(2511,null,o):n.policy&&n.policyReference?f(2509,null,o):n.policy?.name&&lm.getPolicyConfigurations().get(n.policy?.name)!==void 0?f(2510,null,o,n.policy?.name,lm.getPolicyConfigurations().get(n.policy?.name)):null:f(2512,null)}var L4=new Set(ln.defaultChatAgent?[ln.defaultChatAgent.extensionId,ln.defaultChatAgent.chatExtensionId].map(o=>o.toLowerCase()):[]);function Eu(o){return Object.isFrozen(o)?o:nR(o)}var ut=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 dm("",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?Vc(this.contents,n):this.contents}inspect(n,e){let t=this;return{get value(){return Eu(t.rawConfiguration.getValue(n))},get override(){return e?Eu(t.rawConfiguration.getOverrideValue(n,e)):void 0},get merged(){return Eu(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?Eu(r):void 0}}}getOverrideValue(n,e){let t=this.getContentsForOverrideIdentifer(e);return t?n?Vc(t,n):t:void 0}getKeysForOverrideIdentifier(n){let e=[];for(let t of this.overrides)t.identifiers.includes(n)&&e.push(...t.keys);return uo(e)}getAllOverrideIdentifiers(){let n=[];for(let e of this.overrides)n.push(...e.identifiers);return uo(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=er(this.contents),t=er(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=>Nn(d.identifiers,a.identifiers));l?(this.mergeContents(l.contents,a.contents),l.keys.push(...a.keys),l.keys=uo(l.keys)):t.push(er(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 uo([...Object.keys(this.contents),...Object.keys(e)])){let i=this.contents[r],s=e[r];s&&(typeof i=="object"&&typeof s=="object"?(i=er(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&&ze(n[t])&&ze(e[t])){this.mergeContents(n[t],e[t]);continue}n[t]=er(e[t])}}getContentsForOverrideIdentifer(n){let e=null,t=null,r=i=>{i&&(t?this.mergeContents(t,i):t=er(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),ex(this.contents,n),Gr.test(n)&&this.overrides.splice(this.overrides.findIndex(t=>Nn(t.identifiers,Pl(n))),1))}updateValue(n,e,t){if(AS(this.contents,n,e,r=>this.logService.error(r)),t=t||this.keys.indexOf(n)===-1,t&&this.keys.push(n),Gr.test(n)){let r=this.contents[n],i=Pl(n),s={identifiers:i,keys:Object.keys(r),contents:$f(r,l=>this.logService.error(l))},a=this.overrides.findIndex(l=>Nn(l.identifiers,i));a!==-1?this.overrides[a]=s:this.overrides.push(s)}}},dm=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||ut.createEmptyModel(this.logService)}get restrictedConfigurations(){return this._restrictedConfigurations}get errors(){return this._parseErrors}parse(n,e){if(!hr(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 ut(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{Rl(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=Kt.as(pr.Configuration),r=t.getConfigurationProperties(),i=t.getExcludedConfigurationProperties(),s=this.filter(n,r,i,!0,e);n=s.raw;let a=$f(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(Gr.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(Gr.test(r)){let i={},s=n[r];for(let a in s)i[a]=s[a];t.push({identifiers:Pl(r),keys:Object.keys(i),contents:$f(i,e)})}return t}},cm=class extends x{constructor(e,t,r,i,s){super();this.userSettingsResource=e;this.parseOptions=t;this.fileService=i;this.logService=s;this._onDidChange=this._register(new E);this.onDidChange=this._onDidChange.event;this.parser=new dm(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 ut.createEmptyModel(this.logService)}}reparse(e){return e&&(this.parseOptions=e),this.parser.reparse(this.parseOptions),this.parser.configurationModel}getRestrictedSettings(){return this.parser.restrictedConfigurations}},eI=class{constructor(n,e,t,r,i,s,a,l,d,c,u,p,g){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=g}get value(){return Eu(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)}},El=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 Me;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=ut.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 eI(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}=Ti(this._defaultConfiguration,n);e=[...r,...i,...s]}for(let r of e)for(let i of Pl(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=>!Oe(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}=Ti(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}=Ti(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}=Ti(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}=Ti(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}=Ti(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}=Ti(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}=Ti(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 ut(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(v.revive(u[0]),this.parseConfigurationModel(u[1],e)),c),new Me);return new o(t,r,i,s,a,l,d,ut.createEmptyModel(e),new Me,e)}static parseConfigurationModel(n,e){return new ut(n.contents,n.keys,n.overrides,n.raw,e)}};var um=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=El.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!Oe(a,l)}return!0}};function Ti(o,n){let{added:e,removed:t,updated:r}=qP(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=qP({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 qP(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=Vc(n.contents,i),a=Vc(o.contents,i);Oe(s,a)||r.push(i)}}return{added:e,removed:t,updated:r}}var pm=B("policy");var wi=class{constructor(){this.onDidChange=ee.None;this.policyDefinitions={}}async updatePolicyDefinitions(){return{}}getPolicyValue(){}serialize(){}};var fm=class extends x{constructor(e){super();this.logService=e;this._onDidChangeConfiguration=this._register(new E);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._configurationModel=ut.createEmptyModel(e)}get configurationModel(){return this._configurationModel}async initialize(){return this.resetConfigurationModel(),this._register(Kt.as(pr.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,Kt.as(pr.Configuration).getConfigurationProperties()),this._onDidChangeConfiguration.fire({defaults:this.configurationModel,properties:e})}getConfigurationDefaultOverrides(){return{}}resetConfigurationModel(){this._configurationModel=ut.createEmptyModel(this.logService);let e=Kt.as(pr.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 er(t.default)}},gm=class{constructor(){this.onDidChangeConfiguration=ee.None;this.configurationModel=ut.createEmptyModel(new ig)}async initialize(){return this.configurationModel}},kl=class extends x{constructor(e,t,r){super();this.defaultConfiguration=e;this.policyService=t;this.logService=r;this._onDidChangeConfiguration=this._register(new E);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this._submittedPolicyDefinitions=new Map;this._policyNameByKey=new Map;this._configurationModel=ut.createEmptyModel(this.logService),this.configurationRegistry=Kt.as(pr.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 Vp(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(Be(u)&&!p)try{u=this.parse(u)}catch(g){this.logService.error(`Error parsing policy value ${c}:`,In(g));continue}(a?u!==void 0:!Oe(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=ut.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&&(Rl(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=>In(c.error)).join(`
`));return t}};kl=A([b(1,pm),b(2,O)],kl);var Dl=class extends x{constructor(e,t,r,i){super();this.settingsResource=e;this.logService=i;this._onDidChangeConfiguration=this._register(new E);this.onDidChangeConfiguration=this._onDidChangeConfiguration.event;this.defaultConfiguration=this._register(new fm(i)),this.policyConfiguration=r instanceof wi?new gm:this._register(new kl(this.defaultConfiguration,r,i)),this.userConfiguration=this._register(new cm(this.settingsResource,{},re,t,i)),this.configuration=new El(this.defaultConfiguration.configurationModel,this.policyConfiguration.configurationModel,ut.createEmptyModel(i),ut.createEmptyModel(i),ut.createEmptyModel(i),ut.createEmptyModel(i),new Me,ut.createEmptyModel(i),new Me,i),this.configurationEditing=new tI(e,t,this),this.reloadConfigurationScheduler=this._register(new ai(()=>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 El(e,t,ut.createEmptyModel(this.logService),r,ut.createEmptyModel(this.logService),ut.createEmptyModel(this.logService),new Me,ut.createEmptyModel(this.logService),new Me,this.logService)}getConfigurationData(){return this.configuration.toData()}getValue(e,t){let r=typeof e=="string"?e:void 0,i=Hf(e)?e:Hf(t)?t:{};return this.configuration.getValue(r,i,void 0)}async updateValue(e,t,r,i,s){let a=ZR(r)?r:Hf(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=uo(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(Oe(t,d.defaultValue)&&(t=void 0),a?.overrideIdentifiers?.length&&a.overrideIdentifiers.length>1){let u=a.overrideIdentifiers.sort(),p=this.configuration.localUserConfiguration.overrides.find(g=>Nn([...g.identifiers].sort(),u));p&&(a.overrideIdentifiers=p.identifiers)}let c=a?.overrideIdentifiers?.length?[WP(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 um(e,{data:t},this.configuration,void 0,this.logService);i.source=r,this._onDidChangeConfiguration.fire(i)}},tI=class{constructor(n,e,t){this.settingsResource=n;this.fileService=e;this.configurationService=t;this.queue=new ii}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(wl(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=NP(t,i),await this.fileService.writeFile(this.settingsResource,$.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 LP(n,e,t,{tabSize:r,insertSpaces:i,eol:s})}get formattingOptions(){if(!this._formattingOptions){let n=qt===3||qt===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 Ri=B("requestService"),hm="NO_FETCH_TELEMETRY",rI=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}},mm=class extends x{constructor(e){super();this.logService=e;this.counter=0;this._onDidCompleteRequest=this._register(new E);this.onDidCompleteRequest=this._onDidCompleteRequest.event}async logAndRequest(e,t){let r=`#${++this.counter}: ${e.url}`;this.logService.trace(`${r} - begin`,e.type,new rI(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,In(s)),s}}};var Ml=!1,nI=[],zP,VP;function U4(o=!0,n=!0){if(zP===o&&VP===n)return;zP=o,VP=n;let e=Kt.as(pr.Configuration),t=nI;nI=[{id:"http",order:15,title:f(2885,null),type:"object",scope:2,properties:{"http.useLocalProxyConfiguration":{type:"boolean",default:n,markdownDescription:f(2900,null),restricted:!0}}},{id:"http",order:15,title:f(2885,null),type:"object",scope:1,properties:{"http.electronFetch":{type:"boolean",default:!1,description:f(2883,null),restricted:!0}}},{id:"http",order:15,title:f(2885,null),type:"object",scope:o?1:2,properties:{"http.proxy":{type:"string",pattern:"^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",markdownDescription:f(2888,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyStrictSSL":{type:"boolean",default:!0,markdownDescription:f(2896,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyKerberosServicePrincipal":{type:"string",markdownDescription:f(2890,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.noProxy":{type:"array",items:{type:"string"},markdownDescription:f(2887,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxyAuthorization":{type:["null","string"],default:null,markdownDescription:f(2889,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.proxySupport":{type:"string",enum:["off","on","fallback","override"],enumDescriptions:[f(2893,null),f(2894,null),f(2892,null),f(2895,null)],default:"override",markdownDescription:f(2891,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificates":{type:"boolean",default:!0,markdownDescription:f(2897,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.systemCertificatesNode":{type:"boolean",tags:["experimental"],default:Ml,markdownDescription:f(2898,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}},"http.experimental.systemCertificatesV2":{type:"boolean",tags:["experimental"],default:!1,markdownDescription:f(2899,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0},"http.fetchAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2884,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.webSocketAdditionalSupport":{type:"boolean",default:!0,markdownDescription:f(2901,null,"`#http.useLocalProxyConfiguration#`","`#http.proxySupport#`","`#http.systemCertificates#`"),restricted:!0},"http.experimental.networkInterfaceCheckInterval":{type:"number",default:300,minimum:-1,tags:["experimental"],markdownDescription:f(2886,null,"`#http.useLocalProxyConfiguration#`"),restricted:!0,experiment:{mode:"auto"}}}}],e.updateConfigurations({add:nI,remove:t})}U4();var iI=class{constructor(n,e,t){this.id=n;this.dependencies=e;this.callback=t}};var sI=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 iI(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}://${pS}`))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=F();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=v.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}}},oI=new Map;async function aI(o,n,e){e===void 0&&(e=!!(globalThis._VSCODE_PRODUCT_JSON??globalThis.vscode?.context?.configuration()?.product)?.commit);let t=n?`${o}/${n}`:o;if(oI.has(t))return oI.get(t);let r;if(/^\w[\w\d+.-]*:\/\//.test(t))r=t;else{let l=`${e&&(VT||Bv&&QT)?Dw:sf}/${t}`;r=Nt.asBrowserUri(l).toString(!0)}let i=sI.INSTANCE.load(r);return oI.set(t,i),i}var jP="https://mobile.events.data.microsoft.com/OneCollector/1.0",F4="https://mobile.events.data.microsoft.com/ping";async function H4(o,n,e){let t=Qn?await aI("@microsoft/1ds-core-js","bundle/ms.core.min.js"):await import("@microsoft/1ds-core-js"),r=Qn?await aI("@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:jP,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 ym=class{constructor(n,e,t,r,i){this._isInternalTelemetry=n;this._eventPrefix=e;this._defaultData=t;this._xhrOverride=i;this.endPointUrl=jP;this.endPointHealthUrl=F4;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=H4(this._aiCoreOrKey,this._isInternalTelemetry,this._xhrOverride)),this._asyncAiCore.then(e=>{n(e)},e=>{Ye(e),console.error(e)})}}log(n,e){if(!this._aiCoreOrKey)return;e=Ha(e,this._defaultData);let t=Gg(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 $4(o,n){let e=await n.request(o,ke.None),t=(await Nr(e.stream)).toString(),r=e.res.statusCode??200;return{headers:e.res.headers,statusCode:r,responseData:t}}async function W4(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 q4(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:hm};try{let i=o?await $4(r,o):await W4(r);e(i.statusCode,i.headers,i.responseData)}catch{e(0,{})}}var zs=class extends ym{constructor(n,e,t,r,i){let s={sendPOST:(a,l)=>{q4(n,a,l)}};super(e,t,r,i,s)}};var ku=B("environmentService"),St=ku;var Ol=class extends x{constructor(e,t,r,i,s){super();this.prefix=e;let a=t?"remoteTelemetry":qC,l=r.getLogger(a);if(l)this.logger=this._register(l);else{let c=Kg(s,i)?" (Not Sent)":"";this.logger=this._register(r.createLogger(a,{name:f(2905,null,c),group:CP,hidden:!0}))}}flush(){return Promise.resolve()}log(e,t){this.logger.trace(`${this.prefix}telemetry/${e}`,Gg(t))}};Ol=A([b(2,Bx),b(3,ku),b(4,Tt)],Ol);var tue={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 $o=class{constructor(n,e,t){this._configurationService=e;this._productService=t;this._experimentProperties={};this._pendingEvents=[];this._isExperimentPropertySet=!1;this._disposables=new G;this._cleanupPatterns=[];this._appenders=n.appenders,this._commonProperties=n.commonProperties??Object.create(null),this.sessionId=this._commonProperties.sessionID,this.machineId=this._commonProperties["common.machineId"],this.sqmId=this._commonProperties["common.sqmId"],this.devDeviceId=this._commonProperties["common.devDeviceId"],this.firstSessionDate=this._commonProperties["common.firstSessionDate"],this.msftInternal=this._commonProperties["common.msftInternal"],this._piiPaths=n.piiPaths||[],this._telemetryLevel=3,this._sendErrorTelemetry=!!n.sendErrorTelemetry,this._meteredConnectionService=n.meteredConnectionService,this._cleanupPatterns=[/(vscode-)?file:\/\/.*?\/resources\/app\//gi];for(let r of this._piiPaths)this._cleanupPatterns.push(new RegExp(Un(r),"gi")),r.indexOf("\\")>=0&&this._cleanupPatterns.push(new RegExp(Un(r.replace(/\\/g,"/")),"gi"));this._updateTelemetryLevel(),this._disposables.add(this._configurationService.onDidChangeConfiguration(r=>{(r.affectsConfiguration(Ga)||r.affectsConfiguration(jc)||r.affectsConfiguration(Wf))&&this._updateTelemetryLevel()})),n.waitForExperimentProperties?this._flushTimeout=setTimeout(()=>this._flushPendingEvents(),$o.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 qs(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=bP(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<$o.MAX_BUFFER_SIZE&&this._pendingEvents.push({eventName:n,eventLevel:e,data:t});return}this._doLog(n,e,t)}}_doLog(n,e,t){t=Ha(t,this._experimentProperties),t=xP(t,this._cleanupPatterns),t=Ha(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)}};$o=A([b(1,ir),b(2,Tt)],$o);function B4(){let o=f(2922,null,ln.nameLong),n=ln.privacyStatementUrl?f(2908,null,"https://aka.ms/vscode-telemetry",ln.privacyStatementUrl):f(2909,null,"https://aka.ms/vscode-telemetry"),e=Qn?"":f(2914,null),t=f(2907,null),r=f(2912,null),i=f(2923,null),s=f(2921,null),a=`
|       | ${t} | ${r} | ${i} |
|:------|:-------------:|:---------------:|:----------:|
| all   |       \u2713       |        \u2713        |     \u2713      |
| error |       \u2713       |        \u2713        |     -      |
| crash |       \u2713       |        -        |     -      |
| off   |       -       |        -        |     -      |
`,l=f(2917,null);return`
${o} ${n} ${e}

&nbsp;

${s}
${a}

&nbsp;

${l}
`}var z4=Kt.as(pr.Configuration);z4.registerConfiguration({id:rx,order:1,type:"object",title:f(2924,null),properties:{[Ga]:{type:"string",enum:["all","error","crash","off"],enumDescriptions:[f(2916,null),f(2918,null),f(2915,null),f(2919,null)],markdownDescription:B4(),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(2920,null)},enumDescriptions:[{key:"telemetry.telemetryLevel.default",value:f(2916,null)},{key:"telemetry.telemetryLevel.error",value:f(2918,null)},{key:"telemetry.telemetryLevel.crash",value:f(2915,null)},{key:"telemetry.telemetryLevel.off",value:f(2919,null)}]}}},"telemetry.feedback.enabled":{type:"boolean",default:!0,description:f(2913,null),policy:{name:"EnableFeedback",category:"Telemetry",minimumVersion:"1.99",localization:{description:{key:"telemetry.feedback.enabled",value:f(2913,null)}}}},[jc]:{type:"boolean",markdownDescription:ln.privacyStatementUrl?f(2911,null,ln.nameLong,ln.privacyStatementUrl):f(2910,null,ln.nameLong),default:!0,restricted:!0,markdownDeprecationMessage:f(2906,null,`\`#${Ga}#\``),scope:1,tags:["usesOnlineServices","telemetry"]}}});var KP="VSCODE_AGENT_HOST_MACHINE_ID",GP="VSCODE_AGENT_HOST_SQM_ID",JP="VSCODE_AGENT_HOST_DEV_DEVICE_ID";var YP="ec712b3202c5462fb6877acae7f1f9d7-c19ad55e-3e3c-4f99-984b-827f6d95bd9e-6917",vm="GitHub.copilot-chat",V4="GitHub.copilot-chat";function QP(o,n){if(!o)return;let e=Object.create(null);return Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)),e["common.extname"]=V4,e["common.extversion"]=n,e["common.vscodemachineid"]=o["common.machineId"],e["common.vscodesessionid"]=o.sessionID,e["common.vscodecommithash"]=o.commitHash,e["common.vscodeversion"]=o.version,e}var Sm=class extends x{constructor(e){super();this.appender=e;this._register(U(()=>{e.flush()}))}},Cm=class extends x{constructor(e={}){super();this._options=e;this._appender=this._register(new ht)}setContext(e){if(this._context=e?.isInternal?e:void 0,!this._context){this._appender.clear();return}let t=this._options.createAppender??((r,i)=>new zs(r,!0,vm,i??null,YP));this._appender.value??=new Sm(t(this._options.requestService,QP(this._options.commonProperties,this._options.extensionVersion),vm))}send(e,t,r){this._context&&this.sendForContext(this._context,e,t,r)}sendForContext(e,t,r,i){if(!e.isInternal)return;let s=this._options.createAppender??((a,l)=>new zs(a,!0,vm,l??null,YP));this._appender.value??=new Sm(s(this._options.requestService,QP(this._options.commonProperties,this._options.extensionVersion),vm)),this._appender.value.appender.log(t,{...r,...i,"common.tid":e.trackingId,"common.userName":e.userName??"undefined","common.isVscodeTeamMember":e.isVscodeTeamMember?1:0})}};var Im=class extends x{constructor(e,t){super();this._delegate=e;this._restricted=t;this._telemetryLevel=3;this._restrictedTelemetryEnabled=!1;this._internalTelemetryEnabled=!1;ba(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)}sendEnhancedGHTelemetryEventForContext(e,t,r,i){this.telemetryLevel<3||!e.restrictedTelemetryEnabled||this._restricted?.sendEnhancedGHTelemetryEventForContext(e,t,r,i)}sendInternalMSFTTelemetryEvent(e,t,r){this.telemetryLevel<3||!this._internalTelemetryEnabled||this._restricted?.sendInternalMSFTTelemetryEvent(e,t,r)}sendInternalMSFTTelemetryEventForContext(e,t,r,i){this.telemetryLevel<3||!e.isInternal||this._restricted?.sendInternalMSFTTelemetryEventForContext(e,t,r,i)}setCopilotTrackingId(e){this._restricted?.setCopilotTrackingId(e)}setRestrictedTelemetryEndpoint(e){this._restricted?.setRestrictedTelemetryEndpoint(e)}setRestrictedTelemetryEnabled(e){this._restrictedTelemetryEnabled=e,this._restricted?.setRestrictedTelemetryEnabled(e)}setInternalTelemetryContext(e){this._internalTelemetryEnabled=e?.isInternal===!0,this._restricted?.setInternalTelemetryContext(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 bm(o,n){let e=n?.[Kc],t=gx(e);!_m(o)||t===void 0||o.updateTelemetryLevel(t)}function _m(o){return typeof o.updateTelemetryLevel=="function"}async function G4(o,n,e){if(o.builtinExtensionsPath)try{let t=JSON.parse((await n.readFile(Y(v.file(o.builtinExtensionsPath),"copilot","package.json"))).value.toString());return typeof t.version=="string"?t.version:void 0}catch(t){e.debug(`[agentHostTelemetry] Failed to resolve Copilot extension version: ${t instanceof Error?t.message:String(t)}`);return}}async function XP(o){let{environmentService:n,productService:e,fileService:t,loggerService:r,logService:i,disposables:s}=o;if(o.disableTelemetry||!r||!IP(e,n))return s.add(new Im(jg));let a=s.add(new Dl(Y(n.appSettingsHome,"settings.json"),t,new wi,i));await a.initialize();let l=[s.add(new Ol("",!1,r,n,e))],d=TP(e,a),c=Kg(e,n);if(!c&&e.aiConfig?.ariaKey){let _=new zs(o.requestService,d,"monacoworkbench",null,e.aiConfig.ariaKey);s.add(U(()=>{_.flush()})),l.push(_)}let[u,p,g]=await Promise.all([process.env[KP]||Qg(_=>i.error(_)),process.env[GP]||kP(_=>i.error(_)),process.env[JP]||Xg(_=>i.error(_))]),h=yP(K4(),j4(),process.arch,e.commit,e.version,u,p,g,d,e.date),y=new $o({appenders:l,sendErrorTelemetry:!0,commonProperties:h,piiPaths:wP(n)},a,e),I=c?void 0:await G4(n,t,i),S=c?void 0:s.add(new Cm({requestService:o.requestService,commonProperties:h,extensionVersion:I})),C=c?void 0:new Jg(h,i,void 0,S,o.fetchFn);return s.add(new Im(y,C))}var Tm=class{constructor(n){this._reporter=n;this._turnTimings=new Map}turnStarted(n,e,t,r,i,s){let a=this._key(e,t);this._turnTimings.set(a,{stopWatch:lt.create(!1),provider:n,session:e,model:r,modelTelemetryKind:i,permissionLevel:s,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,r){let i=this._key(n,e),s=this._turnTimings.get(i);s&&(this._turnTimings.delete(i),this._reporter.turnCompleted({provider:s.provider,session:s.session,turnId:e,timeToFirstProgress:s.firstProgressMs,totalTime:s.stopWatch.elapsed(),result:t,model:s.model,modelTelemetryKind:s.modelTelemetryKind,permissionLevel:s.permissionLevel,failure:r}))}_key(n,e){return`${n}\0${e}`}};function wm(o,n,e,t,r){let i=o.openDatabase(v.parse(e));i.object.setMetadata(t,r).catch(s=>{n.warn(`[AgentHost] Failed to persist session metadata '${t}'`,s)}).finally(()=>{i.dispose()})}var lI=class{constructor(){this._ctors=[]}register(n){this._ctors.push(n)}createAll(n){return this._ctors.map(e=>new e(n))}},Du=new lI,Ll=class extends x{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)=>wm(this._sessionDataService,this._logService,d,c,u)};this._commands=Du.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),r}}async _run(e,t,r){let i=lt.create(!1);try{await t.run()}catch(s){this._logService.error(`[AgentHostLocalCommands] Command '${e.name}' failed: ${s instanceof Error?s.message:String(s)}`,s)}finally{this._stateManager.dispatchServerAction(r.turnChannel,{type:"chat/turnComplete",turnId:r.turnId,duration:Math.max(0,i.elapsed())}),e.recordsLocalTurn&&this._recordLocalTurn(r.turnChannel,r.turnId),this._notifyTurnConsumable(r.turnChannel)}}_recordLocalTurn(e,t){let r=e,i=de(e)?ce(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,J4(s[a]),l)}};Ll=A([b(3,O),b(4,ur),b(5,nt)],Ll);function J4(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 Mu(o){let n={command:o.command};o.description!==void 0&&(n.description=o.description),o.argumentHint!==void 0&&(n.argumentHint=o.argumentHint);let e=Q4(o.action);return e!==void 0&&(n.action=e),n}function ZP(o){if(!(!o||typeof o!="object"||Array.isArray(o)))return Y4(o.action)}function Y4(o){if(!o||typeof o!="object"||Array.isArray(o))return;let n=o,e,t=n.applyConfig;if(t&&typeof t=="object"&&!Array.isArray(t))for(let[r,i]of Object.entries(t))typeof i=="string"&&(e??={},e[r]=i);if(e!==void 0)return{applyConfig:e}}function Q4(o){if(!(!o?.applyConfig||Object.keys(o.applyConfig).length===0))return{applyConfig:{...o.applyConfig}}}function eE(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 Rm=B("agentHostCompletions");var Nl=class extends x{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),U(()=>this._providers.delete(e))}async completions(e,t=ke.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}}};Nl=A([b(0,O)],Nl);var _pe=new Uint32Array(10);var Tpe=new Uint8Array([114,82,115,101,69,102,97,113,81,116,84,100,119,87,99,122,120,118,103]),wpe=new Uint16Array([107,111,105,79,106,112,117,80,104,27496,28520,27752,121,110,27246,28782,27758,98,109,27757,108]),Rpe=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]),xpe=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 nE(...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 Lpe=rE.bind(void 0,!1),Pm=rE.bind(void 0,!0);function rE(o,n,e){if(!e||e.length<n.length)return null;let t;return o?t=ni(e,n):t=e.indexOf(n)===0,t?n.length>0?[{start:0,end:n.length}]:[]:null}function X4(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 Z4(o,n){return o.length>n.length?null:cI(o.toLowerCase(),n.toLowerCase(),0,0)}function cI(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=cI(o,n,e+1,t+1))?iE({start:t,end:t+1},r):null}return cI(o,n,e,t+1)}function gI(o){return 97<=o&&o<=122}function Ul(o){return 65<=o&&o<=90}function mI(o){return 48<=o&&o<=57}function e5(o){return o===32||o===9||o===10||o===13}var t5=new Set;"()[]{}<>`'\"-/;:,.?!".split("").forEach(o=>t5.add(o.charCodeAt(0)));function oE(o){return gI(o)||Ul(o)||mI(o)}function iE(o,n){return n.length===0?n=[o]:o.end===n[0].start?n[0].start=o.start:n.unshift(o),n}function sE(o,n){for(let e=n;e<o.length;e++){let t=o.charCodeAt(e);if(Ul(t)||mI(t)||e>0&&!oE(o.charCodeAt(e-1)))return e}return o.length}function uI(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=uI(o,n,e+1,t+1);!r&&(i=sE(n,i))<n.length;)r=uI(o,n,e+1,i),i++;return r===null?null:iE({start:t,end:t+1},r)}}function n5(o){let n=0,e=0,t=0,r=0,i=0;for(let c=0;c<o.length;c++)i=o.charCodeAt(c),Ul(i)&&n++,gI(i)&&e++,oE(i)&&t++,mI(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 r5(o){let{upperPercent:n,lowerPercent:e}=o;return e===0&&n>.6}function o5(o){let{upperPercent:n,lowerPercent:e,alphaPercent:t,numericPercent:r}=o;return e>.2&&n<.8&&t>.6&&r<.2}function i5(o){let n=0,e=0,t=0,r=0;for(let i=0;i<o.length;i++)t=o.charCodeAt(i),Ul(t)&&n++,gI(t)&&e++,e5(t)&&r++;return(n===0||e===0)&&r===0?o.length<=30:n<=5}function aE(o,n){if(!n||(n=n.trim(),n.length===0)||!i5(o))return null;n.length>60&&(n=n.substring(0,60));let e=n5(n);if(!o5(e)){if(!r5(e))return null;n=n.toLowerCase()}let t=null,r=0;for(o=o.toLowerCase();r<n.length&&(t=uI(o,n,0,r))===null;)r=sE(n,r+1);return t}var Npe=nE(Pm,aE,X4),Upe=nE(Pm,aE,Z4),Fpe=new bn(1e4);function Em(o,n){let e=uE(o,o.toLowerCase(),0,n,n.toLowerCase(),0,{firstMatchCanBeWeak:!0,boostFullMatch:!0});return e?lE(e):null}function lE(o){if(typeof o>"u")return[];let n=[],e=o[1];for(let t=o.length-1;t>1;t--){let r=o[t]+e,i=n[n.length-1];i&&i.end===r?i.end=r+1:n.push({start:r,end:r+1})}return n}var Ai=128;function hI(){let o=[],n=[];for(let e=0;e<=Ai;e++)n[e]=0;for(let e=0;e<=Ai;e++)o.push(n.slice(0));return o}function dE(o){let n=[];for(let e=0;e<=o;e++)n[e]=0;return n}var cE=dE(2*Ai),pI=dE(2*Ai),Jr=hI(),xi=hI(),Ou=hI(),s5=!1;function dI(o,n,e,t,r){function i(a,l,d=" "){for(;a.length<l;)a=d+a;return a}let s=` |   |${t.split("").map(a=>i(a,3)).join("|")}
`;for(let a=0;a<=e;a++)a===0?s+=" |":s+=`${n[a-1]}|`,s+=o[a].slice(0,r+1).map(l=>i(l.toString(),3)).join("|")+`
`;return s}function a5(o,n,e,t){o=o.substr(n),e=e.substr(t),console.log(dI(xi,o,o.length,e,e.length)),console.log(dI(Ou,o,o.length,e,e.length)),console.log(dI(Jr,o,o.length,e,e.length))}function xm(o,n){if(n<0||n>=o.length)return!1;let e=o.codePointAt(n);switch(e){case 95:case 45:case 46:case 32:case 47:case 92:case 39:case 34:case 58:case 36:case 60:case 62:case 40:case 41:case 91:case 93:case 123:case 125:return!0;case void 0:return!1;default:return!!vw(e)}}function tE(o,n){if(n<0||n>=o.length)return!1;switch(o.charCodeAt(n)){case 32:case 9:return!0;default:return!1}}function Am(o,n,e){return n[o]!==e[o]}function l5(o,n,e,t,r,i,s=!1){for(;n<e&&r<i;)o[n]===t[r]&&(s&&(cE[n]=r),n+=1),r+=1;return n===e}var d5;(e=>{e.Default=[-100,0];function n(t){return!t||t.length===2&&t[0]===-100&&t[1]===0}e.isDefault=n})(d5||={});var fI=class{constructor(n,e){this.firstMatchCanBeWeak=n;this.boostFullMatch=e}static{this.default={boostFullMatch:!0,firstMatchCanBeWeak:!1}}};function uE(o,n,e,t,r,i,s=fI.default){let a=o.length>Ai?Ai:o.length,l=t.length>Ai?Ai:t.length;if(e>=a||i>=l||a-e>l-i||!l5(n,e,a,r,i,l,!0))return;c5(a,l,e,i,n,r);let d=1,c=1,u=e,p=i,g=[!1];for(d=1,u=e;u<a;d++,u++){let C=cE[u],_=pI[u],T=u+1<a?pI[u+1]:l;for(c=C-i+1,p=C;p<T;c++,p++){let w=Number.MIN_SAFE_INTEGER,W=!1;p<=_&&(w=u5(o,n,u,e,t,r,p,l,i,Jr[d-1][c-1]===0,g));let R=0;w!==Number.MIN_SAFE_INTEGER&&(W=!0,R=w+xi[d-1][c-1]);let L=p>C,D=L?xi[d][c-1]+(Jr[d][c-1]>0?-5:0):0,z=p>C+1&&Jr[d][c-1]>0,J=z?xi[d][c-2]+(Jr[d][c-2]>0?-5:0):0;if(z&&(!L||J>=D)&&(!W||J>=R))xi[d][c]=J,Ou[d][c]=3,Jr[d][c]=0;else if(L&&(!W||D>=R))xi[d][c]=D,Ou[d][c]=2,Jr[d][c]=0;else if(W)xi[d][c]=R,Ou[d][c]=1,Jr[d][c]=Jr[d-1][c-1]+1;else throw new Error("not possible")}}if(s5&&a5(o,e,t,i),!g[0]&&!s.firstMatchCanBeWeak)return;d--,c--;let h=[xi[d][c],i],y=0,I=0;for(;d>=1;){let C=c;do{let _=Ou[d][C];if(_===3)C=C-2;else if(_===2)C=C-1;else break}while(C>=1);y>1&&n[e+d-1]===r[i+c-1]&&!Am(C+i-1,t,r)&&y+1>Jr[d][C]&&(C=c),C===c?y++:y=1,I||(I=C),d--,c=C-1,h.push(c)}l-i===a&&s.boostFullMatch&&(h[0]+=2);let S=I-a;return h[0]-=S,h}function c5(o,n,e,t,r,i){let s=o-1,a=n-1;for(;s>=e&&a>=t;)r[s]===i[a]&&(pI[s]=a,s--),a--}function u5(o,n,e,t,r,i,s,a,l,d,c){if(n[e]!==i[s])return Number.MIN_SAFE_INTEGER;let u=1,p=!1;return s===e-t?u=o[e]===r[s]?7:5:Am(s,r,i)&&(s===0||!Am(s-1,r,i))?(u=o[e]===r[s]?7:5,p=!0):xm(i,s)&&(s===0||!xm(i,s-1))?u=5:(xm(i,s-1)||tE(i,s-1))&&(u=5,p=!0),u>1&&e===t&&(c[0]=!0),p||(p=Am(s,r,i)||xm(i,s-1)||tE(i,s-1)),e===t?s>l&&(u-=p?3:5):d?u+=p?2:0:u+=p?0:1,s+1===a&&(u-=p?3:5),u}function km(o,n){if(o.length===0||o.charCodeAt(0)!==47)return;let e=1;for(;e<o.length&&!yI(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 Dm(o,n){if(o.length===0||n<0||n>o.length)return;let e=n;for(;e>0&&!yI(o.charCodeAt(e-1));)e--;if(e>=o.length||o.charCodeAt(e)!==47)return;let t=e+1;for(;t<o.length&&!yI(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,n){return o.length===0||n.toLowerCase().startsWith(o.toLowerCase())?!0:o.length>1&&Em(o,n)!==null}function yI(o){return o===32||o===9||o===10||o===13}var Mm="rename";function pE(o){let n=/^\/rename(?:$|\s+([\s\S]*))/.exec(o);if(n)return(n[1]??"").trim()}var Om=class{constructor(n){this._hasHistory=n;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){let t=km(n.text,n.offset);if(!t)return[];if(!this._hasHistory(n.channel))return[];let r=t.typed;return Vs(r,Mm)?[{insertText:"/"+Mm+" ",rangeStart:t.rangeStart,rangeEnd:t.rangeEnd,attachment:{type:"simple",label:"/"+Mm,_meta:Mu({command:Mm,description:f(2062,null)})}}]:[]}};var CI=class extends x{constructor(e){super();this._context=e;this.name="rename";this.recordsLocalTurn=!0}tryHandle(e){let t=pE(e.text);if(t!==void 0)return{run:async()=>this._run(e.turnChannel,e.turnId,t),suggestedTitle:t}}_run(e,t,r){if(r.length===0)return;let s=(l=>de(l)&&!Re(l))(e)?e:void 0,a=de(e)?ce(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:F(),content:f(2423,null,r)}})}};Du.register(CI);function fE(o){if(!o.startsWith("!"))return;let n=o.slice(1).trim();return n.length>0?n:void 0}var gE=8e4,Lm=12e4,II="<<<COPILOT_SENTINEL_";function Nm(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 X?"powershell":"bash"}}function bI(o){return o==="powershell"?"":" "}function mE(o){let n=o.replace(/\r\n|\r/g,`
`);return/(?<!\\)\n/.test(n)}function hE(o){return ft||mE(o)}function p5(){return F().replace(/-/g,"")}function f5(o,n){return n==="powershell"?`Write-Output "${II}${o}_EXIT_$LASTEXITCODE>>>"`:`echo "${II}${o}_EXIT_$?>>>"`}function g5(o,n){let e=`${II}${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 Pi(o){let n=Sw(o).trim();return n.length>gE&&(n=n.substring(n.length-gE)),n}function Um(o,n,e,t,r){return t.supportsCommandDetection(o.terminalUri)?m5(o,n,e,t,r):h5(o,n,e,t,r)}function yE(o,n,e,t,r){n.createAltBufferPromise(o.terminalUri,t).then(()=>{e.info("[ShellCommand] Command entered alternate buffer"),r({status:"altBuffer",output:""})})}async function m5(o,n,e,t,r){let i=new G,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=Pi(u.output),g=u.exitCode??0;r.info(`[ShellCommand] Command completed (shell integration) with exit code ${g}`),d({status:"completed",exitCode:g,output:p})})),yE(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:Pi(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:Pi(u)})},e);i.add(U(()=>clearTimeout(c)))});try{await t.sendText(o.terminalUri,`${bI(o.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:hE(n)})}catch(a){throw i.dispose(),a}return s}async function h5(o,n,e,t,r){let i=p5(),s=f5(i,o.shellType),a=new G,d=(t.getContent(o.terminalUri)??"").length,c=new Promise(u=>{let p=!1,g=I=>{p||(p=!0,a.dispose(),u(I))},h=()=>{let I=t.getContent(o.terminalUri)??"",S=Math.min(d,I.length),C=I.substring(S),_=g5(C,i);if(_.found){let T=Pi(_.outputBeforeSentinel);r.info(`[ShellCommand] Command completed with exit code ${_.exitCode}`),g({status:"completed",exitCode:_.exitCode,output:T})}};a.add(t.onData(o.terminalUri,()=>{h()})),yE(o,t,r,a,g),a.add(t.onExit(o.terminalUri,I=>{r.info(`[ShellCommand] Shell exited unexpectedly with code ${I}`);let C=(t.getContent(o.terminalUri)??"").substring(d);g({status:"shellExited",exitCode:I,output:Pi(C)})})),a.add(t.onClaimChanged(o.terminalUri,I=>{I.kind==="session"&&!I.toolCallId&&(r.info("[ShellCommand] Continuing in background (claim narrowed)"),g({status:"background",output:""}))}));let y=setTimeout(()=>{r.warn(`[ShellCommand] Command timed out after ${e}ms`);let S=(t.getContent(o.terminalUri)??"").substring(d);g({status:"timeout",output:Pi(S)})},e);a.add(U(()=>clearTimeout(y))),h()});try{await t.sendText(o.terminalUri,`${bI(o.shellType)}${n}`,{shouldExecute:!0,bracketedPasteMode:hE(n)}),await t.sendText(o.terminalUri,s,{shouldExecute:!0})}catch(u){throw a.dispose(),u}return c}var _I=class extends x{constructor(e){super();this._context=e;this.name="bang";this.recordsLocalTurn=!0;this._terminals=new Set;this._register(U(()=>{for(let t of this._terminals)this._context.terminalManager.disposeTerminal(t);this._terminals.clear()}))}tryHandle(e){let t=fE(e.text);if(t!==void 0)return{run:()=>this._run(e.turnChannel,e.turnId,t),suggestedTitle:t}}async _run(e,t,r){let i=this._context,s=de(e)?ce(e):e,a=F(),l=`agenthost-terminal://bang/${F()}`,d=f(2421,null),c=!1;try{let u=i.getState(s)?.workingDirectories?.[0],p=u?v.parse(u).fsPath:void 0,g=await i.terminalManager.getDefaultShell(),h=Nm(g);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},I={channel:l,claim:y,name:d,cwd:p};await i.terminalManager.createTerminal(I,{shell:g,preventShellHistory:!0,nonInteractive:!0}),c=!0,this._terminals.add(l);let S={type:"terminal",resource:l,title:d};i.dispatch(e,{type:"chat/toolCallContentChanged",turnId:t,toolCallId:a,content:[S]});let C=await Um({terminalUri:l,shellType:h},r,Lm,i.terminalManager,i.logService),{success:_,pastTenseMessage:T}=this._summarizeResult(C),w=[S];C.output&&w.push({type:"text",text:C.output}),i.dispatch(e,{type:"chat/toolCallComplete",turnId:t,toolCallId:a,result:{success:_,pastTenseMessage:T,content:w}})}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(2417,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(2419,null)}:{success:!1,pastTenseMessage:f(2416,null,t)}}case"timeout":return{success:!1,pastTenseMessage:f(2422,null)};case"shellExited":return{success:!1,pastTenseMessage:f(2420,null)};case"background":return{success:!0,pastTenseMessage:f(2415,null)};case"altBuffer":return{success:!0,pastTenseMessage:f(2418,null)}}}};Du.register(_I);import{realpath as F5}from"fs";import{homedir as AI}from"os";import{promisify as H5}from"util";var Fl="**",vE="/",Fm="[/\\\\]",Hm="[^/\\\\]",y5=/\//g;function SE(o,n){switch(o){case 0:return"";case 1:return`${Hm}*?`;default:return`(?:${Fm}|${Hm}+${Fm}${n?`|${Fm}${Hm}+`:""})*?`}}function CE(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 wE(o){if(!o)return"";let n="",e=CE(o,vE);if(e.every(t=>t===Fl))n=".*";else{let t=!1;e.forEach((r,i)=>{if(r===Fl){if(t)return;n+=SE(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===vE?u="":u=Un(c),d+=u;continue}switch(c){case"{":s=!0;continue;case"[":l=!0;continue;case"}":{let p=`(?:${CE(a,",").map(g=>wE(g)).join("|")})`;n+=p,s=!1,a="";break}case"]":{n+="["+d+"]",l=!1,d="";break}case"?":n+=Hm;continue;case"*":n+=SE(1);continue;default:n+=Un(c)}}i<e.length-1&&(e[i+1]!==Fl||i+2<e.length)&&(n+=Fm)}t=r===Fl})}return n}var v5=/^\*\*\/\*\.[\w\.-]+$/,S5=/^\*\*\/([\w\.-]+)\/?$/,C5=/^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/,I5=/^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/,b5=/^\*\*((\/[\w\.-]+)+)\/?$/,_5=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,IE=new bn(1e4),bE=function(){return!1},Yr=function(){return null};function wI(o,n){if(!o)return Yr;let e;typeof o!="string"?e=o.pattern:e=o,e=e.trim();let t=n.ignoreCase??!1,r={...n,equals:t?So:(l,d)=>l===d,endsWith:t?mw:(l,d)=>l.endsWith(d),isEqualOrParent:(l,d)=>Co(l,d,n.ignoreCase??!Fe)},i=`${t?e.toLowerCase():e}_${!!n.trimForExclusions}_${t}`,s=IE.get(i);if(s)return _E(s,o,r);let a;return v5.test(e)?s=T5(e.substring(4),e,r):(a=S5.exec(TI(e,r)))?s=w5(a[1],e,r):(n.trimForExclusions?I5:C5).test(e)?s=R5(e,r):(a=b5.exec(TI(e,r)))?s=TE(a[1].substring(1),e,!0,r):(a=_5.exec(TI(e,r)))?s=TE(a[1],e,!1,r):s=x5(e,r),IE.set(i,s),_E(s,o,r)}function _E(o,n,e){if(typeof n=="string")return o;let t=function(r,i){return e.isEqualOrParent(r,n.base)?o(eS(r.substring(n.base.length),He),i):null};return t.allBasenames=o.allBasenames,t.allPaths=o.allPaths,t.basenames=o.basenames,t.patterns=o.patterns,t}function TI(o,n){return n.trimForExclusions&&o.endsWith("/**")?o.substring(0,o.length-2):o}function T5(o,n,e){return function(t,r){return typeof t=="string"&&e.endsWith(t,o)?n:null}}function w5(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 R5(o,n){let e=RE(o.slice(1,-1).split(",").map(a=>wI(a,n)).filter(a=>a!==Yr),o),t=e.length;if(!t)return Yr;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 TE(o,n,e,t){let r=He===ie.sep,i=r?o:o.replace(y5,He),s=He+i,a=ie.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 x5(o,n){try{let e=new RegExp(`^${wE(o)}$`,n.ignoreCase?"i":void 0);return function(t){return e.lastIndex=0,typeof t=="string"&&e.test(t)?o:null}}catch{return Yr}}function $m(o,n,e){return!o||typeof n!="string"?!1:js(o,e)(n)}function js(o,n={}){if(!o)return bE;if(typeof o=="string"||A5(o)){let e=wI(o,n);if(e===Yr)return bE;let t=function(r,i){return!!e(r,i)};return e.allBasenames&&(t.allBasenames=e.allBasenames),e.allPaths&&(t.allPaths=e.allPaths),t}return P5(o,n)}function A5(o){let n=o;return n?typeof n.base=="string"&&typeof n.pattern=="string":!1}function P5(o,n){let e=RE(Object.getOwnPropertyNames(o).map(a=>E5(a,o[a],n)).filter(a=>a!==Yr)),t=e.length;if(!t)return Yr;if(!e.some(a=>!!a.requiresSiblings)){if(t===1)return e[0];let a=function(c,u){let p;for(let g=0,h=e.length;g<h;g++){let y=e[g](c,u);if(typeof y=="string")return y;mf(y)&&(p||(p=[]),p.push(y))}return p?(async()=>{for(let g of p){let h=await g;if(typeof h=="string")return h}return null})():null},l=e.find(c=>!!c.allBasenames);l&&(a.allBasenames=l.allBasenames);let d=e.reduce((c,u)=>u.allPaths?c.concat(u.allPaths):c,[]);return d.length&&(a.allPaths=d),a}let r=function(a,l,d){let c,u;for(let p=0,g=e.length;p<g;p++){let h=e[p];h.requiresSiblings&&d&&(l||(l=ue(a)),c||(c=l.substring(0,l.length-cs(a).length)));let y=h(a,l,c,d);if(typeof y=="string")return y;mf(y)&&(u||(u=[]),u.push(y))}return u?(async()=>{for(let p of u){let g=await p;if(typeof g=="string")return g}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 E5(o,n,e){if(n===!1)return Yr;let t=wI(o,e);if(t===Yr)return Yr;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 mf(u)?u.then(p=>p?o:null):u?o:null};return i.requiresSiblings=!0,i}}return t}function RE(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 RI(o,n){return Nn(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 xE(o,n){return o.replace(/^~($|\/|\\)/,`${n}$1`)}import*as EE from"fs";function AE(){return!!process.versions.electron&&!!ln.commit&&!process.env.VSCODE_DEV}function Lu(){return AE()?Mw:sf}function PE(){return AE()?"node_modules.asar.unpacked":"node_modules"}var k5=new Set(["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"]);function D5(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:k5.has(n))}function M5(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(D5(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 xI=/(?!.*)/,O5=/^[A-Z_][A-Z0-9_]*=/i,Wm=class extends x{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(O5.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=M5(l.node.text);d.kind==="unsafeWrite"&&a.push(d.dest)}else l.name==="heredoc_redirect"||l.name;return r.delete(),s.length>0||a.length>0?{subCommands:s,unsafeWriteDests:a}:void 0}finally{t.delete()}}catch(t){this._logService.warn("[CommandAutoApprover] Tree-sitter parsing failed",t);return}}async _initTreeSitter(){try{let{default:e}=await import("@vscode/tree-sitter-wasm");if(this._store.isDisposed)return;let t=v.joinPath(Nt.asFileUri(Lu()),"@vscode","tree-sitter-wasm","wasm"),r=v.joinPath(t,"tree-sitter.wasm").fsPath;if(await e.Parser.init({locateFile(){return r}}),this._store.isDisposed)return;let i=new e.Parser;this._register(U(()=>{try{i.delete()}catch{}}));let s=v.joinPath(t,"tree-sitter-bash.wasm").fsPath,a=await EE.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(N5)),this._fallbackRules)}_compileRuleEntries(e){let t=[],r=[],i=[],s=[];for(let[a,l]of Object.entries(e)){let d=L5(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 L5(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 fw(i)?xI:i}catch{return xI}}if(o==="")return xI;let t;if(o.includes("/")||o.includes("\\")){let r=o.replace(/[/\\]/g,"%%PATH_SEP%%");r=Un(r),r=r.replace(/%%PATH_SEP%%*/g,"[/\\\\]"),t=`^(?:\\.[/\\\\])?${r}`}else t=Un(o);return new RegExp(`^${t}\\b`)}var N5={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 DE="allow-session",$5=[{id:DE,label:f(2425,null),kind:"approve",group:1},{id:"allow-once",label:f(2424,null),kind:"approve"},{id:"skip",label:f(2426,null),kind:"deny",group:2}],W5={"**/*":!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,"**/.github/agents/**":!1,"**/.github/hooks/**":!1,"**/.claude/agents/**":!1,"**/.claude/settings.json":!1,"**/.claude/settings.local.json":!1},kE=v.file(AI()),q5=(X?[process.env.APPDATA,process.env.LOCALAPPDATA]:ft?[AI()+"/Library"]:[]).filter(Mr),B5=H5(F5);function z5(o,n=X){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 V5(o,n){let e=o.fsPath;try{return v.file(await n(e))}catch(i){if(i.code!=="ENOENT")throw i}let t=[ue(e)],r=te(e);for(;;){let i=te(r);if(i===r)return o;try{let s=await n(r);return v.file(V(s,...t))}catch(s){let a=s.code;if(a!=="ENOENT"&&a!=="ENOTDIR")throw s}t.unshift(ue(r)),r=i}}var Hl=class extends x{constructor(e,t,r,i){super();this._stateManager=e;this._configService=r;this._logService=i;this._realpath=t?.realpath??B5,this._commandAutoApprover=this._register(new Wm(this._logService))}initialize(){return this._commandAutoApprover.initialize()}async getAutoApproval(e,t){let r=this._configService.getEffectiveWorkingDirectory(t),i=r?v.parse(r):void 0;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 await this._isReadAutoApproved(v.file(e.permissionPath),i)?(this._logService.trace(`[SessionPermissionManager] Auto-approving read of ${e.permissionPath}`),"not-needed"):void 0;if(e.permissionKind==="write"&&e.permissionPath)return await this._isEditAutoApproved(v.file(e.permissionPath),i)?(this._logService.trace(`[SessionPermissionManager] Auto-approving write to ${e.permissionPath}`),"not-needed"):void 0;if(e.permissionKind==="shell"&&e.toolInput){if(this._configService.getRootValue(tt,DS)===!1)return;let s=this._commandAutoApprover.shouldAutoApprove(e.toolInput,{autoApproveRules:this._configService.getRootValue(tt,NS),isWriteDestApproved:a=>this._isShellWriteDestApproved(a,i)});if(s==="approved")return this._logService.trace("[SessionPermissionManager] Auto-approving shell command"),"not-needed";s==="denied"&&this._logService.trace("[SessionPermissionManager] Shell command denied by rule");return}}}isGlobalAutoApproveEnabled(){return this._configService.getRootValue(tt,Ya)===!0}getEffectiveApprovalLevel(e){return this._configService.getEffectiveValue(e,Pt,"autoApprove")??"default"}isSessionAutoApproveEnabled(e){return this.getEffectiveApprovalLevel(e)==="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,riskAssessment:i.riskAssessment,edits:i.edits,editable:i.editable,...i._meta?{_meta:i._meta}:{},options:i.options?i.options.slice():$5.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=ce(e);if(r===DE){let s=this._getToolNameForToolCall(e,t);s&&this._addToolToSessionPermissions(i,s)}}async _isReadAutoApproved(e,t){if(!t)return!1;let[r,i]=await Promise.all([this._resolveResourcesForApproval(e),this._resolveResourcesForApproval(t)]);return r!==void 0&&i!==void 0&&r.every(s=>i.some(a=>this._isResourceInDirectory(s,a)))}_isResourceInWorkingDirectory(e,t){return t!==void 0&&this._isResourceInDirectory(e,t)}_isResourceInDirectory(e,t){return re.isEqualOrParent(rn(e),rn(t))}_isShellWriteDestApproved(e,t){let r=this._resolveShellRedirectResource(e,t);return r?this._checkWriteResource(r,t):!1}_resolveShellRedirectResource(e,t){let r=xE(e.trim(),AI());if(r){if(nn(r))return v.file(r);if(t)return v.file(Xn(t.fsPath,r))}}async _isEditAutoApproved(e,t){let r=await this._resolveResourcesForApproval(e);return r!==void 0&&r.every(i=>this._checkWriteResource(i,t))}async _resolveResourcesForApproval(e){let t=[e];if(e.scheme!==ne.file)return t;try{let r=await V5(e,this._realpath);re.isEqual(r,e)||t.push(r)}catch(r){let i=r.code;if(i==="EPERM"||i==="EACCES")return}return t}_checkWriteResource(e,t){try{z5(e.fsPath)}catch{return!1}return!this._isResourceInWorkingDirectory(e,t)||this._isPlatformRestrictedResource(e,t)?!1:this._matchesEditAutoApprovePatterns(e.fsPath)}_isPlatformRestrictedResource(e,t){let i=re.relativePath(kE,e)?.split("/")[0];if(re.isEqualOrParent(e,kE)&&i?.startsWith("."))return!0;for(let s of q5){let a=v.file(s);if(re.isEqualOrParent(e,a))return!(t&&re.isEqualOrParent(t,a))}return!1}_matchesEditAutoApprovePatterns(e){let t=!0;for(let[r,i]of Object.entries(W5))i!==t&&$m(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,Pt,"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,Pt,"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}`))}};Hl=A([b(2,Ue),b(3,O)],Hl);import{CAPIClient as G5,RequestType as Nu}from"@vscode/copilot-api";var j5="https://api.githubcopilot.com",qm={apiBaseUri:"https://api.github.com",graphQlUri:"https://api.github.com/graphql",oauthServer:"https://github.com/login/oauth",enterpriseHost:void 0};function ME(o){if(!o)return qm;let n;try{n=v.parse(o)}catch{return qm}let e=n.authority;if(!e||e==="github.com"||e==="www.github.com"||e==="api.github.com")return qm;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 PI(o){try{let n=v.parse(o??j5,!0);return n.authority?n.with({path:"/mcp",query:null,fragment:null}).toString(!0):void 0}catch{return}}function OE(o){return{resource:o.apiBaseUri,resource_name:"GitHub Copilot",authorization_servers:[o.oauthServer],scopes_supported:["read:user","user:email"],required:!0}}function LE(o){return{resource:`${o.apiBaseUri}/repos`,resource_name:"GitHub Repository",authorization_servers:[o.oauthServer],scopes_supported:["repo"],required:!1}}var wt=B("agentHostGitHubEndpointService"),$l=class extends x{constructor(e,t){super();this._configurationService=e;this._logService=t;this._onDidChange=this._register(new E);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(Dn,"githubEnterpriseUri");return{endpoints:ME(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 OE(this._endpoints)}getRepoResource(){return LE(this._endpoints)}};$l=A([b(0,Ue),b(1,O)],$l);var EI="code-oss";function NE(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 Uu=520,J5=300,UE=1800,FE="2025-04-01",Y5="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE",Q5="vscode-smoke.test",X5="VSCODE_SMOKE_TEST_PROXY_HEADER";function Z5(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)}function eH(o){if(Z5(o))return!0;if(!process.env[X5])return!1;try{return new URL(o).hostname.toLowerCase()===Q5}catch{return!1}}var tH=300,nH="gpt-4o-mini",rH=.1,oH=1,iH="conversation-background",sH=new Set(["4535c7beffc844b46bb1ed4aa04d759a","a5db0bcaae94032fe715fb34a5e4bce2","7184f66dfcee98cb5f08a1cb936d5225","1cb18ac6eedd49b43d74a1c5beb0b955","ea9395b9a9248c05ee6847cbd24355ed"]),aH=new Set(["551cca60ce19654d894e786220822482"]),wr=class extends Error{constructor(e,t,r){super(r??t.error.message);this.status=e;this.envelope=t;this.name="CopilotApiError"}};function Bm(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 wr(o,r,`${t}: ${o} ${n} \u2014 ${r.error.message}`)}var gt=B("copilotApiService"),Ei=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:Nu.Models});if(!r.ok){(r.status===401||r.status===403)&&this._invalidateClientForToken(n);let s=await r.text().catch(()=>"");throw Bm(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=F(),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:Nu.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 Bm(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,nH),a=F();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??rH,top_p:oH}),d=await r.makeRequest({method:"POST",headers:{...t?.headers,"Content-Type":"application/json",Authorization:`Bearer ${i}`,"X-Request-Id":a,"OpenAI-Intent":iH},body:l,signal:t?.signal},{type:Nu.ChatCompletions});if(!d.ok){(d.status===401||d.status===403)&&this._invalidateCopilotTokenForGithub(n);let p=await d.text().catch(()=>"");throw Bm(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([Qg(i=>this._logService.warn("[CopilotApiService] getMachineId failed",i)),Xg(i=>this._logService.warn("[CopilotApiService] getDevDeviceId failed",i))]),t={name:"agent-host",sessionId:F(),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=F();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:Nu.ChatMessages});if(!c.ok){(c.status===401||c.status===403)&&this._invalidateClientForToken(n);let u=await c.text().catch(()=>"");throw Bm(c.status,c.statusText,u)}return c}_getClientForToken(n){return this._getEntryForToken(n).then(e=>e.capiClient)}async resolveRestrictedTelemetryContext(n){let e=await this._getCopilotTokenEntry(n),t=await this._getEntryForToken(n),r=NE(e.token),i=r.get("rt")==="1",s=r.get("tid"),a=i?t.telemetryEndpoint:void 0;return{restrictedTelemetryEnabled:i,trackingId:s,telemetryEndpoint:a,isInternal:e.isInternal,userName:t.login,isVscodeTeamMember:e.isVscodeTeamMember,copilotIgnoreEnabled:t.copilotIgnoreEnabled}}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>J5?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 G5(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[Y5];if(s){if(eH(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+UE,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":FE}});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+UE,login:l.login,telemetryEndpoint:l.endpoints?.telemetry,apiEndpoint:l.endpoints?.api,copilotIgnoreEnabled:l.copilotignore_enabled}}_getCopilotToken(n){return this._getCopilotTokenEntry(n).then(e=>e.token)}_getCopilotTokenEntry(n){let e=Date.now()/1e3,t=this._copilotTokensByGithub.get(n);if(t)return t.then(i=>i.expiresAt-e>tH?i:(this._copilotTokensByGithub.get(n)===t&&this._copilotTokensByGithub.delete(n),this._getCopilotTokenEntry(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}_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":FE}},{type:Nu.CopilotToken});if(!t.ok){let d=await t.text().catch(()=>"");throw new Error(`Copilot session token mint failed: ${t.status} ${t.statusText} \u2014 ${d}`)}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=Array.isArray(r.organization_list)?r.organization_list.filter(d=>typeof d=="string"):[],l=Math.max(s!==void 0?i+s:r.expires_at,i+60);return{token:r.token,expiresAt:l,modelIdsByFamily:new Map,isInternal:a.some(d=>sH.has(d)),isVscodeTeamMember:a.some(d=>aH.has(d))}}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 wr(Uu,a)}if(lH.has(i))return t}}};Ei=A([b(1,O),b(2,Tt),b(3,wt)],Ei);var lH=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);var zm="VSCODE_PROXY_ERROR:",dH=8*1024,cH=/^[A-Za-z0-9+/]+={0,2}$/;function HE(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 Vm(o){let n=o.status===Uu?502:o.status,e=typeof o.envelope.request_id=="string"?o.envelope.request_id:"",t=uH(o.envelope.error.message)??{code:o.envelope.error.type,message:o.envelope.error.message};return{fetchError:{type:HE(n),reason:t.message??o.envelope.error.message,requestId:e,capiError:t}}}function uH(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 jm(o){return`${zm}${Buffer.from(JSON.stringify(o)).toString("base64")}`}function pH(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?HE(n):void 0}function fH(o){let n=pH(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 Km(o){if(!o)return;let n=o.indexOf(zm);if(n===-1)return;let e=n+zm.length,t=o.slice(e).search(/[\s"']/),r=t===-1?o.slice(e):o.slice(e,e+t);if(!(r.length===0||r.length>dH||!cH.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 Fu(o){let n=o.indexOf(zm);return n===-1?o:o.slice(0,n).trim()||o.slice(0,n)}function Hu(o){return{chatError:o}}function $E(o){let n=Km(o);return n?Hu(n):void 0}function WE(o){let n=fH(o);return n?Hu(n):void 0}function Wl(o){let n=Km(o);return n?{message:Fu(o),_meta:Hu(n)}:{message:o}}var ql=class extends x{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 ha;this._cancelledTurnIds=new Map;this._pendingSubagentSignals=new ha;this._queuedMessageSenders=new ha;this._telemetryReporter=new _l(this._telemetryService),this._turnTracker=new Tm(this._telemetryReporter),this._toolCallTracker=this._register(new Yg(this._telemetryReporter)),this._permissionManager=this._register(r.createInstance(Hl,this._stateManager,{})),this._localCommands=this._register(r.createInstance(Ll,this._stateManager,this._options.localTurns,d=>this._tryConsumeNextQueuedMessage(d))),this._titleController=this._register(r.createInstance(bl,this._stateManager,{sessionDataService:this._options.sessionDataService,getGitHubCopilotToken:this._options.getGitHubCopilotToken,copilotApiService:this._options.copilotApiService})),this._register(En(d=>{let c=this._options.agents.read(d);this._publishAgentInfos(c,d)})),this._register(this._stateManager.onDidEmitEnvelope(d=>{if(de(d.channel)&&Tr(d.action)){if(d.action.type==="chat/turnCancelled"){let c=this._cancelledTurnIds.get(d.channel);c||(c=new Set,this._cancelledTurnIds.set(d.channel,c)),c.add(d.action.turnId)}this._syncSessionInputNeededForChatAction(d.channel,d.action)}if(!d.origin&&d.action.type==="chat/toolCallComplete"){let c=d.action;if(!de(d.channel))return;let u=ce(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}});Oe(this._lastAgentInfos,r)||(this._lastAgentInfos=r,this._stateManager.dispatchServerAction(Je,{type:"root/agentsChanged",agents:r}))}async _publishSessionCustomizations(e,t){if(!e.getSessionCustomizations)return;let r=await e.getSessionCustomizations(v.parse(t)),i=this._stateManager.getSessionState(t)?.customizations;i&&Oe(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._syncChatInputNeeded(e,t.request.id);break;case"chat/inputAnswerChanged":this._syncChatInputNeeded(e,t.requestId);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":case"chat/toolCallAuthRequired":case"chat/toolCallAuthResolved":this._syncToolInputNeeded(e,t.turnId,t.toolCallId);break;case"chat/turnComplete":case"chat/turnCancelled":case"chat/error":case"chat/truncated":this._removeSessionInputNeededForChat(e);break}}_syncChatInputNeeded(e,t){let i=this._stateManager.getSessionState(e)?.activeTurn?.responseParts.find(a=>a.kind==="inputRequest"&&a.response===void 0&&a.request.id===t),s=this._chatInputNeededId(e,t);if(!i||i.kind!=="inputRequest"){this._removeSessionInputNeeded(e,s);return}this._setSessionInputNeeded(e,{id:s,kind:"chatInput",chat:e,request:i.request})}_syncToolInputNeeded(e,t,r){let i=this._toolConfirmationNeededId(e,t,r),s=this._toolClientExecutionNeededId(e,t,r),a=this._toolAuthenticationNeededId(e,t,r),l=this._findToolCall(e,t,r),d=!!l&&An(l).autoApproveBySetting===!0;!(d&&l?.status==="pending-confirmation")&&(l?.status==="pending-confirmation"||l?.status==="pending-result-confirmation")&&l?this._setSessionInputNeeded(e,{id:i,kind:"toolConfirmation",chat:e,turnId:t,toolCall:l}):this._removeSessionInputNeeded(e,i);let p=l?.contributor;!d&&l?.status==="running"&&p?.kind==="client"?this._setSessionInputNeeded(e,{id:s,kind:"toolClientExecution",chat:e,turnId:t,clientId:p.clientId,toolCall:l}):this._removeSessionInputNeeded(e,s),l?.status==="auth-required"?this._setSessionInputNeeded(e,{id:a,kind:"toolAuthentication",chat:e,turnId:t,toolCall:l}):this._removeSessionInputNeeded(e,a)}_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=ce(e),i=this._stateManager.getSessionState(r)?.inputNeeded?.find(s=>s.id===t.id);if(!(i&&Oe(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=ce(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=ce(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}`}_toolAuthenticationNeededId(e,t,r){return`toolAuthentication:${e}:${t}:${r}`}initialize(){return this._permissionManager.initialize()}registerProgressListener(e){let t=new G;return t.add(e.onDidSessionProgress(r=>{this._handleAgentSignal(e,r)})),e.onDidCustomizationsChange&&t.add(e.onDidCustomizationsChange(()=>{this._publishAgentInfos(this._options.agents.get()),this._publishSessionCustomizationsForAgent(e)})),e.onDidRequireAuth&&t.add(e.onDidRequireAuth(r=>this._stateManager.emitAuthRequired(r))),t}_handleAgentSignal(e,t){if(t.kind==="subagent_started"){this._handleSubagentStarted(t.chat.toString(),t.toolCallId,t.agentName,t.agentDisplayName,t.agentDescription,t.taskPrompt,t.parentToolCallId),this._drainPendingSubagentSignals(t.chat.toString(),t.toolCallId);return}if(t.kind==="subagent_resumed"){this._resumeSubagentSession(t.chat.toString(),t.toolCallId,t.message);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 c=this._stateManager.getActiveTurnId(a.chatUri);c?this._dispatchActionForSession(t,a.chatUri,c,"remap",e):(this._logService.error(`[AgentSideEffects] Dropping ${this._describeSignal(t)} for inactive subagent ${r}/${i}`),t.kind==="pending_confirmation"&&e.respondToPermissionRequest(t.state.toolCallId,!1));return}let l=this._pendingSubagentSignals.get(r,i);if(t.kind==="pending_confirmation"&&!l){this._logService.error(`[AgentSideEffects] Denying permission for unroutable subagent ${r}/${i}: toolCallId=${t.state.toolCallId}`),e.respondToPermissionRequest(t.state.toolCallId,!1);return}this._logService.trace(`[AgentSideEffects] Buffering ${this._describeSignal(t)} for pending subagent ${r}/${i}`);let d=l;d||(d=[],this._pendingSubagentSignals.set(d,r,i)),d.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,"preserve",e);return}if(t.kind==="pending_confirmation"){this._handleToolReady(t,r,"",e).catch(a=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",a)});return}if(t.kind==="action"){let a=t.action;if(a.type==="chat/turnComplete"&&this._cancelledTurnIds.get(r)?.has(a.turnId)){this._logService.trace(`[AgentSideEffects] Dropping completion for cancelled turn ${a.turnId} on ${r}`);return}this._stateManager.dispatchServerAction(r,a),a.type==="chat/turnComplete"&&this._runTurnCompleteSideEffects(r,void 0)}}_dispatchActionForSession(e,t,r,i,s){if(e.kind==="pending_confirmation"){s&&this._handleToolReady(e,t,r,s).catch(d=>{this._logService.error("[AgentSideEffects] _handleToolReady failed",d)});return}if(e.kind!=="action")return;let a=e.action;if(a.type!=="chat/truncated"&&he(a,{turnId:!0})&&a.turnId!==r)if(i==="remap")a={...a,turnId:r};else{this._logService.trace(`[AgentSideEffects] Dropping stale ${a.type} for ${t}: producerTurnId=${a.turnId}, activeTurnId=${r}`);return}a.type==="chat/toolCallStart"&&s&&(this._toolCallAgents.set(`${t}:${a.toolCallId}`,s.id),this._toolCallTracker.toolCallStarted(s.id,t,a.toolCallId,a.toolName,a.contributor));let l=de(t)?ce(t):t;if((a.type==="chat/toolCallStart"||a.type==="chat/toolCallDelta"||a.type==="chat/toolCallReady")&&An(a).toolKind==="subagent"&&An(a).subagentChatUri===void 0&&(a={...a,_meta:{...a._meta,subagentChatUri:_s(l,a.toolCallId)}}),a.type==="chat/toolCallComplete"&&this._subagentChats.get(t,a.toolCallId)){let c=this._stateManager.getSessionState(t),p=this._getRunningToolCallContent(c,r,a.toolCallId).find(g=>he(g,{type:!0})&&g.type==="subagent");if(p){let g=[...a.result.content??[],p];a={...a,result:{...a.result,content:g}}}}this._stateManager.dispatchServerAction(t,a),(a.type==="chat/delta"||a.type==="chat/responsePart"||a.type==="chat/toolCallStart"||a.type==="chat/reasoning")&&this._turnTracker.markFirstProgress(t,r),a.type==="chat/toolCallComplete"&&(this._toolCallTracker.toolCallCompleted(t,a.toolCallId,a.result),this._pendingSubagentSignals.delete(t,a.toolCallId),AR(a.result).length>0&&this._changesets.onToolCallEditsApplied(l,r)),a.type==="chat/turnComplete"&&(this._turnTracker.turnCompleted(t,r,"success"),this._toolCallTracker.clearSession(t),this._runTurnCompleteSideEffects(t,r)),a.type==="chat/turnCancelled"&&(this._turnTracker.turnCompleted(t,r,"cancelled"),this._toolCallTracker.clearSession(t),this._markSessionUnread(l)),a.type==="chat/error"&&(this._turnTracker.turnCompleted(t,r,"error",{stage:"provider",error:a.error}),this._toolCallTracker.clearSession(t),this._markSessionUnread(l))}_runTurnCompleteSideEffects(e,t){let r=de(e)?ce(e):e;t!==void 0?this._checkpointService.captureTurnCheckpoint(v.parse(r),t).then(()=>{this._changesets.onTurnComplete(r,t)},s=>{this._logService.warn(`[AgentSideEffects] Turn checkpoint capture failed for ${r}/${t}: ${s instanceof Error?s.message:String(s)}`),this._changesets.onTurnComplete(r,t)}):this._changesets.onTurnComplete(r,t),this._tryConsumeNextQueuedMessage(e),this._options.onTurnComplete(r);let i=de(e)&&!Re(e)?e:void 0;this._titleController.refineTitleFromFirstTurn(r,i),this._markSessionUnread(r)}_markSessionUnread(e){(this._stateManager.getSessionSummary(e)?.status??0)&32&&(this._stateManager.dispatchServerAction(e,{type:"session/isReadChanged",isRead:!1}),this._persistSessionFlag(e,"isRead",""))}_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,l){let d=ce(e),c=_s(d,t);if(this._subagentChats.get(e,t)){this._resumeSubagentSession(e,t,a?{text:a,origin:{kind:"user"}}:void 0);return}this._logService.info(`[AgentSideEffects] Starting subagent turn: ${c} (parent=${e}, toolCallId=${t})`);let p=l?this._subagentChats.get(e,l)?.chatUri??e:e,g=F();this._stateManager.dispatchServerAction(c,{type:"chat/turnStarted",turnId:g,startedAt:new Date().toISOString(),message:{text:a??"",origin:{kind:"user"}}}),this._subagentChats.set({parentChatUri:e,toolCallId:t,sessionUri:d,chatUri:c,turnStopWatch:lt.create(!1)},e,t);let h=this._stateManager.getActiveTurnId(p);if(h){let y=this._stateManager.getSessionState(p),I=this._getRunningToolCallContent(y,h,t);this._stateManager.dispatchServerAction(p,{type:"chat/toolCallContentChanged",turnId:h,toolCallId:t,content:[...I,{type:"subagent",resource:c,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[]}_turnDuration(e){let t=e?.elapsed();return typeof t=="number"&&Number.isFinite(t)?Math.max(0,t):0}_resumeSubagentSession(e,t,r){let i=this._subagentChats.get(e,t);if(!i){this._logService.error(`[AgentSideEffects] Cannot resume unknown subagent ${e}/${t}`);return}if(this._stateManager.getActiveTurnId(i.chatUri))return;let s=F();this._logService.info(`[AgentSideEffects] Resuming subagent turn: ${i.chatUri} (parent=${e}, toolCallId=${t})`),this._stateManager.dispatchServerAction(i.chatUri,{type:"chat/turnStarted",turnId:s,startedAt:new Date().toISOString(),message:r??{text:"",origin:{kind:"user"}}}),this._subagentChats.set({...i,turnStopWatch:lt.create(!1)},e,t)}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,duration:this._turnDuration(t.turnStopWatch)}),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,duration:this._turnDuration(r.turnStopWatch)})}removeSubagentSessions(e){for(let r of this._cancelledTurnIds.keys())ce(r)===e&&this._cancelledTurnIds.delete(r);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(!bs(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(v.parse(e),v.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(g=>g.kind==="toolCall"&&g.toolCall.toolCallId===e.state.toolCallId),d=l?.kind==="toolCall"?l.toolCall:void 0;if(d&&d.status!=="streaming"&&d.status!=="running"&&d.status!=="pending-confirmation"){this._toolCallAgents.delete(`${t}:${e.state.toolCallId}`),this._logService.trace(`[AgentSideEffects] Dropping stale tool ready for ${e.state.toolCallId}: status=${d.status}`);return}let 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,...At({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,i="unknown"){let s=de(e)?e:void 0,a=s?ce(s):e;switch(t.type){case"chat/turnStarted":{if(!s)throw new Error(`ChatTurnStarted must be handled on an AHP chat channel: ${e}`);let l=lt.create(!1),d=this._localCommands.tryHandle({turnChannel:e,turnId:t.turnId,text:t.message.text});if(d){d.suggestedTitle!==void 0&&this._titleController.seedProvisionalTitle(a,d.suggestedTitle,s);break}let c=this._stateManager.getSessionState(e);c||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(a,t.message.text,s);let u=this._options.getAgent(a);if(!u){this._stateManager.dispatchServerAction(e,{type:"chat/error",turnId:t.turnId,duration:this._turnDuration(l),error:{errorType:"noAgent",message:"No agent found for session"}});return}let p=t.message.attachments;this._telemetryReporter.userMessageSent(u.id,i,e,c,"direct",p);let{model:g,modelTelemetryKind:h,permissionLevel:y}=this._getTurnTelemetryContext(u,c,t.message.model?.id);this._turnTracker.turnStarted(u.id,e,t.turnId,g,h,y),this._sendTurnMessage({agent:u,sessionChannel:a,turnChannel:e,chat:e,message:t.message,turnId:t.turnId,senderClientId:r,clientType:i,turnStopWatch:l});break}case"chat/toolCallConfirmed":{if(!s)throw new Error(`ChatToolCallConfirmed must be handled on an AHP chat channel: ${e}`);let l=`${e}:${t.toolCallId}`,d=this._toolCallAgents.get(l);d?(this._toolCallAgents.delete(l),this._options.agents.get().find(u=>u.id===d)?.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(!s)throw new Error(`ChatInputCompleted must be handled on an AHP chat channel: ${e}`);this._options.getAgent(a)?.respondToUserInputRequest(t.requestId,t.response,t.answers);break}case"chat/turnCancelled":{if(!s)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 l=this._options.getAgent(a);if(l){let d=v.parse(e);l.chats.abort(d).catch(c=>{this._logService.error("[AgentSideEffects] abort failed",c)})}break}case"session/titleChanged":{if(s){this._stateManager.updateChatTitle(a,s,t.title),this._persistSessionFlag(a,`customChatTitle:${s}`,t.title);break}this._persistSessionFlag(e,"customTitle",t.title);break}case"chat/pendingMessageSet":{if(!s)throw new Error(`${t.type} must be handled on an AHP chat channel: ${e}`);let l=this._stateManager.getChatState(e)?.queuedMessages?.some(d=>d.id===t.id)===!0;t.kind==="queued"&&l&&this._queuedMessageSenders.set({clientId:r,clientType:i},e,t.id),this._syncPendingMessages(e);break}case"chat/pendingMessageRemoved":{if(!s)throw new Error(`${t.type} must be handled on an AHP chat channel: ${e}`);t.kind==="queued"&&this._queuedMessageSenders.delete(e,t.id),this._syncPendingMessages(e);break}case"chat/queuedMessagesReordered":{if(!s)throw new Error(`${t.type} must be handled on an AHP chat channel: ${e}`);this._syncPendingMessages(e);break}case"chat/truncated":{if(!s)throw new Error(`ChatTruncated must be handled on an AHP chat channel: ${e}`);let l=this._options.getAgent(a),d=t.turnId!==void 0?this._options.localTurns.resolveConcreteTurnId(s,t.turnId):t.turnId;l?.truncateSession?.(v.parse(a),d,v.parse(s)).catch(p=>{this._logService.error("[AgentSideEffects] truncateSession failed",p)});let c=new Set((this._stateManager.getChatState(s)?.turns??[]).map(p=>p.id)),u=this._options.localTurns.getLocalTurnIds(s).filter(p=>!c.has(p));this._options.localTurns.deleteLocals(a,u),this._changesets.onSessionTruncated(a);break}case"session/activeClientSet":{let l=this._options.getAgent(e);if(!l)break;let d=t.activeClient,c=l.getOrCreateActiveClient(v.parse(e),{clientId:d.clientId,displayName:d.displayName});c.tools=d.tools,c.customizations=d.customizations??[];break}case"session/activeClientRemoved":{this._options.getAgent(e)?.removeActiveClient(v.parse(e),t.clientId);break}case"root/configChanged":{bm(this._telemetryService,t.config),this._publishAgentInfos(this._options.agents.get()),this._publishAllSessionCustomizations();break}case"session/mcpServerStartRequested":{this._options.getAgent(a)?.startMcpServer?.(v.parse(a),t.id).catch(d=>{this._logService.warn(`[AgentSideEffects] startMcpServer failed for ${a}`,d)});break}case"session/mcpServerStopRequested":{this._options.getAgent(a)?.stopMcpServer?.(v.parse(a),t.id).catch(d=>{this._logService.warn(`[AgentSideEffects] stopMcpServer failed for ${a}`,d)});break}case"session/isReadChanged":{this._persistSessionFlag(e,"isRead",t.isRead?"true":"");break}case"session/isArchivedChanged":{if(this._persistSessionFlag(e,or,t.isArchived?"true":""),this._worktree){let d=v.parse(e),c=M.id(e);(t.isArchived?this._worktree.cleanupWorktreeOnArchive(d,c):this._worktree.recreateWorktreeOnUnarchive(d,c)).catch(p=>this._logService.warn(`[AgentSideEffects] worktree ${t.isArchived?"cleanup":"recreate"} failed for ${e}`,p))}this._options.getAgent(e)?.onArchivedChanged?.(v.parse(e),t.isArchived).catch(d=>{this._logService.warn(`[AgentSideEffects] onArchivedChanged failed for ${e}`,d)});break}case"session/configChanged":{let l=this._stateManager.getSessionState(e),d=l?.config?.values;if(d&&this._persistSessionFlag(e,"configValues",JSON.stringify(d)),this._worktree&&l?.lifecycle==="creating"){let c=M.id(e),u=d?.isolation;u==="worktree"?this._worktree.notePending(c):u==="folder"&&this._worktree.clearPending(c)}this._options.getAgent(e)?.onSessionConfigChanged?.(v.parse(e),d??{});break}case"chat/toolCallComplete":{if(!s)break;this._notifyClientToolCallComplete(a,s,t.toolCallId,t.result,"client-dispatch");break}}}setWorktreeIsolation(e){this._worktree=e}cancelSessionTitleGeneration(e){this._titleController.cancelTitleGeneration(e)}clearQueuedMessageSenders(e){this._queuedMessageSenders.deleteAll(e)}generateForkedTitle(e,t,r,i,s){this._titleController.generateForkedTitle(e,t,r,i,s)}_persistSessionFlag(e,t,r){wm(this._options.sessionDataService,this._logService,e,t,r)}_persistChatDraft(e,t){if(!de(e))return;let r=Le(e);if(!r)return;let i=v.parse(r.session),s=this._options.sessionDataService.openDatabase(i);s.object.setChatDraft(v.parse(e),t).catch(a=>{this._logService.warn(`[AgentSideEffects] Failed to persist chat draft for ${e.toString()}`,a)}).finally(()=>{s.dispose()})}_syncPendingMessages(e){let t=ce(e),r=this._stateManager.getSessionState(e);if(!r)return;this._options.getAgent(t)?.setPendingMessages?.(v.parse(e),r.steeringMessage,[]),this._tryConsumeNextQueuedMessage(e)}_tryConsumeNextQueuedMessage(e){let t=ce(e);if(this._stateManager.getActiveTurnId(e))return;let r=this._stateManager.getSessionState(e);if(!r?.queuedMessages?.length)return;let i=r.queuedMessages[0],s=this._queuedMessageSenders.get(e,i.id)??{clientId:void 0,clientType:"unknown"};this._queuedMessageSenders.delete(e,i.id);let a=F();this._stateManager.dispatchServerAction(e,{type:"chat/turnStarted",turnId:a,startedAt:new Date().toISOString(),message:i.message,queuedMessageId:i.id});let l=lt.create(!1),d=this._localCommands.tryHandle({turnChannel:e,turnId:a,text:i.message.text});if(d){d.suggestedTitle!==void 0&&this._titleController.seedProvisionalTitle(t,d.suggestedTitle,e);return}this._titleController.seedTitleFromFirstMessage(t,i.message.text,e);let c=this._options.getAgent(t);if(!c){this._stateManager.dispatchServerAction(e,{type:"chat/error",turnId:a,duration:this._turnDuration(l),error:{errorType:"noAgent",message:"No agent found for session"}});return}let u=i.message.attachments,p=this._stateManager.getSessionState(e);this._telemetryReporter.userMessageSent(c.id,s.clientType,e,p,"queued",u);let{model:g,modelTelemetryKind:h,permissionLevel:y}=this._getTurnTelemetryContext(c,p,i.message.model?.id);this._turnTracker.turnStarted(c.id,e,a,g,h,y),this._sendTurnMessage({agent:c,sessionChannel:t,turnChannel:e,chat:e,message:i.message,turnId:a,senderClientId:s.clientId,clientType:s.clientType,turnStopWatch:l})}_getTurnTelemetryContext(e,t,r){let i=t?.config?.values.autoApprove,s=typeof i=="string"?i:void 0,a=r===void 0?void 0:e.models.get().find(d=>d.id===r),l;return r==="auto"?l="trusted":r===void 0?l=void 0:a===void 0?l="unknown":l=fP(a)===void 0?"trusted":"byok",{model:r,modelTelemetryKind:l,permissionLevel:s}}async _sendTurnMessage(e){let{agent:t,sessionChannel:r,turnChannel:i,chat:s,message:a,turnId:l,senderClientId:d,clientType:c,turnStopWatch:u}=e,p=this._stateManager.getChatState(s),h=((this._stateManager.getSessionSummary(e.sessionChannel)?.status??0)&64)===64;if(LR(p?.interactivity,h)){let S=h?{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._logService.warn(`[AgentSideEffects] Rejecting turn on read-only chat=${s} (archived=${h}), turnId=${l}`),this._stateManager.dispatchServerAction(i,{type:"chat/error",turnId:l,duration:this._turnDuration(u),error:S}),this._turnTracker.turnCompleted(i,l,"error",{stage:"validation",error:S}),this._toolCallTracker.clearSession(i);return}let y=v.parse(s),I="workingDirectory";try{let S=await this._options.resolveWorkingDirectoryBeforeSend?.({session:e.sessionChannel,chat:s,turnId:l,prompt:a.text}),C=[];a.model&&(I="modelSelection",C.push(t.chats.changeModel(y,a.model))),C.push(t.chats.changeAgent(y,a.agent).catch(T=>{this._logService.error("[AgentSideEffects] changeAgent failed",T)})),await Promise.all(C),I="sendMessage";let _=await this._resolveChatAttachments(r,a.attachments);await t.chats.sendMessage(y,a.text,S,_,l,d,c)}catch(S){let C=gH(I,S),_=C.error;this._logService.error(`[AgentSideEffects] ${I} failed for session=${i}: code=${C.errorCode}, message=${_.message}, type=${C.errorName}`,S),this._stateManager.dispatchServerAction(i,{type:"chat/error",turnId:l,duration:this._turnDuration(u),error:_}),this._turnTracker.turnCompleted(i,l,"error",C),this._toolCallTracker.clearSession(i),this._failSessionCreationIfStillCreating(r,_)}}async _resolveChatAttachments(e,t){return t?.some(r=>r.type==="chat")?Promise.all(t.map(async r=>{if(r.type!=="chat")return r;if((de(r.resource)?ce(r.resource):v.parse(r.resource).toString())!==v.parse(e).toString())throw new Error(`Chat attachment source must belong to the target session: ${r.resource}`);let s=this._resolveSourceChatState(r.resource);if(s?.activeTurn?.id===r.endTurn)throw new Error(`Chat attachment endTurn must reference a completed turn: ${r.resource}#${r.endTurn}`);let a=await this._options.resolveChatAttachmentTurns?.(r.resource)??s?.turns??[];return mP(r,a)})):t}_resolveSourceChatState(e){let t=this._stateManager.getChatState(e);if(t)return t;if(!de(e))return this._stateManager.getDefaultChatState(e);if(Re(e))return this._stateManager.getDefaultChatState(ce(e))}_failSessionCreationIfStillCreating(e,t){if(this._stateManager.getSessionState(e)?.lifecycle!=="creating")return;this._stateManager.dispatchServerAction(e,{type:"session/creationFailed",error:t});let i=this._stateManager.getSessionSummary(e);i&&this._stateManager.markSessionPersisted(e,i)}dispose(){this._toolCallAgents.clear(),this._toolCallTracker.clear(),super.dispose()}};ql=A([b(2,we),b(3,O),b(4,Il),b(5,Pn),b(6,Kr)],ql);function gH(o,n){let e=mH(o,n);return{stage:o,error:e,errorName:n instanceof Error?n.name:typeof n,errorCode:hT(n),errorStack:n instanceof Error?n.stack:void 0}}function mH(o,n){let e=String(n),t=Km(n instanceof Error?n.message:e),r=o==="modelSelection"?"modelSelectionFailed":o==="workingDirectory"?"workingDirectoryFailed":"sendFailed";return t?{errorType:r,message:Fu(e),_meta:Hu(t)}:{errorType:r,message:e}}var Gm=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(v.parse(n))}catch(l){this._logService.warn(`[AgentHostLocalTurns] Failed to open database to persist local turn ${t.id}`,l);return}a.object.insertLocalTurn(s).catch(l=>{this._logService.warn(`[AgentHostLocalTurns] Failed to persist local turn ${t.id}`,l)}).finally(()=>a.dispose())}async loadForChat(n,e){return(await this._load(n)).filter(r=>r.chatUri===e)}noteInMemory(n,e,t,r,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(v.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?.(v.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 Jm=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 $u="vscode.agentFeedback",qE="viewUnreviewedComments",BE="addComment";function hH(o){return o==="user"||o==="codeReview"||o==="prReview"}function yH(o){return o==="created"||o==="accepted"||o==="submitted"||o==="resolved"}function zE(o){let e=o._meta?.[$u];if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(!hH(t.kind)||!yH(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 Qr=BE,OI="listComments",Qm="deleteComments",qu="resolveComments",Bu=qE,KE=new Set(["prReview","codeReview"]),vH=new Set([Bu]);function SH(o){return vH.has(o)}var CH={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"]},IH={type:"object",properties:{}},bH={type:"object",properties:{}},_H={type:"object",properties:{commentIds:{type:"array",items:{type:"string"},description:"Comment IDs to delete."}},required:["commentIds"]},TH={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"]},wH=[{name:Qr,title:"Add Comment (Agent Feedback)",description:"Add a comment to a file range.",inputSchema:CH,annotations:{readOnlyHint:!1}},{name:OI,title:"List Comments (Agent Feedback)",description:"List comments for this session.",inputSchema:IH,annotations:{readOnlyHint:!0}},{name:Qm,title:"Delete Comments (Agent Feedback)",description:"Delete comments for this session.",inputSchema:_H,annotations:{readOnlyHint:!1,destructiveHint:!0}},{name:qu,title:"Resolve Comments (Agent Feedback)",description:"Mark comments for this session as resolved or unresolved.",inputSchema:TH,annotations:{readOnlyHint:!1}},{name:Bu,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:bH,annotations:{readOnlyHint:!0}}];function MI(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 Ym(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 RH(o){let n=o??{},e=MI(n.resourceUri,"resourceUri",Qr),t=MI(n.text,"text",Qr);if(!n.range||typeof n.range!="object"||Array.isArray(n.range))throw new Error(`Invalid ${Qr} input: range must be an object.`);let r=n.range;return{resourceUri:e,text:t,range:{startLineNumber:Ym(r.startLineNumber,"range.startLineNumber",Qr),startColumn:Ym(r.startColumn,"range.startColumn",Qr),endLineNumber:Ym(r.endLineNumber,"range.endLineNumber",Qr),endColumn:Ym(r.endColumn,"range.endColumn",Qr)}}}function VE(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(MI(t,"commentIds[]",n));return[...new Set(e)]}function xH(o){if(o===void 0)return!0;if(typeof o!="boolean")throw new Error(`Invalid ${qu} input: resolved must be a boolean.`);return o}function AH(o){return{start:{line:o.startLineNumber-1,character:o.startColumn-1},end:{line:o.endLineNumber-1,character:o.endColumn-1}}}function PH(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 jE(o){return typeof o=="string"?o:o.markdown}function Ks(o){return zE(o)}function Wu(o){let n=o.entries??[],e=Ks(o),t=n.slice(1).map(r=>jE(r.text));return{id:o.id,resourceUri:o.resource,range:PH(o.range),text:n.length?jE(n[0].text):"",kind:e?.kind??"user",resolved:o.resolved,...t.length?{replies:t}:{}}}function DI(o){return o.annotations.filter(n=>{let e=Ks(n);return!e||!n.entries?.length?!1:(n.resolved?"resolved":e.state??"accepted")!=="created"})}function EH(o){return o.annotations.filter(n=>{let e=Ks(n);return!e||!n.entries?.length?!1:KE.has(e.kind)&&e.pendingAgentReveal===!0})}function kH(o){let n=Ks(o);if(!n)return o;let e={...n,pendingAgentReveal:void 0};return{...o,_meta:{...o._meta,[$u]:e}}}function DH(o){return o.annotations.filter(n=>{let e=Ks(n);return!e||!n.entries?.length?!1:KE.has(e.kind)&&!n.resolved&&(e.state??"accepted")==="created"})}function MH(o){let n=DH(o);if(!n.length)return;let e=0,t=0;for(let a of n){let l=Ks(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 \`${Bu}\` tool to view them.`}function OH(o,n,e,t){switch(e){case Qr:{let{resourceUri:r,range:i,text:s}=RH(t),a=F(),l={kind:"codeReview",state:"created",sessionResource:n},d={id:a,turnId:"",resource:r,range:AH(i),resolved:!1,entries:[{id:`${a}:0`,text:s}],_meta:{[$u]:l}};return{actions:[{type:"annotations/set",annotation:d}],result:"Comment added."}}case OI:{let r={comments:DI(o).map(Wu)},i=MH(o);return i&&(r.note=i),{actions:[],result:JSON.stringify(r,void 0,2)}}case Bu:{let r=EH(o),i=r.map(Wu);return{actions:r.map(a=>({type:"annotations/set",annotation:kH(a)})),result:JSON.stringify({comments:i},void 0,2)}}case Qm:{let r=VE(t?.commentIds,Qm),i=DI(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(Wu);return{actions:a,result:JSON.stringify({deletedCommentIds:l,notFoundCommentIds:d,remainingComments:c},void 0,2)}}case qu:{let r=t??{},i=VE(r.commentIds,qu),s=xH(r.resolved),a=DI(o),l=new Map(a.map(g=>[g.id,g])),d=[],c=[],u=[];for(let g of i){let h=l.get(g);if(!h){u.push(g);continue}let y=Ks(h),I={...y,kind:y?.kind??"user",state:s?"resolved":"submitted",sessionResource:y?.sessionResource??n},S={...h,resolved:s,_meta:{...h._meta,[$u]:I}};d.push({type:"annotations/set",annotation:S}),c.push(g)}let p=a.map(g=>c.includes(g.id)?Wu({...g,resolved:s}):Wu(g));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 LH(o){if(o)try{let n=JSON.parse(o);return Array.isArray(n.comments)?n.comments.length:void 0}catch{return}}function NH(o,n,e){switch(o){case Qr:return{displayName:f(2439,null),invocationMessage:f(2434,null),pastTenseMessage:f(2427,null)};case OI:{let t,r=e?LH(e.text):void 0;return r===void 0?t=f(2429,null):r===1?t=f(2431,null):t=f(2430,null,r),{displayName:f(2441,null),invocationMessage:f(2436,null),pastTenseMessage:t}}case Qm:return{displayName:f(2440,null),invocationMessage:f(2435,null),pastTenseMessage:f(2428,null)};case qu:return{displayName:f(2442,null),invocationMessage:f(2437,null),pastTenseMessage:f(2432,null)};case Bu:return{displayName:f(2443,null),invocationMessage:f(2438,null),pastTenseMessage:f(2433,null)};default:return}}var GE={definitions:wH,requiresConfirmation(o){return SH(o)},getDisplay(o,n,e){return NH(o,n,e)},execute(o,n,e,t){let r=Le(n)?.session??n,i=Lg(r),a=o.getSnapshot(i)?.state??{annotations:[]},l=OH(a,r,e,t);for(let d of l.actions)o.dispatchServerAction(i,d);return l.result}};var LI="agent-host-session",JE="create_session",YE="create_chat",QE="send_message";function Gs(o,n){let e=M.provider(o),t=M.id(o);if(!e)throw new Error(`Cannot build open-session link: missing provider in ${o.toString()}`);let r=v.from({scheme:LI,authority:e,path:`/${t}`}).toString();return n?`${r}?chat=${encodeURIComponent(n)}`:r}function NI(o){let n=typeof o=="string"?v.parse(o):o;if(n.scheme!==LI||!n.authority)return;let e=n.path.replace(/^\//,"");if(e)return M.uri(n.authority,e)}function UI(o){let n=typeof o=="string"?v.parse(o):o;if(n.scheme!==LI)return;let e=/(?:^|&)chat=([^&]+)/.exec(n.query);return e?decodeURIComponent(e[1]):void 0}var Bn="list_sessions",$I="get_current_session",Wo=JE,Xr=YE,ki=QE,Js="get_session_context",Ys="delete_session",XE=3,ZE=25,ek=25,tk=50,UH=new Set([Wo,Xr,ki,Ys]);function FH(o){return UH.has(o)}var FI=["idle","inProgress","inputNeeded","error","archived"],HH={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:[...FI]},description:"Only return sessions whose status matches one of these (e.g. `inputNeeded` for sessions awaiting a reply, `inProgress` for running ones, `archived` for sessions marked Done/completed \u2014 implies `includeArchived`). 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)."}}},$H={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"]},WH={type:"object",properties:{}},qH={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"]},BH={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"]},zH={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"]},HI=["summary","digest","full"],VH={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:[...HI],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"]},jH=[{name:Bn,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:HH,annotations:{readOnlyHint:!0}},{name:$I,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:WH,annotations:{readOnlyHint:!0}},{name:Wo,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:$H,annotations:{readOnlyHint:!1}},{name:Xr,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:qH,annotations:{readOnlyHint:!1}},{name:ki,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:zH,annotations:{readOnlyHint:!1}},{name:Js,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:VH,annotations:{readOnlyHint:!0}},{name:Ys,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:BH,annotations:{readOnlyHint:!1,destructiveHint:!0}}];function Xm(o){let n=Le(o)??void 0;return v.parse(n?.session??o)}function Qs(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 Bl(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 rk(o){if(/^(\/|[a-zA-Z]:[\\/]|\\\\)/.test(o))return v.file(o);try{let n=v.parse(o,!0);return n.scheme?n:void 0}catch{return}}function KH(o,n){let e=n.find(r=>r.workingDirectory?.toString()===o||r.workingDirectory?.fsPath===o);if(e?.workingDirectory)return e.workingDirectory;let t=rk(o);if(!t)throw new Error(`Invalid ${Wo} input: workspace must match a known session workingDirectory, an absolute path, or a valid URI string.`);return t}function ok(o,n){if(o===void 0)return;let e=n.find(t=>t.id===o||t.name===o);if(!e)throw new Error(`Invalid ${Wo} input: model must match an available model id or name.`);return e}function GH(o,n,e){let t=o??{},r=Qs(t.workspace,"workspace",Wo),i=Qs(t.prompt,"prompt",Wo),s=Bl(t.model,"model",Wo);return{workspace:KH(r,n),prompt:i,model:ok(s,e)}}function JH(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}function ik(o){let n=o.status!==void 0?JH(o.status):[];return sk(o)&&!n.includes("archived")&&n.push("archived"),n}function YH(o){let n=ik(o);return n.length>0?n.join(","):o.status!==void 0?"unknown":void 0}function Zm(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 nk(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 QH(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 ${Bn} input: status must be an array of status names.`);let t=n.status.filter(r=>!FI.includes(r));if(t.length>0)throw new Error(`Invalid ${Bn} input: unknown status value(s) ${t.join(", ")}. Valid values: ${FI.join(", ")}.`);e=new Set(n.status)}return{session:Bl(n.session,"session",Bn),status:e,workspace:Bl(n.workspace,"workspace",Bn),withChanges:Zm(n.withChanges,"withChanges",Bn),unread:Zm(n.unread,"unread",Bn),withPullRequest:Zm(n.withPullRequest,"withPullRequest",Bn),includeArchived:Zm(n.includeArchived,"includeArchived",Bn),createdAfter:nk(n.createdAfter,"createdAfter",Bn),createdBefore:nk(n.createdBefore,"createdBefore",Bn)}}function XH(o){let n=o.changes;return!!n&&((n.files??0)>0||(n.additions??0)>0||(n.deletions??0)>0)}function sk(o){return o.isArchived===!0||o.status!==void 0&&(o.status&64)!==0}function ZH(o,n){let e=o.workingDirectory;if(!e)return!1;if(e.toString()===n||e.fsPath===n)return!0;let t=rk(n);return!!t&&t.toString()===e.toString()}function e7(o,n){if(n.session!==void 0){let e=NI(n.session)?.toString()??n.session;return o.filter(t=>t.session.toString()===e)}return o.filter(e=>!(n.status&&!ik(e).some(r=>n.status.has(r))||n.workspace!==void 0&&!ZH(e,n.workspace)||n.withChanges&&!XH(e)||n.unread&&e.isRead!==!1||n.withPullRequest&&!br(e._meta)?.pullRequestUrl||n.includeArchived!==!0&&!n.status?.has("archived")&&sk(e)||n.createdAfter!==void 0&&e.startTime<n.createdAfter||n.createdBefore!==void 0&&e.startTime>n.createdBefore))}function t7(o){let n=bt(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 n7(o){let n=br(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 ak(o){let n=t7(o),e=n7(o),t=YH(o);return{session:o.session.toString(),...o.summary!==void 0?{title:o.summary}:{},...t!==void 0?{status:t}:{},...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(r=>({label:r.label,changeKind:r.changeKind,uriTemplate:r.uriTemplate,...r.description!==void 0?{description:r.description}:{}}))}:{},...n!==void 0?{git:n}:{},...e!==void 0?{github:e}:{}}}function r7(o){return JSON.stringify({sessions:o.map(ak)})}async function o7(o,n,e){let t=e?o.getSessionSpawnDepth(e):0;if(t>=XE)throw new Error(`Refusing to create a session: recursion limit reached (max spawn depth ${XE}). This session was itself created ${t} level(s) deep.`);let r=await o.listSessions(),i=GH(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=v.parse(pe(a));return await o.startPrompt(a,l,i.prompt),{session:a.toString(),chat:l.toString(),openLink:Gs(a)}}function i7(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 eh(o,n){let t=NI(o)?.toString()??o;return n.find(i=>i.session.toString()===t)?.session}function s7(o,n){let e=eh(o,n);if(!e)throw new Error(`Invalid ${Xr} input: session must match the URI of a known session (see list_sessions).`);return e}function a7(o,n,e,t){let r=o??{},i=Qs(r.prompt,"prompt",Xr),s=Bl(r.title,"title",Xr),a=Bl(r.model,"model",Xr),l=ok(a,e),d=Bl(r.session,"session",Xr),c;if(d!==void 0)c=s7(d,n);else if(t)c=t;else throw new Error(`Invalid ${Xr} 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 l7(o,n,e){let t=await o.listSessions(),r=a7(n,t,o.getModels(),e),i=F(),s=v.parse(fi(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:Gs(r.session,i)}}function d7(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 c7(o,n){let e=o??{},t=Qs(e.message,"message",ki),r=Qs(e.session,"session",ki),i=eh(r,n);if(!i)throw new Error(`Invalid ${ki} input: session must match the URI of a known session (see list_sessions).`);let s=UI(r),a=v.parse(s?fi(i.toString(),s):pe(i.toString()));return{session:i,chat:a,message:t,...s!==void 0?{chatId:s}:{}}}async function u7(o,n,e){let t=await o.listSessions(),{session:r,chat:i,chatId:s,message:a}=c7(n,t);if(e&&i.toString()===v.parse(e).toString())throw new Error(`Invalid ${ki} input: refusing to send a message to the current chat.`);return await o.startPrompt(r,i,a),p7(Gs(r,s))}function p7(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 f7=10,g7=50,m7={summary:{user:160,assistant:140,toolInput:0},digest:{user:300,assistant:800,toolInput:0},full:{user:1e3,assistant:2e3,toolInput:200}};function h7(o,n){let e=o??{},t=Qs(e.session,"session",Js),r=eh(t,n);if(!r)throw new Error(`Invalid ${Js} 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"||!HI.includes(e.detail))throw new Error(`Invalid ${Js} input: detail must be one of ${HI.join(", ")}.`);i=e.detail}let s=f7;if(e.transcriptLimit!==void 0){if(typeof e.transcriptLimit!="number"||!Number.isFinite(e.transcriptLimit)||e.transcriptLimit<1)throw new Error(`Invalid ${Js} input: transcriptLimit must be a positive number.`);s=Math.min(Math.floor(e.transcriptLimit),g7)}let a=UI(t);return{session:r,detail:i,transcriptLimit:s,...a!==void 0?{chatId:a}:{}}}function y7(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 v7(o){return o.filter(n=>n.kind==="toolCall").map(n=>n.toolCall)}function S7(o){return o.filter(n=>n.kind==="markdown").map(n=>n.content).join("").trim()}function C7(o){return o.status==="streaming"?void 0:o.toolInput}function I7(o){switch(o){case"complete":return"complete";case"cancelled":return"cancelled";case"error":return"error";default:return"inProgress"}}function b7(o,n,e,t,r){let i=m7[t],s=!1,a=(g,h)=>{if(h<=0||!g)return;let y=y7(g,h);return s=s||y.truncated,y.text||void 0},l=e.turns.map(g=>({message:g.message,parts:g.responseParts,state:g.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((g,h)=>{let y=a(g.message.text,i.user),I=a(S7(g.parts),i.assistant),S=v7(g.parts),C;return t!=="summary"&&S.length>0&&(C=S.map(_=>{if(i.toolInput>0){let T=a(C7(_)??"",i.toolInput);return T!==void 0?{name:_.toolName,input:T}:{name:_.toolName}}return _.toolName})),{turn:d+h+1,state:I7(g.state),...y!==void 0?{user:y}:{},...I!==void 0?{assistant:I}:{},...C?{toolCalls:C}:{}}}),p={session:o.toString(),openLink:Gs(o,n),detail:t,transcript:u,hasMoreHistory:e.hasMoreHistory,truncated:s};return JSON.stringify(p)}async function _7(o,n){let e=await o.listSessions(),{session:t,chatId:r,detail:i,transcriptLimit:s}=h7(n,e),a=o.getChatContext(t,r);return a?b7(t,r,a,i,s):JSON.stringify({session:t.toString(),openLink:Gs(t,r),detail:i,transcript:[],hasMoreHistory:!1,truncated:!1})}function T7(o,n){let e=n.find(t=>t.session.toString()===o.toString());return JSON.stringify({session:o.toString(),openLink:Gs(o),...e?ak(e):{}})}function w7(o){if(o)try{let n=JSON.parse(o);return Array.isArray(n.sessions)?n.sessions.length:void 0}catch{return}}function R7(o,n,e){let r=Qs((o??{}).session,"session",Ys),i=eh(r,n);if(!i)throw new Error(`Invalid ${Ys} input: session must match the URI of a known session (see list_sessions).`);if(e&&i.toString()===e.toString())throw new Error(`Invalid ${Ys} input: refusing to delete the current session.`);return i}async function x7(o,n,e){let t=await o.listSessions(),r=R7(n,t,e);return await o.deleteSession(r),`Deleted session ${r.toString()}. Reply with one short sentence confirming the session was deleted.`}function A7(o,n,e){switch(o){case Bn:{let t,r=e?w7(e.text):void 0;return r===void 0?t=f(2449,null):r===1?t=f(2451,null):t=f(2450,null,r),{displayName:f(2465,null),invocationMessage:f(2458,null),pastTenseMessage:t}}case Wo:return{displayName:f(2461,null),invocationMessage:f(2454,null),pastTenseMessage:f(2445,null)};case Xr:return{displayName:f(2460,null),invocationMessage:f(2453,null),pastTenseMessage:f(2444,null)};case ki:return{displayName:f(2466,null),invocationMessage:f(2459,null),pastTenseMessage:f(2452,null)};case Js:return{displayName:f(2464,null),invocationMessage:f(2457,null),pastTenseMessage:f(2448,null)};case $I:return{displayName:f(2463,null),invocationMessage:f(2456,null),pastTenseMessage:f(2447,null)};case Ys:return{displayName:f(2462,null),invocationMessage:f(2455,null),pastTenseMessage:f(2446,null)};default:return}}function lk(o){let n=0,e=0,t=0;return{definitions:jH,requiresConfirmation(i){return FH(i)},getDisplay(i,s,a){return A7(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 Bn:return r7(e7(await o.listSessions(),QH(l)));case $I:return T7(Xm(s),await o.listSessions());case Wo:{if(n>=ZE)throw new Error(`Refusing to create more than ${ZE} sessions from server tools in this process.`);let d=await o7(o,l,Xm(s));return n++,i7(d)}case Xr:{if(e>=ek)throw new Error(`Refusing to create more than ${ek} chats from server tools in this process.`);let d=await l7(o,l,Xm(s));return e++,d7(d)}case ki:{if(t>=tk)throw new Error(`Refusing to send more than ${tk} messages from server tools in this process.`);let d=await u7(o,l,s);return t++,d}case Js:return _7(o,l);case Ys:return x7(o,l,Xm(s));default:throw new Error(`Unknown session server tool: ${a}`)}}}}function WI(o){return[GE,lk(o)]}var P7=WI();function E7(o,n){return o===n||o.endsWith(`__${n}`)}function Rr(o,n,e){for(let t of P7)if(t.getDisplay){for(let r of t.definitions)if(E7(o,r.name))return t.getDisplay(r.name,n,e)}}import*as qo from"fs/promises";var dk=Object.create(null);function m(o,n){if(Be(n)){let e=dk[n];if(e===void 0)throw new Error(`${o} references an unknown codicon: ${n}`);n=e}return dk[o]=n,{id:o}}var ck={add:m("add",6e4),plus:m("plus",6e4),gistNew:m("gist-new",6e4),repoCreate:m("repo-create",6e4),lightbulb:m("lightbulb",60001),lightBulb:m("light-bulb",60001),repo:m("repo",60002),repoDelete:m("repo-delete",60002),gistFork:m("gist-fork",60003),repoForked:m("repo-forked",60003),gitPullRequest:m("git-pull-request",60004),gitPullRequestAbandoned:m("git-pull-request-abandoned",60004),recordKeys:m("record-keys",60005),keyboard:m("keyboard",60005),tag:m("tag",60006),gitPullRequestLabel:m("git-pull-request-label",60006),tagAdd:m("tag-add",60006),tagRemove:m("tag-remove",60006),person:m("person",60007),personFollow:m("person-follow",60007),personOutline:m("person-outline",60007),personFilled:m("person-filled",60007),sourceControl:m("source-control",60008),mirror:m("mirror",60009),mirrorPublic:m("mirror-public",60009),star:m("star",60010),starAdd:m("star-add",60010),starDelete:m("star-delete",60010),starEmpty:m("star-empty",60010),comment:m("comment",60011),commentAdd:m("comment-add",60011),alert:m("alert",60012),warning:m("warning",60012),search:m("search",60013),searchSave:m("search-save",60013),logOut:m("log-out",60014),signOut:m("sign-out",60014),logIn:m("log-in",60015),signIn:m("sign-in",60015),eye:m("eye",60016),eyeUnwatch:m("eye-unwatch",60016),eyeWatch:m("eye-watch",60016),circleFilled:m("circle-filled",60017),primitiveDot:m("primitive-dot",60017),closeDirty:m("close-dirty",60017),debugBreakpoint:m("debug-breakpoint",60017),debugBreakpointDisabled:m("debug-breakpoint-disabled",60017),debugHint:m("debug-hint",60017),terminalDecorationSuccess:m("terminal-decoration-success",60017),primitiveSquare:m("primitive-square",60018),edit:m("edit",60019),pencil:m("pencil",60019),info:m("info",60020),issueOpened:m("issue-opened",60020),gistPrivate:m("gist-private",60021),gitForkPrivate:m("git-fork-private",60021),lock:m("lock",60021),mirrorPrivate:m("mirror-private",60021),close:m("close",60022),removeClose:m("remove-close",60022),x:m("x",60022),repoSync:m("repo-sync",60023),sync:m("sync",60023),clone:m("clone",60024),desktopDownload:m("desktop-download",60024),beaker:m("beaker",60025),microscope:m("microscope",60025),vm:m("vm",60026),deviceDesktop:m("device-desktop",60026),file:m("file",60027),more:m("more",60028),ellipsis:m("ellipsis",60028),kebabHorizontal:m("kebab-horizontal",60028),mailReply:m("mail-reply",60029),reply:m("reply",60029),organization:m("organization",60030),organizationFilled:m("organization-filled",60030),organizationOutline:m("organization-outline",60030),newFile:m("new-file",60031),fileAdd:m("file-add",60031),newFolder:m("new-folder",60032),fileDirectoryCreate:m("file-directory-create",60032),trash:m("trash",60033),trashcan:m("trashcan",60033),history:m("history",60034),clock:m("clock",60034),folder:m("folder",60035),fileDirectory:m("file-directory",60035),symbolFolder:m("symbol-folder",60035),logoGithub:m("logo-github",60036),markGithub:m("mark-github",60036),github:m("github",60036),terminal:m("terminal",60037),console:m("console",60037),repl:m("repl",60037),zap:m("zap",60038),symbolEvent:m("symbol-event",60038),error:m("error",60039),stop:m("stop",60039),variable:m("variable",60040),symbolVariable:m("symbol-variable",60040),array:m("array",60042),symbolArray:m("symbol-array",60042),symbolModule:m("symbol-module",60043),symbolPackage:m("symbol-package",60043),symbolNamespace:m("symbol-namespace",60043),symbolObject:m("symbol-object",60043),symbolMethod:m("symbol-method",60044),symbolFunction:m("symbol-function",60044),symbolConstructor:m("symbol-constructor",60044),symbolBoolean:m("symbol-boolean",60047),symbolNull:m("symbol-null",60047),symbolNumeric:m("symbol-numeric",60048),symbolNumber:m("symbol-number",60048),symbolStructure:m("symbol-structure",60049),symbolStruct:m("symbol-struct",60049),symbolParameter:m("symbol-parameter",60050),symbolTypeParameter:m("symbol-type-parameter",60050),symbolKey:m("symbol-key",60051),symbolText:m("symbol-text",60051),symbolReference:m("symbol-reference",60052),goToFile:m("go-to-file",60052),symbolEnum:m("symbol-enum",60053),symbolValue:m("symbol-value",60053),symbolRuler:m("symbol-ruler",60054),symbolUnit:m("symbol-unit",60054),activateBreakpoints:m("activate-breakpoints",60055),archive:m("archive",60056),arrowBoth:m("arrow-both",60057),arrowDown:m("arrow-down",60058),arrowLeft:m("arrow-left",60059),arrowRight:m("arrow-right",60060),arrowSmallDown:m("arrow-small-down",60061),arrowSmallLeft:m("arrow-small-left",60062),arrowSmallRight:m("arrow-small-right",60063),arrowSmallUp:m("arrow-small-up",60064),arrowUp:m("arrow-up",60065),bell:m("bell",60066),bold:m("bold",60067),book:m("book",60068),bookmark:m("bookmark",60069),debugBreakpointConditionalUnverified:m("debug-breakpoint-conditional-unverified",60070),debugBreakpointConditional:m("debug-breakpoint-conditional",60071),debugBreakpointConditionalDisabled:m("debug-breakpoint-conditional-disabled",60071),debugBreakpointDataUnverified:m("debug-breakpoint-data-unverified",60072),debugBreakpointData:m("debug-breakpoint-data",60073),debugBreakpointDataDisabled:m("debug-breakpoint-data-disabled",60073),debugBreakpointLogUnverified:m("debug-breakpoint-log-unverified",60074),debugBreakpointLog:m("debug-breakpoint-log",60075),debugBreakpointLogDisabled:m("debug-breakpoint-log-disabled",60075),briefcase:m("briefcase",60076),broadcast:m("broadcast",60077),browser:m("browser",60078),bug:m("bug",60079),calendar:m("calendar",60080),caseSensitive:m("case-sensitive",60081),check:m("check",60082),checklist:m("checklist",60083),chevronDown:m("chevron-down",60084),chevronLeft:m("chevron-left",60085),chevronRight:m("chevron-right",60086),chevronUp:m("chevron-up",60087),chromeClose:m("chrome-close",60088),chromeMaximize:m("chrome-maximize",60089),chromeMinimize:m("chrome-minimize",60090),chromeRestore:m("chrome-restore",60091),circleOutline:m("circle-outline",60092),circle:m("circle",60092),debugBreakpointUnverified:m("debug-breakpoint-unverified",60092),terminalDecorationIncomplete:m("terminal-decoration-incomplete",60092),circleSlash:m("circle-slash",60093),circuitBoard:m("circuit-board",60094),clearAll:m("clear-all",60095),clippy:m("clippy",60096),closeAll:m("close-all",60097),cloudDownload:m("cloud-download",60098),cloudUpload:m("cloud-upload",60099),code:m("code",60100),collapseAll:m("collapse-all",60101),colorMode:m("color-mode",60102),commentDiscussion:m("comment-discussion",60103),creditCard:m("credit-card",60105),dash:m("dash",60108),dashboard:m("dashboard",60109),database:m("database",60110),debugContinue:m("debug-continue",60111),debugDisconnect:m("debug-disconnect",60112),debugPause:m("debug-pause",60113),debugRestart:m("debug-restart",60114),debugStart:m("debug-start",60115),debugStepInto:m("debug-step-into",60116),debugStepOut:m("debug-step-out",60117),debugStepOver:m("debug-step-over",60118),debugStop:m("debug-stop",60119),debug:m("debug",60120),deviceCameraVideo:m("device-camera-video",60121),deviceCamera:m("device-camera",60122),deviceMobile:m("device-mobile",60123),diffAdded:m("diff-added",60124),diffIgnored:m("diff-ignored",60125),diffModified:m("diff-modified",60126),diffRemoved:m("diff-removed",60127),diffRenamed:m("diff-renamed",60128),diff:m("diff",60129),diffSidebyside:m("diff-sidebyside",60129),discard:m("discard",60130),editorLayout:m("editor-layout",60131),emptyWindow:m("empty-window",60132),exclude:m("exclude",60133),extensions:m("extensions",60134),eyeClosed:m("eye-closed",60135),fileBinary:m("file-binary",60136),fileCode:m("file-code",60137),fileMedia:m("file-media",60138),filePdf:m("file-pdf",60139),fileSubmodule:m("file-submodule",60140),fileSymlinkDirectory:m("file-symlink-directory",60141),fileSymlinkFile:m("file-symlink-file",60142),fileZip:m("file-zip",60143),files:m("files",60144),filter:m("filter",60145),flame:m("flame",60146),foldDown:m("fold-down",60147),foldUp:m("fold-up",60148),fold:m("fold",60149),folderActive:m("folder-active",60150),folderOpened:m("folder-opened",60151),gear:m("gear",60152),gift:m("gift",60153),gistSecret:m("gist-secret",60154),gist:m("gist",60155),gitCommit:m("git-commit",60156),gitCompare:m("git-compare",60157),compareChanges:m("compare-changes",60157),gitMerge:m("git-merge",60158),githubAction:m("github-action",60159),githubAlt:m("github-alt",60160),globe:m("globe",60161),grabber:m("grabber",60162),graph:m("graph",60163),gripper:m("gripper",60164),heart:m("heart",60165),home:m("home",60166),horizontalRule:m("horizontal-rule",60167),hubot:m("hubot",60168),inbox:m("inbox",60169),issueReopened:m("issue-reopened",60171),issues:m("issues",60172),italic:m("italic",60173),jersey:m("jersey",60174),json:m("json",60175),bracket:m("bracket",60175),kebabVertical:m("kebab-vertical",60176),key:m("key",60177),law:m("law",60178),lightbulbAutofix:m("lightbulb-autofix",60179),linkExternal:m("link-external",60180),link:m("link",60181),listOrdered:m("list-ordered",60182),listUnordered:m("list-unordered",60183),liveShare:m("live-share",60184),loading:m("loading",60185),location:m("location",60186),mailRead:m("mail-read",60187),mail:m("mail",60188),markdown:m("markdown",60189),megaphone:m("megaphone",60190),mention:m("mention",60191),milestone:m("milestone",60192),gitPullRequestMilestone:m("git-pull-request-milestone",60192),mortarBoard:m("mortar-board",60193),move:m("move",60194),multipleWindows:m("multiple-windows",60195),mute:m("mute",60196),noNewline:m("no-newline",60197),note:m("note",60198),octoface:m("octoface",60199),openPreview:m("open-preview",60200),package:m("package",60201),paintcan:m("paintcan",60202),pin:m("pin",60203),play:m("play",60204),run:m("run",60204),plug:m("plug",60205),preserveCase:m("preserve-case",60206),preview:m("preview",60207),project:m("project",60208),pulse:m("pulse",60209),question:m("question",60210),quote:m("quote",60211),radioTower:m("radio-tower",60212),reactions:m("reactions",60213),references:m("references",60214),refresh:m("refresh",60215),regex:m("regex",60216),remoteExplorer:m("remote-explorer",60217),remote:m("remote",60218),remove:m("remove",60219),replaceAll:m("replace-all",60220),replace:m("replace",60221),repoClone:m("repo-clone",60222),repoForcePush:m("repo-force-push",60223),repoPull:m("repo-pull",60224),repoPush:m("repo-push",60225),report:m("report",60226),requestChanges:m("request-changes",60227),rocket:m("rocket",60228),rootFolderOpened:m("root-folder-opened",60229),rootFolder:m("root-folder",60230),rss:m("rss",60231),ruby:m("ruby",60232),saveAll:m("save-all",60233),saveAs:m("save-as",60234),save:m("save",60235),screenFull:m("screen-full",60236),screenNormal:m("screen-normal",60237),searchStop:m("search-stop",60238),server:m("server",60240),settingsGear:m("settings-gear",60241),settings:m("settings",60242),shield:m("shield",60243),smiley:m("smiley",60244),sortPrecedence:m("sort-precedence",60245),splitHorizontal:m("split-horizontal",60246),splitVertical:m("split-vertical",60247),squirrel:m("squirrel",60248),starFull:m("star-full",60249),starHalf:m("star-half",60250),symbolClass:m("symbol-class",60251),symbolColor:m("symbol-color",60252),symbolConstant:m("symbol-constant",60253),symbolEnumMember:m("symbol-enum-member",60254),symbolField:m("symbol-field",60255),symbolFile:m("symbol-file",60256),symbolInterface:m("symbol-interface",60257),symbolKeyword:m("symbol-keyword",60258),symbolMisc:m("symbol-misc",60259),symbolOperator:m("symbol-operator",60260),symbolProperty:m("symbol-property",60261),wrench:m("wrench",60261),wrenchSubaction:m("wrench-subaction",60261),symbolSnippet:m("symbol-snippet",60262),tasklist:m("tasklist",60263),telescope:m("telescope",60264),textSize:m("text-size",60265),threeBars:m("three-bars",60266),thumbsdown:m("thumbsdown",60267),thumbsup:m("thumbsup",60268),tools:m("tools",60269),triangleDown:m("triangle-down",60270),triangleLeft:m("triangle-left",60271),triangleRight:m("triangle-right",60272),triangleUp:m("triangle-up",60273),twitter:m("twitter",60274),unfold:m("unfold",60275),unlock:m("unlock",60276),unmute:m("unmute",60277),unverified:m("unverified",60278),verified:m("verified",60279),versions:m("versions",60280),vmActive:m("vm-active",60281),vmOutline:m("vm-outline",60282),vmRunning:m("vm-running",60283),watch:m("watch",60284),whitespace:m("whitespace",60285),wholeWord:m("whole-word",60286),window:m("window",60287),wordWrap:m("word-wrap",60288),zoomIn:m("zoom-in",60289),zoomOut:m("zoom-out",60290),listFilter:m("list-filter",60291),listFlat:m("list-flat",60292),listSelection:m("list-selection",60293),selection:m("selection",60293),listTree:m("list-tree",60294),debugBreakpointFunctionUnverified:m("debug-breakpoint-function-unverified",60295),debugBreakpointFunction:m("debug-breakpoint-function",60296),debugBreakpointFunctionDisabled:m("debug-breakpoint-function-disabled",60296),debugStackframeActive:m("debug-stackframe-active",60297),circleSmallFilled:m("circle-small-filled",60298),debugStackframeDot:m("debug-stackframe-dot",60298),terminalDecorationMark:m("terminal-decoration-mark",60298),debugStackframe:m("debug-stackframe",60299),debugStackframeFocused:m("debug-stackframe-focused",60299),debugBreakpointUnsupported:m("debug-breakpoint-unsupported",60300),symbolString:m("symbol-string",60301),debugReverseContinue:m("debug-reverse-continue",60302),debugStepBack:m("debug-step-back",60303),debugRestartFrame:m("debug-restart-frame",60304),debugAlt:m("debug-alt",60305),callIncoming:m("call-incoming",60306),callOutgoing:m("call-outgoing",60307),menu:m("menu",60308),expandAll:m("expand-all",60309),feedback:m("feedback",60310),gitPullRequestReviewer:m("git-pull-request-reviewer",60310),groupByRefType:m("group-by-ref-type",60311),ungroupByRefType:m("ungroup-by-ref-type",60312),account:m("account",60313),gitPullRequestAssignee:m("git-pull-request-assignee",60313),bellDot:m("bell-dot",60314),debugConsole:m("debug-console",60315),library:m("library",60316),output:m("output",60317),runAll:m("run-all",60318),syncIgnored:m("sync-ignored",60319),pinned:m("pinned",60320),githubInverted:m("github-inverted",60321),serverProcess:m("server-process",60322),serverEnvironment:m("server-environment",60323),pass:m("pass",60324),issueClosed:m("issue-closed",60324),stopCircle:m("stop-circle",60325),playCircle:m("play-circle",60326),record:m("record",60327),debugAltSmall:m("debug-alt-small",60328),vmConnect:m("vm-connect",60329),cloud:m("cloud",60330),merge:m("merge",60331),export:m("export",60332),graphLeft:m("graph-left",60333),magnet:m("magnet",60334),notebook:m("notebook",60335),redo:m("redo",60336),checkAll:m("check-all",60337),pinnedDirty:m("pinned-dirty",60338),passFilled:m("pass-filled",60339),circleLargeFilled:m("circle-large-filled",60340),circleLarge:m("circle-large",60341),circleLargeOutline:m("circle-large-outline",60341),combine:m("combine",60342),gather:m("gather",60342),table:m("table",60343),variableGroup:m("variable-group",60344),typeHierarchy:m("type-hierarchy",60345),typeHierarchySub:m("type-hierarchy-sub",60346),typeHierarchySuper:m("type-hierarchy-super",60347),gitPullRequestCreate:m("git-pull-request-create",60348),runAbove:m("run-above",60349),runBelow:m("run-below",60350),notebookTemplate:m("notebook-template",60351),debugRerun:m("debug-rerun",60352),workspaceTrusted:m("workspace-trusted",60353),workspaceUntrusted:m("workspace-untrusted",60354),workspaceUnknown:m("workspace-unknown",60355),terminalCmd:m("terminal-cmd",60356),terminalDebian:m("terminal-debian",60357),terminalLinux:m("terminal-linux",60358),terminalPowershell:m("terminal-powershell",60359),terminalTmux:m("terminal-tmux",60360),terminalUbuntu:m("terminal-ubuntu",60361),terminalBash:m("terminal-bash",60362),arrowSwap:m("arrow-swap",60363),copy:m("copy",60364),personAdd:m("person-add",60365),filterFilled:m("filter-filled",60366),wand:m("wand",60367),debugLineByLine:m("debug-line-by-line",60368),inspect:m("inspect",60369),layers:m("layers",60370),layersDot:m("layers-dot",60371),layersActive:m("layers-active",60372),compass:m("compass",60373),compassDot:m("compass-dot",60374),compassActive:m("compass-active",60375),azure:m("azure",60376),issueDraft:m("issue-draft",60377),gitPullRequestClosed:m("git-pull-request-closed",60378),gitPullRequestDraft:m("git-pull-request-draft",60379),debugAll:m("debug-all",60380),debugCoverage:m("debug-coverage",60381),runErrors:m("run-errors",60382),folderLibrary:m("folder-library",60383),debugContinueSmall:m("debug-continue-small",60384),beakerStop:m("beaker-stop",60385),graphLine:m("graph-line",60386),graphScatter:m("graph-scatter",60387),pieChart:m("pie-chart",60388),bracketDot:m("bracket-dot",60389),bracketError:m("bracket-error",60390),lockSmall:m("lock-small",60391),azureDevops:m("azure-devops",60392),verifiedFilled:m("verified-filled",60393),newline:m("newline",60394),layout:m("layout",60395),layoutActivitybarLeft:m("layout-activitybar-left",60396),layoutActivitybarRight:m("layout-activitybar-right",60397),layoutPanelLeft:m("layout-panel-left",60398),layoutPanelCenter:m("layout-panel-center",60399),layoutPanelJustify:m("layout-panel-justify",60400),layoutPanelRight:m("layout-panel-right",60401),layoutPanel:m("layout-panel",60402),layoutSidebarLeft:m("layout-sidebar-left",60403),layoutSidebarRight:m("layout-sidebar-right",60404),layoutStatusbar:m("layout-statusbar",60405),layoutMenubar:m("layout-menubar",60406),layoutCentered:m("layout-centered",60407),target:m("target",60408),indent:m("indent",60409),recordSmall:m("record-small",60410),errorSmall:m("error-small",60411),terminalDecorationError:m("terminal-decoration-error",60411),arrowCircleDown:m("arrow-circle-down",60412),arrowCircleLeft:m("arrow-circle-left",60413),arrowCircleRight:m("arrow-circle-right",60414),arrowCircleUp:m("arrow-circle-up",60415),layoutSidebarRightOff:m("layout-sidebar-right-off",60416),layoutPanelOff:m("layout-panel-off",60417),layoutSidebarLeftOff:m("layout-sidebar-left-off",60418),blank:m("blank",60419),heartFilled:m("heart-filled",60420),map:m("map",60421),mapHorizontal:m("map-horizontal",60421),foldHorizontal:m("fold-horizontal",60421),mapFilled:m("map-filled",60422),mapHorizontalFilled:m("map-horizontal-filled",60422),foldHorizontalFilled:m("fold-horizontal-filled",60422),circleSmall:m("circle-small",60423),bellSlash:m("bell-slash",60424),bellSlashDot:m("bell-slash-dot",60425),commentUnresolved:m("comment-unresolved",60426),gitPullRequestGoToChanges:m("git-pull-request-go-to-changes",60427),gitPullRequestNewChanges:m("git-pull-request-new-changes",60428),searchFuzzy:m("search-fuzzy",60429),commentDraft:m("comment-draft",60430),send:m("send",60431),sparkle:m("sparkle",60432),insert:m("insert",60433),mic:m("mic",60434),thumbsdownFilled:m("thumbsdown-filled",60435),thumbsupFilled:m("thumbsup-filled",60436),coffee:m("coffee",60437),snake:m("snake",60438),game:m("game",60439),vr:m("vr",60440),chip:m("chip",60441),piano:m("piano",60442),music:m("music",60443),micFilled:m("mic-filled",60444),repoFetch:m("repo-fetch",60445),copilot:m("copilot",60446),lightbulbSparkle:m("lightbulb-sparkle",60447),robot:m("robot",60448),sparkleFilled:m("sparkle-filled",60449),diffSingle:m("diff-single",60450),diffMultiple:m("diff-multiple",60451),surroundWith:m("surround-with",60452),share:m("share",60453),gitStash:m("git-stash",60454),gitStashApply:m("git-stash-apply",60455),gitStashPop:m("git-stash-pop",60456),vscode:m("vscode",60457),vscodeInsiders:m("vscode-insiders",60458),codeOss:m("code-oss",60459),runCoverage:m("run-coverage",60460),runAllCoverage:m("run-all-coverage",60461),coverage:m("coverage",60462),githubProject:m("github-project",60463),mapVertical:m("map-vertical",60464),foldVertical:m("fold-vertical",60464),mapVerticalFilled:m("map-vertical-filled",60465),foldVerticalFilled:m("fold-vertical-filled",60465),goToSearch:m("go-to-search",60466),percentage:m("percentage",60467),sortPercentage:m("sort-percentage",60467),attach:m("attach",60468),goToEditingSession:m("go-to-editing-session",60469),editSession:m("edit-session",60470),codeReview:m("code-review",60471),copilotWarning:m("copilot-warning",60472),python:m("python",60473),copilotLarge:m("copilot-large",60474),copilotWarningLarge:m("copilot-warning-large",60475),keyboardTab:m("keyboard-tab",60476),copilotBlocked:m("copilot-blocked",60477),copilotNotConnected:m("copilot-not-connected",60478),flag:m("flag",60479),lightbulbEmpty:m("lightbulb-empty",60480),symbolMethodArrow:m("symbol-method-arrow",60481),copilotUnavailable:m("copilot-unavailable",60482),repoPinned:m("repo-pinned",60483),keyboardTabAbove:m("keyboard-tab-above",60484),keyboardTabBelow:m("keyboard-tab-below",60485),gitPullRequestDone:m("git-pull-request-done",60486),mcp:m("mcp",60487),extensionsLarge:m("extensions-large",60488),layoutPanelDock:m("layout-panel-dock",60489),layoutSidebarLeftDock:m("layout-sidebar-left-dock",60490),layoutSidebarRightDock:m("layout-sidebar-right-dock",60491),copilotInProgress:m("copilot-in-progress",60492),copilotError:m("copilot-error",60493),copilotSuccess:m("copilot-success",60494),chatSparkle:m("chat-sparkle",60495),searchSparkle:m("search-sparkle",60496),editSparkle:m("edit-sparkle",60497),copilotSnooze:m("copilot-snooze",60498),sendToRemoteAgent:m("send-to-remote-agent",60499),commentDiscussionSparkle:m("comment-discussion-sparkle",60500),chatSparkleWarning:m("chat-sparkle-warning",60501),chatSparkleError:m("chat-sparkle-error",60502),collection:m("collection",60503),newCollection:m("new-collection",60504),thinking:m("thinking",60505),build:m("build",60506),commentDiscussionQuote:m("comment-discussion-quote",60507),cursor:m("cursor",60508),eraser:m("eraser",60509),fileText:m("file-text",60510),quotes:m("quotes",60512),rename:m("rename",60513),runWithDeps:m("run-with-deps",60514),debugConnected:m("debug-connected",60515),strikethrough:m("strikethrough",60516),openInProduct:m("open-in-product",60517),indexZero:m("index-zero",60518),agent:m("agent",60519),editCode:m("edit-code",60520),repoSelected:m("repo-selected",60521),skip:m("skip",60522),mergeInto:m("merge-into",60523),gitBranchChanges:m("git-branch-changes",60524),gitBranchStagedChanges:m("git-branch-staged-changes",60525),gitBranchConflicts:m("git-branch-conflicts",60526),gitBranch:m("git-branch",60527),gitBranchCreate:m("git-branch-create",60527),gitBranchDelete:m("git-branch-delete",60527),searchLarge:m("search-large",60528),terminalGitBash:m("terminal-git-bash",60529),windowActive:m("window-active",60530),forward:m("forward",60531),download:m("download",60532),clockface:m("clockface",60533),unarchive:m("unarchive",60534),sessionInProgress:m("session-in-progress",60535),collectionSmall:m("collection-small",60536),vmSmall:m("vm-small",60537),cloudSmall:m("cloud-small",60538),addSmall:m("add-small",60539),removeSmall:m("remove-small",60540),worktreeSmall:m("worktree-small",60541),worktree:m("worktree",60542),screenCut:m("screen-cut",60543),ask:m("ask",60544),openai:m("openai",60545),claude:m("claude",60546),openInWindow:m("open-in-window",60547),newSession:m("new-session",60548),terminalSecure:m("terminal-secure",60549),chatImport:m("chat-import",60550),chatExport:m("chat-export",60551),shareWindow:m("share-window",60552),circleSlashCompact:m("circle-slash-compact",60553),copilotCompact:m("copilot-compact",60554),folderOpenedCompact:m("folder-opened-compact",60555),folderCompact:m("folder-compact",60556),gearCompact:m("gear-compact",60557),gitBranchCompact:m("git-branch-compact",60558),libraryCompact:m("library-compact",60559),recordKeysCompact:m("record-keys-compact",60560),remoteCompact:m("remote-compact",60561),repoForkedCompact:m("repo-forked-compact",60562),repoCompact:m("repo-compact",60563),shieldCompact:m("shield-compact",60564),sparkleCompact:m("sparkle-compact",60565),symbolColorCompact:m("symbol-color-compact",60566),windowCompact:m("window-compact",60567),errorCompact:m("error-compact",60568),warningCompact:m("warning-compact",60569),passCompact:m("pass-compact",60570),important:m("important",60571),importantCompact:m("important-compact",60572),rocketCompact:m("rocket-compact",60573),unpin:m("unpin",60574),addCompact:m("add-compact",60575),attachCompact:m("attach-compact",60576),beakerCompact:m("beaker-compact",60577),checkCompact:m("check-compact",60578),checklistCompact:m("checklist-compact",60579),chevronDownCompact:m("chevron-down-compact",60580),chevronLeftCompact:m("chevron-left-compact",60581),chevronRightCompact:m("chevron-right-compact",60582),chevronUpCompact:m("chevron-up-compact",60583),circleFilledCompact:m("circle-filled-compact",60584),circleSmallFilledCompact:m("circle-small-filled-compact",60585),closeCompact:m("close-compact",60586),collapseAllCompact:m("collapse-all-compact",60587),commentCompact:m("comment-compact",60588),commentUnresolvedCompact:m("comment-unresolved-compact",60589),debugConnectedCompact:m("debug-connected-compact",60590),debugDisconnectCompact:m("debug-disconnect-compact",60591),editCompact:m("edit-compact",60592),fileMediaCompact:m("file-media-compact",60593),gitFetch:m("git-fetch",60594),lightbulbCompact:m("lightbulb-compact",60595),loadingCompact:m("loading-compact",60596),passFilledCompact:m("pass-filled-compact",60597),projectCompact:m("project-compact",60598),refreshCompact:m("refresh-compact",60599),searchCompact:m("search-compact",60600),sessionInProgressCompact:m("session-in-progress-compact",60601),syncCompact:m("sync-compact",60602),terminalCompact:m("terminal-compact",60603),vmPending:m("vm-pending",60604),worktreeCompact:m("worktree-compact",60605),developerTools:m("developer-tools",60606),cloudCompact:m("cloud-compact",60607),agentCompact:m("agent-compact",60608),askCompact:m("ask-compact",60609),settingsCompact:m("settings-compact",60610),vmCompact:m("vm-compact",60611),runCompact:m("run-compact",60612),gitPullRequestComment:m("git-pull-request-comment",60613),gitPullRequestError:m("git-pull-request-error",60614),rightPanelHide:m("right-panel-hide",60615),rightPanelShow:m("right-panel-show",60616),vscodeInsidersOutline:m("vscode-insiders-outline",60617),vscodeOutline:m("vscode-outline",60618),voiceMode:m("voice-mode",60619),voiceModeCompact:m("voice-mode-compact",60620),micDownload:m("mic-download",60621),micDownloadCompact:m("mic-download-compact",60622),voiceModeDownload:m("voice-mode-download",60623),voiceModeDownloadCompact:m("voice-mode-download-compact",60624),googleGemini:m("google-gemini",60625),kimi:m("kimi",60626),microsoft:m("microsoft",60627),fish1Happy:m("fish1-happy",60628),fish1Neutral:m("fish1-neutral",60629),fish1Sad:m("fish1-sad",60630),fish1VerySad:m("fish1-very-sad",60631),fish2Happy:m("fish2-happy",60632),fish2Neutral:m("fish2-neutral",60633),fish2Sad:m("fish2-sad",60634),fish2VerySad:m("fish2-very-sad",60635),fish3Happy:m("fish3-happy",60636),fish3Neutral:m("fish3-neutral",60637),fish3Sad:m("fish3-sad",60638),fish3VerySad:m("fish3-very-sad",60639),fish4Happy:m("fish4-happy",60640),fish4Neutral:m("fish4-neutral",60641),fish4Sad:m("fish4-sad",60642),fish4VerySad:m("fish4-very-sad",60643),personVoice:m("person-voice",60644),personVoiceCompact:m("person-voice-compact",60645),personVoiceFilled:m("person-voice-filled",60646),personVoiceFilledCompact:m("person-voice-filled-compact",60647)};var k7={dialogError:m("dialog-error","error"),dialogWarning:m("dialog-warning","warning"),dialogInfo:m("dialog-info","info"),dialogClose:m("dialog-close","close"),treeItemExpanded:m("tree-item-expanded","chevron-down"),treeFilterOnTypeOn:m("tree-filter-on-type-on","list-filter"),treeFilterOnTypeOff:m("tree-filter-on-type-off","list-selection"),treeFilterClear:m("tree-filter-clear","close"),treeItemLoading:m("tree-item-loading","loading"),menuSelection:m("menu-selection","check"),menuSubmenu:m("menu-submenu","chevron-right"),menuBarMore:m("menubar-more","more"),scrollbarButtonLeft:m("scrollbar-button-left","triangle-left"),scrollbarButtonRight:m("scrollbar-button-right","triangle-right"),scrollbarButtonUp:m("scrollbar-button-up","triangle-up"),scrollbarButtonDown:m("scrollbar-button-down","triangle-down"),toolBarMore:m("toolbar-more","more"),quickInputBack:m("quick-input-back","arrow-left"),dropDownButton:m("drop-down-button",60084),symbolCustomColor:m("symbol-customcolor",60252),exportIcon:m("export",60332),workspaceUnspecified:m("workspace-unspecified",60355),newLine:m("newline",60394),thumbsDownFilled:m("thumbsdown-filled",60435),thumbsUpFilled:m("thumbsup-filled",60436),gitFetch:m("git-fetch",60445),lightbulbSparkleAutofix:m("lightbulb-sparkle-autofix",60447),debugBreakpointPending:m("debug-breakpoint-pending",60377),chatImport:m("chat-import",60550),chatExport:m("chat-export",60551)},th={...ck,...k7};var uk;(n=>{function o(e){return!!e&&typeof e=="object"&&typeof e.id=="string"}n.isThemeColor=o})(uk||={});var zu;(S=>{S.iconNameSegment="[A-Za-z0-9]+",S.iconNameExpression="[A-Za-z0-9-]+",S.iconModifierExpression="~[A-Za-z]+",S.iconNameCharacter="[A-Za-z0-9~-]";let r=new RegExp(`^(${S.iconNameExpression})(${S.iconModifierExpression})?$`);function i(C){let _=r.exec(C.id);if(!_)return i(th.error);let[,T,w]=_,W=["codicon","codicon-"+T];return w&&W.push("codicon-modifier-"+w.substring(1)),W}S.asClassNameArray=i;function s(C){return i(C).join(" ")}S.asClassName=s;function a(C){return"."+i(C).join(".")}S.asCSSSelector=a;function l(C){return!!C&&typeof C=="object"&&typeof C.id=="string"&&(typeof C.color>"u"||uk.isThemeColor(C.color))}S.isThemeIcon=l;let d=new RegExp(`^\\$\\((${S.iconNameExpression}(?:${S.iconModifierExpression})?)\\)$`);function c(C){let _=d.exec(C);if(!_)return;let[,T]=_;return{id:T}}S.fromString=c;function u(C){return{id:C}}S.fromId=u;function p(C,_){let T=C.id,w=T.lastIndexOf("~");return w!==-1&&(T=T.substring(0,w)),_&&(T=`${T}~${_}`),{id:T}}S.modify=p;function g(C){let _=C.id.lastIndexOf("~");if(_!==-1)return C.id.substring(_+1)}S.getModifier=g;function h(C,_){return C.id===_.id&&C.color?.id===_.color?.id}S.isEqual=h;function y(C){return C?.id===th.file.id}S.isFile=y;function I(C){return C?.id===th.folder.id}S.isFolder=I})(zu||={});var qI=new RegExp(`\\$\\(${zu.iconNameExpression}(?:${zu.iconModifierExpression})?\\)`,"g"),D7=new RegExp(`(\\\\)?${qI.source}`,"g");function pk(o){return o.replace(D7,(n,e)=>e?n:`\\${n}`)}var Phe=new RegExp(`\\\\${qI.source}`,"g");var Ehe=new RegExp(`(\\s)?(\\\\)?${qI.source}(\\s)?`,"g");var khe=new RegExp(`\\$\\(${zu.iconNameCharacter}+\\)`,"g");var nh=class o{static lift(n){let e=new o(n.value,n);return e.uris=n.uris,e.baseUri=n.baseUri?v.revive(n.baseUri):void 0,e}constructor(n="",e=!1){if(this.value=n,typeof this.value!="string")throw Mv("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+=BI(this.supportThemeIcons?pk(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+=`
${M7(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(Un(e),"g");return n.replace(t,(r,i)=>n.charAt(i-1)!=="\\"?`\\${r}`:r)}};function BI(o){return o.replace(/[\\`*_{}[\]()#+!~]/g,"\\$&").replace(/^([ \t]*)-/gm,"$1\\-")}function Xs(o){return o.replace(/[\\\]]/g,"\\$&")}function M7(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}`}var rh="agents/",O7=8,gk=48,L7=8,fk=100,zl=class{constructor(n,e){this._copilotApiService=n;this._logService=e}async generateBranchName(n){let e=await this._generateBranchNameHint(n)??U7(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=N7(r).slice(0,gk).replace(/-+$/g,""),r.length<L7){this._logService.warn("Generated branch name is too short after normalization, discarding.");return}return r}catch(t){this._logService.warn("[AgentBranchNameGenerator] 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 r=`${`${n.branchPrefix??""}${rh}`}${e??n.sessionId}`,i=e?`${r}-${n.sessionId.substring(0,O7)}`:r;for(let s=0;s<fk;s++){let a=s===0?r:e&&s===1?i:`${i}-${e?s:s+1}`;if(!n.branchNameCollides||!await n.branchNameCollides(a))return a}throw new Error(`Unable to find an available branch name after checking ${fk} candidates`)}};zl=A([b(0,gt),b(1,O)],zl);function N7(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 U7(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,gk).replace(/-+$/g,"");return e.length>0?e:void 0}var mk="copilot.worktree.branchName",hk="copilot.worktree.path",Kl="copilot.worktree.repositoryRoot",Gl=class extends Error{constructor(e,t){super(t?f(2482,null,t):f(2481,null,e.fsPath));this.workingDirectory=e;this.reason=t;this.name="SessionWorkingDirectoryMissingError"}},F7=25;function H7(o){return v.joinPath(o,"..",`${ue(o.fsPath)}.worktrees`)}function yk(o,n=""){let e=o;return n&&e.startsWith(n)&&(e=e.substring(n.length)),e.startsWith(rh)&&(e=e.substring(rh.length)),e.replace(/\//g,"-")}function vk(o){return f(2480,null,ot(o))+`

`}function $7(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:F(),content:n},...t.responseParts];e[0]={...t,responseParts:i}}return e}var jl=class extends x{constructor(e,t,r,i,s){super();this._gitService=t;this._sessionDataService=i;this._logService=s;this._createdWorktrees=new Map;this._pendingFirstTurnAnnouncements=new Map;this._pending=new Set;this._logLabel="AgentHost";this._sequencer=new Ze;this._worktreeCreationSequencer=new Ze;this._branchNameGenerator=e??new zl(r,this._logService)}get createdWorktreeSessionIds(){return[...this._createdWorktrees.keys()]}notePending(e){this._pending.add(e)}clearPending(e){this._pending.delete(e)}isWorkingDirectoryPending(e){return this._pending.has(e)}getResolvedWorktree(e){return this._createdWorktrees.get(e)?.worktree}async resolveOnFirstSend(e){return this._sequencer.queue(e.sessionId,async()=>{try{return await this.resolveWorkingDirectory(e)}finally{this.clearPending(e.sessionId)}})}async resolveIsolationConfig(e){let t=e.workingDirectory?await this._getGitInfo(e.workingDirectory):void 0,r=ae({type:"string",title:f(2469,null),description:f(2474,null),enum:t?["folder","worktree"]:["folder"],enumLabels:t?[f(2470,null),f(2472,null)]:[f(2470,null)],enumDescriptions:t?[f(2471,null),f(2473,null)]:[f(2471,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,u;if(t){let p=s==="folder";l=s==="worktree"?t.defaultBranch.name:t.currentBranch,d=s==="worktree"&&typeof e.config?.branch=="string"?e.config.branch:l,a=ae({type:"string",title:f(2467,null),description:f(2468,null),enum:[l],enumLabels:[l],default:l,enumDynamic:!p,readOnly:p,sessionMutable:!1}),c=ae({type:"string",title:f(2475,null),description:f(2476,null),readOnly:!0,sessionMutable:!1}),u=ae({type:"array",title:f(2477,null),description:f(2478,null),items:{type:"string",title:f(2479,null)},readOnly:!0,sessionMutable:!1})}return{isolationProperty:r,branchProperty:a,worktreeBranchPrefixProperty:c,worktreeIncludeFilesProperty:u,isolationValue:s,branchDefault:l,branchValue:d}}async branchCompletions(e,t){if(!e)return{items:[]};let r=await this._gitService.getBranches(e,{pattern:["refs/heads"],sort:"committerdate"});return{items:sP(r.map(s=>s.name),{query:t,limit:F7}).map(s=>({value:s,label:s}))}}async resolveWorkingDirectory(e){let{config:t,workingDirectory:r,sessionId:i,sessionUri:s,prompt:a,githubToken:l}=e;if(t?.isolation!=="worktree"||!r||typeof t.branch!="string")return r;let d=this._createdWorktrees.get(i);if(d)return d.worktree;let c=await this._gitService.getRepositoryRoot(r);if(!c)return r;let u=H7(c),p=typeof t.worktreeBranchPrefix=="string"?t.worktreeBranchPrefix:void 0,g=t.branch,{branchName:h,worktree:y,baseBranch:I}=await this._worktreeCreationSequencer.queue(c.toString(),async()=>{let C=await this._branchNameGenerator.generateBranchName({sessionId:i,message:a,githubToken:l,branchPrefix:p,branchNameCollides:async w=>{if(await this._gitService.branchExists(c,w).catch(()=>!0))return!0;let W=v.joinPath(u,yk(w,p));return W7(W.fsPath)}}),_=v.joinPath(u,yk(C,p)),T=await this._resolveBranchStartPoint(c,g);return await qo.mkdir(u.fsPath,{recursive:!0}),await this._gitService.addWorktree(c,_,C,T),{branchName:C,worktree:_,baseBranch:T}}),S=Array.isArray(t.worktreeIncludeFiles)&&t.worktreeIncludeFiles.every(C=>typeof C=="string")?t.worktreeIncludeFiles:void 0;if(S?.length)try{await this._gitService.copyWorktreeIncludeFiles(c,y,S)}catch(C){this._logService.warn(`[${this._logLabel}:${i}] Failed to copy worktree include files: ${Vl(C)}`)}this._createdWorktrees.set(i,{repositoryRoot:c,worktree:y}),this._pendingFirstTurnAnnouncements.set(i,vk(h));try{await this._writeWorktreeMetadata(s,{branchName:h,baseBranch:I,worktreePath:y,repositoryRoot:c})}catch(C){this._logService.warn(`[${this._logLabel}:${i}] Failed to persist worktree branch metadata: ${Vl(C)}`)}return y}async resolveWorkingDirectoryForResume(e,t,r){return this._sequencer.queue(t,()=>this._resolveWorkingDirectoryForResume(e,t,r))}async _resolveWorkingDirectoryForResume(e,t,r){if(r.scheme!==ne.file)return r;try{return await qo.access(r.fsPath),r}catch{}let i=await this._readWorktreeMetadata(e).catch(()=>{});if(await this._isSessionArchived(e)){if(i?.repositoryRoot)try{return await qo.access(i.repositoryRoot.fsPath),this._logService.info(`[${this._logLabel}:${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(`[${this._logLabel}:${t}] Cannot resume archived session: working directory '${r.fsPath}' is missing and no usable repository-root fallback was found`),new Gl(r)}let a;if(i?.worktreePath&&i.repositoryRoot){let{branchName:l,worktreePath:d,repositoryRoot:c}=i,u=await this._recreateWorktree(t,{branchName:l,worktreePath:d,repositoryRoot:c});if(u.ok)return this._logService.info(`[${this._logLabel}:${t}] Recreated missing worktree '${d.fsPath}' for a live session on resume`),d;a=u.reason}throw this._logService.warn(`[${this._logLabel}:${t}] Cannot resume: working directory '${r.fsPath}' is missing and its worktree could not be recreated${a?`: ${a}`:""}`),new Gl(r,a)}takePendingAnnouncement(e){let t=this._pendingFirstTurnAnnouncements.get(e);return t!==void 0&&this._pendingFirstTurnAnnouncements.delete(e),t}async applyRestoreAnnouncement(e,t){let r=await this._readWorktreeMetadata(e).catch(()=>{});return r?.branchName?$7(t,vk(r.branchName)):t}async removeCreatedWorktree(e){return this._sequencer.queue(e,()=>this._removeCreatedWorktree(e))}async _removeCreatedWorktree(e){this.clearPending(e);let t=this._createdWorktrees.get(e);if(t)try{await this._gitService.removeWorktree(t.repositoryRoot,t.worktree)}catch(r){this._logService.warn(`[${this._logLabel}:${e}] Failed to remove worktree '${t.worktree.fsPath}': ${Vl(r)}`)}finally{this._createdWorktrees.delete(e)}}async removeAllCreatedWorktrees(){await Promise.all(this.createdWorktreeSessionIds.map(e=>this.removeCreatedWorktree(e)))}async cleanupWorktreeOnArchive(e,t){return this._sequencer.queue(t,()=>this._cleanupWorktreeOnArchive(e,t))}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 qo.access(s.fsPath)}catch{this._createdWorktrees.delete(t);return}if(!await this._gitService.branchExists(a,i).catch(()=>!1)){this._logService.info(`[${this._logLabel}:${t}] Skipping worktree cleanup: branch '${i}' is missing`);return}if(await this._gitService.hasUncommittedChanges(s).catch(()=>!0))try{await this._gitService.commitAll(s,f(2483,null))}catch(c){this._logService.warn(`[${this._logLabel}:${t}] Failed to commit uncommitted changes in '${s.fsPath}': ${Vl(c)}`);return}try{await this._gitService.removeWorktree(a,s),this._logService.info(`[${this._logLabel}:${t}] Removed worktree '${s.fsPath}' on archive`)}catch(c){this._logService.warn(`[${this._logLabel}:${t}] Failed to remove worktree '${s.fsPath}' on archive: ${Vl(c)}`)}finally{this._createdWorktrees.delete(t)}}async recreateWorktreeOnUnarchive(e,t){return this._sequencer.queue(t,()=>this._recreateWorktreeOnUnarchive(e,t))}async _recreateWorktreeOnUnarchive(e,t){let r=await this._readWorktreeMetadata(e).catch(()=>{});if(!r?.worktreePath||!r.repositoryRoot)return;try{await qo.access(r.worktreePath.fsPath);return}catch{}let{branchName:i,worktreePath:s,repositoryRoot:a}=r;await this._recreateWorktree(t,{branchName:i,worktreePath:s,repositoryRoot:a})}async _recreateWorktree(e,t){let{branchName:r,worktreePath:i,repositoryRoot:s}=t;if(!await this._gitService.branchExists(s,r).catch(()=>!1)){let l=f(2484,null,r);return this._logService.info(`[${this._logLabel}:${e}] Cannot recreate worktree: branch '${r}' is missing`),{ok:!1,reason:l}}try{return await qo.mkdir(v.joinPath(i,"..").fsPath,{recursive:!0}),await this._gitService.addExistingWorktree(s,i,r),this._createdWorktrees.set(e,{repositoryRoot:s,worktree:i}),this._logService.info(`[${this._logLabel}:${e}] Recreated worktree '${i.fsPath}'`),{ok:!0}}catch(l){let d=Vl(l);return this._logService.warn(`[${this._logLabel}:${e}] Failed to recreate worktree '${i.fsPath}': ${d}`),{ok:!1,reason:d}}}async readWorktreeMetadata(e){return this._readWorktreeMetadata(e)}async resolveWorktreeProject(e){let t=await this._readWorktreeMetadata(e).catch(()=>{});return t?.repositoryRoot?zI(t.repositoryRoot):void 0}createdWorktreeProject(e){let t=this._createdWorktrees.get(e);return t?zI(t.repositoryRoot):void 0}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)??{name:i,startPoint:i};return{currentBranch:i,defaultBranch:s}}async _resolveBranchStartPoint(e,t){let r=await this._gitService.getDefaultBranch(e);return r?.name===t?r.startPoint:t}async _writeWorktreeMetadata(e,t){let r=this._sessionDataService.openDatabase(e);try{let i=[r.object.setMetadata(mk,t.branchName),r.object.setMetadata(hk,t.worktreePath.toString()),r.object.setMetadata(Kl,t.repositoryRoot.toString())];t.baseBranch&&i.push(r.object.setMetadata(bi,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(mk),t.object.getMetadata(hk),t.object.getMetadata(Kl)]);if(!r)return;let a=i?v.parse(i):void 0,l=s?v.parse(s):void 0;return{branchName:r,worktreePath:a,repositoryRoot:l}}finally{t.dispose()}}async _isSessionArchived(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(!t)return!1;try{let[r,i]=await Promise.all([t.object.getMetadata(or),t.object.getMetadata(Fr)]);return r!==void 0?r==="true":i==="true"}finally{t.dispose()}}};jl=A([b(1,$e),b(2,gt),b(3,nt),b(4,O)],jl);function zI(o){return{uri:o,displayName:ue(o.fsPath)||o.toString()}}function Sk(o){return o?zI(v.parse(o)):void 0}function Vl(o){return o instanceof Error?o.message:String(o)}async function W7(o){try{return await qo.access(o),!0}catch{return!1}}import{Worker as q7}from"worker_threads";var Di=class extends x{constructor(e){super();this._logService=e;this._workerFailures=0;this._nextId=1;this._pending=new Map}async computeDiffCounts(e,t,r=JA){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=Nt.asFileUri("vs/platform/agentHost/node/diffWorkerMain.js").fsPath,t=new q7(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()}};Di=A([b(0,O)],Di);function Ck(o){return o.after?.uri??o.before?.uri}function VI(o,n,e,t,r){let i=e.firstKind!=="create",s=e.lastKind!=="delete";return{...i?{before:{uri:v.file(e.firstFilePath).toString(),content:{uri:Ii(o,e.firstToolCallId,e.firstFilePath,"before")}}}:{},...s?{after:{uri:v.file(e.terminalPath).toString(),content:{uri:Ii(n,e.lastToolCallId,e.lastFilePath,"after")}}}:{},diff:{added:t,removed:r}}}async function Ik(o,n,e,t){if(!t)return jI([{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(Ck));if(s.some(y=>y.kind==="rename"||a.has(v.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 I;y.kind==="rename"&&y.originalPath?(I=d.get(y.originalPath)??y.originalPath,d.set(y.filePath,I),d.delete(y.originalPath)):(I=d.get(y.filePath)??y.filePath,d.set(y.filePath,I)),u&&y.turnId===t.changedTurnId&&u.add(I);let S=c.get(I);S?(S.terminalPath=y.filePath,S.lastToolCallId=y.toolCallId,S.lastFilePath=y.filePath,S.lastKind=y.kind):c.set(I,{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=>[Ck(y),y])),g=[],h=[];for(let[y,I]of c){if(u&&!u.has(y)){let S=v.file(I.terminalPath).toString(),C=p.get(S);C&&g.push(C);continue}h.push((async()=>{let S;if(I.firstKind==="create")S="";else{let T=await n.readFileEditContent(I.firstToolCallId,I.firstFilePath);S=T?.beforeContent?new TextDecoder().decode(T.beforeContent):""}let C;if(I.lastKind==="delete")C="";else{let T=await n.readFileEditContent(I.lastToolCallId,I.lastFilePath);C=T?.afterContent?new TextDecoder().decode(T.afterContent):""}if(S===C)return;let _=await e.computeDiffCounts(S,C);g.push(VI(o,o,I,_.added,_.removed))})())}return await Promise.allSettled(h),i&&g.push(...t.previousDiffs),g}async function jI(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 h=await d.db.readFileEditContent(l.firstToolCallId,l.firstFilePath);u=h?.beforeContent?new TextDecoder().decode(h.beforeContent):""}let p;if(l.lastKind==="delete")p="";else{let h=await c.db.readFileEditContent(l.lastToolCallId,l.lastFilePath);p=h?.afterContent?new TextDecoder().decode(h.afterContent):""}if(u===p)return;let g=await n.computeDiffCounts(u,p);s.push(VI(d.sessionUri,c.sessionUri,l,g.added,g.removed))})());return await Promise.allSettled(a),s}async function bk(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 g=await n.readFileEditContent(d.firstToolCallId,d.firstFilePath);c=g?.beforeContent?new TextDecoder().decode(g.beforeContent):""}let u;if(d.lastKind==="delete")u="";else{let g=await n.readFileEditContent(d.lastToolCallId,d.lastFilePath);u=g?.afterContent?new TextDecoder().decode(g.afterContent):""}if(c===u)return;let p=await e.computeDiffCounts(c,u);a.push(VI(o,o,d,p.added,p.removed))})());return await Promise.allSettled(l),a}var Vu="checkpoint.workingDir",Jl=class extends x{constructor(e,t,r){super();this._sessionDataService=e;this._gitService=t;this._logService=r;this._sequencer=new Ze;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(Ws);if(i)return i;let s=this._sanitizedSessionId(e),a=HC(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(Ws,a),await r.object.setMetadata(Vu,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(Ws),r.object.getMetadata(Vu),r.object.getTurnCheckpointRef(t),r.object.getPreviousCheckpointRef(t)]);if(a)return a;if(!i||!s)return;let d=v.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 g=await this._gitService.captureWorkingTreeAsTree(d);if(!g)return;let h=await this._gitService.revParse(c,`${p}^{tree}`);if(h&&h===g)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),I=await this._nextTurnNumber(r.object),S=HC(y,I),C=await this._gitService.commitTree(c,g,p,`Agent host session ${y} - turn ${I}`);return C?(await this._gitService.updateRef(c,S,C),await r.object.setTurnCheckpointRef(t,S),this._logService.trace(`[AgentHostCheckpoint] Captured turn ${I} for ${e.toString()} at ${S}`),S):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(Ws)]);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(Ws)}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(Vu),t.object.getMetadata(Ws),t.object.getAllCheckpointRefs()]);if(!r)return;let a=v.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 M.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};Jl=A([b(0,nt),b(1,$e),b(2,O)],Jl);var Mi=B("agentHostChangesetSubscriptionService");var Yl=B("agentHostChangesetOperationService");var Ql=B("agentHostReviewService");function ju(o){return`refs/agents/${o}/reviewed`}function oh(o,n){return n==="branch"?Fo(o):No(o)}function B7(o){return o==="branch"?Sl:wu}function GI(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 z7(o){let n=o?.status==="ready"?o.files.map(e=>e.edit):void 0;return GI(n)}function V7(o){return GI(o)}function KI(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 Bo=class extends x{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 Ze;this._debouncedDiffTimers=this._register(new Ee);this._perTurnDebouncedDiffTimers=this._register(new Ee);this._activeStaticComputes=new Set;this._pendingMaterialization=new Set;this._diffComputeService=this._register(new Di(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(Fo(e)),this._stateManager.registerChangeset(Uo(e)),this._stateManager.registerChangeset(No(e))}restoreStaticChangeset(e,t,r){let i=this._stateManager.registerChangeset(oh(e,t));this._publishChangesetDiffs(e,i,r)}parsePersistedStaticChangesets(e,t){let r=KI(t.branchRaw,e,"branch",this._logService),i=KI(t.sessionRaw,e,"session",this._logService)??KI(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,$s,JSON.stringify(t))}getListMetadataKeys(e){if(!(this._stateManager.getSessionSummary(e)?.changes||this._stateManager.getChangesetState(No(e))?.status==="ready"))return Vg}computeListEntryChanges(e,t){if(this._stateManager.getSessionState(e))return;let r=t[$s];if(r!==void 0)try{return JSON.parse(r)}catch{return}let i=this._stateManager.getChangesetState(Fo(e)),s=z7(i);if(s)return this.persistChangesSummary(e,s),s;let a=t[Sl],l=t[Cl];if(a===void 0&&l===void 0)return;let d=this.parsePersistedStaticChangesets(e,{branchRaw:a,legacyRaw:l}),c=V7(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(oh(e,t));i&&i.files.length>0||this.restoreStaticChangeset(e,t,r)}refreshChangesetCatalog(e){let t=this._stateManager.getSessionState(e);if(!t||t?.lifecycle==="creationFailed")return;let r=mA(e,t);this._stateManager.setSessionChangesets(e,r)}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=rt(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(yg(e,t)),i;try{i=this._sessionDataService.openDatabase(v.parse(e))}catch(s){return this._logService.warn(`[AgentHostChangesetService] Failed to open session database for turn diff: ${e}`,s),this._stateManager.dispatchServerAction(r,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:s instanceof Error?s.message:String(s)}}),r}try{let s=await this._computeTurnDiffsPreferCheckpoint(e,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(gA(e,t,r)),s;try{s=this._sessionDataService.openDatabase(v.parse(e))}catch(a){return this._logService.warn(`[AgentHostChangesetService] Failed to open session database for compare-turns diff: ${e}`,a),this._stateManager.dispatchServerAction(i,{type:"changeset/statusChanged",status:"error",error:{errorType:"computeFailed",message:a instanceof Error?a.message:String(a)}}),i}try{let a=v.parse(e),[l,d]=await Promise.all([this._checkpointService.getTurnCheckpointPair(a,t).then(p=>p?.current),this._checkpointService.getTurnCheckpointPair(a,r)]);if(!l||!d){let p=!l&&!d?"both turns":l?"modified turn":"original turn";return this._stateManager.dispatchServerAction(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(Uo(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)?.workingDirectories?.[0];if(!t)return;let r;try{r=v.parse(t)}catch{return}return this._gitService.computeSessionFileDiffs(r,{sessionUri:e})}async _computeTurnDiffsPreferCheckpoint(e,t,r){let i=await this._checkpointService.getTurnCheckpointPair(v.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 bk(e,t,this._diffComputeService,r)}async _resolveWorkingDirectory(e){let t=await e.getMetadata(Vu);return t?v.parse(t):void 0}onToolCallEditsApplied(e,t){this._scheduleDebouncedDiffComputation(e,t),this._hasSubscription(e,yg(e,t))&&this._scheduleDebouncedTurnDiffComputation(e,t)}onTurnComplete(e,t){this._cancelDebouncedDiffComputation(e),t!==void 0&&(this._cancelDebouncedTurnDiffComputation(e,t),this._hasSubscription(e,yg(e,t))&&this._scheduleTurnRecompute(e,t)),this._hasSubscription(e,Uo(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,Ft(()=>{this._debouncedDiffTimers.deleteAndDispose(e),this._scheduleStaticRecompute(e,"branch",t),this._scheduleStaticRecompute(e,"session",t)},Bo._DIFF_DEBOUNCE_MS))}_cancelDebouncedDiffComputation(e){this._debouncedDiffTimers.deleteAndDispose(e)}_scheduleDebouncedTurnDiffComputation(e,t){let r=`${e}\0${t}`;this._perTurnDebouncedDiffTimers.set(r,Ft(()=>{this._perTurnDebouncedDiffTimers.deleteAndDispose(r),this._scheduleTurnRecompute(e,t)},Bo._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=oh(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=oh(e,t);this._activeStaticComputes.add(s);let a=i??this._stateManager.getChangesetState(s)?.status,l;try{l=this._sessionDataService.openDatabase(v.parse(e))}catch(d){this._logService.warn(`[AgentHostChangesetService] Failed to open session database for ${t} diff computation: ${e}`,d),this._restoreStaticChangesetStatus(s,a),this._activeStaticComputes.delete(s),this._stateManager.onChangesetLivenessChanged();return}this._stateManager.registerChangeset(s);try{let d=await this._tryComputeGitDiffs(e,l.object,t);if(!d){if(t==="branch"){this._logService.debug(`[AgentHostChangesetService] Branch git diff unavailable for ${e}; preserving cached changeset. previousStatus=${a??"unknown"} cachedFiles=${this._stateManager.getChangesetState(s)?.files.length??0}`),this._restoreStaticChangesetStatus(s,a);return}let u=this._openPeerChatSources(e);try{if(u.length>0){let p=[{sessionUri:e,db:l.object},...u.map(g=>({sessionUri:g.sessionUri,db:g.ref.object}))];d=await jI(p,this._diffComputeService)}else{let p;if(r){let g=this._readPreviousChangesetDiffs(s);g&&(p={changedTurnId:r,previousDiffs:[...g]})}d=await Ik(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,B7(t),JSON.stringify(d)),t==="branch"){this._persistSessionFlag(e,Cl,JSON.stringify(d));let u=GI(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=Zn(i.repoRoot,v.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(!Re(i.resource))try{let s=this._sessionDataService.openDatabase(v.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=(Re(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)?.workingDirectories?.[0];if(!i)return;let s;try{s=v.parse(i)}catch{return}if(r==="session"){let l=this._latestTurnIdAcrossChats(e);if(!l)return;let d=v.parse(e),[c,u]=await Promise.all([this._checkpointService.getBaselineCheckpointRef(d),this._checkpointService.getTurnCheckpointPair(d,l)]);if(!c||!u)return;try{return await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:e,fromRef:c,toRef:u.current})}catch(p){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,p);return}}let a=await this._resolveBranchBaseBranch(e,t);try{return await this._gitService.computeSessionFileDiffs(s,{sessionUri:e,baseBranch:a})}catch(l){this._logService.warn(`[AgentHostChangesetService] git-driven ${r} diff computation failed; falling back to edit-tracker`,l);return}}async _resolveBranchBaseBranch(e,t){let r=await t.getMetadata(bi),i=bt(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}`),zg(r,i)}async _computeReviewedInfo(e,t){let r=this._stateManager.getSessionState(e)?.workingDirectories?.[0];if(!r)return;let i;try{i=v.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(v.parse(e));i.object.setMetadata(t,r).catch(s=>{this._logService.warn(`[AgentHostChangesetService] Failed to persist ${t}`,s)}).finally(()=>{i.dispose()})}};Bo=A([b(0,Ce),b(1,O),b(2,nt),b(3,$e),b(4,Kr),b(5,Ue),b(6,Yl),b(7,Mi),b(8,Ql)],Bo);var Xl=B("agentHostFileMonitorService"),JI=Object.freeze(["**/.git","**/.git/lfs/**","**/.git/logs/**","**/.git/objects/**","**/.git/subtree-cache/**","**/.git/**/*.lock","**/.git/**/FETCH_HEAD","**/.git/**/fsmonitor--daemon/**","**/*.watchman-cookie-*"]);function j7(o){return[...o].sort()}function K7(o){let n=Object.create(null);for(let e of o)n[e]=!0;return js(n)}var Zr=class extends x{constructor(e,t){super();this._fileService=e;this._logService=t;this._entries=this._register(new Ee);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=j7(r.excludes??JI),a=r.debounceMs??Zr._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),U(()=>{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 G;try{let a=s.add(new ht),l=new Set,d=K7(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=Ft(()=>{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(re.isEqualOrParent(r,e.folder)&&!this._isExcluded(e,r))return!0;return!1}_isExcluded(e,t){let r=re.basename(t),i=re.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 re.removeTrailingPathSeparator(re.normalizePath(e))}_key(e,t,r){return`${re.getComparisonKey(e)}\0${r}\0${t.join(`
`)}`}};Zr=A([b(0,xe),b(1,O)],Zr);var Oi="agentHost.git",Li="agentHost.github",sh={[Oi]:!0,[Li]:!0},eo=B("agentHostGitStateService");var YI=class extends Ia{constructor(e,t){super();this._create=e;this._destroy=t}createReferencedObject(e){return this._create(e),e}destroyReferencedObject(e){this._destroy(e)}},Zl=class extends x{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 Ee);this._watchInterestCollection=new YI(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 Ee);this._rootUris=new Map;this._activeSessionRoots=new Map;this._rootActiveSessions=new Map;this._unresolvedActiveSessions=new Set;this._watchAttachmentSequencer=new Ze;this._activeTurnSequencer=new Ze}trackSessionChanges(e,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(Uo(e)),this.untrackSessionChanges(No(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(Fo(e))||this._watchInterestReferences.has(Uo(e))||this._watchInterestReferences.has(No(e))}_attachWatcherIfPossible(e){this._watchAttachmentSequencer.queue(e,async()=>{if(!this._shouldAttachSession(e))return;let t=this._configurationService.getEffectiveWorkingDirectory(e);if(!t){this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}let r;try{r=v.parse(t)}catch(s){this._logService.warn(`[ChangesetFileMonitorCoordinator] Failed to parse working directory URI for ${e}: ${t}`,s),this._pendingWatchInterest.add(e),this._releaseSessionRoot(e);return}if(this._sessionRoot.has(e)&&this._sessionWorkingDirectory.get(e)===t){this._pendingWatchInterest.delete(e);return}let 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=v.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:JI,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=v.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=It(e);if(r)return this._configurationService.getEffectiveWorkingDirectory(r.parentSession.toString())}};Zl=A([b(0,Ce),b(1,Ue),b(2,Xl),b(3,$e),b(4,eo),b(5,O)],Zl);var ed=class extends x{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(Zl)),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[Sl],sessionRaw:t[wu],legacyRaw:t[Cl]}),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=rt(t);if(!r&&!de(t)&&this._stateManager.getSessionState(t)){this._addSubscription(t,Fo(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=rt(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=rt(r);if(i){if(i.kind==="unknown")throw new Error(`Cannot subscribe to unknown changeset resource: ${r}`);this._stateManager.getSessionState(i.sessionUri)||await t(v.parse(i.sessionUri))}}async tryHandleSubscribe(e,t){let r=e.toString(),i=rt(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)}};ed=A([b(0,Ce),b(1,Yl),b(2,Il),b(3,Mi),b(4,eo),b(5,we)],ed);var G7=60,J7=G7*60,QI=J7*24,pSe=QI*7,fSe=QI*30,gSe=QI*365;function _k(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 ah={DateTimeFormat(o,n){return new Xe(()=>{try{return new Intl.DateTimeFormat(o,n)}catch{return new Intl.DateTimeFormat(void 0,n)}})},Collator(o,n){return new Xe(()=>{try{return new Intl.Collator(o,n)}catch{return new Intl.Collator(void 0,n)}})},Segmenter(o,n){return new Xe(()=>{try{return new Intl.Segmenter(o,n)}catch{return new Intl.Segmenter(void 0,n)}})},Locale(o,n){return new Xe(()=>{try{return new Intl.Locale(o,n)}catch{return new Intl.Locale(ti,n)}})},NumberFormat(o,n){return new Xe(()=>{try{return new Intl.NumberFormat(o,n)}catch{return new Intl.NumberFormat(void 0,n)}})}};var Tk=new Xe(()=>{let o=ah.Collator(void 0,{numeric:!0,sensitivity:"base"}).value;return{collator:o,collatorIsNumeric:o.resolvedOptions().numeric}}),SSe=new Xe(()=>({collator:ah.Collator(void 0,{numeric:!0}).value})),CSe=new Xe(()=>({collator:ah.Collator(void 0,{numeric:!0,sensitivity:"accent"}).value}));function Y7(o,n,e=!1){let t=o||"",r=n||"",i=Tk.value.collator.compare(t,r);return Tk.value.collatorIsNumeric&&i===0&&t!==r?t<r?-1:1:i}function lh(o,n,e){let t=o.toLowerCase(),r=n.toLowerCase(),i=Q7(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=Y7(t,r);return l!==0?l:t.localeCompare(r)}function Q7(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 ch=0,wk=[ch,[]];function Rk(o,n,e,t){if(!o||!n)return wk;let r=o.length,i=n.length;if(r<i)return wk;let s=o.toLowerCase();return X7(n,e,i,o,s,r,t)}function X7(o,n,e,t,r,i,s){let a=[],l=[];for(let p=0;p<e;p++){let g=p*i,h=g-i,y=p>0,I=o[p],S=n[p];for(let C=0;C<i;C++){let _=C>0,T=g+C,w=T-1,W=h+C-1,R=_?a[w]:0,L=y&&_?a[W]:0,D=y&&_?l[W]:0,z;!L&&y?z=0:z=Z7(I,S,t,r,C,D),z&&L+z>=R&&(s||y||r.startsWith(n,C))?(l[T]=D+1,a[T]=L+z):(l[T]=ch,a[T]=R)}}let d=[],c=e-1,u=i-1;for(;c>=0&&u>=0;){let p=c*i+u;l[p]===ch||(d.push(u),c--),u--}return[a[e*i-1],d.reverse()]}function Z7(o,n,e,t,r,i){let s=0;if(!e9(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=t9(e.charCodeAt(r-1));a?s+=a:Ul(e.charCodeAt(r))&&i===0&&(s+=2)}return s}function e9(o,n){return o===n?!0:o==="/"||o==="\\"?n==="/"||n==="\\":!1}function t9(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 uh=Object.freeze({score:0}),dh=1<<18,XI=1<<17,ZI=65536;function n9(o,n,e,t){let r=t.values?t.values:[t];return kn({[t.normalized]:{values:r.map(s=>({value:s.normalized,expectContiguousMatch:s.expectContiguousMatch})),label:o,description:n,allowNonContiguousMatches:e}})}function ph(o,n,e,t,r){if(!o||!n.normalized)return uh;let i=t.getItemLabel(o);if(!i)return uh;let s=t.getItemDescription(o),a=n9(i,s,e,n),l=r[a];if(l)return l;let d=r9(i,s,t.getItemPath(o),n,e);return r[a]=d,d}function r9(o,n,e,t,r){let i=!e||!t.containsPathSeparator;return e&&(Fe?t.pathNormalized===e:So(t.pathNormalized,e))?{score:dh,labelMatch:[{start:0,end:o.length}],descriptionMatch:n?[{start:0,end:n.length}]:void 0}:t.values&&t.values.length>1?o9(o,n,e,t.values,i,r):Dk(o,n,e,t,i,r)}function o9(o,n,e,t,r,i){let s=0,a=[],l=[];for(let d of t){let{score:c,labelMatch:u,descriptionMatch:p}=Dk(o,n,e,d,r,i);if(c===ch)return uh;s+=c,u&&a.push(...u),p&&l.push(...p)}return{score:s,labelMatch:Ak(a),descriptionMatch:Ak(l)}}function Dk(o,n,e,t,r,i){if(r||!n){let[s,a]=Rk(o,t.normalized,t.normalizedLowercase,i&&!t.expectContiguousMatch);if(s){let l=Pm(t.normalized,o),d;if(l){d=XI;let c=Math.round(t.normalized.length/o.length*100);d+=c}else d=ZI;return{score:d+s,labelMatch:l||xk(a)}}}if(n){let s=n;e&&(s=`${n}${He}`);let a=s.length,l=`${s}${o}`,[d,c]=Rk(l,t.normalized,t.normalizedLowercase,i&&!t.expectContiguousMatch);if(d){let u=xk(c),p=[],g=[];return u.forEach(h=>{h.start<a&&h.end>a?(p.push({start:0,end:h.end-a}),g.push({start:h.start,end:a})):h.start>=a?p.push({start:h.start-a,end:h.end-a}):g.push(h)}),{score:d,labelMatch:p,descriptionMatch:g}}}return uh}function xk(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 Ak(o){let n=o.sort((r,i)=>r.start-i.start),e=[],t;for(let r of n)!t||!i9(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 i9(o,n){return!(o.end<n.start||n.end<o.start)}function Mk(o,n,e,t,r,i){let s=ph(o,e,t,r,i),a=ph(n,e,t,r,i),l=s.score,d=a.score;if((l===dh||d===dh)&&l!==d)return l===dh?-1:1;if(l>ZI||d>ZI){if(l!==d)return l>d?-1:1;if(l<XI&&d<XI){let I=s9(s.labelMatch,a.labelMatch);if(I!==0)return I}let h=r.getItemLabel(o)||"",y=r.getItemLabel(n)||"";if(h.length!==y.length)return h.length-y.length}if(l!==d)return l>d?-1:1;let c=Array.isArray(s.labelMatch)&&s.labelMatch.length>0,u=Array.isArray(a.labelMatch)&&a.labelMatch.length>0;if(c&&!u)return-1;if(u&&!c)return 1;let p=Pk(o,s,r),g=Pk(n,a,r);return p&&g&&p!==g?g>p?-1:1:a9(o,n,e,r)}function Pk(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 s9(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 a9(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?lh(r,i,e.normalized):s&&a&&s!==a?lh(s,a,e.normalized):c&&u&&c!==u?lh(c,u,e.normalized):0}function Ek(o){return o.startsWith('"')&&o.endsWith('"')}var l9=" ";function Ok(o){typeof o!="string"&&(o="");let n=o.toLowerCase(),{pathNormalized:e,normalized:t,normalizedLowercase:r}=kk(o),i=e.indexOf(He)>=0,s=Ek(o),a,l=o.split(l9);if(l.length>1)for(let d of l){let c=Ek(d),{pathNormalized:u,normalized:p,normalizedLowercase:g}=kk(d);p&&(a||(a=[]),a.push({original:d,originalLowercase:d.toLowerCase(),pathNormalized:u,normalized:p,normalizedLowercase:g,expectContiguousMatch:c}))}return{original:o,originalLowercase:n,pathNormalized:e,normalized:t,normalizedLowercase:r,values:a,containsPathSeparator:i,expectContiguousMatch:s}}function kk(o){let n;X?n=o.replace(/\//g,He):n=o.replace(/\\/g,He);let e=n.replace(/[\*\u2026\s"]/g,"").replace(/(?<=.)#$/,"");return{pathNormalized:n,normalized:e,normalizedLowercase:e.toLowerCase()}}var Lk=50;function d9(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 eb=class{constructor(n){this._workingDirectory=n}getItemLabel(n){return Se(n)}getItemDescription(n){let e=Zn(this._workingDirectory,n);if(!e)return;let t=e.lastIndexOf("/");return t>0?e.slice(0,t):void 0}getItemPath(n){return Zn(this._workingDirectory,n)??n.fsPath}},fh=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)?.workingDirectories?.[0];if(!t)return[];let r=v.parse(t);if(r.scheme!==ne.file)return[];let i=d9(n.text,n.offset);if(!i)return[];let s;try{s=await this._workspaceFiles.getFiles(r,e)}catch(u){if(un(u))return[];throw u}if(e.isCancellationRequested||s.length===0)return[];let a=new eb(r),l=Ok(i.token),d=Object.create(null),c;if(!l.normalized)c=s.slice(0,Lk);else{let u=s.filter(p=>ph(p,l,!0,a,d).score>0);u.sort((p,g)=>Mk(p,g,l,!0,a,d)),c=u.slice(0,Lk)}return c.map(u=>{let p=Se(u);return{insertText:i.triggerChar+p,rangeStart:i.rangeStart,rangeEnd:i.rangeEnd,attachment:{type:"resource",uri:u.toString(),label:p,displayKind:"document"}}})}};var Ku=class{constructor(n){this.type=1,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n}},Ni=class{constructor(n){this.type=2,this.ctime=Date.now(),this.mtime=Date.now(),this.size=0,this.name=n,this.entries=new Map}},td=class extends x{constructor(){super(...arguments);this.memoryFdCounter=0;this.fdMemory=new Map;this._onDidChangeCapabilities=this._register(new E);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._capabilities=525318;this.root=new Ni("");this._onDidChangeFile=this._register(new E);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 Ne("file not found","EntryNotFound")}readFileStream(e){let t=this._lookupAsFile(e,!1).data,r=bo(i=>$.concat(i.map(s=>$.wrap(s))).buffer);return r.end(t),r}async writeFile(e,t,r){let i=Se(e),s=this._lookupParentDirectory(e),a=s.entries.get(i);if(a instanceof Ni)throw Ne("file is directory","EntryIsADirectory");if(!a&&!r.create)throw Ne("file not found","EntryNotFound");if(a&&r.create&&!r.overwrite)throw Ne("file exists already","EntryExists");if(a||(a=new Ku(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=Do(t),s=i&&!!t.append;if(r){if(r instanceof Ni)throw Ne("file is directory","EntryIsADirectory")}else{if(!i)throw Ne("file not found","EntryNotFound");let l=Se(e),d=this._lookupParentDirectory(e);r=new Ku(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 Ne("No file with that descriptor open","Unavailable");if(!a.file.data)return Promise.resolve(0);let l=$.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 Ne("No file with that descriptor open","Unavailable");let l=$.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 Ne("file exists already","EntryExists");let i=this._lookup(e,!1),s=this._lookupParentDirectory(e),a=this._lookupParentDirectory(t),l=Se(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=Ut(e),i=Se(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 Ne("file exists already","EntryExists");let t=Se(e),r=Ut(e),i=this._lookupAsDirectory(r,!1),s=new Ni(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 Ni&&(a=i.entries.get(s)),!a){if(t)return;throw Ne("file not found","EntryNotFound")}i=a}return i}_lookupAsDirectory(e,t){let r=this._lookup(e,t);if(r instanceof Ni)return r;throw Ne("file not a directory","EntryNotADirectory")}_lookupAsFile(e,t){let r=this._lookup(e,t);if(r instanceof Ku)return r;throw Ne("file is a directory","EntryIsADirectory")}_lookupParentDirectory(e){let t=Ut(e);return this._lookupAsDirectory(t,!1)}watch(e,t){return x.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 c9=[];function Nk(o,n,e){n instanceof cr||(n=new cr(n,[],!!e)),c9.push([o,n])}var Uk=B("labelService");var Ju="vscode-agent-host",Fk="_ah";function Hk(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(Fk,_o($.fromString(JSON.stringify(e)),!1,!0)),v.from({scheme:Ju,authority:n,path:o.path||"/",query:t.toString(),fragment:o.fragment})}function $k(o){if(o.scheme!==Ju)return o;let n,e=o.query?new URLSearchParams(o.query).get(Fk):null;if(e)try{n=JSON.parse(xn(e).toString())}catch{n=void 0}return!n||typeof n.scheme!="string"?v.from({scheme:ne.file,path:o.path,fragment:o.fragment}):v.from({scheme:n.scheme,authority:n.authority||void 0,path:o.path,query:n.query||"",fragment:o.fragment})}var Wk={scheme:Ju,formatting:{label:"${path}",separator:"/"}};var Yu=class o extends x{constructor(e=o._DEFAULT_CONNECTION_GRACE_MS){super();this._connectionGraceMs=e;this.capabilities=263178;this._onDidChangeCapabilities=this._register(new E);this.onDidChangeCapabilities=this._onDidChangeCapabilities.event;this._onDidChangeFile=this._register(new E);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new E);this.onDidWatchError=this._onDidWatchError.event;this._authorities=new Map;this._onDidChangeConnection=this._register(new E)}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 ht},this._authorities.set(e,r));let i=r;return this._onDidChangeConnection.fire(e),U(()=>{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=Ft(()=>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 G,i=r.add(new ht),s=e.authority,a={channel:Je,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 g=this._authorities.get(s)?.connections.at(-1);if(g===l)return;i.clear(),l=void 0;let h=g?.watchResource;if(!g||!h)return;d=!0;let y=g;try{let I=await h.call(y,a);if(r.isDisposed){I.dispose();return}let S=this._authorities.get(s);if(!S||S.connections.at(-1)!==y){I.dispose();return}let C=I.onDidChange(_=>this._onDidChangeFile.fire(_.map(T=>({resource:this._encodeUri(T.resource,e.authority),type:T.type}))));i.value=U(()=>{C.dispose(),I.dispose()}),l=y}catch(I){this._onDidWatchError.fire(I instanceof Error?I.message:String(I))}finally{d=!1,c&&(c=!1,u())}};return r.add(this._onDidChangeConnection.event(p=>{p===s&&u()})),u(),r}async stat(e){let 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(v.parse(s.uri),e.authority).path}catch(s){throw this._mapError(s,"EntryNotFound")}}async readdir(e){return(await this._listDirectory(e.authority,e)).map(r=>[r.name,r.type==="directory"?2:1])}async readFile(e){let t=await this._getConnection(e.authority);try{let r=this._decodeUri(e),i=await t.resourceRead(r);return i.encoding==="base64"?xn(i.data).buffer:$.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:Je,uri:s.toString(),data:$.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:Je,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:Je,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:Je,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:Je,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 Ne(`Connection for ${e.authority} does not support resourceRequest`,"Unavailable");let i=this._decodeUri(e);try{await r.resourceRequest({channel:Je,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(Ne(`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(Ne(`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 N&&e.code===ge.PermissionDenied?Ne(e.message,"NoPermissions"):Ne(e instanceof Error?e.message:String(e),t)}_resolve(e,t){return e.resourceResolve({channel:Je,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")}}},mh=class extends Yu{_decodeUri(n){return $k(n)}_encodeUri(n,e){return Hk(n,e)}};var Xu="vscode-synced-customization",u9=B("agentHostFileSystemService"),Qu=class extends x{constructor(e,t){super();this._fileService=e;this._syncedCustomizationProviderRegistered=!1;this._fsProvider=this._register(new mh),this._register(e.registerProvider(Ju,this._fsProvider)),this._register(t.registerFormatter(Wk))}registerAuthority(e,t){return this._fsProvider.registerAuthority(e,t)}ensureSyncedCustomizationProvider(){if(!this._syncedCustomizationProviderRegistered){this._syncedCustomizationProviderRegistered=!0;let e=this._register(new td);this._register(this._fileService.registerProvider(Xu,e))}}};Qu=A([b(0,xe),b(1,Uk)],Qu);Nk(u9,Qu,1);var hh=class extends x{constructor(e){super();this._getAgent=e;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(e,t){let r=Dm(e.text,e.offset);if(!r)return[];let i=typeof e.channel=="string"?v.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 Vs(l,c.slashCommandName)&&!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:eE({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"&&!p9(e)&&t.name!==e.name&&(r=`${e.name}:${t.name}`),{slashCommandName:r,name:t.name,description:t.description,uri:t.uri}}};function p9(o){return o.uri.startsWith(Xu+":")}import*as Bk from"child_process";var f9=new Xe(async()=>(await import("@vscode/ripgrep-universal")).rgPath.replace(/\bnode_modules\.asar\b/,"node_modules.asar.unpacked"));function nd(){return f9.value}var g9=5e4,m9=3e4,rd=class extends x{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+m9};this._cache.set(r,l),a.catch(()=>{this._cache.get(r)===l&&this._cache.delete(r)})}if(t.isCancellationRequested)throw new K;return t===ke.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 nd();return new Promise(r=>{let i=e.fsPath,s=["--files","--hidden","--no-require-git","--follow","--no-config","--glob","!.git"],a;try{a=Bk.spawn(t,s,{cwd:i})}catch(h){this._logService.warn(`[AgentHostWorkspaceFiles] Failed to spawn ripgrep: ${h}`),r([]);return}this._activeChildren.add(a);let l=[],d="",c=!1,u=!1,p=h=>{u||(u=!0,this._activeChildren.delete(a),r(h))};a.stdout.setEncoding("utf8"),a.stdout.on("data",h=>{if(c)return;d+=h;let y;for(;(y=d.indexOf(`
`))>=0;){let I=d.slice(0,y).replace(/\r$/,"");if(d=d.slice(y+1),!!I&&(l.push(v.joinPath(e,I)),l.length>=g9)){c=!0;try{a.kill()}catch{}break}}}),a.stderr.setEncoding("utf8");let g="";a.stderr.on("data",h=>{g+=h}),a.on("error",h=>{this._logService.warn(`[AgentHostWorkspaceFiles] ripgrep error: ${h}`),p([])}),a.on("close",()=>{if(!c&&d.length>0){let h=d.replace(/\r$/,"");h&&l.push(v.joinPath(e,h)),d=""}g&&this._logService.trace(`[AgentHostWorkspaceFiles] ripgrep stderr: ${g}`),p(l)})})}};rd=A([b(0,O)],rd);var zk={serverTools:{listChanged:!0},serverResources:{},sampling:{}},yh={capabilities:zk};function rb(o,n,e){return`mcp-top-level:${o}:${n}:${e}`}function ob(o,n,e){return`mcp://${o}/${encodeURIComponent(n)}/${encodeURIComponent(e)}`}var Ui=class extends x{constructor(e,t){super();this._options=e;this._stateManager=t;this._live=yn(this,new Map);this.runtimeStates=Qc(this,r=>{let i=new Map;for(let s of this._live.read(r).values()){let a=s.topLevelId??this._options.resolveChildId(s.serverName);a!==void 0&&i.set(a,{state:s.state,channel:this._buildChannel(s.serverName,s.state)})}return i})}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,t.enabled));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}serverEnablement(){let e=[];for(let t of this._live.get().values()){let r=t.topLevelId??this._options.resolveChildId(t.serverName);r!==void 0&&e.push({serverName:t.serverName,customizationId:r,enabled:t.enabled})}return e}channelForServer(e){let t=this._live.get().get(e);if(!(!t||t.state.kind!=="ready"))return this._buildChannel(e,t.state)}applyAll(e){sr(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){sr(t=>this._applyOne(e,t))}markStarting(e){sr(t=>{for(let r of e){let i=this._live.get().get(r)?.state.kind;i==="ready"||i==="authRequired"||i==="starting"||this._applyOne({name:r,state:{kind:"starting"}},t)}})}_applyOne(e,t){let r=this._live.get().get(e.name),i=this._stateForUpdate(r?.state,e.state),s=e.enabled??r?.enabled??!0,a=r?.topLevelId;if(a===void 0){let l=this._options.resolveChildId(e.name);if(l!==void 0){this._setLiveEntry(e.name,{serverName:e.name,state:i,enabled:s,topLevelId:void 0},t),this._options.emit({type:"session/mcpServerStateChanged",id:l,state:i,channel:this._buildChannel(e.name,i)});return}a=this._mintTopLevelId(e.name)}this._setLiveEntry(e.name,{serverName:e.name,state:i,enabled:s,topLevelId:a},t),this._options.emit({type:"session/customizationUpdated",customization:this._buildTopLevel(a,e.name,i,s)})}remove(e){sr(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 rb(this._options.providerId,this._options.sessionId,e)}_buildChannel(e,t){if(t.kind==="ready")return ob(this._options.providerId,this._options.sessionId,e)}_buildTopLevel(e,t,r,i){let s=this._buildChannel(t,r),a=this._options.capabilities?{capabilities:this._options.capabilities}:yh;return{type:"mcpServer",id:e,uri:this._mintTopLevelId(t),name:t,enabled:Zs(this._stateManager.getSessionState(this._options.sessionUri.toString())?.customizations??[]).find(l=>l.id===e)?.enabled??i,state:r,channel:s,mcpApp:a}}};Ui=A([b(1,Ce)],Ui);function vh(o,n){return jk(o).find(e=>e.name===n)?.id}function jk(o){let n=[];for(let e of o)if(e.type==="mcpServer")n.push(e);else for(let t of e.children??[])t.type==="mcpServer"&&n.push(t);return n}function Zs(o){let n=[];for(let e of o)if(e.type==="mcpServer")n.push(e);else for(let t of e.children??[])t.type==="mcpServer"&&n.push(e.enabled?t:{...t,enabled:!1});return n}function Sh(o,n){let e=new Map(Zs(n).map(t=>[t.id,t.enabled]));return o.map(t=>{if(t.type==="mcpServer")return Vk(t,e);let r=!1,i=t.children?.map(s=>{let a=s.type==="mcpServer"?Vk(s,e):s;return r||=a!==s,a});return r?{...t,children:i}:t})}function Vk(o,n){let e=n.get(o.id);return e===void 0||e===o.enabled?o:{...o,enabled:e}}function ib(o,n){return jk(o).find(e=>e.id===n)?.name}function Kk(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 sb="vscode-agent-client";function od(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 v.from({scheme:sb,authority:n,path:`/${r}/${e}${i}`,query:o.query||void 0,fragment:o.fragment||void 0})}function Gk(o){let n=o.path,e=o.query||void 0,t=o.fragment||void 0,r=n.indexOf("/",1);if(r===-1)return v.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 v.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)),v.from({scheme:i,authority:l||void 0,path:d,query:e,fragment:t})}var id=class extends x{constructor(e,t,r){super();this._stateManager=e;this._gitStateService=t;this._changesetSubscriptions=r;this._handlerRegistrations=this._register(new Ee);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)),U(()=>{this._handlerRegistrations.deleteAndDispose(e),e.dispose()})}getOperations(e,t,r,i){if(!r){let a=this._stateManager.getSessionState(e);if(r=bt(a?._meta),!r)return[]}i||(i=br(this._stateManager.getSessionState(e)?._meta));let s=rt(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=bt(a?._meta),!r)return}if(!i){let a=this._stateManager.getSessionState(e);i=br(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 N(Dt,`Changeset not found: ${e.channel}`);let r=t.operations?.find(l=>l.id===e.operationId);if(!r)throw new N(oe.InvalidParams,`Unknown operation '${e.operationId}' on changeset ${e.channel}`);if(r.status==="disabled")throw new N(oe.InvalidParams,`Operation '${e.operationId}' is disabled on changeset ${e.channel}`);let i=rt(e.channel);if(i&&this._stateManager.hasActiveTurn(i.sessionUri))throw new N(oe.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 N(oe.InvalidParams,`Operation '${e.operationId}' does not support scope '${s}' (allowed: ${r.scopes.join(", ")})`);let a=this._changesetOperationHandlers.get(e.operationId);if(!a)throw new N(oe.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,ke.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:h9(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),U(()=>{this._changesetOperationHandlers.get(e)===t&&this._changesetOperationHandlers.delete(e)})}};id=A([b(0,Ce),b(1,eo),b(2,Mi)],id);function h9(o){let n=De(o);return o instanceof Error?{errorType:o.name,message:n,stack:o.stack}:{errorType:"Error",message:n}}var ad=B("agentHostOctoKitService"),Jk="2022-11-28",Yk=500,y9=`mutation EnableAutoMerge($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
	enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
		pullRequest { id }
	}
}`,sd=class{constructor(n,e,t){this._logService=e;this._endpoint=t;this.pullRequestSearchEtags=new bn(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 g=c.data?.node_id;return{url:p,number:u,nodeId:typeof g=="string"?g: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(y9,{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":Jk};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(g){throw r.aborted||this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Network error`,g),g}let c=d.headers.get("x-ratelimit-remaining");if(c){let g=v9(c);g!==void 0&&g<100&&this._logService.warn(`[AgentHostOctoKitService] ${e} ${a} - GitHub API rate limit low: ${g} 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 g=await d.text().catch(()=>{}),h=this._formatErrorResponseBody(g);throw this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Status: ${d.status}${h?` - ${h}`:""}`),new Error(`GitHub API request failed: ${e} ${n} - ${d.status} ${d.statusText}${h?` - ${h}`:""}`)}try{return{data:await d.json(),statusCode:u,etag:p}}catch(g){throw this._logService.error(`[AgentHostOctoKit] ${e} ${a} - Failed to parse JSON`,g),g}}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":Jk},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>Yk?`${e.substring(0,Yk)}...`:e}};sd=A([b(1,O),b(2,wt)],sd);function v9(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 ld=class extends x{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 E);this.onDidRefreshSessionGitState=this._onDidRefreshSessionGitState.event;this._gitStateRefreshThrottler=this._register(new df);this._gitStateRefreshCancellationTokenSource=new dt;this._register(U(()=>this._gitStateRefreshCancellationTokenSource.dispose(!0)))}async attachSessionGitHubPullRequest(e){let t=this._stateManager.getSessionState(e);if(!t||t.lifecycle!=="ready")return;let r=br(this._stateManager.getSessionState(e)?._meta);if(!r?.owner||!r?.repo||r?.pullRequestUrl)return;let i=bt(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!=="creationFailed"){if(!t){let i=r?.workingDirectories?.[0];i&&(t=v.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;Oe(bt(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 mn(5e3,this._gitStateRefreshCancellationTokenSource.token)}catch(i){if(un(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=br(r),s={...i??{},...t};if(Oe(i,s))return;let a=Of(r,s);this._stateManager.setSessionMeta(e,a),await this._saveSessionState(e,Li,JSON.stringify(s))}async _setSessionGitState(e,t){let r=this._stateManager.getSessionState(e)?._meta,i=Mf(r,t);this._stateManager.setSessionMeta(e,i),await this._saveSessionState(e,Oi,JSON.stringify(t))}async _saveSessionState(e,t,r){if(this._stateManager.getSessionState(e)?.lifecycle==="creating")return;let s;try{s=this._sessionDataService.openDatabase(v.parse(e))}catch(a){this._logService.warn(`[AgentHostGitStateService][_saveSessionState] Failed to open session database for ${e}`,a);return}try{await s.object.setMetadata(t,r)}catch(a){this._logService.warn(`[AgentHostGitStateService][_saveSessionState] Failed to persist ${t}`,a)}finally{s.dispose()}}};ld=A([b(0,Ce),b(1,$e),b(2,ad),b(3,Hr),b(4,wt),b(5,O),b(6,nt)],ld);var Ch=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 S9=new Set,Ih=class{constructor(){this._subscriptions=new Map}getSessionSubscriptions(n){return this._subscriptions.get(n)??S9}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 C9=2e4,Fi=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=rt(n.channel);if(!r)throw new N(oe.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new N(Dt,`Session not found: ${i}`);let a=s.workingDirectories?.[0];if(!a)throw new N(oe.InternalError,`Session has no working directory: ${i}`);let l=v.parse(a),d=bt(s._meta);if(!d)throw new N(oe.InternalError,`Session's working directory is not a git repo: ${i}`);if(!await this._gitService.hasUncommittedChanges(l))return{message:{markdown:f(2033,null)}};this._throwIfCancelled(e);let u=this._gitHubEndpointService.getCopilotResource(),p=this._agentService.getAuthToken({resource:u.resource,scopes:u.scopes_supported});if(!p)throw new N(_r,f(2028,null),[u]);let g=await this._gitService.computeSessionFileDiffs(l,{sessionUri:i});if(!g||g.length===0)throw new N(oe.InternalError,f(2031,null));this._throwIfCancelled(e);let h;try{h=this._cleanCommitMessage(await this._copilotApiService.utilityChatCompletion(p,{messages:this._buildCommitMessagePrompt(l,d.branchName,g)},{signal:t}))}catch(y){throw this._throwIfCancelled(e),this._isAuthFailure(y)?new N(_r,f(2027,null),[u]):y}if(!h)throw new N(oe.InternalError,f(2032,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostCommitOperationHandler] Committing uncommitted changes for session ${i}`);try{await this._gitService.commitAll(l,h)}catch(y){throw this._throwIfCancelled(e),new N(oe.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(2030,null,h.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: ${Se(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>C9){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=v.parse(n);return e.scheme==="file"?e.fsPath:e.path||n}catch{return n}}_cleanCommitMessage(n){let e=n.trim().replace(/\r\n/g,`
`),t=/^```(?:text|gitcommit)?\s*([\s\S]*?)\s*```$/i.exec(e);return t&&(e=t[1].trim()),e}_isAuthFailure(n){if(n instanceof wr)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 N(oe.InternalError,f(2029,null))}};Fi=A([b(2,Hr),b(3,wt),b(4,$e),b(5,gt),b(6,O)],Fi);var dd=class extends x{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new G,r=s=>this._stateManager.getSessionState(s),i=this._instantiationService.createInstance(Fi,r,s=>this._onCommitted(s));return t.add(e.registerChangesetOperationHandler(Fi.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:Fi.OPERATION_COMMIT,label:f(2034,null),icon:"git-commit",group:"commit",scopes:["changeset"],status:"idle"}]}async _onCommitted(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};dd=A([b(0,Ce),b(1,we)],dd);var to=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=rt(n.channel);if(!r||r.kind!=="uncommitted")throw new N(oe.InvalidParams,`Not an uncommitted changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new N(Dt,`Session not found: ${i}`);if(n.target?.kind!=="resource")throw new N(oe.InvalidParams,`Operation '${to.OPERATION_DISCARD_CHANGES}' requires a resource target.`);let a=s.workingDirectories?.[0];if(!a)throw new N(oe.InternalError,`Session has no working directory: ${i}`);let l=v.parse(a),d=v.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 N(oe.InternalError,`Failed to discard changes: ${c instanceof Error?c.message:String(c)}`)}return{message:{markdown:f(2036,null,Se(d))}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new N(oe.InternalError,f(2035,null))}};to=A([b(1,$e),b(2,O)],to);var cd=class extends x{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){let t=new G,r=s=>this._stateManager.getSessionState(s),i=this._instantiationService.createInstance(to,r);return t.add(e.registerChangesetOperationHandler(to.OPERATION_DISCARD_CHANGES,i)),t}getOperations({changesetKind:e,gitState:t}){return e!=="uncommitted"||(t?.uncommittedChanges??0)<=0?[]:[{id:to.OPERATION_DISCARD_CHANGES,label:f(2037,null),confirmation:f(2038,null),icon:"discard",scopes:["resource"],status:"idle"}]}};cd=A([b(0,Ce),b(1,we)],cd);var I9=12e3,b9=4e3,vn=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=rt(n.channel);if(!r)throw new N(oe.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let i=r.sessionUri,s=this._getSessionState(i);if(!s)throw new N(Dt,`Session not found: ${i}`);let a=s.workingDirectories?.[0];if(!a)throw new N(oe.InternalError,`Session has no working directory: ${i}`);let l=br(s._meta);if(!l?.owner||!l?.repo)throw new N(oe.InternalError,`Session's working directory is not a GitHub-backed git repo: ${i}`);let d=v.parse(a),c=bt(s._meta),u=c?.branchName??await this._gitService.getCurrentBranch(d);if(!u)throw new N(oe.InternalError,`Could not determine current branch for ${d}`);let p=c?.baseBranchName??(await this._gitService.getDefaultBranch(d))?.name;if(!p)throw new N(oe.InternalError,`Could not determine base branch for ${d}`);let g=p,h=this._gitHubEndpointService.getRepoResource(),y=this._agentService.getAuthToken({resource:h.resource,scopes:h.scopes_supported});if(!y)throw new N(_r,f(2040,null),[h]);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(L){throw this._throwIfCancelled(e),new N(oe.InternalError,`Failed to commit changes before creating a pull request: ${L instanceof Error?L.message:String(L)}`)}}this._throwIfCancelled(e);let S=await this._gitService.computeSessionFileDiffs(d,{sessionUri:i,baseBranch:g});if(S===void 0)throw new N(oe.InternalError,f(2048,null));if(S!==void 0&&S.length===0)throw new N(oe.InternalError,f(2056,null));this._throwIfCancelled(e),this._logService.info(`[AgentHostPullRequestOperationHandler] Pushing branch ${u} for session ${i}`);let C=await this._gitService.hasUpstream(d,u);this._throwIfCancelled(e);try{await this._gitService.push(d,{ref:u,setUpstream:!C})}catch(L){throw this._throwIfCancelled(e),new N(oe.InternalError,`Failed to push branch '${u}': ${L instanceof Error?L.message:String(L)}`)}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,g,S,t,e);this._throwIfCancelled(e);let w=T?.title??this._formatTitle(u),W=T?.description??this._formatBody(u,g);this._logService.info(`[AgentHostPullRequestOperationHandler] Creating ${this._draft?"draft ":""}PR ${l.owner}/${l.repo} ${u} -> ${g}`);let R;try{R=await this._octoKitService.createPullRequest(l.owner,l.repo,w,W,u,g,this._draft,y,t)}catch(L){this._throwIfCancelled(e);let D;try{D=await this._octoKitService.findPullRequestByHeadBranch(l.owner,l.repo,u,y,t)}catch{throw this._throwIfCancelled(e),L}if(D)return this._throwIfCancelled(e),await this._finalize(D,!0,i,l.owner,l.repo,y,t,e);throw L}return this._throwIfCancelled(e),await this._finalize(R,!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(2042,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(2044,null);break;case"REBASE":i=f(2043,null);break;default:i=f(2041,null);break}if(e)switch(t){case"enabled":return f(2054,null,n.number,n.url,i);case"failed":return f(2055,null,n.number,n.url,r??"");default:return f(2053,null,n.number,n.url)}switch(t){case"enabled":return f(2050,null,n.number,n.url,i);case"failed":return f(2051,null,n.number,n.url,r??"");default:return this._draft?f(2052,null,n.number,n.url):f(2049,null,n.number,n.url)}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new N(oe.InternalError,f(2046,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(2047,null,n)}_formatBody(n,e){return f(2045,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=Sg(n.turns,{maxChars:I9}),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>b9){e.push("[file list truncated]");break}}return e.join(`
`)}_displayUri(n){try{let e=v.parse(n);return e.scheme==="file"?e.fsPath:e.path||n}catch{return n}}_parseTitleAndDescription(n){let e=n.trim().replace(/\r\n/g,`
`),t=/^```(?:markdown|md|text)?\s*([\s\S]*?)\s*```$/i.exec(e);if(t&&(e=t[1].trim()),!e)return;let r=e.split(`
`),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}}};vn=A([b(4,Hr),b(5,$e),b(6,ad),b(7,wt),b(8,gt),b(9,O)],vn);var ud=class extends x{constructor(e,t,r){super();this._stateManager=e;this._instantiationService=t;this._gitStateService=r}registerHandlers(e){this._registry=e;let t=new G,r=u=>this._stateManager.getSessionState(u),i=u=>this._onPullRequestCreated(u),s=this._instantiationService.createInstance(vn,!1,void 0,r,i),a=this._instantiationService.createInstance(vn,!0,void 0,r,i),l=this._instantiationService.createInstance(vn,!1,"MERGE",r,i),d=this._instantiationService.createInstance(vn,!1,"SQUASH",r,i),c=this._instantiationService.createInstance(vn,!1,"REBASE",r,i);return t.add(e.registerChangesetOperationHandler(vn.OPERATION_CREATE_PR,s)),t.add(e.registerChangesetOperationHandler(vn.OPERATION_CREATE_DRAFT_PR,a)),t.add(e.registerChangesetOperationHandler(vn.OPERATION_CREATE_PR_AUTO_MERGE,l)),t.add(e.registerChangesetOperationHandler(vn.OPERATION_CREATE_PR_AUTO_SQUASH,d)),t.add(e.registerChangesetOperationHandler(vn.OPERATION_CREATE_PR_AUTO_REBASE,c)),t.add({dispose:()=>{this._registry=void 0}}),t}getOperations({sessionKey:e,gitState:t,gitHubState:r}){if(this._stateManager.getSessionState(e)?.lifecycle==="creating"||r?.pullRequestUrl)return;let s=t?.outgoingChanges??0,a=t?.uncommittedChanges??0,l=s>0||a>0;if(!(!t?.hasGitHubRemote||!l))return[{id:"create-pr",label:f(2058,null),icon:"git-pull-request-create",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-merge",label:f(2059,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-squash",label:f(2061,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-pr-auto-rebase",label:f(2060,null),icon:"git-merge",group:"pull-request",scopes:["changeset"],status:"idle"},{id:"create-draft-pr",label:f(2057,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})}};ud=A([b(0,Ce),b(1,we),b(2,eo)],ud);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=rt(n.channel);if(!t)throw new N(oe.InvalidParams,`Not a changeset URI: ${n.channel}`);this._throwIfCancelled(e);let r=t.sessionUri,i=this._getSessionState(r);if(!i)throw new N(Dt,`Session not found: ${r}`);let s=i.workingDirectories?.[0];if(!s)throw new N(oe.InternalError,`Session has no working directory: ${r}`);let a=v.parse(s),d=bt(i._meta)?.branchName??await this._gitService.getCurrentBranch(a);if(!d)throw new N(oe.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 N(oe.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(2064,null)}}}_throwIfCancelled(n){if(n.isCancellationRequested)throw new N(oe.InternalError,f(2063,null))}};Hi=A([b(2,$e),b(3,O)],Hi);var pd=class extends x{constructor(e,t){super();this._stateManager=e;this._instantiationService=t}registerHandlers(e){this._registry=e;let t=new G,r=s=>this._stateManager.getSessionState(s),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({sessionKey:e,gitState:t}){if(!(this._stateManager.getSessionState(e)?.lifecycle==="creating"&&(t?.uncommittedChanges??0)>0)&&!(!t?.upstreamBranchName||(t?.outgoingChanges??0)===0))return[{id:Hi.OPERATION_SYNC,label:f(2065,null,t.outgoingChanges),icon:"sync",group:"sync",scopes:["changeset"],status:"idle"}]}async _onSynced(e){this._registry?.onDidChangeOperations(e),await this._registry?.refreshSessionGitState(e)}};pd=A([b(0,Ce),b(1,we)],pd);var fd=class extends x{constructor(e,t,r,i){super();this._stateManager=e;this._gitService=t;this._sessionDataService=r;this._logService=i;this._sequencer=new Ze;this._register(this._sessionDataService.onWillDeleteSessionData(s=>{s.waitUntil(this.disposeSessionData(s.session.toString()))}))}async setReviewState(e,t,r){let i=rt(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.workingDirectories?.[0])throw new Error(`Session has no working directory: ${i.sessionUri}`);let a=this._sessionDataService.openDatabase(v.parse(i.sessionUri)),l;try{l=await a.object.getMetadata(bi)}finally{a.dispose()}let d=v.parse(s.workingDirectories?.[0]),c=zg(l,bt(s._meta)?.baseBranchName);await this._sequencer.queue(i.sessionUri,async()=>{for(let u of t)await this._setReviewed(i.sessionUri,d,c,v.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=ju(this._sanitizedSessionId(e)),a=await this._gitService.revParse(i,s);if(!a)return;let l=ju(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=Zn(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!==Hs?await this._gitService.revParse(i,`${s}^{tree}`):Hs;if(!a)return;let l=ju(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)?.workingDirectories?.[0];if(!t)return;let r=await this._gitService.getRepositoryRoot(v.parse(t));if(r)try{let i=ju(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 M.id(e).replace(/[^a-zA-Z0-9_.-]/g,"-")}};fd=A([b(0,Ce),b(1,$e),b(2,nt),b(3,O)],fd);var w9=3e4,R9=["isolation","branch","worktreeBranchPrefix","worktreeIncludeFiles"];function ab(o){let n={...o};for(let e of R9)delete n[e];return n}var x9=3e4,A9=15e3,P9=(()=>{let o=process.env[KR],n=o!==void 0?parseInt(o,10):NaN;return Number.isFinite(n)&&n>=0?n:3e4})(),lb="peerChats",bh="peerChatBacking",_h=class extends x{constructor(e,t,r,i,s,a=aP,l,d=jg,c,u,p,g=[]){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._resourceWriteQueue=this._register(new si);this._onDidAction=this._register(new E);this.onDidAction=this._onDidAction.event;this._onDidNotification=this._register(new E);this.onDidNotification=this._onDidNotification.event;this._onMcpNotification=this._register(new E);this.onMcpNotification=this._onMcpNotification.event;this._providers=new Map;this._sessionToProvider=new Map;this._downloadProgressInterest=new Map;this._providerSubscriptions=this._register(new G);this._peerChatCatalogWrites=new Map;this._agents=yn("agents",[]);this._skillCompletionProviderRegistered=!1;this._resourceSubscribers=new Me;this._restoreSessionInFlight=new Map;this._restoreSubagentInFlight=new Map;this._pendingSubagentChats=new Map;this._pendingSubagentChatTimeouts=this._register(new Ee);this._pendingSubagentToolCalls=new Map;this._pendingSessionGc=this._register(new bc);this._pendingSessionRelease=this._register(new bc);this._resourceWatches=this._register(new Ee);this._clientDispatchQueues=new Map;this._logService.info("AgentService initialized"),this._authService=new Ch(e),this._stateManager=this._register(new hl(e,{hostBuildInfo:qR(this._productService),changesetStateRetention:{canEvict:w=>this._changesets?this._isChangesetEvictable(w):!1}})),this._register(this._stateManager.onDidEmitEnvelope(w=>this._onDidAction.fire(w))),this._register(this._stateManager.onDidEmitEnvelope(w=>this._trackPendingSubagentChatFromEnvelope(w))),this._register(this._stateManager.onDidEmitNotification(w=>this._onDidNotification.fire(w)));let h=this._register(new dl(this._stateManager,this._logService,this._rootConfigResource,g));this._configurationService=h;let y=c??this._register(new Zr(this._fileService,this._logService));bm(this._telemetryService,this._stateManager.rootState.config?.values);let I=new vi([O,this._logService],[Hr,this],[Tt,this._productService],[Ue,h],[Ce,this._stateManager],[Xl,y],[$e,this._gitService],[Pn,this._telemetryService],[nt,this._sessionDataService]),S=this._register(new il(I,!0));this._gitHubEndpointService=this._register(S.createInstance($l)),I.set(wt,this._gitHubEndpointService),this._register(this._gitHubEndpointService.onDidChange(()=>{this._stateManager.emitAuthRequired({resource:this._gitHubEndpointService.getCopilotResource().resource,reason:"required"})}));let C=S.createInstance(sd,p);I.set(ad,C);let _=u??S.createInstance(Ei,p);I.set(gt,_),this._gitStateService=this._register(S.createInstance(ld)),I.set(eo,this._gitStateService),I.set(Kr,this._checkpointService),this._changesetSubscriptions=S.createInstance(Ih),I.set(Mi,this._changesetSubscriptions),this._changesetOperationService=this._register(S.createInstance(id)),I.set(Yl,this._changesetOperationService),this._reviewService=this._register(S.createInstance(fd)),I.set(Ql,this._reviewService),this._changesets=this._register(S.createInstance(Bo)),I.set(Il,this._changesets),this._changesetCoordinator=this._register(S.createInstance(ed)),this._register(this._stateManager.onDidChangeSessionActiveTurn(w=>this._changesetCoordinator.onSessionTurnActiveChanged(w.session,w.active))),this._register(this._changesetOperationService.registerContribution(S.createInstance(dd))),this._register(this._changesetOperationService.registerContribution(S.createInstance(ud))),this._register(this._changesetOperationService.registerContribution(S.createInstance(pd))),this._register(this._changesetOperationService.registerContribution(S.createInstance(cd))),this._completions=this._register(S.createInstance(Nl));let T=this._register(S.createInstance(rd));this._register(this._completions.registerProvider(new fh(this._stateManager,T))),this._register(this._completions.registerProvider(new Om(w=>(this._stateManager.getSessionState(w)?.turns.length??0)>0))),this._terminalManager=this._register(S.createInstance(yl)),I.set(ur,this._terminalManager),this._localTurns=new Gm(this._sessionDataService,this._logService),this._sideEffects=this._register(S.createInstance(ql,this._stateManager,{getAgent:w=>this._findProviderForSession(w),sessionDataService:this._sessionDataService,localTurns:this._localTurns,agents:this._agents,copilotApiService:_,getGitHubCopilotToken:()=>this.getAuthToken({resource:this._gitHubEndpointService.getCopilotResource().resource,scopes:this._gitHubEndpointService.getCopilotResource().scopes_supported}),resolveWorkingDirectoryBeforeSend:w=>this._resolveWorkingDirectoryBeforeSend(w),resolveChatAttachmentTurns:w=>this._resolveChatAttachmentTurns(w),onTurnComplete:async w=>{let W=this._stateManager.getSessionState(w)?.workingDirectories?.[0];this._gitStateService.refreshSessionGitState(w,W?v.parse(W):void 0),this._gitStateService.attachSessionGitHubPullRequest(w.toString())}})),this._serverToolHost=new Jm(this._stateManager,WI(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}get agents(){return this._agents}setWorktreeIsolation(e){this._worktree=e,this._configurationService.setWorktreeIsolation(e),this._sideEffects.setWorktreeIsolation(e)}_toProviderConfig(e){return!this._worktree||!e.config?e:{...e,config:ab(e.config)}}async _resolveWorkingDirectoryBeforeSend(e){let t=M.id(e.session),r=this._configurationService.getEffectiveWorkingDirectory(e.session),i=r?v.parse(r):void 0;return this._worktree?.isWorkingDirectoryPending(t)?await this._resolveWorktreeBeforeSend({...e,sessionId:t,pickedFolderUri:i})??i:i?this._configurationService.resolveWorkingDirectoryForResume(e.session,i):void 0}async _resolveChatAttachmentTurns(e){let t=()=>(this._stateManager.getChatState(e)??this._stateManager.getDefaultChatState(e))?.turns,r=t();if(r)return r;let i=v.parse(de(e)?ce(e):e);if(!this._stateManager.getSessionState(i.toString()))await this.restoreSession(i);else{let s=this._findProviderForSession(i);s&&await this._restorePeerChats(s,i)}return t()??[]}async _resolveWorktreeBeforeSend(e){let{sessionId:t,pickedFolderUri:r}=e,i=this._worktree;if(!i)return;try{await i.resolveOnFirstSend({sessionUri:v.parse(e.session),sessionId:t,workingDirectory:r,config:this._configurationService.getSessionConfigValues(e.session),prompt:e.prompt,githubToken:this.getAuthToken({resource:this._gitHubEndpointService.getCopilotResource().resource,scopes:this._gitHubEndpointService.getCopilotResource().scopes_supported})})}catch(a){this._logService.warn(`[AgentService] worktree resolution failed for ${e.session}: ${De(a)}`)}let s=i.takePendingAnnouncement(t);return s!==void 0&&this._stateManager.dispatchServerAction(e.chat,{type:"chat/responsePart",turnId:e.turnId,part:{kind:"markdown",id:F(),content:s}}),i.getResolvedWorktree(t)}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 hh(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=Kk(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=M.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=>$R(this._stateManager.getSessionSummary(e.toString())?._meta),setSessionSpawnDepth:(e,t)=>this._stateManager.dispatchServerAction(e.toString(),{type:"session/metaChanged",_meta:WR(this._stateManager.getSessionSummary(e.toString())?._meta,t)})}}async _startSessionPrompt(e,t,r){let i={text:r,origin:{kind:"user"}},s={type:"chat/turnStarted",turnId:F(),startedAt:new Date().toISOString(),message:i};this._stateManager.dispatchServerAction(t.toString(),s),this._sideEffects.handleAction(t.toString(),s)}_getChatContext(e,t){let r=t?this._stateManager.getChatState(fi(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(),g=this._changesetCoordinator.getListMetadataKeys(p),h=g?{customTitle:!0,isRead:!0,[or]:!0,[Fr]:!0,[rr]:!0,[bh]:!0,[Kl]:!0,...sh,...g}:{customTitle:!0,isRead:!0,[or]:!0,[Fr]:!0,[rr]:!0,[bh]:!0,[Kl]:!0,...sh},y=await u.object.getMetadataObject(h);if(y[bh])return;let I=c;if(y.customTitle&&(I={...I,summary:y.customTitle}),y.isRead!==void 0&&(I={...I,isRead:y.isRead==="true"}),y[or]!==void 0?I={...I,isArchived:y[or]==="true"}:y[Fr]!==void 0&&(I={...I,isArchived:y[Fr]==="true"}),y[Oi])try{let C=JSON.parse(y[Oi]);I={...I,_meta:Mf(I._meta,C)}}catch(C){this._logService.warn(`[AgentService][listSessions] Failed to parse Git state for ${c.session}`,C)}if(y[Li])try{let C=JSON.parse(y[Li]);I={...I,_meta:Of(I._meta,C)}}catch(C){this._logService.warn(`[AgentService][listSessions] Failed to parse GitHub state for ${c.session}`,C)}y[rr]!==void 0&&(I={...I,_meta:Lf(I._meta,y[rr]==="true")});let S=Sk(y[Kl]);return S&&(I={...I,project:S}),this._changesetCoordinator.decorateListEntry(I,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,g=u.workingDirectories?.[0];return{...c,summary:u.title||c.summary,status:u.status,activity:u.activity,modifiedTime:Date.parse(u.modifiedAt),project:u.project?{uri:v.parse(u.project.uri),displayName:u.project.displayName}:c.project,workingDirectory:typeof g=="string"?v.parse(g):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()){if(a.has(c.resource)||Ir(c.resource))continue;let u=c.workingDirectories?.[0];l.push({session:v.parse(c.resource),startTime:Date.parse(c.createdAt),modifiedTime:Date.parse(c.modifiedAt),summary:c.title,status:c.status,activity:c.activity,workingDirectory:typeof u=="string"?v.parse(u):void 0,...c.project?{project:{uri:v.parse(c.project.uri),displayName:c.project.displayName}}:{},changes:c.changes,...c._meta!==void 0?{_meta:c._meta}:{}})}let d=l.length>0?[...s,...l]:s;return this._logService.trace(`[AgentService] listSessions returned ${d.length} sessions (${l.length} state-manager fallback)`),d}async createSession(e){let t=e?.provider??this._defaultProvider,r=t?this._providers.get(t):void 0;if(!r)throw new Error(`No agent provider registered for: ${t??"(none)"}`);if(e?.fork){let g=this._stateManager.getSessionState(e.fork.session.toString())?.turns.slice(0,e.fork.turnIndex+1)??[];if(g.length===0)e={...e,fork:void 0};else{let h=new Map;for(let I of g)h.set(I.id,F());let y=this._localTurns.resolveConcreteTurnId(pe(e.fork.session).toString(),e.fork.turnId);e={...e,fork:{...e.fork,turnIdMapping:h,...y!==void 0?{turnId:y}:{}}}}}if(e?.importConversation){let p=e.importConversation.turns.map(g=>({...g,id:F()}));e={...e,importConversation:{...e.importConversation,turns:p}}}let i=this._sideEffects.initialize(),s=await this._resolveCreatedSessionConfig(r,e),a=s?.values?.isolation==="worktree"&&!e?.fork&&!e?.importConversation;this._logService.trace("[AgentService] createSession: initializing auto-approver and creating session...");let[,l]=await Promise.all([i,this._createProviderSession(r,e,a)]),d=l.session;if(this._logService.trace("[AgentService] createSession: initialization complete"),this._cancelPendingSessionGc(d),this._cancelPendingSessionRelease(d),this._logService.trace(`[AgentService] createSession: provider=${r.id} model=${e?.model?.id??"(default)"}`),this._sessionToProvider.set(d.toString(),r.id),e?.progressToken){let p=this._downloadProgressInterest.get(r.id);p||(p=new Set,this._downloadProgressInterest.set(r.id,p)),p.add(d.toString())}this._logService.trace(`[AgentService] createSession returned: ${d.toString()}`);let c=await(r.getSessionCustomizations?r.getSessionCustomizations(d).catch(p=>{this._logService.error("[AgentService] createSession: failed to resolve initial customizations",p)}):Promise.resolve(void 0));if(e?.fork){let p=this._stateManager.getSessionState(e.fork.session.toString()),g=pe(e.fork.session).toString(),h=pe(d).toString(),y=[];if(p&&e.fork.turnIdMapping){let w=p.turns.slice(0,e.fork.turnIndex+1),W=e.fork.turnIdMapping;y=w.map(R=>({...R,id:W.get(R.id)??F()})),this._persistForkedLocalTurns(d.toString(),g,h,w,y,W)}let I=f(2069,null),S=p?.title,C=S?S.startsWith(I)?S:`${I}${S}`:f(2068,null),_=this._buildInitialSummary(r,d,e,l,C),T=this._stateManager.createSession(_);T.config=s,this._stateManager.seedDefaultChatTurns(_.resource,y),T.activeClients=e.activeClient?[e.activeClient]:[],c&&c.length>0&&(T.customizations=[...c]),y.length>0&&this._sideEffects.generateForkedTitle(_.resource,void 0,y,C,S)}else if(e?.importConversation){let p=[...e.importConversation.turns],g=this._buildImportedTitle(p),h=this._buildInitialSummary(r,d,e,l,g),y=this._stateManager.createSession(h);y.config=s,this._stateManager.seedDefaultChatTurns(h.resource,p),y.activeClients=e.activeClient?[e.activeClient]:[],c&&c.length>0&&(y.customizations=[...c]),p.length>0&&this._sideEffects.generateForkedTitle(h.resource,void 0,p,g)}else{let p=this._buildInitialSummary(r,d,e,l,""),g=this._stateManager.createSession(p,{emitNotification:!l.provisional});g.config=s,g.activeClients=e?.activeClient?[e.activeClient]:[],c&&c.length>0&&(g.customizations=[...c])}s?.values&&Object.keys(s.values).length>0&&!l.provisional&&this._persistConfigValues(d,s.values),this._changesetCoordinator.onSessionCreated(d.toString()),l.provisional||(this._persistWorkspaceless(d,zc(this._stateManager.getSessionSummary(d.toString())?._meta)),this._stateManager.dispatchServerAction(d.toString(),{type:"session/ready"}));let u=l.workingDirectory??e?.workingDirectory;return this._gitStateService.refreshSessionGitState(d.toString(),u),d}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,u;if(r?.sideChat){let h=this._resolveSideChatOrigin(e,r.sideChat);u=h.origin,c={...r,sideChat:{...r.sideChat,source:v.parse(h.sourceChat),...h.providerAnchorTurnId?{providerAnchorTurnId:h.providerAnchorTurnId}:{},...h.sourceContext?{sourceContext:h.sourceContext}:{},...h.partialResponse?{partialResponse:h.partialResponse}:{}}}}if(r?.fork){let h=r.fork.source.toString(),y=this._stateManager.getChatState(h),I=y??this._stateManager.getDefaultChatState(h),S=y?h:pe(h),C=I?.turns??[],_=C.findIndex(T=>T.id===r.fork.turnId);if(_<0)c={...r,fork:void 0};else{let T=C.slice(0,_+1),w=new Map;for(let L of T)w.set(L.id,F());a=T.map(L=>({...L,id:w.get(L.id)??F()})),this._persistForkedLocalTurns(i,S,t.toString(),T,a,w);let W=f(2069,null);d=I?.title||this._stateManager.getSessionState(i)?.title,l=d?d.startsWith(W)?d:`${W}${d}`:f(2067,null);let R=this._localTurns.resolveConcreteTurnId(S,r.fork.turnId);c={...r,fork:{...r.fork,turnIdMapping:w,...R!==void 0?{turnId:R}:{}}}}}let p=await this._createChat(s,t,c),g=p?.providerData;this._stateManager.addChat(i,t.toString(),{...l!==void 0?{title:l}:r?.title!==void 0?{title:r.title}:{},...a!==void 0?{turns:a}:{},...g!==void 0?{providerData:g}:{},...u!==void 0?{origin:u}:{}}),this._persistPeerChat(e,t,g,u),p?.backingSession&&this._markPeerChatBacking(p.backingSession,t),a&&a.length>0&&l!==void 0&&this._sideEffects.generateForkedTitle(i,t.toString(),a,l,d)}_resolveSideChatOrigin(e,t){let r=e.toString(),i=t.source.toString(),{sourceChatKey:s,sourceSessionKey:a,sourceState:l}=this._resolveSessionSourceChat(e,t.source);if(a!==r)throw new Error(`[AgentService] createChat: side chat source ${i} does not belong to session ${r}`);let d=l?.activeTurn?.id===t.turnId?l.activeTurn:void 0;if(!(l?.turns.some(I=>I.id===t.turnId)??!1)&&!d)throw new Error(`[AgentService] createChat: side chat source turn ${t.turnId} not found in ${i}`);let u=!d&&this._localTurns.isLocal(s,t.turnId),p=u?this._localTurns.resolveConcreteTurnId(s,t.turnId):void 0,g=vA(d),h=d||u?SA(l?.turns??[],t.turnId,d):void 0,y=t.selection?.text.trim()?t.selection:t.selection?(()=>{throw new Error("[AgentService] createChat: side chat selection text must be non-empty")})():void 0;return{origin:{kind:"sideChat",chat:s,turnId:t.turnId,...y?{selection:y}:{}},sourceChat:s,...y?{selection:y}:{},...p?{providerAnchorTurnId:p}:{},...h?{sourceContext:h}:{},...g?{partialResponse:g}:{}}}_resolveSessionSourceChat(e,t){let r=e.toString(),i=t.toString(),s=de(i)?ce(i):i,a=this._stateManager.getSessionState(r)?.defaultChat??pe(r),l=i===r?a:this._stateManager.getChatState(i)?i:Re(i)&&s===r?a:i;return{sourceSessionKey:s,sourceChatKey:l,sourceState:l===a?this._stateManager.getChatState(a)??this._stateManager.getDefaultChatState(r):this._stateManager.getChatState(l)}}async disposeChat(e,t){let r=e.toString(),i=this._findProviderForSession(e);this._sideEffects.clearQueuedMessageSenders(t.toString()),this._stateManager.removeChat(r,t.toString()),this._removePersistedPeerChat(e,t),i&&await this._disposeChat(i,t)}_supportsChats(e){return!!e.chats}async _createProviderSession(e,t,r){let i=r&&t?.session?M.id(t.session):void 0;i&&this._worktree?.notePending(i);let s;try{return s=await e.createSession(t?this._toProviderConfig(t):void 0),r&&s.provisional&&this._worktree?.notePending(M.id(s.session)),s}finally{let a=s?.provisional?M.id(s.session):void 0;i&&i!==a&&this._worktree?.clearPending(i)}}async _disposeSession(e,t){await e.disposeSession(t)}async _getChatMessages(e,t){let r=await e.chats.getMessages(t);return this._worktree&&Re(t)?this._worktree.applyRestoreAnnouncement(v.parse(ce(t.toString())),r):r}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.sideChat!==void 0)?{...r.title!==void 0?{title:r.title}:{},...r.model!==void 0?{model:r.model}:{},...r.sideChat!==void 0?{sideChat:r.sideChat}:{}}: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(2070,null);let r=60;return t.length>r?`${t.slice(0,r)}...`:t}_buildInitialSummary(e,t,r,i,s){let a=new Date().toISOString(),l=(i.workingDirectory??r?.workingDirectory)?.toString();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}}:{},workingDirectories:l?[l]:void 0,...!r?.fork&&!r?.workingDirectory?{_meta:Lf(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=this._worktree?.createdWorktreeProject(M.id(e.session))??e.project,a={...i,...s?{project:{uri:s.uri.toString(),displayName:s.displayName}}:{},workingDirectories:e.workingDirectory?[e.workingDirectory.toString()]:i.workingDirectories,modifiedAt:new Date().toISOString()},l=r.config?.values;l&&Object.keys(l).length>0&&this._persistConfigValues(e.session,l),this._persistWorkspaceless(e.session,zc(a._meta)),this._stateManager.markSessionPersisted(t,a),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(2066,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(rr,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)return;let r={provider:e.id,workingDirectory:t.workingDirectory,config:t.config};try{let i=await this._withIsolationSchema(await e.resolveSessionConfig(this._toProviderConfig(r)),r);return{schema:i.schema,values:i.values}}catch(i){return this._logService.error(`[AgentService] Failed to resolve created session config for provider ${e.id}`,i),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 this._withIsolationSchema(await r.resolveSessionConfig(this._toProviderConfig(e)),e)}async _withIsolationSchema(e,t){if(!this._worktree)return e;let r=await this._worktree.resolveIsolationConfig({workingDirectory:t.workingDirectory,config:t.config}),i={isolation:r.isolationProperty.protocol,...ab(e.schema.properties)};r.branchProperty&&(i.branch=r.branchProperty.protocol),r.worktreeBranchPrefixProperty&&(i.worktreeBranchPrefix=r.worktreeBranchPrefixProperty.protocol),r.worktreeIncludeFilesProperty&&(i.worktreeIncludeFiles=r.worktreeIncludeFilesProperty.protocol);let s=ab(e.values);return s.isolation=r.isolationValue,r.branchProperty&&r.branchValue!==void 0&&(s.branch=r.branchValue),r.worktreeBranchPrefixProperty&&typeof t.config?.worktreeBranchPrefix=="string"&&(s.worktreeBranchPrefix=t.config.worktreeBranchPrefix),r.worktreeIncludeFilesProperty&&Array.isArray(t.config?.worktreeIncludeFiles)&&t.config.worktreeIncludeFiles.every(a=>typeof a=="string")&&(s.worktreeIncludeFiles=t.config.worktreeIncludeFiles),{schema:{...e.schema,properties:i},values:s}}async sessionConfigCompletions(e){if(e.property==="branch"&&this._worktree)return this._worktree.branchCompletions(e.workingDirectory,e.query);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(this._toProviderConfig(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())),await this._worktree?.removeCreatedWorktree(M.id(e)),this._changesetCoordinator.onSessionDisposed(e.toString()),this._sideEffects.cancelSessionTitleGeneration(e.toString());for(let r of this._stateManager.getSessionState(e.toString())?.chats??[])this._sideEffects.clearQueuedMessageSenders(r.resource);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=rt(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=Ka(r);if(d!==void 0){if(!this._stateManager.getSessionState(d)){let c=v.parse(d),u=It(c);u?await this._restoreSubagentSession(d,u.parentSession):await this.restoreSession(c)}s=this._stateManager.getSnapshot(r)}}if(!s)if(bs(e))s=await this._awaitPendingSubagentChat(r);else if(await this._changesetCoordinator.tryHandleSubscribe(e,c=>this.restoreSession(c)))s=this._stateManager.getSnapshot(r);else{let c=It(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&&bt(l._meta)===void 0){let d=l.workingDirectories?.[0]?v.parse(l.workingDirectories[0]):void 0;this._gitStateService.refreshSessionGitState(r,d)}return s}catch(i){throw this.unsubscribe(e,t),i}}async _awaitPendingSubagentChat(e){let t=this._pendingSubagentChats.get(e);if(t)return await t.p,this._stateManager.getSnapshot(e)}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,Ft(()=>{this._pendingSessionRelease.deleteAndDispose(e),this._maybeEvictIdleSession(e)},P9))))}_cancelPendingSessionRelease(e){this._pendingSessionRelease.deleteAndDispose(e)}_maybeScheduleSessionGc(e){if(It(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,Ft(()=>{this._pendingSessionGc.deleteAndDispose(e),this._runSessionGc(e).catch(i=>{this._logService.error(i,`[AgentService] GC failed for ${t}`)})},w9)),!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=It(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=DR(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=v.parse(e);if(this._resourceSubscribers.has(t))return!1;let r=rt(e);if(!r)return!1;let i=v.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=It(e);for(;r;){if(gn(r.parentSession,t))return!0;r=It(r.parentSession)}return!1}dispatchAction(e,t,r,i,s="unknown"){this._logService.trace(`[AgentService] dispatchAction: type=${t.type}, clientId=${r}, clientSeq=${i}`,t);let a=de(e)?e:void 0,l=a?ce(a):e,d=this._clientDispatchQueues.get(r);if(!d&&!this._needsAsyncRewrite(l,t)){this._dispatchActionNow(e,l,t,r,i,s);return}let c=(d??Promise.resolve()).then(async()=>{let u=this._needsAsyncRewrite(l,t)?await this._rewriteUserMessageAttachments(l,t,r):t;if(u.type==="changeset/filesReviewChanged"){await this._reviewService.setReviewState(e,u.files,u.reviewed);let p=rt(e);if(!p)throw new Error(`Invalid changeset URI: ${e}`);this._changesets.refreshBranchChangeset(p.sessionUri)}this._dispatchActionNow(e,l,u,r,i,s)}).catch(u=>{this._logService.error(`[AgentService] async dispatchAction failed: ${De(u)}`)});this._clientDispatchQueues.set(r,c.finally(()=>{this._clientDispatchQueues.get(r)===c&&this._clientDispatchQueues.delete(r)}))}_dispatchActionNow(e,t,r,i,s,a){let l={clientId:i,clientSeq:s};this._stateManager.dispatchClientAction(e,r,l),r.type==="root/configChanged"&&this._configurationService.persistRootConfig(),this._sideEffects.handleAction(e,r,i,a)}_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 Y(this._sessionDataService.getSessionDataDir(v.parse(e)),gg)}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=xn(e.data).buffer,a=this._attachmentBasename(e.label,e.contentType);return this._writeAndRewrite(e,s,a,t)}if(e.type==="resource"&&this._isRewritableAttachment(e,r)){let s=v.parse(e.uri);if(s.scheme===ne.file&&await this._fileExistsSafe(s))return e;let a=await this._readClientResource(s,i),l=this._attachmentBasename(e.label,sg(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?od(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=F(),a=Y(i,s,r);await this._fileService.writeFile(a,$.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(Pc(v.file(r)))return r;let i=t?Jx(t):void 0;return i?`${r}${i}`:r}async resourceList(e){let t;try{t=await this._fileService.resolve(e)}catch{throw new N(ge.NotFound,`Directory not found: ${e.toString()}`)}if(!t.isDirectory)throw new N(ge.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 N(Dt,`No agent for session: ${t}`);let i=await this._getSessionMetadataForRestore(r,e);if(!i)throw new N(Dt,`Session not found on backend: ${t}`);let s=v.parse(pe(t)),a;try{a=await this._getChatMessages(r,s)}catch(D){if(D instanceof N)throw D;let z=D instanceof Error?D.message:String(D);throw new N(Ja,`Failed to restore session ${t}: ${z}`)}let l=i.summary??"Session",d,c,u,p,g,h,y,I=this._sessionDataService.tryOpenDatabase?.(e);if(I)try{let D=await I;if(D)try{let z=await D.object.getMetadataObject({customTitle:!0,isRead:!0,[or]:!0,[Fr]:!0,configValues:!0,[rr]:!0,...sh,...Vg});if(z.customTitle&&(l=z.customTitle),z.isRead!==void 0&&(d=z.isRead==="true"),z[or]!==void 0?c=z[or]==="true":z[Fr]!==void 0&&(c=z[Fr]==="true"),h=z,h[$s])try{p=JSON.parse(h[$s])}catch(J){this._logService.warn(`[AgentService] Failed to parse changes summary for ${t}: ${De(J)}`)}if(g=z,g[Oi])try{let J=JSON.parse(g[Oi]);y={[$c]:J}}catch(J){this._logService.warn(`[AgentService] Failed to parse Git state for ${t}: ${De(J)}`)}if(g[Li])try{let J=JSON.parse(g[Li]);y={...y||{},[Wc]:J}}catch(J){this._logService.warn(`[AgentService] Failed to parse GitHub state for ${t}: ${De(J)}`)}if(z[rr]!==void 0&&(y=Lf(y,z[rr]==="true")),z.configValues)try{u=JSON.parse(z.configValues)}catch(J){this._logService.warn(`[AgentService] Failed to parse persisted configValues for ${t}: ${De(J)}`)}}finally{D.dispose()}}catch{}let S=1;d&&(S|=32),c&&(S|=64);let C={resource:t,provider:r.id,title:l,status:S,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,workingDirectories:i.workingDirectory?[i.workingDirectory.toString()]:void 0,_meta:y||i._meta?{...i._meta??{},...y??{}}:void 0},[_,T]=await Promise.all([this._getChatDraft(e,s),this._readPersistedChatTitle(e,s)]),w=await this._interleaveLocalTurns(t,s.toString(),a);this._stateManager.restoreSession(C,w,{draft:_,defaultChatTitle:T});let W=[];W.push((async()=>{if(r.getSubagentSessions)try{let D=await r.getSubagentSessions(e);for(let z of D)this._registerRestoredSubagent(z,C,t)}catch(D){this._logService.warn(`[AgentService] restoreSession failed to eagerly register subagents session=${t}`,D)}})()),W.push(this._restorePeerChats(r,e)),this._changesetCoordinator.onSessionRestored(t,h??{}),i._meta&&this._stateManager.setSessionMeta(t,i._meta);let[R,L]=await Promise.all([this._resolveCreatedSessionConfig(r,{workingDirectory:i.workingDirectory,config:u}),r.getSessionCustomizations?r.getSessionCustomizations(e).catch(D=>{this._logService.error("[AgentService] restoreSession: failed to resolve session customizations",D)}):Promise.resolve(void 0),...W]);R&&this._stateManager.setSessionConfig(t,R),L&&L.length>0&&this._stateManager.setSessionCustomizations(t,L),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=v.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,origin:s.origin}}));for(let s of i){if(!s)continue;let{chatUri:a,title:l,turns:d,draft:c,providerData:u,origin:p}=s;this._stateManager.restoreChat(t.toString(),a.toString(),{title:l,turns:[...d],draft:c,...u!==void 0?{providerData:u}:{},...p!==void 0?{origin:p}:{}})}}_onChatDataChanged(e){let t=Ka(e.chat);if(t===void 0){this._logService.warn(`[AgentService] onDidChangeChatData for malformed chat URI: ${e.chat.toString()}`);return}this._persistPeerChat(v.parse(t),e.chat,e.providerData)}_sequenceSpawnedChat(e){let t=Ts.toSpawnEvent(e);t&&this._onChatSpawned(t)}_trackPendingSubagentChatFromEnvelope(e){let{channel:t,action:r}=e;if(r.type==="chat/toolCallStart"||r.type==="chat/toolCallDelta"||r.type==="chat/toolCallReady"){let i=`${t}:${r.toolCallId}`,s=An(r).subagentChatUri??this._pendingSubagentToolCalls.get(i);if(s===void 0)return;if(r.type==="chat/toolCallReady"&&r.confirmed){this._pendingSubagentToolCalls.delete(i),this._armPendingSubagentChat(s);return}this._pendingSubagentToolCalls.set(i,s);return}if(r.type==="chat/toolCallConfirmed"){let i=`${t}:${r.toolCallId}`,s=this._pendingSubagentToolCalls.get(i);if(s===void 0)return;this._pendingSubagentToolCalls.delete(i),r.approved&&this._armPendingSubagentChat(s);return}r.type==="chat/toolCallComplete"&&this._pendingSubagentToolCalls.delete(`${t}:${r.toolCallId}`)}_armPendingSubagentChat(e){if(this._pendingSubagentChats.has(e)||this._stateManager.getSnapshot(e))return;let t=new be;this._pendingSubagentChats.set(e,t),this._pendingSubagentChatTimeouts.set(e,Ft(()=>{this._pendingSubagentChats.delete(e),this._pendingSubagentChatTimeouts.deleteAndDispose(e),t.complete()},A9))}_resolvePendingSubagentChat(e){let t=this._pendingSubagentChats.get(e);t&&(this._pendingSubagentChats.delete(e),this._pendingSubagentChatTimeouts.deleteAndDispose(e),t.complete())}_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"}:{}}),this._resolvePendingSubagentChat(e.chat.toString())}async _readPersistedPeerChatCatalog(e){let t=await this._sessionDataService.tryOpenDatabase?.(e);if(t)try{let r=await t.object.getMetadata(lb);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}:{},...s.origin!==void 0?{origin:s.origin}:{}}))}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(bh,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,i){let s=t.toString();return this._enqueuePeerChatCatalogWrite(e,a=>{let l=a.find(u=>u.uri===s),d=i??l?.origin,c=a.filter(u=>u.uri!==s);return c.push({uri:s,...r!==void 0?{providerData:r}:{},...d!==void 0?{origin:d}:{}}),c})}_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(lb);if(a!==void 0){let l=JSON.parse(a);Array.isArray(l)&&(i=l.filter(d=>typeof d?.uri=="string").map(d=>({uri:d.uri,...typeof d.providerData=="string"?{providerData:d.providerData}:{},...d.origin!==void 0?{origin:d.origin}:{}})))}}catch(a){this._logService.warn(`[AgentService] Replacing malformed peer-chat catalog for ${e.toString()}: ${De(a)}`)}let s=t(i);await r.object.setMetadata(lb,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 this._withWorktreeProject(t,await e.getSessionMetadata(t))}catch(i){if(i instanceof N)throw i;try{return await this._withWorktreeProject(t,await this._getSessionMetadataFromCatalog(e,t))}catch(s){if(s instanceof N){let a=i instanceof Error?i.message:String(i);throw new N(s.code,`Failed to get session metadata for ${r}: ${a}; ${s.message}`,s.data)}throw s}}return this._withWorktreeProject(t,await this._getSessionMetadataFromCatalog(e,t))}async _withWorktreeProject(e,t){if(!t||!this._worktree)return t;let r=await this._worktree.resolveWorktreeProject(e);return r?{...t,project:r}:t}async _getSessionMetadataFromCatalog(e,t){let r=t.toString(),i;try{i=await e.listSessions()}catch(s){if(s instanceof N)throw s;let a=s instanceof Error?s.message:String(s);throw new N(Ja,`Failed to list sessions for ${r}: ${a}`)}return i.find(s=>s.session.toString()===r)}async resourceRead(e){let t=nP(e.toString());if(t)return this._fetchSessionDbContent(t);let r=oP(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=Vt(s);throw a===1?new N(ge.NotFound,`Content not found: ${e.toString()}`):a===6?new N(ge.PermissionDenied,`Permission denied: ${e.toString()}`):new N(Ja,`Failed to read content: ${e.toString()}: ${De(s)}`)}}async resourceWrite(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{if(!(await this._fileService.stat(Ut(t))).isDirectory)throw new N(ge.NotFound,`Parent directory not found: ${t.toString()}`)}catch(a){throw a instanceof N?a:Vt(a)===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Parent directory not found: ${t.toString()}`)}let r;e.encoding==="base64"?r=xn(e.data):r=$.fromString(e.data);let i=e.mode??"truncate",s=e.position??0;try{return await this._resourceWriteQueue.queueFor(t,async()=>{e.ifMatch!==void 0||i!=="truncate"||s!==0?await this._resourceWriteWithMode(t,r,i,s,e):e.createOnly?await this._createFileExclusive(t,r):await this._fileService.writeFile(t,r)},re),{}}catch(a){if(a instanceof N)throw a;let l=Vt(a);if(e.createOnly&&(l===3||l===4))throw new N(ge.AlreadyExists,`File already exists: ${t.toString()}`);if(l===3){let d=e.ifMatch!==void 0?`ifMatch precondition failed for: ${t.toString()}`:`File changed while writing: ${t.toString()}`;throw new N(ge.Conflict,d)}throw l===4?new N(ge.AlreadyExists,`File already exists: ${t.toString()}`):l===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Failed to write file: ${t.toString()}`)}}async _createFileExclusive(e,t){if(e.scheme!==ne.file){await this._fileService.createFile(e,t,{overwrite:!1});return}let r;try{r=await _9(e.fsPath,"wx")}catch(s){throw E9(s,"EEXIST")?new N(ge.AlreadyExists,`File already exists: ${e.toString()}`):s}let i;try{await r.writeFile(t.buffer)}catch(s){i=s}try{await r.close()}catch(s){i=i?new AggregateError([i,s]):s}if(i){try{await T9(e.fsPath)}catch(s){throw new AggregateError([i,s],`Failed to create and clean up file: ${e.toString()}`)}throw i}}async _resourceWriteWithMode(e,t,r,i,s){let a,l,d;try{let p=await this._fileService.readFile(e);a=p.value,l=p.etag,d=p.mtime}catch(p){if(Vt(p)!==1)throw p}if(s.createOnly&&a!==void 0)throw new N(ge.AlreadyExists,`File already exists: ${e.toString()}`);if(s.ifMatch!==void 0&&(a===void 0||l!==s.ifMatch))throw new N(ge.Conflict,`ifMatch precondition failed for: ${e.toString()}`);let c=a??$.alloc(0),u;switch(r){case"append":{let p=c.byteLength,g=Math.max(0,p-i);u=$.concat([c.slice(0,g),t,c.slice(g,p)]);break}case"insert":{let p=Math.min(i,c.byteLength);u=$.concat([c.slice(0,p),t,c.slice(p,c.byteLength)]);break}case"truncate":default:{let p=Math.min(i,c.byteLength);u=$.concat([c.slice(0,p),t]);break}}s.createOnly?await this._createFileExclusive(e,u):await this._fileService.writeFile(e,u,{etag:l,mtime:d})}async resourceCopy(e){let t=v.parse(e.source),r=v.parse(e.destination);try{return await this._fileService.copy(t,r,!e.failIfExists),{}}catch(i){let s=Vt(i);throw s===4?new N(ge.AlreadyExists,`Destination already exists: ${r.toString()}`):s===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Source not found: ${t.toString()}`)}}async resourceDelete(e){let t=v.parse(e.uri);try{return await this._fileService.del(t,{recursive:e.recursive}),{}}catch(r){throw Vt(r)===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMove(e){let t=v.parse(e.source),r=v.parse(e.destination);try{return await this._fileService.move(t,r,!e.failIfExists),{}}catch(i){let s=Vt(i);throw s===4?new N(ge.AlreadyExists,`Destination already exists: ${r.toString()}`):s===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Source not found: ${t.toString()}`)}}async resourceResolve(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{let r=await this._fileService.stat(t),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 Vt(r)===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Resource not found: ${t.toString()}`)}}async resourceMkdir(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{let r=await this._fileService.stat(t).catch(()=>{});if(r&&!r.isDirectory)throw new N(ge.AlreadyExists,`Path exists and is not a directory: ${t.toString()}`);return await this._fileService.createFolder(t),{}}catch(r){throw r instanceof N?r:Vt(r)===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Failed to create directory: ${t.toString()}`)}}async createResourceWatch(e){let t=typeof e.uri=="string"?v.parse(e.uri):v.revive(e.uri);try{await this._fileService.stat(t)}catch(i){throw Vt(i)===6?new N(ge.PermissionDenied,`Permission denied: ${t.toString()}`):new N(ge.NotFound,`Resource not found: ${t.toString()}`)}return{channel:wR({root:t.toString(),recursive:e.recursive===!0,excludes:e.excludes,includes:e.includes})}}onResourceWatchSubscribed(e){let t=RR(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 G;try{let s=v.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=M9(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,D9(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 ht),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=Ft(()=>{let r=this._resourceWatches.get(e);!r||r.subscribers>0||this._resourceWatches.deleteAndDispose(e)},x9)),!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),await this._worktree?.removeAllCreatedWorktrees(),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 getManagedSettingsDiagnostics(){let e=[...this._providers.values()].filter(t=>t.getManagedSettingsDiagnostics);return Promise.all(e.map(async t=>{try{return{provider:t.id,snapshot:await t.getManagedSettingsDiagnostics()}}catch(r){return{provider:t.id,error:r instanceof Error?r.message:String(r)}}}))}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=v.parse(e.sessionUri),r=this._sessionDataService.openDatabase(t);try{let i=await r.object.readFileEditContent(e.toolCallId,e.filePath);if(!i)throw new N(ge.NotFound,`File edit not found: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);let s=e.part==="before"?i.beforeContent:i.afterContent;if(!s)throw new N(ge.NotFound,`No ${e.part} content for: toolCallId=${e.toolCallId}, filePath=${e.filePath}`);return{data:new TextDecoder().decode(s),encoding:"utf-8",contentType:"text/plain"}}finally{r.dispose()}}async _fetchGitBlobContent(e){if(!this._gitService)throw new N(ge.NotFound,`git service unavailable for: ${e.repoRelativePath}`);let t=this._stateManager.getSessionState(e.sessionUri)?.workingDirectories?.[0];if(!t)throw new N(ge.NotFound,`Session has no working directory for git-blob URI: ${e.sessionUri}`);let r=await this._gitService.showBlob(v.parse(t),e.sha,e.repoRelativePath);if(!r)throw new N(ge.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 g of s){for(let h of g.responseParts)if(h.kind==="toolCall"){let y=h.toolCall,I=y.status==="completed"||y.status==="running"?y.content:void 0;if(I){for(let S of I)if(S.type==="subagent"&&S.resource===e){a=S;break}}}if(a)break}let l=[],d=this._findProviderForSession(t);if(d)try{l=await this._getChatMessages(d,v.parse(e))}catch(g){this._logService.warn(`[AgentService] Failed to load subagent turns for ${e}`,g)}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=_s(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=M.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 E9(o,n){return o instanceof Error&&k9(o,n)}function k9(o,n){return he(o,{code:!0})&&o.code===n}function D9(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 M9(o,n){let e=[],t=(r,i)=>{Or(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 A6,RuntimeConnection as P6}from"@github/copilot-sdk";import*as dn from"fs/promises";import*as $0 from"os";import{pathToFileURL as E6}from"url";function Qk(o,n,e){return Math.min(Math.max(o,n),e)}function Th(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 O9(o,n=[],e={}){let r=new wh(o).scan();return new Rh(r,o,n,e).parse()}function gd(o,n=[],e={}){let t=new wh(o).scan();if(t.length===0||t[0].type!==11)return new Zu(void 0,o);if(!t.slice(1).some(l=>l.type===11))return new Zu(void 0,o);let i=new Rh(t,o,n,e).parse(),s=t[t.length-1],a=s.type===13?o.substring(s.startOffset):"";return new Zu(i,a)}var Zu=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"?L9(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 L9(o,n=0){let e=O9(`[${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 Et(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 wh=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(Et(13,this.pos,this.pos)),this.tokens}scanLine(){if(this.seenBlockColon=!1,this.peekChar()===`
`){this.tokens.push(Et(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(Et(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(Et(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(Et(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(Et(11,this.pos,this.pos+3)),this.pos+=3,this.scanLineContent(),this.scanNewline(),this.seenDocumentStart++;return}if(t==="."&&r==="."&&i==="."&&a){this.tokens.push(Et(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(Et(4,this.pos,this.pos+1)),this.pos++;else if(n==="}"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Et(5,this.pos,this.pos+1)),this.pos++;else if(n==="[")this.flowDepth++,this.tokens.push(Et(6,this.pos,this.pos+1)),this.pos++;else if(n==="]"&&this.flowDepth>0)this.flowDepth--,this.tokens.push(Et(7,this.pos,this.pos+1)),this.pos++;else if(n===","&&this.flowDepth>0)this.tokens.push(Et(3,this.pos,this.pos+1)),this.pos++;else if(n==="-"&&this.isBlockDash())this.tokens.push(Et(2,this.pos,this.pos+1)),this.pos++;else if(n===":"&&this.isBlockColon())this.tokens.push(Et(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(Et(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(Et(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(Et(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(Et(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 g=this.input[this.pos];g>="1"&&g<="9"&&t===0?(t=parseInt(g,10),this.pos++):g==="-"&&r==="clip"?(r="strip",this.pos++):g==="+"&&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,g=0;for(;this.pos<this.input.length&&this.input[this.pos]===" ";)g++,this.pos++;if(this.pos>=this.input.length||this.input[this.pos]===`
`||this.input[this.pos]==="\r"){if(s>0&&g>=s){let I=this.input.substring(p+s,this.pos);a.push(I),I===""?l++:l=0}else a.push(""),l++;this.consumeNewline();continue}if(g===0&&this.input.length-this.pos>=3){let I=this.input[this.pos],S=this.input[this.pos+1],C=this.input[this.pos+2],_=this.input[this.pos+3],T=_===void 0||_===" "||_==="	"||_===`
`||_==="\r";if(I==="-"&&S==="-"&&C==="-"&&T||I==="."&&S==="."&&C==="."&&T){this.pos=p;break}}if(s===0){if(g<=i){this.pos=p;break}s=g}if(g<s){this.pos=p;break}let h=p+s;for(;this.pos<this.input.length&&this.input[this.pos]!==`
`&&this.input[this.pos]!=="\r";)this.pos++;let y=this.input.substring(h,this.pos);a.push(y),l=0,this.consumeNewline()}let d;if(n==="|")d=a.join(`
`);else{d="";let p=!1,g=!1,h=!1;for(let y=0;y<a.length;y++){let I=a[y],S=I.length>0&&(I[0]===" "||I[0]==="	");I===""?(d+=`
`,g=!0):y===0?(d=I,p=S,h=!0):g?((p||S)&&h?d+=`
`+I:d+=I,p=S,g=!1,h=!0):S||p?(d+=`
`+I,p=S,h=!0):(d+=" "+I,p=!1,h=!0)}}if(l>0){let p=d.length;for(;p>0&&d[p-1]===`
`;)p--;d=d.substring(0,p)}let c=a.some(p=>p!=="");switch(r){case"clip":c&&(d+=`
`);break;case"keep":c?d+=`
`.repeat(l+1):d=`
`.repeat(l);break;case"strip":break}let u=this.input.substring(e,this.pos);this.tokens.push(Et(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(Et(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(Et(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]}},Rh=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 N9="https://agent-plugins.org/schemas/";async function db(o,n){let e=Y(o,"plugin.json");if(!await n.exists(e))return;let t;try{t=wl((await n.readFile(e)).value.toString())}catch{return}if(!H9(t)||!U9(t.$schema))return;let r={$schema:t.$schema},i=F9(t.name),s=Xk(t.version),a=Xk(t.description);return{...r,...i?{name:i}:{},...s?{version:s}:{},...a?{description:a}:{}}}function U9(o){return typeof o=="string"&&o.startsWith(N9)&&o.endsWith("/plugin.schema.json")}function Xk(o){return typeof o=="string"?o:void 0}function F9(o){return typeof o=="string"&&o.trim().length>0?o.trim():void 0}function H9(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}var $9;(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&&gn(e.cwd,t.cwd)&&Oe(e.env,t.env)&&e.timeout===t.timeout&&gn(e.sourceUri,t.sourceUri)}n.isEquals=o})($9||={});var W9={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 Ph(o,n,t,r)}},q9={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 s1(o,n,e,t,r,"${CLAUDE_PLUGIN_ROOT}","CLAUDE_PLUGIN_ROOT")}},B9={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 s1(o,n,e,t,r,"${PLUGIN_ROOT}","PLUGIN_ROOT")}},z9={format:3,manifestPath:"plugin.json",hookConfigPath:"",componentPaths:{commands:!1,skills:"skills",agents:!1,rules:!1,hooks:!1,mcpServers:"mcp.json"},requiresManifest:!0,pluginRootTokens:[],pluginRootEnvVars:[],parseHooks(){return[]}};async function tp(o,n){return await db(o,n)?z9:await ea(Y(o,".plugin","plugin.json"),n)?B9:o.path.split("/").includes(".claude")||await ea(Y(o,".claude-plugin","plugin.json"),n)?q9:W9}async function V9(o,n,e){if(n.format===3){let r=await db(o,e);return r?{...r}:void 0}let t=await zo(Y(o,n.manifestPath),e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Zk(o,n,e){return o.componentPaths&&Object.hasOwn(o.componentPaths,n)?void 0:e?.[n]}function ep(o,n,e,t,r,i){let s=n.componentPaths?.[e];return n.componentPaths&&Object.hasOwn(n.componentPaths,e)?typeof s=="string"?e1(o,s,Ah,i):[]:e1(o,t,Y9(r),i)}function np(o,n){let e=et(o.toString());return n?`${e.replace(/#/g,"%23")}#${n}`:e}function j9(o){let n=o.uri.toString();return{type:"agent",id:np(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function K9(o){let n=o.uri.toString();return{type:"skill",id:np(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function G9(o){let n=o.uri.toString();return{type:"rule",id:np(o.uri),uri:n,name:o.name,...o.description?{description:o.description}:{}}}function J9(o){return{type:"hook",id:np(o),uri:o.toString(),name:Se(o)}}function rp(o,n){return{type:"mcpServer",id:np(o,`mcp=${encodeURIComponent(n)}`),uri:o.toString(),name:n,enabled:!0,state:{kind:"stopped"},mcpApp:yh}}var Ah={paths:[],exclusive:!1};function Y9(o){if(o==null)return Ah;if(typeof o=="string"){let n=o.trim();return n?{paths:[n],exclusive:!1}:Ah}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 Ah}function e1(o,n,e,t){let r=t&&Or(o,t)?t:o,i=[];e.exclusive||i.push(Y(o,n));for(let s of e.paths){let a=rn(Y(o,s));Or(a,r)&&i.push(a)}return i}function Q9(o){if(!o||typeof o!="object"||Array.isArray(o))return;let n=o;return Object.hasOwn(n,"mcpServers")?n.mcpServers:n}function X9(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==="streamable-http"||e==="sse"||!e&&r)return r?{type:"http",url:r,headers:d,dev:c}:void 0}}var Z9=/[\s&|<>()^;!`"']/;function e8(o,n,e){if(!o.includes(e))return o;if(!Z9.test(n))return o.replaceAll(e,n);let t=Un(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 t8(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 n8=/\$\{(?![A-Za-z]+:)([A-Z_][A-Z0-9_]*)\}/g;function r8(o){return Uc(o,n=>{if(v.isUri(n))return n;if(typeof n=="string"){let e=n.replace(n8,"${env:$1}");return e!==n?e:void 0}})}var o8={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 i8(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 t1(o,n,e){let t=i8(o);if(!t)return;let r,i=typeof o.cwd=="string"?o.cwd:void 0;return i?i.startsWith("~/")?r=v.joinPath(e,i.substring(2)):nn(i)?r=v.file(i):n&&(r=Y(n,i)):r=n,{...t,cwd:r}}function s8(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=t1(s,n,e);a&&r.push(a)}else{let s=t1(t,n,e);s&&r.push(s)}return r}function Ph(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=J9(o);for(let d of Object.keys(s)){let c=o8[d];if(!c)continue;let u=s[d];if(!Array.isArray(u))continue;let p=[];for(let g of u)p.push(...s8(g,e,t));p.length>0&&a.push({type:c,commands:p,uri:o,originalId:d,customization:l})}return a}function s1(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]=e8(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 g=p;if(Array.isArray(g.hooks))for(let h of g.hooks)d(h);else d(g)}return Ph(o,Uc(n,u=>typeof u=="string"?u.replaceAll(i,e.fsPath):void 0),t,r)}async function zo(o,n){try{let e=await n.readFile(o);return wl(e.value.toString())}catch{return}}async function ea(o,n){try{return await n.resolve(o),!0}catch{return!1}}var xh=".md",n1=".mdc",r1=".instructions.md";async function cb(o,n,e,t){let r=new Set,i=[],s=async(a,l)=>{if(t?.containmentRoot&&!await a1(t.containmentRoot,l,e))return;let d;try{let c=await ub(l,e);d=c.description,a=c.name||a}catch{}r.has(a)||(r.add(a),i.push({uri:l,name:a,...d?{description:d}:{}}))};if(await Promise.all(n.map(async a=>{if(!t?.childDirectoriesOnly){let d=v.joinPath(a,"SKILL.md");if(await ea(d,e)){await s(Se(a),d);return}}let l;try{l=await e.resolve(a)}catch{return}!l.isDirectory||!l.children||await Promise.all(l.children.map(async d=>{let c=v.joinPath(d.resource,"SKILL.md");await ea(c,e)&&await s(Se(d.resource),c)}))})),!t?.childDirectoriesOnly&&i.length===0){let a=v.joinPath(o,"SKILL.md");await ea(a,e)&&await s(Se(o),a)}return i.sort((a,l)=>a.name.localeCompare(l.name)),i}async function a8(o,n,e,t){return cb(o,n,t,e.format===3?{childDirectoriesOnly:!0,containmentRoot:o}:void 0)}async function a1(o,n,e){try{let[t,r]=await Promise.all([e.realpath(o),e.realpath(n)]);return Or(r??rn(n),t??rn(o))}catch{return!1}}async function l8(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&&Pc(i).toLowerCase()===xh){r(Se(i).slice(0,-xh.length),i);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children)!a.isFile||Pc(a.resource).toLowerCase()!==xh||r(Se(a.resource).slice(0,-xh.length),a.resource)}return t.sort((i,s)=>i.name.localeCompare(s.name)),t}function o1(o){let n=Se(o),e=n.toLowerCase();if(e.endsWith(n1))return n.slice(0,-n1.length);if(e.endsWith(r1))return n.slice(0,-r1.length)}async function d8(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=o1(i);a&&r(a,i);continue}if(!(!s.isDirectory||!s.children))for(let a of s.children){if(!a.isFile)continue;let l=o1(a.resource);l&&r(l,a.resource)}}return t.sort((i,s)=>i.name.localeCompare(s.name)),t}async function Eh(o,n){let e=await l8(o,n);if(e.length===0)return e;let t=await Promise.all(e.map(async s=>{try{let{name:a,description:l}=await op(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 op(o,n){let e=Se(o).replace(/(\.agent)?\.md$/i,"");try{let t=await n.readFile(o),r=gd(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=gd(e.value.toString()),r=t?.getStringValue("name")?.trim()||Se(Ut(o)),i=t?.getStringValue("description")?.trim(),s=t?.getBooleanValue("user-invocable");return{name:r,description:i,userInvokable:s}}catch{return{name:Se(Ut(o))}}}async function kh(o,n){let e=Se(o).replace(/(\.instructions)?\.md$/i,"");try{let t=await n.readFile(o),r=gd(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 c8(o,n,e,t,r,i){for(let s of n){let a=await zo(s,t);if(a)return e.parseHooks(s,a,o,r,i)}return[]}async function u8(o,n,e,t){let r=new Map;for(let i of n){if(e.format===3&&!await a1(o,i,t))continue;let s=await zo(i,t);for(let a of l1(i,s,o.fsPath,e))r.has(a.name)||r.set(a.name,a)}return[...r.values()].sort((i,s)=>i.name.localeCompare(s.name))}async function p8(o,n,e,t){return u8(o,n,e,t)}function l1(o,n,e,t){let r=Q9(n);if(!r)return[];let i=[];for(let[s,a]of Object.entries(r)){let l=X9(a);if(!l)continue;let d={name:s,configuration:l,uri:o,customization:rp(o,s)};d=t8(d,e,t.pluginRootTokens,t.pluginRootEnvVars),t.format!==3&&d.configuration.type==="stdio"&&d.configuration.cwd===void 0&&(d={...d,configuration:{...d.configuration,cwd:e}}),t.format!==3&&(d=r8(d)),i.push(d)}return i}async function md(o,n,e,t,r){let i=await tp(o,n),s=await V9(o,i,n);if(i.requiresManifest&&!s)throw new Error(`Plugin manifest '${Y(o,i.manifestPath).toString()}' is missing`);let a=ep(o,i,"hooks",i.hookConfigPath,s?.hooks,r),l=ep(o,i,"mcpServers",".mcp.json",s?.mcpServers,r),d=ep(o,i,"skills","skills",s?.skills,r),c=ep(o,i,"agents","agents",s?.agents,r),u=ep(o,i,"rules","rules",s?.rules,r),p=[],g=Zk(i,"mcpServers",s);g&&typeof g=="object"&&!Array.isArray(g)&&!he(g,{paths:!0})&&(p=l1(Y(o,i.manifestPath),{mcpServers:g},o.fsPath,i));let h=[],y=Zk(i,"hooks",s);if(y&&typeof y=="object"&&!Array.isArray(y)&&!he(y,{paths:!0})){let w=Y(o,i.manifestPath);h=i.parseHooks(w,{hooks:y},o,e,t)}let[I,S,C,_,T]=await Promise.all([h.length>0?Promise.resolve(h):c8(o,a,i,n,e,t),p.length>0?Promise.resolve(p):p8(o,l,i,n),a8(o,d,i,n),Eh(c,n),d8(u,n)]);return{format:i.format,hooks:I,mcpServers:S,skills:C.map(Dh),agents:_.map(hd),instructions:T.map(f8)}}function hd(o){return{...o,customization:j9(o)}}function Dh(o){return{...o,customization:K9(o)}}function f8(o){return{...o,customization:G9(o)}}import*as d1 from"fs/promises";function pb(o,n){return Y(o,".copilot","chats",n)}async function c1(o,n){let e=pb(o,n);return await d1.mkdir(e.fsPath,{recursive:!0}),e}function g8(o){let n=Object.entries(o).filter(([,e])=>e!==void 0);return n.length>0?Object.fromEntries(n):void 0}function yd(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=zn(i.batchSize)??zn(i.batch_size)??1e6,c=d>0?1e6/d:1,u=(..._)=>{let T=_.map(zn).find(w=>w!==void 0);return T===void 0?void 0:T*c},p=u(i.inputPrice,l?a.input_price:void 0),g=u(i.cacheReadPrice,i.cachePrice,l?a.cache_read_price:void 0,l?a.cache_price:void 0),h=u(i.cacheWritePrice,l?a.cache_write_price:void 0),y=u(i.outputPrice,l?a.output_price:void 0),I=zn(i.maxPromptTokens)??zn(i.contextMax)??zn(l?a.max_prompt_tokens:void 0)??zn(l?a.context_max:void 0),S=i.longContext??i.long_context,C;S&&typeof S=="object"&&(C={inputPrice:u(S.inputPrice,S.input_price),cachePrice:u(S.cacheReadPrice,S.cachePrice,S.cache_read_price,S.cache_price),cacheWritePrice:u(S.cacheWritePrice,S.cache_write_price),outputPrice:u(S.outputPrice,S.output_price),contextMax:zn(S.maxPromptTokens)??zn(S.contextMax)??zn(S.max_prompt_tokens)??zn(S.context_max)}),s={inputPrice:p,cachePrice:g,cacheWritePrice:h,outputPrice:y,contextMax:I,longContext:C}}return{multiplier:e,priceCategory:t,discountPercent:r,promo:m8(n),tokenPrices:s}}function zn(o){return typeof o=="number"?o:void 0}function m8(o){let n=o.promo;if(!n||typeof n!="object")return;let e=typeof n.id=="string"?n.id:void 0,t=zn(n.discountPercent)??zn(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 vd(o,n,e){let t=o?.tokenPrices,r=t?.longContext,i=r!==void 0&&(r.inputPrice!==void 0&&r.inputPrice!==t?.inputPrice||r.outputPrice!==void 0&&r.outputPrice!==t?.outputPrice||r.cachePrice!==void 0&&r.cachePrice!==t?.cachePrice||r.cacheWritePrice!==void 0&&r.cacheWritePrice!==t?.cacheWritePrice);return g8({multiplierNumeric:typeof o?.multiplier=="number"?o.multiplier:void 0,inputCost:t?.inputPrice,cacheCost:t?.cachePrice,cacheWriteCost:t?.cacheWritePrice,outputCost:t?.outputPrice,longContextInputCost:i?r.inputPrice??t?.inputPrice:void 0,longContextCacheCost:i?r.cachePrice??t?.cachePrice:void 0,longContextCacheWriteCost:i?r.cacheWritePrice??t?.cacheWritePrice:void 0,longContextOutputCost:i?r.outputPrice??t?.outputPrice:void 0,priceCategory:n??(typeof o?.priceCategory=="string"?o.priceCategory:void 0),category:e,discountPercent:typeof o?.discountPercent=="number"?o.discountPercent:void 0,promo:o?.promo})}function fb(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 $i=B("agentPluginManager");function ta(o){switch(o){case"none":return f(2010,null);case"minimal":return f(2008,null);case"low":return f(2002,null);case"medium":return f(2006,null);case"high":return f(2000,null);case"xhigh":return f(2012,null);case"max":return f(2004,null);default:return o.charAt(0).toUpperCase()+o.slice(1)}}function na(o){switch(o){case"none":return f(2011,null);case"minimal":return f(2009,null);case"low":return f(2003,null);case"medium":return f(2007,null);case"high":return f(2001,null);case"xhigh":return f(2013,null);case"max":return f(2005,null);default:return}}var Mh=B("agentHostOTelService");function u1(o,n){return n.COPILOT_HOME||V(o,".copilot")}import{LogLevel as ra,createFetchPatch as h8,createProxyAuthorizationLookup as y8,createProxyResolver as v8,loadSystemCertificates as S8}from"@vscode/proxy-agent";var Wi=B("agentHostProxyResolver"),Sd=class{constructor(n,e){this._configurationService=n;this._logService=e;this._connections=new Map}register(n,e){return this._connections.set(n,e),U(()=>{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=h8(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),lookupProxyAuthorization:y8({log:this._logService,lookupAuthorization:i=>this._hostLookupAuthorization(i),lookupKerberosAuthorization:i=>this._hostLookupKerberosAuthorization(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")??Ml,loadAdditionalCertificates:async()=>S8({loadSystemCertificatesFromNode:()=>n("http.systemCertificatesNode")??Ml,log:this._logService}),log:this._logService,getLogLevel:()=>{switch(this._logService.getLevel()){case 1:return ra.Trace;case 2:return ra.Debug;case 3:return ra.Info;case 4:return ra.Warning;case 5:return ra.Error;case 0:return ra.Off;default:return ra.Info}},proxyResolveTelemetry:()=>{},isUseHostProxyEnabled:()=>this._connections.size>0,getNetworkInterfaceCheckInterval:()=>(n("http.experimental.networkInterfaceCheckInterval")??300)*1e3,env:process.env};this._proxyAgentParams=r,this._proxyResolver=v8(r)}return this._proxyResolver}async _hostResolveProxy(n){for(let e of this._connections.values())try{return await e.resolveProxy(n)}catch{}}async _hostLookupAuthorization(n){for(let e of this._connections.values())try{return await e.lookupAuthorization(n)}catch{}}async _hostLookupKerberosAuthorization(n){for(let e of this._connections.values())try{return await e.lookupKerberosAuthorization(n)}catch{}}};Sd=A([b(0,ir),b(1,O)],Sd);function Oh(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||!Oe(s.inputSchema,i.inputSchema))return!1}return!0}var Mn=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 Oh(this.merged(),n)}};var qi=B("byokLmBridgeRegistry"),Lh=class{constructor(){this._entries=new Map;this._changeListeners=new Set}onDidChangeModels(n){return this._changeListeners.add(n),U(()=>{this._changeListeners.delete(n)})}_notifyChanged(){for(let n of[...this._changeListeners])n()}register(n,e){this._entries.get(n)?.store.dispose();let t=new G,r={connection:e,models:void 0,store:t};return this._entries.set(n,r),t.add(e.onDidChangeModels(i=>{this._entries.get(n)===r&&(r.models===void 0||!C8(r.models,i))&&(r.models=i,this._notifyChanged())})),this._notifyChanged(),U(()=>{this._entries.get(n)===r&&(this._entries.delete(n),r.store.dispose(),this._notifyChanged())})}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}};function C8(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 I8=1,b8="vscode-copilot-migration";function _8(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:F(),parentId:t,timestamp:i(),type:"subagent.started",data:{toolCallId:l.toolCallId,agentName:c.agentName??c.title,agentDisplayName:c.title,agentDescription:c.description??""}}),s({id:F(),parentId:t,timestamp:i(),type:"tool.execution_start",data:{toolCallId:l.toolCallId,toolName:l.toolName,...d?{arguments:d}:{}}});let u=T8(l.content);s({id:F(),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:F(),parentId:t,timestamp:i(),type:"session.start",data:{sessionId:n.sessionId,copilotVersion:n.copilotVersion??"0.0.0",producer:b8,startTime:i(),version:n.schemaVersion??I8,...n.model?{selectedModel:n.model}:{},...n.workingDirectory?{context:{cwd:n.workingDirectory}}:{}}});for(let l of o){s({id:yR(l.id)?l.id:F(),parentId:t,timestamp:i(),type:"user.message",data:{content:l.message.text,source:"user"}});let d="",c="",u=()=>{!d&&!c||(s({id:F(),parentId:t,timestamp:i(),type:"assistant.message",data:{content:d,messageId:F(),...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:F(),parentId:t,timestamp:i(),type:"abort",data:{reason:"user_initiated"}})}return e}function T8(o){if(!o)return"";let n="";for(let e of o)e.type==="text"&&(n+=e.text);return n}function w8(o){return o.length===0?"":o.map(n=>JSON.stringify(n)).join(`
`)+`
`}function p1(o,n){return w8(_8(o,n))}var gb="/.well-known",R8=`${gb}/oauth-protected-resource`,Nxe=`${gb}/oauth-authorization-server`,Uxe=`${gb}/openid-configuration`;function mb(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))}async function f1(o,n,e={}){let{sameOriginHeaders:t={},fetch:r=fetch}=e,i=new URL(o),s=async(c,u)=>{let p={Accept:"application/json"};new URL(c).origin===i.origin&&(p={...p,...t});let h=await r(c,{method:"GET",headers:p});if(h.status!==200){let I;try{I=await h.text()}catch{I=h.statusText}throw new Error(`Failed to fetch resource metadata from ${c}: ${h.status} ${I}`)}let y=await h.json();if(mb(y)){let I=new URL(y.resource).toString(),S=new URL(u).toString();if(I!==S)throw new Error(`Protected Resource Metadata 'resource' property value "${I}" does not match expected value "${S}" for URL ${c}. Per RFC 9728, these MUST match. See https://datatracker.ietf.org/doc/html/rfc9728#PRConfigurationValidation`);return y}else throw new Error(`Invalid resource metadata from ${c}. Expected to follow shape of https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata (Hints: is scopes_supported an array? Is resource a string?). Current payload: ${JSON.stringify(y)}`)},a=[];if(n)try{return{metadata:await s(n,o),discoveryUrl:n,errors:a}}catch(c){a.push(c instanceof Error?c:new Error(String(c)))}let l=i.pathname!=="/",d=`${i.origin}${R8}`;if(l){let c=`${d}${i.pathname}`;try{return{metadata:await s(c,o),discoveryUrl:c,errors:a}}catch(u){a.push(u instanceof Error?u:new Error(String(u)))}}try{return{metadata:await s(d,i.origin),discoveryUrl:d,errors:a}}catch(c){a.push(c instanceof Error?c:new Error(String(c)))}throw a.length===1?a[0]:new AggregateError(a,"Failed to fetch resource metadata from all attempted URLs")}function x8(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 ia(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=x8(i,r);return!s||!A8(s.directory,e)?!1:(n.command=s.command,!0)}function A8(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=v.file(t),s=v.file(r)}catch{return!1}return re.isEqual(i,s)}var g1="ahp-otlp://logs/{level}",m1="ahp-otlp",P8=["trace","debug","info","warn","error","fatal"];function h1(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 E8(o){let n=o.toLowerCase();return P8.includes(n)?n:void 0}function k8(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 Bi=class{constructor(n){this.attributes=n}toJSON(){return this.attributes}},Nh=class extends x{constructor(){super(...arguments);this._onDidLog=this._register(new E);this.onDidLog=this._onDidLog.event}emit(e){this._onDidLog.fire(e)}},Uh=class extends Ms{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 Bi);a!==-1&&(s=r[a].attributes,r=r.slice(0,a).concat(r.slice(a+1)));let{severityNumber:l,severityText:d}=k8(e);this._emitter.emit({timeUnixNano:L8(Date.now()),severityNumber:l,severityText:d,body:Po([t,...r],i),...s?{attributes:s}:void 0})}};function y1(o){return D8([o])}function D8(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:M8(n.attributes)}:void 0}))}]}]}}function M8(o){return Object.entries(o).map(([n,e])=>({key:n,value:O8(e)}))}function O8(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 L8(o){return`${o}000000`}function v1(o){let n=/^ahp-otlp:\/\/logs\/([^/?#]+)/i.exec(o);if(n)return E8(n[1])}function S1(o){return`ahp-otlp://logs/${o}`}var Fh="autoApprove",C1="default",R1="interactive",I1="plan",ip="autopilot";function b1(){return f(1999,null)}function _1(){return f(1995,null)}function N8(){return f(1992,null)}function U8(){return f(1996,null)}function F8(){return f(1993,null)}function T1(){return f(1997,null)}function H8(){return f(1994,null)}function w1(){return f(1998,null)}function hb(){return[{command:"yolo",sortText:"z1_yolo",options:[{arg:"on",detail:b1(),config:{autoApprove:Fh}},{arg:"off",detail:_1(),config:{autoApprove:C1}}]},{command:"allow-all",sortText:"z1_allow-all",options:[{arg:"on",detail:b1(),config:{autoApprove:Fh}},{arg:"off",detail:_1(),config:{autoApprove:C1}}]},{command:"autopilot",sortText:"z1_autopilot",options:[{arg:"on",detail:N8(),config:{mode:ip}},{arg:"off",detail:U8(),config:{mode:R1}},{detail:F8(),config:{mode:ip},argumentHint:H8()}]},{command:"plan",sortText:"z1_plan",options:[{detail:T1(),config:{mode:I1},argumentHint:w1()}]},{command:"goal",sortText:"z1_goal",options:[{detail:T1(),config:{mode:I1},argumentHint:w1()}]}]}function yb(o){return hb().some(n=>n.command.toLowerCase()===o.toLowerCase())}function $8(o,n){if(o.argumentHint!==void 0||!n)return!0;let e=o.config.autoApprove;if(e!==void 0){let r=n.autoApprove===Fh;return e===Fh?!r:r}let t=o.config.mode;return t===ip?n.mode!==ip:t===R1?n.mode===ip:!0}function x1(o,n){let e=o.trim().toLowerCase(),t=[];for(let r of hb())if(!(e&&!r.command.toLowerCase().startsWith(e)&&(e.length===1||Em(e,r.command)===null)))for(let i of r.options){if(!$8(i,n))continue;let s=i.argumentHint!==void 0,a=s?`/${r.command} `:"",l=s?`/${r.command}`:i.arg?`/${r.command} ${i.arg}`:`/${r.command}`;t.push({insertText:a,label:l,command:r.command,description:i.detail,...i.argumentHint!==void 0?{argumentHint:i.argumentHint}:{},applyConfig:i.config,sortText:i.arg?`${r.sortText}_${i.arg}`:r.sortText})}return t}function A1(o,n){let e=hb().find(a=>a.command.toLowerCase()===o.toLowerCase());if(!e)return;let t=n.trim(),r=e.options.filter(a=>a.arg!==void 0),i=e.options.find(a=>a.arg===void 0);if(r.length>0&&t.length>0){let a=/^(\S+)(?:\s+([\s\S]*))?$/.exec(t),l=a?.[1]?.toLowerCase(),d=r.find(c=>c.arg?.toLowerCase()===l);if(d)return{applyConfig:d.config,strippedPrompt:(a?.[2]??"").trim()};if(!i)return}return{applyConfig:(i??e.options[0]).config,strippedPrompt:t}}var W8="agentFeedback";function Hh(o){return o.type==="annotations"&&o.displayKind===W8}function $h(o){let n=o.annotationIds?.filter(Be)??[];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 Cd="tool_search_tool",no="toolSearch";var P1=new Set(["runTests","rename","usages"]);function Wh(o){if(!o)return!1;let e=o.toLowerCase().replace(/\./g,"-");return!e.startsWith("claude")||e.startsWith("claude-haiku")?!1:!(e.startsWith("claude-1")||e.startsWith("claude-2")||e.startsWith("claude-3")||e.startsWith("claude-instant")||e==="claude-sonnet-4"||e.startsWith("claude-sonnet-4-2")||e==="claude-opus-4"||e.startsWith("claude-opus-4-1")||e.startsWith("claude-opus-4-2"))}var vb=Object.freeze({valid:!1,sessionId:void 0});function qh(o,n){let e=o.authorization;if(typeof e!="string"||!e.startsWith("Bearer "))return vb;let t=e.slice(7),r=t.indexOf(".");if(r===-1)return vb;let i=t.slice(0,r),s=t.slice(r+1);return i!==n||s.length===0?vb:{valid:!0,sessionId:s}}function q8(){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 Id(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 zi=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=q8(),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 bd=class extends Error{};function B8(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 z8(o){switch(o){case"system":case"developer":return"system";case"assistant":return"assistant";case"tool":case"function":return"tool";default:return"user"}}function V8(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 bd(`tool_calls[${e}].function.name is required`);n.push({id:t.id??`call_${e}`,name:r,argumentsJson:t.function?.arguments??"{}"})}return n}function j8(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 E1(o,n){let e=typeof n.model=="string"?n.model:"";if(!e)throw new bd('Request is missing the "model" field');let r=(Array.isArray(n.messages)?n.messages:[]).map(s=>({role:z8(s.role),content:B8(s.content),toolCalls:V8(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:j8(n.tools),modelOptions:Object.keys(i).length?i:void 0}}var Sb=0;function K8(){return Sb=(Sb+1)%Number.MAX_SAFE_INTEGER,`chatcmpl-byok-${Date.now().toString(36)}-${Sb.toString(36)}`}function Bh(o){return`data: ${JSON.stringify(o)}

`}function k1(o,n){let e=K8(),t=Math.floor(Date.now()/1e3),r={id:e,object:"chat.completion.chunk",created:t,model:n},i=[];i.push(Bh({...r,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})),o.content&&i.push(Bh({...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(Bh({...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(Bh(a)),i.push(`data: [DONE]

`),i}function D1(o,n="api_error"){return JSON.stringify({error:{message:o,type:n}})}var zh=B("byokLmProxyService"),M1="ByokLmProxyService",Cb="/v/",O1="/chat/completions",_d=class extends zi{constructor(e,t){super(M1,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}${Cb}${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(`[${M1}] ${i} ${s}`),i==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=qh(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(Cb)||!e.endsWith(O1))return;let t=e.slice(Cb.length,e.length-O1.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 Id(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=E1(i,s)}catch(u){let p=u instanceof bd?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 k1(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(D1(r,i)))}};_d=A([b(0,O),b(1,qi)],_d);var Td=class extends x{constructor(e){super();this.session=e;this._handledEventTypes=new Set;this._onUnhandledEvent=this._register(new E);this.onUnhandledEvent=this._onUnhandledEvent.event;let t=e.on(r=>{this._handledEventTypes.has(r.type)||this._onUnhandledEvent.fire(r)});this._register(U(t)),this._register(U(()=>{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 onAutoModeResolved(){return this._onAutoModeResolved??=this._sdkEvent("session.auto_mode_resolved")}get onManagedSettingsResolved(){return this._onManagedSettingsResolved??=this._sdkEvent("session.managed_settings_resolved")}get onManagedSettingsEnforced(){return this._onManagedSettingsEnforced??=this._sdkEvent("session.managed_settings_enforced")}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 E({onDidAddFirstListener:()=>this._handledEventTypes.add(e),onDidRemoveLastListener:()=>this._handledEventTypes.delete(e)})),r=this.session.on(e,i=>t.fire(i));return this._register(U(r)),t.event}};var Vh=B("sandboxHelperService");import{createHash as r$}from"crypto";var G8=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"]),J8=new Set(["ai","cloud","com","dev","io","me","net","org","tech"]);function sp(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(G8.has(a)||!J8.has(a))return}return i?`*.${s}`:s}}function Y8(o){let n=o.trim();if(n==="*"||!n.includes("://"))return n;try{return v.parse(n).authority}catch{return n}}function Ib(o,n){let e=sp(Y8(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 Kh=B("windowsMxcTerminalSandboxRuntime"),jh=class{constructor(){this._configVersion="0.6.0-alpha"}getExecutablePath(n,e,t){let r=t==="arm64"?"arm64":"x64";return ve.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,ve.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&&ve.isAbsolute(n.shell)?[ve.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 Gh(o,n,e){if(!n.keywords.includes(o.keyword.toLowerCase())||n.condition&&(!e||!n.condition(e)))return!1;if(n.subcommands){let t=Q8(o.args,n.optionsWithValue);if(t===void 0||!n.subcommands.includes(t))return!1}return n.when?.(o)??!0}function Q8(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 X8=new Map([["git","git"],["gh","git"],["gpg","gnupg"],["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 N1(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"]}case"ssh":switch(n){case 2:case 3:default:return["~/.ssh"]}}}function L1(o,n){let e=new Set;for(let r of n)for(let i of Z8)Gh(r,i,{os:o})&&e.add(i.value);let t=[...e].flatMap(r=>N1(r,o));return[...new Set(t)]}var Z8=[{keywords:["gpg","gpg2"],value:"gnupg"},{keywords:["git"],value:"gnupg"},{keywords:["git","ssh","scp","sftp","rsync"],value:"ssh"}];function Jh(o,n,e=[]){if(n.length===0)return L1(o,e);let t=new Set;for(let i of n){let s=X8.get(i.toLowerCase());s&&t.add(s)}let r=[...t].flatMap(i=>N1(i,o));return[...new Set([...r,...L1(o,e)])]}var e$=[{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}];function t$(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 ap(o,n){let e=new Set;for(let r of n)for(let i of e$)Gh(r,i,{os:o})&&n$(i.value,n)&&e.add(i.value);let t={};for(let r of e)F1(t,t$(r,o));return t}function n$(o,n){switch(o){case"gnupg":return n.every(e=>!e.keyword.toLowerCase().startsWith("docker"));case"node":return!0}}function F1(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}U1(r)&&U1(t)&&F1(r,t)}}function U1(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}var HAe=B("terminalSandboxService");var Vn=class extends x{constructor(e,t,r,i){super();this._host=e;this._fileService=t;this._logService=r;this._windowsMxcRuntime=i;this._sandboxSettingsId=F();this._runtimeResolved=!1;this._runAsNode=!1;this._enableWeakerNestedSandbox=!1;this._apparmorRemediationRequested=!1;this._needsForceUpdateConfigFile=!0;this._commandAllowListKeywords=[];this._commandAllowListCommandDetails=[];this._commandAllowNetwork=!1;this._os=qt;this._defaultWritePaths=[];this._fileSystemPathExtUri=new fs(()=>this._os===1);this._buildSandboxPayload=(e,t,r,i,s)=>this._host.buildWindowsMxcSandboxPayload(e,t,r,i,s);this._pathJoin=(...e)=>(this._os===1?ve:ie).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,g=t!==!0&&(a===!0&&d||p),h=this._normalizeCommandDetails(s??[]),y=this._normalizeCommandKeywords(h.map(L=>L.keyword)),I=Jh(this._os,this._commandAllowListKeywords,this._commandAllowListCommandDetails),S=Jh(this._os,y,h),C=ap(this._os,this._commandAllowListCommandDetails),_=ap(this._os,h);if((this._commandAllowListKeywords.length===0||this._needsForceUpdateConfigFile||!this._areStringArraysEqual(this._commandAllowListKeywords,y)||!this._areStringArraysEqual(I,S)||!this._areObjectsEqual(C,_)||this._commandCwd?.toString()!==i?.toString()||this._commandAllowNetwork!==g||this._os===1&&(this._commandLine!==e||this._commandShell!==r))&&(this._commandAllowListKeywords=y,this._commandAllowListCommandDetails=h,this._commandCwd=i,this._commandLine=e,this._commandShell=r,this._commandAllowNetwork=g,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 w=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:g&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...w}}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 W=this._getSandboxCommandWithPreservedCwd(e,i),R=`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(W)}`;if(this._runAsNode){let L=`ELECTRON_RUN_AS_NODE=1 ${R}`;return{command:this._wrapSandboxRuntimeCommandForLaunch(L,i),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:g&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...w}}return{command:this._wrapSandboxRuntimeCommandForLaunch(R,i),isSandboxWrapped:!0,requiresAllowNetworkConfirmation:g&&!this._isSandboxAllowNetworkConfigured()?!0:void 0,...w}}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?.bubblewrapUsable===!1?this._sandboxDependencyStatus.apparmorRestrictsUnprivilegedUserNamespaces!==!0||e&&this._apparmorRemediationRequested?(this._enableWeakerNestedSandbox||(this._enableWeakerNestedSandbox=!0,await this.getSandboxConfigPath(!0,t)),{enabled:!0,sandboxConfigPath:this._sandboxConfigPath,failedCheck:void 0}):(this._apparmorRemediationRequested=!0,{enabled:!0,sandboxConfigPath:r,failedCheck:"bubblewrap",remediations:this._getBubblewrapRemediations(),detail:this._sandboxDependencyStatus.bubblewrapError}):{enabled:!0,sandboxConfigPath:r,failedCheck:"dependencies",missingDependencies:i,canInstallMissingDependencies:!!this._sandboxDependencyStatus?.dependencyInstallCommand}}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(v.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=>Ib(l,d))){s.add(l),a.add(l);continue}r.some(d=>Ib(l,d))||s.add(l)}return{blockedDomains:[...s],deniedDomains:[...a]}}_extractDomains(e){let t=new Set,r;for(Vn._urlRegex.lastIndex=0;(r=Vn._urlRegex.exec(e))!==null;){let i=this._extractDomainFromUrl(r[0]);i&&t.add(i)}for(Vn._sshRemoteRegex.lastIndex=0;(r=Vn._sshRemoteRegex.exec(e))!==null;){let i=sp(r[1],!0);i&&t.add(i)}for(Vn._hostRegex.lastIndex=0;(r=Vn._hostRegex.exec(e))!==null;){let i=sp(r[1]);i&&t.add(i)}return[...t]}_extractDomainFromUrl(e){try{let t=v.parse(e).authority;return sp(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 SC(r)}let t=this._getSandboxConfiguredEnabledValue();return SC(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}-${XT}`,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"),...this._enableWeakerNestedSandbox?{enableWeakerNestedSandbox:!0}:void 0},l=ap(this._os,this._commandAllowListCommandDetails),d=this._getCommandRuntimeFileSystemPaths(l,"allowRead"),c=this._getCommandRuntimeFileSystemPaths(l,"allowWrite"),u=v.joinPath(this._tempDir,`vscode-sandbox-settings-${this._sandboxSettingsId}.json`),p=this._getUriPath(u),g=[],h=[],y=[],I;if(this._os===1){let C=await this._getWindowsMxcFilesystemPolicy(),_=await this._getWindowsMxcEnvironment();g=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(i.allowWrite),...C.readwritePaths]),h=await this._resolveFileSystemPaths([...i.allowRead??[],...C.readonlyPaths]),y=await this._resolveFileSystemPaths(i.denyRead??[]),this._windowsMxcEnvironment=_}else this._os===2?(g=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,c))).filter(C=>C!==p),h=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(r.allowRead,g,d)),y=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...r.denyRead??[],p])),I=r.denyWrite?await this._resolveFileSystemPaths(r.denyWrite):void 0):this._os===3&&(g=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(t.allowWrite,c))).filter(C=>C!==p),h=await this._resolveFileSystemPaths(await this._updateAllowReadPathsWithAllowWrite(t.allowRead,g,d)),y=await this._resolveFileSystemPaths(this._updateDenyReadPathsWithHome([...t.denyRead??[],p])),I=await this._resolveFileSystemPaths(t.denyWrite));let S=this._os===1?await this._windowsMxcRuntime.createConfig({command:this._commandLine??"",shell:this._commandShell,cwd:this._commandCwd??this._getDefaultWindowsMxcCwd(),tempDir:this._tempDir,schemaVersion:s,allowNetwork:e,allowReadPaths:h,allowWritePaths:g,denyReadPaths:y,env:this._windowsMxcEnvironment??[]},this._buildSandboxPayload):{network:e?{allowedDomains:[],deniedDomains:[],enabled:!1}:this.getResolvedNetworkDomains(),filesystem:{denyRead:y,allowRead:h,allowWrite:g,denyWrite:I}};if(this._os!==1){let C=S;this._mergeAdditionalSandboxConfigProperties(C,a),this._mergeAdditionalSandboxConfigProperties(C,l),this._os===2&&(C.allowPty??=!0)}return this._sandboxConfigPath=p,await this._fileService.createFile(u,$.fromString(JSON.stringify(S,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=ap(this._os,this._commandAllowListCommandDetails),a=this._getCommandRuntimeFileSystemPaths(s,"allowRead"),l=this._getCommandRuntimeFileSystemPaths(s,"allowWrite"),d=[],c=[],u=[],p;if(this._os===1){let g=await this._getWindowsMxcFilesystemPolicy();d=await this._resolveFileSystemPaths([...await this._updateAllowWritePathsWithWorkspaceFolders(i.allowWrite),...g.readwritePaths]),c=await this._resolveFileSystemPaths([...i.allowRead??[],...g.readonlyPaths]),u=await this._resolveFileSystemPaths(i.denyRead??[])}else this._os===2?(d=(await this._resolveFileSystemPaths(await this._updateAllowWritePathsWithWorkspaceFolders(r.allowWrite,l))).filter(g=>g!==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(g=>g!==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)?$m(i,r,{ignoreCase:s}):this._fileSystemPathExtUri.isEqualOrParent(this._toFileSystemAccessUri(r),this._toFileSystemAccessUri(i))}_toFileSystemAccessUri(e){return v.from({scheme:"terminal-sandbox-path",path:e.startsWith("/")?e:`/${e}`})}_normalizeFileSystemAccessPath(e,t=!1){let r=this._os===1?e.replace(/\\/g,"/"):e;return this._os===1&&/^\/[a-zA-Z]:($|\/)/.test(r)&&(r=r.slice(1)),(!t||!this._containsGlobPattern(r))&&(r=ie.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?ve:ie).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??[],...Jh(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?ve:ie).isAbsolute(e)}_toFileSystemResource(e){return this._os===1?this._toWindowsFileSystemResource(e):this._userHome?.with({path:e})??this._tempDir?.with({path:e})??this._host.getWriteRoots()[0]?.with({path:e})??v.file(e)}_toWindowsFileSystemResource(e){let t=e.replace(/\\/g,"/");if(/^\/\/[^/]/.test(t)){let r=t.indexOf("/",2);return r===-1?v.from({scheme:"file",authority:t.slice(2),path:"/"}):v.from({scheme:"file",authority:t.slice(2,r),path:t.slice(r)||"/"})}return/^[a-zA-Z]:($|\/)/.test(t)?v.from({scheme:"file",path:`/${t[0].toLowerCase()}${t.slice(1)}`}):/^\/[a-zA-Z]:($|\/)/.test(t)?v.from({scheme:"file",path:`/${t[1].toLowerCase()}${t.slice(2)}`}):v.from({scheme:"file",path:t})}_expandHomePath(e){let t=this._userHome?.path;return t?e==="~"?t:e.startsWith("~/")?this._pathJoin(t,e.slice(2)):e:e}_getSandboxRuntimeReadPaths(){if(!this._appRoot)return[];if(this._os===1)return this._windowsMxcRuntime.getRuntimeReadPaths(this._appRoot,this._mxcPath);let e=[this._appRoot];if(this._execPath)for(let t of[this._execPath,this._pathDirname(this._execPath)])this._isPathUnderAppRoot(t)||e.push(t);return e}_isPathUnderAppRoot(e){return this._appRoot?e===this._appRoot||e.startsWith(`${this._appRoot}${this._os===1?ve.sep:ie.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":vC(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)}};Vn=A([b(1,xe),b(2,O),b(3,Kh)],Vn);var o$="tmp",bb=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 qt}async getRuntimeInfo(){let n=te(Nt.asFileUri("").path),e=!!process.versions.electron,t=PE();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=v.joinPath(n,this._productService.dataFolderName,o$),r=`agenthost_${r$("sha256").update(this._sessionId).digest("hex").substring(0,16)}`;return v.joinPath(e,r)}async getWorkspaceStorageReadRoot(){}getWriteRoots(){return this._workingDirectory?[this._workingDirectory]:[]}async checkSandboxDependencies(){return this._sandboxHelper.checkSandboxDependencies()}async getWindowsMxcFilesystemPolicy(){return this._sandboxHelper.getWindowsMxcFilesystemPolicy()}async getWindowsMxcEnvironment(){return this._sandboxHelper.getWindowsMxcEnvironment()}async buildWindowsMxcSandboxPayload(n,e,t,r,i){return this._sandboxHelper.buildWindowsMxcSandboxPayload(n,e,t,r,i)}getSandboxSetting(n){let e=RA[n];return e===void 0?void 0:this._agentConfigurationService.getRootValue(zr,"sandbox")?.[e]}};function $1(o,n,e,t,r,i,s){let a=new bb(i,s,n,e,t,r);return o.createInstance(Vn,a)}var i$="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.",jo=class extends x{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 E);this.onDidAssociateTerminal=this._onDidAssociateTerminal.event;this._register(U(()=>{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()??F(),t=$1(this._instantiationService,this._environmentService,this._productService,this._agentConfigurationService,this._sandboxHelper,e,this.workingDirectory);this._register(t),this._register(U(()=>{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=F(),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 G,r=()=>{this._busyShellIds.delete(e.id),this._heldShellReleaseListeners.delete(e.id),t.dispose()};t.add(this._terminalManager.onCommandFinished(e.terminalUri,r)),t.add(this._terminalManager.onExit(e.terminalUri,r)),this._heldShellReleaseListeners.set(e.id,t)}_trackToolCall(e,t){this._toolCallShells.set(e,t);let r=this._shells.get(t);if(r){let 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}};jo=A([b(2,ur),b(3,O),b(4,we),b(5,ku),b(6,Tt),b(7,Ue),b(8,Vh)],jo);function Vo(o){return{textResultForLlm:o,resultType:"success"}}function jn(o,n){return{textResultForLlm:o,resultType:"failure",error:n}}function lp(o,n){return{toolResult:o,keepShellBusy:n?.keepShellBusy}}function s$(o,n){switch(o.status){case"completed":{let e=o.exitCode??0,t=`Exit code: ${e}
${o.output}`;return lp(e===0?Vo(t):jn(t))}case"shellExited":return lp(jn(`Shell exited with code ${o.exitCode}
${o.output}`));case"timeout":return lp(jn(`Command timed out after ${Math.round(n/1e3)}s. Partial output:
${o.output}`,"timeout"));case"background":return lp(Vo("The user chose to continue this command in the background. The terminal is still running."),{keepShellBusy:!0});case"altBuffer":return lp(jn(i$,"alternateBuffer"),{keepShellBusy:!0})}}async function a$(o,n,e,t,r){let i=s$(await Um(o,n,e,t,r),e);return{...i,toolResult:{...i.toolResult,textResultForLlm:`Shell ID: ${o.id}
${i.toolResult.textResultForLlm}`}}}async function W1(o,n,e,t){let r=await o.getResolvedExecutable(),i=Nm(r),s=o.getOrCreateSandboxEngine(),a=await s.isEnabled(),l=a?s.getResolvedNetworkDomains():void 0,d={name:i,description:i==="bash"?Og(r)?u$(a,l):c$(a,l):d$(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(S,C)=>{let _=S.timeout??Lm,T=await o.getOrCreateShell(i,C.toolCallId,C.toolCallId),w=!0;try{let W=S.command;if(a){if(S.requestUnsandboxedExecution&&!s.areUnsandboxedCommandsAllowed())return jn("Unsandboxed execution is disabled by the chat.agent.sandbox.allowUnsandboxedCommands setting.","unsandboxed_disabled");let L=async z=>{if(!t){let me=z?.join(", ")??"(unknown)";return jn(`Command requires approval to run outside the sandbox. Blocked domains: ${me}. Re-run with requestUnsandboxedExecution=true and requestUnsandboxedExecutionReason explaining why unsandboxed access is required.`,"sandbox_blocked")}return await t({toolCallId:C.toolCallId,toolName:C.toolName,shellExecutable:r,command:S.command,reason:S.requestUnsandboxedExecutionReason,blockedDomains:z})},D=await s.wrapCommand(S.command,S.requestUnsandboxedExecution,r,T.object.shellType==="bash"?o.workingDirectory:void 0);if(S.requestUnsandboxedExecution&&!D.isSandboxWrapped){let z=await L(D.blockedDomains);if(typeof z!="boolean")return z;if(!z){let J=D.blockedDomains?.join(", ")??"(none)";return jn(`User declined to run command outside the sandbox. Blocked domains: ${J}.`,"sandbox_blocked")}}if(D.requiresUnsandboxConfirmation){let z=await L(D.blockedDomains);if(typeof z!="boolean")return z;if(!z){let J=D.blockedDomains?.join(", ")??"(unknown)";return jn(`User declined to run command outside the sandbox. Blocked domains: ${J}.`,"sandbox_blocked")}D=await s.wrapCommand(S.command,!0,r,T.object.shellType==="bash"?o.workingDirectory:void 0)}W=D.command}let R=await a$(T.object,W,_,n,e);return R.keepShellBusy&&(w=!1,o.holdShellUntilCommandFinishes(T.object)),R.toolResult}finally{w&&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:S=>{let C=o.listShells(),_=S.shell_id?o.getShell(S.shell_id):C[C.length-1];if(!_)return jn("No active shell found.","no_shell");let T=n.getContent(_.terminalUri);return Vo(T?Pi(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 S=>{let C=o.listShells(),_=C[C.length-1];return _?(await n.sendText(_.terminalUri,S.command,{shouldExecute:!1}),Vo("Input sent to shell.")):jn("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:S=>{if(S.shell_id)return o.shutdownShell(S.shell_id)?Vo("Shell stopped."):jn("Shell not found.","not_found");let C=o.listShells(),_=C[C.length-1];return _?(o.shutdownShell(_.id),Vo("Shell stopped.")):jn("No active shell to stop.","no_shell")}},g={name:`list_${i}`,description:`List active ${i} shell instances.`,parameters:{type:"object",properties:{}},overridesBuiltInTool:!0,skipPermission:!0,handler:()=>{let S=o.listShells();if(S.length===0)return Vo("No active shells.");let C=S.map(_=>{let T=n.getExitCode(_.terminalUri),w=T!==void 0?`exited (${T})`:"running";return`- ${_.id}: ${_.shellType} [${w}]`});return Vo(C.join(`
`))}},h=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,g,{name:h,description:y,parameters:{type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Timeout in milliseconds (default 120000)"}},required:["command"]},overridesBuiltInTool:!0,skipPermission:!0,handler:()=>jn(y,"wrong_shell")}]}function l$(o){return o.endsWith("System32\\WindowsPowerShell\\v1.0\\powershell.exe")}function d$(o,n,e,t){let r=l$(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(...q1(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 q1(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 B1(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(q1(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 c$(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.",B1("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 u$(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.",B1("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 p$}from"child_process";function j1(o){let n={};for(let e of o)n[e.name]=G1(e.name,e.configuration);return n}function K1(o){let n={};for(let[e,t]of Object.entries(o))f$(t)&&(n[e]=G1(e,t));return n}function f$(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 G1(o,n){return n.type==="stdio"?{type:"local",command:n.command,args:n.args?[...n.args]:[],tools:["*"],...n.env&&{env:g$(n.env)},...n.cwd&&{cwd:n.cwd}}:{type:"http",url:n.url,tools:["*"],...n.headers&&{headers:{...n.headers}}}}function g$(o){let n={};for(let[e,t]of Object.entries(o))t!==null&&(n[e]=String(t));return n}async function z1(o,n){let e=[];for(let t of o)try{let i=(await n.readFile(t.uri)).value.toString(),s=gd(i);if(!s)e.push({name:t.name,prompt:i});else{let a=s.getStringValue("name")?.trim()||t.name,l=s.getStringValue("description"),d=s.getStringArrayValue("tools"),c=s.getStringArrayValue("skills"),u=s.getBooleanValue("infer"),p=s.getBooleanValue("disable-model-invocation");u===void 0&&p===!0&&(u=!1);let g=s.body??i,h=s.getStringValue("model")??void 0,y=s.getStringArrayValue("model")??void 0;!h&&y&&Array.isArray(y)&&y.length>0&&(h=y[0]),e.push({name:a,...l?{description:l}:{},...h?{model:h}:{},tools:d&&d.length>0?d:null,...c!==void 0?{skills:c}:{},...u!==void 0?{infer:u}:{},prompt:g})}}catch{}return e}async function J1(o,n,e){let t=o.filter(i=>!i.pluginDir||i.pluginDir.scheme!==ne.file),r=await z1(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 z1(i,e))r.some(a=>a.name===s.name)||r.push(s)}return r}function _b(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 Y1(o){return X1(o)}function Q1(o){return X1(o)}function X1(o){let n=new Set,e=[];for(let t of o){let r=te(t.uri.fsPath);n.has(r)||(n.add(r),e.push(r))}return e}function m$(o,n){return n===1&&o.windows?o.windows:n===2&&o.osx?o.osx:n===3&&o.linux?o.linux:o.command}function dp(o,n){let e=m$(o,qt);if(!e)return Promise.resolve("");let t=(o.timeout??30)*1e3,r=o.cwd?.fsPath;return new Promise((i,s)=>{let a=qt===1,c=p$(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",g=>{u+=g.toString()}),c.stderr.on("data",g=>{p+=g.toString()}),n&&c.stdin.write(n),c.stdin.end(),c.on("error",s),c.on("close",g=>{g===0?i(u):s(new Error(`Hook command exited with code ${g}: ${p||u}`))})})}async function V1(o,n){if(!o)return;let e=JSON.stringify(n);for(let t of o)try{let r=await dp(t,e);if(r.trim())try{let i=JSON.parse(r);if(i&&typeof i=="object")return i}catch{}}catch{}}var h$={PreToolUse:"onPreToolUse",PostToolUse:"onPostToolUse",UserPromptSubmit:"onUserPromptSubmitted",SessionStart:"onSessionStart",SessionEnd:"onSessionEnd",ErrorOccurred:"onErrorOccurred"};function Z1(o,n){let e=new Map;for(let c of o){let u=h$[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),V1(r,c)));let i=e.get("onPostToolUse");(i?.length||n)&&(t.onPostToolUse=async c=>(await n?.onPostToolUse(c),V1(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 dp(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 dp(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 dp(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 dp(p,u)}catch{}}),t}function e0(o,n){let e=t=>JSON.stringify(t.map(r=>({format:r.format,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 y$=!1;function cp(o,n){if(!n||o==="win32"&&!y$)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 I of r.denyWrite??[])i.has(I)||s.add(I);for(let I of r.allowWrite??[])!i.has(I)&&!s.has(I)&&a.add(I);for(let I of r.allowRead??[])!i.has(I)&&!s.has(I)&&!a.has(I)&&s.add(I);let d=e==="allowNetwork"||e==="on"&&n.allowNetwork===!0,c=!1,u=n.allowedNetworkDomains,p=n.deniedNetworkDomains,g=!d&&c&&u?.length?[...u]:void 0,h=!d&&c&&p?.length?[...p]:void 0,y=d||!!g||!!h;return{enabled:!0,allowBypass:!0,userPolicy:{filesystem:{...a.size?{readwritePaths:[...a]}:{},...s.size?{readonlyPaths:[...s]}:{},...i.size?{deniedPaths:[...i]}:{}},network:{allowOutbound:y,...y&&g?{allowedHosts:g}:{},...y&&h?{blockedHosts:h}:{}}}}}var Tb="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.",t0=["<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(`
`),up={mode:"customize",sections:{identity:{action:"replace",content:Tb}}},wb=["<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 n0(o){return{mode:"replace",content:o}}function r0(o){return{mode:"customize",sections:o}}function o0(o,n){if(o.mode==="replace")return o;let e=o.content;return{...o,content:e?`${e}

${n}`:n}}function i0(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 pp={OpenBrowserPage:"openBrowserPage",ReadPage:"readPage",ScreenshotPage:"screenshotPage",NavigatePage:"navigatePage",ClickElement:"clickElement",TypeInPage:"typeInPage",HoverElement:"hoverElement",DragElement:"dragElement",HandleDialog:"handleDialog",RunPlaywrightCode:"runPlaywrightCode"},s0=Object.values(pp);var v$=s0.filter(o=>o!==pp.OpenBrowserPage),S$=o=>{if(!o(pp.OpenBrowserPage))return;let n=v$.find(o);if(n)return`Use the browser tools (${pp.OpenBrowserPage}, ${n}, etc.) when beneficial for front-end tasks, such as when visualizing or validating UI changes.`},Yh=[S$],C$=o=>o(no)?`Most tools are deferred and hidden until you search for them. Before calling a tool that has not already been loaded, ALWAYS call \`${Cd}\` first with a short description of the capability you need, then call the specific tool it returns; tools it returns are immediately available and must not be searched for again.`:void 0;function a0(o){return o?[...Yh,C$]:Yh}function I$(o,n=Yh){let e=Qo(n.map(t=>t(o)));return e.length>0?e.join(`
`):void 0}function b$(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 l0(o,n,e=Yh){let t=I$(o,e);return t===void 0?void 0:b$(n,t)}var Rb=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 o0(r,t0)}_resolveModelConfig(n,e){if(!n)return up;let t=this._getContributor(n);if(!t)return up;let r=new t,i=r.resolveFullSystemPrompt?.(n,e);if(i!==void 0)return n0(i);let s=r.resolveSectionOverrides?.(n,e);return s&&Object.keys(s).length>0?r0(s):up}_withUniversalSections(n,e){if(n.mode!=="customize")return n;let t=l0(r=>e.hasClientTool(r),n.sections?.tool_instructions,a0(e.toolSearchActive));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}

${wb}`:wb;return{...n,content:t}}},Qh=new Rb;function _$(){return{identity:{action:"replace",content:Tb},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 T$(o){return o.id.startsWith("claude-opus-4-8")||o.id.startsWith("claude-opus-4.8")}var xb=class{static{this.familyPrefixes=[]}static matchesModel(n){return T$(n)}resolveSectionOverrides(n,e){return e.getSetting("opus48Prompt")===!0?_$():void 0}};Qh.registerPrompt(xb);var Eb="thinkingLevel",ey="contextSize",w$="contextTier",d0=["low","medium","high","xhigh"],R$=["default","long_context"],x$="vscode-agent-host";function kb(o){return new Set(o.tools.map(n=>n.name))}function Pb(o){return d0.some(n=>n===o)}function A$(o){return R$.some(n=>n===o)}function Xh(o){if(typeof o!="object"||o===null)return;let n=Object.getOwnPropertyDescriptor(o,"code")?.value;return typeof n=="number"?n:void 0}function Zh(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 P$(o){if(Xh(o)!==-32603)return!1;let n=Zh(o);return!/\b(corrupt|corrupted|invalid|validation|schema|must be|parse|malformed|unexpected token)\b/i.test(n)}function E$(o){return Xh(o)===-32603&&/\bCustom agent '.+' not found\b/i.test(Zh(o))}function k$(o,n){if(Pb(n))return n;let e=o?.config?.[Eb];return Pb(e)?e:void 0}function ty(o,n,e,t){let r=n.getRootValue(jt,"reasoningEffortOverride"),i=r||void 0;return i!==void 0&&(Pb(i)?e.info(`[Copilot:${t}] Applying reasoning-effort override '${i}'`):e.warn(`[Copilot:${t}] Ignoring invalid reasoning-effort override '${i}'; expected one of [${d0.join(", ")}]`)),k$(o,i)}function ny(o,n,e){let t=o?.config?.[w$];if(A$(t))return t;let r=o?.config?.[ey];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 D$(o,n,e,t){let r;try{r=[...n.getModels()]}catch(d){return t.warn(`[Copilot:${o}] Failed to enumerate BYOK models from renderer bridges`,d),{}}if(r.length===0)return{};let i=new Set;r=r.filter(d=>{let c=`${d.vendor}/${d.id}`;return i.has(c)?!1:(i.add(c),!0)});let s;try{s=await e()}catch(d){return t.warn(`[Copilot:${o}] Failed to start BYOK loopback proxy`,d),{}}let a=[...new Set(r.map(d=>d.vendor))].map(d=>({name:d,type:"openai",wireApi:"completions",baseUrl:s.providerBaseUrl(d),bearerToken:`${s.nonce}.${o}`})),l=r.map(d=>({id:d.id,provider:d.vendor,...d.name!==void 0?{name:d.name}:{},...d.maxContextWindowTokens!==void 0?{maxContextWindowTokens:d.maxContextWindowTokens}:{}}));return t.info(`[Copilot:${o}] Wired ${l.length} BYOK model(s) across ${a.length} provider(s) via loopback proxy ${s.baseUrl}`),{providers:a,models:l}}var wd=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 lt;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 Td(l)}catch(a){let l=a,d=Xh(l),c=Zh(l);if(this._logService.warn(`[Copilot:${n.sessionId}] SDK resumeSession failed: code=${d}, message=${c}`),n.resolvedAgentName&&E$(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 Td(p)}catch(p){l=p,this._logService.warn(`[Copilot:${n.sessionId}] SDK resumeSession without custom agent failed: code=${Xh(p)}, message=${Zh(p)}`)}}if(!P$(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:ty(n.model,this._configurationService,this._logService,n.sessionId),contextTier:ny(n.model,n.longContextWindow,n.freeLongContext),...n.resolvedAgentName?{agent:n.resolvedAgentName}:{},workingDirectory:n.workingDirectory?.fsPath});return await this._applySandboxConfig(r,t,n.sessionId),new Td(r)}_computeSandboxConfig(){if(this._configurationService.getRootValue(jt,"enableCustomTerminalTool")!==!0)return cp(process.platform,this._configurationService.getRootValue(zr,"sandbox"))}async _applySandboxConfig(n,e,t){if(e)try{await n.rpc.options.update({sandboxConfig:e}),this._logService.info(`[Copilot:${t}] Applied SDK sandboxConfig via session.options.update`)}catch(r){this._logService.warn(`[Copilot:${t}] Failed to apply SDK sandboxConfig`,r)}}_resolveByokSessionConfig(n){return D$(n,this._byokLmBridgeRegistry,()=>(this._byokProxyHandle||(this._byokProxyHandle=this._byokLmProxyService.start()),this._byokProxyHandle),this._logService)}async disposeByokProxyHandle(){let n=this._byokProxyHandle;if(this._byokProxyHandle=void 0,!!n)try{(await n).dispose()}catch{}}async _buildSessionConfig(n,e){let t=n.snapshot.plugins,r=await this._resolveByokSessionConfig(n.sessionId),i=this._configurationService.getRootValue(jt,"enableCustomTerminalTool")===!0,s=[];if(i){if(!n.shellManager)throw new Error(`ShellManager is required to launch Copilot session '${n.sessionId}'`);s=await W1(n.shellManager,this._terminalManager,this._logService,S=>e.requestUnsandboxedCommandConfirmation(S))}let a=t.filter(S=>!S.pluginDir||S.pluginDir.scheme!==ne.file),l=await J1(t,n.resolvedAgentName,this._fileService),d=Y1(a.flatMap(S=>S.skills)),c=Q1(t.flatMap(S=>S.instructions)),u=n.kind==="create"?n.model:n.fallback.model,p=kb(n.snapshot),g=Tg(u,this._configurationService.getRootValue(jt,"modelCapabilityOverrides"));u&&g!==u&&this._logService.info(`[Copilot:${n.sessionId}] Model capability override: routing prompt for '${u.id}' as family '${g?.id}'`);let h=this._configurationService.getRootValue(jt,"toolSearchEnabled")===!0&&Wh(g?.id)&&p.has(no),y={getSetting:S=>this._configurationService.getRootValue(jt,S),hasClientTool:S=>p.has(S),workspaceless:n.workspaceless===!0,toolSearchActive:h},I=Qh.resolveSystemMessageConfig(g,y);return this._logService.info(`[Copilot:${n.sessionId}] Resolved system message: ${i0(I)}`),this._logService.getLevel()<=1&&this._logService.trace(`[Copilot:${n.sessionId}] System message config: ${JSON.stringify(I,(S,C)=>typeof C=="function"?"[transform fn]":C)}`),{...r,clientName:x$,enableMcpApps:!0,enableFileHooks:!0,enableConfigDiscovery:!0,requestExtensions:!1,onPermissionRequest:S=>e.handlePermissionRequest(S),onUserInputRequest:(S,C)=>e.handleUserInputRequest(S,C),onElicitationRequest:S=>e.handleElicitationRequest(S),onMcpAuthRequest:(S,C)=>e.handleMcpAuthRequest(S,C),hooks:Z1(a.flatMap(S=>S.hooks),{onPreToolUse:S=>e.handlePreToolUse(S),onPostToolUse:S=>e.handlePostToolUse(S)}),mcpServers:{...K1(n.snapshot.mcpServers),...j1(a.flatMap(S=>S.mcpServers))},onExitPlanModeRequest:(S,C)=>e.handleExitPlanModeRequest(S,C),workingDirectory:n.workingDirectory?.fsPath,customAgents:l,agent:n.resolvedAgentName,skillDirectories:d,instructionDirectories:c,systemMessage:I,toolSearch:h?{enabled:!0,deferThreshold:1}:{enabled:!1},pluginDirectories:Qo(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(tt,Gc)===!0?"export":void 0,enableManagedSettings:!0}}};wd=A([b(0,Ue),b(1,ur),b(2,O),b(3,xe),b(4,zh),b(5,qi)],wd);var Mb=900*1024,M$=50*8192,O$=100,L$=720*60*60*1e3,N$=30,U$=4,Db=1e5;function F$(o,n){let e=o.includes("://")?void 0:/^(?:[^@\s]+@)?(?<host>[^:\s]+):(?<path>.+)$/.exec(o),t,r,i;if(e?.groups)t=e.groups.host,r=e.groups.path,i=`https://${t}/${r}`;else{let c;try{c=new URL(o)}catch{return}t=c.host,r=c.pathname,i=`https://${t}${r}`}let s=t.toLowerCase(),a=s.replace(/:\d+$/,""),l=r.replace(/^\/+|\/+$/g,"");if(a==="github.com"||s===n?.toLowerCase()||a==="ghe.com"||a.endsWith(".ghe.com")){let c=/^(?<owner>[^/]+)\/(?<repo>[^/]+?)(?:\.git)?$/i.exec(l);return c?.groups?{remoteUrl:i,repoId:`${c.groups.owner}/${c.groups.repo}`.toLowerCase(),repoType:"github"}:void 0}let d=null;if(a==="dev.azure.com"?d=/^(?<org>[^/]+)\/(?<project>[^/]+)\/_git\/(?:_(?:optimized|full)\/)?(?<repo>[^/]+?)(?:\.git)?$/i.exec(l):a==="ssh.dev.azure.com"?d=/^v3\/(?<org>[^/]+)\/(?<project>[^/]+)\/(?:_(?:optimized|full)\/)?(?<repo>[^/]+?)(?:\.git)?$/i.exec(l):a.endsWith(".visualstudio.com")&&(d=/^v3\/(?<org>[^/]+)\/(?<project>[^/]+)\/(?:_(?:optimized|full)\/)?(?<repo>[^/]+?)(?:\.git)?$/i.exec(l)??/^(?:[^/]+\/)?(?<project>[^/]+)\/_git\/(?:_(?:optimized|full)\/)?(?<repo>[^/]+?)(?:\.git)?$/i.exec(l),d?.groups&&!d.groups.org&&(d.groups.org=a.substring(0,a.length-17))),!(!d?.groups?.org||!d.groups.project||!d.groups.repo))return{remoteUrl:i,repoId:`${d.groups.org}/${d.groups.project}/${d.groups.repo}`.toLowerCase(),repoType:"ado"}}function H$(o){let n=Buffer.byteLength(o,"utf8");return{diffSizeBytes:n,tooLarge:n>Mb||o.length>M$}}var Rd=class extends x{constructor(e,t,r,i){super();this._reporter=e;this._gitService=t;this._gitHubEndpointService=r;this._logService=i;this._beginResults=new Map;this._isDisposed=!1}async reportBegin(e,t,r,i,s,a){let l=this._beginResults.get(r);l||(l=this._captureSafely(e,t,r,"begin",i,s,a),this._beginResults.set(r,l)),await l}async reportEnd(e,t,r,i,s,a){let l=this._beginResults.get(r);if(l)try{let d=await l;(d==="success"||d==="noChanges")&&await this._captureSafely(e,t,r,"end",i,s,a)}finally{this._beginResults.delete(r)}}clearTurn(e){this._beginResults.delete(e)}dispose(){this._isDisposed=!0,this._beginResults.clear(),super.dispose()}async _captureSafely(e,t,r,i,s,a,l){try{return await this._capture(e,t,r,i,s,a,l)}catch(d){this._logService.warn(`[AgentHostRepoInfoTelemetry] Failed to capture ${i} repo info: ${d instanceof Error?d.message:String(d)}`);return}}async _capture(e,t,r,i,s,a,l){if(!s||!l()||!e.restrictedTelemetryEnabled&&!e.isInternal)return;let[d,c]=await Promise.all([this._gitService.getSessionGitState(s),this._gitService.getUntrackedPaths(s)]),u=d?.upstreamBranchName?.split("/")[0],g=(await this._gitService.getFetchRemoteUrls(s,u))?.map(k=>F$(k,this._gitHubEndpointService.getEnterpriseHost())).find(k=>k!==void 0);if(!g)return;let h=a??d?.upstreamBranchName??d?.baseBranchName??(await this._gitService.getDefaultBranch(s))?.name,[y,I]=await Promise.all([d?.branchName?Promise.resolve(d.branchName):this._gitService.getCurrentBranch(s),this._gitService.resolveBranchBaselineCommit(s,h)]);if(!I)return;let S={...g,headCommitHash:I,headBranchName:y},C=await this._gitService.getBranchDiffSafetyInfo(s,I);if(!C)return;if(C.hasVirtualFileSystem)return this._report(e,l,r,i,S,"virtualFileSystem",0,0,0);if(C.baselineCommitTimestamp===void 0||Date.now()-C.baselineCommitTimestamp>L$)return this._report(e,l,r,i,S,"mergeBaseTooOld",0,0,0);if(C.commitCount===void 0||C.commitCount>=N$)return this._report(e,l,r,i,S,"tooManyCommits",0,0,0);let _=await this._gitService.captureWorkingTreeAsTree(s);if(!_)return;let T=await this._gitService.computeFileDiffsBetweenRefs(s,{sessionUri:t,fromRef:I,toRef:_});if(!T)return;if(T.length===0)return await this._reportIfTreeUnchanged(e,l,r,i,S,s,_,"noChanges",C.workspaceFileCount,0,0);if(T.length>O$)return this._report(e,l,r,i,S,"tooManyChanges",C.workspaceFileCount,T.length,0);let w=await this._gitService.getRepositoryRoot(s);if(!w)return;let W=new Set(c??[]),R=T.map(k=>this._describeFileDiff(w,k,W));if(R.some(k=>k===void 0))return;let L=R,D=JSON.stringify([...new Set(L.map(k=>k.newPath??k.oldPath).filter(k=>k!==void 0))]);if(e.copilotIgnoreEnabled!==!1)return await this._reportIfTreeUnchanged(e,l,r,i,S,s,_,"success",C.workspaceFileCount,T.length,0,D);let z=!1,J=new Lr(U$),me=await Promise.all(L.map(k=>J.queue(async()=>{let P=[k.oldPath,k.newPath].filter(H=>H!==void 0),q=await this._gitService.getDiffPatchBetweenRefs(s,{fromRef:I,toRef:_,paths:P,maxBuffer:Mb});if(!q)throw new Error(`Failed to compute diff for ${P.join(", ")}`);return q.tooLarge&&(z=!0),{uri:k.uri,originalUri:k.originalUri,renameUri:k.renameUri,status:k.status,diff:$$(q.patch??"",k.uri)}})));if(z)return await this._reportIfTreeUnchanged(e,l,r,i,S,s,_,"diffTooLarge",C.workspaceFileCount,T.length,Mb+1,D);let We=JSON.stringify(me),je=H$(We);return je.tooLarge?await this._reportIfTreeUnchanged(e,l,r,i,S,s,_,"diffTooLarge",C.workspaceFileCount,T.length,je.diffSizeBytes,D):await this._reportIfTreeUnchanged(e,l,r,i,S,s,_,"success",C.workspaceFileCount,T.length,je.diffSizeBytes,D,We)}async _reportIfTreeUnchanged(e,t,r,i,s,a,l,d,c,u,p,g,h){let y=await this._gitService.captureWorkingTreeAsTree(a);return!y||y!==l?this._report(e,t,r,i,s,"filesChanged",c,u,0):this._report(e,t,r,i,s,d,c,u,p,g,h)}_describeFileDiff(e,t,r){let i=t.before?.uri,s=t.after?.uri,a=i?Zn(e,v.parse(i)):void 0,l=s?Zn(e,v.parse(s)):void 0;if(!a&&!l||!i&&!s)return;let d=s??i,c;return i?s?i!==s?c="INDEX_RENAMED":c="MODIFIED":c="DELETED":c=l&&r.has(l)?"UNTRACKED":"INDEX_ADDED",{uri:d,originalUri:i??d,renameUri:c==="INDEX_RENAMED"?s:void 0,status:c,oldPath:a,newPath:l}}_report(e,t,r,i,s,a,l,d,c,u,p){return this._isDisposed||!t()||this._reporter.reportRepoInfo(e,{telemetryMessageId:r,location:i,remoteUrl:s.remoteUrl,repoId:s.repoId,repoType:s.repoType,headCommitHash:s.headCommitHash,headBranchName:s.headBranchName,fileRelativePaths:u,diffsJSON:p,result:a,isActiveRepository:"true",workspaceFileCount:l,changedFileCount:d,diffSizeBytes:c}),a}};Rd=A([b(1,$e),b(2,wt),b(3,O)],Rd);function $$(o,n){return o.length<=Db?o:`${o.substring(0,Db)}
... Diff truncated (exceeded ${Db} characters) for ${n}`}var Rt=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 be;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 be;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)}hasBufferedResult(n){return this._earlyResults.has(n)}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 ry(o){let n=o.data,e=n.kind;if(W$(n.content))switch(e.type){case"shell_completed":case"shell_detached_completed":{let r=e.description;return{messageText:r?f(2297,null,r):f(2296,null),startsTurn:!0}}case"agent_completed":return{messageText:e.status==="failed"?f(2292,null,e.agentId):f(2291,null,e.agentId),startsTurn:!0};case"agent_idle":return{messageText:f(2293,null,e.agentId),startsTurn:!0};case"new_inbox_message":return{messageText:f(2295,null,e.senderName),startsTurn:!1};case"instruction_discovered":return{messageText:f(2294,null,e.description??e.sourcePath),startsTurn:!1};default:return}}function W$(o){let n=o.trim();return(/^<system_notification>\s*([\s\S]*?)\s*<\/system_notification>$/.exec(n)?.[1]??n).trim()}function Ob(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}}function Lb(o,n){return`agenthost-terminal://shell/${encodeURIComponent(M.id(o))}/${encodeURIComponent(n)}`}function q$(o){let n=o&&/<shellId: ([^>\r\n]+) completed with exit code (-?\d+)>\s*$/.exec(o);if(n)return{exitCode:Number(n[2]),preview:o.slice(0,n.index)}}var xd=class extends x{constructor(e,t){super();this._sessionUri=e;this._terminalManager=t;this._streams=new Map;this._register(U(()=>{for(let r of this._streams.values())r.created&&this._terminalManager.disposeTerminal(r.uri);this._streams.clear()}))}track(e,t){this._streams.has(e)||this._streams.set(e,{uri:Lb(this._sessionUri,e),title:t,lastEmitted:"",finalized:!1,created:!1})}append(e,t){let r=this._streams.get(e);if(!r)return;let i=!r.created;return i&&this._createTerminal(e,r),r.finalized||t===r.lastEmitted?{uri:r.uri,created:i}:(t.startsWith(r.lastEmitted)?this._terminalManager.appendOutputTerminalData(r.uri,t.slice(r.lastEmitted.length)):(this._terminalManager.resetOutputTerminal(r.uri),this._terminalManager.appendOutputTerminalData(r.uri,t)),r.lastEmitted=t,{uri:r.uri,created:i})}completeToolCall(e,t,r){let i=this._streams.get(e);if(!i)return;let s=r?.result??q$(t);if(!s){if(!i.created){this._streams.delete(e);return}return{uri:i.uri,shouldRetire:!1}}return i.created||this._createTerminal(e,i),s.preview!==void 0&&this.append(e,s.preview),s.exitCode!==void 0&&this._finalize(i,s.exitCode),{uri:i.uri,result:s,shouldRetire:i.finalized&&s.preview!==void 0}}retire(e){let t=this._streams.get(e);t&&(this._streams.delete(e),t.created&&this._terminalManager.disposeTerminal(t.uri))}_finalize(e,t){e.finalized||(e.finalized=!0,this._terminalManager.finalizeOutputTerminal(e.uri,t))}_createTerminal(e,t){let r={kind:"session",session:this._sessionUri.toString(),toolCallId:e};this._terminalManager.createOutputTerminal(t.uri,{title:t.title,claim:r}),t.created=!0}};xd=A([b(1,ur)],xd);function u0(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 c0(o){let n=o?.agent_id;return typeof n=="string"&&n.length>0?n:void 0}var B$=[/^\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 Nb(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 B$){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 z$=new Set(["edit","str_replace","insert","create","apply_patch","git_apply_patch"]),V$=new Set(["edit","str_replace","insert","create"]);function Ad(o,n){return z$.has(o)?!0:o==="str_replace_editor"?n!==void 0&&V$.has(n):!1}function oy(o){if(typeof o=="string"){try{o=JSON.parse(o)}catch{return Nb(o)}if(typeof o=="string")return Nb(o)}if(!o||typeof o!="object")return[];let n=o;if(typeof n.input=="string"||typeof n.patch=="string")return Nb(n);let e=o;return typeof e.path=="string"?[e.path]:[]}var fp=new Set(["bash","powershell"]),Ub=new Set(["write_bash","write_powershell"]),p0=new Set(["read_bash","read_powershell"]),j$=new Set(["task"]),K$=new Set(["grep","rg","glob"]),G$=new Set(["report_intent","skill"]);function iy(o){return G$.has(o)}function f0(o){return o==="list_agents"||o==="read_agent"||o==="write_agent"}function Pd(o){return o==="task_complete"}function J$(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 gp(o,n){let e=J$(o,n);if(e)return`

`+f(2371,null,e)}function ji(o){return fp.has(o)}function sy(o,n){if(ji(o)&&typeof n?.description=="string"&&n.description.length>0)return n.description}function xr(o,n){return o.length>n?o.substring(0,n-3)+"...":o}function ro(o){let n=v.file(o);return`[${Xs(Se(n))}](${n})`}function g0(o){return new nh().appendLink(o,xr(o,80)).value}function Ae(o){return{markdown:o}}function Ar(o){let n=Rr(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(2378,null);case"create":return f(2376,null);case"view":return f(2392,null);case"bash":case"powershell":return f(2400,null);case"read_bash":case"read_powershell":return f(2394,null);case"write_bash":return f(2413,null);case"write_powershell":return f(2414,null);case"stop_bash":case"stop_powershell":case"bash_shutdown":case"powershell_shutdown":return f(2404,null);case"list_bash":case"list_powershell":return f(2385,null);case"grep":case"rg":case"glob":return f(2398,null);case"search_code_subagent":return f(2399,null);case"apply_patch":return f(2372,null);case"git_apply_patch":return f(2390,null);case"codeql_checker":return f(2374,null);case"code_review":return f(2375,null);case"reply_to_comment":return f(2395,null);case"think":return f(2408,null);case"report_intent":return f(2396,null);case"report_progress":return f(2397,null);case"web_search":return f(2411,null);case"web_fetch":return f(2381,null);case"update_todo":return f(2410,null);case"show_file":return f(2401,null);case"fetch_copilot_cli_documentation":return f(2380,null);case"propose_work":return f(2391,null);case"task_complete":return f(2407,null);case"ask_user":return f(2373,null);case"skill":return f(2383,null);case"task":return f(2406,null);case"list_agents":return f(2384,null);case"read_agent":return f(2393,null);case"exit_plan_mode":return f(2379,null);case"sql":return f(2403,null);case"lsp":return f(2386,null);case"create_pull_request":return f(2377,null);case"gh-advisory-database":return f(2382,null);case"store_memory":return f(2405,null);case"parallel_validation":return f(2389,null);case"write_agent":return f(2412,null);case"mcp_reload":return f(2387,null);case"mcp_validate":return f(2388,null);case"tool_search_tool_regex":return f(2409,null);default:return o}}function Pr(o,n,e){let t=Rr(o,e)?.invocationMessage;if(t!==void 0)return t;if(fp.has(o)){let r=e;if(r?.command){let i=r.command.split(`
`)[0];return Ae(f(2357,null,ot(xr(i,80))))}return f(2356,null,n)}if(Ub.has(o)){let r=e;if(r?.command){let i=r.command.split(`
`)[0];return Ae(f(2370,null,ot(xr(i,80))))}return f(2369,null)}if(p0.has(o))return f(2355,null);switch(o){case"view":{let r=e;if(r?.path){let i=ro(r.path),s=u0(r.view_range);return s?s.endLine===-1?Ae(f(2364,null,i,s.startLine)):s.endLine!==s.startLine?Ae(f(2366,null,i,s.startLine,s.endLine)):Ae(f(2365,null,i,s.startLine)):Ae(f(2363,null,i))}return f(2362,null)}case"edit":{let r=e;return r?.path?Ae(f(2346,null,ro(r.path))):f(2345,null)}case"create":{let r=e;return r?.path?Ae(f(2344,null,ro(r.path))):f(2343,null)}case"grep":{let r=e;return r?.pattern?Ae(f(2351,null,ot(xr(r.pattern,80)))):f(2350,null)}case"rg":{let r=e;return r?.pattern?Ae(f(2351,null,ot(xr(r.pattern,80)))):f(2350,null)}case"glob":{let r=e;return r?.pattern?Ae(f(2349,null,ot(xr(r.pattern,80)))):f(2348,null)}case"apply_patch":case"git_apply_patch":{let r=oy(e);return r.length===1?Ae(f(2353,null,ro(r[0]))):r.length>1?Ae(f(2354,null,r.map(ro).join(", "))):f(2352,null)}case"sql":return e?.description||f(2360,null);case"web_fetch":{let r=e;return r?.url?Ae(f(2367,null,g0(r.url))):f(2368,null)}case"exit_plan_mode":return f(2347,null);case"task":return f(2361,null);case"list_agents":case"read_agent":case"write_agent":return mp(o,n,e,!0);default:return n}}function mp(o,n,e,t,r){if(!t)return f(2314,null,n);let i=Rr(o,e,{text:r,success:t})?.pastTenseMessage;if(i!==void 0)return i;if(fp.has(o)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return Ae(f(2327,null,ot(xr(a,80))))}return f(2326,null,n)}if(Ub.has(o)){let s=e;if(s?.command){let a=s.command.split(`
`)[0];return Ae(f(2342,null,ot(xr(a,80))))}return f(2341,null)}if(p0.has(o))return f(2325,null);switch(o){case"view":{let s=e;if(s?.path){let a=ro(s.path),l=u0(s.view_range);return l?l.endLine===-1?Ae(f(2334,null,a,l.startLine)):l.endLine!==l.startLine?Ae(f(2336,null,a,l.startLine,l.endLine)):Ae(f(2335,null,a,l.startLine)):Ae(f(2333,null,a))}return f(2332,null)}case"edit":{let s=e;return s?.path?Ae(f(2312,null,ro(s.path))):f(2311,null)}case"create":{let s=e;return s?.path?Ae(f(2310,null,ro(s.path))):f(2309,null)}case"grep":{let s=e;return s?.pattern?Ae(f(2318,null,ot(xr(s.pattern,80)))):f(2317,null)}case"rg":{let s=e;return s?.pattern?Ae(f(2318,null,ot(xr(s.pattern,80)))):f(2317,null)}case"glob":{let s=e;return s?.pattern?Ae(f(2316,null,ot(xr(s.pattern,80)))):f(2315,null)}case"apply_patch":case"git_apply_patch":{let s=oy(e);return s.length===1?Ae(f(2321,null,ro(s[0]))):s.length>1?Ae(f(2322,null,s.map(ro).join(", "))):f(2320,null)}case"sql":return e?.description||f(2330,null);case"web_fetch":{let s=e;return s?.url?Ae(f(2337,null,g0(s.url))):f(2338,null)}case"exit_plan_mode":return f(2313,null);case"task":return f(2331,null);case"list_agents":return f(2319,null);case"read_agent":{let s=c0(e);return s?Ae(f(2323,null,ot(s))):f(2324,null)}case"write_agent":{let s=c0(e);return s?Ae(f(2339,null,ot(s))):f(2340,null)}default:return n}}function Y$(o,n){if(o)return`synth-skill-${o}`;let e=n.path??n.name;return`synth-skill-${kn(e).toString(16)}`}function ay(o,n){let e=Y$(n,o),t=f(2402,null),r=Xs(o.name),i=o.path?`[${r}](${v.file(o.path)})`:void 0,s=i?Ae(f(2358,null,i)):f(2359,null,o.name),a=i?Ae(f(2328,null,i)):f(2329,null,o.name);return{toolCallId:e,toolName:"skill",displayName:t,invocationMessage:s,pastTenseMessage:a}}function sa(o,n,e){if(!(!n&&!e)){if(fp.has(o)||Ub.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 ly(o){if(fp.has(o))return"terminal";if(j$.has(o))return"subagent";if(K$.has(o))return"search"}function dy(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 cy(o){switch(o){case"powershell":case"write_powershell":case"read_powershell":return"powershell";default:return"shellscript"}}function oo(o){try{return JSON.stringify(o)}catch{return}}function Vi(o){return typeof o=="string"?o:void 0}function m0(o,n,e){let t=Vi(o.path)??Vi(o.fileName),r=Vi(o.fullCommandText),i=Vi(o.intention),s=Vi(o.serverName),a=Vi(o.toolName),l=o.requestSandboxBypass?f(2304,null):f(2305,null);switch(o.kind){case"shell":{let d=r?{command:r}:void 0;ia("bash",d,n);let c=typeof d?.command=="string"?d.command:r;return{confirmationTitle:l,invocationMessage:i??Pr("bash",Ar("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=Vi(o.toolName);if(d&&c&&ji(c)&&typeof d.command=="string"){ia(c,d,n);let u=d.command;return{confirmationTitle:l,invocationMessage:Pr(c,Ar(c),{command:u}),toolInput:u,permissionKind:"shell",permissionPath:t}}return{confirmationTitle:f(2300,null),invocationMessage:Ae(f(2299,null,ot(a??o.kind))),toolInput:oo(d||o),permissionKind:o.kind,permissionPath:t}}case"write":{let d=e?"create":"edit";return{confirmationTitle:e?f(2298,null):f(2308,null),invocationMessage:Pr(d,Ar(d),t?{path:t}:void 0),toolInput:oo(t?{path:t}:o)??void 0,permissionKind:"write",permissionPath:t}}case"mcp":{let d=a??f(2301,null);return{confirmationTitle:s?f(2302,null,s):f(2300,null),invocationMessage:s?`${s}: ${d}`:d,toolInput:oo({serverName:s,toolName:a})??void 0,permissionKind:"mcp",permissionPath:t}}case"read":return{confirmationTitle:f(2303,null),invocationMessage:Pr("view",Ar("view"),t?{path:t}:void 0),permissionKind:"read",permissionPath:t};case"url":{let d=Vi(o.url),c=d?URL.canParse(d)?new URL(d).href:d:void 0;return{confirmationTitle:f(2307,null),invocationMessage:Ae(f(2306,null)),toolInput:c?JSON.stringify({url:c}):void 0,permissionKind:"url"}}default:return{confirmationTitle:f(2300,null),invocationMessage:Ae(f(2299,null,ot(a??o.kind))),toolInput:oo(o)??void 0,permissionKind:o.kind,permissionPath:t}}}var Fb="x-vscode-display-kind=";function h0(o){return o.displayKind===void 0?"text/plain":`text/plain; ${Fb}${encodeURIComponent(o.displayKind)}`}function y0(o){let n=o.split(";").map(e=>e.trim()).find(e=>e.startsWith(Fb));if(n)try{return decodeURIComponent(n.slice(Fb.length))}catch{return}}function v0(o){try{return JSON.stringify(o)}catch{return}}function Q$(o){if(o.type!=="user.message")return!1;let n=o.data.source;return!!n&&n.toLowerCase()!=="user"}function Hb(o,n,e){let t;for(let r of n??[])switch(r.type){case"shell_exit":{let i={exitCode:r.exitCode,...r.outputPreview!==void 0?{preview:r.outputPreview}:{},...r.outputTruncated!==void 0?{truncated:r.outputTruncated}:{}};t={shellId:r.shellId,result:i};let s=o.findIndex(a=>a.type==="terminal");if(s!==-1){let a=o[s];o[s]={...a,result:i}}else e&&o.push({type:"terminal",resource:Lb(e.session,e.toolCallId),title:e.title,isPty:!1,result:i});break}}return t}function hp(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:[],usage:void 0,pendingTools:new Map}}function yp(o,n){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o[n];return typeof e=="string"&&e.length>0?e:void 0}function b0(o){if(!o||typeof o!="object"||Array.isArray(o))return;let n=o.toolDescription;if(!n||typeof n!="object"||Array.isArray(n))return;let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e.ui;if(!(!t||typeof t!="object"||Array.isArray(t)))return yp(t,"resourceUri")}function S0(o,n,e,t,r){if(iy(o))return;let i=n!==void 0?v0(n):void 0,s;if(i)try{s=JSON.parse(i)}catch{}let l=(ia(o,s,t)?v0(s):void 0)??i,d=ly(o),c=d==="subagent"?dy(s):void 0,u=Ar(o);return{toolName:o,displayName:u,invocationMessage:Pr(o,u,s),toolInput:sa(o,s,l),toolKind:d,language:d==="terminal"?cy(o):void 0,intention:sy(o,s),subagentAgentName:c?.agentName,subagentDescription:c?.description,parameters:s,parentToolCallId:e,mcpServerName:yp(r,"mcpServerName"),mcpToolName:yp(r,"mcpToolName"),mcpUiResourceUri:b0(r)}}function C0(o,n){return{id:o.id,message:o.message,responseParts:o.responseParts,usage:o.usage,state:n}}async function _0(o,n,e,t=void 0){let r=t instanceof v?t:t?.workingDirectory,i=t instanceof v?void 0:t?.model,s=t instanceof v?void 0:t?.agent,a=new Map,l=[],d=new Map,c=new Map,u=(k,P)=>(k?c.get(k):void 0)??P;for(let k of e)if(k.type==="subagent.started"&&k.agentId&&c.set(k.agentId,k.data.toolCallId),k.type==="tool.execution_complete"&&d.set(k.data.toolCallId,k.data),k.type==="tool.execution_start"){let P=k.data,q=u(k.agentId,P.parentToolCallId),H=S0(P.toolName,P.arguments,q,r,P);if(!H)continue;a.set(P.toolCallId,H);let j=Be(H.parameters?.command)?H.parameters.command:void 0;Ad(P.toolName,j)&&l.push(P.toolCallId)}let p;if(n&&l.length>0)try{let k=await n.getFileEdits(l);if(k.length>0){p=new Map;for(let P of k){let q=p.get(P.toolCallId);q||(q=[],p.set(P.toolCallId,q)),q.push(P)}}}catch{}let g=o.toString(),h=o.scheme,y=M.id(o),I=[],S=new Map,C=new Map,_=new Map,T=new Map,w,W="cancelled",R=!1,L=!1,D,z=()=>{w&&(I.push(C0(w,W)),w=void 0,W="cancelled",R=!1)},J=k=>{let P=S.get(k);if(!P){C.delete(k);return}S.delete(k);let q=C.get(k)??"complete";if(C.delete(k),P.responseParts.length===0)return;let H=_.get(k)??[];H.push(C0(P,q)),_.set(k,H)},me=k=>{let P=S.get(k);return P||(P=hp(F(),""),S.set(k,P),C.has(k)||C.set(k,"complete")),P},We=k=>k?me(k):w;for(let k of e)switch(k.type){case"assistant.turn_start":k.agentId||(L=!0);break;case"assistant.turn_end":k.agentId||(L=!1);break;case"session.model_change":{i={id:k.data.newModel};break}case"session.auto_mode_resolved":{k.agentId||(D=k.data);break}case"subagent.deselected":{k.agentId||(s=void 0);break}case"user.message":{if(Q$(k))continue;let P=k.data,q=P.interactionId??"",H=P.content??"",j=X$(P.attachments),Q=u(k.agentId,void 0);if(k.agentId&&!Q)continue;if(Q){let Z=me(Q);Z.message={...Z.message,text:H,...j?.length?{attachments:j}:{}}}else{z();let Z=k.id??q;w=hp(Z,H,{attachments:j,model:i,agent:s}),D&&(w.usage={model:D.chosenModel,_meta:{autoModeResolved:D}},D=void 0)}break}case"assistant.message":{let P=k.data,q=P.messageId??P.interactionId??"",H=P.content??"",j=P.reasoningText,Q=!!P.toolRequests&&P.toolRequests.length>0,Z=u(k.agentId,P.parentToolCallId);if(!H&&!j&&!Q){!Z&&w&&!R&&(W="complete");break}let st=k.id??q,Pe=We(Z)??(w=hp(st,""));j&&Pe.responseParts.push({kind:"reasoning",id:F(),content:j}),H&&Pe.responseParts.push({kind:"markdown",id:F(),content:H}),!Z&&Pe===w&&!R&&(W=Q?"cancelled":"complete"),P.toolRequests?.length&&je(Pe,P.toolRequests,Z);break}case"system.notification":{let P=ry(k);if(!P)break;L&&w?w.responseParts.push({kind:"systemNotification",content:P.messageText}):P.startsTurn&&(z(),w=hp(k.id,P.messageText,{origin:"systemNotification"}));break}case"subagent.started":{let P=k.data;T.set(P.toolCallId,{agentName:P.agentName,agentDisplayName:P.agentDisplayName,agentDescription:P.agentDescription});break}case"tool.execution_start":{!u(k.agentId,k.data.parentToolCallId)&&w&&(W="cancelled");break}case"tool.execution_complete":{let P=k.data,q=a.get(P.toolCallId);if(!q)continue;a.delete(P.toolCallId);let H=u(k.agentId,P.parentToolCallId);if(Pd(q.toolName)){let Z=We(H);if(!Z)continue;let st=gp(q.parameters,P.error?.message??P.result?.content);st&&Z.responseParts.push({kind:"markdown",id:F(),content:st}),!H&&P.success&&Z===w&&!R&&(W="complete");continue}let j=We(H);if(!j)continue;let Q=I0(P,q,g,h,y,p,T.get(P.toolCallId));j.responseParts.push(Q),!H&&T.has(P.toolCallId)&&J(P.toolCallId);break}case"skill.invoked":{let P=ay(k.data,k.id),q=u(k.agentId,void 0),H=We(q)??(w=hp(F(),""));!q&&H===w&&(W="cancelled"),H.responseParts.push({kind:"toolCall",toolCall:{status:"completed",toolCallId:P.toolCallId,toolName:P.toolName,displayName:P.displayName,invocationMessage:P.invocationMessage,success:!0,pastTenseMessage:P.pastTenseMessage,confirmed:"not-needed"}});break}case"abort":{let P=u(k.agentId,void 0);P?C.set(P,"cancelled"):(L=!1,w&&(W="cancelled",R=!0));break}default:break}z();for(let k of[...S.keys()])J(k);return{turns:I,subagentTurnsByToolCallId:_};function je(k,P,q){for(let H of P){let j=d.get(H.toolCallId);if(j&&a.has(H.toolCallId))continue;let Q=a.get(H.toolCallId)??S0(H.name,H.arguments,q,r,H);if(Q){if(Pd(Q.toolName)){let Z=gp(Q.parameters,j?.error?.message??j?.result?.content);Z&&k.responseParts.push({kind:"markdown",id:F(),content:Z}),!q&&j?.success&&k===w&&!R&&(W="complete");continue}k.responseParts.push(I0(j??{toolCallId:H.toolCallId,success:!0},Q,g,h,y,p,T.get(H.toolCallId)))}}}}function X$(o){if(!o?.length)return;let n=[];for(let e of o){let t=Z$(e);t&&n.push(t)}return n.length>0?n:void 0}function Z$(o){switch(o.type){case"file":return{type:"resource",uri:v.file(o.path).toString(),label:o.displayName||ue(o.path),displayKind:sg(o.path)?.startsWith("image/")?"image":"document"};case"directory":return{type:"resource",uri:v.file(o.path).toString(),label:o.displayName||ue(o.path),displayKind:"directory"};case"selection":return{type:"resource",uri:v.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")){let e=y0(o.mimeType);return{type:"simple",label:o.displayName??"attachment",modelRepresentation:xn(o.data??"").toString(),...e!==void 0?{displayKind:e}:{}}}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 I0(o,n,e,t,r,i,s){let a=o.error?.message??o.result?.content,l=[];a!==void 0&&l.push({type:"text",text:a}),Hb(l,o.result?.contents,{session:e,toolCallId:o.toolCallId,title:n.displayName});let d=i?.get(o.toolCallId);if(d)for(let y of d){let I=y.kind==="rename"&&y.originalPath?v.file(y.originalPath).toString():v.file(y.filePath).toString(),S=v.file(y.filePath).toString(),C=y.kind!=="create",_=y.kind!=="delete";l.push({type:"fileEdit",before:C?{uri:I,content:{uri:Ii(e,y.toolCallId,y.filePath,"before")}}:void 0,after:_?{uri:S,content:{uri:Ii(e,y.toolCallId,y.filePath,"after")}}:void 0,diff:y.addedLines!==void 0||y.removedLines!==void 0?{added:y.addedLines,removed:y.removedLines}:void 0})}s&&l.push({type:"subagent",resource:ja(e,o.toolCallId),title:s.agentDisplayName,agentName:s.agentName,description:s.agentDescription});let c=n.mcpServerName??yp(o,"mcpServerName"),u=n.mcpToolName??yp(o,"mcpToolName"),p=n.mcpUiResourceUri??b0(o),g=p?{resourceUri:p,...c?{channel:ob(t,r,c)}:{}}:void 0,h={status:"completed",toolCallId:o.toolCallId,toolName:n.toolName,displayName:n.displayName,intention:n.intention,...c?{contributor:{kind:"mcp",customizationId:rb(t,r,c)}}:{},invocationMessage:n.invocationMessage,toolInput:n.toolInput,success:o.success,pastTenseMessage:mp(n.toolName,n.displayName,n.parameters,o.success,o.success?a:void 0),content:l.length>0?l:void 0,error:o.error,confirmed:"not-needed",_meta:At({toolKind:n.toolKind,language:n.language,subagentDescription:n.subagentDescription,subagentAgentName:n.subagentAgentName,mcpServerName:c,mcpToolName:u,ui:g})};return{kind:"toolCall",toolCall:h}}var T0="pending-edit-content";function w0(o,n,e){return v.from({scheme:T0,authority:di($.fromString(o)).toString(),path:`/${encodeURIComponent(n)}/${di($.fromString(e))}`})}function R0(o){let n=new td,e=o.registerProvider(T0,n);return{dispose(){e.dispose(),n.dispose()}}}var Ki=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 hf(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}};Ki=A([b(1,O)],Ki);var t6=".copilot",x0=V(t6,"session-state"),n6="<empty />";function A0(o){if(!URL.canParse(o))return;let n=new URL(o);return n.hash="",n.pathname=n.pathname.replace(/\/+$/,""),n.href}function r6(o){if(!o?.length)return n6;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 o6(o){switch(o){case"autopilot":return{label:f(2274,null),description:f(2273,null)};case"autopilot_fleet":return{label:f(2276,null),description:f(2275,null)};case"interactive":return{label:f(2281,null),description:f(2280,null)};case"exit_only":return{label:f(2278,null),description:f(2277,null)};default:return}}function P0(o){let n=ze(o.toolArgs)?Reflect.get(o.toolArgs,"command"):void 0;return Be(n)?n:void 0}function E0(o){switch(o=o?.toLowerCase()==="goal"?"plan":o,o){case"interactive":case"plan":case"autopilot":return o;default:return}}function i6(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 s6(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 a6(o){let n=process.env.XDG_STATE_HOME;return n?V(n,x0):V(o,x0)}var l6=/^(?:\d{10,}-copilot-tool-output-[a-z0-9]{6}|copilot-tool-output-\d{10,}-[a-z0-9]{6})\.txt$/i;function d6(o,n){let e=rn(v.file(o)),t=rn(v.file(n)),r=rn(v.joinPath(e,".."));if(!re.isEqual(r,t))return!1;let i=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\")),s=i>=0?o.substring(i+1):o;return l6.test(s)}var $b=class{constructor(n,e,t,r){this.id=n;this.ordinal=e;this.senderClientId=t;this.clientType=r;this._state="pending";this._stopWatch=lt.create(!1);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"}get duration(){return Math.max(0,this._stopWatch.elapsed())}markRunning(){this._state==="pending"&&(this._state="running")}markCompleted(){this._state="completed"}markAborted(){this._state="aborted"}},Ed=class extends x{constructor(e,t,r,i,s,a,l,d,c,u){super();this._instantiationService=t;this._logService=r;this._fileService=s;this._environmentService=a;this._configurationService=l;this._stateManager=d;this._telemetryService=c;this._copilotApiService=u;this._activeToolCalls=new Map;this._parentToolCallIdsByAgentId=new Map;this._activeSubagentAgentIds=new Set;this._unroutableSubagentToolCallIds=new Set;this._autoApprovals=new Map;this._pendingAutoApprovals=new Map;this._pendingPermissions=new Map;this._approvedDuplicablePermissionSignatures=new Map;this._pendingUserInputs=new Map;this._pendingElicitations=new Map;this._pendingPlanReviews=new Map;this._nextTurnOrdinal=0;this._autoApprovalExperimentalModeEnabled=!1;this._permissionModeSequencer=new lf;this._steeringMessagesInFlight=new Set;this._pendingSteeringFlips=new Map;this._pendingClientToolCalls=new Rt;this._pendingMcpAuthRequests=new Map;this._pendingEditContentUris=new Map;this._onMcpNotification=this._register(new E);this.onMcpNotification=this._onMcpNotification.event;this._pendingMcpSamplings=new Set;this._hasActivity=!1;this._lastLoggedMcpStatus=new Map;this.sessionId=e.rawSessionId,this.sessionUri=e.sessionUri,this._slashCommandProvider=new Ki(()=>this._wrapper.session.rpc.commands.list({includeBuiltins:!0,includeSkills:!0,includeClientCommands:!0}).then(h=>h.commands),this._logService),this._chatChannelUri=e.chatChannelUri,this._onDidSessionProgress=e.onDidSessionProgress,this._sessionLauncher=e.sessionLauncher,this._launchPlan=e.launchPlan,this._isLaunchTokenStillCurrent=e.isLaunchTokenCurrent??(()=>!0),this._onTurnEnded=e.onTurnEnded??(()=>{}),this._shellManager=e.shellManager,this._nonPtyShellTerminals=this._register(this._instantiationService.createInstance(xd,e.sessionUri)),this._workingDirectory=e.workingDirectory,this._customizationDirectory=e.customizationDirectory,this._serverToolHost=e.serverToolHost,this._platform=e.platform??process.platform,this._telemetryReporter=new _l(this._telemetryService),this._repoInfoTelemetry=this._register(this._instantiationService.createInstance(Rd,this._telemetryReporter)),this._appliedSnapshot=e.clientSnapshot??{tools:[],plugins:[],mcpServers:{}},this._clientToolNames=kb(this._appliedSnapshot);let p=this._launchPlan.kind==="create"?this._launchPlan.model:this._launchPlan.fallback.model,g=Tg(p,this._configurationService.getRootValue(jt,"modelCapabilityOverrides"));this._toolSearchActive=this._configurationService.getRootValue(jt,"toolSearchEnabled")===!0&&Wh(g?.id)&&this._clientToolNames.has(no),this._activeClientToolSet=e.activeClientToolSet??new Mn,this._databaseRef=i.openDatabase(this._storageUri),this._register(U(()=>this._databaseRef.dispose())),this._sessionDataDir=i.getSessionDataDir(this._storageUri),this._editTracker=this._instantiationService.createInstance(Ci,this._storageUri.toString(),this._databaseRef.object),this._mcpCustomizations=this._register(this._instantiationService.createInstance(Ui,{providerId:this.sessionUri.scheme,sessionId:this.sessionId,sessionUri:this.sessionUri,resolveChildId:e.resolveMcpChildId,emit:h=>this._emitAction(h)})),this._register(U(()=>this._denyPendingPermissions())),this._register(U(()=>this._shellManager?.dispose())),this._register(U(()=>this._cancelPendingUserInputs())),this._register(U(()=>this._cancelPendingElicitations())),this._register(U(()=>this._cancelPendingPlanReviews())),this._register(U(()=>this._drainPendingSteeringFlips())),this._register(U(()=>this._cancelPendingMcpSamplings())),this._register(U(()=>this._cancelPendingMcpAuthRequests())),this._shellManager&&this._register(this._shellManager.onDidAssociateTerminal(({toolCallId:h,terminalUri:y,displayName:I})=>{let S=this._activeToolCalls.get(h);S&&(S.content.push({type:"terminal",resource:y,title:I}),this._emitAction({type:"chat/toolCallContentChanged",turnId:this._turnId,toolCallId:h,content:S.content}))})),this._register(U(()=>this._cancelPendingClientToolCalls())),this._register(U(()=>{for(let h of this._pendingAutoApprovals.values())h.complete(void 0);this._pendingAutoApprovals.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 currentTurnClientType(){return this._currentTurn?.clientType??"unknown"}get _storageUri(){return Re(this._chatChannelUri)?this.sessionUri:this._chatChannelUri}get mcpServerStates(){return this._mcpCustomizations.runtimeStates}_emitAction(e,t){this._onDidSessionProgress.fire({kind:"action",resource:Tr(e)?this._chatChannelUri:this.sessionUri,action:e,parentToolCallId:t})}_beginSteeringTurn(e){let t=this._turnId;if(t){let i=this._currentTurn?.duration??0;this._emitAction({type:"chat/turnComplete",turnId:t,duration:i})}let r=F();return this._emitAction({type:"chat/turnStarted",turnId:r,startedAt:new Date().toISOString(),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}_resumeSubagentForEvent(e,t){if(!e.agentId||this._activeSubagentAgentIds.has(e.agentId))return;let r=this._parentToolCallIdsByAgentId.get(e.agentId);r&&(this._activeSubagentAgentIds.add(e.agentId),this._onDidSessionProgress.fire({kind:"subagent_resumed",chat:this._chatChannelUri,toolCallId:r,message:t}))}_completeSubagentTurn(e,t){if(e){if(!this._activeSubagentAgentIds.delete(e))return}else if(!t)return;let r=t??(e?this._parentToolCallIdsByAgentId.get(e):void 0);r&&this._onDidSessionProgress.fire({kind:"subagent_completed",chat:this._chatChannelUri,toolCallId:r})}_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,r="unknown"){this._currentTurn=new $b(e,this._nextTurnOrdinal++,t,r)}_completeActiveTurn(){let e=this._currentTurn;e&&(e.markCompleted(),this._telemetryReporter.toolCallDetails({session:this.sessionUri.toString(),turnId:e.id,clientType:e.clientType,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,duration:e.duration}),this._clearActiveTurn())}_clearActiveTurn(){this._currentTurn=void 0;try{this._onTurnEnded()}catch(e){this._logService.error(e,`[Copilot:${this.sessionId}] onTurnEnded callback failed`)}}_getEditFilePaths(e){return oy(e).map(t=>this._resolveEditFilePath(t))}_resolveEditFilePath(e){return nn(e)||!this._workingDirectory||this._workingDirectory.scheme!==ne.file?e:V(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=F(),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=F(),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;if(e.length===0)return[];let t=this._isToolSearchActive();return(t?e:e.filter(i=>i.name!==no)).map(i=>{if(t&&i.name===no)return{name:Cd,description:i.description??"",parameters:i.inputSchema??{type:"object",properties:{}},overridesBuiltInTool:!0,defer:"never",skipPermission:!0,handler:async(a,l)=>{try{let d=this._toToolSearchCandidates(l.availableTools),c=await this._pendingClientToolCalls.registerAndFire(l.toolCallId,()=>this._emitToolSearchReady(l.toolCallId,d));return this._toToolSearchResult(c,l.availableTools)}catch(d){return this._logService.error(d,`[Copilot:${this.sessionId}] Failed in tool-search handler: toolCallId=${l.toolCallId}`),this._toolSearchFailure(In(d))}}};let s=t?P1.has(i.name)?"never":"auto":void 0;return{name:i.name,description:i.description??"",parameters:i.inputSchema??{type:"object",properties:{}},defer:s,handler:async(a,{toolCallId:l})=>{try{return await this._pendingClientToolCalls.register(l)}catch(d){throw this._logService.error(d,`[Copilot:${this.sessionId}] Failed in client tool handler: tool=${i.name}, toolCallId=${l}`),d}}}})}_isToolSearchActive(){return this._toolSearchActive}_clientToolName(e){return this._isToolSearchActive()&&e===Cd?no:e}_toToolSearchCandidates(e){return(e??[]).filter(t=>t.deferLoading).map(t=>({name:t.name,description:t.description??""}))}_emitToolSearchReady(e,t){let r=this._activeToolCalls.get(e);if(!r)throw new Error(`Tool-search call '${e}' was not tracked.`);this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:e,invocationMessage:Pr(r.toolName,r.displayName,r.parameters),toolInput:sa(r.toolName,r.parameters,r.parameters?oo(r.parameters):void 0),confirmed:"not-needed",_meta:At({...r.meta??{},toolSearchCandidates:t})},r.parentToolCallId)}_toolSearchFailure(e){return{textResultForLlm:e,resultType:"failure",error:e,toolReferences:[]}}_toToolSearchResult(e,t){let r=new Set;for(let a of t??[])a.deferLoading&&(r.add(a.name),a.namespacedName&&r.add(a.namespacedName));let i=this._parseToolSearchNames(e.textResultForLlm),s=i.filter(a=>r.has(a));return this._logService.info(`[Copilot:${this.sessionId}] tool_search override: availableTools=${t?.length??0}, deferred=${r.size}, clientMatched=[${i.join(", ")}] -> toolReferences=[${s.join(", ")}]`),{...e,toolReferences:s}}_parseToolSearchNames(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}_createServerSdkTools(){let e=this._serverToolHost;return e?e.definitions.map(t=>({name:t.name,description:t.description??"",parameters:t.inputSchema??{type:"object",properties:{}},defer:"never",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){if(this._approvedDuplicablePermissionSignatures.delete(e),!t.success&&this._cancelMcpAuthenticationForToolCall(e)){this._activeToolCalls.delete(e);return}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:r6(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)}_cancelMcpAuthenticationForToolCall(e){for(let[t,r]of this._pendingMcpAuthRequests){let i=r.toolCalls.findIndex(s=>s.toolCallId===e);if(i!==-1)return r.toolCalls.splice(i,1),r.toolCalls.length===0&&(this._pendingMcpAuthRequests.delete(t),r.deferred.complete({kind:"cancelled"})),!0}return!1}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._subscribeToPermissionConfigChanges(),this._serverToolHost?.advertise(this._storageUri.toString())}_setPromptCacheState(e){let t=this._stateManager.getSessionSummary(this.sessionUri.toString())?._meta;this._stateManager.setSessionMeta(this.sessionUri.toString(),FR(t,e))}_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)if(!(i.resource.resource!==e.resource||!this._scopesSatisfy(e.scopes,i.requiredScopes))){this._pendingMcpAuthRequests.delete(r);for(let s of i.toolCalls)this._emitAction({type:"chat/toolCallAuthResolved",turnId:s.turnId,toolCallId:s.toolCallId},s.parentToolCallId);i.deferred.complete({kind:"token",accessToken:e.token}),t=!0}return t}async _handleMcpAuthRequest(e){let t=e.reason==="initial"&&this._scopesFromChallenge(e.wwwAuthenticateParams?.scope).length===0?await this._initialGitHubMcpToken(e):void 0;if(t)return this._logService.info(`[Copilot:${this.sessionId}] Reusing the existing GitHub token for initial GitHub MCP authentication`),{kind:"token",accessToken:t};let r=this._protectedResourceFromMcpAuthRequest(e),i=this._scopesFromChallenge(e.wwwAuthenticateParams?.scope),s=e.staticClientConfig?.publicClient?{clientId:e.staticClientConfig.clientId}:e.staticClientConfig?.clientSecret?{clientId:e.staticClientConfig.clientId,clientSecret:e.staticClientConfig.clientSecret}:void 0,a={reason:this._mcpAuthRequiredReason(e.reason),...s?{oauthClient:s}:{},resource:r,requiredScopes:i.length?[...i]:void 0,description:e.wwwAuthenticateParams?.error},l=this._activeMcpToolCalls(e.serverName),d=new be;this._pendingMcpAuthRequests.set(e.requestId,{serverName:e.serverName,resource:r,requiredScopes:i,toolCalls:l,deferred:d}),this._mcpCustomizations.applyOne({name:e.serverName,state:{kind:"authRequired",...a}});for(let c of l)this._emitAction({type:"chat/toolCallAuthRequired",turnId:c.turnId,toolCallId:c.toolCallId,auth:a},c.parentToolCallId);return this._logService.info(`[Copilot:${this.sessionId}] MCP server '${e.serverName}' requires authentication for ${r.resource}`),d.p.finally(()=>this._pendingMcpAuthRequests.delete(e.requestId))}_activeMcpToolCalls(e){if(!this._turnId)return[];let t=[];for(let[r,i]of this._activeToolCalls)i.mcpServerName===e&&t.push({turnId:this._turnId,toolCallId:r,parentToolCallId:i.parentToolCallId});return t}async _initialGitHubMcpToken(e){let t=this._launchPlan.githubToken,r=A0(e.serverUrl);if(!t||r===void 0)return;let i=[PI(void 0)];try{let s=PI(await this._copilotApiService.resolveApiEndpoint(t));s&&i.push(s)}catch(s){this._logService.warn(`[Copilot:${this.sessionId}] Failed to resolve the GitHub MCP server URL: ${In(s)}`);return}return i.some(s=>s&&r===A0(s))?t:void 0}_protectedResourceFromMcpAuthRequest(e){if(e.resourceMetadata)try{let r=JSON.parse(e.resourceMetadata);if(mb(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}}_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()}_cancelPendingMcpAuthRequestsForServer(e){for(let[t,r]of this._pendingMcpAuthRequests)if(r.serverName===e){this._pendingMcpAuthRequests.delete(t);for(let i of r.toolCalls)this._emitAction({type:"chat/toolCallAuthResolved",turnId:i.turnId,toolCallId:i.toolCallId},i.parentToolCallId);r.deferred.complete({kind:"cancelled"})}}async send(e,t,r,i,s,a="unknown"){r&&this._currentTurn?.id!==r&&this.resetTurnState(r,s,a);let l=this._currentTurn;try{await this._send(e,t,i)}catch(d){throw l&&this._currentTurn===l&&this._clearActiveTurn(),d}}async _send(e,t,r){this._logService.info(`[Copilot:${this.sessionId}] sendMessage called: "${e.substring(0,100)}${e.length>100?"...":""}" (${t?.length??0} attachments)`);let i=Ob(e);if(i?.command==="compact"){try{let d=(await this._wrapper.session.rpc.history.compact()).contextWindow?.currentTokens;typeof d=="number"&&this._emitAction({type:"chat/usage",turnId:this._turnId,usage:{inputTokens:d,outputTokens:0,model:this._lastSeenModelId}}),this.emitInitialMarkdown(f(2289,null))}catch(l){if(In(l).toLowerCase().includes("nothing to compact")){this.emitInitialMarkdown(f(2289,null)),this._completeActiveTurn();return}throw this._logService.error(l,`[Copilot:${this.sessionId}] rpc.history.compact failed`),l}this._completeActiveTurn();return}let s=i?A1(i.command,i.rawRest):void 0;if(s){let l=E0(s.applyConfig.mode);l&&(r=l),e=s.strippedPrompt}else if(i?.command==="rubber-duck")if(this._configurationService.getRootValue(jt,"rubberDuck")!==!0)e=i.rest;else{let l=i.rest;e=l?`The user has requested a rubber duck review via the /rubber-duck command. Use the task tool with agent_type: "rubber-duck" to get an independent critique of your current approach, plan, or recent work. Summarize the relevant context for the rubber duck agent so it has what it needs to evaluate it.

Additional instructions: ${l}`:'The user has requested a rubber duck review via the /rubber-duck command. Use the task tool with agent_type: "rubber-duck" to get an independent critique of your current approach, plan, or recent work. Summarize the relevant context for the rubber duck agent so it has what it needs to evaluate it.'}else if(i){let l=await this._slashCommandProvider.resolveSlashCommand(i.command);if(l&&l.kind!=="skill"){let d;try{d=await this._wrapper.session.rpc.commands.invoke({name:l.name,...i.rawRest.length>0?{input:i.rawRest}:{}})}catch(c){throw this._logService.error(c,`[Copilot:${this.sessionId}] rpc.commands.invoke(${i.command}) failed`),c}switch(d.kind){case"text":this._emitMarkdownDelta(d.markdown===!0?d.text:BI(d.text));break;case"completed":d.message&&this._emitMarkdownDelta(d.message);break;case"agent-prompt":{let c=E0(d.mode);c&&(r=c),e=d.prompt;break}case"select-subcommand":this._emitMarkdownDelta(f(2290,null,d.command,d.options.map(c=>c.name).join(", ")));break;default:this._logService.warn(`[Copilot:${this.sessionId}] Unhandled slash command result kind: ${d.kind}`);break}if(d.runtimeSettingsChanged===!0&&this._slashCommandProvider.clearCache(),d.kind!=="agent-prompt"){this._completeActiveTurn();return}}}let a=t?.length?(await Promise.all(t.map(l=>this._toSdkAttachment(l)))).filter(Mr):void 0;a?.length&&this._logService.trace(`[Copilot:${this.sessionId}] Attachments: ${JSON.stringify(a.map(l=>({type:l.type})))}`),await this.applyMode(r),await this.syncPermissionMode("turn-start"),await this._applyEffectiveSandboxConfig(),await this._reconcileMcpServerEnablement(),this._markEnabledMcpServersStarting(),await this._wrapper.session.send({prompt:e,attachments:a?.length?a: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(Hh(e)){let a=$h(e);return a?{type:"blob",data:_o($.fromString(a)),mimeType:"text/plain",displayName:e.label}:void 0}if(e.type==="simple")return e.modelRepresentation?{type:"blob",data:_o($.fromString(e.modelRepresentation)),mimeType:h0(e),displayName:e.label}:void 0;if(e.type==="embeddedResource")return{type:"blob",data:e.data,mimeType:e.contentType,displayName:e.label};if(e.type!=="resource")return;let t=v.parse(e.uri),r=t.scheme==="file"?t.fsPath:t.toString(),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=gw(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._storageUri.toString(),Pt,"mode")==="autopilot"}_isAutoReplyEnabled(){return this._configurationService.getRootValue(tt,MS)===!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._reconcileMcpServerEnablement(),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._storageUri.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?PR({content:d}):void 0,u=An(a).subagentDescription;r.push({resource:v.parse(ja(t,a.toolCallId)),toolCallId:a.toolCallId,title:RS(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 _0(this._storageUri,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._cancelPendingPlanReviews(),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=ze(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._disableMcpServer(t),this._mcpCustomizations.markStarting([t]);try{await this._wrapper.session.rpc.mcp.enable({serverName:t}),await this._wrapper.session.rpc.mcp.listTools({serverName:t})}finally{this._seedMcpServersFromRpc()}}async _reconcileMcpServerEnablement(){let e=this._stateManager.getSessionState(this.sessionUri.toString())?.customizations??[],t=Zs(e);if(t.length===0)return;await this._refreshMcpServersFromRpc();let r=!1;for(let i of this._mcpCustomizations.serverEnablement()){let s=t.find(a=>a.id===i.customizationId)?.enabled;if(!(s===void 0||s===i.enabled))try{s?(this._mcpCustomizations.markStarting([i.serverName]),r=!0,await this._wrapper.session.rpc.mcp.enable({serverName:i.serverName})):(await this._disableMcpServer(i.serverName),r=!0)}catch(a){this._logService.error(a,`[Copilot:${this.sessionId}] Failed to ${s?"enable":"disable"} MCP server ${i.serverName}`)}}r&&await this._refreshMcpServersFromRpc()}_markEnabledMcpServersStarting(){let e=this._stateManager.getSessionState(this.sessionUri.toString())?.customizations??[],t=Zs(e).filter(r=>r.enabled);t.length>0&&this._mcpCustomizations.markStarting(t.map(r=>r.name))}async _disableMcpServer(e){this._cancelPendingMcpAuthRequestsForServer(e),await this._wrapper.session.rpc.mcp.disable({serverName:e})}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=F(),i=F();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}}}async _handlePermissionRequest(e){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"};if(this._unroutableSubagentToolCallIds.delete(t))return this._logService.error(`[Copilot:${this.sessionId}] Rejecting permission request for unroutable subagent tool call: toolCallId=${t}, kind=${e.kind}`),{kind:"reject"};let r=this._lastAppliedPermissionMode==="auto"?await this._takeAutoApproval(t):void 0,i=r?.recommendation;if(i==="approve"&&!e.requestSandboxBypass){if(e.kind==="custom-tool"&&typeof e.toolName=="string"&&this._clientToolNames.has(this._clientToolName(e.toolName))){let T=this._activeToolCalls.get(t),w=T?.displayName??Ar(e.toolName),W=T?.parameters,R=T?.parentToolCallId;this._onDidSessionProgress.fire({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:t,toolName:e.toolName,displayName:w,invocationMessage:Pr(e.toolName,w,W),toolInput:sa(e.toolName,W,oo(W)),riskAssessment:r?.reason?{kind:"judge",status:"complete",reason:r.reason,safety:1}:void 0},parentToolCallId:R})}return{kind:"approve-once"}}let s=this._approvedDuplicablePermissionSignatures.get(t);if(s!==void 0&&(this._approvedDuplicablePermissionSignatures.delete(t),(e.kind==="write"||e.kind==="read")&&Ur(e)===s))return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving duplicate ${e.kind} permission request for tool call ${t}`),{kind:"approve-once"};let a=this._getInternalSessionResourcePath(e);if(a)return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving internal session resource ${a}`),{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"&&d6(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 l=e.kind==="shell"||e.kind==="custom-tool"&&typeof e.toolName=="string"&&ji(e.toolName);if(e.kind==="custom-tool"&&typeof e.toolName=="string"&&this._clientToolNames.has(this._clientToolName(e.toolName))&&this._pendingClientToolCalls.hasBufferedResult(t))return this._logService.info(`[Copilot:${this.sessionId}] Auto-approving client tool ${e.toolName} because its result arrived before the permission request`),{kind:"approve-once"};this._logService.info(`[Copilot:${this.sessionId}] Requesting confirmation for tool call: ${t}`);let d=new be;if(this._pendingPermissions.set(t,d),l&&!e.requestSandboxBypass&&await this._isShellSandboxedByDefault())return this._pendingPermissions.get(t)===d?(this._pendingPermissions.delete(t),this._logService.info(`[Copilot:${this.sessionId}] Auto-approving sandboxed shell command for tool call ${t}`),{kind:"approve-once"}):{kind:"reject"};let c=await this._buildEditsForPermission(e,t);if(!this._pendingPermissions.has(t))return{kind:"reject"};let u=c?.items.some(T=>!T.before&&!!T.after),{confirmationTitle:p,invocationMessage:g,toolInput:h,permissionKind:y,permissionPath:I}=m0(e,this._workingDirectory,u),S=e.toolName??e.kind,C=this._activeToolCalls.get(t)?.parentToolCallId;this._onDidSessionProgress.fire({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:t,toolName:S,displayName:Ar(S),invocationMessage:g,toolInput:h,confirmationTitle:p,riskAssessment:r?.reason?{kind:"judge",status:"complete",reason:r.reason,safety:i==="approve"?1:0}:void 0,edits:c},permissionKind:y,permissionPath:I,requestSandboxBypass:e.requestSandboxBypass,parentToolCallId:C});let _=await d.p;return this._logService.info(`[Copilot:${this.sessionId}] Permission response: toolCallId=${t}, result=${_.kind}`),_.kind==="approve-once"&&(e.kind==="write"||e.kind==="read")&&this._approvedDuplicablePermissionSignatures.set(t,Ur(e)),_}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=rn(v.file(a6(this._environmentService.userHome.fsPath))),i=rn(v.joinPath(r,this.sessionId));if(!re.isEqualOrParent(i,r))return;let s=rn(v.file(t));return re.isEqualOrParent(s,i)?t:void 0}_isSessionAttachmentPath(e){let t=rn(v.joinPath(this._sessionDataDir,gg)),r=rn(v.file(e));return re.isEqualOrParent(r,t)}async _isShellSandboxedByDefault(){return this._isCustomTerminalToolEnabled()?this._shellManager?this._shellManager.getOrCreateSandboxEngine().isEnabled():!1:this._computeSdkSandboxConfig()!==void 0}_isCustomTerminalToolEnabled(){return this._configurationService.getRootValue(jt,"enableCustomTerminalTool")===!0}_computeSdkSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(zr,"sandbox");return cp(this._platform,e)}_isBypassApprovals(){return this._configurationService.getRootValue(tt,Ya)===!0?!0:this._configurationService.getEffectiveValue(this._storageUri.toString(),Pt,"autoApprove")==="autoApprove"}_getSdkPermissionMode(){return this._isBypassApprovals()?"on":this._getConfiguredApprovalLevel()==="assisted"?"auto":"off"}_getConfiguredApprovalLevel(){return this._configurationService.getEffectiveValue(this._storageUri.toString(),Pt,"autoApprove")??"default"}_getConfiguredAgentMode(){return this._configurationService.getEffectiveValue(this._storageUri.toString(),Pt,"mode")??"interactive"}_subscribeToPermissionConfigChanges(){this._register(this._configurationService.onDidRootConfigChange(()=>{this._syncPermissionModeAfterConfigChange()})),this._register(this._configurationService.onDidSessionConfigChange(e=>{e.session===this._storageUri.toString()&&Object.hasOwn(e.config,"autoApprove")&&this._syncPermissionModeAfterConfigChange()}))}async _syncPermissionModeAfterConfigChange(){try{await this.syncPermissionMode("config-change")}catch(e){this._logService.error(e,`[Copilot:${this.sessionId}] Failed to apply permission config change; aborting active turn`);try{await this.abort()}catch(t){this._logService.error(t,`[Copilot:${this.sessionId}] Failed to abort after permission config sync failure`)}}}async _takeAutoApproval(e){if(this._autoApprovals.has(e)){let r=this._autoApprovals.get(e)??void 0;return this._autoApprovals.delete(e),r}let t=new be;this._pendingAutoApprovals.set(e,t);try{return await t.p}finally{this._pendingAutoApprovals.delete(e)}}_recordAutoApproval(e,t){let r=this._pendingAutoApprovals.get(e);if(r){r.complete(t);return}this._autoApprovals.set(e,t??null)}syncPermissionMode(e){return this._permissionModeSequencer.queue(async()=>{let t=this._getSdkPermissionMode(),r=this._getConfiguredApprovalLevel();this._logService.info(`[Copilot:${this.sessionId}] Syncing permission mode: source=${e}, agentMode=${this._getConfiguredAgentMode()}, configuredLevel=${r}, sdkMode=${t}, previousSdkMode=${this._lastAppliedPermissionMode??"unknown"}, globalAutoApprove=${this._configurationService.getRootValue(tt,Ya)===!0}`);let i=t==="auto";if(this._autoApprovalExperimentalModeEnabled!==i){if(!(await this._wrapper.session.rpc.options.update({isExperimentalMode:i})).success)throw new Error(`Copilot SDK rejected experimental mode update required by permission mode '${t}'`);this._autoApprovalExperimentalModeEnabled=i,this._logService.info(`[Copilot:${this.sessionId}] ${i?"Enabled":"Disabled"} SDK experimental mode for permission mode '${t}'`)}if(this._lastAppliedPermissionMode===t)return;let s=await this._wrapper.session.rpc.permissions.setAllowAll({mode:t});if(!s.success||s.mode!==void 0&&s.mode!==t)throw new Error(`Copilot SDK rejected permission mode '${t}'`);this._lastAppliedPermissionMode=t})}async _applyEffectiveSandboxConfig(){if(this._isCustomTerminalToolEnabled())return;let e=this._configurationService.getRootValue(zr,"sandbox"),t=cp(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=v.file(r),a=s.toString(),l=!1;try{l=await this._fileService.exists(s)}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] Failed to check file for edit preview: ${r}`,p)}let d=w0(this._storageUri.toString(),t,r);try{await this._fileService.writeFile(d,$.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"?c6(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?{kind:"approve-once"}:{kind:"denied-interactively-by-user"}),!0):!1}async _requestUnsandboxedCommandConfirmation(e){let t=new be;this._pendingPermissions.set(e.toolCallId,t);let r=Ar(e.toolName),i=e.blockedDomains?.length?e.blockedDomains.join(", "):void 0,s=i?f(2287,null,i):f(2288,null),a=e.reason?f(2286,null,e.reason):i?f(2284,null,i):f(2285,null),l=this._activeToolCalls.get(e.toolCallId)?.parentToolCallId;return this._onDidSessionProgress.fire({kind:"pending_confirmation",chat:this._chatChannelUri,state:{status:"pending-confirmation",toolCallId:e.toolCallId,toolName:e.toolName,displayName:r,invocationMessage:a,toolInput:e.command,confirmationTitle:s},parentToolCallId:l}),(await t.p).kind==="approve-once"}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};if(!this.hasActiveTurn)return this._logService.warn(`[Copilot:${this.sessionId}] Rejecting user input request without an active turn`),{answer:"No active turn",wasFreeform:!0};let i=e.question.substring(0,100);try{let s=F(),a=F();this._logService.info(`[Copilot:${this.sessionId}] User input request: requestId=${s}, question="${i}"`);let l=new be;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(g=>({id:g,label:g})),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 g=!e.choices?.includes(p.value);return{answer:p.value,wasFreeform:g}}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"};if(!this.hasActiveTurn)return this._logService.warn(`[Copilot:${this.sessionId}] Rejecting elicitation request without an active turn`),{action:"decline"};let r=e.message.substring(0,100);try{let i=F();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(([h,y])=>i6(h,y,a.has(h))):void 0,d=new be;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 h=p.answer;return h&&h.state!=="skipped"&&h.value.kind==="text"?{action:"accept",content:{answer:h.value.value}}:{action:"accept"}}let g={};for(let[h,y]of Object.entries(s.properties)){let I=s6(y,p[h]);I!==void 0&&(g[h]=I)}return{action:"accept",content:g}}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")&&this._isBypassApprovals()?{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(Ad(e.toolName,P0(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(Ad(e.toolName,P0(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}}async _beginRepoInfoTelemetry(e,t){let r;try{r=await this._resolveRepoInfoTelemetryContext()}catch(i){this._logService.warn(`[Copilot:${this.sessionId}] Failed to resolve repository info telemetry context: ${In(i)}`);return}if(!(!r||this._store.isDisposed||!t()))return await this._repoInfoTelemetry.reportBegin(r.context,this.sessionUri.toString(),e,this._workingDirectory,r.baseBranch,t),r}async _endRepoInfoTelemetry(e,t,r){!t||this._store.isDisposed||!r()||await this._repoInfoTelemetry.reportEnd(t.context,this.sessionUri.toString(),e,this._workingDirectory,t.baseBranch,r)}_completeActiveRepoInfoTelemetry(){let e=this._activeRepoInfoTurn;if(!e)return;this._activeRepoInfoTurn=void 0;let t=()=>!e.cancelled&&this._isLaunchTokenCurrent();e.begin.then(r=>this._endRepoInfoTelemetry(e.telemetryMessageId,r,t))}_cancelActiveRepoInfoTelemetry(){let e=this._activeRepoInfoTurn;e&&(this._activeRepoInfoTurn=void 0,e.cancelled=!0,e.begin.finally(()=>this._repoInfoTelemetry.clearTurn(e.telemetryMessageId)))}async _resolveRepoInfoTelemetryContext(){if(this._configurationService.getRootValue(tt,ES)===!0)return;let e=this._launchPlan.githubToken;if(!e)return;let[t,r]=await Promise.all([this._copilotApiService.resolveRestrictedTelemetryContext(e),this._databaseRef.object.getMetadata(bi)]);if(!(!t.restrictedTelemetryEnabled&&!t.isInternal))return{context:this._toRepoInfoTelemetryContext(t),baseBranch:r}}_isLaunchTokenCurrent(){return this._launchPlan.githubToken!==void 0&&this._isLaunchTokenStillCurrent()}_toRepoInfoTelemetryContext(e){return{restrictedTelemetryEnabled:e.restrictedTelemetryEnabled,trackingId:e.trackingId,telemetryEndpoint:e.telemetryEndpoint?`${e.telemetryEndpoint.replace(/\/+$/,"")}/telemetry`:void 0,isInternal:e.isInternal===!0,userName:e.userName,isVscodeTeamMember:e.isVscodeTeamMember===!0,copilotIgnoreEnabled:e.copilotIgnoreEnabled}}_subscribeToEvents(){let e=this._wrapper,t=this.sessionId;this._register(e.onSystemNotification(a=>{let l=ry(a);if(!l){this._logService.trace(`[Copilot:${t}] Ignoring system.notification kind=${a.data.kind.type}`);return}if(this._logService.info(`[Copilot:${t}] System notification received: kind=${a.data.kind.type}`),this._turnId){this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"systemNotification",content:l.messageText}});return}if(!l.startsTurn){this._logService.trace(`[Copilot:${t}] Ignoring passive system.notification kind=${a.data.kind.type} without an active turn`);return}let d=F();this.resetTurnState(d),this._emitAction({type:"chat/turnStarted",turnId:d,startedAt:new Date().toISOString(),message:{text:l.messageText,origin:{kind:"systemNotification"}}})})),this._register(e.onUserMessage(a=>{if(a.agentId){this._resumeSubagentForEvent(a,{text:a.data.content,origin:{kind:"user"}});return}if(a.data.source&&a.data.source.toLowerCase()!=="user")return;this._currentTurn?.markRunning();let l=this._takeMatchingPendingSteering(a.data.content);l&&this._beginSteeringTurn(l),this._turnId&&this._databaseRef.object.setTurnEventId(this._turnId,a.id)})),this._register(e.onMessageDelta(a=>{this._logService.trace(`[Copilot:${t}] delta: ${a.data.deltaContent}`),this._resumeSubagentForEvent(a),!this._shouldDropUnmappedSubagentEvent(a,"assistant.message_delta")&&this._emitMarkdownDelta(a.data.deltaContent,this._parentToolCallIdForSubagentEvent(a))})),this._register(e.onMessage(a=>{if(this._logService.info(`[Copilot:${t}] Full message received: ${a.data.content.length} chars`),this._resumeSubagentForEvent(a),!a.agentId){let u=this._currentTurn?.clientType??"unknown";this._telemetryReporter.assistantMessageReceived(this.sessionUri.toString(),u,a.data.serviceRequestId,this._appliedSnapshot.tools),this._telemetryReporter.modelMessageText(this.sessionUri.toString(),u,a.data.content,this._turnOrdinal,a.data.serviceRequestId);let p=this._currentTurn;if(p){p.toolCallRounds++,a.data.model&&(p.lastModel=a.data.model);let g=a.data.toolRequests;if(g?.length){p.totalToolCalls+=g.length,g.length>1&&(p.parallelToolCallRounds++,p.parallelToolCallsTotal+=g.length);for(let h of g)p.toolCounts.set(h.name,(p.toolCounts.get(h.name)??0)+1)}}}if(!a.data.content||this._shouldDropUnmappedSubagentEvent(a,"assistant.message"))return;let l=this._parentToolCallIdForSubagentEvent(a),d=l??"";if(this._currentTurn?.markdownPartIds.has(d))return;let c=F();this._currentTurn?.markdownPartIds.set(d,c),this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:c,content:a.data.content}},l)})),this._register(e.onPermissionRequested(a=>{let l=a.data.permissionRequest.toolCallId;l&&this._recordAutoApproval(l,a.data.promptRequest?.autoApproval)})),this._register(e.onToolStart(a=>{if(iy(a.data.toolName)){this._logService.trace(`[Copilot:${t}] Tool started (hidden): ${a.data.toolName}`);return}this._logService.info(`[Copilot:${t}] Tool started: ${a.data.toolName}`);let l=a.data.arguments!==void 0?oo(a.data.arguments):void 0,d;if(l)try{d=JSON.parse(l)}catch{}ia(a.data.toolName,d,this._workingDirectory)&&(l=oo(d));let c=Ar(a.data.toolName);if(this._resumeSubagentForEvent(a),this._shouldDropUnmappedSubagentEvent(a,"tool.execution_start")){this._unroutableSubagentToolCallIds.add(a.data.toolCallId);return}let u=this._parentToolCallIdForSubagentEvent(a);if(this._activeToolCalls.set(a.data.toolCallId,{toolName:a.data.toolName,displayName:c,parameters:d,content:[],parentToolCallId:u,mcpServerName:a.data.mcpServerName,meta:void 0}),ji(a.data.toolName)&&this._nonPtyShellTerminals.track(a.data.toolCallId,c),Pd(a.data.toolName)){let R=u??"";this._currentTurn?.markdownPartIds.delete(R),this._currentTurn?.reasoningPartIds.delete(R);return}let p=ly(a.data.toolName),g=p==="subagent"?dy(d):void 0,h,y=this._clientToolName(a.data.toolName),I=this._clientToolNames.has(y),S=I?this._activeClientToolSet.ownerOf(y,this._currentTurn?.senderClientId):void 0;if(S)h={kind:"client",clientId:S};else if(a.data.mcpServerName){let R=this._mcpCustomizations.customizationIdForServer(a.data.mcpServerName);R!==void 0&&(h={kind:"mcp",customizationId:R})}this._currentTurn?.markdownPartIds.delete(u??""),this._currentTurn?.reasoningPartIds.delete(u??"");let C={toolKind:p,language:p==="terminal"?cy(a.data.toolName):void 0};g?.description&&(C.subagentDescription=g.description),g?.agentName&&(C.subagentAgentName=g.agentName),l!==void 0&&(C.toolArguments=l),a.data.mcpServerName&&(C.mcpServerName=a.data.mcpServerName),a.data.mcpToolName&&(C.mcpToolName=a.data.mcpToolName);let _=a.data.toolDescription?._meta?.ui?.resourceUri;this._setToolCallUiMeta(C,_,a.data.mcpServerName);let T=this._activeToolCalls.get(a.data.toolCallId);if(T&&(T.meta=C),this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:a.data.toolCallId,toolName:a.data.toolName,displayName:c,intention:sy(a.data.toolName,d),contributor:h,_meta:At(C)},u),I&&!h){this._logService.warn(`[Copilot:${t}] Client tool '${a.data.toolName}' started with no connected client; failing it immediately.`),this._activeToolCalls.delete(a.data.toolCallId),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:a.data.toolCallId,invocationMessage:Pr(a.data.toolName,c,d),toolInput:sa(a.data.toolName,d,l),confirmed:"not-needed"},u),this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:a.data.toolCallId,result:{success:!1,pastTenseMessage:`${c} failed`,error:{message:`No client was connected to run ${c}`}}},u),this._pendingClientToolCalls.respondOrBuffer(a.data.toolCallId,{textResultForLlm:`No client was connected to run ${c}.`,resultType:"failure",error:"No client connected"});return}let w=h?.kind==="client"&&this._lastAppliedPermissionMode==="on";h?.kind==="client"&&!f0(a.data.toolName)&&!w||this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:a.data.toolCallId,invocationMessage:Pr(a.data.toolName,c,d),toolInput:sa(a.data.toolName,d,l),confirmed:"not-needed",...w?{_meta:At({autoApproveBySetting:!0})}:{}},u)})),this._register(e.onToolComplete(async a=>{this._approvedDuplicablePermissionSignatures.delete(a.data.toolCallId);let l=this._activeToolCalls.get(a.data.toolCallId);if(!l){this._unroutableSubagentToolCallIds.delete(a.data.toolCallId);return}let d=l.parentToolCallId??this._parentToolCallIdForSubagentEvent(a);if(!d&&a.agentId){this._logService.warn(`[Copilot:${this.sessionId}] Dropping tool.execution_complete for unknown subagent agentId=${a.agentId}`);return}this._logService.info(`[Copilot:${t}] Tool completed: ${a.data.toolCallId}`),this._activeToolCalls.delete(a.data.toolCallId),this._autoApprovals.delete(a.data.toolCallId),this._pendingAutoApprovals.get(a.data.toolCallId)?.complete(void 0);let c=l.displayName,u=a.data.error?.message??a.data.result?.content;if(Pd(l.toolName)){let C=gp(l.parameters,u);C&&this._emitAction({type:"chat/responsePart",turnId:this._turnId,part:{kind:"markdown",id:F(),content:C}});return}let p=[...l.content];u!==void 0&&p.push({type:"text",text:u});let g=ji(l.toolName)?this._shellManager?.getTerminalUriForToolCall(a.data.toolCallId):void 0,h=!!g;g&&!p.some(C=>C.type==="terminal")&&p.push({type:"terminal",resource:g,title:l.displayName});let y=Hb(p,a.data.result?.contents,{session:this.sessionUri,toolCallId:a.data.toolCallId,title:l.displayName});if(ji(l.toolName)&&!g){let C=this._nonPtyShellTerminals.completeToolCall(a.data.toolCallId,u,y);if(C){h=C.shouldRetire;let _=p.findIndex(T=>T.type==="terminal");if(_===-1)p.push({type:"terminal",resource:C.uri,title:l.displayName,isPty:!1,...C.result?{result:C.result}:{}});else if(C.result){let T=p[_];p[_]={...T,result:C.result}}}}let I=Be(l.parameters?.command)?l.parameters.command:void 0,S=Ad(l.toolName,I)?this._getEditFilePaths(l.parameters):[];for(let C of S)try{let _=await this._editTracker.takeCompletedEdit(this._turnId,a.data.toolCallId,C,l.toolName,l.parameters,this._lastSeenModelId);_&&p.push(_)}catch(_){this._logService.warn(`[Copilot:${t}] Failed to take completed edit`,_)}this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:a.data.toolCallId,result:{success:a.data.success,pastTenseMessage:mp(l.toolName,c,l.parameters,a.data.success,a.data.success?u:void 0),content:p.length>0?p:void 0,error:a.data.error},_meta:l.meta?At(l.meta):void 0},d),h&&this._nonPtyShellTerminals.retire(a.data.toolCallId)})),this._register(e.onIdle(a=>{this._logService.info(`[Copilot:${t}] Session idle`),this._hasActivity&&(this._hasActivity=!1,this._emitAction({type:"session/activityChanged",activity:void 0}));let l=this._currentTurn;if(l){if(a.data.aborted){this._cancelActiveRepoInfoTelemetry(),l.isRunning?(this._logService.trace(`[Copilot:${t}] Idle from abort; tearing down running turn ${l.id}`),l.markAborted(),this._clearActiveTurn()):this._logService.trace(`[Copilot:${t}] Idle from abort; leaving ${l.state} turn ${l.id} open`);return}this._completeActiveRepoInfoTelemetry(),this._completeActiveTurn()}})),this._register(e.onSkillInvoked(a=>{if(this._logService.info(`[Copilot:${t}] Skill invoked: ${a.data.name} (${a.data.path})`),this._resumeSubagentForEvent(a),this._shouldDropUnmappedSubagentEvent(a,"skill.invoked"))return;a.agentId||this._telemetryReporter.skillContentRead({name:a.data.name,path:a.data.path,content:a.data.content,source:a.data.source,pluginName:a.data.pluginName,pluginVersion:a.data.pluginVersion});let l=this._parentToolCallIdForSubagentEvent(a),d=ay(a.data,a.id);this._emitAction({type:"chat/toolCallStart",turnId:this._turnId,toolCallId:d.toolCallId,toolName:d.toolName,displayName:d.displayName},l),this._emitAction({type:"chat/toolCallReady",turnId:this._turnId,toolCallId:d.toolCallId,invocationMessage:d.invocationMessage,confirmed:"not-needed"},l),this._emitAction({type:"chat/toolCallComplete",turnId:this._turnId,toolCallId:d.toolCallId,result:{success:!0,pastTenseMessage:d.pastTenseMessage}},l)})),this._register(e.onSubagentStarted(a=>{a.agentId&&(this._parentToolCallIdsByAgentId.set(a.agentId,a.data.toolCallId),this._activeSubagentAgentIds.add(a.agentId)),this._logService.info(`[Copilot:${t}] Subagent started: toolCallId=${a.data.toolCallId}, agent=${a.data.agentName}`);let l=this._activeToolCalls.get(a.data.toolCallId);this._onDidSessionProgress.fire({kind:"subagent_started",chat:this._chatChannelUri,toolCallId:a.data.toolCallId,agentName:a.data.agentName,agentDisplayName:a.data.agentDisplayName,agentDescription:a.data.agentDescription,taskDescription:l?.meta?.subagentDescription,taskPrompt:typeof l?.parameters?.prompt=="string"?l.parameters.prompt:void 0,parentToolCallId:l?.parentToolCallId})})),this._register(e.onSessionError(a=>{this._logService.error(`[Copilot:${t}] Session error: ${a.data.errorType} - ${a.data.message}`);let l=WE(a.data)??$E(a.data.message);this._emitAction({type:"chat/error",turnId:this._turnId,duration:this._currentTurn?.duration??0,error:{errorType:a.data.errorType,message:Fu(a.data.message),stack:a.data.stack,...l?{_meta:l}:{}}})}));let r,i,s;this._register(e.onAutoModeResolved(a=>{this._lastSeenModelId=a.data.chosenModel;let l=this._turnId;if(this._logService.info(`[Copilot:${t}] Auto mode resolved to ${a.data.chosenModel}${a.data.reasoningBucket?` (${a.data.reasoningBucket})`:""}`),!l)return;s={turnId:l,data:a.data};let d=i===l?r:void 0,c={...d,model:a.data.chosenModel,_meta:{...d?._meta??{},autoModeResolved:a.data}};r=c,i=l,this._emitAction({type:"chat/usage",turnId:l,usage:c})})),this._register(e.onUsage(a=>{this._resumeSubagentForEvent(a);let l=this._parentToolCallIdForSubagentEvent(a);!l&&!a.agentId&&!a.data.parentToolCallId&&a.data.model&&this._setPromptCacheState(a.data.cacheExpiresAt?{modelId:a.data.model,cacheExpiresAt:a.data.cacheExpiresAt}:void 0);let d=a.data.copilotUsage,c=u6(a.data.quotaSnapshots),u=this._currentTurn;typeof a.data.model=="string"&&a.data.model&&(this._lastSeenModelId=a.data.model);let p={inputTokens:a.data.inputTokens,outputTokens:a.data.outputTokens,model:a.data.model,cacheReadTokens:a.data.cacheReadTokens,...typeof a.data.cost=="number"?{cost:a.data.cost}:{}};!l&&u&&(u.parentContextUsage=p);let g=(I,S)=>{let C={};if(typeof S.cost=="number"&&(C.cost=S.cost),I===""&&s?.turnId===this._turnId&&(C.autoModeResolved=s.data),u&&typeof d?.totalNanoAiu=="number"){let _=(u.copilotUsageTotalNanoAiuByScope.get(I)??0)+d.totalNanoAiu;u.copilotUsageTotalNanoAiuByScope.set(I,_),C.copilotUsage={...d,totalNanoAiu:_}}return c&&(C.quotaSnapshots=c),{inputTokens:S.inputTokens,outputTokens:S.outputTokens,model:S.model,cacheReadTokens:S.cacheReadTokens,...Object.keys(C).length>0?{_meta:C}:{}}},h=l?u?.parentContextUsage??{}:p,y=g("",h);r=y,i=this._turnId,this._emitAction({type:"chat/usage",turnId:this._turnId,usage:y}),l&&this._emitAction({type:"chat/usage",turnId:this._turnId,usage:g(l,p)},l)})),this._register(e.onUsage(async a=>{if(this._parentToolCallIdForSubagentEvent(a))return;let l=this._turnId,c=(i===l?r:void 0)??{inputTokens:a.data.inputTokens,outputTokens:a.data.outputTokens,model:a.data.model,cacheReadTokens:a.data.cacheReadTokens};try{let p=(await this._wrapper.session.rpc.metadata.getContextAttribution())?.contextAttribution;if(!p||!l){this._logService.trace(`[Copilot:${t}] contextAttribution: null/empty (turnId=${l})`);return}if(l!==this._turnId||c!==r||i!==l)return;this._logService.getLevel()<=1&&this._logService.trace(`[Copilot:${t}] contextAttribution: totalTokens=${p.totalTokens}, entries=${JSON.stringify(p.entries.map(h=>({kind:h.kind,id:h.id,label:h.label,tokens:h.tokens,parentId:h.parentId})))}`);let g={...c,_meta:{...c._meta??{},contextAttribution:p}};r=g,i=l,this._emitAction({type:"chat/usage",turnId:l,usage:g})}catch(u){this._logService.trace(`[Copilot:${t}] contextAttribution RPC failed: ${u?.message??u}`)}})),this._register(e.onReasoningDelta(a=>{this._logService.trace(`[Copilot:${t}] Reasoning delta: ${a.data.deltaContent.length} chars`),this._resumeSubagentForEvent(a),!this._shouldDropUnmappedSubagentEvent(a,"assistant.reasoning_delta")&&this._emitReasoningDelta(a.data.deltaContent,this._parentToolCallIdForSubagentEvent(a))})),this._register(e.onSessionModeChanged(a=>{if(a.agentId){this._logService.trace(`[Copilot:${t}] Ignoring subagent session.mode_changed: agentId=${a.agentId}, ${a.data.previousMode} -> ${a.data.newMode}`);return}this._logService.info(`[Copilot:${t}] session.mode_changed: ${a.data.previousMode} -> ${a.data.newMode}`);let l=a.data.newMode;l!=="interactive"&&l!=="plan"&&l!=="autopilot"||(this._lastAppliedMode=l,this._syncAhpConfigFromSdkMode(l))})),this._register(e.onMcpServersLoaded(a=>{this._logMcpServersSnapshot(a.data.servers.map(l=>({name:l.name,status:l.status,error:l.error,source:l.source,transport:l.transport,pluginName:l.pluginName,pluginVersion:l.pluginVersion})),"loaded"),this._applyMcpServerList(a.data.servers)})),this._register(e.onMcpServerStatusChanged(a=>{this._logMcpServerLifecycle({name:a.data.serverName,status:a.data.status,error:a.data.error,origin:"statusChanged"});let l=this._toSdkMcpServer(a.data.serverName,a.data.status,a.data.error);if(!l){this._mcpCustomizations.remove(a.data.serverName);return}this._mcpCustomizations.applyOne(l)})),this._register(e.onToolsUpdated(()=>{this._slashCommandProvider.clearCache(),this._fireMcpToolsListChanged()})),this._register(e.onCommandsChanged(()=>{this._slashCommandProvider.clearCache()})),this._seedMcpServersFromRpc()}_seedMcpServersFromRpc(){this._refreshMcpServersFromRpc().catch(e=>{this._logService.warn(`[Copilot:${this.sessionId}] Failed to seed MCP server inventory`,e)})}async _refreshMcpServersFromRpc(){let e=this._wrapper.session.rpc?.mcp;if(!e)return;let t=await e.list();this._store.isDisposed||(this._logMcpServersSnapshot(t.servers.map(r=>({name:r.name,status:r.status,error:r.error,source:r.source,pluginName:r.sourcePlugin,pluginVersion:r.sourcePluginVersion})),"inventory"),this._applyMcpServerList(t.servers))}_applyMcpServerList(e){let t=e.map(r=>this._toSdkMcpServer(r.name,r.status,r.error));this._mcpCustomizations.applyAll(t)}_logMcpServersSnapshot(e,t){let r=new Set;for(let i of e)r.add(i.name),this._logMcpServerLifecycle({...i,origin:t});for(let i of[...this._lastLoggedMcpStatus.keys()])r.has(i)||this._lastLoggedMcpStatus.delete(i)}_logMcpServerLifecycle(e){if(this._lastLoggedMcpStatus.get(e.name)===e.status)return;this._lastLoggedMcpStatus.set(e.name,e.status);let t=this._translateSdkMcpStatus(e.name,e.status,e.error),r={mcpEvent:e.origin,mcpServer:e.name,mcpStatus:e.status,mcpState:t.kind};e.source&&(r.mcpSource=e.source),e.transport&&(r.mcpTransport=e.transport),e.pluginName&&(r.mcpPlugin=e.pluginName),e.pluginVersion&&(r.mcpPluginVersion=e.pluginVersion),t.kind==="error"&&(r.errorType=t.error.errorType);let i=e.error?`: ${e.error}`:"",s=`[Copilot:${this.sessionId}] MCP server '${e.name}' ${e.status} (${t.kind})${i}`;e.status==="failed"?this._logService.error(s,new Bi(r)):this._logService.info(s,new Bi(r))}_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),enabled:t!=="disabled"}}_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._storageUri.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=this._currentTurn?.id;if(!r)return this._logService.warn(`[Copilot:${this.sessionId}] Rejecting plan review request without an active turn`),{approved:!1};let i=F(),s=F();this._logService.info(`[Copilot:${this.sessionId}] exitPlanMode.request: rpcId=${i}, actions=[${e.actions.join(",")}], recommended=${e.recommendedAction}`);let a=null;try{a=(await this._wrapper.session.rpc.plan.read()).path??null}catch(p){this._logService.warn(`[Copilot:${this.sessionId}] rpc.plan.read failed for exit_plan_mode: ${p instanceof Error?p.message:String(p)}`)}if(this._currentTurn?.id!==r)return this._logService.warn(`[Copilot:${this.sessionId}] Rejecting plan review request after its turn ended`),{approved:!1};let l=e.actions.map(p=>{let g=o6(p);return{id:p,label:g?.label??p,description:g?.description,recommended:p===e.recommendedAction}}),d=l.map(p=>({id:p.id,label:p.label,...p.description?{description:p.description}:{},...p.recommended?{default:!0}:{}})),c={id:i,planReview:{title:f(2283,null),content:e.summary||f(2279,null),actions:d,canProvideFeedback:!0,answerQuestionId:s,...a?{planUri:v.file(a).toString()}:{}},questions:[{kind:"single-select",id:s,title:f(2283,null),message:f(2282,null),required:!0,options:l,allowFreeformInput:!0}]},u=new be;this._pendingPlanReviews.set(i,{actions:e.actions,recommendedAction:e.recommendedAction,questionId:s,deferred:u}),this._onDidSessionProgress.fire({kind:"action",resource:this._chatChannelUri,action:{type:"chat/inputRequested",request:c}});try{return await u.p}catch(p){return this._logService.error(p,`[Copilot:${this.sessionId}] exitPlanMode.request handler failed: rpcId=${i}`),{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.agentId||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: ${In(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:M.id(this.sessionUri),isSubagentSession:Ir(this.sessionUri),totalInstructionsCount:i.length,agentInstructionsCount:s,applyingInstructionsCount:a,referencedInstructionsCount:l,claudeMdCount:d})})().catch(i=>{this._logService.trace(`[Copilot:${t}] instructionsCollected telemetry failed: ${In(i)}`)})}))}_subscribeForLogging(){let e=this._wrapper,t=this.sessionId;this._register(e.onUnhandledEvent(r=>{this._logService.trace(`[Copilot:${t}] Unhandled SDK event: ${Ur(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 Bi(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 Bi({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.onManagedSettingsResolved(r=>{this._logService.info(`[Copilot:${t}] Managed settings resolved: source=${r.data.source}, managedKeys=${r.data.managedKeys.join(",")||"(none)"}, bypassPermissionsDisabled=${r.data.bypassPermissionsDisabled}, failClosed=${r.data.failClosed}`)})),this._register(e.onManagedSettingsEnforced(r=>{this._logService.warn(`[Copilot:${t}] Managed settings enforced: action=${r.data.action}, setting=${r.data.setting}, escalation=${r.data.escalation??"(none)"}, failClosed=${r.data.failClosed}, message=${r.data.message}`)})),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(),this._currentTurn?.clientType??"unknown",r.data.content,this._turnOrdinal)})),this._register(e.onPendingMessagesModified(()=>{this._logService.trace(`[Copilot:${t}] Pending messages modified`)})),this._register(e.onTurnStart(r=>{if(this._currentTurn?.markRunning(),this._logService.trace(`[Copilot:${t}] Turn started: ${r.data.turnId}`),!r.agentId){let i=this._currentTurn?.id??r.data.turnId;if(this._activeRepoInfoTurn?.telemetryMessageId===i)return;this._cancelActiveRepoInfoTelemetry();let s={telemetryMessageId:i,cancelled:!1,begin:Promise.resolve(void 0)},a=()=>!s.cancelled&&this._isLaunchTokenCurrent();s.begin=this._beginRepoInfoTelemetry(i,a),this._activeRepoInfoTurn=s}})),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._cancelActiveRepoInfoTelemetry()})),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)`);let i=this._activeToolCalls.get(r.data.toolCallId);if(!i||!ji(i.toolName)||this._shellManager?.getTerminalUriForToolCall(r.data.toolCallId))return;let s=this._nonPtyShellTerminals.append(r.data.toolCallId,r.data.partialOutput);if(s?.created){let{uri:a}=s;i.content.push({type:"terminal",resource:a,title:i.displayName,isPty:!1}),this._emitAction({type:"chat/toolCallContentChanged",turnId:this._turnId,toolCallId:r.data.toolCallId,content:i.content},i.parentToolCallId)}})),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=>{this._completeSubagentTurn(r.agentId,r.data.toolCallId),this._logService.trace(`[Copilot:${t}] Subagent completed: ${r.data.agentName}`)})),this._register(e.onSubagentFailed(r=>{this._completeSubagentTurn(r.agentId,r.data.toolCallId),this._logService.error(`[Copilot:${t}] Subagent failed: ${r.data.agentName} - ${r.data.error}`)})),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}`),r.data.hookType==="agentStop"&&this._completeSubagentTurn(r.agentId)})),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({kind:"reject"});this._pendingPermissions.clear(),this._approvedDuplicablePermissionSignatures.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"})}};Ed=A([b(1,we),b(2,O),b(3,nt),b(4,xe),b(5,St),b(6,Ue),b(7,Ce),b(8,Pn),b(9,gt)],Ed);function c6(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 u6(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 p6(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:ue(t.fsPath)||t.toString()}}function f6(o){let n=o.includes("://")?v.parse(o):v.parse(`https://github.com/${o}`),e=ue(n.path)||o.split("/").filter(Boolean).pop()||o,t=e.endsWith(".git")?e.slice(0,-4):e;return{uri:n,displayName:t}}async function fr(o,n){let e=typeof o?.cwd=="string"?v.file(o.cwd):typeof o?.gitRoot=="string"?v.file(o.gitRoot):void 0,t=await p6(e,n);if(t)return t;if(o?.repository)return f6(o.repository)}var kd=class{constructor(n,e){this._isRestrictedTelemetryEnabled=n;this._telemetryService=e}forward(n){if(n.restricted&&!this._isRestrictedTelemetryEnabled())return;let e=n.event,t={...e.client,...e.properties,...e.metrics,created_at:e.created_at,model_call_id:e.model_call_id,exp_assignment_context:e.exp_assignment_context,session_id:e.session_id??n.sessionId,sdk_session_id:n.sessionId,copilot_tracking_id:e.copilot_tracking_id,kind:e.kind,restricted:n.restricted};if(e.features)for(let[r,i]of Object.entries(e.features))i!==void 0&&(t[`feature.${r}`]=i);this._telemetryService.publicLog(`copilotCli/${e.kind}`,t)}};kd=A([b(1,Pn)],kd);var k0=new Map([["engine.messages",1],["engine.messages.length",3],["model.message.added",2],["model.modelCall.input",2],["model.modelCall.output",2],["model.request.added",2],["model.request.options.added",2]]),uy=class{constructor(n){this._telemetryService=n}isTarget(n){return k0.has(n.event.kind)}route(n,e,t){let{event:r}=n,i=r.kind,s=k0.get(i);if(s===void 0)return!1;if(!n.restricted||!e)return!0;let a={...r.properties,...r.model_call_id&&r.properties.modelCallId===void 0?{modelCallId:r.model_call_id}:{},...t},l=Ho(a);return s&1&&e.restrictedTelemetryEnabled&&this._telemetryService.sendEnhancedGHTelemetryEventForContext(e,i,l,r.metrics),s&2&&e.isInternal&&this._telemetryService.sendInternalMSFTTelemetryEventForContext(e,i,l,r.metrics),!0}};var D0=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","cd","cwd","after","before","add-dir","allow-all","list-dirs","reset-allowed-tools"]),g6=300,py=class{constructor(n,e,t=g6){this.copilotcliId=n;this._sessionInfo=e;this._runtimeSlashCommandCompletionWaitMs=t;this.kinds=new Set(["userMessage"]);this.triggerCharacters=["/"]}async provideCompletionItems(n,e){if(M.provider(n.channel)!==this.copilotcliId)return[];let t=Dm(n.text,n.offset),r=km(n.text,n.offset),i=r??t,s=!r&&!!t;if(!i)return[];let a=M.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"&&!m6(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 g of s){if(!g.name||i&&g.kind!=="skill"||g.kind==="skill"&&a.has(g.name)||D0.has(g.name)||g.aliases?.some(I=>D0.has(I))||yb(g.name)||g.aliases?.some(I=>yb(I))||!d&&g.name==="rubber-duck"||!Vs(l,g.name)&&!g.aliases?.some(I=>Vs(l,I)))continue;let h=[];(g.input?.hint||!g.input?.choices?.length)&&h.push({name:"",description:g.description,argumentHint:g.input?.hint}),g.input?.choices?.length&&h.push(...g.input.choices),Array.from(new Set([g.name].concat(g.aliases??[]))).filter(I=>!u.has(I)).forEach(I=>{h.forEach(S=>{let C=`/${I}${S.name?" "+S.name:""} `,_=S.description??g.description,T=S.argumentHint;u.add(I),c.push({insertText:C,rangeStart:t,rangeEnd:r,attachment:{type:"simple",label:C,_meta:Mu({command:g.name,..._!==void 0?{description:_}:{},...T!==void 0?{argumentHint:T}:{}})}})})})}if(!i){let g=this._sessionInfo.getSessionConfigState?.(n);for(let h of x1(e,g))c.push({insertText:h.insertText,rangeStart:t,rangeEnd:r,attachment:{type:"simple",label:h.label,_meta:Mu({command:h.command,description:h.description,...h.argumentHint!==void 0?{argumentHint:h.argumentHint}:{},action:{applyConfig:h.applyConfig}})}})}let p=g=>ZP(g.attachment._meta)?g.attachment.label:g.insertText;return c.sort((g,h)=>p(g).localeCompare(p(h)))}};function m6(o){return o.uri.startsWith(Xu+":")}import{appendFile as h6,mkdir as y6}from"fs/promises";function M0(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 L0(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()||!v6(t.files,r.files))return!1}return!0}function O0(o,n){let e=Fn(o.type,n.type);return e!==0?e:Fn(o.uri.toString(),n.uri.toString())}function v6(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 Dd(o,n){return Fn(o.uri.toString(),n.uri.toString())}function S6(o,n){let e=Fn(o.uri,n.uri);return e!==0?e:Fn(o.contents,n.contents)}var C6=5,I6=8;var b6=".md",_6=".instructions.md",T6=".json",w6="SKILL.md",R6="README.md",Wb=void 0,x6=new Set(["agents.md","claude.md","gemini.md","copilot-instructions.md"]),Md={workspace:[{path:[".github","agents"],type:"agent",name:".github"},{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"}]},Gi={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 pt(o){if(o.isCancellationRequested)throw new K}function Od(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 pn},o.set(n,r)),r.resourcesToWatch.add(t)}var Ld=class extends x{constructor(e,t,r=v.file,i,s){super();this._workingDirectory=e;this._userHome=t;this._pathToUri=r;this._fileService=i;this._logService=s;this._onDidChange=this._register(new E);this.onDidChange=this._onDidChange.event;this._discoveredDirectories=void 0;this._watchers=new Me;this._register({dispose:()=>this._disposeAllWatchers()}),this._register(this._fileService.onDidFilesChange(a=>{for(let l of this._watchers.values())for(let d of l.resourcesToWatch)if(a.affects(d)){this._scheduleRefresh();return}}))}_scheduleRefresh(){this._onDidChange.fire()}async writeCustomizationDiscoveryDebugLog(e){if(Wb)try{await y6(te(Wb),{recursive:!0}),await h6(Wb,`${JSON.stringify({timestamp:new Date().toISOString(),...e},void 0,2)}
`,"utf8")}catch(t){this._logService.error(`[SessionCustomizationDiscovery] Failed to write discovery debug log: ${t instanceof Error?t.message:String(t)}`)}}async getDiscoveredDirectories(e,t){pt(t);let r={projectPaths:[this._workingDirectory.fsPath]},i=this.getHooksDiscoveryPaths(),s=[],a=[];try{let[l,d,c]=await Promise.all([hs(e.rpc.agents.getDiscoveryPaths(r),t),hs(e.rpc.instructions.getDiscoveryPaths(r),t),hs(e.rpc.skills.getDiscoveryPaths(r),t)]);for(let u of l?.paths??[])pt(t),i.push({uri:this._pathToUri(u.path),type:"agent",files:[],name:ue(u.path),writable:!0});for(let u of d?.paths??[])if(pt(t),u.kind==="file"){let p=this._pathToUri(u.path),g={uri:p,etag:""};re.isEqualOrParent(p,this._workingDirectory)?s.push(g):re.isEqualOrParent(p,this._userHome)&&a.push(g);continue}else u.kind==="directory"&&i.push({uri:this._pathToUri(u.path),type:"instruction",files:[],name:ue(u.path),writable:!0});s.length>0&&i.push({uri:this._workingDirectory,type:"agentInstruction",files:s,name:"",writable:!1}),a.length>0&&i.push({uri:this._userHome,type:"agentInstruction",files:a,name:"",writable:!1});for(let u of c?.paths??[])pt(t),i.push({uri:this._pathToUri(u.path),type:"skill",files:[],name:ue(u.path),writable:!0})}catch(l){if(l instanceof K)throw l;this._logService.debug(`[SessionCustomizationDiscovery] Error getting discovery paths: ${l instanceof Error?l.message:String(l)}`)}return i.sort(O0)}getHooksDiscoveryPaths(){let e=new Me,t=(r,i)=>{e.has(r)||e.set(r,{uri:r,type:"hook",files:[],name:i,writable:!0})};for(let r of Md.workspace)r.type==="hook"&&t(Y(this._workingDirectory,...r.path),r.name);for(let r of Md.user)r.type==="hook"&&t(Y(this._userHome,...r.path),r.name);for(let r of Gi.workspace)r.type==="hook"&&t(Y(this._workingDirectory,...r.path),ue(Y(this._workingDirectory,...r.path).path));for(let r of Gi.user)r.type==="hook"&&t(Y(this._userHome,...r.path),ue(Y(this._userHome,...r.path).path));return[...e.values()]}async _updateWatchers(e,t){let r=new Me,i=new pn,s=new Me;for(let c of e){pt(t);let u=c.uri,p=c.type==="skill"||c.type==="instruction"||c.type==="hook";s.set(u,p),i.add(u);let g=u;for(;!re.isEqual(g,this._workingDirectory)&&!re.isEqual(g,this._userHome);){let h=Ut(g);if(re.isEqual(h,g))break;i.add(h),g=h}for(let h of c.files){pt(t);let y=h.uri;for(;!re.isEqual(y,this._workingDirectory)&&!re.isEqual(y,this._userHome);){let I=Ut(y);if(re.isEqual(I,y))break;i.add(I),y=I}}}pt(t);let a=[...i],l=await this._fileService.resolveAll(a.map(c=>({resource:c}))),d=new pn;for(let c=0;c<l.length;c++){let u=l[c];u.success&&u.stat?.isDirectory&&d.add(a[c])}for(let c of e){pt(t);let u=c.uri,p=s.get(u)??!1;d.has(u)&&Od(r,u,p,u);let g=u;for(;!re.isEqual(g,this._workingDirectory)&&!re.isEqual(g,this._userHome);){let h=Ut(g);if(re.isEqual(h,g))break;d.has(h)&&Od(r,h,!1,g),g=h}for(let h of c.files){pt(t);let y=h.uri;for(;!re.isEqual(y,this._workingDirectory)&&!re.isEqual(y,this._userHome);){let I=Ut(y);if(re.isEqual(I,y))break;d.has(I)&&Od(r,I,!1,y),y=I}}}this._reconcileWatchers(r)}async discover(e,t){await this.writeCustomizationDiscoveryDebugLog({method:"discover",workingDirectory:this._workingDirectory.toString(),userHome:this._userHome.toString()}),this._discoveredDirectories||(this._discoveredDirectories=await this.getDiscoveredDirectories(e,t)),pt(t);let r={projectPaths:[this._workingDirectory.fsPath]};try{let[i,s,a,l]=await Promise.all([this.discoverAgents(r,e,t),this.discoverRules(r,e,t),this.discoverSkills(r,e,t),this.discoverHooks(t),this._updateWatchers(this._discoveredDirectories,t)]);pt(t);let d=[];await this.toDirectoryCustomizations("agent",i,this._discoveredDirectories,d),await this.toDirectoryCustomizations("rule",s,this._discoveredDirectories,d),await this.toDirectoryCustomizations("skill",a,this._discoveredDirectories,d),await this.toDirectoryCustomizations("hook",l,this._discoveredDirectories,d);let c=d.sort(S6);return await this.writeCustomizationDiscoveryDebugLog({method:"discover",result:c.map(u=>({contents:u.contents,uri:u.uri,children:(u.children??[]).map(p=>({type:p.type,uri:p.uri,name:p.name}))}))}),c}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 hs(t.rpc.agents.discover(e),r);for(let a of s.agents)if(a.path){let l=this._pathToUri(a.path);i.push({type:"agent",uri:l.toString(),id:a.id,name:a.name,description:a.description,_meta:M0({userInvocable:a.userInvocable})})}return i}async discoverRules(e,t,r){let i=[],s=new Set,a=await hs(t.rpc.instructions.discover(e),r);await this.writeCustomizationDiscoveryDebugLog({method:"discoverRules.instructions.discover",sources:a.sources.map(l=>({id:l.id,label:l.label,sourcePath:l.sourcePath,applyTo:l.applyTo,type:l.type}))});for(let l of a.sources){let d;nn(l.sourcePath)?d=this._pathToUri(l.sourcePath):d=Y(this._workingDirectory,l.sourcePath);let c=d.toString();i.push({type:"rule",uri:c,id:l.id,name:l.label,description:l.description,globs:l.applyTo?[...l.applyTo]:void 0,alwaysApply:this._isAgentInstructionSource(l)}),s.add(c)}for(let l of this._discoveredDirectories??[])if(l.type==="agentInstruction")for(let d of l.files){let c=d.uri.toString();s.has(c)||(i.push({type:"rule",uri:c,id:et(c),name:ue(d.uri.path),alwaysApply:!0}),s.add(c))}return i}_isAgentInstructionSource(e){if(e.type==="home"||e.type==="repo"||e.type==="model")return!0;let t=ue(e.sourcePath).toLowerCase();return x6.has(t)}async discoverSkills(e,t,r){let i=[],s=await hs(t.rpc.skills.discover(e),r);for(let a of s.skills)if(a.path){let l=this._pathToUri(a.path);i.push({type:"skill",uri:l.toString(),id:a.path,name:a.name,description:a.description})}return i}async discoverHooks(e){let t=new pn,r=[],i=Md.workspace.filter(c=>c.type==="hook"),s=Md.user.filter(c=>c.type==="hook"),a=Gi.workspace.filter(c=>c.type==="hook"),l=Gi.user.filter(c=>c.type==="hook");await Promise.all([...i.map(c=>this._discoverHookRoot(this._workingDirectory,c,t,r,e)),...s.map(c=>this._discoverHookRoot(this._userHome,c,t,r,e)),this._discoverFixedHookFiles(this._workingDirectory,a,t,r,e),this._discoverFixedHookFiles(this._userHome,l,t,r,e)]);let d=[];for(let c of r)for(let u of c.files){let p=u.uri.toString();d.push({type:"hook",id:et(p),uri:p,name:ue(u.uri.path)})}return d.sort((c,u)=>Fn(c.uri,u.uri)),d}async _discoverHookRoot(e,t,r,i,s){let a=Y(e,...t.path),l;try{l=await this._fileService.resolve(a,{resolveMetadata:!0})}catch{}await this._scanForHooks(t,a,l,r,i,s)}async _discoverFixedHookFiles(e,t,r,i,s){for(let a of t){pt(s);let l=Y(e,...a.path),d=[],c;try{c=await this._fileService.resolve(l,{resolveMetadata:!0})}catch{}for(let u of c?.children??[])pt(s),u.isFile&&a.filenames.includes(u.name)&&(r.has(u.resource)||(r.add(u.resource),d.push({uri:u.resource,etag:u.etag})));d.length>0&&i.push({uri:l,type:"hook",files:d.sort(Dd),name:ue(l.path),writable:!0})}}async toDirectoryCustomizations(e,t,r,i){let s=r.filter(p=>e==="agent"?p.type==="agent":e==="rule"?p.type==="instruction"||p.type==="agentInstruction":e==="hook"?p.type==="hook":p.type==="skill"),a=e==="rule"?s.filter(p=>p.type!=="agentInstruction"||re.isEqual(p.uri,this._workingDirectory)||re.isEqual(p.uri,this._userHome)):s,l=e==="skill"?a.filter(p=>!a.some(g=>!re.isEqual(p.uri,g.uri)&&re.isEqualOrParent(p.uri,g.uri))):a,d=new Me;for(let p of l)d.set(p.uri,{uri:p.uri,name:p.name||ue(p.uri.path),writable:p.writable,children:[]});let c=e==="hook"?new pn([...Gi.workspace.filter(p=>p.type==="hook").map(p=>Y(this._workingDirectory,...p.path)),...Gi.user.filter(p=>p.type==="hook").map(p=>Y(this._userHome,...p.path))]):void 0,u=new pn(l.filter(p=>p.type==="agentInstruction").map(p=>p.uri));for(let p of t){if(p.type!==e)continue;let g=v.parse(p.uri),h=l.find(S=>re.isEqualOrParent(g,S.uri));if(!h&&p.type==="rule"&&p.alwaysApply&&p.name.match(/\.md$/i)&&(h=l.find(S=>S.type==="agentInstruction"&&re.isEqualOrParent(g,S.uri))??l.find(S=>S.type==="agentInstruction")),h)for(let S of l)re.isEqualOrParent(g,S.uri)&&S.uri.path.length>h.uri.path.length&&(h=S);let y=h?.uri??Ut(g),I=d.get(y);I||(this._logService.error(`[SessionCustomizationDiscovery] BUG: customization '${p.uri}' of type '${p.type}' is outside discovered directories; creating fallback directory '${y.toString()}'.`),I={uri:y,name:ue(y.path),writable:!0,children:[]},d.set(y,I)),I.children.push(p)}for(let{uri:p,name:g,writable:h,children:y}of d.values())if(!(e==="hook"&&c?.has(p)&&y.length===0)){if(e==="rule"&&u.has(p)){let I=[];for(let S of y){let C=v.parse(S.uri);try{(await this._fileService.resolve(C,{resolveMetadata:!0})).isFile&&I.push(S)}catch{}}if(I.length===0)continue;y.length=0,y.push(...I)}y.sort((I,S)=>Fn(I.uri,S.uri)),i.push({type:"directory",id:et(p.toString()),uri:p.toString(),name:g,enabled:!0,contents:e,writable:h,load:{kind:"loaded"},children:y})}}async scan(e){await this.writeCustomizationDiscoveryDebugLog({method:"scan",workingDirectory:this._workingDirectory.toString(),userHome:this._userHome.toString()}),pt(e);let t=new Me,r=new pn,i=[];await Promise.all([...Md.workspace.map(a=>this._scanRoot(this._workingDirectory,a,r,i,t,e)),...Md.user.map(a=>this._scanRoot(this._userHome,a,r,i,t,e)),this._scanFixedDiscoveryFiles(this._workingDirectory,Gi.workspace,r,i,t,e),this._scanFixedDiscoveryFiles(this._userHome,Gi.user,r,i,t,e)]),pt(e),this._reconcileWatchers(t);let s=i.sort(O0);return await this.writeCustomizationDiscoveryDebugLog({method:"scan",result:s.map(a=>({type:a.type,uri:a.uri.toString(),files:a.files.map(l=>l.uri.toString())}))}),s}async _watchAncestors(e,t,r,i){let s=e;for(let a of t){let l=s,d=Y(l,a);if(!r.has(l)){pt(i);try{if(!(await this._fileService.resolve(l)).isDirectory)return!1}catch{return!1}}Od(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(pt(a),!await this._watchAncestors(e,d.path,s,a))return;let c=Y(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)Od(s,c,!1,Y(c,p));for(let p of u.children)if(pt(a),p.isFile&&d.filenames.includes(p.name)){let g=Y(c,p.name);if(!r.has(g)){r.add(g);let h=l.get(d.type)??[];h.push({uri:g,etag:p.etag}),l.set(d.type,h)}}}}));for(let[d,c]of l.entries())c.length>0&&i.push({uri:e,type:d,files:c.sort(Dd),name:"",writable:!1})}async _scanRoot(e,t,r,i,s,a){pt(a);let l=Y(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),Od(s,l,t.recursive??!1,l),t.type==="skill"){let u=[];await Promise.all(c.map(async p=>{if(pt(a),p.isDirectory){let g=Y(p.resource,w6);try{let h=await this._fileService.resolve(g,{resolveMetadata:!0});h.isFile&&!r.has(g)&&(r.add(g),u.push({uri:g,etag:h.etag}))}catch{}}})),i.push({uri:l,type:t.type,files:u.sort(Dd),name:t.name,writable:!0})}else if(t.type==="agent"){let u=[];for(let p of c)if(pt(a),p.isFile){let g=p.name;g.endsWith(b6)&&g!==R6&&!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(Dd),name:t.name,writable:!0})}else if(t.type==="instruction"){let u=[],p=async(g,h)=>{pt(a);for(let y of g.children??[])if(pt(a),y.isFile)y.name.toLowerCase().endsWith(_6)&&!r.has(y.resource)&&(r.add(y.resource),u.push({uri:y.resource,etag:y.etag}));else if(y.isDirectory&&h<C6){let I;try{I=await this._fileService.resolve(y.resource,{resolveMetadata:!0})}catch{}I&&await p(I,h+1)}};d&&await p(d,0),i.push({uri:l,type:t.type,files:u.sort(Dd),name:t.name,writable:!0})}else t.type==="hook"?await this._scanForHooks(t,l,d,r,i,a):this._logService.warn(`[SessionCustomizationDiscovery] Unrecognized root type '${t.type}' for root '${l.toString()}'`)}async _scanForHooks(e,t,r,i,s,a){let l=[],d=async(c,u)=>{pt(a);for(let p of c.children??[])if(pt(a),p.isFile)p.name.toLowerCase().endsWith(T6)&&!i.has(p.resource)&&(i.add(p.resource),l.push({uri:p.resource,etag:p.etag}));else if(p.isDirectory&&u<I6){let g;try{g=await this._fileService.resolve(p.resource,{resolveMetadata:!0})}catch{}g&&await d(g,u+1)}};r&&await d(r,0),s.push({uri:t,type:e.type,files:l.sort(Dd),name:e.name,writable:!0})}};Ld=A([b(3,xe),b(4,O)],Ld);function k6(o){return typeof o=="object"&&o!==null&&"getManagedSettings"in o&&typeof o.getManagedSettings=="function"}var D6=300,N0="https://api.githubcopilot.com",M6=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"],O6=["HTTP_PROXY","HTTPS_PROXY"];async function qb(o){try{return await dn.access(o),!0}catch{return!1}}function L6(){return process.platform!=="linux"?!1:!process.report?.getReport()?.header?.glibcVersionRuntime}function N6(){let o=`${process.platform}-${process.arch}`;if(process.platform!=="linux")return[o];let n=[`linux-${process.arch}`,`linuxmusl-${process.arch}`];return L6()?n.reverse():n}async function U0(o){let n=[];for(let t of N6()){let r=v.joinPath(o,"@github",`copilot-${t}`,"index.js").fsPath;if(n.push(r),await qb(r))return r}let e=v.joinPath(o,"@github","copilot","index.js").fsPath;if(n.push(e),await qb(e))return e;throw new Error(`Unable to resolve @github/copilot CLI path. Tried: ${n.join(", ")}`)}function F0(o){return o?`${o.replace(/\/+$/,"")}/telemetry`:void 0}function W0(o,n,e){if(!Or(o,n))return;let t=Zn(n,o);if(t!==void 0)return t.length===0?e:Y(e,t)}var aa=class extends ll{},it=class extends x{constructor(e,t,r,i,s,a,l,d,c,u,p,g,h,y,I,S){super();this._logService=e;this._instantiationService=t;this._sessionDataService=r;this._gitService=i;this._configurationService=s;this._stateManager=a;this._gitHubEndpointService=l;this._otelService=d;this._checkpointService=u;this._reviewService=p;this._environmentService=g;this._byokBridgeRegistry=h;this._telemetryService=y;this._copilotApiService=I;this._proxyResolver=S;this.id="copilotcli";this._onDidSessionProgress=this._register(new E);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidSpawnChat=this._register(new E);this.onDidSpawnChat=this._onDidSpawnChat.event;this._onDidMaterializeSession=this._register(new E);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onMcpNotification=this._register(new E);this.onMcpNotification=this._onMcpNotification.event;this._models=yn(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 ht);this._modelCatalogGeneration=0;this._modelRefreshSchedule=this._register(new ht);this._pendingClientRestartReasons=new Set;this._restrictedTelemetryEnabled=!1;this._onDidChangeRestrictedTelemetry=this._register(new E);this.onDidChangeRestrictedTelemetry=this._onDidChangeRestrictedTelemetry.event;this._sessions=this._register(new Ee);this._sdkSessionsById=new Map;this._chatBackings=new Map;this._onDidChangeChatData=this._register(new E);this.onDidChangeChatData=this._onDidChangeChatData.event;this._mcpNotificationSubs=this._register(new Ee);this._resumingSessions=new Map;this._provisionalSessions=new Map;this._sessionSequencer=new Ze;this._activeClients=new Me;this._lastSessionSyncEnabled=this._isSessionSyncEnabled();this._lastRubberDuckEnabled=this._isRubberDuckEnabled();this._lastCopilotSdkLogLevelSetting=this._getCopilotSdkLogLevelSetting();this._lastEnterpriseHost=this._getEnterpriseHost();this._lastSystemProxyEnabled=this._isSystemProxyEnabled();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,a,l)=>this._sendMessage(e,t,i,s,a,l,r),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(Sp,()=>this._ensureClient())),this._sessionLauncher=this._instantiationService.createInstance(wd),this._gitHubTelemetryForwarder=this._instantiationService.createInstance(kd,()=>this._restrictedTelemetryEnabled),this._slashCommandProvider=new Ki(()=>this._ensureClient().then(C=>C.rpc.commands.list().then(_=>_.commands)),this._logService),this._githubTelemetryRouter=_m(this._telemetryService)?new uy(this._telemetryService):void 0,this.onDidCustomizationsChange=this._plugins.onDidChange,this._register(this._onDidSessionProgress.event(C=>this._emitSpawnedChatForSubagentSignal(C))),this._register(c.registerProvider(new py(this.id,{isRubberDuckEnabled:()=>this._isRubberDuckEnabled(),getRuntimeSlashCommands:(C,_)=>this._getRuntimeSlashCommands(C,_),getSessionCustomizations:C=>this.getSessionCustomizations(M.uri(this.id,C)),getSessionConfigState:C=>this._getSessionConfigState(C)},D6))),this._register(this._configurationService.onDidRootConfigChange(()=>{this._restartClientIfStartupConfigChanged().catch(C=>this._logService.error("[Copilot] Failed to apply root config change",C))})),this._register(this._byokBridgeRegistry.onDidChangeModels(()=>{this._logService.info("[Copilot] BYOK bridge changed; refreshing models"),this._refreshByokModels()})),this._register(this._gitHubEndpointService.onDidChange(()=>{this._restartClientIfStartupConfigChanged().catch(C=>this._logService.error("[Copilot] Failed to restart client after endpoint change",C))}))}setServerToolHost(e){this._serverToolHost=e}get restrictedTelemetryEnabled(){return this._restrictedTelemetryEnabled}_emitSpawnedChatForSubagentSignal(e){let t=Ts.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_isSessionSyncEnabled(){return this._configurationService.getRootValue(tt,Gc)===!0}_isRubberDuckEnabled(){return this._configurationService.getRootValue(jt,"rubberDuck")===!0}_getCopilotSdkLogLevelSetting(){return this._configurationService.getRootValue(jt,"copilotSdkLogLevel")??"info"}_resolveCopilotSdkLogLevel(e){return e==="trace"||this._logService.getLevel()===1?"all":"info"}_getEnterpriseHost(){return this._gitHubEndpointService.getEnterpriseHost()}_isPreferLongContextEnabled(){return this._configurationService.getRootValue(tt,OS)===!0}_isSystemProxyEnabled(){return this._configurationService.getRootValue(tt,LS)!==!1}async _restartClientIfStartupConfigChanged(){let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled(),r=this._getCopilotSdkLogLevelSetting(),i=this._getEnterpriseHost(),s=this._isSystemProxyEnabled();if(this._lastSessionSyncEnabled===e&&this._lastRubberDuckEnabled===t&&this._lastCopilotSdkLogLevelSetting===r&&this._lastEnterpriseHost===i&&this._lastSystemProxyEnabled===s)return;let a=[this._lastSessionSyncEnabled!==e?`sessionSync=${e}`:void 0,this._lastRubberDuckEnabled!==t?`rubberDuck=${t}`:void 0,this._lastCopilotSdkLogLevelSetting!==r?`copilotSdkLogLevel=${r}`:void 0,this._lastEnterpriseHost!==i?`enterpriseHost=${i}`:void 0,this._lastSystemProxyEnabled!==s?`systemProxy=${s}`:void 0].filter(l=>l!==void 0).join(", ");this._lastSessionSyncEnabled=e,this._lastRubberDuckEnabled=t,this._lastCopilotSdkLogLevelSetting=r,this._lastEnterpriseHost=i,this._lastSystemProxyEnabled=s,await this._requestClientRestart(`startup config changed: ${a}`)}async _requestClientRestart(e){if(this._shutdownPromise||!this._client)return;this._pendingClientRestartReasons.add(e);let t=this._chatsWithActiveTurn();if(t>0){this._logService.info(`[Copilot] Deferring CopilotClient restart (${e}) until ${t} in-flight turn(s) finish`);return}await this._applyPendingClientRestart()}async _applyPendingClientRestart(){if(this._pendingClientRestartReasons.size===0||this._shutdownPromise||!this._client||this._chatsWithActiveTurn()>0)return;let e=[...this._pendingClientRestartReasons].join("; ");this._logService.info(`[Copilot] Restarting CopilotClient (${e})`),this._sessions.clearAndDisposeAll(),this._mcpNotificationSubs.clearAndDisposeAll(),await this._stopClient(),this._capiModels=[],this._publishModels(),this._scheduleModelRefresh()}_onChatTurnEnded(){this._pendingClientRestartReasons.size!==0&&queueMicrotask(()=>{this._applyPendingClientRestart().catch(e=>this._logService.error("[Copilot] Failed to apply deferred client restart",e))})}_chatsWithActiveTurn(){let e=0;for(let[,t]of this._sessions)for(let r of t.allChatSessions())r.hasActiveTurn&&e++;return e}_createCopilotClient(e){return new A6(e)}getDescriptor(){return{provider:"copilotcli",displayName:"Copilot",description:f(2271,null),capabilities:{multipleChats:{fork:!0,sideChat:!0}}}}getProtectedResources(){return[this._gitHubEndpointService.getCopilotResource(),this._gitHubEndpointService.getRepoResource()]}async getNetworkDiagnosticsEndpoints(){let e=process.env.VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE||N0;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}async getManagedSettingsDiagnostics(){let e=Nt.asFileUri(Lu()),t=await U0(e),r=V(te(t),"sdk","index.js");if(!await qb(r))throw new Error(`Copilot runtime SDK not found at ${r}`);let i=await import(E6(r).href);if(!k6(i))throw new Error("Copilot runtime SDK does not expose getManagedSettings()");let s=this._getEnterpriseHost(),a=await i.getManagedSettings({...this._githubToken?{token:this._githubToken}:{},...s?{host:s}:{}});return{...a.resolved,...a.account?{account:a.account}:{}}}getCustomizations(){return this._plugins.getConfiguredHostCustomizations()}async getSessionCustomizations(e){let t=await this._getSessionCustomizationDirectory(e),i=await this._getOrCreateActiveClient(e,t).pluginController.getCustomizationsSettled(),s=M.id(e),l=this._findAnySession(s)?.topLevelMcpCustomizations()??[],d=[...i,...l],c=this._stateManager.getSessionState(e.toString())?.customizations??[];return Sh(d,c)}async handleMcpRequest(e,t,r,i){let s=M.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=M.id(e);await this._findAnySession(r)?.startMcpServer(t)}async stopMcpServer(e,t){let r=M.id(e);await this._findAnySession(r)?.stopMcpServer(t)}async _getSessionCustomizationDirectory(e){let t=M.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._scheduleModelRefresh()),!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(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,telemetryEndpoint:F0(t.telemetryEndpoint)})}catch(t){this._logService.debug(`[Copilot] Restricted telemetry resolution failed: ${t instanceof Error?t.message:String(t)}`)}}_applyRestrictedTelemetry(e){let t=e?.restrictedTelemetryEnabled===!0;t!==this._restrictedTelemetryEnabled&&(this._restrictedTelemetryEnabled=t,this._logService.info(`[Copilot] Enhanced (restricted) telemetry ${t?"enabled for this account":"disabled"}`),this._onDidChangeRestrictedTelemetry.fire()),_m(this._telemetryService)&&(this._telemetryService.setRestrictedTelemetryEnabled(t),this._telemetryService.setCopilotTrackingId(e?.trackingId),this._telemetryService.setRestrictedTelemetryEndpoint(e?.telemetryEndpoint))}async _routeGitHubTelemetry(e){let t={initiatorClientType:this._clientTypeForTelemetry(e.sessionId)},r=this._githubTelemetryRouter;if(!r?.isTarget(e)){this._gitHubTelemetryForwarder.forward(e);return}if(!e.restricted){r.route(e,void 0,t);return}let i=e.sessionId,s=this._githubToken;if(!s){r.route(e,void 0,t);return}try{let a=await this._copilotApiService.resolveRestrictedTelemetryContext(s);if(this._githubToken!==s)return;r.route(e,{restrictedTelemetryEnabled:a.restrictedTelemetryEnabled,trackingId:a.trackingId,telemetryEndpoint:F0(a.telemetryEndpoint),isInternal:a.isInternal===!0,userName:a.userName,isVscodeTeamMember:a.isVscodeTeamMember===!0},t)}catch(a){this._logService.debug(`[Copilot:${i}] Restricted telemetry context resolution failed; dropping ${e.event.kind}: ${a instanceof Error?a.message:String(a)}`)}}_clientTypeForTelemetry(e){return e?this._sdkSessionsById.get(e)?.currentTurnClientType??"unknown":"unknown"}refreshModels(){return this._scheduledModelRefresh?.deferred.p??this._modelRefreshInFlight??this._startModelRefresh(++this._modelCatalogGeneration)}_scheduleModelRefresh(){let e=++this._modelCatalogGeneration;if(this._scheduledModelRefresh)return this._scheduledModelRefresh.generation=e,this._scheduledModelRefresh.deferred.p;let t={deferred:new be,generation:e};return this._scheduledModelRefresh=t,this._modelRefreshSchedule.value=Ft(()=>{(async()=>{try{if(await this._clientStopping,this._scheduledModelRefresh!==t)return;this._scheduledModelRefresh=void 0,this._modelRefreshSchedule.clear(),await this._startModelRefresh(t.generation)}catch(r){this._logService.error(r,"[Copilot] Failed to schedule model refresh")}finally{this._scheduledModelRefresh===t&&(this._scheduledModelRefresh=void 0,this._modelRefreshSchedule.clear()),t.deferred.complete()}})()},0),t.deferred.p}_startModelRefresh(e){let t=this._refreshModels(0,e).finally(()=>{this._modelRefreshInFlight===t&&(this._modelRefreshInFlight=void 0)});return this._modelRefreshInFlight=t,t}async _refreshModels(e=0,t=this._modelCatalogGeneration){if(this._modelRefreshRetry.clear(),this._shutdownPromise)return;let r=this._githubToken;if(!r){this._capiModels=[],this._publishModels();return}try{let i=await this._listModels(r);this._githubToken===r&&this._modelCatalogGeneration===t&&(this._capiModels=i,this._publishModels())}catch(i){if(this._githubToken!==r||this._modelCatalogGeneration!==t||this._shutdownPromise)return;if(e+1<this._modelRefreshMaxAttempts){let s=this._modelRefreshBackoff(e);this._logService.warn(`[Copilot] Failed to refresh models (attempt ${e+1}), retrying in ${s}ms`,i),this._modelRefreshRetry.value=Ft(()=>{this._refreshModels(e+1,t)},s);return}this._logService.error(i,"[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=pP(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))}_stopClient(){if(this._pendingClientRestartReasons.clear(),this._clientStopping)return this._clientStopping;let e=(async()=>{let t=this._clientStarting;if(t)try{await t}catch{}let r=this._client;this._client=void 0,this._clientStarting=void 0,await r?.stop(),await this._sessionLauncher.disposeByokProxyHandle()})().finally(()=>{this._clientStopping===e&&(this._clientStopping=void 0)});return this._clientStopping=e,e}_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._shutdownPromise)throw new K;for(;this._clientStopping;)if(await this._clientStopping,this._shutdownPromise)throw new K;if(this._client)return this._client;if(this._clientStarting)return this._clientStarting;let e=this._isSessionSyncEnabled(),t=this._isRubberDuckEnabled(),r=this._getCopilotSdkLogLevelSetting(),i=this._getEnterpriseHost(),s=this._isSystemProxyEnabled(),a=(async()=>{this._logService.info("[Copilot] Starting CopilotClient...");let l=Object.assign({},process.env,{ELECTRON_RUN_AS_NODE:"1"});delete l.NODE_OPTIONS,delete l.VSCODE_INSPECTOR_OPTIONS,delete l.VSCODE_ESM_ENTRYPOINT,delete l.VSCODE_HANDLES_UNCAUGHT_ERRORS;for(let T of Object.keys(l))T!=="ELECTRON_RUN_AS_NODE"&&T!=="VSCODE_AGENT_HOST_CAPI_URL_OVERRIDE"&&(T.startsWith("VSCODE_")||T.startsWith("ELECTRON_"))&&delete l[T];if(l.COPILOT_CLI_RUN_AS_NODE="1",l.USE_BUILTIN_RIPGREP="false",l.COPILOT_MCP_APPS="true",l[Vr]=jr,l.AUTO_APPROVAL="true",await this._configureProxyEnv(l),process.platform==="linux"){let T=l.COPILOT_CLI_ENABLED_FEATURE_FLAGS,w=new Set((T??"").split(",").map(W=>W.trim()).filter(Boolean));w.add("SHELL_SPAWN_BACKEND"),l.COPILOT_CLI_ENABLED_FEATURE_FLAGS=[...w].join(",")}l.GITHUB_COPILOT_INTEGRATION_ID=EI,this._logService.info(`[Copilot] Set CLI env: GITHUB_COPILOT_INTEGRATION_ID=${EI}`);let d=this._getEnterpriseHost();d&&(l.COPILOT_GH_HOST=d,this._logService.info(`[Copilot] Set CLI env: COPILOT_GH_HOST=${d}`)),this._isRubberDuckEnabled()?l.RUBBER_DUCK_AGENT="true":delete l.RUBBER_DUCK_AGENT;let c=Nt.asFileUri(Lu()),u=await U0(c);l.MXC_BIN_DIR=v.joinPath(c,"@microsoft","mxc-sdk","bin").fsPath;let p=await nd(),g=te(p),h=Object.keys(l).find(T=>T.toUpperCase()==="PATH")??"PATH",y=l[h];l[h]=y?`${y}${Aa}${g}`:g,this._logService.info(`[Copilot] Resolved CLI path: ${u}`);let I=await this._otelService.getSdkTelemetryConfig(),S=this._resolveCopilotSdkLogLevel(r),C={useLoggedInUser:!1,connection:P6.forStdio({path:u}),env:l,telemetry:I,logLevel:S,enableRemoteSessions:e,onGitHubTelemetry:T=>this._routeGitHubTelemetry(T)},_=this._createCopilotClient(C);if(await _.start(),this._shutdownPromise)throw await _.stop(),new K;if(this._isSessionSyncEnabled()!==e||this._isRubberDuckEnabled()!==t||this._getCopilotSdkLogLevelSetting()!==r||this._getEnterpriseHost()!==i||this._isSystemProxyEnabled()!==s)throw await _.stop(),new Error("Copilot startup config changed while the client was starting");return this._logService.info("[Copilot] CopilotClient started successfully"),this._enablePlanModeOnClient(_),this._client=_,this._clientStarting=void 0,_})();return this._clientStarting=a,a.catch(()=>{this._clientStarting=void 0}),a}_createThinkingLevelConfigSchemaProperty(e,t){if(e?.length)return{type:"string",title:f(2270,null),description:f(2269,null),default:t,enum:[...e],enumLabels:e.map(ta),enumDescriptions:e.map(r=>na(r)??"")}}_createContextSizeConfigSchemaProperty(e){let t=e?.tokenPrices,r=t?.contextMax,i=t?.longContext?.contextMax;if(!(!r||!i||r>=i))return this._isPreferLongContextEnabled()&&!fb(e)?{type:"number",title:f(2268,null),description:f(2266,null),default:i,enum:[i],enumLabels:[Th(i)],enumDescriptions:[f(2267,null)]}:{type:"number",title:f(2268,null),description:f(2266,null),default:r,enum:[r,i],enumLabels:[Th(r),Th(i)],enumDescriptions:[f(2265,null),f(2267,null)]}}_longContextWindowFor(e){if(!e)return;let r=this._models.get().find(i=>i.id===e)?.configSchema?.properties?.[ey]?.enum?.filter(i=>typeof i=="number");return r&&r.length>0?Math.max(...r):void 0}_isFreeLongContext(e){return!!e&&this._freeLongContextModels.has(e)}_createModelPickerMeta(e,t){return vd(t,e.modelPickerPriceCategory,e.modelPickerCategory)}_createModelConfigSchema(e,t){let r={},i=this._createThinkingLevelConfigSchemaProperty(e.supportedReasoningEfforts,e.defaultReasoningEffort);i&&(r[Eb]=i);let s=this._createContextSizeConfigSchemaProperty(t);if(s&&(r[ey]=s),Object.keys(r).length!==0)return{type:"object",properties:r}}_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 Lr(4),i=new Map,a=(await Promise.all(t.map(async l=>{let d=M.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 g=c.workingDirectory??(typeof l.context?.workingDirectory=="string"?v.file(l.context.workingDirectory):void 0);return{session:d,startTime:l.startTime.getTime(),modifiedTime:l.modifiedTime.getTime(),project:u,summary:l.summary,workingDirectory:g}}))).filter(l=>l!==void 0);return this._logService.info(`[Copilot] Found ${a.length} sessions`),a}async getSessionMetadata(e){let t=M.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 Lr(1);a=await this._resolveSessionProject(s?.context,d,new Map),this._storeSessionProjectResolution(e,a)}let l=r?.workingDirectory??(typeof s?.context?.workingDirectory=="string"?v.file(s.context.workingDirectory):void 0);return{session:e,startTime:s?.startTime.getTime()??Date.now(),modifiedTime:s?.modifiedTime.getTime()??Date.now(),project:a,summary:s?.summary,workingDirectory:l}}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=yd(a.billing),d=this._createModelConfigSchema(a,l),c=l?.tokenPrices,u=!!c?.contextMax&&!!c.longContext?.contextMax&&c.longContext.contextMax>c.contextMax;return i&&u&&!fb(l)&&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:d,policyState:a.policy?.state,_meta:this._createModelPickerMeta(a,l)}});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 dn.mkdir(l.fsPath,{recursive:!0}),l}let s=await dn.mkdtemp(V($0.tmpdir(),"agent-host-session-")),a=v.file(s);return this._logService.trace(`[Copilot] No workingDirectory provided, defaulting to temp directory: ${a.fsPath}`),a}_workspacelessScratchDir(e){return pb(this._environmentService.userHome,e)}async _ensureWorkspacelessScratchDir(e,t){try{await dn.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 dn.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=Le(e);if(!t)throw new Error(`Copilot chat operation requires an AHP chat URI: ${e.toString()}`);return{session:v.parse(t.session),chat:e}}_getChatContext(e){let t=Le(e)?e:v.parse(pe(e)),r=v.parse(ce(t)),i=M.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(M.id(e))?.getPeerChat(t.toString())}_ensureEntry(e){let t=this._sessions.get(e);return t||(t=new aa,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?M.id(t.session):F(),i=!t.fork&&!t.workingDirectory,s=await this._resolveCreateWorkingDirectory(t,r,i),a=await this._ensureClient();if(t.fork){let u=M.id(t.fork.session);return this._sessionSequencer.queue(u,async()=>{this._logService.info(`[Copilot] Forking session ${u} at turnId=${t.fork.turnId}`);let g=await(this._findAnySession(u)??await this._resumeSession(u)).getNextTurnEventId(t.fork.turnId),y=(await a.rpc.sessions.fork({sessionId:u,...g?{toEventId:g}:{}})).sessionId,I=this._sessionDataService.getSessionDataDirById(y),S=v.joinPath(I,sl);try{let w=await this._sessionDataService.tryOpenDatabase(t.fork.session);if(w)try{await dn.mkdir(I.fsPath,{recursive:!0}),await dn.rm(S.fsPath,{force:!0}),await w.object.vacuumInto(S.fsPath)}finally{w.dispose()}}catch(w){this._logService.warn(`[Copilot] Failed to copy session database for fork: ${w instanceof Error?w.message:String(w)}`)}let C=await this._resumeSession(y);t.fork.turnIdMapping&&await C.remapTurnIds(t.fork.turnIdMapping);let _=C.sessionUri;this._logService.info(`[Copilot] Forked session created: ${_.toString()}`);try{await this._reviewService.copyReviewedRef(t.fork.session.toString(),_.toString(),s)}catch(w){this._logService.warn(`[Copilot] Failed to copy reviewed ref for fork: ${w instanceof Error?w.message:String(w)}`)}let T=await fr({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=M.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 fr({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 fr({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}:{}}}async _importConversation(e,t,r){let i=e.importConversation,s=M.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=fr({cwd:r.fsPath},this._gitService),d=V(u1(this._environmentService.userHome.fsPath,process.env),"session-state",t,"events.jsonl"),c=p1(i.turns,{sessionId:t,workingDirectory:r.fsPath,model:a?.id});await dn.mkdir(te(d),{recursive:!0}),await dn.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=t??r.workingDirectory,l=a??r.workingDirectory,d=this._getOrCreateActiveClient(s,l);d.pluginController.reanchor(l);let c=await d.snapshot(),u=this._instantiationService.createInstance(jo,s,a),p,g;try{let y=await this._resolveAgentWhenMaterializing(r,c,a);g=y?.agent;let I={kind:"create",client:i,sessionId:e,workingDirectory:a,resolvedAgentName:y?.name,snapshot:c,activeClientToolSet:d.toolSet,shellManager:u,githubToken:this._githubToken,model:r.model,longContextWindow:this._longContextWindowFor(r.model?.id),freeLongContext:this._isFreeLongContext(r.model?.id),workspaceless:r.workspaceless};p=this._createAgentSession(I,l,d),await p.initializeSession(),this._registerInitializedSession(e,p)}catch(y){throw p?.dispose(),y}let h=await fr({cwd:a?.fsPath},this._gitService);return this._provisionalSessions.delete(e),await this._storeSessionMetadata(s,r.model,a,l,h,!0),g!==void 0&&await this._storeSessionAgentMetadata(s,g),this._checkpointService.captureBaseline(s,a).catch(y=>{this._logService.warn(`[Copilot:${e}] Baseline checkpoint capture failed: ${y instanceof Error?y.message:String(y)}`)}),this._logService.info(`[Copilot] Session materialized: ${s.toString()}`),this._onDidMaterializeSession.fire({session:s,workingDirectory:a,project:h}),p}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||gn(e.workingDirectory,t))return;let i=v.parse(r.uri),s=W0(i,e.workingDirectory,t);return s?{uri:s.toString()}:void 0}async resolveSessionConfig(e){let t=Pt.validateOrDefault(px(e.config),{autoApprove:"default",mode:"interactive"});return{schema:Pt.toProtocol(),values:t}}async sessionConfigCompletions(e){return{items:[]}}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=M.id(e);this._logService.info(`[Copilot:${r}] removeActiveClient: clientId=${t}`),this._activeClients.get(e)?.removeClient(t)}onClientToolCallComplete(e,t,r,i){let s=M.id(e);if(Re(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)}}async _sendMessage(e,t,r,i,s,a="unknown",l){let d=this._getChatContext(e);if(d.isPeerChat){let c=await this._ensureChatSession(d.session,e);if(!c)throw new Error(`[Copilot] sendMessage for unknown chat: ${e.toString()}`);i&&c.resetTurnState(i,s,a);let u=this._chatBackings.get(e.toString())?.sideChat,p=u?await c.getMessages():[],g=Ig(t,p,u);await c.send(g,r,i,this._resolveSdkMode(d.session),s,a);return}await this._sessionSequencer.queue(d.sessionId,async()=>{await this._activeClients.get(d.session)?.pluginController.retryFailedClientSyncIfNeeded();let c;this._provisionalSessions.has(d.sessionId)?c=await this._materializeProvisional(d.sessionId,l):c=this._getChatContext(e).target;let u=this._activeClients.get(d.session),p=!!c;this._logService.info(`[Copilot:${d.sessionId}] sendMessage: cachedEntry=${p}, hasActiveClient=${!!u}, activeClientId=${u?"(set)":"(none)"}`),c&&u&&await u.requiresRestart(c.appliedSnapshot)&&(this._logService.info(`[Copilot:${d.sessionId}] Session config changed (requiresRestart=true), refreshing session. clients=[${[...u.toolSet.clientIds()].join(", ")||"(none)"}]`),this._sdkSessionsById.delete(c.sessionId),await c.destroySession(),this._sessions.get(d.sessionId)?.clearDefaultChat(),c=void 0),c||this._logService.info(`[Copilot:${d.sessionId}] No cached entry${p?" (was evicted by requiresRestart)":""}, calling _resumeSession`),c??=await this._resumeSession(d.sessionId),i&&c.resetTurnState(i,s,a);try{let g=this._resolveSdkMode(d.session);await c.send(t,r,i,g,s,a)}catch(g){let h=g?.code,y=g instanceof Error?g.message:String(g);throw this._logService.error(`[Copilot:${d.sessionId}] entry.send() failed: code=${h}, message=${y}, hadCachedEntry=${p}, errorType=${g?.constructor?.name}`),g}})}_resolveSdkMode(e){let t=e.toString();switch(this._configurationService.getEffectiveValue(t,Pt,"mode")){case"plan":return"plan";case"autopilot":return"autopilot";case"interactive":return"interactive";default:return}}_getSessionConfigState(e){let t=M.uri(this.id,e).toString();return{mode:this._configurationService.getEffectiveValue(t,Pt,"mode"),autoApprove:this._configurationService.getEffectiveValue(t,Pt,"autoApprove")}}setPendingMessages(e,t,r){let i=this._getChatContext(e);if(!i.target){this._logService.warn(`[Copilot:${i.sessionId}] setPendingMessages: chat not found for ${e.toString()}`);return}t&&i.target.sendSteering(t)}async getSessionMessages(e){let t=It(e);if(t){let l=t.parentSession,d;for(;d=It(l);)l=d.parentSession;let c=M.id(l),u=this._findAnySession(c)??await this._resumeSession(c).catch(p=>{this._logService.warn(`[Copilot:${c}] Failed to resume root for subagent restore`,p)});return u?u.getSubagentMessages(t.toolCallId):[]}let r=Le(e)?e:v.parse(pe(e)),i=this._getChatContext(r);if(i.isPeerChat){let l=await this._ensureChatSession(i.session,r),d=l?await l.getMessages():[],c=this._chatBackings.get(r.toString())?.sideChat;return bg(d.slice(c?.inheritedTurnCount??0),c)}let s=i.sessionId;if(this._provisionalSessions.has(s))return[];let a=i.target??await this._resumeSession(s).catch(l=>{if(l instanceof Gl)throw l;this._logService.warn(`[Copilot:${s}] Failed to resume session for message lookup`,l)});return a?a.getMessages():[]}async getSubagentSessions(e){if(Le(e)&&!Re(e))return[];if(It(e))return[];let r=M.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=M.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=M.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 _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(Re(e))return;let r=Le(e);if(!r)throw new Error(`[Copilot] createChat: malformed chat URI ${e.toString()}`);let i=v.parse(r.session),s=e.toString();if(this._sessions.get(M.id(i))?.hasPeerChat(s)){let c=this._chatBackings.get(s);return c?{providerData:Br(c),backingSession:M.uri(this.id,c.sdkSessionId)}:void 0}let a=M.id(i),l,d=t?.sideChat?s:a;return await this._sessionSequencer.queue(d,async()=>{if(this._sessions.get(a)?.hasPeerChat(s)){let W=this._chatBackings.get(s);l=W?{providerData:Br(W),backingSession:M.uri(this.id,W.sdkSessionId)}:void 0;return}let c=t?.model,p=this._findAnySession(a)?.workingDirectory??this._provisionalSessions.get(a)?.workingDirectory,g=await this._ensureClient(),h=F(),y=this._getOrCreateActiveClient(i,p),I=await y.snapshot(),S=this._instantiationService.createInstance(jo,e,p),C,_,T;if(t?.fork){if(!p)throw new Error(`[Copilot] createChat fork: missing working directory for session ${i.toString()}`);let W=await this._resolveChatEntry(i,t.fork.source);if(!W)throw new Error(`[Copilot] createChat fork: source chat ${t.fork.source.toString()} not found`);_=(await this._forkSdkChat(g,W,t.fork.turnId,this._sessionDataService.getSessionDataDir(e))).sessionId,C={kind:"resume",client:g,sessionId:_,workingDirectory:p,resolvedAgentName:void 0,snapshot:I,activeClientToolSet:y.toolSet,shellManager:S,githubToken:this._githubToken,fallback:{model:c,longContextWindow:this._longContextWindowFor(c?.id),freeLongContext:this._isFreeLongContext(c?.id)}}}else if(t?.sideChat){if(!p)throw new Error(`[Copilot] createChat side chat: missing working directory for session ${i.toString()}`);let W=await this._resolveChatEntry(i,t.sideChat.source);if(!W)throw new Error(`[Copilot] createChat side chat: source chat ${t.sideChat.source.toString()} not found`);let R=await this._forkSdkChat(g,W,t.sideChat.providerAnchorTurnId??t.sideChat.turnId,this._sessionDataService.getSessionDataDir(e));_=R.sessionId,T={source:t.sideChat.source.toString(),turnId:t.sideChat.turnId,...t.sideChat.selection?{selection:t.sideChat.selection}:{},...t.sideChat.providerAnchorTurnId?{providerAnchorTurnId:t.sideChat.providerAnchorTurnId}:{},inheritedTurnCount:R.inheritedTurnCount,...t.sideChat.sourceContext?{context:t.sideChat.sourceContext}:{},...t.sideChat.partialResponse?{partialResponse:t.sideChat.partialResponse}:{}},C={kind:"resume",client:g,sessionId:_,workingDirectory:p,resolvedAgentName:void 0,snapshot:I,activeClientToolSet:y.toolSet,shellManager:S,githubToken:this._githubToken,fallback:{model:c,longContextWindow:this._longContextWindowFor(c?.id),freeLongContext:this._isFreeLongContext(c?.id)}}}else _=h,C={kind:"create",client:g,sessionId:h,workingDirectory:p,resolvedAgentName:void 0,snapshot:I,activeClientToolSet:y.toolSet,shellManager:S,githubToken:this._githubToken,model:c,longContextWindow:this._longContextWindowFor(c?.id),freeLongContext:this._isFreeLongContext(c?.id)};let w;try{w=this._createAgentSession(C,p,y,{sessionUri:i,chatChannelUri:e}),await w.initializeSession(),T&&(T={...T,inheritedTurnCount:(await w.getMessages()).length}),t?.fork?.turnIdMapping&&await w.remapTurnIds(t.fork.turnIdMapping),this._ensureEntry(a).registerPeerChat(s,new aa(w)),this._sdkSessionsById.set(w.sessionId,w);let W={sdkSessionId:_,...c?{model:c}:{},...T?{sideChat:T}:{}};this._chatBackings.set(s,W),l={providerData:Br(W),backingSession:M.uri(this.id,_)},this._logService.info(`[Copilot] Created additional chat ${s} in session ${i.toString()}${t?.fork?" (forked)":""}`)}catch(W){throw w?.dispose(),W}}),l}async _resolveChatEntry(e,t){let r=M.id(e);return Re(t)||gn(t,e)?this._findAnySession(r)??await this._resumeSession(r).catch(()=>{}):this._ensureChatSession(e,t)}async _forkSdkChat(e,t,r,i){let s=await t.getMessages(),a=s.findIndex(g=>g.id===r),l=a===-1?s.length:a+1,d=await t.getNextTurnEventId(r),u=(await e.rpc.sessions.fork({sessionId:t.sessionId,...d?{toEventId:d}:{}})).sessionId,p=v.joinPath(i,sl);try{let g=await this._sessionDataService.tryOpenDatabase(t.sessionUri);if(g)try{await dn.mkdir(i.fsPath,{recursive:!0}),await dn.rm(p.fsPath,{force:!0}),await g.object.vacuumInto(p.fsPath)}finally{g.dispose()}}catch(g){this._logService.warn(`[Copilot] Failed to copy session database for chat fork: ${g instanceof Error?g.message:String(g)}`)}return{sessionId:u,inheritedTurnCount:l}}async _disposeChat(e,t){if(Re(t))return;let r=t.toString(),i=this._findPeerChat(e,t)?.sessionId??this._chatBackings.get(r)?.sdkSessionId;if(!i){let s=Le(t);s&&(i=(await this._readPersistedChats(e)).get(s.chatId)?.sdkSessionId)}if(this._chatBackings.delete(r),i&&this._sdkSessionsById.delete(i),this._sessions.get(M.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(Re(e))return;let r=Le(e);if(!r)return;let i=e.toString(),s;if(t!==void 0){if(s=_g(t),!s){this._logService.warn(`[Copilot] materializeChat: dropping corrupt providerData for ${i}`);return}}else if(s=(await this._readPersistedChats(v.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:v.parse(fi(e,i)),providerData:Br(s)});return r}async _resolveChatBacking(e,t){let r=t.toString(),i=this._chatBackings.get(r);if(i)return i;let s=Le(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(!Le(t))return;let a=M.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(),g=this._getOrCreateActiveClient(e,u),h=await g.snapshot(),y=this._instantiationService.createInstance(jo,t,u),I={kind:"resume",client:p,sessionId:d.sdkSessionId,workingDirectory:u,resolvedAgentName:void 0,snapshot:h,activeClientToolSet:g.toolSet,shellManager:y,githubToken:this._githubToken,fallback:{model:d.model,longContextWindow:this._longContextWindowFor(d.model?.id),freeLongContext:this._isFreeLongContext(d.model?.id)}},S;try{return S=this._createAgentSession(I,u,g,{sessionUri:e,chatChannelUri:t}),await S.initializeSession(),this._ensureEntry(a).registerPeerChat(r,new aa(S)),this._sdkSessionsById.set(S.sessionId,S),this._logService.info(`[Copilot] Resumed additional chat ${r} in session ${e.toString()}`),S}catch(C){S?.dispose(),this._logService.warn(`[Copilot] Failed to resume additional chat ${r}: ${C instanceof Error?C.message:String(C)}`);return}})}async truncateSession(e,t,r){let i=M.id(e);if(this._provisionalSessions.has(i))return;let s=!Re(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,ty(t,this._configurationService,this._logService,s.sessionId),ny(t,r,i));let d=this._chatBackings.get(s.chatKey);if(d){let c={...d,model:t};this._chatBackings.set(s.chatKey,c),this._onDidChangeChatData.fire({chat:e,providerData:Br(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,ty(t,this._configurationService,this._logService,s.sessionId),ny(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._modelCatalogGeneration++,this._modelRefreshSchedule.clear(),this._scheduledModelRefresh?.deferred.complete(),this._scheduledModelRefresh=void 0,this._modelRefreshRetry.clear(),this._logService.info("[Copilot] Shutting down...");let e=new Set([...this._sessions.keys()]);for(let t of e)await this._sessionSequencer.queue(t,()=>this._destroyAndDisposeSession(t));await this._stopClient()})(),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=M.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 O6)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(!this._isSystemProxyEnabled())return;if(M6.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||N0;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{}await this._requestClientRestart(`CAPI proxy changed after token update (${e??"(none)"} -> ${t??"(none)"})`)}}_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=Le(v.parse(r));i&&M.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(e,t);r=this._instantiationService.createInstance(Ip,e,i,this._onDidSessionProgress),this._activeClients.set(e,r)}return r}_createAgentSession(e,t,r,i){let s=i?.sessionUri??M.uri(this.id,e.sessionId),a=i?.chatChannelUri??v.parse(pe(s)),l=this._instantiationService.createInstance(Ed,{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=>vh(r.pluginController.getCustomizations(),d),serverToolHost:this._serverToolHost,isLaunchTokenCurrent:()=>this._githubToken===e.githubToken,onTurnEnded:()=>this._onChatTurnEnded()});return this._mcpNotificationSubs.set(e.sessionId,jp(l.onMcpNotification(d=>this._onMcpNotification.fire(d)),En(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 aa,this._sessions.set(e,i)),i.setDefaultChat(r,new aa(t)),this._sdkSessionsById.set(t.sessionId,t)}async _destroyAndDisposeSession(e){await this._releaseSessionResources(e)}async _releaseSessionResources(e){for(let s of this._sessions.get(e)?.allChatSessions()??[])this._sdkSessionsById.delete(s.sessionId);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=M.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),await this._applyPendingClientRestart()}_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=M.uri(this.id,e),i=await this._readSessionMetadata(r),s=await t.getSessionMetadata(e).catch(I=>{this._logService.warn(`[Copilot:${e}] getSessionMetadata failed`,I)}),a=i.workingDirectory??(typeof s?.context?.workingDirectory=="string"?v.file(s.context.workingDirectory):void 0);if(!a)throw new Error(`workingDirectory is required to resume Copilot session '${e}'`);let l=a;i.workspaceless?await this._ensureWorkspacelessScratchDir(a,e):l=await this._configurationService.resolveWorkingDirectoryForResume(r.toString(),a);let d=l,c=this._getOrCreateActiveClient(r,d);c.pluginController.reanchor(d);let u=await c.snapshot(),p=this._instantiationService.createInstance(jo,r,l),g=i.agent?this._resolveAgentName(u,i.agent):void 0;i.agent&&!g&&this._logService.info(`[Copilot:${e}] Stored custom agent is not available in the current plugin snapshot; resuming without a custom agent`);let h={kind:"resume",client:t,sessionId:e,workingDirectory:l,resolvedAgentName:g,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(h,d,c);try{await y.initializeSession(),this._registerInitializedSession(e,y)}catch(I){throw y.dispose(),I}return y}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_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(it._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 _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(it._META_MODEL,this._serializeModelSelection(t))),r&&c.push(d.setMetadata(it._META_CWD,r.toString())),i&&c.push(d.setMetadata(it._META_CUSTOMIZATION_DIRECTORY,i.toString())),a&&c.push(d.setMetadata(it._META_PROJECT_RESOLVED,"true")),s&&(c.push(d.setMetadata(it._META_PROJECT_URI,s.uri.toString())),c.push(d.setMetadata(it._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(it._META_MODEL),t.object.getMetadata(it._META_AGENT),t.object.getMetadata(it._META_CWD),t.object.getMetadata(it._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(rr)]);return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(i),workingDirectory:s?v.parse(s):void 0,customizationDirectory:a?v.parse(a):void 0,workspaceless:l==="true"}}finally{t.dispose()}}async _readStoredSessionMetadata(e){let t=await this._sessionDataService.tryOpenDatabase(e);if(t)try{let[r,i,s,a,l,d,c,u]=await Promise.all([t.object.getMetadata(it._META_MODEL),t.object.getMetadata(it._META_AGENT),t.object.getMetadata(it._META_CWD),t.object.getMetadata(it._META_CUSTOMIZATION_DIRECTORY),t.object.getMetadata(it._META_PROJECT_RESOLVED),t.object.getMetadata(it._META_PROJECT_URI),t.object.getMetadata(it._META_PROJECT_DISPLAY_NAME),t.object.getMetadata(rr)]),p=s?v.parse(s):void 0,g=d&&c?{uri:v.parse(d),displayName:c}:void 0;return{model:this._parseModelSelection(r),agent:this._parseAgentSelection(i),workingDirectory:p,customizationDirectory:a?v.parse(a):void 0,project:g,resolved:l==="true"||g!==void 0,workspaceless:u==="true"}}finally{t.dispose()}}async _storeSessionAgentMetadata(e,t){let r=this._sessionDataService.openDatabase(e);try{await r.object.setMetadata(it._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(()=>fr(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())}};it=A([b(0,O),b(1,we),b(2,nt),b(3,$e),b(4,Ue),b(5,Ce),b(6,wt),b(7,Mh),b(8,Rm),b(9,Kr),b(10,Ql),b(11,St),b(12,qi),b(13,Pn),b(14,gt),b(15,Wi)],it);var H0=100,vp=class extends x{constructor(e,t,r,i,s,a,l,d){super();this._getClient=r;this._onDidRefresh=i;this._fileService=s;this._configurationService=a;this._logService=l;this._refreshDelayer=this._register(new gs(H0));this._refreshPromise=null;this._pendingRefreshNotify=!1;this._customizations=[];this._discovery=this._register(d.createInstance(Ld,e,t,v.file)),this._settled=this._queueRefresh(!1,0),this._register(this._discovery.onDidChange(()=>{this._settled=this._queueRefresh(!0)})),this._register(this._configurationService.onDidRootConfigChange(()=>{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=H0){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=li(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{if((this._configurationService.getRootValue(Dn,"sessionCustomizationDiscoveryMode")??mC)==="discover"){let s=await this._discovery.discover(await this._getClient(),e);return e.isCancellationRequested||Oe(this._customizations,s)?!1:(this._customizations=s,this._directories=void 0,!0)}let r=await this._discovery.scan(e);if(e.isCancellationRequested||this._directories&&L0(this._directories,r))return!1;let i=await U6(r,this._fileService);return e.isCancellationRequested?!1:(this._customizations=i,this._directories=r,!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}}};vp=A([b(4,xe),b(5,Ue),b(6,O),b(7,we)],vp);function U6(o,n){return Promise.all(o.map(async e=>{let t=e.uri.toString();return{type:"directory",id:et(t),uri:t,name:e.name,enabled:!0,contents:F6(e.type),writable:e.writable,load:{kind:"loaded"},children:await Promise.all(e.files.map(r=>H6(r.uri,e.type,n)))}}))}function F6(o){switch(o){case"agent":return"agent";case"skill":return"skill";case"instruction":case"agentInstruction":return"rule";case"hook":return"hook"}}async function H6(o,n,e){let t=o.toString(),r=et(t);if(n==="agent"){let i=await op(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 kh(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:Se(o)}:{type:"rule",alwaysApply:!0,id:r,uri:t,name:Se(o)}}function $6(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:v.parse(i.uri),name:i.name,description:i.description,customization:i});continue}if(i.type==="skill"){e.push({uri:v.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:v.parse(i.uri),name:i.name,description:i.description,customization:i})}}if(!(n.length===0&&e.length===0&&t.length===0))return{format:0,hooks:[],mcpServers:[],skills:e,agents:n,instructions:t}}var Sp=class extends x{constructor(e,t,r,i,s,a,l){super();this._getClient=e;this.pluginManager=t;this._logService=r;this._fileService=i;this._configurationService=s;this._instantiationService=a;this._environmentService=l;this._onDidChange=this._register(new E);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)}get configurationService(){return this._configurationService}hostCustomizations(){return this._hostCustomizations}hostSync(){return this._hostSync}getUserHome(){return this._environmentService.userHome}async getClient(){return this._getClient()}createSessionController(e,t){return this._instantiationService.createInstance(Cp,this,e,t)}_applyHostCustomizations(){let t=(this._configurationService.getRootValue(Dn,"customizations")??[]).map(IA);if(Oe(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=v.parse(e.uri),r=await this.tryParsePlugin(t);return r?{customization:{...e,load:{kind:"loaded"},children:_b([r])},pluginDir:t,plugin:r}:{customization:{...e,load:{kind:"error",message:f(2272,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:_b([s])},pluginDir:e.pluginDir,plugin:s,input:r}:{customization:{...i,load:{kind:"error",message:f(2272,null)}},input:r}}async tryParsePlugin(e){try{return await md(e,this._fileService,void 0,this.getUserHome(),e)}catch(t){this._logService.warn(`[Copilot:PluginController] Error parsing plugin '${e.toString()}': ${t instanceof Error?t.message:String(t)}`);return}}};Sp=A([b(1,$i),b(2,O),b(3,xe),b(4,Ue),b(5,we),b(6,St)],Sp);var Cp=class extends x{constructor(e,t,r,i,s,a){super();this._parent=e;this._session=t;this._directory=r;this._stateManager=i;this._logService=s;this._instantiationService=a;this._onDidPublish=this._register(new E);this.onDidPublish=this._onDidPublish.event;this._previousDirectories=[];this._desiredCustomizationById=new Map;this.mcpServerStates=yn(this,new Map);this._clients=new Map;this._sessionDiscovered=this._register(new ht)}get directory(){return this._directory}setDirectory(e){this._directory||!e||(this._directory=e)}reanchor(e){if(this._directory&&gn(this._directory,e))return;let t=this._directory;this._directory=e,this._sessionDiscovered.clear(),t&&!this._previousDirectories.some(r=>gn(r,t))&&this._previousDirectories.push(t)}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._logService.warn("[Copilot:SessionPluginController] Host customization update failed",t)),...[...this._clients.values()].map(t=>t.sync.catch(r=>this._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._logService.warn("[Copilot:SessionPluginController] Host customization update failed",a),this._parent.hostCustomizations())),...[...this._clients.values()].map(a=>a.sync.catch(l=>(this._logService.warn("[Copilot:SessionPluginController] Client customization sync failed",l),a.customizations))),e?.whenSettled()]),r=e?.currentCustomizations()??[],i=r.some(a=>this._isEnabled(a))?$6(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]}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(Oe(s.inputs,t))return s.sync.then(p=>p.map(g=>({customization:this._projectForPublish(g.customization),...g.pluginDir?{pluginDir:g.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 g=this._projectForPublish(p.customization);l.set(g.uri,g)}let d=p=>{let g=this._projectForPublish(p.customization);Oe(l.get(g.uri),g)||(l.set(g.uri,g),i||this._onDidPublish.fire({type:"session/customizationUpdated",customization:g}))},c=s.sync;return(s.sync=c.catch(p=>{this._logService.warn("[Copilot:SessionPluginController] Previous customization sync failed",p)}).then(async()=>{let p=new Map(t.map(y=>[y.uri,y])),g=await this._parent.pluginManager.syncCustomizations(e,t,y=>{a===s.revision&&d({customization:{...y,clientId:e},input:p.get(y.uri)})}),h=await Promise.all(g.map(y=>this._parent.resolveSyncedCustomization(y,e,p.get(y.customization.uri))));if(a===s.revision){s.customizations=h;for(let y of h)d(y)}return h})).then(p=>p.map(g=>({customization:this._overlayMcpState(this._applyEnablement(g.customization)),...g.pluginDir?{pluginDir:g.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._logService.info(`[Copilot:SessionPluginController] Retrying ${i.length} previously-failed client customization(s) for ${e}`),await this.sync(e,i).catch(s=>{this._logService.warn("[Copilot:SessionPluginController] Retried client customization sync failed",s)})}}_discoveredEntry(){if(this._directory)return this._sessionDiscovered.value||(this._sessionDiscovered.value=this._instantiationService.createInstance(vp,this._directory,this._parent.getUserHome(),()=>this._parent.getClient(),()=>this._onDidPublish.fire({type:"session/customizationsChanged",customizations:[...this.getCustomizations()]}))),this._sessionDiscovered.value}_isEnabled(e){return this._desiredEnabled(e)??e.enabled!==!1}_applyEnablement(e){let t=this._isEnabled(e);if(e.type==="mcpServer")return e.enabled===t?e:{...e,enabled:t};let r=e.enabled!==t,i=e.children?.map(s=>{let a=this._desiredEnabled(s);return a===void 0||a===s.enabled?s:(r=!0,{...s,enabled:a})});return r?{...e,enabled:t,children:i}:e}_desiredEnabled(e){let t=this._getDesiredCustomization(e.id);if(t)return t.enabled;if(this._directory)for(let r of this._previousDirectories){let i=W0(v.parse(e.uri),this._directory,r);if(!i)continue;let s=et(i.toString(),e.range),a=this._getDesiredCustomization(s);if(a)return a.enabled}}_getDesiredCustomization(e){let t=this._stateManager.getSessionState(this._session.toString())?.customizations;if(t!==this._indexedDesiredCustomizations){this._indexedDesiredCustomizations=t,this._desiredCustomizationById.clear();for(let r of t??[])if(this._desiredCustomizationById.set(r.id,r),r.type!=="mcpServer")for(let i of r.children??[])this._desiredCustomizationById.set(i.id,i)}return this._desiredCustomizationById.get(e)}_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}};Cp=A([b(3,Ce),b(4,O),b(5,we)],Cp);var Bb=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(()=>{})}},Ip=class extends x{constructor(e,t,r,i){super();this._sessionUri=e;this._configurationService=i;this.toolSet=new Mn;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 Bb(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(tt,mi)??{};return structuredClone(e)}async requiresRestart(e){let t=await this.pluginController.getAppliedPlugins();return!e0(e.plugins,t)||!Oe(e.mcpServers,this._getMcpServers())?!0:!this.toolSet.structuralEquals(e.tools)}};Ip=A([b(3,Ue)],Ip);function Ji(o){switch(o){case"default":case"acceptEdits":case"bypassPermissions":case"plan":case"auto":return o;default:return}}var q0="thinkingLevel";function bp(o){let n=o?.config?.[q0];switch(n){case"low":case"medium":case"high":case"xhigh":case"max":return n;default:return}}var W6=["low","medium","high","xhigh","max"];function zb(o){return W6.includes(o)}function Vb(o){if(o.length===0)return;let n=o.includes("high")?"high":void 0;return{type:"object",properties:{[q0]:{type:"string",title:f(1971,null),description:f(1970,null),enum:[...o],enumLabels:o.map(ta),enumDescriptions:o.map(e=>na(e)??""),...n!==void 0?{default:n}:{}}}}}import{pathToFileURL as K0}from"url";import*as V0 from"fs";import*as j0 from"tar";import{familySync as q6,MUSL as B6}from"detect-libc";var fy,B0=!1;function z0(){return B0||(Fe?fy=q6()===B6?"musl":"glibc":fy=void 0,B0=!0),fy}var z6=new Set(["linux","darwin","win32"]),V6=new Set(["x64","arm64"]);function jb(o,n={platform:process.platform,arch:process.arch,libc:z0()}){if(!(!z6.has(n.platform)||!V6.has(n.arch)))return n.platform==="linux"&&o.hasSeparateMuslLinuxPackage&&n.libc==="musl"?`linux-${n.arch}-musl`:`${n.platform}-${n.arch}`}var Ud=B("agentSdkDownloader"),j6=3e4,K6=250;function G6(o){if(typeof o!="string"||!/^\d+$/.test(o))return;let n=parseInt(o,10);return n>0?n:void 0}var Nd=class extends x{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 E);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]&&jb(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=jb(e);if(!r)return!1;let i=v.joinPath(v.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()+j6}),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=jb(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=pw(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=v.joinPath(v.file(l),".complete");if(await this._fileService.exists(d))return l;let c=this._pendingDownloads.get(l);return c||(c=this._download(e,s,l,d,t).finally(()=>{this._pendingDownloads.delete(l)}),this._pendingDownloads.set(l,c)),c}_cacheDir(e,t,r){return V(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=te(r);await this._fileService.createFolder(v.file(l));let d=`${r}.tmp.${process.pid}`,c=v.file(d);await this._delIgnoringMissing(c),await this._fileService.createFolder(c);let u=F(),p=0,g;this._fireProgress(e,u,"started",0,void 0);try{let h=V(d,"sdk.tgz");await this._fetch(t,h,s,(I,S)=>{p=I,g=S,this._fireProgress(e,u,"progress",I,S)}),await this._extractTarGz(h,d),await this._fileService.del(v.file(h)),await this._fileService.writeFile(v.joinPath(c,".complete"),$.fromString(""));try{await this._fileService.move(c,v.file(r))}catch(I){if(await this._handleRenameLoser(I,i,c))return this._logService.info(`[AgentSdkDownloader] ${e.id}: lost rename race, using existing cache`),this._fireProgress(e,u,"completed",p,g),r;throw I}let y=Math.round((Date.now()-a)/1e3);return this._logService.info(`[AgentSdkDownloader] ${e.id}: downloaded in ${y}s`),this._fireProgress(e,u,"completed",g??p,g),r}catch(h){if(await this._delIgnoringMissing(c),s.isCancellationRequested)throw this._fireProgress(e,u,"failed",p,g,"cancelled"),new K;let y=h instanceof Error?h.message:String(h);throw this._fireProgress(e,u,"failed",p,g,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 vt)||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=G6(s.res.headers["content-length"]);await new Promise((d,c)=>{let u=V0.createWriteStream(t),p=!1,g=0,h=0,y=_=>{if(!i)return;let T=Date.now();!_&&T-h<K6||(h=T,i(g,l))},I=()=>{p||(p=!0,C.dispose(),d())},S=_=>{p||(p=!0,C.dispose(),s.stream.destroy(),u.destroy(),c(_))},C=r.onCancellationRequested(()=>S(new K));u.on("error",S),u.on("finish",I),u.on("drain",()=>s.stream.resume()),s.stream.on("data",_=>{g+=_.byteLength,y(!1),u.write(_.buffer)||s.stream.pause()}),s.stream.on("end",()=>{y(!0),u.end()}),s.stream.on("error",S)})}async _extractTarGz(e,t){await j0.x({file:e,cwd:t})}async _delIgnoringMissing(e){try{await this._fileService.del(e,{recursive:!0})}catch(t){if(Vt(t)!==1)throw t}}};Nd=A([b(0,St),b(1,Tt),b(2,Ri),b(3,xe),b(4,O)],Nd);var Fd={id:"claude",displayName:"Claude",devOverrideEnvVar:Nf,hasSeparateMuslLinuxPackage:!0},$d=B("claudeAgentSdkService"),Hd=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[Nf]||!this._downloader.isAvailable(Fd)?!0:this._downloader.isSdkResolvableWithoutDownload(Fd)}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[Nf];if(n){let e=V(n,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(K0(e).href)}if(this._downloader.isAvailable(Fd)){let e=await this._downloader.loadSdkRoot(Fd,ke.None),t=V(e,"node_modules","@anthropic-ai","claude-agent-sdk","sdk.mjs");return import(K0(t).href)}return import("@anthropic-ai/claude-agent-sdk")}};Hd=A([b(0,O),b(1,Ud)],Hd);import{tmpdir as t3}from"os";import{z as Gt}from"zod";function my(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=gy(r)}catch{i=Gt.any()}n.has(t)||(i=i.optional()),e[t]=i}return e}function gy(o){if(!o||typeof o!="object")return Gt.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=Gt.any():e.length===1?n=Gt.literal(e[0]):n=Gt.union(e.map(t=>Gt.literal(t)))}else if(Array.isArray(o.oneOf)&&o.oneOf.length>0)n=G0(o.oneOf);else if(Array.isArray(o.anyOf)&&o.anyOf.length>0)n=G0(o.anyOf);else switch(Array.isArray(o.type)?o.type[0]:o.type){case"string":n=Gt.string();break;case"number":n=Gt.number();break;case"integer":n=Gt.number().int();break;case"boolean":n=Gt.boolean();break;case"array":n=Gt.array(o.items?gy(o.items):Gt.any());break;case"object":{let t={},r=new Set(o.required??[]);for(let[i,s]of Object.entries(o.properties??{})){let a;try{a=gy(s)}catch{a=Gt.any()}r.has(i)||(a=a.optional()),t[i]=a}n=Gt.object(t);break}case"null":n=Gt.null();break;default:n=Gt.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 G0(o){let n=o.map(e=>{try{return gy(e)}catch{return Gt.any()}});return n.length===1?n[0]:Gt.union(n)}var Wd="host";function J0(o){return o.map(n=>`mcp__${Wd}__${n}`)}async function Y0(o,n,e){let t=await Promise.all(o.definitions.map(r=>e.tool(r.name,r.description??"",my(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:Wd,tools:t})}var Q0="claudecode/toolUseId";async function X0(o,n,e){let t=await Promise.all(o.map(r=>e.tool(r.name,r.description??"",my(r.inputSchema),async(i,s)=>{let a=J6(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["${Q0}"]).`}],isError:!0}:n(a)})));return e.createSdkMcpServer({name:_p,tools:t})}function J6(o){if(!o||typeof o!="object")return;let n=o._meta;if(!n||typeof n!="object")return;let e=n[Q0];return typeof e=="string"?e:void 0}var _p="client";function qd(o){let n=`mcp__${_p}__`;return o.startsWith(n)?o.slice(n.length):o}function Z0(o){return o.startsWith(`mcp__${_p}__`)}var Y6=new Map([["opus",new Set(["1m"])]]),Kb=new Map;function Rp(o){if(o!==void 0)return la(o)?.toSdkModelId()??o}function la(o){let n=o.toLowerCase();if(Kb.has(n))return Kb.get(n);let e=X6(n);return Kb.set(n,e),e}var Q6=/^(?<base>.*)-(?<date>\d{8})$/;function X6(o){let n="",e=o,t=Q6.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 wp(r.groups.name,r.groups.major,r.groups.minor,Tp(r.groups.mod,n));let i=e.match(/^claude-(?<major>\d+)-(?<minor>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(i?.groups)return wp(i.groups.name,i.groups.major,i.groups.minor,Tp(i.groups.mod,n));let s=e.match(/^claude-(?<name>\w+)-(?<major>\d+)\.(?<minor>\d+)(?:-(?<mod>.+))?$/);if(s?.groups)return wp(s.groups.name,s.groups.major,s.groups.minor,Tp(s.groups.mod,n));let a=e.match(/^claude-(?<name>\w+)-(?<major>\d+)(?:-(?<mod>.+))?$/);if(a?.groups)return wp(a.groups.name,a.groups.major,void 0,Tp(a.groups.mod,n));let l=e.match(/^claude-(?<major>\d+)-(?<name>\w+)(?:-(?<mod>.+))?$/);if(l?.groups)return wp(l.groups.name,l.groups.major,void 0,Tp(l.groups.mod,n));let d=e.match(/^(?<name>\w+)$/);if(d?.groups)return Z6(d.groups.name)}function Tp(o,n){return o&&n?`${o}-${n}`:o||n}function eD(o,n,e,t,r){let i=e!==void 0?`claude-${o}-${n}${t}${e}`:`claude-${o}-${n}`;return r?`${i}-${r}`:i}function Z6(o){return{name:o,version:"",modifiers:"",toSdkModelId:()=>o,toEndpointModelId:()=>o}}function wp(o,n,e,t){let r=e!==void 0?`${n}.${e}`:n,i=e3(o,t);return{name:o,version:r,modifiers:t,toSdkModelId:()=>eD(o,n,e,"-",i),toEndpointModelId:()=>eD(o,n,e,".",i)}}function e3(o,n){if(!n)return"";let e=Y6.get(o);if(!e)return"";if(e.has(n))return n;let t=n.split("-")[0];return e.has(t)?t:""}var n3=new Set([_p,Wd]);function tD(o){return n3.has(o)}async function Gb(o,n,e){let t=n.kind==="proxy",r=oD(t),i=await nd(),s={...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",[Vr]:jr,PATH:`${te(i)}${Aa}${process.env.PATH??""}`};return{cwd:o.workingDirectory.fsPath,executable:process.execPath,env:r,abortController:o.abortController,allowDangerouslySkipPermissions:!0,canUseTool:o.canUseTool,onElicitation:o.onElicitation,disallowedTools:["WebSearch"],includePartialMessages:!0,forwardSubagentText:!0,enableFileCheckpointing:!0,model:Rp(o.model?.id),effort:bp(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(a=>({type:"local",path:a.fsPath}))}:{},...o.agent?{agent:o.agent}:{},settingSources:["user","project","local"],settings:{env:s},systemPrompt:{type:"preset",preset:"claude_code"},stderr:e}}async function nD(o,n,e){let t=o.consume();return t.length===0?void 0:{client:await X0(t,i=>n.register(i),e)}}function rD(){return{cwd:t3(),executable:process.execPath,env:oD(!1),abortController:new AbortController,systemPrompt:{type:"preset",preset:"claude_code"},settings:{env:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}}}function oD(o=!0){let n=o?{ELECTRON_RUN_AS_NODE:"1",NODE_OPTIONS:void 0,ANTHROPIC_API_KEY:void 0,HOME:process.env.HOME,USERPROFILE:process.env.USERPROFILE}:{...process.env,ELECTRON_RUN_AS_NODE:"1",NODE_OPTIONS:void 0};n[Vr]=jr;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 Ap={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},Skill:{permissionKind:"skill"},TaskCreate:{permissionKind:"custom-tool"},TaskUpdate:{permissionKind:"custom-tool"},TaskList:{permissionKind:"custom-tool"},TaskGet:{permissionKind:"custom-tool"}},xp="mcp__";function hy(o){let n=Ap[o];return n?n.permissionKind:o.startsWith(xp)?"mcp":"custom-tool"}function On(o){let n=Rr(o,void 0)?.displayName;if(n!==void 0)return n;switch(o){case"Bash":return f(2096,null);case"BashOutput":return f(2097,null);case"KillBash":return f(2102,null);case"Read":return f(2108,null);case"Glob":return f(2100,null);case"Grep":return f(2101,null);case"LS":return f(2103,null);case"NotebookRead":return f(2107,null);case"Write":return f(2117,null);case"Edit":return f(2098,null);case"MultiEdit":return f(2105,null);case"NotebookEdit":return f(2106,null);case"TodoWrite":return f(2115,null);case"WebFetch":return f(2116,null);case"Task":case"Agent":return f(2110,null);case"ExitPlanMode":return f(2099,null);case"AskUserQuestion":return f(2095,null);case"Skill":return f(2109,null);case"TaskCreate":return f(2111,null);case"TaskUpdate":return f(2114,null);case"TaskList":return f(2113,null);case"TaskGet":return f(2112,null)}return o.startsWith(xp)?f(2104,null,o.slice(xp.length)):o}function io(o,n){let e=Ap[o];if(!e?.pathField||typeof n!="object"||n===null)return;let t=n[e.pathField];return typeof t=="string"?t:void 0}function iD(o){return Ap[o]?.isFileEdit===!0}var sD=new Set(Object.entries(Ap).filter(([,o])=>o.interactive).map(([o])=>o));function aD(o){switch(hy(o)){case"shell":return f(2091,null);case"write":return f(2094,null);case"read":return f(2090,null);case"url":return f(2093,null);case"skill":return f(2092,null);case"mcp":{let n=o.startsWith(xp)?o.slice(xp.length).split("__")[0]:void 0;return n?f(2089,null,n):f(2088,null)}default:return f(2088,null)}}function Ko(o){let n=Jb(o);return n?At(n):void 0}function Jb(o){let n=Ap[o];if(n?.toolKind)return{toolKind:n.toolKind}}function cn(o){return{markdown:o}}function Bd(o){let n=v.file(o);return`[${Xs(Se(n))}](${n})`}function Sn(o,n){if(o===null||typeof o!="object")return;let e=o[n];return typeof e=="string"&&e.length>0?e:void 0}function lD(o){let n=Sn(o,"command");return n?n.split(`
`)[0]:void 0}function dD(o){let n=Sn(o,"status");return n==="in_progress"||n==="completed"||n==="deleted"?n:void 0}function Go(o,n,e){let t=Rr(o,e)?.invocationMessage;if(t!==void 0)return t;switch(o){case"Bash":{let r=lD(e);return r?cn(f(2148,null,ot(fn(r,80)))):f(2147,null)}case"BashOutput":return f(2149,null);case"KillBash":return f(2156,null);case"Read":case"NotebookRead":{let r=io(o,e);return r?cn(f(2160,null,Bd(r))):f(2159,null)}case"LS":{let r=io(o,e);return r?cn(f(2158,null,Bd(r))):f(2157,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let r=io(o,e);return r?cn(f(2151,null,Bd(r))):f(2150,null)}case"TodoWrite":return f(2171,null);case"Grep":{let r=Sn(e,"pattern");return r?cn(f(2155,null,ot(fn(r,80)))):f(2154,null)}case"Glob":{let r=Sn(e,"pattern");return r?cn(f(2153,null,ot(fn(r,80)))):f(2152,null)}case"WebFetch":{let r=Sn(e,"url");return r?cn(f(2172,null,`[${Xs(fn(r,80))}](${r})`)):f(2173,null)}case"Task":case"Agent":{let r=Sn(e,"description");return r||n}case"Skill":{let r=Sn(e,"skill");return r?cn(f(2162,null,ot(fn(r,80)))):f(2161,null)}case"TaskCreate":{let r=Sn(e,"subject");return r?f(2165,null,fn(r,80)):f(2164,null)}case"TaskUpdate":switch(dD(e)){case"in_progress":return f(2169,null);case"completed":return f(2163,null);case"deleted":return f(2166,null);default:return f(2170,null)}case"TaskList":return f(2168,null);case"TaskGet":return f(2167,null);default:return n}}function yy(o,n,e,t,r){if(!t)return f(2123,null,n);let i=Rr(o,e,{text:r,success:t})?.pastTenseMessage;if(i!==void 0)return i;switch(o){case"Bash":{let s=lD(e);return s?cn(f(2119,null,ot(fn(s,80)))):f(2118,null)}case"BashOutput":return f(2120,null);case"KillBash":return f(2128,null);case"Read":case"NotebookRead":{let s=io(o,e);return s?cn(f(2132,null,Bd(s))):f(2131,null)}case"LS":{let s=io(o,e);return s?cn(f(2130,null,Bd(s))):f(2129,null)}case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":{let s=io(o,e);return s?cn(f(2122,null,Bd(s))):f(2121,null)}case"TodoWrite":return f(2144,null);case"Grep":{let s=Sn(e,"pattern");return s?cn(f(2127,null,ot(fn(s,80)))):f(2126,null)}case"Glob":{let s=Sn(e,"pattern");return s?cn(f(2125,null,ot(fn(s,80)))):f(2124,null)}case"WebFetch":{let s=Sn(e,"url");return s?cn(f(2145,null,`[${Xs(fn(s,80))}](${s})`)):f(2146,null)}case"Task":case"Agent":return f(2135,null);case"Skill":{let s=Sn(e,"skill");return s?cn(f(2134,null,ot(fn(s,80)))):f(2133,null)}case"TaskCreate":{let s=Sn(e,"subject");return s?f(2138,null,fn(s,80)):f(2137,null)}case"TaskUpdate":switch(dD(e)){case"in_progress":return f(2142,null);case"completed":return f(2136,null);case"deleted":return f(2139,null);default:return f(2143,null)}case"TaskList":return f(2141,null);case"TaskGet":return f(2140,null);default:return n}}function Yi(o,n){if(n!==void 0){if(o==="Bash"||o==="BashOutput"||o==="KillBash"){let e=Sn(n,"command");if(e)return e}if(o==="Grep"||o==="Glob"){let e=Sn(n,"pattern");if(e)return e}try{return JSON.stringify(n,null,2)}catch{return}}}function zd(o,n,e){let t=new Yb(n,e);for(let r of o){let i=uD(r);i!==void 0&&t.consume(i)}return t.finish()}function vy(o,n){let e=!1,t;for(let r of o){let i=uD(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 uD(o){let n=r3(o);switch(o.type){case"user":return o3(o,n);case"assistant":return i3(o,n);case"system":return s3(o,n);default:return}}function r3(o){if(typeof o.timestamp!="string")return;let n=Date.parse(o.timestamp);return Number.isFinite(n)?new Date(n).toISOString():void 0}function o3(o,n){let e=l3(o.message);if(e===void 0||g3(e))return;if(typeof e=="string")return{kind:"user-text",uuid:o.uuid,text:e,timestamp:n};let t=e.filter(r=>r.type==="text");if(t.length===0){let r=e.filter(i=>i.type==="tool_result");return r.length>0?{kind:"user-tool-results",uuid:o.uuid,results:r,timestamp:n}:void 0}return{kind:"user-text",uuid:o.uuid,text:t.map(r=>r.text).join(`
`),timestamp:n}}function i3(o,n){let e=d3(o.message);if(!(e===void 0||e.length===0))return{kind:"assistant",uuid:o.uuid,blocks:e,isInner:o.parent_tool_use_id!==null,timestamp:n}}function s3(o,n){let e=c3(o.message);if(e===void 0||!a3.has(e))return;let t=u3(o.message)??`[${e}]`;return{kind:"system-notification",uuid:o.uuid,subtype:e,text:t,timestamp:n}}var a3=new Set(["compact_boundary","notification"]),cD=/^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>/,Yb=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,startedAt:n.timestamp,responseParts:[],pendingToolUseIds:new Set,toolCallParts:new Map};return;case"user-tool-results":{let e=!1;for(let t of n.results)e=this._attachToolResult(t)===this._active?.id||e;e&&this._active&&n.timestamp&&(this._active.lastResponseAt=n.timestamp);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}),n.timestamp&&(this._active.lastResponseAt=n.timestamp);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:"",startedAt:n.timestamp,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,qd(r.name),r.input);n.timestamp&&(this._active.lastResponseAt=n.timestamp)}_openToolUse(n,e,t){if(this._active===void 0)return;let r=On(e),i=t!==null&&typeof t=="object"?t:void 0,s=Ko(e),a={status:"cancelled",toolCallId:n,toolName:e,displayName:r,invocationMessage:Go(e,r,i),toolInput:i!==void 0?Yi(e,i):typeof t=="string"?t:t!==void 0?f3(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=An(s).toolKind==="subagent",l=p3(n.content)??[],d=l.filter(u=>u.type==="text").map(u=>u.text).join(`
`);a&&l.push({type:"subagent",resource:ja(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:yy(s.toolName,s.displayName,e.parsedInput,!i,d),content:l.length>0?l:void 0,...s._meta?{_meta:s._meta}:{}};return r.toolCall=c,this._active?.id===t&&this._active.pendingToolUseIds.delete(n.tool_use_id),t}_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=n.startedAt===void 0?void 0:Date.parse(n.startedAt),r=n.lastResponseAt===void 0?void 0:Date.parse(n.lastResponseAt),i=t!==void 0&&r!==void 0&&Number.isFinite(t)&&Number.isFinite(r)?Math.max(0,r-t):void 0,s={id:n.id,startedAt:n.startedAt,duration:i,message:{text:n.userText,origin:{kind:"user"}},responseParts:n.responseParts,usage:void 0,state:e};this._turns.push(s),this._active=void 0}};function l3(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 d3(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 c3(o){if(o===null||typeof o!="object")return;let n=o.subtype;return typeof n=="string"?n:void 0}function u3(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 p3(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 f3(o){try{return JSON.stringify(o)}catch{return}}function g3(o){if(typeof o=="string")return cD.test(o);let n=o.find(e=>e.type==="text");return n!==void 0&&cD.test(n.text)}var da=class{validateOrThrow(n){let e=this.validate(n);if(e.error)throw new Error(e.error.message);return e.content}},Vd=class extends da{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}}},m3=new Vd("string");function Xt(){return m3}var h3=new Vd("number");function so(){return h3}var bLe=new Vd("boolean");var y3=new Vd("object");function pD(){return y3}var Qb=class extends da{validate(n){return{content:n,error:void 0}}getJSONSchema(){return{}}};function v3(){return new Qb}function fD(){return v3()}var Pp=class{constructor(n){this.validator=n}};function $t(o){return new Pp(o)}var Xb=class extends da{constructor(e){super();this.properties=e}validate(e){if(typeof e!="object"||e===null)return{content:void 0,error:{message:"Expected object"}};let t={};for(let r in this.properties){let i=this.properties[r],s=e[r],a=i instanceof Pp,l=a?i.validator:i;if(a&&s===void 0)continue;let{content:d,error:c}=l.validate(s);if(c)return{content:void 0,error:{message:`Error in property '${r}': ${c.message}`}};t[r]=d}return{content:t,error:void 0}}getJSONSchema(){let e=[],t={};for(let[i,s]of Object.entries(this.properties)){let a=s instanceof Pp,l=a?s.validator:s;t[i]=l.getJSONSchema(),a||e.push(i)}return{type:"object",properties:t,...e.length>0?{required:e}:{}}}};function jd(o){return new Xb(o)}var Zb=class extends da{constructor(e){super();this.validator=e}validate(e){if(!Array.isArray(e))return{content:void 0,error:{message:"Expected array"}};let t=[];for(let r=0;r<e.length;r++){let{content:i,error:s}=this.validator.validate(e[r]);if(s)return{content:void 0,error:{message:`Error in element ${r}: ${s.message}`}};t.push(i)}return{content:t,error:void 0}}getJSONSchema(){return{type:"array",items:this.validator.getJSONSchema()}}};function Qi(o){return new Zb(o)}var e_=class extends da{constructor(e){super();this.value=e}validate(e){return e!==this.value?{content:void 0,error:{message:`Expected: ${this.value}`}}:{content:e,error:void 0}}getJSONSchema(){return{const:this.value}}};function gD(o){return new e_(o)}var Ep=new Set(["Task","Agent"]),S3=/^\s*agentId:\s+([a-z0-9]+)\b/im,t_=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)}},Sy=class extends x{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 t_(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),t?.prompt!==void 0&&r.prompt===void 0&&(r.prompt=t.prompt),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 n_(e))this.recordSpawn(t,{agentId:r})}_evictInnerEdgesFor(e){for(let[t,r]of this._innerToParent)r===e&&this._innerToParent.delete(t)}};function n_(o){let n=new Map;for(let e of o)for(let t of e.responseParts){let r=C3(t);r&&n.set(r.toolCallId,r.agentId)}return n}function C3(o){if(o.kind!=="toolCall")return;let n=o.toolCall;if(!Ep.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=S3.exec(r.text);if(i)return{toolCallId:n.toolCallId,agentId:i[1]}}}var r_=class{constructor(n,e){this._sdk=n;this._logService=e;this.name="text_suffix"}async lookup(n,e){let t=await mD(this._sdk,this._logService,e,"TextSuffix");if(t)return n_(t).get(n)}};async function mD(o,n,e,t){if(e.parentTranscript)return e.parentTranscript;try{let r=await o.getSessionMessages(e.parentSessionId,{includeSystemMessages:!0});return zd(r,e.parentUri,n)}catch(r){n.warn(`[claudeSubagentResolver] ${t}: parent transcript fetch failed: ${r}`);return}}function hD(o){let n=Xt().validate(o);return n.error?void 0:n.content}function o_(o){let n=pD().validate(o);if(!(n.error||n.content===null||Array.isArray(n.content)))return n.content}var i_=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=b3(s);if(a!==void 0&&a===t)return i}}async _loadParentPrompt(n,e){let t=await mD(this._sdk,this._logService,e,"PromptMatch");if(t)return I3(t,n)}};function I3(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(!Ep.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=o_(s);return a?hD(a.prompt):void 0}}function b3(o){for(let n of o){if(n.type!=="user")continue;let e=o_(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=o_(r);if(!i||i.type!=="text")continue;let s=hD(i.text);if(s!==void 0)return s}}}var s_=class{constructor(){this.name="native"}async lookup(){}};async function _3(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 T3(o,n){return[new r_(o,n),new i_(o,n),new s_]}async function yD(o,n,e,t,r){let i=It(o);if(!i)throw new Error(`getSubagentTranscript: not a subagent URI: ${o.toString()}`);let{parentSession:s,toolCallId:a}=i,l=M.id(s),d=await _3(a,{parentUri:s,parentSessionId:l,token:r},{strategies:T3(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 zd(c,o,t)}var w3="claude-client";function vD(o,n){let r={content:(o.content??[]).map((i,s)=>R3(i,n,s))};return o.structuredContent!==void 0&&(r.structuredContent=o.structuredContent),(!o.success||o.error)&&(r.isError=!0),r}function R3(o,n,e){switch(o.type){case"text":return{type:"text",text:o.text};case"embeddedResource":return x3(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 x3(o,n,e){return o.contentType.startsWith("image/")?{type:"image",data:o.data,mimeType:o.contentType}:{type:"resource",resource:{uri:`${w3}://${encodeURIComponent(n)}/${e}`,mimeType:o.contentType,blob:o.data}}}function Xi(o,n){return Ji(o.getSessionConfigValues(n.toString())?.permissionMode)}var a_=class{constructor(){this._toolSet=new Mn;this._merged=xs({owner:this,equalsFn:(n,e)=>Oh(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)}},Cy=class extends x{constructor(){super();this.model=new a_;this._dirty=!1;this._ignoreNextFire=!0;this._lastAppliedTools=[];this._register(En(e=>{let t=this.model.merged.read(e);if(this._ignoreNextFire){this._ignoreNextFire=!1,this._lastAppliedTools=t;return}Oh(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 A3={synced:[]},l_=class{constructor(){this._byClient=new Map;this._state=xs({owner:this,equalsFn:P3},A3);this.state=this._state}_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),this._state.set({synced:this._mergedSynced()},void 0)}removeClient(n){this._byClient.delete(n)&&this._state.set({synced:this._mergedSynced()},void 0)}},Iy=class extends x{constructor(){super();this.model=new l_;this._dirty=!1;this._appliedPluginPaths=[];this._ignoreNextFire=!0;this.onDidChange=ee.fromObservableLight(this.model.state);this._register(En(e=>{if(this.model.state.read(e),this._ignoreNextFire){this._ignoreNextFire=!1;return}this._dirty=!0}))}get hasDifference(){return this._dirty}hasDifferenceFrom(e){return this._dirty||!D3(this._appliedPluginPaths,e)}consume(e){return this._appliedPluginPaths=e,this._dirty=!1,e}markDirty(){this._dirty=!0}};function P3(o,n){return E3(o.synced,n.synced)}function E3(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||CD(t.load)!==CD(r.load)||!k3(t.children,r.children)||o[e].pluginDir?.toString()!==n[e].pluginDir?.toString())return!1}return!0}function CD(o){return o&&o.message?o.message:void 0}function k3(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 D3(o,n){return Nn(o,n,(e,t)=>e.toString()===t.toString())}function M3(o,n){let e=[];return o&&(e.push(v.joinPath(o,".claude","settings.json")),e.push(v.joinPath(o,".mcp.json"))),e.push(v.joinPath(n,".claude","settings.json")),e}function O3(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 ID(o,n,e){let t=new Set,r=[];for(let i of M3(o,n)){let s=await zo(i,e),a=O3(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(rp(i,l)))}return r.sort((i,s)=>i.name.localeCompare(s.name)),r}function d_(o){switch(o){case"connected":return{kind:"ready"};case"disabled":return{kind:"stopped"};default:return{kind:"starting"}}}function c_(o,n){let e=[v.joinPath(n,".claude","CLAUDE.md")];return o&&e.push(v.joinPath(o,"CLAUDE.md"),v.joinPath(o,".claude","CLAUDE.md"),v.joinPath(o,"CLAUDE.local.md")),e}var L3=32;async function bD(o,n,e=new Set,t=0){let r=o.toString();if(t>L3||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 bD(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 _D(o,n,e){let t=[];for(let i of c_(o,n))if(await ea(i,e)){let s=i.toString(),a=Se(i),l={type:"rule",id:et(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 bD(v.joinPath(i,".claude","rules"),e);for(let a of s){let l=await kh(a,e),d=a.toString(),c=!!l.globs?.length,u={type:"rule",id:et(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 TD="agent-builtin",N3=[{name:"init",description:()=>f(2177,null)},{name:"review",description:()=>f(2180,null)},{name:"security-review",description:()=>f(2182,null)},{name:"code-review",description:()=>f(2175,null)},{name:"simplify",description:()=>f(2183,null)},{name:"verify",description:()=>f(2185,null)},{name:"run",description:()=>f(2181,null)},{name:"loop",description:()=>f(2179,null)},{name:"claude-api",description:()=>f(2174,null)},{name:"fewer-permission-prompts",description:()=>f(2176,null)},{name:"update-config",description:()=>f(2184,null)},{name:"keybindings-help",description:()=>f(2178,null)},{name:"write-a-skill",description:()=>f(2186,null)}],wD=[{name:"claude",description:()=>f(2187,null)},{name:"claude-code-guide",description:()=>f(2188,null)},{name:"Explore",description:()=>f(2189,null)},{name:"general-purpose",description:()=>f(2190,null)},{name:"Plan",description:()=>f(2191,null)}];function RD(o){if(o.length===0)return;let n=o.map(t=>{let r=v.from({scheme:TD,path:`/skill/${encodeURIComponent(t.name)}`}).toString();return{type:"skill",id:et(r),uri:r,name:t.name,description:t.description}}),e=v.from({scheme:TD,path:"/skills"}).toString();return{type:"directory",id:et(e),uri:e,name:"builtin",enabled:!0,contents:"skill",writable:!1,load:{kind:"loaded"},children:n}}function xD(o){return RD(N3.filter(n=>!o.has(n.name)).map(n=>({name:n.name,description:n.description()})))}function AD(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 RD(t)}var u_="general-purpose",kD="claude-internal";function by(o,n,e,t){let r=v.joinPath(o,".claude",n).toString();return{type:"directory",id:et(r),uri:r,name:n,enabled:!0,contents:e,writable:!0,load:{kind:"loaded"},children:[...t]}}function U3(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:et(n),uri:n,name:o.id,enabled:!0,load:{kind:"loaded"},children:e}}function PD(o,n){return n&&o.scheme===n.scheme&&Or(o,n)?"workspace":"user"}function ED(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(PD(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(PD(v.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(by(c,"agents","agent",u.agents)),u.skills.length>0&&a.push(by(c,"skills","skill",u.skills)),u.rules.length>0&&a.push(by(c,"rules","rule",u.rules)),u.hooks.length>0&&a.push(by(c,"hooks","hook",u.hooks))}for(let d of t)a.push(U3(d));return a.push(...n),a}function p_(o,n){return v.from({scheme:kD,path:`/${o}/${encodeURIComponent(n)}`})}async function f_(o,n,e,t){if(!o)return;let r=v.parse(o.uri);if(r.scheme===kD){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 op(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 DD(o,n,e,t,r,i,s){let a=[],l=new Set,d=new Set,c=new Set;if(s)for(let w of t){let W=s.plugins.find(D=>D.source===w.id||v.file(D.path).fsPath===w.root.fsPath);if(!W)continue;a.push(w);let R=W.name,L=(D,z)=>{D.add(z),R&&D.add(`${R}:${z}`)};for(let D of w.parsed.agents)L(l,D.name);for(let D of w.parsed.skills)L(d,D.name);for(let D of w.parsed.mcpServers)L(c,D.name)}else a.push(...t);let u=new Set(o.filter(w=>w.customization.type==="skill").map(w=>w.name)),p=s?AD(s.commands.filter(w=>!d.has(w.name)),u):xD(u),g=w=>p?[...w,p]:w;if(!s){let w=new Set(o.filter(R=>R.customization.type==="agent").map(R=>R.name)),W=wD.filter(R=>R.name!==u_&&!w.has(R.name)).map(R=>hd({uri:p_("agent",R.name),name:R.name,description:R.description()}));return g(ED([...o,...W],n,e,t,r,i))}let h=new Set(s.agents.map(w=>w.name)),y=new Set(s.commands.map(w=>w.name)),I=new Map(s.mcpServers.map(w=>[w.name,w])),S=new Set,C=[];for(let w of o)if(w.customization.type==="agent"){if(w.name===u_)continue;h.has(w.name)&&(C.push(w),S.add(w.name))}else w.customization.type==="skill"?y.has(w.name)&&C.push(w):C.push(w);for(let w of s.agents)w.name===u_||S.has(w.name)||l.has(w.name)||C.push(hd({uri:p_("agent",w.name),name:w.name,...w.description?{description:w.description}:{}}));let _=new Set,T=[];for(let w of n){let W=I.get(w.name);W&&(_.add(w.name),T.push({...w,state:d_(W.status)}))}for(let[w,W]of I)_.has(w)||c.has(w)||tD(w)||T.push({...rp(p_("mcp",w),w),state:d_(W.status)});return g(ED(C,T,e,a,r,i))}var F3=Object.freeze(["agents","skills","commands","rules","plugins","CLAUDE.md","settings.json","settings.local.json"]),_y=class o extends x{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 F3)s.push(v.joinPath(c,u))};if(n){let c=v.joinPath(n,".claude");a(c,!0),l(c),a(n,!1),s.push(v.joinPath(n,".mcp.json"))}let d=v.joinPath(e,".claude");a(d,!0),l(d),s.push(...c_(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 H3(o){let n=v.joinPath(o,".claude");return{agents:v.joinPath(n,"agents"),skills:v.joinPath(n,"skills"),commands:v.joinPath(n,"commands")}}function g_(o,n){for(let e of n)o.has(e.name)||o.set(e.name,e)}async function $3(o,n){let e=await Promise.all(o.map(async t=>{let r=Ut(t.uri),i=await tp(r,n);return n.exists(v.joinPath(r,i.manifestPath))}));return o.filter((t,r)=>!e[r])}async function MD(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}=H3(s),[c,u,p]=await Promise.all([Eh([a],e),cb(l,[l],e),Eh([d],e)]);g_(r,c.map(hd));let g=await $3(u,e);g_(i,g.map(Dh)),g_(i,p.map(Dh))}return[...r.values(),...i.values()]}function W3(o,n){let e=[];return o&&(e.push(v.joinPath(o,".claude","settings.json")),e.push(v.joinPath(o,".claude","settings.local.json"))),e.push(v.joinPath(n,".claude","settings.json")),e}async function OD(o,n,e){let t=[],r=new pn;for(let i of W3(o,n)){if(r.has(i))continue;r.add(i);let s=await zo(i,e);if(s===void 0)continue;let a=Ph(i,s,o,n);a.length>0&&t.push(a[0].customization)}return t}var q3="skills-dir";function B3(o,n){let e=[v.joinPath(n,".claude","settings.json")];return o&&(e.push(v.joinPath(o,".claude","settings.json")),e.push(v.joinPath(o,".claude","settings.local.json"))),e}async function z3(o,n,e){let t=new Map,r=new pn;for(let i of B3(o,n)){if(r.has(i))continue;r.add(i);let s=await zo(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 V3(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 m_(o,n){let e=await tp(o,n);return n.exists(v.joinPath(o,e.manifestPath))}async function j3(o,n,e,t){let r=[];n&&r.push(v.joinPath(n,".claude","skills",o)),r.push(v.joinPath(e,".claude","skills",o));for(let i of r)if(await m_(i,t))return i}async function K3(o,n,e,t){let r=v.joinPath(e,".claude","plugins","cache",n,o);if(await m_(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 m_(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 LD(o,n,e,t){let r=await z3(o,n,e),i=[],s=new pn;for(let a of r){let l=V3(a);if(!l){t.warn(`[claudeNativePluginScan] skipping malformed plugin id '${a}'`);continue}let d=l.marketplace===q3?await j3(l.plugin,o,n,e):await K3(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 md(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 Ty(o,n){let e=[{type:"text",text:o}];if(!n?.length)return e;let t=[],r=[],i=[];for(let s of n){if(Hh(s)){let l=$h(s);l&&i.push(l);continue}if(s.type==="simple"){s.modelRepresentation&&r.push(s.modelRepresentation);continue}if(s.type!=="resource")continue;let a=v.parse(s.uri);if(s.displayKind==="selection"){let l=s.selection?`:${s.selection.range.start.line+1}`:"";t.push(`- ${ND(a)}${l}`)}else t.push(`- ${ND(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 ND(o){return o.scheme==="file"?o.fsPath:o.toString()}var Kd=class extends x{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 be;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 be}}})}}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 be}};Kd=A([b(3,O)],Kd);var Gd=class extends x{constructor(e,t,r,i){super();this._logService=r;this._editToolPaths=new Map;this._register(t),this._editTracker=i.createInstance(Ci,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"||!iD(i.name))continue;let s=io(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}`)}}}}};Gd=A([b(2,O),b(3,we)],Gd);var h_=Ep;function wy(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,taskPrompt:i.prompt,parentToolCallId:t.getParentSpawn(e)?.toolUseId},...r]}function UD(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 FD(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=typeof r?.prompt=="string"?r.prompt:void 0,l=o.input!==void 0?G3(o.input):void 0;t.recordSpawn(o.id,{subagentType:s,description:i,prompt:a});let d={...Jb(o.name)};return d.toolKind||(d.toolKind="subagent"),i&&(d.subagentDescription=i),s&&(d.subagentAgentName=s),{kind:"action",resource:n,action:{type:"chat/toolCallReady",turnId:e,toolCallId:o.id,invocationMessage:Go(o.name,On(o.name),o.input),...l!==void 0?{toolInput:l}:{},confirmed:"not-needed",_meta:At(d)}}}function HD(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=qd(d.name);t.startToolBlock(l,d.id,c,e),t.toolCalls.seedParsedInput(d.id,d.input),i.noteInnerTool(d.id,r);let u=On(c),p=Ko(c),g=Yi(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:Go(c,u,d.input),...g!==void 0?{toolInput:g}:{},confirmed:"not-needed"}});continue}}return a}function G3(o){try{return JSON.stringify(o)}catch{return}}var y_="User declined",v_="The user declined the plan, maybe ask why?",Ry="The user cancelled the question";function $D(o){switch(o){case y_:case v_:return"denied";case Ry:return"cancelled";default:return}}var xy=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=On(n.toolName);n.info={toolName:n.toolName,displayName:r,parsedInput:e,invocationMessage:Go(n.toolName,r,e),toolInput:Yi(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 Py=class{constructor(){this._activeToolBlocks=new Map;this.toolCalls=new xy;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 WD(o,n,e,t,r,i,s,a){if(r.getLevel()<=1)try{let l=JSON.stringify(o,(d,c)=>typeof c=="string"&&c.length>200?c.slice(0,200)+"\u2026":c);r.trace(`[claudeMapSessionEvents] SDK message type=${o.type}: ${l?.slice(0,2e3)??"<unserializable>"}`)}catch{r.trace(`[claudeMapSessionEvents] SDK message type=${o.type} (unserializable)`)}switch(o.type){case"stream_event":return wy(tW(o.event,n,e,t,r,o.parent_tool_use_id,i,s),n,o.parent_tool_use_id,i);case"result":return Z3(o,n,e,a,t,r,i);case"assistant":return wy(J3(o,n,e,t,o.parent_tool_use_id,i),n,o.parent_tool_use_id,i);case"user":return wy(Y3(o,n,t,r,i),n,o.parent_tool_use_id,i);default:return o.type==="system"?UD(o,n,i):[]}}function J3(o,n,e,t,r,i){if(r===null){let s=[];for(let a of o.message.content)a.type!=="tool_use"||!h_.has(a.name)||s.push(FD(a,n,e,i));return s}return HD(o,n,e,t,r,i)}function Y3(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=Q3(a.content)??[],u=e.takeFileEdit(a.tool_use_id);u&&c.push(u);let p=e.toolCalls.lookup(a.tool_use_id)?.info,g=c.filter(S=>S.type==="text").map(S=>S.text).join(`
`),h=p?yy(p.toolName,p.displayName,p.parsedInput,!d,g):`${On(l.toolName)} finished`,y=d?$D(g):void 0;s.push({kind:"action",resource:n,action:{type:"chat/toolCallComplete",turnId:l.turnId,toolCallId:a.tool_use_id,result:{success:!d,pastTenseMessage:h,content:c.length>0?c:void 0,...y?{error:{message:g,code:y}}:{}}}}),e.completeToolCall(a.tool_use_id);let I=r.getSpawn(a.tool_use_id);I&&!I.background&&I.markCompleted()&&(s.push({kind:"subagent_completed",chat:n,toolCallId:a.tool_use_id}),r.removeSpawn(a.tool_use_id))}return s}function Q3(o){if(typeof o=="string")return[{type:"text",text:o}];if(!Array.isArray(o))return;let n=[];for(let e of o)X3(e)&&n.push({type:"text",text:e.text});return n.length>0?n:void 0}function X3(o){if(o===null||typeof o!="object")return!1;let n=o;return n.type==="text"&&typeof n.text=="string"}function Z3(o,n,e,t,r,i,s){let a=[];if(o.subtype==="success"){let d=Object.keys(o.modelUsage)[0];a.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,...d?{model:d}:{}}}})}let l=eW(o);l!==void 0&&a.push({kind:"action",resource:n,action:{type:"chat/error",turnId:e,duration:typeof t=="number"&&Number.isFinite(t)?Math.max(0,t):0,error:{errorType:o.subtype,...Wl(l)}}}),r.clearPendingToolCalls(i);for(let d of s.drainForegroundSpawns())i.warn(`[claudeMapSessionEvents] turn ended with pending subagent-spawning tool_use ${d.toolUseId} (agentId=${d.agentId??"<unresolved>"}); dropping cross-message state`);return a}function eW(o){if(o.subtype==="success")return o.is_error?o.result:void 0;if(o.subtype==="error_during_execution")return o.errors?.join(`
`)}function tW(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:Ay(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:Ay(e,t,o.index,r),content:""}}}];if(l.type==="tool_use"){let d=qd(l.name),c=Z0(l.name);t.startToolBlock(o.index,l.id,d,e);let u=!c&&h_.has(d);i===null?u&&s.recordSpawn(l.id):s.noteInnerTool(l.id,i);let p=Ko(d),g=c?a?.(d):void 0;return[{kind:"action",resource:n,action:{type:"chat/toolCallStart",turnId:e,toolCallId:l.id,toolName:d,displayName:On(d),...g?{contributor:{kind:"client",clientId:g}}:{},...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:Ay(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:Ay(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=Ko(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 Ay(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 Jd=class extends x{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 E);this.onDidProduceSignal=this._onDidProduceSignal.event;this._mapperState=new Py;this._clientToolOwner=s,this._editObserver=this._register(a.createInstance(Gd,e.toString(),r))}setClientToolOwner(e){this._clientToolOwner=e}async handle(e,t,r){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 i=WD(e,this._chatChannelUri,t,this._mapperState,this._logService,this._subagents,this._clientToolOwner,r);for(let s of i)this._onDidProduceSignal.fire(s)}catch(i){this._logService.warn(`[ClaudeSdkMessageRouter] mapper threw, skipping message: ${i}`)}}};Jd=A([b(5,we),b(6,O)],Jd);var Yd=class extends x{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 E);this.onDidProduceSignal=this._onDidProduceSignal.event;this._warm=i,this._abortController=s,this._wireAbortHandler(s),this._queue=this._register(c.createInstance(Kd,e,()=>this._abortController.signal,p=>this._onDidProduceSignal.fire({kind:"steering_consumed",chat:this.chatChannelUri,id:p}))),this._router=this._register(c.createInstance(Jd,t,r,a,l,d)),this._register(this._router.onDidProduceSignal(p=>this._onDidProduceSignal.fire(p))),this._register(U(()=>this._abortController.abort())),this._register(U(()=>{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 t=await this._ensureQueryBound();return this._applyMcpServerEnablement(t,e,!0)}async stopMcpServer(e){let t=await this._ensureQueryBound();return this._applyMcpServerEnablement(t,e,!1)}async reconcileMcpServerEnablement(e){let t=await this._ensureQueryBound(),r=new Map((await t.mcpServerStatus()).map(i=>[i.name,i.status!=="disabled"]));for(let[i,s]of e){let a=r.get(i);if(!(a===void 0||a===s)&&!await this._applyMcpServerEnablement(t,i,s))return!1}return!0}async _applyMcpServerEnablement(e,t,r){return!e.toggleMcpServer||r&&!e.reconnectMcpServer?!1:(await e.toggleMcpServer(t,r),r&&await e.reconnectMcpServer(t),!0)}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,stopWatch:lt.create(!1),deferred:new be};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,stopWatch:r.stopWatch,deferred:new be,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,i=this._queue.peekParent()?.stopWatch.elapsed();try{await this._router.handle(t,r,i)}catch(s){this._logService.warn(`[ClaudeSdkPipeline:${this.sessionId}] router threw, skipping: ${s}`)}if(t.type==="result"){let s=this._queue.settleHead();this._logService.info(`[Claude:${this.sessionId}] result for sdkUuid=${s?.sdkUuid}`),s&&this._queue.isEmpty&&this._onDidProduceSignal.fire({kind:"action",resource:this.chatChannelUri,action:{type:"chat/turnComplete",turnId:s.turnId,duration:Math.max(0,s.stopWatch.elapsed())}})}}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),!un(r))throw r}}};Yd=A([b(8,we),b(9,O)],Yd);function nW(o,n,e){return Xi(o,n)??e}var Er=class extends x{constructor(e,t,r,i,s,a,l,d,c,u,p,g,h,y,I,S,C,_,T,w,W){super();this.sessionId=e;this.sessionUri=t;this.chatChannelUri=r;this.workspace=i;this._pendingClientToolCalls=u;this._permissionModeFallback=g;this._metadataStore=h;this._instantiationService=y;this._configurationService=I;this._stateManager=S;this._sdkService=C;this._sessionDataService=_;this._logService=T;this._fileService=w;this._environmentService=W;this._customizationWatcher=this._register(new G);this.subagents=this._register(new Sy);this._pendingPermissions=new Rt;this._pendingUserInputs=new Rt;this.clientCustomizationsDiff=this._register(new Iy);this._onDidSessionProgress=this._register(new E);this.onDidSessionProgress=this._onDidSessionProgress.event;this._currentTurnNanoAiu=0;this._transportKind="proxy";this._onDidCustomizationsChange=this._register(new E);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())),this._watchCustomizations(this.workspace)}get _storageUri(){return Re(this._chatChannelUri)?this.sessionUri:this._chatChannelUri}get _sessionCustomizations(){return this._stateManager.getSessionState(this.sessionUri.toString())?.customizations??[]}get workingDirectory(){return this._workingDirectory??this.workspace}get pendingClientToolCalls(){return this._pendingClientToolCalls}get permissionModeFallback(){return this._permissionModeFallback}static createProvisional(e,t,r,i,s,a,l,d,c,u,p,g){return g.createInstance(Er,e,t,r,i,s,a,l,d,new AbortController,c,new Cy,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?vh(this._lastCustomizations,r):void 0;return i===void 0?e:{...e,action:{...e.action,contributor:{kind:"mcp",customizationId:i}}}}_watchCustomizations(e){this._customizationWatcher.clear();let t=this._customizationWatcher.add(new _y(e,this._environmentService.userHome,this._fileService,this._logService));this._customizationWatcher.add(t.onDidChange(()=>this._onDidCustomizationsChange.fire()))}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(e.workingDirectory&&!gn(e.workingDirectory,this.workingDirectory)&&(this._workingDirectory=e.workingDirectory,this._watchCustomizations(e.workingDirectory)),!this.workingDirectory)throw new Error(`Cannot materialize Claude session ${this.sessionId}: workingDirectory is required`);this._transportKind=e.transport.kind;let t=Xi(this._configurationService,this._storageUri)??this._permissionModeFallback,{mcpServers:r,allowedTools:i}=await this._buildStartupToolWiring(e.serverToolHost),s=await f_(this._provisionalAgent,this._fileService,this._logService,this.sessionId),a=await Gb({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:this.abortController,permissionMode:t,canUseTool:e.canUseTool,onElicitation:e.onElicitation,isResume:e.isResume,resumeSessionAt:this._pendingResumeSessionAt,mcpServers:r,allowedTools:i,plugins:this.clientCustomizationsDiff.consume(this._desiredClientPluginPaths()),agent:s},e.transport,u=>this._logService.error(`[Claude SDK stderr] ${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(Yd,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(Rp(this._provisionalModel?.id),bp(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=Xi(this._configurationService,this._storageUri)??this._permissionModeFallback;try{let{mcpServers:g,allowedTools:h}=await this._buildStartupToolWiring(e.serverToolHost),y=await f_(this._provisionalAgent,this._fileService,this._logService,this.sessionId),I=new AbortController,S=await Gb({sessionId:this.sessionId,workingDirectory:this.workingDirectory,model:this._provisionalModel,abortController:I,permissionMode:p,canUseTool:e.canUseTool,onElicitation:e.onElicitation,isResume:!0,resumeSessionAt:this._pendingResumeSessionAt,mcpServers:g,allowedTools:h,plugins:this.clientCustomizationsDiff.consume(this._desiredClientPluginPaths()),agent:y},e.transport,_=>this._logService.error(`[Claude SDK stderr] ${_}`));this._logService.info(`[Claude] session ${this.sessionId}: resume rebuild agent=${S.agent??"(none)"}`);let C=await this._sdkService.startup({options:S});return this._pendingResumeSessionAt=void 0,{warm:C,abortController:I}}catch(g){throw this.toolDiff.markDirty(),this.clientCustomizationsDiff.markDirty(),g}}),await this._reconcileMcpServerEnablement(),e.serverToolHost?.advertise(this._storageUri.toString()),this._onDidCustomizationsChange.fire()}async _buildStartupToolWiring(e){let t=await nD(this.toolDiff,this._pendingClientToolCalls,this._sdkService),r=e?await Y0(e,this._storageUri.toString(),this._sdkService):void 0,i=!t&&!r?void 0:{...t??{},...r?{[Wd]:r}:{}},s=e?e.toolNames.filter(a=>!e.requiresConfirmation(a)):void 0;return{mcpServers:i,allowedTools:s?J0(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.hasDifferenceFrom(this._desiredClientPluginPaths())||this._pendingResumeSessionAt!==void 0?await this._rebindForSyncedState():await r.setPermissionMode(nW(this._configurationService,this._storageUri,this._permissionModeFallback)),await this._reconcileMcpServerEnablement(),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){this._provisionalModel=e,this._pipeline&&(await this._pipeline.setModel(Rp(e.id)),await this._pipeline.setEffort(bp(e))),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:Ty(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||!this._pipeline.hasActiveTurn?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=vD(t,e);return this._pendingClientToolCalls.respond(e,r)}async rebindForClientTools(){await this._rebindForSyncedState()}adoptClientCustomizations(e,t){this.clientCustomizationsDiff.model.setSyncedCustomizations(e,t)}getClientCustomizations(){return this.clientCustomizationsDiff.model.state.get().synced}async getSessionCustomizations(){let{synced:e}=this.clientCustomizationsDiff.model.state.get(),t=this._environmentService.userHome,[r,i,s,a,l]=await Promise.all([MD(this.workingDirectory,t,this._fileService),_D(this.workingDirectory,t,this._fileService),ID(this.workingDirectory,t,this._fileService),OD(this.workingDirectory,t,this._fileService),LD(this.workingDirectory,t,this._fileService,this._logService)]),d;if(this._pipeline)try{d=await this._pipeline.snapshotResolvedCustomizations()}catch(y){this._logService.warn(`[Claude:${this.sessionId}] snapshotResolvedCustomizations failed`,y)}let c=DD([...r,...i],s,a,l,this.workingDirectory,t,d),u=this._sessionCustomizations,p=new Map(u.map(y=>[y.id,y.enabled])),g=e.map(y=>({...y.customization,enabled:p.get(y.customization.id)??y.customization.enabled}));g.push(...c);let h=Sh(g,u);return this._lastCustomizations=h,h}async _reconcileMcpServerEnablement(){let e=this._requirePipeline(),t=this._sessionCustomizations,r=new Map(Zs(t).map(i=>[i.name,i.enabled]));if(r.size!==0&&!await e.reconcileMcpServerEnablement(r))throw new Error("Claude SDK cannot reconcile MCP server enablement")}_desiredClientPluginPaths(){let e=this._sessionCustomizations,t=new Map(e.map(i=>[i.id,i.enabled])),r=[];for(let i of this.clientCustomizationsDiff.model.state.get().synced)i.pluginDir&&(t.get(i.customization.id)??i.customization.enabled)!==!1&&r.push(i.pluginDir);return r}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 ib(this._lastCustomizations,e)??ib(await this.getSessionCustomizations(),e)}dispose(){this._pendingPermissions.denyAll(!1),this._pendingUserInputs.denyAll({response:"cancel"}),this._pendingClientToolCalls.rejectAll(new K),super.dispose()}};Er=A([b(13,we),b(14,Ue),b(15,Ce),b(16,$d),b(17,nt),b(18,O),b(19,xe),b(20,St)],Er);function qD(o,n){let e=typeof o.plan=="string"?o.plan:"";return{status:"pending-confirmation",toolCallId:n,toolName:"ExitPlanMode",displayName:On("ExitPlanMode"),invocationMessage:{markdown:e},toolInput:JSON.stringify(o),confirmationTitle:f(2087,null),options:[{id:"approve",label:f(2085,null),kind:"approve"},{id:"deny",label:f(2086,null),kind:"deny"}]}}function BD(o){let n=o;if(n.questions?.length)return{questions:n.questions}}function zD(o,n){return o||`q-${n}`}function VD(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=zD(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 jD(o,n){let e={};for(let t=0;t<o.questions.length;t++){let r=o.questions[t],i=n[zD(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 KD(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 rW(o,i,e,t,r)}finally{r.signal.removeEventListener("abort",s)}}async function rW(o,n,e,t,r){if(sD.has(e))return oW(o,n,e,t,r);let i=hy(e),s=On(e),a=r.blockedPath??io(e,t),l=Yi(e,t),d=Ko(e),c={status:"pending-confirmation",toolCallId:r.toolUseID,toolName:e,displayName:s,invocationMessage:Go(e,s,t),toolInput:l,confirmationTitle:aD(e),...d?{_meta:d}:{}},u=S_(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:y_}}function S_(o,n){if(!n.agentID)return;let e=o.subagents.getParentSpawn(n.toolUseID);if(e)return e.setAgentId(n.agentID),e.toolUseId}function oW(o,n,e,t,r){switch(e){case"ExitPlanMode":return iW(o,n,t,r);case"AskUserQuestion":return sW(o,n,t,r);default:return Promise.resolve({behavior:"deny",message:`Unsupported interactive tool: ${e}`})}}async function iW(o,n,e,t){let r=t.toolUseID,i=S_(n,t);return await n.requestPermission({toolUseID:r,state:qD(e,r),permissionKind:hy("ExitPlanMode"),...i!==void 0?{parentToolCallId:i}:{}})?(o.configurationService.updateSessionConfig(n.sessionUri.toString(),{permissionMode:"acceptEdits"}),{behavior:"allow",updatedInput:e}):{behavior:"deny",message:v_}}async function sW(o,n,e,t){let r=t.toolUseID,i=BD(e);if(!i)return{behavior:"deny",message:"AskUserQuestion called without questions"};let s=S_(n,t),a=await n.requestUserInput({id:r,questions:VD(i)},s);if(a.response!=="accept"||!a.answers)return{behavior:"deny",message:Ry};let l=jD(i,a.answers);return Object.keys(l).length===0?{behavior:"deny",message:Ry}:{behavior:"allow",updatedInput:{...e,answers:l}}}var GD=jd({const:Xt(),title:$t(Xt())}),aW=jd({type:$t(Xt()),title:$t(Xt()),description:$t(Xt()),format:$t(Xt()),default:$t(fD()),minimum:$t(so()),maximum:$t(so()),minLength:$t(so()),maxLength:$t(so()),minItems:$t(so()),maxItems:$t(so()),enum:$t(Qi(Xt())),enumNames:$t(Qi(Xt())),oneOf:$t(Qi(GD)),items:$t(jd({enum:$t(Qi(Xt())),anyOf:$t(Qi(GD))}))});function JD(o){if(!ze(o))return;let n=o.properties;if(!ze(n))return;let e=o.required,t=new Set(Array.isArray(e)?e.filter(Be):[]),r=[];for(let[i,s]of Object.entries(n)){let{content:a,error:l}=aW.validate(s);l||r.push([i,a])}return{fields:r,required:t}}function YD(o,n){if(n.mode==="url"){let r={id:o,message:n.message};return n.url&&(r.url=n.url),r}let e=JD(n.requestedSchema);if(!e||e.fields.length===0)return{id:o,message:n.message};let t=e.fields.map(([r,i])=>lW(r,i,e.required.has(r)));return{id:o,message:n.message,questions:t}}function QD(o,n,e){if(n==="decline")return{action:"decline"};if(n!=="accept")return{action:"cancel"};let t=o.mode==="url"?void 0:JD(o.requestedSchema);if(!t)return{action:"accept"};let r=[];for(let[i,s]of t.fields){let a=e&&Object.hasOwn(e,i)?e[i]:void 0,l=dW(s,a);l!==void 0&&r.push([i,l])}return{action:"accept",content:Object.fromEntries(r)}}function Ey(){return{action:"cancel"}}function lW(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:typeof n.default=="boolean"?n.default:void 0};case"number":case"integer":return{...t,kind:n.type==="integer"?"integer":"number",min:n.minimum,max:n.maximum,defaultValue:typeof n.default=="number"?n.default:void 0};case"array":return{...t,kind:"multi-select",allowFreeformInput:!1,options:n.items?.anyOf?n.items.anyOf.map(r=>({id:r.const,label:r.title||r.const})):(n.items?.enum??[]).map(r=>({id:r,label:r})),min:n.minItems,max:n.maxItems};default:if(n.oneOf)return{...t,kind:"single-select",allowFreeformInput:!1,options:n.oneOf.map(r=>({id:r.const,label:r.title||r.const}))};if(n.enum){let r=n.enumNames;return{...t,kind:"single-select",allowFreeformInput:!1,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:typeof n.default=="string"?n.default:void 0}}}function dW(o,n){if(!n||n.state==="skipped")return;let{value:e}=n;switch(o.type){case"boolean":if(e.kind==="boolean")return e.value;if(e.kind==="text"){if(e.value==="true")return!0;if(e.value==="false")return!1}return;case"number":case"integer":{let t=e.kind==="number"?e.value:e.kind==="text"&&e.value.trim()!==""?Number(e.value):void 0;return t===void 0||!Number.isFinite(t)?void 0:o.type==="integer"?Math.trunc(t):t}case"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;default:return e.kind==="text"||e.kind==="selected"?e.value:void 0}}async function XD(o,n,e,t){let r=o.getSession(n);if(!r)return Ey();let i=F();if(t.signal.aborted)return Ey();let s=YD(i,e);if(!s.url&&!s.questions?.length)return Ey();let a=()=>{r.respondToUserInputRequest(i,"cancel")};t.signal.addEventListener("abort",a);try{let{response:l,answers:d}=await r.requestUserInput(s);return QD(e,l,d)}finally{t.signal.removeEventListener("abort",a)}}import{once as uW}from"events";var cW=["interleaved-thinking","context-management","advanced-tool-use"];function ZD(o){let n=o.split(",").map(e=>e.trim()).filter(e=>e&&cW.some(t=>e.startsWith(t+"-")));return n.length>0?n.join(","):void 0}function C_(o,n){return{type:"error",error:{type:o,message:n},request_id:null}}function gr(o,n,e,t){o.writeHead(n,{"Content-Type":"application/json"}),o.end(JSON.stringify(C_(e,t)))}function eM(o,n,e){o.writeHead(n,{"Content-Type":"application/json"}),o.end(JSON.stringify(e))}function tM(o){return`event: error
data: ${JSON.stringify(o)}

`}var Dy=B("claudeProxyService"),pW=new Set(["anthropic"]),fW="/v1/messages",Qd="ClaudeProxyService",nM="vscode_claude_code";function I_(o){let n=o?.copilot_usage?.total_nano_aiu;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}var Xd=class extends zi{constructor(e,t){super(Qd,e);this._copilotApiService=t;this._onDidReportCredits=new E;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){gr(e,500,"api_error","Internal proxy error")}_reportCredits(e,t){e===void 0||t===void 0||(this._logService.trace(`[${Qd}] 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(`[${Qd}] ${i} ${s}`),i==="GET"&&s==="/"){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}let a=qh(e.headers,r.nonce);if(!a.valid){gr(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"){gr(t,501,"api_error","count_tokens not supported by CAPI");return}gr(t,404,"not_found_error",`No route for ${i} ${s}`)}async _handleModels(e,t,r){let i=rM(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(!gW(d))continue;let c=la(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 Id(e)}catch(I){gr(t,400,"invalid_request_error",`Failed to read request body: ${ky(I)}`);return}let a;try{a=JSON.parse(s)}catch{gr(t,400,"invalid_request_error","Request body is not valid JSON");return}if(!a||typeof a!="object"){gr(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){gr(t,400,"invalid_request_error","Missing required field: model");return}if(!Array.isArray(l.messages)){gr(t,400,"invalid_request_error","Missing required field: messages");return}let c=la(d);if(!c){gr(t,404,"not_found_error",`Unknown model: ${d}`);return}let u=c.toEndpointModelId();l.model=u;let p=l.stream===!0,g=rM(e.headers),h={ac:new AbortController,res:t,clientGone:!1};r.inFlight.add(h);let y=()=>{h.clientGone=!0,h.ac.abort()};t.on("close",y);try{p?await this._streamMessages(l,g,t,h,r,d,i):await this._sendNonStreamingMessage(l,g,t,h,r,d,i)}finally{t.removeListener("close",y),r.inFlight.delete(h)}}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(g){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,g,!0);return}this._reportCredits(l,I_(c));let u=iM(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(h){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,h,!0);return}let u;try{u=await c.next()}catch(h){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}this._writeUpstreamErrorResponse(r,h,!0);return}r.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushHeaders(),yW(r);let p=async h=>{let y=mW(h,this._logService),I=`event: ${y.type}
data: ${JSON.stringify(y)}

`;if(!r.write(I))try{await uW(r,"drain",{signal:i.ac.signal})}catch{return!1}return!0},g;try{if(!u.done&&(g=I_(u.value)??g,!await p(u.value)))return;for(;;){let h;try{h=await c.next()}catch(I){if(i.ac.signal.aborted){!i.clientGone&&!r.writableEnded&&r.destroy();return}let S=I instanceof wr?oM(I):C_("api_error",ky(I));if(!r.writableEnded){try{r.write(tM(S))}catch{}try{r.end()}catch{}}return}if(h.done)break;if(g=I_(h.value)??g,!await p(h.value))return}r.writableEnded||r.end(),this._reportCredits(l,g)}catch(h){if(this._logService.warn(`[${Qd}] stream loop unexpected error: ${ky(h)}`),!r.writableEnded)try{r.end()}catch{}}}_writeUpstreamErrorResponse(e,t,r=!1){if(e.headersSent){if(this._logService.warn(`[${Qd}] cannot write upstream error after headers sent: ${ky(t)}`),!e.writableEnded)try{e.end()}catch{}return}if(t instanceof wr){let i=t.status===Uu?502:t.status;eM(e,i,r?oM(t):t.envelope);return}gr(e,502,"api_error",t instanceof Error?t.message:String(t))}};Xd=A([b(0,O),b(1,gt)],Xd);function gW(o){return pW.has(o.vendor.toLowerCase())?Array.isArray(o.supported_endpoints)&&o.supported_endpoints.includes(fW):!1}function iM(o,n){let e=la(o);if(!e){n.warn(`[${Qd}] outbound model ID could not be parsed for SDK rewrite: ${o}`);return}return e.toSdkModelId()}function mW(o,n){if(o.type!=="message_start")return o;let e=iM(o.message.model,n);return e===void 0||e===o.message.model?o:{...o,message:{...o.message,model:e}}}function rM(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=ZD(t);i!==void 0&&(n["anthropic-beta"]=i)}let r=o["user-agent"];return typeof r=="string"&&r.length>0&&(n["User-Agent"]=hW(r)),n}function hW(o){let n=o.indexOf("/");return n===-1?`${nM}/${o}`:`${nM}${o.substring(n)}`}function yW(o){let n=o.socket;if(n&&typeof n.setNoDelay=="function")try{n.setNoDelay(!0)}catch{}}function ky(o){return o instanceof Error?o.message:String(o)}function oM(o){let n=jm(Vm(o));return{...o.envelope,error:{...o.envelope.error,message:`${o.envelope.error.message} ${n}`}}}var Zt=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(Zt.KEY_CUSTOMIZATION_DIRECTORY,e.customizationDirectory.toString())),e.model&&i.push(r.setMetadata(Zt.KEY_MODEL,SW(e.model))),e.permissionMode&&i.push(r.setMetadata(Zt.KEY_PERMISSION_MODE,e.permissionMode)),e.agent!==void 0&&i.push(r.setMetadata(Zt.KEY_AGENT,e.agent===null?"":JSON.stringify({uri:e.agent.uri}))),e.transport&&i.push(r.setMetadata(Zt.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(Zt.KEY_CUSTOMIZATION_DIRECTORY),e.object.getMetadata(Zt.KEY_MODEL),e.object.getMetadata(Zt.KEY_PERMISSION_MODE),e.object.getMetadata(Zt.KEY_AGENT),e.object.getMetadata(Zt.KEY_TRANSPORT)]);return{customizationDirectory:t?v.parse(t):void 0,model:CW(r),permissionMode:Ji(i),agent:vW(s),transport:a==="proxy"||a==="native"?a:void 0}}finally{e.dispose()}}project(n){return{session:M.uri(this._provider,n.sessionId),startTime:n.createdAt??n.lastModified,modifiedTime:n.lastModified,summary:n.customTitle??n.summary,workingDirectory:n.cwd?v.file(n.cwd):void 0}}};Zt=A([b(1,nt)],Zt);function vW(o){if(o)try{let n=JSON.parse(o);if(n&&typeof n=="object"&&typeof n.uri=="string")return{uri:n.uri}}catch{}}function SW(o){return JSON.stringify(o)}function CW(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 IW="vscode_claude_code";function bW(o){return o.vendor==="Anthropic"&&!!o.supported_endpoints?.includes("/v1/messages")&&!!o.model_picker_enabled&&!!o.capabilities?.supports?.tool_calls&&la(o.id)!==void 0}function _W(o,n){let e=o.capabilities?.supports,t=(e?.reasoning_effort??[]).filter(zb),r=Vb(t),i=o.policy?.state,s=yd(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:vd(s,a)}}function TW(o,n){let e=(o.supportedEffortLevels??[]).filter(zb),t=Vb(e);return{provider:n,id:o.value,name:o.displayName,supportsVision:!1,...t?{configSchema:t}:{}}}var b_=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)}},Zd=class extends x{constructor(e,t,r,i,s,a,l,d,c,u,p,g){super();this._logService=e;this._copilotApiService=t;this._claudeProxyService=r;this._sdkService=i;this._stateManager=s;this._gitService=a;this._configurationService=l;this._gitHubEndpointService=d;this._instantiationService=c;this._pluginManager=u;this._productService=p;this._environmentService=g;this.id=XR;this._onDidSessionProgress=this._register(new E);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidCustomizationsChange=this._register(new E);this.onDidCustomizationsChange=this._onDidCustomizationsChange.event;this._onDidRequireAuth=this._register(new E);this.onDidRequireAuth=this._onDidRequireAuth.event;this._models=yn(this,[]);this.models=this._models;this._transportMode="proxy";this._sessions=this._register(new Ee);this._chatBackings=new Map;this._onDidChangeChatData=this._register(new E);this.onDidChangeChatData=this._onDidChangeChatData.event;this._onDidSpawnChat=this._register(new E);this.onDidSpawnChat=this._onDidSpawnChat.event;this._activeClientHandles=new Map;this._onDidMaterializeSession=this._register(new E);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._disposeSequencer=new Ze;this._sessionSequencer=new Ze;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,a)=>this._sendMessage(e,t,r,i,s,a),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=c.createInstance(Zt,this.id),this._register(this._claudeProxyService.onDidReportCredits(h=>{this._findSessionBySdkId(h.sessionId)?.recordTurnCredits(h.totalNanoAiu)})),this._transportMode=this._resolveTransportMode(),this._register(this._configurationService.onDidRootConfigChange(()=>{let h=this._resolveTransportMode();h!==this._transportMode&&(this._transportMode=h,this._models.set([],void 0),this._startModelRefresh(),h==="proxy"&&!this._proxyHandle&&this._onDidRequireAuth.fire({resource:this._gitHubEndpointService.getCopilotResource().resource,reason:"required"}))})),this._transportMode==="native"&&queueMicrotask(()=>{this._startModelRefresh()})}_findAnySession(e){return this._sessions.get(e)?.defaultChat}_findChat(e,t){let r=this._sessions.get(M.id(e));if(r)return r.getChat((t??v.parse(pe(e))).toString())}_getChatContext(e){let t=Le(e)?e:v.parse(pe(e)),r=v.parse(ce(t)),i=M.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 My(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 My;return i.setDefaultChat(pe(t),this._wireEntry(r)),this._sessions.set(e,i),i}_emitSpawnedChatEvents(e){let t=Ts.toSpawnEvent(e);t&&this._onDidSpawnChat.fire(t)}_resolveTransportMode(){return this._configurationService.getRootValue(Dn,"claudeUseCopilotProxy")??!0?"proxy":"native"}getDescriptor(){return{provider:this.id,displayName:f(2084,null),description:f(2083,null),capabilities:{multipleChats:{fork:!0,sideChat:!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 N(_r,"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;let r=this._githubToken!==t;if(!r&&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(),r&&this._models.set([],void 0),this._startModelRefresh(),!0}_isProxyEnabled(){return this._transportMode==="proxy"}refreshModels(){return this._modelRefreshInFlight??this._startModelRefresh()}_startModelRefresh(){let e=this._refreshModels().finally(()=>{this._modelRefreshInFlight===e&&(this._modelRefreshInFlight=void 0)});return this._modelRefreshInFlight=e,e}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")}}async _fetchNativeModels(){let e={[Symbol.asyncIterator]:()=>({next:()=>new Promise(()=>{})})},t=rD(),r=await this._sdkService.query({prompt:e,options:t});try{return(await r.supportedModels()).map(s=>TW(s,this.id))}finally{r.close(),t.abortController?.abort()}}async _fetchProxyModels(e){let t=`${IW}/${this._productService.version}`;return(await this._copilotApiService.models(e,{headers:{"User-Agent":t},suppressIntegrationId:!0})).filter(bW).sort((i,s)=>Number(s.is_chat_default)-Number(i.is_chat_default)).map(i=>_W(i,this.id))}async createSession(e={}){if(this._ensureAuthenticated(),e.fork)return this._forkSession(e,e.fork);let t=e.session?M.id(e.session):F(),r=M.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 c1(this._environmentService.userHome,t),a=e.workingDirectory?await fr({cwd:e.workingDirectory.fsPath},this._gitService):void 0,l=this._resolvePermissionMode(e.config),d=Er.createProvisional(t,r,v.parse(pe(r)),s,a,e.model,e.agent,e.config,new Rt,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=M.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=vy(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?v.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=Le(e);if(!t)throw new Error(`Claude chat operation requires an AHP chat URI: ${e.toString()}`);return{session:v.parse(t.session),chat:e}}async _forkSession(e,t){if(Ir(t.session))throw new Error("Cannot fork a subagent session");let r=M.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=vy(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=M.uri(this.id,l),c={};try{c=await this._metadataStore.read(t.session)}catch(S){this._logService.warn(`[Claude] fork: source overlay read failed for ${r}; continuing with defaults`,S)}let u=e.model??c.model,p=e.agent??c.agent,g=Ji(e.config?.permissionMode)??c.permissionMode;await this._metadataStore.write(d,{...u?{model:u}:{},...g?{permissionMode:g}:{},...p?{agent:p}:{}});let h=await this._sdkService.getSessionInfo(l),y=h?.cwd?v.file(h.cwd):e.workingDirectory;if(!y)throw new Error(`Cannot fork session ${r}: forked session ${l} has no working directory (SDK cwd missing and none supplied)`);let I;try{I=await fr({cwd:y.fsPath},this._gitService)}catch(S){this._logService.warn(`[Claude] fork: project resolution failed for ${l}; continuing without project`,S)}return{session:d,workingDirectory:y,...I?{project:I}:{}}})}_makeCanUseTool(e){return(t,r,i)=>KD({getSession:s=>this._findSessionBySdkId(s),configurationService:this._configurationService},e,t,r,i)}_makeOnElicitation(e){return(t,r)=>XD({getSession:i=>this._findSessionBySdkId(i)},e,t,r)}async _materializeProvisional(e,t){let r=this._findAnySession(e);if(!r)throw new Error(`Cannot materialize unknown provisional session: ${e}`);let i=this._ensureAuthenticated(),s=this._makeCanUseTool(e),a=this._makeOnElicitation(e);try{await r.materialize({transport:i,canUseTool:s,onElicitation:a,isResume:!1,workingDirectory:t,serverToolHost:this._serverToolHost})}catch(l){throw this._sessions.deleteAndDispose(e),l}return this._onDidMaterializeSession.fire({session:r.sessionUri,workingDirectory:r.workingDirectory,project:r.project}),r}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?v.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(g){this._logService.warn(`[Claude:${e}] overlay read failed during resume; continuing with defaults`,g)}let l=Xi(this._configurationService,t)??a.permissionMode??"default",d;try{d=await fr({cwd:s.fsPath},this._gitService)}catch(g){this._logService.warn(`[Claude:${e}] project resolution failed during resume; continuing without project`,g)}let c=Er.createProvisional(e,t,v.parse(pe(t)),s,d,a.model,a.agent,void 0,new Rt,l,this._metadataStore,this._instantiationService);this._seedSessionEntry(e,t,c);let u=this._makeCanUseTool(e),p=this._makeOnElicitation(e);try{await c.materialize({transport:r,canUseTool:u,onElicitation:p,isResume:!0,serverToolHost:this._serverToolHost})}catch(g){throw this._sessions.deleteAndDispose(e),g}return this._onDidMaterializeSession.fire({session:t,workingDirectory:s,project:d}),c}_resolvePermissionMode(e){return Ji(e?.permissionMode)??"default"}disposeSession(e){let t=M.id(e);return this._disposeSequencer.queue(t,async()=>{await this._teardownEntry(t),this._pruneActiveClientHandles(t)})}releaseSession(e){let t=M.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=Le(v.parse(i));s&&M.id(v.parse(s.session))===e&&this._chatBackings.delete(i)}}async _createChat(e,t){if(this._ensureAuthenticated(),Re(e))return;let r=Le(e);if(!r)throw new Error(`[Claude] createChat: malformed chat URI ${e.toString()}`);let i=v.parse(r.session),s=e.toString(),a=M.id(i),l,d=t?.sideChat?s:a;return await this._sessionSequencer.queue(d,async()=>{let c=this._chatBackings.get(s);if(c){l={providerData:Br(c),backingSession:M.uri(this.id,c.sdkSessionId)};return}let u=await this._resolveParentSession(i,a),p=t?.model??u.model,g,h;if(t?.fork)g=(await this._forkChat(i,t.fork))?.sessionId;else if(t?.sideChat){let I=await this._forkChat(i,{source:t.sideChat.source,turnId:t.sideChat.providerAnchorTurnId??t.sideChat.turnId});g=I?.sessionId;let S=t.sideChat.sourceContext??(I?void 0:this._buildSideChatContext(i,t.sideChat.source,t.sideChat.turnId));if(!I&&!S&&!t.sideChat.partialResponse)throw new Error(`[Claude] createChat side chat: source turn ${t.sideChat.turnId} could not be forked`);h={source:t.sideChat.source.toString(),turnId:t.sideChat.turnId,...t.sideChat.selection?{selection:t.sideChat.selection}:{},...t.sideChat.providerAnchorTurnId?{providerAnchorTurnId:t.sideChat.providerAnchorTurnId}:{},inheritedTurnCount:I?.inheritedTurnCount??0,...S?{context:S}:{},...t.sideChat.partialResponse?{partialResponse:t.sideChat.partialResponse}:{}}}g??=F();let y={sdkSessionId:g,...p?{model:p}:{},...h?{sideChat:h}:{}};this._chatBackings.set(s,y),l={providerData:Br(y),backingSession:M.uri(this.id,g)},await this._metadataStore.write(e,{...p?{model:p}:{},...u.agent?{agent:u.agent}:{},...u.permissionMode?{permissionMode:u.permissionMode}:{}}),this._logService.info(`[Claude] Created additional chat ${e.toString()} in session ${i.toString()}${t?.fork?" (forked)":""}`)}),l}async _disposeChat(e,t){if(Re(t))return;let r=t.toString(),i=M.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?v.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 fr({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=Xi(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=vy(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}),l=i.findIndex(c=>c.uuid===s),d=zd(i.slice(0,l+1),t.source,this._logService).length;return{sessionId:a,inheritedTurnCount:d}}async _resolveChatSdkId(e,t){if(Re(t)||t.toString()===e.toString())return M.id(e);let r=this._findChat(e,t)?.sessionId;return r||this._resolveChatBacking(t)?.sdkSessionId}_getSourceChatState(e,t){return Re(t)||t.toString()===e.toString()?this._stateManager.getDefaultChatState(e.toString()):this._stateManager.getChatState(t.toString())}_buildSideChatContext(e,t,r){let i=this._getSourceChatState(e,t);if(!i)return;let s=i.turns.findIndex(l=>l.id===r),a=s>=0?i.turns.slice(0,s+1):i.activeTurn?.id===r?i.turns:void 0;return a?Cg(a,i.activeTurn?.id===r?i.activeTurn:void 0):void 0}_resolveChatBacking(e){return this._chatBackings.get(e.toString())}_ensureSessionEntry(e){let t=M.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=Er.createProvisional(t,e,v.parse(pe(e)),i.workingDirectory,i.project,i.model,i.agent,void 0,new Rt,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),u=this._makeOnElicitation(a.sessionId);try{await a.materialize({transport:d,canUseTool:c,onElicitation:u,isResume:!!l,serverToolHost:this._serverToolHost})}catch(p){throw i.disposePeerChat(r),p}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,M.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=Xi(this._configurationService,t)??a.permissionMode??s.permissionMode,d=a.model??i.model,c=Er.createProvisional(i.sdkSessionId,e,t,s.workingDirectory,s.project,d,a.agent??s.agent,void 0,new Rt,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={...r,model:t};this._chatBackings.set(e.toString(),i),this._onDidChangeChatData.fire({chat:e,providerData:Br(i)})}async materializeChat(e,t){if(Re(e)||!Le(e)||t===void 0)return;let i=_g(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(M.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(Ir(e)){let d=It(e),c=d?this._sessions.get(M.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 yD(e,c.subagents,this._sdkService,this._logService,ke.None)}catch(u){return this._logService.warn(`[Claude] getSubagentTranscript threw for ${e.toString()}`,u),[]}}let t=Le(e)?e:v.parse(pe(e)),r=Le(t);if(!r)return[];let i=v.parse(r.session),s=M.id(i),a=this._getChatContext(t);if(a.isPeerChat){let d=await this._resolveChatSdkId(i,t);if(!d)return[];let c=await this._reconstructTurns(d,t,a.target),u=this._resolveChatBacking(t)?.sideChat;return bg(c.slice(u?.inheritedTurnCount??0),u)}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=zd(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 e.map(t=>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=M.id(e),r=await this._sdkService.getSessionInfo(t);if(r)return this._metadataStore.project(r)}resolveSessionConfig(e){let t=Hn({permissionMode:ae({type:"string",title:f(2071,null),description:f(2082,null),enum:["default","acceptEdits","plan","auto","bypassPermissions"],enumLabels:[f(2078,null),f(2072,null),f(2080,null),f(2074,null),f(2076,null)],enumDescriptions:[f(2079,null),f(2073,null),f(2081,null),f(2075,null),f(2077,null)],default:"default",sessionMutable:!0}),permissions:Pt.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,a){let l=s??F(),d=this._getChatContext(e);return d.isPeerChat?this._sessionSequencer.queue(d.chatKey,async()=>{let c=await this._materializeChatLocked(d.session,e),u=this._resolveChatBacking(e)?.sideChat,p=u?await this._reconstructTurns(c.sessionId,e,c):[],g=Ig(t,p,u);await c.send(this._buildSdkPrompt(c.sessionId,g,i,l),l)}):this._sessionSequencer.queue(d.sessionId,async()=>{let c=this._getChatContext(e).target,u;c?.isPipelineReady?u=c:c?u=await this._materializeProvisional(d.sessionId,r):u=await this._resumeSession(d.sessionId,d.session),await u.send(this._buildSdkPrompt(d.sessionId,t,i,l),l)})}_buildSdkPrompt(e,t,r,i){return{type:"user",message:{role:"user",content:Ty(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){let i=this._getChatContext(e);if(this._logService.info(`[Claude] setPendingMessages for ${e.toString()}: steering=${t?.id??"none"} queued=${r.length}`),!i.target){this._logService.warn(`[Claude] setPendingMessages: chat not found for ${e.toString()}`);return}t&&i.target.injectSteering(t)}onSessionConfigChanged(e,t){let r=this._sessions.get(this._getChatContext(e).sessionId);if(!r)return;let i=Ji(t.permissionMode);for(let s of r.allChatSessions()){if(!s.isPipelineReady)continue;let a=i??s.permissionModeFallback;s.setPermissionMode(a).catch(l=>{this._logService.warn(`[Claude:${s.sessionId}] mid-turn setPermissionMode(${a}) failed`,l)})}}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=M.id(e),i=`${r}\0${t.clientId}`,s=this._activeClientHandles.get(i);return s||(s=new b_(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=M.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=It(s);)s=a.parentSession;let l=M.id(s);this._sessions.get(l)?.defaultChat?.completeClientToolCall(r,i)}async syncClientCustomizations(e,t,r,i){let s=M.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}})}getCustomizations(){return[]}async getSessionCustomizations(e){let t=this._findAnySession(M.id(e));return t?await t.getSessionCustomizations():[]}async startMcpServer(e,t){await this._findAnySession(M.id(e))?.startMcpServer(t)}async stopMcpServer(e,t){await this._findAnySession(M.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)}};Zd=A([b(0,O),b(1,gt),b(2,Dy),b(3,$d),b(4,Ce),b(5,$e),b(6,Ue),b(7,wt),b(8,we),b(9,$i),b(10,Tt),b(11,St)],Zd);var My=class extends ll{get defaultChat(){return super.defaultChat}};import{spawn as mq}from"child_process";import*as ao from"fs";import*as hO from"os";function aM(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 wW(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 RW(o){return{state:{kind:"ready"},tools:wW(o.tools),resources:o.resources,resourceTemplates:o.resourceTemplates}}function lM(o){let n=new Map;for(let e of o)n.set(e.name,RW(e));return n}function Oy(o){let n=[];for(let[e,t]of o)n.push({name:e,state:t.state});return n}function dM(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 cM(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 xW(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 sM(o){let n={};if(!o)return n;for(let[e,t]of Object.entries(o))t!=null&&(n[e]=String(t));return n}function AW(o){return Array.isArray(o)?o.filter(n=>n!=null).map(n=>String(n)):[]}function __(o){if(o.type==="stdio"){let t={command:o.command},r=AW(o.args);r.length>0&&(t.args=r);let i=sM(o.env);return Object.keys(i).length>0&&(t.env=i),typeof o.cwd=="string"&&(t.cwd=o.cwd),t}let n={url:o.url},e=sM(o.headers);return Object.keys(e).length>0&&(n.http_headers=e),n}function kp(o){let n={};for(let[e,t]of Object.entries(o??{}))xW(t)&&(n[e]=__(t));return n}function Zi(o){if(!URL.canParse(o))return;let n=new URL(o);return n.hash="",n.pathname=n.pathname.replace(/\/+$/,""),n.href}function uM(o){return o?/not logged in|mcp login|log in to|unauthori[sz]ed|requires? (?:authentication|authorization|login)|\b401\b/i.test(o):!1}function pM(o,n){if(n.size===0)return o;let e={};for(let[t,r]of Object.entries(o)){let i=r.url!==void 0?Zi(r.url):void 0,s=i!==void 0?n.get(i):void 0;e[t]=s!==void 0?{...r,http_headers:{...PW(r.http_headers),Authorization:`Bearer ${s}`}}:r}return e}function PW(o){let n={};if(o)for(let[e,t]of Object.entries(o))e.toLowerCase()!=="authorization"&&(n[e]=t);return n}var EW="codex-skills",kW="codex-hooks";function DW(o){switch(o){case"repo":return"Repository";case"user":return"User";case"system":return"Built-in";case"admin":return"Admin";default:return o}}var MW=["repo","user","system","admin"];function OW(o){let n=v.file(o.path).toString();return{type:"skill",id:et(n),uri:n,name:o.name,description:o.description,enabled:o.enabled}}function fM(o){let n=new Map;for(let t of o?.data??[])for(let r of t.skills??[]){let i=n.get(r.scope);i||(i=new Map,n.set(r.scope,i)),i.has(r.path)||i.set(r.path,r)}let e=[];for(let t of MW){let r=n.get(t);if(!r||r.size===0)continue;let i=[...r.values()].sort((a,l)=>a.name.localeCompare(l.name)).map(OW),s=v.from({scheme:EW,path:`/${t}`}).toString();e.push({type:"directory",id:et(s),uri:s,name:DW(t),enabled:!0,contents:"skill",writable:!1,load:{kind:"loaded"},children:i})}return e}function LW(o){let n=v.file(o.sourcePath).with({fragment:o.key}).toString();return{type:"hook",id:et(n),uri:n,name:o.eventName,enabled:o.enabled}}function gM(o){let n=new Map;for(let r of o?.data??[])for(let i of r.hooks??[])n.has(i.key)||n.set(i.key,i);if(n.size===0)return[];let e=[...n.values()].sort((r,i)=>Number(r.displayOrder-i.displayOrder)||r.key.localeCompare(i.key)).map(LW),t=v.from({scheme:kW,path:"/hooks"}).toString();return[{type:"directory",id:et(t),uri:t,name:"Hooks",enabled:!0,contents:"hook",writable:!1,load:{kind:"loaded"},children:e}]}var ec=class{constructor(){this._byClient=new Map;this._enablement=new Map}setClient(n,e){this._byClient.set(n,e)}removeClient(n){return this._byClient.delete(n)}setEnabled(n,e){return this._enablement.get(n)!==!1===e?!1:(e?this._enablement.delete(n):this._enablement.set(n,!1),!0)}has(n){return this._merged().some(e=>e.synced.customization.id===n)}isEmpty(){return this._merged().length===0}_merged(){let n=new Set,e=[];for(let t of this._byClient.values())for(let r of t){let i=r.synced.customization.id;n.has(i)||(n.add(i),e.push(r))}return e}_isEnabled(n){return this._enablement.get(n)!==!1}enabledPlugins(){return this._merged().filter(n=>n.parsed!==void 0&&this._isEnabled(n.synced.customization.id))}toCustomizations(){return this._merged().map(n=>{let e=n.synced.customization,t=n.parsed?NW(n.parsed):e.children;return{...e,enabled:this._isEnabled(e.id),...t?{children:t}:{}}})}};function NW(o){let n=new Map,e=t=>{n.has(t.id)||n.set(t.id,t)};for(let t of o.agents)e(t.customization);for(let t of o.skills)e(t.customization);for(let t of o.instructions)e(t.customization);for(let t of o.hooks)e(t.customization);for(let t of o.mcpServers)e(t.customization);return[...n.values()]}function Ly(o){let n={};for(let e of o)for(let t of e.parsed?.mcpServers??UW)Object.prototype.hasOwnProperty.call(n,t.name)||(n[t.name]=__(t.configuration));return n}var UW=[];function mM(o){let n=new Set;for(let e of o)for(let t of e.parsed?.skills??[])n.add(te(te(t.uri.fsPath)));return[...n].sort()}function yM(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(FW(r,i,e.has(r)));return t.length>0?{id:o,message:n.message,questions:t}:{id:o,message:n.message}}function vM(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=HW(e?.[r]);s!==void 0&&(t[r]=s)}return{action:"accept",content:t,_meta:null}}function T_(){return{action:"decline",content:null,_meta:null}}function SM(){return{action:"cancel",content:null,_meta:null}}function FW(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:hM(n.minItems),max:hM(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 HW(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 hM(o){return o==null?void 0:Number(o)}var es=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r;this.name="JsonRpcError"}},$W=2e3,Ny=class extends x{constructor(e,t,r=$W){super();this._transport=e;this._onLog=t;this._graceKillMs=r;this._onExit=this._register(new E);this.onExit=this._onExit.event;this._onTransportError=this._register(new E);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),U(()=>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 es(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 es(-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 es(-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 es(-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),U(()=>{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),U(()=>{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 CM(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 nc from"fs";var Uy=B("codexProxyService"),WW="codex-auto-review",en="CodexProxyService",IM="vscode_codex",qW="VSCODE_CODEX_PROXY_DUMP_DIR",BW=0;function zW(){return String(++BW).padStart(4,"0")}function VW(){let o=process.env[qW];if(o)try{return nc.mkdirSync(o,{recursive:!0}),o}catch{return}}function Dp(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 tc=class extends zi{constructor(e,t){super(en,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(`[${en}] >>> ${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){Dp(t,401,"authentication_error","Invalid authentication");return}if(i==="GET"&&s==="/v1/models"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({models:[]}));return}if(i==="POST"&&(s==="/v1/responses"||s==="/responses"||s==="//responses")){await this._handleResponses(e,t,r);return}Dp(t,404,"not_found_error",`No route for ${i} ${s}`)}async _handleResponses(e,t,r){let i;try{i=await Id(e)}catch(g){Dp(t,400,"invalid_request_error",`Failed to read request body: ${g instanceof Error?g.message:String(g)}`);return}let s=jW(i,r.state);s.remappedFrom&&this._logService.info(`[${en}] remapped unsupported reviewer model '${s.remappedFrom}' -> '${s.remappedTo}'`),i=s.body;let a=VW(),l=a?zW():void 0;if(a&&l){let g=V(a,`req-${l}-${Date.now()}.json`);try{nc.writeFileSync(g,i),this._logService.info(`[${en}] dumped request body to ${g}`)}catch(h){this._logService.warn(`[${en}] failed to dump request body: ${h instanceof Error?h.message:String(h)}`)}}try{let g=JSON.parse(i);if(this._logService.info(`[${en}] >>> /responses body: model=${g.model??"<none>"}, previous_response_id=${g.previous_response_id??"<none>"}, stream=${g.stream??"<none>"}, input_items=${Array.isArray(g.input)?g.input.length:"<not-array>"}`),Array.isArray(g.input))for(let y=0;y<g.input.length;y++){let I=g.input[y],S=I?.type??"<none>",C=I&&typeof I=="object"?Object.keys(I).join(","):typeof I,_="";if(S==="message"){let T=I?.content?.[0]?.text??"";_=`role=${I?.role??"?"} chars=${T.length}`}else if(S==="function_call")_=`name=${I?.name??"?"} call_id=${I?.call_id??"?"}`;else if(S==="function_call_output"){let T=I?.output??"";_=`call_id=${I?.call_id??"?"} output_chars=${typeof T=="string"?T.length:0}`}else if(S==="reasoning"){let T=I?.summary??I?.content??"";_=`summary_chars=${typeof T=="string"?T.length:JSON.stringify(T).length} encrypted=${typeof I?.encrypted_content=="string"}`}else _=JSON.stringify(I).slice(0,120);this._logService.info(`[${en}]   input[${y}] type=${S} keys=[${C}] ${_}`)}let h=Object.keys(g).filter(y=>y!=="input").sort();this._logService.info(`[${en}]   top-level keys (excl. input)=[${h.join(", ")}]`);for(let y of h){if(y==="instructions"||y==="tools"){let C=g[y],_=typeof C=="string"?C.length:JSON.stringify(C).length;this._logService.info(`[${en}]     ${y}=<${_} chars elided>`);continue}let I=g[y],S=typeof I=="object"?JSON.stringify(I).slice(0,300):String(I);this._logService.info(`[${en}]     ${y}=${S}`)}}catch{this._logService.info(`[${en}] >>> /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=KW(e.headers);try{this._logService.info(`[${en}] forwarding to CAPI responses...`);let g=await this._copilotApiService.responses(u,i,{headers:p,signal:d.ac.signal,suppressIntegrationId:!0}),h=g.headers.get("content-type")??"application/json",y=[...g.headers.entries()].map(([T,w])=>`${T}: ${w}`).join(", ");if(this._logService.info(`[${en}] <<< CAPI response: status=${g.status}, contentType=${h}, headers=[${y}]`),t.writeHead(g.status,{"Content-Type":h}),!g.body){t.end();return}let I=g.body.getReader(),S=a&&l?nc.createWriteStream(V(a,`res-${l}-${Date.now()}.txt`)):void 0,C="",_={};try{for(;;){let{done:T,value:w}=await I.read();if(T||d.clientGone)break;if(w&&w.byteLength>0){let W=Buffer.from(w);t.write(W),S&&S.write(W),C+=W.toString("utf8");let R;for(;(R=C.indexOf(`
`))>=0;){let L=C.slice(0,R).trimEnd();if(C=C.slice(R+1),L.startsWith("event:")){let D=L.slice(6).trim();_[D]=(_[D]??0)+1}}}}}finally{try{I.releaseLock()}catch{}S?.end()}if(Object.keys(_).length){let T=Object.entries(_).map(([w,W])=>`${w}=${W}`).join(", ");this._logService.info(`[${en}] <<< SSE event counts: ${T}`)}t.end()}catch(g){if(d.clientGone){this._logService.info(`[${en}] client disconnected during upstream call`);return}if(g instanceof wr){this._logService.error(`[${en}] CAPI error: status=${g.status}, message=${g.message}`);let h=jm(Vm(g));Dp(t,g.status,"api_error",`${g.message} ${h}`);return}this._logService.error(`[${en}] upstream error: ${g instanceof Error?g.message:String(g)}`),Dp(t,502,"api_error",g instanceof Error?g.message:String(g))}finally{t.removeListener("close",c),r.inFlight.delete(d)}}};tc=A([b(0,O),b(1,gt)],tc);function jW(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!==WW)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 KW(o){let n={},e=o["user-agent"];return typeof e=="string"&&e.length>0&&(n["User-Agent"]=GW(e)),n}function GW(o){let n=o.indexOf("/");return n===-1?`${IM}/${o}`:`${IM}${o.substring(n)}`}function kr(o){let n=/^\s*\S*sh(?:\.exe)?\s+-[a-z]*c\s+([\s\S]+)$/i.exec(o);return n?JW(n[1].trim()):o}function JW(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 Hy(o=new Set,n=new Mn){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 w_(o){o.itemToPartId.clear(),o.itemToToolCall.clear(),o.itemToReasoningPartId.clear(),o.declinedToolCalls.clear(),o.pendingPreflight=void 0}function Fy(o){let n=o.pendingPreflight;return n?(o.pendingPreflight=void 0,n.completion):[]}function R_(o){let n=[];for(let e of o)e.type==="text"&&n.push(e.text);return n.join(`

`)}function x_(o,n,e){return`${o}:${n}:${e}`}function A_(o,n,e){let t=o.itemToReasoningPartId.get(e);if(t)return{partId:t,actions:[]};let r=F();return o.itemToReasoningPartId.set(e,r),{partId:r,actions:[{type:"chat/responsePart",turnId:n,part:{kind:"reasoning",id:r,content:""}}]}}function $y(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 Wy(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 Mp(o){return o.map(n=>`${Wy([n])}
${n.diff}`.trim()).join(`

`)}function bM(o){return typeof o=="string"?o:JSON.stringify(o,null,2)}function _M(o){return JSON.stringify(o,null,2)}function wM(o){return o?.map(n=>n.type==="inputText"?n.text:n.imageUrl).join(`
`)??""}function YW(o,n){if(n)return n;if(!o)return"";let e=o.content.map(bM).join(`
`),t=o.structuredContent!==null?bM(o.structuredContent):"";return[e,t].filter(Boolean).join(`
`)}function RM(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 TM(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 QW(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?TM(t[0]):t.map((r,i)=>`Agent ${i+1}: ${TM(r)}`).join(`
`)}function xM(o,n,e){o.currentTurnId=n.turn.id,w_(o);let t=e,r=n.turn.items?.[0];if(r&&r.type==="userMessage"){let i=R_(r.content);i.length>0&&(t=i)}return[{type:"chat/turnStarted",turnId:n.turn.id,startedAt:typeof n.turn.startedAt=="number"?new Date(n.turn.startedAt*1e3).toISOString():new Date().toISOString(),message:{text:t,origin:{kind:"user"}}}]}function AM(o,n){return A_(o,n.turnId,x_(n.itemId,"summary",n.summaryIndex)).actions}function PM(o,n){let e=A_(o,n.turnId,x_(n.itemId,"summary",n.summaryIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function EM(o,n){let e=A_(o,n.turnId,x_(n.itemId,"text",n.contentIndex));return[...e.actions,{type:"chat/reasoning",turnId:n.turnId,partId:e.partId,content:n.delta}]}function XW(o,n){for(let e of[...o.itemToReasoningPartId.keys()])e.startsWith(`${n}:`)&&o.itemToReasoningPartId.delete(e)}function kM(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 DM(o,n){if(n.item.type==="commandExecution"){let r=o.pendingPreflight;if(r&&r.turnId===n.turnId&&r.command===kr(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=Fy(o),t=ZW(o,n);return e.length===0?t:[...e,...t]}function ZW(o,n){if(n.item.type==="agentMessage"){let e=F();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=F();o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"shell",output:""});let t=kr(n.item.command??"");return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"shell",displayName:"Run shell command",_meta:At({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:At({toolKind:"terminal"})}]}if(n.item.type==="webSearch"){let e=F();o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"web_search",output:""});let t=$y(n.item.query,n.item.action);return[{type:"chat/toolCallStart",turnId:n.turnId,toolCallId:e,toolName:"web_search",displayName:"Web search",_meta:At({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:At({toolKind:"search"})}]}if(n.item.type==="fileChange"){let e=F(),t=Mp(n.item.changes);o.itemToToolCall.set(n.item.id,{toolCallId:e,turnId:n.turnId,toolName:"file_edit",output:t});let r=Wy(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=F(),t=`${n.item.server}.${n.item.tool}`,r=_M(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=F(),t=n.item.namespace?`${n.item.namespace}.${n.item.tool}`:n.item.tool,r=_M(n.item.arguments),i=wM(n.item.contentItems),a=n.item.namespace===null&&o.serverToolNames.has(n.item.tool)?void 0:o.clientToolSet.ownerOf(n.item.tool),l=Rr(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=F(),t=RM(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 MM(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 OM(o,n){let e=o.itemToToolCall.get(n.itemId);return e?(e.output=Mp(n.changes),[{type:"chat/toolCallContentChanged",turnId:e.turnId,toolCallId:e.toolCallId,content:e.output?[{type:"text",text:e.output}]:[]}]):[]}function LM(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 NM(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 UM(o,n){let e=o.itemToPartId.get(n.itemId);return e?[{type:"chat/delta",turnId:n.turnId,partId:e,content:n.delta}]:[]}function P_(o,n){if(n.item.type==="agentMessage")return o.itemToPartId.delete(n.item.id),[];if(n.item.type==="reasoning")return XW(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=kr(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=Fy(o);return o.pendingPreflight={toolCallId:e.toolCallId,turnId:e.turnId,command:s,completion:d},c}return[...Fy(o),...d]}if(n.item.type==="webSearch"){let r=$y(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=Mp(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=YW(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=wM(n.item.contentItems)||e.output,s=i?[{type:"text",text:i}]:void 0,a=r?Rr(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=RM(n.item.tool),i=n.item.status==="completed",s=QW(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 FM(o,n,e){o.currentTurnId=void 0,o.itemToPartId.clear(),o.itemToReasoningPartId.clear();let t=Fy(o),r=[...o.itemToToolCall.values()];o.itemToToolCall.clear();let i=n.turn.id,s=n.turn.status,a=typeof n.turn.durationMs=="number"&&Number.isFinite(n.turn.durationMs)&&n.turn.durationMs>=0?n.turn.durationMs:typeof n.turn.startedAt=="number"&&typeof n.turn.completedAt=="number"?Math.max(0,(n.turn.completedAt-n.turn.startedAt)*1e3):typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0,l=r.map(d=>({type:"chat/toolCallComplete",turnId:d.turnId,toolCallId:d.toolCallId,result:{success:!1,pastTenseMessage:`Stopped ${d.toolName}`,content:d.output?[{type:"text",text:d.output}]:void 0,error:{message:s==="interrupted"?"Turn interrupted before the tool completed":"Turn completed before the tool reported completion"}}}));if(s==="failed"&&n.turn.error){let d=n.turn.error.message??"Codex turn failed";return[...t,...l,{type:"chat/error",turnId:i,duration:a,error:{errorType:"CodexError",...Wl(d)}},{type:"chat/turnComplete",turnId:i,duration:a}]}return s==="interrupted"?[...t,...l,{type:"chat/turnCancelled",turnId:i,duration:a}]:[...t,...l,{type:"chat/turnComplete",turnId:i,duration:a}]}function HM(o){switch(o){case"completed":return"complete";case"interrupted":return"cancelled";case"failed":return"error";default:return"complete"}}function $M(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 WM(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 qM from"crypto";import*as BM from"fs";import*as zM from"os";var eq=[];function E_(o,n){let e=[],t=[],r=[o];if(n&&n.length>0)for(let s of n)switch(s.type){case"resource":{let a=v.parse(s.uri);a.scheme==="file"?r.push(`@${a.fsPath}`):r.push(a.toString());break}case"embeddedResource":{if(s.contentType.startsWith("image/")){let a=tq(s.contentType),l=V(zM.tmpdir(),`codex-img-${qM.randomBytes(8).toString("hex")}${a}`);try{BM.writeFileSync(l,Buffer.from(s.data,"base64")),e.push(l),t.push({type:"localImage",path:l})}catch{}break}if(nq(s.contentType)){let a=rq(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:eq}),{input:t,cleanupPaths:e}}function tq(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 nq(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 rq(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 VM(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 jM(o,n,e){let t={};for(let r of o)t[r.id]={answers:oq(e?.[r.id],n)};return{answers:t}}function qy(o){let n={};for(let e of o)n[e.id]={answers:[]};return{answers:n}}function oq(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 KM(o){let n=[];for(let e of o.turns??[]){let t=iq(e);t&&n.push(t)}return n}function iq(o){let n="",e=[],t,r=()=>{t&&(e.push(k_(t.item,t.command)),t=void 0)};for(let i of o.items??[]){if(i.type==="commandExecution"){let s=kr(i.command??"");if(t&&t.command===s){t=void 0,e.push(k_(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(k_(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:F(),content:i.text}):i.type==="webSearch"?e.push(sq(i)):i.type==="fileChange"&&e.push(aq(i))}if(r(),!(!n&&e.length===0))return{id:o.id,message:{text:n,origin:{kind:"user"}},responseParts:e,usage:void 0,state:HM(o.status)}}function GM(o){return o?[{type:"text",text:o}]:void 0}function k_(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:F(),toolName:"shell",displayName:"Run shell command",_meta:At({toolKind:"terminal"}),invocationMessage:n,toolInput:n,confirmed:"not-needed",success:e,pastTenseMessage:i,content:GM(t),error:e?void 0:{message:r!==null?`Exit code ${r}`:"Command failed"}}}}function sq(o){let n=$y(o.query,o.action);return{kind:"toolCall",toolCall:{status:"completed",toolCallId:F(),toolName:"web_search",displayName:"Web search",_meta:At({toolKind:"search"}),invocationMessage:n,toolInput:n,confirmed:"not-needed",success:!0,pastTenseMessage:`Searched ${n}`}}}function aq(o){let n=o.status==="completed",e=Wy(o.changes)||"Apply file changes",t=Mp(o.changes);return{kind:"toolCall",toolCall:{status:"completed",toolCallId:F(),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:GM(t),error:n?void 0:{message:`Patch ${o.status}`}}}}var Kn=class{constructor(n,e){this._sessionDataService=n;this._logService=e}static{this.KEY_THREAD_ID="codex.threadId"}static{this.KEY_CWD="codex.cwd"}static{this.KEY_MODEL="codex.model"}async write(n,e){try{let t=this._sessionDataService.openDatabase(n),r=t.object;try{let i=[];e.threadId!==void 0&&i.push(r.setMetadata(Kn.KEY_THREAD_ID,e.threadId)),e.cwd!==void 0&&i.push(r.setMetadata(Kn.KEY_CWD,e.cwd.toString())),e.modelId!==void 0&&i.push(r.setMetadata(Kn.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(Kn.KEY_THREAD_ID),e.object.getMetadata(Kn.KEY_CWD),e.object.getMetadata(Kn.KEY_MODEL)]);return{threadId:t??void 0,cwd:r?v.parse(r):void 0,modelId: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)}`),{}}}};Kn=A([b(0,nt),b(1,O)],Kn);function JM(o,n){return o==="copilot"?n==="vscode-proxy":n!=="vscode-proxy"}function YM(o,n,e){return{threadId:n,modelProvider:o==="copilot"?"vscode-proxy":"openai",...Object.keys(e).length>0?{config:{mcp_servers:e}}:{}}}function QM(o,n,e,t){if(o==="copilot"!=(e!==void 0))throw new Error(`Codex ${o} launch received an invalid proxy configuration`);let r={...n,[Vr]:jr};e&&(r.OPENAI_API_KEY=e.nonce);let i=[...e?['model_provider="vscode-proxy"','model_providers.vscode-proxy.name="VS Code Proxy"',`model_providers.vscode-proxy.base_url="${e.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"]:[],`shell_environment_policy.set.${Vr}="${jr}"`,"features.tool_call_mcp_elicitation=false",...e?["features.image_generation=false"]:[]];return{env:r,args:["app-server",...i.flatMap(s=>["-c",s]),...t]}}function XM(o){return o.account?.type==="chatgpt"?{usageSource:"openai",status:"signedIn",authType:"chatgpt",planType:o.account.planType}:o.account?.type==="apiKey"?{usageSource:"openai",status:"signedIn",authType:"apiKey"}:o.account?{usageSource:"openai",status:"signedIn",authType:"other"}:{usageSource:"openai",status:"signedOut"}}function ZM(o,n){return o==="openai"&&n.status==="signedOut"?"copilot":o}function eO(o,n){return o==="openai"?n:{...n,usageSource:"copilot"}}function tO(o,n,e){return[o==="openai"?{...n,required:!1}:n,e]}var By=["default","auto-review","full-access"],rc="default";function zy(o){switch(o){case"default":case"auto-review":case"full-access":return o;default:return}}function Vy(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 D_(o){for(let n of By){let e=Vy(n);if(e.approvalPolicy===o.approvalPolicy&&e.sandboxMode===o.sandboxMode&&e.approvalsReviewer===o.approvalsReviewer)return n}}function lq(o){switch(o){case"never":case"on-request":case"on-failure":case"untrusted":return o;default:return}}function dq(o){switch(o){case"read-only":case"workspace-write":case"danger-full-access":return o;default:return}}function jy(o,n){let e=zy(o?.["codex.permissionsPreset"]);return e?Vy(e):{approvalPolicy:lq(o?.["codex.approvalPolicy"])??n.approvalPolicy,sandboxMode:dq(o?.["codex.sandboxMode"])??n.sandboxMode,approvalsReviewer:"user"}}function Ky(o,n){let e=zy(o?.["codex.permissionsPreset"]);if(e)return{"codex.permissionsPreset":e};let t=jy(o,n),r=D_(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":rc}}function rO(o){if(Array.isArray(o))return o.filter(n=>typeof n=="string"&&n.length>0)}function oO(o){return typeof o=="boolean"?o:void 0}function iO(o){switch(o){case"disabled":case"cached":case"live":return o;default:return}}function M_(o){switch(o){case"none":case"minimal":case"low":case"medium":case"high":case"xhigh":return o;default:return}}function sO(o){switch(o){case"none":case"friendly":case"pragmatic":return o;default:return}}function aO(o){switch(o){case"auto":case"concise":case"detailed":case"none":return o;default:return}}function lO(o){return o==="plan"?"plan":"default"}function cq(o){switch(o){case"inProgress":return"in_progress";case"timedOut":return"timed_out";default:return o}}function dO(o){return o==="unifiedExec"?"unified_exec":o}function uq(o){switch(o){case"socks5Tcp":return"socks5_tcp";case"socks5Udp":return"socks5_udp";default:return o}}function pq(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 fq(o){switch(o.type){case"command":return{type:"command",source:dO(o.source),command:o.command,cwd:o.cwd};case"execve":return{type:"execve",source:dO(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:uq(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:pq(o.permissions)}}}function cO(o){let n={id:o.reviewId,turn_id:o.turnId,started_at_ms:o.startedAtMs,status:cq(o.review.status),action:fq(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 uO(o){switch(o.type){case"command":return{title:"Run command",detail:kr(o.command),toolKind:"terminal"};case"execve":return{title:"Run program",detail:kr([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 gq(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 pO(o,n){let e=o.detail?.trim(),t="**Auto-review denied**",r=[e?`\u26A0\uFE0F ${t} \u2014 ${o.title}: ${gq(e)}`:`\u26A0\uFE0F ${t} \u2014 ${o.title}`],i=n?.trim();return i&&r.push("",...i.split(`
`)),`

${r.map(a=>a?`> ${a}`:">").join(`
`)}
`}var hq={name:"vscode_agent_host",title:"VS Code Agent Host",version:"0.1.0"},fO="thinkingLevel",yq="vscode_codex",ic=["minimal","low","medium","high"],vq={serverTools:{listChanged:!0},serverResources:{}},gO="mcp_tool_call_approval_",Sq="Allow",Cq="__codex_mcp_decline__",Iq="/responses";function bq(){let o=Pt.definition.mode.protocol,n=(o.enum??[]).flatMap((e,t)=>e==="autopilot"?[]:[t]);return ae({...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 Gy=Hn({"codex.permissionsPreset":ae({type:"string",title:f(2211,null),description:f(2218,null),enum:[...By],enumLabels:[f(2214,null),f(2212,null),f(2216,null)],enumDescriptions:[f(2215,null),f(2213,null),f(2217,null)],default:rc,sessionMutable:!0}),"codex.approvalPolicy":ae({type:"string",title:f(2197,null),description:f(2206,null),enum:["never","on-request","on-failure","untrusted"],enumLabels:[f(2198,null),f(2202,null),f(2200,null),f(2204,null)],enumDescriptions:[f(2199,null),f(2203,null),f(2201,null),f(2205,null)],default:"on-request",sessionMutable:!0}),"codex.sandboxMode":ae({type:"string",title:f(2233,null),description:f(2240,null),enum:["read-only","workspace-write","danger-full-access"],enumLabels:[f(2236,null),f(2238,null),f(2234,null)],enumDescriptions:[f(2237,null),f(2239,null),f(2235,null)],default:"workspace-write",sessionMutable:!0}),"codex.webSearchMode":ae({type:"string",title:f(2241,null),description:f(2245,null),enum:["disabled","cached","live"],enumLabels:[f(2243,null),f(2242,null),f(2244,null)],default:"disabled",sessionMutable:!1}),"codex.modelReasoningEffort":ae({type:"string",title:f(2207,null),description:f(2208,null),enum:[...ic],enumLabels:ic.map(ta),enumDescriptions:ic.map(o=>na(o)??""),default:"medium",sessionMutable:!0}),mode:bq(),"codex.personality":ae({type:"string",title:f(2219,null),description:f(2226,null),enum:["none","friendly","pragmatic"],enumLabels:[f(2222,null),f(2220,null),f(2224,null)],enumDescriptions:[f(2223,null),f(2221,null),f(2225,null)],default:"none",sessionMutable:!0}),"codex.reasoningSummary":ae({type:"string",title:f(2227,null),description:f(2232,null),enum:["auto","concise","detailed","none"],enumLabels:[f(2228,null),f(2229,null),f(2230,null),f(2231,null)],default:"auto",sessionMutable:!0}),"codex.additionalDirectories":ae({type:"array",title:f(2194,null),description:f(2196,null),items:{type:"string",title:f(2195,null)},enumDynamic:!0,default:[],sessionMutable:!0}),"codex.networkAccessEnabled":ae({type:"boolean",title:f(2209,null),description:f(2210,null),default:!1,sessionMutable:!0}),permissions:Pt.definition.permissions}),_q=Hn({mode:Gy.definition.mode,"codex.permissionsPreset":Gy.definition["codex.permissionsPreset"],permissions:Pt.definition.permissions}),Gn={"codex.permissionsPreset":rc,"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"},Tq=6e4,ca={id:"codex",displayName:"Codex",devOverrideEnvVar:GR,hasSeparateMuslLinuxPackage:!1};function wq(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 mO(o){return!o||o.length===0?"":o.map(n=>`${n.name}\0${n.description??""}\0${JSON.stringify(n.inputSchema??null)}`).sort().join("")}function O_(o){return Object.keys(o).sort().map(e=>`${e}\0${JSON.stringify(o[e])}`).join("")}var L_=class{constructor(n,e,t,r,i){this._getSession=n;this.clientId=e;this.displayName=t;this._onToolsSet=r;this._syncCustomizations=i;this._customizations=[]}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 this._customizations}set customizations(n){this._customizations=n,this._syncCustomizations(n)}};function Rq(o){switch(o){case"accept":case"acceptForSession":case"decline":case"cancel":return o;default:return"decline"}}var oc=class extends x{constructor(e,t,r,i,s,a,l,d,c,u,p){super();this._logService=e;this._copilotApiService=t;this._codexProxyService=r;this._configurationService=i;this._gitHubEndpointService=s;this._agentSdkDownloader=a;this._productService=l;this._pluginManager=d;this._fileService=c;this._environmentService=u;this._instantiationService=p;this.id=Ff;this._onDidSessionProgress=this._register(new E);this.onDidSessionProgress=this._onDidSessionProgress.event;this._onDidMaterializeSession=this._register(new E);this.onDidMaterializeSession=this._onDidMaterializeSession.event;this._onDidRequireAuth=this._register(new E);this.onDidRequireAuth=this._onDidRequireAuth.event;this._onMcpNotification=this._register(new E);this.onMcpNotification=this._onMcpNotification.event;this._models=yn(this,[]);this.models=this._models;this._openAIAccountState={usageSource:"openai",status:"signedOut"};this._providerConfigurationValues={};this._providerConfigurationWrite=Promise.resolve();this._providerConfigurationReady=!1;this._sessions=new Map;this._sessionIdByThreadId=new Map;this._subagentsByThreadId=new Map;this._mcpInventory=new Map;this._mcpAuthTokens=new Map;this._mcpAuthServerUrlsByResource=new Map;this._connection={kind:"idle"};this._connectionGeneration=0;this._usageSourceValidation=Promise.resolve();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,a)=>this._sendMessage(e,t,i,s,r),abort:e=>this._abort(e),changeModel:(e,t)=>this._changeModel(e,t),changeAgent:(e,t)=>Promise.resolve(),getMessages:e=>this.getSessionMessages(e)};this._metadataStore=this._instantiationService.createInstance(Kn),this._usageSource=this._resolveUsageSource(),this._register(this._configurationService.onDidRootConfigChange(()=>{let g=this._resolveUsageSource();g!==this._usageSource?this._requestUsageSourceChange(g):this._pendingUsageSource=void 0,this._queueProviderConfigurationWrite()})),this._refreshProviderConfiguration(),this._usageSource==="openai"&&(this._usageSourceValidation=this._validateOpenAIUsageSource())}async _validateOpenAIUsageSource(){let e;try{let r=await this._ensureConnection(!0);e=await this._refreshAccount(r.client,!1)}catch(r){if(this._usageSource!=="openai")return;let i=r instanceof Error?r.message:String(r);this._setOpenAIAccountState({usageSource:"openai",status:"error",error:i},!1);return}if(this._usageSource!=="openai")return;let t=ZM(this._usageSource,e);if(t==="copilot"){this._logService.info("[Codex] OpenAI is signed out; falling back to GitHub Copilot"),this._configurationService.updateRootConfig({codexUsageSource:t});return}e.status==="signedIn"&&this._queueModelRefresh()}_setOpenAIAccountState(e,t=!0){this._openAIAccountState=e}_resolveUsageSource(){return this._configurationService.getRootValue(Dn,"codexUsageSource")??"copilot"}_requestUsageSourceChange(e){if(this._hasActiveTurns()){this._pendingUsageSource=e,this._logService.info(`[Codex] Deferring usage source change to '${e}' until active turns finish`);return}if(e==="openai"){this._applyUsageSourceChange(e,!1,!1),this._usageSourceValidation=this._validateOpenAIUsageSource();return}this._applyUsageSourceChange(e)}_applyUsageSourceChange(e,t=!0,r=!0){let i=this._usageSource;this._pendingUsageSource=void 0,this._usageSource=e,this._disposeConnection();for(let s of this._sessions.values())this._resetSessionForUsageSourceChange(s,e,i);this._subagentsByThreadId.clear(),this._models.set([],void 0),r&&(e==="openai"?this._queueModelRefresh():this._githubToken?this._queueModelRefresh():this._onDidRequireAuth.fire({resource:this._gitHubEndpointService.getCopilotResource().resource,reason:"required"}))}_resetSessionForUsageSourceChange(e,t,r){e.threadId!==void 0&&(this._logService.info(`[Codex:${e.sessionId}] replacing ${r??"incompatible-provider"} thread ${e.threadId} with a fresh ${t} thread`),this._sessionIdByThreadId.delete(e.threadId),e.threadId=void 0,e.materializePromise=void 0,e.materializedToolsSig=void 0,e.materializedMcpSig=void 0,e.needsResume=!1,e.hostTurnIdByAppTurnId.clear(),e.codexTurnIdByHostTurnId.clear())}_hasActiveTurns(){return[...this._sessions.values()].some(e=>e.currentTurnId!==void 0)||[...this._subagentsByThreadId.values()].some(e=>e.session.currentTurnId!==void 0)}_applyPendingUsageSourceIfIdle(){let e=this._pendingUsageSource;e&&!this._hasActiveTurns()&&this._applyUsageSourceChange(e)}getProtectedResources(){return tO(this._usageSource,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,this._usageSource==="openai"?(this._refreshProviderConfiguration(),!0):(r&&this._connection.kind==="ready"&&this._connection.proxyHandle?(this._connection.proxyHandle.setToken(t),this._queueModelRefresh()):r&&this._queueModelRefresh(),this._logService.info("[Codex] Auth token updated"),this._refreshProviderConfiguration(),!0)}async handleAuthenticationToken(e){let t=Zi(e.resource);if(t===void 0)return!1;let r=new Set(this._mcpAuthServerUrlsByResource.get(t)??[]);if(this._isConfiguredHttpServerUrl(t)&&r.add(t),r.size===0)return!1;let i=!1;for(let s of r)this._mcpAuthTokens.get(s)!==e.token&&(this._mcpAuthTokens.set(s,e.token),i=!0);return i&&(this._logService.info(`[Codex] stored MCP auth token for ${e.resource}; reconnecting affected sessions`),await this._reconnectSessionsForMcpAuth(r)),!0}_isConfiguredHttpServerUrl(e){return Object.values(kp(this._configurationService.getRootValue(tt,mi))).some(t=>t.url!==void 0&&Zi(t.url)===e)?!0:[...this._sessions.values()].some(t=>[...this._httpMcpServerUrls(t).values()].includes(e))}async _reconnectSessionsForMcpAuth(e){for(let t of this._sessions.values())if(!(t.disposed||t.threadId===void 0)&&[...this._httpMcpServerUrls(t).values()].some(r=>e.has(r)))if(t.firstTurnSent)t.needsResume=!0;else try{await this._restartThreadWithCurrentTools(t)}catch(r){this._logService.warn(`[Codex:${t.sessionId}] reconnect after MCP auth failed: ${r instanceof Error?r.message:String(r)}`)}}refreshModels(){return this._modelsRefreshPromise??this._queueModelRefresh()}_queueModelRefresh(){let e=this._refreshModels().finally(()=>{this._modelsRefreshPromise===e&&(this._modelsRefreshPromise=void 0)});return this._modelsRefreshPromise=e,e}_ensureAuthenticated(){if(this._usageSource==="openai")return;let e=this._githubToken;if(!e)throw new N(_r,"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:{[fO]:{type:"string",title:f(2193,null),description:f(2192,null),default:"medium",enum:[...ic],enumLabels:ic.map(ta),enumDescriptions:ic.map(e=>na(e)??"")}}}}_getReasoningEffort(e){let t=M_(e.model?.config?.[fO]);if(t)return t;let r=this._configurationService.getSessionConfigValues(e.sessionUri.toString());return M_(r?.["codex.modelReasoningEffort"])??Gn["codex.modelReasoningEffort"]}_readSessionConfig(e){return Gy.validateOrDefault(this._configurationService.getSessionConfigValues(e.sessionUri.toString()),Gn)}_resolveSessionPermissions(e){let t=this._configurationService.getSessionConfigValues(e.sessionUri.toString()),r={approvalPolicy:Gn["codex.approvalPolicy"],sandboxMode:Gn["codex.sandboxMode"]};return jy(Ky(t,r),r)}_sandboxPolicy(e,t,r){if(r==="danger-full-access")return{type:"dangerFullAccess"};let i=oO(t["codex.networkAccessEnabled"])??Gn["codex.networkAccessEnabled"];return r==="read-only"?{type:"readOnly",networkAccess:!1}:{type:"workspaceWrite",writableRoots:[...e.workingDirectory?[e.workingDirectory.fsPath]:[],...rO(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=sO(r["codex.personality"])??Gn["codex.personality"],p=aO(r["codex.reasoningSummary"])??Gn["codex.reasoningSummary"],h={mode:lO(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:h,...d?{runtimeWorkspaceRoots:d}:{}}}async _refreshModels(){let e=this._usageSource;if(e==="openai"){await this._refreshOpenAIModels();return}let t=this._githubToken;if(!t){this._models.set([],void 0);return}try{let r=`${yq}/${this._productService.version}`,i=await this._copilotApiService.models(t,{headers:{"User-Agent":r},suppressIntegrationId:!0});if(this._usageSource!==e||this._githubToken!==t)return;let s=this._createReasoningEffortConfigSchema(),a=i.filter(l=>l.supported_endpoints?.includes(Iq)).sort((l,d)=>Number(d.is_chat_default)-Number(l.is_chat_default)).map(l=>({provider:this.id,id:l.id,name:l.name??l.id,maxContextWindow:l.capabilities?.limits?.max_context_window_tokens,maxOutputTokens:l.capabilities?.limits?.max_output_tokens,maxPromptTokens:l.capabilities?.limits?.max_prompt_tokens,supportsVision:!!l.capabilities?.supports?.vision,configSchema:s,policyState:l.policy?.state,_meta:vd(yd(l.billing),typeof l.model_picker_price_category=="string"?l.model_picker_price_category:void 0)}));this._models.set(a,void 0)}catch(r){this._logService.warn(`[Codex] Failed to refresh models: ${r instanceof Error?r.message:String(r)}`)}}async _refreshOpenAIModels(){try{let e=await this._ensureConnection();if(e.usageSource!=="openai")return;let t=[],r=null;do{let a=await e.client.request("model/list",{cursor:r,limit:100,includeHidden:!1});t.push(...a.data),r=a.nextCursor}while(r!==null);let i=this._createReasoningEffortConfigSchema(),s=t.sort((a,l)=>Number(l.isDefault)-Number(a.isDefault)).map(a=>({provider:this.id,id:a.model,name:a.displayName,supportsVision:a.inputModalities.includes("image"),configSchema:i}));this._usageSource==="openai"&&this._models.set(s,void 0)}catch(e){this._logService.warn(`[Codex] Failed to refresh OpenAI models: ${e instanceof Error?e.message:String(e)}`)}}async _ensureConnection(e=!1){if(this._connection.kind==="ready")return Promise.resolve(this._connection);if(this._connection.kind==="starting")return this._connection.promise;if(!e&&this._usageSource==="openai"){let l=this._usageSourceValidation;for(await l;l!==this._usageSourceValidation;)l=this._usageSourceValidation,await l}let t=this._ensureAuthenticated(),r=this._usageSource,i=this._connectionGeneration,a=this._startConnection(r,t).then(l=>{if(i!==this._connectionGeneration||r!==this._usageSource){l.client.dispose(),l.proxyHandle?.dispose();try{l.child.kill("SIGKILL")}catch{}throw new Error("Codex usage source changed while app-server was starting")}return this._connection={kind:"ready",...l},l}).catch(l=>{throw i===this._connectionGeneration&&(this._connection={kind:"idle"}),l});return this._connection={kind:"starting",promise:a},a}async _resolveSdkRoot(){if(this._agentSdkDownloader.isAvailable(ca))return this._agentSdkDownloader.loadSdkRoot(ca,ke.None);let e=await Eq();return e?(this._logService.info(`[Codex] resolving SDK from repo node_modules (dev fallback): ${e}`),e):this._agentSdkDownloader.loadSdkRoot(ca,ke.None)}async _startConnection(e,t){let r=await this._resolveSdkRoot(),i=Aq(process.platform,process.arch);if(!i)throw new Error(`Codex: unsupported platform ${process.platform}-${process.arch}`);let s=Pq(i);if(!s)throw new Error(`Codex: no binary triple known for sdkTarget '${i}'`);let a=process.platform==="win32"?"codex.exe":"codex",l=V(r,"node_modules",`@openai/codex-${i}`,"vendor",s,"bin",a);try{ao.accessSync(l,ao.constants.X_OK)}catch(C){throw new Error(`Codex binary not executable: ${l} (${C instanceof Error?C.message:String(C)})`)}let d;if(e==="copilot"){if(!t)throw new Error("Codex Copilot launch requires a GitHub token");d=await this._codexProxyService.start(t)}let c=xq(process.env[YR]),u=QM(e,process.env,d,c),p=u.env,g=process.env[JR];g&&(p.CODEX_HOME=g);let h=[...u.args];this._logService.info(`[Codex] spawning usageSource=${e} proxy=${d?"enabled":"disabled"} ${l} ${h.join(" ")}`);let y=mq(l,h,{env:p,stdio:["pipe","pipe","pipe"]});y.stderr.setEncoding("utf8"),y.stderr.on("data",C=>this._logService.info(`[Codex stderr] ${String(C).trimEnd()}`));let I=CM(y),S=new Ny(I,(C,_)=>{this._logService.info(`[CodexClient ${C}] ${_}`)});S.onExit(C=>{this._logService.warn(`[Codex] app-server exited code=${C.code} signal=${C.signal}`),this._handleConnectionLost()}),S.onTransportError(C=>{this._logService.error(`[Codex] transport error: ${C.message}`),this._handleConnectionLost()});try{await S.request("initialize",{clientInfo:hq,capabilities:{experimentalApi:!0,requestAttestation:!1,optOutNotificationMethods:null}}),S.notify("initialized",void 0),g&&d&&await S.request("account/login/start",{type:"apiKey",apiKey:d.nonce}),e==="openai"&&this._refreshAccount(S)}catch(C){S.dispose(),d?.dispose();try{y.kill("SIGKILL")}catch{}throw C}return this._registerIgnoredNotifications(S),this._register(S.onNotification("account/login/completed",()=>{})),this._register(S.onNotification("account/updated",()=>{this._usageSource==="openai"&&this._connection.kind==="ready"&&this._connection.client===S&&(this._refreshAccount(S),this._queueModelRefresh())})),this._register(S.onNotification("turn/started",C=>this._dispatchByThread(C.threadId,_=>this._handleTurnStartedNotification(_,C)))),this._register(S.onNotification("item/started",C=>this._dispatchByThread(C.threadId,_=>this._handleItemStarted(_,C)))),this._register(S.onNotification("item/agentMessage/delta",C=>this._dispatchByThread(C.threadId,_=>UM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/commandExecution/outputDelta",C=>this._dispatchByThread(C.threadId,_=>MM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/fileChange/patchUpdated",C=>this._dispatchByThread(C.threadId,_=>OM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/fileChange/outputDelta",C=>this._dispatchByThread(C.threadId,_=>LM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/mcpToolCall/progress",C=>this._dispatchByThread(C.threadId,_=>NM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/reasoning/summaryPartAdded",C=>this._dispatchByThread(C.threadId,_=>AM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/reasoning/summaryTextDelta",C=>this._dispatchByThread(C.threadId,_=>PM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("item/reasoning/textDelta",C=>this._dispatchByThread(C.threadId,_=>EM(_.mapState,this._withHostTurnId(_,C))))),this._register(S.onNotification("thread/tokenUsage/updated",C=>this._dispatchByThread(C.threadId,_=>kM(this._withHostTurnId(_,C))))),this._register(S.onNotification("item/completed",C=>this._dispatchItemCompleted(C))),this._register(S.onNotification("turn/completed",C=>this._dispatchTurnCompleted(C))),this._register(S.onNotification("guardianWarning",C=>this._dispatchByThread(C.threadId,_=>this._handleGuardianWarning(_,C)))),this._register(S.onNotification("item/autoApprovalReview/completed",C=>{this._handleGuardianReviewCompleted(S,C)})),this._register(S.onNotification("mcpServer/startupStatus/updated",C=>this._handleMcpStartupStatus(S,C.name,C.status,C.error))),this._register(S.onRequest("item/commandExecution/requestApproval",C=>this._handleCommandApprovalRequestRpc(C))),this._register(S.onRequest("item/fileChange/requestApproval",C=>this._handleFileChangeApprovalRequestRpc(C))),this._register(S.onRequest("item/permissions/requestApproval",C=>this._handlePermissionsApprovalRequestRpc(C))),this._register(S.onRequest("item/tool/call",C=>this._handleDynamicToolCallRpc(C))),this._register(S.onRequest("item/tool/requestUserInput",C=>this._handleUserInputRequestRpc(C))),this._register(S.onRequest("mcpServer/elicitation/request",C=>this._handleElicitationRequestRpc(C))),this._refreshMcpInventory(S),{client:S,usageSource:e,proxyHandle:d,child:y}}_buildSessionMcpServers(e){let t=kp(this._configurationService.getRootValue(tt,mi)),r=Ly(e.clientCustomizations.enabledPlugins());return pM({...t,...r},this._mcpAuthTokens)}_httpMcpServerUrls(e){let t=kp(this._configurationService.getRootValue(tt,mi)),r=Ly(e.clientCustomizations.enabledPlugins()),i=new Map;for(let[s,a]of Object.entries({...t,...r})){let l=a.url!==void 0?Zi(a.url):void 0;l!==void 0&&i.set(s,l)}return i}_mcpServerUrlForName(e){let t=kp(this._configurationService.getRootValue(tt,mi));if(t[e]?.url!==void 0)return t[e].url;for(let r of this._sessions.values()){let i=Ly(r.clientCustomizations.enabledPlugins());if(i[e]?.url!==void 0)return i[e].url}}_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:wq(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:qy(e.questions)};if(!r.currentTurnId)return this._logService.warn(`[Codex] user input request without an active turn for threadId=${e.threadId}; returning empty answers`),{result:qy(e.questions)};let i=e.questions.length===1&&e.questions[0].id.startsWith(gO)?e.questions[0]:void 0;if(i){let l=i.id.slice(gO.length),d=r.mapState.itemToToolCall.get(l);if(d)return this._handleMcpToolApprovalViaCard(r,i,d)}let s=F(),a=VM(s,e.questions);try{let l=await r.pendingUserInputs.registerAndFire(s,()=>{this._fire(r.sessionUri,{type:"chat/inputRequested",request:a})});return{result:jM(e.questions,l.response,l.answers)}}catch{return{result:qy(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"?Sq:Cq;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:T_()};if(!r.currentTurnId)return this._logService.warn(`[Codex] elicitation request without an active turn for threadId=${e.threadId}; declining`),{result:T_()};let i=F(),s=yM(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:vM(e,a.response,a.answers)}}catch(a){return this._logService.info(`[Codex] elicitation cancelled requestId=${i}: ${a instanceof Error?a.message:String(a)}`),{result:SM()}}}_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 xM(e.mapState,this._withHostTurn(e,t),e.lastPromptText),[]}_handleTurnCompletedNotification(e,t){let r=t.turn.id,i=this._hostTurnId(e,r),s=FM(e.mapState,this._withHostTurn(e,t),this._clearTurnStopWatch(e));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):DM(e.mapState,this._withHostTurnId(e,t))}_handleSteeredUserMessage(e,t){let r=R_(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,duration:this._clearTurnStopWatch(e)});let a=F();return i&&e.hostTurnIdByAppTurnId.set(i,a),e.currentTurnId=a,w_(e.mapState),r.push({type:"chat/turnStarted",turnId:a,startedAt:new Date().toISOString(),message:t.message,queuedMessageId:t.id}),this._startTurnStopWatch(e),r}_drainPendingSteering(e){if(e.pendingSteeringFlips.size===0)return;let t=[...e.pendingSteeringFlips.keys()];e.pendingSteeringFlips.clear();for(let r of t)this._fireSteeringConsumed(e,r)}_fireSteeringConsumed(e,t){this._onDidSessionProgress.fire({kind:"steering_consumed",chat:v.parse(pe(e.sessionUri)),id:t})}_registerIgnoredNotifications(e){let t=["thread/started","thread/status/changed","thread/settings/updated","thread/goal/updated","thread/goal/cleared","account/rateLimits/updated","remoteControl/status/changed","serverRequest/resolved","item/autoApprovalReview/started"];for(let r of t)this._register(e.onNotification(r,()=>{}))}async _refreshAccount(e,t=!0){try{let r=await e.request("account/read",{refreshToken:!1}),i=XM(r);return this._setOpenAIAccountState(i,t),this._logService.info(`[Codex] account/read accountType=${r.account?.type??"none"} requiresOpenaiAuth=${r.requiresOpenaiAuth}${i.planType?` planType=${i.planType}`:""}`),i}catch(r){let i=r instanceof Error?r.message:String(r);this._logService.warn(`[Codex] account/read failed: ${i}`);let s={usageSource:"openai",status:"error",error:i};return this._setOpenAIAccountState(s,t),s}}async _readProviderConfiguration(){let t=await(await this._ensureConnection()).client.request("config/read",{includeLayers:!0}),r=t.layers?.find(s=>s.name.type==="user"&&s.name.profile===null)??t.layers?.find(s=>s.name.type==="user"),i=r?.config&&typeof r.config=="object"&&!Array.isArray(r.config)?r.config:{};return{"codex.personality":this._readConfigurationValue(i,"personality")??"default","codex.autoReviewPolicy":this._readConfigurationValue(i,"auto_review.policy")??""}}async _writeProviderConfiguration(e,t){await(await this._ensureConnection()).client.request("config/batchWrite",{edits:e==="codex.autoReviewPolicy"&&t===""?[{keyPath:"auto_review",value:null,mergeStrategy:"replace"}]:e==="codex.personality"&&t==="default"?[{keyPath:"personality",value:null,mergeStrategy:"replace"}]:[{keyPath:e==="codex.personality"?"personality":"auto_review.policy",value:t,mergeStrategy:"replace"}],expectedVersion:null,reloadUserConfig:!0})}_refreshProviderConfiguration(){return this._providerConfigurationRefresh??=(async()=>{try{this._providerConfigurationValues=await this._readProviderConfiguration(),this._providerConfigurationReady=!0,this._configurationService.updateRootConfig(this._providerConfigurationValues)}catch(e){this._logService.warn(`[Codex] Failed to read config.toml: ${e instanceof Error?e.message:String(e)}`)}finally{this._providerConfigurationRefresh=void 0}})()}_queueProviderConfigurationWrite(){if(!this._providerConfigurationReady)return;let e=this._configurationService.getRootConfigValues?.()??{};for(let t of["codex.personality","codex.autoReviewPolicy"]){if(e[t]===this._providerConfigurationValues[t])continue;let r=e[t];r!==void 0&&(this._providerConfigurationWrite=this._providerConfigurationWrite.then(async()=>{this._providerConfigurationValues[t]!==r&&(await this._writeProviderConfiguration(t,r),this._providerConfigurationValues[t]=r)}).catch(i=>this._logService.error(`[Codex] Failed to update config.toml: ${i instanceof Error?i.message:String(i)}`)))}}_readConfigurationValue(e,t){let r=e;for(let i of t.split(".")){if(!r||Array.isArray(r)||typeof r!="object")return;r=r[i]}return r}_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=P_(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=P_(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:v.parse(pe(t.session.sessionUri)),toolCallId:t.toolCallId}),this._applyPendingUsageSourceIfIdle();return}this._dispatchByThread(e.threadId,r=>this._handleTurnCompletedNotification(r,e)),this._applyPendingUsageSourceIfIdle()}_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=v.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,taskPrompt:typeof r.prompt=="string"&&r.prompt.length>0?r.prompt:void 0}),this._logService.trace(`[Codex:${e.sessionId}] subagent spawned thread=${d} toolCall=${i.toolCallId} model=${a??"(default)"}`)}}_createSubagentSession(e,t){let r=new Mn;return{sessionId:e.sessionId,threadId:t,sessionUri:e.sessionUri,workingDirectory:e.workingDirectory,managedWorkingDirectory:void 0,mapState:Hy(new Set(this._serverToolHost?.toolNames??[]),r),pendingCommandApprovals:new Rt,acceptedForSession:e.acceptedForSession,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:r,pendingClientToolCalls:new Rt,pendingUserInputs:new Rt,materializedToolsSig:void 0,materializedMcpSig:void 0,firstTurnSent:!0,model:e.model,currentTurnId:void 0,turnStopWatch: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,clientCustomizations:new ec}}_fireSubagent(e,t){this._onDidSessionProgress.fire({kind:"action",resource:v.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=kr(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:Rq(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=uO(t.action);this._fire(i.sessionUri,{type:"chat/responsePart",turnId:s,part:{kind:"markdown",id:F(),content:pO(a,t.review.rationale)}});let l=F(),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:cO(t)}),this._fire(i.sessionUri,{type:"chat/toolCallComplete",turnId:s,toolCallId:l,result:{success:!0,pastTenseMessage:"Approved anyway"}})}catch(p){let g=p instanceof Error?p.message:String(p);this._logService.warn(`[Codex:${r}] approveGuardianDeniedAction failed for reviewId=${t.reviewId}: ${g}`),this._fire(i.sessionUri,{type:"chat/toolCallComplete",turnId:s,toolCallId:l,result:{success:!1,pastTenseMessage:"Approval failed",error:{message:g}}})}}}_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;if(t.currentTurnId=void 0,t.currentAppTurnId=void 0,i&&t.hostTurnIdByAppTurnId.delete(i),r){let s=this._clearTurnStopWatch(t);this._fire(t.sessionUri,{type:"chat/error",turnId:r,duration:s,error:{errorType:"CodexDisconnected",message:"Codex app-server disconnected; session must restart."}}),this._fire(t.sessionUri,{type:"chat/turnComplete",turnId:r,duration:s})}}for(let t of this._subagentsByThreadId.values())t.session.pendingCommandApprovals.denyAll("decline"),t.session.pendingClientToolCalls.rejectAll(new K),t.session.pendingUserInputs.rejectAll(new K),t.session.currentTurnId=void 0,t.session.currentAppTurnId=void 0;this._subagentsByThreadId.clear(),this._applyPendingUsageSourceIfIdle();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)}`)}}}_disposeConnection(){let e=this._connection;if(this._connectionGeneration++,this._connection={kind:"idle"},e.kind==="ready"){try{e.client.dispose()}catch{}try{e.proxyHandle?.dispose()}catch{}try{e.child.kill("SIGKILL")}catch{}}}getDescriptor(){return{provider:this.id,displayName:f(2248,null),description:this._usageSource==="openai"?f(2247,null):f(2246,null)}}_sessionUriFromChat(e){let t=Le(e);return t?v.parse(t.session):e}async createSession(e={}){this._logService.info(`[Codex DEBUG] createSession usageSource=${this._usageSource} accountStatus=${eO(this._usageSource,this._openAIAccountState).status} session=${e.session?.toString()??"(none)"} model=${e.model?.id??"(none)"} cwd=${e.workingDirectory?.toString()??"(none)"}`);let t=this._usageSourceValidation;for(await t;t!==this._usageSourceValidation;)t=this._usageSourceValidation,await t;if(this._ensureAuthenticated(),e.fork)return this._forkSession(e,e.fork);let r=this._supportedModelOrUndefined(e.model),i=e.session?M.id(e.session):F(),s=e.session??M.uri(this.id,i),a=this._sessions.get(i);if(a)return a.model=r??a.model,{session:s,workingDirectory:a.workingDirectory??e.workingDirectory,provisional:a.threadId===void 0};let l=new Mn,d={sessionId:i,threadId:void 0,sessionUri:s,workingDirectory:e.workingDirectory,managedWorkingDirectory:void 0,mapState:Hy(new Set(this._serverToolHost?.toolNames??[]),l),pendingCommandApprovals:new Rt,acceptedForSession:new Set,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:l,pendingClientToolCalls:new Rt,pendingUserInputs:new Rt,materializedToolsSig:void 0,materializedMcpSig:void 0,firstTurnSent:!1,model:r,currentTurnId:void 0,turnStopWatch: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,clientCustomizations:new ec};return this._sessions.set(i,d),this._schedulePrewarm(d),{session:s,workingDirectory:e.workingDirectory,provisional:!0}}_createResumedSessionEntry(e,t,r,i,s){let a=new Mn;return{sessionId:e,threadId:t,sessionUri:r,workingDirectory:i,managedWorkingDirectory:void 0,mapState:Hy(new Set(this._serverToolHost?.toolNames??[]),a),pendingCommandApprovals:new Rt,acceptedForSession:new Set,handledGuardianReviews:new Set,pendingGuardianReviewCards:new Set,pendingSteeringFlips:new Map,clientToolSet:a,pendingClientToolCalls:new Rt,pendingUserInputs:new Rt,materializedToolsSig:void 0,materializedMcpSig:void 0,firstTurnSent:!0,model:s,currentTurnId:void 0,turnStopWatch: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,clientCustomizations:new ec}}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(M.id(t.session)),l=a?.codexTurnIdByHostTurnId.get(t.turnId)??t.turnId,d=$M(s.map(L=>L.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(),g=this._supportedModelOrUndefined(e.model),h=this._configurationService.getSessionConfigValues(t.session.toString()),y={approvalPolicy:Gn["codex.approvalPolicy"],sandboxMode:Gn["codex.sandboxMode"]},{approvalPolicy:I,sandboxMode:S,approvalsReviewer:C}=jy(Ky({...h,...e.config},y),y),_=await p.client.request("thread/fork",{threadId:i,...g?{model:g.id}:{},approvalPolicy:I,sandbox:S,approvalsReviewer:C}),T=_.thread.id;if(u>0)try{await p.client.request("thread/rollback",{threadId:T,numTurns:u})}catch(L){let D=L instanceof Error?L.message:String(L);this._logService.warn(`[Codex:${T}] fork rollback failed (numTurns=${u}); discarding fork: ${D}`);try{await p.client.request("thread/archive",{threadId:T})}catch(z){this._logService.warn(`[Codex:${T}] failed to archive orphaned fork after rollback failure: ${z instanceof Error?z.message:String(z)}`)}throw new Error(`Failed to fork codex session ${i}: could not roll back forked thread ${T} to the requested turn (${D})`)}let w=M.uri(this.id,T),W=_.cwd?v.file(_.cwd):r.thread.cwd?v.file(r.thread.cwd):e.workingDirectory,R=this._createResumedSessionEntry(T,T,w,W,g);if(this._sessions.set(T,R),this._sessionIdByThreadId.set(T,T),!R.serverToolsAdvertised&&this._serverToolHost&&(R.serverToolsAdvertised=!0,this._serverToolHost.advertise(R.sessionUri.toString())),this._persistMaterializedSession(R),t.turnIdMapping&&t.turnIdMapping.size>0)try{let D=(await this._readSession(w))?.thread.turns??[],z=WM(s.map(J=>J.id),D.map(J=>J.id),c,a?.hostTurnIdByAppTurnId,t.turnIdMapping);for(let[J,me]of z)R.codexTurnIdByHostTurnId.set(J,me)}catch(L){this._logService.warn(`[Codex:${T}] failed to seed forked turn-id map: ${L instanceof Error?L.message:String(L)}`)}return this._logService.info(`[Codex] forked session ${i} \u2192 ${T} (kept ${s.length-u}/${s.length} turns)`),{session:w,workingDirectory:W,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 h=V(hO.tmpdir(),"vscode-agent-codex",e.sessionId);await ao.promises.mkdir(h,{recursive:!0}),e.workingDirectory=v.file(h),e.managedWorkingDirectory=e.workingDirectory,this._logService.info(`[Codex] no working directory supplied for session=${e.sessionUri.toString()}; using managed temp folder ${h}`)}let t=await this._ensureConnection(),r=this._readSessionConfig(e),i=await this._resolveModel(e),{approvalPolicy:s,sandboxMode:a,approvalsReviewer:l}=this._resolveSessionPermissions(e),d=this._buildSessionMcpServers(e),c={web_search:iO(r["codex.webSearchMode"])??Gn["codex.webSearchMode"]},u=Object.keys(d);u.length>0&&(c.mcp_servers=d,this._logService.info(`[Codex] thread/start for session=${e.sessionUri.toString()} with ${u.length} MCP server(s): ${u.join(", ")}`));let g=(await t.client.request("thread/start",{cwd:e.workingDirectory.fsPath,model:i.id,approvalPolicy:s,sandbox:a,approvalsReviewer:l,config:c,dynamicTools:this._buildDynamicTools(e)})).thread.id;if(e.disposed){try{await t.client.request("thread/unsubscribe",{threadId:g})}catch(h){this._logService.info(`[Codex:${g}] thread/unsubscribe after disposed prewarm failed: ${h instanceof Error?h.message:String(h)}`)}return}e.threadId=g,e.materializedMcpSig=O_(d),e.materializedToolsSig=mO(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())),this._refreshSkillHookCustomizations(e),this._refreshSkillExtraRoots()}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&&(this._configurationService.isWorkingDirectoryPending(e.sessionUri.toString())||(async()=>{if(!await this._agentSdkDownloader.isSdkResolvableWithoutDownload(ca)){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)},Tq);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 _adoptWorkingDirectoryBeforeSend(e,t){if(!t||gn(e.workingDirectory,t))return;if(e.prewarmClaimed){e.threadId===void 0&&!e.materializePromise&&(e.workingDirectory=t);return}this._claimPrewarm(e);let r=e.materializePromise;if(r)try{await r}catch(s){this._logService.info(`[Codex] stale prewarm failed before working directory changed for session=${e.sessionUri.toString()}: ${s instanceof Error?s.message:String(s)}`)}let i=e.threadId;if(i!==void 0){e.threadId=void 0,this._sessionIdByThreadId.delete(i);let s=this._connection;if(s.kind==="ready")try{await s.client.request("thread/unsubscribe",{threadId:i})}catch(a){this._logService.warn(`[Codex] stale prewarm unsubscribe failed session=${e.sessionUri.toString()} threadId=${i}: ${a instanceof Error?a.message:String(a)}`)}}e.workingDirectory=t}_startTurnStopWatch(e){let t=lt.create(!1);return e.turnStopWatch=t,t}_clearTurnStopWatch(e){let t=e.turnStopWatch?.elapsed();return e.turnStopWatch=void 0,typeof t=="number"&&Number.isFinite(t)?Math.max(0,t):0}async _sendMessage(e,t,r,i,s){let a=this._sessionUriFromChat(e);this._logService.info(`[Codex DEBUG] sendMessage session=${a.toString()} prompt=${JSON.stringify(t).slice(0,60)}`);let l=M.id(a),d=this._sessions.get(l);if(!d)throw new Error(`Codex session not found: ${a.toString()}`);await this._adoptWorkingDirectoryBeforeSend(d,s);let c=await this._ensureConnection(),u=i??F();try{this._claimPrewarm(d),await this._materializeIfNeeded(d),this._persistMaterializedSession(d)}catch(S){let C=S instanceof Error?S.message:String(S);this._logService.error(`[Codex:${l}] materialize failed: ${C}`);let _=this._clearTurnStopWatch(d);this._fire(a,{type:"chat/error",turnId:u,duration:_,error:{errorType:"CodexMaterializeFailed",message:C}}),this._fire(a,{type:"chat/turnComplete",turnId:u,duration:_});return}let p=mO(d.clientToolSet.merged())!==d.materializedToolsSig,g=O_(this._buildSessionMcpServers(d))!==d.materializedMcpSig;if(!d.firstTurnSent&&!d.needsResume&&(p||g))try{await this._restartThreadWithCurrentTools(d),this._persistMaterializedSession(d)}catch(S){let C=S instanceof Error?S.message:String(S);this._logService.error(`[Codex:${l}] tool re-materialize failed: ${C}`);let _=this._clearTurnStopWatch(d);this._fire(a,{type:"chat/error",turnId:u,duration:_,error:{errorType:"CodexMaterializeFailed",message:C}}),this._fire(a,{type:"chat/turnComplete",turnId:u,duration:_});return}let h=d.threadId;if(d.needsResume)try{let S=this._buildSessionMcpServers(d);await c.client.request("thread/resume",YM(this._usageSource,h,S)),d.materializedMcpSig=O_(S),d.needsResume=!1}catch(S){let C=this._clearTurnStopWatch(d);this._fire(a,{type:"chat/error",turnId:u,duration:C,error:{errorType:"CodexResumeFailed",message:S instanceof Error?S.message:String(S)}}),this._fire(a,{type:"chat/turnComplete",turnId:u,duration:C});return}let{input:y,cleanupPaths:I}=E_(t,r);d.lastPromptText=t,d.currentTurnId=u,this._startTurnStopWatch(d);try{let S=await this._resolveModel(d),C=this._turnStartOptions(d,S.id);await c.client.request("turn/start",{threadId:h,input:y.slice(),model:S.id,...C}),d.firstTurnSent=!0}catch(S){if(S instanceof K){this._fire(a,{type:"chat/turnCancelled",turnId:u,duration:this._clearTurnStopWatch(d)});return}let C=S instanceof Error?S.message:String(S);this._logService.error(`[Codex:${l}] turn/start error: ${C}`);let _=this._clearTurnStopWatch(d);this._fire(a,{type:"chat/error",turnId:u,duration:_,error:{errorType:"CodexTurnError",...Wl(C)}}),this._fire(a,{type:"chat/turnComplete",turnId:u,duration:_})}finally{I.length>0&&setTimeout(()=>{for(let S of I)try{ao.unlinkSync(S)}catch{}},3e4)}}setPendingMessages(e,t,r){if(!t)return;let i=this._sessionUriFromChat(e),s=M.id(i),a=this._sessions.get(s);if(!a||a.pendingSteeringFlips.has(t.id))return;let l=a.currentAppTurnId,d=this._connection,c=t.message.text,u=c.length>0||(t.message.attachments?.length??0)>0;if(!l||d.kind!=="ready"||a.threadId===void 0||!u){this._fireSteeringConsumed(a,t.id);return}let{input:p}=E_(c,t.message.attachments),g=a.threadId;a.pendingSteeringFlips.set(t.id,t),d.client.request("turn/steer",{threadId:g,input:p.slice(),expectedTurnId:l}).catch(h=>{if(a.pendingSteeringFlips.delete(t.id)&&this._fireSteeringConsumed(a,t.id),h instanceof es){this._logService.info(`[Codex:${s}] turn/steer skipped: ${h.message}`);return}this._logService.warn(`[Codex:${s}] turn/steer failed: ${h instanceof Error?h.message:String(h)}`)})}async _abort(e){let t=this._sessionUriFromChat(e),r=M.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=M.id(e),r=this._sessions.get(t);r&&await this._teardownSessionInMemory(r,t)}async releaseSession(e){let t=M.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.clientCustomizations.isEmpty()||this._refreshSkillExtraRoots(),e.managedWorkingDirectory){let i=e.managedWorkingDirectory.fsPath;ao.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(M.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(M.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(M.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?KM(t.thread):[])}async getSessionMetadata(e){let t=M.id(e),r=await this._readSession(e);if(r){if(!this._sessions.has(t)){let i=r.thread.cwd?v.file(r.thread.cwd):void 0,s=r.thread.id,a=this._createResumedSessionEntry(t,s,e,i,void 0);this._sessions.set(t,a),this._sessionIdByThreadId.set(s,t),JM(this._usageSource,r.thread.modelProvider)||this._resetSessionForUsageSourceChange(a,this._usageSource),!a.serverToolsAdvertised&&this._serverToolHost&&(a.serverToolsAdvertised=!0,this._serverToolHost.advertise(a.sessionUri.toString()))}return this._threadToMetadata(r.thread,e)}}async _readSession(e){let t=M.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(ca))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)??M.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?v.file(e.cwd):void 0}}setServerToolHost(e){this._serverToolHost=e}getOrCreateActiveClient(e,t){let r=M.id(e);return new L_(()=>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)"}]`),i=>{this._syncClientCustomizations(e,t.clientId,[...i])})}removeActiveClient(e,t){let r=M.id(e),i=this._sessions.get(r);i?.clientToolSet.delete(t),i?.clientCustomizations.removeClient(t)&&this._refreshSkillExtraRoots()}onClientToolCallComplete(e,t,r,i){let s=M.id(e);this._sessions.get(s)?.pendingClientToolCalls.respondOrBuffer(r,i)}async _syncClientCustomizations(e,t,r){let i=this._sessions.get(M.id(e));if(!i)return;let s=await this._pluginManager.syncCustomizations(t,[...r],l=>this._fire(e,{type:"session/customizationUpdated",customization:l}));if(i.disposed)return;let a=await Promise.all(s.map(l=>this._parseClientPlugin(i,l)));i.disposed||(i.clientCustomizations.setClient(t,a),this._publishClientCustomizations(i),await this._refreshSkillExtraRoots())}async _parseClientPlugin(e,t){if(!t.pluginDir)return{synced:t,parsed:void 0};try{let r=await md(t.pluginDir,this._fileService,e.workingDirectory,this._environmentService.userHome,t.pluginDir);return{synced:t,parsed:r}}catch(r){return this._logService.warn(`[Codex] failed to parse client plugin ${t.customization.uri}: ${r instanceof Error?r.message:String(r)}`),{synced:t,parsed:void 0}}}_publishClientCustomizations(e){for(let t of e.clientCustomizations.toCustomizations())this._fire(e.sessionUri,{type:"session/customizationUpdated",customization:t})}async _refreshSkillExtraRoots(){if(this._connection.kind!=="ready")return;let e=[];for(let r of this._sessions.values())r.disposed||e.push(...r.clientCustomizations.enabledPlugins());let t=mM(e);try{await this._connection.client.request("skills/extraRoots/set",{extraRoots:t}),t.length>0&&this._logService.info(`[Codex] applied ${t.length} client-plugin skill root(s)`)}catch(r){this._logService.warn(`[Codex] skills/extraRoots/set failed: ${r instanceof Error?r.message:String(r)}`)}}async getSessionCustomizations(e){let t=this._sessions.get(M.id(e));if(!t)return[];let r=this._getOrCreateMcpController(t);r.applyAll(Oy(this._mcpInventory)),this._refreshMcpCustomizationIds(t,r);let i=await this._fetchSkillHookContainers(t);return[...t.clientCustomizations.toCustomizations(),...r.topLevelCustomizations(),...i]}async _fetchSkillHookContainers(e){if(this._connection.kind!=="ready"||!e.workingDirectory)return[];let t=e.workingDirectory.fsPath,r=this._connection.client,[i,s]=await Promise.all([r.request("skills/list",{cwds:[t]}).catch(a=>{this._logService.warn(`[Codex] skills/list failed: ${a instanceof Error?a.message:String(a)}`)}),r.request("hooks/list",{cwds:[t]}).catch(a=>{this._logService.warn(`[Codex] hooks/list failed: ${a instanceof Error?a.message:String(a)}`)})]);return[...fM(i),...gM(s)]}async _refreshSkillHookCustomizations(e){if(e.disposed)return;let t=await this._fetchSkillHookContainers(e);if(!e.disposed)for(let r of t)this._fire(e.sessionUri,{type:"session/customizationUpdated",customization:r})}async handleMcpRequest(e,t,r,i){let s=M.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=dM(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(M.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(M.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(Oy(this._mcpInventory)),this._refreshMcpCustomizationIds(e,r),r.serverNameForCustomizationId(t)}_getOrCreateMcpController(e){return e.mcpController||(e.mcpController=this._instantiationService.createInstance(Ui,{providerId:this.id,sessionId:e.sessionId,sessionUri:e.sessionUri,resolveChildId:()=>{},emit:t=>this._fire(e.sessionUri,t),capabilities:vq})),e.mcpController}_applyMcpInventoryToSessions(){let e=Oy(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=lM(t),i=[];for(let[s,a]of r){let l=this._mcpInventory.get(s);l&&cM(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._logService.info(`[Codex] MCP inventory refreshed: ${this._mcpInventory.size===0?"(none)":[...this._mcpInventory].map(([s,a])=>`${s} [${a.state.kind}, ${a.tools.length} tool(s)]`).join(", ")}`),this._applyMcpInventoryToSessions();for(let s of i)this._fireMcpToolsListChanged(s)}_handleMcpStartupStatus(e,t,r,i){if(!(this._connection.kind==="ready"&&this._connection.client!==e)){if(this._logService.info(`[Codex] MCP server '${t}' startup status: ${r}${i?` (${i})`:""}`),r==="ready"){this._refreshMcpInventory(e);return}if(r==="failed"&&uM(i)){let s=this._mcpServerUrlForName(t),a=s!==void 0?Zi(s):void 0;if(s!==void 0&&a!==void 0){this._mcpAuthTokens.delete(a)&&this._logService.info(`[Codex] MCP server '${t}' rejected the stored token; clearing it to allow re-authentication`),this._surfaceMcpAuthRequired(e,t,s,i);return}}this._setMcpServerState(t,aM(r,i))}}_setMcpServerState(e,t){let r=this._mcpInventory.get(e);this._mcpInventory.set(e,{state:t,tools:r?.tools??[],resources:r?.resources??[],resourceTemplates:r?.resourceTemplates??[]}),this._applyMcpInventoryToSessions()}async _surfaceMcpAuthRequired(e,t,r,i){let s={resource:r,resource_name:t},a;try{let c=await hf(f1(r,void 0),15e3);c?(s=c.metadata,a=c.metadata.scopes_supported,this._logService.info(`[Codex] discovered OAuth metadata for MCP server '${t}': authorization_servers=[${(c.metadata.authorization_servers??[]).join(", ")}]`)):this._logService.warn(`[Codex] timed out discovering OAuth metadata for MCP server '${t}' at ${r}; the Authenticate action may not be able to complete`)}catch(c){this._logService.warn(`[Codex] failed to discover OAuth metadata for MCP server '${t}' at ${r}; the Authenticate action may not be able to complete: ${c instanceof Error?c.message:String(c)}`)}if(this._connection.kind==="ready"&&this._connection.client!==e)return;let l=Zi(r),d=Zi(s.resource)??l;if(l!==void 0&&d!==void 0){let c=this._mcpAuthServerUrlsByResource.get(d)??new Set;c.add(l),this._mcpAuthServerUrlsByResource.set(d,c)}this._logService.info(`[Codex] MCP server '${t}' requires authentication for ${r}`),this._setMcpServerState(t,{kind:"authRequired",reason:"required",resource:s,requiredScopes:a&&a.length>0?a:void 0,description:i??void 0})}_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(){this._disposeConnection();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=Gy.validateOrDefault(e.config,Gn),r=_q.toProtocol(),i={...e.config,mode:t.mode};return delete i["codex.permissionsPreset"],delete i["codex.approvalPolicy"],delete i["codex.sandboxMode"],Object.assign(i,Ky(e.config,{approvalPolicy:Gn["codex.approvalPolicy"],sandboxMode:Gn["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=nn(t)?t:Xn(r??process.cwd(),t),s=t.endsWith(He)?i:te(i),a=t.endsWith(He)?"":ue(i).toLowerCase();try{return{items:(await ao.promises.readdir(s,{withFileTypes:!0})).filter(d=>d.isDirectory()&&d.name.toLowerCase().startsWith(a)).slice(0,50).map(d=>{let c=V(s,d.name);return{value:c,label:d.name,description:c}})}}catch{return{items:[]}}}_fire(e,t){this._onDidSessionProgress.fire({kind:"action",resource:Tr(t)?v.parse(pe(e)):e,action:t})}dispose(){this._disposeConnection();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()}};oc=A([b(0,O),b(1,gt),b(2,Uy),b(3,Ue),b(4,wt),b(5,Ud),b(6,Tt),b(7,$i),b(8,xe),b(9,St),b(10,we)],oc);function xq(o){if(!o)return[];try{let n=JSON.parse(o);return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}catch{return[]}}function Aq(o,n){if(!(o!=="linux"&&o!=="darwin"&&o!=="win32"||n!=="x64"&&n!=="arm64"))return`${o}-${n}`}function Pq(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 Eq(o=kq){try{let n=await o();return te(te(te(te(n))))}catch{return}}async function kq(){let{createRequire:o}=await import("node:module");return o(import.meta.url).resolve("@openai/codex/package.json")}function yO(o){return{provider:Ff,title:f(2264,null),description:f(2251,null),properties:{"codex.personality":{type:"string",title:f(2256,null),description:f(2258,null),default:"default",enum:["default","friendly","pragmatic"],enumLabels:[f(2257,null),f(2259,null),f(2260,null)]},"codex.autoReviewPolicy":{type:"string",title:f(2249,null),description:f(2250,null),default:""}},settings:[{key:"codex.personality",group:f(2261,null)},{key:"codex.autoReviewPolicy",group:f(2262,null),kind:"multiline",saveLabel:f(2263,null)}],configurationFile:{resource:v.file(V(o.fsPath,".codex","config.toml")).toString(),title:f(2255,null),description:f(2252,null),openLabel:f(2254,null),documentationUrl:"https://learn.chatgpt.com/docs/config-file/config-basic",documentationLabel:f(2253,null)}}}import{lookup as Dq}from"dns";var CO=B("networkDiagnosticsService"),IO=1e4,vO=64*1024,Mq=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy","NO_PROXY","no_proxy"],Oq=["http.proxy","http.proxyStrictSSL","http.proxySupport","http.noProxy"],sc=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 Mq){let s=process.env[i];s&&(t[i]=s)}let r={};for(let i of Oq){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([SO(t,4),SO(t,6)]),s;try{s=await this._proxyResolver.resolveProxy(n)}catch(d){this._logService.debug(`[AgentHost] Network diagnostics: proxy resolution for ${n} failed: ${N_(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:IO,callSite:hm},ke.None),c=(await Nr(d.stream)).toString();return{...a,statusCode:d.res.statusCode,body:c.length>vO?c.slice(0,vO):c,durationMs:Date.now()-l}}catch(d){return{...a,error:N_(d),durationMs:Date.now()-l}}}};sc=A([b(0,Ri),b(1,Wi),b(2,ir),b(3,Tt),b(4,O)],sc);function Lq(o,n){return new Promise((e,t)=>{Dq(o,{family:n},(r,i)=>r?t(r):e(i))})}async function SO(o,n){let e=Date.now();try{return{address:await Nq(Lq(o,n),IO),durationMs:Date.now()-e}}catch(t){return{durationMs:Date.now()-e,error:N_(t)}}}function Nq(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 N_(o){let n=new Set;function e(t){if(n.has(t))return"";if(n.add(t),!(t instanceof Error))return String(t);let r=[t.cause?e(t.cause):"",...t instanceof AggregateError?t.errors.map(e):[]].filter(Boolean).join(", ");return r?`${t.message}: ${r}`:t.message}return e(o)}import{mkdir as tB}from"fs/promises";var Uq=/^[0-9a-fA-F]+$/,Fq="00000000000000000000000000000000",bO="0000000000000000";function _O(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=qq(r.resource?.attributes);for(let s of r.scopeSpans??[])if(s)for(let a of s.spans??[])try{let l=Hq(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 Hq(o,n){if(!o)return;let e=(o.traceId??"").toLowerCase(),t=(o.spanId??"").toLowerCase();if(!U_(e,32)||e===Fq)throw new Error(`invalid traceId: ${o.traceId}`);if(!U_(t,16)||t===bO)throw new Error(`invalid spanId: ${o.spanId}`);let r;if(o.parentSpanId){let c=o.parentSpanId.toLowerCase();U_(c,16)&&c!==bO&&(r=c)}let i=H_(o.startTimeUnixNano),s=H_(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??[])$_(a,c);let l=[];for(let c of o.events??[]){let u=$q(c);u&&l.push(u)}let d=Wq(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 $q(o){if(!o)return;let n=H_(o.timeUnixNano);if(n===void 0)return;let e={};for(let t of o.attributes??[])$_(e,t);return{name:o.name??"",timestamp:n,attributes:Object.keys(e).length>0?e:void 0}}function Wq(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 qq(o){let n={};if(!o)return n;for(let e of o)$_(n,e);return n}function $_(o,n){if(!n||typeof n.key!="string"||n.key.length===0)return;let e=F_(n.value);e!==void 0&&(o[n.key]=e)}function F_(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(F_);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]=F_(e.value));return JSON.stringify(n)}if(typeof o.bytesValue=="string")return o.bytesValue}}function H_(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 U_(o,n){return o.length===n&&Uq.test(o)}var Bq="/v1/traces",zq=64*1024*1024;async function TO(o,n,e={}){let t=e.maxBodyBytes??zq,i=(await import("http")).createServer();i.on("request",(c,u)=>{Vq(c,u,o,n,t).catch(p=>{if(n.error(`[agentHost-otel] receiver: unhandled error: ${p instanceof Error?p.message:String(p)}`),!u.headersSent)ts(u,500,"internal error");else if(!u.writableEnded)try{u.end()}catch{}})}),await new Promise((c,u)=>{let p=g=>u(g);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=U(()=>{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 Vq(o,n,e,t,r){if((o.url??"").split("?",1)[0]!==Bq){ts(n,404,"not found");return}if(o.method!=="POST"){n.setHeader("allow","POST"),ts(n,405,"method not allowed");return}let a=(o.headers["content-type"]??"").toString().toLowerCase();if(!a.includes("application/json")){ts(n,415,"unsupported content-type; this receiver only accepts application/json");return}let l=(o.headers["content-encoding"]??"").toString().toLowerCase();if(l&&l!=="identity"){ts(n,415,`unsupported content-encoding: ${l}`);return}let d;try{d=await jq(o,r)}catch(g){g instanceof Jy?ts(n,413,"payload too large"):ts(n,400,"failed to read body");return}if(e.onForward)try{e.onForward(d,a)}catch(g){t.warn(`[agentHost-otel] forward callback threw: ${g instanceof Error?g.message:String(g)}`)}let c;try{c=JSON.parse(d.toString("utf8"))}catch(g){ts(n,400,`invalid json: ${g instanceof Error?g.message:String(g)}`);return}let u=_O(c);try{e.onSpans(u)}catch(g){t.warn(`[agentHost-otel] onSpans handler threw: ${g instanceof Error?g.message:String(g)}`)}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 Jy=class extends Error{};function jq(o,n){return new Promise((e,t)=>{let r=[],i=0,s=c=>{if(i+=c.length,i>n){d(),t(new Jy(`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 ts(o,n,e){o.statusCode=n,o.setHeader("content-type","text/plain; charset=utf-8"),o.end(e)}import{URL as wO}from"url";import{promises as Kq}from"fs";function Gq(o){try{let n=new wO(o);return n.pathname===""||n.pathname==="/"?(n.pathname="/v1/traces",n.toString()):o}catch{return o}}var Yy=class extends x{constructor(e,t,r){super();this._options=e;this._logService=t;this._fetchFn=r;this._queue=new ii;this._disposed=!1;this._resolvedEndpoint=Gq(e.endpoint),this._register(U(()=>{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 wO(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 Jq(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 Jq(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 Qy=class extends x{constructor(e,t){super();this._options=e;this._logService=t;this._queue=new ii;this._disposed=!1;this._register(U(()=>{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 Kq.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)}`)}}},Xy=class extends x{constructor(e){super();this._logService=e;this._disposed=!1;this._register(U(()=>{this._disposed=!0}))}forwardSpans(e){if(!this._disposed)for(let t of e.spans)this._logService.info(`[agentHost-otel] span ${Yq(t)}`)}async flush(){}};function Yq(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 Zy=class extends x{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 Qq}from"fs";import{createRequire as Xq}from"module";var Ln={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"},Op={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 Zq=Xq(import.meta.url);function eB(){return Zq("node:sqlite")}var RO=1,xO=10080*60*1e3,AO=100,Cn={operation_name:Ln.OPERATION_NAME,provider_name:Ln.PROVIDER_NAME,agent_name:Ln.AGENT_NAME,conversation_id:Ln.CONVERSATION_ID,request_model:Ln.REQUEST_MODEL,response_model:Ln.RESPONSE_MODEL,input_tokens:Ln.USAGE_INPUT_TOKENS,output_tokens:Ln.USAGE_OUTPUT_TOKENS,cached_tokens:Ln.USAGE_CACHE_READ_INPUT_TOKENS,reasoning_tokens:Ln.USAGE_REASONING_TOKENS,tool_name:Ln.TOOL_NAME,tool_call_id:Ln.TOOL_CALL_ID,tool_type:Ln.TOOL_TYPE,chat_session_id:Op.CHAT_SESSION_ID,turn_index:Op.TURN_INDEX,ttft_ms:Op.TIME_TO_FIRST_TOKEN},b9e=B("otelSqliteStore"),ev=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,Cn.operation_name),this._attr(n,Cn.provider_name),this._attr(n,Cn.agent_name),this._attr(n,Cn.conversation_id),this._attr(n,Cn.request_model),this._attr(n,Cn.response_model),this._attr(n,Cn.input_tokens),this._attr(n,Cn.output_tokens),this._attr(n,Cn.cached_tokens),this._attr(n,Cn.reasoning_tokens),this._attr(n,Cn.tool_name),this._attr(n,Cn.tool_call_id),this._attr(n,Cn.tool_type),this._attr(n,Cn.chat_session_id),this._attr(n,Cn.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=xO){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,Op.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:"&&Qq(te(this._dbPath),{recursive:!0});let{DatabaseSync:n}=eB(),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)>=RO||n.exec(`
			CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
			INSERT OR REPLACE INTO schema_version (version) VALUES (${RO});

			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()-xO;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(AO);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,AO)}};var nB=QR;function W_(o){if(!o)return!1;let n=o.trim().toLowerCase();return n==="true"||n==="1"||n==="yes"||n==="on"}function rB(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 oB(o){let n=W_(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=W_(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:W_(o.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT),headers:rB(o.OTEL_EXPORTER_OTLP_HEADERS)}}var ac=class extends x{constructor(e,t,r){super();this._fetchFn=e;this._logService=t;this._config=oB(process.env),this._spansDbPath=V(r.userDataPath,nB)}async getSdkTelemetryConfig(){if(this._config.enabled){if(this._config.dbSpanExporter){if(await this._ensureStarted(),this._receiver)return this._buildLoopbackConfig();if(!this._config.otlpEndpoint&&this._config.exporterType!=="console"&&!this._config.filePath)return}return this._buildPassthroughConfig()}}getSpansDbPath(){return this._config.dbSpanExporter?v.file(this._spansDbPath):void 0}async flush(){await this._startPromise,this._forwarder&&await this._forwarder.flush()}_buildLoopbackConfig(){return{exporterType:"otlp-http",otlpEndpoint:this._receiver.baseUrl,sourceName:this._config.sourceName,captureContent:this._config.captureContent}}_buildPassthroughConfig(){return{exporterType:this._config.exporterType,otlpEndpoint:this._config.otlpEndpoint,filePath:this._config.filePath,sourceName:this._config.sourceName,captureContent:this._config.captureContent}}_ensureStarted(){return this._startPromise||(this._startPromise=this._start().catch(e=>{this._logService.error("[agentHost.otel] failed to start loopback OTel pipeline",e),this._receiver=void 0,this._forwarder=void 0})),this._startPromise}async _start(){await tB(te(this._spansDbPath),{recursive:!0});let e=new ev(this._spansDbPath);this._register(U(()=>e.close())),this._forwarder=this._buildOutboundForwarder();let t=await TO({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 Yy({endpoint:this._config.otlpEndpoint,headers:this._config.headers},this._logService,this._fetchFn));break;case"file":this._config.filePath&&e.push(new Qy({filePath:this._config.filePath},this._logService));break;case"console":e.push(new Xy(this._logService));break}if(e.length)return e.length===1?e[0]:new Zy(e)}};ac=A([b(1,O),b(2,St)],ac);var tv=class extends Error{constructor(e,t,r){super(t);this.code=e;this.data=r}},PO=class o extends x{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=ke.None,r){if(this._store.isDisposed)return Promise.reject(new K);let i=this._nextRequestId++,s=new be,a=new dt;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(q_(e)){he(e,{result:!0})?this._handleResult(e):this._handleError(e);return}if(iB(e))return this._handleRequest(e);sB(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 tv(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 dt;this._register(U(()=>t.dispose(!0)));try{let r=this._handlers.handleRequest(e,t.token),i=aB(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 tv?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 iB(o){return"method"in o&&"id"in o&&(typeof o.id=="string"||typeof o.id=="number")}function q_(o){return he(o,{id:!0,result:!0})||he(o,{id:!0,error:!0})}function sB(o){return he(o,{method:!0})&&!he(o,{id:!0})}function aB(o){return typeof o=="object"&&o!==null&&"then"in o&&typeof o.then=="function"}function EO(o,n){if(Is(o.channel)){for(let e of n)if(Is(e))return!0;return!1}for(let e of n)if(e===o.channel)return!0;return!1}var ns="0.7.0",g8e=Object.freeze(["0.7.0","0.6.0","0.5.2","0.5.1"]);function kO(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 B_(o,n){let[e,t,r]=kO(o),[i,s,a]=kO(n);return e-i||t-s||r-a}var m8e={"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/workingDirectorySet":"0.7.0","session/workingDirectoryRemoved":"0.7.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/toolCallAuthRequired":"0.6.0","chat/toolCallAuthResolved":"0.6.0","chat/turnComplete":"0.4.0","chat/turnCancelled":"0.4.0","chat/error":"0.4.0","chat/activityChanged":"0.5.0","chat/workingDirectorySet":"0.7.0","chat/workingDirectoryRemoved":"0.7.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 DO(o){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(o);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])]}function lB(o,n){let e=DO(o),t=DO(n);return!e||!t||e[0]!==t[0]||e[0]===0&&e[1]!==t[1]?!1:B_(o,n)<=0}function MO(o,n){let e;for(let t of o)lB(t,n)&&(e===void 0||B_(t,e)>0)&&(e=t);return e}var z_="_vscodeUpgrade";var OO="VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";function nv(){let o=process.env[OO];return o&&o.length>0?o:void 0}async function LO(o=nv()){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: ${OO} is not set.`))}function NO(o,n){if(o!=="resourceRead"||!dB(n))return!1;let e=n.uri;if(typeof e!="string")return!1;try{return v.parse(e).scheme===ne.file}catch{return!1}}function dB(o){return typeof o=="object"&&o!==null&&he(o,{uri:!0})}var cB=1e3,UO=3e4,uB=new Set(["session/workingDirectorySet","session/workingDirectoryRemoved","chat/workingDirectorySet","chat/workingDirectoryRemoved"]);function pB(o){return o==="streaming"||o==="running"||o==="pending-confirmation"}function ua(o,n){return{jsonrpc:"2.0",id:o,result:n}}function lc(o,n,e,t){return{jsonrpc:"2.0",id:o,error:{code:n,message:e,...t!==void 0?{data:t}:{}}}}function pa(o,n){if(n instanceof N)return lc(o,n.code,n.message,n.data);let e=n instanceof Error?n.stack??n.message:String(n);return lc(o,Ja,e)}function fB(o,n,e){return!(e instanceof N)||e.code!==ge.NotFound||!NO(o,n)}function FO(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function gB(o){if(!FO(o))return;let n=o.channel;if(!(typeof n!="string"||!n.startsWith("mcp://")))return n}function rv(o){if(o.toLowerCase().startsWith(`${m1}:`)){let n=v1(o);return n?{kind:"otlp-logs",uri:S1(n),level:n}:void 0}return xR(o)?{kind:"resource-watch",uri:o}:{kind:"state",uri:o}}var rs=class extends x{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 E);this.onDidChangeConnectionCount=this._onDidChangeConnectionCount.event;this._requestHandlers={subscribe:async(e,t)=>{let r=rv(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 N(Dt,`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(v.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 N?i:new N(Dt,`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 N(Dt,`Fork source session not found: ${t.fork.session}`);let a=s.turns.findIndex(l=>l.id===t.fork.turnId);if(a<0)throw new N(Dt,`Fork turn ID ${t.fork.turnId} not found in session ${t.fork.session}`);i={session:v.parse(t.fork.session),turnIndex:a,turnId:t.fork.turnId}}if(t.activeClient&&t.activeClient.clientId!==e.clientId)throw new N(oe.InvalidParams,"createSession.activeClient.clientId must match the connection's clientId");try{r=await this._agentService.createSession({provider:t.provider,workingDirectory:t.workingDirectories?.[0]?v.parse(t.workingDirectories[0]):void 0,session:v.parse(t.channel),fork:i,config:t.config,activeClient:t.activeClient,progressToken:t.progressToken})}catch(s){throw s instanceof N?s:new N(ix,s instanceof Error?s.message:String(s))}return r.toString()!==v.parse(t.channel).toString()&&this._logService.warn(`[ProtocolServer] createSession: provider returned URI ${r.toString()} but client requested ${t.channel}`),null},disposeSession:async(e,t)=>(await this._agentService.disposeSession(v.parse(t.channel)),null),createChat:async(e,t)=>{let r=this._stateManager.getSessionState(t.channel);if(!r)throw new N(Dt,`Session not found: ${t.channel}`);let i=r.defaultChat??pe(t.channel);if(v.parse(t.chat).toString()===v.parse(i).toString())return null;let s=t.source,a;if(s)switch(s.kind){case"fork":a={fork:{source:v.parse(s.chat),turnId:s.turnId}};break;case"sideChat":a={sideChat:{source:v.parse(s.chat),turnId:s.turnId,...s.selection?{selection:s.selection}:{}}};break;default:throw new N(oe.InvalidParams,`Unsupported createChat source kind: ${String(s.kind)}`)}return await this._agentService.createChat(v.parse(t.channel),v.parse(t.chat),a),null},disposeChat:async(e,t)=>{let r=v.parse(t.channel),i=Le(r);return i&&await this._agentService.disposeChat(v.parse(i.session),r),null},resourceWrite:async(e,t)=>this._agentService.resourceWrite(t),listSessions:async()=>({items:(await this._agentService.listSessions()).map(r=>{let i=M.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}}:{},workingDirectories:r.workingDirectory?[r.workingDirectory.toString()]:void 0,changes:r.changes,...r._meta!==void 0?{_meta:r._meta}:{}}})}),resolveSessionConfig:async(e,t)=>this._agentService.resolveSessionConfig({provider:t.provider,workingDirectory:t.workingDirectory?v.parse(t.workingDirectory):void 0,config:t.config}),sessionConfigCompletions:async(e,t)=>this._agentService.sessionConfigCompletions({provider:t.provider,workingDirectory:t.workingDirectory?v.parse(t.workingDirectory):void 0,config:t.config,property:t.property,query:t.query}),completions:async(e,t)=>this._agentService.completions(t),fetchTurns:async(e,t)=>{let r=this._stateManager.getChatState(t.channel);if(!r)throw new N(Dt,`Session not found: ${t.channel}`);if(t.cursor&&t.cursor!==r.turnsNextCursor)throw new N(oe.InvalidParams,"Unrecognized fetchTurns cursor");return this._stateManager.dispatchServerAction(t.channel,{type:"chat/turnsLoaded",turns:[]}),{}},resourceList:async(e,t)=>this._agentService.resourceList(v.parse(t.uri)),resourceRead:async(e,t)=>this._agentService.resourceRead(v.parse(t.uri)),resourceCopy:async(e,t)=>this._agentService.resourceCopy(t),resourceDelete:async(e,t)=>this._agentService.resourceDelete(t),resourceMove:async(e,t)=>this._agentService.resourceMove(t),resourceResolve:async(e,t)=>this._agentService.resourceResolve(t),resourceMkdir:async(e,t)=>this._agentService.resourceMkdir(t),createResourceWatch:async(e,t)=>this._agentService.createResourceWatch(t),resourceRequest:async(e,t)=>({}),authenticate:async(e,t)=>{if(!(await this._agentService.authenticate(t)).authenticated)throw new N(_r,`Authentication failed for resource: ${t.resource}`);return{}},createTerminal:async(e,t)=>(await this._agentService.createTerminal(t),null),disposeTerminal:async(e,t)=>(await this._agentService.disposeTerminal(v.parse(t.channel)),null),invokeChangesetOperation:async(e,t)=>this._agentService.invokeChangesetOperation(t)};this._reverseRequestId=0;this._pendingReverseRequests=new Map;this._register(this._server.onConnection(l=>{this._handleNewConnection(l)})),this._register(this._stateManager.onDidEmitEnvelope(l=>{if(this._replayBuffer.push(l),this._replayBuffer.length>cB&&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(ce(l.channel),l.channel)}})),this._register(this._stateManager.onDidEmitNotification(l=>{this._broadcastNotification(l)})),this._register(this._agentService.onMcpNotification(l=>{this._broadcastMcpNotification(l)})),this._config.otlpLogEmitter&&this._register(this._config.otlpLogEmitter.onDidLog(l=>this._broadcastOtlpLog(l)))}_handleNewConnection(e){let t=new G,r;t.add(e.onMessage(i=>{if(ax(i)){if(this._logService.trace(`[ProtocolServer] request: method=${i.method} id=${i.id}`),i.method==="ping"){e.send(ua(i.id,null));return}if(!r&&i.method==="initialize"){try{let s=this._handleInitialize(i.params,e,t);r=s.client,e.send(ua(i.id,s.response))}catch(s){e.send(pa(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(pa(i.id,a));return}s.then(a=>e.send(ua(i.id,a)),a=>e.send(pa(i.id,a)));return}if(i.method===z_){this._handleVscodeUpgrade(i.id,e);return}if(!r){e.send(lc(i.id,oe.MethodNotFound,`Method not found: ${i.method}`));return}this._handleRequest(r,i.method,i.params,i.id)}else if(lx(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;uB.has(s.type)?(this._logService.warn(`[ProtocolServer] rejecting unsupported client action: ${s.type}`),this._stateManager.rejectClientAction(a,s,{clientId:r.clientId,clientSeq:i.params.clientSeq},`Unsupported action: ${s.type}`)):(fu(s)||Tr(s)||vg(s)||gu(s)||mu(s)||s.type==="root/configChanged")&&this._agentService.dispatchAction(a,s,r.clientId,i.params.clientSeq,cP(r.clientInfo))}break}else if(q_(i)){let s=this._pendingReverseRequests.get(i.id);s&&s.client===r&&(this._pendingReverseRequests.delete(i.id),he(i,{error:!0})?s.reject(new N(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",clientInfo:i.clientInfo,lastSeenAt:Date.now(),disconnectTimeouts:new Ee}),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=MO(i,ns);if(!s){let d={supportedVersions:[`^${ns}`],_meta:nv()?{vscodeUpgradeMethod:z_}:void 0};throw new N(sx,`Client offered protocol versions [${i.join(", ")}], none of which are compatible with this server's version ${ns} (server accepts ^${ns}).`,d)}let a={clientId:e.clientId,clientInfo:e.clientInfo,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:g1}:void 0}}}_addInitialSubscription(e,t){let r=rv(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(v.parse(r.uri),e.clientId),this._clearClientToolCallDisconnectTimeout(e.clientId,r.uri),i}_handleVscodeUpgrade(e,t){let r=nv();if(!r){t.send(lc(e,oe.MethodNotFound,"No upgrade supervisor is available for this agent host."));return}LO(r).then(i=>t.send(ua(e,i)),i=>{this._logService.warn(`[ProtocolServer] vscodeUpgrade signal failed: ${i instanceof Error?i.message:String(i)}`),t.send(pa(e,i))})}_handleReconnect(e,t,r){this._logService.info(`[ProtocolServer] Reconnect: clientId=${e.clientId}, lastSeenSeq=${e.lastSeenServerSeq}`);let i=this._clients.get(e.clientId);if(!i)throw new N(ge.NotFound,`Reconnect client not found: ${e.clientId}`);let s={clientId:e.clientId,clientInfo:i.clientInfo,protocolVersion:ns,transport:t,subscriptions:new Map,disposables:r};this._attachConnection(e.clientId,s),this._registerClientFileSystemAuthority(e.clientId,r);let a=this._replayBuffer.length>0?this._replayBuffer[0].serverSeq:this._stateManager.serverSeq,l=e.lastSeenServerSeq>=a,d=this._restoreReconnectSubscriptions(s,e,l);return{client:s,responsePromise:d}}_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=rv(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(v.parse(l),e.clientId);return e.subscriptions.set(d.uri,d),this._clearClientToolCallDisconnectTimeout(e.clientId,d.uri),c}catch(c){this._logService.info(`[ProtocolServer] Reconnect: failed to restore subscription ${l}: ${c instanceof Error?c.message:String(c)}`),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"&&pB(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,UO-s);i.disconnectTimeouts.set(r,Ft(()=>{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==="grace"&&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.clientInfo=t.clientInfo??r.clientInfo):(r?.disconnectTimeouts.dispose(),this._clients.set(e,{state:"active",clientInfo:t.clientInfo??r?.clientInfo,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",clientInfo:void 0,lastSeenAt:Date.now(),disconnectTimeouts:new Ee};return this._clients.set(e,r),r}_getActiveClient(e){return this._getActiveClientFromRecord(this._clients.get(e))}_getActiveClientFromRecord(e){if(e?.state==="active")return e.connections[e.connections.length-1]}_releaseClientSubscriptions(e,t){for(let r of e.subscriptions.values())if(r.kind==="state"){if(this._hasSubscriptionInOtherConnection(t,e,r.uri))continue;this._agentService.unsubscribe(v.parse(r.uri),e.clientId)}else r.kind==="resource-watch"&&this._agentService.onResourceWatchUnsubscribed(r.uri);e.subscriptions.clear()}_hasSubscriptionInOtherConnection(e,t,r){if(e.state!=="active")return!1;for(let 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()-UO*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(ua(i,d??null))}).catch(d=>{fB(t,r,d)&&this._logService.error(`[ProtocolServer] Request '${t}' failed`,d),e.transport.send(pa(i,d))});return}let a=this._handleExtensionRequest(t,r);if(a){a.then(d=>{e.transport.send(ua(i,d??null))}).catch(d=>{this._logService.error(`[ProtocolServer] Extension request '${t}' failed`,d),e.transport.send(pa(i,d))});return}let l=gB(r);if(l!==void 0){let d=FO(r)?r:void 0;this._agentService.handleMcpRequest(l,t,d).then(c=>{e.transport.send(ua(i,c??null))}).catch(c=>{if(c instanceof Error&&c.message.startsWith("Method not found")){e.transport.send(lc(i,oe.MethodNotFound,c.message));return}this._logService.error(`[ProtocolServer] mcp:// request '${t}' on ${l} failed`,c),e.transport.send(pa(i,c))});return}e.transport.send(lc(i,oe.MethodNotFound,`Method not found: ${t}`))}_handleExtensionRequest(e,t){if(this._config.allowExtensionMethods!==!1)switch(e){case"shutdown":return this._agentService.shutdown();case"getNetworkDiagnosticsInfo":return this._agentService.getNetworkDiagnosticsInfo();case"getManagedSettingsDiagnostics":return this._agentService.getManagedSettingsDiagnostics();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=rv(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(v.parse(i.uri),e.clientId),de(i.uri))this._releaseActiveClientForSession(ce(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=y1(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<h1(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:Is(t.channel)?EO(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=A([b(5,O)],rs);var ov=class extends x{constructor(e){super();this._onConnection=this._register(new E);this.onConnection=this._onConnection.event;this.address=void 0;for(let t of e)this._register(t),this._register(t.onConnection(r=>this._onConnection.fire(r)))}};var mB="ahp",hB=75*1024*1024,yB=5,vB=1024*1024,SB=1024*1024,CB=16*1024,dc=class extends x{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=Y(this._options.logsHome,mB);let i=TB(this._options.connectionId).slice(0,64);this._baseName=`ahp-${_B(new Date)}-${i}.jsonl`,this._maxFileSizeBytes=this._options.maxFileSizeBytes??hB,this._maxFiles=this._options.maxFiles??yB,this._currentFile=Y(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=IB(s);a.length>SB&&(i.truncated=!0,a=bB(s,CB));let l=`${a}
`;this._pending.push($.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]:$.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>vB&&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 Y(this._directory,this._baseName);let t=this._baseName.slice(0,-6);return Y(this._directory,`${t}.${e}.jsonl`)}async _getFileSize(e){try{return(await this._fileService.resolve(e)).size??0}catch{return 0}}};dc=A([b(1,xe),b(2,O)],dc);function V_(o){return $.fromString(o).byteLength}function IB(o){return JSON.stringify(o,HO)}function bB(o,n){return JSON.stringify(o,function(e,t){let r=HO.call(this,e,t);return typeof r=="string"&&r.length>n?`${r.slice(0,n)}\u2026[${r.length-n} more chars elided]`:r})}function HO(o,n){return n&&typeof n=="object"&&n.$mid===1&&Aw(n)?v.revive(n).toString():n}function _B(o){return o.toISOString().replace(/[:.]/g,"-")}function TB(o){return o.replace(/[\\/:\*\?"<>\|\s]+/g,"-").replace(/^-+|-+$/g,"")||"connection"}var j_=class extends x{constructor(e,t,r){super();this._ws=e;this._WebSocket=t;this._ahpLogger=r;this._onMessage=this._register(new E);this.onMessage=this._onMessage.event;this._onClose=this._register(new E);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",V_(s)),this._onMessage.fire(a)}catch{this.send({jsonrpc:"2.0",id:null,error:{code:qf,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",V_(t)),this._ws.send(t)}}dispose(){this._ws.close(),super.dispose()}},cc=class o extends x{constructor(e,t,r,i,s,a){super();this._logService=t;this._ahpLogOptions=r;this._connectionCount=0;this._onConnection=this._register(new E);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 h=a.parse(u.req.url??"",!0).query[uS];if(!l.connectionTokenValidate(h)){this._logService.warn("[WebSocketProtocol] Connection rejected: invalid connection token"),p(!1,403,"Forbidden");return}p(!0)}:void 0;if(l.socketPath){this._httpServer=s.createServer(),this._wss=new i.WebSocketServer({server:this._httpServer,verifyClient:c});let u=this._httpServer;this.whenListening=new Promise((p,g)=>{u.once("listening",()=>{this._logService.info(`[WebSocketProtocol] Server listening on socket ${l.socketPath}`),p()}),u.once("error",g)}),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,g)=>{u.once("listening",()=>{let h=u.address(),y=!h||typeof h=="string"?`${d}:${l.port}`:`${h.address}:${h.port}`;this._logService.info(`[WebSocketProtocol] Server listening on ${y}`),p()}),u.once("error",g)})}this._wss.on("connection",u=>{this._logService.trace("[WebSocketProtocol] New client connection");let p=new j_(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(dc,{logsHome:this._ahpLogOptions.logsHome,connectionId:`agent-host-${++this._connectionCount}-${F()}`,transport:"websocket"})}dispose(){this._wss.close(),this._httpServer?.close(),super.dispose()}};var iv=class extends x{constructor(){super(...arguments);this._onConnection=this._register(new E);this.onConnection=this._onConnection.event;this.address=void 0;this._transports=new Map}listen(e,t){switch(t){case"frame":return this._getOrCreateTransport(e).onFrame;case"close":return this._getOrCreateTransport(e).onClose}throw new Error(`Invalid listen: ${t}`)}async call(e,t,r){switch(t){case"connect":{let i=this._getOrCreateTransport(e);i.connect()&&this._onConnection.fire(i);return}case"send":{if(typeof r!="string")throw new Error("send: arg must be a string frame");let i=this._transports.get(e);if(!i?.isConnected)throw new Error("send: client is not connected");i.acceptFrame(r);return}case"close":this.closeClient(e);return}throw new Error(`Invalid call: ${t}`)}closeClient(e){let t=this._transports.get(e);t&&(this._transports.delete(e),t.dispose())}dispose(){let e=[...this._transports.values()];this._transports.clear();for(let t of e)t.dispose();super.dispose()}_getOrCreateTransport(e){if(this._store.isDisposed)throw new Error("MessagePortProtocolServer is disposed");let t=this._transports.get(e);if(!t){t=new K_,this._transports.set(e,t);let r=t.onClose(()=>{r.dispose(),this._transports.get(e)===t&&this._transports.delete(e)})}return t}},K_=class extends x{constructor(){super(...arguments);this._onFrame=this._register(new E);this.onFrame=this._onFrame.event;this._onMessage=this._register(new E);this.onMessage=this._onMessage.event;this._onClose=this._register(new E);this.onClose=this._onClose.event;this._isConnected=!1;this._isClosed=!1}get isConnected(){return this._isConnected&&!this._isClosed}connect(){return this._isClosed||this._isConnected?!1:(this._isConnected=!0,!0)}acceptFrame(e){try{this._onMessage.fire(JSON.parse(e))}catch{this.send({jsonrpc:"2.0",id:null,error:{code:qf,message:"Parse error"}})}}send(e){this.isConnected&&this._onFrame.fire(JSON.stringify(e))}dispose(){this._isClosed||(this._isClosed=!0,this._isConnected=!1,this._onClose.fire(),super.dispose())}};import{execFile as wB}from"child_process";import{createHash as WO,randomBytes as $O}from"crypto";import*as Wt from"fs";import*as qO from"os";var J_=1,RB="agent-host",xB="local-endpoint",AB="metadata.json",PB=Qi(jd({type:gD("editor"),schemaVersion:so(),pid:so(),instanceId:Xt(),endpointPath:Xt(),connectionToken:Xt(),protocolVersion:Xt()}));function BO(o){let n=$O(16).toString("base64url");return{type:"editor",schemaVersion:J_,pid:process.pid,instanceId:n,endpointPath:EB(o,n),connectionToken:$O(32).toString("base64url"),protocolVersion:ns}}async function zO(o){let n=JO(o);await Wt.promises.mkdir(n,{recursive:!0,mode:448});let e=await Wt.promises.lstat(n);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Local agent host endpoint metadata directory is not a directory: ${n}`);if(process.platform==="win32")await kB(n);else{if(process.getuid&&e.uid!==process.getuid())throw new Error(`Local agent host endpoint metadata directory is not owned by the current user: ${n}`);await Wt.promises.chmod(n,448)}}async function VO(o){if(process.platform!=="win32"){let n=QO(o);await Wt.promises.mkdir(n,{recursive:!0,mode:448});let e=await Wt.promises.lstat(n);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Local agent host endpoint socket directory is not a directory: ${n}`);if(process.getuid&&e.uid!==process.getuid())throw new Error(`Local agent host endpoint socket directory is not owned by the current user: ${n}`);await Wt.promises.chmod(n,448)}}async function jO(o,n){let e=YO(o),t=`${e}.${n.instanceId}.tmp`,r=XO(e).filter(s=>s.pid!==n.pid||s.type!==n.type);r.push(n);let i=await Wt.promises.open(t,"wx",384);try{await i.writeFile(JSON.stringify(r),"utf8"),await i.sync()}finally{await i.close()}try{await Wt.promises.rename(t,e)}finally{await Wt.promises.rm(t,{force:!0})}}function KO(o,n){let e=YO(o),t=XO(e),r=t.filter(i=>i.pid!==n.pid||i.instanceId!==n.instanceId||i.type!==n.type);r.length!==t.length&&(r.length===0?Wt.rmSync(e,{force:!0}):Wt.writeFileSync(e,JSON.stringify(r),{encoding:"utf8",mode:384}))}function GO(o){process.platform!=="win32"&&Wt.rmSync(o,{force:!0})}function JO(o){return V(o,RB,xB)}function YO(o){return V(JO(o),AB)}function QO(o){let n=process.getuid?.().toString()??"",e=WO("sha256").update(`${n}:${o}`).digest("hex").slice(0,12);return V(qO.tmpdir(),`vscode-ah-${e}`)}function EB(o,n){return process.platform==="win32"?`\\\\.\\pipe\\vscode-agent-host-${WO("sha256").update(o).digest("hex")}-${n}`:V(QO(o),`${n}.sock`)}function XO(o){try{let n=Wt.lstatSync(o);if(!n.isFile()||n.isSymbolicLink())return[];let e=PB.validate(JSON.parse(Wt.readFileSync(o,"utf8")));return e.error?[]:e.content.filter(t=>t.schemaVersion===J_).map(t=>({...t,schemaVersion:J_}))}catch(n){if(DB(n)||n instanceof SyntaxError)return[];throw n}}async function kB(o){let n=process.env.SystemRoot??process.env.WINDIR;if(!n)throw new Error("Unable to resolve the Windows system directory for local agent host metadata.");let e=V(n,"System32"),r=(await G_(V(e,"whoami.exe"),["/user","/fo","csv","/nh"])).match(/S-\d+(?:-\d+)+/)?.[0];if(!r)throw new Error("Unable to determine the current Windows user SID for local agent host metadata.");let i=V(e,"icacls.exe");await G_(i,[o,"/reset"]),await G_(i,[o,"/inheritance:r","/grant:r",`*${r}:(OI)(CI)F`,"*S-1-5-18:(OI)(CI)F","*S-1-5-32-544:(OI)(CI)F"])}function G_(o,n){return new Promise((e,t)=>{wB(o,[...n],{encoding:"utf8",windowsHide:!0},(r,i)=>r?t(r):e(String(i)))})}function DB(o){return o?.code==="ENOENT"}var sv=class{constructor(n,e){this._agentService=n;this._connectionTrackerService=e}createSessionWithExtensions(n){return this._agentService.createSession(n)}createChatWithExtensions(n,e,t){return this._agentService.createChat(n,e,t)}shutdown(){return this._agentService.shutdown()}getNetworkDiagnosticsInfo(){return this._agentService.getNetworkDiagnosticsInfo()}getManagedSettingsDiagnostics(){return this._agentService.getManagedSettingsDiagnostics()}diagnosticsFetch(n){return this._agentService.diagnosticsFetch(n)}startWebSocketServer(){return this._connectionTrackerService.startWebSocketServer()}getInspectInfo(n){return this._connectionTrackerService.getInspectInfo(n)}};import{homedir as HB,tmpdir as $B}from"os";var ZO=/^([^.]+\..+)[:=](.+)$/,Ie=class{constructor(n,e,t){this._args=n;this.paths=e;this.productService=t}get appRoot(){return te(Nt.asFileUri("").fsPath)}get userHome(){return v.file(this.paths.homeDir)}get userDataPath(){return this.paths.userDataDir}get appSettingsHome(){return v.file(V(this.userDataPath,"User"))}get tmpDir(){return v.file(this.paths.tmpDir)}get cacheHome(){return v.file(this.userDataPath)}get stateResource(){return Y(this.appSettingsHome,"globalStorage","storage.json")}get userRoamingDataHome(){return this.appSettingsHome.with({scheme:ne.vscodeUserData})}get userDataSyncHome(){return Y(this.appSettingsHome,"sync")}get logsHome(){if(!this.args.logsPath){let n=_k(new Date).replace(/-|:|\.\d+Z$/g,"");this.args.logsPath=V(this.userDataPath,"logs",n)}return v.file(this.args.logsPath)}get sync(){return this.args.sync}get workspaceStorageHome(){return Y(this.appSettingsHome,"workspaceStorage")}get localHistoryHome(){return Y(this.appSettingsHome,"History")}get keyboardLayoutResource(){return Y(this.userRoamingDataHome,"keyboardLayout.json")}get argvResource(){let n=at.VSCODE_PORTABLE;return n?v.file(V(n,"argv.json")):Y(this.appSettingsHome,"argv.json")}get isExtensionDevelopment(){return!!this.args.extensionDevelopmentPath}get untitledWorkspacesHome(){return v.file(V(this.userDataPath,"Workspaces"))}get builtinExtensionsPath(){let n=this.args["builtin-extensions-dir"];return n?Xn(n):Rn(V(Nt.asFileUri("").fsPath,"..","extensions"))}get extensionsDownloadLocation(){let n=this.args["extensions-download-dir"];return n?v.file(Xn(n)):v.file(V(this.userDataPath,"CachedExtensionVSIXs"))}get extensionsPath(){let n=this.args["extensions-dir"];if(n)return Xn(n);let e=at.VSCODE_EXTENSIONS;if(e)return e;let t=at.VSCODE_PORTABLE;return t?V(t,"extensions"):Y(this.userHome,this.productService.dataFolderName,"extensions").fsPath}get appSharedDataHome(){let n=this.args["shared-data-dir"];if(n)return v.file(Xn(n));let e=at.VSCODE_PORTABLE;return e?v.file(V(e,"shared-data")):Y(this.userHome,this.productService.sharedDataFolderName)}get extensionDevelopmentLocationURI(){let n=this.args.extensionDevelopmentPath;if(Array.isArray(n))return n.map(e=>/^[^:/?#]+?:\/\//.test(e)?v.parse(e):v.file(Rn(e)))}get extensionDevelopmentKind(){return this.args.extensionDevelopmentKind?.map(n=>n==="ui"||n==="workspace"||n==="web"?n:"workspace")}get extensionTestsLocationURI(){let n=this.args.extensionTestsPath;if(n)return/^[^:/?#]+?:\/\//.test(n)?v.parse(n):v.file(Rn(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=at.VSCODE_SKIP_BUILTIN_EXTENSIONS;return n?n.split(",").map(e=>e.trim()).filter(e=>e):[]}get debugExtensionHost(){return MB(this.args,this.isBuilt)}get debugRenderer(){return!!this.args.debugRenderer}get isBuilt(){return!at.VSCODE_DEV}get verbose(){return!!this.args.verbose}get logLevel(){return this.args.log?.find(n=>!ZO.test(n))}get extensionLogLevel(){let n=[];for(let e of this.args.log||[]){let t=ZO.exec(e);t?.[1]&&t[2]&&n.push([t[1],t[2]])}return n.length?n:void 0}get serviceMachineIdResource(){return Y(v.file(this.userDataPath),"machineid")}get crashReporterId(){return this.args["crash-reporter-id"]}get crashReporterDirectory(){return this.args["crash-reporter-directory"]}get disableTelemetry(){return!!this.args["disable-telemetry"]}get disableExperiments(){return!!this.args["disable-experiments"]}get disableWorkspaceTrust(){return!!this.args["disable-workspace-trust"]}get useInMemorySecretStorage(){return!!this.args["use-inmemory-secretstorage"]}get policyFile(){if(this.args["__enable-file-policy"]){let n=at.VSCODE_PORTABLE;return n?v.file(V(n,"policy.json")):Y(this.userHome,this.productService.dataFolderName,"policy.json")}}get agentSessionsWorkspace(){return Y(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}};A([_e],Ie.prototype,"appRoot",1),A([_e],Ie.prototype,"userHome",1),A([_e],Ie.prototype,"userDataPath",1),A([_e],Ie.prototype,"appSettingsHome",1),A([_e],Ie.prototype,"tmpDir",1),A([_e],Ie.prototype,"cacheHome",1),A([_e],Ie.prototype,"stateResource",1),A([_e],Ie.prototype,"userRoamingDataHome",1),A([_e],Ie.prototype,"userDataSyncHome",1),A([_e],Ie.prototype,"sync",1),A([_e],Ie.prototype,"workspaceStorageHome",1),A([_e],Ie.prototype,"localHistoryHome",1),A([_e],Ie.prototype,"keyboardLayoutResource",1),A([_e],Ie.prototype,"argvResource",1),A([_e],Ie.prototype,"isExtensionDevelopment",1),A([_e],Ie.prototype,"untitledWorkspacesHome",1),A([_e],Ie.prototype,"builtinExtensionsPath",1),A([_e],Ie.prototype,"extensionsDownloadLocation",1),A([_e],Ie.prototype,"extensionsPath",1),A([_e],Ie.prototype,"appSharedDataHome",1),A([_e],Ie.prototype,"extensionDevelopmentLocationURI",1),A([_e],Ie.prototype,"extensionDevelopmentKind",1),A([_e],Ie.prototype,"extensionTestsLocationURI",1),A([_e],Ie.prototype,"debugExtensionHost",1),A([_e],Ie.prototype,"logLevel",1),A([_e],Ie.prototype,"extensionLogLevel",1),A([_e],Ie.prototype,"serviceMachineIdResource",1),A([_e],Ie.prototype,"disableTelemetry",1),A([_e],Ie.prototype,"disableExperiments",1),A([_e],Ie.prototype,"disableWorkspaceTrust",1),A([_e],Ie.prototype,"useInMemorySecretStorage",1),A([_e],Ie.prototype,"policyFile",1),A([_e],Ie.prototype,"agentSessionsWorkspace",1);function MB(o,n){return eL(o["inspect-extensions"],o["inspect-brk-extensions"],5870,n,o.debugId,o.extensionEnvironment)}function eL(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 tL}from"os";import{resolve as OB,isAbsolute as LB,join as uc}from"path";var NB=process.env.VSCODE_CWD||process.cwd();function nL(o,n){let e=UB(o,n),t=[e];return LB(e)||t.unshift(NB),OB(...t)}function UB(o,n){process.env.VSCODE_DEV&&(n="code-oss-dev");let e=process.env.VSCODE_PORTABLE;if(e)return uc(e,"user-data");let t=process.env.VSCODE_APPDATA;if(t)return uc(t,n);let r=o["user-data-dir"];return r||FB(n)}function FB(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=uc(e,"AppData","Roaming")}break;case"darwin":n=uc(tL(),"Library","Application Support");break;case"linux":n=process.env.XDG_CONFIG_HOME||uc(tL(),".config");break;default:throw new Error("Platform not supported")}return uc(n,o)}var av=class extends Ie{constructor(n,e){let t=HB();super(n,{homeDir:t,tmpDir:$B(),userDataDir:nL(n,e.nameShort)},e)}};import WB from"minimist";var Y$e={o:f(2585,null),e:f(2569,null),t:f(2599,null),m:f(2580,null)};var Y_={chat:{type:"subcommand",description:"Pass in a prompt to run in a chat session in the current working directory.",options:{_:{type:"string[]",description:f(2589,null)},mode:{type:"string",cat:"o",alias:"m",args:"mode",description:f(2556,null)},"add-file":{type:"string[]",cat:"o",alias:"a",args:"path",description:f(2551,null)},maximize:{type:"boolean",cat:"o",description:f(2555,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2592,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2583,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2588,null)},help:{type:"boolean",alias:"h",description:f(2571,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(2557,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(2557,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(2557,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(2561,null)},merge:{type:"boolean",cat:"o",alias:"m",args:["path1","path2","base","result"],description:f(2581,null)},add:{type:"boolean",cat:"o",alias:"a",args:"folder",description:f(2550,null)},remove:{type:"boolean",cat:"o",args:"folder",description:f(2590,null)},goto:{type:"boolean",cat:"o",alias:"g",args:"file:line[:character]",description:f(2570,null)},"new-window":{type:"boolean",cat:"o",alias:"n",description:f(2582,null)},"reuse-window":{type:"boolean",cat:"o",alias:"r",description:f(2591,null)},agents:{type:"boolean",cat:"o",deprecates:["sessions"],description:f(2553,null)},wait:{type:"boolean",cat:"o",alias:"w",description:f(2609,null)},waitMarkerFilePath:{type:"string"},locale:{type:"string",cat:"o",args:"locale",description:f(2577,null)},"user-data-dir":{type:"string",cat:"o",args:"dir",description:f(2606,null)},profile:{type:"string",cat:"o",args:"profileName",description:f(2588,null)},help:{type:"boolean",cat:"o",alias:"h",description:f(2571,null)},"stdin-to-clipboard":{type:"boolean",cat:"o",alias:"c",description:f(2558,null)},"extensions-dir":{type:"string",deprecates:["extensionHomePath"],cat:"e",args:"dir",description:f(2568,null)},"extensions-download-dir":{type:"string"},"builtin-extensions-dir":{type:"string"},"shared-data-dir":{type:"string"},"list-extensions":{type:"boolean",cat:"e",description:f(2576,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(2593,null)},category:{type:"string",allowEmptyValue:!0,cat:"e",description:f(2554,null),args:"category"},"install-extension":{type:"string[]",cat:"e",args:"ext-id | path",description:f(2575,null)},"pre-release":{type:"boolean",cat:"e",description:f(2574,null)},"uninstall-extension":{type:"string[]",cat:"e",args:"ext-id",description:f(2601,null)},"update-extensions":{type:"boolean",cat:"e",description:f(2604,null)},"enable-proposed-api":{type:"string[]",allowEmptyValue:!0,cat:"e",args:"ext-id",description:f(2567,null)},"add-mcp":{type:"string[]",cat:"m",args:"json",description:f(2552,null)},version:{type:"boolean",cat:"t",alias:"v",description:f(2608,null)},verbose:{type:"boolean",cat:"t",global:!0,description:f(2607,null)},log:{type:"string[]",cat:"t",args:"level",global:!0,description:f(2579,null)},status:{type:"boolean",alias:"s",cat:"t",description:f(2594,null)},"prof-startup":{type:"boolean",cat:"t",description:f(2587,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(2564,null)},"disable-extension":{type:"string[]",cat:"t",args:"ext-id",description:f(2563,null)},sync:{type:"string",cat:"t",description:f(2600,null),args:["on | off"]},"inspect-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugPluginHost"],args:"port",cat:"t",description:f(2573,null)},"inspect-brk-extensions":{type:"string",allowEmptyValue:!0,deprecates:["debugBrkPluginHost"],args:"port",cat:"t",description:f(2572,null)},"disable-lcd-text":{type:"boolean",cat:"t",description:f(2566,null)},"disable-gpu":{type:"boolean",cat:"t",description:f(2565,null)},"disable-chromium-sandbox":{type:"boolean",cat:"t",description:f(2562,null)},sandbox:{type:"boolean"},"locate-shell-integration-path":{type:"string",cat:"t",args:["shell"],description:f(2578,null)},telemetry:{type:"boolean",cat:"t",description:f(2597,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(2598,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[]"}},qB={onUnknownOption:()=>{},onMultipleValues:()=>{},onEmptyValue:()=>{},onDeprecatedOption:()=>{}};function lv(o,n,e=qB){let t=o.find((p,g)=>p.length>0&&p[0]!=="-"&&n.hasOwnProperty(p)&&n[p].type==="subcommand"),r={},i=["_"],s=[],a={},l;for(let p in n){let g=n[p];g.type==="subcommand"?p===t&&(l=g):(g.alias&&(r[p]=g.alias),g.type==="string"||g.type==="string[]"?(i.push(p),g.deprecates&&i.push(...g.deprecates)):g.type==="boolean"&&(s.push(p),g.deprecates&&s.push(...g.deprecates)),g.global&&(a[p]=g))}if(l&&t){let p=a;for(let I in l.options)p[I]=l.options[I];let g=o.filter(I=>I!==t),h=e.getSubcommandReporter?e.getSubcommandReporter(t):void 0,y=lv(g,p,h);return{[t]:y,_:[]}}let d=WB(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 g=n[p];if(g.type==="subcommand")continue;g.alias&&delete u[g.alias];let h=u[p];if(g.deprecates)for(let y of g.deprecates)u.hasOwnProperty(y)&&(h||(h=u[y],h&&e.onDeprecatedOption(y,g.deprecationMessage||f(2560,null,p))),delete u[y]);if(typeof h<"u"){if(g.type==="string[]"){if(Array.isArray(h)||(h=[h]),!g.allowEmptyValue){let y=h.filter(I=>I.length>0);y.length!==h.length&&(e.onEmptyValue(p),h=y.length>0?y:void 0)}}else g.type==="string"&&(Array.isArray(h)?(h=h.pop(),e.onMultipleValues(p,h)):!h&&!g.allowEmptyValue&&(e.onEmptyValue(p),h=void 0));c[p]=h,g.deprecationMessage&&e.onDeprecatedOption(p,g.deprecationMessage)}delete u[p]}for(let p in u)e.onUnknownOption(p);return c}var dv=class extends x{constructor(n,e=[]){super(),this.logger=new og([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 BB(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 rL(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 oL(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 cv=class extends Ms{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&&oL(this._logger,a)}))}async _createSpdLogLogger(e,t,r,i){let s=r?6:1,a=30/s*dg.MB,l=await BB(e,t,a,s,i);if(l){this._logger=l,oL(this._logger,this.getLevel());for(let{level:d,message:c}of this.buffer)rL(this._logger,d,c);this.buffer=[]}}log(e,t){this._logger?rL(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 uv=class extends du{doCreateLogger(n,e,t){return new cv(F(),n.fsPath,!t?.donotRotate,!!t?.donotUseFormatters,e)}};var pv=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=>nC(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 nC(t[0])?this.loggerService.setLogLevel(t[0]):this.loggerService.setLogLevel(v.revive(r.transformIncoming(t[0][0])),t[0][1]);case"getRegisteredLoggers":return Promise.resolve([...this.loggerService.getRegisteredLoggers()].map(i=>this.transformLogger(i,r)))}throw new Error(`Call not found: ${e}`)}transformLogger(n,e){return{...n,resource:e.transformOutgoingURI(n.resource)}}};var iL=new class{transformIncoming(o){return o}transformOutgoing(o){return o}transformOutgoingURI(o){return o}transformOutgoingScheme(o){return o}};function Q_(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 zB(){if(typeof performance=="object"&&typeof performance.mark=="function"&&!performance.nodeTiming)return typeof performance.timeOrigin!="number"&&!performance.timing?Q_():{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 Q_(o)}else return console.trace("perf-util loaded in UNKNOWN environment"),Q_()}function VB(o){return o.MonacoPerformanceMarks||(o.MonacoPerformanceMarks=zB()),o.MonacoPerformanceMarks}var X_=VB(globalThis),sL=X_.mark,O6e=X_.clearMarks,L6e=X_.getMarks;async function fv(o,n,e,t,r,i){let s;try{await jB(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 jB(o,n,e,t,r,i){Z_(i);let s=await o.open(n,{create:!1});try{Z_(i);let a=0,l=0,d=r&&typeof r.length=="number"?r.length:void 0,c=$.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=$.alloc(Math.min(r.bufferSize,typeof d=="number"?d:r.bufferSize)),p=0);while(l>0&&(typeof d!="number"||d>0)&&Z_(i)&&KB(a,r));if(p>0){let g=p;typeof d=="number"&&(g=Math.min(p,d)),e.write(t(c.slice(0,g)))}}catch(a){throw Oo(a)}finally{await o.close(s)}}function Z_(o){if(o.isCancellationRequested)throw $p();return!0}function KB(o,n){if(typeof n?.limits?.size=="number"&&o>n.limits.size)throw Ne(f(2768,null),"EntryTooLarge");return!0}var os=class extends x{constructor(e){super();this.logService=e;this.BUFFER_SIZE=256*1024;this._onDidChangeFileSystemProviderRegistrations=this._register(new E);this.onDidChangeFileSystemProviderRegistrations=this._onDidChangeFileSystemProviderRegistrations.event;this._onWillActivateFileSystemProvider=this._register(new E);this.onWillActivateFileSystemProvider=this._onWillActivateFileSystemProvider.event;this._onDidChangeFileSystemProviderCapabilities=this._register(new E);this.onDidChangeFileSystemProviderCapabilities=this._onDidChangeFileSystemProviderCapabilities.event;this.provider=new Map;this._onDidRunOperation=this._register(new E);this.onDidRunOperation=this._onDidRunOperation.event;this.internalOnDidFilesChange=this._register(new E);this._onDidUncorrelatedFilesChange=this._register(new E);this.onDidFilesChange=this._onDidUncorrelatedFilesChange.event;this._onDidWatchError=this._register(new E);this.onDidWatchError=this._onDidWatchError.event;this.activeWatchers=new Map;this.writeQueue=this._register(new si)}registerProvider(e,t){if(this.provider.has(e))throw new Error(`A filesystem provider for the scheme '${e}' is already registered.`);sL(`code/registerFilesystem/${e}`);let r=new G;return this.provider.set(e,t),this._onDidChangeFileSystemProviderRegistrations.fire({added:!0,scheme:e,provider:t}),r.add(t.onDidChangeFile(i=>{let s=new lg(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}))),U(()=>{this._onDidChangeFileSystemProviderRegistrations.fire({added:!1,scheme:e,provider:t}),this.provider.delete(e),tn(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 vr.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 Sa.map(this.provider,([e,t])=>({scheme:e,capabilities:t.capabilities}))}async withProvider(e){if(!Nw(e))throw new vt(f(2757,null,this.resourceForError(e)),8);await this.activateProvider(e.scheme);let t=this.provider.get(e.scheme);if(!t){let r=new Jn;throw r.message=f(2759,null,e.toString()),r}return t}async withReadProvider(e){let t=await this.withProvider(e);if(Mo(t)||Wn(t)||cg(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(Mo(t)||Wn(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 cu(r)==="EntryNotFound"?new vt(f(2754,null,this.resourceForError(e)),1):Oo(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=qr.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:dC({mtime:r.mtime,size:r.size}),children:void 0};if(d.isDirectory&&a(d,i)){try{let c=await e.readdir(t),u=await vr.settled(c.map(async([p,g])=>{try{let h=l.joinPath(t,p),y=s?await e.stat(h):{type:g};return await this.toFileStat(e,h,y,c.length,s,a)}catch(h){return this.logService.trace(h),null}}));d.children=Qo(u)}catch(c){this.logService.trace(c),d.children=[]}return d}return d}async resolveAll(e){return vr.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(Xx(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 vt(f(2750,null,this.resourceForError(e)),3,t)}async createFile(e,t=$.fromString(""),r){await this.doValidateCreateFile(e,r);let i=await this.writeFile(e,t);return this._onDidRunOperation.fire(new ko(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(lC(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)),!Mo(i)||Wn(i)&&d instanceof $||Wn(i)&&lC(i)&&a?.atomic?await this.doWriteUnbuffered(i,e,a,d):await this.doWriteBuffered(i,e,a,d instanceof $?Jw(d):d),this._onDidRunOperation.fire(new ko(e,4))}catch(l){throw new vt(f(2749,null,this.resourceForError(e),Oo(l).toString()),Vt(l),a)}return this.resolve(e,{resolveMetadata:!0})}async peekBufferForWriting(e,t){let r;if(Wn(e)&&!(t instanceof $))if(Ec(t)){let i=await zw(t,3);i.ended?r=$.concat(i.buffer):r=i}else r=Bw(t,i=>$.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(2767,null,this.resourceForError(t)));if(i?.append&&!Yx(e))throw new vt(f(2746,null,this.resourceForError(t)),6);if(!!i?.atomic){if(!(e.capabilities&32768))throw new Error(f(2765,null,this.resourceForError(t)));if(!(e.capabilities&2))throw new Error(f(2766,null,this.resourceForError(t)));if(s)throw new Error(f(2764,null,this.resourceForError(t)))}let l;try{l=await e.stat(t)}catch{return Object.create(null)}if((l.type&2)!==0)throw new vt(f(2752,null,this.resourceForError(t)),0,i);this.throwIfFileIsReadonly(t,l);let d;if(typeof i?.mtime=="number"&&typeof i.etag=="string"&&i.etag!==pg&&typeof l.mtime=="number"&&typeof l.size=="number"&&i.mtime<l.mtime&&i.etag!==dC({mtime:i.mtime,size:l.size})){if(d=await this.peekBufferForWriting(e,r),d instanceof $&&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 vt(f(2753,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 Nr(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 dt(i),a=r;ug(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!==pg&&await l,a?.atomic&&ug(e)||!(Mo(e)||cg(e))||Wn(e)&&a?.preferUnbuffered?d=this.readFileUnbuffered(e,t,a):cg(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 vf(d),this.restoreReadError(c,t,a)}}restoreReadError(e,t,r){let i=f(2747,null,this.resourceForError(t),Oo(e).toString());return e instanceof ol?new ol(i,e.stat,r):e instanceof rl?new rl(i,e.fileOperationResult,e.size,e.options):new vt(i,Vt(e),r)}readFileStreamed(e,t,r,i=Object.create(null)){let s=e.readFileStream(t,i,r);return Cf(s,{data:a=>a instanceof $?a:$.wrap(a),error:a=>this.restoreReadError(a,t,i)},a=>$.concat(a))}readFileBuffered(e,t,r,i=Object.create(null)){let s=Dc();return fv(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=bo(s=>$.concat(s));return(async()=>{try{let s;r?.atomic&&ug(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($.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 vt(f(2751,null,this.resourceForError(e)),0,t);if(typeof t?.etag=="string"&&t.etag!==pg&&t.etag===r.etag)throw new ol(f(2755,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 rl(f(2756,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 ko(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 ko(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&&aC(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(Mo(e)&&Mo(r))return this.doPipeBuffered(e,t,r,i);if(Mo(e)&&Wn(r))return this.doPipeBufferedToUnbuffered(e,t,r,i);if(Wn(e)&&Mo(r))return this.doPipeUnbufferedToBuffered(e,t,r,i);if(Wn(e)&&Wn(r))return this.doPipeUnbuffered(e,t,r,i)}async doCopyFolder(e,t,r,i){await r.mkdir(i),Array.isArray(t.children)&&await vr.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(2760,null,this.resourceForError(t),this.resourceForError(i)));if(!l&&c.isEqualOrParent(i,t))throw new Error(f(2761,null,this.resourceForError(t),this.resourceForError(i)))}let d=await this.exists(i);if(d&&!l){if(!a)throw new vt(f(2762,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(2763,null,this.resourceForError(t),this.resourceForError(i)))}}return{exists:d,isSameResourceWithDifferentPathCase:l}}getExtUri(e){let t=this.isPathCaseSensitive(e);return{providerExtUri:t?ye:fS,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 ko(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(2758,null,this.resourceForError(t)));break}catch(s){if(cu(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(cu(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(2745,null,this.resourceForError(e)));let s=t?.atomic;if(s&&!(r.capabilities&65536))throw new Error(f(2741,null,this.resourceForError(e)));if(i&&s)throw new Error(f(2744,null,this.resourceForError(e)));let a;try{a=await r.stat(e)}catch{}if(a)this.throwIfFileIsReadonly(e,a);else throw new vt(f(2743,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(2742,null,this.resourceForError(e)))}return r}async del(e,t){let r=await this.doValidateDelete(e,t),i=t;if(Zx(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 ko(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&&Qx(r)?r.cloneFile(e,t):(await this.mkdirp(i,this.getExtUri(i).providerExtUri.dirname(t)),r===i&&aC(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:os.WATCHER_CORRELATION_IDS++})}watch(e,t={recursive:!1,excludes:[]}){let r=new G,i=!1,s=()=>{i=!0};r.add(U(()=>s())),(async()=>{try{let l=await this.doWatch(e,t);i?tn(l):s=()=>tn(l)}catch(l){this.logService.error(l)}})();let a=t.correlationId;if(typeof a=="number"){let l=r.add(new E);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=kn([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,U(()=>{s&&(s.count--,s.count===0&&(tn(s.disposable),this.activeWatchers.delete(i)))})}dispose(){super.dispose();for(let[,e]of this.activeWatchers)tn(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{Ec(i)||yf(i)?await this.doWriteStreamBufferedQueued(e,s,i):await this.doWriteReadableBufferedQueued(e,s,i)}catch(a){throw Oo(a)}finally{await e.close(s)}},this.getExtUri(e).providerExtUri)}async doWriteStreamBufferedQueued(e,t,r){let i=0,s;if(yf(r)){if(r.buffer.length>0){let a=$.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)=>{Sf(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 $?s=i:Ec(i)?s=await Nr(i):yf(i)?s=await Yw(i):s=Gw(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=$.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 Oo(l)}finally{await vr.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,$.wrap(a),a.byteLength,0,0)}catch(a){throw Oo(a)}finally{await r.close(s)}}async doPipeBufferedToUnbuffered(e,t,r,i){let s=await Nr(this.readFileBuffered(e,t,ke.None));await this.doWriteUnbuffered(r,i,void 0,s)}throwIfFileSystemIsReadonly(e,t){if(e.capabilities&2048)throw new vt(f(2748,null,this.resourceForError(t)),6);return e}throwIfFileIsReadonly(e,t){if((t.permissions??0)&1)throw new vt(f(2748,null,this.resourceForError(e)),6)}resourceForError(e){return e.scheme===ne.file?e.fsPath:e.toString(!0)}};os=A([b(0,O)],os);import{constants as rT,promises as fa}from"fs";function yv(o){return typeof o.correlationId=="number"}function aL(o){return o.recursive===!0}var gv=class o extends x{constructor(e,t,r,i){super();this.onFileChanges=e;this.onLogMessage=t;this.verboseLogging=r;this.options=i;this.watcherDisposables=this._register(new ht);this.requests=void 0;this.restartCounter=0}static{this.MAX_RESTARTS=5}init(){let e=new G;this.watcherDisposables.value=e,this.watcher=this.createWatcher(e),this.watcher.setVerboseLogging(this.verboseLogging),e.add(this.watcher.onDidChangeFile(t=>this.onFileChanges(t))),e.add(this.watcher.onDidLogMessage(t=>this.onLogMessage(t))),e.add(this.watcher.onDidError(t=>this.onError(t.error,t.request)))}onError(e,t){this.canRestart(e,t)?this.restartCounter<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()}},mv=class extends gv{constructor(n,e,t){super(n,e,t,{type:"node.js",restartOnError:!1})}},hv=class extends gv{constructor(n,e,t){super(n,e,t,{type:"universal",restartOnError:!0})}};function tT(o){return o.map(n=>({type:n.type,resource:v.revive(n.resource),cId:n.cId}))}function lL(o){let n=new eT;for(let e of o)n.processEvent(e);return n.coalesce()}function GB(o,n){return typeof n=="string"&&!n.startsWith(Fl)&&!nn(n)?{base:o,pattern:n}:n}function nT(o,n,e){let t=[];for(let r of n)t.push(js(GB(o,r),{ignoreCase:e}));return t}var eT=class{constructor(){this.coalesced=new Set;this.mapPathToChange=new Map}toKey(n){return Fe?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=>eA(t.resource.fsPath,r,!Fe))?!1:(e.push(t.resource.fsPath),!0)).concat(n)}};function dL(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 cL(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 vv=class extends x{constructor(e,t){super();this.logService=e;this.options=t;this._onDidChangeFile=this._register(new E);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidWatchError=this._register(new E);this.onDidWatchError=this._onDidWatchError.event;this.universalWatchRequests=[];this.universalWatchRequestDelayer=this._register(new ms(this.getRefreshWatchersDelay(this.universalWatchRequests.length)));this.nonRecursiveWatchRequests=[];this.nonRecursiveWatchRequestDelayer=this._register(new ms(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=Ov(this.universalWatchRequests,r);return this.refreshUniversalWatchers(),U(()=>{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(aL(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=>Ye(e))}doRefreshUniversalWatchers(){return this.universalWatcher||(this.universalWatcher=this._register(this.createUniversalWatcher(e=>this._onDidChangeFile.fire(tT(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=Ov(this.nonRecursiveWatchRequests,r);return this.refreshNonRecursiveWatchers(),U(()=>{i(),this.refreshNonRecursiveWatchers()})}refreshNonRecursiveWatchers(){this.nonRecursiveWatchRequestDelayer.trigger(()=>this.doRefreshNonRecursiveWatchers(),this.getRefreshWatchersDelay(this.nonRecursiveWatchRequests.length)).catch(e=>Ye(e))}doRefreshNonRecursiveWatchers(){return this.nonRecursiveWatcher||(this.nonRecursiveWatcher=this._register(this.createNonRecursiveWatcher(e=>this._onDidChangeFile.fire(tT(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 Rn(e.fsPath)}toWatchPath(e){let t=this.toFilePath(e);return _w(t)}};var Sv=class extends hv{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){let e=n.add(new xf(Nt.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)`))),vs.toService(Zw(e.getChannel("watcher")))}};import{watchFile as JB,unwatchFile as YB}from"fs";var Cv=class extends x{constructor(){super();this._onDidChangeFile=this._register(new E);this.onDidChangeFile=this._onDidChangeFile.event;this._onDidLogMessage=this._register(new E);this.onDidLogMessage=this._onDidLogMessage.event;this._onDidWatchFail=this._register(new E);this.onDidWatchFail=this._onDidWatchFail.event;this.correlatedWatchRequests=new Map;this.nonCorrelatedWatchRequests=new Map;this.suspendedWatchRequests=this._register(new Ee);this.suspendedWatchRequestsWithPolling=new Set;this.updateWatchersDelayer=this._register(new ms(this.getUpdateWatchersDelay()));this.suspendedWatchRequestPollingInterval=5007;this.joinWatch=new be;this.verboseLogging=!1;this._register(this.onDidWatchFail(e=>this.suspendWatchRequest({id:this.computeId(e),correlationId:this.isCorrelated(e)?e.correlationId:void 0,path:e.path})))}isCorrelated(e){return yv(e)}computeId(e){return this.isCorrelated(e)?e.correlationId:kn(e)}async watch(e){this.joinWatch.isSettled||this.joinWatch.complete(),this.joinWatch=new be;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=>Ye(r))}getUpdateWatchersDelay(){return 800}isSuspended(e){let t=this.computeId(e);return this.suspendedWatchRequestsWithPolling.has(t)?"polling":this.suspendedWatchRequests.has(t)}async suspendWatchRequest(e){if(this.suspendedWatchRequests.has(e.id))return;let t=new G;this.suspendedWatchRequests.set(e.id,t),await this.joinWatch.p,!t.isDisposed&&(this.monitorSuspendedWatchRequest(e,t),this.updateWatchers(!0))}resumeWatchRequest(e){this.suspendedWatchRequests.deleteAndDispose(e.id),this.suspendedWatchRequestsWithPolling.delete(e.id),this.updateWatchers(!1)}monitorSuspendedWatchRequest(e,t){this.doMonitorWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher to monitor ${e.path}`),this.suspendedWatchRequestsWithPolling.delete(e.id)):(this.doMonitorWithNodeJS(e,t),this.suspendedWatchRequestsWithPolling.add(e.id))}doMonitorWithExistingWatcher(e,t){let r=this.recursiveWatcher?.subscribe(e.path,(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{JB(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(U(()=>{this.trace(`stopping fs.watchFile() on ${e.path} (correlationId: ${e.correlationId})`);try{YB(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:v.file(e.path),type:1,cId:e.correlationId};this._onDidChangeFile.fire([t]),this.traceEvent(t,e),this.resumeWatchRequest(e)}isPathNotFound(e){return e.ctimeMs===0&&e.ino===0}async stop(){this.suspendedWatchRequests.clearAndDisposeAll(),this.suspendedWatchRequestsWithPolling.clear()}traceEvent(e,t){if(this.verboseLogging){let r=` >> normalized ${e.type===1?"[ADDED]":e.type===2?"[DELETED]":"[CHANGED]"} ${e.resource.fsPath}`;this.traceWithCorrelation(r,t)}}traceWithCorrelation(e,t){this.verboseLogging&&this.trace(`${e}${typeof t.correlationId=="number"?` <${t.correlationId}> `:""}`)}requestToString(e){return`${e.path} (excludes: ${e.excludes.length>0?e.excludes:"<none>"}, includes: ${e.includes&&e.includes.length>0?JSON.stringify(e.includes):"<all>"}, filter: ${cL(e.filter)}, correlationId: ${typeof e.correlationId=="number"?e.correlationId:"<none>"})`}async setVerboseLogging(e){this.verboseLogging=e}};import{watch as QB,promises as XB}from"fs";var Iv=class o extends x{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 Da({maxWorkChunkSize:100,throttleDelay:200,maxBufferedWork:1e4},e=>this.onDidFilesChange(e)));this.fileChangesAggregator=this._register(new ff(e=>this.handleFileChanges(e),o.FILE_CHANGES_HANDLER_DELAY));this.cts=new dt;this.realPath=new Xe(async()=>{let e=this.request.path;try{e=await Ge.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=!Fe;this.excludes=nT(this.request.path,this.request.excludes,l),this.includes=this.request.includes?nT(this.request.path,this.request.includes,l):void 0,this.filter=yv(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 XB.stat(this.request.path);if(this.cts.token.isCancellationRequested)return;await $v(this.doWatch(e.isDirectory()),this._store)}catch(e){e.code!=="ENOENT"?this.error(e):this.trace(`ignoring a path for watching who's stat info failed to resolve: ${this.request.path} (error: ${e})`),this.notifyWatchFailed()}}notifyWatchFailed(){this.didFail=!0,this.onDidWatchFail?.()}async doWatch(e){let t=new G;return this.doWatchWithExistingWatcher(e,t)?(this.trace(`reusing an existing recursive watcher for ${this.request.path}`),this._isReusingRecursiveWatcher=!0):(this._isReusingRecursiveWatcher=!1,await this.doWatchWithNodeJS(e,t)),t}doWatchWithExistingWatcher(e,t){if(e)return!1;let r=v.file(this.request.path),i=this.recursiveWatcher?.subscribe(this.request.path,async(s,a)=>{t.isDisposed||(s?await $v(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(ft&&Co(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 dt(this.cts.token);t.add(U(()=>i.dispose(!0)));let s=new G;t.add(s);try{let a=v.file(this.request.path),l=ue(r),d=QB(r);s.add(U(()=>{d.removeAllListeners(),d.close()})),this.trace(`Started watching: '${r}'`);let c=new Set;if(e)try{for(let p of await Ge.readdir(r))c.add(p)}catch(p){this.error(p)}if(i.token.isCancellationRequested)return;let u=new Map;s.add(U(()=>{for(let[,p]of u)p.dispose();u.clear()})),d.on("error",(p,g)=>{i.token.isCancellationRequested||(this.error(`Failed to watch ${r} for changes using fs.watch() (${p}, ${g})`),this.notifyWatchFailed())}),d.on("change",(p,g)=>{if(i.token.isCancellationRequested)return;this.verboseLogging&&this.traceWithCorrelation(`[raw] ["${p}"] ${g}`);let h="";if(g&&(h=g.toString(),ft&&(h=Fc(h))),!(!h||p!=="change"&&p!=="rename"))if(e)if(p==="rename"){u.get(h)?.dispose();let y=setTimeout(async()=>{if(u.delete(h),Ea(h,l,!Fe)&&!await Ge.exists(r)){this.onWatchedPathDeleted(a);return}if(i.token.isCancellationRequested)return;let I=await this.existsChildStrictCase(V(r,h));if(i.token.isCancellationRequested)return;let S;I?c.has(h)?S=0:(S=1,c.add(h)):(c.delete(h),S=2),this.onFileChange({resource:Y(a,h),type:S,cId:this.request.correlationId})},o.FILE_DELETE_HANDLER_DELAY);u.set(h,U(()=>clearTimeout(y)))}else{let y;c.has(h)?y=0:(y=1,c.add(h)),this.onFileChange({resource:Y(a,h),type:y,cId:this.request.correlationId})}else if(p==="rename"||!Ea(h,l,!Fe)){let y=setTimeout(async()=>{let I=await Ge.exists(r);i.token.isCancellationRequested||(I?(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(U(()=>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=lL(e),r=[];for(let s of t){if(dL(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(Fe)return Ge.exists(e);try{let t=ue(e);return(await Ge.readdir(te(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 bv=class extends Cv{constructor(e){super();this.recursiveWatcher=e;this.onDidError=ee.None;this._watchers=new Map;this.worker=this._register(new ht)}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&&RI(s.request.excludes,i.excludes)&&RI(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 Da({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 Fe?e:e.toLowerCase()}startWatching(e){let t=new Iv(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 _v=class extends mv{constructor(n,e,t){super(n,e,t),this.init()}createWatcher(n){return n.add(new bv(void 0))}};var Tv=class o extends vv{constructor(){super(...arguments);this.onDidChangeCapabilities=ee.None;this.resourceLocks=new Me(e=>re.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,Fe&&(this._capabilities|=1024)),this._capabilities}async stat(e){try{let{stat:t,symbolicLink:r}=await hn.stat(this.toFilePath(e)),i;return(t.mode&128)===0&&(i=2),(t.mode&rT.S_IXUSR||t.mode&rT.S_IXGRP||t.mode&rT.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 Ge.realpath(t)}async readdir(e){try{let t=await Ge.readdir(this.toFilePath(e),{withFileTypes:!0}),r=[];return await Promise.all(t.map(async i=>{try{let s;i.isSymbolicLink()?s=(await this.stat(Y(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 cf;return this.resourceLocks.set(e,i),this.traceLock(`[Disk FileSystemProvider]: createResourceLock() - new resource lock created (${t})`),U(()=>{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 fa.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=bo(s=>$.concat(s.map(a=>$.wrap(a))).buffer);return fv(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,Y(Ut(e),`${Se(e)}${r.atomic.postfix}`),t,r):this.doWriteFile(e,t,r)}async canWriteFileAtomic(e){try{let t=this.toFilePath(e),{symbolicLink:r}=await hn.stat(t);if(r)return!1}catch{}return!0}async doWriteFileAtomic(e,t,r,i){let s=new G;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 Ge.exists(a)){if(!r.overwrite)throw Ne(f(2771,null),"EntryExists")}else if(!r.create)throw Ne(f(2774,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;Do(t)&&!r&&(s=await this.createResourceLock(e));let a;try{if(Do(t)&&t.unlock)try{let{stat:l}=await hn.stat(i);l.mode&128||await fa.chmod(i,l.mode|128)}catch(l){l.code!=="ENOENT"&&this.logService.trace(l)}if(X&&Do(t)&&!t.append)try{a=await Ge.open(i,"r+"),await Ge.ftruncate(a,0)}catch(l){if(l.code!=="ENOENT"&&this.logService.trace(l),typeof a=="number"){try{await Ge.close(a)}catch(d){this.logService.trace(d)}a=void 0}}typeof a!="number"&&(a=await Ge.open(i,Do(t)?t.append?"a":"w":"r"))}catch(l){throw s?.dispose(),Do(t)?await this.toFileSystemProviderWriteError(e,l):this.toFileSystemProviderError(l)}if(this.mapHandleToPos.set(a,0),Do(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 Ge.fdatasync(e)}catch(r){o.configureFlushOnWrite(!1),this.logService.error(r)}return await Ge.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 Ge.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 Ww(()=>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 Ge.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 fa.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=V(te(r),`${ue(r)}${t.atomic.postfix}`)),await Ge.rm(r,1,i)}else try{await fa.unlink(r)}catch(i){if(i.code==="EPERM"||i.code==="EISDIR"){let s=!1;try{let{stat:a,symbolicLink:l}=await hn.stat(r);s=a.isDirectory()&&!l}catch{}if(s)await fa.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 Ge.rename(i,s)}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2775,null,ue(i),ue(te(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 Ge.copy(i,s,{preserveSymlinks:!0})}catch(a){throw(a.code==="EINVAL"||a.code==="EBUSY"||a.code==="ENAMETOOLONG")&&(a=new Error(f(2769,null,ue(i),ue(te(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=Ea(s,a,!0)),l){if(r==="copy")throw Ne(f(2770,null),"EntryExists");if(r==="move")return}let c=await this.statIgnoreError(e);if(!c)throw Ne(f(2773,null),"EntryNotFound");let u=await this.statIgnoreError(t);if(u){if(!i)throw Ne(f(2772,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(Ea(i,s,!a))return;let l=new G;try{l.add(await this.createResourceLock(e)),l.add(await this.createResourceLock(t)),r&&await fa.mkdir(te(s),{recursive:!0}),await fa.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 Sv(i=>e(i),i=>t(i),r)}createNonRecursiveWatcher(e,t,r){return new _v(i=>e(i),i=>t(i),r)}toFileSystemProviderError(e){if(e instanceof nl)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 Ne(t,r)}async toFileSystemProviderWriteError(e,t){let r=this.toFileSystemProviderError(t);if(e&&r.code==="NoPermissions")try{let{stat:i}=await hn.stat(this.toFilePath(e));i.mode&128||(r=Ne(t,"EntryWriteLocked"))}catch(i){this.logService.trace(i)}return r}};import{parse as gL}from"url";import{spawn as ZB}from"child_process";import mBe from"assert";function oT(o){return o.VSCODE_CLI==="1"}var iT;async function uL(o,n,e,t){return e["force-disable-user-env"]?(n.trace("resolveShellEnv(): skipped (--force-disable-user-env)"),{}):X?(n.trace("resolveShellEnv(): skipped (Windows)"),{}):oT(t)&&!e["force-user-env"]?(n.trace("resolveShellEnv(): skipped (VSCODE_CLI is set)"),{}):(oT(t)?n.trace("resolveShellEnv(): running (--force-user-env)"):n.trace("resolveShellEnv(): running (macOS/Linux)"),iT||(iT=vr.withAsyncBody(async(r,i)=>{let s=new dt,a=1e4,l=o.getValue("application.shellEnvironmentResolutionTimeout");typeof l=="number"&&(a=Qk(l,1,120)*1e3);let d=setTimeout(()=>{s.dispose(!0),i(new Error(f(2904,null)))},a);try{r(await ez(n,s.token))}catch(c){!un(c)&&!s.token.isCancellationRequested?i(new Error(f(2902,null,De(c)))):r({})}finally{clearTimeout(d),s.dispose()}})),iT)}async function ez(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=F().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 Rg(qt,s);return o.trace("getUnixShellEnvironment#shell",a),new Promise((l,d)=>{if(n.isCancellationRequested)return d(new K);let c=ue(a),u,p,g="";/^(?:pwsh|powershell)(?:-preview)?$/.test(c)?(u=`& '${process.execPath}' ${g} -p '''${r}'' + JSON.stringify(process.env) + ''${r}'''`,p=["-Login","-Command"]):c==="nu"?(u=`^'${process.execPath}' ${g} -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}' ${g} -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 h=ZB(a,[...p,u],{detached:!0,stdio:["ignore","pipe","pipe"],env:s});n.onCancellationRequested(()=>(h.kill(),d(new K))),h.on("error",S=>{o.error("getUnixShellEnvironment#errorChildProcess",De(S)),d(S)});let y=[];h.stdout.on("data",S=>y.push(S));let I=[];h.stderr.on("data",S=>I.push(S)),h.on("close",(S,C)=>{let _=Buffer.concat(y).toString("utf8");o.trace("getUnixShellEnvironment#raw",_);let T=Buffer.concat(I).toString("utf8");if(T.trim()&&o.trace("getUnixShellEnvironment#stderr",T),S||C)return d(new Error(f(2903,null,S,C)));let w=i.exec(_),W=w?w[1]:"{}";try{let R=JSON.parse(W);e?R.ELECTRON_RUN_AS_NODE=e:delete R.ELECTRON_RUN_AS_NODE,t?R.ELECTRON_NO_ATTACH_CONSOLE=t:delete R.ELECTRON_NO_ATTACH_CONSOLE,delete R.VSCODE_RESOLVING_ENVIRONMENT,delete R.XDG_RUNTIME_DIR,o.trace("getUnixShellEnvironment#result",R),l(R)}catch(R){o.error("getUnixShellEnvironment#errorCaught",De(R)),d(R)}})})}import{parse as pL}from"url";function tz(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 fL(o,n,e={}){let t=pL(o),r=e.proxyUrl||tz(t,n);if(!r)return null;let i=pL(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:zp(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 nz}from"zlib";var rz=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),oz=/^(GET|HEAD|OPTIONS)$/i;function iz(o){if(o instanceof Error){let n=o.code;return!!n&&rz.has(n)}return!1}var pc=class extends mm{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 uL(this.configurationService,this.logService,this.environmentService.args,process.env)}catch(d){this.shellEnvErrorLogged||(this.shellEnvErrorLogged=!0,this.logService.error("resolving shell environment failed",In(d)))}let a={...process.env,...s},l=e.agent?e.agent:await fL(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,()=>mL(e,t))}async resolveProxy(e){}async lookupAuthorization(e){}async lookupKerberosAuthorization(e){try{let t=this.getConfigValue("http.proxyKerberosServicePrincipal");return"Negotiate "+await sz(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",Ml),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}};pc=A([b(1,ir),b(2,St),b(3,O)],pc);async function sz(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 az(o){return(gL(o.url).protocol==="https:"?await import("https"):await import("http")).request}async function mL(o,n){let t,r=oz.test(o.type||"GET");for(let i=1;i<=3;i++)try{return await lz(o,n)}catch(s){if(t=s,s instanceof K||!r||!iz(s)||i===3)throw s;await mn(100*i,n)}throw t}async function lz(o,n){return vr.withAsyncBody(async(e,t)=>{let r=gL(o.url),i=o.getRawRequest?o.getRawRequest(o):await az(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:zp(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=is(o.followRedirects)?o.followRedirects:3;if(d.statusCode&&d.statusCode>=300&&d.statusCode<400&&c>0&&d.headers.location)mL({...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(nz())),e({res:d,stream:Qw(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 dz=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","ENETDOWN","ENETUNREACH","EPROTO"]),cz=/^(GET|HEAD|OPTIONS)$/i;function uz(o){if(o instanceof Error){let n=o.code;return!!n&&dz.has(n)}return!1}var fc=class extends pc{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=cz.test(e.type||"GET");for(let a=1;a<=3;a++)try{return await this._requestAttempt(e,t)}catch(l){if(i=l,un(l)||!s||!uz(l)||a===3)throw l;await mn(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:pz(e),body:e.data,signal:s,cache:e.disableCache?"no-store":void 0}),l=a.body?mz(a.body,r,i):gz(i);return{res:{statusCode:a.status,headers:fz(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}}};fc=A([b(0,ir),b(1,St),b(2,O),b(3,Wi)],fc);function pz(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 fz(o){let n=Object.create(null);return o.headers.forEach((e,t)=>{n[t]=e}),n}function gz(o){let n=Dc();return n.end(),o.dispose(),n}function mz(o,n,e){let t=o.getReader(),r=Dc({highWaterMark:16}),i=r.destroy.bind(r);return r.destroy=()=>{n.abort(),t.cancel(),e.dispose(),i()},hz(t,r,e),r}async function hz(o,n,e){try{for(;;){let{done:t,value:r}=await o.read();if(t)break;await n.write($.wrap(r))}n.end()}catch(t){n.error(t instanceof Error?t:new Error(String(t))),n.end()}finally{e.dispose()}}async function hL(o,n,e,t,r){let i=new wi;o.set(pm,i);let s=Y(e.userRoamingDataHome,"settings.json"),a=r.add(new Dl(s,n,i,t));await a.initialize(),o.set(ir,a);let l=new Sd(a,t);o.set(Wi,l);let d=r.add(new fc(a,e,t,l));return o.set(Ri,d),{proxyResolver:l,requestService:d}}import*as CL from"fs";var yL=[{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 Dr(o,n){return new Promise((e,t)=>{o.exec(n,r=>r?t(r):e())})}function mt(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 lo(o,n,e){return new Promise((t,r)=>{o.get(n,e,(i,s)=>{if(i)return r(i);t(s)})})}function Jo(o,n,e){return new Promise((t,r)=>{o.all(n,e,(i,s)=>{if(i)return r(i);t(s)})})}function sT(o){return new Promise((n,e)=>{o.close(t=>t?e(t):n())})}function yz(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 vz(o,n){await Dr(o,"PRAGMA foreign_keys = ON");let t=(await lo(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 Dr(o,"BEGIN TRANSACTION");try{for(let i of r)await Dr(o,i.sql),await Dr(o,`PRAGMA user_version = ${i.version}`);await Dr(o,"COMMIT")}catch(i){throw await Dr(o,"ROLLBACK"),i}}}var wv=class o{constructor(n,e=yL){this._path=n;this._migrations=e;this._fileEditSequencer=new Ze;this._metadataSequencer=new Ze;this._pendingWrites=new Set}static async open(n,e=yL){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 CL.promises.mkdir(te(this._path),{recursive:!0});let n=await yz(this._path);try{await vz(n,this._migrations)}catch(e){throw await sT(n),this._dbPromise=void 0,e}if(this._closed)throw await sT(n),new Error("SessionDatabase has been disposed");return n})().catch(n=>{throw this._dbPromise=void 0,n})),this._dbPromise)}async getAllTables(){let n=await this._ensureDb();return(await Jo(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 mt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n])})}deleteTurn(n){return this._track(async()=>{let e=await this._ensureDb();await mt(e,"DELETE FROM turns WHERE id = ?",[n])})}setTurnEventId(n,e){return this._track(async()=>{let t=await this._ensureDb();await mt(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await mt(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 lo(e,"SELECT event_id FROM turns WHERE id = ?",[n]))?.event_id??void 0}async getNextTurnEventId(n){let e=await this._ensureDb();return(await lo(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 lo(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 mt(t,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n]),await mt(t,"UPDATE turns SET checkpoint_ref = ? WHERE id = ?",[e,n])})}async getTurnCheckpointRef(n){let e=await this._ensureDb();return(await lo(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 lo(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 Jo(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 mt(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 mt(e,"DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)",[n])})}deleteAllTurns(){return this._track(async()=>{let n=await this._ensureDb();await Dr(n,"DELETE FROM turns")})}insertLocalTurn(n){return this._track(async()=>{let e=await this._ensureDb();await mt(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 Jo(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 mt(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 mt(e,"INSERT OR IGNORE INTO turns (id) VALUES (?)",[n.turnId]),await mt(e,`INSERT OR REPLACE INTO file_edits
					(turn_id, tool_call_id, file_path, edit_type, original_path, before_content, after_content, added_lines, removed_lines)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[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 Jo(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 Jo(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 Jo(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 lo(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?SL(r.before_content):void 0,afterContent:r.after_content?SL(r.after_content):void 0}})}async getMetadata(n){let e=await this._ensureDb();return(await lo(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 Jo(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 mt(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 mt(r,"DELETE FROM chat_drafts WHERE chat_uri = ?",[t]);return}await mt(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 lo(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 mt(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 mt(t,"DELETE FROM reviewed_files WHERE uri = ? AND nonce = ?",[n.toString(),e])})}async getReviewedFiles(){let n=await this._ensureDb();return(await Jo(n,"SELECT uri, nonce FROM reviewed_files ORDER BY rowid",[])).map(vL)}async getReviewedFilesForUri(n){let e=await this._ensureDb();return(await Jo(e,"SELECT uri, nonce FROM reviewed_files WHERE uri = ? ORDER BY rowid",[n.toString()])).map(vL)}async isFileReviewed(n,e){let t=await this._ensureDb();return!!await lo(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 Dr(e,"PRAGMA defer_foreign_keys = ON"),await Dr(e,"BEGIN TRANSACTION");try{let t=[...n.keys()];if(t.length>0){let r=t.map(()=>"?").join(",");await mt(e,`DELETE FROM turns WHERE id NOT IN (${r})`,t)}for(let[r,i]of n)await mt(e,"UPDATE turns SET id = ? WHERE id = ?",[i,r]),await mt(e,"UPDATE file_edits SET turn_id = ? WHERE turn_id = ?",[i,r]);if(t.length>0){let r=t.map(()=>"?").join(",");await mt(e,`DELETE FROM local_turns WHERE turn_id NOT IN (${r})`,t)}for(let[r,i]of n)await mt(e,"UPDATE local_turns SET turn_id = ? WHERE turn_id = ?",[i,r]),await mt(e,"UPDATE local_turns SET anchor_turn_id = ? WHERE anchor_turn_id = ?",[i,r]);await Dr(e,"COMMIT")}catch(t){throw await Dr(e,"ROLLBACK"),t}})}async whenIdle(){for(;this._pendingWrites.size>0;)await Promise.allSettled([...this._pendingWrites])}async vacuumInto(n){let e=await this._ensureDb();await mt(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=>sT(n)).catch(()=>{})||!0)}dispose(){this.close()}};function vL(o){return{uri:v.parse(o.uri),nonce:o.nonce}}function SL(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 aT=class extends Ia{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 wv(t);return this.liveDatabases.add(r),r}destroyReferencedObject(e,t){this.liveDatabases.delete(t),t.dispose()}},gc=class{constructor(n,e,t,r){this._fileService=e;this._logService=t;this._onWillDeleteSessionData=new E;this._basePath=v.joinPath(n,"agentSessionData"),this._databases=new aT(r??(i=>v.joinPath(this._basePath,i,sl).fsPath),this._logService)}get onWillDeleteSessionData(){return this._onWillDeleteSessionData.event}getSessionDataDir(n){return v.joinPath(this._basePath,this._sanitizedSessionKey(n))}getSessionDataDirById(n){let e=n.replace(/[^a-zA-Z0-9_.-]/g,"-");return v.joinPath(this._basePath,e)}_sanitizedSessionKey(n){return this._dataKey(n).replace(/[^a-zA-Z0-9_.-]/g,"-")}_dataKey(n){let e=M.id(n);return n.authority?`${n.authority}-${e}`:e}openDatabase(n){return this._databases.acquire(this._sanitizedSessionKey(n))}async tryOpenDatabase(n){let e=this._sanitizedSessionKey(n),t=v.joinPath(this._basePath,e,sl);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}}};gc=A([b(1,xe),b(2,O)],gc);import{execFile as bz}from"child_process";import{readFile as _z}from"fs/promises";import{constants as Sz,promises as Cz}from"fs";import{createInterface as Iz}from"readline";async function IL(o){if(ft||X)return;let n;for(let e of["/etc/os-release","/usr/lib/os-release","/etc/lsb-release"])try{n=await Cz.open(e,Sz.R_OK);break}catch{}if(!n){o("Unable to retrieve release information from known identifier paths.");return}try{let e=new Set(["ID","DISTRIB_ID","ID_LIKE","VERSION_ID","DISTRIB_RELEASE"]),t={id:"unknown"};for await(let r of Iz({input:n.createReadStream(),crlfDelay:1/0})){if(!r.includes("="))continue;let i=r.split("=")[0].toUpperCase().trim();if(e.has(i)){let s=r.split("=")[1].replace(/"/g,"").toLowerCase().trim();i==="ID"||i==="DISTRIB_ID"?t.id=s:i==="ID_LIKE"?t.id_like=s:(i==="VERSION_ID"||i==="DISTRIB_RELEASE")&&(t.version_id=s)}}return t}catch(e){o(e)}finally{await n.close()}}var Tz=[{distributionIds:["debian","ubuntu","linuxmint","pop","elementary","kali","raspbian"],commands:[["apt-get","apt-get update && apt-get install -y"],["apt","apt update && apt install -y"]]},{distributionIds:["fedora","rhel","centos","rocky","almalinux"],commands:[["dnf","dnf install -y"],["yum","yum install -y"]]},{distributionIds:["arch","manjaro","endeavouros"],commands:[["pacman","pacman -S --needed --noconfirm"]]},{distributionIds:["suse","opensuse","opensuse-leap","opensuse-tumbleweed"],commands:[["zypper","zypper --non-interactive install"]]},{distributionIds:["alpine"],commands:[["apk","apk add"]]}],Rv=class o{static async checkSandboxDependenciesWith(n,e=Fe,t=s=>o._probeBubblewrap(s),r=()=>o._resolveLinuxInstallEnvironment(),i=()=>o._resolveAppArmorRestriction()){if(!e)return;let[s,a]=await Promise.all([n("bwrap"),n("socat")]),l=s?await t(s):{usable:!1},[d,c]=await Promise.all([!s||!a?o._findDependencyInstallCommand(n,r):void 0,s&&!l.usable?i():void 0]);return{bubblewrapInstalled:!!s,bubblewrapUsable:l.usable,bubblewrapError:l.error,socatInstalled:!!a,dependencyInstallCommand:d,...c===void 0?void 0:{apparmorRestrictsUnprivilegedUserNamespaces:c}}}static async _resolveAppArmorRestriction(){let n=await _z("/proc/sys/kernel/apparmor_restrict_unprivileged_userns","utf8").catch(()=>{});return n===void 0?void 0:n.trim()==="1"}static async _findDependencyInstallCommand(n,e){let t=await e(),r=Tz.find(s=>s.distributionIds.some(a=>t.distributionIds.includes(a)));if(!r)return;let i=t.isRoot?"":await n("sudo")?"sudo ":void 0;if(i!==void 0){for(let[s,a]of r.commands)if(await n(s))return a.split(" && ").map(l=>`${i}${l}`).join(" && ")}}static async _resolveLinuxInstallEnvironment(){let n=await IL(()=>{});return{distributionIds:[n?.id,...n?.id_like?.split(/\s+/)??[]].filter(e=>!!e),isRoot:process.getuid?.()===0}}checkSandboxDependencies(){return o.checkSandboxDependenciesWith(wf)}static _probeBubblewrap(n){return new Promise(e=>{bz(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(!X)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(!X)return;let n=[];for(let s of["SystemRoot","PATH","ComSpec","PATHEXT","PSModulePath"]){let a=To(process.env,s);typeof a=="string"&&a&&n.push(`${s}=${a}`)}let e=To(process.env,"USERPROFILE");typeof e=="string"&&e&&n.push(`USERPROFILE=${e}`);let t=To(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(!X)return;let{buildSandboxPayload:s}=await import("@microsoft/mxc-sdk");return s(n,e,t,r,i)}async _getPSHome(){let n=To(process.env,"PSHOME");if(typeof n=="string"&&n)return n;let e=await wf("pwsh")??await wf("powershell");return e?ve.dirname(e):void 0}_getLocalAppData(){let n=To(process.env,"LOCALAPPDATA");return typeof n=="string"&&n?n:void 0}};var xv=class extends Yu{_decodeUri(n){return Gk(n)}_encodeUri(n,e){return od(n,e)}};var bL=B("agentHostByokLmHandler");var _L="agentHostClientByokLm";function TL(o){return{chat:n=>o.call("chat",n),onDidChangeModels:o.listen("models")}}var Av=class{constructor(n,e){this._handler=n;this._logService=e}listen(n,e){if(e==="models")return this._modelsSnapshotEvent();throw new Error(`No event '${e}' on AgentHostClientByokLmChannel`)}_modelsSnapshotEvent(){let n=new G,e=n.add(new ka),t=n.add(new E({onDidAddFirstListener:()=>{this._handler.onDidChangeModels&&n.add(this._handler.onDidChangeModels(()=>{r()})),r()},onDidRemoveLastListener:()=>n.dispose()})),r=()=>{n.isDisposed||e.queue(async()=>{try{let i=await this._handler.listModels(ke.None);n.isDisposed||t.fire(i)}catch(i){this._logService.warn("AgentHostClientByokLmChannel: failed to enumerate BYOK models from the renderer",i)}})};return t.event}async call(n,e,t){if(e==="chat")return await this._handler.chat(t,ke.None);throw new Error(`Unknown command '${e}' on AgentHostClientByokLmChannel`)}};Av=A([b(0,bL),b(1,O)],Av);var wL="agentHostClientProxy";function RL(o){return{resolveProxy:n=>o.call("resolveProxy",{url:n}),lookupAuthorization:n=>o.call("lookupAuthorization",{authInfo:n}),lookupKerberosAuthorization:n=>o.call("lookupKerberosAuthorization",{url:n})}}var Pv=class{constructor(n){this._requestService=n}listen(n,e){throw new Error(`No event '${e}' on AgentHostClientProxyChannel`)}async call(n,e,t){switch(e){case"resolveProxy":{let{url:r}=t;return await this._requestService.resolveProxy(r)}case"lookupAuthorization":{let{authInfo:r}=t;return await this._requestService.lookupAuthorization(r)}case"lookupKerberosAuthorization":{let{url:r}=t;return await this._requestService.lookupKerberosAuthorization(r)}}throw new Error(`Unknown command '${e}' on AgentHostClientProxyChannel`)}};Pv=A([b(0,Ri)],Pv);var wz=20,mc=class{constructor(n,e,t,r=wz){this._fileService=e;this._logService=t;this._sequencer=new Ze;this._lru=[];this._cacheLoaded=!1;this._basePath=v.joinPath(n,"agentPlugins"),this._cachePath=v.joinPath(this._basePath,"cache.json"),this._maxPlugins=r}get basePath(){return this._basePath}async syncCustomizations(n,e,t){return await this._ensureCacheLoaded(),await Promise.all(e.map(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=od(v.parse(e.uri),n),r=this._dirFor(e.uri,e.nonce);return e.nonce&&this._findEntry(e.uri,e.nonce)&&await this._fileService.exists(r)?(this._touchLru(e.uri,e.nonce),this._logService.trace(`[AgentPluginManager] Nonce match for ${e.uri}, skipping copy`),r):(this._logService.info(`[AgentPluginManager] Syncing plugin: ${e.uri} \u2192 ${r.toString()}`),await this._fileService.copy(t,r,!0),this._removeEntry(e.uri,e.nonce),this._lru.push({uri:e.uri,nonce:e.nonce??""}),await this._cleanupStaleNoncesFor(e.uri),await this._evictIfNeeded(),await this._persistCache(),r)}_keyForUri(n){return this._sanitize(n)}_keyForNonce(n){return n&&this._sanitize(n)||"default"}_sanitize(n){return n.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,128)}_dirFor(n,e){return v.joinPath(this._basePath,this._keyForUri(n),this._keyForNonce(e))}_pluginRootFor(n){return v.joinPath(this._basePath,this._keyForUri(n))}_findEntry(n,e){let t=e??"";return this._lru.find(r=>r.uri===n&&r.nonce===t)}_removeEntry(n,e){let t=this._findEntry(n,e);t&&this._removeEntryRef(t)}_removeEntryRef(n){let e=this._lru.indexOf(n);e!==-1&&this._lru.splice(e,1)}_touchLru(n,e){let t=this._findEntry(n,e);t&&(this._removeEntryRef(t),this._lru.push(t))}async _tryDeleteDir(n){try{return await this._fileService.del(n,{recursive:!0}),!0}catch(e){return this._logService.warn(`[AgentPluginManager] Failed to remove plugin dir ${n.toString()}`,e),!1}}async _cleanupStaleNonces(){for(let n of new Set(this._lru.map(e=>e.uri)))await this._cleanupStaleNoncesFor(n)}async _cleanupStaleNoncesFor(n){let t=this._lru.filter(r=>r.uri===n).slice(0,-1);for(let r of t)this._logService.info(`[AgentPluginManager] Evicting stale nonce for plugin: ${n}`),await this._tryDeleteDir(this._dirFor(r.uri,r.nonce))&&this._removeEntryRef(r)}async _evictIfNeeded(){let n=0;for(;this._lru.length>this._maxPlugins&&n<this._lru.length;){let e=this._lru[n];this._logService.info(`[AgentPluginManager] Evicting plugin: ${e.uri}`),await this._tryDeleteDir(this._dirFor(e.uri,e.nonce))?(this._lru.splice(n,1),this._lru.some(t=>t.uri===e.uri)||await this._tryDeleteDir(this._pluginRootFor(e.uri))):n++}}async _ensureCacheLoaded(){if(!this._cacheLoaded){this._cacheLoaded=!0;try{if(!await this._fileService.exists(this._cachePath))return;let n=await this._fileService.readFile(this._cachePath),e=JSON.parse(n.value.toString());if(!Array.isArray(e))return;for(let t of e)typeof t.uri=="string"&&typeof t.nonce=="string"&&this._lru.push({uri:t.uri,nonce:t.nonce});this._logService.trace(`[AgentPluginManager] Loaded ${e.length} cache entries from disk`)}catch(n){this._logService.warn("[AgentPluginManager] Failed to load cache from disk",n)}await this._cleanupStaleNonces(),await this._persistCache()}}async _persistCache(){try{let n=this._lru.map(e=>({uri:e.uri,nonce:e.nonce}));await this._fileService.createFolder(this._basePath),await this._fileService.writeFile(this._cachePath,$.fromString(JSON.stringify(n)))}catch(n){this._logService.warn("[AgentPluginManager] Failed to persist cache to disk",n)}}};mc=A([b(1,xe),b(2,O)],mc);import*as Ev from"child_process";import*as kL from"fs/promises";import{cp as Rz}from"@vscode/fs-copyfile";var hc=class{constructor(n,e,t){this._fileService=n;this._environmentService=e;this._logService=t;this._repositoryRoots=new bn(100);this._repositoryRootSequencer=new Ze}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{name:e,startPoint:e};let t=e.substring(20);return await this._runGit(n,["show-ref","--verify","--quiet",`refs/remotes/origin/${t}`])!==void 0?{name:t,startPoint:`origin/${t}`}:await this._runGit(n,["show-ref","--verify","--quiet",`refs/heads/${t}`])!==void 0?{name:t,startPoint:t}:void 0}}async getRefs(n,e){let t=["for-each-ref","--format=%(refname)%00%(upstream)"];if(e?.sort&&e.sort!=="alphabetically"&&t.push("--sort",`-${e.sort}`),e?.count&&t.push(`--count=${e.count}`),e?.pattern){let i=Array.isArray(e.pattern)?e.pattern:[e.pattern];for(let s of i)t.push(s.startsWith("refs/")?s:`refs/${s}`)}let r=await this._runGit(n,t);return Lz(r)}async getBranches(n,e){return(await this.getRefs(n,e)).filter(r=>r.kind===0||r.kind===1)}async getBranch(n,e){let t=await this.getBranches(n,{pattern:e});return t.length>0?t[0]:void 0}async getRepositoryRoot(n){let e=n.toString();return this._repositoryRootSequencer.queue(e,async()=>{let t=this._repositoryRoots.get(e);if(t)return t;try{let r=(await this._runGit(n,["rev-parse","--show-toplevel"]))?.trim();return r&&(t=v.file(r),this._repositoryRoots.set(e,t)),t}catch{}})}async getWorktreeRoots(n){let e=await this._runGit(n,["worktree","list","--porcelain"]);return e?e.split(/\r?\n/g).filter(t=>t.startsWith("worktree ")).map(t=>v.file(t.substring(9))):[]}async addWorktree(n,e,t,r){let 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 Lr(15),l=(await Promise.allSettled(r.map(d=>s.queue(async()=>{let c=V(e.fsPath,ef(n.fsPath,d));await kL.mkdir(te(c),{recursive:!0}),await Rz(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=AL(i).length>0,a;if(!s)a=await this._runGit(t,["diff","--raw","--numstat","--diff-filter=ADMR","-z",r,"--"]);else{let l=lT(i);a=await this._runWithTempIndex(t,r,l)}if(a!==void 0)return PL(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??Hs}async _runWithTempIndex(n,e,t){let r=v.joinPath(this._environmentService.tmpDir,`agent-host-git-diff-${F()}`);await this._fileService.createFolder(r);let s={GIT_INDEX_FILE:v.joinPath(r,"index").fsPath};s.COMMAND_HOOK_LOCK="1";try{return await this._runGit(n,["read-tree","HEAD"],{env:s})===void 0&&await this._runGit(n,["read-tree",Hs],{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=v.joinPath(e,"pathspec");return await this._fileService.writeFile(i,$.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(g=>g.length>0);if(s.length===0)return[];let a=e.map(g=>js(g)),l=new Set((i??"").split("\0").filter(g=>g.endsWith("/"))),d=[],c=new Set;for(let g of s)if(a.some(h=>h(g)))d.push(g);else if(l.size>0){let h=xL(g,l);h!==void 0&&c.add(h)}if(d.length===0)return[];let u=new Set;for(let g of l)c.has(g)||u.add(g);let p=[...u];for(let g of d)(u.size===0||xL(g,u)===void 0)&&p.push(g);return p.map(g=>V(n.fsPath,g))}async showBlob(n,e,t){if(await this.getRepositoryRoot(n))return new Promise(i=>{Ev.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($.wrap(a))})})}async getSessionGitState(n){return this._computeSessionGitState(n)}async getFetchRemoteUrls(n,e){let t=await this.getRepositoryRoot(n);if(t)return DL(await this._runGit(t,["remote","-v"]),e)}async getUntrackedPaths(n){let e=await this.getRepositoryRoot(n);if(!e)return;let t=await this._runGit(e,["status","--porcelain=v1","-z","--untracked-files=all"]);return t===void 0?void 0:AL(t)}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=lT(t),i=v.joinPath(this._environmentService.tmpDir,`agent-host-checkpoint-${F()}`);await this._fileService.createFolder(i);let a={GIT_INDEX_FILE:v.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",Hs],{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=>{Ev.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=v.joinPath(this._environmentService.tmpDir,`agent-host-review-overlay-${F()}`);await this._fileService.createFolder(i);let a={GIT_INDEX_FILE:v.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=Pz(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:PL(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 getBranchDiffSafetyInfo(n,e){let t=await this.getRepositoryRoot(n);if(!t)return;let[r,i,s,a,l]=await Promise.all([this._runGit(t,["config","--get","core.virtualfilesystem"]),this._runGit(t,["config","--get","core.sparsecheckout"]),this._runGit(t,["show","-s","--format=%ct",e]),this._runGit(t,["rev-list","--count",`${e}..HEAD`]),this._runGit(t,["ls-files","--cached","--others","--exclude-standard","-z"])]),d=new Set(["true","yes","on","1"]).has(i?.trim().toLowerCase()??""),c=Number(s?.trim()),u=Number(a?.trim());return{hasVirtualFileSystem:!!r?.trim()||d,baselineCommitTimestamp:Number.isFinite(c)?c*1e3:void 0,commitCount:Number.isFinite(u)?u:void 0,workspaceFileCount:l?.split("\0").filter(Boolean).length??0}}async getDiffPatchBetweenRefs(n,e){let t=await this.getRepositoryRoot(n);if(!t)return;let r=[...new Set(e.paths)];if(r.length===0)return{patch:"",tooLarge:!1};try{let i=await this._runGit(t,["diff","--patch","--no-ext-diff","--find-renames","--diff-filter=ADMR",e.fromRef,e.toRef,"--",...r],{maxBuffer:e.maxBuffer,throwOnError:!0});return i===void 0?void 0:{patch:i,tooLarge:!1}}catch(i){if(Uz(i))return{patch:void 0,tooLarge:!0};throw i}}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=Ez(t),a=kz(r),l=Oz(i),d=Dz(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`]),g=p===void 0?NaN:Number(p.trim());Number.isFinite(g)&&(c=g)}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 Nz(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=Ev.execFile("git",[...e],{cwd:n.fsPath,env:s,maxBuffer:t?.maxBuffer??32*1024*1024},(u,p,g)=>{if(u){if(g&&this._logService.warn(`[agentHostGitService] > git ${e.join(" ")} failed; full stderr:
${g}`),t?.throwOnError){i(new Error(xz(e,a,l,u,g),{cause:u}));return}r(void 0);return}r(p)}),c=setTimeout(()=>{l=!0,d.kill()},a);d.on("exit",()=>clearTimeout(c))})}};hc=A([b(0,xe),b(1,St),b(2,O)],hc);function xL(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 xz(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=Az(r);return a?`${s}: ${a}`:s}function Az(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 AL(o){return lT(o,n=>n==="??")}function lT(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 Pz(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 PL(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 g=i[l++];if(!g)continue;s.push({kind:"rename",oldPath:p,newPath:g});break}default:break}}else{let[c,u,p]=d.split("	"),g;if(p===""||p===void 0){let h=i[l++];g=i[l++]??h??""}else g=p;if(!g)continue;a.set(g,{added:c==="-"?0:Number(c)||0,removed:u==="-"?0:Number(u)||0})}}return s.map(d=>{let c=a.get(d.newPath??d.oldPath??""),u=d.oldPath?v.joinPath(n,d.oldPath):void 0,p=d.newPath?v.joinPath(n,d.newPath):void 0,g=d.kind!=="create"&&d.oldPath&&u?{uri:u.toString(),content:{uri:FC(e,t,d.oldPath,u.path)}}:void 0,h=d.kind!=="delete"&&d.newPath&&p?{uri:p.toString(),content:r!==void 0?{uri:FC(e,r,d.newPath,p.path)}:{uri:p.toString()}}:void 0,y={added:c?.added??0,removed:c?.removed??0};return{...g?{before:g}:{},...h?{after:h}:{},diff:y}})}function Ez(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 kz(o){if(o!==void 0)return o.trim()?/github\.com[:\/]/i.test(o):!1}function DL(o,n){if(o===void 0)return;let e=[];for(let i of o.split(/\r?\n/)){let s=/^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(i.trim());s&&e.push({name:s[1],url:s[2]})}let t=new Set([n,"origin"].filter(i=>!!i)),r=[...e.filter(i=>i.name===n),...e.filter(i=>i.name==="origin"&&i.name!==n),...e.filter(i=>!t.has(i.name))];return[...new Set(r.map(i=>i.url))]}function Dz(o){let n=DL(o);if(n)for(let e of n){let t=Mz(e);if(t)return t}}function Mz(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 Oz(o){let n=o?.trim();if(!n)return;let e="refs/remotes/origin/";return n.startsWith(e)?n.substring(e.length):n}function EL(o){if(!o.startsWith("refs/remotes/"))return;let n=o.substring(13),e=n.split("/")[0];return{ref:o,name:n,remote:e}}function Lz(o){if(!o)return[];let n=[];for(let e of o.split(/\r?\n/g)){let[t,r]=e.trim().split("\0");if(t.startsWith("refs/heads/"))n.push({ref:t,name:t.substring(11),upstream:r?EL(r):void 0,kind:0});else if(t.startsWith("refs/remotes/")&&!/^refs\/remotes\/[^/]+\/HEAD$/.test(t)){let i=EL(t);i&&n.push({...i,kind:1})}else t.startsWith("refs/tags/")&&n.push({ref:t,name:t.substring(10),kind:3})}return n}function Nz(o){let n={};for(let[e,t]of Object.entries(o))t!==void 0&&(n[e]=t);return n}function Uz(o){let n=o instanceof Error?o.cause:void 0;return n instanceof Error&&n.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"}var ML;(n=>{function o(e,t){return e.callstack<t.callstack?-1:e.callstack>t.callstack?1:0}n.compare=o})(ML||={});function Fz(o){if(!o||typeof o!="object")return{callstack:void 0,msg:Ur(o)};let n=Array.isArray(o.stack)?o.stack.join(`
`):o.stack,e=o.message?o.message:Ur(o);return{callstack:n,msg:e}}var Lp=class o{constructor(n,e=o.ERROR_FLUSH_TIMEOUT){this._flushHandle=void 0;this._buffer=[];this._disposables=new G;this._telemetryService=n,this._flushDelay=e;let t=ga.addListener(r=>this._onErrorEvent(r));this._disposables.add(U(t)),this.installErrorListeners()}static{this.ERROR_FLUSH_TIMEOUT=5*1e3}dispose(){clearTimeout(this._flushHandle),this._flushBuffer(),this._disposables.dispose()}installErrorListeners(){}_onErrorEvent(n){if(!n||n.code||(n.detail&&n.detail.stack&&(n=n.detail),Jn.isErrorNoTelemetry(n)||n instanceof vt||Hp.is(n)||typeof n?.message=="string"&&n.message.includes("Unable to read file")))return;let{callstack:e,msg:t}=Fz(n);if(!e)return;let r={msg:t,callstack:e};Ra.is(n)&&(r.kind=n.kind,r.listenerCount=n.listenerCount),this._enqueue(r)}_enqueue(n){let e=ST(this._buffer,n,ML.compare);e<0?(n.count=1,this._buffer.splice(~e,0,n)):(this._buffer[e].count||(this._buffer[e].count=0),this._buffer[e].count+=1),this._flushHandle===void 0&&(this._flushHandle=setTimeout(()=>{this._flushBuffer(),this._flushHandle=void 0},this._flushDelay))}_flushBuffer(){for(let n of this._buffer)this._telemetryService.publicLogError2("UnhandledError",n);this._buffer.length=0}};var Np=class extends Lp{installErrorListeners(){fT(e=>console.error(e));let n=[];process.on("unhandledRejection",(e,t)=>{n.push(t),setTimeout(()=>{let r=n.indexOf(t);r>=0&&t.catch(i=>{n.splice(r,1),un(i)||(console.warn(`rejected promise not handled within 1 second: ${i}`),i.stack&&console.warn(`stack trace: ${i.stack}`),e&&Ye(e))})},1e3)}),process.on("rejectionHandled",e=>{let t=n.indexOf(e);t>=0&&n.splice(t,1)}),process.on("uncaughtException",e=>{gT(e)||Ye(e)})}};Hz().catch(o=>{console.error(o),process.exit(1)});async function Hz(){let o;Af(process)?o=new Ss:o=new Rf("agentHost");let n=new G,e=n.add(new ht),t={_serviceBrand:void 0,...ln},r=new av(lv(process.argv,Y_),t),i=new uv(Kx(r),r.logsHome);o.registerChannel("agentHostLogger",new pv(i,()=>iL));let s=i.createLogger("agenthost",{name:f(2039,null)}),a=n.add(new Nh),l=n.add(new Uh(a)),d=new dv(s,[l]);!r.isBuilt&&Vx&&n.add(jx(d)),d.info("Agent Host process started successfully");let c=n.add(new os(d));n.add(c.registerProvider(ne.file,n.add(new Tv(d)))),n.add(R0(c));let u=new gc(v.file(r.userDataPath),c,d),p=Y(r.appSettingsHome,"globalStorage","agent-host-config.json"),g,h,y,I,S,C=Uf(process.env[jR],!0);try{let R=new vi;R.set(St,r),R.set(O,d),R.set(xe,c),R.set(nt,u),R.set(Tt,t);let L=await hL(R,c,r,d,n);S=L.proxyResolver;let D=S.fetch.bind(S),z=await XP({environmentService:r,productService:t,fileService:c,loggerService:i,logService:d,disposables:n,fetchFn:D,requestService:L.requestService});e.value=new Np(z),R.set(Pn,z),h=new il(R);let J=n.add(h.createInstance(Zr));R.set(Xl,J),R.set(Kh,h.createInstance(jh)),R.set(Vh,new Rv);let me=h.createInstance(hc);R.set($e,me);let We=n.add(h.createInstance(Jl));R.set(Kr,We);let je=n.add(h.createInstance(Nd));R.set(Ud,je),y=je.onDidDownloadProgress;let k=h.createInstance(Hd);R.set($d,k),I=new Lh,R.set(qi,I);let P=n.add(h.createInstance(_d));R.set(zh,P);let q=n.add(h.createInstance(ac,D));R.set(Mh,q),g=new _h(d,c,u,t,me,We,p,z,J,void 0,D,[yO(r.userHome)]);let H=h.createInstance(sc);R.set(CO,H),g.setNetworkDiagnosticsService(H),R.set(Hr,g),R.set(Ce,g.stateManager);let j=new mc(v.file(r.userDataPath),c,d);R.set($i,j);let Q=n.add(new Di(d));R.set(Hg,Q),R.set(Bg,h.createInstance(vl)),R.set(ur,g.terminalManager),R.set(Ue,g.configurationService),R.set(wt,g.gitHubEndpointService),R.set(Rm,g.completionsService);let Z=h.createInstance(Ei,D);R.set(gt,Z),g.setWorktreeIsolation(n.add(h.createInstance(jl,void 0)));let st=n.add(h.createInstance(Xd));R.set(Dy,st);let Pe=n.add(h.createInstance(tc));if(R.set(Uy,Pe),g.registerProvider(h.createInstance(it)),Uf(process.env[zR],!0)&&(!r.isBuilt||je.isAvailable(Fd))&&g.registerProvider(h.createInstance(Zd)),!r.isBuilt||je.isAvailable(ca)){let kt=g.configurationService,xt=!1,Lt=()=>{if(xt)return;let mr=Uf(process.env[VR],!1),co=kt.getRootValue(tt,kS)===!0;(mr||co)&&(xt=!0,g.registerProvider(h.createInstance(oc)))};Lt(),n.add(kt.onDidRootConfigChange(()=>Lt()))}}catch(R){throw d.error("Failed to create AgentService",R),R}if(n.add(h.createInstance(el,g.agents,Gx)),y&&n.add(y(R=>g.emitDownloadProgress(R.packageId,R.displayName,R.receivedBytes,R.totalBytes,R.phase==="completed"||R.phase==="failed"))),!(o instanceof Ss)){let R=vs.fromService(g,n);o.registerChannel("agentHost",R)}let _=n.add(new xv);if(n.add(c.registerProvider(sb,_)),o instanceof Ss){let R=n.add(new G),L=new iv,D=await $z(r.userDataPath,d,h,r.logsHome);try{let z=R.add(new ov([L,...D?[D.server]:[]]));R.add(new rs(g,g.stateManager,z,{defaultDirectory:v.file(yc.homedir()).toString(),completionTriggerCharacters:g.completionTriggerCharacters,terminalCommandPrefix:"!",otlpLogEmitter:a,allowExtensionMethods:!1},_,d));let J=new Map,me=We=>{if(J.has(We))return;let je=We.ctx;if(typeof je!="string"||!je)return;let k=new G,P=H=>o.getChannel(H,j=>j.ctx===je),q=RL(P(wL));if(k.add(S.register(je,q)),C&&I){let H=TL(P(_L));k.add(I.register(je,H))}J.set(We,k)};R.add(o.onDidAddConnection(me)),R.add(o.onDidRemoveConnection(We=>{typeof We.ctx=="string"&&L.closeClient(We.ctx);let je=J.get(We);je&&(je.dispose(),J.delete(We))})),R.add(U(()=>{for(let We of J.values())We.dispose();J.clear()}));for(let We of o.connections)me(We);if(o.registerChannel("agentHostProtocol",L),D)try{await jO(r.userDataPath,D.metadata),R.add(U(()=>{kv(r.userDataPath,D.metadata,d)}))}catch(We){d.error("[AgentHost] Failed to publish local protocol endpoint; continuing with MessagePort only",We),D.server.dispose(),kv(r.userDataPath,D.metadata,d)}}catch(z){throw R.dispose(),D&&kv(r.userDataPath,D.metadata,d),z}}let T=n.add(new E),w,W={onDidChangeConnectionCount:T.event,async startWebSocketServer(){if(w)return w;let R=X?`\\\\.\\pipe\\vscode-agent-host-${F().replace(/-/g,"")}`:V(yc.tmpdir(),`vscode-agent-host-${F().replace(/-/g,"")}.sock`),L=n.add(await cc.create({socketPath:R},d,{instantiationService:h,logsHome:r.logsHome})),D=n.add(new rs(g,g.stateManager,L,{defaultDirectory:v.file(yc.homedir()).toString(),completionTriggerCharacters:g.completionTriggerCharacters,terminalCommandPrefix:"!",otlpLogEmitter:a},_,d));return n.add(D.onDidChangeConnectionCount(z=>T.fire(z))),d.info(`[AgentHost] Dynamic WebSocket server listening on ${R}`),w={socketPath:R},w},async getInspectInfo(R){let L=Up.url();if(!L&&R){try{Up.open(0,"127.0.0.1",!1)}catch(D){d.error("[AgentHost] Failed to open inspector",D);return}L=Up.url()}if(L)try{let D=new URL(L);if(D.protocol!=="ws:"){d.warn(`[AgentHost] Unexpected inspector URL: ${L}`);return}let z=Number(D.port),J=D.pathname.replace(/^\/+/,"");if(!Number.isInteger(z)||!J){d.warn(`[AgentHost] Unexpected inspector URL: ${L}`);return}let me=D.hostname==="0.0.0.0"?"127.0.0.1":D.hostname==="::"?"::1":D.hostname,We=me.includes(":")?`[${me}]`:me;return{host:me,port:z,devtoolsUrl:`devtools://devtools/bundled/js_app.html?v8only=true&ws=${We}:${D.port}/${J}`}}catch{d.warn(`[AgentHost] Unexpected inspector URL: ${L}`);return}}};o instanceof Ss?o.registerChannel("agentHostManagement",vs.fromService(new sv(g,W),n)):o.registerChannel("agentHostConnectionTracker",vs.fromService(W,n)),Wz(g,_,h,r.logsHome,d,a,n,R=>T.fire(R)).catch(R=>{d.error("Failed to start WebSocket server",R)}),process.once("exit",()=>{g.dispose(),d.dispose(),n.dispose()})}async function $z(o,n,e,t){let r,i;try{let s=BO(o);return r=s,await zO(o),X||await VO(o),i=await cc.create({socketPath:s.endpointPath,connectionTokenValidate:a=>a===s.connectionToken},n,{instantiationService:e,logsHome:t}),await i.whenListening,{metadata:s,server:i}}catch(s){try{i?.dispose()}catch(a){n.error("[AgentHost] Failed to dispose local protocol endpoint",a)}r&&kv(o,r,n),n.error("[AgentHost] Failed to start local protocol endpoint; continuing with MessagePort only",s);return}}function kv(o,n,e){try{KO(o,n)}catch(t){e.error("[AgentHost] Failed to clean up local protocol metadata",t)}try{GO(n.endpointPath)}catch(t){e.error("[AgentHost] Failed to clean up local protocol socket",t)}}async function Wz(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 cc.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})),g=s.add(new rs(o,o.stateManager,p,{defaultDirectory:v.file(yc.homedir()).toString(),completionTriggerCharacters:o.completionTriggerCharacters,terminalCommandPrefix:"!",otlpLogEmitter:i},n,r));s.add(g.onDidChangeConnectionCount(a)),await p.whenListening;let h=d??`${u}:${p.boundPort??l}`;r.info(`[AgentHost] WebSocket server listening on ${h}`),console.log(`Agent host server listening on ${h}`)}
