export { B as BULK_DELETE_MAX_THREADS, C as ChatStoreInputError, t as threadTitleFromMessage } from '../core-7qIM7svy.js';
import { g as ChatMessagePart } from '../parts-IB-Kbb7z.js';
export { C as ChatAttachmentKind, a as ChatAttachmentPart, b as ChatFilePart, c as ChatImagePart, d as ChatInteractionPart, e as ChatMentionKind, f as ChatMentionPart, h as ChatNoticePart, i as ChatPartTime, j as ChatPlanPart, k as ChatReasoningPart, l as ChatStepFinishPart, m as ChatStepStartPart, n as ChatSubtaskPart, o as ChatTextPart, p as ChatToolPart, q as ChatToolState, r as ChatToolStatus, s as ChatUsageTokens, D as DEFAULT_ATTACHMENT_PROMPT_HEADER, S as StorableHarnessPartKind, t as attachmentInputToPart, u as attachmentKindForMime, v as attachmentPartsFromMessageParts, w as buildAttachmentPromptBlock, x as historyContentWithAttachments, y as isChatAttachmentPart, z as isChatInteractionPart, A as isChatMentionPart, B as isChatPlanPart, E as isChatStepFinishPart, F as isChatTextPart, G as isChatToolPart, H as mentionInputToPart, I as mentionPartsFromMessageParts, J as toChatMessageParts } from '../parts-IB-Kbb7z.js';
import * as drizzle_orm from 'drizzle-orm';
import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
import { SQLiteColumnBuilderBase, AnySQLiteTable, AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
export { d as attachmentPartKey } from '../stream-normalizer-DWvtmY6F.js';
import '@tangle-network/agent-interface';
import '../contract-KfqJh_au.js';
import '../plans/index.js';

/** A product table referenced by FK — only the `id` column is touched. */
type ChatParentTable = AnySQLiteTable & {
    id: AnySQLiteColumn;
};
interface CreateChatTablesOptions<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}> {
    /** The product's workspace table — threads reference `workspaceTable.id`
     *  with cascade. Omitted: `workspace_id` stays a plain indexed text column
     *  (products whose tenant table lives in another database). */
    workspaceTable?: ChatParentTable;
    /** Prefixes table AND index names (`'chat_'` → `chat_thread`,
     *  `idx_chat_thread_workspace`) for products that namespace chat tables in a
     *  shared database. Default: unprefixed `thread`/`message` (legal/gtm row
     *  compatibility). */
    tablePrefix?: string;
    /** Product columns merged into the thread table (the `/missions` extras
     *  pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */
    threadExtraColumns?: TThreadExtras;
    /** Product columns merged into the message table — e.g. legal's
     *  `vault_files`. */
    messageExtraColumns?: TMessageExtras;
}
declare function createChatTables<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}>(options?: CreateChatTablesOptions<TThreadExtras, TMessageExtras>): {
    threads: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
        name: `${string}thread`;
        schema: undefined;
        columns: {
            id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
            workspaceId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"workspace_id", [string, ...string[]], number | undefined>>;
            title: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"title", [string, ...string[]], number | undefined>>;
            category: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"category", [string, ...string[]], number | undefined>;
            isPinned: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteBooleanBuilderInitial<"is_pinned">>>;
            createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
            updatedAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"updated_at">>>;
        } & TThreadExtras extends infer T extends Record<string, drizzle_orm.ColumnBuilderBase<drizzle_orm.ColumnBuilderBaseConfig<drizzle_orm.ColumnDataType, string>, object>> ? { [Key in keyof T]: drizzle_orm.BuildColumn<TTableName, {
            _: Omit<T[Key]["_"], "name"> & {
                name: T[Key]["_"]["name"] extends "" ? drizzle_orm.Assume<Key, string> : T[Key]["_"]["name"];
            };
        }, TDialect>; } : never;
        dialect: "sqlite";
    }>;
    messages: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
        name: `${string}message`;
        schema: undefined;
        columns: {
            id: drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"id", [string, ...string[]], number | undefined>>>>;
            threadId: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"thread_id", [string, ...string[]], number | undefined>>;
            role: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"role", ["user", "assistant", "system", "tool"], number | undefined>>;
            content: drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"content", [string, ...string[]], number | undefined>>;
            parts: drizzle_orm.HasDefault<drizzle_orm.$Type<drizzle_orm_sqlite_core.SQLiteTextJsonBuilderInitial<"parts">, ChatMessagePart[]>>;
            toolName: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"tool_name", [string, ...string[]], number | undefined>;
            model: drizzle_orm_sqlite_core.SQLiteTextBuilderInitial<"model", [string, ...string[]], number | undefined>;
            inputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"input_tokens">;
            outputTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"output_tokens">;
            reasoningTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"reasoning_tokens">;
            cacheReadTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_read_tokens">;
            cacheWriteTokens: drizzle_orm_sqlite_core.SQLiteIntegerBuilderInitial<"cache_write_tokens">;
            costUsd: drizzle_orm_sqlite_core.SQLiteRealBuilderInitial<"cost_usd">;
            createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_sqlite_core.SQLiteTimestampBuilderInitial<"created_at">>>;
        } & TMessageExtras extends infer T_1 extends Record<string, drizzle_orm.ColumnBuilderBase<drizzle_orm.ColumnBuilderBaseConfig<drizzle_orm.ColumnDataType, string>, object>> ? { [Key_1 in keyof T_1]: drizzle_orm.BuildColumn<TTableName, {
            _: Omit<T_1[Key_1]["_"], "name"> & {
                name: T_1[Key_1]["_"]["name"] extends "" ? drizzle_orm.Assume<Key_1, string> : T_1[Key_1]["_"]["name"];
            };
        }, TDialect>; } : never;
        dialect: "sqlite";
    }>;
};
/**
 * The base (no-extras) table pair, pinned via an instantiation expression:
 * `ReturnType<typeof createChatTables>` on the bare generic substitutes the
 * extras params with their CONSTRAINT (`Record<string,
 * SQLiteColumnBuilderBase>`), stamping an index signature into the column map
 * that widens every concrete column to `unknown`/`notNull: false` — concrete
 * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`
 * is non-generic, so its plain `ReturnType` never hits this.)
 */
