import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; /** One session's complete tool invocations, including all diagnostics routes. */ export class LspSessionScope { #operations = new Map>(); #closing?: Promise; assertOpen() { if (this.#closing) throw new Error("LSP session is closing; request aborted."); } context(ctx: T): T { // Keep Pi's lazy context getters. Never reach an old UI getter once shutdown starts. return Object.create(ctx, { ui: { get: () => { const scope = this; return new Proxy(ctx.ui, { get(target, property) { // setStatus must keep working after close(): lane // cleanups (clearStatus in finally blocks) run during // shutdown and must not leave status lines behind. // Everything else is a business call and is refused. if (property === "setStatus") return target.setStatus.bind(target); scope.assertOpen(); const value = Reflect.get(target, property); return typeof value === "function" ? value.bind(target) : value; }, }); }, }, }); } async run( caller: AbortSignal | undefined, operation: (signal: AbortSignal) => Promise, ) { this.assertOpen(); const controller = new AbortController(); const abort = () => controller.abort(new Error("LSP request aborted.")); let settle!: () => void; this.#operations.set( controller, new Promise((resolve) => { settle = resolve; }), ); caller?.addEventListener("abort", abort, { once: true }); if (caller?.aborted) abort(); try { controller.signal.throwIfAborted(); const result = await operation(controller.signal); controller.signal.throwIfAborted(); return result; } finally { caller?.removeEventListener("abort", abort); this.#operations.delete(controller); settle(); } } close(): Promise { if (!this.#closing) { // Publish the closing state before abort callbacks can reenter this scope. this.#closing = Promise.allSettled(this.#operations.values()).then( () => {}, ); for (const controller of this.#operations.keys()) { controller.abort(new Error("LSP session is closing; request aborted.")); } } return this.#closing; } }