@lumavox/react 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +84 -2
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/provider.d.ts +33 -0
- package/dist/provider.js +60 -0
- package/dist/read.d.ts +30 -0
- package/dist/read.js +71 -0
- package/dist/use-agent.d.ts +101 -0
- package/dist/use-agent.js +363 -0
- package/dist/use-facts.d.ts +15 -0
- package/dist/use-facts.js +24 -0
- package/dist/use-relation.d.ts +10 -0
- package/dist/use-relation.js +27 -0
- package/dist/use-sessions.d.ts +19 -0
- package/dist/use-sessions.js +65 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lumavox
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lumavox/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React and React Native hooks for Lumavox agents, over
|
|
4
|
+
[`@lumavox/client`](https://www.npmjs.com/package/@lumavox/client): a
|
|
5
|
+
conversation that keeps itself connected, the person's sessions, what is
|
|
6
|
+
remembered about them, and how each agent feels about them. React 18 or
|
|
7
|
+
later; no other dependency.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @lumavox/react @lumavox/client
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { createClient } from "@lumavox/client";
|
|
15
|
+
import { AgentProvider, useAgent } from "@lumavox/react";
|
|
16
|
+
|
|
17
|
+
const lumavox = createClient({
|
|
18
|
+
getToken: async () => (await fetch("/api/lumavox-key")).text(),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export function App() {
|
|
22
|
+
return (
|
|
23
|
+
<AgentProvider client={lumavox}>
|
|
24
|
+
<Chat />
|
|
25
|
+
</AgentProvider>
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function Chat() {
|
|
30
|
+
const agent = useAgent({ agentId: "agt_..." });
|
|
31
|
+
return (
|
|
32
|
+
<>
|
|
33
|
+
<p>{agent.turn?.text}</p>
|
|
34
|
+
<button disabled={agent.state === "connecting"} onClick={() => agent.send("Hello!")}>
|
|
35
|
+
Say hello
|
|
36
|
+
</button>
|
|
37
|
+
</>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The guide, with every example: the docs' **SDKs** tab, *React*.
|
|
43
|
+
|
|
44
|
+
## `useAgent(target, options)`
|
|
45
|
+
|
|
46
|
+
`target` is `{ agentId, resume?, title? }` — the person's last
|
|
47
|
+
conversation with the agent by default, a new one with `resume: false` —
|
|
48
|
+
or `{ sessionId }`. It opens the session on mount, connects, and closes on
|
|
49
|
+
unmount; handlers live in a ref, so new ones on every render never
|
|
50
|
+
redial.
|
|
51
|
+
|
|
52
|
+
| Returns | |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `state` `ready` `turn` `caption` `relation` `queued` | the conversation's snapshot |
|
|
55
|
+
| `session` | the session it opened, with its last messages |
|
|
56
|
+
| `error` | `{ kind, message }`: the session, an `error` frame, the close, the microphone |
|
|
57
|
+
| `speaking` `recording` | the adapter is playing; the recorder is open |
|
|
58
|
+
| `send` `startAudio` `sendAudio` `endAudio` `cancel` `mute` `reconnect` `close` | the conversation's |
|
|
59
|
+
| `startRecording` `stopRecording({ transcribeOnly, discard })` | through the `audio` adapter |
|
|
60
|
+
| `newSession()` | a new conversation with the same agent |
|
|
61
|
+
| `conversation` | the `Conversation` itself |
|
|
62
|
+
|
|
63
|
+
Every `@lumavox/client` handler is an option (`onText`, `onDone`, …), and
|
|
64
|
+
`speech` and `thoughts`. **`audio`**, an `AgentAudio` — a player and a
|
|
65
|
+
recorder — makes replies audible and `startRecording` work: replies play
|
|
66
|
+
as they arrive and stop on `cancel`, `mute` or a new message; recording
|
|
67
|
+
opens the microphone first and the recording at the rate it was granted.
|
|
68
|
+
Without an adapter or an `onAudio`, no speech is asked for. The SDK ships
|
|
69
|
+
no player or recorder in this release: write one on Web Audio, or on your
|
|
70
|
+
React Native audio library.
|
|
71
|
+
|
|
72
|
+
## Reading
|
|
73
|
+
|
|
74
|
+
Each returns `{ data, error, loading, refresh }`, with `error` a
|
|
75
|
+
`PlatformError`; there is no shared cache — on TanStack Query, call
|
|
76
|
+
`client.*` in your own queries instead.
|
|
77
|
+
|
|
78
|
+
| Hook | |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `useSessions({ limit, offset })` | a page of the person's conversations |
|
|
81
|
+
| `useSession(id)` | one, with `messages`, `hasOlder` and `loadOlder()` |
|
|
82
|
+
| `useFacts()` | what is remembered, with `forget(id)` and `forgetAll()` |
|
|
83
|
+
| `useRelation(agentId)` | live from an open `useAgent` under the same provider, else read once |
|
|
84
|
+
|
|
85
|
+
MIT, copyright Lumavox.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lumavox/react`: hooks for React and React Native alike, over
|
|
3
|
+
* `@lumavox/client` — `useAgent` for a conversation, and `useSessions`,
|
|
4
|
+
* `useSession`, `useFacts` and `useRelation` for what the REST routes
|
|
5
|
+
* read. `useSyncExternalStore`, and nothing else of React's that 18 lacks;
|
|
6
|
+
* no data library: an app on TanStack Query calls `client.*` itself.
|
|
7
|
+
*/
|
|
8
|
+
export { AgentProvider, type AgentProviderProps, useClient, } from "./provider.js";
|
|
9
|
+
export { asPlatformError, type Read } from "./read.js";
|
|
10
|
+
export { type AgentControls, type AgentError, type AgentTarget, type RecordingOptions, type StopRecordingOptions, type UseAgentOptions, useAgent, } from "./use-agent.js";
|
|
11
|
+
export { type FactsRead, useFacts } from "./use-facts.js";
|
|
12
|
+
export { useRelation } from "./use-relation.js";
|
|
13
|
+
export { type SessionRead, useSession, useSessions, } from "./use-sessions.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lumavox/react`: hooks for React and React Native alike, over
|
|
3
|
+
* `@lumavox/client` — `useAgent` for a conversation, and `useSessions`,
|
|
4
|
+
* `useSession`, `useFacts` and `useRelation` for what the REST routes
|
|
5
|
+
* read. `useSyncExternalStore`, and nothing else of React's that 18 lacks;
|
|
6
|
+
* no data library: an app on TanStack Query calls `client.*` itself.
|
|
7
|
+
*/
|
|
8
|
+
export { AgentProvider, useClient, } from "./provider.js";
|
|
9
|
+
export { asPlatformError } from "./read.js";
|
|
10
|
+
export { useAgent, } from "./use-agent.js";
|
|
11
|
+
export { useFacts } from "./use-facts.js";
|
|
12
|
+
export { useRelation } from "./use-relation.js";
|
|
13
|
+
export { useSession, useSessions, } from "./use-sessions.js";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<AgentProvider client>`: the `@lumavox/client` every hook below it
|
|
3
|
+
* uses — and a register of the conversations `useAgent` holds open, by
|
|
4
|
+
* agent, so `useRelation` reads one live instead of asking the API. Every
|
|
5
|
+
* hook also takes `client` directly, for an app with no provider.
|
|
6
|
+
*/
|
|
7
|
+
import type { Client, Conversation } from "@lumavox/client";
|
|
8
|
+
import { type ReactNode } from "react";
|
|
9
|
+
/** The conversations open under a provider, by agent id. */
|
|
10
|
+
export declare class Live {
|
|
11
|
+
private readonly open;
|
|
12
|
+
private readonly listeners;
|
|
13
|
+
get(agentId: string): Conversation | null;
|
|
14
|
+
/** `conversation` talks to `agentId`; answers the unregister. */
|
|
15
|
+
add(agentId: string, conversation: Conversation): () => void;
|
|
16
|
+
subscribe(fn: () => void): () => void;
|
|
17
|
+
private changed;
|
|
18
|
+
}
|
|
19
|
+
interface Provided {
|
|
20
|
+
client: Client;
|
|
21
|
+
live: Live;
|
|
22
|
+
}
|
|
23
|
+
export interface AgentProviderProps {
|
|
24
|
+
client: Client;
|
|
25
|
+
children?: ReactNode;
|
|
26
|
+
}
|
|
27
|
+
/** The client for every hook below it. Make the client once, outside render. */
|
|
28
|
+
export declare function AgentProvider({ client, children }: AgentProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<Provided | null>>;
|
|
29
|
+
/** The client a hook uses: its own `client`, or the provider's. */
|
|
30
|
+
export declare function useClient(client?: Client): Client;
|
|
31
|
+
/** The provider's register of open conversations, or `null` without one. */
|
|
32
|
+
export declare function useLive(): Live | null;
|
|
33
|
+
export {};
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, } from "react";
|
|
2
|
+
/** The conversations open under a provider, by agent id. */
|
|
3
|
+
export class Live {
|
|
4
|
+
constructor() {
|
|
5
|
+
this.open = new Map();
|
|
6
|
+
this.listeners = new Set();
|
|
7
|
+
}
|
|
8
|
+
get(agentId) {
|
|
9
|
+
return this.open.get(agentId) ?? null;
|
|
10
|
+
}
|
|
11
|
+
/** `conversation` talks to `agentId`; answers the unregister. */
|
|
12
|
+
add(agentId, conversation) {
|
|
13
|
+
this.open.set(agentId, conversation);
|
|
14
|
+
this.changed();
|
|
15
|
+
return () => {
|
|
16
|
+
if (this.open.get(agentId) === conversation)
|
|
17
|
+
this.open.delete(agentId);
|
|
18
|
+
this.changed();
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
subscribe(fn) {
|
|
22
|
+
this.listeners.add(fn);
|
|
23
|
+
return () => {
|
|
24
|
+
this.listeners.delete(fn);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
changed() {
|
|
28
|
+
for (const fn of this.listeners)
|
|
29
|
+
fn();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const Context = createContext(null);
|
|
33
|
+
/** The client for every hook below it. Make the client once, outside render. */
|
|
34
|
+
export function AgentProvider({ client, children }) {
|
|
35
|
+
const provided = useProvided(client);
|
|
36
|
+
return createElement(Context.Provider, { value: provided }, children);
|
|
37
|
+
}
|
|
38
|
+
const registers = new WeakMap();
|
|
39
|
+
/** One register per client, however often the provider renders. */
|
|
40
|
+
function useProvided(client) {
|
|
41
|
+
let provided = registers.get(client);
|
|
42
|
+
if (!provided) {
|
|
43
|
+
provided = { client, live: new Live() };
|
|
44
|
+
registers.set(client, provided);
|
|
45
|
+
}
|
|
46
|
+
return provided;
|
|
47
|
+
}
|
|
48
|
+
/** The client a hook uses: its own `client`, or the provider's. */
|
|
49
|
+
export function useClient(client) {
|
|
50
|
+
const provided = useContext(Context);
|
|
51
|
+
const chosen = client ?? provided?.client;
|
|
52
|
+
if (!chosen) {
|
|
53
|
+
throw new Error("No Lumavox client: wrap the app in <AgentProvider client={…}>, or pass `client` to the hook.");
|
|
54
|
+
}
|
|
55
|
+
return chosen;
|
|
56
|
+
}
|
|
57
|
+
/** The provider's register of open conversations, or `null` without one. */
|
|
58
|
+
export function useLive() {
|
|
59
|
+
return useContext(Context)?.live ?? null;
|
|
60
|
+
}
|
package/dist/read.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every read hook answers — `{ data, error, loading, refresh }` — and
|
|
3
|
+
* nothing shared between them: no cache, so two components reading the
|
|
4
|
+
* same thing read it twice. An app on TanStack Query calls `client.*` in
|
|
5
|
+
* its own queries instead.
|
|
6
|
+
*
|
|
7
|
+
* **A late answer is dropped quietly**: one for a component gone, or for a
|
|
8
|
+
* read a newer one replaced — never a state update after unmount, never
|
|
9
|
+
* an older page over a newer one.
|
|
10
|
+
*/
|
|
11
|
+
import { PlatformError } from "@lumavox/client";
|
|
12
|
+
export interface Read<T> {
|
|
13
|
+
/** The answer; `null` until the first arrives. */
|
|
14
|
+
data: T | null;
|
|
15
|
+
/** Why the last read failed; cleared by the next that succeeds. */
|
|
16
|
+
error: PlatformError | null;
|
|
17
|
+
loading: boolean;
|
|
18
|
+
/** Read again. Answers once it has. */
|
|
19
|
+
refresh(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
/** Any failure as a `PlatformError`: `getToken`'s own included. */
|
|
22
|
+
export declare function asPlatformError(error: unknown): PlatformError;
|
|
23
|
+
/**
|
|
24
|
+
* `load`, run on mount and whenever `key` changes — not while it is
|
|
25
|
+
* `null` — and its answer as a `Read`. `set` changes `data` in place,
|
|
26
|
+
* after a delete, say, without a read.
|
|
27
|
+
*/
|
|
28
|
+
export declare function useRead<T>(key: string | null, load: () => Promise<T>): Read<T> & {
|
|
29
|
+
set(change: (data: T | null) => T | null): void;
|
|
30
|
+
};
|
package/dist/read.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every read hook answers — `{ data, error, loading, refresh }` — and
|
|
3
|
+
* nothing shared between them: no cache, so two components reading the
|
|
4
|
+
* same thing read it twice. An app on TanStack Query calls `client.*` in
|
|
5
|
+
* its own queries instead.
|
|
6
|
+
*
|
|
7
|
+
* **A late answer is dropped quietly**: one for a component gone, or for a
|
|
8
|
+
* read a newer one replaced — never a state update after unmount, never
|
|
9
|
+
* an older page over a newer one.
|
|
10
|
+
*/
|
|
11
|
+
import { PlatformError } from "@lumavox/client";
|
|
12
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
13
|
+
/** Any failure as a `PlatformError`: `getToken`'s own included. */
|
|
14
|
+
export function asPlatformError(error) {
|
|
15
|
+
if (error instanceof PlatformError)
|
|
16
|
+
return error;
|
|
17
|
+
return new PlatformError({
|
|
18
|
+
status: 0,
|
|
19
|
+
type: "client_error",
|
|
20
|
+
message: error instanceof Error ? error.message : String(error),
|
|
21
|
+
requestId: null,
|
|
22
|
+
cause: error,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* `load`, run on mount and whenever `key` changes — not while it is
|
|
27
|
+
* `null` — and its answer as a `Read`. `set` changes `data` in place,
|
|
28
|
+
* after a delete, say, without a read.
|
|
29
|
+
*/
|
|
30
|
+
export function useRead(key, load) {
|
|
31
|
+
const [data, setData] = useState(null);
|
|
32
|
+
const [error, setError] = useState(null);
|
|
33
|
+
const [loading, setLoading] = useState(key !== null);
|
|
34
|
+
const latest = useRef(0);
|
|
35
|
+
const mounted = useRef(true);
|
|
36
|
+
const loader = useRef(load);
|
|
37
|
+
loader.current = load;
|
|
38
|
+
const refresh = useCallback(async () => {
|
|
39
|
+
const mine = ++latest.current;
|
|
40
|
+
setLoading(true);
|
|
41
|
+
try {
|
|
42
|
+
const answer = await loader.current();
|
|
43
|
+
if (mounted.current && mine === latest.current) {
|
|
44
|
+
setData(answer);
|
|
45
|
+
setError(null);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch (failure) {
|
|
49
|
+
// swallowed: it is the hook's `error`, the caller's to show.
|
|
50
|
+
if (mounted.current && mine === latest.current) {
|
|
51
|
+
setError(asPlatformError(failure));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
if (mounted.current && mine === latest.current)
|
|
56
|
+
setLoading(false);
|
|
57
|
+
}
|
|
58
|
+
}, []);
|
|
59
|
+
useEffect(() => {
|
|
60
|
+
mounted.current = true;
|
|
61
|
+
if (key !== null)
|
|
62
|
+
void refresh();
|
|
63
|
+
return () => {
|
|
64
|
+
mounted.current = false;
|
|
65
|
+
};
|
|
66
|
+
}, [key, refresh]);
|
|
67
|
+
const set = useCallback((change) => {
|
|
68
|
+
setData((current) => change(current));
|
|
69
|
+
}, []);
|
|
70
|
+
return { data, error, loading, refresh, set };
|
|
71
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useAgent`: a conversation with an agent, for a component — opened on
|
|
3
|
+
* mount (`sessions.create`, then `connect`), closed on unmount, its
|
|
4
|
+
* `snapshot` rendered through `useSyncExternalStore`.
|
|
5
|
+
*
|
|
6
|
+
* - **Handlers in a ref**: every render may pass new ones, and none
|
|
7
|
+
* redials. The conversation is made once per session.
|
|
8
|
+
* - **Audio through an `AgentAudio`** (`@lumavox/client`): every reply
|
|
9
|
+
* frame is played, and playback stops on `cancel`, `mute`, a `send` or a
|
|
10
|
+
* spoken turn — and stays stopped for the rest of that reply's frames,
|
|
11
|
+
* which keep arriving for a moment. `startRecording` opens the recorder
|
|
12
|
+
* *then* the recording, at the rate the recorder was granted, so a
|
|
13
|
+
* refused microphone never opens a window on the socket. The adapter is
|
|
14
|
+
* the app's: the hook never disposes it.
|
|
15
|
+
* - **A late answer is dropped quietly**: a session opened after unmount
|
|
16
|
+
* is never connected, and a press released while the microphone was
|
|
17
|
+
* still opening gives it back.
|
|
18
|
+
*/
|
|
19
|
+
import { type AgentAudio, type Client, type CloseInfo, type ConnectOptions, type Conversation, type ConversationHandlers, type ErrorFrame, type PlatformError, type SessionDetail, type Snapshot, type StartAudioOptions, type TranscriptOutcome, type TurnOptions, type TurnOutcome } from "@lumavox/client";
|
|
20
|
+
/** Whom to talk to; `null` for nobody yet — nothing is opened. */
|
|
21
|
+
export type AgentTarget =
|
|
22
|
+
/** An agent: the person's last conversation with it, by default — `resume: false` for a new one. */
|
|
23
|
+
{
|
|
24
|
+
agentId: string;
|
|
25
|
+
resume?: boolean;
|
|
26
|
+
title?: string;
|
|
27
|
+
}
|
|
28
|
+
/** A conversation already opened. */
|
|
29
|
+
| {
|
|
30
|
+
sessionId: string;
|
|
31
|
+
};
|
|
32
|
+
export interface UseAgentOptions extends ConversationHandlers, ConnectOptions {
|
|
33
|
+
/** The client, when there is no `<AgentProvider>`. */
|
|
34
|
+
client?: Client;
|
|
35
|
+
/** A player and a recorder: replies are played, and `startRecording` records. Yours to dispose. */
|
|
36
|
+
audio?: AgentAudio;
|
|
37
|
+
}
|
|
38
|
+
/** What went wrong last; cleared by the next turn. */
|
|
39
|
+
export type AgentError =
|
|
40
|
+
/** Opening the session failed: the API's answer. */
|
|
41
|
+
{
|
|
42
|
+
kind: "session";
|
|
43
|
+
message: string;
|
|
44
|
+
error: PlatformError;
|
|
45
|
+
}
|
|
46
|
+
/** The edge's `error` frame. */
|
|
47
|
+
| {
|
|
48
|
+
kind: "frame";
|
|
49
|
+
message: string;
|
|
50
|
+
frame: ErrorFrame;
|
|
51
|
+
}
|
|
52
|
+
/** The conversation ended and will not reconnect. */
|
|
53
|
+
| {
|
|
54
|
+
kind: "closed";
|
|
55
|
+
message: string;
|
|
56
|
+
close: CloseInfo;
|
|
57
|
+
}
|
|
58
|
+
/** The microphone: refused, failed, or at a rate the socket does not take. */
|
|
59
|
+
| {
|
|
60
|
+
kind: "audio";
|
|
61
|
+
message: string;
|
|
62
|
+
error: unknown;
|
|
63
|
+
};
|
|
64
|
+
export interface RecordingOptions {
|
|
65
|
+
/** Hz to ask the recorder for: 16,000 by default. It must grant one of `RECORDING_RATES`. */
|
|
66
|
+
rate?: number;
|
|
67
|
+
/** A dictation: the reply being spoken plays on. */
|
|
68
|
+
transcribeOnly?: boolean;
|
|
69
|
+
}
|
|
70
|
+
export interface StopRecordingOptions {
|
|
71
|
+
/** No turn: this recording's words, answered by `stopRecording`. */
|
|
72
|
+
transcribeOnly?: boolean;
|
|
73
|
+
/** Throw it away: the recording is cancelled, and so is a turn running. */
|
|
74
|
+
discard?: boolean;
|
|
75
|
+
}
|
|
76
|
+
export interface AgentControls extends Snapshot {
|
|
77
|
+
/** The session `useAgent` opened — with its last messages — or `null` for a `sessionId`. */
|
|
78
|
+
session: SessionDetail | null;
|
|
79
|
+
error: AgentError | null;
|
|
80
|
+
/** The adapter is playing a reply. */
|
|
81
|
+
speaking: boolean;
|
|
82
|
+
/** The recorder is open. */
|
|
83
|
+
recording: boolean;
|
|
84
|
+
/** The conversation itself, once it is made. */
|
|
85
|
+
conversation: Conversation | null;
|
|
86
|
+
send(text: string, options?: TurnOptions): Promise<TurnOutcome>;
|
|
87
|
+
startAudio(options: StartAudioOptions): string | null;
|
|
88
|
+
sendAudio(pcm: ArrayBuffer | Int16Array): boolean;
|
|
89
|
+
endAudio: Conversation["endAudio"];
|
|
90
|
+
/** Open the recorder, then the recording. Answers whether it is recording. */
|
|
91
|
+
startRecording(options?: RecordingOptions): Promise<boolean>;
|
|
92
|
+
/** Close the recorder and end the recording: as a turn, as words, or discarded. */
|
|
93
|
+
stopRecording(options?: StopRecordingOptions): Promise<TurnOutcome | TranscriptOutcome | null>;
|
|
94
|
+
cancel(): void;
|
|
95
|
+
mute(): void;
|
|
96
|
+
reconnect(): void;
|
|
97
|
+
/** A new conversation with the same agent. */
|
|
98
|
+
newSession(): void;
|
|
99
|
+
close(): void;
|
|
100
|
+
}
|
|
101
|
+
export declare function useAgent(target: AgentTarget | null, options?: UseAgentOptions): AgentControls;
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useAgent`: a conversation with an agent, for a component — opened on
|
|
3
|
+
* mount (`sessions.create`, then `connect`), closed on unmount, its
|
|
4
|
+
* `snapshot` rendered through `useSyncExternalStore`.
|
|
5
|
+
*
|
|
6
|
+
* - **Handlers in a ref**: every render may pass new ones, and none
|
|
7
|
+
* redials. The conversation is made once per session.
|
|
8
|
+
* - **Audio through an `AgentAudio`** (`@lumavox/client`): every reply
|
|
9
|
+
* frame is played, and playback stops on `cancel`, `mute`, a `send` or a
|
|
10
|
+
* spoken turn — and stays stopped for the rest of that reply's frames,
|
|
11
|
+
* which keep arriving for a moment. `startRecording` opens the recorder
|
|
12
|
+
* *then* the recording, at the rate the recorder was granted, so a
|
|
13
|
+
* refused microphone never opens a window on the socket. The adapter is
|
|
14
|
+
* the app's: the hook never disposes it.
|
|
15
|
+
* - **A late answer is dropped quietly**: a session opened after unmount
|
|
16
|
+
* is never connected, and a press released while the microphone was
|
|
17
|
+
* still opening gives it back.
|
|
18
|
+
*/
|
|
19
|
+
import { RECORDING_RATES, } from "@lumavox/client";
|
|
20
|
+
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
|
|
21
|
+
import { useClient, useLive } from "./provider.js";
|
|
22
|
+
import { asPlatformError } from "./read.js";
|
|
23
|
+
/** Every handler passed straight through; `onAudio` is wired apart. */
|
|
24
|
+
const PASSED = [
|
|
25
|
+
"onReady",
|
|
26
|
+
"onTurnStart",
|
|
27
|
+
"onHeard",
|
|
28
|
+
"onHeardPartial",
|
|
29
|
+
"onKnowledge",
|
|
30
|
+
"onMood",
|
|
31
|
+
"onThought",
|
|
32
|
+
"onText",
|
|
33
|
+
"onChunk",
|
|
34
|
+
"onToolStart",
|
|
35
|
+
"onToolEnd",
|
|
36
|
+
"onUsage",
|
|
37
|
+
"onMuted",
|
|
38
|
+
"onAudioStart",
|
|
39
|
+
"onAudioEnd",
|
|
40
|
+
"onTranscript",
|
|
41
|
+
"onDone",
|
|
42
|
+
"onInterrupted",
|
|
43
|
+
"onRelation",
|
|
44
|
+
"onError",
|
|
45
|
+
"onState",
|
|
46
|
+
"onClose",
|
|
47
|
+
"onDisconnect",
|
|
48
|
+
"onWarning",
|
|
49
|
+
"onEvent",
|
|
50
|
+
];
|
|
51
|
+
const snapshotOf = (state) => ({
|
|
52
|
+
state,
|
|
53
|
+
ready: null,
|
|
54
|
+
turn: null,
|
|
55
|
+
caption: null,
|
|
56
|
+
relation: null,
|
|
57
|
+
queued: 0,
|
|
58
|
+
});
|
|
59
|
+
const OPENING = snapshotOf("connecting");
|
|
60
|
+
const CLOSED = snapshotOf("closed");
|
|
61
|
+
const notOpen = {
|
|
62
|
+
status: "dropped",
|
|
63
|
+
reason: "closed",
|
|
64
|
+
detail: "The conversation is not open.",
|
|
65
|
+
};
|
|
66
|
+
export function useAgent(target, options = {}) {
|
|
67
|
+
const client = useClient(options.client);
|
|
68
|
+
const live = useLive();
|
|
69
|
+
const latest = useRef(options);
|
|
70
|
+
latest.current = options;
|
|
71
|
+
const [conversation, setConversation] = useState(null);
|
|
72
|
+
const [session, setSession] = useState(null);
|
|
73
|
+
const [error, setError] = useState(null);
|
|
74
|
+
const [speaking, setSpeaking] = useState(false);
|
|
75
|
+
const [recording, setRecording] = useState(false);
|
|
76
|
+
const [failed, setFailed] = useState(false);
|
|
77
|
+
const current = useRef(null);
|
|
78
|
+
const waiting = useRef([]);
|
|
79
|
+
const opening = useRef(false);
|
|
80
|
+
/** The reply's frames still arriving after a stop are not played. */
|
|
81
|
+
const silenced = useRef(false);
|
|
82
|
+
const capture = useRef(null);
|
|
83
|
+
const sessionId = target && "sessionId" in target ? target.sessionId : null;
|
|
84
|
+
const agentId = target && "agentId" in target ? target.agentId : null;
|
|
85
|
+
const resume = target && "agentId" in target ? target.resume : undefined;
|
|
86
|
+
const title = target && "agentId" in target ? target.title : undefined;
|
|
87
|
+
const targetKey = sessionId ? `s:${sessionId}` : `a:${agentId}`;
|
|
88
|
+
/** `newSession()`: a new conversation with this agent, for this target. */
|
|
89
|
+
const [fresh, setFresh] = useState(null);
|
|
90
|
+
const renewal = fresh?.key === targetKey ? fresh : null;
|
|
91
|
+
const hush = useCallback(() => {
|
|
92
|
+
silenced.current = true;
|
|
93
|
+
latest.current.audio?.stop();
|
|
94
|
+
setSpeaking(false);
|
|
95
|
+
}, []);
|
|
96
|
+
useEffect(() => {
|
|
97
|
+
let alive = true;
|
|
98
|
+
let made = null;
|
|
99
|
+
setError(null);
|
|
100
|
+
setFailed(false);
|
|
101
|
+
setSession(null);
|
|
102
|
+
const settleWaiting = (c) => {
|
|
103
|
+
for (const resolve of waiting.current.splice(0))
|
|
104
|
+
resolve(c);
|
|
105
|
+
};
|
|
106
|
+
// Nobody to talk to: nothing to open, and nothing waits for it.
|
|
107
|
+
if (!sessionId && !agentId && !renewal) {
|
|
108
|
+
opening.current = false;
|
|
109
|
+
settleWaiting(null);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
opening.current = true;
|
|
113
|
+
const open = async () => {
|
|
114
|
+
let id = renewal ? null : sessionId;
|
|
115
|
+
if (id === null) {
|
|
116
|
+
const detail = await client.sessions.create({
|
|
117
|
+
agent_id: renewal?.agentId ?? agentId,
|
|
118
|
+
...(renewal
|
|
119
|
+
? { resume: false }
|
|
120
|
+
: resume === undefined
|
|
121
|
+
? {}
|
|
122
|
+
: { resume }),
|
|
123
|
+
...(title ? { title } : {}),
|
|
124
|
+
});
|
|
125
|
+
if (!alive)
|
|
126
|
+
return;
|
|
127
|
+
setSession(detail);
|
|
128
|
+
id = detail.id;
|
|
129
|
+
}
|
|
130
|
+
made = client.connect(id, wire(), {
|
|
131
|
+
speech: latest.current.speech,
|
|
132
|
+
thoughts: latest.current.thoughts,
|
|
133
|
+
});
|
|
134
|
+
current.current = made;
|
|
135
|
+
opening.current = false;
|
|
136
|
+
setConversation(made);
|
|
137
|
+
settleWaiting(made);
|
|
138
|
+
};
|
|
139
|
+
/** The handlers the conversation is given: each calls the latest. */
|
|
140
|
+
const wire = () => {
|
|
141
|
+
const handlers = {};
|
|
142
|
+
for (const name of PASSED) {
|
|
143
|
+
handlers[name] = (value) => latest.current[name]?.(value);
|
|
144
|
+
}
|
|
145
|
+
const wired = handlers;
|
|
146
|
+
wired.onTurnStart = (frame) => {
|
|
147
|
+
silenced.current = false;
|
|
148
|
+
setError(null);
|
|
149
|
+
latest.current.onTurnStart?.(frame);
|
|
150
|
+
};
|
|
151
|
+
wired.onError = (frame) => {
|
|
152
|
+
setError({ kind: "frame", message: frame.detail, frame });
|
|
153
|
+
latest.current.onError?.(frame);
|
|
154
|
+
};
|
|
155
|
+
wired.onClose = (close) => {
|
|
156
|
+
setError({
|
|
157
|
+
kind: "closed",
|
|
158
|
+
message: close.reason || `The conversation closed (${close.code}).`,
|
|
159
|
+
close,
|
|
160
|
+
});
|
|
161
|
+
latest.current.onClose?.(close);
|
|
162
|
+
};
|
|
163
|
+
// Only when something plays it: with no `onAudio`, no speech is asked for.
|
|
164
|
+
if (latest.current.audio || latest.current.onAudio) {
|
|
165
|
+
wired.onAudio = (frame) => {
|
|
166
|
+
const audio = latest.current.audio;
|
|
167
|
+
if (audio && !silenced.current) {
|
|
168
|
+
audio.play(frame.pcm, frame);
|
|
169
|
+
setSpeaking(true);
|
|
170
|
+
}
|
|
171
|
+
latest.current.onAudio?.(frame);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
return wired;
|
|
175
|
+
};
|
|
176
|
+
open().catch((failure) => {
|
|
177
|
+
// swallowed: it is the hook's `error`, the caller's to show.
|
|
178
|
+
if (!alive)
|
|
179
|
+
return;
|
|
180
|
+
const error = asPlatformError(failure);
|
|
181
|
+
opening.current = false;
|
|
182
|
+
setFailed(true);
|
|
183
|
+
setError({ kind: "session", message: error.message, error });
|
|
184
|
+
settleWaiting(null);
|
|
185
|
+
});
|
|
186
|
+
return () => {
|
|
187
|
+
alive = false;
|
|
188
|
+
opening.current = false;
|
|
189
|
+
const open = capture.current;
|
|
190
|
+
if (open) {
|
|
191
|
+
open.cancelled = open.over = true;
|
|
192
|
+
capture.current = null;
|
|
193
|
+
void latest.current.audio?.stopCapture();
|
|
194
|
+
}
|
|
195
|
+
latest.current.audio?.stop();
|
|
196
|
+
made?.close();
|
|
197
|
+
if (current.current === made)
|
|
198
|
+
current.current = null;
|
|
199
|
+
settleWaiting(null);
|
|
200
|
+
setConversation(null);
|
|
201
|
+
setRecording(false);
|
|
202
|
+
setSpeaking(false);
|
|
203
|
+
};
|
|
204
|
+
}, [client, sessionId, agentId, resume, title, renewal]);
|
|
205
|
+
// The agent stopped speaking when the adapter's queue plays out.
|
|
206
|
+
const audio = options.audio;
|
|
207
|
+
useEffect(() => audio?.onDrained(() => setSpeaking(false)), [audio]);
|
|
208
|
+
const subscribe = useCallback((fn) => conversation?.subscribe(fn) ?? (() => { }), [conversation]);
|
|
209
|
+
const empty = failed || !target ? CLOSED : OPENING;
|
|
210
|
+
const snapshot = useSyncExternalStore(subscribe, () => conversation?.snapshot ?? empty, () => conversation?.snapshot ?? empty);
|
|
211
|
+
// Open conversations, by agent, for `useRelation`.
|
|
212
|
+
const talkingTo = snapshot.ready?.agent_id ?? null;
|
|
213
|
+
useEffect(() => {
|
|
214
|
+
if (!live || !conversation || !talkingTo)
|
|
215
|
+
return;
|
|
216
|
+
return live.add(talkingTo, conversation);
|
|
217
|
+
}, [live, conversation, talkingTo]);
|
|
218
|
+
/** The conversation, now or once it is made; `null` if it never will be. */
|
|
219
|
+
const connected = useCallback(() => {
|
|
220
|
+
if (current.current)
|
|
221
|
+
return Promise.resolve(current.current);
|
|
222
|
+
if (!opening.current)
|
|
223
|
+
return Promise.resolve(null);
|
|
224
|
+
return new Promise((resolve) => waiting.current.push(resolve));
|
|
225
|
+
}, []);
|
|
226
|
+
const controls = useMemo(() => ({
|
|
227
|
+
send(text, turn) {
|
|
228
|
+
hush();
|
|
229
|
+
const now = current.current;
|
|
230
|
+
if (now)
|
|
231
|
+
return now.send(text, turn);
|
|
232
|
+
return connected().then((c) => (c ? c.send(text, turn) : notOpen));
|
|
233
|
+
},
|
|
234
|
+
startAudio: (start) => current.current?.startAudio(start) ?? null,
|
|
235
|
+
sendAudio: (pcm) => current.current?.sendAudio(pcm) ?? false,
|
|
236
|
+
endAudio: ((end) => current.current
|
|
237
|
+
? current.current.endAudio(end)
|
|
238
|
+
: Promise.resolve(notOpen)),
|
|
239
|
+
async startRecording(record = {}) {
|
|
240
|
+
const recorder = latest.current.audio;
|
|
241
|
+
const c = current.current;
|
|
242
|
+
if (!recorder || !c || capture.current)
|
|
243
|
+
return false;
|
|
244
|
+
if (!record.transcribeOnly)
|
|
245
|
+
hush();
|
|
246
|
+
const mine = {
|
|
247
|
+
started: false,
|
|
248
|
+
cancelled: false,
|
|
249
|
+
over: false,
|
|
250
|
+
early: [],
|
|
251
|
+
};
|
|
252
|
+
capture.current = mine;
|
|
253
|
+
setRecording(true);
|
|
254
|
+
let granted;
|
|
255
|
+
try {
|
|
256
|
+
({ rate: granted } = await recorder.startCapture((pcm) => {
|
|
257
|
+
if (mine.over)
|
|
258
|
+
return;
|
|
259
|
+
if (mine.started)
|
|
260
|
+
c.sendAudio(pcm);
|
|
261
|
+
else
|
|
262
|
+
mine.early.push(pcm);
|
|
263
|
+
}, { rate: record.rate ?? 16000 }));
|
|
264
|
+
}
|
|
265
|
+
catch (failure) {
|
|
266
|
+
// swallowed: it is the hook's `error`, the caller's to show.
|
|
267
|
+
if (capture.current === mine)
|
|
268
|
+
capture.current = null;
|
|
269
|
+
mine.over = true;
|
|
270
|
+
setRecording(false);
|
|
271
|
+
setError({
|
|
272
|
+
kind: "audio",
|
|
273
|
+
message: "Could not open the microphone.",
|
|
274
|
+
error: failure,
|
|
275
|
+
});
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
if (mine.cancelled) {
|
|
279
|
+
// Released while it opened: give the microphone back.
|
|
280
|
+
mine.over = true;
|
|
281
|
+
await recorder.stopCapture();
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
if (!RECORDING_RATES.includes(granted)) {
|
|
285
|
+
capture.current = null;
|
|
286
|
+
mine.over = true;
|
|
287
|
+
setRecording(false);
|
|
288
|
+
await recorder.stopCapture();
|
|
289
|
+
setError({
|
|
290
|
+
kind: "audio",
|
|
291
|
+
message: `The microphone opened at ${granted} Hz, which cannot be transcribed: ${RECORDING_RATES.join(", ")}.`,
|
|
292
|
+
error: null,
|
|
293
|
+
});
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
c.startAudio({ rate: granted });
|
|
297
|
+
mine.started = true;
|
|
298
|
+
for (const pcm of mine.early.splice(0))
|
|
299
|
+
c.sendAudio(pcm);
|
|
300
|
+
return true;
|
|
301
|
+
},
|
|
302
|
+
async stopRecording(stop = {}) {
|
|
303
|
+
const mine = capture.current;
|
|
304
|
+
const recorder = latest.current.audio;
|
|
305
|
+
capture.current = null;
|
|
306
|
+
setRecording(false);
|
|
307
|
+
if (!mine || !recorder)
|
|
308
|
+
return null;
|
|
309
|
+
if (!mine.started) {
|
|
310
|
+
mine.cancelled = true;
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
// The recorder's last samples arrive before it settles.
|
|
314
|
+
await recorder.stopCapture();
|
|
315
|
+
mine.over = true;
|
|
316
|
+
const c = current.current;
|
|
317
|
+
if (!c)
|
|
318
|
+
return notOpen;
|
|
319
|
+
if (stop.discard) {
|
|
320
|
+
c.cancel();
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
if (stop.transcribeOnly)
|
|
324
|
+
return c.endAudio({ transcribeOnly: true });
|
|
325
|
+
hush();
|
|
326
|
+
return c.endAudio();
|
|
327
|
+
},
|
|
328
|
+
cancel() {
|
|
329
|
+
hush();
|
|
330
|
+
current.current?.cancel();
|
|
331
|
+
},
|
|
332
|
+
mute() {
|
|
333
|
+
hush();
|
|
334
|
+
current.current?.mute();
|
|
335
|
+
},
|
|
336
|
+
reconnect: () => current.current?.reconnect(),
|
|
337
|
+
close() {
|
|
338
|
+
hush();
|
|
339
|
+
current.current?.close();
|
|
340
|
+
},
|
|
341
|
+
}), [connected, hush]);
|
|
342
|
+
const readyAgent = snapshot.ready?.agent_id ?? null;
|
|
343
|
+
const newSession = useCallback(() => {
|
|
344
|
+
const agent = agentId ?? readyAgent;
|
|
345
|
+
if (!agent)
|
|
346
|
+
return;
|
|
347
|
+
setFresh((last) => ({
|
|
348
|
+
key: targetKey,
|
|
349
|
+
agentId: agent,
|
|
350
|
+
n: (last?.n ?? 0) + 1,
|
|
351
|
+
}));
|
|
352
|
+
}, [agentId, readyAgent, targetKey]);
|
|
353
|
+
return {
|
|
354
|
+
...snapshot,
|
|
355
|
+
session,
|
|
356
|
+
error,
|
|
357
|
+
speaking,
|
|
358
|
+
recording,
|
|
359
|
+
conversation,
|
|
360
|
+
...controls,
|
|
361
|
+
newSession,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What is remembered about the person (`useFacts`), and forgetting it. A
|
|
3
|
+
* person with nothing remembered — or talking only to agents with memory
|
|
4
|
+
* off — has an empty list, which the route answers as one: never an
|
|
5
|
+
* error (`apps/api/test/sdk-client.test.ts` holds it).
|
|
6
|
+
*/
|
|
7
|
+
import type { Client, FactInfo } from "@lumavox/client";
|
|
8
|
+
import { type Read } from "./read.js";
|
|
9
|
+
export interface FactsRead extends Read<FactInfo[]> {
|
|
10
|
+
/** Forget one; a fact already gone is forgotten too. Rejects with the API's error. */
|
|
11
|
+
forget(id: string): Promise<void>;
|
|
12
|
+
/** Forget everything about the person. Their conversations stay. */
|
|
13
|
+
forgetAll(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare function useFacts(client?: Client): FactsRead;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { useCallback } from "react";
|
|
2
|
+
import { useClient } from "./provider.js";
|
|
3
|
+
import { useRead } from "./read.js";
|
|
4
|
+
export function useFacts(client) {
|
|
5
|
+
const c = useClient(client);
|
|
6
|
+
const read = useRead("facts", () => c.facts.list().then((list) => list.facts));
|
|
7
|
+
const { set } = read;
|
|
8
|
+
const forget = useCallback(async (id) => {
|
|
9
|
+
await c.facts.delete(id);
|
|
10
|
+
set((facts) => facts?.filter((fact) => fact.id !== id) ?? null);
|
|
11
|
+
}, [c, set]);
|
|
12
|
+
const forgetAll = useCallback(async () => {
|
|
13
|
+
await c.facts.deleteAll();
|
|
14
|
+
set(() => []);
|
|
15
|
+
}, [c, set]);
|
|
16
|
+
return {
|
|
17
|
+
data: read.data,
|
|
18
|
+
error: read.error,
|
|
19
|
+
loading: read.loading,
|
|
20
|
+
refresh: read.refresh,
|
|
21
|
+
forget,
|
|
22
|
+
forgetAll,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How one agent feels about the person (`useRelation`): **live from the
|
|
3
|
+
* socket** while a `useAgent` under the same `<AgentProvider>` talks to
|
|
4
|
+
* that agent — `ready` brings it, and a turn that moves it says so — and
|
|
5
|
+
* otherwise read once from `GET /v1/agent/relations`. `data` is `null`
|
|
6
|
+
* for an agent that keeps no relationship.
|
|
7
|
+
*/
|
|
8
|
+
import type { Client, RelationInfo } from "@lumavox/client";
|
|
9
|
+
import { type Read } from "./read.js";
|
|
10
|
+
export declare function useRelation(agentId: string, client?: Client): Read<RelationInfo | null>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { useClient, useLive } from "./provider.js";
|
|
3
|
+
import { useRead } from "./read.js";
|
|
4
|
+
const none = () => () => { };
|
|
5
|
+
export function useRelation(agentId, client) {
|
|
6
|
+
const c = useClient(client);
|
|
7
|
+
const live = useLive();
|
|
8
|
+
const conversation = useSyncExternalStore(useCallback((fn) => live?.subscribe(fn) ?? (() => { }), [live]), () => live?.get(agentId) ?? null, () => null);
|
|
9
|
+
const fromSocket = useSyncExternalStore(conversation ? (fn) => conversation.subscribe(fn) : none, () => conversation?.snapshot.relation ?? null, () => null);
|
|
10
|
+
const read = useRead(conversation ? null : `relation:${agentId}`, () => c.relations
|
|
11
|
+
.list({ agent_id: agentId })
|
|
12
|
+
.then((list) => list.relations[0] ?? null));
|
|
13
|
+
if (conversation) {
|
|
14
|
+
return {
|
|
15
|
+
data: fromSocket,
|
|
16
|
+
error: null,
|
|
17
|
+
loading: false,
|
|
18
|
+
refresh: read.refresh,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
data: read.data,
|
|
23
|
+
error: read.error,
|
|
24
|
+
loading: read.loading,
|
|
25
|
+
refresh: read.refresh,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The person's conversations (`useSessions`) and one of them with its
|
|
3
|
+
* transcript (`useSession`), read through the client's REST routes — each
|
|
4
|
+
* a `Read` (`read.ts`): `{ data, error, loading, refresh }`.
|
|
5
|
+
*/
|
|
6
|
+
import type { Client, MessageInfo, SessionDetail, SessionGetParams, SessionInfo, SessionListParams } from "@lumavox/client";
|
|
7
|
+
import { type Read } from "./read.js";
|
|
8
|
+
/** One page of the person's conversations, newest first. */
|
|
9
|
+
export declare function useSessions(params?: SessionListParams, client?: Client): Read<SessionInfo[]>;
|
|
10
|
+
export interface SessionRead extends Read<SessionDetail> {
|
|
11
|
+
/** Every message read so far, oldest first: the older pages, then the latest. */
|
|
12
|
+
messages: MessageInfo[];
|
|
13
|
+
/** There are older messages than `messages` holds. */
|
|
14
|
+
hasOlder: boolean;
|
|
15
|
+
/** Read the page before the oldest message held. */
|
|
16
|
+
loadOlder(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
/** A conversation and its transcript's latest page; `loadOlder` reads back. */
|
|
19
|
+
export declare function useSession(id: string | null, params?: SessionGetParams, client?: Client): SessionRead;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { useClient } from "./provider.js";
|
|
3
|
+
import { asPlatformError, useRead } from "./read.js";
|
|
4
|
+
/** One page of the person's conversations, newest first. */
|
|
5
|
+
export function useSessions(params = {}, client) {
|
|
6
|
+
const c = useClient(client);
|
|
7
|
+
const { limit, offset } = params;
|
|
8
|
+
const read = useRead(`${limit ?? ""}:${offset ?? ""}`, () => c.sessions.page({ limit, offset }));
|
|
9
|
+
return {
|
|
10
|
+
data: read.data,
|
|
11
|
+
error: read.error,
|
|
12
|
+
loading: read.loading,
|
|
13
|
+
refresh: read.refresh,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** A conversation and its transcript's latest page; `loadOlder` reads back. */
|
|
17
|
+
export function useSession(id, params = {}, client) {
|
|
18
|
+
const c = useClient(client);
|
|
19
|
+
const { limit } = params;
|
|
20
|
+
const read = useRead(id === null ? null : `${id}:${limit ?? ""}`, () => c.sessions.get(id, { limit }));
|
|
21
|
+
const [older, setOlder] = useState([]);
|
|
22
|
+
const [before, setBefore] = useState(null);
|
|
23
|
+
const [loadingOlder, setLoadingOlder] = useState(false);
|
|
24
|
+
const [olderError, setOlderError] = useState(null);
|
|
25
|
+
const page = useRef(0);
|
|
26
|
+
// A new first page starts the transcript again.
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
page.current += 1;
|
|
29
|
+
setOlder([]);
|
|
30
|
+
setOlderError(null);
|
|
31
|
+
setBefore(read.data?.next_before ?? null);
|
|
32
|
+
}, [read.data]);
|
|
33
|
+
const loadOlder = useCallback(async () => {
|
|
34
|
+
if (id === null || before === null)
|
|
35
|
+
return;
|
|
36
|
+
const mine = page.current;
|
|
37
|
+
setLoadingOlder(true);
|
|
38
|
+
try {
|
|
39
|
+
const detail = await c.sessions.get(id, { limit, before });
|
|
40
|
+
if (mine !== page.current)
|
|
41
|
+
return;
|
|
42
|
+
setOlder((held) => [...detail.messages, ...held]);
|
|
43
|
+
setBefore(detail.next_before ?? null);
|
|
44
|
+
setOlderError(null);
|
|
45
|
+
}
|
|
46
|
+
catch (failure) {
|
|
47
|
+
// swallowed: it is the hook's `error`, the caller's to show.
|
|
48
|
+
if (mine === page.current)
|
|
49
|
+
setOlderError(asPlatformError(failure));
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
if (mine === page.current)
|
|
53
|
+
setLoadingOlder(false);
|
|
54
|
+
}
|
|
55
|
+
}, [c, id, limit, before]);
|
|
56
|
+
return {
|
|
57
|
+
data: read.data,
|
|
58
|
+
error: olderError ?? read.error,
|
|
59
|
+
loading: read.loading || loadingOlder,
|
|
60
|
+
refresh: read.refresh,
|
|
61
|
+
messages: [...older, ...(read.data?.messages ?? [])],
|
|
62
|
+
hasOlder: before !== null,
|
|
63
|
+
loadOlder,
|
|
64
|
+
};
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lumavox/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "React and React Native hooks for Lumavox agents: a conversation that keeps itself connected, sessions, memory and relations, over @lumavox/client.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"@ino/source": "./src/index.ts",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "node scripts/build.mjs",
|
|
23
|
+
"prepack": "node scripts/build.mjs",
|
|
24
|
+
"check": "biome check --write",
|
|
25
|
+
"format": "biome format --write",
|
|
26
|
+
"lint": "biome lint",
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"test:unit": "vitest run",
|
|
29
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p test"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@lumavox/client": "0.1.1"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"react": ">=18"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@biomejs/biome": "2.6.2",
|
|
39
|
+
"@testing-library/react": "^16.3.3",
|
|
40
|
+
"@types/node": "^24",
|
|
41
|
+
"@types/react": "^19",
|
|
42
|
+
"esbuild": "^0.28.1",
|
|
43
|
+
"happy-dom": "^21.0.4",
|
|
44
|
+
"react": "19.3.1",
|
|
45
|
+
"react-dom": "19.3.1",
|
|
46
|
+
"typescript": "^6",
|
|
47
|
+
"vitest": "^4.1.12"
|
|
48
|
+
}
|
|
49
|
+
}
|