@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 -1
  35. package/dist/chunk-ZWG2TMUL.js.map +0 -1
@@ -179,6 +179,15 @@ interface ConversationPersistence {
179
179
  getItem(key: string): string | null | Promise<string | null>;
180
180
  setItem(key: string, value: string): void | Promise<void>;
181
181
  removeItem(key: string): void | Promise<void>;
182
+ /**
183
+ * Optional: the keys under a prefix. With it (or `removePrefix`), a sign-out and an erasure are guaranteed to find every
184
+ * key kept, ones no index lists too (an earlier version's, a write lost with its process); without either, only the
185
+ * keys this version indexed and the shapes it can derive from them. AsyncStorage and MMKV: `getAllKeys()` filtered
186
+ * by the prefix; web `localStorage`: `Object.keys(localStorage)` filtered.
187
+ */
188
+ keys?(prefix: string): readonly string[] | Promise<readonly string[]>;
189
+ /** Optional: removes every key under a prefix at once (used instead of `keys` where it cannot reach a kept record). */
190
+ removePrefix?(prefix: string): void | Promise<void>;
182
191
  }
183
192
  interface ConversationOptions {
184
193
  /**
@@ -217,7 +226,24 @@ interface ConversationOptions {
217
226
  readonly clock?: {
218
227
  now(): number;
219
228
  };
229
+ /**
230
+ * What the person and the agent did live, for analytics (never what a transcript or the device brought back): the
231
+ * person sent a text, a reply finished, a card was drawn. Carries no text.
232
+ */
233
+ readonly onActivity?: (activity: ConversationActivity) => void;
220
234
  }
235
+ /** One live step of the conversation, without its words. */
236
+ type ConversationActivity = {
237
+ readonly type: 'message_sent';
238
+ readonly id: string;
239
+ } | {
240
+ readonly type: 'reply_completed';
241
+ readonly turnId: string;
242
+ } | {
243
+ readonly type: 'card_shown';
244
+ readonly cardId: string;
245
+ readonly kind: string;
246
+ };
221
247
  /** A text is at most 2000 code points (`TurnInput`). */
222
248
  declare const MAX_TEXT = 2000;
