import { R as ReconcileStaleTurnLockOptions } from '../stale-turn-lock-DucQzvXu.js';
import { T as TurnEventStore } from '../turn-buffer-BcPfhr1_.js';

/**
 * `/turn-stream` core — the pure, substrate-free half of the shared durable
 * turn replay/broadcast/lock channel (issue #221).
 *
 * Extracted from the reference consumer's hand-rolled Durable Object
 * (gtm-agent `SessionStreamDO` + `session-broadcast.ts`): the per-turn
 * segment store that backs reconnect replay over a live socket, the
 * single-flight chat-turn lock record and its release fences, and the wire
 * contract (channel keys, endpoint paths, request/response bodies) shared by
 * the DO transport shell (`./do`) and the worker-side adapters
 * (`./adapters`). Everything here is plain data + functions — no
 * `cloudflare:workers`, no storage, no sockets — so the semantics are
 * unit-testable in Node and the DO stays a thin shell.
 *
 * ── The two-lane rule (measured, not assumed) ────────────────────────────
 *
 * A 4-arm A/B on production (sandbox.tangle.tools, SDK 0.12.0, one box, one
 * gateway client per arm) established which sandbox lane a browser can see:
 *
 *   | turn driver                          | raw turn events | seen at gateway |
 *   | ------------------------------------ | --------------- | --------------- |
 *   | `box.streamPrompt()` (run/stream)    | 71 / 527 / 408  | 0 / 0 / 0       |
 *   | `box.session(id).sendMessage()`      | 297             | 297             |
 *
 * `POST /agents/run/stream` publishes nothing to the sidecar session event
 * bus, so a `SessionGatewayClient` attached to that session receives zero
 * turn events — three different session-id strategies all got 0, the id was
 * not the variable. `POST /agents/sessions/{id}/messages` publishes to the
 * bus and the gateway delivered every frame, byte-matching the sidecar tail.
 *
 * Consequences for this module, and they cut both ways:
 *
 * 1. INTERACTIVE sandbox turns should be driven on the message lane and
 *    tailed by the browser through `box.mintScopedToken({ scope: 'session' })`
 *    + `SessionGatewayClient`. Re-broadcasting those same events through the
 *    per-turn SEGMENT buffer below duplicates the SDK and adds a worker hop.
 *    That half is `@deprecated` (see the tags on {@link createSegmentStore},
 *    {@link appendSegmentEvent}, {@link replayActiveSegment} and
 *    `broadcastTurnStreamEvent` in `./adapters`).
 * 2. DETACHED/autonomous turns are INVISIBLE to the gateway:
 *    `dispatchPrompt({ detach: true })` and `driveTurn` both go through
 *    `streamPrompt` internally, i.e. the run/stream lane, which does not fan
 *    out. A browser that must tail an unattended run still needs a buffer —
 *    `runDetachedTurn` (`/chat-routes`) over the durable turn-event rows
 *    below. That half is NOT deprecated and has no SDK replacement today.
 * 3. The LOCK and the per-workspace SIGNALS have no gateway equivalent at
 *    all (the gateway is per-session and read-only). They stay canonical.
 *
 * Server-side resume of a run/stream turn is also already solved by the SDK
 * and needs nothing here: `box.streamPrompt('', { executionId, lastEventId })`
 * replays strictly after the cursor without re-dispatching — measured across
 * a SIGKILL mid-run and a fresh process resuming from the cursor alone:
 * 0 lost, 0 duplicated, 0 out-of-order, ids 1..517 contiguous.
 */
/** One event on a turn-stream channel. `seq` is monotonic within a turn
 *  segment and assigned by {@link appendSegmentEvent} on arrival at the DO. */
interface TurnStreamEvent {
    type: string;
    data?: unknown;
    timestamp: number;
    seq?: number;
}
/** Terminal run markers: they close a turn segment and auto-release the
 *  channel's chat-turn lock for the segment's execution.
 *
 *  KEPT (not deprecated with the segment buffer): the lock auto-release
 *  reads it. A product that stops broadcasting turn events to the thread
 *  channel loses only that auto-release — the cooperative release on settle
 *  (`createDurableTurnLock().release`) and `reconcileStaleDurableTurnLock`
 *  both still fire, which is what actually frees a wedged lane. */
declare function isTerminalRunEvent(type: string): boolean;
/** Define the scope level for acquiring a turn lock within thread or workspace contexts */
type TurnLockScope = 'thread' | 'workspace';
/** Generate a unique string key combining workspace and thread identifiers.
 *
 *  KEPT: thread-scope LOCKS are keyed on it (see {@link turnLockChannelKey}).
 *  Only its second use — addressing a live-viewer socket for interactive
 *  sandbox-turn rebroadcast — is superseded by the session gateway. */
declare function threadChannelKey(workspaceId: string, threadId: string): string;
/** Generate a unique channel key based on the given workspace identifier.
 *
 *  KEPT and canonical: the per-workspace signal channel (`thread.created`,
 *  `thread.activity`) plus workspace-scope locks. The session gateway is
 *  per-SESSION and read-only, so it cannot carry either. */
