@ghuri/ai-widget 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/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # @ghuri/ai-widget
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ghuri AI's chat widget for products. Design and decisions: [docs/chat-widget.md](../docs/chat-widget.md).
4
+
5
+ | Entry | What it is | Status |
6
+ |---|---|---|
7
+ | `@ghuri/ai-widget/core` | The logic layer: `ChatClient` (sessions, streaming, confirmations, errors, history). No dependencies. | built |
8
+ | `@ghuri/ai-widget` | The `<ghuri-chat>` web component (Lit, shadow DOM); also re-exports the logic layer | built |
9
+ | `@ghuri/ai-widget/react` | `<GhuriChat>` for React (React 18+) | built |
10
+
11
+ ## The element
12
+
13
+ ```ts
14
+ import '@ghuri/ai-widget' // registers <ghuri-chat>
15
+
16
+ const chat = document.querySelector('ghuri-chat')! // <ghuri-chat layout="panel"></ghuri-chat>
17
+ chat.configure({
18
+ apiUrl: 'https://ai.ghuri.org',
19
+ startSession, refreshUserToken, endSession, // your backend, as below
20
+ layout: 'panel', // or 'page' (full page, conversation list on the left)
21
+ title: 'Ghuri AI', subtitle: 'Amar Shop', // you may rename it; the kite and the "Ghuri AI" line stay
22
+ locale: 'bn', // 'bn' | 'en'; `labels` overrides any word
23
+ starters: ['আজকের অর্ডারগুলো দেখাও'],
24
+ toolSteps: 'show', // or 'hide'
25
+ cards: { theme_preview: { result: (container, ctx) => { container.textContent = 'Preview open' } } },
26
+ })
27
+ chat.show(); chat.hide(); chat.toggle() // panel: shown only while `open`
28
+ chat.ask('Ask AI about order #1042', { send: false }) // open with a question
29
+ chat.newConversation(); chat.openConversation(id); chat.end()
30
+ chat.setOptions({ title: 'VAT assistant' }) // change the look without reconnecting
31
+ chat.addEventListener('ghuri:tool-result', (e) => {/* e.detail: toolName, input, output */})
32
+ // also ghuri:approval-pending, ghuri:turn-end, ghuri:open, ghuri:close
33
+ ```
34
+
35
+ **Theme:** CSS custom properties on the element or any ancestor, usually pointing at your own tokens:
36
+ `--ghuri-accent`, `--ghuri-accent-text`, `--ghuri-accent-soft`, `--ghuri-accent-soft-text`, `--ghuri-accent-border`,
37
+ `--ghuri-surface`, `--ghuri-background`, `--ghuri-muted-surface`, `--ghuri-text`, `--ghuri-muted`, `--ghuri-border`,
38
+ `--ghuri-success`, `--ghuri-warning`, `--ghuri-warning-soft`, `--ghuri-danger`, `--ghuri-danger-soft`,
39
+ `--ghuri-font`, `--ghuri-font-size`, `--ghuri-radius`, `--ghuri-radius-sm`, `--ghuri-bubble-radius`,
40
+ `--ghuri-shadow`, `--ghuri-page-width`, and `--ghuri-kite-maroon` / `-red` / `-green` (lift them in dark mode).
41
+
42
+ **Parts** for anything else (`ghuri-chat::part(user-bubble) { background: … }`): `header`, `title`, `user-bubble`,
43
+ `assistant`, `tool-step`, `decided`, `confirm-card`, `confirm-header`, `button-primary`, `button-secondary`,
44
+ `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`.
45
+
46
+ **Custom cards** (`cards: { <tool name>: { result?, confirm? } }`): `result` replaces a finished tool's step,
47
+ `confirm` replaces the generic confirm card when that tool's change waits alone (`ctx.decide(true | false)`). The
48
+ renderer draws into a container in your page's DOM, shown in the widget through a slot, so your CSS and components
49
+ work in it. It is called again when the step changes; the cleanup it returns runs when the card goes away.
50
+
51
+ Model text is drawn as Markdown without ever being parsed as HTML: raw HTML shows as text, images are not loaded,
52
+ and only `http(s)` and `mailto` links become links (new tab, no referrer). Enter sends, Shift+Enter is a new line,
53
+ and Enter during IME composition (Bangla keyboards) never sends. While a reply is streaming, closing the tab asks
54
+ first.
55
+
56
+ ## React
57
+
58
+ ```tsx
59
+ import { GhuriChat } from '@ghuri/ai-widget/react'
60
+
61
+ <GhuriChat
62
+ apiUrl="https://ai.ghuri.org"
63
+ startSession={start} refreshUserToken={refresh} endSession={end}
64
+ open={open} onClose={() => setOpen(false)} locale="bn" subtitle={store.name}
65
+ onToolResult={(e) => queryClient.invalidateQueries(/* … */)}
66
+ cards={{ inventory_adjust: { confirm: (ctx) => <StockChange ctx={ctx} /> } }}
67
+ />
68
+ ```
69
+
70
+ ## Logic layer
71
+
72
+ ```ts
73
+ import { ChatClient } from '@ghuri/ai-widget/core'
74
+
75
+ const chat = new ChatClient({
76
+ apiUrl: 'https://ai.ghuri.org',
77
+ // Your backend, never Ghuri AI directly: it holds the app key and mints the user's MCP token.
78
+ startSession: () => post('/your-api/assistant/sessions/'), // → { sessionId, sessionToken, expiresAt }
79
+ refreshUserToken: (id) => post(`/your-api/assistant/sessions/${id}/refresh/`),
80
+ endSession: (id) => del(`/your-api/assistant/sessions/${id}/`),
81
+ })
82
+
83
+ chat.subscribe((state) => render(state)) // status, messages (text and tool steps), pendingApprovals, problem
84
+ chat.on('tool-result', (e) => { /* e.toolName, e.input, e.output */ })
85
+
86
+ await chat.send('lal saree koto ache?')
87
+ await chat.decide([{ approvalId, approved: true }]) // or chat.approveAll() / chat.rejectAll()
88
+ chat.stop(); await chat.retry(); await chat.reload()
89
+ await chat.listConversations(); await chat.openConversation(id); chat.newConversation()
90
+ await chat.end() // logout or store switch
91
+ ```
92
+
93
+ `state.problem.code` says what went wrong in terms a UI can word: `reconnecting`, `token-expired` (offer "Continue"),
94
+ `in-progress`, `conversation-full`, `throttled` (`retryAfter` seconds), `forbidden`, `store-unreachable`,
95
+ `unavailable`, `cut-off` (offer "Reload"), `failed` (`message`).
96
+
97
+ The session token is kept in memory only. A `401` is handled once per request: an expired user token is refreshed
98
+ through your backend (a new session is started if your backend says its session is gone), an expired session is
99
+ replaced; then the request is sent again.
100
+
101
+ ## Development
102
+
103
+ ```bash
104
+ npm --prefix widget ci
105
+ npm --prefix widget test # vitest; no network
106
+ npm --prefix widget run build # dist/
107
+ npm --prefix widget run dev # demo/ on a fake Ghuri AI that replays the fixtures
108
+ ```
109
+
110
+ The tests read `test/fixtures/`, which ghuri-ai's own `tests/widget-contract.test.ts` records from the real server.
111
+ When the server's stream changes, that test shows the fixture diff; update it with
112
+ `npx vitest run tests/widget-contract.test.ts -u` and fix the widget until its tests pass again.
@@ -0,0 +1,89 @@
1
+ import type { ChatClientOptions, ChatEvents, ChatState, ConversationSummary, Decision, Problem } from './types';
2
+ type Listener = (state: ChatState) => void;
3
+ type EventListener<K extends keyof ChatEvents> = (event: ChatEvents[K]) => void;
4
+ /** What the user is told about a failed request. */
5
+ export declare function problemFor(err: unknown): Problem;
6
+ export declare class ChatClient {
7
+ private readonly opts;
8
+ private state;
9
+ private view;
10
+ private readonly listeners;
11
+ private readonly events;
12
+ private session;
13
+ private starting;
14
+ private controller;
15
+ /** Every tool step of the open conversation, by tool call id (an approval's reply finishes earlier steps). */
16
+ private tools;
17
+ /** Tool name → title, learnt from the stream (saved messages do not carry titles). */
18
+ private readonly titles;
19
+ private retryAction;
20
+ /**
21
+ * Bumped whenever the open conversation is replaced (new, opened, ended). A turn or a load that started under an
22
+ * older generation stops touching the state, so a reply that was replaced cannot overwrite what replaced it.
23
+ */
24
+ private generation;
25
+ private seq;
26
+ constructor(opts: ChatClientOptions);
27
+ getState(): ChatState;
28
+ /** Called on every change; returns the unsubscribe function. */
29
+ subscribe(listener: Listener): () => void;
30
+ on<K extends keyof ChatEvents>(name: K, listener: EventListener<K>): () => void;
31
+ private emit;
32
+ private changed;
33
+ private id;
34
+ private now;
35
+ private ensureSession;
36
+ /**
37
+ * A request to Ghuri AI with the session token. A `401` is handled once: an expired user token is refreshed through
38
+ * the product (or, if the product's session is gone, a new session started), an expired session is replaced; then
39
+ * the request is sent again.
40
+ */
41
+ private request;
42
+ private json;
43
+ /** Send a message. Waiting changes, if any, are cancelled by it (Ghuri AI closes them). */
44
+ send(text: string): Promise<void>;
45
+ /** Confirm or cancel the waiting changes: one decision for each, sent together. */
46
+ decide(decisions: Decision[]): Promise<void>;
47
+ /** Confirm every waiting change. */
48
+ approveAll(): Promise<void>;
49
+ /** Cancel every waiting change. */
50
+ rejectAll(reason?: string): Promise<void>;
51
+ /** Stop the reply being written (Ghuri AI stops the turn; what finished is kept). */
52
+ stop(): void;
53
+ /** Run the action that failed again (Try again). */
54
+ retry(): Promise<void>;
55
+ dismissProblem(): void;
56
+ /** Start a new conversation (the next message creates it). */
57
+ newConversation(): void;
58
+ /** The user's conversations in this product and tenant, newest first. */
59
+ listConversations(opts?: {
60
+ limit?: number;
61
+ offset?: number;
62
+ }): Promise<{
63
+ count: number;
64
+ results: ConversationSummary[];
65
+ }>;
66
+ /** Open a saved conversation, including any change still waiting for a decision. */
67
+ openConversation(id: string): Promise<void>;
68
+ /** Load the open conversation again (after a reply was cut off). */
69
+ reload(): Promise<void>;
70
+ /** End the session through the product (logout, store switch) and forget everything. */
71
+ end(): Promise<void>;
72
+ private busy;
73
+ /**
74
+ * Post a message or decisions and read the streamed reply into a new assistant message. Returns `not-sent` when the
75
+ * request failed or was refused before a reply started (nothing happened on the server), else `answered`.
76
+ */
77
+ private turn;
78
+ /**
79
+ * Steps still writing or running when a reply ended early never get their result: mark them, so nothing spins
80
+ * forever. A confirmed change in that state may or may not have run ("outcome unknown").
81
+ */
82
+ private settleUnfinished;
83
+ private drop;
84
+ private finishTurn;
85
+ /** Apply one stream chunk to the reply being written. */
86
+ private apply;
87
+ private toolPart;
88
+ }
89
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { ChatMessage, PendingApproval, ToolPart } from './types';
2
+ type Part = {
3
+ type?: string;
4
+ [key: string]: any;
5
+ };
6
+ type ModelMessage = {
7
+ role?: string;
8
+ content?: string | Part[];
9
+ };
10
+ /**
11
+ * Convert saved messages. `titles` (tool name → title) labels tool steps; saved messages do not carry titles, so it
12
+ * holds what the widget learnt while streaming, plus the titles of `pending` approvals.
13
+ */
14
+ export declare function messagesFromHistory(messages: ModelMessage[], pending?: PendingApproval[], titles?: Map<string, string>): ChatMessage[];
15
+ /** Every part of `messages`, for lookups by tool call id. */
16
+ export declare function toolParts(messages: ChatMessage[]): Map<string, ToolPart>;
17
+ export {};
@@ -0,0 +1,4 @@
1
+ export { ChatClient, problemFor } from './client';
2
+ export { messagesFromHistory } from './history';
3
+ export { parseSse, readChunks, SseParser, type StreamChunk } from './sse';
4
+ export type * from './types';
@@ -0,0 +1,24 @@
1
+ /** One parsed chunk. Unknown types are passed through and ignored by the client. */
2
+ export type StreamChunk = {
3
+ type: string;
4
+ [key: string]: unknown;
5
+ };
6
+ /** Parse a complete SSE text (tests, or a body read in one go). */
7
+ export declare function parseSse(text: string): StreamChunk[];
8
+ /**
9
+ * An incremental SSE parser: feed it text as it arrives, get back the chunks whose events are complete. Handles events
10
+ * split across reads, `\r\n` line endings, comment lines and several `data:` lines per event (joined with `\n`).
11
+ */
12
+ export declare class SseParser {
13
+ private buffer;
14
+ /** A `\r` that ended the last read: it may be the first half of a `\r\n` split across two reads. */
15
+ private carry;
16
+ /** True once `data: [DONE]` was seen. */
17
+ done: boolean;
18
+ push(text: string): StreamChunk[];
19
+ /** The stream ended: parse what is left (an event without its blank line). */
20
+ end(): StreamChunk[];
21
+ private parseEvent;
22
+ }
23
+ /** Read a fetch response body as stream chunks, as they arrive. */
24
+ export declare function readChunks(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<StreamChunk>;
@@ -0,0 +1,134 @@
1
+ /** What the product's backend returns when it starts a session (Ghuri AI's `POST /v1/sessions` answer). */
2
+ export interface SessionInfo {
3
+ sessionId: string;
4
+ sessionToken: string;
5
+ expiresAt: string;
6
+ }
7
+ /** How the widget reaches Ghuri AI and the product's own backend. */
8
+ export interface ChatClientOptions {
9
+ /** Ghuri AI's base URL, e.g. `https://ai.ghuri.org`. */
10
+ apiUrl: string;
11
+ /** Start a session for the signed-in user, through the product's backend. */
12
+ startSession: () => Promise<SessionInfo>;
13
+ /** Give the session a fresh user token, through the product's backend (`user_token_expired`). */
14
+ refreshUserToken: (sessionId: string) => Promise<void>;
15
+ /** End the session, through the product's backend (logout, store switch). */
16
+ endSession?: (sessionId: string) => Promise<void>;
17
+ /** Defaults to the global `fetch`. */
18
+ fetch?: typeof fetch;
19
+ /** Defaults to `Date.now`. */
20
+ now?: () => number;
21
+ }
22
+ /** One step of the AI's work in a reply: a tool it called. */
23
+ export interface ToolPart {
24
+ kind: 'tool';
25
+ toolCallId: string;
26
+ toolName: string;
27
+ /** The tool's human title from the product's MCP server, when it has one. */
28
+ title?: string;
29
+ input?: unknown;
30
+ /**
31
+ * `input`: the AI is still writing the call; `running`: the call was sent; `awaiting-approval`: a change waiting for
32
+ * the user's decision; `done` / `error`: finished; `denied`: the user cancelled it.
33
+ */
34
+ state: 'input' | 'running' | 'awaiting-approval' | 'done' | 'error' | 'denied';
35
+ approvalId?: string;
36
+ output?: unknown;
37
+ errorText?: string;
38
+ }
39
+ export interface TextPart {
40
+ kind: 'text';
41
+ id: string;
42
+ text: string;
43
+ }
44
+ export type MessagePart = TextPart | ToolPart;
45
+ export interface ChatMessage {
46
+ id: string;
47
+ role: 'user' | 'assistant';
48
+ parts: MessagePart[];
49
+ }
50
+ /** A change waiting for the user's decision (Ghuri AI's `pendingApprovals`). */
51
+ export interface PendingApproval {
52
+ approvalId: string;
53
+ toolCallId: string;
54
+ toolName: string;
55
+ title?: string;
56
+ input: unknown;
57
+ }
58
+ export interface Decision {
59
+ approvalId: string;
60
+ approved: boolean;
61
+ reason?: string;
62
+ }
63
+ /** The end of a turn (Ghuri AI's `data-turn` part). */
64
+ export interface TurnResult {
65
+ turnId: number;
66
+ conversationId: string;
67
+ status: 'ok' | 'paused' | 'error';
68
+ pendingApprovals: PendingApproval[];
69
+ error?: string;
70
+ limitReached?: 'conversation' | 'turn';
71
+ userTokenExpired?: boolean;
72
+ }
73
+ /**
74
+ * Something the user should be told, in plain words. The UI picks the wording; `retryAfter` is in seconds.
75
+ *
76
+ * - `reconnecting`: getting a fresh session or token (no action needed)
77
+ * - `token-expired`: the store stopped accepting the assistant mid-reply; the token was refreshed, offer "Continue"
78
+ * - `in-progress`: the previous reply is still being written
79
+ * - `conversation-full`: start a new conversation
80
+ * - `throttled`: wait `retryAfter` seconds
81
+ * - `forbidden`: the user may not do that in this store
82
+ * - `store-unreachable`: the product's MCP server failed; nothing was changed
83
+ * - `unavailable`: Ghuri AI or the network is down
84
+ * - `cut-off`: the reply stopped before it finished; reload the conversation
85
+ * - `failed`: anything else (`message` has the server's text)
86
+ */
87
+ export type ProblemCode = 'reconnecting' | 'token-expired' | 'in-progress' | 'conversation-full' | 'throttled' | 'forbidden' | 'store-unreachable' | 'unavailable' | 'cut-off' | 'failed';
88
+ export interface Problem {
89
+ code: ProblemCode;
90
+ retryAfter?: number;
91
+ message?: string;
92
+ }
93
+ /** A conversation in the history list (`GET /v1/conversations`). */
94
+ export interface ConversationSummary {
95
+ id: string;
96
+ title: string;
97
+ createdAt: string;
98
+ updatedAt: string;
99
+ }
100
+ /**
101
+ * - `idle`: ready for a message
102
+ * - `sending`: waiting for the reply to start
103
+ * - `streaming`: the reply is arriving
104
+ * - `awaiting-approval`: the reply paused on changes the user must confirm or cancel
105
+ * - `loading`: opening a conversation
106
+ */
107
+ export type ChatStatus = 'idle' | 'sending' | 'streaming' | 'awaiting-approval' | 'loading';
108
+ export interface ChatState {
109
+ status: ChatStatus;
110
+ conversationId: string | null;
111
+ messages: ChatMessage[];
112
+ pendingApprovals: PendingApproval[];
113
+ problem: Problem | null;
114
+ /** The last turn's result, when there was one. */
115
+ lastTurn: TurnResult | null;
116
+ }
117
+ /** Events for the host page (the element re-dispatches them as `ghuri:*` DOM events). */
118
+ export interface ChatEvents {
119
+ /** A tool finished (successfully or not). */
120
+ 'tool-result': {
121
+ toolCallId: string;
122
+ toolName: string;
123
+ title?: string;
124
+ input: unknown;
125
+ output?: unknown;
126
+ error?: string;
127
+ };
128
+ /** The reply paused on changes the user must decide. */
129
+ 'approval-pending': {
130
+ approvals: PendingApproval[];
131
+ };
132
+ /** A turn ended. */
133
+ 'turn-end': TurnResult;
134
+ }