/** * ChatTransport — singleton transport adapter that bridges chatSession * (the view-side state holder) to the real backend chat pipeline * (AG-UI SSE at `/api/adaptive/stream`). * * This is the unification of two formerly separate paths: * - `ChatAssistantLit` (old) owns the transport plumbing — * AgUiTransport, Cloudflare Turnstile, headers, A2UI passthrough, * telemetry, fallback card. * - `AdaptiveChatBar` + `chatSession` (new) owns the canvas-lid UX — * glassmorphism bar, bubble-up trail, per-page persistence. * * This module ports every transport-side concern from ChatAssistantLit * into a session-shaped adapter so the new bar gets full backend * parity. The bar stays a pure view; the transport stays a pure pipe. * * Lifecycle: * - `configure({ backendUrl, runtime, ... })` — called once by the * SDK runtime at bootstrap from chat config. Idempotent; second * call with the same backendUrl is a no-op. * - Connection is LAZY. The transport doesn't acquire Turnstile or * open the SSE until the first chatSession.send() — saves cost * on pages where the user never opens chat. * - On chatSession.send → transport ensures connected (acquires * Turnstile token, builds AgUiTransport) then forwards * `{type:'user-message', text}` to the agent. * - On chatSession.onInterrupt → transport sends stop-generation. * - AgUi events stream into chatSession via receiveStart / Delta / * End / error. * - A2UI custom events forward to runtime.actions.applyBatch so the * agent can drive canvas updates. * * Telemetry parity with ChatAssistantLit: * - chatbot.transport_error (every error, with status/body/name) * - chatbot.a2ui_applied * - chatbot.fallback_rendered — emitted when the transport gives up * (Turnstile failed AND backend rejected) so existing PostHog * queries keep working. * * Threading model: single-flight per page. Multiple concurrent sends * are queued by AgUiTransport itself. Multiple bar mounts share this * one transport via chatSession. */ import type { ElementMutation, MutationEnvelope } from './elements'; import type { ChatbotWidgetRuntime } from './types'; /** * Per-customer "chat unavailable" card config. Surfaced via onFallback * when the transport gives up after repeated failures. Mirrors * ChatbotFallback in types.ts so consumers can pass the same config. */ export interface ChatbotFallbackConfig { title?: string; message?: string; ctaLabel?: string; ctaHref?: string; } export interface ChatTransportConfig { /** Backend host, e.g. "https://demo-api.syntrologie.com" or "" for same-origin. */ backendUrl: string; /** Runtime hooks for A2UI apply + telemetry. */ runtime: ChatbotWidgetRuntime; /** Optional thread id for conversation continuity across reloads. */ threadId?: string; /** * Optional set of client-tool names the transport should treat as * "needs user approval" (surfaced via chatSession.toolCalls instead * of auto-executed server-side). Empty by default — all tool calls * are server-driven and the transport just emits the "tool call * happened" event. */ clientTools?: Set; /** * Per-customer "chat unavailable" card. Rendered by the host * (typically AdaptiveChatBarMountable) after repeated connect * failures wipe the chat surface — exactly the same UX * ChatAssistantLit's fallback path provides. */ fallback?: ChatbotFallbackConfig; /** * Arbitrary JSON object attached to every AG-UI request as * `forwardedProps`. Used by the adaptive chat surface to ship the * LLM-authored UI element config (`uiTemplates`, `elementsEnabled`) * per request — the backend reads these to enable the * `mount_element` / `patch_element` / `unmount_element` tools. * Callable form is re-evaluated on every turn so a config edit can * land mid-conversation. */ forwardedProps?: Record | (() => Record | undefined); /** * Optional callback for `syntro.element.mutation` AG-UI custom events. * The transport decodes the envelope on receipt; if it matches the * element-mutation schema, mutations are routed here instead of the * generic `runtime.actions.applyBatch` legacy path. Consumers are * expected to forward to `ElementInstanceStore.apply(mutations)` — * we don't take a store reference directly so the transport stays * agnostic of which surface owns the store (the chat-bar widget * may own one; ChatAssistantLit owns its own; both share this * singleton transport). * * When unset, element-mutation envelopes fall back to applyBatch, * matching legacy behaviour (which would no-op since applyBatch * doesn't know about MutationEnvelope). */ onElementMutation?: (mutations: ElementMutation[]) => void; /** Session-owned lifecycle; legacy array consumers retain onElementMutation. */ onElementEnvelope?: (envelope: MutationEnvelope) => Promise; /** * Slot the chat-bar widget is mounted into (e.g. ``"drawer"``, * ``"adaptive-chat"``). Forwarded as ``X-Active-Lid-Slot`` on every * ``/api/adaptive/stream`` request so the backend can route mounts to * the canvas next to whichever lid the visitor sent from. Optional — * omitting it falls back to the template's static ``default_slot`` * server-side, which is the pre-change behaviour. */ activeLidSlot?: string; /** Sticky persona identity (FEAT-1784917430) — forwarded as headers so the * agent speaks AS the persona the visitor sees. ASCII-sanitized client-side; * the server re-sanitizes and never trusts these for anything but voice. */ personaId?: string; personaName?: string; personaRole?: string; } /** * Debounce window for connect errors. Single transient errors * (cold-start 502, brief CORS preflight failure) should NOT swap the * chat to the fallback card; only sustained failure should. Matches * ChatAssistantLit's ERROR_DEBOUNCE_MS. */ export declare const FALLBACK_DEBOUNCE_MS = 1500; export interface FallbackPayload { reason: 'connect_failed' | 'connect_timeout'; fallback: ChatbotFallbackConfig; transportId: string; transportAgeMs: number; messagesSucceeded: number; hadTurnstileToken: boolean | null; errorStatus: number | null; errorBody: string | null; errorMessage: string | null; errorName: string | null; } export type FallbackListener = (payload: FallbackPayload) => void; /** * Visitor-facing progress copy for a tool call, shown in the thinking chip. * Returns an ORDERED set of phrasings for the tool's category: the first shows * immediately, and `ChatTransport` rotates through the rest every few seconds * while the same phase runs (see `_startThinkingCycle`) so a long — or looping * — tool phase reads as live progress instead of one frozen string. Keyed on * substrings of the (technical) tool name so it survives renames; never shows * the raw name. * * Distinct buckets matter: `retrieve_wiki` (search), `get_wiki_route` * (navigate) and `read_section` (read) all used to collapse to one identical * "Finding the right page…", which made a multi-call research loop look like a * single calm step. Check search/retrieve BEFORE the generic `wiki` fallback so * `retrieve_wiki` lands on "Searching…", not "Looking that up…". * * ───────────────────────────────────────────────────────────────────────── * AUTHORING CONTRACT — read before adding or editing a variant. * * These strings are NOT only shown standalone. When the workspace ships a * persona roster, `AdaptiveChatTrail` composes each variant into the single * visitor-facing status line as: * * "{persona name} is {variant, first character lowercased}…" * * e.g. "Assembling relevant information" → "Jordan is assembling relevant * information…", and "Almost there" → "Jordan is almost there…". * * So EVERY variant must read naturally after `"{name} is "`. Concretely: * 1. Start with a capitalised ordinary word — a present participle * ("Assembling", "Pulling") or an adverbial complement ("Almost"). * A leading acronym breaks the case shift ("FAQ lookup" → "fAQ lookup"). * 2. No subject of its own — "Looking that up for you", never * "I'm looking that up" or "The assistant is looking that up". * 3. No terminal punctuation — the composed line supplies the trailing * ellipsis; a variant ending in "…"/"." would stutter or read as two * sentences. * `thinking-status-line.integration.test.ts` enforces (1)–(3) mechanically * over every variant this function can return; it cannot judge whether a * phrase READS well after "is", so do that by eye when you add one. * ───────────────────────────────────────────────────────────────────────── */ export declare function toolNarrationVariants(name: string): string[]; export declare class ChatTransport { private _config; private _status; private _agui; private _transportUnsub; private _sessionUnsubSend; private _sessionUnsubInterrupt; private _sessionUnsubToolResult; private _connectInFlight; /** Bounded streaming-message id for the currently-being-typed assistant turn. */ private _currentAssistantMessageId; /** Intent messageIds this transport actually dispatched (BUG-1784021805). * The server's `suppressToast` hint assumes the intent frame reached us — * but that frame is fire-and-forget, and a fresh visitor's connection gap * loses it. Only the transport knows what it dispatched, so suppression is * honored ONLY when the sibling intent (`{id}-intent`) went through here. */ private _dispatchedNudgeIntentIds; /** Outcome bookkeeping for telemetry. */ private _hadTurnstileToken; /** Count of successful round-trips for telemetry payloads. */ private _messagesSucceeded; /** True once a successful assistant message has landed — gates fallback. */ private _hasSucceeded; /** True once fallback has fired (one-shot). */ private _fallbackRendered; /** * Per-send override for ``X-Active-Lid-Slot``. Set in the * ``chatSession.onSend`` listener immediately before each * ``_forwardUserMessage`` and consumed by ``buildHeaders`` on the * outbound request. The singleton transport is shared by every * mounted chat-bar (drawer + inline) so cached ``_config.activeLidSlot`` * follows whichever bar last reconfigured — using that for routing * silently misroutes tiles when both bars coexist. Per-send threading * pins the header to the bar that actually sent the message. */ private _pendingLidSlot; /** * Per-send forwardedProps override. Set in the ``chatSession.onSend`` * listener before each ``_forwardUserMessage`` and spread OVER the * config-level forwardedProps for that one request (see * ``_resolveForwardedProps``). Overwritten on EVERY send — ``null`` when * the send carried no envelope — so turn provenance can never leak onto a * later typed message and make it look synthetic. Same lifecycle as * ``_pendingLidSlot``. */ private _pendingForwardedProps; /** Active debounce timer; null when no debounce pending. */ private _errorDebounceTimer; /** Rotates thinking-chip phrasings during a long/looping tool phase (C9). */ private _thinkingCycleTimer; /** * Per-class rotation counter, keyed by the narration set's first variant. * A NEW tool class shows its primary (variant A) so it's recognizable; a * REPEATED same-class call advances to the next variant, so a research loop * of (e.g.) several searches reads as different thinking, not one repeated * label. Bounded to ~6 keys (one per tool class). */ private _thinkingClassSeq; /** Most recent error payload, captured so debounced fallback can attach it. */ private _lastErrorPayload; private _fallbackListeners; /** * Per-configure-cycle id for correlating telemetry events from a * single transport lifetime. Mirrors ChatAssistantLit's mountId * but scoped to configure cycles since the transport is a * singleton across mounts. */ private _transportId; private _configuredAt; /** Injected clock for the per-run timings; production uses Date.now. */ private readonly _now; /** Per-run telemetry state (FEAT-1789150184). The chat session owns the turn; this mirrors it per run. */ private _runTurn; private _runStartedAt; private _firstDeltaAt; private _runMounts; private _runCards; /** The mount_* tool of every mount this run fired, in order — which surfaces * the concierge chose (a carousel on one turn, separate cards on another). */ private _runMountTools; /** * Count of RUN_FINISHED events the server still owes us that must be * swallowed, not reported — one per interrupt. NOT a boolean: an * interrupt latches this debt against whichever run's RUN_FINISHED * arrives next, and a visitor can interrupt then immediately send again * before the first run's late RUN_FINISHED shows up. Clearing this in * `onSend` (as a boolean would need to, to arm for the NEXT run) would * let that late RUN_FINISHED slip through and get misattributed to the * new run — a phantom `reply_received` at turn N+1 with near-zero * ttft/total. The counter survives across sends and is only decremented * by an actual RUN_FINISHED, so debt from run N is always paid by run * N's own (possibly late) finish, never by run N+1's. */ private _pendingSuppressedFinishes; constructor(opts?: { now?: () => number; }); /** The transport is not an element: atoms go straight to document, where TelemetryCore listens. */ private _reportAtom; /** * Configure the transport. Idempotent — calling again with the same * backendUrl is a no-op; calling with a different backendUrl tears * the connection down and re-arms. */ configure(config: ChatTransportConfig): void; /** ms since the most recent configure() call. 0 before any configure. */ private _ageMs; /** True when configure() has been called and we're ready to lazy-connect on send. */ get isConfigured(): boolean; /** True when AgUiTransport is up. */ get isConnected(): boolean; /** * Subscribe to fallback events — fires once per configure cycle * when the transport gives up after sustained failure. Hosts * (typically AdaptiveChatBarMountable) use this to swap the chat * bar for a static "contact support" card. */ onFallback(listener: FallbackListener): () => void; /** * Test seam — drive a synthetic error event through the transport's * error handling without standing up a real AgUi transport. Production * code path uses _onTransportEvent. Exported as a public method to * keep the test isolation simple; not part of the documented API. */ simulateError(payload: { message?: string; status?: number | null; body?: string | null; errorName?: string | null; }): void; /** * Test seam — drive the FULL server-error path (fallback kernel + the * visitor-facing chip), exactly what the `case 'error'` transport-event * branch does. `midAnswer` simulates an assistant message having been * mid-stream when the connection died. */ simulateServerError(payload: { message?: string; status?: number | null; body?: string | null; errorName?: string | null; midAnswer?: boolean; }): void; /** * Test seam — register a synthetic successful message-complete so * the hasSucceeded gate flips without a real AgUi round-trip. */ simulateSuccessfulMessage(): void; /** * Test seam — return the lid slot that the next outbound request * WOULD tag ``X-Active-Lid-Slot`` with, given current state. Mirrors * the exact resolution buildHeaders uses (per-send slot wins over * cached config). Not part of the documented API. */ getActiveLidSlotForTest(): string | null; /** * Tear connection-level state down. Used internally by configure() * to swap backends; preserves host-registered fallback listeners * because the host UI handler (e.g. AdaptiveChatBarMountable's * "swap to fallback card" callback) is configuration-independent. */ private _disconnect; /** * Tear everything down — connection state PLUS host listeners. * Use this in test teardown or when fully shutting the transport * (page unload, integration test reset). The mountable calls * _disconnect indirectly via reconfigure. */ reset(): void; /** AbortController for the live /session SSE reader; null = not running. */ private _sessionStreamAbort; /** Capped reconnect backoff for the session stream. */ private _sessionStreamBackoffMs; /** * Open the persistent `/api/adaptive/session` SSE and feed its frames * through the SAME `_onTransportEvent` switch the AG-UI path uses * (FEAT-1783640628 — proactive nudges). * * The AG-UI cutover left this endpoint with no client consumer, so * server-INITIATED events had nowhere to land. A fetch-based reader — * unlike EventSource — can send the SDK token, and the visitor ids that * write the server's nudge identity bridge. Idempotent; reconnects with * capped backoff; `reset()`/`stopSessionStream()` tears it down. */ startSessionStream(): Promise; stopSessionStream(): void; private _clearDebounceTimer; /** * Show a per-call rotating variant in the thinking chip immediately (so * consecutive tool calls differ), then rotate through the remaining phrasings * every 4s while the same tool phase runs (C9). A * single tool call can sit for tens of seconds (the model reasoning about the * next step, or a slow retrieval); a static chip reads as frozen and hides a * loop. Cycling makes a long/looping phase read as live progress. Restarting * (a new tool), any output (message/thinking), or teardown clears the cycle. */ private _startThinkingCycle; private _stopThinkingCycle; /** * Shared error-handling kernel — called by the AG-UI subscriber and * by the simulateError test seam. Publishes transport_error * telemetry, captures lastErrorPayload, and starts the debounce * timer that will fire fallback if no successful message arrives * before it expires. Gated by hasSucceeded (post-success errors * never fallback) and _fallbackRendered (one-shot). */ private _handleErrorEvent; /** * Fire the fallback. One-shot per configure cycle. Notifies all * fallback listeners with the per-customer card config and the * diagnostic snapshot for telemetry/debug. */ private _renderFallback; /** * forwardedProps for the NEXT outbound AG-UI request: the config-level * value (late-bound — `configure()` can update uiTemplates / * elementsEnabled mid-session without a reconnect, so this must be * resolved per request, not captured at construction) with the per-send * envelope spread over it. Shallow merge; per-send wins per top-level key. */ private _resolveForwardedProps; private _wireSession; private _forwardUserMessage; /** * Ensure AgUiTransport is up. Idempotent — multiple concurrent calls * dedupe to a single Turnstile acquisition + transport setup. * Returns true on success, false on terminal failure. */ private _ensureConnected; /** * Acquire a Turnstile token for a visitor send. Only reached from * `_ensureConnected`, i.e. on interaction. Returns null without touching * Cloudflare when the build has no sitekey or the backend does not enforce * the check; null also when acquisition fails. */ private _acquireTurnstileWithChallenge; /** * Look up a tool call's current chatSession-side status by id. * Used to decide between addToolCall (first sighting) and * updateToolCall (subsequent updates) when AG-UI re-emits * `tool-call` events for client tools transitioning to 'pending'. */ private _findToolCallStatus; /** * Convert one server-transcript message (the session store shape: * ``{id, role, content, timestamp, status, toolCalls?}`` with toolCalls * in AG-UI wire shape) into a TrailMessage. Returns null for entries the * trail can't render (missing id, system/tool roles, empty content with * no tool receipts) — the transcript may legitimately contain them. */ private _snapshotToTrailMessage; /** AG-UI wire-shape toolCalls → settled TrailToolCall receipts. */ private _snapshotToolCalls; /** Map AG-UI ToolCallStatus to TrailToolCall status. */ private _mapToolCallStatus; private _onTransportEvent; } /** * The module-level singleton. Imported by both the SDK runtime * bootstrap (to call configure) and any code that needs to read * transport state. Mirrors the chatSession singleton shape. */ export declare const chatTransport: ChatTransport; //# sourceMappingURL=ChatTransport.d.ts.map