/**
 * Owns one session's PTY + parser lifecycle.
 */
export class AgentPipeline {
    sessionId;
    pty;
    parser;
    msgStore;
    eventBus;
    destroyed = false;
    offData;
    offExit;
    offPatch;
    offSessionId;
    constructor(sessionId, pty, parser, msgStore, eventBus) {
        this.sessionId = sessionId;
        this.pty = pty;
        this.parser = parser;
        this.msgStore = msgStore;
        this.eventBus = eventBus;
        this.offPatch = this.msgStore.onPatch((patch, seq) => {
            this.eventBus.emit('session:patch', { sessionId: this.sessionId, patch, seq });
        });
        this.offSessionId = this.msgStore.onSessionId((agentSessionId) => {
            this.eventBus.emit('session:sessionId', { sessionId: this.sessionId, agentSessionId });
        });
        this.offData = this.pty.onData((data) => {
            if (this.destroyed)
                return;
            this.msgStore.pushStdout(data);
            this.eventBus.emit('session:stdout', { sessionId: this.sessionId, data });
            this.parser?.processData(data);
        });
        this.offExit = this.pty.onExit(({ exitCode }) => {
            if (this.destroyed)
                return;
            this.parser?.finish(exitCode);
            this.msgStore.pushFinished();
            this.eventBus.emit('session:exit', { sessionId: this.sessionId, exitCode });
            // Self-cleanup: remove MsgStore listeners so stale references don't accumulate.
            // SessionManager.session:exit handler also calls destroy(), but this ensures
            // cleanup even if external code doesn't explicitly destroy the pipeline.
            this.destroy();
        });
    }
    get isAlive() {
        return !this.destroyed;
    }
    write(data) {
        if (this.destroyed)
            return;
        this.pty.write(data);
    }
    resize(cols, rows) {
        if (this.destroyed)
            return;
        this.pty.resize(cols, rows);
    }
    destroy() {
        if (this.destroyed)
            return;
        this.destroyed = true;
        this.offData?.dispose();
        this.offExit?.dispose();
        this.offPatch?.();
        this.offSessionId?.();
        this.parser?.finish();
        try {
            this.pty.kill();
        }
        catch {
            // ignore kill errors for already-exited processes
        }
    }
}
//# sourceMappingURL=agent-pipeline.js.map