type ChatTables = ReturnType<typeof createChatTables<{}, {}>>;
type ChatThreadRow = ChatTables['threads']['$inferSelect'];
type ChatMessageRow = ChatTables['messages']['$inferSelect'];
type NewChatThreadRow = ChatTables['threads']['$inferInsert'];
type NewChatMessageRow = ChatTables['messages']['$inferInsert'];

/**
 * Typed CRUD over the tables from `createChatTables`. Works against any
 * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,
 * never `.run()`/`.all()`, so sync and async drivers behave identically.
 *
 * Access control is an injected seam, never an import: single-thread routes
 * check workspace access themselves (they know the thread), while
 * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request
 * can span workspaces — it is called once per distinct workspace and any
 * throw rejects the whole request before a single delete runs (fail-closed;
 * legal's bulk-delete semantics).
 *
 * Deletes run messages-first in ONE `db.batch` round trip when the driver has
 * one (D1, libsql), so a partial failure never leaves orphaned rows behind a
 * deleted thread; drivers without `batch` (better-sqlite3) fall back to
 * sequential awaits in the same order.
 */

/** Any SQLite drizzle database — `any` erases the driver-specific run-result
 *  and schema generics so better-sqlite3, D1, and libsql handles all fit.
 *  `batch` is structural: present on D1/libsql drizzle instances. */
type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> & {
    batch?: (statements: [unknown, ...unknown[]]) => Promise<unknown[]>;
};
/** Product-injected access check. Throw to deny; the store never interprets
 *  users or roles itself. */
type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>;
interface ListThreadsInput {
    workspaceId: string;
    /** Clamped to 1..200; default 50 (legal's list route semantics). */
    limit?: number;
    /** Clamped to >= 0; default 0. */
    offset?: number;
}
interface ListThreadsResult<TThread = ChatThreadRow> {
    threads: TThread[];
    total: number;
    limit: number;
    offset: number;
}
interface CreateThreadInput {
    workspaceId: string;
    /** Title source when `title` is absent: first non-empty line, 80-char cap
     *  (`threadTitleFromMessage`). */
    firstMessage?: string;
    /** Explicit title; still normalized through `threadTitleFromMessage` so a
     *  multi-page paste never becomes a sidebar entry. */
    title?: string;
    category?: string | null;
    isPinned?: boolean;
    /** Opaque product-column values written verbatim in the SAME insert (the
     *  `/missions` extras pattern). Never read, validated, or defaulted here. */
    extras?: Record<string, unknown>;
}
interface AppendMessageInput {
    threadId: string;
    role: 'user' | 'assistant' | 'system' | 'tool';
    content: string;
    parts?: ChatMessagePart[];
    toolName?: string | null;
    model?: string | null;
    inputTokens?: number | null;
    outputTokens?: number | null;
    reasoningTokens?: number | null;
    cacheReadTokens?: number | null;
    cacheWriteTokens?: number | null;
    costUsd?: number | null;
    /** Opaque product-column values written verbatim in the SAME insert. */
    extras?: Record<string, unknown>;
}
interface ListMessagesOptions {
    limit?: number;
    offset?: number;
}
interface BulkDeleteThreadsInput {
    ids: string[];
    /** Called once per distinct workspace the ids touch, before ANY delete. */
    assertAccess: WorkspaceAccessCheck;
}
interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {
    listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>;
    getThread(threadId: string): Promise<TThread | null>;
    createThread(input: CreateThreadInput): Promise<TThread>;
    renameThread(threadId: string, title: string): Promise<TThread | null>;
    pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>;
    /** Messages + thread in one batch. Resolves false when the thread does not
     *  exist. `assertAccess` (optional) receives the thread's workspaceId before
     *  the delete — single-thread callers usually check access themselves. */
    deleteThread(threadId: string, options?: {
        assertAccess?: WorkspaceAccessCheck;
    }): Promise<boolean>;
    bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{
        deleted: number;
    }>;
    /** Ordered oldest-first: `created_at`, then rowid (insertion order within a
     *  same-second burst — a user+assistant pair lands in one epoch second). */
    listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>;
    /** Inserts the message and bumps the thread's `updatedAt` in one batch so
     *  workspace recency sorts stay truthful. */
    appendMessage(input: AppendMessageInput): Promise<TMessage>;
}
declare function createChatStore<TTables extends ChatTables>(db: ChatDatabase, tables: TTables): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']>;

export { type AppendMessageInput, type BulkDeleteThreadsInput, type ChatDatabase, ChatMessagePart, type ChatMessageRow, type ChatParentTable, type ChatStore, type ChatTables, type ChatThreadRow, type CreateChatTablesOptions, type CreateThreadInput, type ListMessagesOptions, type ListThreadsInput, type ListThreadsResult, type NewChatMessageRow, type NewChatThreadRow, type WorkspaceAccessCheck, createChatStore, createChatTables };
