function normalizeLimit(limit) {
    if (!Number.isFinite(limit))
        return 1;
    return Math.max(1, Math.floor(limit));
}
function listTasksSnapshot(snapshot, limit = 100) {
    return snapshot.tasks.slice(0, normalizeLimit(limit));
}
function getTaskSnapshot(snapshot, taskId) {
    return snapshot.tasks.find((task) => task.id === taskId) ?? null;
}
function requireControlPlane(controlPlane) {
    if (!controlPlane) {
        throw new Error('Ops control plane is not available in this runtime.');
    }
    return controlPlane;
}
export function createRuntimeOpsApi(options) {
    return {
        tasks: {
            snapshot() {
                return options.tasksReadModel.getSnapshot();
            },
            list(limit = 100) {
                return listTasksSnapshot(options.tasksReadModel.getSnapshot(), limit);
            },
            get(taskId) {
                return getTaskSnapshot(options.tasksReadModel.getSnapshot(), taskId);
            },
            running() {
                return options.tasksReadModel.getSnapshot().tasks.filter((task) => task.status === 'running');
            },
            create(input) {
                return options.taskManager.createTask(input);
            },
            update(taskId, input) {
                return options.taskManager.updateTask(taskId, input);
            },
            complete(taskId, result) {
                return options.taskManager.completeTask(taskId, result);
            },
            fail(taskId, input) {
                return options.taskManager.failTask(taskId, input);
            },
            cancel(taskId, note) {
                requireControlPlane(options.opsControlPlane).cancelTask(taskId, note);
            },
            pause(taskId, note) {
                requireControlPlane(options.opsControlPlane).pauseTask(taskId, note);
            },
            resume(taskId, note) {
                requireControlPlane(options.opsControlPlane).resumeTask(taskId, note);
            },
            retry(taskId, note) {
                requireControlPlane(options.opsControlPlane).retryTask(taskId, note);
            },
        },
        agents: {
            cancel(agentId, note) {
                requireControlPlane(options.opsControlPlane).cancelAgent(agentId, note);
            },
        },
    };
}
