var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
// Only tokens emitted by the model node(s) are surfaced to the user; other
// graph nodes (tools, summarization, etc.) are internal.
const STREAMABLE_NODES = ["model", "model_request"];
function getInterruptItems(interrupt) {
    return Array.isArray(interrupt) ? interrupt : [interrupt];
}
/**
 * Normalize raw LangGraph interrupt object(s) into provider-agnostic descriptors.
 * Kept in the llm layer so the LangGraph interrupt shape never reaches the app.
 */
export function normalizeInterrupts(interrupt) {
    return getInterruptItems(interrupt).flatMap((item) => {
        const value = item && typeof item === "object" && "value" in item
            ? item.value
            : item;
        const actionRequests = value && typeof value === "object"
            ? value.actionRequests
            : undefined;
        const interruptId = item && typeof item === "object"
            ? item.id
            : undefined;
        return typeof interruptId === "string" && Array.isArray(actionRequests)
            ? [{ id: interruptId, count: actionRequests.length }]
            : [];
    });
}
function extractBlocks(token) {
    if (Array.isArray(token === null || token === void 0 ? void 0 : token.contentBlocks)) {
        return token.contentBlocks;
    }
    if (Array.isArray(token === null || token === void 0 ? void 0 : token.content)) {
        return token.content;
    }
    return [];
}
/**
 * Convert one raw LangGraph stream entry into zero or more normalized chunks.
 * Pure and synchronous so the parsing rules can be unit-tested in isolation.
 */
export function parseRawStreamChunk(entry) {
    const [mode, chunk] = entry;
    if (mode === "updates") {
        if (chunk && typeof chunk === "object" && "__interrupt__" in chunk) {
            const interrupt = chunk.__interrupt__;
            return [{ kind: "interrupt", interrupt, descriptors: normalizeInterrupts(interrupt) }];
        }
        return [];
    }
    const [token, metadata] = chunk;
    const nodeName = typeof (metadata === null || metadata === void 0 ? void 0 : metadata.langgraph_node) === "string" ? metadata.langgraph_node : "";
    if (nodeName && !STREAMABLE_NODES.includes(nodeName)) {
        return [];
    }
    const blocks = extractBlocks(token);
    const chunks = [];
    const reasoning = blocks
        .filter((block) => (block === null || block === void 0 ? void 0 : block.type) === "reasoning")
        .map((block) => { var _a; return String((_a = block.reasoning) !== null && _a !== void 0 ? _a : ""); })
        .join("");
    const text = blocks
        .filter((block) => (block === null || block === void 0 ? void 0 : block.type) === "text")
        .map((block) => { var _a; return String((_a = block.text) !== null && _a !== void 0 ? _a : ""); })
        .join("");
    if (reasoning) {
        chunks.push({ kind: "reasoning", delta: reasoning });
    }
    if (text) {
        chunks.push({ kind: "text", delta: text });
    }
    return chunks;
}
/**
 * Adapt the raw LangGraph `["messages" | "updates", ...]` stream into a typed
 * `AgentStreamChunk` stream for the application layer.
 */
export function adaptRawStream(raw) {
    return __asyncGenerator(this, arguments, function* adaptRawStream_1() {
        var _a, e_1, _b, _c;
        try {
            for (var _d = true, raw_1 = __asyncValues(raw), raw_1_1; raw_1_1 = yield __await(raw_1.next()), _a = raw_1_1.done, !_a; _d = true) {
                _c = raw_1_1.value;
                _d = false;
                const entry = _c;
                for (const chunk of parseRawStreamChunk(entry)) {
                    yield yield __await(chunk);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_d && !_a && (_b = raw_1.return)) yield __await(_b.call(raw_1));
            }
            finally { if (e_1) throw e_1.error; }
        }
    });
}
