UNPKG

@code-yeongyu/senpi

Version:

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

249 lines • 12.9 kB
import type { AgentSession } from "./agent-session.ts"; import type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from "./agent-session-services.ts"; import type { BrowserEngine } from "./browser-engine.ts"; import type { PromptSurface } from "./dynamic-prompt/types.ts"; import type { HostMcpRegistry } from "./extensions/builtin/mcp/host-registry.ts"; import type { ProjectTrustContext, ReplacedSessionContext, SessionContext, SessionKind, SessionStartEvent } from "./extensions/index.ts"; import type { CreateAgentSessionResult } from "./sdk.ts"; import type { SessionHolderEndpoint } from "./session-hold-errors.ts"; import { SessionManager } from "./session-manager.ts"; import type { SettingsManager } from "./settings-manager.ts"; /** * Result returned by runtime creation. * * The caller gets the created session, its cwd-bound services, and all * diagnostics collected during setup. */ export interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult { services: AgentSessionServices; diagnostics: AgentSessionRuntimeDiagnostic[]; } /** Immutable flags selected when a runtime is first launched. */ export interface AgentSessionLaunchProfile { cwd: string; spawnedBy?: import("./session-lifecycle-types.ts").SpawnedBy; /** Host-owned public endpoint evidence; never sourced from client session context. */ holderEndpoint?: SessionHolderEndpoint; permissionPreset?: string; /** `host_default`: `permissionPreset` is the host's own default (an embedder's host option), not a client's choice. */ permissionPresetSource?: "host_default"; creationModel?: { provider: string; modelId: string; }; initialThinkingLevel?: string; /** * Visibility class of this session (`open_session.kind`), absent for classic * launches. It reaches the extensions this session loads and nothing else: it * never takes part in auth, model or resource resolution. */ sessionKind?: SessionKind; /** Opaque labels the opener attached (`open_session.context`), absent when none. */ sessionContext?: SessionContext; /** * Per-session auto-titling (`open_session.auto_title`). When set, this session * ignores the host-wide `--auto-title-sessions` / appMode default. */ autoTitle?: boolean; /** Per-session prompt surface (`open_session.promptSurface`); absent means `SENPI_PROMPT_SURFACE`. */ promptSurface?: PromptSurface; /** Per-session browser engine (`open_session.browserEngine`); absent means none was chosen. */ browserEngine?: BrowserEngine; /** * Per-session retry fallback (`open_session.retryFallback`): applied to THIS session's settings as an * in-memory override that is never written to a settings file, so one session's chain never reaches * another session on the host or the user's settings. Absent means the host's settings decide. */ retryFallback?: SessionRetryFallbackProfile; /** * Per-session caller env (`open_session.env`, senpi#4381): the variables THIS session's tool * subprocesses see on top of the process environment. Never the host's own, never another session's. */ sessionEnv?: Readonly<Record<string, string>>; } /** The fallback policy one session runs with, chosen by its opener (e.g. a task child's own chain). */ export interface SessionRetryFallbackProfile { readonly modelFallback: boolean; /** Chain key (selector, optionally `:thinking`) to its ordered fallback selectors. */ readonly fallbackChains: Readonly<Record<string, readonly string[]>>; } /** Overlays a session's fallback policy on its settings in memory: never saved, never shared. */ export declare function applyRetryFallbackProfile(settingsManager: SettingsManager, profile: SessionRetryFallbackProfile): void; /** * Creates a full runtime for a target cwd and session manager. * * The factory closes over process-global fixed inputs, recreates cwd-bound * services for the effective cwd, resolves session options against those * services, and finally creates the AgentSession. */ export type CreateAgentSessionRuntimeFactory = (options: { cwd: string; agentDir: string; mcpRegistry?: HostMcpRegistry; sessionManager: SessionManager; sessionStartEvent?: SessionStartEvent; projectTrustContext?: ProjectTrustContext; launchProfile?: Readonly<AgentSessionLaunchProfile>; }) => Promise<CreateAgentSessionRuntimeResult>; /** * Thrown when /import references a JSONL file path that does not exist. */ export declare class SessionImportFileNotFoundError extends Error { readonly filePath: string; constructor(filePath: string); } /** * Owns the current AgentSession plus its cwd-bound services. * * Session replacement methods tear down the current runtime first, then create * and apply the next runtime. If creation fails, the error is propagated to the * caller. The caller is responsible for user-facing error handling. */ export declare class AgentSessionRuntime { private rebindSession?; private beforeSessionInvalidate?; private readonly sessionReplaceListeners; private _session; private _services; private readonly createRuntime; private _diagnostics; private _modelFallbackMessage?; private _launchProfile?; private _sessionHold?; private _removedOnReplacement?; constructor(_session: AgentSession, _services: AgentSessionServices, createRuntime: CreateAgentSessionRuntimeFactory, _diagnostics?: AgentSessionRuntimeDiagnostic[], _modelFallbackMessage?: string, launchProfile?: Readonly<AgentSessionLaunchProfile>); /** Stops advertising the open session to other processes; a runtime that replaces this one holds its own. */ releaseSessionHold(): void; /** A speculative host session becomes durable only when a caller claims its already-built runtime. */ persistSession(): Promise<void>; get services(): AgentSessionServices; get session(): AgentSession; get cwd(): string; get diagnostics(): readonly AgentSessionRuntimeDiagnostic[]; get modelFallbackMessage(): string | undefined; get launchProfile(): Readonly<AgentSessionLaunchProfile> | undefined; /** Moves this session to another prompt surface; later replacements (switch, new, fork) keep it. */ setPromptSurface(surface: PromptSurface): void; /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */ setBrowserEngine(engine: BrowserEngine): void; /** * Moves this session to another permission preset (a later `open_session.permissionPreset`): the * permission extension enforces it from the next tool call, and later replacements (switch, new, * fork) keep it. */ setPermissionPreset(preset: string): void; /** The session teardownCurrent disposed; it stays the live session only until apply() installs a replacement. */ private _disposedSession; /** * Keeps a Full-access-only project trust in step with the preset (senpi#3414, #3420). Leaving Full * access withdraws it, unless the user has since saved "trust"; going back restores it, unless the * user saved "do not trust". Either way the session's runtime is rebuilt so project extensions, * skills, hooks and MCP servers load or unload, and nothing can cancel that rebuild. The trust is * never saved. The saved decision includes the one a linked git worktree inherits from its main * checkout (senpi#4388), which is read asynchronously, so each sync runs after the previous one and * becomes `projectTrustChange` at once. A sync that fails (an unreadable trust store) is recorded as a * diagnostic and never blocks the next one. Returns when the sync, and any rebuild it started, has settled. */ private syncFullAccessTrust; /** Settles when the rebuild that followed a Full-access trust change has finished. */ get projectTrustChange(): Promise<void>; /** * Runs `task` after every trust change already started here and before any started later (senpi#6176), so an * explicit trust decision and a Full access sync never read each other's saved value mid-change. */ runInProjectTrustChangeOrder<T>(task: () => Promise<T>): Promise<T>; private _projectTrustChange; /** Failed trust rebuilds; kept across session replacement so the error stays visible. */ private _trustChangeDiagnostics; /** * Gives this process's sessions their fallback policy (`set_retry_fallback`); later replacements * (switch, new, fork) keep it. Callers set it before the first turn: a chain never changes under a * retry already in flight. */ setRetryFallback(profile: SessionRetryFallbackProfile): void; setRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void; /** * Set a synchronous callback that runs after `session_shutdown` handlers finish * but before the current session is invalidated. * * This is for host-owned UI teardown that must not yield to the event loop, * such as detaching extension-provided TUI components before the old extension * context becomes stale. */ setBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void; /** * Run `listener` synchronously while the current session is REPLACED (new, switch, fork, resume), after * `session_shutdown` handlers and before the outgoing session is disposed, so it can still write to that * transcript. Unlike `setBeforeSessionInvalidate` it never runs from `dispose()`, and any number of * listeners coexist. Returns the function that removes it. */ onBeforeSessionReplace(listener: () => void): () => void; /** Attachment transitions are ordered by the RPC entry's lifecycle mutex. */ emitAttachmentEvent(type: "session_parked" | "session_resumed"): Promise<void>; private emitBeforeSwitch; private emitBeforeFork; private teardownCurrent; private reportRemovedExtensions; private apply; private finishSessionReplacement; switchSession(sessionPath: string, options?: { cwdOverride?: string; withSession?: (ctx: ReplacedSessionContext) => Promise<void>; projectTrustContextFactory?: (cwd: string) => ProjectTrustContext; }): Promise<{ cancelled: boolean; }>; newSession(options?: { parentSession?: string; setup?: (sessionManager: SessionManager) => Promise<void>; withSession?: (ctx: ReplacedSessionContext) => Promise<void>; }): Promise<{ cancelled: boolean; }>; fork(entryId: string, options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void>; }): Promise<{ cancelled: boolean; selectedText?: string; }>; /** * Import a session JSONL file and switch runtime state to the imported session. * * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`. * @throws {SessionImportFileNotFoundError} When the input path does not exist. * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided. */ importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean; }>; /** * Abort the active run, waiting at most the #3711 quit budget. Arming the budget first makes this wait count * against the same total the `session_shutdown` handlers share, so a turn held by an extension cannot delay quit * past it. */ private endActiveRunWithinQuitBudget; /** * `processExit`: the caller exits the process right after, so quit-time handlers share the total quit budget * (senpi#3711). An RPC host closing one session leaves it unset and keeps only the per-handler limits. */ dispose(options?: { readonly processExit?: boolean; readonly endActiveRun?: boolean; }): Promise<void>; } /** * Create the initial runtime from a runtime factory and initial session target. * * The same factory is stored on the returned AgentSessionRuntime and reused for * later /new, /resume, /fork, and import flows. */ export declare function createAgentSessionRuntime(createRuntime: CreateAgentSessionRuntimeFactory, options: { cwd: string; agentDir: string; sessionManager: SessionManager; sessionStartEvent?: SessionStartEvent; launchProfile?: Readonly<AgentSessionLaunchProfile>; }): Promise<AgentSessionRuntime>; export { type AgentSessionRuntimeDiagnostic, type AgentSessionServices, type CreateAgentSessionFromServicesOptions, type CreateAgentSessionServicesOptions, createAgentSessionFromServices, createAgentSessionServices, } from "./agent-session-services.ts"; //# sourceMappingURL=agent-session-runtime.d.ts.map