import { Part } from '@tangle-network/agent-interface';
import { a as ChatInteractionField, b as ChatInteractionStatus, h as InteractionAnswers, N as NoticeKind } from './contract-KfqJh_au.js';
import { ChatPlanPersistedPart } from './plans/index.js';

/**
 * Wire contract between the chat client (composer + `streamChatTurn`) and the
 * assembled server vertical (`createChatTurnRoutes`). Import-free on purpose:
 * `/web-react` re-exports these types into browser bundles, so nothing here may
 * reach a Node builtin or an engine package.
 *
 * The part shape mirrors the sandbox SDK's `PromptInputPart` structurally
 * (text | image | file with filename/mediaType/url/path/content) — derived
 * here, not imported, so the client bundle never touches the SDK.
 */
interface ChatTurnTextPartInput {
    type: 'text';
    text: string;
}
/** A non-text prompt part the upload route hands back and the client echoes
 *  on send. `url` carries an inline `data:` URI for small files; `path` is a
 *  sandbox workspace reference for large ones (the >1 MiB gateway body cap
 *  makes the two-step upload mandatory). */
interface ChatTurnFilePartInput {
    type: 'image' | 'file';
    filename?: string;
    mediaType?: string;
    url?: string;
    path?: string;
    content?: string;
}
type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput;
/** POST body for the turn route. `content` may be empty when `parts` carry the
 *  message (an image-only send). Product routing fields (workspaceId etc.) ride
 *  alongside and are read by the product's `authorize` seam. */
interface ChatTurnRequestPayload {
    threadId: string;
    content?: string;
    /** Non-text parts from the upload route, echoed back verbatim. */
    parts?: ChatTurnFilePartInput[];
    /** `@`-picked file mentions for this turn — path references into the
     *  workspace sandbox, NOT uploads, so they travel in their own field rather
     *  than as `parts` entries. A product whose `parts` field is already spoken
     *  for (an attachment sentinel) can still send mentions, and mentions
     *  persist as their own `ChatMentionPart`s so a retry rebuilds them. The
     *  route validates this field with {@link parseFileMentions} and replaces it
     *  on the payload with the validated, deduped list. */
    mentions?: FileMention[];
    model?: string;
    effort?: 'auto' | 'low' | 'medium' | 'high';
    harness?: string;
    /** Client-generated idempotency key for the logical turn (retry-safe). */
    turnId?: string;
    [key: string]: unknown;
}
/** `fetch` init for the turn route — the one place the client wire shape is
 *  serialized, so composer glue and products never drift from the server's
 *  parser. */
declare function chatTurnRequestInit(payload: ChatTurnRequestPayload): RequestInit;
declare const INLINE_PARTS_MAX_BYTES = 950000;
declare class ChatTurnInputError extends Error {
    readonly status: number;
    readonly code: string;
    constructor(message: string, status?: number, code?: string);
}
declare function promptPartsByteSize(parts: ChatTurnPartInput[]): number;
/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow
 *  the gateway cap. Path-ref parts are tiny by construction and always pass. */
declare function assertPromptPartsWithinCap(parts: ChatTurnPartInput[], maxBytes?: number): void;
/** A file mention resolved from the composer's `@`-picker: the
 *  workspace-relative path plus enough metadata to build a prompt part and
 *  pointer text. `path` is the canonical identity — the mention pill's
 *  `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */
interface FileMention {
    path: string;
    name: string;
    size?: number;
}
/** The `image/*` mime for a mention path by extension, or `undefined` for
 *  anything not in the known image set (dispatched as `type: 'file'`). */
declare function mediaTypeForMentionPath(path: string): string | undefined;
/** The image/file split a mention is rendered and persisted under — the
 *  composer pill's icon, the dispatched part's `type`, and
 *  `ChatMentionPart.mentionKind` are all this one value. */
type ChatMentionKind = 'image' | 'file';
/** `image` when the path's extension is in the known image set (the same table
 *  {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a
 *  client that needs only the discriminant — a pill icon, a persisted part's
 *  `mentionKind` — never re-declares the extension table; two frozen copies of
 *  one mime table is how one gains a format and the other doesn't. */
