import type { LucidClientLike, LucidRawRunner } from '../stores/lucid.js';
import type { Actor } from '../types.js';
import type { PoppyPrincipal } from './auth.js';
import type { PoppyContext, PoppyEvent, PoppyEventBody, PoppyHandoff, PoppyResponder } from './protocol.js';
/**
 * A Poppy conversation as this surface keeps it. It belongs to a Personal Agent (`clientId`) and
 * one of its Users (`userId`); once it used an account here, to that account too (`accountRef`,
 * §8.2). The agent side of it is an agent thread (`threadId`) — a Direct Conversation shares its
 * parent's thread, which is how the Company Agent knows what was said in either (§8.10).
 */
export interface PoppyConversationRecord {
    id: string;
    clientId: string;
    userId: string;
    accountRef: string | null;
    agentName: string;
    threadId: string | null;
    /** Set on a Direct Conversation: the conversation it was opened from. */
    parentId: string | null;
    /** On a parent: its open Direct Conversation. */
    openDirectId: string | null;
    /** The state of §8.7 — `working` is not an event, the other three are `state` events. */
    working: boolean;
    handoff: PoppyHandoff;
    responder: PoppyResponder;
    closed: boolean;
    /** The User's context as last shared — fields a message leaves out keep their value (§8.4). */
    context: PoppyContext;
    /** The `Poppy-Version` of the request that started it (§8.2); `null` on a conversation older than 1.0. */
    protocolVersion: string | null;
    /** The extensions that request declared, `{ name: version }` (§3.4). */
    extensions: Record<string, string>;
    /**
     * What the Company Agent is to speak about first, before any message of the Personal Agent — set
     * on a Direct Conversation opened without one (§8.10) until its first turn takes it up.
     */
    prompt: string | null;
    /** The run whose reply is being written, while there is one. */
    activeRunId: string | null;
    /**
     * The latest request the active run takes into account — the `as_of_request` of its reply (§8.4),
     * kept so a reply written after its process died still says it.
     */
    asOfRequest?: string | null;
    /**
     * The operations this conversation asked approval for (Operations extension), by `operation_id`:
     * what each one performs, and where it stands.
     */
    operations?: Record<string, PoppyConversationOperation>;
    /**
     * The position of the last message event a turn has taken up. The event log IS the turn queue:
     * user messages after it are what the next turn answers — on whichever replica picks it up.
     */
    turnSeq: number;
    /** Who the latest request came as — what the next turn runs as. */
    grant: PoppyGrant | null;
    /** Events at or below this sequence number were pruned: a cursor there is `cursor_expired`. */
    prunedSeq: number;
    createdAt: number;
    updatedAt: number;
}
/** The identity a conversation's turns run as: that of its latest request (§8.11). */
export interface PoppyGrant {
    actor: Actor;
    /** The token's account scopes; empty when signed out. */
    scopes: string[];
    signedIn: boolean;
    /**
     * The extensions the latest request declared, `{ name: version }` (§3.4) — which extension
     * content the Company may send (§8.4).
     */
    extensions?: Record<string, string>;
    /** The latest request's principal (without its actor) — who an operation is asked for. */
    principal?: Omit<PoppyPrincipal, 'actor'>;
}
/**
 * An operation a conversation asked approval for (Operations §3, §4): the action it performs —
 * the tool call, or the independent proposal — and its state.
 */
export interface PoppyConversationOperation {
    operationId: string;
    /** The latest revision returned for it. */
    revision: string;
    expiresAt: string;
    summary?: string;
    /** The terms of the latest revision. */
    terms: Record<string, unknown>;
    /** The tool the action calls, and its input. */
    tool: string;
    input: unknown;
    /** The independent proposal that performs it, when the action is one. */
    proposalId: string | null;
    /**
     * `pending` — waiting for an approval; `approved` — approved, the Company Agent performs it on
     * its next call of the same tool with the same input; `performing`; `performed` — done, never
     * again (Operations §7).
     */
    status: 'pending' | 'approved' | 'performing' | 'performed';
    createdAt: number;
    updatedAt: number;
}
export type PoppyConversationPatch = Partial<Pick<PoppyConversationRecord, 'accountRef' | 'threadId' | 'openDirectId' | 'working' | 'handoff' | 'responder' | 'closed' | 'context' | 'prompt' | 'activeRunId' | 'asOfRequest' | 'operations' | 'turnSeq' | 'grant' | 'prunedSeq'>>;
/** An event with its position in the conversation. */
export interface StoredPoppyEvent {
    seq: number;
    event: PoppyEvent;
}
/** What an accepted request keeps for its retries (§8.3). */
export interface PoppyMessageReceipt {
    fingerprint: string;
    conversationId: string;
    /** The HTTP status and body the first delivery got. */
    response: {
        status: number;
        body: Record<string, unknown>;
    };
}
export type PoppyMessageClaim = {
    status: 'claimed';
} | ({
    status: 'existing';
} & PoppyMessageReceipt);
/**
 * Where conversations, their events and message receipts live. Events are append-only and read by
 * position, so a cursor replays exactly what came after it, on any replica.
 *
 * @experimental Implements Personal Agent Protocol 1.0 (https://personalagentprotocol.org/docs/1.0/spec).
 * The surface may still change between minor releases of this package while it settles.
 */
