UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

1,174 lines • 50.3 kB
/**
 * RPC Client for programmatic access to the coding agent.
 *
 * Spawns the agent in RPC mode and provides a typed API for all operations.
 */
import { spawn } from "node:child_process";
import { clientMessageIdentity } from "../../core/client-message-identity.js";
import { MissingSessionCwdError } from "../../core/session-cwd.js";
import { unknownCommandErrorFromWire } from "../../core/unknown-command.js";
import { signalSpawnedChild } from "../../utils/child-signal.js";
import { DETACH_CONNECTION_CAPABILITY } from "./custom-capability.js";
import { ORIGIN_HOST_INSTANCE_FIELD, originHostInstance } from "./host-observe-request.js";
import { RpcCommandError } from "./rpc-command-error.js";
import { handleRpcReply, UnawaitedReplies } from "./rpc-client-replies.js";
import { RpcClientAdmissions, } from "./rpc-client-admissions.js";
export { RpcCommandError } from "./rpc-command-error.js";
import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.js";
import { isProviderAccountEvent } from "./rpc-client-events.js";
import { childEnvironmentOf } from "./host-identity-env.js";
import { connectRpcClientSocket } from "./rpc-client-socket.js";
import { armRequestDeadline, OPEN_AFTER_QUEUED_DEADLINE_MS, openStalledMessage, PROMPT_ACK_MAX_WAIT_MS, PROMPT_AFTER_QUEUED_DEADLINE_MS, PROMPT_COMPACTION_DEADLINE_MS, promptStalledMessage, REQUEST_DEADLINE_MS, RpcRequestTimeoutError, requestDeadlineMs, } from "./rpc-request-deadline.js";
import { RPC_ERROR_SESSION_NOT_ATTACHED, RPC_ERROR_UNKNOWN_COMMAND } from "./rpc-types.js";
// ============================================================================
// RPC Client
// ============================================================================
export class RpcTransportGoneError extends Error {
    constructor(message = "Shared RPC host is unavailable") {
        super(message);
        this.code = "rpc_transport_gone";
        this.name = "RpcTransportGoneError";
    }
}
export function isTransportGoneError(error) {
    return (error instanceof RpcTransportGoneError ||
        (error instanceof Error &&
            (error.message === "Client not started" ||
                error.message.startsWith("RPC transport is not writable.") ||
                error.message === "RPC socket closed")));
}
export class RpcClientOpenInFlightError extends Error {
    constructor() {
        super("An open_session request is already in flight");
        this.code = "open_session_in_flight";
        this.name = "RpcClientOpenInFlightError";
    }
}
// Keep pre-lease startup delivery bounded by both record count and wire size.
const MAX_PENDING_SESSION_EVENTS = 512;
const MAX_PENDING_SESSION_EVENT_BYTES = 1024 * 1024;
export class RpcClient {
    constructor(options = {}) {
        this.admissions = new RpcClientAdmissions((command) => this.send(command, false));
        this.process = null;
        this.socket = null;
        this.stopReadingStdout = null;
        this.eventListeners = [];
        /** Replies to records this client sent without waiting (senpi#5761), consumed quietly. */
        this.unawaitedReplies = new UnawaitedReplies();
        this.pendingRequests = new Map();
        this.requestId = 0;
        /**
         * Compactions observed for this client's session and not yet ended, keyed by operation id (`""` for
         * hosts that send none), with the time each started. Tracking each operation separately means a
         * stale or overlapping start never hides another operation's end.
         */
        this.compactions = new Map();
        this.pendingOpenSession = false;
        this.pendingSessionEvents = [];
        this.pendingSessionEventBytes = 0;
        this.stderr = "";
        this.exitError = null;
        this.disconnectNotified = false;
        this.stopping = false;
        /** The host generation this client runs inside, named on every socket request (#3272). */
        this.originHost = originHostInstance();
        this.options = options;
        // The event stream is already scoped to this client's session, including
        // pre-lease events replayed after open_session.
        this.onEvent((event) => {
            switch (event.type) {
                case "compaction_start": {
                    const key = event.requestId ?? "";
                    if (this.compactions.has(key))
                        return;
                    this.compactions.set(key, Date.now());
                    break;
                }
                case "compaction_end":
                    if (!this.compactions.delete(event.requestId ?? ""))
                        return;
                    break;
                case "session_replaced":
                    this.compactions.clear();
                    break;
                default:
                    return;
            }
            for (const pending of this.pendingRequests.values()) {
                if (pending.sessionId === this.sessionId)
                    pending.onCompaction?.(this.isCompacting());
            }
        });
    }
    /**
     * Start the RPC agent process.
     */
    async start() {
        if (this.process || this.socket) {
            throw new Error("Client already started");
        }
        this.exitError = null;
        this.compactions.clear();
        this.stopping = false;
        this.disconnectNotified = false;
        if (this.options.socketPath) {
            await this.startSocket(this.options.socketPath);
            return;
        }
        const cliPath = this.options.cliPath ?? "dist/cli.js";
        const args = ["--mode", "rpc"];
        // A lone --provider is a CLI error; without a model the host keeps its default model, as before.
        if (this.options.provider && this.options.model) {
            args.push("--provider", this.options.provider);
        }
        if (this.options.model) {
            args.push("--model", this.options.model);
        }
        if (this.options.args) {
            args.push(...this.options.args);
        }
        const childProcess = spawn("node", [cliPath, ...args], {
            cwd: this.options.cwd,
            env: {
                // A stdio child never reads the host's supervisor hand-off (senpi#5635).
                ...childEnvironmentOf(process.env),
                // The spawned child must BE the process this client signals and reaps. An ambient
                // SENPI_RUNTIME=bun pin makes the launcher re-exec under Bun via spawnSync, so a
                // SIGTERM to the wrapper leaves the Bun host running: it keeps the session lease
                // and keeps writing session state after stop() resolved. Pin the runtime to the
                // interpreter chosen here; options.env is
                // spread last so a caller can still override the pin explicitly.
                SENPI_RUNTIME: "node",
                ...this.options.env,
            },
            stdio: ["pipe", "pipe", "pipe"],
            // Callers may be console-less on win32 (GUI hosts, detached daemons), and a
            // console-subsystem child would then allocate a fresh visible terminal window.
            windowsHide: true,
        });
        this.process = childProcess;
        // Collect stderr for debugging
        childProcess.stderr?.on("data", (data) => {
            this.stderr += data.toString();
            process.stderr.write(data);
        });
        childProcess.once("exit", (code, signal) => {
            if (this.process !== childProcess)
                return;
            const error = this.createProcessExitError(code, signal);
            this.exitError = error;
            this.rejectPendingRequests(error);
        });
        childProcess.once("error", (error) => {
            if (this.process !== childProcess)
                return;
            const processError = new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);
            this.exitError = processError;
            this.rejectPendingRequests(processError);
        });
        childProcess.stdin?.on("error", (error) => {
            if (this.process !== childProcess)
                return;
            const stdinError = this.exitError ?? new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);
            this.exitError = stdinError;
            this.rejectPendingRequests(stdinError);
        });
        // Set up strict JSONL reader for stdout.
        this.stopReadingStdout = attachJsonlLineReader(childProcess.stdout, (line) => {
            this.handleLine(line);
        });
        // Wait a moment for process to initialize
        await new Promise((resolve) => setTimeout(resolve, 100));
        if (this.process.exitCode !== null) {
            const error = this.exitError ?? this.createProcessExitError(this.process.exitCode, this.process.signalCode);
            this.exitError = error;
            throw error;
        }
    }
    /**
     * Whether a compaction is in progress for this client's session. A start whose end never arrives (a
     * dropped frame, or a host that stopped without one) stops counting once it is older than the
     * compaction budget, so it cannot leave every later prompt on the long wait.
     */
    isCompacting() {
        const now = Date.now();
        for (const [key, startedAt] of this.compactions) {
            if (now - startedAt >= PROMPT_COMPACTION_DEADLINE_MS)
                this.compactions.delete(key);
        }
        return this.compactions.size > 0;
    }
    /**
     * Stop the RPC agent process.
     */
    async stop() {
        this.compactions.clear();
        this.pendingOpenSession = false;
        this.pendingSessionEvents = [];
        this.pendingSessionEventBytes = 0;
        if (this.socket) {
            this.stopping = true;
            this.stopReadingStdout?.();
            this.stopReadingStdout = null;
            this.socket.destroy();
            this.socket = null;
            this.sessionId = undefined;
            this.pendingOpenSession = false;
            this.pendingSessionEvents = [];
            this.notifyDisconnect(new RpcTransportGoneError());
            return;
        }
        if (!this.process)
            return;
        this.stopReadingStdout?.();
        this.stopReadingStdout = null;
        signalSpawnedChild(this.process, "SIGTERM");
        // Wait for process to exit
        await new Promise((resolve) => {
            const timeout = setTimeout(() => {
                if (this.process)
                    signalSpawnedChild(this.process, "SIGKILL");
                resolve();
            }, 1000);
            this.process?.on("exit", () => {
                clearTimeout(timeout);
                resolve();
            });
        });
        this.process = null;
        this.pendingRequests.clear();
    }
    async startSocket(path) {
        const socket = await connectRpcClientSocket(path, this.options);
        this.socket = socket;
        this.stopReadingStdout = attachJsonlLineReader(socket, (line) => this.handleLine(line));
        socket.once("close", () => {
            if (this.socket !== socket)
                return;
            this.socket = null;
            this.notifyDisconnect(new RpcTransportGoneError());
        });
        socket.once("error", (error) => {
            if (this.socket !== socket)
                return;
            this.notifyDisconnect(new RpcTransportGoneError());
            void error;
        });
    }
    /**
     * Subscribe to agent events.
     */
    onEvent(listener) {
        this.eventListeners.push(listener);
        return () => {
            const index = this.eventListeners.indexOf(listener);
            if (index !== -1) {
                this.eventListeners.splice(index, 1);
            }
        };
    }
    /**
     * Get collected stderr output (useful for debugging).
     */
    getStderr() {
        return this.stderr;
    }
    // =========================================================================
    // Command Methods
    // =========================================================================
    async setClientInfo(width, capabilities) {
        await this.send({ type: "set_client_info", width, capabilities }, this.sessionId !== undefined);
    }
    async openSession(options) {
        if (this.pendingOpenSession)
            throw new RpcClientOpenInFlightError();
        this.pendingOpenSession = true;
        try {
            const opened = options.admissionId === undefined
                ? this.getData(await this.send({ type: "open_session", ...options }, false))
                : await this.admissions.open({ ...options, admissionId: options.admissionId });
            this.sessionId = opened.sessionId;
            this.compactions.clear();
            this.pendingOpenSession = false;
            this.flushPendingSessionEvents();
            return opened;
        }
        catch (error) {
            this.pendingOpenSession = false;
            this.pendingSessionEvents = [];
            this.pendingSessionEventBytes = 0;
            throw error;
        }
    }
    async sendExtensionUIResponse(response) {
        await this.send(response, true, undefined, false);
    }
    async resumeSession() {
        await this.send({ type: "resume_session" });
    }
    /**
     * Task-parent run controls (senpi#3811), sent on a `task_parent` connection. A refusal the engine answers as an
     * error (`wrong_parent`, `task_parent_required`) throws with its message; a stale release is an answer.
     */
    async pauseForRun(command) {
        return this.getData(await this.send({ ...command, type: "pause_for_run" }));
    }
    async resumeForRun(command) {
        return this.getData(await this.send({ ...command, type: "resume_for_run" }));
    }
    /** Human input held for a paused session; from a task parent it names the parent session that paused the child. */
    async holdInput(command) {
        return this.getData(await this.send({ ...command, type: "hold_input" }));
    }
    /** Draft update for an open `question` request; fire-and-forget like the response. */
    async sendExtensionUIProgress(progress) {
        await this.send(progress, true, undefined, false);
    }
    /** `unload_session`: a refusal is an answer (`outcome: "refused"` with reason and action), not a throw. */
    async unloadSession(options) {
        const sessionId = options.sessionId ?? this.sessionId;
        if (!sessionId)
            throw new Error("unload_session needs a session");
        return this.getData(await this.send({ ...options, type: "unload_session", sessionId }, false));
    }
    /**
     * Patch the context the attached session publishes (`set_session_context`); `null` deletes a key.
     * Rejects with {@link RpcCommandError} carrying the host's code (`session_not_attached`, `invalid_session_context`);
     * a client with no attached session and no `sessionId` refuses locally with the same `session_not_attached` code.
     */
    async setSessionContext(patch, sessionId = this.sessionId) {
        if (!sessionId) {
            throw new RpcCommandError(`${RPC_ERROR_SESSION_NOT_ATTACHED}: set_session_context needs a session`, RPC_ERROR_SESSION_NOT_ATTACHED, {
                reason: "this client has no attached session",
                action: "attach with openSession first, or pass a sessionId",
            });
        }
        this.getData(await this.send({ type: "set_session_context", sessionId, patch }, false));
    }
    async closeSession(sessionId = this.sessionId) {
        if (!sessionId)
            return;
        try {
            this.getData(await this.send({ type: "close_session", sessionId }, false));
        }
        catch (error) {
            if (!isTransportGoneError(error))
                throw error;
        }
        if (this.sessionId === sessionId) {
            this.sessionId = undefined;
            this.compactions.clear();
        }
    }
    /**
     * Drop this connection's session attachments and wait until the host confirms they are gone (senpi#3238).
     * A host without `detach_connection` is left to today's release on socket close: `"unsupported"`.
     * Otherwise `deferred` names the sessions that still count this connection (see `detach_connection`).
     */
    async detachConnection() {
        const info = this.getData(await this.send({ type: "get_protocol_info" }, false));
        if (!Array.isArray(info.capabilities) || !info.capabilities.includes(DETACH_CONNECTION_CAPABILITY))
            return "unsupported";
        const data = this.getData(await this.send({ type: "detach_connection" }, false));
        const deferred = Array.isArray(data?.deferred)
            ? data.deferred.filter((id) => typeof id === "string")
            : [];
        return { deferred };
    }
    async listSessions(options) {
        const response = await this.send({ type: "list_sessions", ...options }, false);
        return this.getData(response).sessions;
    }
    async prompt(message, optionsOrImages) {
        const options = Array.isArray(optionsOrImages)
            ? { images: optionsOrImages }
            : (optionsOrImages ?? {});
        const response = await this.send({
            type: "prompt",
            message,
            ...clientMessageIdentity(options),
            ...(options.images ? { images: options.images } : {}),
            ...(options.streamingBehavior ? { streamingBehavior: options.streamingBehavior } : {}),
            ...(options.thinkingLevel ? { thinkingLevel: options.thinkingLevel } : {}),
            ...(options.sessionTitlePrompt !== undefined ? { sessionTitlePrompt: options.sessionTitlePrompt } : {}),
            ...(options.expandPromptTemplates !== undefined
                ? { expandPromptTemplates: options.expandPromptTemplates }
                : {}),
            ...(options.unknownCommandAsText ? { unknownCommandAsText: true } : {}),
        }, true, {
            onResponse: (wireResponse) => {
                if (!wireResponse.success) {
                    options?.preflightResult?.(false);
                    return;
                }
                const data = wireResponse.data;
                options?.promptDisposition?.(data?.disposition ?? "handled");
                options?.preflightResult?.(true);
            },
            onReject: () => {
                options?.preflightResult?.(false);
            },
        });
        if (!response.success) {
            const failure = response;
            const unknownCommand = failure.errorCode === RPC_ERROR_UNKNOWN_COMMAND
                ? unknownCommandErrorFromWire(failure.errorData)
                : undefined;
            throw unknownCommand ?? new RpcCommandError(failure.error, failure.errorCode, failure.errorData);
        }
        // Older hosts omit the disposition; "handled" matches the promptDisposition callback fallback.
        return response.data?.disposition ?? "handled";
    }
    async appendUserMessage(content) {
        await this.send({ type: "append_user_message", content });
    }
    async appendSessionEntry(entry) {
        await this.send({ type: "append_session_entry", entry });
    }
    async sendCustomMessage(message, options) {
        await this.send({ type: "send_custom_message", ...message, ...options });
    }
    /**
     * Start a turn from the current leaf with no new prompt (#1930), for example after an
     * edited assistant response. Refused with `streaming` or `nothing_to_continue`.
     */
    async continueFromLeaf() {
        const response = await this.send({ type: "continue_from_leaf" });
        this.getData(response);
    }
    /**
     * Queue a steering message to interrupt the agent mid-run.
     */
    async steer(message, images, recovery) {
        const response = await this.send({
            type: "steer",
            message,
            images,
            enqueueOrder: recovery?.enqueueOrder,
            ...clientMessageIdentity(recovery),
        });
        // Older hosts omit the disposition; degrade like prompt() so clients render only canonical events.
        return this.getData(response)?.disposition ?? "handled";
    }
    /**
     * Queue a follow-up message to be processed after the agent finishes.
     */
    async followUp(message, images, recovery) {
        const response = await this.send({
            type: "follow_up",
            message,
            images,
            enqueueOrder: recovery?.enqueueOrder,
            ...clientMessageIdentity(recovery),
        });
        // Older hosts omit the disposition; degrade like prompt() so clients render only canonical events.
        return this.getData(response)?.disposition ?? "handled";
    }
    async abort(options) {
        if (options === undefined) {
            try {
                await this.send({ type: "abort" });
            }
            catch (error) {
                if (!isTransportGoneError(error))
                    throw error;
            }
            return;
        }
        return this.getData(await this.send({ ...options, type: "abort" }));
    }
    /**
     * The newest receipt of one effect (`get_effect_status`, capability `effect_ledger`). With `sessionPath`
     * the host reads that transcript from disk, so a session no host holds is answered without loading it.
     */
    async getEffectStatus(effectId, options = {}) {
        const command = {
            type: "get_effect_status",
            effectId,
            ...(options.sessionPath === undefined ? {} : { sessionPath: options.sessionPath }),
        };
        return this.getData(await this.send(command, options.sessionPath === undefined));
    }
    /**
     * The pending inputs in durable custody (queued, sending, failed) and an explicit outcome for each id in
     * `knownClientMessageIds` (at most 64), consistent through `throughCursor`.
     */
    async getPendingInputs(knownClientMessageIds) {
        const command = {
            type: "get_pending_inputs",
            ...(knownClientMessageIds === undefined ? {} : { knownClientMessageIds: [...knownClientMessageIds] }),
        };
        return this.getData(await this.send(command));
    }
    /** Abort with host refusals and transport loss surfaced to machine callers. */
    async abortStrict() {
        this.getData(await this.send({ type: "abort" }));
    }
    async abortCompaction() {
        await this.send({ type: "abort_compaction" });
    }
    async reload() {
        const response = await this.send({ type: "reload" });
        return this.getData(response);
    }
    async checkReloadVeto() {
        const response = await this.send({ type: "check_reload_veto" });
        return this.getData(response);
    }
    /**
     * Clear queued steering and follow-up messages, returning their text.
     */
    async clearQueue(options) {
        const response = await this.send({ type: "clear_queue", abortWillFollow: options?.abortWillFollow });
        return this.getData(response);
    }
    async getSteeringMessages() {
        const response = await this.send({ type: "get_steering_messages" });
        return this.getData(response).messages;
    }
    async getFollowUpMessages() {
        const response = await this.send({ type: "get_follow_up_messages" });
        return this.getData(response).messages;
    }
    async abortBranchSummary() {
        await this.send({ type: "abort_branch_summary" });
    }
    async recordBashResult(command, result, excludeFromContext) {
        await this.send({ type: "record_bash_result", command, result, excludeFromContext });
    }
    async setLabel(entryId, label) {
        await this.send({ type: "set_label", entryId, label });
    }
    /**
     * Start a new session, optionally with parent tracking.
     * @param parentSession - Optional parent session path for lineage tracking
     * @returns Object with `cancelled: true` if an extension cancelled the new session
     */
    async newSession(parentSession) {
        const response = await this.send({ type: "new_session", parentSession });
        return this.getData(response);
    }
    /**
     * Get current session state.
     */
    async getState() {
        const response = await this.send({ type: "get_state" });
        return this.getData(response);
    }
    /**
     * Set model by provider and ID.
     */
    async setModel(provider, modelId) {
        const response = await this.send({ type: "set_model", provider, modelId });
        return this.getData(response);
    }
    /**
     * Cycle to next model.
     */
    async setFavoriteModels(models) {
        await this.send({ type: "set_favorite_models", models });
    }
    async setScopedModels(models) {
        await this.send({ type: "set_scoped_models", models });
    }
    async cycleModel(direction = "forward") {
        const response = await this.send({ type: "cycle_model", direction });
        return this.getData(response);
    }
    /**
     * Get list of available models.
     */
    async getAvailableModels() {
        const response = await this.send({ type: "get_available_models" });
        return this.getData(response).models;
    }
    /**
     * Set thinking level.
     *
     * `scope: "turn"` changes only this session's level without rewriting the model's remembered
     * level; it throws when the active model does not support the requested level, and the
     * session keeps the level it already had.
     */
    async setThinkingLevel(level, options) {
        const response = await this.send({ type: "set_thinking_level", level, scope: options?.scope });
        if (!response.success) {
            throw new Error(response.error);
        }
    }
    /**
     * Cycle thinking level.
     */
    async cycleThinkingLevel() {
        const response = await this.send({ type: "cycle_thinking_level" });
        return this.getData(response);
    }
    /**
     * Get list of available thinking levels for the current model.
     */
    async getAvailableThinkingLevels() {
        const response = await this.send({ type: "get_available_thinking_levels" });
        return this.getData(response).levels;
    }
    /**
     * The level a model runs at in this session (the current one when it is active, otherwise what a
     * switch to it would restore), where that level comes from, and the levels the model supports.
     */
    async getModelThinkingLevel(provider, modelId) {
        const response = await this.send({ type: "get_model_thinking_level", provider, modelId });
        return this.getData(response);
    }
    /**
     * Turn ChatGPT Subscription fast mode (the `priority` service tier) on or off for the active model.
     *
     * The choice is remembered per model, so a later session on the same model starts the same
     * way. Throws when the request is refused: a non-Codex model, or an active `:priority` model
     * pin that fast mode must not undo.
     */
    async setFastMode(enabled) {
        const response = await this.send({ type: "set_fast_mode", enabled });
        return this.getData(response);
    }
    /** Current fast-mode state and the service tier requests would carry. */
    async getFastMode() {
        const response = await this.send({ type: "get_fast_mode" });
        return this.getData(response);
    }
    /**
     * Set steering mode.
     */
    async setSteeringMode(mode) {
        await this.send({ type: "set_steering_mode", mode });
    }
    /**
     * Set follow-up mode.
     */
    async setFollowUpMode(mode) {
        await this.send({ type: "set_follow_up_mode", mode });
    }
    /**
     * Compact session context.
     */
    async compact(customInstructions) {
        const response = await this.send({ type: "compact", customInstructions });
        return this.getData(response);
    }
    /**
     * Set auto-compaction enabled/disabled.
     */
    async setAutoCompaction(enabled) {
        await this.send({ type: "set_auto_compaction", enabled });
    }
    /**
     * Set auto-retry enabled/disabled.
     */
    async setAutoRetry(enabled) {
        await this.send({ type: "set_auto_retry", enabled });
    }
    /**
     * Abort in-progress retry.
     */
    async abortRetry() {
        await this.send({ type: "abort_retry" });
    }
    /**
     * Give this single-session process its fallback chain before the first turn (`set_retry_fallback`).
     * Requires the `retry_fallback_command` capability.
     */
    async setRetryFallback(retryFallback) {
        await this.send({ type: "set_retry_fallback", retryFallback });
    }
    /**
     * Execute a bash command.
     */
    async bash(command, options) {
        const response = await this.send({
            type: "bash",
            command,
            excludeFromContext: options?.excludeFromContext,
            executionId: options?.executionId,
            operations: options?.operations,
        });
        return this.getData(response);
    }
    async navigateTree(targetId, options) {
        const response = await this.send({ type: "navigate_tree", targetId, ...options });
        return this.getData(response);
    }
    /**
     * Abort running bash command.
     */
    async abortBash() {
        await this.send({ type: "abort_bash" });
    }
    async cleanupBashOutput(path) {
        await this.send({ type: "cleanup_bash_output", path });
    }
    /**
     * Get session statistics.
     */
    async getSessionStats() {
        const response = await this.send({ type: "get_session_stats" });
        return this.getData(response);
    }
    /** Which file a message's path means, by the engine's one rule (senpi#3415). */
    async resolvePath(path) {
        const response = await this.send({ type: "resolve_path", path });
        return this.getData(response);
    }
    /**
     * Export session to HTML.
     */
    async exportHtml(outputPath, themeName) {
        const response = await this.send({ type: "export_html", outputPath, themeName });
        return this.getData(response);
    }
    async exportJsonl(outputPath) {
        const response = await this.send({ type: "export_jsonl", outputPath });
        return this.getData(response);
    }
    /**
     * Switch to a different session file.
     * @returns Object with `cancelled: true` if an extension cancelled the switch
     */
    async switchSession(sessionPath, options) {
        const response = await this.send({ type: "switch_session", sessionPath, cwdOverride: options?.cwdOverride });
        return this.getData(response);
    }
    /**
     * Fork from a specific message.
     * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)
     */
    async fork(entryId, options) {
        const response = await this.send({ type: "fork", entryId, position: options?.position });
        return this.getData(response);
    }
    /**
     * Clone the current active branch into a new session.
     * @returns Object with `cancelled: true` if an extension cancelled the clone
     */
    async clone() {
        const response = await this.send({ type: "clone" });
        return this.getData(response);
    }
    /**
     * Get messages available for forking.
     */
    async getForkMessages() {
        const response = await this.send({ type: "get_fork_messages" });
        return this.getData(response).messages;
    }
    /**
     * Get session entries in append order, optionally only those after the `since` entry id. Pass `page`
     * (`limit` and/or `maxBytes`) to read a long history in bounded pages: repeat with `since: nextSince`
     * until `hasMore` is false. An unpaged read of a history too large for one answer fails with
     * `response_too_large`.
     */
    async getEntries(since, page) {
        const response = await this.send({ type: "get_entries", since, ...page });
        return this.getData(response);
    }
    /**
     * Get the session entry tree.
     */
    async getTree() {
        const response = await this.send({ type: "get_tree" });
        return this.getData(response);
    }
    /**
     * Replace an assistant response with an edited copy (branches to the target's parent and appends
     * the copy as the new leaf). Pass the `leafId` you last observed as `expectedLeafId` so a stale
     * edit is refused with `errorCode: "stale_leaf"` instead of rewriting a conversation another client
     * moved. Failures reject with an {@link RpcCommandError} carrying the typed `errorCode`.
     */
    async editAssistantMessage(entryId, text, options = {}) {
        const response = await this.send({
            type: "edit_assistant_message",
            entryId,
            text,
            expectedLeafId: options.expectedLeafId,
            summarize: options.summarize,
            customInstructions: options.customInstructions,
        });
        return this.getData(response);
    }
    /**
     * Replace a user prompt without starting a turn. Address the message by entryId and pass the
     * separately observed leafId as expectedLeafId. Refusals reject with RpcCommandError.
     */
    async editUserMessage(entryId, text, options = {}) {
        const response = await this.send({
            type: "edit_user_message",
            entryId,
            text,
            expectedLeafId: options.expectedLeafId,
            summarize: options.summarize,
            customInstructions: options.customInstructions,
        });
        return this.getData(response);
    }
    /**
     * Get text of last assistant message.
     */
    async getLastAssistantText() {
        const response = await this.send({ type: "get_last_assistant_text" });
        return this.getData(response).text;
    }
    /**
     * Set the session display name.
     */
    async setSessionName(name) {
        await this.send({ type: "set_session_name", name });
    }
    /**
     * Archive or unarchive the session; the flag is stored in its session file.
     */
    async setSessionArchived(archived) {
        await this.send({ type: "set_session_archived", archived });
    }
    /**
     * Mark the session Done or reopen it; the flag and how it was reached (`by`) are stored in its session file.
     */
    async setSessionSettled(settled, by) {
        await this.send({ type: "set_session_settled", settled, ...(by !== undefined ? { by } : {}) });
    }
    /**
     * Report that the user started typing a draft, so a first-activity prompt-cache prewarm can run (senpi#3859).
     */
    async recordDraftActivity() {
        await this.send({ type: "record_user_activity", kind: "draft" });
    }
    async importJsonl(inputPath, cwdOverride) {
        const response = await this.send({ type: "import_jsonl", inputPath, cwdOverride });
        return this.getData(response);
    }
    /**
     * Get all messages in the session.
     */
    async getMessages() {
        const response = await this.send({ type: "get_messages" });
        return this.getData(response).messages;
    }
    /**
     * Fetch one media block that arrived as an `image_ref` placeholder.
     *
     * `contentIndex` is the index inside the tool result's `content` array carried by
     * the placeholder's `ref`. Rejects with `media_not_found` when the tool call is
     * unknown or the index does not point at an image block.
     */
    async getMedia(toolCallId, contentIndex) {
        const response = await this.send({ type: "get_media", toolCallId, contentIndex });
        return this.getData(response).content;
    }
    /**
     * Get available commands (extension commands, prompt templates, skills).
     */
    async getCommands() {
        const response = await this.send({ type: "get_commands" });
        return this.getData(response).commands;
    }
    /** Invoke one extension-owned RPC request handler and return its structured result. */
    async requestExtension(name, data) {
        const response = await this.send({
            type: "extension_request",
            name,
            ...(data === undefined ? {} : { data }),
        });
        return this.getData(response);
    }
    /** Read live and recently settled eval cells without a model tool call. */
    async listEvalCells() {
        return this.getData(await this.send({ type: "eval_cells.list" }));
    }
    /** Read a bounded UTF-8 output tail; the host caps tailBytes at 64 KiB. */
    async peekEvalCell(cellId, tailBytes) {
        return this.getData(await this.send({ type: "eval_cells.peek", cellId, ...(tailBytes === undefined ? {} : { tailBytes }) }));
    }
    /** Stop a session-owned cell and return its confirmed terminal snapshot. */
    async stopEvalCell(cellId) {
        return this.getData(await this.send({ type: "eval_cells.stop", cellId }));
    }
    /** List safe metadata for the named provider's configured account slots. */
    async getProviderAccounts(provider) {
        const response = await this.send({ type: "get_provider_accounts", provider });
        return this.getData(response).accounts;
    }
    /**
     * Re-run the sign-in connection test on one Claude subscription account and return the stored `check`. Hosts
     * advertising `provider_account_test` answer it; other providers fail with `unsupported_provider`.
     */
    async testProviderAccount(provider, name) {
        const response = await this.send({ type: "test_provider_account", provider, name });
        return this.getData(response).check;
    }
    /** Pin a provider account for future session-affine requests, or clear the pin. */
    async pinProviderAccount(provider, name) {
        await this.send({ type: "account_pin", provider, name });
    }
    /** Set the order the provider's accounts are tried in after a pin, or clear it with null. */
    async orderProviderAccounts(provider, names) {
        await this.send({ type: "account_order", provider, names });
    }
    /**
     * Remove a persisted provider account slot. Environment slots are read-only. `notice` is set when the account was
     * removed but something could not be cleaned up (a Claude CLI sign-out that could not run, a malformed slot).
     */
    async removeProviderAccount(provider, name) {
        const data = this.getData(await this.send({ type: "account_remove", provider, name }));
        return data === undefined ? {} : { notice: data.notice };
    }
    /** Reset one account's local health on a host advertising `account_reset`; rejects with RpcCommandError on failure. */
    async resetProviderAccount(provider, name) {
        this.getData(await this.send({ type: "account_reset", provider, name }));
    }
    // =========================================================================
    // Helpers
    // =========================================================================
    /**
     * Wait for agent to become idle (no streaming).
     * Resolves on agent_idle: agent_settled can arrive while extension agent_settled handlers still run (omo#11419).
     */
    waitForIdle(timeout = 60000) {
        return new Promise((resolve, reject) => {
            const timer = setTimeout(() => {
                unsubscribe();
                reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));
            }, timeout);
            const unsubscribe = this.onEvent((event) => {
                if (event.type === "agent_idle") {
                    clearTimeout(timer);
                    unsubscribe();
                    resolve();
                }
            });
        });
    }
    /**
     * Collect events until agent becomes idle.
     */
    collectEvents(timeout = 60000) {
        return new Promise((resolve, reject) => {
            const events = [];
            const timer = setTimeout(() => {
                unsubscribe();
                reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));
            }, timeout);
            const unsubscribe = this.onEvent((event) => {
                if (isProviderAccountEvent(event) ||
                    event.type === "extension_event" ||
                    event.type === "bash_start" ||
                    event.type === "bash_end" ||
                    event.type === "extension_ui_request" ||
                    event.type === "secret_input_settled" ||
                    // Connection-level, not part of the agent's event stream.
                    event.type === "session_replaced" ||
                    event.type === "session_parked" ||
                    event.type === "session_released" ||
                    event.type === "session_archived_changed" ||
                    event.type === "session_settled_changed" ||
                    event.type === "queued" ||
                    event.type === "socket_closing" ||
                    event.type === "message_tool_arguments_reset")
                    return;
                events.push(event);
                if (event.type === "agent_idle") {
                    clearTimeout(timer);
                    unsubscribe();
                    resolve(events);
                }
            });
        });
    }
    /**
     * Send prompt and wait for completion, returning all events.
     */
    async promptAndWait(message, images, timeout = 60000) {
        const eventsPromise = this.collectEvents(timeout);
        await this.prompt(message, images ? { images } : undefined);
        return eventsPromise;
    }
    // =========================================================================
    // Internal
    // =========================================================================
    handleLine(line) {
        try {
            const data = JSON.parse(line);
            if (handleRpcReply(data, this.pendingRequests, this.admissions, this.unawaitedReplies))
                return;
            this.admissions.receive(data);
            if (data.type === "queued" && typeof data.for_request === "string")
                this.pendingRequests.get(data.for_request)?.onQueued?.(data.position);
            // Otherwise it's an event. During open_session, retain tagged events until
            // the response establishes the lease so startup hooks are not lost.
            if (typeof data.sessionId === "string" && data.sessionId !== this.sessionId) {
                if (this.pendingOpenSession) {
                    const bytes = Buffer.byteLength(line);
                    this.pendingSessionEvents.push({ sessionId: data.sessionId, event: data, bytes });
                    this.pendingSessionEventBytes += bytes;
                    while (this.pendingSessionEvents.length > MAX_PENDING_SESSION_EVENTS ||
                        this.pendingSessionEventBytes > MAX_PENDING_SESSION_EVENT_BYTES) {
                        const oldest = this.pendingSessionEvents.shift();
                        if (!oldest)
                            break;
                        this.pendingSessionEventBytes -= oldest.bytes;
                    }
                }
                return;
            }
            // Iterate a snapshot so listeners that unsubscribe during dispatch
            // do not cause later listeners to miss this event.
            for (const listener of [...this.eventListeners]) {
                listener(data);
            }
        }
        catch {
            // Ignore non-JSON lines
        }
    }
    flushPendingSessionEvents() {
        const pending = this.pendingSessionEvents;
        this.pendingSessionEvents = [];
        this.pendingSessionEventBytes = 0;
        for (const { sessionId, event } of pending) {
            if (sessionId !== this.sessionId)
                continue;
            for (const listener of [...this.eventListeners])
                listener(event);
        }
    }
    createProcessExitError(code, signal) {
        return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);
    }
    notifyDisconnect(error) {
        this.admissions.clear();
        this.rejectPendingRequests(error);
        if (!this.disconnectNotified && !this.stopping) {
            this.disconnectNotified = true;
            this.options.onDisconnect?.(error);
        }
    }
    rejectPendingRequests(error) {
        for (const pending of this.pendingRequests.values()) {
            pending.onReject?.(error);
            pending.reject(error);
        }
        this.pendingRequests.clear();
    }
    async send(command, route = true, hooks, expectResponse = true) {
        const childProcess = this.process;
        const stream = this.socket ?? childProcess?.stdin;
        if (!stream) {
            throw new RpcTransportGoneError();
        }
        if (this.exitError) {
            throw this.exitError;
        }
        if (childProcess?.exitCode !== null && childProcess?.exitCode !== undefined) {
            const error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);
            this.exitError = error;
            throw error;
        }
        if (stream.destroyed || !stream.writable) {
            const error = new RpcTransportGoneError();
            this.notifyDisconnect(error);
            throw error;
        }
        // Extension-UI replies and progress carry the host's request id; never mint one.
        const ownId = command.type === "extension_ui_response" || command.type === "extension_ui_progress" ? command.id : undefined;
        const id = ownId ?? `req_${++this.requestId}`;
        const fullCommand = {
            ...command,
            ...(route && this.sessionId && !("sessionId" in command) ? { sessionId: this.sessionId } : {}),
            ...(ownId === undefined ? { id } : {}),
            ...(this.socket && this.originHost ? { [ORIGIN_HOST_INSTANCE_FIELD]: this.originHost } : {}),
        };
        if (!expectResponse) {
            this.unawaitedReplies.note(id);
            stream.write(serializeJsonLine(fullCommand));
            return Promise.resolve({ type: "response", command: command.type, success: true });
        }
        const sessionId = "sessionId" in fullCommand ? fullCommand.sessionId : undefined;
        return new Promise((resolve, reject) => {
            const timeoutMessage = () => `Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`;
            let promptCap;
            let promptReceived = false;
            const expire = (timeoutError) => {
                clearTimeout(promptCap);
                const pending = this.pendingRequests.get(id);
                this.pendingRequests.delete(id);
                pending?.onReject?.(timeoutError);
                reject(timeoutError);
            };
            const deadline = armRequestDeadline(command.type === "prompt" && sessionId === this.sessionId && this.isCompacting()
                ? PROMPT_COMPACTION_DEADLINE_MS
                : requestDeadlineMs(command), timeoutMessage, expire);
            // Compaction events extend a prompt's wait, but never past this cap from when it was sent.
            if (command.type === "prompt") {
                promptCap = setTimeout(() => {
                    deadline.clear();
                    expire(new RpcRequestTimeoutError(timeoutMessage()));
                }, PROMPT_ACK_MAX_WAIT_MS);
            }
            this.pendingRequests.set(id, {
                sessionId,
                resolve: (response) => {
                    deadline.clear();
                    clearTimeout(promptCap);
                    resolve(response);
                },
                reject: (error) => {
                    deadline.clear();
                    clearTimeout(promptCap);
                    reject(error);
                },
                ...(command.type === "prompt"
                    ? {
                        onCompaction: (compacting) => compacting
                            ? deadline.extend(PROMPT_COMPACTION_DEADLINE_MS, timeoutMessage)
                            : promptReceived
                                ? deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS, promptStalledMessage)
                                : deadline.extend(REQUEST_DEADLINE_MS, timeoutMessage),
                        // The host received the prompt: its preflight may outlive the plain request deadline (senpi#2871).
                        // A compaction's own wait is longer: the acknowledgement must never shorten it.
                        onQueued: () => {
                            promptReceived = true;
                            if (!this.isCompacting())
                                deadline.extend(PROMPT_AFTER_QUEUED_DEADLINE_MS, promptStalledMessage);
                        },
                    }
                    : {}),
                ...(command.type === "open_session"
                    ? {
                        onQueued: (position) => deadline.extend(OPEN_AFTER_QUEUED_DEADLINE_MS, () => openStalledMessage(position)),
                    }
                    : {}),
                ...(hooks?.onResponse ? { onResponse: hooks.onResponse } : {}),
                ...(hooks?.onReject ? { onReject: hooks.onReject } : {}),
            });
            try {
                stream.write(serializeJsonLine(fullCommand));
            }
            catch (error) {
                const writeError = error instanceof Error ? error : new Error(String(error));
                const pending = this.pendingRequests.get(id);
                this.pendingRequests.delete(id);
                pending?.onReject?.(writeError);
                pending?.reject(writeError);
            }
        });
    }
    getData(response) {
        if (!response.success) {
            const errorResponse = response;
            if (errorResponse.errorCode === "missing_session_cwd" && errorResponse.errorData) {
                throw new MissingSessionCwdError(errorResponse.errorData);
            }
            throw new RpcCommandError(errorResponse.error, errorResponse.errorCode, errorResponse.errorData);
        }
        // Type assertion: we trust response.data matches T based on the command sent.
        // This is safe because each public method specifies the correct T for its command.
        const successResponse = response;
        return successResponse.data;
    }
}
//# sourceMappingURL=rpc-client.js.map