function normalizeErrorMessage(payload, fallback) {
    if (payload &&
        typeof payload === 'object' &&
        typeof payload.error === 'string') {
        return payload.error;
    }
    return fallback;
}
export async function probeHubInitAccess(hubHttpUrl, options) {
    const fetchImpl = options?.fetchImpl ?? fetch;
    const headers = {
        accept: 'application/json',
    };
    if (options?.apiKey) {
        if (options.apiKey.startsWith('agc_')) {
            headers['x-agentuity-auth-api-key'] = options.apiKey;
        }
        else {
            headers['authorization'] = `Bearer ${options.apiKey}`;
        }
    }
    if (options?.orgId) {
        headers['x-agentuity-orgid'] = options.orgId;
    }
    try {
        const response = await fetchImpl(`${hubHttpUrl}/api/hub/init`, {
            headers,
            signal: AbortSignal.timeout(10_000),
        });
        let payload;
        try {
            payload = await response.json();
        }
        catch {
            payload = undefined;
        }
        if (response.status === 401 || response.status === 403) {
            return {
                ok: false,
                code: 'unauthorized',
                message: normalizeErrorMessage(payload, `${response.status} ${response.statusText}`),
            };
        }
        if (!response.ok) {
            return {
                ok: false,
                code: 'http_error',
                message: normalizeErrorMessage(payload, `${response.status} ${response.statusText}`),
            };
        }
        if (!payload ||
            typeof payload !== 'object' ||
            payload.type !== 'init') {
            return {
                ok: false,
                code: 'invalid_response',
                message: 'Hub init endpoint did not return an init payload',
            };
        }
        return { ok: true };
    }
    catch (error) {
        return {
            ok: false,
            code: 'network_error',
            message: error instanceof Error ? error.message : String(error),
        };
    }
}
//# sourceMappingURL=tui-init.js.map