@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
865 lines • 44.3 kB
TypeScript
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage, ImageContent, Message, SystemMessage, TextContent, ThinkingSelection, ToolResultMessage, Usage, UserMessage } from "@earendil-works/pi-ai";
import { EventLoopSlicer } from "./event-loop-slicer.ts";
import type { InputSource } from "./extensions/types.ts";
import type { RecoveryCarrier } from "./session-recovery-identity.ts";
import type { ModelChangeOrigin, ModelChangeSource } from "./model-change-origin.ts";
import type { RepositoryIdentity } from "./repository-identity.ts";
import { type SessionListProgress } from "./session-discovery.ts";
import { loadEntriesFromFile } from "./session-entry-file.ts";
import { type SessionSettled } from "./session-settled.ts";
import { type HistoryReducer } from "./session-history-reduce.ts";
import type { SpawnedBy } from "./session-lifecycle-types.ts";
import { type TranscriptTransition } from "./session-transcript-journal.ts";
import type { SessionOwnership } from "./session-move/ownership.ts";
import { type ResidentStoreStats, ResidentStringStore } from "./session-resident-store.ts";
import { type DurableStoreBinding, type ProjectionWarning } from "./session-store/durable-binding.ts";
import { type SessionRecovery } from "./session-write-recovery.ts";
export type { SessionListProgress } from "./session-discovery.ts";
export { loadEntriesFromFile, loadEntriesFromFileAsync } from "./session-entry-file.ts";
export type { SessionRecovery, SessionRecoveryCause } from "./session-write-recovery.ts";
import { type BashExecutionMessage, type CustomMessage } from "./messages.ts";
/** Request-local field carried across context hooks; never persisted or sent to providers. */
export declare const SESSION_CONTEXT_ENTRY_ID = "__piSessionContextEntryId";
/** Entry identity for a transient message projected from session history. */
export declare function getSessionContextEntryId(message: AgentMessage): string | undefined;
/**
* Copy a message's context entry identity onto a derived message object. Context
* pipeline stages that spread messages call this so checkpoint provenance (the
* openai-remote replay boundary) survives both the cloned and the shared-transcript
* context-hook paths. The derived object gets the id both in the WeakMap (matching
* originals) and as the own enumerable property it would have carried via spread on
* the clone path — the source is only read, never written (senpi#2525).
*/
export declare function inheritSessionContextEntryId<T extends AgentMessage>(derived: T, source: AgentMessage): T;
export interface UsageTotals {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
/** Some summed turn had no known price, so `cost` is a lower bound (senpi#3844). */
costUnknown?: true;
latestCacheHitRate: number | undefined;
}
export declare const CURRENT_SESSION_VERSION = 3;
export interface SessionHeader {
type: "session";
version?: number;
id: string;
timestamp: string;
cwd: string;
parentSession?: string;
/** Execution ancestry, unlike parentSession's transcript/fork provenance. */
spawnedBy?: SpawnedBy;
}
export interface NewSessionOptions {
id?: string;
parentSession?: string;
spawnedBy?: SpawnedBy;
}
export interface SessionEntryBase {
type: string;
id: string;
parentId: string | null;
timestamp: string;
}
export interface SessionMessageEntry extends SessionEntryBase {
type: "message";
message: AgentMessage;
/**
* Where a user message came from: the `source` its `input` event reported. Stored on the entry, never on
* the message, so it stays in the session record and out of provider requests. Absent on every other
* entry and on user input that ran no `input` event (restored, moved or edited input): unknown origin.
*/
inputSource?: InputSource;
}
export interface ThinkingLevelChangeEntry extends SessionEntryBase {
type: "thinking_level_change";
thinkingLevel: string;
/** Explicit selector provenance. Omitted by legacy entries and SDK-defaulted fallbacks. */
thinkingSelection?: ThinkingSelection;
/** Source of a model switch or explicit thinking-level request, including RPC requests without an effectId. */
triggerSource?: ModelChangeSource;
triggerActor?: string;
/** The RPC model or thinking-level effect that applied this value. */
effectId?: string;
/** Model the level applied to (senpi#3819); absent on older entries. Feeds the per-session per-model map. */
provider?: string;
modelId?: string;
}
export interface ConfigurationUpdateEntry extends SessionEntryBase {
type: "configuration_update";
reasoning: {
effort: string;
};
}
export interface ModelChangeEntry extends SessionEntryBase {
type: "model_change";
provider: string;
modelId: string;
/** Transient fallback changes are excluded from restored session defaults. */
reason?: "fallback" | "fallback-revert";
/** The model active before a fallback window, retained for restart restoration. */
originalProvider?: string;
originalModelId?: string;
/** What made the switch (senpi#2870); omitted by entries written before it was recorded. */
source?: ModelChangeSource;
/** Who issued it, where known: an extension path, an RPC client, the picker used. */
actor?: string;
/** The switch landed while a turn was streaming. */
duringTurn?: boolean;
/** The RPC `effectId` that asked for the switch, so a reopen can tell the receipt was applied. */
effectId?: string;
}
/**
* A model switch the session refused. Recorded because the refusal happens
* before any `model_change` is appended, which left an attempted-and-rejected
* switch indistinguishable from one the user never made (#1526).
*
* Durability follows the shared session-file contract, it is not special-cased:
* `_persist` buffers every entry until the branch holds a user or assistant
* message (#10000), so a refusal recorded before the session's first message
* reaches the JSONL only when that message flushes the buffer. A session that
* never gets one keeps the record in memory for its lifetime and never writes a file.
*/
export interface ModelChangeRejectedEntry extends SessionEntryBase {
type: "model_change_rejected";
provider: string;
modelId: string;
reason: "context-budget" | "auth";
/**
* The guard's own explanation, including its remedy. Named `detail` rather
* than `message` so this entry stays structurally distinct from
* `SessionMessageEntry`, whose `message` is an object.
*/
detail: string;
/** Budget numbers; present only for the context-budget reason. */
contextWindow?: number;
liveContextTokens?: number;
requiredTokens?: number;
shortfallTokens?: number;
safetyMarginProfile?: string;
}
export interface UsageEntry extends SessionEntryBase {
type: "usage";
/** Arbitrary usage category, such as "cache_warm". */
kind: string;
provider: string;
model: string;
usage: Usage;
/** Optional human-readable qualifier for usage notices. */
note?: string;
}
export interface CompactionEntry<T = unknown> extends SessionEntryBase {
type: "compaction";
summary: string;
firstKeptEntryId: string;
tokensBefore: number;
/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
details?: T;
/** Usage from the LLM call(s) that generated this summary, if available */
usage?: Usage;
/** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
fromHook?: boolean;
/** Complete prompt and tool state at this compaction boundary. */
systemMessage?: SystemMessage;
}
export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
type: "branch_summary";
fromId: string;
summary: string;
/** Extension-specific data (not sent to LLM) */
details?: T;
/** Usage from the LLM call that generated this summary, if available */
usage?: Usage;
/** True if generated by an extension, false if pi-generated */
fromHook?: boolean;
}
/**
* Custom entry for extensions to store extension-specific data in the session.
* Use customType to identify your extension's entries.
*
* Purpose: Persist extension state across session reloads. On reload, extensions can
* scan entries for their customType and reconstruct internal state.
*
* Does NOT participate in LLM context (ignored by buildSessionContext).
* For injecting content into context, see CustomMessageEntry.
*/
export interface CustomEntry<T = unknown> extends SessionEntryBase {
type: "custom";
customType: string;
data?: T;
/** Written at session start without user action; see `AppendEntryOptions.startupBookkeeping` (senpi#3263). */
startupBookkeeping?: true;
}
/** Label entry for user-defined bookmarks/markers on entries. */
export interface LabelEntry extends SessionEntryBase {
type: "label";
targetId: string;
label: string | undefined;
}
/** Session metadata entry (e.g., user-defined display name). */
export interface SessionInfoEntry extends SessionEntryBase {
type: "session_info";
name?: string;
}
/**
* Custom message entry for extensions to inject messages into LLM context.
* Use customType to identify your extension's entries.
*
* Unlike CustomEntry, this DOES participate in LLM context.
* The content is converted to a user message in buildSessionContext().
* Use details for extension-specific metadata (not sent to LLM).
*
* display controls TUI rendering:
* - false: hidden entirely
* - true: rendered with distinct styling (different from user messages)
*/
export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
type: "custom_message";
customType: string;
content: string | (TextContent | ImageContent)[];
details?: T;
display: boolean;
}
/** Content that an append-only context edit may replace without changing message metadata. */
export type ContextEditableContent = UserMessage["content"] | AssistantMessage["content"] | ToolResultMessage["content"] | CustomMessage["content"];
/** Append-only change to one earlier entry's contribution to model context. */
export interface ContextEditEntry extends SessionEntryBase {
type: "context_edit";
targetId: string;
/** Null omits the target from model context. A value replaces only its content. */
replacement: {
content: ContextEditableContent;
} | null;
}
/** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
export type SessionEntry = SessionMessageEntry | ThinkingLevelChangeEntry | ConfigurationUpdateEntry | ModelChangeEntry | ModelChangeRejectedEntry | UsageEntry | CompactionEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | ContextEditEntry | LabelEntry | SessionInfoEntry;
/** Raw file entry (includes header) */
export type FileEntry = SessionHeader | SessionEntry;
/** Tree node for getTree() - defensive copy of session structure */
export interface SessionTreeNode {
entry: SessionEntry;
children: SessionTreeNode[];
/** Resolved label for this entry, if any */
label?: string;
/** Timestamp of the latest label change for this entry, if any */
labelTimestamp?: string;
}
export interface ProjectedSessionEntry {
/** Raw append-only entry that owns this projected contribution. */
sourceEntry: SessionEntry;
/** Model-visible messages after context edits. Empty for state-only entries and omissions. */
messages: AgentMessage[];
}
export interface SessionProjection {
entries: ProjectedSessionEntry[];
messages: AgentMessage[];
thinkingLevel: string;
model: {
provider: string;
modelId: string;
} | null;
}
export interface SessionContext {
messages: AgentMessage[];
thinkingLevel: string;
thinkingSelection?: ThinkingSelection;
configurationUpdate?: {
effort: string;
};
model: {
provider: string;
modelId: string;
} | null;
}
export interface SessionInfo {
path: string;
id: string;
/** Working directory where the session was started. Empty string for old sessions. */
cwd: string;
/** User-defined display name from session_info entries. */
name?: string;
/** Path to the parent session (if this session was forked). */
parentSessionPath?: string;
created: Date;
modified: Date;
messageCount: number;
firstMessage: string;
allMessagesText: string;
/** Latest repository identity the session recorded (see `repository-identity`). */
repositoryIdentity?: RepositoryIdentity;
/** Set on sessions of the current repository recorded at a path that no longer exists. */
moved?: boolean;
}
export type ReadonlySessionManager = Pick<SessionManager, "getCwd" | "getSessionDir" | "getSessionId" | "getSessionFile" | "getLeafId" | "getLeafEntry" | "getEntry" | "getLabel" | "getBranch" | "getFullBranch" | "buildContextEntries" | "buildSessionContext" | "buildSessionProjection" | "getHeader" | "getEntries" | "reduceHistory" | "getTree" | "getSessionName">;
/** The id a session file's name carries (`<timestamp>_<id>.jsonl`), when the name has that shape and the id is valid. */
export declare function sessionFileNameId(path: string): string | undefined;
export declare function assertValidSessionId(id: string): void;
/** Exported for testing */
export declare function migrateSessionEntries(entries: FileEntry[]): void;
/** Exported for compaction.test.ts */
export declare function parseSessionEntries(content: string): FileEntry[];
export declare function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null;
/**
* Project one selected session entry into LLM/runtime messages.
* Plain custom entries are display/state entries and do not participate in context.
*/
export declare function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[];
/**
* Build the active, compaction-aware session entry list.
*
* This follows the current leaf path. If the path contains compaction entries,
* the latest compaction is represented by the compaction entry itself, followed
* by the kept entries starting at firstKeptEntryId and all entries after the
* compaction entry. Older summarized entries are omitted.
*/
export declare function buildContextEntries(entries: SessionEntry[], leafId?: string | null, byId?: Map<string, SessionEntry>): SessionEntry[];
/** Build provenance-preserving, compaction-aware model context. */
export declare function buildSessionProjection(entries: SessionEntry[], leafId?: string | null, byId?: Map<string, SessionEntry>): SessionProjection;
/**
* Build the session context from entries using tree traversal.
* If leafId is provided, walks from that entry to root.
* Handles compaction, branch summaries and context edits along the path: the messages are the
* canonical session projection's.
*/
export declare function buildSessionContext(entries: SessionEntry[], leafId?: string | null, byId?: Map<string, SessionEntry>): SessionContext;
/**
* Compute the default session directory for a cwd.
* Encodes cwd into a safe directory name under ~/.senpi/agent/sessions/.
*/
export declare function getDefaultSessionDirPath(cwd: string, agentDir?: string): string;
export declare function getDefaultSessionDir(cwd: string, agentDir?: string): string;
/** Exported for testing */
export declare function findMostRecentSession(sessionDir: string, cwd?: string): string | null;
/** Test seam for observing disk reloads without mocking ESM filesystem exports. */
export declare function setSessionEntryLoaderForTesting(loader: typeof loadEntriesFromFile): () => void;
export declare class SessionManager {
private sessionId;
private sessionFile;
private sessionDir;
/** Set by `adoptHomeSessionDir` when the open session lives in another app's store. */
private homeSessionDir;
private cwd;
private persist;
private readonly writeGuard;
private readonly writeFence;
private durable;
private bindPending;
private bindRaced;
private readonly projectionWarningListeners;
private flushed;
private headerWrite;
private ownedHeaderFile;
private tailMayBeTorn;
/** Why the tail may be torn, for the notice the person gets when it is set aside. */
private tornTailCause;
private readonly pendingRecoveries;
private recoveryListener;
private fileEntries;
private byId;
private entryOrdersById;
private messageEntryPositions;
private labelsById;
private labelTimestampsById;
private leafId;
private readonly transcriptFile;
private transcriptJournal;
private transcriptBytes;
private readonly capturesTranscriptBase;
private residentStore;
private readonly callKeys;
private mirrorTrimmed;
private loadingFullMirror;
/**
* Ids of entries a compaction trimmed from the resident mirror. They are still in the session file,
* so a new entry must not reuse one: a reused id turns the file's parent chain into a cycle and the
* next resume never finishes opening the session.
*/
private trimmedIds;
private readonly idsInUse;
private fullEntryCount;
private historyGeneration;
private verbatimFromCount;
private readonly historyReductions;
private compactEntriesCache;
/**
* Materialized views of `fileEntries` (`compact`) and, once the mirror is trimmed, of the full
* persisted history (`history`). Keyed by the mirror array and its length: appends push onto the
* same array, so a view extends by materializing only the new tail, while anything that rebuilds
* the mirror assigns a new array and invalidates both. Context builds run several times per turn;
* without this each one re-copied every entry of the session.
*/
private compactView;
private projectionMemo;
private historyView;
/** Id -> entry of the compact view, extended with it, so the branch shares its materialized objects. */
private compactLookup;
private mutationCount;
private entriesCache;
private branchCache;
private sessionNameCache;
private archivedCache;
private settledCache;
private usageTotals;
private constructor();
/**
* Reload session entries from the session file on disk.
*/
reloadFromDisk(): void;
/** Brings `id` back into the mirror by reloading the whole file when the mirror does not hold it. */
private _loadFullMirrorFor;
/** Switch to a different session file (used for resume and branching) */
setSessionFile(sessionFile: string): void;
private _setSessionFile;
/**
* `_setSessionFile` for a host that shares its event loop: the same steps, with the
* transcript-sized parse and externalize run in slices that yield (senpi#3518).
*/
private _setSessionFileAsync;
/** Points this manager at `sessionFile`; the path when it exists, undefined when a new session was started there. */
private _beginSessionFile;
/** Takes the loaded entries as this session's history; false when an empty file was initialized instead. */
private _adoptFileEntries;
/** Indexes the externalized entries; the file is the session's flushed authority from here on. */
private _completeFileLoad;
newSession(options?: NewSessionOptions): string | undefined;
/** Resets every in-memory field onto a fresh header. Allocates no session path. */
private _resetToNewSession;
private _loadEntries;
/**
* Keeps only the latest compaction's window of a just-loaded file resident (senpi#3519). The
* full-history count and usage totals are taken from the whole file first: a trimmed mirror
* cannot recompute them, so `_buildIndex` leaves them alone while the mirror is trimmed. Returns the
* file's full history when it trimmed, undefined when the whole file stays resident.
*/
private _retainLoadedTail;
private _buildIndex;
private _rewriteFile;
/** Wire the owning reader/writer's capture; until it lands snapshots use the bounded accepted tail. */
private _captureTranscriptBase;
/** Starts journaling committed transcript changes and returns the whole transcript they follow (R3.C1.1). */
beginTranscriptJournal(): TranscriptTransition[];
/** The transcript changes committed since the journal began or was last drained. */
drainTranscript(): TranscriptTransition[];
private _journalReplace;
private _transcriptSnapshot;
private _transcriptPersistence;
/** Pending journal values are the writer's bytes too, not a second serialization of the same entry. */
private _transcriptEntryBytes;
private _serializedFileEntries;
isPersisted(): boolean;
/** Give an unclaimed in-memory session its first file without rebuilding or changing its identity. */
enablePersistence(): Promise<void>;
getCwd(): string;
getSessionDir(): string;
/**
* Where this folder lists its sessions and creates new ones. A session opened from another app's
* registered store keeps its per-session state beside its file (`getSessionDir()`), but listing and
* new files stay in this folder's own session dir, never in that store (omo-desktop-app#8097).
*/
getHomeSessionDir(): string;
/**
* Called right after opening a picked session (`/resume`, `--resume`): when its file lives in another
* app's registered store, this folder's own session dir stays the home for listing and new sessions.
*/
adoptHomeSessionDir(): Promise<void>;
usesDefaultSessionDir(): boolean;
private moveToHomeSessionDir;
getSessionId(): string;
getSessionFile(): string | undefined;
/** Who may write this file now, from the same fold every persisted write is checked against. */
getOwnership(): SessionOwnership;
/**
* Exposes the resident store for out-of-band string lifecycles such as the
* agent's runtime message state (tokenized while idle, hydrated per turn).
*/
getResidentStore(): ResidentStringStore;
getResidentStoreStats(): ResidentStoreStats;
/**
* Writes the buffered header (and anything buffered behind it) through an exclusive create, as
* the first assistant message would, and appends every later entry immediately. A session that
* is exposed to other processes needs its id on disk first: a reopen of a missing file mints a
* new id. The write is asynchronous (the session path never blocks on the filesystem); entries
* persisted while it runs are appended by it before the transcript counts as flushed.
*/
persistHeaderNow(): Promise<void>;
isTranscriptFlushed(): boolean;
/**
* Removes the session file when this process created it with persistHeaderNow() and it holds only
* setup entries (header, model, thinking level, configuration, labels), `custom` entries their
* writer marked `startupBookkeeping` (the startup rules scan, repository identity) and engine lifecycle
* bookkeeping (senpi#3864, including a file that bookkeeping created itself), then returns to
* buffering so a later entry cannot recreate a header-less file; those entries reach disk again with
* the first message (senpi#3263). Any message (user, assistant, `!cmd`), delivered `custom_message`,
* session name, other `custom` entry (such as a paid cache prewarm or a todo list) or usage record
* keeps the file, and a file opened from disk is never deleted here.
*/
discardHeaderOnlyFile(): Promise<boolean>;
private _writeHeaderAsync;
/**
* A new session file is created only once the session contains a user or assistant message.
* Setup entries alone (model, thinking level, system prompt) stay in memory so opening and
* closing the agent without chatting leaves no file behind. Starting at the user message (not the
* first assistant reply) keeps the prompt on disk if the first turn never completes (#10000).
* An explicit persistHeaderNow() still writes the header first: a session exposed to other
* processes needs its id on disk before any conversation.
*/
private _hasConversation;
/**
* Receives each repair of this session's file once (senpi#4295): a torn tail set aside on open, or the fragment of a
* failed append set aside before the next one. Repairs made before a listener exists are delivered on registration.
*/
onRecovery(listener: (recovery: SessionRecovery) => void): () => void;
private _reportRecovery;
private _settleFinalLine;
/**
* Writes `entry`, which is not in `fileEntries` yet, before memory commits it. A throw means the
* file did not take the entry, so the caller commits nothing and no later entry can chain onto it.
*/
_persist(entry: SessionEntry): string | undefined;
private _commitBoundAppend;
/**
* S20b: binds this session to the durable store (opt-in; the Bun default is S21b). From here every write commits to
* the store first and the JSONL is its projection. Ends when this manager switches to another session file.
*/
bindDurableStore(binding: DurableStoreBinding): Promise<void>;
/** Resolves once the durable binding's deferred projection work (ledger records, reprojection) has run. */
settleDurableProjection(): Promise<void>;
/** Every projection write that failed after its store commit, one warning per failed write. */
onProjectionWarning(listener: (warning: ProjectionWarning) => void): () => void;
private _headerLine;
private _storedEntries;
private _appendEntry;
/**
* senpi#2537: the mirror used to hold its own JSON copy of every message the agent persisted, so each
* message's object and array skeleton was resident twice (strings were already shared). For a message
* that is plain JSON with no resident token, the mirror keeps a shallow copy instead: its own object
* (context projections tag it, never the agent's object), sharing the agent's content arrays. The file
* holds what `_persist` wrote, and a reload reads the same JSON. Anything else keeps the JSON copy: a
* resident token means the idle release may tokenize the agent's strings in place later, and a
* non-JSON value (a Date, NaN, a class instance) would make the mirror differ from a reload.
*/
private _shareMessage;
private _commitEntry;
private _noteSessionFlags;
/**
* Append an already-materialized entry without rewriting its identity or tree
* fields. This is the transport seam for entries captured by another manager.
*/
appendEntry(entry: SessionEntry): void;
private _materializeEntry;
/**
* Fold one entry into the running usage totals. Totals iterate ALL entries
* (not branch-scoped), matching the footer hot path's historical semantics.
*/
private _accumulateUsage;
/**
* O(1) running usage totals across ALL session entries (not branch-scoped).
* Maintained incrementally; identical to summing usage over getEntries().
*/
getUsageTotals(): UsageTotals;
/** Append a message as child of current leaf, then advance leaf. Returns entry id.
* Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
* Reason: we want these to be top-level entries in the session, not message session entries,
* so it is easier to find them.
* These need to be appended via appendCompaction() and appendBranchSummary() methods.
*/
appendMessage(message: Message | CustomMessage | BashExecutionMessage): string;
/**
* `appendMessage` for a message the session's own agent produced and whose content it does not change
* after it is persisted (senpi#2537). The mirror keeps a shallow copy that shares the message's content
* instead of a full JSON copy (see `_shareMessage` for when it falls back). `appendMessage` keeps the
* full copy: a caller may still change its object after appending.
*/
appendOwnedMessage(message: Message | CustomMessage | BashExecutionMessage, options?: {
readonly inputSource?: InputSource | undefined;
readonly recoveryOwner?: RecoveryCarrier;
/** The message's bridge-started calls, content index to the key minted with their start (RULING-127 (b)). */
readonly bridgedCalls?: ReadonlyMap<number, string>;
}): string;
/** `entry` as the session file holds it: its persisted call keys back in place (RULING-127 (c)). */
persistedEntry(entry: SessionEntry): FileEntry;
private _appendMessage;
/** Runtime append position for this exact persisted message object, if known. */
getMessageEntryPosition(message: AgentMessage): Readonly<{
entryId: string;
order: number;
}> | undefined;
/** Runtime/file append position for an entry, used with getMessageEntryPosition(). */
getEntryOrder(entryId: string): number | undefined;
/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
appendThinkingLevelChange(thinkingLevel: string, thinkingSelection?: ThinkingSelection, trigger?: ModelChangeOrigin, model?: {
readonly provider: string;
readonly id: string;
}): string;
/** Append a durable Responses configuration update as child of current leaf. */
appendConfigurationUpdate(effort: string): string;
/**
* Append a refused model switch (#1526). The refusal happens before any
* `model_change` is written, so without this the attempt leaves no trace.
*/
appendModelChangeRejected(details: Omit<ModelChangeRejectedEntry, "type" | "id" | "parentId" | "timestamp">): string;
/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */
appendModelChange(provider: string, modelId: string, reason?: "fallback" | "fallback-revert", originalProvider?: string, originalModelId?: string, attribution?: {
readonly origin: ModelChangeOrigin;
readonly duringTurn: boolean;
}): string;
/** Append model-attributed usage that does not participate in LLM context. Returns the appended entry. */
appendUsage(kind: string, provider: string, model: string, usage: Usage, note?: string): UsageEntry;
/** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
appendCompaction<T = unknown>(summary: string, firstKeptEntryId: string | null, tokensBefore: number, details?: T, fromHook?: boolean, usage?: Usage): string;
/**
* Release what outlives this manager in the process: the shared host's write
* grant and the blob directory backing its resident mirror. The session JSONL
* is untouched - it is the authority the next reader loads from. Idempotent.
*/
dispose(): void;
/**
* The blob directory is keyed by session id, so every live manager over the same
* session file hydrates from it. Removing it while one of them is still reading
* would cost that manager a full JSONL recovery per evicted string, so the last
* owner to let go is the one that clears it.
*/
private _releaseBlobsDirUnlessShared;
private _removeBlobsDir;
private _trimMirrorAfterCompaction;
/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. */
appendCustomEntry(customType: string, data?: unknown, options?: {
startupBookkeeping?: boolean;
}): string;
/** Append a session info entry (e.g., display name). Returns entry id. */
appendSessionInfo(name: string): string;
/**
* Get the current session name from the latest session_info entry, if any.
* O(1): the value is maintained incrementally on appendSessionInfo() and index rebuilds.
*/
getSessionName(): string | undefined;
/**
* Whether the newest `session_archived` entry naming this session archives it (senpi#6677). O(1): kept on append
* and index rebuilds, so a listing never materializes the history of an idle trimmed session.
*/
isArchived(): boolean;
/** The newest `session_settled` entry naming this session (the Done flag); O(1) like `isArchived()`. */
getSettled(): SessionSettled;
/**
* Append a custom message entry (for extensions) that participates in LLM context.
* @param customType Extension identifier for filtering on reload
* @param content Message content (string or TextContent/ImageContent array)
* @param display Whether to show in TUI (true = styled display, false = hidden)
* @param details Optional extension-specific metadata (not sent to LLM)
* @returns Entry id
*/
appendCustomMessageEntry<T = unknown>(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details?: T, options?: {
readonly recoveryOwner?: RecoveryCarrier;
}): string;
/** Append a branch-local edit to an earlier model-visible entry. */
appendContextEdit(targetId: string, replacement: ContextEditEntry["replacement"]): string;
getLeafId(): string | null;
getLeafEntry(): SessionEntry | undefined;
getEntry(id: string): SessionEntry | undefined;
/**
* Get all direct children of an entry.
*/
getChildren(parentId: string): SessionEntry[];
/**
* Get the label for an entry, if any.
*/
getLabel(id: string): string | undefined;
/**
* Set or clear a label on an entry.
* Labels are user-defined markers for bookmarking/navigation.
* Pass undefined or empty string to clear the label.
*/
appendLabelChange(targetId: string, label: string | undefined): string;
/**
* Walk from entry to root, returning all entries in path order.
* Includes all entry types (messages, compaction, model changes, etc.).
* Use buildSessionContext() to get the resolved messages for the LLM.
*/
getBranch(fromId?: string): SessionEntry[];
/**
* The path from `fromId` (default: the leaf) to the root over the whole persisted history. `getBranch()`
* answers a trimmed mirror from the latest compaction window (senpi#3519); readers that need every entry
* of the path, such as a fork's new file or the files a session touched, read it here from the file.
*/
getFullBranch(fromId?: string): SessionEntry[];
/**
* The cached branch extended by entries appended under its leaf since, when that is all that
* changed (same mirror array, the new leaf descends from the cached one within a short walk).
* Appending a message used to re-materialize the whole branch on the next read.
*/
private _extendBranchCache;
/**
* Build the active, compaction-aware entry list for context/rendering.
* Uses tree traversal from current leaf.
*/
buildContextEntries(): SessionEntry[];
/**
* Build the canonical session projection (context edits, compaction boundary) from the current
* leaf. Reads the compact mirror like buildSessionContext(), so a trimmed mirror never reloads
* the full history.
*/
buildSessionProjection(): SessionProjection;
/**
* Projection of the current leaf over the compact view, memoized until the view or the leaf
* changes: several context builds run per turn over the same, unchanged session. Callers get
* copies of the arrays because the agent appends to the message array it receives.
*/
private _projectCurrent;
/**
* The memoized leaf path extended by entries appended under its leaf, when the compact view only
* grew by such a chain (the normal case while a session runs); undefined when it must be rebuilt.
*/
private _extendPath;
/**
* Build the session context (what gets sent to the LLM).
* Uses tree traversal from current leaf.
*/
buildSessionContext(): SessionContext;
hasContextMessages(): boolean;
hasThinkingLevelChanges(): boolean;
countCompactions(): number;
private hasBranchEntry;
/**
* Get session header.
*/
getHeader(): SessionHeader | null;
/**
* Get all session entries (excludes header).
* The session is append-only: use appendXXX() to add entries, branch() to
* change the leaf pointer. Entries cannot be modified or deleted.
*
* The result is memoized behind the session mutation counter: repeated calls
* without an intervening mutation return the SAME shared array instance.
* Callers must not mutate the returned array or its entries; copy first if
* you need to filter/reorder.
*/
getEntries(): SessionEntry[];
/** Returns the maintained non-header entry count without loading or materializing history. */
getEntryCount(): number;
/**
* Folds the whole history (every branch, append order, like `getEntries()`) without keeping a full-history view
* (senpi#2537): the history is read once per load, later calls fold only the entries appended since. For per-turn
* readers that need the latest or the since-last of something; see `HistoryReducer` for the reducer contract.
*/
reduceHistory<S>(reducer: HistoryReducer<S>): S;
private _appendedSince;
private _readWholeHistory;
/**
* Release the memoized materialized views. Materialized entries hold the full
* persisted strings, so views kept between turns pin the whole session text
* in memory even while nothing runs. The next read rebuilds them from the
* bounded resident store.
*/
dropMaterializedCaches(): void;
/** Whether a full-history view of a trimmed mirror is held: the whole file's entries, parsed. */
holdsMaterializedHistory(): boolean;
/** The view's entries extended by the mirror's new tail, or undefined when it must be rebuilt. */
private _extendView;
/**
* The compact view's materialized entry for each path entry, or undefined when one is not in the
* view. The branch is a subset of the compact view whenever the leaf is in the mirror; sharing its
* objects keeps one materialized copy of the session instead of two (about 20 MB at 50k entries).
*/
private _fromCompactView;
private _bindMessagePositions;
private _materializeEntries;
private _getCompactEntries;
/** The file's whole history, its persisted call keys taken out like a load does (RULING-126 (1a)). */
private _loadFullHistoryEntries;
/**
* Get the session as a tree structure. Returns a shallow defensive copy of all entries.
* A well-formed session has exactly one root (first entry with parentId === null).
* Orphaned entries (broken parent chain) are also returned as roots.
*/
getTree(): SessionTreeNode[];
/**
* Start a new branch from an earlier entry.
* Moves the leaf pointer to the specified entry. The next appendXXX() call
* will create a child of that entry, forming a new branch. Existing entries
* are not modified or deleted.
*/
branch(branchFromId: string): void;
/**
* Reset the leaf pointer to null (before any entries).
* The next appendXXX() call will create a new root entry (parentId = null).
* Use this when navigating to re-edit the first user message.
*/
resetLeaf(): void;
/**
* Start a new branch with a summary of the abandoned path.
* Same as branch(), but also appends a branch_summary entry that captures
* context from the abandoned conversation path.
*/
branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean, usage?: Usage): string;
/** The messages a leaf move took off and put on the active path, when a consumer journals the transcript. */
private _branchFlow;
/**
* Create a new session file containing only the path from root to the specified leaf.
* Useful for extracting a single conversation path from a branched session.
* Returns the new session file path, or undefined if not persisting.
*/
createBranchedSession(leafId: string): string | undefined;
/**
* Create a new session.
* @param cwd Working directory (stored in session header)
* @param sessionDir Optional session directory. If omitted, uses default (~/.senpi/agent/sessions/<encoded-cwd>/).
*/
static create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager;
/**
* Open a specific session file.
* @param path Path to session file
* @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
* @param cwdOverride Optional cwd override instead of the session header cwd.
* @param options Applied only when this open CREATES the session (the path does not exist
* yet, or exists and is empty). An existing session file keeps the id in its header.
*/
static open(path: string, sessionDir?: string, cwdOverride?: string, options?: NewSessionOptions): SessionManager;
/**
* `open` for a process whose event loop serves other sessions (the multi-session RPC host):
* the transcript is parsed and externalized in slices that yield, so opening a large
* session never holds every other session's requests (senpi#3518).
*/
static openAsync(path: string, sessionDir?: string, cwdOverride?: string, options?: NewSessionOptions, slicer?: EventLoopSlicer): Promise<SessionManager>;
/**
* Continue the most recent session, or create new if none.
* @param cwd Working directory
* @param sessionDir Optional session directory. If omitted, uses default (~/.senpi/agent/sessions/<encoded-cwd>/).
*/
static continueRecent(cwd: string, sessionDir?: string): SessionManager;
/** The file `continueRecent` would open, found without loading it (loading can migrate and rewrite the file). */
static recentSessionFile(cwd: string, sessionDir?: string): string | null;
/** Create an in-memory session (no file persistence), optionally from entries held outside the filesystem. */
static inMemory(cwd?: string, options?: NewSessionOptions, entries?: FileEntry[]): SessionManager;
/**
* Fork a session from another project directory into the current project.
* Creates a new session in the target cwd with the full history from the source session.
* @param sourcePath Path to the source session file
* @param targetCwd Target working directory (where the new session will be stored)
* @param sessionDir Optional session directory. If omitted, uses default for targetCwd.
*/
static forkFrom(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager;
/**
* Find an exact session ID without loading transcript bodies.
* @param cwd Working directory (used to compute default session directory)
* @param id Exact session ID
* @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
*/
static findById(cwd: string, id: string, sessionDir?: string): string | undefined;
/**
* List all sessions for a directory.
* @param cwd Working directory (used to compute default session directory)
* @param sessionDir Optional session directory. If omitted, uses default (~/.senpi/agent/sessions/<encoded-cwd>/).
* @param onProgress Optional callback for progress updates (loaded, total)
*/
static list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;
/**
* List all sessions across all project directories.
* @param onProgress Optional callback for progress updates (loaded, total)
*/
static listAll(onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;
static listAll(sessionDir?: string, onProgress?: SessionListProgress, signal?: AbortSignal): Promise<SessionInfo[]>;
}
//# sourceMappingURL=session-manager.d.ts.map