"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamFileWriter = void 0;
/**
 * Buffered append-writer for live LLM streaming.
 *
 * Why this exists: the previous implementation called fs.appendFileSync on
 * every text_delta event from the CLI shim. A typical Opus run emits ~5
 * deltas/sec for ~5 minutes = ~1500 sync disk writes per doer, each one
 * blocking the daemon event loop. Worse, the cockpit polls answer.md every
 * 8s — it doesn't benefit from per-delta granularity.
 *
 * Now we flush whenever the buffer crosses 4KB OR a 750ms quiet timer
 * fires, whichever comes first. Cockpit poll cadence is unchanged but
 * the daemon does ~50 writes per run instead of ~1500.
 *
 * Caller MUST call flushNow() before any direct read of `path` or before
 * fs.writeFileSync overwrites it — the buffer is otherwise lost.
 *
 * Failure semantics: if the underlying appendFileSync ever throws (FS
 * ENOSPC, EACCES, etc.) the writer flips to a "dead" state and surfaces
 * the cause via lastError(). Subsequent write() calls become no-ops; the
 * buffered chunk that failed is dropped (re-trying would just fail again
 * synchronously and leak more memory). The runner inspects isDead() /
 * lastError() in its finally block to surface a cli_error event so the
 * user knows their answer.md is partial — silent loss was the previous
 * behavior and round-2 review flagged it.
 */
const fs = __importStar(require("fs"));
class StreamFileWriter {
    filePath;
    flushBytes;
    flushMs;
    buf = '';
    flushTimer = null;
    dead = false;
    lastErr = null;
    constructor(filePath, flushBytes = 4096, flushMs = 750) {
        this.filePath = filePath;
        this.flushBytes = flushBytes;
        this.flushMs = flushMs;
    }
    write(chunk) {
        if (!chunk || this.dead)
            return;
        this.buf += chunk;
        if (this.buf.length >= this.flushBytes) {
            this.flushNow();
        }
        else if (this.flushTimer === null) {
            this.flushTimer = setTimeout(() => this.flushNow(), this.flushMs);
        }
    }
    flushNow() {
        if (this.flushTimer !== null) {
            clearTimeout(this.flushTimer);
            this.flushTimer = null;
        }
        if (this.buf.length === 0 || this.dead)
            return;
        try {
            fs.appendFileSync(this.filePath, this.buf);
            this.buf = '';
        }
        catch (err) {
            // Permanent failure — flip dead, drop the in-flight buffer to free
            // memory, surface via lastError() for the runner to forward as a
            // cli_error so the user sees something instead of a quietly stale
            // answer.md.
            this.dead = true;
            this.lastErr = err instanceof Error ? err : new Error(String(err));
            this.buf = '';
        }
    }
    isDead() {
        return this.dead;
    }
    lastError() {
        return this.lastErr;
    }
}
exports.StreamFileWriter = StreamFileWriter;
//# sourceMappingURL=stream-file-writer.js.map