// Force strict mode and setup for ESM
"use strict";
import {
  SessionNotFoundError
} from "./chunk-L4Y55KIS.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/serve/workspace-registry.ts
init_esbuild_shims();
function createWorkspaceSessionOwnerIndex() {
  const bySessionId = /* @__PURE__ */ new Map();
  const register = /* @__PURE__ */ __name((sessionId, workspaceCwd) => {
    let owners = bySessionId.get(sessionId);
    if (!owners) {
      owners = /* @__PURE__ */ new Set();
      bySessionId.set(sessionId, owners);
    }
    owners.add(workspaceCwd);
  }, "register");
  const remove = /* @__PURE__ */ __name((sessionId, workspaceCwd) => {
    if (workspaceCwd === void 0) {
      bySessionId.delete(sessionId);
      return;
    }
    const owners = bySessionId.get(sessionId);
    if (!owners) return;
    owners.delete(workspaceCwd);
    if (owners.size === 0) {
      bySessionId.delete(sessionId);
    }
  }, "remove");
  return {
    register,
    remove,
    getWorkspaceCwds: /* @__PURE__ */ __name((sessionId) => [...bySessionId.get(sessionId) ?? []], "getWorkspaceCwds"),
    removeWorkspace: /* @__PURE__ */ __name((workspaceCwd) => {
      for (const [sessionId, owners] of bySessionId) {
        owners.delete(workspaceCwd);
        if (owners.size === 0) bySessionId.delete(sessionId);
      }
    }, "removeWorkspace"),
    handleBridgeSessionLifecycle: /* @__PURE__ */ __name((event) => {
      if (event.type === "registered") {
        register(event.sessionId, event.workspaceCwd);
      } else {
        remove(event.sessionId, event.workspaceCwd);
      }
    }, "handleBridgeSessionLifecycle")
  };
}
__name(createWorkspaceSessionOwnerIndex, "createWorkspaceSessionOwnerIndex");
function createWorkspaceRegistry(inputRuntimes, options = {}) {
  if (inputRuntimes.length === 0) {
    throw new Error(
      "WorkspaceRegistry requires at least one workspace runtime."
    );
  }
  const primaryRuntimes = inputRuntimes.filter((runtime) => runtime.primary);
  if (primaryRuntimes.length !== 1) {
    throw new Error(
      "WorkspaceRegistry requires exactly one primary workspace runtime."
    );
  }
  const byCwd = /* @__PURE__ */ new Map();
  const byId = /* @__PURE__ */ new Map();
  for (const runtime of inputRuntimes) {
    if (byCwd.has(runtime.workspaceCwd)) {
      throw new Error(
        `Duplicate workspace runtime cwd ${JSON.stringify(
          runtime.workspaceCwd
        )}.`
      );
    }
    byCwd.set(runtime.workspaceCwd, runtime);
    if (byId.has(runtime.workspaceId)) {
      throw new Error(
        `Duplicate workspace runtime id ${JSON.stringify(
          runtime.workspaceId
        )}.`
      );
    }
    byId.set(runtime.workspaceId, runtime);
  }
  const runtimes = [...inputRuntimes];
  const states = new WeakMap(
    inputRuntimes.map((runtime) => [runtime, "active"])
  );
  const primary = primaryRuntimes[0];
  const sessionOwnerIndex = options.sessionOwnerIndex;
  const scanLiveOwners = /* @__PURE__ */ __name((sessionId) => {
    const matches = [];
    for (const runtime of runtimes) {
      if (states.get(runtime) !== "active") continue;
      try {
        runtime.bridge.getSessionSummary(sessionId);
        matches.push(runtime);
      } catch (err) {
        if (err instanceof SessionNotFoundError) continue;
        throw err;
      }
    }
    for (const match of matches) {
      sessionOwnerIndex?.register(sessionId, match.workspaceCwd);
    }
    if (matches.length === 0) return { kind: "not_found" };
    if (matches.length === 1) {
      return { kind: "found", runtime: matches[0] };
    }
    return { kind: "ambiguous", runtimes: matches };
  }, "scanLiveOwners");
  return {
    primary,
    // Return a frozen snapshot: `runtimes` is mutable internally (see `add`),
    // but callers must not be able to push/splice into the registry's state.
    list: /* @__PURE__ */ __name(() => Object.freeze(
      runtimes.filter((runtime) => states.get(runtime) === "active")
    ), "list"),
    listManaged: /* @__PURE__ */ __name(() => Object.freeze([...runtimes]), "listManaged"),
    getByWorkspaceCwd: /* @__PURE__ */ __name((workspaceCwd) => {
      const runtime = byCwd.get(workspaceCwd);
      return runtime && states.get(runtime) === "active" ? runtime : void 0;
    }, "getByWorkspaceCwd"),
    getByWorkspaceId: /* @__PURE__ */ __name((workspaceId) => {
      const runtime = byId.get(workspaceId);
      return runtime && states.get(runtime) === "active" ? runtime : void 0;
    }, "getByWorkspaceId"),
    getManagedByWorkspaceCwd: /* @__PURE__ */ __name((workspaceCwd) => byCwd.get(workspaceCwd), "getManagedByWorkspaceCwd"),
    getManagedByWorkspaceId: /* @__PURE__ */ __name((workspaceId) => byId.get(workspaceId), "getManagedByWorkspaceId"),
    resolveWorkspaceCwd: /* @__PURE__ */ __name((workspaceCwd) => workspaceCwd === void 0 ? primary : (() => {
      const runtime = byCwd.get(workspaceCwd);
      return runtime && states.get(runtime) === "active" ? runtime : void 0;
    })(), "resolveWorkspaceCwd"),
    add: /* @__PURE__ */ __name((runtime) => {
      if (byCwd.has(runtime.workspaceCwd)) {
        throw new Error(
          `Duplicate workspace runtime cwd ${JSON.stringify(runtime.workspaceCwd)}.`
        );
      }
      if (byId.has(runtime.workspaceId)) {
        throw new Error(
          `Duplicate workspace runtime id ${JSON.stringify(runtime.workspaceId)}.`
        );
      }
      byCwd.set(runtime.workspaceCwd, runtime);
      byId.set(runtime.workspaceId, runtime);
      runtimes.push(runtime);
      states.set(runtime, "active");
    }, "add"),
    beginDrain: /* @__PURE__ */ __name((runtime) => {
      if (runtime.primary || states.get(runtime) !== "active") return false;
      states.set(runtime, "draining");
      return true;
    }, "beginDrain"),
    cancelDrain: /* @__PURE__ */ __name((runtime) => {
      if (states.get(runtime) === "draining") states.set(runtime, "active");
    }, "cancelDrain"),
    completeDrain: /* @__PURE__ */ __name((runtime) => {
      if (runtime.primary || states.get(runtime) !== "draining") return;
      states.set(runtime, "removed");
      byCwd.delete(runtime.workspaceCwd);
      byId.delete(runtime.workspaceId);
      const index = runtimes.indexOf(runtime);
      if (index >= 0) runtimes.splice(index, 1);
      sessionOwnerIndex?.removeWorkspace(runtime.workspaceCwd);
    }, "completeDrain"),
    resolveLiveSessionOwner: /* @__PURE__ */ __name((sessionId) => {
      const indexedCwds = sessionOwnerIndex?.getWorkspaceCwds(sessionId) ?? [];
      if (indexedCwds.length > 0) {
        const matches = [];
        for (const workspaceCwd of indexedCwds) {
          const runtime = byCwd.get(workspaceCwd);
          if (!runtime || states.get(runtime) === "removed") {
            sessionOwnerIndex?.remove(sessionId, workspaceCwd);
            continue;
          }
          if (states.get(runtime) !== "active") continue;
          try {
            runtime.bridge.getSessionSummary(sessionId);
            matches.push(runtime);
          } catch (err) {
            if (err instanceof SessionNotFoundError) {
              sessionOwnerIndex?.remove(sessionId, workspaceCwd);
              continue;
            }
            throw err;
          }
        }
        if (matches.length === 1) {
          return { kind: "found", runtime: matches[0] };
        }
        if (matches.length > 1) {
          return { kind: "ambiguous", runtimes: matches };
        }
      }
      return scanLiveOwners(sessionId);
    }, "resolveLiveSessionOwner")
  };
}
__name(createWorkspaceRegistry, "createWorkspaceRegistry");
function createSingleWorkspaceRegistry(runtime, options = {}) {
  return createWorkspaceRegistry([runtime], options);
}
__name(createSingleWorkspaceRegistry, "createSingleWorkspaceRegistry");

export {
  createWorkspaceSessionOwnerIndex,
  createWorkspaceRegistry,
  createSingleWorkspaceRegistry
};
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