declare function mentionKindForPath(path: string): ChatMentionKind;
interface FileMentionsToPartsOptions {
    /** Resolve a mention's workspace-relative path to the absolute path the
     *  dispatched part should carry (e.g. a host prefixing the in-box vault
     *  root). Default: identity — the path travels unchanged. */
    resolvePath?: (path: string) => string;
}
/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —
 *  `image` vs `file` by extension, and always a `path`, never a `url` (the
 *  url/path XOR invariant: a mention is a sandbox path reference, never
 *  inline bytes). */
declare function fileMentionsToParts(mentions: readonly FileMention[], opts?: FileMentionsToPartsOptions): ChatTurnFilePartInput[];
/** The agent-facing pointer block appended to the dispatched prompt — never
 *  persisted in message `content`. Empty array → `''` so callers can append
 *  unconditionally. This is the sole producer of that text: the current
 *  turn's dispatch and any history projection built from the same mention
 *  list both route through here, so the two can't drift apart. */
declare function buildMentionPromptBlock(mentions: readonly Pick<FileMention, 'name' | 'path'>[]): string;
/** Hard cap on mentions per turn. Bounds the prompt pointer block, the
 *  persisted parts, and whatever media budget a dispatch draws from them. */
declare const MENTION_MAX_COUNT = 16;
type SandboxMentionPathCheck = {
    succeeded: true;
} | {
    succeeded: false;
    error: string;
};
/**
 * Validate a workspace-relative sandbox mention path. Rejects traversal (a
 * `..` path segment), absolute paths (leading `/`), backslashes, and null
 * bytes — the four ways a path picked in a client can escape the root the
 * index route scanned.
 *
 * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,
 * and an ASCII-only charset would silently drop real files from a feature
 * whose whole job is naming them.
 */
declare function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck;
/**
 * Validates the untyped `mentions` array off the wire, mirroring
 * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)
 * naming the offending entry. Never sanitizes-and-continues — a traversal path
 * is a rejected request, not a trimmed one.
 *
 * A path repeated within one turn is deduped to its first occurrence rather
 * than rejected: mentioning the same file twice is plausible user input, not
 * an attack.
 */
declare function parseFileMentions(raw: unknown): FileMention[];
/** Validates the untyped `parts` array off the wire. Returns the typed parts
 *  or throws `ChatTurnInputError` (400) naming the offending entry. */
declare function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[];

/**
 * The stored shape of `message.parts` — one typed vocabulary for every part a
 * product persists into a chat transcript. NOT an ad-hoc union reverse-
 * engineered from product schemas; each member is matched field-for-field to
 * its canonical source:
 *
 * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s
 *   `normalizePersistedPart` produces from the harness lane's
 *   `message.part.updated` events (ADC sidecar
 *   `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in
 *   an `{id, sessionID, messageID}` envelope; the projection strips the
 *   session/message ids and keeps the per-segment part id).
 * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical
 *   `MessagePartSchema` members (ADC
 *   `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries
 *   the harness's per-step usage receipt — tokens
 *   `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is
 *   also the shape the message-level token/cost columns mirror.
 * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned
 *   sub-agent task).
 * - `interaction` / `notice`: the persisted-part codecs in
 *   `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,
 *   `noticePart`) — type-only imports, one source of truth for their statuses
 *   and field shapes.
 * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox
 *   SDK's authoritative plan lifecycle.
 * - `mention`: an `@`-picked reference to a file that already lives in the
 *   workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus
 *   the image/file discriminant). Neither transport lane produces it — the
 *   turn route persists it from the request's `mentions` field — but it is a
 *   part a product persists into a transcript, so it belongs in this
 *   vocabulary rather than in a parallel one.
 *
 * `@tangle-network/agent-interface` exports the canonical wire `Part` union,
 * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that
 * is deliberately NOT persisted, so the stored union is defined here as the
 * envelope-free projection (a type-level coverage check against the peer's
 * `Part['type']` lives in the tests). Contribute-down candidate: if
 * agent-interface grows envelope-free persisted-part types, re-export them
 * here and delete these definitions.
 *
 * Two transport lanes serialize into this SAME stored shape:
 * - harness lane: canonical `message.part.updated` parts, merged/normalized by
 *   `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);
 * - router/openai-compat lane: `text_delta`/`tool_call` stream events are
 *   mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +
 *   `/stream`'s `normalizeToolEvent`) and then persisted identically — the
 *   store never sees a router-specific shape.
 */

