import { ClaudeProviderAccountAuthoritySnapshotV1 } from "@opengeni/contracts"; import { ResourceRef, type SessionTurnSurface, type BillingOrigin, type McpPersonalConnectionDelegation, type McpConnectionAccountBinding, type ConnectionAccountIntent, type DraftTimelineAnnotation, type LatencyMode, type ReasoningEffort, type SessionEvent, type SessionPromptRouting, type SessionTurn, type TurnExecutionPolicyV1, type TimelineAnnotation, type PersonalResourceAttachmentIntent } from "@opengeni/contracts"; import { type Database, type SessionActivityDatabase } from "./database.js"; import { type SessionCommandActor, type SessionCommandReceiptRow } from "./session-control.js"; import * as schema from "./schema.js"; export type QueueCommandConflictCode = "QUEUE_VERSION_CHANGED" | "QUEUE_PROMPT_STARTED" | "QUEUE_ANCHOR_CHANGED" | "PROMPT_CHANGED" | "DRAFT_CHANGED" | "DRAFT_NOT_EMPTY" | "EDIT_SOURCE_CHANGED" | "ONCE_ATTACHMENT_IMMUTABLE" | "WAITING_FOR_MACHINE_OWNER"; export declare class QueueCommandConflictError extends Error { readonly code: QueueCommandConflictCode; readonly current: { queueVersion: number; turnVersion?: number; draftRevision?: number; }; readonly name = "QueueCommandConflictError"; constructor(code: QueueCommandConflictCode, message: string, current: { queueVersion: number; turnVersion?: number; draftRevision?: number; }); } /** * A session that keeps personal memory (a private session or a user-scoped * memory session) can only run work caused by a verified human: its owner for * a private session. Every turn resolves that owner before the model runs, so * admitting a prompt without one only produces a turn that fails on start. * Refuse it at admission with a reason the caller can act on. */ export declare class PersonalSessionInitiatorRequiredError extends Error { readonly name = "PersonalSessionInitiatorRequiredError"; readonly code = "PERSONAL_SESSION_OWNER_REQUIRED"; constructor(); } export type ComposerDraftRow = typeof schema.composerDrafts.$inferSelect; export type QueuedTurnRow = typeof schema.sessionTurns.$inferSelect; export type QueueCommandResult = { receipt: SessionCommandReceiptRow; queueVersion: number; items: QueuedTurnRow[]; eventIds: string[]; replay: boolean; }; export type EditQueueCommandResult = QueueCommandResult & { draft: ComposerDraftRow; }; export type SteerQueueCommandResult = QueueCommandResult & { interruptionCount: number; workspaceControlEventId: string | null; workflowId: string; wakeRevision: number; }; /** * How a person's prompt asks to be delivered. `steer_or_send` is resolved to * `steer` or `send` inside the prompt transaction (see * `submitHumanPromptInTransaction`); only the resolved one is recorded. */ export type HumanPromptDelivery = "send" | "steer" | "steer_or_send"; /** * The receipt action of a prompt. `steer_or_send` may steer, so it shares the * Steer action; its request hash keeps it distinct from a plain Steer. */ export declare function humanPromptCommandAction(delivery: HumanPromptDelivery): "prompt.send" | "prompt.steer"; export type SubmitHumanPromptResult = { receipt: SessionCommandReceiptRow; routing: SessionPromptRouting; queueVersion: number; accepted: SessionEvent; events: SessionEvent[]; turn: SessionTurn; /** Current actor/session composer after an exact draft-bound submission. */ draft: ComposerDraftRow | null; /** Backward-compatible row identities for lower-level callers. */ acceptedEventId: string; eventIds: string[]; turnId: string; wakeRevision: number; interruptionCount: number; workspaceControlEventId: string | null; /** * The chat runs on another person's personal machine, so this message waits * for its owner instead of running (`machine-owner-wait.ts`). As decided at * acceptance. */ waitsForMachineOwner: boolean; replay: boolean; }; export declare function replaySubmittedHumanPromptFromBoundaryReceipt(db: Database, input: { workspaceId: string; sessionId: string; subjectId: string; actor: SessionCommandActor; operationKey: string; delivery: HumanPromptDelivery; boundaryRequestHash: string; expectedDraftRevision?: number | null; /** Wait for an overlapping same-key transaction before checking committed replay truth. */ serializeOperation?: boolean; }): Promise; /** * When the target reads an Agent message, as known when it was accepted. A * message is Queue: `starts_next_turn` (the target was idle, so it wakes now), * `after_current_turn` (mid-turn: read once that turn ends), `after_resume` * (paused) or `when_next_turn_starts` (it cannot start a turn right now). */ export type AgentMessageReadAt = "starts_next_turn" | "after_current_turn" | "after_resume" | "when_next_turn_starts"; /** * When the target reads an Agent Steer: at its `next_step`, `after_compaction` * when a context compaction is in flight, `replaces_waiting_turn` when its turn * had no live attempt (waiting for an approval, an answer or capacity) and the * steer superseded it now, cancelling its open questions and approvals, or * `starts_next_turn` when it had no turn at all. */ export type AgentSteerReadAt = "starts_next_turn" | "next_step" | "after_compaction" | "replaces_waiting_turn"; export type AgentInternalUpdateCommandResult = { receipt: SessionCommandReceiptRow; updateId: string; readAt: ReadAt; eventIds: string[]; wakeRevision: number | null; shouldSignal: boolean; workflowId: string; effectiveState: "active" | "paused"; interruptionCount: number; workspaceControlEventId: string | null; replay: boolean; }; type SteerSupersessionResult = { interruptionCount: number; steerTargetTurn: typeof schema.sessionTurns.$inferSelect | null; replacedTurn: typeof schema.sessionTurns.$inferSelect | null; liveCurrentTurnId: string | null; deferredUntilCompaction: boolean; /** * The live attempt keeps running and hands over at its next model-step * boundary: after the current step's tool calls finish, before the next * model request. Nothing in flight is interrupted. */ deferredUntilModelStep: boolean; lastSequence: number; }; /** True when the Steer leaves the live attempt running until a safe boundary. */ export declare function steerSupersessionIsDeferred(supersession: Pick): boolean; /** * One canonical replacement transition shared by human row/new-prompt Steer * and Agent Steer. A live owner keeps running and hands over at its next * model-step boundary (the worker's model-call admission reads the pending * Steer, so the current step's tool calls finish and nothing is cut off). With * `interrupt`, the live owner is interrupted now and remains current until * exact settlement. An ownerless approval/recovery/capacity turn is superseded * now either way. */ export declare function supersedeSessionCurrentDirectionInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; activeTurnId: string | null; actor: SessionCommandActor; operationId: string; controlRevision: number; lastSequence: number; /** Interrupt a live attempt now instead of at its next model step. */ interrupt?: boolean; /** Who the ownerless supersession records, when not the acting command actor. */ supersededBy?: string; }): Promise; export type WaitingSteerResolution = { wakeRevision: number; workflowId: string; /** Committed events to fan out live (closed calls, supersession, status). */ eventIds: string[]; }; /** * A Steer accepted while the current turn was running waits for that turn's * next model step. If the turn stops in an ownerless wait first (an approval, * a structured question or a capacity wait), there is no next model step to * hand over at, so the waiting Steer replaces the wait now, exactly as a Steer * accepted after the wait began would: unexecuted approvals and questions are * closed and the Steer runs next. The worker calls this right after it * settles such a wait. Returns null when no Steer is waiting, the turn moved * on, or the session is paused (the Steer then stays first in line). */ export declare function resolveWaitingSteerInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise; /** {@link resolveWaitingSteerInTransaction} in its own session-activity transaction. */ export declare function resolveWaitingSteer(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise; export declare function getComposerDraftInTransaction(db: Database, input: { workspaceId: string; sessionId: string; subjectId: string; lock?: boolean; }): Promise; /** * A draft that follows the chat's settings reads as the chat's current * effective model, reasoning effort and speed (the same projection a Send * without a model uses), so a change made outside the composer is what the * person sees and sends. A draft with the person's own pick is returned as * stored. Call inside the caller's workspace/subject RLS boundary. */ export declare function withEffectiveComposerDraftPolicy(db: Database, draft: ComposerDraftRow | null): Promise; export declare function saveComposerDraftInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; expectedRevision: number; text: string; annotations?: DraftTimelineAnnotation[]; resources: ResourceRef[]; /** * The person's pick in the composer. Omit all three to keep the draft on * the chat's own settings, so it follows later changes to them. */ model?: string | undefined; reasoningEffort?: ReasoningEffort | undefined; latencyMode?: LatencyMode | undefined; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; }): Promise; export declare function moveQueuedTurnInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; beforeTurnId: string | null; expectedQueueVersion: number; actor: SessionCommandActor; operationKey: string; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; }): Promise; export declare function deleteSessionQueueItemInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedTurnVersion: number; actor: SessionCommandActor; operationKey: string; reason?: string | null; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; }): Promise; export declare function editQueuedTurnInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; subjectId: string; expectedTurnVersion: number; expectedDraftRevision: number; replaceDraft: boolean; actor: SessionCommandActor; operationKey: string; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; }): Promise; export declare function steerQueuedTurnInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; expectedTurnVersion: number; controlEtag?: string | null; actor: SessionCommandActor; operationKey: string; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; /** * Interrupt the running attempt now, cutting off its in-flight step, * instead of handing over at its next model step. Also turns an * already-deferred Steer into an immediate one ("Send now"). */ interrupt?: boolean; }): Promise; /** * Session statuses whose active turn waits with no live attempt and that an * ordinary human Send takes over (Steer semantics) instead of queueing behind: * a pending decision, or a turn parked on provider capacity such as a used-up * subscription. See `submitHumanPromptInTransaction`. */ export declare function sendTakesOverActiveWait(status: string): boolean; export declare function submitHumanPromptInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; subjectId: string; subjectLabel?: string; actor: SessionCommandActor; operationKey: string; /** Stable parsed boundary-request identity used before mutable enrichment. */ boundaryRequestHash?: string; delivery: HumanPromptDelivery; controlEtag?: string | null; expectedDraftRevision?: number | null; text: string; annotations?: TimelineAnnotation[]; modelContext?: string | null; resources: ResourceRef[]; /** Actor-owned resources used only for the exact durable-draft fence. */ composerDraftResources?: ResourceRef[]; model?: string | null; reasoningEffort?: ReasoningEffort | null; latencyMode?: LatencyMode | null; reasoningEffortFallback: ReasoningEffort; /** Trusted API/core admission snapshot. Omitted only by legacy low-level callers. */ turnExecutionPolicy?: TurnExecutionPolicyV1; /** Trusted core-only metadata attached to the admitted turn. */ turnMetadata?: Record; /** Trusted display projection; the durable turn still receives `text`. */ messagePresentation?: { kind: "realtime_voice" | "realtime_voice_handoff"; text: string; context: string; }; /** False when the human input originated inside the active realtime provider session. */ mirrorToRealtime?: boolean; source: "user" | "api"; /** Content-free product surface the request entered through. */ surface?: SessionTurnSurface | null; /** * Funding origin of whoever sent this message, frozen on its turn. An * edit is billed to its sender too; null inherits the session's latest. */ billingOrigin?: BillingOrigin | null; /** Record the admitted run's durable usage fact in this transaction. */ recordAgentRunUsage?: boolean; personalConnectionDelegations?: McpPersonalConnectionDelegation[]; mcpAccountBindings?: McpConnectionAccountBinding[] | null; /** The sender's account intent: their principal and explicit picks. */ connectionAccountIntent?: ConnectionAccountIntent | null; personalResourceAttachment?: PersonalResourceAttachmentIntent; mcpCredentialUpdates?: Array<{ id: string; headersEncrypted: Record; }>; /** Trusted database-only admission seam. It runs only after a completed * operation replay has been ruled out; throwing rolls the prompt back. */ beforeFreshPromptCommit?: (tx: Database, authority: { claudeProviderAccountAuthoritySnapshot: ClaudeProviderAccountAuthoritySnapshotV1; /** * The accepted source the snapshot was copied from (an edit's source * turn, or the receiving session of agent-submitted work); absent * when the prompt resolved the current source. */ claudeAcceptedSource?: { kind: "session_turn"; turnId: string; } | { kind: "receiving_session"; sessionId: string; }; }) => Promise; /** Backend-only authority capture, atomic with the newly accepted turn. */ captureTurnAuthority?: (tx: Database, turnId: string) => Promise; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }): Promise; export declare function sendAgentMessageInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; targetSessionId: string; actor: Extract; operationKey: string; text: string; /** Fresh admission only, after receipt replay and exact caller authority. */ assertFreshAdmission?: (tx: SessionActivityDatabase) => Promise; /** * Bound the workspace control prefix wait (request-scoped API callers pass * `workspaceControlRequestLockTimeoutMs()`); omit for lifecycle callers. */ controlLockTimeoutMs?: number; }): Promise>; export declare function steerAgentSessionInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; targetSessionId: string; actor: Extract; operationKey: string; instruction: string; /** Runs before resume, supersession or interruption; never on receipt replay. */ assertFreshAdmission?: (tx: SessionActivityDatabase) => Promise; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }): Promise>; export {};