@vinaverse/client 0.1.0-alpha.10 → 0.1.0-alpha.12

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 (51) hide show
  1. package/README.md +22 -4
  2. package/dist/agent/index.cjs +43 -9
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +3 -3
  5. package/dist/agent/index.d.ts +3 -3
  6. package/dist/agent/index.js +1 -1
  7. package/dist/backend/index.cjs +37 -10
  8. package/dist/backend/index.cjs.map +1 -1
  9. package/dist/backend/index.d.cts +13 -3
  10. package/dist/backend/index.d.ts +13 -3
  11. package/dist/backend/index.js +38 -11
  12. package/dist/backend/index.js.map +1 -1
  13. package/dist/{chunk-O3NLAZGZ.js → chunk-5THD6XC7.js} +45 -11
  14. package/dist/chunk-5THD6XC7.js.map +1 -0
  15. package/dist/chunk-D56MNG3E.js +9 -0
  16. package/dist/{chunk-YNUHXJD6.js.map → chunk-D56MNG3E.js.map} +1 -1
  17. package/dist/contract-Be2oVHNr.d.cts +6 -0
  18. package/dist/contract-Be2oVHNr.d.ts +6 -0
  19. package/dist/conversation/index.cjs +2 -2
  20. package/dist/conversation/index.cjs.map +1 -1
  21. package/dist/conversation/index.d.cts +5 -5
  22. package/dist/conversation/index.d.ts +5 -5
  23. package/dist/conversation/index.js +1 -1
  24. package/dist/history/index.cjs +282 -0
  25. package/dist/history/index.cjs.map +1 -0
  26. package/dist/history/index.d.cts +91 -0
  27. package/dist/history/index.d.ts +91 -0
  28. package/dist/history/index.js +261 -0
  29. package/dist/history/index.js.map +1 -0
  30. package/dist/index.cjs +2 -2
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +2 -2
  33. package/dist/index.d.ts +2 -2
  34. package/dist/index.js +1 -1
  35. package/dist/{runtime-Z1RI10lU.d.ts → runtime-BR2lS_Vg.d.cts} +26 -3
  36. package/dist/{runtime-CISPp9nJ.d.cts → runtime-CZyVCueC.d.ts} +26 -3
  37. package/dist/{session-CPz4pcPu.d.cts → session-D0ijOQX3.d.cts} +98 -5
  38. package/dist/{session-CPz4pcPu.d.ts → session-D0ijOQX3.d.ts} +98 -5
  39. package/dist/{store-DZka9T2-.d.ts → store-CGRSxVcL.d.ts} +1 -1
  40. package/dist/{store-BxiicOKG.d.cts → store-CxoHwd64.d.cts} +1 -1
  41. package/dist/testing/index.cjs +158 -14
  42. package/dist/testing/index.cjs.map +1 -1
  43. package/dist/testing/index.d.cts +42 -5
  44. package/dist/testing/index.d.ts +42 -5
  45. package/dist/testing/index.js +159 -15
  46. package/dist/testing/index.js.map +1 -1
  47. package/package.json +24 -1
  48. package/dist/chunk-O3NLAZGZ.js.map +0 -1
  49. package/dist/chunk-YNUHXJD6.js +0 -9
  50. package/dist/contract-DmQs8amJ.d.cts +0 -6
  51. package/dist/contract-DmQs8amJ.d.ts +0 -6
@@ -1,8 +1,8 @@
1
- export { C as CONTRACT } from '../contract-DmQs8amJ.cjs';
2
- import { Q as Question, A as AnswerInput } from '../session-CPz4pcPu.cjs';
3
- export { a as Card, b as CardGroup, c as CardImage, d as CardKind, C as CardLink, e as ClientErrorCode, H as HeldCard, f as HeldQuestion, P as Proposal, g as ProposalOutcome, T as ToolLine, V as VinaverseClientError, W as Welcome, i as isKnownCard } from '../session-CPz4pcPu.cjs';
4
- import { C as ConversationStore, a as ConversationOptions, S as SessionRequest, b as ConversationSession } from '../store-BxiicOKG.cjs';
5
- export { c as CardItem, d as ConversationActivity, e as ConversationBanner, f as ConversationPersistence, g as ConversationStatus, h as ConversationView, F as FrameScheduler, M as MAX_TEXT, i as MessageItem, j as MessageState, k as SessionReason, l as StreamingText, m as SystemEvent, n as SystemItem, T as TimelineItem, o as createConversation } from '../store-BxiicOKG.cjs';
1
+ export { C as CONTRACT } from '../contract-Be2oVHNr.cjs';
2
+ import { Q as Question, A as AnswerInput } from '../session-D0ijOQX3.cjs';
3
+ export { a as Card, b as CardGroup, c as CardImage, d as CardKind, C as CardLink, e as ClientErrorCode, H as HeldCard, f as HeldQuestion, P as Proposal, g as ProposalOutcome, T as ToolLine, V as VinaverseClientError, W as Welcome, i as isKnownCard } from '../session-D0ijOQX3.cjs';
4
+ import { C as ConversationStore, a as ConversationOptions, S as SessionRequest, b as ConversationSession } from '../store-CxoHwd64.cjs';
5
+ export { c as CardItem, d as ConversationActivity, e as ConversationBanner, f as ConversationPersistence, g as ConversationStatus, h as ConversationView, F as FrameScheduler, M as MAX_TEXT, i as MessageItem, j as MessageState, k as SessionReason, l as StreamingText, m as SystemEvent, n as SystemItem, T as TimelineItem, o as createConversation } from '../store-CxoHwd64.cjs';
6
6
 
7
7
  type AnswerProblem =
8
8
  /** Nothing chosen or typed, and the question is required (or skipped while required). */
@@ -1,8 +1,8 @@
1
- export { C as CONTRACT } from '../contract-DmQs8amJ.js';
2
- import { Q as Question, A as AnswerInput } from '../session-CPz4pcPu.js';
3
- export { a as Card, b as CardGroup, c as CardImage, d as CardKind, C as CardLink, e as ClientErrorCode, H as HeldCard, f as HeldQuestion, P as Proposal, g as ProposalOutcome, T as ToolLine, V as VinaverseClientError, W as Welcome, i as isKnownCard } from '../session-CPz4pcPu.js';
4
- import { C as ConversationStore, a as ConversationOptions, S as SessionRequest, b as ConversationSession } from '../store-DZka9T2-.js';
5
- export { c as CardItem, d as ConversationActivity, e as ConversationBanner, f as ConversationPersistence, g as ConversationStatus, h as ConversationView, F as FrameScheduler, M as MAX_TEXT, i as MessageItem, j as MessageState, k as SessionReason, l as StreamingText, m as SystemEvent, n as SystemItem, T as TimelineItem, o as createConversation } from '../store-DZka9T2-.js';
1
+ export { C as CONTRACT } from '../contract-Be2oVHNr.js';
2
+ import { Q as Question, A as AnswerInput } from '../session-D0ijOQX3.js';
3
+ export { a as Card, b as CardGroup, c as CardImage, d as CardKind, C as CardLink, e as ClientErrorCode, H as HeldCard, f as HeldQuestion, P as Proposal, g as ProposalOutcome, T as ToolLine, V as VinaverseClientError, W as Welcome, i as isKnownCard } from '../session-D0ijOQX3.js';
4
+ import { C as ConversationStore, a as ConversationOptions, S as SessionRequest, b as ConversationSession } from '../store-CGRSxVcL.js';
5
+ export { c as CardItem, d as ConversationActivity, e as ConversationBanner, f as ConversationPersistence, g as ConversationStatus, h as ConversationView, F as FrameScheduler, M as MAX_TEXT, i as MessageItem, j as MessageState, k as SessionReason, l as StreamingText, m as SystemEvent, n as SystemItem, T as TimelineItem, o as createConversation } from '../store-CGRSxVcL.js';
6
6
 
7
7
  type AnswerProblem =
8
8
  /** Nothing chosen or typed, and the question is required (or skipped while required). */
@@ -1,4 +1,4 @@
1
- export { CONTRACT } from '../chunk-YNUHXJD6.js';
1
+ export { CONTRACT } from '../chunk-D56MNG3E.js';
2
2
  import { createConversation } from '../chunk-46D3FSLU.js';
3
3
  export { ConversationStore, MAX_TEXT, createConversation, isAllowedLink, isValidLinkPrefix } from '../chunk-46D3FSLU.js';
4
4
  export { VinaverseClientError, isKnownCard } from '../chunk-GWLLUOFY.js';
