/** * ChatSession — singleton holder of the chat conversation state. * * The chat is conceptually one thing. Whether it's rendered in the * mini-canvas's lid, the drawer's lid, or as a tile inside any slot, * they're all VIEWS of the same conversation. This module owns that * shared state. * * Why a module-level singleton (not on `runtime`): * - Per-page scope is the right granularity for a chat (one user, * one conversation, however many canvas instances on the page). * - Avoids a new SmartCanvasRuntime API surface for now. Easy to * promote to `runtime.chat` later without breaking the widget API. * - Module identity is stable per page; multiple imports return the * same instance. * * Separation of concerns: * - `ChatSession` owns state: messages, inFlight. * - Views (AdaptiveChatBar via AdaptiveChatBarMountable) subscribe * to state changes and dispatch user actions back via send() / * interrupt(). * - Transports (the LLM call, SSE pipeline, stub timers) listen * for "send" / "interrupt" events and eventually call receive() * with the assistant's reply. Transports are NOT owned by this * module — adapters live separately. * * No persistence in this slice. Future: snapshot to runtime.state * for cross-session continuity. */ import type { ChatSendVia } from '@syntrologie/sdk-contracts'; import type { TrailMessage, TrailToolCall } from './AdaptiveChatTrail'; export interface ChatSessionState { readonly messages: readonly TrailMessage[]; readonly inFlight: boolean; /** * Latest reasoning narration from the model, streamed via the * AG-UI `THINKING_TEXT_MESSAGE_CONTENT` channel. Empty string when * no thinking turn is active. Consumers render this in place of * the silent loading dots while the model decides what to do * between tool calls. Cleared the moment a real text or tool-call * event lands — at that point the model has switched to producing * visible output and the narration is over. */ readonly thinkingText: string; /** User sends so far in this session; the single turn counter. */ readonly turn: number; } export interface ToolResultEvent { toolCallId: string; result: unknown; approved: boolean; } export type ChatSessionSubscriber = (state: ChatSessionState) => void; export type SendListener = (event: { text: string; id: string; turn: number; via: ChatSendVia; activeLidSlot?: string; forwardedProps?: Record; }) => void; export type InterruptListener = () => void; export type ToolResultListener = (event: ToolResultEvent) => void; /** Optional per-send envelope. */ export interface SendOptions { /** * The slot the calling chat-bar lives in (e.g. ``"drawer"``, * ``"adaptive-chat"``). Forwarded to transport listeners so the * outbound request can tag the correct ``X-Active-Lid-Slot`` regardless * of which bar most recently configured the singleton transport. * Without per-send threading, two coexisting chat-bars race over the * transport's cached ``activeLidSlot`` and the user-facing routing * silently follows whichever bar configured last. */ activeLidSlot?: string; /** * Merged into THIS request's forwardedProps only — never sticky. The * transport spreads it over the config-level forwardedProps for the one * AG-UI request this send produces (see ChatTransport). Used for turn * provenance (`{ origin: TurnOrigin }`): a later typed message must not * inherit it, or every message would look synthetic. */ forwardedProps?: Record; /** * Which affordance produced this send. Rides * `syntro_chat_message_sent.via`. */ via: ChatSendVia; } export type Unsubscribe = () => void; export declare class ChatSession { private _messages; private _inFlight; private _runActive; private _thinkingText; private _nextId; private _turn; private subscribers; private sendListeners; private interruptListeners; private toolResultListeners; /** Snapshot the current state. Always returns a fresh immutable view. */ getState(): ChatSessionState; /** User sends so far in this session; the single turn counter. */ get turn(): number; /** * Append a delta to the active thinking turn's narration buffer. * Forwarded from the AG-UI THINKING_TEXT_MESSAGE_CONTENT event so * the chat trail can render the model's own reasoning instead of * silent loading dots between turns. */ appendThinkingDelta(delta: string): void; /** * Replace the active thinking narration outright (vs. appendThinkingDelta's * streaming accumulation). Used to surface tool-call progress — e.g. * "Searching…" while the agent works a tool — so a long tool phase shows * what's happening instead of silent dots. No-op if unchanged. */ setThinkingText(text: string): void; /** * End the active thinking turn — drop any narration so the trail * stops showing it. Fires on real text-message-start and on * tool-call-start, the moment the model switches from reasoning * to visible output. */ clearThinking(): void; setRunActive(active: boolean): void; /** * Subscribe to state changes. Called immediately with the current * state, then again on every change. Returns an unsubscribe function. */ subscribe(cb: ChatSessionSubscriber): Unsubscribe; /** * User submitted a message. Appends a user-role message, sets * inFlight=true, notifies state subscribers, and fires a "send" * event so transports can pick it up. Empty/whitespace text is a * no-op (matches the chat bar's local guard). */ send(text: string, opts: SendOptions): void; /** * Single-shot assistant reply (no streaming). Equivalent to * receiveStart + receiveDelta + receiveEnd in one call. Useful for * stub transports and tests that don't model streaming. */ receive(text: string): void; /** * Begin a streaming assistant message. Appends an empty assistant * message with status='streaming'. Caller (transport adapter) feeds * deltas via receiveDelta(id, text) and signals completion via * receiveEnd(id). `inFlight` stays true through the stream. */ receiveStart(id: string): void; /** * Append a delta to a streaming message. No-op when the id is * unknown (race between transport events and reset, etc.) — never * throws so transports can fire-and-forget. */ receiveDelta(id: string, delta: string): void; /** * Mark a streaming message complete and clear inFlight. No-op when * the id is unknown (defensive against transport double-fires). */ receiveEnd(id: string): void; /** * Transport reports a fatal error. Marks any in-flight streaming * message as 'error' (so the trail can render a styled error chip * instead of pretending the partial text was a complete answer), * appends a system-role message with the error text for visibility, * and clears inFlight. Also drops any pending thinking narration * — leaving stale "Let me check…" alongside an error chip reads * as if the assistant is still working when it isn't. */ error(message: string): void; /** * User clicked the in-flight stop button. Clears inFlight and * fires an "interrupt" event so transports can cancel their * in-flight request. No-op if not in-flight (idempotent). Drops * any pending thinking narration for the same reason as error(): * the visitor explicitly asked the assistant to stop, so it * shouldn't keep narrating in the trail. */ interrupt(): void; /** * Wipe state. Used by the canvas-close path (start a fresh * conversation next time) and by tests. */ reset(): void; /** Register a transport's send listener. Returns unsubscribe. */ onSend(listener: SendListener): Unsubscribe; /** * True when at least one transport has wired itself to the session's * send pipeline. Views can use this to surface "no chat backend * connected" affordances instead of hanging in `inFlight` after a * send fires into the void. */ hasTransport(): boolean; /** Register a transport's interrupt listener. Returns unsubscribe. */ onInterrupt(listener: InterruptListener): Unsubscribe; /** * Register a transport's tool-result listener. The transport * forwards `tool-result` actions back to the agent after the user * approves or rejects a client-tool call. Returns unsubscribe. */ onToolResult(listener: ToolResultListener): Unsubscribe; /** * Attach a tool call to a streaming assistant message. No-op when * the message id is unknown (race between transport events and * reset / late mount). */ addToolCall(messageId: string | number, toolCall: TrailToolCall): void; /** * Create an empty, already-settled assistant message at `id` if one * doesn't already exist. Idempotent — safe to call on every tool-call * sighting. * * Exists for TOOL-ONLY turns: pydantic-ai's AG-UI adapter mints a fresh * `parent_message_id` per model response regardless of content * (`before_response` → `self.new_message_id()`) and stamps it on every * `TOOL_CALL_START`, even when the response has no text. When the * model's entire action is one or more tool calls with no narration * (a parallel `mount_*` + `suggest_replies` batch, most commonly), no * `TEXT_MESSAGE_START` is ever emitted for that id, so nothing would * otherwise create the host message `addToolCall` needs — and the tool * call (and any chips/receipts derived from it) silently vanishes * (BUG-1786654199). Call this before `addToolCall` on a tool call's * first sighting so it always has a message to land on. * * Deliberately status:'complete' (not 'streaming' via `receiveStart`): * a tool-only message has no text to stream, so there's nothing for a * later `receiveEnd` to settle — leaving it 'streaming' would paint * the trail's streaming/typing visual state forever. */ ensureAssistantMessage(id: string | number): void; /** * Partially update a tool call by id. Used by the transport to * advance status (args-streaming → running → done) as AG-UI events * arrive. No-op when the id is unknown. */ updateToolCall(toolCallId: string, patch: Partial): void; /** * Resolve a (client-) tool call. Marks the call done, persists, and * fires onToolResult so the transport can forward the result + the * user's approve/reject decision back to the agent. No-op when the * id is unknown. */ resolveToolCall(toolCallId: string, result: unknown, approved: boolean): void; /** * Hydrate from the server transcript (the /session SSE's * messages-snapshot) — the server is the transcript of record * (FEAT-1783701440). Snapshot order is truth: shared ids keep the * LOCAL object (it may carry richer live tool-call state) but take the * snapshot's position; snapshot-only messages (history on reload, a * nudge missed during an SSE gap) are inserted; local-only messages * (an in-flight turn, the greeting) float after in local order. * * Deploy-boundary guard: a user message persisted under a pre-Phase-2 * transport id (before ids were threaded) would arrive as * "snapshot-only" next to its local twin — skip snapshot USER messages * whose exact text already exists locally under a different id. */ hydrate(snapshotMessages: TrailMessage[]): void; private notify; } /** * The module-level singleton. Every `` (regardless * of which slot it lives in) reads from and writes to this instance. * Multiple imports of this module return the same object. * * Scope: per-page. Correct for the canonical case (one user, one * conversation, however many canvas views surface it). Multiple * `` instances on the same page will share state — * tracked in project_future_work.md for per-runtime scoping. */ export declare const chatSession: ChatSession; //# sourceMappingURL=ChatSession.d.ts.map