/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */
interface ChatPartTime {
    start?: number;
    end?: number;
}
/** `id` is the harness's per-segment identity; absent on legacy/router parts,
 *  which collapse to a single logical text stream. Never invented client-side. */
interface ChatTextPart {
    type: 'text';
    text: string;
    id?: string;
}
interface ChatReasoningPart {
    type: 'reasoning';
    text: string;
    id?: string;
    time?: ChatPartTime;
}
/** Superset of the sidecar's status enum (`pending|running|completed|failed`)
 *  and agent-interface's `ToolState` statuses; `error` is the persisted
 *  terminal form `/stream`'s `normalizePersistedPart` settles on. */
type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed';
interface ChatToolState {
    status: ChatToolStatus;
    input?: unknown;
    output?: unknown;
    error?: string;
    title?: string;
    metadata?: Record<string, unknown>;
    time?: ChatPartTime;
}
interface ChatToolPart {
    type: 'tool';
    id: string;
    tool: string;
    callID?: string;
    state: ChatToolState;
}
/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file
 *  shapes; response-side every field besides `type` is optional. */
interface ChatFilePart {
    type: 'file';
    id?: string;
    filename?: string;
    mediaType?: string;
    url?: string;
    path?: string;
    content?: string;
}
interface ChatImagePart {
    type: 'image';
    filename?: string;
    mediaType?: string;
    url?: string;
    path?: string;
}
interface ChatSubtaskPart {
    type: 'subtask';
    prompt: string;
    description: string;
    agent: string;
    id?: string;
}
/** OpenCode step-boundary marker — no renderable text; preserved so mappers
 *  never coerce it into a "[object Object]" text part. */
interface ChatStepStartPart {
    type: 'step-start';
}
/** Per-step usage receipt as the harness reports it (sidecar
 *  `StepFinishPartSchema`). The message-level token/cost columns are this
 *  shape flattened. */
interface ChatUsageTokens {
    total?: number;
    input?: number;
    output?: number;
    reasoning?: number;
    cache?: {
        write?: number;
        read?: number;
    };
}
interface ChatStepFinishPart {
    type: 'step-finish';
    reason?: string;
    tokens?: ChatUsageTokens;
    cost?: number;
}
/** Persisted human-in-the-loop ask — byte-matches
 *  `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */
interface ChatInteractionPart {
    type: 'interaction';
    id: string;
    kind: string;
    title: string;
    body?: string;
    answerSpec: {
        fields: ChatInteractionField[];
    };
    status: ChatInteractionStatus;
    answers?: InteractionAnswers;
    cancelReason?: string;
}
type ChatPlanPart = ChatPlanPersistedPart;
/** Persisted one-line transcript notice — byte-matches `noticePart` in
 *  `/web-react`'s chat-interactions contract. */
interface ChatNoticePart {
    type: 'notice';
    id: string;
    noticeKind: NoticeKind;
    text: string;
}
/**
 * A file the user `@`-mentioned on this turn: a workspace-relative path into
 * the sandbox, never bytes. `type: 'mention'` is its own discriminant
 * precisely so it does NOT collide with the `file`/`image` attachment parts —
 * an attachment carries content the product uploaded, a mention points at
 * something the box already has, and a transcript renders them differently
 * (an inline pill, not an attachment card).
 *
 * `path` is the identity: mentioning one file twice in a turn folds to one
 * part. `turnId` is optional and set by products that rebuild a turn's
 * mentions on retry.
 */
interface ChatMentionPart {
    type: 'mention';
    mentionKind: ChatMentionKind;
    path: string;
    name: string;
    size?: number;
    turnId?: string;
}
type ChatMessagePart = ChatTextPart | ChatReasoningPart | ChatToolPart | ChatFilePart | ChatImagePart | ChatSubtaskPart | ChatStepStartPart | ChatStepFinishPart | ChatInteractionPart | ChatNoticePart | ChatPlanPart | ChatMentionPart;
/** Every canonical harness wire-part kind must be storable — compile-time
 *  guarantee that a new agent-interface part kind cannot silently fall out of
 *  the persisted vocabulary. */
