import { IAIProvider, IContextWindowState, IHistoryEntry, IHookTypeExecutor, ISpinner, ITerminalOutput, IToolSchema, IToolWithEventService, IUserInteraction, Robota, TModelEffort, TPermissionMode, TSessionEndReason, TToolArgs, TUniversalMessage, TUniversalValue } from "@robota-sdk/agent-core"; import { ICompactEvent, TCompactTrigger } from "@robota-sdk/agent-interface-transport"; //#region src/context-window-tracker.d.ts /** Auto-compact when context usage reaches this fraction */ declare const AUTO_COMPACT_THRESHOLD = 0.835; type TAutoCompactThreshold = number | false; declare class ContextWindowTracker { private contextUsedTokens; private readonly contextMaxTokens; private autoCompactThreshold; constructor(model: string, contextMaxTokens?: number, autoCompactThreshold?: TAutoCompactThreshold); /** Get current context window state */ getContextState(): IContextWindowState; /** Whether auto-compaction threshold has been exceeded */ shouldAutoCompact(): boolean; /** The auto-compaction policy for this tracker. */ getAutoCompactThreshold(): TAutoCompactThreshold; /** Update the auto-compaction policy for this tracker. */ setAutoCompactThreshold(autoCompactThreshold: TAutoCompactThreshold): void; /** * Estimate token usage from conversation history. * * Uses the shared core estimator (`estimateContextTokensFromMessages`) so session display, * /context, auto-compact, and core execution guards reason about the same effective token state. * That estimator prefers the provider's actual reported token count (which includes the system * prompt and tool schemas) over a raw serialized-history char heuristic, falling back to the * serialized estimate only when no provider usage is present on the latest message. */ updateFromHistory(history: TUniversalMessage[]): void; /** Reset token tracking */ reset(): void; } //#endregion //#region src/session-logger.d.ts /** * Session Logger — pluggable logging interface for session events. * * ISessionLogger defines the contract. FileSessionLogger is the default * implementation that writes JSONL to disk. Consumers can implement their * own (e.g., remote, database, silent) and inject via Session constructor. */ /** Session log event data — extensible record of event metadata. */ type TSessionLogValue = string | number | boolean | object | null | undefined; type TSessionLogData = Record; interface IExternalPayloadReference { kind: 'external-payload'; encoding: 'json'; sha256: string; byteLength: number; relativePath: string; } interface IFileSessionLoggerOptions { externalPayloadThresholdBytes?: number; redactedValue?: string; } /** * Session logger interface — injected into Session for pluggable logging. * * Implementations decide where and how to persist session events. * The Session class calls log() for every significant action. */ interface ISessionLogger { /** Log a session event with structured data. */ log(sessionId: string, event: string, data: TSessionLogData): void; } /** * File-based session logger — writes JSONL to {logDir}/{sessionId}.jsonl. * * This is the default implementation used by the CLI. * Each line is a self-contained JSON object with timestamp, sessionId, event, and data. */ declare class FileSessionLogger implements ISessionLogger { private readonly logDir; private readonly options; constructor(logDir: string, options?: IFileSessionLoggerOptions); log(sessionId: string, event: string, data: TSessionLogData): void; } /** No-op logger — used when logging is disabled. */ declare class SilentSessionLogger implements ISessionLogger { log(): void; } //#endregion //#region src/permission-types.d.ts /** * Permission handler result: * - true: allow this invocation * - false: deny this invocation * - 'allow-session': allow this invocation and auto-approve this tool for the rest of the session * - 'allow-project': allow this invocation and persist the approval to .robota/settings.local.json */ type TPermissionResult = boolean | 'allow-session' | 'allow-project'; /** * Custom permission handler — called when a tool needs user approval. * Returns true to allow, false to deny, or 'allow-session' to remember for the session. */ type TPermissionHandler = (toolName: string, toolArgs: TToolArgs) => Promise; interface IPermissionEnforcerOptions { sessionId: string; cwd: string; getPermissionMode: () => TPermissionMode; config: { permissions: { allow: string[]; deny: string[]; }; hooks?: Record; }; terminal: ITerminalOutput; permissionHandler?: TPermissionHandler; promptForApprovalFn?: (terminal: ITerminalOutput, toolName: string, toolArgs: TToolArgs) => Promise; sessionLogger?: ISessionLogger; onToolExecution?: (event: { type: 'start' | 'end'; toolName: string; toolArgs?: TToolArgs; success?: boolean; denied?: boolean; toolResultData?: string; executionId?: string; }) => void; /** Additional hook type executors (e.g. prompt, agent) beyond the core defaults. */ hookTypeExecutors?: IHookTypeExecutor[]; /** Absolute path to session transcript file — passed to PreToolUse hook inputs as transcript_path */ transcriptPath?: string; /** Called when the user selects "allow for project" — persists the tool pattern to project settings. */ onProjectAllowTool?: (toolName: string) => void; } //#endregion //#region src/permission-enforcer.d.ts declare class PermissionEnforcer { private readonly sessionId; private readonly cwd; private readonly getPermissionMode; private readonly config; private readonly terminal; private readonly permissionHandler?; private readonly promptForApprovalFn?; private readonly sessionLogger?; private readonly onToolExecution?; private readonly hookTypeExecutors?; private readonly transcriptPath?; private readonly sessionAllowedTools; private readonly onProjectAllowTool?; constructor(options: IPermissionEnforcerOptions); /** Wrap all tools with permission checking */ wrapTools(tools: IToolWithEventService[]): IToolWithEventService[]; /** Get tools that have been session-approved (via "Allow always" choice). */ getSessionAllowedTools(): string[]; /** Clear all session-scoped allow rules. */ clearSessionAllowedTools(): void; /** * Wrap a tool with permission checking. * The wrapper intercepts execute() and runs permission evaluation before delegating. * If denied, returns a tool result indicating the action was blocked. */ private wrapToolWithPermission; /** Evaluate permission for a tool call using the current mode and config */ checkPermission(toolName: string, toolArgs: TToolArgs): Promise; /** Delegate session event to the injected logger. */ private log; } //#endregion //#region src/session-base.d.ts declare abstract class SessionBase { protected abstract readonly robota: Robota; protected abstract readonly permissionEnforcer: PermissionEnforcer; protected abstract readonly contextTracker: ContextWindowTracker; protected abstract permissionMode: TPermissionMode; protected abstract activePresetId: string; protected abstract parallelSubagentsEnabled: boolean; protected abstract readonly sessionId: string; protected abstract readonly aiProvider: IAIProvider; protected abstract readonly toolSchemas: IToolSchema[]; protected abstract model: string; protected abstract systemMessage: string; protected abstract messageCount: number; protected abstract abortController: AbortController | null; getPermissionMode(): TPermissionMode; /** Change the active permission mode — future tool calls will use the new mode. */ setPermissionMode(mode: TPermissionMode): void; /** Read the active preset id (PRESET-011 runtime state). */ getActivePresetId(): string; /** * Set the active preset id. PURE STATE — this only records which preset is active; * it does not re-apply any preset options (permission/model/persona). Higher layers * own re-application (PRESET-012/013/014). */ setActivePresetId(id: string): void; /** Whether subagent dispatch is currently allowed for this session (PRESET-016 runtime gate). */ getParallelSubagentsEnabled(): boolean; /** Toggle subagent dispatch live. Only effective if the agent runtime was built at assembly. */ setParallelSubagentsEnabled(enabled: boolean): void; getSessionId(): string; getSystemMessage(): string; /** * Replace the active system message and propagate it so the next provider request carries it. * Records the live value on `this.systemMessage` (re-injected on compaction) and delegates to * `Robota.updateSystemPrompt`, which updates the single-source `config.systemMessage` and the live * conversation store head. The system prompt is an agent-level concern, not model config, so this * does not route through `setModel`. Used by persona application, the self-verification toggle, and * AGENTS.md/CLAUDE.md staleness refresh. */ updateSystemMessage(newMessage: string): void; /** * Re-apply model options to the live session (PRESET-013 model/effort re-application seam). * * Propagates model/effort/temperature/maxOutputTokens to the agent via `robota.setModel` so the * next call reflects them, and updates `this.model` to keep `getModelId()` accurate. The preset * `maxOutputTokens` field maps to the agent's `maxTokens` channel. Absent fields are left untouched. */ applyModelOptions(options: { model?: string; effort?: TModelEffort; temperature?: number; maxOutputTokens?: number; }): Promise; getToolSchemas(): IToolSchema[]; getMessageCount(): number; /** Get tools that have been session-approved (via "Allow always" choice). */ getSessionAllowedTools(): string[]; clearSessionAllowedTools(): void; /** Abort the currently running execution. No-op if nothing is running. */ abort(): void; isRunning(): boolean; getContextState(): IContextWindowState; /** Estimate context usage from current conversation history (used after session restore). */ syncContextFromHistory(): void; getAutoCompactThreshold(): TAutoCompactThreshold; setAutoCompactThreshold(threshold: number | false): void; getHistory(): TUniversalMessage[]; getFullHistory(): IHistoryEntry[]; getSessionTokenUsage(): { inputTokens: number; outputTokens: number; } | undefined; getModelId(): string; /** Add an event entry to history (not a chat message) */ addHistoryEntry(entry: IHistoryEntry): void; /** Inject a message into conversation history without execution (used for session restore). */ injectMessage(role: 'user' | 'assistant' | 'system' | 'tool', content: string, options?: { toolCallId?: string; name?: string; }): void; /** * Inject a full TUniversalMessage preserving all fields (toolCalls, toolCallId, null content). * Used during session restore to correctly reconstruct tool_use+tool_result pairs. */ injectRawMessage(msg: TUniversalMessage): void; clearHistory(): void; } //#endregion //#region src/session-store.d.ts /** A persisted session record */ interface ISessionRecord { /** Unique session identifier */ id: string; /** Optional human-readable session name */ name?: string; /** Working directory when the session was created */ cwd: string; /** ISO-8601 creation timestamp */ createdAt: string; /** ISO-8601 last-updated timestamp */ updatedAt: string; /** Conversation messages (opaque to the store) */ messages: unknown[]; /** Full UI timeline (chat + events) for rendering restoration */ history?: unknown[]; /** Exact system prompt used to create the session. */ systemPrompt?: string; /** Tool schemas registered for the session. */ toolSchemas?: IToolSchema[]; /** Latest background task snapshots for resume/debugging. */ backgroundTasks?: unknown[]; /** Durable non-streaming background task events for resume/debugging. */ backgroundTaskEvents?: unknown[]; /** Latest background job group snapshots for resume/debugging. */ backgroundJobGroups?: unknown[]; /** Durable background job group events for resume/debugging. */ backgroundJobGroupEvents?: unknown[]; /** Durable skill activation events for resume/debugging. */ skillActivationEvents?: unknown[]; /** Durable automatic memory events for resume/debugging. */ memoryEvents?: unknown[]; /** Memory references used by the latest prompt turn. */ usedMemoryReferences?: unknown[]; /** SDK-owned context reference inventory for resume/debugging. */ contextReferences?: unknown[]; /** Provider sandbox snapshot identifier for workspace hydration on resume. */ sandboxSnapshotId?: string; } /** Minimal persistence port consumed by Session. */ interface ISessionStore { save(session: ISessionRecord): void; load(id: string): ISessionRecord | undefined; list(): ISessionRecord[]; delete(id: string): void; /** Return the absolute file path for a session file, if the store is file-backed. */ getFilePath?(id: string): string; } /** * Persistent session store backed by individual JSON files. * * Construct with a custom `baseDir` to redirect storage (useful in tests). */ declare class SessionStore implements ISessionStore { private readonly baseDir; constructor(baseDir?: string); /** Ensure the storage directory exists */ private ensureDir; /** Absolute path to a session's JSON file */ private filePath; /** Return the absolute file path for a session — implements ISessionStore.getFilePath */ getFilePath(id: string): string; /** * Persist a session record to disk atomically (CORE-019). * Creates the storage directory if needed. * * Bytes go to a same-directory temp file first, then move into place with rename — * a crash mid-write can therefore never leave a truncated JSON where the previous * record used to be. Same-directory is load-bearing: cross-device rename is a copy. */ save(session: ISessionRecord): void; /** * Load a session by its ID. * Returns `undefined` when the session file does not exist or is corrupt. */ load(id: string): ISessionRecord | undefined; /** * List all persisted sessions, sorted by `updatedAt` descending (most recent first). */ list(): ISessionRecord[]; /** * Delete a session by its ID. * No-ops silently if the session does not exist. */ delete(id: string): void; } //#endregion //#region src/session-types.d.ts /** Options for graceful session shutdown. */ interface ISessionShutdownOptions { reason?: TSessionEndReason; } /** Options for constructing a Session */ interface ISessionOptions { /** Pre-constructed tools to register with the agent */ tools: IToolWithEventService[]; /** Pre-constructed AI provider */ provider: IAIProvider; /** Pre-built system message string */ systemMessage: string; /** Terminal I/O for permission prompts */ terminal: ITerminalOutput; /** Permission and hook configuration */ permissions?: { allow: string[]; deny: string[]; }; hooks?: Record; /** Initial permission mode */ permissionMode?: TPermissionMode; /** * Injected "ask the user" port (CMD-005): forwarded into the agent config so model-invoked tools * (AskUserQuestion) can solicit a structured answer. Absent in headless/automation sessions. */ ask?: IUserInteraction['ask']; /** Default trust level — used to derive permissionMode if not given */ defaultTrustLevel?: 'safe' | 'moderate' | 'full'; /** Active preset id selected at startup (PRESET-011 runtime state). Defaults to 'default'. */ activePresetId?: string; /** * Whether subagent dispatch is allowed for this session (PRESET-016 runtime gate). Defaults to * true (current behavior). Only meaningful when the agent runtime was built at assembly. */ enableParallelSubagents?: boolean; /** Model name (for context window sizing and Robota config) */ model?: string; /** Provider idle timeout in milliseconds for each model call */ providerTimeout?: number; /** Maximum number of agentic turns per run() call. Undefined = unlimited. */ maxTurns?: number; /** Optional session store for persistence */ sessionStore?: ISessionStore; /** Override session ID (used when resuming a session to reuse the original ID) */ sessionId?: string; /** Custom permission handler (overrides terminal-based prompts, used by Ink UI) */ permissionHandler?: TPermissionHandler; /** Called when the user selects "allow for project" — persists the tool pattern to project settings. */ onProjectAllowTool?: (toolName: string) => void; /** Callback for text deltas — enables streaming text to the UI in real-time */ onTextDelta?: (delta: string) => void; /** Callback when context window usage is refreshed */ onContextUpdate?: (state: IContextWindowState) => void; /** Custom prompt-for-approval function (injected from CLI) */ promptForApproval?: (terminal: ITerminalOutput, toolName: string, toolArgs: TToolArgs) => Promise; /** Callback when a tool starts or finishes execution — enables real-time tool display in UI */ onToolExecution?: (event: { type: 'start' | 'end'; toolName: string; toolArgs?: TToolArgs; success?: boolean; denied?: boolean; toolResultData?: string; executionId?: string; }) => void; /** Callback when context is compacted */ onCompact?: (summary: string) => void; /** Callback with structured compaction metadata */ onCompactEvent?: (event: ICompactEvent) => void; /** Instructions to include in the compaction prompt (e.g. from CLAUDE.md) */ compactInstructions?: string; /** Override context max tokens (otherwise derived from model name) */ contextMaxTokens?: number; /** Auto-compact threshold as a 0-1 fraction. Set false to disable automatic compaction. */ autoCompactThreshold?: TAutoCompactThreshold; /** Session logger — injected for pluggable session event logging. */ sessionLogger?: ISessionLogger; /** Additional hook type executors (e.g. prompt, agent) beyond the core defaults. */ hookTypeExecutors?: IHookTypeExecutor[]; /** Name reported to the Robota agent config. Defaults to 'agent' if not provided. */ agentName?: string; /** Request structured output from the provider for this session. */ responseFormat?: { type: 'text' | 'json_object'; }; /** * Reasoning-effort dial threaded to the Robota agent config and on to the provider * request builder. When unset, the framework→provider seam defaults it to `'high'`. */ effort?: TModelEffort; } //#endregion //#region src/session.d.ts /** Wraps a Robota agent with project context, permission state, and optional persistence. */ declare class Session extends SessionBase { protected readonly robota: Robota; protected readonly permissionEnforcer: PermissionEnforcer; protected readonly contextTracker: ContextWindowTracker; protected permissionMode: TPermissionMode; protected activePresetId: string; protected parallelSubagentsEnabled: boolean; protected readonly sessionId: string; protected aiProvider: IAIProvider; protected readonly toolSchemas: IToolSchema[]; protected model: string; protected systemMessage: string; protected messageCount: number; protected abortController: AbortController | null; private readonly terminal; private readonly sessionStore?; private readonly cwd; private readonly hooks?; private readonly hookTypeExecutors?; private readonly onTextDeltaCallback?; private readonly onContextUpdateCallback?; private readonly onToolExecutionCallback?; private readonly onCompactCallback?; private readonly onCompactEventCallback?; private readonly sessionLogger?; private readonly maxTurns?; private readonly compactionOrchestrator; private shutdownPromise; /** Stdout collected from SessionStart hooks, injected on first run(). */ private sessionStartStdout; /** Absolute path to the session transcript file, if file-backed storage is active. */ private readonly transcriptPath; constructor(options: ISessionOptions); run(message: string, rawInput?: string): Promise; private log; private persistSessionInternal; /** * Gracefully end the session and fire SessionEnd hooks once — **best-effort** (CORE-013 * disposal convention): never rejects, so `void session.shutdown()` cannot become an * unhandled rejection. Step failures are recorded to the session log and remaining steps * still run. */ shutdown(options?: ISessionShutdownOptions): Promise; swapProvider(newProvider: IAIProvider, model: string): void; compact(instructions?: string, trigger?: TCompactTrigger): Promise; private buildRunContext; } //#endregion //#region src/compaction-orchestrator.d.ts /** * Thrown when a compaction summary is invalid (non-string or empty provider content). * Conversation history is append-only source data — callers must not clear or replace * it when this is thrown (see SPEC § Compaction Failure Contract). */ declare class CompactionError extends Error { constructor(message: string); } interface ICompactionOptions { sessionId: string; cwd: string; model: string; hooks?: Record; compactInstructions?: string; /** Additional hook type executors (e.g. prompt, agent) beyond the core defaults. */ hookTypeExecutors?: IHookTypeExecutor[]; } declare class CompactionOrchestrator { private readonly sessionId; private readonly cwd; private readonly model; private readonly hooks?; private readonly compactInstructions?; private readonly hookTypeExecutors?; constructor(options: ICompactionOptions); /** * Run compaction — summarize the conversation to free context space. * @param provider - The AI provider to use for summarization * @param history - Current conversation history * @param instructions - Optional focus instructions for the summary * @returns The generated summary string (always a non-empty string) * @throws {CompactionError} when the provider returns a non-string or empty summary — * callers must leave the conversation history untouched in that case */ compact(provider: IAIProvider, history: TUniversalMessage[], instructions?: string): Promise; /** Build the compaction prompt from conversation history */ private buildCompactionPrompt; } //#endregion //#region src/session-log-events.d.ts /** * INFRA-017: typed contract for session-log event names + replay keys (SSOT). * * The `FileSessionLogger` writes JSONL lines `{ timestamp, sessionId, event, ...data }`. The event * names were previously implicit string literals scattered across the session/execution code. This * module names them once so the writer, the replay validator (`session-log-validation.ts`), and the * session-log replay provider (INFRA-017 / TEST-008) share one type-safe schema — without changing * what is written (it formalizes the existing format, it does not add a new one). * * The **replay substrate** is the provider/tool execution layer, keyed deterministically: * a `provider_request` (executionId + round) is answered by its recorded * `provider_native_raw_payload` / `provider_response_normalized`; a `tool_execution_request` * (executionId + toolCallId) by its `tool_execution_result`. `validateSessionReplayLogEntries` * proves a log carries all of these (i.e. is replay-complete). */ /** Canonical session-log event names. */ declare const SESSION_LOG_EVENT: { readonly sessionInit: "session_init"; readonly sessionShutdown: "session_shutdown"; readonly context: "context"; readonly contextCompact: "context_compact"; readonly error: "error"; readonly historyMutation: "history_mutation"; readonly providerRequest: "provider_request"; readonly providerNativeRawPayload: "provider_native_raw_payload"; readonly providerResponseRaw: "provider_response_raw"; readonly providerResponseNormalized: "provider_response_normalized"; readonly toolExecutionRequest: "tool_execution_request"; readonly toolExecutionResult: "tool_execution_result"; readonly user: "user"; readonly preRun: "pre_run"; readonly textDelta: "text_delta"; readonly assistant: "assistant"; readonly toolCall: "tool_call"; readonly toolResult: "tool_result"; readonly toolBlocked: "tool_blocked"; readonly toolDenied: "tool_denied"; readonly serverTool: "server_tool"; }; type TSessionLogEventName = (typeof SESSION_LOG_EVENT)[keyof typeof SESSION_LOG_EVENT]; /** Common envelope written for every line by `FileSessionLogger`. */ interface ISessionLogLine { readonly timestamp: string; readonly sessionId: string; readonly event: string; readonly [key: string]: unknown; } /** Replay correlation key for a provider call. */ interface IProviderEventKey { readonly executionId: string; readonly round: number; } /** Replay correlation key for a tool execution. */ interface IToolEventKey { readonly executionId: string; readonly toolCallId: string; } /** Narrow a raw log line to a specific event name. */ declare function isSessionLogEvent(line: ISessionLogLine, name: TName): line is ISessionLogLine & { event: TName; }; //#endregion //#region src/session-log-validation.d.ts interface ISessionReplayValidationIssue { code: 'PROVIDER_RESPONSE_RAW_MISSING' | 'PROVIDER_NATIVE_RAW_PAYLOAD_MISSING' | 'PROVIDER_RESPONSE_NORMALIZED_MISSING' | 'TOOL_RESULT_MISSING' | 'PAYLOAD_REFERENCE_INVALID'; message: string; eventIndex?: number; executionId?: string; round?: number; toolCallId?: string; } interface ISessionReplayValidationResult { ok: boolean; issues: ISessionReplayValidationIssue[]; } declare function validateSessionReplayLogEntries(entries: readonly ISessionLogEntry[]): ISessionReplayValidationResult; //#endregion //#region src/session-log-replay.d.ts interface ISessionLogEntry extends Record { timestamp: string; sessionId: string; event: string; } interface ISessionReplayRecord { sessionId: string | undefined; cwd: string | undefined; createdAt: string | undefined; updatedAt: string | undefined; messages: TUniversalMessage[]; history: IHistoryEntry[]; backgroundTaskEvents: object[]; backgroundJobGroupEvents: object[]; memoryEvents: object[]; } declare function loadSessionLogEntries(logFile: string): ISessionLogEntry[]; declare function replaySessionLogEntries(entries: readonly ISessionLogEntry[]): ISessionReplayRecord; //#endregion export { AUTO_COMPACT_THRESHOLD, CompactionError, CompactionOrchestrator, ContextWindowTracker, FileSessionLogger, type IExternalPayloadReference, type IFileSessionLoggerOptions, type IProviderEventKey, type ISessionLogEntry, type ISessionLogLine, type ISessionLogger, type ISessionOptions, type ISessionRecord, type ISessionReplayRecord, type ISessionReplayValidationIssue, type ISessionReplayValidationResult, type ISessionShutdownOptions, type ISessionStore, type ISpinner, type ITerminalOutput, type IToolEventKey, PermissionEnforcer, SESSION_LOG_EVENT, Session, SessionStore, SilentSessionLogger, type TAutoCompactThreshold, type TPermissionHandler, type TPermissionResult, type TSessionLogData, type TSessionLogEventName, type TSessionLogValue, isSessionLogEvent, loadSessionLogEntries, replaySessionLogEntries, validateSessionReplayLogEntries }; //# sourceMappingURL=index.d.ts.map