export function createLinearTaskDag(state, runId, tasks) {
    const ids = [];
    for (const task of tasks) {
        const id = state.createTask({
            runId,
            agent: task.agent,
            title: task.title,
            detail: task.detail,
        });
        const previous = ids.at(-1);
        if (previous)
            state.addTaskDependency(id, previous);
        ids.push(id);
    }
    return ids;
}
export class DurableTaskQueue {
    state;
    constructor(state) {
        this.state = state;
    }
    createLinearDag(runId, tasks) {
        return createLinearTaskDag(this.state, runId, tasks);
    }
    runnable(runId, limit = 20) {
        return this.state.listRunnableTasks(runId, limit);
    }
    claimNext(runId, claimant = "local-worker") {
        return this.state.claimNextTask(runId, claimant);
    }
    complete(taskId, detail = "completed") {
        this.state.updateTaskStatus(taskId, "succeeded", detail);
    }
    retry(taskId, detail = "retry requested") {
        return this.state.retryTask(taskId, detail);
    }
    retryFailed(runId, detail = "retry failed tasks") {
        return this.state
            .listTasks(runId)
            .filter((task) => task.status === "failed" || task.status === "cancelled")
            .map((task) => this.retry(task.id, detail));
    }
    fail(taskId, detail = "failed") {
        this.state.updateTaskStatus(taskId, "failed", detail);
    }
    pauseRun(runId, reason = "paused by user") {
        this.state.updateRunStatus(runId, "paused", reason);
    }
    resumeRun(runId, reason = "resumed by user") {
        this.state.updateRunStatus(runId, "running", reason);
    }
    cancelRun(runId, reason = "cancelled by user") {
        this.state.updateRunStatus(runId, "cancelled", reason);
        for (const task of this.state.listTasks(runId)) {
            if (task.status !== "succeeded" && task.status !== "cancelled") {
                this.state.updateTaskStatus(task.id, "cancelled", reason);
            }
        }
        for (const job of this.state.listJobs({ runId, limit: 100 })) {
            if (job.status === "queued" || job.status === "running") {
                this.state.finishJob(job.id, "cancelled", reason);
            }
        }
    }
}
