import { acpToTrace, emitToBraintrust } from "@poe-code/acp-telemetry";
export function createSpawnMiddleware(client) {
    return async (ctx, next) => {
        let aborted = false;
        try {
            await next();
        }
        catch (err) {
            const metadataCtx = ctx;
            metadataCtx.metadata = {
                ...metadataCtx.metadata,
                aborted: true
            };
            aborted = true;
            throw err;
        }
        finally {
            const source = ctx.eventStream;
            if (!source || aborted) {
                await emitSpawnTraceFromCurrentSpan(client, ctx);
            }
            else {
                const parentSpan = await readCurrentSpan(client);
                if (parentSpan !== undefined) {
                    ctx.eventStream = (async function* () {
                        try {
                            yield* source;
                        }
                        finally {
                            emitSpawnTrace(client, ctx, parentSpan);
                        }
                    })();
                }
            }
        }
    };
}
async function emitSpawnTraceFromCurrentSpan(client, ctx) {
    const parentSpan = await readCurrentSpan(client);
    if (parentSpan !== undefined) {
        emitSpawnTrace(client, ctx, parentSpan);
    }
}
async function readCurrentSpan(client) {
    try {
        const { currentSpan } = await import("braintrust");
        return currentSpan();
    }
    catch (err) {
        client.recordError(err, "log spawn session");
        return undefined;
    }
}
function emitSpawnTrace(client, ctx, parentSpan) {
    try {
        emitToBraintrust(acpToTrace(ctx), parentSpan);
    }
    catch (err) {
        client.recordError(err, "log spawn session");
    }
}