declare function workspaceChannelKey(workspaceId: string): string;
/** The channel a lock lives on: workspace-scope locks serialize every thread
 *  in the workspace (one shared sandbox), thread-scope locks serialize one
 *  thread (router lane). Same keying as the reference consumer, so a product
 *  swapping its fork for this package contends on identical instances. */
declare function turnLockChannelKey(workspaceId: string, threadId: string, scope: TurnLockScope): string;
/** Generate a storage channel key string for a given turn identifier.
 *
 *  KEPT and canonical: the DETACHED lane's durable turn-event rows live on
 *  this instance. A detached run never reaches the session gateway, so this
 *  is the only way a browser tails one. */
declare function turnStorageChannelKey(turnId: string): string;
/** Generate a unique channel key string based on the provided scope identifier.
 *
 *  KEPT and canonical: backs `TurnEventStore.listRunning`, which is how a
 *  reloaded client rediscovers an in-flight DETACHED turn. */
declare function scopeIndexChannelKey(scopeId: string): string;
/** DEPRECATED (interactive turn-rebroadcast buffer) — represent a segment of a turn containing events, sequence limit, and terminal status.
 *
 *  @deprecated Part of the interactive turn-rebroadcast buffer — see the
 *  two-lane rule in this file's header. Removal is a major-version change. */
interface TurnSegment {
    events: TurnStreamEvent[];
    maxSeq: number;
    terminal: boolean;
}
/** DEPRECATED (interactive turn-rebroadcast buffer) — define a store managing segments and tracking the active execution identifier.
 *
 *  @deprecated Part of the interactive turn-rebroadcast buffer — see the
 *  two-lane rule in this file's header. Removal is a major-version change. */
interface SegmentStore {
    segments: Map<string, TurnSegment>;
    activeExecutionId: string | null;
}
/** DEPRECATED (interactive turn-rebroadcast buffer) — per-turn replay window. Generous enough for normal turns; a turn that
 *  exceeds it loses its earliest deltas from replay (a late resumer
 *  self-heals via the final `result` event + loader revalidation).
 *
 *  @deprecated Sizes the interactive turn-rebroadcast buffer only. The
 *  DETACHED lane's durable rows (`turnEvent:` storage) are uncapped and are
 *  not affected. */
declare const MAX_SEGMENT_EVENTS = 2000;
/** Recent `thread.created` markers kept for late-connecting sidebars.
 *
 *  KEPT: a workspace-level signal, not a turn rebroadcast. */
declare const MAX_RECENT_CREATED = 50;
/** A responding marker older than this is treated as stale, so a dropped
 *  `end` broadcast can't leave a permanently-stuck "responding" dot. */
declare const ACTIVITY_TTL_MS: number;
/** DEPRECATED (interactive sandbox-turn rebroadcast; the SDK's session gateway replaces it) — create a SegmentStore with initialized segments and no active execution ID.
 *
 *  @deprecated Backs the interactive sandbox-turn rebroadcast, which the
 *  sandbox SDK already does better (measured: run/stream → 0 frames at the
 *  gateway, message lane → 297/297; see the two-lane rule in this file's
 *  header). Sandbox turns: drive on `box.session(id).sendMessage()` and let
 *  the browser attach with `box.mintScopedToken({ scope: 'session' })` +
 *  `SessionGatewayClient`. Sandbox-FREE turns: `/stream`'s
 *  `replayTurnEvents` (`GET /chat/stream/:turnId`) already follows a running
 *  turn from a cursor. Detached turns keep the durable turn-event rows —
 *  they are a different, non-deprecated lane. Removal is a major-version
 *  change; nothing is deleted here. */
declare function createSegmentStore(): SegmentStore;
/**
 * DEPRECATED (interactive turn-rebroadcast buffer) — append a per-turn event to
 * its execution's segment, assigning a monotonic
 * `seq`. A `session.run.started` (or the first-seen event for an execution)
 * opens a fresh segment, makes it active, and drops prior turns' buffers so a
 * resumer only ever replays the current turn. A terminal run event marks the
 * segment terminal. Returns the seq-stamped event to broadcast.
 *
 * @deprecated The interactive rebroadcast half — {@link createSegmentStore}
 * names the replacement per lane; this file's header holds the measurement.
 */
declare function appendSegmentEvent(store: SegmentStore, executionId: string, incoming: TurnStreamEvent, maxEvents?: number): TurnStreamEvent;
/**
 * DEPRECATED (interactive turn-rebroadcast buffer; the SDK replays losslessly on
 * both lanes) — events of the active, non-terminal turn with `seq > afterSeq`,
 * i.e. what a
 * (re)connecting client replays before going live. A terminal (finished) turn
 * replays nothing: the client falls back to the loader's persisted row.
 *
 * @deprecated The interactive rebroadcast half — {@link createSegmentStore}
 * names the replacement per lane. The SDK's own reconnect replay is
 * `SessionGatewayClient` + `lastEventId` (browser) or
 * `box.streamPrompt('', { executionId, lastEventId })` (worker); both were
 * measured lossless.
 */
