@vinaverse/client 0.1.0-alpha.1 → 0.1.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +127 -1
  3. package/dist/agent/index.cjs +3321 -0
  4. package/dist/agent/index.cjs.map +1 -0
  5. package/dist/agent/index.d.cts +57 -0
  6. package/dist/agent/index.d.ts +57 -0
  7. package/dist/agent/index.js +99 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/backend/index.cjs +295 -0
  10. package/dist/backend/index.cjs.map +1 -0
  11. package/dist/backend/index.d.cts +82 -0
  12. package/dist/backend/index.d.ts +82 -0
  13. package/dist/backend/index.js +277 -0
  14. package/dist/backend/index.js.map +1 -0
  15. package/dist/chunk-46D3FSLU.js +997 -0
  16. package/dist/chunk-46D3FSLU.js.map +1 -0
  17. package/dist/chunk-D56MNG3E.js +9 -0
  18. package/dist/chunk-D56MNG3E.js.map +1 -0
  19. package/dist/{chunk-AWHPWRGT.js → chunk-GWLLUOFY.js} +71 -15
  20. package/dist/chunk-GWLLUOFY.js.map +1 -0
  21. package/dist/chunk-JI6HUXH3.js +861 -0
  22. package/dist/chunk-JI6HUXH3.js.map +1 -0
  23. package/dist/contract-Be2oVHNr.d.cts +6 -0
  24. package/dist/contract-Be2oVHNr.d.ts +6 -0
  25. package/dist/conversation/index.cjs +356 -27
  26. package/dist/conversation/index.cjs.map +1 -1
  27. package/dist/conversation/index.d.cts +23 -307
  28. package/dist/conversation/index.d.ts +23 -307
  29. package/dist/conversation/index.js +36 -760
  30. package/dist/conversation/index.js.map +1 -1
  31. package/dist/history/index.cjs +282 -0
  32. package/dist/history/index.cjs.map +1 -0
  33. package/dist/history/index.d.cts +91 -0
  34. package/dist/history/index.d.ts +91 -0
  35. package/dist/history/index.js +261 -0
  36. package/dist/history/index.js.map +1 -0
  37. package/dist/index.cjs +70 -8
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +2 -1
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.js +2 -1
  42. package/dist/runtime-6O0qIPmo.d.cts +394 -0
  43. package/dist/runtime-CNgz2_8G.d.ts +394 -0
  44. package/dist/{session--W6JXfwo.d.cts → session-D0ijOQX3.d.cts} +3330 -1614
  45. package/dist/{session--W6JXfwo.d.ts → session-D0ijOQX3.d.ts} +3330 -1614
  46. package/dist/store-CGRSxVcL.d.ts +414 -0
  47. package/dist/store-CxoHwd64.d.cts +414 -0
  48. package/dist/testing/index.cjs +418 -0
  49. package/dist/testing/index.cjs.map +1 -0
  50. package/dist/testing/index.d.cts +97 -0
  51. package/dist/testing/index.d.ts +97 -0
  52. package/dist/testing/index.js +403 -0
  53. package/dist/testing/index.js.map +1 -0
  54. package/package.json +105 -11
  55. package/dist/chunk-AWHPWRGT.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/events.ts","../../src/agent/cards.ts","../../src/engine.ts","../../src/errors.ts","../../src/secret.ts","../../src/sse.ts","../../src/session.ts","../../src/conversation/links.ts","../../src/conversation/timeline.ts","../../src/conversation/store.ts","../../src/agent/runtime.ts"],"names":["text","field","OUTCOMES","str","b","kept","current","list"],"mappings":";;;AAwCA,IAAM,UAAA,GAAqC;AAAA,EACzC,YAAA,EAAc,IAAA;AAAA,EACd,SAAA,EAAW,IAAA;AAAA,EACX,OAAA,EAAS,IAAA;AAAA,EACT,UAAA,EAAY,IAAA;AAAA,EACZ,OAAA,EAAS,IAAA;AAAA,EACT,KAAA,EAAO,IAAA;AAAA,EACP,MAAA,EAAQ,IAAA;AAAA,EACR,OAAA,EAAS,IAAA;AAAA,EACT,YAAA,EAAc,IAAA;AAAA,EACd,YAAA,EAAc,IAAA;AAAA,EACd,QAAA,EAAU,IAAA;AAAA,EACV,OAAA,EAAS,IAAA;AAAA,EACT,KAAA,EAAO,IAAA;AAAA,EACP,QAAA,EAAU,IAAA;AAAA,EACV,QAAA,EAAU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C,IAAA,CAAK,GAAA,CAAI,KAAA,EAAO,GAAM,CAAA,GACtB,KAAA;AACN,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC3C,QAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,UAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,IAAI,CAAA;AACzC,UAAA,OAAA,EAAQ;AAAA,QACV,GAAG,IAAI,CAAA;AACP,QAAA,SAAS,IAAA,GAAO;AACd,UAAA,YAAA,CAAa,KAAK,CAAA;AAClB,UAAA,MAAA,CAAO,KAAK,CAAA;AAAA,QACd;AACA,QAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,MACxD,CAAC,CAAA;AACD,MAAA,OAAA,CAAQ,UAAU,CAAC,CAAA;AAAA,IACrB;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["// Typed events and cards, from the generated contract types (vinaverse-v1.yaml). Within v1 the server may add event\n// types, card kinds, question kinds and codes (docs/realtime-protocol.md §5), so inbound frames are never validated\n// strictly: an unknown event is ignored and an unknown card kind is skipped where it is drawn.\nimport type { components } from './generated/vinaverse-v1.js';\n\n/** Every schema of the pinned public contract (vinaverse-v1), by name: `Schemas['Session']`, `Schemas['Card']`, … */\nexport type Schemas = components['schemas'];\n\nexport type ClientEvent = Schemas['ClientEvent'];\nexport type ServerEvent = Schemas['ServerEvent'];\nexport type ServerEventType = ServerEvent['type'];\nexport type ServerEventOf<T extends ServerEventType> = Extract<\n ServerEvent,\n { type: T }\n>;\nexport type Card = Schemas['Card'];\nexport type CardKind = Card['kind'];\nexport type Question = Schemas['Question'];\nexport type AnswerInput = Schemas['AnswerInput'];\nexport type Proposal = Schemas['Proposal'];\nexport type TranscriptItem = Schemas['TranscriptItem'];\nexport type ClientSecret = Schemas['ClientSecret'];\nexport type TurnInput = Schemas['TurnInput'];\n/** v1-draft.20: the tenant's greeting for the session's mode, and the chips that send a message as the person's own. */\nexport type Welcome = Schemas['Welcome'];\nexport type CardImage = Schemas['CardImage'];\nexport type CardGroup = Schemas['CardGroup'];\nexport type CardLink = Schemas['CardLink'];\n/** The session as createSession returns it to the tenant's backend, which passes this part to the app. */\nexport type SessionInfo = Pick<\n Schemas['Session'],\n 'id' | 'realtime_url' | 'turns_url' | 'conversation_id'\n> & {\n client_secret: ClientSecret | string;\n};\n\n/** The outcomes an app reports on a proposal card with `ui.action`. */\nexport type ProposalOutcome = 'confirmed' | 'declined' | 'failed' | 'expired';\n\n// A record over every kind, so a kind added to the contract fails the type check until it is listed here.\nconst CARD_KINDS: Record<CardKind, true> = {\n professional: true,\n workspace: true,\n service: true,\n time_slots: true,\n booking: true,\n quote: true,\n policy: true,\n handoff: true,\n metric_chart: true,\n metric_table: true,\n gap_list: true,\n cluster: true,\n claim: true,\n document: true,\n question: true,\n proposal: true,\n next_step: true,\n links: true,\n};\n\n/** Whether this client knows how to read a card of this kind; skip any other card (§5). */\nexport function isKnownCard(card: { kind: string }): card is Card {\n return Object.hasOwn(CARD_KINDS, card.kind);\n}\n","// A card as a UI draws it: the contract's card read once, every field checked, so a renderer never meets a bad value\n// (a photo that is not https, a rating out of range, a group id the contract would refuse). A kind this client does not\n// know is null: the UI skips it (§5).\nimport type { CardLink, Schemas } from '../events.js';\nimport { isKnownCard } from '../events.js';\n\ntype Fields = Readonly<Record<string, unknown>>;\n\n/** An amount in minor units with its ISO 4217 currency. */\nexport interface AgentMoney {\n readonly amount: number;\n readonly currency: string;\n}\n\nexport interface AgentCardAction {\n readonly action: string;\n readonly label: string;\n readonly deepLink: string | null;\n}\n\n/** What a card is about, as the tenant's tools name it: a UI routes a tap on the card here. */\nexport interface AgentCardTarget {\n readonly type: string;\n readonly id: string;\n}\n\nexport interface ReadCard {\n readonly id: string;\n readonly kind: Schemas['Card']['kind'];\n /** `professional` and `workspace`: drawn as a listing (photo, rating, price from, next open time). */\n readonly listing: boolean;\n readonly title: string;\n readonly subtitle: string | null;\n readonly body: string | null;\n readonly badges: readonly string[];\n readonly actions: readonly AgentCardAction[];\n readonly target: AgentCardTarget | null;\n /** The hero photo: the first https image, else `image_url`; `ratio` is width / height when both are known. */\n readonly hero: { readonly url: string; readonly ratio: number | null } | null;\n readonly rating: { readonly stars: number; readonly count: number } | null;\n readonly priceFrom: AgentMoney | null;\n readonly price: AgentMoney | null;\n readonly nextAvailable: string | null;\n readonly startsAt: string | null;\n /** Cards one turn draws together; `carousel` draws them in a row, anything else a list. */\n readonly group: {\n readonly id: string;\n readonly layout: 'list' | 'carousel';\n } | null;\n /** A `links` card's links, each with a label of at most 40 code points and a known purpose. */\n readonly links: readonly CardLink[];\n /** A `proposal` card's proposal id. */\n readonly proposalId: string | null;\n}\n\nconst LISTING = new Set(['professional', 'workspace']);\nconst PURPOSES = new Set(['help', 'support', 'policy', 'contact', 'feedback']);\nconst GROUP_ID = /^[A-Za-z0-9_-]{1,64}$/;\nconst CURRENCY = /^[A-Z]{3}$/;\n\nconst isFields = (v: unknown): v is Fields =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\nconst text = (v: unknown): string | null => (typeof v === 'string' ? v : null);\nconst whole = (v: unknown): number | null =>\n typeof v === 'number' && Number.isInteger(v) ? v : null;\nconst list = (v: unknown): readonly unknown[] => (Array.isArray(v) ? v : []);\nconst https = (v: unknown): string | null => {\n const url = text(v);\n return url !== null && /^https:\\/\\//i.test(url) ? url : null;\n};\nconst instant = (v: unknown): string | null => {\n const at = text(v);\n return at !== null && !Number.isNaN(Date.parse(at)) ? at : null;\n};\n\nfunction money(v: unknown): AgentMoney | null {\n if (!isFields(v)) return null;\n const amount = whole(v.amount);\n const currency = text(v.currency);\n return amount !== null &&\n amount >= 0 &&\n currency !== null &&\n CURRENCY.test(currency)\n ? { amount, currency }\n : null;\n}\n\nfunction hero(card: Fields): ReadCard['hero'] {\n for (const image of list(card.images)) {\n if (!isFields(image)) continue;\n const url = https(image.url);\n if (url === null) continue;\n const width = whole(image.width);\n const height = whole(image.height);\n return {\n url,\n ratio: width && height && width > 0 && height > 0 ? width / height : null,\n };\n }\n const legacy = https(card.image_url);\n return legacy === null ? null : { url: legacy, ratio: null };\n}\n\n/** The contract's card (a `HeldCard`'s `card`, or a frame's), read for drawing; null for a kind this client skips. */\nexport function readCard(value: unknown): ReadCard | null {\n if (!isFields(value)) return null;\n const id = text(value.id);\n const kind = text(value.kind);\n const title = text(value.title);\n if (id === null || kind === null || title === null) return null;\n if (!isKnownCard({ kind })) return null;\n const rating = isFields(value.rating) ? value.rating : null;\n const ppm = whole(rating?.value_ppm);\n const count = whole(rating?.count);\n const group = isFields(value.group) ? value.group : null;\n const groupId = text(group?.id);\n const ref = isFields(value.ref) ? value.ref : null;\n const refType = text(ref?.type);\n const refId = text(ref?.id);\n const proposal = isFields(value.proposal) ? value.proposal : null;\n return {\n id,\n kind: kind as ReadCard['kind'],\n listing: LISTING.has(kind),\n title,\n subtitle: text(value.subtitle),\n body: text(value.body),\n badges: list(value.badges).filter(\n (b): b is string => typeof b === 'string',\n ),\n actions: list(value.actions).flatMap((a) => {\n if (!isFields(a)) return [];\n const action = text(a.action);\n const label = text(a.label);\n return action === null || label === null\n ? []\n : [{ action, label, deepLink: text(a.deep_link) }];\n }),\n target:\n refType !== null && refId !== null ? { type: refType, id: refId } : null,\n hero: hero(value),\n rating:\n ppm !== null &&\n count !== null &&\n ppm >= 0 &&\n ppm <= 5_000_000 &&\n count >= 0\n ? { stars: ppm / 1_000_000, count }\n : null,\n priceFrom: money(value.price_from),\n price: money(value.price),\n nextAvailable: instant(value.next_available),\n startsAt: instant(value.starts_at),\n group:\n groupId !== null && GROUP_ID.test(groupId)\n ? {\n id: groupId,\n layout: group?.layout === 'carousel' ? 'carousel' : 'list',\n }\n : null,\n links: list(value.links).flatMap((l) => {\n if (!isFields(l)) return [];\n const label = text(l.label);\n const url = text(l.url)?.trim() ?? '';\n const purpose = text(l.purpose);\n return label &&\n [...label].length <= 40 &&\n url &&\n purpose &&\n PURPOSES.has(purpose)\n ? [{ label, url, purpose: purpose as CardLink['purpose'] }]\n : [];\n }),\n proposalId: kind === 'proposal' ? text(proposal?.id) : null,\n };\n}\n","// The conversation engine: the state an app keeps for one agent\n// conversation, moved by what it sends, what it receives and what happens to\n// its connection, as docs/realtime-protocol.md decides it. It models what the\n// protocol decides (cards, locks, acknowledgements, resends, outcomes,\n// reconnects), never how an app draws it, and it is held to the shared\n// recordings (vinaverse-contracts conformance/realtime/*) by its tests.\n// Pure and synchronous: the session transport feeds it, and so can a test.\n\n/** A frame as received or sent: its `type`, and whatever else the contract gives it. */\nexport interface Frame {\n readonly type: string;\n readonly [field: string]: unknown;\n}\n\n/** A card as the app holds it. `locked` lists the question ids (the card's, or a `rate_each` row's) drawn locked. */\nexport interface HeldCard {\n readonly id: string;\n readonly kind: string;\n readonly card: Readonly<Record<string, unknown>>;\n readonly question?: HeldQuestion;\n readonly locked: readonly string[];\n /** The turn that drew the card, when known: `ui.action` names it with the card's `id`. */\n readonly turnId?: string;\n /** A proposal's first reported outcome (`confirmed`, `declined`, `failed`, `expired`); later ones change nothing. */\n readonly outcome?: string | null;\n /** Arrival order, shared with messages: a timeline sorts both by it. Moves when the card is drawn again. */\n readonly seq: number;\n}\n\nexport interface HeldQuestion {\n readonly question_id: string;\n readonly kind: string;\n readonly state: string;\n readonly answer?: unknown;\n readonly row_answers?: readonly { question_id: string; answer: unknown }[];\n readonly rows?: readonly { question_id: string }[];\n readonly [field: string]: unknown;\n}\n\nexport interface Message {\n readonly role: 'assistant' | 'person' | 'staff' | (string & {});\n readonly text: string;\n /**\n * Stable for the message's life, to key it in a list: a person's text by its `client_event_id`, an agent's reply by\n * its turn (`a:<turn_id>`), a staff reply by its `message_id` (`s:<id>`), a guardrail refusal by the input it answers\n * (`r:<client_event_id>`), a transcript item by its server `id` as the live key it matches, or by its time and role\n * (`t:<at>:<role>`) from a server that sends no `id`.\n */\n readonly key: string;\n /** Arrival order, shared with cards: a timeline sorts both by it. */\n readonly seq: number;\n /**\n * A reply cut off after some of it streamed; what streamed stands (§6): `blocked` (`output_blocked`), `interrupted`\n * (`cancelled`, as when a person from the business takes over, or the connection dropped), `failed` (any other code).\n */\n readonly partial?: 'blocked' | 'interrupted' | 'failed';\n /** A person's text recorded during a takeover (`input.received`): the business reads it; no agent turn runs. */\n readonly received?: true;\n /** The agent's reply is a guardrail refusal (`input.rejected` `guardrail`, its `message`). */\n readonly refusal?: true;\n}\n\n/** A person from the business is replying (`takeover.started`); `by` is their role as the person sees it. */\nexport interface Takeover {\n readonly by: string | null;\n readonly at: string;\n}\n\n/** The turn's text streamed so far (`message.delta`), until its `message.completed`. */\nexport interface Streaming {\n readonly turnId: string;\n readonly text: string;\n /** Taken at the turn's first delta, and kept by its message: a reply sorts before the cards its turn drew after it. */\n readonly seq: number;\n}\n\nexport interface Connection {\n readonly name: string;\n readonly state: 'open' | 'closed';\n readonly code?: number;\n readonly reason?: string;\n}\n\nexport interface ToolLine {\n readonly turn_id: string;\n readonly label: string;\n readonly state: string;\n}\n\n/**\n * Whether and how the conversation goes on after a connection ends:\n * - `allowed`: reconnect to the same session;\n * - `user_action_only`: the session was revoked or replaced (the conversation continued elsewhere): resume only when\n * the person asks;\n * - `new_session_on_next_action`: the session ended (idle, expired, limit_reached) but the conversation did not; its\n * secret is spent. On the person's next action, the app has its backend create a new session for the same\n * conversation and calls `resume()`.\n */\nexport type Reconnect =\n | 'allowed'\n | 'user_action_only'\n | 'new_session_on_next_action';\n\n/** The engine's whole state, for an app to draw. */\nexport interface ConversationState {\n readonly sessionId: string | null;\n readonly conversationId: string | null;\n readonly connection: Connection | null;\n /** How the conversation goes on after the connection ends (`Reconnect`). */\n readonly reconnect: Reconnect;\n readonly messages: readonly Message[];\n /** Every card held, oldest first. */\n readonly cards: readonly HeldCard[];\n /** The newest question card still open: the one to answer. */\n readonly openQuestion: string | null;\n /** Events sent and neither acknowledged nor refused, by `client_event_id`: resend them, same id, after a reconnect. */\n readonly unacknowledged: readonly Frame[];\n /** Ids refused for now (`turn_in_progress`, `screen_unavailable`): send again with the same id. */\n readonly resend: readonly string[];\n /**\n * Texts and answers refused with `limit_reached`: never resent in this session (it would get the same refusal);\n * resent, same id, on the next session's `session.ready`. Kept apart from `resend` (conformance README, `held`). A\n * refused action is dropped: a new session cannot act on an earlier session's card.\n */\n readonly held: readonly string[];\n /** Typed messages whose refusal stands, by `client_event_id`: shown as not sent, never resent. */\n readonly refused: Readonly<Record<string, string>>;\n /** The last `flow.completed`: `ok`, `refused` or `failed` (an unknown result reads as `failed`). */\n readonly flow: {\n readonly flow: unknown;\n readonly result: 'ok' | 'refused' | 'failed';\n } | null;\n /** The turn in progress. */\n readonly turn: string | null;\n /** The last state of each tool line (the last 100). */\n readonly tools: readonly ToolLine[];\n readonly handoffs: readonly unknown[];\n /** The codes of `error` and `turn.failed` events (the last 100). */\n readonly errors: readonly string[];\n /**\n * While `reconnect` is `new_session_on_next_action`: the `client_event_id`s held for the next session (unacknowledged,\n * or refused for this session's turn limit). Draw them as \"sends when you continue\", not as failed. Empty otherwise.\n */\n readonly heldForNextSession: readonly string[];\n /** Seconds left when `session.expiring` arrived (WebSocket only, about a minute before the end); null otherwise. */\n readonly expiring: number | null;\n /** The turn's text streamed so far, until its `message.completed` (or its end, which keeps it as a message). */\n readonly streaming: Streaming | null;\n /** While a person from the business replies (§8): from `takeover.started` to `takeover.ended`. */\n readonly takeover: Takeover | null;\n /** Every refusal's code and `message` (`input.rejected`), by `client_event_id`; `refused` lists those that stand. */\n readonly rejections: Readonly<\n Record<string, { code: string; message: string }>\n >;\n /** The AI disclosure `session.ready` carries: always shown, never removed. Null until the first one. */\n readonly disclosure: string | null;\n /** `session.ready`'s `limits.turns_left`, when given. */\n readonly turnsLeft: number | null;\n}\n\nconst UNLOCKS_KEEP_LOCKED = new Set([\n 'card_superseded',\n 'client_event_id_reused',\n]);\nconst RESEND = new Set(['turn_in_progress', 'screen_unavailable']);\nconst FLOW_RESULTS = new Set(['ok', 'refused', 'failed']);\nconst OUTCOMES = new Set(['confirmed', 'declined', 'failed', 'expired']);\n/** `session.closed` reasons after which the conversation goes on here: reconnect (idle, on the next input). */\n/** `server_restart`: reserved (the gateway does not send it today); the same session is reconnected to. */\nconst RECONNECTABLE = new Set(['server_restart']);\n/** The session ended, the conversation goes on: a new session on the next action. */\nconst NEW_SESSION = new Set(['idle', 'expired', 'limit_reached']);\nconst KEEP = 100;\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\ninterface Card {\n id: string;\n kind: string;\n card: Record<string, unknown>;\n question?: Mutable<HeldQuestion>;\n locked: string[];\n turnId?: string;\n outcome?: string | null;\n /** The `client_event_id` that reported `outcome`. */\n outcomeBy?: string;\n seq: number;\n}\n\nconst str = (v: unknown): string | undefined =>\n typeof v === 'string' ? v : undefined;\n\n// TypeScript `private` rather than `#` fields: the package ships ES2022 as is, and Hermes (React Native) has no\n// `#` private fields.\nexport class ConversationEngine {\n private sessionId: string | null = null;\n private conversationId: string | null = null;\n private connection: Mutable<Connection> | null = null;\n private reconnect: Reconnect = 'allowed';\n private messages: Message[] = [];\n private cards = new Map<string, Card>();\n private unacknowledged = new Map<string, Frame>();\n private resend: string[] = [];\n private held: string[] = [];\n private refused: Record<string, string> = {};\n private flow: ConversationState['flow'] = null;\n private turn: string | null = null;\n private tools: ToolLine[] = [];\n private handoffs: unknown[] = [];\n private errors: string[] = [];\n private expiring: number | null = null;\n private streaming: Streaming | null = null;\n private takeover: Takeover | null = null;\n private rejections: Record<string, { code: string; message: string }> = {};\n private disclosure: string | null = null;\n private turnsLeft: number | null = null;\n /** The next arrival number for a message or a card. */\n private seq = 0;\n /** The cards drawn before a resumed flow's transcript replaced them: proposal outcomes carry over. */\n private replaced: Map<string, Card> | null = null;\n /** client_event_id → the first event the app sent under it, until it is settled. */\n private readonly inputs = new Map<string, Frame>();\n\n // ------------------------------------------------------------ what happens around the frames\n\n /** The tenant's backend created a session (and named its conversation). */\n sessionCreated(sessionId: string, conversationId?: string | null): void {\n this.sessionId = sessionId;\n this.conversationId = conversationId ?? null;\n }\n\n /** A connection opened: the user's own action, or an allowed reconnect, so it lifts a hold on reconnecting. */\n connected(name: string): void {\n this.connection = { name, state: 'open' };\n this.reconnect = 'allowed';\n }\n\n /** A connection closed with its code. `4403` (revoked) and `4409` (replaced) hold reconnecting for a user action. */\n closed(name: string, code: number): void {\n if (this.connection?.name !== name) return;\n this.connection.state = 'closed';\n this.connection.code = code;\n // The session.closed reason decides when one preceded the close ({idle} then 4403 is still a new session on the\n // next action); the close code decides only on its own: 4403 and 4409 wait for the person, 4408 wants a new\n // session.\n if (this.connection.reason === undefined) {\n if (code === 4403 || code === 4409) this.reconnect = 'user_action_only';\n else if (code === 4408) this.reconnect = 'new_session_on_next_action';\n }\n this.cutOff('interrupted');\n this.turn = null;\n }\n\n /** The app was killed: what it drew is gone; what it sent and never saw acknowledged it kept, to resend. */\n killed(): void {\n this.messages = [];\n this.cards = new Map();\n this.turn = null;\n this.streaming = null;\n this.takeover = null; // announced again on the next connection's session.ready, if it goes on\n }\n\n // ------------------------------------------------------------ what the app sends\n\n sent(event: Frame): void {\n const id = str(event.client_event_id);\n switch (event.type) {\n case 'ui.answer': {\n if (id === undefined) return;\n if (!this.inputs.has(id)) this.inputs.set(id, event);\n this.unqueue(id);\n this.unacknowledged.set(id, event);\n const card = this.cards.get(str(event.card_id) ?? '');\n const questionId = str(event.question_id);\n if (card && questionId) lock(card, questionId);\n return;\n }\n case 'input.text': {\n if (id === undefined) return;\n if (!this.inputs.has(id)) this.inputs.set(id, event);\n this.unqueue(id);\n delete this.refused[id];\n this.unacknowledged.set(id, event);\n return;\n }\n case 'ui.action': {\n if (id !== undefined) {\n if (!this.inputs.has(id)) this.inputs.set(id, event);\n this.unqueue(id);\n this.unacknowledged.set(id, event);\n }\n const card = this.cards.get(str(event.card_id) ?? '');\n const action = str(event.action);\n if (\n card?.kind === 'proposal' &&\n action &&\n OUTCOMES.has(action) &&\n card.outcome === null\n ) {\n card.outcome = action;\n if (id !== undefined) card.outcomeBy = id;\n }\n return;\n }\n default:\n return;\n }\n }\n\n // ------------------------------------------------------------ what the server sends\n\n received(event: Frame): void {\n switch (event.type) {\n case 'session.ready':\n this.ready(event);\n return;\n case 'turn.started': {\n this.turn = str(event.turn_id) ?? null;\n const id = str(event.client_event_id);\n if (id !== undefined) {\n const sent = this.inputs.get(id);\n this.settle(id);\n if (sent?.type === 'input.text') {\n this.say('person', str(sent.text) ?? '', id);\n }\n }\n return;\n }\n case 'message.delta': {\n const turnId = str(event.turn_id) ?? '';\n const text = str(event.text) ?? '';\n if (this.streaming?.turnId === turnId)\n this.streaming = {\n ...this.streaming,\n text: this.streaming.text + text,\n };\n else {\n this.cutOff('interrupted'); // another turn's text, never completed\n this.streaming = { turnId, text, seq: this.seq++ };\n }\n return;\n }\n case 'message.completed': {\n const turnId = str(event.turn_id) ?? '';\n const streaming =\n this.streaming?.turnId === turnId ? this.streaming : null;\n if (streaming) this.streaming = null;\n this.say(\n 'assistant',\n str(event.text) ?? '',\n `a:${turnId}`,\n {},\n streaming?.seq,\n );\n return;\n }\n case 'ui.cards':\n for (const card of asArray(event.cards))\n this.hold(card, str(event.turn_id));\n return;\n case 'tool.status': {\n const line = {\n turn_id: str(event.turn_id) ?? '',\n label: str(event.label) ?? '',\n state: str(event.state) ?? '',\n };\n const at = this.tools.findIndex(\n (t) => t.turn_id === line.turn_id && t.label === line.label,\n );\n if (at === -1) this.tools = [...this.tools, line].slice(-KEEP);\n else this.tools[at] = line;\n return;\n }\n case 'handoff.created':\n this.handoffs.push(event.ticket);\n return;\n case 'turn.completed':\n this.turn = null;\n return;\n case 'turn.failed': {\n // What streamed before the failure stands (§6), cut off: blocked, interrupted (a takeover) or failed.\n const code = str(event.code) ?? '';\n if (this.streaming?.turnId === str(event.turn_id))\n this.cutOff(\n code === 'output_blocked'\n ? 'blocked'\n : code === 'cancelled'\n ? 'interrupted'\n : 'failed',\n );\n this.turn = null;\n this.error(code);\n return;\n }\n case 'takeover.started':\n this.takeover = {\n by: str(event.by) ?? null,\n at: str(event.at) ?? '',\n };\n return;\n case 'takeover.ended':\n this.takeover = null;\n return;\n case 'message.staff': {\n const id = str(event.message_id);\n if (id !== undefined)\n this.say('staff', str(event.text) ?? '', `s:${id}`);\n return;\n }\n case 'input.received': {\n // During a takeover: the text was recorded for the business; no turn runs, and it is never resent.\n const id = str(event.client_event_id);\n if (id === undefined) return;\n const sent = this.inputs.get(id);\n this.settle(id);\n if (sent?.type === 'input.text')\n this.say('person', str(sent.text) ?? '', id, { received: true });\n return;\n }\n case 'ui.answer.recorded':\n this.recorded(event);\n return;\n case 'ui.answer.rejected':\n this.rejected(event);\n return;\n case 'input.rejected':\n this.inputRejected(event);\n return;\n case 'flow.completed': {\n const result = str(event.result) ?? '';\n this.flow = {\n flow: event.flow,\n result: (FLOW_RESULTS.has(result) ? result : 'failed') as\n | 'ok'\n | 'refused'\n | 'failed',\n };\n return;\n }\n case 'session.closed': {\n const reason = str(event.reason);\n // No reason (a malformed frame): read as a bare close, so the close code that follows decides.\n if (reason === undefined) return;\n // Idle, expired, limit_reached: the session is over, the conversation is not; a new session on the next\n // action. A server restart (reserved): the same session again. Replaced, revoked, or a reason this client\n // does not know (read as revoked): only on a user action.\n if (NEW_SESSION.has(reason))\n this.reconnect = 'new_session_on_next_action';\n else if (!RECONNECTABLE.has(reason))\n this.reconnect = 'user_action_only';\n if (this.connection) this.connection.reason = reason;\n return;\n }\n case 'session.expiring':\n this.expiring =\n typeof event.seconds_left === 'number' ? event.seconds_left : null;\n return;\n case 'error': {\n this.error(str(event.code) ?? '');\n const id = str(event.client_event_id);\n // An older server's retryable error for an unchecked input: handled as input.rejected.\n if (id !== undefined && event.code === 'screen_unavailable') {\n this.inputRejected(event);\n } else if (id !== undefined) {\n this.settle(id);\n }\n return;\n }\n default:\n return; // an event type this client does not know is ignored\n }\n }\n\n private ready(event: Frame): void {\n const session = event.session as { id?: unknown } | undefined;\n this.sessionId = str(session?.id) ?? this.sessionId;\n this.turn = null;\n this.expiring = null;\n this.disclosure = str(event.disclosure) ?? this.disclosure;\n const limits = event.limits as { turns_left?: unknown } | undefined;\n this.turnsLeft =\n typeof limits?.turns_left === 'number' ? limits.turns_left : null;\n // A takeover still in progress is announced again after session.ready (§8).\n this.takeover = null;\n this.cutOff('interrupted');\n if (event.resumed !== true) return;\n // A resumed session brings the server's view of the conversation. With the live ids (v1-draft.17) it merges\n // into what the app holds, so older history the app loaded stays; without them it replaces what the app drew.\n if (event.transcript !== undefined && transcriptHasIds(event.transcript)) {\n this.mergeTranscript(asArray(event.transcript));\n } else if (event.transcript !== undefined) {\n this.messages = [];\n this.replaced = this.cards;\n this.cards = new Map();\n for (const item of asArray(event.transcript)) {\n if (item.role === 'card')\n this.hold(item.card as Record<string, unknown>);\n else {\n const role = str(item.role) ?? '';\n this.say(\n role,\n str(item.text) ?? '',\n transcriptKey(role, str(item.id), str(item.at)),\n item.interrupted === true ? { partial: 'interrupted' } : {},\n );\n }\n }\n }\n // The open question, and the proposals still awaiting an outcome.\n for (const card of asArray(event.pending_cards))\n this.hold(card, str(card.turn_id));\n this.replaced = null;\n }\n\n /**\n * A transcript merged by key: an item the app holds keeps its place, with the text the server recorded; one it does\n * not hold goes just after the nearest earlier item it does (just before the first later one when none came before,\n * at the end when it holds none of them). Nothing the app holds is dropped.\n */\n private mergeTranscript(items: Record<string, unknown>[]): void {\n const seqOf = (key: string | undefined) =>\n key === undefined\n ? undefined\n : (this.messages.find((m) => m.key === key) ?? this.cards.get(key))\n ?.seq;\n const keys = items.map((item) =>\n item.role === 'card'\n ? str((item.card as Frame | undefined)?.id)\n : transcriptKey(str(item.role) ?? '', str(item.id), str(item.at)),\n );\n let prev: number | undefined;\n items.forEach((item, i) => {\n const key = keys[i];\n if (key === undefined) return;\n const known = seqOf(key);\n let at: number | undefined;\n if (known === undefined) {\n // Halfway to the nearest held item: after the one before, or before the first one after; else at the end.\n const near =\n prev ??\n keys\n .slice(i + 1)\n .map(seqOf)\n .find((q) => q !== undefined);\n if (near !== undefined) {\n const seqs = [...this.messages, ...this.cards.values()].map(\n (h) => h.seq,\n );\n const bound =\n prev === undefined\n ? Math.max(near - 1, ...seqs.filter((q) => q < near))\n : Math.min(...seqs.filter((q) => q > near));\n if (Number.isFinite(bound)) at = (near + bound) / 2;\n }\n }\n if (item.role === 'card') this.hold(item.card as Frame, undefined, at);\n else {\n const text = str(item.text) ?? '';\n const partial = item.interrupted === true ? 'interrupted' : undefined;\n if (known === undefined)\n this.say(\n str(item.role) ?? '',\n text,\n key,\n partial ? { partial } : {},\n at,\n );\n else\n this.messages = this.messages.map((m) => {\n if (m.key !== key) return m;\n // The server's record stands: a reply cut off here but finished there is whole again.\n const { partial: local, ...rest } = m;\n const kept =\n partial ?? (local === 'interrupted' ? undefined : local);\n return {\n ...rest,\n text: text || m.text,\n ...(kept ? { partial: kept } : {}),\n };\n });\n }\n prev = seqOf(key);\n });\n this.messages.sort((a, b) => a.seq - b.seq);\n }\n\n private hold(\n raw: Record<string, unknown> | undefined,\n turnId?: string,\n at?: number,\n ): void {\n if (!raw) return;\n const id = str(raw.id);\n if (id === undefined) return;\n const kind = str(raw.kind) ?? '';\n const question = raw.question as Mutable<HeldQuestion> | undefined;\n const card: Card = {\n id,\n kind,\n card: raw,\n ...(question ? { question: structuredCopy(question) } : {}),\n locked: lockedFrom(question),\n ...(turnId !== undefined ? { turnId } : {}),\n // A card still held keeps its place when it is drawn again (a reconnect's pending cards, a repeated ui.cards).\n seq: this.cards.get(id)?.seq ?? at ?? this.seq++,\n };\n // A held answer keeps its question locked until it is resent (§2), however the card is drawn again (a resumed\n // session.ready, or a turn's ui.cards before the resend).\n for (const held of this.held) {\n const sent = this.inputs.get(held);\n if (sent?.type === 'ui.answer' && sent.card_id === id) {\n const questionId = str(sent.question_id);\n if (questionId !== undefined) lock(card, questionId);\n }\n }\n if (kind === 'proposal') {\n // Drawn again (a resumed session's pending cards, a repeated ui.cards): the outcome reported stands.\n const held = this.cards.get(id) ?? this.replaced?.get(id);\n card.outcome = held?.outcome ?? null;\n if (held?.outcomeBy !== undefined) card.outcomeBy = held.outcomeBy;\n }\n this.cards.delete(id); // newest last\n this.cards.set(id, card);\n }\n\n private recorded(event: Frame): void {\n const id = str(event.client_event_id) ?? '';\n const card = this.cards.get(str(event.card_id) ?? '');\n const sent = this.inputs.get(id);\n this.settle(id);\n if (!card?.question || !sent) return;\n const q = card.question;\n const questionId = str(event.question_id) ?? '';\n lock(card, questionId);\n if (q.kind === 'rate_each') {\n const rows = (q.row_answers ?? []).filter(\n (r) => r.question_id !== questionId,\n );\n q.row_answers = [\n ...rows,\n { question_id: questionId, answer: sent.answer },\n ];\n const answered = q.row_answers;\n if (\n (q.rows ?? []).every((r) =>\n answered.some((a) => a.question_id === r.question_id),\n )\n ) {\n q.state = 'answered';\n lock(card, q.question_id); // every row answered: the whole card is locked\n }\n } else {\n q.answer = sent.answer;\n q.state = 'answered';\n }\n }\n\n private rejected(event: Frame): void {\n this.settle(str(event.client_event_id) ?? '');\n const card = this.cards.get(str(event.card_id) ?? ''); // a rejected answer shows on its question\n const questionId = str(event.question_id);\n if (!card || questionId === undefined) return;\n if (UNLOCKS_KEEP_LOCKED.has(str(event.code) ?? '')) lock(card, questionId);\n else unlock(card, questionId); // the four unlocking codes, and any code this client does not know\n }\n\n private inputRejected(event: Frame): void {\n const id = str(event.client_event_id);\n if (id === undefined) return;\n this.unacknowledged.delete(id);\n const code = str(event.code) ?? '';\n this.rejections[id] = { code, message: str(event.message) ?? '' };\n if (RESEND.has(code)) {\n if (!this.resend.includes(id)) this.resend.push(id);\n return;\n }\n if (code === 'limit_reached') {\n // The session has no turns left (the socket stays open; no session.closed follows). A text or an answer never\n // ran: it is held for the next session of the conversation, which only the tenant's backend creates, on the\n // person's next action, and resent there under the same id, never in this session (it would get the same\n // refusal). An action is dropped: a new session cannot act on an earlier session's card.\n this.unqueue(id);\n const kind = this.inputs.get(id)?.type;\n if (kind === 'input.text' || kind === 'ui.answer') {\n if (!this.held.includes(id)) this.held.push(id);\n } else this.inputs.delete(id); // an action, or nothing this client sent\n this.reconnect = 'new_session_on_next_action';\n return;\n }\n // screened, guardrail, an unknown code…: shown as not sent, never resent. A duplicate's earlier turn stands.\n if (code !== 'duplicate') this.refused[id] = code;\n const sent = this.inputs.get(id);\n if (code === 'guardrail' && sent?.type === 'input.text') {\n // The tenant's refusal is the agent's reply to the person's text (§6).\n this.say('person', str(sent.text) ?? '', id);\n this.say('assistant', str(event.message) ?? '', `r:${id}`, {\n refusal: true,\n });\n }\n this.inputs.delete(id);\n }\n\n /** No longer to resend, nor held for the next session (sent again, or settled). */\n private unqueue(id: string): void {\n this.resend = this.resend.filter((r) => r !== id);\n this.held = this.held.filter((r) => r !== id);\n }\n\n /** An input acknowledged or refused for good: nothing more is resent under its id. */\n private settle(id: string): void {\n delete this.rejections[id]; // a refusal for now (turn_in_progress, screen_unavailable) no longer applies\n this.unacknowledged.delete(id);\n this.inputs.delete(id);\n this.unqueue(id); // a copy sent twice can be answered after a refusal\n }\n\n /** Adds a message once: a key already held (a frame seen twice) changes nothing. */\n private say(\n role: string,\n text: string,\n key: string,\n extra: Pick<Message, 'partial' | 'received' | 'refusal'> = {},\n seq?: number,\n ): void {\n if (this.messages.some((m) => m.key === key)) return;\n this.messages.push({ role, text, key, seq: seq ?? this.seq++, ...extra });\n }\n\n /** The turn's streamed text, kept as the agent's message when the turn ends without its `message.completed`. */\n private cutOff(partial: NonNullable<Message['partial']>): void {\n const streaming = this.streaming;\n this.streaming = null;\n // Stored as the runtime records it: trimmed (the reference client does the same).\n const text = streaming?.text.trim();\n if (streaming && text)\n this.say(\n 'assistant',\n text,\n `a:${streaming.turnId}`,\n { partial },\n streaming.seq,\n );\n }\n\n private error(code: string): void {\n this.errors = [...this.errors, code].slice(-KEEP);\n }\n\n /**\n * An input that could not be delivered, or whose retries are spent (`screen_unavailable` after the last try): it is\n * no longer resent. A typed message is shown as not sent, with `code`; an answer's question unlocks so the person\n * can answer again; a proposal outcome it reported is taken back, so it can be reported again.\n */\n giveUp(clientEventId: string, code: string): void {\n const sent = this.inputs.get(clientEventId);\n if (!sent) return;\n const rejection = this.rejections[clientEventId];\n this.resend = this.resend.filter((r) => r !== clientEventId);\n this.settle(clientEventId);\n const card = this.cards.get(str(sent.card_id) ?? '');\n if (sent.type === 'input.text') {\n this.refused[clientEventId] = code;\n if (rejection) this.rejections[clientEventId] = rejection; // its last message, shown with \"not sent\"\n } else if (sent.type === 'ui.answer') {\n const questionId = str(sent.question_id);\n if (card && questionId !== undefined) unlock(card, questionId);\n } else if (card?.outcomeBy === clientEventId) {\n card.outcome = null;\n delete card.outcomeBy;\n }\n }\n\n /** A turn the app stopped where no event will say so (an SSE turn cancelled): none is in progress. */\n turnEnded(): void {\n this.turn = null;\n }\n\n // ------------------------------------------------------------ reading it\n\n /** The event first sent under a `client_event_id`, to resend it unchanged. */\n input(clientEventId: string): Frame | undefined {\n return this.inputs.get(clientEventId);\n }\n\n state(): ConversationState {\n const cards = [...this.cards.values()].map(freeze);\n const open = cards.filter(\n (c) => c.kind === 'question' && c.question?.state === 'open',\n );\n return {\n sessionId: this.sessionId,\n conversationId: this.conversationId,\n connection: this.connection ? { ...this.connection } : null,\n reconnect: this.reconnect,\n messages: [...this.messages],\n cards,\n openQuestion: open.length ? (open[open.length - 1] as HeldCard).id : null,\n unacknowledged: [...this.unacknowledged.values()],\n resend: [...this.resend],\n held: [...this.held],\n refused: { ...this.refused },\n flow: this.flow,\n turn: this.turn,\n tools: [...this.tools],\n handoffs: [...this.handoffs],\n errors: [...this.errors],\n streaming: this.streaming,\n takeover: this.takeover,\n rejections: { ...this.rejections },\n disclosure: this.disclosure,\n turnsLeft: this.turnsLeft,\n heldForNextSession:\n this.reconnect === 'new_session_on_next_action'\n ? [\n ...new Set([\n ...this.unacknowledged.keys(),\n ...this.resend,\n ...this.held,\n ]),\n ]\n : [],\n expiring: this.expiring,\n };\n }\n}\n\n/**\n * A transcript item's key: the live one when the server names it (`id`, v1-draft.17: the turn, the\n * `client_event_id` or the staff `message_id`), so a resumed message keeps the key it was drawn under; its time and\n * role from an older server.\n */\nfunction transcriptKey(\n role: string,\n id: string | undefined,\n at: string | undefined,\n): string {\n if (id === undefined) return `t:${at ?? ''}:${role}`;\n if (role === 'assistant') return `a:${id}`;\n if (role === 'staff') return `s:${id}`;\n return id;\n}\n\n/**\n * Whether a resumed transcript names every message by its live id (v1-draft.17), so it can merge into what the app\n * holds by key. A card item is named by its card's `id`.\n */\nexport function transcriptHasIds(transcript: unknown): boolean {\n return asArray(transcript).every((item) =>\n item.role === 'card'\n ? str((item.card as Record<string, unknown> | undefined)?.id) !==\n undefined\n : str(item.id) !== undefined,\n );\n}\n\nfunction lockedFrom(question: HeldQuestion | undefined): string[] {\n if (!question) return [];\n if (question.state !== 'open') {\n return [\n question.question_id,\n ...(question.rows ?? []).map((r) => r.question_id),\n ];\n }\n return (question.row_answers ?? []).map((r) => r.question_id);\n}\n\nfunction lock(card: Card, id: string): void {\n if (!card.locked.includes(id)) card.locked.push(id);\n}\n\nfunction unlock(card: Card, id: string): void {\n card.locked = card.locked.filter((q) => q !== id);\n}\n\nfunction freeze(card: Card): HeldCard {\n return {\n id: card.id,\n kind: card.kind,\n card: card.card,\n ...(card.question ? { question: { ...card.question } } : {}),\n locked: [...card.locked],\n ...(card.turnId !== undefined ? { turnId: card.turnId } : {}),\n ...(card.outcome !== undefined ? { outcome: card.outcome } : {}),\n seq: card.seq,\n };\n}\n\nfunction asArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? (value as Record<string, unknown>[]) : [];\n}\n\nfunction structuredCopy<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n","/** Why the client refused to do something; `code` is stable, `message` is for people. */\nexport type ClientErrorCode =\n /** A service key (`vv_sk_`) was given: it belongs on the tenant's backend, never in an app. */\n | 'service_key'\n /** The value is not a client secret (`vv_cs_` and at least 16 base64url characters). */\n | 'invalid_secret'\n /** The action needs the WebSocket (answers to question cards); the session runs over SSE. */\n | 'needs_websocket'\n /** The session was closed by the app, or ended for good (replaced, revoked, expired). */\n | 'session_ended'\n /** An SSE request failed: `status` holds the HTTP status. */\n | 'http_error'\n /**\n * The session ended but the conversation did not (idle, expired, its turn limit): its secret is spent. Have your\n * backend create a new session for the conversation and call `resume()` with it.\n */\n | 'needs_new_session';\n\nexport class VinaverseClientError extends Error {\n override readonly name = 'VinaverseClientError';\n readonly code: ClientErrorCode;\n readonly status: number | undefined;\n\n constructor(code: ClientErrorCode, message: string, status?: number) {\n super(message);\n this.code = code;\n this.status = status;\n }\n}\n","import { VinaverseClientError } from './errors.js';\n\nconst CLIENT_SECRET = /^vv_cs_[A-Za-z0-9_-]{16,}$/;\n\n/**\n * The client secret, checked: an app holds only the session's `vv_cs_` secret, which the tenant's backend got from\n * createSession. A service key is refused outright, so it never reaches a socket or a request from an app. The error\n * never repeats the value.\n */\nexport function clientSecret(value: unknown): string {\n const secret =\n typeof value === 'object' && value !== null\n ? (value as { value?: unknown }).value\n : value;\n if (typeof secret === 'string' && secret.startsWith('vv_sk_')) {\n throw new VinaverseClientError(\n 'service_key',\n 'A Vinaverse service key belongs on your backend only. Pass the session client secret (vv_cs_…) to the app.',\n );\n }\n if (typeof secret !== 'string' || !CLIENT_SECRET.test(secret)) {\n throw new VinaverseClientError(\n 'invalid_secret',\n 'Expected a session client secret (vv_cs_…).',\n );\n }\n return secret;\n}\n","// The SSE fallback (createTurnSse, createCardActionSse): one POST per turn, whose response streams that turn's\n// ServerEvents. Each SSE event's `event:` is a ServerEvent `type` and its `data:` the event JSON.\n\nimport type { Frame } from './engine.js';\nimport { VinaverseClientError } from './errors.js';\n\n/** The largest SSE event read: a ServerEvent is far smaller; more means the stream is not what it should be. */\nconst MAX_EVENT_CHARS = 1024 * 1024;\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/** One SSE request: where and with which secret, and the `fetch` to use. */\nexport interface SseTarget {\n /** The session's `turns_url` (`…/v1/sessions/{session_id}/turns`). */\n readonly turnsUrl: string;\n readonly secret: string;\n readonly fetch?: FetchLike;\n readonly signal?: AbortSignal;\n}\n\n/** Run one turn from a typed message (`createTurnSse`), yielding its events as they arrive. */\nexport function turnSse(\n target: SseTarget,\n input: { text: string; client_event_id?: string },\n): AsyncGenerator<Frame> {\n return post(target, target.turnsUrl, input);\n}\n\n/** Send a card action, such as a proposal outcome, and stream the resulting turn (`createCardActionSse`). */\nexport function cardActionSse(\n target: SseTarget,\n turnId: string,\n input: { card_id: string; action: string; client_event_id?: string },\n): AsyncGenerator<Frame> {\n return post(\n target,\n `${target.turnsUrl.replace(/\\/+$/, '')}/${encodeURIComponent(turnId)}/actions`,\n input,\n );\n}\n\nasync function* post(\n target: SseTarget,\n url: string,\n body: unknown,\n): AsyncGenerator<Frame> {\n const doFetch = target.fetch ?? globalThis.fetch;\n const response = await doFetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${target.secret}`,\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n },\n body: JSON.stringify(body),\n ...(target.signal ? { signal: target.signal } : {}),\n });\n if (!response.ok) {\n throw new VinaverseClientError(\n 'http_error',\n `The turn request failed with HTTP ${response.status}.`,\n response.status,\n );\n }\n // React Native's fetch has no streaming body: the events then arrive together, when the turn ends.\n const chunks = response.body\n ? decode(response.body)\n : once(await response.text());\n yield* sseFrames(chunks);\n}\n\n/** Frames from an SSE text stream: blank-line separated events, `data:` lines joined; comments and non-JSON skipped. */\nexport async function* sseFrames(\n chunks: AsyncIterable<string>,\n): AsyncGenerator<Frame> {\n let buffer = '';\n for await (const chunk of chunks) {\n buffer += chunk;\n if (buffer.length > MAX_EVENT_CHARS && boundary(buffer) === null) {\n throw new VinaverseClientError(\n 'http_error',\n 'An SSE event is larger than 1 MiB.',\n );\n }\n let end = boundary(buffer);\n while (end !== null) {\n const frame = parseEvent(buffer.slice(0, end.at));\n buffer = buffer.slice(end.at + end.length);\n if (frame) yield frame;\n end = boundary(buffer);\n }\n }\n const last = parseEvent(buffer);\n if (last) yield last;\n}\n\nfunction boundary(buffer: string): { at: number; length: number } | null {\n const match = /\\r?\\n\\r?\\n|\\r\\r/.exec(buffer);\n return match ? { at: match.index, length: match[0].length } : null;\n}\n\nfunction parseEvent(block: string): Frame | null {\n let type: string | undefined;\n const data: string[] = [];\n for (const line of block.split(/\\r?\\n|\\r/)) {\n if (line === '' || line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? '' : line.slice(colon + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n if (field === 'event') type = value;\n else if (field === 'data') data.push(value);\n }\n if (data.length === 0) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(data.join('\\n'));\n } catch {\n return null;\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))\n return null;\n const frame = parsed as Record<string, unknown>;\n const kind = typeof frame.type === 'string' ? frame.type : type;\n return kind === undefined ? null : ({ ...frame, type: kind } as Frame);\n}\n\nasync function* decode(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n yield decoder.decode(value, { stream: true });\n }\n const rest = decoder.decode();\n if (rest) yield rest;\n } finally {\n reader.releaseLock();\n }\n}\n\nasync function* once(text: string): AsyncGenerator<string> {\n yield text;\n}\n","// The realtime session for apps: one conversation with an agent over the WebSocket (docs/realtime-protocol.md), with the\n// SSE turns as the fallback. It authenticates with the session's client secret only, reconnects and resumes from\n// `session.ready`, resends what was never acknowledged under the same `client_event_id`, retries what was refused\n// for now, and holds the conversation's state in a ConversationEngine. Headless: an app draws from `state`.\nimport {\n ConversationEngine,\n type ConversationState,\n type Frame,\n} from './engine.js';\nimport { VinaverseClientError } from './errors.js';\nimport type {\n AnswerInput,\n ClientEvent,\n ClientSecret,\n ProposalOutcome,\n ServerEvent,\n SessionInfo,\n} from './events.js';\nimport { clientSecret } from './secret.js';\nimport { cardActionSse, type FetchLike, turnSse } from './sse.js';\n\n/** The part of a WebSocket the session uses: the browser, React Native and Node 22+ ones all fit. */\nexport interface WebSocketLike {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: ((event: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: ((event: { code: number; reason?: string }) => void) | null;\n onerror: ((event: unknown) => void) | null;\n}\n\n/**\n * Opens a WebSocket. `headers` is set only with `auth: 'header'`. The default factory passes them as React Native's\n * WebSocket takes them (its third argument) or, on Node 22+, as its WebSocket does (`{ protocols, headers }`); a\n * browser's WebSocket cannot send headers, so browsers use the subprotocol.\n */\nexport type WebSocketFactory = (\n url: string,\n protocols: string[],\n headers?: Record<string, string>,\n) => WebSocketLike;\n\n/** How the client secret reaches the server (§1); the secret never goes in the URL. */\nexport type AuthMode = 'header' | 'subprotocol' | 'first_frame';\n\nexport type SessionStatus =\n /** Opening a connection, or waiting for `session.ready`. */\n | 'connecting'\n /** `session.ready` arrived: events flow. */\n | 'ready'\n /** Waiting to reconnect after the connection dropped. */\n | 'reconnecting'\n /** Disconnected; connects again on the next send or `connect()`. */\n | 'idle'\n /** Running turns over SSE, because the WebSocket could not be opened (twice); `connect()` tries it again. */\n | 'sse'\n /**\n * The session ended. `state.reconnect` says what next: `new_session_on_next_action` after it ended idle, expired\n * or at its limit (have your backend create a new session for the conversation on the person's next action, then\n * `resume()` it; what they send meanwhile is held and resent there), or `user_action_only` (the conversation\n * continued elsewhere, or the session was revoked: resume only when the person asks).\n */\n | 'ended'\n /** The client secret was refused (4401) and no fresh one could be had. */\n | 'unauthorized'\n /** Closed by the app. */\n | 'closed';\n\nexport interface SessionOptions {\n /** The session the tenant's backend created: its `id`, `realtime_url`, `turns_url` and `client_secret`. */\n readonly session: SessionInfo;\n /**\n * A fresh client secret for the session named, from the tenant's backend (refreshClientSecret is a service-key\n * call), when the server refuses the current one (4401): for example after the first connection's window (two\n * minutes from issue on the current gateway) passed. It is asked for the session in use; an answer that arrives\n * after `resume()` moved to another session, or after `close()`, is dropped. Without it, a refused secret ends in\n * `unauthorized`.\n */\n readonly refreshSecret?: (\n sessionId: string,\n ) => Promise<ClientSecret | string>;\n /**\n * Default `subprotocol` (`vinaverse.v1, bearer.<secret>`). `header` where the WebSocket takes headers: React\n * Native and Node 22+ with the default factory, or your own `webSocket`.\n */\n readonly auth?: AuthMode;\n /** Default: the global WebSocket. */\n readonly webSocket?: WebSocketFactory;\n /** Default: the global fetch. Used by the SSE fallback. */\n readonly fetch?: FetchLike;\n /** Fall back to SSE turns when the WebSocket cannot be opened. Default true. */\n readonly sseFallback?: boolean;\n /** Delays before reconnecting after a drop, in ms; the last one repeats. Default 1 s doubling to 30 s. */\n readonly reconnectDelays?: readonly number[];\n /** Attempts to reconnect before going `idle`; they count again once a connection stayed up 30 s. Default 8. */\n readonly maxReconnects?: number;\n /** Delays before resending an input refused with `screen_unavailable`, in ms. Default 2 s, 4 s, 8 s. */\n readonly screenRetryDelays?: readonly number[];\n /** The `ping` interval while in the foreground, in ms. Default 25 s. */\n readonly pingInterval?: number;\n /** New `client_event_id`s. Default: random, `ce_` and 22 characters. */\n readonly createId?: () => string;\n /** An engine to continue, for example one an app kept across a restart. */\n readonly engine?: ConversationEngine;\n}\n\nexport interface SessionEvents {\n /**\n * Every event the server sends, `message.delta` included. A type this client does not know arrives too (§5), so a\n * `switch` on `type` keeps a default branch.\n */\n event: ServerEvent;\n /** The conversation's state changed. */\n state: ConversationState;\n status: SessionStatus;\n /**\n * Something failed that no call returned: an input that could not be delivered (it is also shown as not sent in\n * the state), an SSE turn, or getting a fresh secret.\n */\n error: VinaverseClientError;\n}\n\ntype Listener<T> = (value: T) => void;\n\nconst OPEN = 1;\nconst SUBPROTOCOL = 'vinaverse.v1';\nconst DEFAULT_RECONNECT = [1000, 2000, 4000, 8000, 16000, 30000];\nconst DEFAULT_SCREEN_RETRY = [2000, 4000, 8000];\nconst NO_RECONNECT = new Set([4403, 4409]);\n/** Failed first connections before falling back to SSE. */\nconst FALLBACK_AFTER = 2;\n/** A connection up this long gives the reconnect budget back. */\nconst STABLE_MS = 30_000;\n\n/** Why an SSE request was stopped. */\ntype Stop = 'close' | 'cancel';\n\n/** An SSE request in flight: the input it delivers, and why it was stopped (tracked here, not in the signal). */\ninterface Stream {\n readonly id: string | undefined;\n stop?: Stop;\n}\n\n// TypeScript `private` rather than `#` fields: the package ships ES2022 as is, and Hermes (React Native) has no\n// `#` private fields.\nexport class VinaverseSession {\n readonly engine: ConversationEngine;\n private info: SessionInfo;\n private secret: string;\n private readonly options: SessionOptions;\n private socket: WebSocketLike | null = null;\n /** The engine's name for the connection in `socket`, once it opened. */\n private opened: string | null = null;\n private connection = 0;\n private ready = false;\n private current: SessionStatus = 'idle';\n private everOpened = false;\n private firstFailures = 0;\n private attempts = 0;\n /** The reason of the `session.closed` that preceded the close, on the current connection. */\n private closeReason: string | null = null;\n private stableTimer: ReturnType<typeof setTimeout> | undefined;\n /** SSE requests in flight. */\n private readonly streams = new Map<AbortController, Stream>();\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n private pingTimer: ReturnType<typeof setInterval> | undefined;\n private foreground = true;\n private refreshed = false;\n /** client_event_id → why it waits: after the turn, or after a backoff. */\n private readonly waiting = new Map<string, 'turn' | 'screen'>();\n /** client_event_id → the session that refused it for its turn limit: resent only on another session. */\n private readonly heldForSession = new Map<string, string>();\n private readonly screenTries = new Map<string, number>();\n private readonly screenTimers = new Map<\n string,\n ReturnType<typeof setTimeout>\n >();\n private readonly listeners: {\n [K in keyof SessionEvents]: Set<Listener<SessionEvents[K]>>;\n } = {\n event: new Set(),\n state: new Set(),\n status: new Set(),\n error: new Set(),\n };\n\n constructor(options: SessionOptions) {\n this.options = options;\n this.info = options.session;\n this.secret = clientSecret(options.session.client_secret);\n this.engine = options.engine ?? new ConversationEngine();\n this.named(options.session);\n }\n\n /** The engine names the session, and keeps the conversation it already knew when this one does not say. */\n private named(session: SessionInfo): void {\n this.engine.sessionCreated(\n session.id,\n session.conversation_id ?? this.engine.state().conversationId,\n );\n }\n\n get status(): SessionStatus {\n return this.current;\n }\n\n get state(): ConversationState {\n return this.engine.state();\n }\n\n on<K extends keyof SessionEvents>(\n name: K,\n listener: Listener<SessionEvents[K]>,\n ): () => void {\n this.listeners[name].add(listener);\n return () => this.listeners[name].delete(listener);\n }\n\n // ------------------------------------------------------------ connecting\n\n /**\n * Connect, or reconnect: the user's own action, so it also resumes after the conversation continued elsewhere\n * or the secret was refused.\n */\n connect(): void {\n if (this.current === 'closed') throw ended();\n if (this.engine.state().reconnect === 'new_session_on_next_action') {\n // The secret is spent: a connection with it would only be refused (and read as \"continued elsewhere\").\n throw new VinaverseClientError(\n 'needs_new_session',\n 'This session has ended; create a new session for the conversation and call resume() with it.',\n );\n }\n this.start();\n }\n\n private start(): void {\n this.cancelReconnect();\n this.attempts = 0;\n this.refreshed = false;\n this.open();\n }\n\n /**\n * Continue the conversation on a new session the tenant's backend created for it (by `conversation_key` or\n * `conversation_id`): its `session.ready` brings the transcript and pending cards, and what was never\n * acknowledged is resent there. A user action, like `connect()`.\n */\n resume(session: SessionInfo): void {\n const secret = clientSecret(session.client_secret);\n if (this.current === 'closed') throw ended();\n this.info = session;\n this.secret = secret;\n this.named(session);\n this.drop(1000);\n this.start();\n }\n\n /** Close for good: the connection, any SSE turn still streaming, and every timer. */\n close(): void {\n this.cancelReconnect();\n this.drop(1000);\n this.stopSse('close');\n for (const timer of this.screenTimers.values()) clearTimeout(timer);\n this.screenTimers.clear();\n this.setStatus('closed');\n }\n\n /** Ping only while the app is in the foreground (every 25 s); in the background the connection may idle out. */\n setForeground(foreground: boolean): void {\n this.foreground = foreground;\n if (foreground && this.ready) this.startPing();\n else this.stopPing();\n }\n\n private open(): void {\n this.drop(1000);\n const factory = this.options.webSocket ?? defaultWebSocket();\n if (!factory) {\n this.fallBack();\n return;\n }\n const auth = this.options.auth ?? 'subprotocol';\n const protocols =\n auth === 'subprotocol'\n ? [SUBPROTOCOL, `bearer.${this.secret}`]\n : [SUBPROTOCOL];\n const headers =\n auth === 'header'\n ? { authorization: `Bearer ${this.secret}` }\n : undefined;\n const name = `c${++this.connection}`;\n this.closeReason = null;\n let socket: WebSocketLike;\n try {\n socket = factory(this.info.realtime_url, protocols, headers);\n } catch {\n this.fallBack();\n return;\n }\n this.socket = socket;\n this.ready = false;\n this.setStatus(this.attempts > 0 ? 'reconnecting' : 'connecting');\n socket.onopen = () => {\n if (this.socket !== socket) return;\n this.opened = name;\n this.everOpened = true;\n this.engine.connected(name);\n this.emitState();\n if (auth === 'first_frame')\n socket.send(\n JSON.stringify({ type: 'session.auth', client_secret: this.secret }),\n );\n };\n socket.onmessage = (event) => {\n if (this.socket === socket) this.frame(event.data);\n };\n socket.onerror = () => {};\n socket.onclose = (event) => {\n if (this.socket !== socket) return;\n const opened = this.opened !== null;\n this.forget(event.code);\n this.afterClose(event.code, opened);\n };\n }\n\n private afterClose(code: number, opened: boolean): void {\n if (this.current === 'closed') return;\n if (this.engine.state().reconnect !== 'allowed' || NO_RECONNECT.has(code)) {\n this.setStatus('ended');\n return;\n }\n if (code === 4401) {\n this.refresh();\n return;\n }\n if (!opened && !this.everOpened) {\n // Never connected yet: try once more before running turns over SSE.\n this.firstFailures++;\n if (\n this.firstFailures >= FALLBACK_AFTER &&\n this.options.sseFallback !== false\n ) {\n this.fallBack();\n return;\n }\n this.scheduleReconnect();\n return;\n }\n // server_restart is reserved (the gateway does not send it today): the same session again, with backoff.\n if (this.closeReason === 'server_restart') {\n this.scheduleReconnect();\n return;\n }\n if (code === 1000) {\n this.setStatus('idle'); // reconnect on the next send\n return;\n }\n this.scheduleReconnect();\n }\n\n /** After a 4401: one fresh secret for the session in use, unless it moved on or was closed meanwhile. */\n private refresh(): void {\n const refreshSecret = this.options.refreshSecret;\n if (!refreshSecret || this.refreshed) {\n this.setStatus('unauthorized');\n return;\n }\n this.refreshed = true;\n const sessionId = this.info.id;\n const current = () =>\n this.current !== 'closed' && this.info.id === sessionId;\n refreshSecret(sessionId)\n .then((fresh) => {\n if (!current()) return;\n this.secret = clientSecret(fresh);\n this.open();\n })\n .catch((error: unknown) => {\n if (!current()) return;\n this.setStatus('unauthorized');\n this.emit('error', asClientError(error, 'invalid_secret'));\n });\n }\n\n private scheduleReconnect(): void {\n const max = this.options.maxReconnects ?? 8;\n if (this.attempts >= max) {\n this.setStatus('idle');\n return;\n }\n const delays = this.options.reconnectDelays ?? DEFAULT_RECONNECT;\n const delay = delays[Math.min(this.attempts, delays.length - 1)] ?? 0;\n this.attempts++;\n this.setStatus('reconnecting');\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined;\n this.open();\n }, delay);\n }\n\n private cancelReconnect(): void {\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = undefined;\n }\n\n private fallBack(): void {\n this.socket = null;\n if (this.options.sseFallback === false) {\n this.setStatus('idle');\n return;\n }\n this.setStatus('sse');\n // What was held for the WebSocket goes over SSE now (an answer cannot: it is shown as not sent); what is\n // already streaming over SSE is not sent twice.\n for (const event of this.engine.state().unacknowledged) this.overSse(event);\n // Inputs waiting for a turn to end: with no SSE turn running, none will end to resend them.\n if (this.streams.size === 0) this.resendWaiting('turn');\n }\n\n /** Close the current connection, if any, without reacting to its close event. */\n private drop(code: number): void {\n const socket = this.socket;\n this.forget(code);\n if (socket && socket.readyState <= OPEN) {\n try {\n socket.close(code);\n } catch {\n // already closing\n }\n }\n }\n\n private forget(code: number): void {\n this.socket = null;\n this.ready = false;\n this.stopPing();\n if (this.stableTimer !== undefined) clearTimeout(this.stableTimer);\n this.stableTimer = undefined;\n if (this.opened !== null) {\n this.engine.closed(this.opened, code);\n this.opened = null;\n this.emitState();\n }\n }\n\n // ------------------------------------------------------------ receiving\n\n private frame(data: unknown): void {\n if (typeof data !== 'string') return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n return;\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Frame).type !== 'string'\n )\n return;\n this.receive(parsed as Frame);\n }\n\n private receive(event: Frame): void {\n if (this.current === 'closed') return;\n this.engine.received(event);\n this.emit('event', event as unknown as ServerEvent);\n const id =\n typeof event.client_event_id === 'string'\n ? event.client_event_id\n : undefined;\n switch (event.type) {\n case 'session.ready':\n this.ready = true;\n this.refreshed = false;\n this.firstFailures = 0;\n this.stableTimer = setTimeout(() => {\n this.stableTimer = undefined;\n this.attempts = 0;\n }, STABLE_MS);\n this.setStatus('ready');\n if (this.foreground) this.startPing();\n this.resendUnacknowledged();\n this.resendWaiting('turn');\n this.resendHeldForSession();\n break;\n case 'turn.completed':\n case 'turn.failed':\n // A tap or an answer refused with turn_in_progress during a takeover waits for no turn: the hand-back frees it.\n case 'takeover.ended':\n this.resendWaiting('turn');\n break;\n case 'turn.started':\n case 'ui.answer.recorded':\n case 'ui.answer.rejected':\n if (id !== undefined) this.screenTries.delete(id);\n break;\n case 'input.rejected':\n case 'error':\n this.refusedForNow(event);\n break;\n case 'session.closed':\n // Every reason but server_restart (reserved) ends the session here; the engine says what comes next.\n this.closeReason = typeof event.reason === 'string' ? event.reason : '';\n if (this.engine.state().reconnect !== 'allowed')\n this.setStatus('ended');\n break;\n default:\n break;\n }\n this.emitState();\n }\n\n private refusedForNow(event: Frame): void {\n const id =\n typeof event.client_event_id === 'string'\n ? event.client_event_id\n : undefined;\n if (id === undefined) return;\n if (event.code === 'limit_reached') {\n // No turns left in this session: a text or an answer is held for the next one (resume()); an action is\n // dropped. The session has ended for new input either way.\n this.heldForSession.set(id, this.info.id); // an action is dropped: resending it later finds nothing\n this.setStatus('ended');\n return;\n }\n if (!this.engine.state().resend.includes(id)) return;\n if (event.code === 'turn_in_progress') {\n this.waiting.set(id, 'turn');\n return;\n }\n // screen_unavailable: a short backoff, then the same input under the same id; after the last try, not sent.\n const tries = this.screenTries.get(id) ?? 0;\n const delays = this.options.screenRetryDelays ?? DEFAULT_SCREEN_RETRY;\n if (tries >= delays.length) {\n this.screenTries.delete(id);\n this.waiting.delete(id);\n this.engine.giveUp(id, 'screen_unavailable');\n return;\n }\n this.screenTries.set(id, tries + 1);\n this.waiting.set(id, 'screen');\n this.screenTimers.set(\n id,\n setTimeout(() => {\n this.screenTimers.delete(id);\n if (this.waiting.get(id) === 'screen') this.resend(id);\n }, delays[tries]),\n );\n }\n\n private resendUnacknowledged(): void {\n for (const event of this.engine.state().unacknowledged)\n this.transmit(event);\n }\n\n /** What a turn limit held, on a session other than the one that refused it. */\n private resendHeldForSession(): void {\n for (const [id, refusedIn] of [...this.heldForSession]) {\n if (refusedIn === this.info.id) continue;\n this.heldForSession.delete(id);\n this.resend(id);\n }\n }\n\n private resendWaiting(reason: 'turn'): void {\n for (const [id, why] of [...this.waiting])\n if (why === reason) this.resend(id);\n }\n\n private resend(id: string): void {\n this.waiting.delete(id);\n const event = this.engine.input(id);\n if (!event) return;\n if (this.live() || this.awaitingNewSession()) this.deliver(event);\n else this.hold(event);\n }\n\n /** Keep an input for a later session: unacknowledged, so the next `session.ready` (after resume()) sends it. */\n private hold(event: Frame): void {\n if (this.current === 'closed') return;\n this.engine.sent(event);\n this.emitState();\n }\n\n /** The session ended: retries waiting on a timer would go nowhere, so their inputs are held for the next session. */\n private holdRetries(): void {\n for (const [id, timer] of [...this.screenTimers]) {\n clearTimeout(timer);\n this.screenTimers.delete(id);\n this.waiting.delete(id);\n const event = this.engine.input(id);\n if (event) this.hold(event);\n }\n }\n\n // ------------------------------------------------------------ sending\n\n /** Send a typed message; returns its `client_event_id`. Over SSE it runs the turn there. */\n sendText(text: string): string {\n const id = this.newId();\n this.deliver({ type: 'input.text', text, client_event_id: id });\n return id;\n }\n\n /** Answer a question card (or a `rate_each` row, by the row's `question_id`); returns the `client_event_id`. */\n answer(cardId: string, questionId: string, answer: AnswerInput): string {\n if (this.current === 'sse') {\n throw new VinaverseClientError(\n 'needs_websocket',\n 'Question cards are answered over the WebSocket.',\n );\n }\n const id = this.newId();\n this.deliver({\n type: 'ui.answer',\n client_event_id: id,\n card_id: cardId,\n question_id: questionId,\n answer,\n });\n return id;\n }\n\n /**\n * Report a proposal's outcome after the tenant's backend answered (§6): `confirmed`, `declined`, `failed` or\n * `expired`. The first outcome per card is final. Returns the `client_event_id`.\n */\n reportOutcome(cardId: string, outcome: ProposalOutcome): string {\n return this.action(cardId, outcome);\n }\n\n /** A card action (`ui.action`), named by the card's `id`; the card's turn is taken from the state. */\n action(cardId: string, action: string): string {\n const turnId = this.engine\n .state()\n .cards.find((c) => c.id === cardId)?.turnId;\n if (turnId === undefined)\n throw new RangeError(`No turn is known for card ${cardId}.`);\n const id = this.newId();\n this.deliver({\n type: 'ui.action',\n client_event_id: id,\n turn_id: turnId,\n card_id: cardId,\n action,\n });\n return id;\n }\n\n /** Stop the turn in progress: `input.cancel` on the WebSocket; over SSE, the turn's request is stopped. */\n cancel(turnId: string): void {\n if (this.current === 'sse') {\n this.stopSse('cancel');\n this.engine.turnEnded();\n this.emitState();\n return;\n }\n this.transmit({ type: 'input.cancel', turn_id: turnId });\n }\n\n /** Ended idle: inputs are held for the new session that `resume()` brings. */\n private awaitingNewSession(): boolean {\n return (\n this.current === 'ended' &&\n this.engine.state().reconnect === 'new_session_on_next_action'\n );\n }\n\n private live(): boolean {\n return (\n this.current !== 'closed' &&\n this.current !== 'ended' &&\n this.current !== 'unauthorized'\n );\n }\n\n /**\n * Every input goes through here: recorded as sent (unacknowledged until the server answers it), then over SSE,\n * or on the WebSocket when the session is ready, or held and resent once `session.ready` arrives.\n */\n private deliver(event: Frame): void {\n if (!this.live() && !this.awaitingNewSession()) throw ended();\n this.engine.sent(event);\n this.emitState();\n if (this.current === 'sse') this.overSse(event);\n else if (this.ready) this.transmit(event);\n else if (this.current === 'idle') this.connect();\n }\n\n private transmit(event: Frame | ClientEvent): void {\n const socket = this.socket;\n if (!socket || socket.readyState !== OPEN) return;\n socket.send(JSON.stringify(event));\n }\n\n /** One input over SSE: a typed message or a card action; an answer cannot go, and is shown as not sent. */\n private overSse(event: Frame): void {\n const id =\n typeof event.client_event_id === 'string'\n ? event.client_event_id\n : undefined;\n const notSent = (error: VinaverseClientError) => {\n if (id !== undefined) this.engine.giveUp(id, error.code);\n this.emitState();\n this.emit('error', error);\n };\n if (id !== undefined && this.inFlight(id)) return;\n const controller = new AbortController();\n const target = { ...this.sseTarget(), signal: controller.signal };\n let frames: AsyncGenerator<Frame>;\n if (event.type === 'input.text') {\n frames = turnSse(target, {\n text: String(event.text),\n ...(id !== undefined ? { client_event_id: id } : {}),\n });\n } else if (event.type === 'ui.action') {\n frames = cardActionSse(target, String(event.turn_id), {\n card_id: String(event.card_id),\n action: String(event.action),\n ...(id !== undefined ? { client_event_id: id } : {}),\n });\n } else {\n notSent(\n new VinaverseClientError(\n 'needs_websocket',\n 'Question cards are answered over the WebSocket.',\n ),\n );\n return;\n }\n const stream: Stream = { id };\n this.streams.set(controller, stream);\n void (async () => {\n try {\n for await (const frame of frames) {\n if (controller.signal.aborted) break;\n this.receive(frame);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n notSent(asClientError(error, 'http_error'));\n return;\n }\n } finally {\n this.streams.delete(controller);\n }\n if (controller.signal.aborted) {\n if (stream.stop === 'cancel' && id !== undefined) {\n this.engine.giveUp(id, 'cancelled'); // a no-op once its turn started\n this.emitState();\n }\n return;\n }\n // The stream ended without answering the input (no turn, no refusal): it was not sent.\n if (id !== undefined && this.isUnacknowledged(id)) {\n notSent(\n new VinaverseClientError(\n 'http_error',\n 'The turn ended without taking the input.',\n ),\n );\n }\n })();\n }\n\n private isUnacknowledged(id: string): boolean {\n return this.engine\n .state()\n .unacknowledged.some((e) => e.client_event_id === id);\n }\n\n private inFlight(id: string): boolean {\n for (const stream of this.streams.values())\n if (stream.id === id) return true;\n return false;\n }\n\n private stopSse(why: Stop): void {\n for (const [controller, stream] of [...this.streams]) {\n stream.stop = why;\n controller.abort();\n }\n }\n\n private sseTarget() {\n return {\n turnsUrl: this.info.turns_url,\n secret: this.secret,\n ...(this.options.fetch ? { fetch: this.options.fetch } : {}),\n };\n }\n\n private newId(): string {\n return (this.options.createId ?? randomId)();\n }\n\n // ------------------------------------------------------------ pings and listeners\n\n private startPing(): void {\n this.stopPing();\n this.pingTimer = setInterval(\n () => this.transmit({ type: 'ping' }),\n this.options.pingInterval ?? 25_000,\n );\n }\n\n private stopPing(): void {\n if (this.pingTimer !== undefined) clearInterval(this.pingTimer);\n this.pingTimer = undefined;\n }\n\n private setStatus(status: SessionStatus): void {\n if (this.current === status) return;\n this.current = status;\n if (status === 'ended') this.holdRetries();\n this.emit('status', status);\n }\n\n private emitState(): void {\n if (this.listeners.state.size) this.emit('state', this.engine.state());\n }\n\n private emit<K extends keyof SessionEvents>(\n name: K,\n value: SessionEvents[K],\n ): void {\n for (const listener of this.listeners[name]) listener(value);\n }\n}\n\nfunction ended(): VinaverseClientError {\n return new VinaverseClientError(\n 'session_ended',\n 'The session has ended; resume it on a new session.',\n );\n}\n\nfunction asClientError(\n error: unknown,\n code: VinaverseClientError['code'],\n): VinaverseClientError {\n if (error instanceof VinaverseClientError) return error;\n return new VinaverseClientError(\n code,\n error instanceof Error ? error.message : String(error),\n );\n}\n\nfunction defaultWebSocket(): WebSocketFactory | null {\n const Ctor = (\n globalThis as { WebSocket?: new (...args: unknown[]) => WebSocketLike }\n ).WebSocket;\n if (!Ctor) return null;\n // Node itself, not a browser that also has `process` (an Electron renderer): its WebSocket cannot take headers.\n const scope = globalThis as {\n process?: { versions?: { node?: unknown } };\n document?: unknown;\n };\n const node =\n typeof scope.process?.versions?.node === 'string' &&\n scope.document === undefined;\n return (url, protocols, headers) => {\n if (!headers) return new Ctor(url, protocols);\n // Node's WebSocket (undici) takes headers in its init; React Native's in its third argument.\n return node\n ? new Ctor(url, { protocols, headers })\n : new Ctor(url, protocols, { headers });\n };\n}\n\nconst ALPHABET =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n\n/** A `client_event_id`: not a secret, only unique in its conversation; Math.random where no crypto exists (Hermes). */\nexport function randomId(): string {\n const bytes = new Uint8Array(22);\n const crypto = (\n globalThis as {\n crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array };\n }\n ).crypto;\n if (crypto?.getRandomValues) crypto.getRandomValues(bytes);\n else\n for (let i = 0; i < bytes.length; i++)\n bytes[i] = Math.floor(Math.random() * 256);\n let id = 'ce_';\n for (const byte of bytes) id += ALPHABET[byte % ALPHABET.length];\n return id;\n}\n","// The deep-link rule an app applies to a card's `deep_link` and a proposal's `edit_deep_link` before it opens one\n// (docs/realtime-protocol.md §6, admin-v1.yaml `Connector.deep_link_prefixes`): the link starts with a prefix the\n// tenant registered, compared code point for code point, and what follows the prefix is on the allowlist. The\n// patterns are the contract's own (fixtures/api/deep-link-vectors.json), and the tests run its vectors.\n\nconst PREFIX =\n /^[a-z][a-z0-9+.-]*:(\\/\\/\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?\\/|\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*\\/)(\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*\\/)*$/;\nconst PREFIX_HTTPS =\n /^https?:\\/\\/[a-z0-9-]+(\\.[a-z0-9-]+)*(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?\\/\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*\\//;\nconst REFUSED_SCHEMES =\n /^(javascript|vbscript|data|blob|file|filesystem|about|view-source|intent|android-app|content|jar|mhtml|itms-services|ftp|ws|wss):/;\n// biome-ignore lint/suspicious/noControlCharactersInRegex: the contract refuses control characters in a prefix.\nconst CONTROLS = /[\\x00-\\x1f\\x7f]/;\nconst REMAINDER =\n /^(\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*(\\/\\.*[A-Za-z0-9_~-][A-Za-z0-9._~-]*)*\\/?)?(\\?([A-Za-z0-9._~=&-]|%(2[0-46-9A-Ea-e]|3[0-9B-Fb-f]|[46][0-9A-Fa-f]|5[0-9ABD-Fabd-f]|7[0-9A-Ea-e]))*)?$/;\n\n/** Whether a prefix may be registered: the contract's prefix pattern, no refused scheme, no control character. */\nexport function isValidLinkPrefix(prefix: string): boolean {\n if (CONTROLS.test(prefix) || REFUSED_SCHEMES.test(prefix)) return false;\n if (/^https?:/.test(prefix) && !PREFIX_HTTPS.test(prefix)) return false;\n return PREFIX.test(prefix);\n}\n\n/**\n * Whether a card's link may be opened: it starts with one of the registered prefixes (invalid ones are ignored) and\n * what follows is a path and an optional query of the allowed characters. Route by the page it names; never open a\n * query value.\n */\nexport function isAllowedLink(\n link: string,\n prefixes: readonly string[],\n): boolean {\n return prefixes.some(\n (prefix) =>\n isValidLinkPrefix(prefix) &&\n link.startsWith(prefix) &&\n REMAINDER.test(link.slice(prefix.length)),\n );\n}\n","// The timeline: the engine's messages and cards, the store's pending texts and system rows, in one list sorted by\n// arrival, each item reused from the previous list when nothing about it changed (structural sharing).\nimport type { ConversationState, HeldCard, Message } from '../engine.js';\nimport { isKnownCard } from '../events.js';\nimport type {\n CardItem,\n MessageItem,\n MessageState,\n SystemItem,\n TimelineItem,\n} from './view.js';\n\n/** A text the person sent through the store, kept until the engine holds it as a message or forgets it. */\nexport interface SentText {\n readonly text: string;\n /** Where it sorts until it becomes a message: just after what was drawn when it was sent. */\n readonly order: number;\n}\n\nexport interface TimelineInput {\n readonly state: ConversationState;\n /** Items restored from persistence, drawn first. */\n readonly history: readonly TimelineItem[];\n /** By `client_event_id`, in the order sent. */\n readonly sent: ReadonlyMap<string, SentText>;\n /** Texts not yet given to a session (no session yet): drawn as sending. */\n readonly early: ReadonlySet<string>;\n /** Ids the person sent again (`retry`): their old \"not sent\" item is gone. */\n readonly retried: ReadonlySet<string>;\n readonly busy: ReadonlySet<string>;\n /**\n * Where cards sit after a resumed session's transcript replaced the messages: by card key, an order just after the\n * message they followed, so a card the session draws again (a pending proposal) stays in its place.\n */\n readonly cardOrder?: ReadonlyMap<string, number>;\n /** Cards a transcript (text only) dropped from the engine, kept where they were. */\n readonly kept?: readonly {\n readonly item: CardItem;\n readonly order: number;\n }[];\n /** Cards an earlier session drew that the current one does not hold again: drawn restored, taking no tap. */\n readonly inert?: ReadonlySet<string>;\n /** A resumed session brought its own transcript: the history kept on the device gives way to it. */\n readonly transcriptSeen?: boolean;\n /** Proposals whose tenant decision threw. */\n readonly decisionErrors?: ReadonlySet<string>;\n readonly system: readonly {\n readonly item: SystemItem;\n readonly order: number;\n }[];\n}\n\n/** The highest arrival number drawn, so something added now sorts after it. */\nexport function lastOrder(state: ConversationState): number {\n let last = -1;\n for (const m of state.messages) last = Math.max(last, m.seq);\n for (const c of state.cards) last = Math.max(last, c.seq);\n if (state.streaming) last = Math.max(last, state.streaming.seq);\n return last;\n}\n\n/** The person's text's state, or null when it is no longer pending (a message now, or settled with nothing to draw). */\nexport function pendingState(\n id: string,\n input: Pick<TimelineInput, 'state' | 'early' | 'retried'>,\n): Exclude<MessageState, 'sent' | 'delivered' | 'streaming'> | null {\n const { state } = input;\n if (input.retried.has(id)) return null;\n if (input.early.has(id)) return 'sending';\n if (state.messages.some((m) => m.key === id)) return null;\n const refused = state.refused[id];\n if (refused !== undefined) return refused === 'guardrail' ? null : 'not_sent';\n if (state.heldForNextSession.includes(id)) return 'held';\n if (\n state.resend.includes(id) ||\n state.held.includes(id) ||\n state.unacknowledged.some((f) => f.client_event_id === id)\n )\n return 'sending';\n return null; // a duplicate whose earlier turn stands, or forgotten\n}\n\nexport function buildTimeline(\n input: TimelineInput,\n previous: readonly TimelineItem[],\n): readonly TimelineItem[] {\n const before = new Map(previous.map((item) => [item.key, item]));\n const live: { item: TimelineItem; order: number }[] = [];\n const { state } = input;\n\n for (const m of state.messages)\n live.push({ item: messageItem(m), order: m.seq });\n if (state.streaming) {\n live.push({\n item: {\n type: 'message',\n key: `a:${state.streaming.turnId}`,\n role: 'agent',\n text: '',\n state: 'streaming',\n },\n order: state.streaming.seq,\n });\n }\n for (const card of state.cards) {\n if (!isKnownCard(card.card as { kind: string })) continue; // §5: skip a kind this client does not know\n live.push({\n item: {\n type: 'card',\n key: card.id,\n card,\n busy: !input.inert?.has(card.id) && input.busy.has(card.id),\n ...(input.inert?.has(card.id) ? { restored: true as const } : {}),\n ...(input.decisionErrors?.has(card.id)\n ? { decisionError: true as const }\n : {}),\n },\n order: input.cardOrder?.get(card.id) ?? card.seq,\n });\n }\n for (const { item, order } of input.system) live.push({ item, order });\n const held = new Set(state.cards.map((c) => c.id));\n for (const { item, order } of input.kept ?? [])\n if (!held.has(item.key)) live.push({ item, order });\n for (const [id, sent] of input.sent) {\n const pending = pendingState(id, input);\n if (pending === null) continue;\n const rejection = state.rejections[id];\n live.push({\n item: {\n type: 'message',\n key: id,\n role: 'person',\n text: sent.text,\n state: pending,\n ...(pending === 'not_sent'\n ? {\n rejection: rejection ?? {\n code: state.refused[id] ?? '',\n message: '',\n },\n }\n : {}),\n },\n order: sent.order,\n });\n }\n live.sort((a, b) => a.order - b.order); // stable: equal orders keep the order they were added in\n\n // History gives way to the conversation: an item the live session holds again (a restored card in pending_cards)\n // takes the history item's place, so it updates without moving; the whole of it gives way once a resumed session\n // brought its own transcript.\n const items = mergeByKey(\n input.transcriptSeen === true ? [] : input.history,\n live.map((l) => l.item),\n );\n\n let same = items.length === previous.length;\n const shared = items.map((item, i) => {\n const prev = before.get(item.key);\n const kept = prev !== undefined && equal(prev, item) ? prev : item;\n if (kept !== previous[i]) same = false;\n return kept;\n });\n return same ? previous : shared;\n}\n\n/**\n * History and the live conversation as one list, by key: a live item the history holds takes its place (it updates\n * without moving). One it does not hold, between two that it does, goes just after the live item before it (just\n * before the next one when none came before); after the last one the history holds, it goes at the end, after the\n * history.\n */\nexport function mergeByKey(\n history: readonly TimelineItem[],\n live: readonly TimelineItem[],\n): TimelineItem[] {\n if (!history.length) return [...live];\n const items = [...history];\n const at = (key: string) => items.findIndex((item) => item.key === key);\n let last = -1;\n live.forEach((item, i) => {\n const found = at(item.key);\n if (found >= 0) {\n items[found] = item;\n last = found;\n return;\n }\n const next = live\n .slice(i + 1)\n .map((l) => at(l.key))\n .find((p) => p >= 0);\n last = next === undefined ? items.length : last >= 0 ? last + 1 : next;\n items.splice(last, 0, item);\n });\n return items;\n}\n\nfunction messageItem(m: Message): MessageItem {\n const role = m.role === 'assistant' ? 'agent' : m.role;\n return {\n type: 'message',\n key: m.key,\n role,\n text: m.text,\n state: m.received ? 'delivered' : 'sent',\n ...(m.partial ? { partial: m.partial } : {}),\n ...(m.refusal ? { refusal: true as const } : {}),\n };\n}\n\nfunction equal(a: TimelineItem, b: TimelineItem): boolean {\n if (a.type !== b.type || a.key !== b.key) return false;\n if (a.type === 'message' && b.type === 'message')\n return (\n a.role === b.role &&\n a.text === b.text &&\n a.state === b.state &&\n a.partial === b.partial &&\n a.refusal === b.refusal &&\n a.rejection?.code === b.rejection?.code &&\n a.rejection?.message === b.rejection?.message\n );\n if (a.type === 'card' && b.type === 'card')\n return (\n a.busy === b.busy &&\n a.restored === b.restored &&\n a.decisionError === b.decisionError &&\n sameCard(a.card, b.card)\n );\n return a === b; // system items are made once and kept\n}\n\nfunction sameCard(a: HeldCard, b: HeldCard): boolean {\n return (\n a.card === b.card &&\n a.seq === b.seq &&\n a.turnId === b.turnId &&\n a.outcome === b.outcome &&\n a.locked.length === b.locked.length &&\n a.locked.every((q, i) => q === b.locked[i]) &&\n a.question?.state === b.question?.state &&\n JSON.stringify(a.question?.answer) === JSON.stringify(b.question?.answer) &&\n JSON.stringify(a.question?.row_answers) ===\n JSON.stringify(b.question?.row_answers)\n );\n}\n\n/** The parts of an item worth keeping across an app restart: what was on the server, never what was pending. */\nexport function persistable(item: TimelineItem): boolean {\n if (item.type === 'message')\n return item.state === 'sent' || item.state === 'delivered';\n return item.type === 'card';\n}\n","// The conversation store: one conversation with an agent, for any UI framework. It owns the session (and the next\n// one after a resume), turns the engine's state into a view a UI draws, and runs what the protocol asks of an app\n// on the person's actions: resume on the next action, hold what was typed early, decide proposals through the\n// tenant's handler, keep streamed text to one update per frame. No framework import: React, React Native and Angular\n// bind to `subscribe` and `getSnapshot`.\nimport {\n ConversationEngine,\n type ConversationState,\n transcriptHasIds,\n} from '../engine.js';\nimport { VinaverseClientError } from '../errors.js';\nimport type {\n AnswerInput,\n ClientSecret,\n ProposalOutcome,\n ServerEvent,\n SessionInfo,\n Welcome,\n} from '../events.js';\nimport {\n randomId,\n type SessionOptions,\n type SessionStatus,\n VinaverseSession,\n} from '../session.js';\nimport { isAllowedLink } from './links.js';\nimport {\n buildTimeline,\n lastOrder,\n persistable,\n type SentText,\n} from './timeline.js';\nimport type {\n CardItem,\n ConversationBanner,\n ConversationStatus,\n ConversationView,\n StreamingText,\n SystemItem,\n TimelineItem,\n} from './view.js';\n\n/** Why the store asks the tenant's backend for a session. */\nexport type SessionReason =\n /** The conversation opens (`start()`). */\n | 'open'\n /** The session ended (idle, expired, its turn limit) and the person acted again. */\n | 'resume'\n /** The conversation continued on another device, and the person chose to continue here. */\n | 'continue_here';\n\nexport interface SessionRequest {\n readonly reason: SessionReason;\n /** The conversation so far, when known: the backend names it (with its `conversation_key`) to resume it. */\n readonly conversationId: string | null;\n /** For `subject.locale` and `subject.timezone`, which the backend sets. */\n readonly locale?: string;\n readonly timeZone?: string;\n /**\n * Aborted when the answer is no longer wanted (the conversation was disposed or cleared, or a newer request took\n * its place): pass it to `fetch`, so a late answer never opens a socket after the person left.\n */\n readonly signal?: AbortSignal;\n}\n\n/** What `createSession` gave the tenant's backend, as it passes it on: the session, its agent and disclosure. */\nexport type ConversationSession = SessionInfo & {\n readonly agent?: {\n readonly display_name?: string;\n readonly avatar_url?: string;\n };\n readonly disclosure?: string;\n /**\n * When the session ends (`Session.expires_at`: the earliest of its own limit and the tenant's tool token). Past it,\n * the conversation goes on in a new session from `getSession`, never with a fresh secret for this one.\n */\n readonly expires_at?: string;\n /** v1-draft.20: the tenant's greeting and chips for the session's mode (`Session.welcome`); no model call. */\n readonly welcome?: Welcome;\n};\n\n/**\n * Runs a callback before the next frame; `requestAnimationFrame` where there is one. Every listener, of the view and\n * of the streaming text, is called from it, at most once per frame: a zone.js app re-enters its zone here once. A\n * test passes one that runs the callback at once.\n */\nexport interface FrameScheduler {\n request(callback: () => void): unknown;\n cancel(handle: unknown): void;\n}\n\n/** Where the drawn conversation is kept across app restarts (opt-in; prefer encrypted storage). */\nexport interface ConversationPersistence {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n /**\n * Optional: the keys under a prefix. With it (or `removePrefix`), a sign-out and an erasure are guaranteed to find every\n * key kept, ones no index lists too (an earlier version's, a write lost with its process); without either, only the\n * keys this version indexed and the shapes it can derive from them. AsyncStorage and MMKV: `getAllKeys()` filtered\n * by the prefix; web `localStorage`: `Object.keys(localStorage)` filtered.\n */\n keys?(prefix: string): readonly string[] | Promise<readonly string[]>;\n /** Optional: removes every key under a prefix at once (used instead of `keys` where it cannot reach a kept record). */\n removePrefix?(prefix: string): void | Promise<void>;\n}\n\nexport interface ConversationOptions {\n /**\n * A session from the tenant's backend, which creates it with its service key (the app never holds one). Asked once\n * per need: when the conversation opens, and on the person's action after a session ended.\n */\n readonly getSession: (\n request: SessionRequest,\n ) => Promise<ConversationSession>;\n /** A fresh client secret for a session (on 4401), from the tenant's backend. */\n readonly refreshSecret?: (\n sessionId: string,\n ) => Promise<ClientSecret | string>;\n readonly locale?: string;\n readonly timeZone?: string;\n /** The prefixes the tenant registered for card links (`checkLink`). */\n readonly deepLinkPrefixes?: readonly string[];\n /** Keep the drawn conversation across restarts (off unless given). */\n readonly persistence?: ConversationPersistence;\n /** Its key; one per signed-in person. Default `vinaverse.conversation`. */\n readonly persistenceKey?: string;\n /** Default: `requestAnimationFrame`, else a 16 ms timer, resolved when first used (never at import or creation). */\n readonly scheduler?: FrameScheduler;\n /** The transport's own options (`auth`, `webSocket`, `fetch`, delays…). */\n readonly transport?: Omit<\n SessionOptions,\n 'session' | 'refreshSecret' | 'engine' | 'createId'\n >;\n /** New `client_event_id`s. Default: random, `ce_` and 22 characters. */\n readonly createId?: () => string;\n /** Something failed that no call returned: getting a session, an input that could not be delivered. */\n readonly onError?: (error: unknown) => void;\n /**\n * Close the connection while the app is in the background, and open it again in the foreground (a backend that\n * mints a client secret per connection: with `refreshSecret`, a fresh one is asked for first). Default false: the\n * connection stays, with no pings, until the session idles out. Nothing typed or answered is lost either way.\n */\n readonly closeInBackground?: boolean;\n /**\n * The time a session's end (`expires_at`) is judged by. Default: the device's. Give the server's (a clock synced from\n * responses): a phone set late would reuse a dead session, set early drop a live one.\n */\n readonly clock?: { now(): number };\n /**\n * What the person and the agent did live, for analytics (never what a transcript or the device brought back): the\n * person sent a text, a reply finished, a card was drawn. Carries no text.\n */\n readonly onActivity?: (activity: ConversationActivity) => void;\n}\n\n/** One live step of the conversation, without its words. */\nexport type ConversationActivity =\n | { readonly type: 'message_sent'; readonly id: string }\n | { readonly type: 'reply_completed'; readonly turnId: string }\n | {\n readonly type: 'card_shown';\n readonly cardId: string;\n readonly kind: string;\n };\n\n/** A text is at most 2000 code points (`TurnInput`). */\nexport const MAX_TEXT = 2000;\n/** Turns whose starting text the store remembers, for `retryTurn`. */\nconst TURN_INPUTS = 50;\n/** History kept across restarts: the newest items. */\nconst HISTORY = 100;\nconst PERSIST_DELAY = 500;\nconst PERSIST_VERSION = 1;\n\nconst NO_ITEMS: readonly TimelineItem[] = [];\nconst OUTCOMES: ReadonlySet<string> = new Set([\n 'confirmed',\n 'declined',\n 'failed',\n 'expired',\n]);\n\nexport class ConversationStore {\n private readonly options: ConversationOptions;\n private readonly engine = new ConversationEngine();\n private session: VinaverseSession | null = null;\n private info: ConversationSession | null = null;\n private getting: Promise<VinaverseSession | null> | null = null;\n private failed = false;\n private disposed = false;\n private online: boolean | null = null;\n private foreground = true;\n private lastStatus: SessionStatus = 'idle';\n private offlineAfterRetries = false;\n /** The id the next send gets, so a text typed before the session keeps its key. */\n private nextId: string | null = null;\n\n private readonly sent = new Map<string, SentText>();\n private readonly early = new Map<string, string>();\n private readonly retried = new Set<string>();\n private readonly busy = new Set<string>();\n /** Proposals whose tenant decision threw: shown as recoverable, the person may decide again. */\n private readonly decisionErrors = new Set<string>();\n private system: { item: SystemItem; order: number }[] = [];\n /** The person's text that started each recent turn, by `turn_id` (`turn.started` echoes its `client_event_id`). */\n private readonly turnInputs = new Map<string, string>();\n /** Numbers system rows that carry no id of their own. */\n private systemSeq = 0;\n private history: readonly TimelineItem[] = NO_ITEMS;\n private historyState: ConversationView['history'] = 'none';\n /** A resumed session.ready carried a transcript: the server's history replaced what the device kept. */\n private transcriptSeen = false;\n /** The session of the last session.ready: a card of another one takes no tap (§6). */\n private readySession: string | null = null;\n private cardOrder = new Map<string, number>();\n private kept: { item: CardItem; order: number }[] = [];\n /** Cards an earlier session drew, kept by a merged transcript: drawn as restored, taking no tap. */\n private readonly inert = new Set<string>();\n private locale: string | undefined;\n /** The request for a session in flight, to abort when it is no longer wanted. */\n private fetching: { abort(): void } | null = null;\n\n private view: ConversationView;\n private readonly listeners = new Set<() => void>();\n private streaming: StreamingText | null = null;\n private readonly streamListeners = new Set<() => void>();\n /** The frame that will notify, and what it will notify about. */\n private frame: unknown = undefined;\n private framePending = false;\n private viewDirty = false;\n private streamDirty = false;\n private persistTimer: ReturnType<typeof setTimeout> | undefined;\n private unsubscribe: (() => void)[] = [];\n\n constructor(options: ConversationOptions) {\n this.options = options;\n this.locale = options.locale;\n this.view = this.compute(null);\n this.restore();\n }\n\n // ------------------------------------------------------------ reading\n\n getSnapshot = (): ConversationView => this.view;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n getStreaming = (): StreamingText | null => this.streaming;\n\n subscribeStreaming = (listener: () => void): (() => void) => {\n this.streamListeners.add(listener);\n return () => this.streamListeners.delete(listener);\n };\n\n /** Whether a card's link may be opened (the deep-link rule, against `deepLinkPrefixes`). */\n checkLink(link: string): boolean {\n return isAllowedLink(link, this.options.deepLinkPrefixes ?? []);\n }\n\n // ------------------------------------------------------------ the conversation's life\n\n /** Ask for a session and connect, early: a client secret must open its first connection within two minutes. */\n start(): void {\n this.live();\n if (this.session) {\n if (this.session.status === 'idle') this.session.connect();\n // Refused, and a new session refused as well: the person's \"Try again\" asks for another.\n else if (this.session.status === 'unauthorized')\n void this.resumeWith('resume');\n return;\n }\n void this.ensureSession('open');\n }\n\n /** Close for good. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.fetching?.abort();\n this.fetching = null;\n this.session?.close();\n for (const off of this.unsubscribe) off();\n this.unsubscribe = [];\n clearTimeout(this.persistTimer);\n this.update();\n this.flush(); // the closed view reaches the listeners now: no frame may come after the screen is gone\n }\n\n /** Close for good and forget the conversation kept on the device (sign-out). Never throws for the storage. */\n clear(): void {\n this.dispose();\n this.history = NO_ITEMS;\n try {\n const removed = this.options.persistence?.removeItem(this.key());\n if (removed) removed.catch(() => undefined);\n } catch {\n // storage blocked: sign-out goes on\n }\n this.update();\n this.flush();\n }\n\n /**\n * The person switched the app's language: the UI's words change at once (the kit's own locale); the next session\n * asks for this locale (`subject.locale`). The open session keeps its language: the agent answers in the new one\n * from the next session, and the store never starts a session for it.\n */\n setLocale(locale: string | undefined): void {\n this.locale = locale;\n }\n\n /** The app came to the foreground or went to the background (AppState, `visibilitychange`). */\n setForeground(foreground: boolean): void {\n this.foreground = foreground;\n if (this.options.closeInBackground && !this.disposed) {\n if (!foreground) {\n this.suspend();\n return;\n }\n if (this.suspended) {\n void this.wake();\n return;\n }\n }\n this.session?.setForeground(foreground);\n if (foreground) this.reconnectIfDown();\n }\n\n /** In the background (`closeInBackground`): the connection is closed; the engine keeps what was sent, to resend. */\n private suspended = false;\n private suspend(): void {\n const session = this.session;\n if (!session || this.suspended || session.status === 'ended') return;\n this.suspended = true;\n for (const off of this.unsubscribe) off();\n this.unsubscribe = [];\n session.close();\n this.update();\n }\n\n /**\n * Back in the foreground, or the person acted while away: a new connection to the same session, with a fresh secret\n * when the backend gives one. A session that passed its end meanwhile is never reopened (a fresh secret cannot bring\n * back an expired tool token): the person's action continues the conversation in a new session from `getSession`,\n * and until then nothing connects.\n */\n private async wake(byPerson = false): Promise<void> {\n const info = this.info;\n if (info && this.sessionOver()) {\n if (byPerson) await this.resumeWith('resume');\n else this.update();\n return;\n }\n this.suspended = false;\n if (!info) return;\n let next: ConversationSession = info;\n if (this.options.refreshSecret) {\n try {\n next = {\n ...info,\n client_secret: await this.options.refreshSecret(info.id),\n };\n } catch (error) {\n this.options.onError?.(error); // the secret held may still open it; a refused one asks again (4401)\n }\n }\n if (this.disposed || this.suspended) return;\n this.open(next);\n }\n\n /** The network as the app sees it; null when unknown. Back online reconnects a connection that gave up. */\n setOnline(online: boolean | null): void {\n this.online = online;\n if (online) this.reconnectIfDown();\n this.update();\n }\n\n // ------------------------------------------------------------ the person's actions\n\n /** Send a typed message; returns its `client_event_id`. Typed before a session exists, it is sent once one does. */\n send(text: string): string {\n this.live();\n if (!text.trim()) throw new RangeError('A message needs some text.');\n if ([...text].length > MAX_TEXT)\n throw new RangeError(`A message is at most ${MAX_TEXT} characters.`);\n const id = (this.options.createId ?? randomId)();\n this.sent.set(id, { text, order: lastOrder(this.engine.state()) + 0.5 });\n this.tellActivity({ type: 'message_sent', id });\n if (!this.session) {\n this.early.set(id, text);\n void this.ensureSession('open');\n this.update();\n return id;\n }\n if (this.suspended) {\n // Typed while the connection is closed for the background: held, and sent once it is open again.\n this.early.set(id, text);\n void this.wake(true);\n this.update();\n return id;\n }\n if (this.nextFrom(this.engine.state()) === 'continue_here') {\n // The session refuses input now; typing here is the person continuing here, so it goes to the next session.\n this.early.set(id, text);\n void this.resumeWith('continue_here');\n this.update();\n return id;\n }\n if (this.sessionOver()) {\n // Past the session's end (its tool token with it): the text goes to a new session for the same conversation.\n this.early.set(id, text);\n void this.resumeWith('resume');\n this.update();\n return id;\n }\n this.nextId = id;\n this.session.sendText(text);\n this.nextId = null;\n this.continueIfEnded();\n return id;\n }\n\n /** Answer a question card (a `rate_each` row by its `question_id`); returns the `client_event_id`. */\n answer(cardId: string, questionId: string, answer: AnswerInput): string {\n const session = this.required();\n const id = session.answer(cardId, questionId, answer);\n this.continueIfEnded();\n return id;\n }\n\n /** A card action (`ui.action`) other than a proposal's outcome. */\n cardAction(cardId: string, action: string): string {\n return this.required().action(cardId, action);\n }\n\n /**\n * Decide a proposal: `decide` is the tenant's own call (its backend, the person's token), which confirms or\n * declines it and says the outcome; the store then reports it. One decision per card; the card is busy meanwhile.\n * Resolves to the outcome reported, or null when the card was busy or already decided.\n *\n * Only an outcome `decide` resolves with is reported (§6: the first is final). When `decide` throws, or resolves\n * with anything but `confirmed`, `declined`, `failed` or `expired`, nothing is reported: the backend may have\n * applied the change, so the outcome stays unknown; the card shows `decisionError` and the person may decide\n * again. When the conversation is disposed meanwhile (sign-out), the outcome is not reported either: the tenant's\n * backend holds it, and the session takes it as unknown.\n */\n async decideProposal(\n cardId: string,\n decide: () => Promise<ProposalOutcome>,\n ): Promise<ProposalOutcome | null> {\n this.live();\n const card = this.engine.state().cards.find((c) => c.id === cardId);\n if (card?.kind !== 'proposal') return null;\n if (this.busy.has(cardId) || (card.outcome ?? null) !== null) return null;\n this.busy.add(cardId);\n this.decisionErrors.delete(cardId);\n this.update();\n try {\n const outcome: unknown = await decide();\n if (typeof outcome !== 'string' || !OUTCOMES.has(outcome))\n throw new TypeError(\n `decide() resolved with ${JSON.stringify(outcome)}, not confirmed, declined, failed or expired`,\n );\n if (this.disposed) return outcome as ProposalOutcome;\n if (this.view.next === 'continue') await this.resumeWith('resume');\n this.required().reportOutcome(cardId, outcome as ProposalOutcome);\n return outcome as ProposalOutcome;\n } catch (error) {\n this.decisionErrors.add(cardId);\n throw error;\n } finally {\n this.busy.delete(cardId);\n this.update();\n }\n }\n\n /** Send a \"not sent\" message again, as a new message (the person's action). Returns the new id. */\n retry(key: string): string | null {\n const sent = this.sent.get(key);\n if (!sent || this.engine.state().refused[key] === undefined) return null;\n this.retried.add(key);\n this.sent.delete(key);\n return this.send(sent.text);\n }\n\n /**\n * Send again the person's text whose turn failed before any reply (a `turn_failed` row with `data.retry`), as a new\n * message (the person's action). Once per row: its `retry` turns false. Returns the new id, or null when the row\n * allows no retry.\n */\n retryTurn(key: string): string | null {\n const at = this.system.findIndex(\n (s) => s.item.key === key && s.item.event === 'turn_failed',\n );\n const entry = this.system[at];\n if (entry?.item.data.retry !== true) return null;\n const text = this.turnText(String(entry.item.data.turn ?? ''));\n if (text === undefined) return null;\n this.system = this.system.map((s, i) =>\n i === at\n ? { ...s, item: { ...s.item, data: { ...s.item.data, retry: false } } }\n : s,\n );\n return this.send(text);\n }\n\n /** After the conversation continued on another device: continue it here (the person's choice). */\n continueHere(): Promise<void> {\n return this.resumeWith('continue_here');\n }\n\n /** Stop the turn in progress. */\n cancel(): void {\n const turn = this.engine.state().turn;\n if (this.session && turn) this.session.cancel(turn);\n }\n\n // ------------------------------------------------------------ sessions\n\n private async ensureSession(\n reason: SessionReason,\n ): Promise<VinaverseSession | null> {\n if (this.session) return this.session;\n if (this.getting) return this.getting;\n this.getting = this.fetchSession(reason).then((info) => {\n this.getting = null;\n if (!info || this.disposed) return null;\n this.open(info);\n return this.session;\n });\n this.update();\n return this.getting;\n }\n\n private async fetchSession(\n reason: SessionReason,\n ): Promise<ConversationSession | null> {\n this.failed = false;\n this.fetching?.abort(); // a newer request takes the place of an older one\n const Controller = (\n globalThis as { AbortController?: new () => AbortController }\n ).AbortController;\n const controller = Controller ? new Controller() : null;\n const mine = { abort: () => controller?.abort() };\n this.fetching = mine;\n let aborted = false;\n const signal = controller?.signal;\n signal?.addEventListener('abort', () => {\n aborted = true;\n });\n try {\n const info = await this.options.getSession({\n reason,\n conversationId: this.engine.state().conversationId,\n ...(this.locale !== undefined ? { locale: this.locale } : {}),\n ...(this.options.timeZone !== undefined\n ? { timeZone: this.options.timeZone }\n : {}),\n ...(signal ? { signal } : {}),\n });\n return aborted || this.fetching !== mine ? null : info;\n } catch (error) {\n if (aborted || this.fetching !== mine) return null; // no longer wanted: not a failure\n this.failed = true;\n this.getting = null;\n this.options.onError?.(error);\n this.update();\n return null;\n } finally {\n if (this.fetching === mine) this.fetching = null;\n }\n }\n\n private open(info: ConversationSession): void {\n this.info = info;\n this.suspended = false;\n const refreshSecret = this.options.refreshSecret;\n const session = new VinaverseSession({\n ...this.options.transport,\n session: info,\n engine: this.engine,\n ...(refreshSecret\n ? {\n // Past the session's end a fresh secret cannot help: refused here, and the store rolls over instead.\n refreshSecret: (id: string) =>\n this.sessionOver()\n ? Promise.reject(\n new VinaverseClientError(\n 'needs_new_session',\n 'This session has ended.',\n ),\n )\n : refreshSecret(id),\n }\n : {}),\n createId: () => this.nextId ?? (this.options.createId ?? randomId)(),\n });\n this.session = session;\n this.unsubscribe.push(\n session.on('state', () => this.update()),\n session.on('status', (status) => this.statusChanged(status)),\n session.on('event', (event) => this.event(event)),\n session.on('error', (error) => {\n if (!this.sessionOver()) this.options.onError?.(error); // past its end, the refusal is the rollover's cue\n }),\n );\n session.setForeground(this.foreground);\n session.connect();\n this.flushEarly();\n }\n\n /** What was typed before there was a session to take it. */\n private flushEarly(): void {\n const session = this.session;\n if (!session) return;\n for (const [id, text] of this.early) {\n this.nextId = id;\n session.sendText(text);\n }\n this.nextId = null;\n this.early.clear();\n this.update();\n }\n\n /** A new session for the conversation, then `resume()`: once per person action, never in a loop. */\n private resuming: Promise<void> | null = null;\n private resumeWith(reason: SessionReason): Promise<void> {\n this.live();\n if (this.resuming) return this.resuming;\n if (!this.session) return this.ensureSession(reason).then(() => undefined);\n this.resuming = this.fetchSession(reason).then((info) => {\n this.resuming = null;\n if (!info || this.disposed || !this.session) return;\n if (this.session.status === 'closed') {\n this.open(info); // closed for the background: a connection of its own\n return;\n }\n this.info = info;\n this.session.resume(info);\n this.flushEarly();\n });\n return this.resuming;\n }\n\n /** The person acted after the session ended idle, expired or at its limit: the next session takes what they sent. */\n private continueIfEnded(): void {\n if (this.nextFrom(this.engine.state()) === 'continue')\n void this.resumeWith('resume');\n this.update();\n }\n\n private reconnectIfDown(): void {\n const session = this.session;\n if (\n session &&\n session.status === 'idle' &&\n !this.sessionOver() && // past its end: the person's next action gets a new session\n this.nextFrom(this.engine.state()) === null\n )\n session.connect();\n }\n\n /** A refusal already led to a new session, and none has been ready since: another refusal is no cue. */\n private rolled = false;\n\n private statusChanged(status: SessionStatus): void {\n // A refused secret (a 4401 that no fresh secret got past) means the session is over, whatever the device's clock\n // says: a phone running behind the server still thinks it open. The conversation goes on in a new session, once\n // until a session is ready, so a backend whose new session is refused too leaves the view unauthorized, never a\n // loop.\n if (status === 'ready') this.rolled = false;\n if (status === 'unauthorized' && !this.rolled) {\n this.rolled = true;\n void this.resumeWith('resume');\n }\n if (status === 'idle')\n this.offlineAfterRetries = this.lastStatus === 'reconnecting';\n else if (status !== 'reconnecting') this.offlineAfterRetries = false;\n this.lastStatus = status;\n this.update();\n }\n\n /** The app's analytics hears of a step; what it throws is reported (`onError`), never in the way of a send or a frame. */\n private tellActivity(activity: ConversationActivity): void {\n try {\n this.options.onActivity?.(activity);\n } catch (error) {\n this.options.onError?.(error);\n }\n }\n\n /** The live frames analytics hears of: a reply finished, cards drawn. */\n private activity(frame: Record<string, unknown>): void {\n if (!this.options.onActivity) return;\n const on = (a: ConversationActivity) => this.tellActivity(a);\n if (frame.type === 'message.completed' && typeof frame.turn_id === 'string')\n on({ type: 'reply_completed', turnId: frame.turn_id });\n if (frame.type === 'ui.cards' && Array.isArray(frame.cards))\n for (const card of frame.cards as { id?: unknown; kind?: unknown }[])\n if (typeof card.id === 'string' && typeof card.kind === 'string')\n on({ type: 'card_shown', cardId: card.id, kind: card.kind });\n }\n\n private event(event: ServerEvent): void {\n const frame = event as unknown as Record<string, unknown>;\n const str = (v: unknown) => (typeof v === 'string' ? v : null);\n this.activity(frame);\n const add = (\n key: string,\n kind: SystemItem['event'],\n data: SystemItem['data'],\n ) => {\n if (this.system.some((s) => s.item.key === key)) return;\n this.system = [\n ...this.system,\n {\n item: { type: 'system', key, event: kind, data },\n order: lastOrder(this.engine.state()) + 0.75,\n },\n ];\n };\n switch (frame.type) {\n case 'session.ready': {\n const session = (frame.session as { id?: unknown } | undefined)?.id;\n const moved =\n typeof session === 'string' && session !== this.readySession;\n if (typeof session === 'string') this.readySession = session;\n // A transcript without the live ids replaced the messages: the device's history gives way, and the cards on\n // screen are anchored where they were. One with them merged by key, and nothing gives way.\n if (\n frame.resumed === true &&\n Array.isArray(frame.transcript) &&\n !transcriptHasIds(frame.transcript)\n ) {\n this.transcriptSeen = true;\n this.anchorCards(moved);\n } else if (moved && frame.resumed === true) {\n // A card an earlier session drew takes no tap in this one (§6), unless this session holds it again.\n const pending = new Set(\n (Array.isArray(frame.pending_cards) ? frame.pending_cards : []).map(\n (c) => str((c as { id?: unknown }).id),\n ),\n );\n for (const card of this.engine.state().cards)\n if (pending.has(card.id)) this.inert.delete(card.id);\n else this.inert.add(card.id);\n }\n return;\n }\n // `at` is required (v1-draft.15); the same takeover announced again after a reconnect has the same `at`, so it\n // draws one row. A frame without one still gets a row of its own.\n case 'takeover.started':\n add(\n `takeover:${str(frame.at) ?? `#${++this.systemSeq}`}`,\n 'takeover_started',\n { by: str(frame.by) },\n );\n return;\n case 'takeover.ended':\n add(\n `takeover-ended:${str(frame.at) ?? `#${++this.systemSeq}`}`,\n 'takeover_ended',\n {},\n );\n return;\n case 'handoff.created': {\n const ticket = frame.ticket as Record<string, unknown> | undefined;\n add(`handoff:${str(ticket?.id) ?? ''}`, 'handoff_created', {\n expected_response: str(ticket?.expected_response),\n });\n return;\n }\n case 'flow.completed':\n add(`flow:#${++this.systemSeq}`, 'flow_completed', {\n result: str(frame.result),\n code: str(frame.code),\n });\n return;\n case 'turn.started': {\n const turn = str(frame.turn_id);\n const input = str(frame.client_event_id);\n if (turn === null || input === null) return;\n this.turnInputs.set(turn, input);\n if (this.turnInputs.size > TURN_INPUTS) {\n const oldest = this.turnInputs.keys().next().value;\n if (oldest !== undefined) this.turnInputs.delete(oldest);\n }\n return;\n }\n case 'turn.failed': {\n const turn = str(frame.turn_id) ?? '';\n // A reply that streamed is kept, cut off; a turn that failed before any text gets a row of its own.\n if (this.engine.state().messages.some((m) => m.key === `a:${turn}`))\n return;\n if (frame.code === 'cancelled') return; // stopped on purpose (cancel(), a takeover): nothing failed\n add(`failed:${turn}`, 'turn_failed', {\n code: str(frame.code),\n message: str(frame.message),\n retryable: frame.retryable === true,\n retry: frame.retryable === true && this.turnText(turn) !== undefined,\n turn,\n });\n return;\n }\n default:\n return;\n }\n }\n\n /** The person's text that started a turn, while its message is on screen. */\n private turnText(turn: string): string | undefined {\n const input = this.turnInputs.get(turn);\n if (input === undefined) return undefined;\n const message = this.engine\n .state()\n .messages.find((m) => m.key === input && m.role === 'person');\n return message?.text || undefined;\n }\n\n /**\n * A resumed session's transcript replaced the messages, and a chat transcript carries text only: the engine drops\n * the cards it drew, and draws the pending ones again at the end. Each card on screen is anchored just after the\n * message it followed (by key; the transcript keeps the live keys), so a pending proposal stays where it was, and a\n * card the transcript dropped stays drawn there; taking no tap when it belongs to an earlier session.\n */\n private anchorCards(sessionChanged: boolean): void {\n const state = this.engine.state();\n const seqOf = new Map(state.messages.map((m) => [m.key, m.seq]));\n const first = Math.min(...state.messages.map((m) => m.seq), 0);\n const held = new Set(state.cards.map((c) => c.id));\n const order = new Map<string, number>();\n const kept: { item: CardItem; order: number }[] = [];\n let anchor = first - 1;\n let step = 0;\n for (const item of this.view.items) {\n if (item.type === 'message' && seqOf.has(item.key)) {\n anchor = seqOf.get(item.key) as number;\n step = 0;\n } else if (item.type === 'card') {\n const at = anchor + 0.5 + ++step / 1000;\n order.set(item.key, at);\n if (!held.has(item.key))\n kept.push({\n item: sessionChanged\n ? { ...item, busy: false, restored: true }\n : item,\n order: at,\n });\n }\n }\n this.cardOrder = order;\n this.kept = kept;\n }\n\n // ------------------------------------------------------------ the view\n\n /**\n * Recomputes now (getSnapshot and getStreaming are always current) and notifies from the scheduler, at most once\n * per frame, both channels in the same flush: a streamed reply that completes becomes its message in one frame.\n */\n private update(): void {\n const state = this.engine.state();\n this.stream(state);\n const view = this.compute(state);\n if (view !== this.view) {\n this.view = view;\n this.viewDirty = true;\n this.schedulePersist();\n }\n if (this.viewDirty || this.streamDirty) this.scheduleNotify();\n }\n\n private scheduleNotify(): void {\n if (this.framePending || this.disposed) return;\n // Nobody listens yet (a store created on the server, or before its screen): no frame is asked for, so no global is\n // touched; a listener reads the current snapshot when it subscribes.\n if (this.listeners.size === 0 && this.streamListeners.size === 0) return;\n this.framePending = true;\n this.frame = this.scheduler().request(() => {\n this.frame = undefined;\n this.framePending = false;\n this.flush();\n });\n }\n\n /** Calls the listeners of what changed since the last flush. */\n private flush(): void {\n if (this.frame !== undefined) {\n this.scheduler().cancel(this.frame);\n this.frame = undefined;\n this.framePending = false;\n }\n const view = this.viewDirty;\n const stream = this.streamDirty;\n this.viewDirty = false;\n this.streamDirty = false;\n if (stream) for (const l of [...this.streamListeners]) l();\n if (view) for (const l of [...this.listeners]) l();\n }\n\n private compute(state: ConversationState | null): ConversationView {\n const s = state ?? this.engine.state();\n const prev: ConversationView | undefined = this.view;\n for (const id of [...this.sent.keys()])\n if (!this.early.has(id) && s.messages.some((m) => m.key === id))\n this.sent.delete(id);\n const items = buildTimeline(\n {\n state: s,\n history: this.history,\n sent: this.sent,\n early: new Set(this.early.keys()),\n retried: this.retried,\n busy: this.busy,\n decisionErrors: this.decisionErrors,\n transcriptSeen: this.transcriptSeen,\n cardOrder: this.cardOrder,\n kept: this.kept,\n inert: this.inert,\n system: this.system,\n },\n prev?.items ?? NO_ITEMS,\n );\n const status = this.status();\n const next = this.nextFrom(s);\n const activity =\n s.turn === null ? [] : s.tools.filter((t) => t.turn_id === s.turn);\n const name = this.info?.agent?.display_name ?? null;\n const avatarUrl = this.info?.agent?.avatar_url ?? null;\n const view: ConversationView = {\n status,\n conversationId: s.conversationId,\n banner: banner(status, next),\n next,\n agent: sameAgent(prev?.agent, name, avatarUrl)\n ? (prev as ConversationView).agent\n : { name, avatarUrl },\n disclosure: s.disclosure ?? this.info?.disclosure ?? null,\n welcome: this.info?.welcome ?? null,\n takeover: s.takeover,\n items,\n activity:\n prev && sameTools(prev.activity, activity) ? prev.activity : activity,\n responding: s.turn !== null || s.streaming !== null,\n openQuestion: s.openQuestion,\n answersNeedWebSocket: status === 'sse',\n turnsLeft: s.turnsLeft,\n history: this.historyState,\n };\n if (prev && shallowEqual(prev, view)) return prev;\n return view;\n }\n\n private status(): ConversationStatus {\n if (this.disposed) return 'closed';\n if (this.suspended) return 'idle'; // in the background on purpose: nothing to show\n const session = this.session;\n if (!session) {\n if (this.failed) return 'unavailable';\n return this.getting || this.early.size ? 'starting' : 'idle';\n }\n const status = session.status;\n if (this.failed && status === 'ended') return 'unavailable';\n if (status === 'idle')\n return this.offlineAfterRetries || this.online === false\n ? 'offline'\n : 'idle';\n if (status === 'reconnecting' && this.online === false) return 'offline';\n return status;\n }\n\n private nextFrom(state: ConversationState): ConversationView['next'] {\n if (this.session?.status !== 'ended' && state.reconnect === 'allowed')\n return null;\n if (state.reconnect === 'new_session_on_next_action') return 'continue';\n if (state.reconnect === 'user_action_only') return 'continue_here';\n return null;\n }\n\n /** The streamed text, current at once; its listeners hear of it with the next flush. */\n private stream(state: ConversationState): void {\n const s = state.streaming;\n if (!s) {\n if (this.streaming !== null) {\n this.streaming = null;\n this.streamDirty = true;\n }\n return;\n }\n if (this.streaming?.turnId === s.turnId && this.streaming.text === s.text)\n return;\n this.streaming = { key: `a:${s.turnId}`, turnId: s.turnId, text: s.text };\n this.streamDirty = true;\n }\n\n private scheduler(): FrameScheduler {\n return this.options.scheduler ?? defaultScheduler;\n }\n\n // ------------------------------------------------------------ persistence\n\n private key(): string {\n return this.options.persistenceKey ?? 'vinaverse.conversation';\n }\n\n private restore(): void {\n const store = this.options.persistence;\n if (!store) return;\n const done = () => {\n this.historyState = 'restored';\n this.update();\n };\n const apply = (raw: string | null) => {\n if (this.disposed) return;\n if (raw === null) return done();\n try {\n const saved = JSON.parse(raw) as { v?: unknown; items?: unknown };\n // Another version (an older kit's), or not a list: dropped. It still ends restored, or the skeleton stays.\n if (saved.v === PERSIST_VERSION && Array.isArray(saved.items))\n this.history = (saved.items as TimelineItem[]).map((item) =>\n item.type === 'card'\n ? ({ ...item, busy: false, restored: true } as CardItem)\n : item,\n );\n } catch {\n // A kept conversation that no longer reads is dropped, never fatal.\n }\n done();\n };\n try {\n const raw = store.getItem(this.key());\n if (typeof raw === 'string' || raw === null) apply(raw);\n else {\n // Async storage (Capacitor Preferences, IndexedDB): the UI draws a skeleton, not an empty conversation.\n this.historyState = 'restoring';\n this.view = this.compute(null);\n raw.then(apply, () => {\n if (!this.disposed) done();\n });\n }\n } catch {\n done(); // storage unavailable: nothing restored\n }\n }\n\n private schedulePersist(): void {\n const store = this.options.persistence;\n if (!store || this.disposed || this.persistTimer !== undefined) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = undefined;\n const items = this.view.items.filter(persistable).slice(-HISTORY);\n try {\n void store.setItem(\n this.key(),\n JSON.stringify({ v: PERSIST_VERSION, items }),\n );\n } catch {\n // storage full or unavailable: the conversation goes on\n }\n }, PERSIST_DELAY);\n }\n\n // ------------------------------------------------------------ guards\n\n /** Past the session's end (`expires_at`), when the backend passed it on. */\n private sessionOver(): boolean {\n const end = this.info?.expires_at;\n return (\n end !== undefined &&\n (this.options.clock?.now() ?? Date.now()) >= Date.parse(end)\n );\n }\n\n private live(): void {\n if (this.disposed)\n throw new VinaverseClientError(\n 'session_ended',\n 'This conversation was closed.',\n );\n }\n\n private required(): VinaverseSession {\n this.live();\n if (!this.session)\n throw new VinaverseClientError(\n 'session_ended',\n 'The conversation has no session yet: start() it first.',\n );\n return this.session;\n }\n}\n\n/** One conversation with an agent, for any UI: see `ConversationStore`. */\nexport function createConversation(\n options: ConversationOptions,\n): ConversationStore {\n return new ConversationStore(options);\n}\n\nconst defaultScheduler: FrameScheduler = {\n request(callback) {\n const raf = (\n globalThis as {\n requestAnimationFrame?: (cb: () => void) => unknown;\n }\n ).requestAnimationFrame;\n return raf ? { raf: raf(callback) } : { timer: setTimeout(callback, 16) };\n },\n cancel(handle) {\n const h = handle as {\n raf?: unknown;\n timer?: ReturnType<typeof setTimeout>;\n };\n const caf = (globalThis as { cancelAnimationFrame?: (id: unknown) => void })\n .cancelAnimationFrame;\n if (h.raf !== undefined) caf?.(h.raf);\n if (h.timer !== undefined) clearTimeout(h.timer);\n },\n};\n\nfunction banner(\n status: ConversationStatus,\n next: ConversationView['next'],\n): ConversationBanner {\n if (status === 'connecting' || status === 'starting') return 'connecting';\n if (status === 'reconnecting') return 'reconnecting';\n if (status === 'offline') return 'offline';\n if (status === 'unavailable' || status === 'unauthorized')\n return 'unavailable';\n if (next === 'continue_here') return 'continued_elsewhere';\n return null;\n}\n\nfunction sameAgent(\n agent: ConversationView['agent'] | undefined,\n name: string | null,\n avatarUrl: string | null,\n): boolean {\n return agent?.name === name && agent?.avatarUrl === avatarUrl;\n}\n\nfunction sameTools(\n a: ConversationView['activity'],\n b: ConversationView['activity'],\n): boolean {\n return (\n a.length === b.length &&\n a.every(\n (t, i) =>\n t.turn_id === b[i]?.turn_id &&\n t.label === b[i]?.label &&\n t.state === b[i]?.state,\n )\n );\n}\n\nfunction shallowEqual(a: ConversationView, b: ConversationView): boolean {\n return (\n a.status === b.status &&\n a.banner === b.banner &&\n a.next === b.next &&\n a.agent.name === b.agent.name &&\n a.agent.avatarUrl === b.agent.avatarUrl &&\n a.disclosure === b.disclosure &&\n a.takeover?.by === b.takeover?.by &&\n a.takeover?.at === b.takeover?.at &&\n (a.takeover === null) === (b.takeover === null) &&\n a.items === b.items &&\n a.activity === b.activity &&\n a.responding === b.responding &&\n a.openQuestion === b.openQuestion &&\n a.answersNeedWebSocket === b.answersNeedWebSocket &&\n a.turnsLeft === b.turnsLeft &&\n a.history === b.history\n );\n}\n","// The agent runtime: everything an app needs around a conversation store, so the app keeps only its own API (the\n// `AgentBackend`), its router and its brand. One conversation per person, mode, business and thread, never mixed; kept\n// while a view shows it (and, by policy, across screens while its session lives); the tenant's backend waited out by a\n// retry policy, never answered with a new conversation; typed reasons when there is no session; a clock adapter for\n// the session's end; the screen context told at open and live where the backend serves it; status, name, ratings,\n// sign-out and events. No React: the kits bind to it.\n\nimport {\n type ConversationActivity,\n type ConversationOptions,\n type ConversationPersistence,\n type ConversationSession,\n type ConversationStore,\n createConversation,\n type SessionRequest,\n} from '../conversation/store.js';\nimport { VinaverseClientError } from '../errors.js';\nimport type { ClientSecret, Schemas } from '../events.js';\nimport { randomId } from '../session.js';\n\n/** Whose conversation: a person (null for a guest), the app's side, the business acted for, and the thread. */\nexport interface AgentKey {\n readonly subject: string | null;\n readonly mode: string;\n readonly scope?: string | null;\n /** Default `chat`; a flow of its own (a business setup, say) is another thread. */\n readonly thread?: string;\n}\n\ntype ScreenContext = Schemas['ScreenContext'];\n\n/**\n * Where the person asks from, in the contract's vocabulary (`ScreenContext`: the screen, the entity, the filters): told\n * to the agent as data (`Session.screen_context`), never as their words. The tenant's backend vouches for it.\n */\nexport interface AgentPlace {\n readonly screen: ScreenContext['screen'];\n readonly entity?: { readonly type: string; readonly id: string } | null;\n readonly filters?: ScreenContext['filters'];\n}\n\n/** How the person came in: the kit's parts say `launcher` and `ask`; an app adds `deep_link` or its own words. */\nexport type AgentEntryPoint =\n | 'launcher'\n | 'ask'\n | 'deep_link'\n | (string & Record<never, never>);\n\n/** What the runtime asks the tenant's backend for: a session, for this key, told this place. */\nexport interface AgentSessionRequest extends SessionRequest {\n readonly key: AgentKey;\n /**\n * This session creation's id: the same through its retries, so the backend uses it as the gateway's idempotency key\n * and never opens twice; a new one for every creation (a first open, a resume, continue-here, a rollover). A creation\n * that could not reach the backend keeps it, and its whole request, for the next try, the person's \"try again\" too,\n * for 24 hours. An `unknown_open` answer is final: not retried under it.\n */\n readonly openId: string;\n /** The runtime's `agent`, for a backend that serves more than one. */\n readonly agent: string | null;\n readonly place: AgentPlace | null;\n /**\n * The place's revision (`ScreenContext.revision`): higher than any the session was told before, and lower than any\n * `updateContext` after it, so the API keeps the newest place across a session's rollover.\n */\n readonly placeRevision: number;\n /** How the person came in (`launcher`, `ask`, `deep_link`, the app's own words), passed through. */\n readonly entryPoint: AgentEntryPoint | null;\n}\n\n/** Why there is no session, typed, so an app never needs sentinel errors of its own. */\nexport type AgentFailureReason =\n /** The conversation is over (its session's own end, or a refusal with no finer reason). */\n | 'ended'\n /** The conversation asked for does not exist for this person (deleted, or never theirs). */\n | 'not_found'\n /** Past the time the conversation is kept. */\n | 'expired'\n /** The conversation belongs to another business, mode or agent than the key's. */\n | 'mismatch'\n /** The conversation's flow is completed; a new one starts when the person asks. */\n | 'completed'\n /** The person may not act for this business or conversation. */\n | 'forbidden'\n /** The server holds a newer screen context than the one told (an update, never a session). */\n | 'conflict'\n /** The backend could not tell whether the session opened: unavailable, never retried, its `openId` kept for support. */\n | 'unknown_open'\n /** The person's sign-in was refused by the tenant's API. */\n | 'auth'\n /** The agent is switched off for this tenant, mode or person. */\n | 'off'\n | 'rate_limited'\n /** No network, a timeout: retried, then said. */\n | 'network'\n /** The tenant's API or Vinaverse failed (5xx): retried, then said. */\n | 'server'\n /** The backend answered with a session the runtime will not use (not wss://, a field missing). */\n | 'invalid_session'\n | 'unknown';\n\n/**\n * A refusal from the backend, typed: `ended` (the conversation is over; a new one starts only when the person asks) or\n * `unavailable` with its reason. An error with `retryable: true` (and its `reason`, `network` by default) is waited out\n * by the retry policy, then said as `unreachable`.\n */\nexport class AgentRefusal extends Error {\n readonly reason: AgentFailureReason;\n readonly code: string | null;\n constructor(\n readonly kind: 'ended' | 'unavailable',\n options: {\n readonly reason?: AgentFailureReason;\n readonly code?: string;\n readonly message?: string;\n } = {},\n ) {\n super(\n options.message ??\n (kind === 'ended' ? 'The conversation is over.' : 'No agent now.'),\n );\n this.name = 'AgentRefusal';\n this.reason = options.reason ?? (kind === 'ended' ? 'ended' : 'unknown');\n this.code = options.code ?? null;\n }\n}\n\nexport interface AgentStatus {\n readonly available: boolean;\n /** The floating launcher may show. */\n readonly launcher: boolean;\n readonly displayName: string | null;\n readonly avatarUrl: string | null;\n readonly features: {\n readonly history: boolean;\n readonly memory: boolean;\n readonly businessAgent: boolean;\n readonly businessSetup: boolean;\n };\n}\n\n/** The status as the backend reads it; what it leaves out is off. */\nexport interface AgentStatusRead {\n readonly available: boolean;\n readonly launcher?: boolean;\n readonly displayName?: string | null;\n readonly avatarUrl?: string | null;\n readonly features?: Partial<AgentStatus['features']>;\n}\n\n/** The status and where its read stands, so a screen tells \"reading\" from \"could not read\". */\nexport interface AgentStatusState {\n readonly status: AgentStatus | null;\n readonly reading: boolean;\n readonly failed: boolean;\n}\n\n/** The tenant's backend: the one piece of integration an app writes. */\nexport interface AgentBackend {\n /** A session from the tenant's API (it creates it at Vinaverse with its service key), or an `AgentRefusal`. */\n openSession(request: AgentSessionRequest): Promise<ConversationSession>;\n /**\n * A fresh client secret for the same session (before its end): a `ClientSecret` `{ value, expires_at }`, or its\n * value. A refusal (`session_closed`: the session is over) goes on with the conversation in a new session.\n */\n refreshSecret?(sessionId: string): Promise<ClientSecret | string>;\n /**\n * The person's place changed while the chat is open: the tenant's backend tells Vinaverse\n * (`PUT /v1/sessions/{id}/context`). A place cleared (`tell({ place: null })`) comes as `{ screen: 'other' }`.\n * `revision` only grows for a conversation, across its sessions. A conflict (`decodeBackendFailure`'s\n * `context_conflict`, or a refusal with reason `conflict`, with the server's `currentRevision`) is sent once more\n * above it, then said as `moved`. Absent, or refused otherwise, the kit offers a question about the new place.\n */\n updateContext?(\n sessionId: string,\n place: AgentPlace,\n revision: number,\n ): Promise<void>;\n /** Whether the agent is offered, and what it can do. Absent: available, nothing extra. */\n status?(signal?: AbortSignal): Promise<AgentStatusRead>;\n /** A thumbs on a whole reply; best effort, never an error for the person. */\n sendFeedback?(feedback: {\n readonly sessionId: string;\n readonly turnId: string;\n readonly rating: AgentRating;\n }): Promise<void>;\n /** Sign-out: end the person's open sessions at the tenant's API. */\n endSessions?(): Promise<void>;\n /** History's delete: the tenant's API deletes the person's conversation (authenticated, theirs only). */\n deleteConversation?(conversationId: string): Promise<void>;\n /**\n * History: the person's past conversations with the agent, newest activity first, a page at a time (`cursor` from\n * the page before). The person comes from the backend's authentication, never from here.\n */\n listConversations?(\n query: {\n readonly mode: string;\n readonly scope: string | null;\n readonly agent: string | null;\n readonly limit?: number;\n readonly cursor: string | null;\n },\n signal?: AbortSignal,\n ): Promise<Schemas['ConversationPage']>;\n /** History: a past conversation's messages and cards, the newest page first, oldest first within a page. */\n readConversation?(\n conversationId: string,\n page: { readonly limit?: number; readonly cursor: string | null },\n signal?: AbortSignal,\n ): Promise<Schemas['TimelinePage']>;\n}\n\nexport type AgentRating = 'up' | 'down';\nexport type AgentFailure = 'ended' | 'unreachable' | 'unavailable';\n\nexport type AgentEventType =\n | 'session_opened'\n | 'session_resumed'\n | 'session_retried'\n | 'session_failed'\n | 'conversation_ended'\n | 'context_updated'\n | 'rated'\n | 'chip_tapped'\n | 'card_action'\n | 'target_opened'\n | 'link_opened'\n | 'launcher_shown'\n | 'launcher_opened'\n | 'launcher_greeted'\n | 'greeting_closed'\n | 'message_sent'\n | 'reply_completed'\n | 'card_shown';\n\n/** For the app's analytics: what happened, for which conversation, with nothing the person said. */\nexport interface AgentEvent {\n readonly type: AgentEventType;\n /** The conversation, as a hash of its key (`hashKey`): stable, and never the person's id. */\n readonly key?: string;\n readonly sessionId?: string;\n readonly failure?: AgentFailure;\n readonly reason?: AgentFailureReason;\n readonly attempt?: number;\n readonly turnId?: string;\n readonly rating?: AgentRating;\n readonly cardId?: string;\n readonly kind?: string;\n /** Where the person opened from (`launcher`, `ask`, `deep_link`, the app's own words). */\n readonly from?: AgentEntryPoint;\n}\n\n/** What a UI draws around the store: why there is no session, whether the person moved, the thumbs given. */\nexport interface AgentConversationState {\n readonly failure: AgentFailure | null;\n readonly reason: AgentFailureReason | null;\n /** The API's own code for the failure (`conversation_expired`, …), when it gave one. */\n readonly code: string | null;\n /** The session was told another place than the one the person now asks from, and it could not be told live. */\n readonly moved: boolean;\n readonly ratings: ReadonlyMap<string, AgentRating>;\n readonly sessionId: string | null;\n /**\n * The conversation the key holds: the one it continues before a session opens, then its session's. Null for a new\n * one not yet opened. History's delete compares against it (`deleteConversation` does).\n */\n readonly conversationId: string | null;\n /** The open the backend could not settle (`unknown_open`), for support; null otherwise. */\n readonly openId: string | null;\n}\n\nexport interface AgentConversation {\n /** The key as a string, for the app's own maps and the events. */\n readonly key: string;\n readonly store: ConversationStore;\n /**\n * A view attaches: kept, with its connection, while any view is attached. The first time, it starts. Returns the\n * detach: with no view attached it is suspended (no pings; closed with `closeInBackground`) while its session lives\n * (`keepAlive: 'session'`), and let go when it has none, is past its end, or `keepAlive` is `'view'`. Separate from the\n * app's background, which the platform adapter tells the store.\n */\n show(open?: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: AgentEntryPoint | null;\n }): () => void;\n /**\n * The place and the way in changed while a view is attached: told live where the backend can, else on the next\n * session. `undefined` keeps what was told; `null` clears it.\n */\n tell(open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: AgentEntryPoint | null;\n }): void;\n getState(): AgentConversationState;\n subscribe(listener: () => void): () => void;\n /** Asks for a session again, after the backend could not be reached. */\n retry(): void;\n /**\n * Whether a reply can be rated: one this runtime saw given live. A reply restored from the device or a resumed\n * transcript cannot be, until the API rates a turn by its conversation; the kits draw no thumbs for it.\n */\n canRate(turnId: string): boolean;\n /** A thumbs on a whole reply, against the session it was given in; a change of mind only is sent again. */\n rate(turnId: string, rating: AgentRating): void;\n /**\n * Sends the person's `text` once in this conversation's life (a chip tapped twice, a retried tap). It is shown as\n * theirs: only words they typed or tapped, never the app's in their name.\n */\n sendOnce(text: string): void;\n}\n\n/** When the runtime tries the backend again: before each try, a delay; `isRetryable` decides which errors are waited out. */\nexport interface AgentRetryPolicy {\n readonly delays: readonly number[];\n readonly isRetryable?: (error: unknown) => boolean;\n}\n\n/** The time the runtime judges a session's end by: the server's, when the app has it (a clock synced from responses). */\nexport interface AgentClock {\n now(): number;\n}\n\nexport interface AgentRuntimeOptions {\n readonly backend: AgentBackend;\n /**\n * The agent this runtime talks to (its id at Vinaverse). It is part of every key, so two agents sharing the device's\n * storage (`conversation.persistence`) never share a conversation. Default: none (one agent per storage namespace).\n */\n readonly agent?: string;\n /** The store's own options (locale, time zone, deep-link prefixes, transport, persistence, closeInBackground…). */\n readonly conversation?: Omit<\n ConversationOptions,\n 'getSession' | 'refreshSecret' | 'clock'\n >;\n /** Default: 500, 1500, 3500 ms, for errors with `retryable: true`; applied to `openSession` and `refreshSecret`. */\n readonly retry?: AgentRetryPolicy;\n /** Default: the device's clock. Give the server's: a phone set wrong otherwise reuses a dead session or drops a live one. */\n readonly clock?: AgentClock;\n /** `session` (default): kept while its session lives with no view attached; `view`: let go when the last view goes. */\n readonly keepAlive?: 'session' | 'view';\n /** How long a status read stays fresh. Default 5 minutes. */\n readonly statusStaleMs?: number;\n /**\n * DANGEROUS: for mocks and local development only. Lets a leg's session address be plaintext (`ws://`, `http://`),\n * which would carry the person's messages and the session's secret unencrypted. Off by default, whatever transport\n * the app supplies; outside `__DEV__` the runtime warns once.\n */\n readonly insecureAddresses?: AgentInsecureAddresses;\n readonly onEvent?: (event: AgentEvent) => void;\n /**\n * Where the launcher remembers it greeted a person (the app's preferences store). Given here, the launcher reads and\n * writes it through the runtime (`greetings`), a sign-out fences it, and `erase()` removes it.\n */\n readonly greetingStorage?: ConversationPersistence;\n /**\n * Keys an earlier version of the app or the kit wrote that no index lists, for a storage with neither `keys` nor\n * `removePrefix`: removed by every sign-out from `conversation.persistence`, and by `erase()` from `greetingStorage`\n * too. The migration that makes their removal certain on such a storage.\n */\n readonly legacyKeys?: readonly string[];\n /** Where the runtime's warnings go (the app's logger, crash reporter); default `console.warn`. */\n readonly onWarning?: (message: string, warning: AgentWarning) => void;\n}\n\n/**\n * What a warning is about, for an app's logger to count without reading the message: `insecure_addresses` (a leg let\n * off the wss:// and https:// check outside development), `callback_threw` (the app's `onEvent` or `onActivity` threw;\n * `callback` names it), `events_dropped` (the oldest analytics events, while the salt is read).\n */\nexport interface AgentWarning {\n readonly code: 'insecure_addresses' | 'callback_threw' | 'events_dropped';\n readonly callback?: 'onEvent' | 'onActivity';\n}\n\n/** The legs whose session address may be plaintext: `realtime` (the WebSocket), `turns` (HTTP). */\nexport interface AgentInsecureAddresses {\n readonly realtime?: boolean;\n readonly turns?: boolean;\n}\n\nexport interface AgentRuntime {\n /** The app's backend, as given: history (`@vinaverse/client/history`) reads its pages through it. */\n readonly backend: AgentBackend;\n /** The key's conversation: the same while it lives; a new one after `startNew`, `dispose` or its end. */\n conversation(key: AgentKey): AgentConversation;\n /**\n * The key's conversation as it stands, ending nothing and telling no one: for a render (`useSyncExternalStore`).\n * One past its session's end is ended when it is next shown, and subscribers then read the key's next one.\n */\n peek(key: AgentKey): AgentConversation;\n /** A new conversation for the key from the person's next opening; the old one is let go and forgotten. */\n startNew(key: AgentKey): void;\n /**\n * Closes the key's conversation now; the next opening continues it in a new session. What the device kept of it and\n * the conversation it continues stay: `forget` removes them.\n */\n dispose(key: AgentKey): void;\n /**\n * Closes the key's conversation and forgets it on this device: the conversation it continued and the transcript kept\n * by `persistence`. History's \"delete\" calls it after the tenant's backend deleted the conversation.\n */\n forget(key: AgentKey): void;\n /** Ends every conversation no view shows that is past its session's end. The kits call it when the app comes back. */\n sweep(): void;\n /**\n * History's delete: the backend deletes the conversation, then the device forgets it, only where the key still\n * continues that conversation (an older history entry never forgets the key's newer one).\n */\n deleteConversation(key: AgentKey, conversationId: string): Promise<void>;\n /**\n * The person's erasure on this device: a sign-out, plus the launcher's greeting records (`greetingStorage`) and the\n * analytics salt, every key this version and alpha.5 or alpha.6 wrote. Keys no index lists (an earlier version's, a\n * write lost with its process) are found only when the storage has `keys` or `removePrefix`.\n */\n erase(): Promise<void>;\n /** The launcher's greeting storage, under the sign-out fence; null without `greetingStorage`. */\n readonly greetings: ConversationPersistence | null;\n /**\n * The key goes on with this conversation (history's \"Continue\"): pinned for the key and opened through the backend's\n * resume. One that is gone (404, 410: the backend's `AgentRefusal('ended')`) is said as `ended`, never replaced by a\n * new one silently.\n */\n continue(key: AgentKey, conversationId: string): AgentConversation;\n /**\n * Every conversation closed and forgotten, and everything this runtime kept on the device (every transcript it ever\n * wrote under `conversation.persistenceKey`, even of conversations already closed), the status and the name; then\n * the backend is told to end the sessions at the same time. A late answer from before (a session, a status, a write)\n * changes nothing. Kept on purpose: the launcher's greeting records and the analytics salt (`erase` takes them).\n */\n signOut(): Promise<void>;\n /** The agent's status, read from the backend at most every `statusStaleMs`. */\n status(): Promise<AgentStatus>;\n getStatus(): AgentStatus | null;\n /**\n * The status with where its read stands: `reading` while one is out, `failed` when the last one could not be read\n * (the status held before, if any, stays). One object until it changes, for `useSyncExternalStore`.\n */\n getStatusState(): AgentStatusState;\n /**\n * Which person's turn it is on this device: a number that changes at every sign-out and erasure. Work begun under an\n * older one (a history page, a transcript) is dropped when it lands.\n */\n epoch(): number;\n /** The agent's name: from the newest session, else from the status. */\n getName(): string | null;\n /** Told when the status or name changes, and when a key's conversation is let go (its next one is another). */\n subscribe(listener: () => void): () => void;\n /** An event from a kit or the app, passed to `onEvent`. */\n emit(event: AgentEvent): void;\n}\n\n/** The launcher's greeting records' prefix: outside the transcripts' (`vinaverse.agent.`), so a sign-out keeps them. */\nconst GREETED = 'vinaverse.greeted';\n/** Where alpha.5 and alpha.6 kept them. */\nconst GREETED_BEFORE = 'vinaverse.agent.greeted';\n\n/**\n * Where the launcher remembers that it greeted a person in a mode, the key its storage sees. Encoded so a guest\n * (`null`) is never a person whose id is \"guest\".\n */\nexport function greetedKey(subject: string | null, mode: string): string {\n return `${GREETED}.${JSON.stringify([subject, mode])}`;\n}\n\n/** The tuple inside a key written by this version (`<prefix>.<agentKey>`), or null for any other. */\nfunction tupleOf(key: string, prefix: string): unknown[] | null {\n if (!key.startsWith(`${prefix}.[`)) return null;\n try {\n const t: unknown = JSON.parse(key.slice(prefix.length + 1));\n return Array.isArray(t) ? t : null;\n } catch {\n return null;\n }\n}\n\n/** alpha.5 and alpha.6 kept a transcript and a greeting under these names: found from the keys this version knows. */\nfunction legacyTranscripts(keys: ReadonlySet<string>, prefix: string) {\n const out: string[] = [];\n for (const key of keys) {\n const t = tupleOf(key, prefix);\n if (t)\n out.push(\n `${prefix}.${t[1] ?? 'guest'}|${t[2]}|${t[3] ?? '-'}|${t[4] ?? 'chat'}`,\n );\n }\n return out;\n}\nfunction legacyGreetings(pairs: Iterable<readonly [unknown, unknown]>) {\n const out: string[] = [];\n for (const [subject, mode] of pairs)\n out.push(`${GREETED_BEFORE}.${subject ?? 'guest'}:${mode}`);\n return out;\n}\n\nconst NOT_KEPT = new Set(['starting', 'unavailable', 'unauthorized', 'closed']);\n/** A place cleared, as `updateContext` sends it: a screen the vocabulary keeps for none in particular. */\nconst CLEARED: AgentPlace = { screen: 'other' };\n\n/**\n * A conversation's key as analytics sees it: SHA-256 of the install's salt and the key, 128 bits in hex. Stable per\n * install (the runtime keeps the salt in the app's storage until `erase()`), never the person's id, and not\n * recomputable from a guessed id without the salt.\n */\nexport function hashKey(key: string, salt: string): string {\n return `k${sha256(`${salt}\\u0000${key}`).slice(0, 32)}`;\n}\n\nlet K: number[] | undefined;\nlet H: number[] | undefined;\n\n/** SHA-256 of a string's UTF-8 bytes, in hex (FIPS 180-4; no platform crypto: Hermes has none, and this is sync). */\nexport function sha256(text: string): string {\n if (!K || !H) {\n // The first 32 bits of the fractional parts of the primes' cube roots (K) and the first eight's square roots (H).\n K = [];\n H = [];\n for (let n = 2; K.length < 64; n++) {\n let prime = true;\n for (let d = 2; d * d <= n; d++) if (n % d === 0) prime = false;\n if (!prime) continue;\n if (H.length < 8) H.push(((Math.sqrt(n) % 1) * 2 ** 32) | 0);\n K.push(((Math.cbrt(n) % 1) * 2 ** 32) | 0);\n }\n }\n const bytes: number[] = [];\n const s = encodeURIComponent(text);\n for (let i = 0; i < s.length; i++)\n if (s[i] === '%') {\n bytes.push(Number.parseInt(s.slice(i + 1, i + 3), 16));\n i += 2;\n } else bytes.push(s.charCodeAt(i));\n const bits = bytes.length * 8;\n bytes.push(0x80);\n while (bytes.length % 64 !== 56) bytes.push(0);\n for (const word of [Math.floor(bits / 2 ** 32), bits >>> 0])\n bytes.push(\n word >>> 24,\n (word >>> 16) & 255,\n (word >>> 8) & 255,\n word & 255,\n );\n const h = [...H];\n const w = new Array<number>(64);\n const ror = (x: number, n: number) => (x >>> n) | (x << (32 - n));\n for (let at = 0; at < bytes.length; at += 64) {\n for (let i = 0; i < 64; i++) {\n if (i < 16) {\n const b = at + i * 4;\n w[i] =\n ((bytes[b] as number) << 24) |\n ((bytes[b + 1] as number) << 16) |\n ((bytes[b + 2] as number) << 8) |\n (bytes[b + 3] as number);\n } else {\n const x = w[i - 15] as number;\n const y = w[i - 2] as number;\n w[i] =\n ((w[i - 16] as number) +\n (ror(x, 7) ^ ror(x, 18) ^ (x >>> 3)) +\n (w[i - 7] as number) +\n (ror(y, 17) ^ ror(y, 19) ^ (y >>> 10))) |\n 0;\n }\n }\n let [a, b, c, d, e, f, g, k] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ];\n for (let i = 0; i < 64; i++) {\n const t1 =\n (k +\n (ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)) +\n ((e & f) ^ (~e & g)) +\n (K[i] as number) +\n (w[i] as number)) |\n 0;\n const t2 =\n ((ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)) +\n ((a & b) ^ (a & c) ^ (b & c))) |\n 0;\n k = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n [a, b, c, d, e, f, g, k].forEach((v, i) => {\n h[i] = ((h[i] as number) + v) | 0;\n });\n }\n return h.map((v) => (v >>> 0).toString(16).padStart(8, '0')).join('');\n}\nconst NO_FEATURES: AgentStatus['features'] = {\n history: false,\n memory: false,\n businessAgent: false,\n businessSetup: false,\n};\nconst SYSTEM_CLOCK: AgentClock = { now: () => Date.now() };\n\n/**\n * The key as a string: one conversation per agent, person, mode, business and thread. Encoded as a JSON array, so no\n * value can pass for another (a guest is `null`, never a subject named \"guest\"; a `|` in an id is just a character).\n */\nexport function agentKey(key: AgentKey, agent: string | null = null): string {\n return JSON.stringify([\n agent,\n key.subject,\n key.mode,\n key.scope ?? null,\n key.thread ?? 'chat',\n ]);\n}\n\nconst samePlace = (a: AgentPlace | null, b: AgentPlace | null) =>\n a?.screen === b?.screen &&\n (a?.entity?.type ?? null) === (b?.entity?.type ?? null) &&\n (a?.entity?.id ?? null) === (b?.entity?.id ?? null) &&\n JSON.stringify(a?.filters ?? null) === JSON.stringify(b?.filters ?? null);\n\n/** A session the runtime will use: an id, a secret, and `wss://` and `https://` addresses unless a leg is let off. */\nfunction usable(\n session: ConversationSession,\n insecure: AgentInsecureAddresses,\n): boolean {\n return (\n typeof session.id === 'string' &&\n session.id !== '' &&\n (insecure.realtime === true ||\n /^wss:\\/\\//i.test(session.realtime_url ?? '')) &&\n (insecure.turns === true || /^https:\\/\\//i.test(session.turns_url ?? '')) &&\n Boolean(session.client_secret)\n );\n}\n\n/** Once, as the runtime is made (once per app), outside development: plaintext would carry messages and the secret. */\nfunction warnInsecure(\n insecure: AgentInsecureAddresses,\n warn: (message: string, warning: AgentWarning) => void,\n): void {\n if (!(insecure.realtime || insecure.turns)) return;\n if ((globalThis as { __DEV__?: boolean }).__DEV__ === true) return;\n warn(\n '@vinaverse/client/agent: insecureAddresses lets sessions use plaintext ws:// or http:// addresses. For mocks and local development only.',\n { code: 'insecure_addresses' },\n );\n}\n\ninterface Entry {\n readonly key: string;\n readonly store: ConversationStore;\n readonly listeners: Set<() => void>;\n state: AgentConversationState;\n place: AgentPlace | null;\n told: AgentPlace | null;\n revision: number;\n entryPoint: string | null;\n expiresAt: number | null;\n shown: number;\n started: boolean;\n suspended: boolean;\n sentOnce: Set<string>;\n /** Ends it at its session's end while no view shows it (when the app's timers run; `sweep` otherwise). */\n timer: ReturnType<typeof setTimeout> | undefined;\n /** Each reply's own session, so a thumbs rates the turn against the session it was given in. */\n readonly turns: Map<string, string>;\n /**\n * The session creation that could not reach the backend: asked again unchanged (its `openId`, its body) by the next\n * try, the person's too, for a day, so a creation whose answer was lost never opens a second session.\n */\n failedOpen:\n | { readonly request: AgentSessionRequest; readonly at: number }\n | undefined;\n}\n\n/** How long a failed session creation is asked again under its own `openId` (the gateway keeps one 24 hours). */\nconst OPEN_KEPT_MS = 24 * 3_600_000;\n/** Events kept while the analytics salt is read; the oldest go past it. */\nconst MAX_WAITING = 100;\n\nexport function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime {\n const { backend } = options;\n const policy: Required<AgentRetryPolicy> = {\n delays: options.retry?.delays ?? [500, 1500, 3500],\n isRetryable: options.retry?.isRetryable ?? retryable,\n };\n const clock = options.clock ?? SYSTEM_CLOCK;\n const keepAlive = options.keepAlive ?? 'session';\n const staleMs = options.statusStaleMs ?? 5 * 60_000;\n const insecure = options.insecureAddresses ?? {};\n warnInsecure(insecure, options.onWarning ?? ((m: string) => console.warn(m)));\n const live = new Map<string, Entry>();\n const current = new Map<string, string>();\n const listeners = new Set<() => void>();\n let status: { value: AgentStatus; at: number } | null = null;\n let reading: Promise<AgentStatus> | null = null;\n const NO_STATUS: AgentStatusState = {\n status: null,\n reading: false,\n failed: false,\n };\n let statusState = NO_STATUS;\n const setStatusState = (next: Omit<AgentStatusState, 'status'>) => {\n statusState = { status: status?.value ?? null, ...next };\n changed();\n };\n let sessionName: string | null = null;\n // Bumped by every sign-out: anything begun before it (a status read, a write to the device) lands nowhere.\n let generation = 0;\n const keyOf = (key: AgentKey) => agentKey(key, options.agent ?? null);\n const prefix = options.conversation?.persistenceKey ?? 'vinaverse.agent';\n const storage = guardedStorage(\n options.conversation?.persistence,\n prefix,\n () => generation,\n );\n const greetings = guardedStorage(\n options.greetingStorage,\n GREETED,\n () => generation,\n );\n\n const warn: (message: string, warning: AgentWarning) => void =\n options.onWarning ?? ((m: string) => console.warn(m));\n /** The app's callback runs isolated: what it throws is said through `onWarning`, never in the way of a frame. */\n const isolated = (what: 'onEvent' | 'onActivity', call: () => void) => {\n try {\n call();\n } catch (error) {\n warn(\n `@vinaverse/client/agent: the app's ${what} threw (${error instanceof Error ? error.message : String(error)}); the conversation went on.`,\n { code: 'callback_threw', callback: what },\n );\n }\n };\n\n // Analytics never sees a key, which names the person: a hash of it under the install's salt, kept in the app's\n // storage (a new one per process without storage). Events wait for the salt's first read.\n const saltStore =\n options.conversation?.persistence ?? options.greetingStorage;\n const saltKey = `${prefix}:salt`;\n let salt: string | null = null;\n const waiting: AgentEvent[] = [];\n const loadSalt = () => {\n if (!options.onEvent) return; // no analytics, nothing kept for it\n const settle = (kept: string | null | undefined) => {\n if (salt !== null) return;\n if (kept) salt = kept;\n else {\n salt = randomId().slice(3);\n void Promise.resolve(saltStore?.setItem(saltKey, salt)).catch(\n () => undefined,\n );\n }\n for (const event of waiting.splice(0)) deliver(event);\n };\n try {\n const got = saltStore?.getItem(saltKey);\n if (typeof got === 'string' || got == null) settle(got);\n else got.then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n };\n const deliver = (event: AgentEvent) =>\n isolated('onEvent', () =>\n options.onEvent?.(\n event.key ? { ...event, key: hashKey(event.key, salt ?? '') } : event,\n ),\n );\n let dropping = false;\n const emit = (event: AgentEvent) => {\n if (!options.onEvent) return;\n if (salt !== null) return deliver(event);\n // A storage whose read never settles costs the oldest events, never memory.\n if (waiting.push(event) > MAX_WAITING) {\n waiting.shift();\n if (!dropping)\n warn(\n '@vinaverse/client/agent: the analytics salt is still being read from storage; the oldest events are dropped.',\n { code: 'events_dropped' },\n );\n dropping = true;\n }\n };\n loadSalt();\n const changed = () => {\n for (const l of [...listeners]) l();\n };\n const update = (entry: Entry, next: Partial<AgentConversationState>) => {\n entry.state = { ...entry.state, ...next };\n for (const l of [...entry.listeners]) l();\n };\n\n const end = (k: string) => {\n const entry = live.get(k);\n if (!entry) return;\n live.delete(k);\n clearTimeout(entry.timer);\n entry.store.dispose();\n emit({ type: 'conversation_ended', key: k });\n changed(); // the key's next conversation is another one\n };\n\n const patiently = <T>(\n run: () => Promise<T>,\n signal: AbortSignal | undefined,\n key: string,\n ) =>\n retrying(run, policy, signal, (attempt) =>\n emit({ type: 'session_retried', key, attempt }),\n );\n\n async function open(\n entry: Entry,\n key: AgentKey,\n request: SessionRequest,\n ): Promise<ConversationSession> {\n // Let go meanwhile (a start new, a sign-out): nothing to open.\n if (live.get(entry.key) !== entry) throw new AgentRefusal('unavailable');\n // A creation that could not reach the backend is asked again as it was; any other is a new one, with its own id\n // (a first open, a resume, continue-here, a rollover), the same through its retries. The runtime keeps which\n // conversation the key continues: the app's adapter is a plain call.\n const held =\n entry.failedOpen && clock.now() - entry.failedOpen.at < OPEN_KEPT_MS\n ? entry.failedOpen\n : undefined;\n entry.failedOpen = undefined;\n const asked: AgentSessionRequest = held\n ? {\n ...held.request,\n ...(request.signal ? { signal: request.signal } : {}),\n }\n : {\n ...request,\n conversationId:\n request.conversationId ?? current.get(entry.key) ?? null,\n key,\n openId: `op_${randomId().slice(3)}`,\n agent: options.agent ?? null,\n place: entry.place,\n placeRevision: ++entry.revision,\n entryPoint: entry.entryPoint,\n };\n const { conversationId, openId, place: told } = asked;\n let session: ConversationSession;\n try {\n session = await patiently(\n () => backend.openSession(asked),\n request.signal,\n entry.key,\n );\n if (!usable(session, insecure))\n throw new AgentRefusal('unavailable', {\n reason: 'invalid_session',\n message:\n 'Unusable session: an id, a secret, wss:// and https:// addresses.',\n });\n } catch (error) {\n if (live.get(entry.key) === entry) {\n const failure: AgentFailure = isRefusal(error)\n ? error.kind === 'ended' && conversationId !== null\n ? 'ended'\n : 'unavailable'\n : policy.isRetryable(error)\n ? 'unreachable'\n : 'unavailable';\n const reason = reasonOf(error, failure);\n const code = isRefusal(error) ? error.code : codeOf(error);\n if (failure === 'unreachable') {\n const { signal, ...again } = asked;\n void signal; // kept without its signal: the next try brings its own\n entry.failedOpen = { request: again, at: held?.at ?? clock.now() };\n }\n // An open the backend could not settle is said as unavailable, never retried, its id kept for support.\n const unsettled =\n reason === 'unknown_open'\n ? String(field(error, 'openId') ?? openId)\n : null;\n update(entry, { failure, reason, code, openId: unsettled });\n emit({ type: 'session_failed', key: entry.key, failure, reason });\n }\n throw error;\n }\n // Let go while the backend answered (a start new, a sign-out): touch nothing, or the old conversation would be\n // pinned again as the key's current one.\n if (live.get(entry.key) !== entry) throw new AgentRefusal('unavailable');\n entry.told = told;\n entry.expiresAt = session.expires_at\n ? Date.parse(session.expires_at)\n : null;\n if (session.conversation_id)\n current.set(entry.key, session.conversation_id);\n const name = session.agent?.display_name?.trim();\n if (name && name !== sessionName) {\n sessionName = name;\n changed();\n }\n update(entry, {\n failure: null,\n reason: null,\n code: null,\n openId: null,\n sessionId: session.id,\n conversationId: session.conversation_id ?? conversationId,\n moved: !samePlace(told, entry.place),\n });\n emit({\n type: conversationId === null ? 'session_opened' : 'session_resumed',\n key: entry.key,\n sessionId: session.id,\n ...(entry.entryPoint ? { from: entry.entryPoint } : {}),\n });\n return session;\n }\n\n /** Where a key's conversation is kept on the device, with `persistence`. */\n const kept = (k: string) => `${prefix}.${k}`;\n\n /**\n * Everything of the person on this device goes; the backend is told to end the sessions at the same time, never\n * after a slow storage. A write, a read or a status from before lands nowhere (the generation).\n */\n const signOut = async (erasing: boolean) => {\n generation++;\n if (erasing) salt = null; // events wait for the next install's salt\n for (const entry of live.values()) {\n clearTimeout(entry.timer);\n entry.store.clear();\n }\n const known = new Set([...live.keys(), ...current.keys()]);\n live.clear();\n current.clear();\n sessionName = null;\n status = null;\n reading = null;\n statusState = NO_STATUS;\n changed();\n // The people this device knew, for the greeting records alpha.5 and alpha.6 named after them.\n const pairs: [unknown, unknown][] = [];\n await Promise.all([\n backend.endSessions?.().catch(() => undefined),\n storage?.purge(\n [`${prefix}.`],\n (keys) => {\n const all = new Set([...keys, ...[...known].map(kept)]);\n for (const key of all) {\n const t = tupleOf(key, prefix);\n if (t) pairs.push([t[1], t[2]]);\n }\n return [\n ...all,\n ...legacyTranscripts(all, prefix),\n ...(options.legacyKeys ?? []),\n ];\n },\n `${GREETED}.`,\n ),\n ]);\n if (!erasing) return;\n await Promise.all([\n Promise.resolve(saltStore?.removeItem(saltKey)).catch(() => undefined),\n greetings?.purge([`${GREETED}.`, `${GREETED_BEFORE}.`], (keys) => {\n for (const key of keys) {\n const t = tupleOf(key, GREETED);\n if (t) pairs.push([t[0], t[1]]);\n }\n return [...legacyGreetings(pairs), ...(options.legacyKeys ?? [])];\n }),\n ]);\n loadSalt(); // a new install's, as far as analytics can tell\n };\n\n /** The key's conversation is no longer this device's: its pinned id and its kept transcript go. */\n const forget = (k: string) => {\n current.delete(k);\n const entry = live.get(k);\n if (entry) {\n entry.store.clear();\n end(k);\n } else void storage?.removeItem(kept(k));\n };\n\n const activity = (entry: Entry, a: ConversationActivity) => {\n const sessionId = entry.state.sessionId;\n if (a.type === 'reply_completed' && sessionId) {\n entry.turns.set(a.turnId, sessionId);\n update(entry, {}); // the reply can be rated now\n }\n emit({\n type: a.type,\n key: entry.key,\n ...(sessionId ? { sessionId } : {}),\n ...(a.type === 'reply_completed' ? { turnId: a.turnId } : {}),\n ...(a.type === 'card_shown' ? { cardId: a.cardId, kind: a.kind } : {}),\n });\n };\n\n function make(key: AgentKey): Entry {\n const k = keyOf(key);\n const own = options.conversation ?? {};\n const refresh = backend.refreshSecret?.bind(backend);\n const entry: Entry = {\n key: k,\n store: createConversation({\n ...own,\n ...(storage\n ? {\n persistence: storage,\n persistenceKey: kept(k),\n }\n : {}),\n onActivity: (a) => {\n activity(entry, a);\n isolated('onActivity', () => own.onActivity?.(a));\n },\n getSession: (request) => open(entry, key, request),\n ...(refresh\n ? {\n // A refusal (`session_closed`) is the store's cue to go on in a new session, never a fault.\n refreshSecret: (id: string) =>\n patiently(() => refresh(id), undefined, k).catch((error) => {\n throw isRefusal(error)\n ? new VinaverseClientError(\n 'needs_new_session',\n error.message,\n )\n : error;\n }),\n }\n : {}),\n clock,\n onError: (error) => {\n // A refusal is said through the state, and a session the server closed is rolled over: neither is a fault.\n if (!isRefusal(error) && codeOf(error) !== 'needs_new_session')\n own.onError?.(error);\n },\n }),\n listeners: new Set(),\n state: {\n failure: null,\n reason: null,\n code: null,\n moved: false,\n ratings: new Map(),\n sessionId: null,\n conversationId: current.get(k) ?? null,\n openId: null,\n },\n place: null,\n told: null,\n revision: 0,\n entryPoint: null,\n expiresAt: null,\n shown: 0,\n started: false,\n suspended: false,\n sentOnce: new Set(),\n timer: undefined,\n turns: new Map(),\n failedOpen: undefined,\n };\n return entry;\n }\n\n const over = (entry: Entry) =>\n entry.expiresAt !== null && entry.expiresAt <= clock.now();\n\n /** No view shows it: it ends at its session's end, even unseen (while the app's timers run). */\n const expireLater = (entry: Entry) => {\n clearTimeout(entry.timer);\n if (entry.expiresAt === null) return;\n entry.timer = setTimeout(\n () => {\n entry.timer = undefined;\n if (live.get(entry.key) !== entry || entry.shown > 0) return;\n if (over(entry)) end(entry.key);\n else expireLater(entry); // the clock it is judged by ran slower than the timer\n },\n Math.max(0, entry.expiresAt - clock.now()),\n );\n };\n\n /**\n * The new place: told live when the backend can (the session then knows it; `null` clears it), else `moved` until the\n * next session. Only the newest telling lands, and only on the session it was told to.\n */\n const tell = (\n entry: Entry,\n at: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: AgentEntryPoint | null;\n },\n ) => {\n if (at.place !== undefined) entry.place = at.place;\n if (at.entryPoint !== undefined) entry.entryPoint = at.entryPoint;\n const sessionId = entry.state.sessionId;\n const moved = sessionId !== null && !samePlace(entry.told, entry.place);\n update(entry, { moved });\n const updateContext = backend.updateContext?.bind(backend);\n if (!moved || !updateContext || sessionId === null) return;\n const asked = generation;\n const current = () =>\n asked === generation &&\n live.get(entry.key) === entry &&\n entry.state.sessionId === sessionId;\n const send = (again: boolean) => {\n // Always the newest place: a resend after a conflict carries what the person sees now.\n const place = entry.place;\n const revision = ++entry.revision;\n updateContext(sessionId, place ?? CLEARED, revision).then(\n () => {\n if (!current() || entry.revision !== revision) return;\n entry.told = place;\n update(entry, { moved: !samePlace(entry.told, entry.place) });\n emit({ type: 'context_updated', key: entry.key, sessionId });\n },\n (error: unknown) => {\n // The server holds a newer revision (`current_revision`): the newest place once more above it, only if the\n // session and the person are still the ones it was told for; then `moved`.\n const theirs = field(error, 'currentRevision');\n const conflict =\n field(error, 'outcome') === 'context_conflict' ||\n field(error, 'reason') === 'conflict';\n if (!conflict || again || !current() || entry.revision !== revision)\n return; // not served, or refused: the question about this place stays the way to say it\n if (typeof theirs === 'number' && theirs >= entry.revision)\n entry.revision = theirs;\n send(true);\n },\n );\n };\n send(false);\n };\n\n function handle(entry: Entry): AgentConversation {\n return {\n key: entry.key,\n store: entry.store,\n show(at = {}) {\n // Let go meanwhile, or past its session's end with no view: nothing to show; the key's next one is read anew.\n if (live.get(entry.key) !== entry) return () => undefined;\n if (entry.shown === 0 && over(entry)) {\n end(entry.key);\n return () => undefined;\n }\n entry.shown++;\n clearTimeout(entry.timer);\n entry.timer = undefined;\n if (entry.suspended) {\n entry.suspended = false;\n entry.store.setForeground(true);\n }\n tell(entry, at);\n if (!entry.started) {\n entry.started = true;\n entry.store.start();\n }\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry.shown--;\n if (entry.shown > 0 || live.get(entry.key) !== entry) return;\n if (\n keepAlive === 'view' ||\n NOT_KEPT.has(entry.store.getSnapshot().status) ||\n entry.expiresAt === null ||\n over(entry)\n ) {\n end(entry.key);\n return;\n }\n entry.suspended = true;\n entry.store.setForeground(false);\n expireLater(entry);\n };\n },\n tell: (at) => tell(entry, at),\n getState: () => entry.state,\n subscribe(listener) {\n entry.listeners.add(listener);\n return () => entry.listeners.delete(listener);\n },\n retry() {\n update(entry, {\n failure: null,\n reason: null,\n code: null,\n openId: null,\n });\n entry.store.start();\n },\n canRate: (turnId) => entry.turns.has(turnId),\n rate(turnId, rating) {\n // The session the reply was given in, never the one open now: a reply restored from before is not rated.\n const sessionId = entry.turns.get(turnId);\n if (!sessionId || entry.state.ratings.get(turnId) === rating) return;\n update(entry, {\n ratings: new Map(entry.state.ratings).set(turnId, rating),\n });\n emit({ type: 'rated', key: entry.key, sessionId, turnId, rating });\n void backend\n .sendFeedback?.({ sessionId, turnId, rating })\n .catch(() => undefined);\n },\n sendOnce(text) {\n if (entry.sentOnce.has(text)) return;\n entry.sentOnce.add(text);\n entry.store.send(text);\n },\n };\n }\n\n const handles = new WeakMap<Entry, AgentConversation>();\n\n const lookup = (key: AgentKey) => {\n const k = keyOf(key);\n let entry = live.get(k);\n if (!entry) {\n entry = make(key);\n live.set(k, entry);\n }\n let h = handles.get(entry);\n if (!h) {\n h = handle(entry);\n handles.set(entry, h);\n }\n return h;\n };\n\n return {\n conversation(key) {\n const k = keyOf(key);\n const entry = live.get(k);\n if (entry && entry.shown === 0 && over(entry)) end(k);\n return lookup(key);\n },\n peek: lookup,\n startNew(key) {\n const k = keyOf(key);\n current.delete(k);\n end(k);\n },\n dispose(key) {\n end(keyOf(key));\n },\n forget(key) {\n forget(keyOf(key));\n },\n sweep() {\n for (const entry of [...live.values()])\n if (entry.shown === 0 && over(entry)) end(entry.key);\n },\n continue(key, conversationId) {\n const k = keyOf(key);\n if (current.get(k) !== conversationId) {\n // What the device kept is another conversation's: forgotten, so the resumed transcript is the only one drawn.\n forget(k);\n current.set(k, conversationId);\n }\n return lookup(key);\n },\n async signOut() {\n await signOut(false);\n },\n async erase() {\n await signOut(true);\n },\n async deleteConversation(key, conversationId) {\n if (!backend.deleteConversation)\n throw new Error(\n '@vinaverse/client/agent: deleteConversation needs AgentBackend.deleteConversation.',\n );\n await backend.deleteConversation(conversationId);\n const k = keyOf(key);\n const continued =\n current.get(k) ??\n live.get(k)?.store.getSnapshot().conversationId ??\n null;\n if (continued === conversationId) forget(k);\n },\n greetings: greetings ?? null,\n status() {\n if (status && clock.now() - status.at < staleMs)\n return Promise.resolve(status.value);\n if (reading) return reading;\n const asked = generation;\n const read = readStatus(backend).then(\n (value) => {\n if (asked !== generation) return value; // read for the person before a sign-out: not kept\n reading = null;\n status = { value, at: clock.now() };\n setStatusState({ reading: false, failed: false });\n return value;\n },\n (error: unknown) => {\n if (asked === generation) {\n reading = null;\n setStatusState({ reading: false, failed: true });\n }\n throw error;\n },\n );\n reading = read;\n setStatusState({ reading: true, failed: statusState.failed });\n return read;\n },\n getStatus: () => status?.value ?? null,\n getStatusState: () => statusState,\n backend,\n epoch: () => generation,\n getName: () => sessionName ?? status?.value.displayName ?? null,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n emit,\n };\n}\n\n/**\n * The app's storage as the runtime's stores use it: writes and removals for a key run in the order they were made, a\n * read waits for them, a write begun before a sign-out lands nowhere, and every key written is listed (under\n * `<prefix>:index`), so a sign-out removes all of them, closed conversations' too.\n */\nfunction guardedStorage(\n raw: ConversationPersistence | undefined,\n prefix: string,\n generation: () => number,\n):\n | (ConversationPersistence & {\n purge(\n under: readonly string[],\n extra?: (keys: ReadonlySet<string>) => Iterable<string>,\n keep?: string,\n ): Promise<void>;\n })\n | undefined {\n if (!raw) return undefined;\n const indexKey = `${prefix}:index`;\n const chains = new Map<string, Promise<unknown>>();\n const pending = new Map<string, number>();\n const queued = <T>(key: string, op: () => T | Promise<T>): Promise<T> => {\n pending.set(key, (pending.get(key) ?? 0) + 1);\n const run = (chains.get(key) ?? Promise.resolve()).then(op);\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n chains.set(key, settled);\n void settled.then(() => {\n const left = (pending.get(key) ?? 1) - 1;\n if (left > 0) pending.set(key, left);\n else {\n pending.delete(key);\n if (chains.get(key) === settled) chains.delete(key);\n }\n });\n return run;\n };\n const safe = <T>(p: Promise<T>) => p.catch(() => undefined);\n const readIndex = async (): Promise<Set<string>> => {\n try {\n const value = await raw.getItem(indexKey);\n const list: unknown = value ? JSON.parse(value) : [];\n return new Set(\n Array.isArray(list)\n ? list.filter((k): k is string => typeof k === 'string')\n : [],\n );\n } catch {\n return new Set();\n }\n };\n const listed = new Set<string>();\n const list = (key: string) => {\n if (listed.has(key)) return;\n listed.add(key);\n void safe(\n queued(indexKey, async () => {\n const all = await readIndex();\n if (all.has(key)) return;\n all.add(key);\n await raw.setItem(indexKey, JSON.stringify([...all]));\n }),\n );\n };\n return {\n getItem(key) {\n // A read that finishes after a sign-out answers nothing: the next person never sees the last one's record.\n const asked = generation();\n const read = pending.has(key)\n ? queued(key, () => raw.getItem(key))\n : raw.getItem(key);\n if (typeof read === 'string' || read === null) return read;\n return Promise.resolve(read).then(\n (v) => (asked === generation() ? (v ?? null) : null),\n () => null,\n );\n },\n setItem(key, value) {\n const asked = generation();\n return safe(\n queued(key, () => {\n if (asked !== generation()) return;\n list(key);\n return raw.setItem(key, value);\n }),\n );\n },\n removeItem: (key) => safe(queued(key, () => raw.removeItem(key))),\n /**\n * Everything kept: the index, what the app's storage finds under `under` (`removePrefix`, else `keys`), and `extra`\n * (older key shapes). Nothing under `keep` goes, so `removePrefix` is used only for a prefix that cannot reach it.\n */\n async purge(\n under: readonly string[],\n extra: (keys: ReadonlySet<string>) => Iterable<string> = () => [],\n keep?: string,\n ) {\n const all = new Set([...listed, ...(await readIndex())]);\n listed.clear();\n for (const p of under)\n try {\n if (raw.removePrefix && !keep?.startsWith(p))\n await raw.removePrefix(p);\n else if (raw.keys)\n for (const key of await raw.keys(p))\n if (!keep || !key.startsWith(keep)) all.add(key);\n } catch {\n // storage that cannot list: the index and the known shapes still go\n }\n for (const key of extra(all)) all.add(key);\n await Promise.all(\n [...all].map((key) => safe(queued(key, () => raw.removeItem(key)))),\n );\n await safe(queued(indexKey, () => raw.removeItem(indexKey)));\n },\n };\n}\n\nasync function readStatus(backend: AgentBackend): Promise<AgentStatus> {\n const read: AgentStatusRead = backend.status\n ? await backend.status()\n : { available: true };\n const available = read.available === true;\n const features = read.features ?? NO_FEATURES;\n return {\n available,\n launcher: available && read.launcher === true,\n displayName: read.displayName?.trim() || null,\n avatarUrl: read.avatarUrl?.startsWith('https://') ? read.avatarUrl : null,\n features: {\n history: available && features.history === true,\n memory: available && features.memory === true,\n businessAgent: available && features.businessAgent === true,\n businessSetup: available && features.businessSetup === true,\n },\n };\n}\n\n/**\n * An `AgentRefusal`, also one made by another copy of this package (the mock in `@vinaverse/client/testing`, the\n * backend helpers in `@vinaverse/client/backend`, a second install): recognised by its name and kind, not its class.\n */\nexport function isRefusal(error: unknown): error is AgentRefusal {\n return (\n error instanceof AgentRefusal ||\n (field(error, 'name') === 'AgentRefusal' &&\n (field(error, 'kind') === 'ended' ||\n field(error, 'kind') === 'unavailable'))\n );\n}\n\nconst field = (error: unknown, name: string): unknown =>\n typeof error === 'object' && error !== null\n ? (error as Record<string, unknown>)[name]\n : undefined;\n\nconst retryable = (error: unknown) => field(error, 'retryable') === true;\n\nconst REASONS = new Set<AgentFailureReason>([\n 'ended',\n 'not_found',\n 'expired',\n 'mismatch',\n 'completed',\n 'forbidden',\n 'conflict',\n 'unknown_open',\n 'auth',\n 'off',\n 'rate_limited',\n 'network',\n 'server',\n 'invalid_session',\n 'unknown',\n]);\n\nfunction reasonOf(error: unknown, failure: AgentFailure): AgentFailureReason {\n if (isRefusal(error)) return error.reason;\n const given = field(error, 'reason');\n if (typeof given === 'string' && REASONS.has(given as AgentFailureReason))\n return given as AgentFailureReason;\n const status = field(error, 'status');\n if (status === 401 || status === 403) return 'auth';\n if (status === 429) return 'rate_limited';\n if (typeof status === 'number' && status >= 500) return 'server';\n return failure === 'unreachable' ? 'network' : 'unknown';\n}\n\nfunction codeOf(error: unknown): string | null {\n const code = field(error, 'code') ?? field(error, 'outcome');\n return typeof code === 'string' ? code : null;\n}\n\n/** Tries again after each delay while the policy says so; an outage is said, never answered with a new conversation. */\nasync function retrying<T>(\n run: () => Promise<T>,\n policy: Required<AgentRetryPolicy>,\n signal: AbortSignal | undefined,\n onRetry: (attempt: number) => void,\n): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await run();\n } catch (error) {\n const delay = policy.delays[attempt];\n if (delay === undefined || !policy.isRetryable(error) || signal?.aborted)\n throw error;\n // The server's own wait (`Retry-After`), when longer than the policy's.\n const asked = field(error, 'retryAfterMs');\n const wait =\n typeof asked === 'number' && asked > delay\n ? Math.min(asked, 60_000) // never stalled by a bad `Retry-After`\n : delay;\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', stop);\n resolve();\n }, wait);\n function stop() {\n clearTimeout(timer);\n reject(error);\n }\n signal?.addEventListener('abort', stop, { once: true });\n });\n onRetry(attempt + 1);\n }\n }\n}\n"]}