@vinaverse/client 0.1.0-alpha.5 → 0.1.0-alpha.7

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 (35) hide show
  1. package/README.md +67 -7
  2. package/dist/agent/index.cjs +526 -78
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +2 -2
  5. package/dist/agent/index.d.ts +2 -2
  6. package/dist/agent/index.js +2 -2
  7. package/dist/backend/index.cjs +268 -0
  8. package/dist/backend/index.cjs.map +1 -0
  9. package/dist/backend/index.d.cts +72 -0
  10. package/dist/backend/index.d.ts +72 -0
  11. package/dist/backend/index.js +250 -0
  12. package/dist/backend/index.js.map +1 -0
  13. package/dist/chunk-3BLRAWNC.js +840 -0
  14. package/dist/chunk-3BLRAWNC.js.map +1 -0
  15. package/dist/{chunk-ZWG2TMUL.js → chunk-46D3FSLU.js} +24 -2
  16. package/dist/chunk-46D3FSLU.js.map +1 -0
  17. package/dist/conversation/index.cjs +22 -0
  18. package/dist/conversation/index.cjs.map +1 -1
  19. package/dist/conversation/index.d.cts +2 -2
  20. package/dist/conversation/index.d.ts +2 -2
  21. package/dist/conversation/index.js +2 -2
  22. package/dist/{runtime-DDxwWBBr.d.cts → runtime-C3ZknHdG.d.cts} +139 -20
  23. package/dist/{runtime-B4nKwOTF.d.ts → runtime-CZ1hLvAl.d.ts} +139 -20
  24. package/dist/{store-C7FtS5AY.d.cts → store-7WU1kD9W.d.cts} +31 -1
  25. package/dist/{store-DFk0ayh8.d.ts → store-DrXSPHu6.d.ts} +31 -1
  26. package/dist/testing/index.cjs +38 -1
  27. package/dist/testing/index.cjs.map +1 -1
  28. package/dist/testing/index.d.cts +14 -3
  29. package/dist/testing/index.d.ts +14 -3
  30. package/dist/testing/index.js +40 -3
  31. package/dist/testing/index.js.map +1 -1
  32. package/package.json +21 -2
  33. package/dist/chunk-3WR2SUG2.js +0 -416
  34. package/dist/chunk-3WR2SUG2.js.map +0 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EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,MACxD,CAAC,CAAA;AACD,MAAA,OAAA,CAAQ,UAAU,CAAC,CAAA;AAAA,IACrB;AAAA,EACF;AACF","file":"chunk-3BLRAWNC.js","sourcesContent":["// 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 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\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) => void;\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 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 /** 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) => 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 );\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) => 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 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 = 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: string, 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 );\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 );\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 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 changed();\n return value;\n },\n (error: unknown) => {\n if (asked === generation) reading = null;\n throw error;\n },\n );\n reading = read;\n return read;\n },\n getStatus: () => status?.value ?? null,\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"]}