declare function replayActiveSegment(store: SegmentStore, afterSeq: number): TurnStreamEvent[];
/**
 * Remove responding entries (threadId → startedAt) older than `ttlMs`, so a
 * dropped `end` broadcast can't leave a permanently-stuck dot. Mutates
 * `active` and returns the removed thread ids.
 */
declare function pruneStaleThreads(active: Map<string, number>, now: number, ttlMs: number): string[];
/** Default lifetime of an unreleased lock. Long enough that a legitimately
 *  slow sandbox turn never loses its guard mid-run; the way OUT of a wedge is
 *  never the TTL but `reconcileStaleTurnLock` (in `/chat-routes`), which
 *  probes the execution's actual state.
 *
 *  Everything from here down is the LOCK, and it is fully KEPT. The sandbox
 *  SDK ships no single-flight primitive — the session gateway is a read-only
 *  fanout — so moving a product to the message lane changes nothing about
 *  who is allowed to start a turn. */
declare const TURN_LOCK_TTL_MS: number;
/** The stored single-flight lock. Field-compatible with the reference
 *  consumer's `ChatTurnLock` so adoption is a swap, not a migration. */
interface DurableTurnLock {
    workspaceId: string;
    threadId: string;
    scope: TurnLockScope;
    executionId: string;
    lockId: string;
    startedAt: number;
    expiresAt: number;
    turnId?: string;
    /** The turn released this lock, but a product-owned post-turn task (e.g.
     *  file persistence reading the box) is still running, so the release is
     *  parked on the lock until the task settles. Written only through the DO's
     *  defer seam — the base package never sets it on its own. */
    releasePending?: boolean;
}
/** Define input parameters required to acquire a turn-based lock in a workspace thread */
interface TurnLockAcquireInput {
    workspaceId: string;
    threadId: string;
    scope: TurnLockScope;
    executionId: string;
    lockId: string;
    turnId?: string;
}
/** Resolve the result of attempting to acquire a turn lock indicating success or active lock status */
type TurnLockAcquireResult = {
    acquired: true;
    lock: DurableTurnLock;
} | {
    acquired: false;
    active: DurableTurnLock;
};
/** Define input parameters required to release a turn lock in a specific workspace thread */
interface TurnLockReleaseInput {
    workspaceId: string;
    threadId: string;
    scope: TurnLockScope;
    executionId: string;
    lockId: string;
}
/** Fenced out-of-band release (stop button, stale-lock reconciliation). The
 *  fences make it refuse a SUCCESSOR lock: `interruptedAt` must not precede
 *  the lock's own start, and when either side names a turn, both must name
 *  the same one. */
interface TurnLockInterruptedReleaseInput {
    workspaceId: string;
    threadId: string;
    /** Try only this scope; omit to try workspace then thread. */
    scope?: TurnLockScope;
    interruptedAt: number;
    turnId?: string;
}
/** `stored` is what the DO read from storage; expired locks are dead. */
declare function activeTurnLock(stored: DurableTurnLock | undefined, now: number): DurableTurnLock | null;
/** Create a durable turn lock object with timing and scope based on input parameters */
declare function createTurnLock(input: TurnLockAcquireInput, now: number, ttlMs?: number): DurableTurnLock;
/** A cooperative release must present the lock's own identity — both the
 *  execution and the lockId minted at acquire — so a retry of a PREVIOUS turn
 *  can never release the current one. `lockId` is optional only for the DO's
 *  internal terminal-event auto-release, which knows the execution but not
 *  the caller-held lockId. */
declare function turnLockMatchesRelease(active: DurableTurnLock, input: {
    executionId: string;
    lockId?: string;
}): boolean;
/**
 * The interrupted/stale release fence. `interruptedAt` is the instant the
 * releasing evidence was observed (the stop click, the stale-lock probe) —
 * a lock STARTED after that instant is a successor the evidence says nothing
 * about, so it survives. When the lock recorded a client turnId, the release
 * must name the same turn; a lock without one refuses a turn-specific
 * release (it cannot prove it is that turn).
 */
declare function interruptedReleaseApplies(active: DurableTurnLock, input: {
    threadId: string;
    interruptedAt: number;
    turnId?: string;
}): boolean;
/** Provide constant paths for managing chat turn streams and locks */
declare const TURN_STREAM_PATHS: {
    readonly broadcast: "/broadcast";
    readonly lockAcquire: "/chat-turn-lock/acquire";
    readonly lockRelease: "/chat-turn-lock/release";
    readonly lockReleaseInterrupted: "/chat-turn-lock/release-interrupted";
    readonly turnEventsAppend: "/turn-events/append";
    readonly turnEventsRead: "/turn-events/read";
    readonly turnStatusSet: "/turn-status/set";
    readonly turnStatusGet: "/turn-status/get";
    readonly scopeStatusSet: "/turn-scope/set";
    readonly scopeRunningList: "/turn-scope/running";
};
/** Storage keys inside a DO instance. Exported for subclass coexistence —
 *  a product extending the DO must not collide with these. */
