@vinaverse/client 0.1.0-alpha.6 → 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.
- package/README.md +66 -6
- package/dist/agent/index.cjs +523 -75
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +2 -2
- package/dist/backend/index.cjs +268 -0
- package/dist/backend/index.cjs.map +1 -0
- package/dist/backend/index.d.cts +72 -0
- package/dist/backend/index.d.ts +72 -0
- package/dist/backend/index.js +250 -0
- package/dist/backend/index.js.map +1 -0
- package/dist/chunk-3BLRAWNC.js +840 -0
- package/dist/chunk-3BLRAWNC.js.map +1 -0
- package/dist/{chunk-ZWG2TMUL.js → chunk-46D3FSLU.js} +24 -2
- package/dist/chunk-46D3FSLU.js.map +1 -0
- package/dist/conversation/index.cjs +22 -0
- package/dist/conversation/index.cjs.map +1 -1
- package/dist/conversation/index.d.cts +2 -2
- package/dist/conversation/index.d.ts +2 -2
- package/dist/conversation/index.js +2 -2
- package/dist/{runtime-DLJbJkSr.d.ts → runtime-C3ZknHdG.d.cts} +137 -20
- package/dist/{runtime-CErMdYxJ.d.cts → runtime-CZ1hLvAl.d.ts} +137 -20
- package/dist/{store-C7FtS5AY.d.cts → store-7WU1kD9W.d.cts} +31 -1
- package/dist/{store-DFk0ayh8.d.ts → store-DrXSPHu6.d.ts} +31 -1
- package/dist/testing/index.cjs +38 -1
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +14 -3
- package/dist/testing/index.d.ts +14 -3
- package/dist/testing/index.js +40 -3
- package/dist/testing/index.js.map +1 -1
- package/package.json +21 -2
- package/dist/chunk-XPES5PZ3.js +0 -416
- package/dist/chunk-XPES5PZ3.js.map +0 -1
- package/dist/chunk-ZWG2TMUL.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/runt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,EAAA,OAAO,OAAA,KAAY,gBAAgB,SAAA,GAAY,SAAA;AACjD;AAEA,SAAS,OAAO,KAAA,EAA+B;AAC7C,EAAA,MAAM,IAAA,GAAO,KAAA,CAAM,KAAA,EAAO,MAAM,CAAA;AAChC,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,IAAA;AAC3C;AAGA,eAAe,QAAA,CACb,GAAA,EACA,MAAA,EACA,MAAA,EACA,OAAA,EACY;AACZ,EAAA,KAAA,IAAS,OAAA,GAAU,KAAK,OAAA,EAAA,EAAW;AACjC,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,GAAA,EAAI;AAAA,IACnB,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAA,GAAO,MAAA,CAAO,MAAA,CAAO,OAAO,CAAA;AAClC,MAAA,IAAI,SAAS,MAAA,IAAa,CAAC,OAAO,WAAA,CAAY,KAAK,KAAK,MAAA,EAAQ,OAAA;AAC9D,QAAA,MAAM,KAAA;AACR,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,EAAS,MAAA,KAAW;AAC3C,QAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,UAAA,MAAA,EAAQ,mBAAA,CAAoB,SAAS,IAAI,CAAA;AACzC,UAAA,OAAA,EAAQ;AAAA,QACV,GAAG,IAAI,CAAA;AACP,QAAA,SAAS,IAAA,GAAO;AACd,UAAA,YAAA,CAAa,KAAK,CAAA;AAClB,UAAA,MAAA,CAAO,KAAK,CAAA;AAAA,QACd;AACA,QAAA,MAAA,EAAQ,iBAAiB,OAAA,EAAS,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,MACxD,CAAC,CAAA;AACD,MAAA,OAAA,CAAQ,UAAU,CAAC,CAAA;AAAA,IACrB;AAAA,EACF;AACF","file":"chunk-XPES5PZ3.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 ConversationOptions,\n type ConversationSession,\n type ConversationStore,\n createConversation,\n type SessionRequest,\n} from '../conversation/store.js';\nimport type { Schemas } from '../events.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/** 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 readonly place: AgentPlace | null;\n /** How the person came in (`button`, `inbox`, …): the app's own words, passed through. */\n readonly entryPoint: string | 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 asked for is over: not theirs, deleted (404), or past the time it is kept (410). */\n | 'ended'\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 /** A fresh client secret for the same session (before its end). */\n refreshSecret?(sessionId: string): Promise<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`). Absent, or refused, the kit offers a question about the new place instead.\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}\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\n/** For the app's analytics: what happened, for which conversation, with nothing the person said. */\nexport interface AgentEvent {\n readonly type: AgentEventType;\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 (`entryPoint`, the screen). */\n readonly from?: string;\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\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?: string | null;\n }): () => void;\n /** The place and the way in changed while a view is attached: told live where the backend can, else on the next session. */\n tell(open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: string | 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 /** A thumbs on a whole reply; 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 /** 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 /** 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 /** Closes the key's conversation now and drops every reference to it; the next opening continues it in a new session. */\n dispose(key: AgentKey): void;\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 /** Every conversation closed and forgotten (what the device kept too), and the backend told to end the sessions. */\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\nconst NOT_KEPT = new Set(['starting', 'unavailable', 'unauthorized', 'closed']);\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/** The key as a string: one conversation per person, mode, business and thread. */\nexport function agentKey(key: AgentKey): string {\n return `${key.subject ?? 'guest'}|${key.mode}|${key.scope ?? '-'}|${key.thread ?? 'chat'}`;\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. It is for mocks and local development only; remove it from release builds.',\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}\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\n const emit = (event: AgentEvent) => options.onEvent?.(event);\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 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 const told = entry.place;\n // The runtime keeps which conversation the key continues: the app's adapter is a plain call.\n const conversationId =\n request.conversationId ?? current.get(entry.key) ?? null;\n let session: ConversationSession;\n try {\n session = await patiently(\n () =>\n backend.openSession({\n ...request,\n conversationId,\n key,\n place: told,\n entryPoint: entry.entryPoint,\n }),\n request.signal,\n entry.key,\n );\n if (!usable(session, insecure))\n throw new AgentRefusal('unavailable', {\n reason: 'invalid_session',\n message:\n 'The session is not usable (an id, a secret, a wss:// realtime_url and an https:// turns_url).',\n });\n } catch (error) {\n if (live.get(entry.key) === entry) {\n const failure: AgentFailure =\n error instanceof AgentRefusal\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 = error instanceof AgentRefusal ? error.code : codeOf(error);\n update(entry, { failure, reason, code });\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 sessionId: session.id,\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) =>\n `${options.conversation?.persistenceKey ?? 'vinaverse.agent'}.${k}`;\n\n function make(key: AgentKey): Entry {\n const k = agentKey(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 ...(own.persistence\n ? {\n persistenceKey: kept(k),\n }\n : {}),\n getSession: (request) => open(entry, key, request),\n ...(refresh\n ? {\n refreshSecret: (id: string) =>\n patiently(() => refresh(id), undefined, k),\n }\n : {}),\n clock,\n onError: (error) => {\n // A refusal is said through the state, never reported as a fault.\n if (!(error instanceof AgentRefusal)) 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 },\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 };\n return entry;\n }\n\n const over = (entry: Entry) =>\n entry.expiresAt !== null && entry.expiresAt <= clock.now();\n\n /** The new place: told live when the backend can (the session then knows it), else `moved` until the next session. */\n const tell = (\n entry: Entry,\n at: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: string | null;\n },\n ) => {\n entry.place = at.place ?? null;\n entry.entryPoint = at.entryPoint ?? null;\n const sessionId = entry.state.sessionId;\n const moved = sessionId !== null && !samePlace(entry.told, entry.place);\n update(entry, { moved });\n const place = entry.place;\n if (!moved || !place || !backend.updateContext || sessionId === null)\n return;\n const revision = ++entry.revision;\n backend.updateContext(sessionId, place, revision).then(\n () => {\n if (live.get(entry.key) !== entry || entry.revision !== revision)\n 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 () => undefined, // not served, or refused: the question about this place stays the way to say it\n );\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 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 };\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, { failure: null, reason: null, code: null });\n entry.store.start();\n },\n rate(turnId, rating) {\n const sessionId = entry.state.sessionId;\n if (sessionId === null || entry.state.ratings.get(turnId) === rating)\n 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 = agentKey(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 = agentKey(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 = agentKey(key);\n current.delete(k);\n end(k);\n },\n dispose(key) {\n end(agentKey(key));\n },\n continue(key, conversationId) {\n const k = agentKey(key);\n if (current.get(k) !== conversationId) {\n current.set(k, conversationId);\n // What the device kept is another conversation's: forgotten, so the resumed transcript is the only one drawn.\n const entry = live.get(k);\n if (entry) {\n entry.store.clear();\n end(k);\n } else {\n try {\n void Promise.resolve(\n options.conversation?.persistence?.removeItem(kept(k)),\n ).catch(() => undefined);\n } catch {\n // storage blocked: the transcript the session brings still merges by id\n }\n }\n }\n return lookup(key);\n },\n async signOut() {\n for (const entry of live.values()) entry.store.clear();\n live.clear();\n current.clear();\n sessionName = null;\n changed();\n await backend.endSessions?.().catch(() => undefined);\n },\n status() {\n if (status && clock.now() - status.at < staleMs)\n return Promise.resolve(status.value);\n reading ??= readStatus(backend).then(\n (value) => {\n reading = null;\n status = { value, at: clock.now() };\n changed();\n return value;\n },\n (error: unknown) => {\n reading = null;\n throw error;\n },\n );\n return reading;\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\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\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 '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 (error instanceof AgentRefusal) 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');\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 wait = policy.delays[attempt];\n if (wait === undefined || !policy.isRetryable(error) || signal?.aborted)\n throw error;\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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/conversation/links.ts","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F,EAAE,OAAA,KAAY,CAAA,CAAE,CAAC,CAAA,EAAG,OAAA,IACpB,EAAE,KAAA,KAAU,CAAA,CAAE,CAAC,CAAA,EAAG,KAAA,IAClB,EAAE,KAAA,KAAU,CAAA,CAAE,CAAC,CAAA,EAAG;AAAA,GACtB;AAEJ;AAEA,SAAS,YAAA,CAAa,GAAqB,CAAA,EAA8B;AACvE,EAAA,OACE,CAAA,CAAE,MAAA,KAAW,CAAA,CAAE,MAAA,IACf,EAAE,MAAA,KAAW,CAAA,CAAE,MAAA,IACf,CAAA,CAAE,SAAS,CAAA,CAAE,IAAA,IACb,CAAA,CAAE,KAAA,CAAM,SAAS,CAAA,CAAE,KAAA,CAAM,IAAA,IACzB,CAAA,CAAE,KAAA,CAAM,SAAA,KAAc,CAAA,CAAE,KAAA,CAAM,aAC9B,CAAA,CAAE,UAAA,KAAe,CAAA,CAAE,UAAA,IACnB,EAAE,QAAA,EAAU,EAAA,KAAO,CAAA,CAAE,QAAA,EAAU,MAC/B,CAAA,CAAE,QAAA,EAAU,EAAA,KAAO,CAAA,CAAE,QAAA,EAAU,EAAA,IAC9B,CAAA,CAAE,QAAA,KAAa,UAAW,CAAA,CAAE,QAAA,KAAa,IAAA,CAAA,IAC1C,CAAA,CAAE,UAAU,CAAA,CAAE,KAAA,IACd,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-ZWG2TMUL.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\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\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 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 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 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"]}
|