@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
623 lines • 26 kB
TypeScript
/**
* RPC Client for programmatic access to the coding agent.
*
* Spawns the agent in RPC mode and provides a typed API for all operations.
*/
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { ImageContent } from "@earendil-works/pi-ai";
import type { PromptDisposition, QueuedInputDisposition, SessionStats } from "../../core/agent-session.ts";
import type { SessionRetryFallbackProfile } from "../../core/agent-session-runtime.ts";
import type { BashResult } from "../../core/bash-executor.ts";
import { type ClientMessageIdentity } from "../../core/client-message-identity.ts";
import type { CompactionResult } from "../../core/compaction/index.ts";
import type { ServiceTier } from "../../core/extensions/builtin/service-tier.ts";
import type { ResolvedMessagePath } from "../../core/message-path-resolution.ts";
import { RpcClientAdmissions, type CompactOpenResult, type LegacyOpenResult, type RpcOpenOptions } from "./rpc-client-admissions.ts";
export { RpcCommandError } from "./rpc-command-error.ts";
export type { RpcClientEvent, RpcEventListener, RpcProviderAccountEvent } from "./rpc-client-events.ts";
import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts";
import type { ThreadSettledBy } from "../../core/session-settled.ts";
import type { ThinkingLevelSource } from "../../core/session-thinking-memory.ts";
import type { JsonAgentSessionEvent } from "../json-event.ts";
import { type RpcEventListener } from "./rpc-client-events.ts";
import type { EditAssistantMessageResult, EditUserMessageResult, RpcCommand, RpcEvalCell, RpcEvalCellSnapshot, RpcExtensionUIProgress, RpcExtensionUIResponse, RpcProviderAccount, RpcResponse, RpcSessionModelEntry, RpcSessionState, RpcSlashCommand, RpcUnloadAnswer } from "./rpc-types.ts";
export interface RpcClientOptions {
/** Connect to an existing multi-session Unix socket instead of spawning a child. */
socketPath?: string;
/** Endpoint credential lookup only; does not change the client's configuration profile. */
keyRoot?: string;
/** Called once when an established transport disconnects. */
onDisconnect?: (error: RpcTransportGoneError) => void;
/** Path to the CLI entry point (default: searches for dist/cli.js) */
cliPath?: string;
/** Working directory for the agent */
cwd?: string;
/** Environment variables */
env?: Record<string, string>;
/** Provider to use */
provider?: string;
/** Model ID to use */
model?: string;
/** Additional CLI arguments */
args?: string[];
}
export interface ModelInfo {
provider: string;
id: string;
contextWindow: number;
reasoning: boolean;
supportedThinkingLevels?: ThinkingLevel[];
}
type PromptOptions = ClientMessageIdentity & {
images?: ImageContent[];
streamingBehavior?: "steer" | "followUp";
thinkingLevel?: ThinkingLevel;
promptDisposition?: (disposition: PromptDisposition) => void;
preflightResult?: (success: boolean) => void;
sessionTitlePrompt?: string | false;
expandPromptTemplates?: boolean;
unknownCommandAsText?: boolean;
};
export declare class RpcTransportGoneError extends Error {
readonly code: "rpc_transport_gone";
constructor(message?: string);
}
export declare function isTransportGoneError(error: unknown): error is RpcTransportGoneError;
/** The options of a typed `abort` (see `docs/rpc.md`, `abort`). */
export type RpcAbortOptions = Omit<Extract<RpcCommand, {
type: "abort";
}>, "type" | "id" | "sessionId">;
/** The host's answer to a typed `abort`; an older host answers with no data. */
export type RpcAbortAnswer = Extract<RpcResponse, {
command: "abort";
success: true;
}>["data"];
/** `get_effect_status`: the receipt, or proof the whole transcript holds none. */
export type RpcEffectStatusAnswer = Extract<RpcResponse, {
command: "get_effect_status";
success: true;
}>["data"];
/** `get_pending_inputs`: pending inputs in durable custody, and an outcome for each known id. */
export type RpcPendingInputsAnswer = Extract<RpcResponse, {
command: "get_pending_inputs";
success: true;
}>["data"];
export declare class RpcClientOpenInFlightError extends Error {
readonly code: "open_session_in_flight";
constructor();
}
export declare class RpcClient {
readonly admissions: RpcClientAdmissions;
private process;
private socket;
private stopReadingStdout;
private eventListeners;
/** Replies to records this client sent without waiting (senpi#5761), consumed quietly. */
private readonly unawaitedReplies;
private pendingRequests;
private requestId;
private sessionId;
/**
* 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.
*/
private readonly compactions;
private pendingOpenSession;
private pendingSessionEvents;
private pendingSessionEventBytes;
private stderr;
private exitError;
private disconnectNotified;
private stopping;
private options;
/** The host generation this client runs inside, named on every socket request (#3272). */
private readonly originHost;
constructor(options?: RpcClientOptions);
/**
* Start the RPC agent process.
*/
start(): Promise<void>;
/**
* 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.
*/
private isCompacting;
/**
* Stop the RPC agent process.
*/
stop(): Promise<void>;
private startSocket;
/**
* Subscribe to agent events.
*/
onEvent(listener: RpcEventListener): () => void;
/**
* Get collected stderr output (useful for debugging).
*/
getStderr(): string;
setClientInfo(width: number, capabilities?: string[]): Promise<void>;
openSession(options: RpcOpenOptions & {
admissionId: string;
}): Promise<CompactOpenResult>;
openSession(options: RpcOpenOptions & {
admissionId?: undefined;
}): Promise<LegacyOpenResult>;
openSession(options: RpcOpenOptions): Promise<LegacyOpenResult | CompactOpenResult>;
sendExtensionUIResponse(response: RpcExtensionUIResponse): Promise<void>;
resumeSession(): Promise<void>;
/**
* 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.
*/
pauseForRun(command: Omit<Extract<RpcCommand, {
type: "pause_for_run";
}>, "type" | "id">): Promise<{
held: true;
childSeq: number;
}>;
resumeForRun(command: Omit<Extract<RpcCommand, {
type: "resume_for_run";
}>, "type" | "id">): Promise<{
released: boolean;
reason?: "stale" | "not_held";
otherHoldLive?: boolean;
turnId?: string;
}>;
/** Human input held for a paused session; from a task parent it names the parent session that paused the child. */
holdInput(command: Omit<Extract<RpcCommand, {
type: "hold_input";
}>, "type" | "id">): Promise<{
entryId?: string;
duplicate?: boolean;
alreadyDelivered?: boolean;
}>;
/** Draft update for an open `question` request; fire-and-forget like the response. */
sendExtensionUIProgress(progress: RpcExtensionUIProgress): Promise<void>;
/** `unload_session`: a refusal is an answer (`outcome: "refused"` with reason and action), not a throw. */
unloadSession(options: Omit<Extract<RpcCommand, {
type: "unload_session";
}>, "type" | "id" | "sessionId"> & {
readonly sessionId?: string;
}): Promise<RpcUnloadAnswer>;
/**
* 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.
*/
setSessionContext(patch: Record<string, string | number | boolean | null>, sessionId?: string | undefined): Promise<void>;
closeSession(sessionId?: string | undefined): Promise<void>;
/**
* 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`).
*/
detachConnection(): Promise<{
readonly deferred: readonly string[];
} | "unsupported">;
listSessions(options?: {
observe?: boolean;
include_workers?: boolean;
}): Promise<Array<{
sessionId: string;
durableSessionId?: string;
sessionPath?: string;
cwd: string;
name?: string;
status: "opening" | "open" | "closing" | "closed";
/** Live client attachments; absent from hosts older than the `retain_on_disconnect` capability. */
attachments?: number;
}>>;
/**
* Send a prompt to the agent.
* Returns the prompt's disposition after acceptance; use onEvent() to receive streaming events.
* If the disposition is "handled", no run started for this prompt, so don't wait for agent_settled.
*
* The disposition/preflight callbacks mirror AgentSession's local prompt contract:
* they fire synchronously while the response frame is dispatched — before any
* queued message_start event — so optimistic-echo eligibility is settled in wire
* order. A success response without a disposition (older host) maps to "handled"
* so the echo degrades to canonical-only rendering instead of double-rendering.
*/
prompt(message: string, images?: ImageContent[]): Promise<PromptDisposition>;
prompt(message: string, options?: PromptOptions): Promise<PromptDisposition>;
appendUserMessage(content: unknown): Promise<void>;
appendSessionEntry(entry: import("../../core/session-manager.ts").SessionEntry): Promise<void>;
sendCustomMessage<T = unknown>(message: {
customType: string;
content: unknown;
display: boolean;
details?: T;
}, options?: {
triggerTurn?: boolean;
deliverAs?: "steer" | "followUp" | "nextTurn";
}): Promise<void>;
/**
* 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`.
*/
continueFromLeaf(): Promise<void>;
/**
* Queue a steering message to interrupt the agent mid-run.
*/
steer(message: string, images?: ImageContent[], recovery?: ClientMessageIdentity & {
enqueueOrder?: number;
}): Promise<QueuedInputDisposition>;
/**
* Queue a follow-up message to be processed after the agent finishes.
*/
followUp(message: string, images?: ImageContent[], recovery?: ClientMessageIdentity & {
enqueueOrder?: number;
}): Promise<QueuedInputDisposition>;
/**
* Abort current operation. With no options this is the fire-and-forget abort it always was (transport
* loss resolves). With options it is the typed abort: `effectId` records a receipt, `awaitIdle` answers
* once the turn stopped (or `graceMs` passed), `clearQueue` drains queued input first; the host's
* answer (`effectId`, `state`, `effect`, `stopped`, `idle`, `cleared`) is returned.
*/
abort(): Promise<void>;
abort(options: RpcAbortOptions): Promise<RpcAbortAnswer>;
abort(options?: RpcAbortOptions): Promise<RpcAbortAnswer | undefined>;
/**
* 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.
*/
getEffectStatus(effectId: string, options?: {
readonly sessionPath?: string;
}): Promise<RpcEffectStatusAnswer>;
/**
* The pending inputs in durable custody (queued, sending, failed) and an explicit outcome for each id in
* `knownClientMessageIds` (at most 64), consistent through `throughCursor`.
*/
getPendingInputs(knownClientMessageIds?: readonly string[]): Promise<RpcPendingInputsAnswer>;
/** Abort with host refusals and transport loss surfaced to machine callers. */
abortStrict(): Promise<void>;
abortCompaction(): Promise<void>;
reload(): Promise<{
cancelled: boolean;
reason?: string;
}>;
checkReloadVeto(): Promise<{
cancelled: boolean;
reason?: string;
}>;
/**
* Clear queued steering and follow-up messages, returning their text.
*/
clearQueue(options?: {
abortWillFollow?: boolean;
}): Promise<{
steering: string[];
followUp: string[];
ordered: Array<{
text: string;
mode: "steer" | "followUp";
enqueueOrder: number;
revision: number;
}>;
}>;
getSteeringMessages(): Promise<string[]>;
getFollowUpMessages(): Promise<string[]>;
abortBranchSummary(): Promise<void>;
recordBashResult(command: string, result: BashResult, excludeFromContext?: boolean): Promise<void>;
setLabel(entryId: string, label?: string): Promise<void>;
/**
* 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
*/
newSession(parentSession?: string): Promise<{
cancelled: boolean;
}>;
/**
* Get current session state.
*/
getState(): Promise<RpcSessionState>;
/**
* Set model by provider and ID.
*/
setModel(provider: string, modelId: string): Promise<{
provider: string;
id: string;
systemPromptName?: string;
}>;
/**
* Cycle to next model.
*/
setFavoriteModels(models: RpcSessionModelEntry[]): Promise<void>;
setScopedModels(models: RpcSessionModelEntry[]): Promise<void>;
cycleModel(direction?: "forward" | "backward"): Promise<{
model: {
provider: string;
id: string;
};
thinkingLevel: ThinkingLevel;
isScoped: boolean;
} | null>;
/**
* Get list of available models.
*/
getAvailableModels(): Promise<ModelInfo[]>;
/**
* 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.
*/
setThinkingLevel(level: ThinkingLevel, options?: {
scope?: "turn";
}): Promise<void>;
/**
* Cycle thinking level.
*/
cycleThinkingLevel(): Promise<{
level: ThinkingLevel;
} | null>;
/**
* Get list of available thinking levels for the current model.
*/
getAvailableThinkingLevels(): Promise<ThinkingLevel[]>;
/**
* 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.
*/
getModelThinkingLevel(provider: string, modelId: string): Promise<{
level: ThinkingLevel;
source: ThinkingLevelSource;
availableLevels: ThinkingLevel[];
}>;
/**
* 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.
*/
setFastMode(enabled: boolean): Promise<{
enabled: boolean;
serviceTier: ServiceTier;
provider: string;
modelId: string;
}>;
/** Current fast-mode state and the service tier requests would carry. */
getFastMode(): Promise<{
enabled: boolean;
serviceTier: ServiceTier | null;
}>;
/**
* Set steering mode.
*/
setSteeringMode(mode: "all" | "one-at-a-time"): Promise<void>;
/**
* Set follow-up mode.
*/
setFollowUpMode(mode: "all" | "one-at-a-time"): Promise<void>;
/**
* Compact session context.
*/
compact(customInstructions?: string): Promise<CompactionResult>;
/**
* Set auto-compaction enabled/disabled.
*/
setAutoCompaction(enabled: boolean): Promise<void>;
/**
* Set auto-retry enabled/disabled.
*/
setAutoRetry(enabled: boolean): Promise<void>;
/**
* Abort in-progress retry.
*/
abortRetry(): Promise<void>;
/**
* Give this single-session process its fallback chain before the first turn (`set_retry_fallback`).
* Requires the `retry_fallback_command` capability.
*/
setRetryFallback(retryFallback: SessionRetryFallbackProfile): Promise<void>;
/**
* Execute a bash command.
*/
bash(command: string, options?: {
excludeFromContext?: boolean;
executionId?: string;
operations?: Record<string, unknown>;
}): Promise<BashResult>;
navigateTree(targetId: string, options?: {
intent?: "select" | "resume";
summarize?: boolean;
customInstructions?: string;
replaceInstructions?: boolean;
label?: string;
expectedLeafId?: string;
}): Promise<{
cancelled: boolean;
leafId: string | null;
editorText?: string;
aborted?: boolean;
summaryEntry?: unknown;
}>;
/**
* Abort running bash command.
*/
abortBash(): Promise<void>;
cleanupBashOutput(path: string): Promise<void>;
/**
* Get session statistics.
*/
getSessionStats(): Promise<SessionStats>;
/** Which file a message's path means, by the engine's one rule (senpi#3415). */
resolvePath(path: string): Promise<ResolvedMessagePath>;
/**
* Export session to HTML.
*/
exportHtml(outputPath?: string, themeName?: string): Promise<{
path: string;
}>;
exportJsonl(outputPath?: string): Promise<{
path: string;
}>;
/**
* Switch to a different session file.
* @returns Object with `cancelled: true` if an extension cancelled the switch
*/
switchSession(sessionPath: string, options?: {
cwdOverride?: string;
}): Promise<{
cancelled: boolean;
}>;
/**
* Fork from a specific message.
* @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)
*/
fork(entryId: string, options?: {
position?: "before" | "at";
}): Promise<{
text: string;
cancelled: boolean;
}>;
/**
* Clone the current active branch into a new session.
* @returns Object with `cancelled: true` if an extension cancelled the clone
*/
clone(): Promise<{
cancelled: boolean;
}>;
/**
* Get messages available for forking.
*/
getForkMessages(): Promise<Array<{
entryId: string;
text: string;
}>>;
/**
* 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`.
*/
getEntries(since?: string, page?: {
readonly limit?: number;
readonly maxBytes?: number;
}): Promise<{
entries: SessionEntry[];
leafId: string | null;
hasMore?: boolean;
nextSince?: string;
}>;
/**
* Get the session entry tree.
*/
getTree(): Promise<{
tree: SessionTreeNode[];
leafId: string | null;
}>;
/**
* 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`.
*/
editAssistantMessage(entryId: string, text: string, options?: {
expectedLeafId?: string;
summarize?: boolean;
customInstructions?: string;
}): Promise<EditAssistantMessageResult>;
/**
* 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.
*/
editUserMessage(entryId: string, text: string, options?: {
expectedLeafId?: string;
summarize?: boolean;
customInstructions?: string;
}): Promise<EditUserMessageResult>;
/**
* Get text of last assistant message.
*/
getLastAssistantText(): Promise<string | null>;
/**
* Set the session display name.
*/
setSessionName(name: string): Promise<void>;
/**
* Archive or unarchive the session; the flag is stored in its session file.
*/
setSessionArchived(archived: boolean): Promise<void>;
/**
* Mark the session Done or reopen it; the flag and how it was reached (`by`) are stored in its session file.
*/
setSessionSettled(settled: boolean, by?: ThreadSettledBy): Promise<void>;
/**
* Report that the user started typing a draft, so a first-activity prompt-cache prewarm can run (senpi#3859).
*/
recordDraftActivity(): Promise<void>;
importJsonl(inputPath: string, cwdOverride?: string): Promise<{
cancelled: boolean;
}>;
/**
* Get all messages in the session.
*/
getMessages(): Promise<AgentMessage[]>;
/**
* 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.
*/
getMedia(toolCallId: string, contentIndex: number): Promise<ImageContent>;
/**
* Get available commands (extension commands, prompt templates, skills).
*/
getCommands(): Promise<RpcSlashCommand[]>;
/** Invoke one extension-owned RPC request handler and return its structured result. */
requestExtension<T = unknown>(name: string, data?: unknown): Promise<T>;
/** Read live and recently settled eval cells without a model tool call. */
listEvalCells(): Promise<RpcEvalCell[]>;
/** Read a bounded UTF-8 output tail; the host caps tailBytes at 64 KiB. */
peekEvalCell(cellId: string, tailBytes?: number): Promise<RpcEvalCellSnapshot>;
/** Stop a session-owned cell and return its confirmed terminal snapshot. */
stopEvalCell(cellId: string): Promise<RpcEvalCellSnapshot>;
/** List safe metadata for the named provider's configured account slots. */
getProviderAccounts(provider: string): Promise<RpcProviderAccount[]>;
/**
* 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`.
*/
testProviderAccount(provider: string, name: string): Promise<NonNullable<RpcProviderAccount["check"]>>;
/** Pin a provider account for future session-affine requests, or clear the pin. */
pinProviderAccount(provider: string, name: string | null): Promise<void>;
/** Set the order the provider's accounts are tried in after a pin, or clear it with null. */
orderProviderAccounts(provider: string, names: string[] | null): Promise<void>;
/**
* 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).
*/
removeProviderAccount(provider: string, name: string): Promise<{
notice?: string;
}>;
/** Reset one account's local health on a host advertising `account_reset`; rejects with RpcCommandError on failure. */
resetProviderAccount(provider: string, name: string): Promise<void>;
/**
* 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?: number): Promise<void>;
/**
* Collect events until agent becomes idle.
*/
collectEvents(timeout?: number): Promise<JsonAgentSessionEvent[]>;
/**
* Send prompt and wait for completion, returning all events.
*/
promptAndWait(message: string, images?: ImageContent[], timeout?: number): Promise<JsonAgentSessionEvent[]>;
private handleLine;
private flushPendingSessionEvents;
private createProcessExitError;
private notifyDisconnect;
private rejectPendingRequests;
private send;
private getData;
}
//# sourceMappingURL=rpc-client.d.ts.map