declare const TURN_STREAM_STORAGE_KEYS: {
    readonly lock: "chatTurnLock";
    readonly activeThreads: "activeThreads";
    readonly turnStatus: "turnStatus";
    readonly turnScope: "turnScopeIndex";
    readonly turnEventPrefix: "turnEvent:";
};
/** Zero-padded seq so DO storage `list({ prefix })` returns rows in replay
 *  order without a sort. 10 digits holds any realistic turn. */
declare function turnEventStorageKey(seq: number): string;

/**
 * `TurnStreamDO` — the shared Durable Object transport shell over the pure
 * core (`./core`). One class serves every channel family; the instance NAME
 * decides which endpoints a given instance ever sees:
 *
 * - **thread channel** (`${workspaceId}:${threadId}`) — the thread-scope lock
 *   (KEPT), plus the live turn rebroadcast: WebSocket fanout and per-turn
 *   segments with `sync`/`afterSeq` reconnect replay. That rebroadcast is
 *   `@deprecated` for sandbox-backed interactive turns — the sandbox session
 *   gateway already does it, browser-direct, when the turn is driven on the
 *   message lane (`./core`'s header has the production measurement).
 * - **workspace channel** (`${workspaceId}`) — coarse sidebar signals
 *   (`thread.activity` responding set, durable across eviction;
 *   `thread.created` recent list) and the workspace-scope lock. KEPT: the
 *   gateway is per-session and read-only, so it carries neither.
 * - **turn storage** (`turn:${turnId}`) — the durable `TurnEventStore` rows +
 *   status for one buffered turn (replay survives DO eviction — this is what
 *   graduates the vertical's `turnStore` from no-op). KEPT and load-bearing:
 *   a DETACHED run never reaches the gateway, so this is the only way a
 *   browser tails autonomous work.
 * - **scope index** (`scope:${scopeId}`) — the running-turn index backing
 *   `TurnEventStore.listRunning` reconnect discovery. KEPT.
 *
 * The class is a PLAIN class over a structural {@link TurnStreamDOState} —
 * no `cloudflare:workers` import, so this package stays substrate-free and
 * the DO is unit-testable in Node. Cloudflare's `DurableObjectState`
 * satisfies the interface; a product binds it in wrangler by re-exporting:
 *
 *   // worker entry
 *   export { TurnStreamDO } from '@tangle-network/agent-app/turn-stream'
 *
 * Fan-out enumerates `state.getWebSockets()` (never an in-memory socket map)
 * and reads per-socket metadata from the serialized attachment, so it is
 * correct across WebSocket hibernation.
 *
 * Product extension (how the reference consumer keeps its Vault machinery
 * while deleting its fork): subclass and override
 * {@link TurnStreamDO.handleProductRequest} (extra POST endpoints),
 * {@link TurnStreamDO.shouldDeferLockRelease} /
 * {@link TurnStreamDO.completeDeferredLockRelease} (park a lock release
 * behind a product-owned post-turn task), and
 * {@link TurnStreamDO.productSyncEvents} (extra state replayed to a
 * late-connecting socket). Product storage keys must avoid
 * {@link TURN_STREAM_STORAGE_KEYS}.
 */

/** The socket surface the DO touches. Cloudflare's hibernatable `WebSocket`
 *  satisfies it. */
interface TurnStreamSocket {
    send(data: string): void;
    close(code?: number, reason?: string): void;
    serializeAttachment(value: unknown): void;
    deserializeAttachment(): unknown;
}
/** The storage surface the DO touches (Cloudflare `DurableObjectStorage`
 *  satisfies it structurally). `list` must return keys in ascending order —
 *  the turn-event rows rely on it for replay order. */