@@ -0,0 +1,282 @@
1
+ 'use strict';
2
+
3
+ // src/agent/runtime.ts
4
+ var AgentRefusal = class extends Error {
5
+ constructor(kind, options = {}) {
6
+ super(
7
+ options.message ?? (kind === "ended" ? "The conversation is over." : "No agent now.")
8
+ );
9
+ this.kind = kind;
10
+ this.name = "AgentRefusal";
11
+ this.reason = options.reason ?? (kind === "ended" ? "ended" : "unknown");
12
+ this.code = options.code ?? null;
13
+ }
14
+ kind;
15
+ reason;
16
+ code;
17
+ };
18
+ function isRefusal(error) {
19
+ return error instanceof AgentRefusal || field(error, "name") === "AgentRefusal" && (field(error, "kind") === "ended" || field(error, "kind") === "unavailable");
20
+ }
21
+ var field = (error, name) => typeof error === "object" && error !== null ? error[name] : void 0;
22
+
23
+ // src/history/index.ts
24
+ function continueKey(conversation, subject, thread) {
25
+ return {
26
+ subject,
27
+ mode: conversation.experience_mode,
28
+ scope: conversation.business_scope_id ?? null,
29
+ ...thread ? { thread } : {}
30
+ };
31
+ }
32
+ function historyItems(data) {
33
+ return data.map((item, seq) => {
34
+ if (item.type === "card") {
35
+ const outcome = item.proposal_outcome;
36
+ const card = {
37
+ type: "card",
38
+ key: item.card.id,
39
+ busy: false,
40
+ restored: true,
41
+ card: {
42
+ id: item.card.id,
43
+ kind: item.card.kind,
44
+ card: item.card,
45
+ locked: [],
46
+ turnId: item.turn_id,
47
+ outcome: outcome && outcome !== "pending" ? outcome : null,
48
+ seq
49
+ }
50
+ };
51
+ return card;
52
+ }
53
+ const message = {
54
+ type: "message",
55
+ key: `h:${item.id}`,
56
+ role: item.role === "assistant" ? "agent" : item.role,
57
+ text: item.text,
58
+ state: "sent",
59
+ ...item.interrupted ? { partial: "interrupted" } : {},
60
+ ...item.refusal ? { refusal: true } : {}
61
+ };
62
+ return message;
63
+ });
64
+ }
65
+ function reasonOf(error) {
66
+ if (isRefusal(error)) return error.reason;
67
+ const given = error?.reason;
68
+ return typeof given === "string" ? given : "unknown";
69
+ }
70
+ function staleCursor(error) {
71
+ const e = error;
72
+ return e?.outcome === "unavailable" && e.gatewayCode === "invalid_request" && e.retryable === false;
73
+ }
74
+ function paged(runtime, empty) {
75
+ let state = empty;
76
+ let epoch = runtime.epoch();
77
+ let asked = 0;
78
+ const listeners = /* @__PURE__ */ new Set();
79
+ const set = (next) => {
80
+ state = { ...state, ...next };
81
+ for (const l of [...listeners]) l();
82
+ };
83
+ const fresh = () => {
84
+ if (runtime.epoch() === epoch) return;
85
+ epoch = runtime.epoch();
86
+ asked++;
87
+ state = empty;
88
+ };
89
+ let off = null;
90
+ return {
91
+ get: () => {
92
+ fresh();
93
+ return state;
94
+ },
95
+ set,
96
+ subscribe(listener) {
97
+ listeners.add(listener);
98
+ off ??= runtime.subscribe(() => {
99
+ const before = state;
100
+ fresh();
101
+ if (state !== before) for (const l of [...listeners]) l();
102
+ });
103
+ return () => {
104
+ listeners.delete(listener);
105
+ if (listeners.size === 0) {
106
+ off?.();
107
+ off = null;
108
+ }
109
+ };
110
+ },
111
+ /** Reads a page; `apply` lands only for the newest read, under the same person. */
112
+ read(call, apply, failed) {
113
+ fresh();
114
+ const mine = ++asked;
115
+ const under = epoch;
116
+ set({ loading: true });
117
+ call().then(
118
+ (value) => {
119
+ if (mine === asked && under === runtime.epoch()) apply(value);
120
+ },
121
+ (error) => {
122
+ if (mine === asked && under === runtime.epoch()) failed(error);
123
+ }
124
+ );
125
+ }
126
+ };
127
+ }
128
+ var NO_HISTORY = {
129
+ conversations: [],
130
+ loading: false,
131
+ failure: null,
132
+ done: false,
133
+ started: false
134
+ };
135
+ function createAgentHistory(options) {
136
+ const { runtime } = options;
137
+ const backend = options.backend ?? runtime.backend;
138
+ const store = paged(runtime, NO_HISTORY);
139
+ let cursor = null;
140
+ let restarted = false;
141
+ const page = (from) => {
142
+ const list = backend.listConversations?.bind(backend);
143
+ if (!list) {
144
+ store.set({ started: true, failure: "off", done: true });
145
+ return;
146
+ }
147
+ store.read(
148
+ () => list({
149
+ mode: options.mode,
150
+ scope: options.scope ?? null,
151
+ agent: options.agent ?? null,
152
+ limit: options.pageSize ?? 20,
153
+ cursor: from
154
+ }),
155
+ (got) => {
156
+ const known = new Set(
157
+ from ? store.get().conversations.map((c) => c.id) : []
158
+ );
159
+ cursor = got.next_cursor;
160
+ store.set({
161
+ conversations: [
162
+ ...from ? store.get().conversations : [],
163
+ ...got.data.filter((c) => !known.has(c.id))
164
+ ],
165
+ loading: false,
166
+ failure: null,
167
+ done: cursor === null
168
+ });
169
+ },
170
+ (error) => {
171
+ if (from !== null && staleCursor(error) && !restarted) {
172
+ restarted = true;
173
+ cursor = null;
174
+ page(null);
175
+ return;
176
+ }
177
+ store.set({ loading: false, failure: reasonOf(error) });
178
+ }
179
+ );
180
+ };
181
+ const refresh = () => {
182
+ cursor = null;
183
+ restarted = false;
184
+ store.set({ started: true });
185
+ page(null);
186
+ };
187
+ const loadMore = () => {
188
+ const s = store.get();
189
+ if (!s.started || s.loading || s.done || cursor === null) return;
190
+ page(cursor);
191
+ };
192
+ return {
193
+ getSnapshot: store.get,
194
+ subscribe: store.subscribe,
195
+ refresh,
196
+ loadMore,
197
+ retry: () => cursor === null ? refresh() : loadMore(),
198
+ async remove(key, conversationId) {
199
+ try {
200
+ await runtime.deleteConversation(key, conversationId);
201
+ } catch (error) {
202
+ if (!(isRefusal(error) && error.reason === "not_found")) throw error;
203
+ }
204
+ store.set({
205
+ conversations: store.get().conversations.filter((c) => c.id !== conversationId)
206
+ });
207
+ }
208
+ };
209
+ }
210
+ var NO_TRANSCRIPT = {
211
+ items: [],
212
+ loading: false,
213
+ failure: null,
214
+ done: false,
215
+ started: false
216
+ };
217
+ function createAgentTranscript(options) {
218
+ const { runtime } = options;
219
+ const backend = options.backend ?? runtime.backend;
220
+ const store = paged(runtime, NO_TRANSCRIPT);
221
+ let cursor = null;
222
+ let restarted = false;
223
+ const page = (from) => {
224
+ const read = backend.readConversation?.bind(backend);
225
+ if (!read) {
226
+ store.set({ started: true, failure: "off", done: true });
227
+ return;
228
+ }
229
+ store.read(
230
+ () => read(options.conversationId, {
231
+ limit: options.pageSize ?? 30,
232
+ cursor: from
233
+ }),
234
+ (got) => {
235
+ const earlier = historyItems(got.data);
236
+ const held = from ? store.get().items : [];
237
+ const keys = new Set(held.map((i) => i.key));
238
+ cursor = got.next_cursor;
239
+ store.set({
240
+ items: [...earlier.filter((i) => !keys.has(i.key)), ...held],
241
+ loading: false,
242
+ failure: null,
243
+ done: cursor === null
244
+ });
245
+ },
246
+ (error) => {
247
+ if (from !== null && staleCursor(error) && !restarted) {
248
+ restarted = true;
249
+ cursor = null;
250
+ page(null);
251
+ return;
252
+ }
253
+ store.set({ loading: false, failure: reasonOf(error) });
254
+ }
255
+ );
256
+ };
257
+ const load = () => {
258
+ cursor = null;
259
+ restarted = false;
260
+ store.set({ started: true });
261
+ page(null);
262
+ };
263
+ const loadEarlier = () => {
264
+ const s = store.get();
265
+ if (!s.started || s.loading || s.done || cursor === null) return;
266
+ page(cursor);
267
+ };
268
+ return {
269
+ getSnapshot: store.get,
270
+ subscribe: store.subscribe,
271
+ load,
272
+ loadEarlier,
273
+ retry: () => cursor === null ? load() : loadEarlier()
274
+ };
275
+ }
276
+
277
+ exports.continueKey = continueKey;
278
+ exports.createAgentHistory = createAgentHistory;
279
+ exports.createAgentTranscript = createAgentTranscript;
280
+ exports.historyItems = historyItems;
281
+ //# sourceMappingURL=index.cjs.map
282
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agent/runtime.ts","../../src/history/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,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,IAAA;AAiBX,CAAA;AAs3CO,SAAS,UAAU,KAAA,EAAuC;AAC/D,EAAA,OACE,KAAA,YAAiB,YAAA,IAChB,KAAA,CAAM,KAAA,EAAO,MAAM,CAAA,KAAM,cAAA,KACvB,KAAA,CAAM,KAAA,EAAO,MAAM,CAAA,KAAM,OAAA,IACxB,KAAA,CAAM,KAAA,EAAO,MAAM,CAAA,KAAM,aAAA,CAAA;AAEjC;AAEA,IAAM,KAAA,GAAQ,CAAC,KAAA,EAAgB,IAAA,KAC7B,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,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UAAA,SAAA,GAAY,IAAA;AACZ,UAAA,MAAA,GAAS,IAAA;AACT,UAAA,IAAA,CAAK,IAAI,CAAA;AACT,UAAA;AAAA,QACF;AACA,QAAA,KAAA,CAAM,GAAA,CAAI,EAAE,OAAA,EAAS,KAAA,EAAO,SAAS,QAAA,CAAS,KAAK,GAAG,CAAA;AAAA,MACxD;AAAA,KACF;AAAA,EACF,CAAA;AACA,EAAA,MAAM,OAAO,MAAM;AACjB,IAAA,MAAA,GAAS,IAAA;AACT,IAAA,SAAA,GAAY,KAAA;AACZ,IAAA,KAAA,CAAM,GAAA,CAAI,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA;AAC3B,IAAA,IAAA,CAAK,IAAI,CAAA;AAAA,EACX,CAAA;AACA,EAAA,MAAM,cAAc,MAAM;AACxB,IAAA,MAAM,CAAA,GAAI,MAAM,GAAA,EAAI;AACpB,IAAA,IAAI,CAAC,EAAE,OAAA,IAAW,CAAA,CAAE,WAAW,CAAA,CAAE,IAAA,IAAQ,WAAW,IAAA,EAAM;AAC1D,IAAA,IAAA,CAAK,MAAM,CAAA;AAAA,EACb,CAAA;AACA,EAAA,OAAO;AAAA,IACL,aAAa,KAAA,CAAM,GAAA;AAAA,IACnB,WAAW,KAAA,CAAM,SAAA;AAAA,IACjB,IAAA;AAAA,IACA,WAAA;AAAA,IACA,OAAO,MAAO,MAAA,KAAW,IAAA,GAAO,IAAA,KAAS,WAAA;AAAY,GACvD;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 status and where its read stands, so a screen tells \"reading\" from \"could not read\". */\nexport interface AgentStatusState {\n readonly status: AgentStatus | null;\n readonly reading: boolean;\n readonly failed: boolean;\n}\n\n/** The tenant's backend: the one piece of integration an app writes. */\nexport interface AgentBackend {\n /** A session from the tenant's API (it creates it at Vinaverse with its service key), or an `AgentRefusal`. */\n openSession(request: AgentSessionRequest): Promise<ConversationSession>;\n /**\n * A fresh client secret for the same session (before its end): a `ClientSecret` `{ value, expires_at }`, or its\n * value. A refusal (`session_closed`: the session is over) goes on with the conversation in a new session.\n */\n refreshSecret?(sessionId: string): Promise<ClientSecret | string>;\n /**\n * The person's place changed while the chat is open: the tenant's backend tells Vinaverse\n * (`PUT /v1/sessions/{id}/context`). A place cleared (`tell({ place: null })`) comes as `{ screen: 'other' }`.\n * `revision` only grows for a conversation, across its sessions. A conflict (`decodeBackendFailure`'s\n * `context_conflict`, or a refusal with reason `conflict`, with the server's `currentRevision`) is sent once more\n * above it, then said as `moved`. Absent, or refused otherwise, the kit offers a question about the new place.\n */\n updateContext?(\n sessionId: string,\n place: AgentPlace,\n revision: number,\n ): Promise<void>;\n /** Whether the agent is offered, and what it can do. Absent: available, nothing extra. */\n status?(signal?: AbortSignal): Promise<AgentStatusRead>;\n /** A thumbs on a whole reply; best effort, never an error for the person. */\n sendFeedback?(feedback: {\n readonly sessionId: string;\n readonly turnId: string;\n readonly rating: AgentRating;\n }): Promise<void>;\n /** Sign-out: end the person's open sessions at the tenant's API. */\n endSessions?(): Promise<void>;\n /** History's delete: the tenant's API deletes the person's conversation (authenticated, theirs only). */\n deleteConversation?(conversationId: string): Promise<void>;\n /**\n * History: the person's past conversations with the agent, newest activity first, a page at a time (`cursor` from\n * the page before). The person comes from the backend's authentication, never from here.\n */\n listConversations?(\n query: {\n readonly mode: string;\n readonly scope: string | null;\n readonly agent: string | null;\n readonly limit?: number;\n readonly cursor: string | null;\n },\n signal?: AbortSignal,\n ): Promise<Schemas['ConversationPage']>;\n /** History: a past conversation's messages and cards, the newest page first, oldest first within a page. */\n readConversation?(\n conversationId: string,\n page: { readonly limit?: number; readonly cursor: string | null },\n signal?: AbortSignal,\n ): Promise<Schemas['TimelinePage']>;\n}\n\nexport type AgentRating = 'up' | 'down';\nexport type AgentFailure = 'ended' | 'unreachable' | 'unavailable';\n\nexport type AgentEventType =\n | 'session_opened'\n | 'session_resumed'\n | 'session_retried'\n | 'session_failed'\n | 'conversation_ended'\n | 'context_updated'\n | 'rated'\n | 'chip_tapped'\n | 'card_action'\n | 'target_opened'\n | 'link_opened'\n | 'launcher_shown'\n | 'launcher_opened'\n | 'launcher_greeted'\n | 'greeting_closed'\n | 'message_sent'\n | 'reply_completed'\n | 'card_shown';\n\n/** For the app's analytics: what happened, for which conversation, with nothing the person said. */\nexport interface AgentEvent {\n readonly type: AgentEventType;\n /** The conversation, as a hash of its key (`hashKey`): stable, and never the person's id. */\n readonly key?: string;\n readonly sessionId?: string;\n readonly failure?: AgentFailure;\n readonly reason?: AgentFailureReason;\n readonly attempt?: number;\n readonly turnId?: string;\n readonly rating?: AgentRating;\n readonly cardId?: string;\n readonly kind?: string;\n /** Where the person opened from (`launcher`, `ask`, `deep_link`, the app's own words). */\n readonly from?: AgentEntryPoint;\n}\n\n/** What a UI draws around the store: why there is no session, whether the person moved, the thumbs given. */\nexport interface AgentConversationState {\n readonly failure: AgentFailure | null;\n readonly reason: AgentFailureReason | null;\n /** The API's own code for the failure (`conversation_expired`, …), when it gave one. */\n readonly code: string | null;\n /** The session was told another place than the one the person now asks from, and it could not be told live. */\n readonly moved: boolean;\n readonly ratings: ReadonlyMap<string, AgentRating>;\n readonly sessionId: string | null;\n /**\n * The conversation the key holds: the one it continues before a session opens, then its session's. Null for a new\n * one not yet opened. History's delete compares against it (`deleteConversation` does).\n */\n readonly conversationId: string | null;\n /** The open the backend could not settle (`unknown_open`), for support; null otherwise. */\n readonly openId: string | null;\n}\n\nexport interface AgentConversation {\n /** The key as a string, for the app's own maps and the events. */\n readonly key: string;\n readonly store: ConversationStore;\n /**\n * A view attaches: kept, with its connection, while any view is attached. The first time, it starts. Returns the\n * detach: with no view attached it is suspended (no pings; closed with `closeInBackground`) while its session lives\n * (`keepAlive: 'session'`), and let go when it has none, is past its end, or `keepAlive` is `'view'`. Separate from the\n * app's background, which the platform adapter tells the store.\n */\n show(open?: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: AgentEntryPoint | null;\n }): () => void;\n /**\n * The place and the way in changed while a view is attached: told live where the backend can, else on the next\n * session. `undefined` keeps what was told; `null` clears it.\n */\n tell(open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: AgentEntryPoint | null;\n }): void;\n getState(): AgentConversationState;\n subscribe(listener: () => void): () => void;\n /** Asks for a session again, after the backend could not be reached. */\n retry(): void;\n /**\n * Whether a reply can be rated: one this runtime saw given live. A reply restored from the device or a resumed\n * transcript cannot be, until the API rates a turn by its conversation; the kits draw no thumbs for it.\n */\n canRate(turnId: string): boolean;\n /** A thumbs on a whole reply, against the session it was given in; a change of mind only is sent again. */\n rate(turnId: string, rating: AgentRating): void;\n /**\n * Sends the person's `text` once in this conversation's life (a chip tapped twice, a retried tap). It is shown as\n * theirs: only words they typed or tapped, never the app's in their name.\n */\n sendOnce(text: string): void;\n}\n\n/** When the runtime tries the backend again: before each try, a delay; `isRetryable` decides which errors are waited out. */\nexport interface AgentRetryPolicy {\n readonly delays: readonly number[];\n readonly isRetryable?: (error: unknown) => boolean;\n}\n\n/** The time the runtime judges a session's end by: the server's, when the app has it (a clock synced from responses). */\nexport interface AgentClock {\n now(): number;\n}\n\nexport interface AgentRuntimeOptions {\n readonly backend: AgentBackend;\n /**\n * The agent this runtime talks to (its id at Vinaverse). It is part of every key, so two agents sharing the device's\n * storage (`conversation.persistence`) never share a conversation. Default: none (one agent per storage namespace).\n */\n readonly agent?: string;\n /** The store's own options (locale, time zone, deep-link prefixes, transport, persistence, closeInBackground…). */\n readonly conversation?: Omit<\n ConversationOptions,\n 'getSession' | 'refreshSecret' | 'clock'\n >;\n /** Default: 500, 1500, 3500 ms, for errors with `retryable: true`; applied to `openSession` and `refreshSecret`. */\n readonly retry?: AgentRetryPolicy;\n /** Default: the device's clock. Give the server's: a phone set wrong otherwise reuses a dead session or drops a live one. */\n readonly clock?: AgentClock;\n /** `session` (default): kept while its session lives with no view attached; `view`: let go when the last view goes. */\n readonly keepAlive?: 'session' | 'view';\n /** How long a status read stays fresh. Default 5 minutes. */\n readonly statusStaleMs?: number;\n /**\n * DANGEROUS: for mocks and local development only. Lets a leg's session address be plaintext (`ws://`, `http://`),\n * which would carry the person's messages and the session's secret unencrypted. Off by default, whatever transport\n * the app supplies; outside `__DEV__` the runtime warns once.\n */\n readonly insecureAddresses?: AgentInsecureAddresses;\n readonly onEvent?: (event: AgentEvent) => void;\n /**\n * Where the launcher remembers it greeted a person (the app's preferences store). Given here, the launcher reads and\n * writes it through the runtime (`greetings`), a sign-out fences it, and `erase()` removes it.\n */\n readonly greetingStorage?: ConversationPersistence;\n /**\n * Keys an earlier version of the app or the kit wrote that no index lists, for a storage with neither `keys` nor\n * `removePrefix`: removed by every sign-out from `conversation.persistence`, and by `erase()` from `greetingStorage`\n * too. The migration that makes their removal certain on such a storage.\n */\n readonly legacyKeys?: readonly string[];\n /** Where the runtime's warnings go (the app's logger, crash reporter); default `console.warn`. */\n readonly onWarning?: (message: string, warning: AgentWarning) => void;\n}\n\n/**\n * What a warning is about, for an app's logger to count without reading the message: `insecure_addresses` (a leg let\n * off the wss:// and https:// check outside development), `callback_threw` (the app's `onEvent` or `onActivity` threw;\n * `callback` names it), `events_dropped` (the oldest analytics events, while the salt is read).\n */\nexport interface AgentWarning {\n readonly code:\n | 'insecure_addresses'\n | 'callback_threw'\n | 'events_dropped'\n | 'context_refused';\n readonly callback?: 'onEvent' | 'onActivity';\n}\n\n/** The legs whose session address may be plaintext: `realtime` (the WebSocket), `turns` (HTTP). */\nexport interface AgentInsecureAddresses {\n readonly realtime?: boolean;\n readonly turns?: boolean;\n}\n\nexport interface AgentRuntime {\n /** The app's backend, as given: history (`@vinaverse/client/history`) reads its pages through it. */\n readonly backend: AgentBackend;\n /** The key's conversation: the same while it lives; a new one after `startNew`, `dispose` or its end. */\n conversation(key: AgentKey): AgentConversation;\n /**\n * The key's conversation as it stands, ending nothing and telling no one: for a render (`useSyncExternalStore`).\n * One past its session's end is ended when it is next shown, and subscribers then read the key's next one.\n */\n peek(key: AgentKey): AgentConversation;\n /** A new conversation for the key from the person's next opening; the old one is let go and forgotten. */\n startNew(key: AgentKey): void;\n /**\n * Closes the key's conversation now; the next opening continues it in a new session. What the device kept of it and\n * the conversation it continues stay: `forget` removes them.\n */\n dispose(key: AgentKey): void;\n /**\n * Closes the key's conversation and forgets it on this device: the conversation it continued and the transcript kept\n * by `persistence`. History's \"delete\" calls it after the tenant's backend deleted the conversation.\n */\n forget(key: AgentKey): void;\n /** Ends every conversation no view shows that is past its session's end. The kits call it when the app comes back. */\n sweep(): void;\n /**\n * History's delete: the backend deletes the conversation, then the device forgets it, only where the key still\n * continues that conversation (an older history entry never forgets the key's newer one).\n */\n deleteConversation(key: AgentKey, conversationId: string): Promise<void>;\n /**\n * The person's erasure on this device: a sign-out, plus the launcher's greeting records (`greetingStorage`) and the\n * analytics salt, every key this version and alpha.5 or alpha.6 wrote. Keys no index lists (an earlier version's, a\n * write lost with its process) are found only when the storage has `keys` or `removePrefix`.\n */\n erase(): Promise<void>;\n /** The launcher's greeting storage, under the sign-out fence; null without `greetingStorage`. */\n readonly greetings: ConversationPersistence | null;\n /**\n * The key goes on with this conversation (history's \"Continue\"): pinned for the key and opened through the backend's\n * resume. One that is gone (404, 410: the backend's `AgentRefusal('ended')`) is said as `ended`, never replaced by a\n * new one silently.\n */\n continue(key: AgentKey, conversationId: string): AgentConversation;\n /**\n * Every conversation closed and forgotten, and everything this runtime kept on the device (every transcript it ever\n * wrote under `conversation.persistenceKey`, even of conversations already closed), the status and the name; then\n * the backend is told to end the sessions at the same time. A late answer from before (a session, a status, a write)\n * changes nothing. Kept on purpose: the launcher's greeting records and the analytics salt (`erase` takes them).\n */\n signOut(): Promise<void>;\n /** The agent's status, read from the backend at most every `statusStaleMs`. */\n status(): Promise<AgentStatus>;\n getStatus(): AgentStatus | null;\n /**\n * The status with where its read stands: `reading` while one is out, `failed` when the last one could not be read\n * (the status held before, if any, stays). One object until it changes, for `useSyncExternalStore`.\n */\n getStatusState(): AgentStatusState;\n /**\n * Which person's turn it is on this device: a number that changes at every sign-out and erasure. Work begun under an\n * older one (a history page, a transcript) is dropped when it lands.\n */\n epoch(): number;\n /** The agent's name: from the newest session, else from the status. */\n getName(): string | null;\n /** Told when the status or name changes, and when a key's conversation is let go (its next one is another). */\n subscribe(listener: () => void): () => void;\n /** An event from a kit or the app, passed to `onEvent`. */\n emit(event: AgentEvent): void;\n}\n\n/** The launcher's greeting records' prefix: outside the transcripts' (`vinaverse.agent.`), so a sign-out keeps them. */\nconst GREETED = 'vinaverse.greeted';\n/** Where alpha.5 and alpha.6 kept them. */\nconst GREETED_BEFORE = 'vinaverse.agent.greeted';\n\n/**\n * Where the launcher remembers that it greeted a person in a mode, the key its storage sees. Encoded so a guest\n * (`null`) is never a person whose id is \"guest\".\n */\nexport function greetedKey(subject: string | null, mode: string): string {\n return `${GREETED}.${JSON.stringify([subject, mode])}`;\n}\n\n/** The tuple inside a key written by this version (`<prefix>.<agentKey>`), or null for any other. */\nfunction tupleOf(key: string, prefix: string): unknown[] | null {\n if (!key.startsWith(`${prefix}.[`)) return null;\n try {\n const t: unknown = JSON.parse(key.slice(prefix.length + 1));\n return Array.isArray(t) ? t : null;\n } catch {\n return null;\n }\n}\n\n/** alpha.5 and alpha.6 kept a transcript and a greeting under these names: found from the keys this version knows. */\nfunction legacyTranscripts(keys: ReadonlySet<string>, prefix: string) {\n const out: string[] = [];\n for (const key of keys) {\n const t = tupleOf(key, prefix);\n if (t)\n out.push(\n `${prefix}.${t[1] ?? 'guest'}|${t[2]}|${t[3] ?? '-'}|${t[4] ?? 'chat'}`,\n );\n }\n return out;\n}\nfunction legacyGreetings(pairs: Iterable<readonly [unknown, unknown]>) {\n const out: string[] = [];\n for (const [subject, mode] of pairs)\n out.push(`${GREETED_BEFORE}.${subject ?? 'guest'}:${mode}`);\n return out;\n}\n\nconst NOT_KEPT = new Set(['starting', 'unavailable', 'unauthorized', 'closed']);\n/** A place cleared, as `updateContext` sends it: a screen the vocabulary keeps for none in particular. */\nconst CLEARED: AgentPlace = { screen: 'other' };\n\n/**\n * A conversation's key as analytics sees it: SHA-256 of the install's salt and the key, 128 bits in hex. Stable per\n * install (the runtime keeps the salt in the app's storage until `erase()`), never the person's id, and not\n * recomputable from a guessed id without the salt.\n */\nexport function hashKey(key: string, salt: string): string {\n return `k${sha256(`${salt}\\u0000${key}`).slice(0, 32)}`;\n}\n\nlet K: number[] | undefined;\nlet H: number[] | undefined;\n\n/** SHA-256 of a string's UTF-8 bytes, in hex (FIPS 180-4; no platform crypto: Hermes has none, and this is sync). */\nexport function sha256(text: string): string {\n if (!K || !H) {\n // The first 32 bits of the fractional parts of the primes' cube roots (K) and the first eight's square roots (H).\n K = [];\n H = [];\n for (let n = 2; K.length < 64; n++) {\n let prime = true;\n for (let d = 2; d * d <= n; d++) if (n % d === 0) prime = false;\n if (!prime) continue;\n if (H.length < 8) H.push(((Math.sqrt(n) % 1) * 2 ** 32) | 0);\n K.push(((Math.cbrt(n) % 1) * 2 ** 32) | 0);\n }\n }\n const bytes: number[] = [];\n const s = encodeURIComponent(text);\n for (let i = 0; i < s.length; i++)\n if (s[i] === '%') {\n bytes.push(Number.parseInt(s.slice(i + 1, i + 3), 16));\n i += 2;\n } else bytes.push(s.charCodeAt(i));\n const bits = bytes.length * 8;\n bytes.push(0x80);\n while (bytes.length % 64 !== 56) bytes.push(0);\n for (const word of [Math.floor(bits / 2 ** 32), bits >>> 0])\n bytes.push(\n word >>> 24,\n (word >>> 16) & 255,\n (word >>> 8) & 255,\n word & 255,\n );\n const h = [...H];\n const w = new Array<number>(64);\n const ror = (x: number, n: number) => (x >>> n) | (x << (32 - n));\n for (let at = 0; at < bytes.length; at += 64) {\n for (let i = 0; i < 64; i++) {\n if (i < 16) {\n const b = at + i * 4;\n w[i] =\n ((bytes[b] as number) << 24) |\n ((bytes[b + 1] as number) << 16) |\n ((bytes[b + 2] as number) << 8) |\n (bytes[b + 3] as number);\n } else {\n const x = w[i - 15] as number;\n const y = w[i - 2] as number;\n w[i] =\n ((w[i - 16] as number) +\n (ror(x, 7) ^ ror(x, 18) ^ (x >>> 3)) +\n (w[i - 7] as number) +\n (ror(y, 17) ^ ror(y, 19) ^ (y >>> 10))) |\n 0;\n }\n }\n let [a, b, c, d, e, f, g, k] = h as [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n ];\n for (let i = 0; i < 64; i++) {\n const t1 =\n (k +\n (ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)) +\n ((e & f) ^ (~e & g)) +\n (K[i] as number) +\n (w[i] as number)) |\n 0;\n const t2 =\n ((ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)) +\n ((a & b) ^ (a & c) ^ (b & c))) |\n 0;\n k = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n [a, b, c, d, e, f, g, k].forEach((v, i) => {\n h[i] = ((h[i] as number) + v) | 0;\n });\n }\n return h.map((v) => (v >>> 0).toString(16).padStart(8, '0')).join('');\n}\nconst NO_FEATURES: AgentStatus['features'] = {\n history: false,\n memory: false,\n businessAgent: false,\n businessSetup: false,\n};\nconst SYSTEM_CLOCK: AgentClock = { now: () => Date.now() };\n\n/**\n * The key as a string: one conversation per agent, person, mode, business and thread. Encoded as a JSON array, so no\n * value can pass for another (a guest is `null`, never a subject named \"guest\"; a `|` in an id is just a character).\n */\nexport function agentKey(key: AgentKey, agent: string | null = null): string {\n return JSON.stringify([\n agent,\n key.subject,\n key.mode,\n key.scope ?? null,\n key.thread ?? 'chat',\n ]);\n}\n\nconst samePlace = (a: AgentPlace | null, b: AgentPlace | null) =>\n a?.screen === b?.screen &&\n (a?.entity?.type ?? null) === (b?.entity?.type ?? null) &&\n (a?.entity?.id ?? null) === (b?.entity?.id ?? null) &&\n JSON.stringify(a?.filters ?? null) === JSON.stringify(b?.filters ?? null);\n\n/** A session the runtime will use: an id, a secret, and `wss://` and `https://` addresses unless a leg is let off. */\nfunction usable(\n session: ConversationSession,\n insecure: AgentInsecureAddresses,\n): boolean {\n return (\n typeof session.id === 'string' &&\n session.id !== '' &&\n (insecure.realtime === true ||\n /^wss:\\/\\//i.test(session.realtime_url ?? '')) &&\n (insecure.turns === true || /^https:\\/\\//i.test(session.turns_url ?? '')) &&\n Boolean(session.client_secret)\n );\n}\n\n/** Whether this is a development build (React Native's `__DEV__`): what only a developer should read is said there. */\nconst devBuild = () => (globalThis as { __DEV__?: boolean }).__DEV__ === true;\n\n/** Once, as the runtime is made (once per app), outside development: plaintext would carry messages and the secret. */\nfunction warnInsecure(\n insecure: AgentInsecureAddresses,\n warn: (message: string, warning: AgentWarning) => void,\n): void {\n if (!(insecure.realtime || insecure.turns)) return;\n if ((globalThis as { __DEV__?: boolean }).__DEV__ === true) return;\n warn(\n '@vinaverse/client/agent: insecureAddresses lets sessions use plaintext ws:// or http:// addresses. For mocks and local development only.',\n { code: 'insecure_addresses' },\n );\n}\n\ninterface Entry {\n readonly key: string;\n readonly store: ConversationStore;\n readonly listeners: Set<() => void>;\n state: AgentConversationState;\n place: AgentPlace | null;\n told: AgentPlace | null;\n revision: number;\n /** A place being told (one `updateContext` in flight at a time), and whether a newer one waits behind it. */\n telling: boolean;\n queued: boolean;\n entryPoint: string | null;\n expiresAt: number | null;\n shown: number;\n started: boolean;\n suspended: boolean;\n sentOnce: Set<string>;\n /** Ends it at its session's end while no view shows it (when the app's timers run; `sweep` otherwise). */\n timer: ReturnType<typeof setTimeout> | undefined;\n /** Each reply's own session, so a thumbs rates the turn against the session it was given in. */\n readonly turns: Map<string, string>;\n /**\n * The session creation that could not reach the backend: asked again unchanged (its `openId`, its body) by the next\n * try, the person's too, for a day, so a creation whose answer was lost never opens a second session.\n */\n failedOpen:\n | { readonly request: AgentSessionRequest; readonly at: number }\n | undefined;\n}\n\n/** How long a failed session creation is asked again under its own `openId` (the gateway keeps one 24 hours). */\nconst OPEN_KEPT_MS = 24 * 3_600_000;\n/** Events kept while the analytics salt is read; the oldest go past it. */\nconst MAX_WAITING = 100;\n\nexport function createAgentRuntime(options: AgentRuntimeOptions): AgentRuntime {\n const { backend } = options;\n const policy: Required<AgentRetryPolicy> = {\n delays: options.retry?.delays ?? [500, 1500, 3500],\n isRetryable: options.retry?.isRetryable ?? retryable,\n };\n const clock = options.clock ?? SYSTEM_CLOCK;\n const keepAlive = options.keepAlive ?? 'session';\n const staleMs = options.statusStaleMs ?? 5 * 60_000;\n const insecure = options.insecureAddresses ?? {};\n warnInsecure(insecure, options.onWarning ?? ((m: string) => console.warn(m)));\n const live = new Map<string, Entry>();\n const current = new Map<string, string>();\n const listeners = new Set<() => void>();\n let status: { value: AgentStatus; at: number } | null = null;\n let reading: Promise<AgentStatus> | null = null;\n const NO_STATUS: AgentStatusState = {\n status: null,\n reading: false,\n failed: false,\n };\n let statusState = NO_STATUS;\n const setStatusState = (next: Omit<AgentStatusState, 'status'>) => {\n statusState = { status: status?.value ?? null, ...next };\n changed();\n };\n let sessionName: string | null = null;\n // Bumped by every sign-out: anything begun before it (a status read, a write to the device) lands nowhere.\n let generation = 0;\n const keyOf = (key: AgentKey) => agentKey(key, options.agent ?? null);\n const prefix = options.conversation?.persistenceKey ?? 'vinaverse.agent';\n const storage = guardedStorage(\n options.conversation?.persistence,\n prefix,\n () => generation,\n );\n const greetings = guardedStorage(\n options.greetingStorage,\n GREETED,\n () => generation,\n );\n\n const warn: (message: string, warning: AgentWarning) => void =\n options.onWarning ?? ((m: string) => console.warn(m));\n /** The app's callback runs isolated: what it throws is said through `onWarning`, never in the way of a frame. */\n const isolated = (what: 'onEvent' | 'onActivity', call: () => void) => {\n try {\n call();\n } catch (error) {\n warn(\n `@vinaverse/client/agent: the app's ${what} threw (${error instanceof Error ? error.message : String(error)}); the conversation went on.`,\n { code: 'callback_threw', callback: what },\n );\n }\n };\n\n // Analytics never sees a key, which names the person: a hash of it under the install's salt, kept in the app's\n // storage (a new one per process without storage). Events wait for the salt's first read.\n const saltStore =\n options.conversation?.persistence ?? options.greetingStorage;\n const saltKey = `${prefix}:salt`;\n let salt: string | null = null;\n const waiting: AgentEvent[] = [];\n const loadSalt = () => {\n if (!options.onEvent) return; // no analytics, nothing kept for it\n const settle = (kept: string | null | undefined) => {\n if (salt !== null) return;\n if (kept) salt = kept;\n else {\n salt = randomId().slice(3);\n void Promise.resolve(saltStore?.setItem(saltKey, salt)).catch(\n () => undefined,\n );\n }\n for (const event of waiting.splice(0)) deliver(event);\n };\n try {\n const got = saltStore?.getItem(saltKey);\n if (typeof got === 'string' || got == null) settle(got);\n else got.then(settle, () => settle(null));\n } catch {\n settle(null);\n }\n };\n const deliver = (event: AgentEvent) =>\n isolated('onEvent', () =>\n options.onEvent?.(\n event.key ? { ...event, key: hashKey(event.key, salt ?? '') } : event,\n ),\n );\n let dropping = false;\n const emit = (event: AgentEvent) => {\n if (!options.onEvent) return;\n if (salt !== null) return deliver(event);\n // A storage whose read never settles costs the oldest events, never memory.\n if (waiting.push(event) > MAX_WAITING) {\n waiting.shift();\n if (!dropping)\n warn(\n '@vinaverse/client/agent: the analytics salt is still being read from storage; the oldest events are dropped.',\n { code: 'events_dropped' },\n );\n dropping = true;\n }\n };\n loadSalt();\n const changed = () => {\n for (const l of [...listeners]) l();\n };\n const update = (entry: Entry, next: Partial<AgentConversationState>) => {\n entry.state = { ...entry.state, ...next };\n for (const l of [...entry.listeners]) l();\n };\n\n const end = (k: string) => {\n const entry = live.get(k);\n if (!entry) return;\n live.delete(k);\n clearTimeout(entry.timer);\n entry.store.dispose();\n emit({ type: 'conversation_ended', key: k });\n changed(); // the key's next conversation is another one\n };\n\n const patiently = <T>(\n run: () => Promise<T>,\n signal: AbortSignal | undefined,\n key: string,\n ) =>\n retrying(run, policy, signal, (attempt) =>\n emit({ type: 'session_retried', key, attempt }),\n );\n\n async function open(\n entry: Entry,\n key: AgentKey,\n request: SessionRequest,\n ): Promise<ConversationSession> {\n // Let go meanwhile (a start new, a sign-out): nothing to open.\n if (live.get(entry.key) !== entry) throw new AgentRefusal('unavailable');\n // A creation that could not reach the backend is asked again as it was; any other is a new one, with its own id\n // (a first open, a resume, continue-here, a rollover), the same through its retries. The runtime keeps which\n // conversation the key continues: the app's adapter is a plain call.\n const held =\n entry.failedOpen && clock.now() - entry.failedOpen.at < OPEN_KEPT_MS\n ? entry.failedOpen\n : undefined;\n entry.failedOpen = undefined;\n const asked: AgentSessionRequest = held\n ? {\n ...held.request,\n ...(request.signal ? { signal: request.signal } : {}),\n }\n : {\n ...request,\n conversationId:\n request.conversationId ?? current.get(entry.key) ?? null,\n key,\n openId: `op_${randomId().slice(3)}`,\n agent: options.agent ?? null,\n place: entry.place,\n placeRevision: ++entry.revision,\n entryPoint: entry.entryPoint,\n };\n const { conversationId, openId, place: told } = asked;\n let session: ConversationSession;\n try {\n session = await patiently(\n () => backend.openSession(asked),\n request.signal,\n entry.key,\n );\n if (!usable(session, insecure))\n throw new AgentRefusal('unavailable', {\n reason: 'invalid_session',\n message:\n 'Unusable session: an id, a secret, wss:// and https:// addresses.',\n });\n } catch (error) {\n if (live.get(entry.key) === entry) {\n const failure: AgentFailure = isRefusal(error)\n ? error.kind === 'ended' && conversationId !== null\n ? 'ended'\n : 'unavailable'\n : policy.isRetryable(error)\n ? 'unreachable'\n : 'unavailable';\n const reason = reasonOf(error, failure);\n const code = isRefusal(error) ? error.code : codeOf(error);\n if (failure === 'unreachable') {\n const { signal, ...again } = asked;\n void signal; // kept without its signal: the next try brings its own\n entry.failedOpen = { request: again, at: held?.at ?? clock.now() };\n }\n // An open the backend could not settle is said as unavailable, never retried, its id kept for support.\n const unsettled =\n reason === 'unknown_open'\n ? String(field(error, 'openId') ?? openId)\n : null;\n update(entry, { failure, reason, code, openId: unsettled });\n emit({ type: 'session_failed', key: entry.key, failure, reason });\n }\n throw error;\n }\n // Let go while the backend answered (a start new, a sign-out): touch nothing, or the old conversation would be\n // pinned again as the key's current one.\n if (live.get(entry.key) !== entry) throw new AgentRefusal('unavailable');\n entry.told = told;\n entry.expiresAt = session.expires_at\n ? Date.parse(session.expires_at)\n : null;\n if (session.conversation_id)\n current.set(entry.key, session.conversation_id);\n const name = session.agent?.display_name?.trim();\n if (name && name !== sessionName) {\n sessionName = name;\n changed();\n }\n update(entry, {\n failure: null,\n reason: null,\n code: null,\n openId: null,\n sessionId: session.id,\n conversationId: session.conversation_id ?? conversationId,\n moved: !samePlace(told, entry.place),\n });\n emit({\n type: conversationId === null ? 'session_opened' : 'session_resumed',\n key: entry.key,\n sessionId: session.id,\n ...(entry.entryPoint ? { from: entry.entryPoint } : {}),\n });\n return session;\n }\n\n /** Where a key's conversation is kept on the device, with `persistence`. */\n const kept = (k: string) => `${prefix}.${k}`;\n\n /**\n * Everything of the person on this device goes; the backend is told to end the sessions at the same time, never\n * after a slow storage. A write, a read or a status from before lands nowhere (the generation).\n */\n const signOut = async (erasing: boolean) => {\n generation++;\n if (erasing) salt = null; // events wait for the next install's salt\n for (const entry of live.values()) {\n clearTimeout(entry.timer);\n entry.store.clear();\n }\n const known = new Set([...live.keys(), ...current.keys()]);\n live.clear();\n current.clear();\n sessionName = null;\n status = null;\n reading = null;\n statusState = NO_STATUS;\n changed();\n // The people this device knew, for the greeting records alpha.5 and alpha.6 named after them.\n const pairs: [unknown, unknown][] = [];\n await Promise.all([\n backend.endSessions?.().catch(() => undefined),\n storage?.purge(\n [`${prefix}.`],\n (keys) => {\n const all = new Set([...keys, ...[...known].map(kept)]);\n for (const key of all) {\n const t = tupleOf(key, prefix);\n if (t) pairs.push([t[1], t[2]]);\n }\n return [\n ...all,\n ...legacyTranscripts(all, prefix),\n ...(options.legacyKeys ?? []),\n ];\n },\n `${GREETED}.`,\n ),\n ]);\n if (!erasing) return;\n await Promise.all([\n Promise.resolve(saltStore?.removeItem(saltKey)).catch(() => undefined),\n greetings?.purge([`${GREETED}.`, `${GREETED_BEFORE}.`], (keys) => {\n for (const key of keys) {\n const t = tupleOf(key, GREETED);\n if (t) pairs.push([t[0], t[1]]);\n }\n return [...legacyGreetings(pairs), ...(options.legacyKeys ?? [])];\n }),\n ]);\n loadSalt(); // a new install's, as far as analytics can tell\n };\n\n /** The key's conversation is no longer this device's: its pinned id and its kept transcript go. */\n const forget = (k: string) => {\n current.delete(k);\n const entry = live.get(k);\n if (entry) {\n entry.store.clear();\n end(k);\n } else void storage?.removeItem(kept(k));\n };\n\n const activity = (entry: Entry, a: ConversationActivity) => {\n const sessionId = entry.state.sessionId;\n if (a.type === 'reply_completed' && sessionId) {\n entry.turns.set(a.turnId, sessionId);\n update(entry, {}); // the reply can be rated now\n }\n emit({\n type: a.type,\n key: entry.key,\n ...(sessionId ? { sessionId } : {}),\n ...(a.type === 'reply_completed' ? { turnId: a.turnId } : {}),\n ...(a.type === 'card_shown' ? { cardId: a.cardId, kind: a.kind } : {}),\n });\n };\n\n function make(key: AgentKey): Entry {\n const k = keyOf(key);\n const own = options.conversation ?? {};\n const refresh = backend.refreshSecret?.bind(backend);\n const entry: Entry = {\n key: k,\n store: createConversation({\n ...own,\n ...(storage\n ? {\n persistence: storage,\n persistenceKey: kept(k),\n }\n : {}),\n onActivity: (a) => {\n activity(entry, a);\n isolated('onActivity', () => own.onActivity?.(a));\n },\n getSession: (request) => open(entry, key, request),\n ...(refresh\n ? {\n // A refusal (`session_closed`) is the store's cue to go on in a new session, never a fault.\n refreshSecret: (id: string) =>\n patiently(() => refresh(id), undefined, k).catch((error) => {\n throw isRefusal(error)\n ? new VinaverseClientError(\n 'needs_new_session',\n error.message,\n )\n : error;\n }),\n }\n : {}),\n clock,\n onError: (error) => {\n // A refusal is said through the state, and a session the server closed is rolled over: neither is a fault.\n if (!isRefusal(error) && codeOf(error) !== 'needs_new_session')\n own.onError?.(error);\n },\n }),\n listeners: new Set(),\n state: {\n failure: null,\n reason: null,\n code: null,\n moved: false,\n ratings: new Map(),\n sessionId: null,\n conversationId: current.get(k) ?? null,\n openId: null,\n },\n place: null,\n told: null,\n revision: 0,\n telling: false,\n queued: false,\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. One `updateContext` is in\n * flight per conversation: a place told meanwhile (`show` and `tell` in one move, or rapid moves) waits, only the\n * newest, and goes with the next revision when the one in flight settles.\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 if (entry.telling) {\n entry.queued = true; // the newest place goes when the one in flight settles\n return;\n }\n entry.telling = true;\n const asked = generation;\n const current = () =>\n asked === generation &&\n live.get(entry.key) === entry &&\n entry.state.sessionId === sessionId;\n // The one in flight settled: the place told meanwhile, if any and still this conversation's, goes next.\n const settle = () => {\n entry.telling = false;\n if (!entry.queued) return;\n entry.queued = false;\n if (asked === generation && live.get(entry.key) === entry)\n tell(entry, {});\n };\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 // A backend that throws as it is called (not in its promise) is a refusal too: settled like one, so the\n // next place is never left waiting behind a telling that never ends.\n let told: Promise<void>;\n try {\n told = updateContext(sessionId, place ?? CLEARED, revision);\n } catch (error) {\n told = Promise.reject(error);\n }\n told.then(\n () => {\n if (current() && entry.revision === revision) {\n entry.told = place;\n update(entry, { moved: !samePlace(entry.told, entry.place) });\n emit({ type: 'context_updated', key: entry.key, sessionId });\n }\n settle();\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 if (typeof theirs === 'number' && theirs >= entry.revision)\n entry.revision = theirs;\n send(true);\n return;\n }\n // Not served, or refused: the question about this place stays the way to say it. A refusal that is no\n // conflict (a 400 is the kit's or the backend's mistake, never the person's) is said in development.\n if (!conflict && devBuild()) {\n const status = field(error, 'status');\n warn(\n `@vinaverse/client/agent: updateContext was refused${typeof status === 'number' ? ` (${status})` : ''}: ${error instanceof Error ? error.message : String(error)}. The new place is offered as a question instead.`,\n { code: 'context_refused' },\n );\n }\n settle();\n },\n );\n };\n send(false);\n };\n\n function handle(entry: Entry): AgentConversation {\n return {\n key: entry.key,\n store: entry.store,\n show(at = {}) {\n // Let go meanwhile, or past its session's end with no view: nothing to show; the key's next one is read anew.\n if (live.get(entry.key) !== entry) return () => undefined;\n if (entry.shown === 0 && over(entry)) {\n end(entry.key);\n return () => undefined;\n }\n entry.shown++;\n clearTimeout(entry.timer);\n entry.timer = undefined;\n if (entry.suspended) {\n entry.suspended = false;\n entry.store.setForeground(true);\n }\n tell(entry, at);\n if (!entry.started) {\n entry.started = true;\n entry.store.start();\n }\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry.shown--;\n if (entry.shown > 0 || live.get(entry.key) !== entry) return;\n if (\n keepAlive === 'view' ||\n NOT_KEPT.has(entry.store.getSnapshot().status) ||\n entry.expiresAt === null ||\n over(entry)\n ) {\n end(entry.key);\n return;\n }\n entry.suspended = true;\n entry.store.setForeground(false);\n expireLater(entry);\n };\n },\n tell: (at) => tell(entry, at),\n getState: () => entry.state,\n subscribe(listener) {\n entry.listeners.add(listener);\n return () => entry.listeners.delete(listener);\n },\n retry() {\n update(entry, {\n failure: null,\n reason: null,\n code: null,\n openId: null,\n });\n entry.store.start();\n },\n canRate: (turnId) => entry.turns.has(turnId),\n rate(turnId, rating) {\n // The session the reply was given in, never the one open now: a reply restored from before is not rated.\n const sessionId = entry.turns.get(turnId);\n if (!sessionId || entry.state.ratings.get(turnId) === rating) return;\n update(entry, {\n ratings: new Map(entry.state.ratings).set(turnId, rating),\n });\n emit({ type: 'rated', key: entry.key, sessionId, turnId, rating });\n void backend\n .sendFeedback?.({ sessionId, turnId, rating })\n .catch(() => undefined);\n },\n sendOnce(text) {\n if (entry.sentOnce.has(text)) return;\n entry.sentOnce.add(text);\n entry.store.send(text);\n },\n };\n }\n\n const handles = new WeakMap<Entry, AgentConversation>();\n\n const lookup = (key: AgentKey) => {\n const k = keyOf(key);\n let entry = live.get(k);\n if (!entry) {\n entry = make(key);\n live.set(k, entry);\n }\n let h = handles.get(entry);\n if (!h) {\n h = handle(entry);\n handles.set(entry, h);\n }\n return h;\n };\n\n return {\n conversation(key) {\n const k = keyOf(key);\n const entry = live.get(k);\n if (entry && entry.shown === 0 && over(entry)) end(k);\n return lookup(key);\n },\n peek: lookup,\n startNew(key) {\n const k = keyOf(key);\n current.delete(k);\n end(k);\n },\n dispose(key) {\n end(keyOf(key));\n },\n forget(key) {\n forget(keyOf(key));\n },\n sweep() {\n for (const entry of [...live.values()])\n if (entry.shown === 0 && over(entry)) end(entry.key);\n },\n continue(key, conversationId) {\n const k = keyOf(key);\n if (current.get(k) !== conversationId) {\n // What the device kept is another conversation's: forgotten, so the resumed transcript is the only one drawn.\n forget(k);\n current.set(k, conversationId);\n }\n return lookup(key);\n },\n async signOut() {\n await signOut(false);\n },\n async erase() {\n await signOut(true);\n },\n async deleteConversation(key, conversationId) {\n if (!backend.deleteConversation)\n throw new Error(\n '@vinaverse/client/agent: deleteConversation needs AgentBackend.deleteConversation.',\n );\n await backend.deleteConversation(conversationId);\n const k = keyOf(key);\n const continued =\n current.get(k) ??\n live.get(k)?.store.getSnapshot().conversationId ??\n null;\n if (continued === conversationId) forget(k);\n },\n greetings: greetings ?? null,\n status() {\n if (status && clock.now() - status.at < staleMs)\n return Promise.resolve(status.value);\n if (reading) return reading;\n const asked = generation;\n const read = readStatus(backend).then(\n (value) => {\n if (asked !== generation) return value; // read for the person before a sign-out: not kept\n reading = null;\n status = { value, at: clock.now() };\n setStatusState({ reading: false, failed: false });\n return value;\n },\n (error: unknown) => {\n if (asked === generation) {\n reading = null;\n setStatusState({ reading: false, failed: true });\n }\n throw error;\n },\n );\n reading = read;\n setStatusState({ reading: true, failed: statusState.failed });\n return read;\n },\n getStatus: () => status?.value ?? null,\n getStatusState: () => statusState,\n backend,\n epoch: () => generation,\n getName: () => sessionName ?? status?.value.displayName ?? null,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n emit,\n };\n}\n\n/**\n * The app's storage as the runtime's stores use it: writes and removals for a key run in the order they were made, a\n * read waits for them, a write begun before a sign-out lands nowhere, and every key written is listed (under\n * `<prefix>:index`), so a sign-out removes all of them, closed conversations' too.\n */\nfunction guardedStorage(\n raw: ConversationPersistence | undefined,\n prefix: string,\n generation: () => number,\n):\n | (ConversationPersistence & {\n purge(\n under: readonly string[],\n extra?: (keys: ReadonlySet<string>) => Iterable<string>,\n keep?: string,\n ): Promise<void>;\n })\n | undefined {\n if (!raw) return undefined;\n const indexKey = `${prefix}:index`;\n const chains = new Map<string, Promise<unknown>>();\n const pending = new Map<string, number>();\n const queued = <T>(key: string, op: () => T | Promise<T>): Promise<T> => {\n pending.set(key, (pending.get(key) ?? 0) + 1);\n const run = (chains.get(key) ?? Promise.resolve()).then(op);\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n chains.set(key, settled);\n void settled.then(() => {\n const left = (pending.get(key) ?? 1) - 1;\n if (left > 0) pending.set(key, left);\n else {\n pending.delete(key);\n if (chains.get(key) === settled) chains.delete(key);\n }\n });\n return run;\n };\n const safe = <T>(p: Promise<T>) => p.catch(() => undefined);\n const readIndex = async (): Promise<Set<string>> => {\n try {\n const value = await raw.getItem(indexKey);\n const list: unknown = value ? JSON.parse(value) : [];\n return new Set(\n Array.isArray(list)\n ? list.filter((k): k is string => typeof k === 'string')\n : [],\n );\n } catch {\n return new Set();\n }\n };\n const listed = new Set<string>();\n const list = (key: string) => {\n if (listed.has(key)) return;\n listed.add(key);\n void safe(\n queued(indexKey, async () => {\n const all = await readIndex();\n if (all.has(key)) return;\n all.add(key);\n await raw.setItem(indexKey, JSON.stringify([...all]));\n }),\n );\n };\n return {\n getItem(key) {\n // A read that finishes after a sign-out answers nothing: the next person never sees the last one's record.\n const asked = generation();\n const read = pending.has(key)\n ? queued(key, () => raw.getItem(key))\n : raw.getItem(key);\n if (typeof read === 'string' || read === null) return read;\n return Promise.resolve(read).then(\n (v) => (asked === generation() ? (v ?? null) : null),\n () => null,\n );\n },\n setItem(key, value) {\n const asked = generation();\n return safe(\n queued(key, () => {\n if (asked !== generation()) return;\n list(key);\n return raw.setItem(key, value);\n }),\n );\n },\n removeItem: (key) => safe(queued(key, () => raw.removeItem(key))),\n /**\n * Everything kept: the index, what the app's storage finds under `under` (`removePrefix`, else `keys`), and `extra`\n * (older key shapes). Nothing under `keep` goes, so `removePrefix` is used only for a prefix that cannot reach it.\n */\n async purge(\n under: readonly string[],\n extra: (keys: ReadonlySet<string>) => Iterable<string> = () => [],\n keep?: string,\n ) {\n const all = new Set([...listed, ...(await readIndex())]);\n listed.clear();\n for (const p of under)\n try {\n if (raw.removePrefix && !keep?.startsWith(p))\n await raw.removePrefix(p);\n else if (raw.keys)\n for (const key of await raw.keys(p))\n if (!keep || !key.startsWith(keep)) all.add(key);\n } catch {\n // storage that cannot list: the index and the known shapes still go\n }\n for (const key of extra(all)) all.add(key);\n await Promise.all(\n [...all].map((key) => safe(queued(key, () => raw.removeItem(key)))),\n );\n await safe(queued(indexKey, () => raw.removeItem(indexKey)));\n },\n };\n}\n\nasync function readStatus(backend: AgentBackend): Promise<AgentStatus> {\n const read: AgentStatusRead = backend.status\n ? await backend.status()\n : { available: true };\n const available = read.available === true;\n const features = read.features ?? NO_FEATURES;\n return {\n available,\n launcher: available && read.launcher === true,\n displayName: read.displayName?.trim() || null,\n avatarUrl: read.avatarUrl?.startsWith('https://') ? read.avatarUrl : null,\n features: {\n history: available && features.history === true,\n memory: available && features.memory === true,\n businessAgent: available && features.businessAgent === true,\n businessSetup: available && features.businessSetup === true,\n },\n };\n}\n\n/**\n * An `AgentRefusal`, also one made by another copy of this package (the mock in `@vinaverse/client/testing`, the\n * backend helpers in `@vinaverse/client/backend`, a second install): recognised by its name and kind, not its class.\n */\nexport function isRefusal(error: unknown): error is AgentRefusal {\n return (\n error instanceof AgentRefusal ||\n (field(error, 'name') === 'AgentRefusal' &&\n (field(error, 'kind') === 'ended' ||\n field(error, 'kind') === 'unavailable'))\n );\n}\n\nconst field = (error: unknown, name: string): unknown =>\n typeof error === 'object' && error !== null\n ? (error as Record<string, unknown>)[name]\n : undefined;\n\nconst retryable = (error: unknown) => field(error, 'retryable') === true;\n\nconst REASONS = new Set<AgentFailureReason>([\n 'ended',\n 'not_found',\n 'expired',\n 'mismatch',\n 'completed',\n 'forbidden',\n 'conflict',\n 'unknown_open',\n 'auth',\n 'off',\n 'rate_limited',\n 'network',\n 'server',\n 'invalid_session',\n 'unknown',\n]);\n\nfunction reasonOf(error: unknown, failure: AgentFailure): AgentFailureReason {\n if (isRefusal(error)) return error.reason;\n const given = field(error, 'reason');\n if (typeof given === 'string' && REASONS.has(given as AgentFailureReason))\n return given as AgentFailureReason;\n const status = field(error, 'status');\n if (status === 401 || status === 403) return 'auth';\n if (status === 429) return 'rate_limited';\n if (typeof status === 'number' && status >= 500) return 'server';\n return failure === 'unreachable' ? 'network' : 'unknown';\n}\n\nfunction codeOf(error: unknown): string | null {\n const code = field(error, 'code') ?? field(error, 'outcome');\n return typeof code === 'string' ? code : null;\n}\n\n/** Tries again after each delay while the policy says so; an outage is said, never answered with a new conversation. */\nasync function retrying<T>(\n run: () => Promise<T>,\n policy: Required<AgentRetryPolicy>,\n signal: AbortSignal | undefined,\n onRetry: (attempt: number) => void,\n): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await run();\n } catch (error) {\n const delay = policy.delays[attempt];\n if (delay === undefined || !policy.isRetryable(error) || signal?.aborted)\n throw error;\n // The server's own wait (`Retry-After`), when longer than the policy's.\n const asked = field(error, 'retryAfterMs');\n const wait =\n typeof asked === 'number' && asked > delay\n ? Math.min(asked, 60_000) // never stalled by a bad `Retry-After`\n : delay;\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', stop);\n resolve();\n }, wait);\n function stop() {\n clearTimeout(timer);\n reject(error);\n }\n signal?.addEventListener('abort', stop, { once: true });\n });\n onRetry(attempt + 1);\n }\n }\n}\n","// @vinaverse/client/history: a person's past conversations with the agent (C2), through the tenant's backend\n// (`AgentBackend.listConversations`, `readConversation`): the list, newest activity first, a page at a time; a past\n// conversation's transcript, newest page first, earlier pages prepended; delete through the runtime. No React: the\n// kits bind to it. Nothing begun before a sign-out lands after it (the runtime's `epoch`).\nimport {\n type AgentBackend,\n type AgentFailureReason,\n type AgentKey,\n type AgentRuntime,\n isRefusal,\n} from '../agent/runtime.js';\nimport type {\n CardItem,\n MessageItem,\n TimelineItem,\n} from '../conversation/view.js';\nimport type { Schemas } from '../events.js';\n\nexport type ConversationSummary = Schemas['ConversationSummary'];\ntype HistoryItem = Schemas['TimelineItem'];\n\n/**\n * The key a past conversation continues under for this person: its side and business as it was bound when it started\n * (`experience_mode`, `business_scope_id`), the `thread` given (default `chat`). For `runtime.continue(key, id)` and\n * `deleteConversation(key, id)`, so the device forgets it only where that key still continues it.\n */\nexport function continueKey(\n conversation: ConversationSummary,\n subject: string | null,\n thread?: string,\n): AgentKey {\n return {\n subject,\n mode: conversation.experience_mode,\n scope: conversation.business_scope_id ?? null,\n ...(thread ? { thread } : {}),\n };\n}\n\n/**\n * A past conversation's items as the kits draw them: messages as sent (an `assistant` reply is the agent's, cut-off\n * replies and refusals marked), cards restored (drawn as they were, taking no answer or action), a proposal with the\n * outcome it had. Keyed by the server's ids, so pages merge without doubles.\n */\nexport function historyItems(data: readonly HistoryItem[]): TimelineItem[] {\n return data.map((item, seq): TimelineItem => {\n if (item.type === 'card') {\n const outcome = item.proposal_outcome;\n const card: CardItem = {\n type: 'card',\n key: item.card.id,\n busy: false,\n restored: true,\n card: {\n id: item.card.id,\n kind: item.card.kind,\n card: item.card as unknown as Readonly<Record<string, unknown>>,\n locked: [],\n turnId: item.turn_id,\n outcome: outcome && outcome !== 'pending' ? outcome : null,\n seq,\n },\n };\n return card;\n }\n const message: MessageItem = {\n type: 'message',\n key: `h:${item.id}`,\n role: item.role === 'assistant' ? 'agent' : item.role,\n text: item.text,\n state: 'sent',\n ...(item.interrupted ? { partial: 'interrupted' as const } : {}),\n ...(item.refusal ? { refusal: true as const } : {}),\n };\n return message;\n });\n}\n\n/** Why a page could not be read, as the runtime says it. */\nfunction reasonOf(error: unknown): AgentFailureReason {\n if (isRefusal(error)) return error.reason;\n const given = (error as { reason?: unknown } | null)?.reason;\n return typeof given === 'string' ? (given as AgentFailureReason) : 'unknown';\n}\n\n/**\n * The cursor restart (`vinaverse.agent-backend/1`): a page asked with a cursor, refused `unavailable`, not retryable,\n * with the gateway's `invalid_request`, had a cursor the gateway no longer takes (stale, or of other filters). Asked\n * again from the first page, once. Any other refusal is said as it is.\n */\nfunction staleCursor(error: unknown): boolean {\n const e = error as {\n outcome?: unknown;\n gatewayCode?: unknown;\n retryable?: unknown;\n } | null;\n return (\n e?.outcome === 'unavailable' &&\n e.gatewayCode === 'invalid_request' &&\n e.retryable === false\n );\n}\n\n/** A paged store: one page read at a time, dropped when it lands after a newer read or a sign-out. */\nfunction paged<S extends { readonly loading: boolean }>(\n runtime: AgentRuntime,\n empty: S,\n) {\n let state = empty;\n let epoch = runtime.epoch();\n let asked = 0;\n const listeners = new Set<() => void>();\n const set = (next: Partial<S>) => {\n state = { ...state, ...next };\n for (const l of [...listeners]) l();\n };\n // A sign-out empties what the last person had, as soon as anyone listens again.\n const fresh = () => {\n if (runtime.epoch() === epoch) return;\n epoch = runtime.epoch();\n asked++;\n state = empty;\n };\n let off: (() => void) | null = null;\n return {\n get: () => {\n fresh();\n return state;\n },\n set,\n subscribe(listener: () => void) {\n listeners.add(listener);\n off ??= runtime.subscribe(() => {\n const before = state;\n fresh();\n if (state !== before) for (const l of [...listeners]) l();\n });\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n off?.();\n off = null;\n }\n };\n },\n /** Reads a page; `apply` lands only for the newest read, under the same person. */\n read<T>(\n call: () => Promise<T>,\n apply: (value: T) => void,\n failed: (error: unknown) => void,\n ) {\n fresh();\n const mine = ++asked;\n const under = epoch;\n set({ loading: true } as Partial<S>);\n call().then(\n (value) => {\n if (mine === asked && under === runtime.epoch()) apply(value);\n },\n (error: unknown) => {\n if (mine === asked && under === runtime.epoch()) failed(error);\n },\n );\n },\n };\n}\n\nexport interface AgentHistoryState {\n readonly conversations: readonly ConversationSummary[];\n /** A page is being read. */\n readonly loading: boolean;\n /** Why the last page could not be read; null when it was. `off` when the backend serves no history. */\n readonly failure: AgentFailureReason | null;\n /** Every page is read. */\n readonly done: boolean;\n /** The first page was asked for. */\n readonly started: boolean;\n}\n\nexport interface AgentHistory {\n getSnapshot(): AgentHistoryState;\n subscribe(listener: () => void): () => void;\n /** Reads the first page anew: the first time, after a failure, or to see what changed. */\n refresh(): void;\n /** The next older page, when there is one and none is being read. */\n loadMore(): void;\n /** Reads again the page that failed: the first (as `refresh`), or the next. */\n retry(): void;\n /**\n * Deletes a past conversation (the runtime's `deleteConversation` for the key that holds it, so the device forgets\n * it only where the key still continues it) and drops its row. One already gone (`not_found`) is dropped too.\n */\n remove(key: AgentKey, conversationId: string): Promise<void>;\n}\n\nexport interface AgentHistoryOptions {\n readonly runtime: AgentRuntime;\n /** Default: the runtime's. */\n readonly backend?: AgentBackend;\n /** The app's side: `customer` or `business`. */\n readonly mode: string;\n /** The business acted for, with `business`. */\n readonly scope?: string | null;\n /** The agent, for a backend that serves more than one. */\n readonly agent?: string | null;\n /** Conversations per page (1–50). Default 20. */\n readonly pageSize?: number;\n}\n\nconst NO_HISTORY: AgentHistoryState = {\n conversations: [],\n loading: false,\n failure: null,\n done: false,\n started: false,\n};\n\n/** A person's past conversations, newest activity first. */\nexport function createAgentHistory(options: AgentHistoryOptions): AgentHistory {\n const { runtime } = options;\n const backend = options.backend ?? runtime.backend;\n const store = paged(runtime, NO_HISTORY);\n let cursor: string | null = null;\n let restarted = false;\n const page = (from: string | null) => {\n const list = backend.listConversations?.bind(backend);\n if (!list) {\n store.set({ started: true, failure: 'off', done: true });\n return;\n }\n store.read(\n () =>\n list({\n mode: options.mode,\n scope: options.scope ?? null,\n agent: options.agent ?? null,\n limit: options.pageSize ?? 20,\n cursor: from,\n }),\n (got) => {\n const known = new Set(\n from ? store.get().conversations.map((c) => c.id) : [],\n );\n cursor = got.next_cursor;\n store.set({\n conversations: [\n ...(from ? store.get().conversations : []),\n ...got.data.filter((c) => !known.has(c.id)),\n ],\n loading: false,\n failure: null,\n done: cursor === null,\n });\n },\n (error) => {\n if (from !== null && staleCursor(error) && !restarted) {\n restarted = true;\n cursor = null;\n page(null);\n return;\n }\n store.set({ loading: false, failure: reasonOf(error) });\n },\n );\n };\n const refresh = () => {\n cursor = null;\n restarted = false;\n store.set({ started: true });\n page(null);\n };\n const loadMore = () => {\n const s = store.get();\n if (!s.started || s.loading || s.done || cursor === null) return;\n page(cursor);\n };\n return {\n getSnapshot: store.get,\n subscribe: store.subscribe,\n refresh,\n loadMore,\n retry: () => (cursor === null ? refresh() : loadMore()),\n async remove(key, conversationId) {\n try {\n await runtime.deleteConversation(key, conversationId);\n } catch (error) {\n if (!(isRefusal(error) && error.reason === 'not_found')) throw error;\n }\n store.set({\n conversations: store\n .get()\n .conversations.filter((c) => c.id !== conversationId),\n });\n },\n };\n}\n\nexport interface AgentTranscriptState {\n /** The conversation's items, oldest first, as the kits draw them (`historyItems`). */\n readonly items: readonly TimelineItem[];\n readonly loading: boolean;\n /** Why the last page could not be read: `not_found` (deleted, or never theirs), `expired`, … */\n readonly failure: AgentFailureReason | null;\n /** Nothing earlier to read. */\n readonly done: boolean;\n readonly started: boolean;\n}\n\nexport interface AgentTranscript {\n getSnapshot(): AgentTranscriptState;\n subscribe(listener: () => void): () => void;\n /** Reads the newest page anew. */\n load(): void;\n /** The page before the earliest read, prepended. */\n loadEarlier(): void;\n /** Reads again the page that failed: the newest (as `load`), or the earlier one. */\n retry(): void;\n}\n\nexport interface AgentTranscriptOptions {\n readonly runtime: AgentRuntime;\n /** Default: the runtime's. */\n readonly backend?: AgentBackend;\n readonly conversationId: string;\n /** Items per page. Default 30. */\n readonly pageSize?: number;\n}\n\nconst NO_TRANSCRIPT: AgentTranscriptState = {\n items: [],\n loading: false,\n failure: null,\n done: false,\n started: false,\n};\n\n/** A past conversation's transcript, read-only: newest page first, earlier pages prepended. */\nexport function createAgentTranscript(\n options: AgentTranscriptOptions,\n): AgentTranscript {\n const { runtime } = options;\n const backend = options.backend ?? runtime.backend;\n const store = paged(runtime, NO_TRANSCRIPT);\n let cursor: string | null = null;\n let restarted = false;\n const page = (from: string | null) => {\n const read = backend.readConversation?.bind(backend);\n if (!read) {\n store.set({ started: true, failure: 'off', done: true });\n return;\n }\n store.read(\n () =>\n read(options.conversationId, {\n limit: options.pageSize ?? 30,\n cursor: from,\n }),\n (got) => {\n const earlier = historyItems(got.data);\n const held = from ? store.get().items : [];\n const keys = new Set(held.map((i) => i.key));\n cursor = got.next_cursor;\n store.set({\n items: [...earlier.filter((i) => !keys.has(i.key)), ...held],\n loading: false,\n failure: null,\n done: cursor === null,\n });\n },\n (error) => {\n // An earlier page's cursor went stale: read back from the newest page, once.\n if (from !== null && staleCursor(error) && !restarted) {\n restarted = true;\n cursor = null;\n page(null);\n return;\n }\n store.set({ loading: false, failure: reasonOf(error) });\n },\n );\n };\n const load = () => {\n cursor = null;\n restarted = false;\n store.set({ started: true });\n page(null);\n };\n const loadEarlier = () => {\n const s = store.get();\n if (!s.started || s.loading || s.done || cursor === null) return;\n page(cursor);\n };\n return {\n getSnapshot: store.get,\n subscribe: store.subscribe,\n load,\n loadEarlier,\n retry: () => (cursor === null ? load() : loadEarlier()),\n };\n}\n"]}
@@ -0,0 +1,91 @@
1
+ import { h as AgentFailureReason, j as AgentKey, o as AgentRuntime, A as AgentBackend } from '../runtime-BR2lS_Vg.cjs';
2
+ import { T as TimelineItem } from '../store-CxoHwd64.cjs';
3
+ import { S as Schemas } from '../session-D0ijOQX3.cjs';
4
+
5
+ type ConversationSummary = Schemas['ConversationSummary'];
6
+ type HistoryItem = Schemas['TimelineItem'];
7
+ /**
8
+ * The key a past conversation continues under for this person: its side and business as it was bound when it started
9
+ * (`experience_mode`, `business_scope_id`), the `thread` given (default `chat`). For `runtime.continue(key, id)` and
10
+ * `deleteConversation(key, id)`, so the device forgets it only where that key still continues it.
11
+ */
12
+ declare function continueKey(conversation: ConversationSummary, subject: string | null, thread?: string): AgentKey;
13
+ /**
14
+ * A past conversation's items as the kits draw them: messages as sent (an `assistant` reply is the agent's, cut-off
15
+ * replies and refusals marked), cards restored (drawn as they were, taking no answer or action), a proposal with the
16
+ * outcome it had. Keyed by the server's ids, so pages merge without doubles.
17
+ */
18
+ declare function historyItems(data: readonly HistoryItem[]): TimelineItem[];
19
+ interface AgentHistoryState {
20
+ readonly conversations: readonly ConversationSummary[];
21
+ /** A page is being read. */
22
+ readonly loading: boolean;
23
+ /** Why the last page could not be read; null when it was. `off` when the backend serves no history. */
24
+ readonly failure: AgentFailureReason | null;
25
+ /** Every page is read. */
26
+ readonly done: boolean;
27
+ /** The first page was asked for. */
28
+ readonly started: boolean;
29
+ }
30
+ interface AgentHistory {
31
+ getSnapshot(): AgentHistoryState;
32
+ subscribe(listener: () => void): () => void;
33
+ /** Reads the first page anew: the first time, after a failure, or to see what changed. */
34
+ refresh(): void;
35
+ /** The next older page, when there is one and none is being read. */
36
+ loadMore(): void;
37
+ /** Reads again the page that failed: the first (as `refresh`), or the next. */
38
+ retry(): void;
39
+ /**
40
+ * Deletes a past conversation (the runtime's `deleteConversation` for the key that holds it, so the device forgets
41
+ * it only where the key still continues it) and drops its row. One already gone (`not_found`) is dropped too.
42
+ */
43
+ remove(key: AgentKey, conversationId: string): Promise<void>;
44
+ }
45
+ interface AgentHistoryOptions {
46
+ readonly runtime: AgentRuntime;
47
+ /** Default: the runtime's. */
48
+ readonly backend?: AgentBackend;
49
+ /** The app's side: `customer` or `business`. */
50
+ readonly mode: string;
51
+ /** The business acted for, with `business`. */
52
+ readonly scope?: string | null;
53
+ /** The agent, for a backend that serves more than one. */
54
+ readonly agent?: string | null;
55
+ /** Conversations per page (1–50). Default 20. */
56
+ readonly pageSize?: number;
57
+ }
58
+ /** A person's past conversations, newest activity first. */
59
+ declare function createAgentHistory(options: AgentHistoryOptions): AgentHistory;
60
+ interface AgentTranscriptState {
61
+ /** The conversation's items, oldest first, as the kits draw them (`historyItems`). */
62
+ readonly items: readonly TimelineItem[];
63
+ readonly loading: boolean;
64
+ /** Why the last page could not be read: `not_found` (deleted, or never theirs), `expired`, … */
65
+ readonly failure: AgentFailureReason | null;
66
+ /** Nothing earlier to read. */
67
+ readonly done: boolean;
68
+ readonly started: boolean;
69
+ }
70
+ interface AgentTranscript {
71
+ getSnapshot(): AgentTranscriptState;
72
+ subscribe(listener: () => void): () => void;
73
+ /** Reads the newest page anew. */
74
+ load(): void;
75
+ /** The page before the earliest read, prepended. */
76
+ loadEarlier(): void;
77
+ /** Reads again the page that failed: the newest (as `load`), or the earlier one. */
78
+ retry(): void;
79
+ }
80
+ interface AgentTranscriptOptions {
81
+ readonly runtime: AgentRuntime;
82
+ /** Default: the runtime's. */
83
+ readonly backend?: AgentBackend;
84
+ readonly conversationId: string;
85
+ /** Items per page. Default 30. */
86
+ readonly pageSize?: number;
87
+ }
88
+ /** A past conversation's transcript, read-only: newest page first, earlier pages prepended. */
89
+ declare function createAgentTranscript(options: AgentTranscriptOptions): AgentTranscript;
90
+
91
+ export { type AgentHistory, type AgentHistoryOptions, type AgentHistoryState, type AgentTranscript, type AgentTranscriptOptions, type AgentTranscriptState, type ConversationSummary, continueKey, createAgentHistory, createAgentTranscript, historyItems };