223
249
  declare class ConversationStore {
@@ -346,6 +372,10 @@ declare class ConversationStore {
346
372
  /** A refusal already led to a new session, and none has been ready since: another refusal is no cue. */
347
373
  private rolled;
348
374
  private statusChanged;
375
+ /** The app's analytics hears of a step; what it throws is reported (`onError`), never in the way of a send or a frame. */
376
+ private tellActivity;
377
+ /** The live frames analytics hears of: a reply finished, cards drawn. */
378
+ private activity;
349
379
  private event;
350
380
  /** The person's text that started a turn, while its message is on screen. */
351
381
  private turnText;
@@ -381,4 +411,4 @@ declare class ConversationStore {
381
411
  /** One conversation with an agent, for any UI: see `ConversationStore`. */
382
412
  declare function createConversation(options: ConversationOptions): ConversationStore;
383
413
 
384
- export { ConversationStore as C, type FrameScheduler as F, MAX_TEXT as M, type SessionRequest as S, type TimelineItem as T, type ConversationOptions as a, type ConversationSession as b, type CardItem as c, type ConversationBanner as d, type ConversationPersistence as e, type ConversationStatus as f, type ConversationView as g, type MessageItem as h, type MessageState as i, type SessionReason as j, type StreamingText as k, type SystemEvent as l, type SystemItem as m, createConversation as n };
414
+ export { ConversationStore as C, type FrameScheduler as F, MAX_TEXT as M, type SessionRequest as S, type TimelineItem as T, type ConversationOptions as a, type ConversationSession as b, type CardItem as c, type ConversationActivity as d, type ConversationBanner as e, type ConversationPersistence as f, type ConversationStatus as g, type ConversationView as h, type MessageItem as i, type MessageState as j, type SessionReason as k, type StreamingText as l, type SystemEvent as m, type SystemItem as n, createConversation as o };
@@ -106,7 +106,7 @@ function createMockAgent(options = {}) {
106
106
  turn++;
107
107
  const turnId = `turn_MOCK${turn}`;
108
108
  said.push({ role: "person", text, id });
109
- const answer = options.reply?.(text, { turn, key: held?.key ?? "" }) ?? `You said: ${text}`;
109
+ const answer = options.script?.[turn - 1] ?? options.reply?.(text, { turn, key: held?.key ?? "" }) ?? `You said: ${text}`;
110
110
  const reply = typeof answer === "string" ? { text: answer } : answer;
111
111
  deliver({ type: "turn.started", turn_id: turnId, client_event_id: id });
112
112
  if (reply.fail) {
@@ -208,6 +208,43 @@ var mockCards = {
208
208
  ...extra
209
209
  };
210
210
  },
211
+ /** A proposal the person confirms in the app (`confirm_mode: tenant_app`), pending for a day unless `expires_at`. */
212
+ proposal(id, proposal = {}) {
213
+ const title = proposal.title ?? "Silk press with Riley";
214
+ return {
215
+ id,
216
+ kind: "proposal",
217
+ title,
218
+ actions: [],
219
+ source: { tool: "create_proposal", call_id: "call_MOCK" },
220
+ proposal: {
221
+ id: `prp_${id}`,
222
+ status: "pending",
223
+ topic: proposal.topic ?? "booking",
224
+ title,
225
+ summary: proposal.summary ?? "Wednesday at 10:00 \xB7 $45",
226
+ fields: [],
227
+ expires_at: proposal.expires_at ?? new Date(Date.now() + 24 * 36e5).toISOString(),
228
+ confirm_mode: "tenant_app"
229
+ }
230
+ };
231
+ },
232
+ /** Times to book, from `start` on the hour, one an hour. */
233
+ timeSlots(id, start, count = 3) {
234
+ const at = Date.parse(start);
235
+ return {
236
+ id,
237
+ kind: "time_slots",
238
+ title: "Open times",
239
+ slots: Array.from({ length: count }, (_, i) => ({
240
+ id: `slot_${i + 1}`,
241
+ start: new Date(at + i * 36e5).toISOString(),
242
+ end: new Date(at + (i + 1) * 36e5).toISOString()
243
+ })),
244
+ actions: [],
245
+ source: { tool: "get_availability", call_id: "call_MOCK" }
246
+ };
247
+ },
211
248
  links(id) {
212
249
  return {
213
250
  id,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/agent/runtime.ts","../../src/testing/index.ts"],"names":[],"mappings":";;;AAmEO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CACW,IAAA,EACT,OAAA,GAII,EAAC,EACL;AACA,IAAA,KAAA;AAAA,MACE,OAAA,CAAQ,OAAA,KACL,IAAA,KAAS,OAAA,GAAU,2BAAA,GAA8B,eAAA;AAAA,KACtD;AAVS,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAWT,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,OAAA,CAAQ,MAAA,KAAW,IAAA,KAAS,UAAU,OAAA,GAAU,SAAA,CAAA;AAC9D,IAAA,IAAA,CAAK,IAAA,GAAO,QAAQ,IAAA,IAAQ,IAAA;AAAA,EAC9B;AAAA,EAdW,IAAA;AAAA,EAHF,MAAA;AAAA,EACA,I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OAAA,EAAS;AAAA;AACX,OACF;AAAA,MACA,SAAS,EAAC;AAAA,MACV,MAAA,EAAQ,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,WAAA;AAAY,KAChD;AAAA,EACF;AACF","file":"index.cjs","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}\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(insecure: AgentInsecureAddresses): void {\n if (!(insecure.realtime || insecure.turns)) return;\n if ((globalThis as { __DEV__?: boolean }).__DEV__ === true) return;\n console.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);\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","// @vinaverse/client/testing: a scripted agent for an app's mock mode and tests, with no tenant and no network. It is an\n// `AgentBackend` (sessions, fresh secrets, status, feedback) and a WebSocket factory that speaks the realtime protocol:\n// session.ready (resumed with the conversation's transcript), replies streamed sentence by sentence, cards, a turn that\n// fails, refusals when opening (ended, unreachable, unavailable). The app scripts only its own answers.\nimport type {\n AgentBackend,\n AgentSessionRequest,\n AgentStatusRead,\n} from '../agent/runtime.js';\nimport { AgentRefusal } from '../agent/runtime.js';\nimport type { ConversationSession } from '../conversation/store.js';\nimport type { Card, Welcome } from '../events.js';\nimport type { WebSocketFactory, WebSocketLike } from '../session.js';\n\n/** One reply of the scripted agent. */\nexport interface MockReply {\n readonly text?: string;\n readonly cards?: readonly Card[];\n /** The turn fails before any text, with this code (`internal`, `timeout`, …). */\n readonly fail?: string;\n}\n\nexport interface MockAgentOptions {\n /** The agent's answer to the person's text. Default: an echo. */\n readonly reply?: (\n text: string,\n context: { readonly turn: number; readonly key: string },\n ) => MockReply | string;\n readonly agentName?: string;\n readonly disclosure?: string;\n readonly welcome?: Welcome;\n /** A refusal when opening a session (the scripted backend's answer), by request. */\n readonly refuse?: (\n request: AgentSessionRequest,\n attempt: number,\n ) => 'ended' | 'unreachable' | 'unavailable' | undefined;\n /** How long a session lives. Default 30 minutes. */\n readonly sessionMs?: number;\n readonly status?: AgentStatusRead;\n /** The clock sessions are dated by; default the device's. */\n readonly now?: () => number;\n}\n\nexport interface MockAgent {\n readonly backend: AgentBackend;\n /** The store's transport: `conversation.transport.webSocket`. */\n readonly webSocket: WebSocketFactory;\n /** What the app sent: feedback, sessions asked for, places told. */\n readonly log: {\n readonly sessions: AgentSessionRequest[];\n readonly feedback: unknown[];\n readonly contexts: unknown[];\n readonly ended: number;\n };\n}\n\ninterface Said {\n readonly role: 'person' | 'assistant';\n readonly text: string;\n readonly id: string;\n}\n\nconst sentences = (text: string) => text.match(/[^.!?]+[.!?]*\\s*/g) ?? [text];\n\nexport function createMockAgent(options: MockAgentOptions = {}): MockAgent {\n const now = options.now ?? (() => Date.now());\n const conversations = new Map<string, Said[]>();\n const sessions = new Map<string, { conversation: string; key: string }>();\n const log = {\n sessions: [] as AgentSessionRequest[],\n feedback: [] as unknown[],\n contexts: [] as unknown[],\n ended: 0,\n };\n let attempts = 0;\n let count = 0;\n\n const backend: AgentBackend = {\n async openSession(request) {\n log.sessions.push(request);\n attempts++;\n const refusal = options.refuse?.(request, attempts);\n if (refusal === 'unreachable')\n throw Object.assign(new Error('mock: unreachable'), {\n retryable: true,\n reason: 'network',\n });\n if (refusal) throw new AgentRefusal(refusal);\n if (\n request.conversationId !== null &&\n !conversations.has(request.conversationId)\n )\n throw new AgentRefusal('ended', { code: 'conversation_not_found' });\n count++;\n const conversation = request.conversationId ?? `cnv_MOCK${count}`;\n if (!conversations.has(conversation)) conversations.set(conversation, []);\n const id = `ses_MOCK${count}`;\n sessions.set(id, { conversation, key: `${request.key.mode}` });\n const session: ConversationSession = {\n id,\n realtime_url: `wss://mock.vinaverse.invalid/v1/sessions/${id}/realtime`,\n turns_url: `https://mock.vinaverse.invalid/v1/sessions/${id}/turns`,\n client_secret: `vv_cs_${'mock'.repeat(6)}`,\n conversation_id: conversation,\n expires_at: new Date(\n now() + (options.sessionMs ?? 30 * 60_000),\n ).toISOString(),\n ...(options.agentName\n ? { agent: { display_name: options.agentName } }\n : {}),\n ...(options.disclosure ? { disclosure: options.disclosure } : {}),\n ...(options.welcome ? { welcome: options.welcome } : {}),\n };\n return session;\n },\n async refreshSecret() {\n return `vv_cs_${'mock'.repeat(6)}`;\n },\n async updateContext(sessionId, place, revision) {\n log.contexts.push({ sessionId, place, revision });\n },\n async status() {\n return (\n options.status ?? {\n available: true,\n launcher: true,\n displayName: options.agentName ?? null,\n }\n );\n },\n async sendFeedback(feedback) {\n log.feedback.push(feedback);\n },\n async endSessions() {\n log.ended++;\n },\n };\n\n const webSocket: WebSocketFactory = (url) => {\n const sessionId = /sessions\\/([^/]+)\\/realtime/.exec(url)?.[1] ?? '';\n const held = sessions.get(sessionId);\n const said = held ? (conversations.get(held.conversation) ?? []) : [];\n let turn = said.filter((s) => s.role === 'person').length;\n let state = 0;\n const socket: WebSocketLike = {\n get readyState() {\n return state;\n },\n onopen: null,\n onmessage: null,\n onclose: null,\n onerror: null,\n send(data) {\n const frame = JSON.parse(data) as Record<string, unknown>;\n if (frame.type === 'ping') return deliver({ type: 'pong' });\n if (frame.type !== 'input.text') return;\n const id = String(frame.client_event_id ?? '');\n const text = String(frame.text ?? '');\n turn++;\n const turnId = `turn_MOCK${turn}`;\n said.push({ role: 'person', text, id });\n const answer =\n options.reply?.(text, { turn, key: held?.key ?? '' }) ??\n `You said: ${text}`;\n const reply: MockReply =\n typeof answer === 'string' ? { text: answer } : answer;\n deliver({ type: 'turn.started', turn_id: turnId, client_event_id: id });\n if (reply.fail) {\n deliver({\n type: 'turn.failed',\n turn_id: turnId,\n code: reply.fail,\n message: '',\n retryable: true,\n });\n return;\n }\n let so = '';\n for (const part of reply.text ? sentences(reply.text) : []) {\n so += part;\n deliver({ type: 'message.delta', turn_id: turnId, text: part });\n }\n if (reply.text) {\n deliver({\n type: 'message.completed',\n turn_id: turnId,\n text: so.trim(),\n });\n said.push({ role: 'assistant', text: so.trim(), id: turnId });\n }\n if (reply.cards?.length)\n deliver({ type: 'ui.cards', turn_id: turnId, cards: reply.cards });\n deliver({ type: 'turn.completed', turn_id: turnId });\n },\n close(code) {\n if (state === 3) return;\n state = 3;\n setTimeout(() => socket.onclose?.({ code: code ?? 1000 }), 0);\n },\n };\n function deliver(event: unknown) {\n setTimeout(() => {\n if (state === 1) socket.onmessage?.({ data: JSON.stringify(event) });\n }, 0);\n }\n setTimeout(() => {\n state = 1;\n socket.onopen?.({});\n const resumed = said.length > 0;\n socket.onmessage?.({\n data: JSON.stringify({\n type: 'session.ready',\n session: { id: sessionId, status: 'open' },\n resumed,\n limits: {},\n disclosure:\n options.disclosure ?? 'An AI agent. Powered by Vinaverse.',\n ...(resumed\n ? {\n transcript: said.map((s) => ({\n role: s.role,\n text: s.text,\n id: s.id,\n at: new Date(now()).toISOString(),\n })),\n }\n : {}),\n }),\n });\n }, 0);\n return socket;\n };\n\n return { backend, webSocket, log };\n}\n\n/** Cards as a tenant's tools would give them, for mock replies and tests. */\nexport const mockCards = {\n professional(id: string, extra: Partial<Card> = {}): Card {\n return {\n id,\n kind: 'professional',\n title: 'Riley Sample',\n subtitle: 'Barber · Los Angeles',\n ref: { type: 'professional', id },\n images: [\n {\n url: `https://images.example.test/${id}.webp`,\n width: 1600,\n height: 1000,\n },\n ],\n rating: { value_ppm: 4_800_000, count: 132 },\n price_from: { amount: 4500, currency: 'USD' },\n actions: [],\n source: { tool: 'search_professionals', call_id: 'call_MOCK' },\n ...extra,\n } as Card;\n },\n workspace(id: string, extra: Partial<Card> = {}): Card {\n return {\n id,\n kind: 'workspace',\n title: 'Suite 4',\n subtitle: 'Private suite · Atlanta',\n ref: { type: 'workspace', id },\n price_from: { amount: 6500, currency: 'USD' },\n actions: [],\n source: { tool: 'search_spaces', call_id: 'call_MOCK' },\n ...extra,\n } as Card;\n },\n links(id: string): Card {\n return {\n id,\n kind: 'links',\n title: 'Pages that can help',\n links: [\n {\n label: 'Help center',\n url: 'https://help.example.test/',\n purpose: 'help',\n },\n {\n label: 'Contact us',\n url: 'https://help.example.test/contact',\n purpose: 'contact',\n },\n ],\n actions: [],\n source: { tool: 'scope', call_id: 'turn_MOCK' },\n } as Card;\n },\n};\n"]}
1
+ {"version":3,"sources":["../../src/agent/runtime.ts","../../src/testing/index.ts"],"names":[],"mappings":";;;AA0GO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CACW,IAAA,EACT,OAAA,GAII,EAAC,EACL;AACA,IAAA,KAAA;AAAA,MACE,OAAA,CAAQ,OAAA,KACL,IAAA,KAAS,OAAA,GAAU,2BAAA,GAA8B,eAAA;AAAA,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AAY;AAAA,QAChD,GAAA,EAAK,IAAI,IAAA,CAAK,EAAA,GAAA,CAAM,IAAI,CAAA,IAAK,IAAS,EAAE,WAAA;AAAY,OACtD,CAAE,CAAA;AAAA,MACF,SAAS,EAAC;AAAA,MACV,MAAA,EAAQ,EAAE,IAAA,EAAM,kBAAA,EAAoB,SAAS,WAAA;AAAY,KAC3D;AAAA,EACF,CAAA;AAAA,EACA,MAAM,EAAA,EAAkB;AACtB,IAAA,OAAO;AAAA,MACL,EAAA;AAAA,MACA,IAAA,EAAM,OAAA;AAAA,MACN,KAAA,EAAO,qBAAA;AAAA,MACP,KAAA,EAAO;AAAA,QACL;AAAA,UACE,KAAA,EAAO,aAAA;AAAA,UACP,GAAA,EAAK,4BAAA;AAAA,UACL,OAAA,EAAS;AAAA,SACX;AAAA,QACA;AAAA,UACE,KAAA,EAAO,YAAA;AAAA,UACP,GAAA,EAAK,mCAAA;AAAA,UACL,OAAA,EAAS;AAAA;AACX,OACF;AAAA,MACA,SAAS,EAAC;AAAA,MACV,MAAA,EAAQ,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,WAAA;AAAY,KAChD;AAAA,EACF;AACF","file":"index.cjs","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","// @vinaverse/client/testing: a scripted agent for an app's mock mode and tests, with no tenant and no network. It is an\n// `AgentBackend` (sessions, fresh secrets, status, feedback) and a WebSocket factory that speaks the realtime protocol:\n// session.ready (resumed with the conversation's transcript), replies streamed sentence by sentence, cards, a turn that\n// fails, refusals when opening (ended, unreachable, unavailable). The app scripts only its own answers.\nimport type {\n AgentBackend,\n AgentSessionRequest,\n AgentStatusRead,\n} from '../agent/runtime.js';\nimport { AgentRefusal } from '../agent/runtime.js';\nimport type { ConversationSession } from '../conversation/store.js';\nimport type { Card, Welcome } from '../events.js';\nimport type { WebSocketFactory, WebSocketLike } from '../session.js';\n\n/** One reply of the scripted agent. */\nexport interface MockReply {\n readonly text?: string;\n readonly cards?: readonly Card[];\n /** The turn fails before any text, with this code (`internal`, `timeout`, …). */\n readonly fail?: string;\n}\n\nexport interface MockAgentOptions {\n /** Replies in order, one per turn (text, cards, a failure), after which `reply` (or the echo) answers. */\n readonly script?: readonly (MockReply | string)[];\n /** The agent's answer to the person's text. Default: the `script`, then an echo. */\n readonly reply?: (\n text: string,\n context: { readonly turn: number; readonly key: string },\n ) => MockReply | string;\n readonly agentName?: string;\n readonly disclosure?: string;\n readonly welcome?: Welcome;\n /** A refusal when opening a session (the scripted backend's answer), by request. */\n readonly refuse?: (\n request: AgentSessionRequest,\n attempt: number,\n ) => 'ended' | 'unreachable' | 'unavailable' | undefined;\n /** How long a session lives. Default 30 minutes. */\n readonly sessionMs?: number;\n readonly status?: AgentStatusRead;\n /** The clock sessions are dated by; default the device's. */\n readonly now?: () => number;\n}\n\nexport interface MockAgent {\n readonly backend: AgentBackend;\n /** The store's transport: `conversation.transport.webSocket`. */\n readonly webSocket: WebSocketFactory;\n /** What the app sent: feedback, sessions asked for, places told. */\n readonly log: {\n readonly sessions: AgentSessionRequest[];\n readonly feedback: unknown[];\n readonly contexts: unknown[];\n readonly ended: number;\n };\n}\n\ninterface Said {\n readonly role: 'person' | 'assistant';\n readonly text: string;\n readonly id: string;\n}\n\nconst sentences = (text: string) => text.match(/[^.!?]+[.!?]*\\s*/g) ?? [text];\n\nexport function createMockAgent(options: MockAgentOptions = {}): MockAgent {\n const now = options.now ?? (() => Date.now());\n const conversations = new Map<string, Said[]>();\n const sessions = new Map<string, { conversation: string; key: string }>();\n const log = {\n sessions: [] as AgentSessionRequest[],\n feedback: [] as unknown[],\n contexts: [] as unknown[],\n ended: 0,\n };\n let attempts = 0;\n let count = 0;\n\n const backend: AgentBackend = {\n async openSession(request) {\n log.sessions.push(request);\n attempts++;\n const refusal = options.refuse?.(request, attempts);\n if (refusal === 'unreachable')\n throw Object.assign(new Error('mock: unreachable'), {\n retryable: true,\n reason: 'network',\n });\n if (refusal) throw new AgentRefusal(refusal);\n if (\n request.conversationId !== null &&\n !conversations.has(request.conversationId)\n )\n throw new AgentRefusal('ended', { code: 'conversation_not_found' });\n count++;\n const conversation = request.conversationId ?? `cnv_MOCK${count}`;\n if (!conversations.has(conversation)) conversations.set(conversation, []);\n const id = `ses_MOCK${count}`;\n sessions.set(id, { conversation, key: `${request.key.mode}` });\n const session: ConversationSession = {\n id,\n realtime_url: `wss://mock.vinaverse.invalid/v1/sessions/${id}/realtime`,\n turns_url: `https://mock.vinaverse.invalid/v1/sessions/${id}/turns`,\n client_secret: `vv_cs_${'mock'.repeat(6)}`,\n conversation_id: conversation,\n expires_at: new Date(\n now() + (options.sessionMs ?? 30 * 60_000),\n ).toISOString(),\n ...(options.agentName\n ? { agent: { display_name: options.agentName } }\n : {}),\n ...(options.disclosure ? { disclosure: options.disclosure } : {}),\n ...(options.welcome ? { welcome: options.welcome } : {}),\n };\n return session;\n },\n async refreshSecret() {\n return `vv_cs_${'mock'.repeat(6)}`;\n },\n async updateContext(sessionId, place, revision) {\n log.contexts.push({ sessionId, place, revision });\n },\n async status() {\n return (\n options.status ?? {\n available: true,\n launcher: true,\n displayName: options.agentName ?? null,\n }\n );\n },\n async sendFeedback(feedback) {\n log.feedback.push(feedback);\n },\n async endSessions() {\n log.ended++;\n },\n };\n\n const webSocket: WebSocketFactory = (url) => {\n const sessionId = /sessions\\/([^/]+)\\/realtime/.exec(url)?.[1] ?? '';\n const held = sessions.get(sessionId);\n const said = held ? (conversations.get(held.conversation) ?? []) : [];\n let turn = said.filter((s) => s.role === 'person').length;\n let state = 0;\n const socket: WebSocketLike = {\n get readyState() {\n return state;\n },\n onopen: null,\n onmessage: null,\n onclose: null,\n onerror: null,\n send(data) {\n const frame = JSON.parse(data) as Record<string, unknown>;\n if (frame.type === 'ping') return deliver({ type: 'pong' });\n if (frame.type !== 'input.text') return;\n const id = String(frame.client_event_id ?? '');\n const text = String(frame.text ?? '');\n turn++;\n const turnId = `turn_MOCK${turn}`;\n said.push({ role: 'person', text, id });\n const answer =\n options.script?.[turn - 1] ??\n options.reply?.(text, { turn, key: held?.key ?? '' }) ??\n `You said: ${text}`;\n const reply: MockReply =\n typeof answer === 'string' ? { text: answer } : answer;\n deliver({ type: 'turn.started', turn_id: turnId, client_event_id: id });\n if (reply.fail) {\n deliver({\n type: 'turn.failed',\n turn_id: turnId,\n code: reply.fail,\n message: '',\n retryable: true,\n });\n return;\n }\n let so = '';\n for (const part of reply.text ? sentences(reply.text) : []) {\n so += part;\n deliver({ type: 'message.delta', turn_id: turnId, text: part });\n }\n if (reply.text) {\n deliver({\n type: 'message.completed',\n turn_id: turnId,\n text: so.trim(),\n });\n said.push({ role: 'assistant', text: so.trim(), id: turnId });\n }\n if (reply.cards?.length)\n deliver({ type: 'ui.cards', turn_id: turnId, cards: reply.cards });\n deliver({ type: 'turn.completed', turn_id: turnId });\n },\n close(code) {\n if (state === 3) return;\n state = 3;\n setTimeout(() => socket.onclose?.({ code: code ?? 1000 }), 0);\n },\n };\n function deliver(event: unknown) {\n setTimeout(() => {\n if (state === 1) socket.onmessage?.({ data: JSON.stringify(event) });\n }, 0);\n }\n setTimeout(() => {\n state = 1;\n socket.onopen?.({});\n const resumed = said.length > 0;\n socket.onmessage?.({\n data: JSON.stringify({\n type: 'session.ready',\n session: { id: sessionId, status: 'open' },\n resumed,\n limits: {},\n disclosure:\n options.disclosure ?? 'An AI agent. Powered by Vinaverse.',\n ...(resumed\n ? {\n transcript: said.map((s) => ({\n role: s.role,\n text: s.text,\n id: s.id,\n at: new Date(now()).toISOString(),\n })),\n }\n : {}),\n }),\n });\n }, 0);\n return socket;\n };\n\n return { backend, webSocket, log };\n}\n\n/** Cards as a tenant's tools would give them, for mock replies and tests. */\nexport const mockCards = {\n professional(id: string, extra: Partial<Card> = {}): Card {\n return {\n id,\n kind: 'professional',\n title: 'Riley Sample',\n subtitle: 'Barber · Los Angeles',\n ref: { type: 'professional', id },\n images: [\n {\n url: `https://images.example.test/${id}.webp`,\n width: 1600,\n height: 1000,\n },\n ],\n rating: { value_ppm: 4_800_000, count: 132 },\n price_from: { amount: 4500, currency: 'USD' },\n actions: [],\n source: { tool: 'search_professionals', call_id: 'call_MOCK' },\n ...extra,\n } as Card;\n },\n workspace(id: string, extra: Partial<Card> = {}): Card {\n return {\n id,\n kind: 'workspace',\n title: 'Suite 4',\n subtitle: 'Private suite · Atlanta',\n ref: { type: 'workspace', id },\n price_from: { amount: 6500, currency: 'USD' },\n actions: [],\n source: { tool: 'search_spaces', call_id: 'call_MOCK' },\n ...extra,\n } as Card;\n },\n /** A proposal the person confirms in the app (`confirm_mode: tenant_app`), pending for a day unless `expires_at`. */\n proposal(\n id: string,\n proposal: {\n readonly topic?: string;\n readonly title?: string;\n readonly summary?: string;\n readonly expires_at?: string;\n } = {},\n ): Card {\n const title = proposal.title ?? 'Silk press with Riley';\n return {\n id,\n kind: 'proposal',\n title,\n actions: [],\n source: { tool: 'create_proposal', call_id: 'call_MOCK' },\n proposal: {\n id: `prp_${id}`,\n status: 'pending',\n topic: proposal.topic ?? 'booking',\n title,\n summary: proposal.summary ?? 'Wednesday at 10:00 · $45',\n fields: [],\n expires_at:\n proposal.expires_at ??\n new Date(Date.now() + 24 * 3_600_000).toISOString(),\n confirm_mode: 'tenant_app',\n },\n } as Card;\n },\n /** Times to book, from `start` on the hour, one an hour. */\n timeSlots(id: string, start: string, count = 3): Card {\n const at = Date.parse(start);\n return {\n id,\n kind: 'time_slots',\n title: 'Open times',\n slots: Array.from({ length: count }, (_, i) => ({\n id: `slot_${i + 1}`,\n start: new Date(at + i * 3_600_000).toISOString(),\n end: new Date(at + (i + 1) * 3_600_000).toISOString(),\n })),\n actions: [],\n source: { tool: 'get_availability', call_id: 'call_MOCK' },\n } as Card;\n },\n links(id: string): Card {\n return {\n id,\n kind: 'links',\n title: 'Pages that can help',\n links: [\n {\n label: 'Help center',\n url: 'https://help.example.test/',\n purpose: 'help',\n },\n {\n label: 'Contact us',\n url: 'https://help.example.test/contact',\n purpose: 'contact',\n },\n ],\n actions: [],\n source: { tool: 'scope', call_id: 'turn_MOCK' },\n } as Card;\n },\n};\n"]}
@@ -1,6 +1,6 @@
1
- import { A as AgentBackend, p as AgentSessionRequest, r as AgentStatusRead } from '../runtime-DDxwWBBr.cjs';
1
+ import { A as AgentBackend, q as AgentSessionRequest, s as AgentStatusRead } from '../runtime-C3ZknHdG.cjs';
2
2
  import { B as WebSocketFactory, a as Card, W as Welcome } from '../session-8W3fRNeb.cjs';
3
- import '../store-C7FtS5AY.cjs';
3
+ import '../store-7WU1kD9W.cjs';
4
4
 
5
5
  /** One reply of the scripted agent. */
6
6
  interface MockReply {
@@ -10,7 +10,9 @@ interface MockReply {
10
10
  readonly fail?: string;
11
11
  }
12
12
  interface MockAgentOptions {
13
- /** The agent's answer to the person's text. Default: an echo. */
13
+ /** Replies in order, one per turn (text, cards, a failure), after which `reply` (or the echo) answers. */
14
+ readonly script?: readonly (MockReply | string)[];
15
+ /** The agent's answer to the person's text. Default: the `script`, then an echo. */
14
16
  readonly reply?: (text: string, context: {
15
17
  readonly turn: number;
16
18
  readonly key: string;
@@ -43,6 +45,15 @@ declare function createMockAgent(options?: MockAgentOptions): MockAgent;
43
45
  declare const mockCards: {
44
46
  professional(id: string, extra?: Partial<Card>): Card;
45
47
  workspace(id: string, extra?: Partial<Card>): Card;
48
+ /** A proposal the person confirms in the app (`confirm_mode: tenant_app`), pending for a day unless `expires_at`. */
49
+ proposal(id: string, proposal?: {
50
+ readonly topic?: string;
51
+ readonly title?: string;
52
+ readonly summary?: string;
53
+ readonly expires_at?: string;
54
+ }): Card;
55
+ /** Times to book, from `start` on the hour, one an hour. */
56
+ timeSlots(id: string, start: string, count?: number): Card;
46
57
  links(id: string): Card;
47
58
  };
48
59
 
@@ -1,6 +1,6 @@
1
- import { A as AgentBackend, p as AgentSessionRequest, r as AgentStatusRead } from '../runtime-B4nKwOTF.js';
1
+ import { A as AgentBackend, q as AgentSessionRequest, s as AgentStatusRead } from '../runtime-CZ1hLvAl.js';
2
2
  import { B as WebSocketFactory, a as Card, W as Welcome } from '../session-8W3fRNeb.js';
3
- import '../store-DFk0ayh8.js';
3
+ import '../store-DrXSPHu6.js';
4
4
 
5
5
  /** One reply of the scripted agent. */
6
6
  interface MockReply {
@@ -10,7 +10,9 @@ interface MockReply {
10
10
  readonly fail?: string;
11
11
  }
12
12
  interface MockAgentOptions {
13
- /** The agent's answer to the person's text. Default: an echo. */
13
+ /** Replies in order, one per turn (text, cards, a failure), after which `reply` (or the echo) answers. */
14
+ readonly script?: readonly (MockReply | string)[];
15
+ /** The agent's answer to the person's text. Default: the `script`, then an echo. */
14
16
  readonly reply?: (text: string, context: {
15
17
  readonly turn: number;
16
18
  readonly key: string;
@@ -43,6 +45,15 @@ declare function createMockAgent(options?: MockAgentOptions): MockAgent;
43
45
  declare const mockCards: {
44
46
  professional(id: string, extra?: Partial<Card>): Card;
45
47
  workspace(id: string, extra?: Partial<Card>): Card;
48
+ /** A proposal the person confirms in the app (`confirm_mode: tenant_app`), pending for a day unless `expires_at`. */
49
+ proposal(id: string, proposal?: {
50
+ readonly topic?: string;
51
+ readonly title?: string;
52
+ readonly summary?: string;
53
+ readonly expires_at?: string;
54
+ }): Card;
55
+ /** Times to book, from `start` on the hour, one an hour. */
56
+ timeSlots(id: string, start: string, count?: number): Card;
46
57
  links(id: string): Card;
47
58
  };
48
59
 
@@ -1,5 +1,5 @@
1
- import { AgentRefusal } from '../chunk-3WR2SUG2.js';
2
- import '../chunk-ZWG2TMUL.js';
1
+ import { AgentRefusal } from '../chunk-3BLRAWNC.js';
2
+ import '../chunk-46D3FSLU.js';
3
3
  import '../chunk-GWLLUOFY.js';
4
4
 
5
5
  // src/testing/index.ts
@@ -92,7 +92,7 @@ function createMockAgent(options = {}) {
92
92
  turn++;
93
93
  const turnId = `turn_MOCK${turn}`;
94
94
  said.push({ role: "person", text, id });
95
- const answer = options.reply?.(text, { turn, key: held?.key ?? "" }) ?? `You said: ${text}`;
95
+ const answer = options.script?.[turn - 1] ?? options.reply?.(text, { turn, key: held?.key ?? "" }) ?? `You said: ${text}`;
96
96
  const reply = typeof answer === "string" ? { text: answer } : answer;
97
97
  deliver({ type: "turn.started", turn_id: turnId, client_event_id: id });
98
98
  if (reply.fail) {
@@ -194,6 +194,43 @@ var mockCards = {
194
194
  ...extra
195
195
  };
196
196
  },
197
+ /** A proposal the person confirms in the app (`confirm_mode: tenant_app`), pending for a day unless `expires_at`. */
198
+ proposal(id, proposal = {}) {
199
+ const title = proposal.title ?? "Silk press with Riley";
200
+ return {
201
+ id,
202
+ kind: "proposal",
203
+ title,
204
+ actions: [],
205
+ source: { tool: "create_proposal", call_id: "call_MOCK" },
206
+ proposal: {
207
+ id: `prp_${id}`,
208
+ status: "pending",
209
+ topic: proposal.topic ?? "booking",
210
+ title,
211
+ summary: proposal.summary ?? "Wednesday at 10:00 \xB7 $45",
212
+ fields: [],
213
+ expires_at: proposal.expires_at ?? new Date(Date.now() + 24 * 36e5).toISOString(),
214
+ confirm_mode: "tenant_app"
215
+ }
216
+ };
217
+ },
218
+ /** Times to book, from `start` on the hour, one an hour. */
219
+ timeSlots(id, start, count = 3) {
220
+ const at = Date.parse(start);
221
+ return {
222
+ id,
223
+ kind: "time_slots",
224
+ title: "Open times",
225
+ slots: Array.from({ length: count }, (_, i) => ({
226
+ id: `slot_${i + 1}`,
227
+ start: new Date(at + i * 36e5).toISOString(),
228
+ end: new Date(at + (i + 1) * 36e5).toISOString()
229
+ })),
230
+ actions: [],
231
+ source: { tool: "get_availability", call_id: "call_MOCK" }
232
+ };
233
+ },
197
234
  links(id) {
198
235
  return {
199
236
  id,