interface TurnStreamStorage {
    get<T = unknown>(key: string): Promise<T | undefined>;
    put<T = unknown>(key: string, value: T): Promise<void>;
    delete(key: string): Promise<boolean | void>;
    list<T = unknown>(options: {
        prefix: string;
        start?: string;
    }): Promise<Map<string, T>>;
}
/** The `DurableObjectState` surface the DO uses. */
interface TurnStreamDOState {
    storage: TurnStreamStorage;
    acceptWebSocket(ws: TurnStreamSocket): void;
    getWebSockets(): TurnStreamSocket[];
}
/** Define options to override default TTL and event limits for TURN stream DO operations */
interface TurnStreamDOOptions {
    /** Override {@link TURN_LOCK_TTL_MS}. */
    lockTtlMs?: number;
    /** Override {@link MAX_SEGMENT_EVENTS}. */
    maxSegmentEvents?: number;
    /** Override {@link ACTIVITY_TTL_MS}. */
    activityTtlMs?: number;
}
/** Manage per-turn segments and track active threads with durable event storage */
declare class TurnStreamDO {
    protected readonly state: TurnStreamDOState;
    protected readonly env: unknown;
    protected readonly options: TurnStreamDOOptions;
    private segments;
    private recentCreated;
    private activeThreads;
    constructor(state: TurnStreamDOState, env?: unknown, options?: TurnStreamDOOptions);
    fetch(request: Request): Promise<Response>;
    /** Called for any request no base endpoint claimed (before the 404), so a
     *  subclass adds product endpoints without touching base routing. Return
     *  `null` to decline. */
    protected handleProductRequest(_request: Request, _url: URL): Promise<Response | null>;
    /** Consulted before any lock release (cooperative, interrupted, or the
     *  terminal-event auto-release). Return `true` while a product-owned
     *  post-turn task for `executionId` must keep the scope serialized (e.g.
     *  file persistence still reading the box) — the release is then parked as
     *  `releasePending` on the lock and completed via
     *  {@link completeDeferredLockRelease}. Base: never defer. */
    protected shouldDeferLockRelease(_executionId: string): Promise<boolean>;
    /** Complete a release parked by {@link shouldDeferLockRelease}. A subclass
     *  calls this when its deferred condition settles. */
    protected completeDeferredLockRelease(executionId: string): Promise<boolean>;
    /** Extra product state replayed to a socket during its `sync`, after the
     *  base replay for its scope (e.g. an in-flight persistence status card).
     *  Base: none. */
    protected productSyncEvents(_scope: 'thread' | 'workspace', _meta: {
        sessionId: string;
    }): Promise<TurnStreamEvent[]>;
    private handleWebSocketUpgrade;
    /**
     * First (and only) client message after open: `{ type: 'sync', afterSeq }`.
     * Replays the current state for the socket's scope, then marks it `synced`
     * so live broadcasts start flowing. Because the DO is single-threaded, the
     * replay snapshot and the synced flip are atomic w.r.t. broadcasts — every
     * event reaches the socket exactly once, in order, via replay XOR live
     * fan-out.
     */
    webSocketMessage(ws: TurnStreamSocket, message: string | ArrayBuffer): Promise<void>;
    webSocketClose(ws: TurnStreamSocket, code: number, reason: string): void;
    webSocketError(): void;
    private trySend;
    private handleBroadcast;
    private loadActiveThreads;
    private persistActiveThreads;
    protected loadActiveLock(now?: number): Promise<DurableTurnLock | null>;
    private releaseActiveLock;
    /** Park a release on the lock itself; {@link completeDeferredLockRelease}
     *  finishes it once the product's deferred condition settles. */
    private deferLockRelease;
    private handleLockAcquire;
    private handleLockRelease;
    private handleLockReleaseInterrupted;
    private handleTurnEventsAppend;
    private handleTurnEventsRead;
    private handleTurnStatusSet;
    private handleTurnStatusGet;
    private handleScopeStatusSet;
    private handleScopeRunningList;
}

/**
 * Worker-side adapters over {@link TurnStreamDO}: the concrete implementations
 * of the chat vertical's `turnStore` and `turnLock` seams, the WebSocket
 * upgrade forwarder, the best-effort broadcast helpers, and an in-process
 * memory harness for tests and keyless local dev.
 *
 * Everything takes the namespace STRUCTURALLY ({@link TurnStreamNamespaceLike}
 * — Cloudflare's `DurableObjectNamespace` satisfies it), so nothing here
 * imports Cloudflare types and the same adapters run against the memory
 * harness in vitest.
 *
 * Live fanout is deliberately NOT a side effect of the turn-event store: the
 * store is keyed by turnId/scopeId while viewer sockets live on the
 * `${workspaceId}:${threadId}` channel, and only the product's per-turn
 * context knows both. Products wire the workspace signal helpers into
 * `createChatTurnRoutes`' `onEvent`.
 *
 * Which adapters are still the right answer (see `./core`'s header for the
 * production measurement behind this split):
 *
 * | adapter                              | status                            |
 * | ------------------------------------ | --------------------------------- |
 * | {@link createDurableTurnLock}        | KEPT — no SDK equivalent          |
 * | {@link reconcileStaleDurableTurnLock}| KEPT — no SDK equivalent          |
 * | {@link createDurableObjectTurnEventStore} | KEPT — the DETACHED lane     |
 * | {@link broadcastWorkspaceActivity}   | KEPT — workspace signal           |
 * | {@link broadcastThreadCreated}       | KEPT — workspace signal           |
 * | {@link createTurnStreamUpgradeHandler} | KEPT for the workspace channel  |
 * | {@link broadcastTurnStreamEvent}     | `@deprecated` for sandbox turns   |
 */