export interface PoppyStore {
    createConversation(record: PoppyConversationRecord): Promise<void>;
    getConversation(id: string): Promise<PoppyConversationRecord | null>;
    updateConversation(id: string, patch: PoppyConversationPatch): Promise<void>;
    /**
     * Append an event, numbered after the conversation's last. With `key`, at most one event per key
     * is ever appended: a second append answers the first event with `created: false` — what keeps a
     * re-read turn from writing its reply twice.
     */
    appendEvent(conversationId: string, body: PoppyEventBody, options?: {
        key?: string;
    }): Promise<{
        event: StoredPoppyEvent;
        created: boolean;
    }>;
    /** Events after `afterSeq`, in order, at most `limit`. */
    listEvents(conversationId: string, afterSeq: number, limit: number): Promise<StoredPoppyEvent[]>;
    /** The position of an event, `null` when the conversation has no such event (any more). */
    findEventSeq(conversationId: string, eventId: string): Promise<number | null>;
    /** Drop the events created before `before` (epoch ms), keeping at least the last one. */
    pruneEvents(conversationId: string, before: number): Promise<void>;
    /**
     * Claim request `messageId` for `owner` — atomically, so two deliveries of one request are one
     * (§8.3). Also what ties a `user_requested` event to the Direct Conversation that accepted it.
     */
    claimMessage(owner: string, messageId: string, receipt: PoppyMessageReceipt): Promise<PoppyMessageClaim>;
    /** Drop a claim whose request could not be taken, so its retry is processed afresh. */
    releaseMessage(owner: string, messageId: string): Promise<void>;
    /**
     * Take (or renew) the right to write the reply of the conversation's active run for `ttlMs` —
     * `false` while another holder's lease is live. What lets any replica pick up a reply whose
     * writer died, without two writing it at once.
     */
    leaseReader(conversationId: string, holder: string, ttlMs: number): Promise<boolean>;
    releaseReader(conversationId: string, holder: string): Promise<void>;
}
/** `evt_<seq in base 36>_<random>`: unique, and its position survives the event being pruned. */
export declare function newEventId(seq: number): string;
/** The position an event id was minted at, or `null` for an id this surface never minted. */
export declare function eventIdSeq(id: string): number | null;
/**
 * A record as stored before the 1.0 state model (a single `status`: `working` / `idle` / `queued` /
 * `closed`) or the 1.0 fields, brought to the current shape. Safe on a current record.
 */
export declare function upgradePoppyRecord(raw: PoppyConversationRecord & {
    status?: string;
}): PoppyConversationRecord;
/** Process-local {@link PoppyStore} — tests and single-instance dev. */
export declare class InMemoryPoppyStore implements PoppyStore {
    #private;
    createConversation(record: PoppyConversationRecord): Promise<void>;
    getConversation(id: string): Promise<PoppyConversationRecord | null>;
    updateConversation(id: string, patch: PoppyConversationPatch): Promise<void>;
    appendEvent(conversationId: string, body: PoppyEventBody, options?: {
        key?: string;
    }): Promise<{
        event: {
            seq: number;
            event: PoppyEvent;
        };
        created: boolean;
    }>;
    listEvents(conversationId: string, afterSeq: number, limit: number): Promise<{
        seq: number;
        event: PoppyEvent;
    }[]>;
    findEventSeq(conversationId: string, eventId: string): Promise<number | null>;
    pruneEvents(conversationId: string, before: number): Promise<void>;
    claimMessage(owner: string, messageId: string, receipt: PoppyMessageReceipt): Promise<{
        fingerprint: string;
        conversationId: string;
        /** The HTTP status and body the first delivery got. */
        response: {
            status: number;
            body: Record<string, unknown>;
        };
        status: 'existing';
    } | {
        status: 'claimed';
    }>;
    releaseMessage(owner: string, messageId: string): Promise<void>;
    leaseReader(conversationId: string, holder: string, ttlMs: number): Promise<boolean>;
    releaseReader(conversationId: string, holder: string): Promise<void>;
}
export declare const POPPY_TABLES: {
    readonly conversations: 'agent_poppy_conversation';
    readonly events: 'agent_poppy_event';
    readonly messages: 'agent_poppy_message';
};
/**
 * `CREATE TABLE IF NOT EXISTS` DDL for the Poppy tables — the agent tables' portable dialect
 * (quoted identifiers, epoch-ms `BIGINT`, `TEXT` JSON; `forDialect` adapts it to MySQL). An event's
 * primary key is its position, so two appends racing for one position cannot both win; a message's
 * is its (owner, id), the idempotency lock of §8.3.
 */
