@vinaverse/react 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.
- package/dist/agent.js +1 -158
- package/dist/agent.js.map +1 -1
- package/dist/chunk-V4UBOVTK.js +160 -0
- package/dist/chunk-V4UBOVTK.js.map +1 -0
- package/dist/history.cjs +91 -0
- package/dist/history.cjs.map +1 -0
- package/dist/history.d.cts +55 -0
- package/dist/history.d.ts +55 -0
- package/dist/history.js +77 -0
- package/dist/history.js.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +38 -5
package/dist/agent.js
CHANGED
|
@@ -1,160 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
export { greetedKey } from '@vinaverse/client/agent';
|
|
3
|
-
import { useContext, useRef, useCallback, useSyncExternalStore, useLayoutEffect, useEffect, useState, createContext } from 'react';
|
|
4
|
-
import { jsx } from 'react/jsx-runtime';
|
|
5
|
-
|
|
6
|
-
// src/agent.tsx
|
|
7
|
-
var RuntimeContext = /* @__PURE__ */ createContext(null);
|
|
8
|
-
function AgentRuntimeProvider(props) {
|
|
9
|
-
return /* @__PURE__ */ jsx(RuntimeContext.Provider, { value: props.runtime, children: props.children });
|
|
10
|
-
}
|
|
11
|
-
function useAgentRuntime() {
|
|
12
|
-
const runtime = useContext(RuntimeContext);
|
|
13
|
-
if (!runtime)
|
|
14
|
-
throw new Error("Agent hooks render inside <AgentRuntimeProvider>.");
|
|
15
|
-
return runtime;
|
|
16
|
-
}
|
|
17
|
-
function useAgentConversation(key, open = {}) {
|
|
18
|
-
const runtime = useAgentRuntime();
|
|
19
|
-
const keyRef = useRef(key);
|
|
20
|
-
keyRef.current = key;
|
|
21
|
-
const k = agentKey(key);
|
|
22
|
-
const read = useCallback(() => runtime.peek(keyRef.current), [runtime, k]);
|
|
23
|
-
const conversation = useSyncExternalStore(runtime.subscribe, read, read);
|
|
24
|
-
const openRef = useRef(open);
|
|
25
|
-
openRef.current = open;
|
|
26
|
-
useLayoutEffect(() => conversation.show(openRef.current), [conversation]);
|
|
27
|
-
const { place, entryPoint } = open;
|
|
28
|
-
const screen = place?.screen;
|
|
29
|
-
const entityType = place?.entity?.type;
|
|
30
|
-
const entityId = place?.entity?.id;
|
|
31
|
-
const filters = place?.filters ? JSON.stringify(place.filters) : null;
|
|
32
|
-
const cleared = place === null;
|
|
33
|
-
useLayoutEffect(() => {
|
|
34
|
-
conversation.tell(openRef.current);
|
|
35
|
-
}, [
|
|
36
|
-
conversation,
|
|
37
|
-
screen,
|
|
38
|
-
entityType,
|
|
39
|
-
entityId,
|
|
40
|
-
filters,
|
|
41
|
-
cleared,
|
|
42
|
-
entryPoint
|
|
43
|
-
]);
|
|
44
|
-
const state = useSyncExternalStore(
|
|
45
|
-
conversation.subscribe,
|
|
46
|
-
conversation.getState,
|
|
47
|
-
conversation.getState
|
|
48
|
-
);
|
|
49
|
-
const startNew = useCallback(
|
|
50
|
-
() => runtime.startNew(keyRef.current),
|
|
51
|
-
[runtime]
|
|
52
|
-
);
|
|
53
|
-
return { conversation, state, startNew };
|
|
54
|
-
}
|
|
55
|
-
function useAgentStatus() {
|
|
56
|
-
const runtime = useAgentRuntime();
|
|
57
|
-
useEffect(() => {
|
|
58
|
-
runtime.status().catch(() => void 0);
|
|
59
|
-
}, [runtime]);
|
|
60
|
-
return useSyncExternalStore(
|
|
61
|
-
runtime.subscribe,
|
|
62
|
-
runtime.getStatus,
|
|
63
|
-
runtime.getStatus
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
function useAgentStatusState() {
|
|
67
|
-
const runtime = useAgentRuntime();
|
|
68
|
-
useEffect(() => {
|
|
69
|
-
runtime.status().catch(() => void 0);
|
|
70
|
-
}, [runtime]);
|
|
71
|
-
return useSyncExternalStore(
|
|
72
|
-
runtime.subscribe,
|
|
73
|
-
runtime.getStatusState,
|
|
74
|
-
runtime.getStatusState
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
function useAgentName(fallback) {
|
|
78
|
-
const runtime = useAgentRuntime();
|
|
79
|
-
return useSyncExternalStore(runtime.subscribe, runtime.getName, runtime.getName) ?? fallback;
|
|
80
|
-
}
|
|
81
|
-
function useAgentFeatures() {
|
|
82
|
-
const status = useAgentStatus();
|
|
83
|
-
return {
|
|
84
|
-
available: status?.available === true,
|
|
85
|
-
launcher: status?.launcher === true,
|
|
86
|
-
history: status?.features.history === true,
|
|
87
|
-
memory: status?.features.memory === true,
|
|
88
|
-
businessAgent: status?.features.businessAgent === true,
|
|
89
|
-
businessSetup: status?.features.businessSetup === true
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
function useAgentProfile(fallback) {
|
|
93
|
-
const status = useAgentStatus();
|
|
94
|
-
return { name: useAgentName(fallback), avatarUrl: status?.avatarUrl ?? null };
|
|
95
|
-
}
|
|
96
|
-
async function forgetGreeting(storage, subject, modes, storageKey = greetedKey) {
|
|
97
|
-
for (const mode of modes) await storage.removeItem(storageKey(subject, mode));
|
|
98
|
-
}
|
|
99
|
-
var MEMORY = /* @__PURE__ */ new Map();
|
|
100
|
-
var memory = {
|
|
101
|
-
getItem: (k) => MEMORY.get(k) ?? null,
|
|
102
|
-
setItem: (k, v) => void MEMORY.set(k, v),
|
|
103
|
-
removeItem: (k) => void MEMORY.delete(k)
|
|
104
|
-
};
|
|
105
|
-
function useAgentLauncher(options) {
|
|
106
|
-
const runtime = useAgentRuntime();
|
|
107
|
-
const status = useAgentStatus();
|
|
108
|
-
const { subject, mode, onOpen } = options;
|
|
109
|
-
const storage = options.storage ?? runtime.greetings ?? memory;
|
|
110
|
-
const shows = status?.launcher === true && options.visible !== false;
|
|
111
|
-
const key = (options.storageKey ?? greetedKey)(subject, mode);
|
|
112
|
-
const [greeted, setGreeted] = useState(
|
|
113
|
-
null
|
|
114
|
-
);
|
|
115
|
-
const [due, setDue] = useState(null);
|
|
116
|
-
useEffect(() => {
|
|
117
|
-
let live = true;
|
|
118
|
-
Promise.resolve(storage.getItem(key)).then(
|
|
119
|
-
(value) => {
|
|
120
|
-
if (live) setGreeted({ key, done: value === "1" });
|
|
121
|
-
},
|
|
122
|
-
() => {
|
|
123
|
-
if (live) setGreeted({ key, done: false });
|
|
124
|
-
}
|
|
125
|
-
);
|
|
126
|
-
return () => {
|
|
127
|
-
live = false;
|
|
128
|
-
};
|
|
129
|
-
}, [storage, key]);
|
|
130
|
-
const pending = shows && greeted?.key === key && !greeted.done;
|
|
131
|
-
useEffect(() => {
|
|
132
|
-
if (!pending) return;
|
|
133
|
-
const timer = setTimeout(() => {
|
|
134
|
-
setDue(key);
|
|
135
|
-
runtime.emit({ type: "launcher_greeted" });
|
|
136
|
-
}, options.delayMs ?? 1200);
|
|
137
|
-
return () => clearTimeout(timer);
|
|
138
|
-
}, [pending, key, runtime, options.delayMs]);
|
|
139
|
-
const done = useCallback(() => {
|
|
140
|
-
setGreeted({ key, done: true });
|
|
141
|
-
void Promise.resolve(storage.setItem(key, "1")).catch(() => void 0);
|
|
142
|
-
}, [storage, key]);
|
|
143
|
-
const open = useCallback(() => {
|
|
144
|
-
done();
|
|
145
|
-
runtime.emit({ type: "launcher_opened" });
|
|
146
|
-
onOpen();
|
|
147
|
-
}, [done, runtime, onOpen]);
|
|
148
|
-
const dismiss = useCallback(() => {
|
|
149
|
-
done();
|
|
150
|
-
runtime.emit({ type: "greeting_closed" });
|
|
151
|
-
}, [done, runtime]);
|
|
152
|
-
useEffect(() => {
|
|
153
|
-
if (shows) runtime.emit({ type: "launcher_shown" });
|
|
154
|
-
}, [shows, runtime]);
|
|
155
|
-
return { shows, greets: pending && due === key, open, dismiss };
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
export { AgentRuntimeProvider, forgetGreeting, useAgentConversation, useAgentFeatures, useAgentLauncher, useAgentName, useAgentProfile, useAgentRuntime, useAgentStatus, useAgentStatusState };
|
|
1
|
+
export { AgentRuntimeProvider, forgetGreeting, greetedKey, useAgentConversation, useAgentFeatures, useAgentLauncher, useAgentName, useAgentProfile, useAgentRuntime, useAgentStatus, useAgentStatusState } from './chunk-V4UBOVTK.js';
|
|
159
2
|
//# sourceMappingURL=agent.js.map
|
|
160
3
|
//# sourceMappingURL=agent.js.map
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent.tsx"],"names":[],"mappings":";;;;;;AAyBA,IAAM,cAAA,iCAAoE,IAAI,CAAA;AAGvE,SAAS,qBAAqB,KAAA,EAGvB;AACZ,EAAA,uBACE,GAAA,CAAC,eAAe,QAAA,EAAf,EAAwB,OAAO,KAAA,CAAM,OAAA,EACnC,gBAAM,QAAA,EACT,CAAA;AAEJ;AAEO,SAAS,eAAA,GAAgC;AAC9C,EAAA,MAAM,OAAA,GAAU,WAAW,cAAc,CAAA;AACzC,EAAA,IAAI,CAAC,OAAA;AACH,IAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AACrE,EAAA,OAAO,OAAA;AACT;AAaO,SAAS,oBAAA,CACd,GAAA,EACA,IAAA,GAGI,EAAC,EACiB;AACtB,EAAA,MAAM,UAAU,eAAA,EAAgB;AAChC,EAAA,MAAM,MAAA,GAAS,OAAO,GAAG,CAAA;AACzB,EAAA,MAAA,CAAO,OAAA,GAAU,GAAA;AACjB,EAAA,MAAM,CAAA,GAAI,SAAS,GAAG,CAAA;AAEtB,EAAA,MAAM,IAAA,GAAO,WAAA,CAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA,EAAG,CAAC,OAAA,EAAS,CAAC,CAAC,CAAA;AACzE,EAAA,MAAM,YAAA,GAAe,oBAAA,CAAqB,OAAA,CAAQ,SAAA,EAAW,MAAM,IAAI,CAAA;AACvE,EAAA,MAAM,OAAA,GAAU,OAAO,IAAI,CAAA;AAC3B,EAAA,OAAA,CAAQ,OAAA,GAAU,IAAA;AAGlB,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,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,EACvE,CAAA,EAAG,CAAC,OAAA,EAAS,GAAG,CAAC,CAAA;AACjB,EAAA,MAAM,IAAA,GAAO,YAAY,MAAM;AAC7B,IAAA,IAAA,EAAK;AACL,IAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,iBAAA,EAAmB,CAAA;AACxC,IAAA,MAAA,EAAO;AAAA,EACT,CAAA,EAAG,CAAC,IAAA,EAAM,OAAA,EAAS,MAAM,CAAC,CAAA;AAC1B,EAAA,MAAM,OAAA,GAAU,YAAY,MAAM;AAChC,IAAA,IAAA,EAAK;AACL,IAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,iBAAA,EAAmB,CAAA;AAAA,EAC1C,CAAA,EAAG,CAAC,IAAA,EAAM,OAAO,CAAC,CAAA;AAClB,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,OAAO,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,kBAAkB,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,KAAA,EAAO,OAAO,CAAC,CAAA;AACnB,EAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,WAAW,GAAA,KAAQ,GAAA,EAAK,MAAM,OAAA,EAAQ;AAChE","file":"agent.js","sourcesContent":["// React bindings of the agent runtime (@vinaverse/client/agent): a provider and hooks, thin by design. The runtime holds\n// every rule; these subscribe, show a conversation while a component is mounted, and read the launcher's state. No\n// react-native or DOM import.\nimport type {\n AgentConversation,\n AgentConversationState,\n AgentKey,\n AgentPlace,\n AgentRuntime,\n AgentStatus,\n AgentStatusState,\n} from '@vinaverse/client/agent';\nimport { agentKey, greetedKey } from '@vinaverse/client/agent';\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nconst RuntimeContext = /* @__PURE__ */ createContext<AgentRuntime | null>(null);\n\n/** The app's agent runtime, made once (module level, or memoized) and given to everything below. */\nexport function AgentRuntimeProvider(props: {\n readonly runtime: AgentRuntime;\n readonly children?: ReactNode;\n}): ReactNode {\n return (\n <RuntimeContext.Provider value={props.runtime}>\n {props.children}\n </RuntimeContext.Provider>\n );\n}\n\nexport function useAgentRuntime(): AgentRuntime {\n const runtime = useContext(RuntimeContext);\n if (!runtime)\n throw new Error('Agent hooks render inside <AgentRuntimeProvider>.');\n return runtime;\n}\n\nexport interface UseAgentConversation {\n readonly conversation: AgentConversation;\n readonly state: AgentConversationState;\n /** A new conversation for this key (the old one let go and forgotten). */\n readonly startNew: () => void;\n}\n\n/**\n * The key's conversation, shown while the component is mounted (kept across screens; released when it unmounts), told\n * the place and the way in as they change. A start over or its end hands the component the key's next conversation.\n */\nexport function useAgentConversation(\n key: AgentKey,\n open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: string | null;\n } = {},\n): UseAgentConversation {\n const runtime = useAgentRuntime();\n const keyRef = useRef(key);\n keyRef.current = key;\n const k = agentKey(key);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the key's string reads it again when the key changes\n const read = useCallback(() => runtime.peek(keyRef.current), [runtime, k]);\n const conversation = useSyncExternalStore(runtime.subscribe, read, read);\n const openRef = useRef(open);\n openRef.current = open;\n // Layout effects: they run before any passive effect, a child's included, so a chat below that starts the\n // conversation early (`VinaverseChat`) finds it shown and told the place.\n useLayoutEffect(() => conversation.show(openRef.current), [conversation]);\n const { place, entryPoint } = open;\n const screen = place?.screen;\n const entityType = place?.entity?.type;\n const entityId = place?.entity?.id;\n const filters = place?.filters ? JSON.stringify(place.filters) : null;\n const cleared = place === null;\n // biome-ignore lint/correctness/useExhaustiveDependencies: told by value, so a place made again each render is the same\n useLayoutEffect(() => {\n conversation.tell(openRef.current);\n }, [\n conversation,\n screen,\n entityType,\n entityId,\n filters,\n cleared,\n entryPoint,\n ]);\n const state = useSyncExternalStore(\n conversation.subscribe,\n conversation.getState,\n conversation.getState,\n );\n const startNew = useCallback(\n () => runtime.startNew(keyRef.current),\n [runtime],\n );\n return { conversation, state, startNew };\n}\n\n/** The agent's status (read once, then at most every few minutes); null until the first read. */\nexport function useAgentStatus(): AgentStatus | null {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // an unread status is no agent: the launcher stays hidden\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatus,\n runtime.getStatus,\n );\n}\n\n/**\n * The status with where its read stands (`{ status, reading, failed }`): a screen tells \"still reading\" from \"could\n * not read\" and draws each its own way. Reads the status, as `useAgentStatus` does.\n */\nexport function useAgentStatusState(): AgentStatusState {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // said through `failed`\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatusState,\n runtime.getStatusState,\n );\n}\n\n/** The agent's name: the newest session's, else the status's, else `fallback`. */\nexport function useAgentName(fallback: string): string {\n const runtime = useAgentRuntime();\n return (\n useSyncExternalStore(runtime.subscribe, runtime.getName, runtime.getName) ??\n fallback\n );\n}\n\n/** What the agent can do, from the status (all off until it is read, and when the agent is off). */\nexport function useAgentFeatures(): AgentStatus['features'] & {\n readonly available: boolean;\n readonly launcher: boolean;\n} {\n const status = useAgentStatus();\n return {\n available: status?.available === true,\n launcher: status?.launcher === true,\n history: status?.features.history === true,\n memory: status?.features.memory === true,\n businessAgent: status?.features.businessAgent === true,\n businessSetup: status?.features.businessSetup === true,\n };\n}\n\n/** The agent as an entry shows it before any session: its name (`fallback` until known) and avatar. */\nexport function useAgentProfile(fallback: string): {\n readonly name: string;\n readonly avatarUrl: string | null;\n} {\n const status = useAgentStatus();\n return { name: useAgentName(fallback), avatarUrl: status?.avatarUrl ?? null };\n}\n\n/**\n * Where the launcher remembers that it greeted a person in a mode (sync or async; the app's preferences store). A\n * sign-out keeps it on purpose (a person is not greeted again after signing back in). Given to the runtime as\n * `greetingStorage`, `runtime.erase()` erases it; `forgetGreeting` is the low-level helper for a storage of the app's.\n */\nexport interface GreetingStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n /** Erasure removes the record, never leaves a key that names the person. */\n removeItem(key: string): void | Promise<void>;\n}\n\n/** Where the greeting is remembered, per person and mode: the default the storage sees, unless the app maps its own. */\nexport { greetedKey };\n\n/** Removes the launcher's record of greeting this person in these modes (`runtime.erase()` does it for `greetingStorage`). */\nexport async function forgetGreeting(\n storage: GreetingStorage,\n subject: string | null,\n modes: readonly string[],\n storageKey: (subject: string | null, mode: string) => string = greetedKey,\n): Promise<void> {\n for (const mode of modes) await storage.removeItem(storageKey(subject, mode));\n}\n\nconst MEMORY = new Map<string, string>();\nconst memory: GreetingStorage = {\n getItem: (k) => MEMORY.get(k) ?? null,\n setItem: (k, v) => void MEMORY.set(k, v),\n removeItem: (k) => void MEMORY.delete(k),\n};\n\nexport interface UseAgentLauncher {\n /** The status offers the launcher, and the app shows it here. */\n readonly shows: boolean;\n /** Its greeting bubble: once per person and mode, a moment after the launcher shows. */\n readonly greets: boolean;\n /** The person opens the agent (the greeting is done too). */\n readonly open: () => void;\n /** The person closes the greeting. */\n readonly dismiss: () => void;\n}\n\n/** The floating launcher's state: whether it shows and greets, and its two actions. */\nexport function useAgentLauncher(options: {\n readonly subject: string | null;\n readonly mode: string;\n /** The app's own rule (the tabs it shows on, no keyboard up…); default true. */\n readonly visible?: boolean;\n readonly storage?: GreetingStorage;\n /** The storage's key for a person and mode, to reuse a record the app already keeps. Default `greetedKey`. */\n readonly storageKey?: (subject: string | null, mode: string) => string;\n /** How long after showing the greeting appears. Default 1200 ms. */\n readonly delayMs?: number;\n readonly onOpen: () => void;\n}): UseAgentLauncher {\n const runtime = useAgentRuntime();\n const status = useAgentStatus();\n const { subject, mode, onOpen } = options;\n // The app's own store, else the runtime's (`greetingStorage`: fenced by a sign-out, reached by `erase()`).\n const storage = options.storage ?? runtime.greetings ?? memory;\n const shows = status?.launcher === true && options.visible !== false;\n const key = (options.storageKey ?? greetedKey)(subject, mode);\n const [greeted, setGreeted] = useState<{ key: string; done: boolean } | null>(\n null,\n );\n const [due, setDue] = useState<string | null>(null);\n useEffect(() => {\n let live = true;\n Promise.resolve(storage.getItem(key)).then(\n (value) => {\n if (live) setGreeted({ key, done: value === '1' });\n },\n () => {\n if (live) setGreeted({ key, done: false });\n },\n );\n return () => {\n live = false;\n };\n }, [storage, key]);\n const pending = shows && greeted?.key === key && !greeted.done;\n useEffect(() => {\n if (!pending) return;\n const timer = setTimeout(() => {\n setDue(key);\n runtime.emit({ type: 'launcher_greeted' });\n }, options.delayMs ?? 1200);\n return () => clearTimeout(timer);\n }, [pending, key, runtime, options.delayMs]);\n const done = useCallback(() => {\n setGreeted({ key, done: true });\n void Promise.resolve(storage.setItem(key, '1')).catch(() => undefined);\n }, [storage, key]);\n const open = useCallback(() => {\n done();\n runtime.emit({ type: 'launcher_opened' });\n onOpen();\n }, [done, runtime, onOpen]);\n const dismiss = useCallback(() => {\n done();\n runtime.emit({ type: 'greeting_closed' });\n }, [done, runtime]);\n useEffect(() => {\n if (shows) runtime.emit({ type: 'launcher_shown' });\n }, [shows, runtime]);\n return { shows, greets: pending && due === key, open, dismiss };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent.js"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { greetedKey, agentKey } from '@vinaverse/client/agent';
|
|
2
|
+
export { greetedKey } from '@vinaverse/client/agent';
|
|
3
|
+
import { useContext, useRef, useCallback, useSyncExternalStore, useLayoutEffect, useEffect, useState, createContext } from 'react';
|
|
4
|
+
import { jsx } from 'react/jsx-runtime';
|
|
5
|
+
|
|
6
|
+
// src/agent.tsx
|
|
7
|
+
var RuntimeContext = /* @__PURE__ */ createContext(null);
|
|
8
|
+
function AgentRuntimeProvider(props) {
|
|
9
|
+
return /* @__PURE__ */ jsx(RuntimeContext.Provider, { value: props.runtime, children: props.children });
|
|
10
|
+
}
|
|
11
|
+
function useAgentRuntime() {
|
|
12
|
+
const runtime = useContext(RuntimeContext);
|
|
13
|
+
if (!runtime)
|
|
14
|
+
throw new Error("Agent hooks render inside <AgentRuntimeProvider>.");
|
|
15
|
+
return runtime;
|
|
16
|
+
}
|
|
17
|
+
function useAgentConversation(key, open = {}) {
|
|
18
|
+
const runtime = useAgentRuntime();
|
|
19
|
+
const keyRef = useRef(key);
|
|
20
|
+
keyRef.current = key;
|
|
21
|
+
const k = agentKey(key);
|
|
22
|
+
const read = useCallback(() => runtime.peek(keyRef.current), [runtime, k]);
|
|
23
|
+
const conversation = useSyncExternalStore(runtime.subscribe, read, read);
|
|
24
|
+
const openRef = useRef(open);
|
|
25
|
+
openRef.current = open;
|
|
26
|
+
useLayoutEffect(() => conversation.show(openRef.current), [conversation]);
|
|
27
|
+
const { place, entryPoint } = open;
|
|
28
|
+
const screen = place?.screen;
|
|
29
|
+
const entityType = place?.entity?.type;
|
|
30
|
+
const entityId = place?.entity?.id;
|
|
31
|
+
const filters = place?.filters ? JSON.stringify(place.filters) : null;
|
|
32
|
+
const cleared = place === null;
|
|
33
|
+
useLayoutEffect(() => {
|
|
34
|
+
conversation.tell(openRef.current);
|
|
35
|
+
}, [
|
|
36
|
+
conversation,
|
|
37
|
+
screen,
|
|
38
|
+
entityType,
|
|
39
|
+
entityId,
|
|
40
|
+
filters,
|
|
41
|
+
cleared,
|
|
42
|
+
entryPoint
|
|
43
|
+
]);
|
|
44
|
+
const state = useSyncExternalStore(
|
|
45
|
+
conversation.subscribe,
|
|
46
|
+
conversation.getState,
|
|
47
|
+
conversation.getState
|
|
48
|
+
);
|
|
49
|
+
const startNew = useCallback(
|
|
50
|
+
() => runtime.startNew(keyRef.current),
|
|
51
|
+
[runtime]
|
|
52
|
+
);
|
|
53
|
+
return { conversation, state, startNew };
|
|
54
|
+
}
|
|
55
|
+
function useAgentStatus() {
|
|
56
|
+
const runtime = useAgentRuntime();
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
runtime.status().catch(() => void 0);
|
|
59
|
+
}, [runtime]);
|
|
60
|
+
return useSyncExternalStore(
|
|
61
|
+
runtime.subscribe,
|
|
62
|
+
runtime.getStatus,
|
|
63
|
+
runtime.getStatus
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
function useAgentStatusState() {
|
|
67
|
+
const runtime = useAgentRuntime();
|
|
68
|
+
useEffect(() => {
|
|
69
|
+
runtime.status().catch(() => void 0);
|
|
70
|
+
}, [runtime]);
|
|
71
|
+
return useSyncExternalStore(
|
|
72
|
+
runtime.subscribe,
|
|
73
|
+
runtime.getStatusState,
|
|
74
|
+
runtime.getStatusState
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
function useAgentName(fallback) {
|
|
78
|
+
const runtime = useAgentRuntime();
|
|
79
|
+
return useSyncExternalStore(runtime.subscribe, runtime.getName, runtime.getName) ?? fallback;
|
|
80
|
+
}
|
|
81
|
+
function useAgentFeatures() {
|
|
82
|
+
const status = useAgentStatus();
|
|
83
|
+
return {
|
|
84
|
+
available: status?.available === true,
|
|
85
|
+
launcher: status?.launcher === true,
|
|
86
|
+
history: status?.features.history === true,
|
|
87
|
+
memory: status?.features.memory === true,
|
|
88
|
+
businessAgent: status?.features.businessAgent === true,
|
|
89
|
+
businessSetup: status?.features.businessSetup === true
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function useAgentProfile(fallback) {
|
|
93
|
+
const status = useAgentStatus();
|
|
94
|
+
return { name: useAgentName(fallback), avatarUrl: status?.avatarUrl ?? null };
|
|
95
|
+
}
|
|
96
|
+
async function forgetGreeting(storage, subject, modes, storageKey = greetedKey) {
|
|
97
|
+
for (const mode of modes) await storage.removeItem(storageKey(subject, mode));
|
|
98
|
+
}
|
|
99
|
+
var MEMORY = /* @__PURE__ */ new Map();
|
|
100
|
+
var memory = {
|
|
101
|
+
getItem: (k) => MEMORY.get(k) ?? null,
|
|
102
|
+
setItem: (k, v) => void MEMORY.set(k, v),
|
|
103
|
+
removeItem: (k) => void MEMORY.delete(k)
|
|
104
|
+
};
|
|
105
|
+
function useAgentLauncher(options) {
|
|
106
|
+
const runtime = useAgentRuntime();
|
|
107
|
+
const status = useAgentStatus();
|
|
108
|
+
const { subject, mode, onOpen } = options;
|
|
109
|
+
const storage = options.storage ?? runtime.greetings ?? memory;
|
|
110
|
+
const shows = status?.launcher === true && options.visible !== false;
|
|
111
|
+
const key = (options.storageKey ?? greetedKey)(subject, mode);
|
|
112
|
+
const [greeted, setGreeted] = useState(
|
|
113
|
+
null
|
|
114
|
+
);
|
|
115
|
+
const [due, setDue] = useState(null);
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
let live = true;
|
|
118
|
+
Promise.resolve(storage.getItem(key)).then(
|
|
119
|
+
(value) => {
|
|
120
|
+
if (live) setGreeted({ key, done: value === "1" });
|
|
121
|
+
},
|
|
122
|
+
() => {
|
|
123
|
+
if (live) setGreeted({ key, done: false });
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
return () => {
|
|
127
|
+
live = false;
|
|
128
|
+
};
|
|
129
|
+
}, [storage, key]);
|
|
130
|
+
const pending = shows && greeted?.key === key && !greeted.done;
|
|
131
|
+
useEffect(() => {
|
|
132
|
+
if (!pending) return;
|
|
133
|
+
const timer = setTimeout(() => {
|
|
134
|
+
setDue(key);
|
|
135
|
+
runtime.emit({ type: "launcher_greeted" });
|
|
136
|
+
}, options.delayMs ?? 1200);
|
|
137
|
+
return () => clearTimeout(timer);
|
|
138
|
+
}, [pending, key, runtime, options.delayMs]);
|
|
139
|
+
const done = useCallback(() => {
|
|
140
|
+
setGreeted({ key, done: true });
|
|
141
|
+
void Promise.resolve(storage.setItem(key, "1")).catch(() => void 0);
|
|
142
|
+
}, [storage, key]);
|
|
143
|
+
const open = useCallback(() => {
|
|
144
|
+
done();
|
|
145
|
+
runtime.emit({ type: "launcher_opened" });
|
|
146
|
+
onOpen();
|
|
147
|
+
}, [done, runtime, onOpen]);
|
|
148
|
+
const dismiss = useCallback(() => {
|
|
149
|
+
done();
|
|
150
|
+
runtime.emit({ type: "greeting_closed" });
|
|
151
|
+
}, [done, runtime]);
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
if (shows) runtime.emit({ type: "launcher_shown" });
|
|
154
|
+
}, [shows, runtime]);
|
|
155
|
+
return { shows, greets: pending && due === key, open, dismiss };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export { AgentRuntimeProvider, forgetGreeting, useAgentConversation, useAgentFeatures, useAgentLauncher, useAgentName, useAgentProfile, useAgentRuntime, useAgentStatus, useAgentStatusState };
|
|
159
|
+
//# sourceMappingURL=chunk-V4UBOVTK.js.map
|
|
160
|
+
//# sourceMappingURL=chunk-V4UBOVTK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent.tsx"],"names":[],"mappings":";;;;;;AAyBA,IAAM,cAAA,iCAAoE,IAAI,CAAA;AAGvE,SAAS,qBAAqB,KAAA,EAGvB;AACZ,EAAA,uBACE,GAAA,CAAC,eAAe,QAAA,EAAf,EAAwB,OAAO,KAAA,CAAM,OAAA,EACnC,gBAAM,QAAA,EACT,CAAA;AAEJ;AAEO,SAAS,eAAA,GAAgC;AAC9C,EAAA,MAAM,OAAA,GAAU,WAAW,cAAc,CAAA;AACzC,EAAA,IAAI,CAAC,OAAA;AACH,IAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AACrE,EAAA,OAAO,OAAA;AACT;AAaO,SAAS,oBAAA,CACd,GAAA,EACA,IAAA,GAGI,EAAC,EACiB;AACtB,EAAA,MAAM,UAAU,eAAA,EAAgB;AAChC,EAAA,MAAM,MAAA,GAAS,OAAO,GAAG,CAAA;AACzB,EAAA,MAAA,CAAO,OAAA,GAAU,GAAA;AACjB,EAAA,MAAM,CAAA,GAAI,SAAS,GAAG,CAAA;AAEtB,EAAA,MAAM,IAAA,GAAO,WAAA,CAAY,MAAM,OAAA,CAAQ,I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AK,OAAA,EAAS,OAAA,CAAQ,OAAO,CAAC,CAAA;AAC3C,EAAA,MAAM,IAAA,GAAO,YAAY,MAAM;AAC7B,IAAA,UAAA,CAAW,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,EAAM,CAAA;AAC9B,IAAA,KAAK,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,GAAA,EAAK,GAAG,CAAC,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,EACvE,CAAA,EAAG,CAAC,OAAA,EAAS,GAAG,CAAC,CAAA;AACjB,EAAA,MAAM,IAAA,GAAO,YAAY,MAAM;AAC7B,IAAA,IAAA,EAAK;AACL,IAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,iBAAA,EAAmB,CAAA;AACxC,IAAA,MAAA,EAAO;AAAA,EACT,CAAA,EAAG,CAAC,IAAA,EAAM,OAAA,EAAS,MAAM,CAAC,CAAA;AAC1B,EAAA,MAAM,OAAA,GAAU,YAAY,MAAM;AAChC,IAAA,IAAA,EAAK;AACL,IAAA,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,iBAAA,EAAmB,CAAA;AAAA,EAC1C,CAAA,EAAG,CAAC,IAAA,EAAM,OAAO,CAAC,CAAA;AAClB,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,OAAO,OAAA,CAAQ,IAAA,CAAK,EAAE,IAAA,EAAM,kBAAkB,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,KAAA,EAAO,OAAO,CAAC,CAAA;AACnB,EAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,WAAW,GAAA,KAAQ,GAAA,EAAK,MAAM,OAAA,EAAQ;AAChE","file":"chunk-V4UBOVTK.js","sourcesContent":["// React bindings of the agent runtime (@vinaverse/client/agent): a provider and hooks, thin by design. The runtime holds\n// every rule; these subscribe, show a conversation while a component is mounted, and read the launcher's state. No\n// react-native or DOM import.\nimport type {\n AgentConversation,\n AgentConversationState,\n AgentKey,\n AgentPlace,\n AgentRuntime,\n AgentStatus,\n AgentStatusState,\n} from '@vinaverse/client/agent';\nimport { agentKey, greetedKey } from '@vinaverse/client/agent';\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nconst RuntimeContext = /* @__PURE__ */ createContext<AgentRuntime | null>(null);\n\n/** The app's agent runtime, made once (module level, or memoized) and given to everything below. */\nexport function AgentRuntimeProvider(props: {\n readonly runtime: AgentRuntime;\n readonly children?: ReactNode;\n}): ReactNode {\n return (\n <RuntimeContext.Provider value={props.runtime}>\n {props.children}\n </RuntimeContext.Provider>\n );\n}\n\nexport function useAgentRuntime(): AgentRuntime {\n const runtime = useContext(RuntimeContext);\n if (!runtime)\n throw new Error('Agent hooks render inside <AgentRuntimeProvider>.');\n return runtime;\n}\n\nexport interface UseAgentConversation {\n readonly conversation: AgentConversation;\n readonly state: AgentConversationState;\n /** A new conversation for this key (the old one let go and forgotten). */\n readonly startNew: () => void;\n}\n\n/**\n * The key's conversation, shown while the component is mounted (kept across screens; released when it unmounts), told\n * the place and the way in as they change. A start over or its end hands the component the key's next conversation.\n */\nexport function useAgentConversation(\n key: AgentKey,\n open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: string | null;\n } = {},\n): UseAgentConversation {\n const runtime = useAgentRuntime();\n const keyRef = useRef(key);\n keyRef.current = key;\n const k = agentKey(key);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the key's string reads it again when the key changes\n const read = useCallback(() => runtime.peek(keyRef.current), [runtime, k]);\n const conversation = useSyncExternalStore(runtime.subscribe, read, read);\n const openRef = useRef(open);\n openRef.current = open;\n // Layout effects: they run before any passive effect, a child's included, so a chat below that starts the\n // conversation early (`VinaverseChat`) finds it shown and told the place.\n useLayoutEffect(() => conversation.show(openRef.current), [conversation]);\n const { place, entryPoint } = open;\n const screen = place?.screen;\n const entityType = place?.entity?.type;\n const entityId = place?.entity?.id;\n const filters = place?.filters ? JSON.stringify(place.filters) : null;\n const cleared = place === null;\n // biome-ignore lint/correctness/useExhaustiveDependencies: told by value, so a place made again each render is the same\n useLayoutEffect(() => {\n conversation.tell(openRef.current);\n }, [\n conversation,\n screen,\n entityType,\n entityId,\n filters,\n cleared,\n entryPoint,\n ]);\n const state = useSyncExternalStore(\n conversation.subscribe,\n conversation.getState,\n conversation.getState,\n );\n const startNew = useCallback(\n () => runtime.startNew(keyRef.current),\n [runtime],\n );\n return { conversation, state, startNew };\n}\n\n/** The agent's status (read once, then at most every few minutes); null until the first read. */\nexport function useAgentStatus(): AgentStatus | null {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // an unread status is no agent: the launcher stays hidden\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatus,\n runtime.getStatus,\n );\n}\n\n/**\n * The status with where its read stands (`{ status, reading, failed }`): a screen tells \"still reading\" from \"could\n * not read\" and draws each its own way. Reads the status, as `useAgentStatus` does.\n */\nexport function useAgentStatusState(): AgentStatusState {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // said through `failed`\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatusState,\n runtime.getStatusState,\n );\n}\n\n/** The agent's name: the newest session's, else the status's, else `fallback`. */\nexport function useAgentName(fallback: string): string {\n const runtime = useAgentRuntime();\n return (\n useSyncExternalStore(runtime.subscribe, runtime.getName, runtime.getName) ??\n fallback\n );\n}\n\n/** What the agent can do, from the status (all off until it is read, and when the agent is off). */\nexport function useAgentFeatures(): AgentStatus['features'] & {\n readonly available: boolean;\n readonly launcher: boolean;\n} {\n const status = useAgentStatus();\n return {\n available: status?.available === true,\n launcher: status?.launcher === true,\n history: status?.features.history === true,\n memory: status?.features.memory === true,\n businessAgent: status?.features.businessAgent === true,\n businessSetup: status?.features.businessSetup === true,\n };\n}\n\n/** The agent as an entry shows it before any session: its name (`fallback` until known) and avatar. */\nexport function useAgentProfile(fallback: string): {\n readonly name: string;\n readonly avatarUrl: string | null;\n} {\n const status = useAgentStatus();\n return { name: useAgentName(fallback), avatarUrl: status?.avatarUrl ?? null };\n}\n\n/**\n * Where the launcher remembers that it greeted a person in a mode (sync or async; the app's preferences store). A\n * sign-out keeps it on purpose (a person is not greeted again after signing back in). Given to the runtime as\n * `greetingStorage`, `runtime.erase()` erases it; `forgetGreeting` is the low-level helper for a storage of the app's.\n */\nexport interface GreetingStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n /** Erasure removes the record, never leaves a key that names the person. */\n removeItem(key: string): void | Promise<void>;\n}\n\n/** Where the greeting is remembered, per person and mode: the default the storage sees, unless the app maps its own. */\nexport { greetedKey };\n\n/** Removes the launcher's record of greeting this person in these modes (`runtime.erase()` does it for `greetingStorage`). */\nexport async function forgetGreeting(\n storage: GreetingStorage,\n subject: string | null,\n modes: readonly string[],\n storageKey: (subject: string | null, mode: string) => string = greetedKey,\n): Promise<void> {\n for (const mode of modes) await storage.removeItem(storageKey(subject, mode));\n}\n\nconst MEMORY = new Map<string, string>();\nconst memory: GreetingStorage = {\n getItem: (k) => MEMORY.get(k) ?? null,\n setItem: (k, v) => void MEMORY.set(k, v),\n removeItem: (k) => void MEMORY.delete(k),\n};\n\nexport interface UseAgentLauncher {\n /** The status offers the launcher, and the app shows it here. */\n readonly shows: boolean;\n /** Its greeting bubble: once per person and mode, a moment after the launcher shows. */\n readonly greets: boolean;\n /** The person opens the agent (the greeting is done too). */\n readonly open: () => void;\n /** The person closes the greeting. */\n readonly dismiss: () => void;\n}\n\n/** The floating launcher's state: whether it shows and greets, and its two actions. */\nexport function useAgentLauncher(options: {\n readonly subject: string | null;\n readonly mode: string;\n /** The app's own rule (the tabs it shows on, no keyboard up…); default true. */\n readonly visible?: boolean;\n readonly storage?: GreetingStorage;\n /** The storage's key for a person and mode, to reuse a record the app already keeps. Default `greetedKey`. */\n readonly storageKey?: (subject: string | null, mode: string) => string;\n /** How long after showing the greeting appears. Default 1200 ms. */\n readonly delayMs?: number;\n readonly onOpen: () => void;\n}): UseAgentLauncher {\n const runtime = useAgentRuntime();\n const status = useAgentStatus();\n const { subject, mode, onOpen } = options;\n // The app's own store, else the runtime's (`greetingStorage`: fenced by a sign-out, reached by `erase()`).\n const storage = options.storage ?? runtime.greetings ?? memory;\n const shows = status?.launcher === true && options.visible !== false;\n const key = (options.storageKey ?? greetedKey)(subject, mode);\n const [greeted, setGreeted] = useState<{ key: string; done: boolean } | null>(\n null,\n );\n const [due, setDue] = useState<string | null>(null);\n useEffect(() => {\n let live = true;\n Promise.resolve(storage.getItem(key)).then(\n (value) => {\n if (live) setGreeted({ key, done: value === '1' });\n },\n () => {\n if (live) setGreeted({ key, done: false });\n },\n );\n return () => {\n live = false;\n };\n }, [storage, key]);\n const pending = shows && greeted?.key === key && !greeted.done;\n useEffect(() => {\n if (!pending) return;\n const timer = setTimeout(() => {\n setDue(key);\n runtime.emit({ type: 'launcher_greeted' });\n }, options.delayMs ?? 1200);\n return () => clearTimeout(timer);\n }, [pending, key, runtime, options.delayMs]);\n const done = useCallback(() => {\n setGreeted({ key, done: true });\n void Promise.resolve(storage.setItem(key, '1')).catch(() => undefined);\n }, [storage, key]);\n const open = useCallback(() => {\n done();\n runtime.emit({ type: 'launcher_opened' });\n onOpen();\n }, [done, runtime, onOpen]);\n const dismiss = useCallback(() => {\n done();\n runtime.emit({ type: 'greeting_closed' });\n }, [done, runtime]);\n useEffect(() => {\n if (shows) runtime.emit({ type: 'launcher_shown' });\n }, [shows, runtime]);\n return { shows, greets: pending && due === key, open, dismiss };\n}\n"]}
|
package/dist/history.cjs
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var history = require('@vinaverse/client/history');
|
|
4
|
+
var react = require('react');
|
|
5
|
+
require('@vinaverse/client/agent');
|
|
6
|
+
require('react/jsx-runtime');
|
|
7
|
+
|
|
8
|
+
// src/history.tsx
|
|
9
|
+
var RuntimeContext = /* @__PURE__ */ react.createContext(null);
|
|
10
|
+
function useAgentRuntime() {
|
|
11
|
+
const runtime = react.useContext(RuntimeContext);
|
|
12
|
+
if (!runtime)
|
|
13
|
+
throw new Error("Agent hooks render inside <AgentRuntimeProvider>.");
|
|
14
|
+
return runtime;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/history.tsx
|
|
18
|
+
function useAgentHistory(options) {
|
|
19
|
+
const runtime = useAgentRuntime();
|
|
20
|
+
const { subject, mode, thread, pageSize } = options;
|
|
21
|
+
const scope = options.scope ?? null;
|
|
22
|
+
const agent = options.agent ?? null;
|
|
23
|
+
const history$1 = react.useMemo(
|
|
24
|
+
() => history.createAgentHistory({
|
|
25
|
+
runtime,
|
|
26
|
+
mode,
|
|
27
|
+
scope,
|
|
28
|
+
agent,
|
|
29
|
+
...pageSize === void 0 ? {} : { pageSize }
|
|
30
|
+
}),
|
|
31
|
+
[runtime, mode, scope, agent, pageSize]
|
|
32
|
+
);
|
|
33
|
+
const state = react.useSyncExternalStore(
|
|
34
|
+
history$1.subscribe,
|
|
35
|
+
history$1.getSnapshot,
|
|
36
|
+
history$1.getSnapshot
|
|
37
|
+
);
|
|
38
|
+
react.useEffect(() => {
|
|
39
|
+
if (!state.started) history$1.refresh();
|
|
40
|
+
}, [history$1, state.started]);
|
|
41
|
+
const keyOf = react.useCallback(
|
|
42
|
+
(conversation) => history.continueKey(conversation, subject, thread),
|
|
43
|
+
[subject, thread]
|
|
44
|
+
);
|
|
45
|
+
return {
|
|
46
|
+
state,
|
|
47
|
+
refresh: history$1.refresh,
|
|
48
|
+
loadMore: history$1.loadMore,
|
|
49
|
+
retry: history$1.retry,
|
|
50
|
+
keyOf,
|
|
51
|
+
remove: react.useCallback(
|
|
52
|
+
(conversation) => history$1.remove(keyOf(conversation), conversation.id),
|
|
53
|
+
[history$1, keyOf]
|
|
54
|
+
),
|
|
55
|
+
continue: react.useCallback(
|
|
56
|
+
(conversation) => runtime.continue(keyOf(conversation), conversation.id),
|
|
57
|
+
[runtime, keyOf]
|
|
58
|
+
)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function useAgentTranscript(conversationId, options = {}) {
|
|
62
|
+
const runtime = useAgentRuntime();
|
|
63
|
+
const { pageSize } = options;
|
|
64
|
+
const transcript = react.useMemo(
|
|
65
|
+
() => history.createAgentTranscript({
|
|
66
|
+
runtime,
|
|
67
|
+
conversationId,
|
|
68
|
+
...pageSize === void 0 ? {} : { pageSize }
|
|
69
|
+
}),
|
|
70
|
+
[runtime, conversationId, pageSize]
|
|
71
|
+
);
|
|
72
|
+
const state = react.useSyncExternalStore(
|
|
73
|
+
transcript.subscribe,
|
|
74
|
+
transcript.getSnapshot,
|
|
75
|
+
transcript.getSnapshot
|
|
76
|
+
);
|
|
77
|
+
react.useEffect(() => {
|
|
78
|
+
if (!state.started) transcript.load();
|
|
79
|
+
}, [transcript, state.started]);
|
|
80
|
+
return {
|
|
81
|
+
state,
|
|
82
|
+
load: transcript.load,
|
|
83
|
+
loadEarlier: transcript.loadEarlier,
|
|
84
|
+
retry: transcript.retry
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
exports.useAgentHistory = useAgentHistory;
|
|
89
|
+
exports.useAgentTranscript = useAgentTranscript;
|
|
90
|
+
//# sourceMappingURL=history.cjs.map
|
|
91
|
+
//# sourceMappingURL=history.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent.tsx","../src/history.tsx"],"names":["useContext","history","useMemo","createAgentHistory","useSyncExternalStore","useEffect","useCallback","continueKey","createAgentTranscript"],"mappings":";;;;;;;;AAyBA,IAAM,cAAA,uCAAoE,IAAI,CAAA;AAcvE,SAAS,eAAA,GAAgC;AAC9C,EAAA,MAAM,OAAA,GAAUA,iBAAW,cAAc,CAAA;AACzC,EAAA,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ACpB;AACF","file":"history.cjs","sourcesContent":["// React bindings of the agent runtime (@vinaverse/client/agent): a provider and hooks, thin by design. The runtime holds\n// every rule; these subscribe, show a conversation while a component is mounted, and read the launcher's state. No\n// react-native or DOM import.\nimport type {\n AgentConversation,\n AgentConversationState,\n AgentKey,\n AgentPlace,\n AgentRuntime,\n AgentStatus,\n AgentStatusState,\n} from '@vinaverse/client/agent';\nimport { agentKey, greetedKey } from '@vinaverse/client/agent';\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nconst RuntimeContext = /* @__PURE__ */ createContext<AgentRuntime | null>(null);\n\n/** The app's agent runtime, made once (module level, or memoized) and given to everything below. */\nexport function AgentRuntimeProvider(props: {\n readonly runtime: AgentRuntime;\n readonly children?: ReactNode;\n}): ReactNode {\n return (\n <RuntimeContext.Provider value={props.runtime}>\n {props.children}\n </RuntimeContext.Provider>\n );\n}\n\nexport function useAgentRuntime(): AgentRuntime {\n const runtime = useContext(RuntimeContext);\n if (!runtime)\n throw new Error('Agent hooks render inside <AgentRuntimeProvider>.');\n return runtime;\n}\n\nexport interface UseAgentConversation {\n readonly conversation: AgentConversation;\n readonly state: AgentConversationState;\n /** A new conversation for this key (the old one let go and forgotten). */\n readonly startNew: () => void;\n}\n\n/**\n * The key's conversation, shown while the component is mounted (kept across screens; released when it unmounts), told\n * the place and the way in as they change. A start over or its end hands the component the key's next conversation.\n */\nexport function useAgentConversation(\n key: AgentKey,\n open: {\n readonly place?: AgentPlace | null;\n readonly entryPoint?: string | null;\n } = {},\n): UseAgentConversation {\n const runtime = useAgentRuntime();\n const keyRef = useRef(key);\n keyRef.current = key;\n const k = agentKey(key);\n // biome-ignore lint/correctness/useExhaustiveDependencies: the key's string reads it again when the key changes\n const read = useCallback(() => runtime.peek(keyRef.current), [runtime, k]);\n const conversation = useSyncExternalStore(runtime.subscribe, read, read);\n const openRef = useRef(open);\n openRef.current = open;\n // Layout effects: they run before any passive effect, a child's included, so a chat below that starts the\n // conversation early (`VinaverseChat`) finds it shown and told the place.\n useLayoutEffect(() => conversation.show(openRef.current), [conversation]);\n const { place, entryPoint } = open;\n const screen = place?.screen;\n const entityType = place?.entity?.type;\n const entityId = place?.entity?.id;\n const filters = place?.filters ? JSON.stringify(place.filters) : null;\n const cleared = place === null;\n // biome-ignore lint/correctness/useExhaustiveDependencies: told by value, so a place made again each render is the same\n useLayoutEffect(() => {\n conversation.tell(openRef.current);\n }, [\n conversation,\n screen,\n entityType,\n entityId,\n filters,\n cleared,\n entryPoint,\n ]);\n const state = useSyncExternalStore(\n conversation.subscribe,\n conversation.getState,\n conversation.getState,\n );\n const startNew = useCallback(\n () => runtime.startNew(keyRef.current),\n [runtime],\n );\n return { conversation, state, startNew };\n}\n\n/** The agent's status (read once, then at most every few minutes); null until the first read. */\nexport function useAgentStatus(): AgentStatus | null {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // an unread status is no agent: the launcher stays hidden\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatus,\n runtime.getStatus,\n );\n}\n\n/**\n * The status with where its read stands (`{ status, reading, failed }`): a screen tells \"still reading\" from \"could\n * not read\" and draws each its own way. Reads the status, as `useAgentStatus` does.\n */\nexport function useAgentStatusState(): AgentStatusState {\n const runtime = useAgentRuntime();\n useEffect(() => {\n runtime.status().catch(() => undefined); // said through `failed`\n }, [runtime]);\n return useSyncExternalStore(\n runtime.subscribe,\n runtime.getStatusState,\n runtime.getStatusState,\n );\n}\n\n/** The agent's name: the newest session's, else the status's, else `fallback`. */\nexport function useAgentName(fallback: string): string {\n const runtime = useAgentRuntime();\n return (\n useSyncExternalStore(runtime.subscribe, runtime.getName, runtime.getName) ??\n fallback\n );\n}\n\n/** What the agent can do, from the status (all off until it is read, and when the agent is off). */\nexport function useAgentFeatures(): AgentStatus['features'] & {\n readonly available: boolean;\n readonly launcher: boolean;\n} {\n const status = useAgentStatus();\n return {\n available: status?.available === true,\n launcher: status?.launcher === true,\n history: status?.features.history === true,\n memory: status?.features.memory === true,\n businessAgent: status?.features.businessAgent === true,\n businessSetup: status?.features.businessSetup === true,\n };\n}\n\n/** The agent as an entry shows it before any session: its name (`fallback` until known) and avatar. */\nexport function useAgentProfile(fallback: string): {\n readonly name: string;\n readonly avatarUrl: string | null;\n} {\n const status = useAgentStatus();\n return { name: useAgentName(fallback), avatarUrl: status?.avatarUrl ?? null };\n}\n\n/**\n * Where the launcher remembers that it greeted a person in a mode (sync or async; the app's preferences store). A\n * sign-out keeps it on purpose (a person is not greeted again after signing back in). Given to the runtime as\n * `greetingStorage`, `runtime.erase()` erases it; `forgetGreeting` is the low-level helper for a storage of the app's.\n */\nexport interface GreetingStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n /** Erasure removes the record, never leaves a key that names the person. */\n removeItem(key: string): void | Promise<void>;\n}\n\n/** Where the greeting is remembered, per person and mode: the default the storage sees, unless the app maps its own. */\nexport { greetedKey };\n\n/** Removes the launcher's record of greeting this person in these modes (`runtime.erase()` does it for `greetingStorage`). */\nexport async function forgetGreeting(\n storage: GreetingStorage,\n subject: string | null,\n modes: readonly string[],\n storageKey: (subject: string | null, mode: string) => string = greetedKey,\n): Promise<void> {\n for (const mode of modes) await storage.removeItem(storageKey(subject, mode));\n}\n\nconst MEMORY = new Map<string, string>();\nconst memory: GreetingStorage = {\n getItem: (k) => MEMORY.get(k) ?? null,\n setItem: (k, v) => void MEMORY.set(k, v),\n removeItem: (k) => void MEMORY.delete(k),\n};\n\nexport interface UseAgentLauncher {\n /** The status offers the launcher, and the app shows it here. */\n readonly shows: boolean;\n /** Its greeting bubble: once per person and mode, a moment after the launcher shows. */\n readonly greets: boolean;\n /** The person opens the agent (the greeting is done too). */\n readonly open: () => void;\n /** The person closes the greeting. */\n readonly dismiss: () => void;\n}\n\n/** The floating launcher's state: whether it shows and greets, and its two actions. */\nexport function useAgentLauncher(options: {\n readonly subject: string | null;\n readonly mode: string;\n /** The app's own rule (the tabs it shows on, no keyboard up…); default true. */\n readonly visible?: boolean;\n readonly storage?: GreetingStorage;\n /** The storage's key for a person and mode, to reuse a record the app already keeps. Default `greetedKey`. */\n readonly storageKey?: (subject: string | null, mode: string) => string;\n /** How long after showing the greeting appears. Default 1200 ms. */\n readonly delayMs?: number;\n readonly onOpen: () => void;\n}): UseAgentLauncher {\n const runtime = useAgentRuntime();\n const status = useAgentStatus();\n const { subject, mode, onOpen } = options;\n // The app's own store, else the runtime's (`greetingStorage`: fenced by a sign-out, reached by `erase()`).\n const storage = options.storage ?? runtime.greetings ?? memory;\n const shows = status?.launcher === true && options.visible !== false;\n const key = (options.storageKey ?? greetedKey)(subject, mode);\n const [greeted, setGreeted] = useState<{ key: string; done: boolean } | null>(\n null,\n );\n const [due, setDue] = useState<string | null>(null);\n useEffect(() => {\n let live = true;\n Promise.resolve(storage.getItem(key)).then(\n (value) => {\n if (live) setGreeted({ key, done: value === '1' });\n },\n () => {\n if (live) setGreeted({ key, done: false });\n },\n );\n return () => {\n live = false;\n };\n }, [storage, key]);\n const pending = shows && greeted?.key === key && !greeted.done;\n useEffect(() => {\n if (!pending) return;\n const timer = setTimeout(() => {\n setDue(key);\n runtime.emit({ type: 'launcher_greeted' });\n }, options.delayMs ?? 1200);\n return () => clearTimeout(timer);\n }, [pending, key, runtime, options.delayMs]);\n const done = useCallback(() => {\n setGreeted({ key, done: true });\n void Promise.resolve(storage.setItem(key, '1')).catch(() => undefined);\n }, [storage, key]);\n const open = useCallback(() => {\n done();\n runtime.emit({ type: 'launcher_opened' });\n onOpen();\n }, [done, runtime, onOpen]);\n const dismiss = useCallback(() => {\n done();\n runtime.emit({ type: 'greeting_closed' });\n }, [done, runtime]);\n useEffect(() => {\n if (shows) runtime.emit({ type: 'launcher_shown' });\n }, [shows, runtime]);\n return { shows, greets: pending && due === key, open, dismiss };\n}\n","// React bindings of a person's history (@vinaverse/client/history): the list of their past conversations and one\n// read back, each a store subscribed to while a component is mounted; delete and continue through the runtime. An\n// entry of its own, so an app that draws no history ships none of it. No react-native or DOM import.\nimport type { AgentConversation, AgentKey } from '@vinaverse/client/agent';\nimport {\n type AgentHistory,\n type AgentHistoryState,\n type AgentTranscript,\n type AgentTranscriptState,\n type ConversationSummary,\n continueKey,\n createAgentHistory,\n createAgentTranscript,\n} from '@vinaverse/client/history';\nimport { useCallback, useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { useAgentRuntime } from './agent.js';\n\nexport interface UseAgentHistoryOptions {\n /** The person signed in (null for a guest): the key a conversation continues or is deleted under. */\n readonly subject: string | null;\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 /** The thread a continued conversation runs in; default `chat`. */\n readonly thread?: string;\n /** Conversations per page (1–50). Default 20. */\n readonly pageSize?: number;\n}\n\nexport interface UseAgentHistory {\n readonly state: AgentHistoryState;\n /** Reads the first page anew (after a failure, or to see what changed). */\n readonly refresh: () => void;\n /** The next older page, when there is one and none is being read. */\n readonly loadMore: () => void;\n /** Reads again the page that failed: the first, or the next. */\n readonly retry: () => void;\n /** The key the conversation continues under for this person (`continueKey`). */\n readonly keyOf: (conversation: ConversationSummary) => AgentKey;\n /**\n * Deletes the conversation at the backend and drops its row; the device forgets it only where its key still\n * continues it. One already gone is dropped too; any other failure is thrown, the row kept.\n */\n readonly remove: (conversation: ConversationSummary) => Promise<void>;\n /**\n * The person goes on with a past conversation: pinned for its key and opened through the backend's resume when the\n * app shows it (`AgentChat` with `keyOf(conversation)`, or `show()` on what this returns).\n */\n readonly continue: (conversation: ConversationSummary) => AgentConversation;\n}\n\n/** The person's past conversations, read as the component mounts, newest activity first. */\nexport function useAgentHistory(\n options: UseAgentHistoryOptions,\n): UseAgentHistory {\n const runtime = useAgentRuntime();\n const { subject, mode, thread, pageSize } = options;\n const scope = options.scope ?? null;\n const agent = options.agent ?? null;\n const history = useMemo<AgentHistory>(\n () =>\n createAgentHistory({\n runtime,\n mode,\n scope,\n agent,\n ...(pageSize === undefined ? {} : { pageSize }),\n }),\n [runtime, mode, scope, agent, pageSize],\n );\n const state = useSyncExternalStore(\n history.subscribe,\n history.getSnapshot,\n history.getSnapshot,\n );\n useEffect(() => {\n if (!state.started) history.refresh();\n }, [history, state.started]);\n const keyOf = useCallback(\n (conversation: ConversationSummary) =>\n continueKey(conversation, subject, thread),\n [subject, thread],\n );\n return {\n state,\n refresh: history.refresh,\n loadMore: history.loadMore,\n retry: history.retry,\n keyOf,\n remove: useCallback(\n (conversation: ConversationSummary) =>\n history.remove(keyOf(conversation), conversation.id),\n [history, keyOf],\n ),\n continue: useCallback(\n (conversation: ConversationSummary) =>\n runtime.continue(keyOf(conversation), conversation.id),\n [runtime, keyOf],\n ),\n };\n}\n\nexport interface UseAgentTranscript {\n readonly state: AgentTranscriptState;\n /** Reads the newest page anew. */\n readonly load: () => void;\n /** The page before the earliest read, prepended. */\n readonly loadEarlier: () => void;\n /** Reads again the page that failed: the newest, or the earlier one. */\n readonly retry: () => void;\n}\n\n/** A past conversation read back, newest page first, as the component mounts. */\nexport function useAgentTranscript(\n conversationId: string,\n options: { readonly pageSize?: number } = {},\n): UseAgentTranscript {\n const runtime = useAgentRuntime();\n const { pageSize } = options;\n const transcript = useMemo<AgentTranscript>(\n () =>\n createAgentTranscript({\n runtime,\n conversationId,\n ...(pageSize === undefined ? {} : { pageSize }),\n }),\n [runtime, conversationId, pageSize],\n );\n const state = useSyncExternalStore(\n transcript.subscribe,\n transcript.getSnapshot,\n transcript.getSnapshot,\n );\n useEffect(() => {\n if (!state.started) transcript.load();\n }, [transcript, state.started]);\n return {\n state,\n load: transcript.load,\n loadEarlier: transcript.loadEarlier,\n retry: transcript.retry,\n };\n}\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { AgentKey, AgentConversation } from '@vinaverse/client/agent';
|
|
2
|
+
import { AgentHistoryState, ConversationSummary, AgentTranscriptState } from '@vinaverse/client/history';
|
|
3
|
+
|
|
4
|
+
interface UseAgentHistoryOptions {
|
|
5
|
+
/** The person signed in (null for a guest): the key a conversation continues or is deleted under. */
|
|
6
|
+
readonly subject: string | null;
|
|
7
|
+
/** The app's side: `customer` or `business`. */
|
|
8
|
+
readonly mode: string;
|
|
9
|
+
/** The business acted for, with `business`. */
|
|
10
|
+
readonly scope?: string | null;
|
|
11
|
+
/** The agent, for a backend that serves more than one. */
|
|
12
|
+
readonly agent?: string | null;
|
|
13
|
+
/** The thread a continued conversation runs in; default `chat`. */
|
|
14
|
+
readonly thread?: string;
|
|
15
|
+
/** Conversations per page (1–50). Default 20. */
|
|
16
|
+
readonly pageSize?: number;
|
|
17
|
+
}
|
|
18
|
+
interface UseAgentHistory {
|
|
19
|
+
readonly state: AgentHistoryState;
|
|
20
|
+
/** Reads the first page anew (after a failure, or to see what changed). */
|
|
21
|
+
readonly refresh: () => void;
|
|
22
|
+
/** The next older page, when there is one and none is being read. */
|
|
23
|
+
readonly loadMore: () => void;
|
|
24
|
+
/** Reads again the page that failed: the first, or the next. */
|
|
25
|
+
readonly retry: () => void;
|
|
26
|
+
/** The key the conversation continues under for this person (`continueKey`). */
|
|
27
|
+
readonly keyOf: (conversation: ConversationSummary) => AgentKey;
|
|
28
|
+
/**
|
|
29
|
+
* Deletes the conversation at the backend and drops its row; the device forgets it only where its key still
|
|
30
|
+
* continues it. One already gone is dropped too; any other failure is thrown, the row kept.
|
|
31
|
+
*/
|
|
32
|
+
readonly remove: (conversation: ConversationSummary) => Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* The person goes on with a past conversation: pinned for its key and opened through the backend's resume when the
|
|
35
|
+
* app shows it (`AgentChat` with `keyOf(conversation)`, or `show()` on what this returns).
|
|
36
|
+
*/
|
|
37
|
+
readonly continue: (conversation: ConversationSummary) => AgentConversation;
|
|
38
|
+
}
|
|
39
|
+
/** The person's past conversations, read as the component mounts, newest activity first. */
|
|
40
|
+
declare function useAgentHistory(options: UseAgentHistoryOptions): UseAgentHistory;
|
|
41
|
+
interface UseAgentTranscript {
|
|
42
|
+
readonly state: AgentTranscriptState;
|
|
43
|
+
/** Reads the newest page anew. */
|
|
44
|
+
readonly load: () => void;
|
|
45
|
+
/** The page before the earliest read, prepended. */
|
|
46
|
+
readonly loadEarlier: () => void;
|
|
47
|
+
/** Reads again the page that failed: the newest, or the earlier one. */
|
|
48
|
+
readonly retry: () => void;
|
|
49
|
+
}
|
|
50
|
+
/** A past conversation read back, newest page first, as the component mounts. */
|
|
51
|
+
declare function useAgentTranscript(conversationId: string, options?: {
|
|
52
|
+
readonly pageSize?: number;
|
|
53
|
+
}): UseAgentTranscript;
|
|
54
|
+
|
|
55
|
+
export { type UseAgentHistory, type UseAgentHistoryOptions, type UseAgentTranscript, useAgentHistory, useAgentTranscript };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { AgentKey, AgentConversation } from '@vinaverse/client/agent';
|
|
2
|
+
import { AgentHistoryState, ConversationSummary, AgentTranscriptState } from '@vinaverse/client/history';
|
|
3
|
+
|
|
4
|
+
interface UseAgentHistoryOptions {
|
|
5
|
+
/** The person signed in (null for a guest): the key a conversation continues or is deleted under. */
|
|
6
|
+
readonly subject: string | null;
|
|
7
|
+
/** The app's side: `customer` or `business`. */
|
|
8
|
+
readonly mode: string;
|
|
9
|
+
/** The business acted for, with `business`. */
|
|
10
|
+
readonly scope?: string | null;
|
|
11
|
+
/** The agent, for a backend that serves more than one. */
|
|
12
|
+
readonly agent?: string | null;
|
|
13
|
+
/** The thread a continued conversation runs in; default `chat`. */
|
|
14
|
+
readonly thread?: string;
|
|
15
|
+
/** Conversations per page (1–50). Default 20. */
|
|
16
|
+
readonly pageSize?: number;
|
|
17
|
+
}
|
|
18
|
+
interface UseAgentHistory {
|
|
19
|
+
readonly state: AgentHistoryState;
|
|
20
|
+
/** Reads the first page anew (after a failure, or to see what changed). */
|
|
21
|
+
readonly refresh: () => void;
|
|
22
|
+
/** The next older page, when there is one and none is being read. */
|
|
23
|
+
readonly loadMore: () => void;
|
|
24
|
+
/** Reads again the page that failed: the first, or the next. */
|
|
25
|
+
readonly retry: () => void;
|
|
26
|
+
/** The key the conversation continues under for this person (`continueKey`). */
|
|
27
|
+
readonly keyOf: (conversation: ConversationSummary) => AgentKey;
|
|
28
|
+
/**
|
|
29
|
+
* Deletes the conversation at the backend and drops its row; the device forgets it only where its key still
|
|
30
|
+
* continues it. One already gone is dropped too; any other failure is thrown, the row kept.
|
|
31
|
+
*/
|
|
32
|
+
readonly remove: (conversation: ConversationSummary) => Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* The person goes on with a past conversation: pinned for its key and opened through the backend's resume when the
|
|
35
|
+
* app shows it (`AgentChat` with `keyOf(conversation)`, or `show()` on what this returns).
|
|
36
|
+
*/
|
|
37
|
+
readonly continue: (conversation: ConversationSummary) => AgentConversation;
|
|
38
|
+
}
|
|
39
|
+
/** The person's past conversations, read as the component mounts, newest activity first. */
|
|
40
|
+
declare function useAgentHistory(options: UseAgentHistoryOptions): UseAgentHistory;
|
|
41
|
+
interface UseAgentTranscript {
|
|
42
|
+
readonly state: AgentTranscriptState;
|
|
43
|
+
/** Reads the newest page anew. */
|
|
44
|
+
readonly load: () => void;
|
|
45
|
+
/** The page before the earliest read, prepended. */
|
|
46
|
+
readonly loadEarlier: () => void;
|
|
47
|
+
/** Reads again the page that failed: the newest, or the earlier one. */
|
|
48
|
+
readonly retry: () => void;
|
|
49
|
+
}
|
|
50
|
+
/** A past conversation read back, newest page first, as the component mounts. */
|
|
51
|
+
declare function useAgentTranscript(conversationId: string, options?: {
|
|
52
|
+
readonly pageSize?: number;
|
|
53
|
+
}): UseAgentTranscript;
|
|
54
|
+
|
|
55
|
+
export { type UseAgentHistory, type UseAgentHistoryOptions, type UseAgentTranscript, useAgentHistory, useAgentTranscript };
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { useAgentRuntime } from './chunk-V4UBOVTK.js';
|
|
2
|
+
import { createAgentHistory, continueKey, createAgentTranscript } from '@vinaverse/client/history';
|
|
3
|
+
import { useMemo, useSyncExternalStore, useEffect, useCallback } from 'react';
|
|
4
|
+
|
|
5
|
+
function useAgentHistory(options) {
|
|
6
|
+
const runtime = useAgentRuntime();
|
|
7
|
+
const { subject, mode, thread, pageSize } = options;
|
|
8
|
+
const scope = options.scope ?? null;
|
|
9
|
+
const agent = options.agent ?? null;
|
|
10
|
+
const history = useMemo(
|
|
11
|
+
() => createAgentHistory({
|
|
12
|
+
runtime,
|
|
13
|
+
mode,
|
|
14
|
+
scope,
|
|
15
|
+
agent,
|
|
16
|
+
...pageSize === void 0 ? {} : { pageSize }
|
|
17
|
+
}),
|
|
18
|
+
[runtime, mode, scope, agent, pageSize]
|
|
19
|
+
);
|
|
20
|
+
const state = useSyncExternalStore(
|
|
21
|
+
history.subscribe,
|
|
22
|
+
history.getSnapshot,
|
|
23
|
+
history.getSnapshot
|
|
24
|
+
);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
if (!state.started) history.refresh();
|
|
27
|
+
}, [history, state.started]);
|
|
28
|
+
const keyOf = useCallback(
|
|
29
|
+
(conversation) => continueKey(conversation, subject, thread),
|
|
30
|
+
[subject, thread]
|
|
31
|
+
);
|
|
32
|
+
return {
|
|
33
|
+
state,
|
|
34
|
+
refresh: history.refresh,
|
|
35
|
+
loadMore: history.loadMore,
|
|
36
|
+
retry: history.retry,
|
|
37
|
+
keyOf,
|
|
38
|
+
remove: useCallback(
|
|
39
|
+
(conversation) => history.remove(keyOf(conversation), conversation.id),
|
|
40
|
+
[history, keyOf]
|
|
41
|
+
),
|
|
42
|
+
continue: useCallback(
|
|
43
|
+
(conversation) => runtime.continue(keyOf(conversation), conversation.id),
|
|
44
|
+
[runtime, keyOf]
|
|
45
|
+
)
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function useAgentTranscript(conversationId, options = {}) {
|
|
49
|
+
const runtime = useAgentRuntime();
|
|
50
|
+
const { pageSize } = options;
|
|
51
|
+
const transcript = useMemo(
|
|
52
|
+
() => createAgentTranscript({
|
|
53
|
+
runtime,
|
|
54
|
+
conversationId,
|
|
55
|
+
...pageSize === void 0 ? {} : { pageSize }
|
|
56
|
+
}),
|
|
57
|
+
[runtime, conversationId, pageSize]
|
|
58
|
+
);
|
|
59
|
+
const state = useSyncExternalStore(
|
|
60
|
+
transcript.subscribe,
|
|
61
|
+
transcript.getSnapshot,
|
|
62
|
+
transcript.getSnapshot
|
|
63
|
+
);
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
if (!state.started) transcript.load();
|
|
66
|
+
}, [transcript, state.started]);
|
|
67
|
+
return {
|
|
68
|
+
state,
|
|
69
|
+
load: transcript.load,
|
|
70
|
+
loadEarlier: transcript.loadEarlier,
|
|
71
|
+
retry: transcript.retry
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export { useAgentHistory, useAgentTranscript };
|
|
76
|
+
//# sourceMappingURL=history.js.map
|
|
77
|
+
//# sourceMappingURL=history.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/history.tsx"],"names":[],"mappings":";;;;AAuDO,SAAS,gBACd,OAAA,EACiB;AACjB,EAAA,MAAM,UAAU,eAAA,EAAgB;AAChC,EAAA,MAAM,EAAE,OAAA,EAAS,IAAA,EAAM,MAAA,EAAQ,UAAS,GAAI,OAAA;AAC5C,EAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,IAAA;AAC/B,EAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,IAAA;AAC/B,EAAA,MAAM,OAAA,GAAU,OAAA;AAAA,IACd,MACE,kBAAA,CAAmB;AAAA,MACjB,OAAA;AAAA,MACA,IAAA;AAAA,MACA,KAAA;AAAA,MACA,KAAA;AAAA,MACA,GAAI,QAAA,KAAa,MAAA,GAAY,E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,UAAA,GAAa,OAAA;AAAA,IACjB,MACE,qBAAA,CAAsB;AAAA,MACpB,OAAA;AAAA,MACA,cAAA;AAAA,MACA,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS,KAC9C,CAAA;AAAA,IACH,CAAC,OAAA,EAAS,cAAA,EAAgB,QAAQ;AAAA,GACpC;AACA,EAAA,MAAM,KAAA,GAAQ,oBAAA;AAAA,IACZ,UAAA,CAAW,SAAA;AAAA,IACX,UAAA,CAAW,WAAA;AAAA,IACX,UAAA,CAAW;AAAA,GACb;AACA,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,EAAS,UAAA,CAAW,IAAA,EAAK;AAAA,EACtC,CAAA,EAAG,CAAC,UAAA,EAAY,KAAA,CAAM,OAAO,CAAC,CAAA;AAC9B,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,MAAM,UAAA,CAAW,IAAA;AAAA,IACjB,aAAa,UAAA,CAAW,WAAA;AAAA,IACxB,OAAO,UAAA,CAAW;AAAA,GACpB;AACF","file":"history.js","sourcesContent":["// React bindings of a person's history (@vinaverse/client/history): the list of their past conversations and one\n// read back, each a store subscribed to while a component is mounted; delete and continue through the runtime. An\n// entry of its own, so an app that draws no history ships none of it. No react-native or DOM import.\nimport type { AgentConversation, AgentKey } from '@vinaverse/client/agent';\nimport {\n type AgentHistory,\n type AgentHistoryState,\n type AgentTranscript,\n type AgentTranscriptState,\n type ConversationSummary,\n continueKey,\n createAgentHistory,\n createAgentTranscript,\n} from '@vinaverse/client/history';\nimport { useCallback, useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { useAgentRuntime } from './agent.js';\n\nexport interface UseAgentHistoryOptions {\n /** The person signed in (null for a guest): the key a conversation continues or is deleted under. */\n readonly subject: string | null;\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 /** The thread a continued conversation runs in; default `chat`. */\n readonly thread?: string;\n /** Conversations per page (1–50). Default 20. */\n readonly pageSize?: number;\n}\n\nexport interface UseAgentHistory {\n readonly state: AgentHistoryState;\n /** Reads the first page anew (after a failure, or to see what changed). */\n readonly refresh: () => void;\n /** The next older page, when there is one and none is being read. */\n readonly loadMore: () => void;\n /** Reads again the page that failed: the first, or the next. */\n readonly retry: () => void;\n /** The key the conversation continues under for this person (`continueKey`). */\n readonly keyOf: (conversation: ConversationSummary) => AgentKey;\n /**\n * Deletes the conversation at the backend and drops its row; the device forgets it only where its key still\n * continues it. One already gone is dropped too; any other failure is thrown, the row kept.\n */\n readonly remove: (conversation: ConversationSummary) => Promise<void>;\n /**\n * The person goes on with a past conversation: pinned for its key and opened through the backend's resume when the\n * app shows it (`AgentChat` with `keyOf(conversation)`, or `show()` on what this returns).\n */\n readonly continue: (conversation: ConversationSummary) => AgentConversation;\n}\n\n/** The person's past conversations, read as the component mounts, newest activity first. */\nexport function useAgentHistory(\n options: UseAgentHistoryOptions,\n): UseAgentHistory {\n const runtime = useAgentRuntime();\n const { subject, mode, thread, pageSize } = options;\n const scope = options.scope ?? null;\n const agent = options.agent ?? null;\n const history = useMemo<AgentHistory>(\n () =>\n createAgentHistory({\n runtime,\n mode,\n scope,\n agent,\n ...(pageSize === undefined ? {} : { pageSize }),\n }),\n [runtime, mode, scope, agent, pageSize],\n );\n const state = useSyncExternalStore(\n history.subscribe,\n history.getSnapshot,\n history.getSnapshot,\n );\n useEffect(() => {\n if (!state.started) history.refresh();\n }, [history, state.started]);\n const keyOf = useCallback(\n (conversation: ConversationSummary) =>\n continueKey(conversation, subject, thread),\n [subject, thread],\n );\n return {\n state,\n refresh: history.refresh,\n loadMore: history.loadMore,\n retry: history.retry,\n keyOf,\n remove: useCallback(\n (conversation: ConversationSummary) =>\n history.remove(keyOf(conversation), conversation.id),\n [history, keyOf],\n ),\n continue: useCallback(\n (conversation: ConversationSummary) =>\n runtime.continue(keyOf(conversation), conversation.id),\n [runtime, keyOf],\n ),\n };\n}\n\nexport interface UseAgentTranscript {\n readonly state: AgentTranscriptState;\n /** Reads the newest page anew. */\n readonly load: () => void;\n /** The page before the earliest read, prepended. */\n readonly loadEarlier: () => void;\n /** Reads again the page that failed: the newest, or the earlier one. */\n readonly retry: () => void;\n}\n\n/** A past conversation read back, newest page first, as the component mounts. */\nexport function useAgentTranscript(\n conversationId: string,\n options: { readonly pageSize?: number } = {},\n): UseAgentTranscript {\n const runtime = useAgentRuntime();\n const { pageSize } = options;\n const transcript = useMemo<AgentTranscript>(\n () =>\n createAgentTranscript({\n runtime,\n conversationId,\n ...(pageSize === undefined ? {} : { pageSize }),\n }),\n [runtime, conversationId, pageSize],\n );\n const state = useSyncExternalStore(\n transcript.subscribe,\n transcript.getSnapshot,\n transcript.getSnapshot,\n );\n useEffect(() => {\n if (!state.started) transcript.load();\n }, [transcript, state.started]);\n return {\n state,\n load: transcript.load,\n loadEarlier: transcript.loadEarlier,\n retry: transcript.retry,\n };\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -88,6 +88,10 @@ Object.defineProperty(exports, "formatDate", {
|
|
|
88
88
|
enumerable: true,
|
|
89
89
|
get: function () { return copy.formatDate; }
|
|
90
90
|
});
|
|
91
|
+
Object.defineProperty(exports, "formatDateTime", {
|
|
92
|
+
enumerable: true,
|
|
93
|
+
get: function () { return copy.formatDateTime; }
|
|
94
|
+
});
|
|
91
95
|
Object.defineProperty(exports, "formatDayTime", {
|
|
92
96
|
enumerable: true,
|
|
93
97
|
get: function () { return copy.formatDayTime; }
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Translate, CopyOverrides } from '@vinaverse/tokens/copy';
|
|
2
|
-
export { AI_MARK, BANNED_WORDS, COPY, Copy, CopyKey, CopyOverrides, Translate, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
2
|
+
export { AI_MARK, BANNED_WORDS, COPY, Copy, CopyKey, CopyOverrides, Translate, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDateTime, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
3
3
|
import { ReactNode } from 'react';
|
|
4
4
|
import { ConversationView, StreamingText } from '@vinaverse/client/conversation';
|
|
5
5
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Translate, CopyOverrides } from '@vinaverse/tokens/copy';
|
|
2
|
-
export { AI_MARK, BANNED_WORDS, COPY, Copy, CopyKey, CopyOverrides, Translate, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
2
|
+
export { AI_MARK, BANNED_WORDS, COPY, Copy, CopyKey, CopyOverrides, Translate, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDateTime, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
3
3
|
import { ReactNode } from 'react';
|
|
4
4
|
import { ConversationView, StreamingText } from '@vinaverse/client/conversation';
|
|
5
5
|
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createTranslate, textDirection } from '@vinaverse/tokens/copy';
|
|
2
|
-
export { AI_MARK, BANNED_WORDS, COPY, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
2
|
+
export { AI_MARK, BANNED_WORDS, COPY, bannedWordsIn, builtInCopy, createTranslate, formatDate, formatDateTime, formatDayTime, formatMoney, formatTimeRange, textDirection } from '@vinaverse/tokens/copy';
|
|
3
3
|
import { useMemo, useContext, useSyncExternalStore, useRef, useCallback, createContext } from 'react';
|
|
4
4
|
import { jsx } from 'react/jsx-runtime';
|
|
5
5
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vinaverse/react",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.12",
|
|
4
4
|
"description": "Vinaverse for React: hooks over the conversation store, and the copy and formatting every Vinaverse React UI shares. No react-native or DOM import.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Vinaverse, Inc.",
|
|
@@ -47,6 +47,20 @@
|
|
|
47
47
|
"default": "./dist/agent.cjs"
|
|
48
48
|
}
|
|
49
49
|
},
|
|
50
|
+
"./history": {
|
|
51
|
+
"react-native": {
|
|
52
|
+
"types": "./dist/history.d.cts",
|
|
53
|
+
"default": "./dist/history.cjs"
|
|
54
|
+
},
|
|
55
|
+
"import": {
|
|
56
|
+
"types": "./dist/history.d.ts",
|
|
57
|
+
"default": "./dist/history.js"
|
|
58
|
+
},
|
|
59
|
+
"require": {
|
|
60
|
+
"types": "./dist/history.d.cts",
|
|
61
|
+
"default": "./dist/history.cjs"
|
|
62
|
+
}
|
|
63
|
+
},
|
|
50
64
|
"./package.json": "./package.json"
|
|
51
65
|
},
|
|
52
66
|
"main": "./dist/index.cjs",
|
|
@@ -56,8 +70,8 @@
|
|
|
56
70
|
"dist"
|
|
57
71
|
],
|
|
58
72
|
"dependencies": {
|
|
59
|
-
"@vinaverse/client": "0.1.0-alpha.
|
|
60
|
-
"@vinaverse/tokens": "0.1.0-alpha.
|
|
73
|
+
"@vinaverse/client": "0.1.0-alpha.12",
|
|
74
|
+
"@vinaverse/tokens": "0.1.0-alpha.12"
|
|
61
75
|
},
|
|
62
76
|
"peerDependencies": {
|
|
63
77
|
"react": ">=19.1"
|
|
@@ -76,7 +90,8 @@
|
|
|
76
90
|
"react/jsx-runtime",
|
|
77
91
|
"@vinaverse/client",
|
|
78
92
|
"@vinaverse/tokens/copy",
|
|
79
|
-
"@vinaverse/client/agent"
|
|
93
|
+
"@vinaverse/client/agent",
|
|
94
|
+
"@vinaverse/client/history"
|
|
80
95
|
],
|
|
81
96
|
"limit": "1.5 kB"
|
|
82
97
|
},
|
|
@@ -89,7 +104,22 @@
|
|
|
89
104
|
"react/jsx-runtime",
|
|
90
105
|
"@vinaverse/client",
|
|
91
106
|
"@vinaverse/tokens/copy",
|
|
92
|
-
"@vinaverse/client/agent"
|
|
107
|
+
"@vinaverse/client/agent",
|
|
108
|
+
"@vinaverse/client/history"
|
|
109
|
+
],
|
|
110
|
+
"limit": "1.5 kB"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"name": "@vinaverse/react/history (ESM, everything; react and the other @vinaverse packages excluded)",
|
|
114
|
+
"path": "dist/history.js",
|
|
115
|
+
"import": "*",
|
|
116
|
+
"ignore": [
|
|
117
|
+
"react",
|
|
118
|
+
"react/jsx-runtime",
|
|
119
|
+
"@vinaverse/client",
|
|
120
|
+
"@vinaverse/tokens/copy",
|
|
121
|
+
"@vinaverse/client/agent",
|
|
122
|
+
"@vinaverse/client/history"
|
|
93
123
|
],
|
|
94
124
|
"limit": "1.5 kB"
|
|
95
125
|
}
|
|
@@ -98,6 +128,9 @@
|
|
|
98
128
|
"*": {
|
|
99
129
|
"agent": [
|
|
100
130
|
"./dist/agent.d.cts"
|
|
131
|
+
],
|
|
132
|
+
"history": [
|
|
133
|
+
"./dist/history.d.cts"
|
|
101
134
|
]
|
|
102
135
|
}
|
|
103
136
|
},
|