/** Resolve a stub interface for handling fetch requests with optional initialization parameters */
interface TurnStreamStubLike {
    fetch(input: Request | string, init?: RequestInit): Promise<Response>;
}
/** The surface of `DurableObjectNamespace` the adapters use. */
interface TurnStreamNamespaceLike {
    idFromName(name: string): unknown;
    get(id: unknown): TurnStreamStubLike;
}
/**
 * A {@link TurnEventStore} backed by {@link TurnStreamDO} storage — the
 * production implementation of `createChatTurnRoutes`' `turnStore` seam for
 * apps that don't run D1 for turn events (or want replay co-located with the
 * live channel). Each buffered turn lives on its own `turn:<turnId>` DO
 * instance; `listRunning` reconnect discovery rides a per-scope index
 * instance. Drops in wherever `createD1TurnEventStore(env.DB)` would.
 *
 * KEPT and load-bearing for AUTONOMOUS work. A detached run
 * (`dispatchPrompt({ detach: true })`, `driveTurn`) executes on the sandbox
 * run/stream lane, which publishes nothing to the session event bus — a
 * `SessionGatewayClient` attached to that session sees zero turn events
 * (measured: 0 of 71 / 0 of 527 / 0 of 408 across three session-id
 * strategies). So a browser that must tail a mission step, a queue job, or
 * an inbound-email review has no SDK path; it needs these durable rows plus
 * `runDetachedTurn` (`/chat-routes`). Nothing here is deprecated.
 */
declare function createDurableObjectTurnEventStore(namespace: TurnStreamNamespaceLike): TurnEventStore;
/** Define input parameters required to acquire a durable turn lock in a workspace thread context */
interface AcquireDurableTurnLockInput {
    workspaceId: string;
    threadId: string;
    scope: TurnLockScope;
    executionId: string;
    turnId?: string;
    /** Supply to reclaim/retry with a stable id; default mints a UUID. */
    lockId?: string;
}
/** Acquire a durable turn lock in the specified namespace with given input parameters */
declare function acquireDurableTurnLock(namespace: TurnStreamNamespaceLike, input: AcquireDurableTurnLockInput): Promise<TurnLockAcquireResult>;
/** Release a durable turn lock and indicate if the release was successful or deferred */
declare function releaseDurableTurnLock(namespace: TurnStreamNamespaceLike, input: TurnLockReleaseInput): Promise<{
    released: boolean;
    deferred?: boolean;
}>;
/** Define input parameters to release an interrupted durable turn lock in a workspace or thread */
interface ReleaseInterruptedDurableTurnLockInput {
    workspaceId: string;
    threadId: string;
    /** Try only this scope; omit to try workspace then thread (a stop button
     *  doesn't know which lane the wedged turn ran on). */
    scope?: TurnLockScope;
    interruptedAt: number;
    turnId?: string;
}
/** Fenced out-of-band release — the DO refuses a successor lock (started
 *  after `interruptedAt`) and a turnId mismatch. Returns whether any scope
 *  released. */
declare function releaseInterruptedDurableTurnLock(namespace: TurnStreamNamespaceLike, input: ReleaseInterruptedDurableTurnLockInput): Promise<boolean>;
/** Define options to reconcile stale durable turn locks with context, namespace, workspace, and active lock details */
interface ReconcileStaleDurableTurnLockOptions extends Pick<ReconcileStaleTurnLockOptions, 'probeSandbox' | 'probeSession' | 'graceMs' | 'terminalGraceMs' | 'context' | 'log' | 'now'> {
    namespace: TurnStreamNamespaceLike;
    workspaceId: string;
    threadId: string;
    /** The lock the acquire attempt was refused on. */
    active: DurableTurnLock;
}
/**
 * `/chat-routes`' `reconcileStaleTurnLock` policy wired to the DO: the
 * product supplies the probes (which box, what its session says), the policy
 * decides, and a release lands as a FENCED interrupted release —
 * `interruptedAt` is the policy's `fence.observedAt`, so a successor lock
 * acquired while the probes were in flight survives by construction.
 */
declare function reconcileStaleDurableTurnLock(options: ReconcileStaleDurableTurnLockOptions): Promise<{
    released: boolean;
    diagnostics: Record<string, unknown>;
}>;
/** The subset of `ChatTurnProduceArgs` the lock adapter reads — structural,
 *  so this module needs no import from `/chat-routes/turn-routes` (which
 *  would drag the `agent-runtime` peer into every `/turn-stream` consumer). */
