import { forbidden } from '../../../types-global/errors.js';
/**
 * Wraps an InMemoryTaskStore to add session ownership enforcement.
 *
 * Tracks which session created each task and rejects access from
 * non-owning sessions. Tasks created without a sessionId are accessible
 * by any session (backwards-compatible with stdio/unauth flows).
 *
 * @experimental
 */
export class SessionAwareTaskStore {
    inner;
    /** Maps taskId -> sessionId that created it */
    ownership = new Map();
    constructor(inner) {
        this.inner = inner;
    }
    async createTask(taskParams, requestId, request, sessionId) {
        const task = await this.inner.createTask(taskParams, requestId, request, sessionId);
        if (sessionId) {
            this.ownership.set(task.taskId, sessionId);
        }
        return task;
    }
    async getTask(taskId, sessionId) {
        this.assertOwnership(taskId, sessionId);
        return await this.inner.getTask(taskId, sessionId);
    }
    async storeTaskResult(taskId, status, result, sessionId) {
        this.assertOwnership(taskId, sessionId);
        await this.inner.storeTaskResult(taskId, status, result, sessionId);
    }
    async getTaskResult(taskId, sessionId) {
        this.assertOwnership(taskId, sessionId);
        return await this.inner.getTaskResult(taskId, sessionId);
    }
    async updateTaskStatus(taskId, status, statusMessage, sessionId) {
        this.assertOwnership(taskId, sessionId);
        await this.inner.updateTaskStatus(taskId, status, statusMessage, sessionId);
    }
    async listTasks(cursor, sessionId) {
        const result = await this.inner.listTasks(cursor, sessionId);
        // Filter: session-bound tasks are only visible to their owning session.
        // Sessionless callers see only unowned tasks (consistent with StorageBackedTaskStore).
        const filtered = result.tasks.filter((task) => {
            const owner = this.ownership.get(task.taskId);
            if (!owner)
                return true; // Unowned — visible to everyone
            return owner === sessionId; // Session-bound — visible only to owner
        });
        const out = { tasks: filtered };
        if (result.nextCursor)
            out.nextCursor = result.nextCursor;
        return out;
    }
    /**
     * Validates that the caller's session matches the task's owner.
     * Tasks created without a sessionId are accessible by any session.
     */
    assertOwnership(taskId, callerSessionId) {
        const owner = this.ownership.get(taskId);
        if (!owner)
            return; // No owner recorded — accessible by anyone
        if (owner !== callerSessionId) {
            throw forbidden(`Access denied to task ${taskId}`);
        }
    }
}
//# sourceMappingURL=sessionAwareTaskStore.js.map