import { type Activity, type Block, type ClientTool, type Conversation, type FilesystemEntry, type Message, type MessagePage, type PlanSnapshot, type Todo, type ToolActivity } from "@cubos/agent-sdk"; import { type ReactNode } from "react"; import { type ComponentMap } from "./blocks.js"; export interface UseConversationOptions { /** * How many events a history page asks for. Counts events, not messages, so a * page of a tool-heavy turn can yield only a couple of bubbles — which is why * a UI should keep calling `loadOlder` until `hasOlder` is false rather than * assuming one page fills the viewport. */ pageSize?: number; /** Which agent a conversation created by the first `send` talks to. Optional * when the token names exactly one. */ agentSlug?: string; /** * Called once, with the conversation the first `send` created, when this hook * was given `null`. Point it at whatever owns the selection — `setState`, a * router navigation — and pass the id back on the next render. * * The messages already on screen survive that hand-off, so the user's first * message doesn't blink out while the conversation is adopted. * * **Awaited.** It runs after the conversation exists and before the message * is posted, which is the only window in which an app can set something up * that the very first turn depends on — declaring its own client tools, for * one. Returning a promise holds the send until it resolves; a throw fails * the send, which is the honest outcome for setup that did not happen. */ onCreated?: (conversation: Conversation) => void | Promise; /** * Functions the agent may call, keyed by tool name. Declared on the * conversation, then executed here as the agent calls them: the turn suspends * on the call and resumes with whatever the handler returns. * * They ride the subscription this hook already holds — no second stream. */ clientTools?: Record>; /** * Whether this hook declares `clientTools` on the conversation. Defaults to * true, which is what an app with a fixed tool set wants. * * Turn it off to declare the set yourself, with `setClientTools`, and pass * every handler the agent might ever call here. That splits two things this * hook otherwise ties together: *what can run* (the handlers, which must * cover any call that arrives) and *what the agent is told about* (the * declaration). An app whose tools depend on the open screen needs that * split — the declaration should change on navigation, while the handlers * must stay complete, or a call issued a moment earlier would find no * implementation. */ declareClientTools?: boolean; /** * What your app currently has on screen — the open page, the selected record, * the filters in force. Free-form: prose or JSON, whatever the agent reads * best. * * Set it and forget it — update it as often as your screen moves. Nothing is * sent while nobody is listening: the value is held and flushed at the two * moments the agent can actually read it, just before a message and on any * change while a turn is running. A user browsing eleven screens before typing * anything costs one request, and the agent is told once. * * Undefined leaves it alone; `null` clears it. */ context?: string | null; /** * What draws each component, keyed by tag name (PascalCase, as the agent * writes them). Renderers only — what the agent is *told* about a component * comes from the libraries below. * * Extra entries are fine and useful: they draw components of older messages * that no enabled library offers any more. */ components?: ComponentMap; /** * Slugs of the component libraries this screen can render. Replaces the * conversation's list, so pass the complete one; `[]` takes the agent back to * plain markdown. * * The libraries are authored by the operator over the admin API, because their * entries reach the model verbatim. This is the half that depends on which of * your screens is open, which is why it is yours. Narrow it as the app * navigates — the hook only re-declares at moments the change can't disturb a * turn in flight. * * A tag the libraries offer with no renderer in `components` is a block the * agent will write and nothing will draw, so the hook logs a warning naming * it. The reverse is never warned about. */ componentLibraries?: string[]; /** Draws the prose around those components. Without it markdown renders as * plain text — see `renderBlocks`. */ renderMarkdown?: (text: string) => ReactNode; /** Wraps each block of an agent message, so the app can lay prose and * components out differently — see `renderBlocks`. */ wrapBlock?: (node: ReactNode, block: Block) => ReactNode; /** A client tool's handler threw, or its result couldn't be delivered. The * agent is told either way; this is for your logs. */ onClientToolError?: (err: unknown) => void; } export interface UseConversationResult { conversation: Conversation | null; /** Oldest first, deduped by id, including any message still in flight. */ messages: Message[]; /** Every tool the agent used, folded and ordered by `seq`. Use `trailFor` to * get the ones behind a given reply; this is the whole conversation's. */ toolActivity: ToolActivity[]; /** * The steps behind one reply — what the agent did between the message before * it and this one — for a "how I got here" disclosure. * * Empty for a user message: a trail belongs to the answer, not the question. * Every entry carries its `arguments` once the call that issued them has been * seen — which for a step still running can be a moment later, so phrase from * the tool name and let the arguments sharpen it. */ trailFor: (message: Message) => ToolActivity[]; /** * The steps no reply has claimed yet — what the agent has done since the last * message. Non-empty while a turn is running, which is what lets a UI draw the * trail as it happens instead of only once the answer lands, and non-empty * after a turn that produced no message at all. */ pendingTrail: ToolActivity[]; /** The plan the given reply was written under, or null when the agent kept * none — the last revision inside the same window as `trailFor`, so an old * answer never shows a newer plan. */ planFor: (message: Message) => Todo[] | null; /** The plan of the turn still running, for the same reason `pendingTrail` * exists. */ pendingPlan: Todo[] | null; /** The newest plan in the conversation, regardless of which turn wrote it. */ todos: Todo[]; activity: Activity; /** * Whether a turn is running right now — the signal to key a "working" * indicator on. * * The server decides this, not you and not the SDK: `hasPendingTurn` is a * trigger over the event log ("a user message newer than the last * `turn_done`"), pushed on connect and on every change, so it cannot read * false while a turn is in flight — not between two replies of one turn, not * while a tool runs, not while a client tool suspends it. * * Not the same as `activity.isProcessing`, and the difference is the whole * reason this exists: a client tool **suspends** the turn while your app * answers it, so the conversation stops being "processing" for as long as * that takes. A UI keyed on activity alone stops its spinner in the middle of * the work and starts it again a second later. * * True from the moment a message is sent until the `turn_done` that follows * it, and true whenever the server says it is processing — either is enough. */ isTurnRunning: boolean; /** True until the first history page and the first stream frame land. False * immediately when the conversation came from the client's cache. */ isLoading: boolean; /** There is older history behind what is loaded. */ hasOlder: boolean; /** A `loadOlder` is in flight. */ isLoadingOlder: boolean; /** * Prepends history before the oldest message held. Safe to call while the * agent is mid-turn — live messages keep arriving and land in order. * * One call is one visible step back: history is paged by *event*, and a page * can be nothing but the tool calls behind one reply, so the hook keeps * paging until at least one message it did not already hold lands (or the * beginning is reached), rather than resolving with nothing changed on * screen and leaving the app to guess whether to ask again. * * Resolves to the number of messages actually added. `0` with `hasOlder` * still true is rare — the page cap was hit mid-scan — and means "call * again"; `0` with `hasOlder` false is the beginning of the conversation. */ loadOlder: () => Promise; /** Set on a failed send or an unrecoverable load. Stream failures land in * `streamError` instead, so a dead subscription and a rejected send can be * told apart. */ error: Error | null; /** * The live subscription died and will not come back: the token was rejected * twice (the SDK forces a refresh and retries once before giving up), the * conversation is gone, or the server refused the stream. * * This is the case a UI cannot infer — everything still renders, the agent * simply never answers again. Nothing here recovers on its own: remount the * hook, or change `conversationId` and back, to resubscribe. */ streamError: Error | null; /** * True while the event stream is connected. False before the first connect, * between a drop and the reconnect that follows it, and whenever * `conversationId` is null. * * A drop is ordinary — the SDK reconnects with backoff, and a socket that * went silent is dropped by the watchdog within ~30s — so treat this as the * signal for a discreet "reconnecting…" hint, never as an error. */ isStreamLive: boolean; /** * Appends the message optimistically, then reconciles with the server's echo. * Rejects on failure, having already rolled the optimistic copy back. * * On the blank slate (`null` id) it creates the conversation first and reports * it through `onCreated`, so a UI never branches on "no conversation yet". */ send: (content: string) => Promise; /** Uploads a recorded clip. The words appear once the agent's STT model has * transcribed it, so nothing is echoed optimistically — there is no text to * echo yet. Creates the conversation on the blank slate, like `send`. */ sendAudio: (audio: Blob) => Promise; /** * Up to 10 images as ONE message, so the agent reasons over the set instead of * one turn per picture. `caption` becomes the message's text, and a per-image * `label` names it for the model. * * Nothing is echoed optimistically: the bubble needs the server's attachment * ids to fetch the bytes back, so it appears with the echo. Creates the * conversation on the blank slate, like `send`. */ sendImages: (images: Array<{ image: Blob; filename?: string; label?: string; }>, caption?: string) => Promise; /** True while a send is in flight. */ isSending: boolean; /** * The agent's reply as React nodes: your components where it used them, your * markdown renderer around them. * * Null for a message with no blocks — every user message, and any agent * message from a server that predates them. Render `content` for those. */ renderMessage: (message: Message) => ReactNode[] | null; /** * Declare the current `clientTools` now. * * Rarely needed: the hook already declares when the session starts and before * every message, which covers an app whose tool set follows the open screen. * This is for the one moment it cannot see — inside a tool that just moved the * app, where the verbs of the new screen have to be available for the step the * agent takes next, and where declaring is safe because the call running it * holds the lease. */ syncClientTools: () => Promise; /** * Bumped whenever the conversation's files change, from any source — the * agent writing one, this app uploading one, another tab deleting one. * * The hook does not hold the listing itself, for the same reason it does not * hold which conversation is open: the directory the user is looking at is * the app's state. What only the hook can supply is *when* to look again, * since it already has the stream. Use it as a dependency: * * ```ts * useEffect(() => { void listFiles(path).then(setEntries) }, [listFiles, path, filesystemRevision]) * ``` */ filesystemRevision: number; /** One directory, never recursive. Empty on the blank slate — there is no * conversation yet, and listing is not a reason to create one. */ listFiles: (path?: string) => Promise; /** One file's bytes. */ readFile: (path: string) => Promise; /** * Uploads files. Creates the conversation on the blank slate, like `send`. * * Starts no turn: the user dropping a file is not asking a question. The * agent is told what changed at the start of its next request, so upload * first and then `send` if you want it acted on — those are one turn, not two. */ writeFiles: (files: Array<{ path: string; file: Blob; filename?: string; }>) => Promise; deleteFile: (path: string) => Promise; moveFile: (from: string, to: string) => Promise; } /** * The paging loop behind `loadOlder`: fetches backwards from `oldestSeq` until * a page brings a message not in `held`, the beginning is reached, or * `maxPages` is spent. `onPage` receives every page as it lands, so the caller * merges each one — the tool activity and plans on a page with no message are * still worth holding. `held` is extended in place with what was added. * Exported for its test — the hook is the only caller. */ export declare function pageOlderUntilNew(opts: { oldestSeq: number | null; hasOlder: boolean; held: Set; fetchPage: (before: number) => Promise; onPage: (page: MessagePage) => void; maxPages?: number; }): Promise<{ added: number; oldestSeq: number | null; hasOlder: boolean; }>; /** A message can arrive twice — once in a history page, once as a stream frame — * and a `loadOlder` page lands in front of what is already held. Key by id and * sort by seq so both are non-events. */ export declare function mergeMessages(existing: Message[], incoming: Message[]): Message[]; /** * The steps behind one reply: what the agent did between the message before it * and this one. * * The previous message is what bounds the turn. Without it the first reply * would claim every step ever taken, and each later one would claim the steps * of the reply before it. Exported for its test — the hook is the only caller. * * Expects `messages` ordered by `seq`. */ export declare function trailOf(message: Message, messages: Message[], activity: ToolActivity[]): ToolActivity[]; /** * The steps that no reply has claimed yet: everything after the last message * held. * * This is what makes a trail watchable while it happens. `trailOf` needs a * message to hang steps on, and mid-turn there is none — the agent is still * working. These are those steps. * * It also covers the turn that ends with **no** message at all: an agent can * call tools and stop without writing a reply, and without this those steps * would never be shown by anything, because nothing would ever arrive to anchor * them. * * The optimistic copy of a just-sent message is skipped: it carries * `MAX_SAFE_INTEGER` as its seq, so counting it would put the boundary past * every real step and this would always come back empty. * * Expects `messages` ordered by `seq`. */ export declare function trailAfterLast(messages: Message[], activity: ToolActivity[]): ToolActivity[]; /** * Is a turn running? * * Three signals, and none of them is a comparison this file makes up. * * `hasPendingTurn` is the server's, and the trigger behind it computes exactly * "there is a user message newer than the last `turn_done`" — which is what * being owed a reply means, and it stays true while a client tool suspends the * turn, when nothing is processing and the agent has answered nothing yet. * `isProcessing` says the work is happening right now. The optimistic copy * covers the moment between pressing enter and the first frame. * * Both arrive as `conversation_status` frames on the *event* stream, which is * what makes reading them here safe. Published on the metadata stream instead — * a second connection — they raced the reply they were about, and the UI showed * a finished turn with nothing in it for as long as that race lasted. * * What is deliberately *not* here is a rule deriving "finished" from the log. * Twice now that has been wrong in opposite directions: reading a missing turn * cursor as "no turn has ended" left the dots on a conversation idle for hours, * and reading a *previous* turn's `turn_done` as this turn's end collapsed the * trail mid-work, while the agent was paused waiting on a client tool. The * server already publishes the answer; recomputing it from a cursor the client * keeps separately only creates two halves that can disagree. * * Exported for its test; the hook is the only caller. */ export declare function turnIsRunning(messages: Message[], activity: Activity): boolean; /** * Plan revisions, deduped by `seq` and ordered. * * The same revision arrives twice routinely — once from the history page and * again from the stream frame that follows it — and two identical plans against * one turn would make `planOf` pick arbitrarily between them. */ export declare function mergePlans(existing: PlanSnapshot[], incoming: PlanSnapshot[]): PlanSnapshot[]; /** * The plan as it stood when a reply was written. * * The agent revises the list several times per turn — one revision per step it * ticks off. Showing them all would be a diff log; showing the newest against * an old answer would be a lie. So: the last revision in the same window * `trailOf` uses, which is the plan the reply was written under. * * Returns null rather than an empty list when there is none, so a caller can * tell "no plan" from "a plan with nothing in it". * * Expects `messages` and `plans` ordered by `seq`. */ export declare function planOf(message: Message, messages: Message[], plans: PlanSnapshot[]): Todo[] | null; /** The plan of the turn still running — the counterpart of `trailAfterLast`. */ export declare function planAfterLast(messages: Message[], plans: PlanSnapshot[]): Todo[] | null; /** * One conversation, live: history, streamed messages, the agent's plan and * whether it is working right now. * * The id is yours to own — component state, a route param, whatever. Pass * `null` for the blank slate: nothing connects, and the first `send` creates the * conversation and hands it to `onCreated`. * * ```tsx * const [id, setId] = useState(null); * const { messages, send } = useConversation(id, { * agentSlug: "support", * onCreated: (c) => setId(c.id), * }); * ``` */ export declare function useConversation(conversationId: string | null, options?: UseConversationOptions): UseConversationResult;