import { logger } from "./logger.js";
function shouldClaimLaunchBinding() {
    return process.env.AWS_MCP_CLAIM_LAUNCH_BINDING !== "false";
}
function normalizeBridgeBaseUrl(serverConfig) {
    return String(serverConfig.runtimeBridgeBaseUrl || "").trim().replace(/\/$/, "");
}
export async function claimRuntimeLaunchBinding(agentConfig, serverConfig) {
    if (!shouldClaimLaunchBinding()) {
        return null;
    }
    const bridgeBaseUrl = normalizeBridgeBaseUrl(serverConfig);
    if (!bridgeBaseUrl) {
        logger.warn("[RuntimeLaunchBinding] 已请求认领启动绑定，但未配置 AWS_RUNTIME_BRIDGE_BASE_URL");
        return null;
    }
    const workspacePath = String(agentConfig.workspacePath || "").trim();
    if (!workspacePath) {
        logger.warn("[RuntimeLaunchBinding] workspacePath 为空，无法认领启动绑定");
        return null;
    }
    const body = {
        workspacePath,
        serverUrl: serverConfig.serverUrl,
    };
    let response;
    try {
        response = await fetch(`${bridgeBaseUrl}/runtime/binding/claim-agent`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body),
        });
    }
    catch (error) {
        logger.warn(`[RuntimeLaunchBinding] 无法连接 runtime-bridge 认领启动绑定: ${error instanceof Error ? error.message : String(error)}`);
        return null;
    }
    if (response.status === 404) {
        logger.warn(`[RuntimeLaunchBinding] 未找到待认领启动绑定: ${workspacePath}`);
        return null;
    }
    if (!response.ok) {
        throw new Error(`Failed to claim runtime launch binding: ${response.status} ${response.statusText}`);
    }
    const payload = (await response.json());
    if (!payload.agentId) {
        throw new Error(payload.error || "runtime-bridge did not return agentId");
    }
    return payload;
}
//# sourceMappingURL=runtime-launch-binding.js.map