interface TurnLockSeamArgs<TContext> {
    identity: {
        tenantId: string;
        sessionId: string;
    };
    executionId: string;
    context: TContext;
    body: {
        turnId?: string;
    };
}
/** Verdict shape of the vertical's `turnLock.acquire`. */
type TurnLockSeamResult = {
    acquired: true;
    handle?: unknown;
} | {
    acquired: false;
    response: Response;
};
/** Define options for creating a durable turn lock with customizable scope and identification methods */
interface CreateDurableTurnLockOptions<TContext> {
    namespace: TurnStreamNamespaceLike;
    /** Which lane serializes this turn: `'workspace'` (shared sandbox — one
     *  turn per workspace) or `'thread'` (router lane — one turn per thread). */
    scopeOf(args: TurnLockSeamArgs<TContext>): TurnLockScope;
    /** Override the execution id the lock records (e.g. a follow-up reclaiming
     *  the execution it already dispatched). Default: the turn's own. */
    lockExecutionIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined;
    /** Client turn id recorded on the lock (fences interrupted releases to the
     *  right turn). Default: the request body's `turnId`. */
    clientTurnIdOf?(args: TurnLockSeamArgs<TContext>): string | undefined;
    /**
     * Attempt stale-lock recovery after a refused acquire. Return whether the
     * held lock was released (the adapter then retries the acquire once).
     * Products wire {@link reconcileStaleDurableTurnLock} with their sandbox +
     * session probes here. Omit → a refused acquire is final.
     */
    reconcile?(args: TurnLockSeamArgs<TContext>, active: DurableTurnLock): Promise<{
        released: boolean;
        diagnostics?: Record<string, unknown>;
    }>;
    /** Build the refusal `Response`. Default: a 409 with the shared body shape
     *  (`code`, `message`, lock identity + age, reconcile diagnostics). */
    onRefused?(active: DurableTurnLock, diagnostics: Record<string, unknown> | undefined): Response;
}
/**
 * The vertical's `turnLock` seam on the shared DO: dual-scope single-flight
 * acquire (with one reconcile-then-retry pass when the product supplies a
 * stale-lock reconciler) and cooperative release on settle. The returned
 * object satisfies `createChatTurnRoutes`' `ChatTurnLock<TContext>`
 * structurally.
 */
declare function createDurableTurnLock<TContext>(options: CreateDurableTurnLockOptions<TContext>): {
    acquire(args: TurnLockSeamArgs<TContext>): Promise<TurnLockSeamResult>;
    release(handle: unknown): Promise<void>;
};
/**
 * DEPRECATED for sandbox-backed interactive turns (drive on the session-message
 * lane + `SessionGatewayClient` instead) — fan a turn event out to the
 * per-thread channel. `executionId` groups events
 * into a per-turn segment with a monotonic seq, so a reconnecting client
 * replays only the active turn and resumes from a cursor. Callers MUST await
 * (the DO assigns seq on arrival — emission order matters); failures are
 * swallowed (fanout is best-effort and never breaks chat delivery).
 *
 * @deprecated For a SANDBOX-backed interactive turn this re-broadcasts events
 * the sandbox platform already fans out, at the cost of a worker hop. Drive
 * the turn on the session-MESSAGE lane instead —
 * `box.createSession({ sessionId, backend })` then
 * `box.session(id).sendMessage({ parts: [{ type: 'text', text }] })` — and let
 * the tab attach with `box.mintScopedToken({ scope: 'session', sessionId,
 * runtimeSessionId })` + `SessionGatewayClient`
 * (`@tangle-network/sandbox/session-gateway`). Measured on production
 * (4 arms, SDK 0.12.0): turns driven with `box.streamPrompt()` delivered
 * 0 of 71 / 0 of 527 / 0 of 408 turn events to a gateway client, because
 * `POST /agents/run/stream` publishes nothing to the session event bus;
 * the message lane delivered 297 of 297.
 *
 * Two things this deprecation does NOT cover, both still supported:
 * DETACHED runs (no gateway fanout at all — keep `runDetachedTurn` over the
 * durable turn-event rows) and the per-workspace signals
 * ({@link broadcastWorkspaceActivity} / {@link broadcastThreadCreated}).
 * A SANDBOX-FREE copilot that wants a second viewer should use `/stream`'s
 * `replayTurnEvents` (`GET /chat/stream/:turnId`), which follows a running
 * turn from a cursor without a second broadcast fabric.
 *
 * Kept for back-compat; removal is a major-version change.
 */
declare function broadcastTurnStreamEvent(namespace: TurnStreamNamespaceLike, input: {
    workspaceId: string;
    threadId: string;
    executionId: string;
    event: {
        type: string;
        data?: Record<string, unknown>;
    };
}): Promise<void>;
/** Coarse per-workspace marker that a thread's turn started / ended — drives
 *  a sidebar "agent responding" indicator subscribed once per workspace. */
declare function broadcastWorkspaceActivity(namespace: TurnStreamNamespaceLike, workspaceId: string, threadId: string, phase: 'start' | 'end'): Promise<void>;
/** Per-workspace marker that a new thread was created, so an already-open
 *  history list prepends it without a reload. */