type StorableHarnessPartKind = Part['type'] & ChatMessagePart['type'];
/**
 * The typed projection at the `/stream` → `/chat-store` boundary. The stream
 * normalizers (`normalizePersistedPart`/`mergePersistedPart`/
 * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they
 * normalize wire shapes and do not own the stored vocabulary. THIS module
 * owns it, so this is where rows gain the `ChatMessagePart` type: each entry
 * is validated against its kind's required fields and narrowed, junk is
 * dropped, and — enforced by the exhaustiveness check below — no storable
 * kind can silently fall out (the step-finish/interaction trap).
 */
declare function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[];
declare function isChatToolPart(part: ChatMessagePart): part is ChatToolPart;
declare function isChatTextPart(part: ChatMessagePart): part is ChatTextPart;
declare function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart;
declare function isChatPlanPart(part: ChatMessagePart): part is ChatPlanPart;
declare function isChatStepFinishPart(part: ChatMessagePart): part is ChatStepFinishPart;
/** Widened to `unknown` — unlike its siblings this guard also runs over raw
 *  untyped stored rows (a transcript renderer reads `message.parts` before the
 *  typed projection), which is exactly what {@link mentionPartsFromMessageParts}
 *  needs. `path` and `name` carry the pill; a row missing either is unrenderable.
 *
 *  Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,
 *  then {@link mentionInputToPart}): a blank `name` is rejected there and so is
 *  rejected here, and `size` — optional, but typed `number` once present — is
 *  type-checked so `'12'` or `null` cannot ride through the guard wearing a
 *  type it does not have. Negative sizes are NOT re-rejected: the wire screens
 *  them, `mentionInputToPart` trusts its input, and a read guard stricter than
 *  what the writer can emit would drop rows it produced itself. */
declare function isChatMentionPart(part: unknown): part is ChatMentionPart;
/** Every mention part on one message, in stored order. The projection a
 *  transcript renderer runs before deciding which mentions the message text
 *  already shows inline (see `segmentMentionContent` in `/web-react`). */
declare function mentionPartsFromMessageParts(parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined): ChatMentionPart[];
/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the
 *  part the turn route persists. An absent/non-finite `size` is DROPPED rather
 *  than stored as `undefined`, so a stored row never carries a key that means
 *  nothing. */
declare function mentionInputToPart(input: FileMention): ChatMentionPart;

export { type ChatTurnRequestPayload as A, type ChatTurnPartInput as B, type ChatFilePart as C, type ChatTurnFilePartInput as D, ChatTurnInputError as E, type FileMention as F, type ChatTurnTextPartInput as G, type FileMentionsToPartsOptions as H, INLINE_PARTS_MAX_BYTES as I, type SandboxMentionPathCheck as J, assertPromptPartsWithinCap as K, buildMentionPromptBlock as L, MENTION_MAX_COUNT as M, chatTurnRequestInit as N, fileMentionsToParts as O, mediaTypeForMentionPath as P, mentionKindForPath as Q, parseChatTurnParts as R, type StorableHarnessPartKind as S, parseFileMentions as T, promptPartsByteSize as U, validateSandboxMentionPath as V, type ChatImagePart as a, type ChatInteractionPart as b, type ChatMentionKind as c, type ChatMentionPart as d, type ChatMessagePart as e, type ChatNoticePart as f, type ChatPartTime as g, type ChatPlanPart as h, type ChatReasoningPart as i, type ChatStepFinishPart as j, type ChatStepStartPart as k, type ChatSubtaskPart as l, type ChatTextPart as m, type ChatToolPart as n, type ChatToolState as o, type ChatToolStatus as p, type ChatUsageTokens as q, isChatInteractionPart as r, isChatMentionPart as s, isChatPlanPart as t, isChatStepFinishPart as u, isChatTextPart as v, isChatToolPart as w, mentionInputToPart as x, mentionPartsFromMessageParts as y, toChatMessageParts as z };