@@ -353,6 +353,7 @@ var ConversationStore = class {
353
353
  throw new RangeError(`A message is at most ${MAX_TEXT} characters.`);
354
354
  const id = (this.options.createId ?? randomId)();
355
355
  this.sent.set(id, { text, order: lastOrder(this.engine.state()) + 0.5 });
356
+ this.tellActivity({ type: "message_sent", id });
356
357
  if (!this.session) {
357
358
  this.early.set(id, text);
358
359
  void this.ensureSession("open");
@@ -600,9 +601,30 @@ var ConversationStore = class {
600
601
  this.lastStatus = status;
601
602
  this.update();
602
603
  }
604
+ /** The app's analytics hears of a step; what it throws is reported (`onError`), never in the way of a send or a frame. */
605
+ tellActivity(activity) {
606
+ try {
607
+ this.options.onActivity?.(activity);
608
+ } catch (error) {
609
+ this.options.onError?.(error);
610
+ }
611
+ }
612
+ /** The live frames analytics hears of: a reply finished, cards drawn. */
613
+ activity(frame) {
614
+ if (!this.options.onActivity) return;
615
+ const on = (a) => this.tellActivity(a);
616
+ if (frame.type === "message.completed" && typeof frame.turn_id === "string")
617
+ on({ type: "reply_completed", turnId: frame.turn_id });
618
+ if (frame.type === "ui.cards" && Array.isArray(frame.cards)) {
619
+ for (const card of frame.cards)
620
+ if (typeof card.id === "string" && typeof card.kind === "string")
621
+ on({ type: "card_shown", cardId: card.id, kind: card.kind });
622
+ }
623
+ }
603
624
  event(event) {
604
625
  const frame = event;
605
626
  const str = (v) => typeof v === "string" ? v : null;
627
+ this.activity(frame);
606
628
  const add = (key, kind, data) => {
607
629
  if (this.system.some((s) => s.item.key === key)) return;
608
630
  this.system = [
@@ -971,5 +993,5 @@ function shallowEqual(a, b) {
971
993
  }
972
994
 
973
995
  export { ConversationStore, MAX_TEXT, createConversation, isAllowedLink, isValidLinkPrefix };
974
- //# sourceMappingURL=chunk-ZWG2TMUL.js.map
975
- //# sourceMappingURL=chunk-ZWG2TMUL.js.map
996
+ //# sourceMappingURL=chunk-46D3FSLU.js.map
997
+ //# sourceMappingURL=chunk-46D3FSLU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation/links.ts","../src/conversation/timeline.ts","../src/conversation/store.ts"],"names":[],"mappings":";;;AAKA,IAAM,MAAA,GACJ,mOAAA;AACF,IAAM,YAAA,GACJ,sKAAA;AACF,IAAM,eAAA,GACJ,mIAAA;AAEF,IAAM,QAAA,GAAW,iBAAA;AACjB,IAAM,SAAA,GACJ,wLAAA;AAGK,SAAS,kBAAkB,MAAA,EAAyB;AACzD,EAAA,IAAI,QAAA,CAAS,KAAK,MAAM,CAAA,IAAK,gBAAgB,IAAA,CAAK,MAAM,GAAG,OAAO,KAAA;AAClE,EAAA,IAAI,UAAA,CAAW,KAAK,MAAM,CAAA,IAAK,CAAC,YAAA,CAAa,IAAA,CAAK,MAAM,CAAA,EAAG,OAAO,KAAA;AAClE,EAAA,OAAO,MAAA,CAAO,KAAK,MAAM,CAAA;AAC3B;AAOO,SAAS,aAAA,CACd,MACA,QAAA,EACS;AACT,EAAA,OAAO,QAAA,CAAS,IAAA;AAAA,IACd,CAAC,MAAA,KACC,iBAAA,CAAkB,MAAM,KACxB,IAAA,CAAK,UAAA,CAAW,MAAM,CAAA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CAAA,CAAE,QAAA,KAAa,EAAE,QAAA,IACjB,CAAA,CAAE,UAAA,KAAe,CAAA,CAAE,UAAA,IACnB,CAAA,CAAE,YAAA,KAAiB,CAAA,CAAE,gBACrB,CAAA,CAAE,oBAAA,KAAyB,CAAA,CAAE,oBAAA,IAC7B,EAAE,SAAA,KAAc,CAAA,CAAE,SAAA,IAClB,CAAA,CAAE,YAAY,CAAA,CAAE,OAAA;AAEpB","file":"chunk-46D3FSLU.js","sourcesContent":["// 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"]}
@@ -1820,6 +1820,7 @@ var ConversationStore = class {
1820
1820
  throw new RangeError(`A message is at most ${MAX_TEXT} characters.`);
1821
1821
  const id = (this.options.createId ?? randomId)();
1822
1822
  this.sent.set(id, { text, order: lastOrder(this.engine.state()) + 0.5 });
1823
+ this.tellActivity({ type: "message_sent", id });
1823
1824
  if (!this.session) {
1824
1825
  this.early.set(id, text);
1825
1826
  void this.ensureSession("open");
@@ -2067,9 +2068,30 @@ var ConversationStore = class {
2067
2068
  this.lastStatus = status;
2068
2069
  this.update();
2069
2070
  }
2071
+ /** The app's analytics hears of a step; what it throws is reported (`onError`), never in the way of a send or a frame. */
2072
+ tellActivity(activity) {
2073
+ try {
2074
+ this.options.onActivity?.(activity);
2075
+ } catch (error) {
2076
+ this.options.onError?.(error);
2077
+ }
2078
+ }
2079
+ /** The live frames analytics hears of: a reply finished, cards drawn. */
2080
+ activity(frame) {
2081
+ if (!this.options.onActivity) return;
2082
+ const on = (a) => this.tellActivity(a);
2083
+ if (frame.type === "message.completed" && typeof frame.turn_id === "string")
2084
+ on({ type: "reply_completed", turnId: frame.turn_id });
2085
+ if (frame.type === "ui.cards" && Array.isArray(frame.cards)) {
2086
+ for (const card of frame.cards)
2087
+ if (typeof card.id === "string" && typeof card.kind === "string")
2088
+ on({ type: "card_shown", cardId: card.id, kind: card.kind });
2089
+ }
2090
+ }
2070
2091
  event(event) {
2071
2092
  const frame = event;
2072
2093
  const str2 = (v) => typeof v === "string" ? v : null;
2094
+ this.activity(frame);
2073
2095
  const add = (key, kind, data) => {
2074
2096
  if (this.system.some((s) => s.item.key === key)) return;
2075
2097
  this.system = [