declare function broadcastThreadCreated(namespace: TurnStreamNamespaceLike, workspaceId: string, thread: {
    threadId: string;
    title: string;
}): Promise<void>;
/** Represent success or failure of a TURN stream upgrade authorization with optional response data */
type TurnStreamUpgradeAuthorization = {
    ok: true;
} | {
    ok: false;
    response: Response;
};
/** Define options for creating a TURN stream upgrade handler including namespace, path, and authorization logic */
interface CreateTurnStreamUpgradeHandlerOptions {
    namespace: TurnStreamNamespaceLike;
    /** The worker route serving the stream. Default `/api/session-stream`. */
    path?: string;
    /** Viewer access check (session cookie → workspace membership). */
    authorize(request: Request, target: {
        workspaceId: string;
        threadId: string | null;
    }): Promise<TurnStreamUpgradeAuthorization>;
}
/**
 * The worker-entry WebSocket forwarder. Call BEFORE the app router (a router
 * loader cannot return a 101); returns `null` for requests that are not a
 * WebSocket upgrade on the configured path.
 *
 *   GET {path}?workspaceId=...            → workspace channel (sidebar)
 *   GET {path}?workspaceId=...&threadId=… → thread channel (turn resume)
 *
 * After the 101, the client sends `{type:'sync', afterSeq}` and receives the
 * replay-then-live stream (see {@link TurnStreamDO.webSocketMessage}).
 *
 * NOT deprecated — the workspace variant (no `threadId`) is the canonical
 * transport for the per-workspace signals, which the session gateway cannot
 * carry (it is per-session and read-only). The THREAD variant is the
 * deprecated half: for a sandbox-backed interactive turn the tab should
 * attach to the session gateway directly instead of to this socket. See
 * {@link broadcastTurnStreamEvent} for the measurement and the replacement
 * wiring.
 */
declare function createTurnStreamUpgradeHandler(options: CreateTurnStreamUpgradeHandlerOptions): (request: Request) => Promise<Response | null>;

/**
 * In-process turn-stream harness: a fake namespace that routes `idFromName`
 * to REAL {@link TurnStreamDO} instances over an in-memory storage/socket
 * state. The adapters and the DO run their production code paths — only the
 * Cloudflare runtime (isolation, hibernation, real sockets) is simulated.
 *
 * For vitest composition tests and keyless local dev (the same role
 * `createMemoryTurnEventStore` plays for the D1 store). Not for production:
 * state is per-process and evaporates on restart.
 */

/** A test-side viewer socket: records frames sent by the DO and lets the
 *  test drive the `sync` handshake. */
interface MemoryTurnStreamSocket extends TurnStreamSocket {
    readonly frames: string[];
    readonly closed: boolean;
}
/** Define an in-memory channel for streaming turn-based data with viewer socket connection support */
interface MemoryTurnStreamChannel {
    /** Attach a viewer socket to this channel (bypasses the HTTP 101 — the
     *  upgrade handshake is Cloudflare-runtime-only) and run its `sync`. */
    connect(input: {
        sessionId: string;
        scope: 'thread' | 'workspace';
        afterSeq?: number;
    }): Promise<MemoryTurnStreamSocket>;
    readonly instance: TurnStreamDO;
}
/** Provide an interface to manage channels and namespaces for memory-based turn stream testing */
interface MemoryTurnStreamHarness {
    namespace: TurnStreamNamespaceLike;
    /** The channel (creating its DO instance if needed) for a channel key —
     *  e.g. `threadChannelKey(ws, thread)` — to connect test viewers. */
    channel(name: string): MemoryTurnStreamChannel;
}
/**
 * Build the harness. `createInstance` lets a product test run its own
 * `TurnStreamDO` subclass through the same wiring.
 */
declare function createMemoryTurnStreamHarness(createInstance?: (state: TurnStreamDOState) => TurnStreamDO, _options?: TurnStreamDOOptions): MemoryTurnStreamHarness;

export { ACTIVITY_TTL_MS, type AcquireDurableTurnLockInput, type CreateDurableTurnLockOptions, type CreateTurnStreamUpgradeHandlerOptions, type DurableTurnLock, MAX_RECENT_CREATED, MAX_SEGMENT_EVENTS, type MemoryTurnStreamChannel, type MemoryTurnStreamHarness, type MemoryTurnStreamSocket, type ReconcileStaleDurableTurnLockOptions, type ReleaseInterruptedDurableTurnLockInput, type SegmentStore, TURN_LOCK_TTL_MS, TURN_STREAM_PATHS, TURN_STREAM_STORAGE_KEYS, type TurnLockAcquireInput, type TurnLockAcquireResult, type TurnLockInterruptedReleaseInput, type TurnLockReleaseInput, type TurnLockScope, type TurnLockSeamArgs, type TurnLockSeamResult, type TurnSegment, TurnStreamDO, type TurnStreamDOOptions, type TurnStreamDOState, type TurnStreamEvent, type TurnStreamNamespaceLike, type TurnStreamSocket, type TurnStreamStorage, type TurnStreamStubLike, type TurnStreamUpgradeAuthorization, acquireDurableTurnLock, activeTurnLock, appendSegmentEvent, broadcastThreadCreated, broadcastTurnStreamEvent, broadcastWorkspaceActivity, createDurableObjectTurnEventStore, createDurableTurnLock, createMemoryTurnStreamHarness, createSegmentStore, createTurnLock, createTurnStreamUpgradeHandler, interruptedReleaseApplies, isTerminalRunEvent, pruneStaleThreads, reconcileStaleDurableTurnLock, releaseDurableTurnLock, releaseInterruptedDurableTurnLock, replayActiveSegment, scopeIndexChannelKey, threadChannelKey, turnEventStorageKey, turnLockChannelKey, turnLockMatchesRelease, turnStorageChannelKey, workspaceChannelKey };