export declare function poppyTableStatements(schema?: string): string[];
/**
 * The conversation columns added with Poppy 1.0 — added to a table created before it. Nullable: a
 * row without them is read by its pre-1.0 `status` (which the table still has, and new rows still
 * fill with a summary of the state).
 */
export declare const POPPY_1_0_COLUMNS: readonly [{
    readonly table: "agent_poppy_conversation";
    readonly column: 'working';
    readonly type: 'SMALLINT NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'handoff';
    readonly type: 'VARCHAR(16) NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'closed';
    readonly type: 'SMALLINT NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'protocol_version';
    readonly type: 'VARCHAR(16) NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'extensions';
    readonly type: 'TEXT NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'prompt';
    readonly type: 'TEXT NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'as_of_request';
    readonly type: 'VARCHAR(256) NULL';
}, {
    readonly table: "agent_poppy_conversation";
    readonly column: 'operations';
    readonly type: 'TEXT NULL';
}];
/**
 * Create the Poppy tables if missing, and add the columns a table created by an earlier version
 * lacks. Idempotent. `schema` puts them in that database schema (created when missing); refused on
 * SQLite.
 */
export declare function ensurePoppyTables(db: LucidRawRunner, options?: {
    schema?: string | undefined;
}): Promise<void>;
export interface LucidPoppyStoreOptions {
    /** Create the tables on first use (`CREATE TABLE IF NOT EXISTS`). Default `true`. */
    autoCreateTables?: boolean;
    /**
     * The database schema (a Postgres schema, a MySQL database) the tables live in. Default: none —
     * the connection's current schema. Refused on SQLite.
     */
    schema?: string | undefined;
}
/** {@link PoppyStore} over Lucid (any of SQLite / Postgres / MySQL). */
export declare class LucidPoppyStore implements PoppyStore {
    #private;
    private readonly db;
    constructor(db: LucidClientLike & LucidRawRunner, options?: LucidPoppyStoreOptions);
    /** Provision the tables (once). A failure is retried on the next call. */
    ready(): Promise<void>;
    createConversation(input: PoppyConversationRecord): Promise<void>;
    getConversation(id: string): Promise<PoppyConversationRecord | null>;
    updateConversation(id: string, patch: PoppyConversationPatch): Promise<void>;
    appendEvent(conversationId: string, body: PoppyEventBody, options?: {
        key?: string;
    }): Promise<{
        event: {
            seq: number;
            event: PoppyEvent;
        };
        created: boolean;
    }>;
    listEvents(conversationId: string, afterSeq: number, limit: number): Promise<{
        seq: number;
        event: PoppyEvent;
    }[]>;
    findEventSeq(conversationId: string, eventId: string): Promise<number | null>;
    pruneEvents(conversationId: string, before: number): Promise<void>;
    claimMessage(owner: string, messageId: string, receipt: PoppyMessageReceipt): Promise<{
        status: 'claimed';
        fingerprint?: never;
        conversationId?: never;
        response?: never;
    } | {
        status: 'existing';
        fingerprint: string;
        conversationId: string;
        response: PoppyMessageReceipt['response'];
    }>;
    releaseMessage(owner: string, messageId: string): Promise<void>;
    leaseReader(conversationId: string, holder: string, ttlMs: number): Promise<boolean>;
    releaseReader(conversationId: string, holder: string): Promise<void>;
}
//# sourceMappingURL=store.d.ts.map