import { ToolSet } from "ai"; //#region src/experimental/memory/session/types.d.ts /** * Minimal message part shape used by Session internals. * Vercel AI SDK's `UIMessagePart` is structurally compatible. */ interface SessionMessagePart { type: string; text?: string; toolCallId?: string; toolName?: string; input?: unknown; output?: unknown; state?: string; result?: unknown; } /** * Minimal message shape used by Session internals. * Vercel AI SDK's `UIMessage` is structurally compatible — you can pass * `UIMessage` objects directly without conversion. */ interface SessionMessage { id: string; role: string; parts: SessionMessagePart[]; createdAt?: Date; } /** * Options for creating a Session. */ interface SessionOptions { /** Context blocks for the system prompt. */ context?: ContextConfig[]; /** Provider for persisting the frozen system prompt. */ promptStore?: WritableContextProvider; } //#endregion //#region src/experimental/memory/session/provider.d.ts interface SearchResult { id: string; role: string; content: string; createdAt?: string; sessionId?: string; } interface StoredCompaction { id: string; summary: string; fromMessageId: string; toMessageId: string; createdAt: string; } /** * Session storage provider. * Messages are tree-structured via parentId for branching. */ interface SessionProvider { getMessage(id: string): SessionMessage | null; /** * Get conversation as a path from root to leaf. * Applies compaction overlays. If leafId is null, uses the latest leaf. */ getHistory(leafId?: string | null): SessionMessage[]; getLatestLeaf(): SessionMessage | null; getBranches(messageId: string): SessionMessage[]; getPathLength(leafId?: string | null): number; /** * Append a message. Parented to the latest leaf unless parentId is provided. * Idempotent — same message.id twice is a no-op. */ appendMessage(message: SessionMessage, parentId?: string | null): void; updateMessage(message: SessionMessage): void; deleteMessages(messageIds: string[]): void; clearMessages(): void; addCompaction( summary: string, fromMessageId: string, toMessageId: string ): StoredCompaction; getCompactions(): StoredCompaction[]; searchMessages?(query: string, limit?: number): SearchResult[]; } //#endregion //#region src/experimental/memory/session/providers/agent.d.ts interface SqlProvider { sql>( strings: TemplateStringsArray, ...values: (string | number | boolean | null)[] ): T[]; } declare class AgentSessionProvider implements SessionProvider { private agent; private initialized; private sessionId; /** * @param agent - Agent or any object with a `sql` tagged template method * @param sessionId - Optional session ID to isolate multiple sessions in the same DO. * Messages are filtered by session_id within shared tables. */ constructor(agent: SqlProvider, sessionId?: string); private ensureTable; getMessage(id: string): SessionMessage | null; getHistory(leafId?: string | null): SessionMessage[]; getLatestLeaf(): SessionMessage | null; getBranches(messageId: string): SessionMessage[]; getPathLength(leafId?: string | null): number; appendMessage(message: SessionMessage, parentId?: string | null): void; updateMessage(message: SessionMessage): void; deleteMessages(messageIds: string[]): void; clearMessages(): void; addCompaction( summary: string, fromMessageId: string, toMessageId: string ): StoredCompaction; getCompactions(): StoredCompaction[]; searchMessages(query: string, limit?: number): SearchResult[]; private latestLeafRow; private indexFTS; private deleteFTS; private applyCompactions; private parse; private parseRows; } //#endregion //#region src/experimental/memory/session/search.d.ts /** * Storage interface for searchable context. * * - `get()` returns a summary of indexed content (rendered into system prompt) * - `search(query)` full-text search (via search_context tool) * - `set(key, content)` indexes content under a key (via set_context tool) */ interface SearchProvider extends ContextProvider { search(query: string): Promise; set?(key: string, content: string): Promise; } /** * Check if a provider is a SearchProvider (has a `search` method). */ declare function isSearchProvider( provider: unknown ): provider is SearchProvider; /** * SearchProvider backed by Durable Object SQLite with FTS5. * * - `get()` returns a count of indexed entries * - `search(query)` full-text search using FTS5 * - `set(key, content)` indexes or replaces content under a key * * Each instance uses a namespaced FTS5 table to avoid collisions * with the session message search. * * @example * ```ts * Session.create(this) * .withContext("knowledge", { * provider: new AgentSearchProvider(this) * }) * ``` */ declare class AgentSearchProvider implements SearchProvider { private agent; private label; private initialized; constructor(agent: SqlProvider); init(label: string): void; private ensureTable; get(): Promise; search(query: string): Promise; set(key: string, content: string): Promise; private deleteFTS; } //#endregion //#region src/experimental/memory/session/skills.d.ts /** * Storage interface for skill collections. * * - `get()` returns metadata listing (rendered into system prompt) * - `load(key)` fetches full content (via load_context tool) * - `set(key, content, description?)` writes an entry (via set_context tool) */ interface SkillProvider extends ContextProvider { load(key: string): Promise; set?(key: string, content: string, description?: string): Promise; } /** * Check if a provider is a SkillProvider (has a `load` method). */ declare function isSkillProvider(provider: unknown): provider is SkillProvider; /** * SkillProvider backed by an R2 bucket. * * - `get()` returns a metadata listing of all skills (key + description) * - `load(key)` fetches a skill's full content * - `set(key, content, description?)` writes a skill * * Descriptions are pulled from R2 custom metadata (`description` key). * If a prefix is provided, it is prepended on storage operations and * stripped from keys in metadata. * * @example * ```ts * const skills = new R2SkillProvider(env.SKILLS_BUCKET, { prefix: "skills/" }); * ``` */ declare class R2SkillProvider implements SkillProvider { private bucket; private prefix; constructor( bucket: R2Bucket, options?: { prefix?: string; } ); get(): Promise; load(key: string): Promise; set(key: string, content: string, description?: string): Promise; } //#endregion //#region src/experimental/memory/session/context.d.ts /** * Base storage interface for a context block. * A provider with only `get()` is readonly. */ interface ContextProvider { get(): Promise; /** Called by the context system to provide the block label before first use. */ init?(label: string): void; } /** * Writable context provider — extends ContextProvider with `set()`. * Blocks backed by this provider are writable via the `set_context` tool. */ interface WritableContextProvider extends ContextProvider { set(content: string): Promise; } /** * Check if a provider is writable (has a `set` method). */ declare function isWritableProvider( provider: unknown ): provider is WritableContextProvider; /** * Configuration for a context block. */ interface ContextConfig { /** Block label — used as key and in tool descriptions */ label: string; /** Human-readable description (shown to AI in tool) */ description?: string; /** Maximum tokens allowed. Enforced on set. */ maxTokens?: number; /** Storage provider. Determines block behavior: * - ContextProvider (get only) → readonly * - WritableContextProvider (get+set) → writable via set_context * - SkillProvider (get+load+set?) → on-demand via load_context * - SearchProvider (get+search+set?) → searchable via search_context * If omitted, auto-wired to writable SQLite when using builder. */ provider?: | ContextProvider | WritableContextProvider | SkillProvider | SearchProvider; } /** * A loaded context block with computed token count. */ interface ContextBlock { label: string; description?: string; content: string; tokens: number; maxTokens?: number; /** True if provider is writable (has set) */ writable: boolean; /** True if backed by a SkillProvider */ isSkill: boolean; /** True if backed by a SearchProvider */ isSearchable: boolean; } //#endregion //#region src/experimental/memory/utils/compaction-helpers.d.ts /** Prefix for all compaction messages (overlays and summaries) */ declare const COMPACTION_PREFIX = "compaction_"; /** Check if a message is a compaction message */ declare function isCompactionMessage(msg: SessionMessage): boolean; /** * Align a boundary index forward to avoid splitting tool call/result groups. * If the boundary falls between an assistant message with tool calls and its * tool results, move it forward past the results. */ declare function alignBoundaryForward( messages: SessionMessage[], idx: number ): number; /** * Align a boundary index backward to avoid splitting tool call/result groups. * If the boundary falls in the middle of tool results, move it backward to * include the assistant message that made the calls. */ declare function alignBoundaryBackward( messages: SessionMessage[], idx: number ): number; /** * Find the compression end boundary using a token budget for the tail. * Walks backward from the end, accumulating tokens until budget is reached. * Returns the index where compression should stop (everything from this * index onward is protected). * * @param messages All messages * @param headEnd Index where the protected head ends (compression starts here) * @param tailTokenBudget Maximum tokens to keep in the tail * @param minTailMessages Minimum messages to protect in the tail (fallback) */ declare function findTailCutByTokens( messages: SessionMessage[], headEnd: number, tailTokenBudget?: number, minTailMessages?: number ): number; /** * Fix orphaned tool call/result pairs after compaction. * * Two failure modes: * 1. Tool result references a call_id whose assistant tool_call was removed * → Remove the orphaned result * 2. Assistant has tool_calls whose results were dropped * → Add stub results so the API doesn't error * * @param messages Messages after compaction * @returns Sanitized messages with no orphaned pairs */ declare function sanitizeToolPairs( messages: SessionMessage[] ): SessionMessage[]; /** * Compute a summary token budget based on the content being compressed. * 20% of the compressed content, clamped to 2K-8K tokens. */ declare function computeSummaryBudget(messages: SessionMessage[]): number; /** * Build a prompt for LLM summarization of compressed messages. * * @param messages Messages to summarize * @param previousSummary Previous summary for iterative updates (or null for first compaction) * @param budget Target token count for the summary */ declare function buildSummaryPrompt( messages: SessionMessage[], previousSummary: string | null, budget: number ): string; /** * Result of a compaction function — describes the overlay to store. */ interface CompactResult { /** First message ID in the compacted range */ fromMessageId: string; /** Last message ID in the compacted range */ toMessageId: string; /** Summary text to store as the overlay */ summary: string; } interface CompactOptions { /** * Function to call the LLM for summarization. * Takes a user prompt string, returns the LLM's text response. */ summarize: (prompt: string) => Promise; /** Number of head messages to protect (default: 2) */ protectHead?: number; /** Token budget for tail protection (default: 20000) */ tailTokenBudget?: number; /** Minimum tail messages to protect (default: 2) */ minTailMessages?: number; } /** * Reference compaction implementation. * * Implements the full hermes-style compaction algorithm: * 1. Protect head messages (first N) * 2. Protect tail by token budget (walk backward) * 3. Align boundaries to tool call groups * 4. Summarize middle section with LLM (structured format) * 5. Sanitize orphaned tool pairs * 6. Iterative summary updates on subsequent compactions * * @example * ```typescript * import { createCompactFunction } from "agents/experimental/memory/utils"; * * const session = new Session(provider, { * compaction: { * tokenThreshold: 100000, * fn: createCompactFunction({ * summarize: (prompt) => generateText({ model, prompt }).then(r => r.text) * }) * } * }); * ``` */ declare function createCompactFunction( opts: CompactOptions ): (messages: SessionMessage[]) => Promise; //#endregion export { SessionOptions as A, AgentSessionProvider as C, StoredCompaction as D, SessionProvider as E, SessionMessage as O, isSearchProvider as S, SearchResult as T, R2SkillProvider as _, alignBoundaryForward as a, AgentSearchProvider as b, createCompactFunction as c, sanitizeToolPairs as d, ContextBlock as f, isWritableProvider as g, WritableContextProvider as h, alignBoundaryBackward as i, SessionMessagePart as k, findTailCutByTokens as l, ContextProvider as m, CompactOptions as n, buildSummaryPrompt as o, ContextConfig as p, CompactResult as r, computeSummaryBudget as s, COMPACTION_PREFIX as t, isCompactionMessage as u, SkillProvider as v, SqlProvider as w, SearchProvider as x, isSkillProvider as y }; //# sourceMappingURL=compaction-helpers-CzCq1-fF.d.ts.map