import { createPublicKey } from 'node:crypto';
import { APIResponseSchema } from '@agentuity/server';
import { z } from 'zod';
import { StructuredError } from '@agentuity/core';
const DevmodeRequestSchema = z.object({
    hostname: z.string().optional().describe('the hostname for the endpoint'),
    publicKey: z.string().optional().describe('the public key PEM for the endpoint'),
});
function extractPublicKeyPEM(privateKeyPEM) {
    try {
        const publicKey = createPublicKey(privateKeyPEM);
        return publicKey.export({ type: 'spki', format: 'pem' });
    }
    catch {
        return undefined;
    }
}
const DevmodeResponseSchema = z.object({
    id: z.string(),
    hostname: z.string(),
    privateKey: z.string().optional(),
});
const DevmodeResponseAPISchema = APIResponseSchema(DevmodeResponseSchema);
const DevmodeEndpointError = StructuredError('DevmodeEndpointError');
/**
 * Reserve (or re-use) an Agentuity devmode endpoint for the current
 * project. The platform returns a hostname plus a private key the
 * gravity binary uses to authenticate when it dials the public-URL
 * tunnel. Re-passing a previously-issued private key keeps the same
 * hostname stable across dev sessions on the same machine.
 *
 * KNOWN PLATFORM BUG: as of 2026-05-07 this endpoint routes hostnames
 * by the caller's `User-Agent` and v3-shaped UAs (`Agentuity CLI/3.x`)
 * receive hostnames under `*.agentuity.live`, which has no wildcard
 * DNS configured — so the URL never resolves. v2 UAs and curl get
 * `*.agentuity-us.live`, which works. Tracking in agentuity/infra#210.
 */
export async function generateEndpoint(apiClient, projectId, hostname, privateKey) {
    const publicKey = privateKey ? extractPublicKeyPEM(privateKey) : undefined;
    const resp = await apiClient.request('POST', `/cli/devmode/3/${projectId}`, DevmodeResponseAPISchema, { hostname, publicKey }, DevmodeRequestSchema);
    if (!resp.success) {
        throw new DevmodeEndpointError({ message: resp.message });
    }
    return resp.data;
}
//# sourceMappingURL=api.js.map