UNPKG

@code-yeongyu/senpi

Version:

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

612 lines • 30.2 kB
import { constants, copyFileSync, existsSync, mkdirSync } from "node:fs"; import { basename, join, parse, resolve } from "node:path"; import { resolvePath } from "../utils/paths.js"; import { emitSessionShutdownEvent } from "./extensions/runner.js"; import { applyClientPermissionMode, clientNamedPreset, markHostDefaultPresetFlag, withClientPreset, } from "./permission-mode.js"; import { assertSessionCwdExists } from "./session-cwd.js"; import { holdSessionFile } from "./session-holders.js"; import { SessionManager } from "./session-manager.js"; import { reserveSessionWrite, unregisterSessionWriter } from "./session-write-reservation.js"; import { resetTimings, time } from "./timings.js"; import { getSavedProjectTrust, ProjectTrustStore } from "./trust-manager.js"; /** Overlays a session's fallback policy on its settings in memory: never saved, never shared. */ export function applyRetryFallbackProfile(settingsManager, profile) { settingsManager.applyOverrides({ retry: { modelFallback: profile.modelFallback, fallbackChains: Object.fromEntries(Object.entries(profile.fallbackChains).map(([key, entries]) => [key, [...entries]])), }, }); } /** * Thrown when /import references a JSONL file path that does not exist. */ export class SessionImportFileNotFoundError extends Error { constructor(filePath) { super(`File not found: ${filePath}`); this.name = "SessionImportFileNotFoundError"; this.filePath = filePath; } } function extractUserMessageText(content) { if (typeof content === "string") { return content; } return content .filter((part) => part.type === "text" && typeof part.text === "string") .map((part) => part.text) .join(""); } /** * 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 class AgentSessionRuntime { constructor(_session, _services, createRuntime, _diagnostics = [], _modelFallbackMessage, launchProfile) { this.sessionReplaceListeners = new Set(); this._projectTrustChange = Promise.resolve(); /** Failed trust rebuilds; kept across session replacement so the error stays visible. */ this._trustChangeDiagnostics = []; this._session = _session; this._services = _services; this.createRuntime = createRuntime; this._diagnostics = _diagnostics; this._modelFallbackMessage = _modelFallbackMessage; this._launchProfile = launchProfile; markHostDefaultPresetFlag(_session, launchProfile); applyClientPermissionMode(_session, clientNamedPreset(launchProfile), { announce: false }); this._sessionHold = holdActiveSession(_session.sessionManager, wasFlushed(_session.sessionManager), launchProfile?.holderEndpoint); } /** Stops advertising the open session to other processes; a runtime that replaces this one holds its own. */ releaseSessionHold() { this._sessionHold?.release(); this._sessionHold = undefined; } /** A speculative host session becomes durable only when a caller claims its already-built runtime. */ async persistSession() { await this.session.sessionManager.enablePersistence(); this._sessionHold ??= holdActiveSession(this.session.sessionManager, false, this._launchProfile?.holderEndpoint); } get services() { return this._services; } get session() { return this._session; } get cwd() { return this._services.cwd; } get diagnostics() { return this._trustChangeDiagnostics.length === 0 ? this._diagnostics : [...this._diagnostics, ...this._trustChangeDiagnostics]; } get modelFallbackMessage() { return this._modelFallbackMessage; } get launchProfile() { return this._launchProfile; } /** Moves this session to another prompt surface; later replacements (switch, new, fork) keep it. */ setPromptSurface(surface) { this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), promptSurface: surface }); this._session.setPromptSurface(surface); } /** Moves this session to another browser engine; later replacements (switch, new, fork) keep it. */ setBrowserEngine(engine) { this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), browserEngine: engine }); this._session.setBrowserEngine(engine); } /** * 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) { this._launchProfile = withClientPreset(this._launchProfile ?? { cwd: this.cwd }, preset); this._session.extensionRunner.setFlagValue("permission-preset", preset); // While a replacement is in flight (or after one failed) the live session is the disposed one: // nothing may rebuild it. The preset is recorded above, and apply() syncs the next replacement to // it before that one goes live. There is no flag to clear: the check is the session itself. if (this._session !== this._disposedSession) { this.syncFullAccessTrust(this._session, preset); applyClientPermissionMode(this._session, preset, { announce: true }); } } /** * 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. */ syncFullAccessTrust(session, preset) { const settings = session.settingsManager; const change = this._projectTrustChange .then(async () => { // The session's own project: a replacement can belong to another project than the retired one (#3420 review). const saved = await getSavedProjectTrust(new ProjectTrustStore(this.services.agentDir), session.sessionManager.getCwd()); // The session may have been retired while the decision was read; a retired session is never rebuilt. if (session === this._disposedSession) return; if (preset !== "full-access" && settings.isTrustFromFullAccess() && saved !== true) settings.setProjectTrusted(false); else if (preset === "full-access" && settings.canRestoreFullAccessTrust() && saved !== false) settings.setProjectTrusted(true); else return; await session.applyProjectTrustChange().catch((error) => { this._trustChangeDiagnostics = [ ...this._trustChangeDiagnostics, { type: "error", message: `Updating project code after a Full access change failed: ${String(error)}`, }, ]; }); }) .catch((error) => { this._trustChangeDiagnostics = [ ...this._trustChangeDiagnostics, { type: "error", message: `Reading the project trust after a Full access change failed: ${String(error)}`, }, ]; }); this._projectTrustChange = change; return change; } /** Settles when the rebuild that followed a Full-access trust change has finished. */ get projectTrustChange() { return this._projectTrustChange; } /** * 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(task) { const run = this._projectTrustChange.then(task); this._projectTrustChange = run.then(() => undefined, () => undefined); return run; } /** * 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) { const retryFallback = Object.freeze({ modelFallback: profile.modelFallback, fallbackChains: Object.freeze(Object.fromEntries(Object.entries(profile.fallbackChains).map(([key, entries]) => [key, Object.freeze([...entries])]))), }); this._launchProfile = Object.freeze({ ...(this._launchProfile ?? { cwd: this.cwd }), retryFallback }); applyRetryFallbackProfile(this._session.settingsManager, retryFallback); } setRebindSession(rebindSession) { this.rebindSession = rebindSession; } /** * 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) { this.beforeSessionInvalidate = beforeSessionInvalidate; } /** * 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) { this.sessionReplaceListeners.add(listener); return () => { this.sessionReplaceListeners.delete(listener); }; } /** Attachment transitions are ordered by the RPC entry's lifecycle mutex. */ async emitAttachmentEvent(type) { const runner = this.session.extensionRunner; if (runner.hasHandlers(type)) await runner.emit({ type }); } async emitBeforeSwitch(reason, targetSessionFile) { const runner = this.session.extensionRunner; if (!runner.hasHandlers("session_before_switch")) { return { cancelled: false }; } const result = await runner.emit({ type: "session_before_switch", reason, targetSessionFile, }); return { cancelled: result?.cancel === true }; } async emitBeforeFork(entryId, options) { const runner = this.session.extensionRunner; if (!runner.hasHandlers("session_before_fork")) { return { cancelled: false }; } const result = await runner.emit({ type: "session_before_fork", entryId, ...options, }); return { cancelled: result?.cancel === true }; } async teardownCurrent(reason, targetSessionFile, targetSessionId) { const mark = (label) => { if (reason === "resume") time(label, "switch"); }; // Settle the active response before replacement so the outgoing turn and // any completed tool results are persisted to the old session. The abort names the // replacement, so a client sees why its running turn ended before `session_replaced` arrives. await this.session.abort(reason === "new" || reason === "fork" || reason === "resume" ? { cause: { kind: "session_replaced", reason, ...(targetSessionFile === undefined ? {} : { targetSessionFile }), ...(targetSessionId === undefined ? {} : { targetSessionId }), }, } : undefined); mark("abort"); const oldRunner = this.session.extensionRunner; // Test hosts and partial runner implementations may lack identity introspection; // skip removal reporting there rather than break the replacement itself. if (typeof oldRunner.getExtensionIdentities === "function") { this._removedOnReplacement = { oldRunner, oldIdentities: oldRunner.getExtensionIdentities(), reason, }; } await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason, targetSessionFile, }); mark("shutdown"); for (const listener of [...this.sessionReplaceListeners]) listener(); this.beforeSessionInvalidate?.(); const replaced = this.session.sessionManager; this.session.dispose(); this._disposedSession = this.session; // As in dispose(): the replaced session's tool child has stopped and its commands are swept before replacement. await this.session.whenToolChildClosed(); // Nothing writes to the replaced manager once its session is disposed, so the // shared host may hand its session file to another worker. unregisterSessionWriter(replaced); this.releaseSessionHold(); mark("dispose"); } async reportRemovedExtensions() { const pending = this._removedOnReplacement; this._removedOnReplacement = undefined; if (!pending) return; const newRunner = this.session.extensionRunner; if (typeof newRunner.getExtensionIdentities !== "function") return; const newResolvedPaths = new Set(newRunner.getExtensionIdentities().map((extension) => extension.resolvedPath)); const removed = pending.oldIdentities.filter((extension) => !newResolvedPaths.has(extension.resolvedPath)); if (removed.length === 0) return; await pending.oldRunner.emit({ type: "session_extensions_removed", reason: pending.reason, removed }); } async apply(result, hold) { this._sessionHold = hold ?? holdActiveSession(result.session.sessionManager, false, this._launchProfile?.holderEndpoint); // The replacement was built from the profile read before its runtime was created; an attach // that moved a setting while it was being built reached only the retired session (senpi#2842). // Its project trust follows the CURRENT preset before it goes live: a replacement built while the // session was still Full access must not be reachable with that trust's project code (#3420). A // preset change that lands while that rebuild runs reaches only the retired session, so sync // again until the preset stops moving, then install the profile read last. let syncedPreset; while (this._launchProfile?.permissionPreset !== undefined && this._launchProfile.permissionPreset !== syncedPreset) { syncedPreset = this._launchProfile.permissionPreset; await this.syncFullAccessTrust(result.session, syncedPreset); } const profile = this._launchProfile; this._session = result.session; if (profile?.permissionPreset !== undefined) this._session.extensionRunner.setFlagValue("permission-preset", profile.permissionPreset); markHostDefaultPresetFlag(this._session, profile); applyClientPermissionMode(this._session, clientNamedPreset(profile), { announce: false }); if (profile?.promptSurface !== undefined) this._session.setPromptSurface(profile.promptSurface); if (profile?.browserEngine !== undefined) this._session.setBrowserEngine(profile.browserEngine); this._services = result.services; this._diagnostics = result.diagnostics; this._modelFallbackMessage = result.modelFallbackMessage; await this.reportRemovedExtensions(); } async finishSessionReplacement(withSession) { if (this.rebindSession) { await this.rebindSession(this.session); } if (withSession) { await withSession(this.session.createReplacedSessionContext()); } } async switchSession(sessionPath, options) { resetTimings("switch"); const beforeResult = await this.emitBeforeSwitch("resume", sessionPath); if (beforeResult.cancelled) { return beforeResult; } time("beforeSwitch", "switch"); const previousSessionFile = this.session.sessionFile; const sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride); await sessionManager.adoptHomeSessionDir(); await assertSessionCwdExists(sessionManager, this.cwd); // Held before the current session is torn down: a session being moved fails the switch here. const hold = holdActiveSession(sessionManager, wasFlushed(sessionManager), this._launchProfile?.holderEndpoint); time("open", "switch"); try { await this.teardownCurrent("resume", sessionManager.getSessionFile(), sessionManager.getSessionId()); await this.apply(await this.createRuntime({ cwd: sessionManager.getCwd(), agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile }, projectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()), launchProfile: this._launchProfile, }), hold); } catch (error) { if (this._sessionHold !== hold) hold?.release(); throw error; } time("apply", "switch"); await this.finishSessionReplacement(options?.withSession); time("rebind", "switch"); return { cancelled: false }; } async newSession(options) { const beforeResult = await this.emitBeforeSwitch("new"); if (beforeResult.cancelled) { return beforeResult; } const previousSessionFile = this.session.sessionFile; const sessionDir = this.session.sessionManager.getHomeSessionDir(); const sessionManager = this.session.sessionManager.isPersisted() ? SessionManager.create(this.cwd, sessionDir) : SessionManager.inMemory(this.cwd); if (options?.parentSession) { sessionManager.newSession({ parentSession: options.parentSession }); } await this.teardownCurrent("new", sessionManager.getSessionFile(), sessionManager.getSessionId()); await this.apply(await this.createRuntime({ cwd: this.cwd, agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "new", previousSessionFile }, launchProfile: this._launchProfile, })); if (options?.setup) { await options.setup(this.session.sessionManager); this.session.refreshContext(); } await this.finishSessionReplacement(options?.withSession); return { cancelled: false }; } async fork(entryId, options) { const position = options?.position ?? "before"; const beforeResult = await this.emitBeforeFork(entryId, { position }); if (beforeResult.cancelled) { return { cancelled: true }; } let targetLeafId; let selectedText; const selectedEntry = this.session.sessionManager.getEntry(entryId); if (!selectedEntry) { throw new Error("Invalid entry ID for forking"); } if (position === "at") { targetLeafId = selectedEntry.id; } else { if (selectedEntry.type !== "message" || selectedEntry.message.role !== "user") { throw new Error("Invalid entry ID for forking"); } targetLeafId = selectedEntry.parentId; selectedText = extractUserMessageText(selectedEntry.message.content); } const previousSessionFile = this.session.sessionFile; if (this.session.sessionManager.isPersisted()) { const currentSessionFile = this.session.sessionFile; if (!currentSessionFile) { throw new Error("Persisted session is missing a session file"); } const sessionDir = this.session.sessionManager.getHomeSessionDir(); if (!targetLeafId) { const sessionManager = SessionManager.create(this.cwd, sessionDir); sessionManager.newSession({ parentSession: currentSessionFile }); await this.teardownCurrent("fork", sessionManager.getSessionFile(), sessionManager.getSessionId()); await this.apply(await this.createRuntime({ cwd: this.cwd, agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile }, launchProfile: this._launchProfile, })); await this.finishSessionReplacement(options?.withSession); return { cancelled: false, selectedText }; } if (!existsSync(currentSessionFile)) { throw new Error("This session has not been saved yet. Send a message before cloning or forking it."); } const sessionManager = SessionManager.open(currentSessionFile, sessionDir); const forkedSessionPath = sessionManager.createBranchedSession(targetLeafId); if (!forkedSessionPath) { throw new Error("Failed to create forked session"); } await this.teardownCurrent("fork", sessionManager.getSessionFile(), sessionManager.getSessionId()); await this.apply(await this.createRuntime({ cwd: sessionManager.getCwd(), agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile }, launchProfile: this._launchProfile, })); await this.finishSessionReplacement(options?.withSession); return { cancelled: false, selectedText }; } const sessionManager = this.session.sessionManager; // The in-memory fork reuses this manager and gets its new id only after the old turn is torn down, // so the replacement is named without an id it does not have yet. await this.teardownCurrent("fork"); if (!targetLeafId) { sessionManager.newSession({ parentSession: previousSessionFile }); } else { sessionManager.createBranchedSession(targetLeafId); } await this.apply(await this.createRuntime({ cwd: this.cwd, agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile }, launchProfile: this._launchProfile, })); await this.finishSessionReplacement(options?.withSession); return { cancelled: false, selectedText }; } /** * 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. */ async importFromJsonl(inputPath, cwdOverride) { const resolvedPath = resolvePath(inputPath); if (!existsSync(resolvedPath)) { throw new SessionImportFileNotFoundError(resolvedPath); } const sessionDir = this.session.sessionManager.getHomeSessionDir(); if (!existsSync(sessionDir)) { mkdirSync(sessionDir, { recursive: true }); } let destinationPath = join(sessionDir, basename(resolvedPath)); const sourceAlreadyStored = resolve(destinationPath) === resolvedPath; if (!sourceAlreadyStored) { const { name, ext } = parse(destinationPath); let suffix = 1; while (existsSync(destinationPath)) { destinationPath = join(sessionDir, `${name}-${suffix++}${ext}`); } } const beforeResult = await this.emitBeforeSwitch("resume", destinationPath); if (beforeResult.cancelled) { return beforeResult; } const previousSessionFile = this.session.sessionFile; reserveSessionWrite(destinationPath); if (!sourceAlreadyStored) { copyFileSync(resolvedPath, destinationPath, constants.COPYFILE_EXCL); } const sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride); await assertSessionCwdExists(sessionManager, this.cwd); await this.teardownCurrent("resume", sessionManager.getSessionFile(), sessionManager.getSessionId()); await this.apply(await this.createRuntime({ cwd: sessionManager.getCwd(), agentDir: this.services.agentDir, sessionManager, sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile }, launchProfile: this._launchProfile, })); await this.finishSessionReplacement(); return { cancelled: false }; } /** * 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. */ async endActiveRunWithinQuitBudget(processExit) { if (processExit) this.session.extensionRunner.armProcessExitBudget(); const budgetMs = this.services.settingsManager.getSessionShutdownQuitBudgetMs(); if (budgetMs === 0) { await this.session.abort(); return; } let timer; try { await Promise.race([ this.session.abort(), new Promise((resolve) => { timer = setTimeout(resolve, budgetMs); }), ]); } finally { if (timer !== undefined) clearTimeout(timer); } } /** * `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. */ async dispose(options = {}) { // A person quitting ends the active run first, as teardownCurrent() does (senpi#5753). Otherwise // `session_shutdown` tears extension resources down under a running tool and the loop sends that failure // to the model in one more request. Host closes keep their own bounded abort handling. if (options.endActiveRun === true) await this.endActiveRunWithinQuitBudget(options.processExit === true); await emitSessionShutdownEvent(this.session.extensionRunner, { type: "session_shutdown", reason: "quit", ...(this.session.closedOnRequest ? { closed: true } : {}) }, options); this.beforeSessionInvalidate?.(); this.session.dispose(); await this.session.whenToolChildClosed(); this.releaseSessionHold(); } } // A persisted session is written to disk with its first assistant message, so one that has an // assistant message and no file was moved away after it was read. function wasFlushed(sessionManager) { return sessionManager.getEntries().some((entry) => entry.type === "message" && entry.message.role === "assistant"); } function holdActiveSession(sessionManager, expectExisting, holderEndpoint) { const sessionFile = sessionManager.getSessionFile(); if (!sessionManager.isPersisted() || sessionFile === undefined) return undefined; return holdSessionFile(sessionFile, sessionManager.getSessionId(), { cwd: sessionManager.getCwd(), expectExisting, holderEndpoint, }); } /** * 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 async function createAgentSessionRuntime(createRuntime, options) { await assertSessionCwdExists(options.sessionManager, options.cwd); const result = await createRuntime(options); return new AgentSessionRuntime(result.session, result.services, createRuntime, result.diagnostics, result.modelFallbackMessage, options.launchProfile); } export { createAgentSessionFromServices, createAgentSessionServices, } from "./agent-session-services.js"; //# sourceMappingURL=agent-session-runtime.js.map