function applyDecs2203RFactory() {
    function createAddInitializerMethod(initializers, decoratorFinishedRef) {
        return function addInitializer(initializer) {
            assertNotFinished(decoratorFinishedRef, "addInitializer");
            assertCallable(initializer, "An initializer");
            initializers.push(initializer);
        };
    }
    function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
        var kindStr;
        switch(kind){
            case 1:
                kindStr = "accessor";
                break;
            case 2:
                kindStr = "method";
                break;
            case 3:
                kindStr = "getter";
                break;
            case 4:
                kindStr = "setter";
                break;
            default:
                kindStr = "field";
        }
        var ctx = {
            kind: kindStr,
            name: isPrivate ? "#" + name : name,
            static: isStatic,
            private: isPrivate,
            metadata: metadata
        };
        var decoratorFinishedRef = {
            v: false
        };
        ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
        var get, set;
        if (kind === 0) {
            if (isPrivate) {
                get = desc.get;
                set = desc.set;
            } else {
                get = function() {
                    return this[name];
                };
                set = function(v) {
                    this[name] = v;
                };
            }
        } else if (kind === 2) {
            get = function() {
                return desc.value;
            };
        } else {
            if (kind === 1 || kind === 3) {
                get = function() {
                    return desc.get.call(this);
                };
            }
            if (kind === 1 || kind === 4) {
                set = function(v) {
                    desc.set.call(this, v);
                };
            }
        }
        ctx.access = get && set ? {
            get: get,
            set: set
        } : get ? {
            get: get
        } : {
            set: set
        };
        try {
            return dec(value, ctx);
        } finally{
            decoratorFinishedRef.v = true;
        }
    }
    function assertNotFinished(decoratorFinishedRef, fnName) {
        if (decoratorFinishedRef.v) {
            throw new Error("attempted to call " + fnName + " after decoration was finished");
        }
    }
    function assertCallable(fn, hint) {
        if (typeof fn !== "function") {
            throw new TypeError(hint + " must be a function");
        }
    }
    function assertValidReturnValue(kind, value) {
        var type = typeof value;
        if (kind === 1) {
            if (type !== "object" || value === null) {
                throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
            }
            if (value.get !== undefined) {
                assertCallable(value.get, "accessor.get");
            }
            if (value.set !== undefined) {
                assertCallable(value.set, "accessor.set");
            }
            if (value.init !== undefined) {
                assertCallable(value.init, "accessor.init");
            }
        } else if (type !== "function") {
            var hint;
            if (kind === 0) {
                hint = "field";
            } else if (kind === 10) {
                hint = "class";
            } else {
                hint = "method";
            }
            throw new TypeError(hint + " decorators must return a function or void 0");
        }
    }
    function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
        var decs = decInfo[0];
        var desc, init, value;
        if (isPrivate) {
            if (kind === 0 || kind === 1) {
                desc = {
                    get: decInfo[3],
                    set: decInfo[4]
                };
            } else if (kind === 3) {
                desc = {
                    get: decInfo[3]
                };
            } else if (kind === 4) {
                desc = {
                    set: decInfo[3]
                };
            } else {
                desc = {
                    value: decInfo[3]
                };
            }
        } else if (kind !== 0) {
            desc = Object.getOwnPropertyDescriptor(base, name);
        }
        if (kind === 1) {
            value = {
                get: desc.get,
                set: desc.set
            };
        } else if (kind === 2) {
            value = desc.value;
        } else if (kind === 3) {
            value = desc.get;
        } else if (kind === 4) {
            value = desc.set;
        }
        var newValue, get, set;
        if (typeof decs === "function") {
            newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
            if (newValue !== void 0) {
                assertValidReturnValue(kind, newValue);
                if (kind === 0) {
                    init = newValue;
                } else if (kind === 1) {
                    init = newValue.init;
                    get = newValue.get || value.get;
                    set = newValue.set || value.set;
                    value = {
                        get: get,
                        set: set
                    };
                } else {
                    value = newValue;
                }
            }
        } else {
            for(var i = decs.length - 1; i >= 0; i--){
                var dec = decs[i];
                newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
                if (newValue !== void 0) {
                    assertValidReturnValue(kind, newValue);
                    var newInit;
                    if (kind === 0) {
                        newInit = newValue;
                    } else if (kind === 1) {
                        newInit = newValue.init;
                        get = newValue.get || value.get;
                        set = newValue.set || value.set;
                        value = {
                            get: get,
                            set: set
                        };
                    } else {
                        value = newValue;
                    }
                    if (newInit !== void 0) {
                        if (init === void 0) {
                            init = newInit;
                        } else if (typeof init === "function") {
                            init = [
                                init,
                                newInit
                            ];
                        } else {
                            init.push(newInit);
                        }
                    }
                }
            }
        }
        if (kind === 0 || kind === 1) {
            if (init === void 0) {
                init = function(instance, init) {
                    return init;
                };
            } else if (typeof init !== "function") {
                var ownInitializers = init;
                init = function(instance, init) {
                    var value = init;
                    for(var i = 0; i < ownInitializers.length; i++){
                        value = ownInitializers[i].call(instance, value);
                    }
                    return value;
                };
            } else {
                var originalInitializer = init;
                init = function(instance, init) {
                    return originalInitializer.call(instance, init);
                };
            }
            ret.push(init);
        }
        if (kind !== 0) {
            if (kind === 1) {
                desc.get = value.get;
                desc.set = value.set;
            } else if (kind === 2) {
                desc.value = value;
            } else if (kind === 3) {
                desc.get = value;
            } else if (kind === 4) {
                desc.set = value;
            }
            if (isPrivate) {
                if (kind === 1) {
                    ret.push(function(instance, args) {
                        return value.get.call(instance, args);
                    });
                    ret.push(function(instance, args) {
                        return value.set.call(instance, args);
                    });
                } else if (kind === 2) {
                    ret.push(value);
                } else {
                    ret.push(function(instance, args) {
                        return value.call(instance, args);
                    });
                }
            } else {
                Object.defineProperty(base, name, desc);
            }
        }
    }
    function applyMemberDecs(Class, decInfos, metadata) {
        var ret = [];
        var protoInitializers;
        var staticInitializers;
        var existingProtoNonFields = new Map();
        var existingStaticNonFields = new Map();
        for(var i = 0; i < decInfos.length; i++){
            var decInfo = decInfos[i];
            if (!Array.isArray(decInfo)) continue;
            var kind = decInfo[1];
            var name = decInfo[2];
            var isPrivate = decInfo.length > 3;
            var isStatic = kind >= 5;
            var base;
            var initializers;
            if (isStatic) {
                base = Class;
                kind = kind - 5;
                staticInitializers = staticInitializers || [];
                initializers = staticInitializers;
            } else {
                base = Class.prototype;
                protoInitializers = protoInitializers || [];
                initializers = protoInitializers;
            }
            if (kind !== 0 && !isPrivate) {
                var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
                var existingKind = existingNonFields.get(name) || 0;
                if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
                    throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
                } else if (!existingKind && kind > 2) {
                    existingNonFields.set(name, kind);
                } else {
                    existingNonFields.set(name, true);
                }
            }
            applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
        }
        pushInitializers(ret, protoInitializers);
        pushInitializers(ret, staticInitializers);
        return ret;
    }
    function pushInitializers(ret, initializers) {
        if (initializers) {
            ret.push(function(instance) {
                for(var i = 0; i < initializers.length; i++){
                    initializers[i].call(instance);
                }
                return instance;
            });
        }
    }
    function applyClassDecs(targetClass, classDecs, metadata) {
        if (classDecs.length > 0) {
            var initializers = [];
            var newClass = targetClass;
            var name = targetClass.name;
            for(var i = classDecs.length - 1; i >= 0; i--){
                var decoratorFinishedRef = {
                    v: false
                };
                try {
                    var nextNewClass = classDecs[i](newClass, {
                        kind: "class",
                        name: name,
                        addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
                        metadata
                    });
                } finally{
                    decoratorFinishedRef.v = true;
                }
                if (nextNewClass !== undefined) {
                    assertValidReturnValue(10, nextNewClass);
                    newClass = nextNewClass;
                }
            }
            return [
                defineMetadata(newClass, metadata),
                function() {
                    for(var i = 0; i < initializers.length; i++){
                        initializers[i].call(newClass);
                    }
                }
            ];
        }
    }
    function defineMetadata(Class, metadata) {
        return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
            configurable: true,
            enumerable: true,
            value: metadata
        });
    }
    return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
        if (parentClass !== void 0) {
            var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
        }
        var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
        var e = applyMemberDecs(targetClass, memberDecs, metadata);
        if (!classDecs.length) defineMetadata(targetClass, metadata);
        return {
            e: e,
            get c () {
                return applyClassDecs(targetClass, classDecs, metadata);
            }
        };
    };
}
function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
    return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
}
var _computedKey, _initProto;
import { ReadableStream, TransformStream, randomUUID } from "@llamaindex/env";
import { Settings } from "../Settings.js";
import { wrapEventCaller } from "../internal/context/EventCaller.js";
import { consoleLogger, emptyLogger } from "../internal/logger.js";
import { getCallbackManager } from "../internal/settings/CallbackManager.js";
import { isAsyncIterable } from "../internal/utils.js";
export const MAX_TOOL_CALLS = 10;
export function createTaskOutputStream(handler, context) {
    const steps = [];
    return new ReadableStream({
        pull: async (controller)=>{
            const step = {
                id: randomUUID(),
                context,
                prevStep: null,
                nextSteps: new Set()
            };
            if (steps.length > 0) {
                step.prevStep = steps[steps.length - 1];
            }
            const taskOutputs = [];
            steps.push(step);
            const enqueueOutput = (output)=>{
                context.logger.log("Enqueueing output for step(id, %s).", step.id);
                taskOutputs.push(output);
                controller.enqueue(output);
            };
            getCallbackManager().dispatchEvent("agent-start", {
                payload: {
                    startStep: step
                }
            });
            context.logger.log("Starting step(id, %s).", step.id);
            await handler(step, enqueueOutput);
            context.logger.log("Finished step(id, %s).", step.id);
            // fixme: support multi-thread when there are multiple outputs
            // todo: for now we pretend there is only one task output
            const { isLast, taskStep } = taskOutputs[0];
            context = {
                ...taskStep.context,
                store: {
                    ...taskStep.context.store
                },
                toolCallCount: 1
            };
            if (isLast) {
                context.logger.log("Final step(id, %s) reached, closing task.", step.id);
                getCallbackManager().dispatchEvent("agent-end", {
                    payload: {
                        endStep: step
                    }
                });
                controller.close();
            }
        }
    });
}
_computedKey = Symbol.toStringTag;
/**
 * Worker will schedule tasks and handle the task execution
 */ export class AgentWorker {
    #taskSet = new Set();
    createTask(query, context) {
        context.store.messages.push({
            role: "user",
            content: query
        });
        const taskOutputStream = createTaskOutputStream(this.taskHandler, context);
        return new ReadableStream({
            start: async (controller)=>{
                for await (const stepOutput of taskOutputStream){
                    this.#taskSet.add(stepOutput.taskStep);
                    controller.enqueue(stepOutput);
                    if (stepOutput.isLast) {
                        let currentStep = stepOutput.taskStep;
                        while(currentStep){
                            this.#taskSet.delete(currentStep);
                            currentStep = currentStep.prevStep;
                        }
                        controller.close();
                    }
                }
            }
        });
    }
    [_computedKey] = "AgentWorker";
}
/**
 * Runner will manage the task execution and provide a high-level API for the user
 */ export class AgentRunner {
    static{
        ({ e: [_initProto] } = _apply_decs_2203_r(this, [
            [
                wrapEventCaller,
                2,
                "chat"
            ]
        ], []));
    }
    #llm;
    #tools;
    #systemPrompt = null;
    #chatHistory;
    #runner;
    #verbose;
    static defaultCreateStore() {
        return Object.create(null);
    }
    constructor(params){
        _initProto(this);
        const { llm, chatHistory, systemPrompt, runner, tools, verbose } = params;
        this.#llm = llm;
        this.#chatHistory = chatHistory;
        this.#runner = runner;
        if (systemPrompt) {
            this.#systemPrompt = systemPrompt;
        }
        this.#tools = tools;
        this.#verbose = verbose;
    }
    get llm() {
        return this.#llm;
    }
    get chatHistory() {
        return this.#chatHistory;
    }
    get verbose() {
        return Settings.debug || this.#verbose;
    }
    reset() {
        this.#chatHistory = [];
    }
    getTools(query) {
        return typeof this.#tools === "function" ? this.#tools(query) : this.#tools;
    }
    static shouldContinue(task) {
        return task.context.toolCallCount < MAX_TOOL_CALLS;
    }
    createTask(message, stream = false, verbose = undefined) {
        const initialMessages = [
            ...this.#chatHistory
        ];
        if (this.#systemPrompt !== null) {
            const systemPrompt = this.#systemPrompt;
            const alreadyHasSystemPrompt = initialMessages.filter((msg)=>msg.role === "system").some((msg)=>Object.is(msg.content, systemPrompt));
            if (!alreadyHasSystemPrompt) {
                initialMessages.push({
                    content: systemPrompt,
                    role: "system"
                });
            }
        }
        return this.#runner.createTask(message, {
            stream,
            toolCallCount: 0,
            llm: this.#llm,
            getTools: (message)=>this.getTools(message),
            store: {
                ...this.createStore(),
                messages: initialMessages,
                toolOutputs: []
            },
            shouldContinue: AgentRunner.shouldContinue,
            logger: // disable verbose if explicitly set to false
            verbose === false ? emptyLogger : verbose || this.verbose ? consoleLogger : emptyLogger
        });
    }
    async chat(params) {
        const task = this.createTask(params.message, !!params.stream);
        for await (const stepOutput of task){
            // update chat history for each round
            this.#chatHistory = [
                ...stepOutput.taskStep.context.store.messages
            ];
            if (stepOutput.isLast) {
                const { output, taskStep } = stepOutput;
                if (isAsyncIterable(output)) {
                    return output.pipeThrough(new TransformStream({
                        transform (chunk, controller) {
                            controller.enqueue({
                                response: chunk,
                                get sources () {
                                    return [
                                        ...taskStep.context.store.toolOutputs
                                    ];
                                }
                            });
                        }
                    }));
                } else {
                    return {
                        response: output,
                        get sources () {
                            return [
                                ...taskStep.context.store.toolOutputs
                            ];
                        }
                    };
                }
            }
        }
        throw new Error("Task ended without a last step.");
    }
}
