@scrimpify-software/rag-widgets 0.0.0-stage → 1.2.0

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,306 @@
1
- # Temporary Holding Version
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.
1
+ # @scrimpify-software/rag-widgets
2
+
3
+ Plug-and-play RAG chat widgets for any React app — by **KnowLayer**.
4
+
5
+ Drop an AI-powered chat assistant into your product in under 5 minutes. Connect it to any KnowLayer RAG backend and let your users ask questions against your knowledge base.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @scrimpify-software/rag-widgets
11
+ # or
12
+ pnpm add @scrimpify-software/rag-widgets
13
+ # or
14
+ yarn add @scrimpify-software/rag-widgets
15
+ ```
16
+
17
+ > **Peer dependencies:** `react` ≥ 18 and `react-dom` ≥ 18
18
+
19
+ ## Quick Start: `KnowLayerWidget`
20
+
21
+ One component, three required props:
22
+
23
+ ```tsx
24
+ import { KnowLayerWidget } from "@scrimpify-software/rag-widgets";
25
+
26
+ <KnowLayerWidget
27
+ clientId="your-client-id"
28
+ chatType="floating"
29
+ welcomeMessage="Hi! Ask me anything about our docs."
30
+ />
31
+ ```
32
+
33
+ | Prop | Required | Description |
34
+ |------|----------|-------------|
35
+ | `clientId` | Yes | Your team's public client ID. Never pass `clientSecret`. |
36
+ | `chatType` | Yes | `"floating"` (chat bubble in the corner), `"embedded"` (inline chat panel) or `"search"` (one-shot Q&A box) |
37
+ | `welcomeMessage` | Yes | Greeting in the chat, or intro text above the search box |
38
+ | `apiUrl` | No | KnowLayer API base URL |
39
+ | `getToken` / `getFirebaseIdToken` | No | Signed-in users (see [Authentication](#authentication)) |
40
+ | `theme` | No | `"light"` (default) or `"dark"` |
41
+
42
+ Every widget shows a "Powered by KnowLayer" footer.
43
+
44
+ ## Widgets
45
+
46
+ Need more control (title, position, size, citations)? Use the underlying components directly:
47
+
48
+ | Widget | Description |
49
+ |--------|-------------|
50
+ | `<FloatingChat />` | Floating bubble button that opens a chat popup — great for support overlays |
51
+ | `<EmbeddedChat />` | Inline chat panel that fits inside any container |
52
+ | `<SearchWidget />` | Single-question search box with answer + sources |
53
+
54
+ ## Advanced usage
55
+
56
+ ### Public site (`clientId` only)
57
+
58
+ Anonymous visitors. The widget mints a short-lived public session from your published `clientId`. No secret, no login.
59
+
60
+ ```tsx
61
+ import { FloatingChat } from "@scrimpify-software/rag-widgets";
62
+
63
+ <FloatingChat apiUrl="https://api.example.com" clientId="your-client-id" />
64
+ ```
65
+
66
+ ### Authenticated (your site’s backend)
67
+
68
+ Signed-in users on **your** product. Your server holds `client_secret` and mints a session JWT; the widget never sees the secret.
69
+
70
+ ```tsx
71
+ import { FloatingChat } from "@scrimpify-software/rag-widgets";
72
+
73
+ <FloatingChat
74
+ apiUrl="https://api.example.com"
75
+ clientId="your-client-id"
76
+ getToken={async () => {
77
+ const res = await fetch("/api/knowlayer-token", { credentials: "include" });
78
+ if (!res.ok) throw new Error("KnowLayer session failed");
79
+ const data = await res.json();
80
+ return data.token;
81
+ }}
82
+ />
83
+ ```
84
+
85
+ #### Express: `POST /api/knowlayer-token`
86
+
87
+ Call KnowLayer with HTTP Basic `client_id:client_secret` and the email of the **already authenticated** user. **Never take email from the query string** (or any other browser-controlled field) — attackers can spoof it.
88
+
89
+ ```js
90
+ app.post("/api/knowlayer-token", async (req, res) => {
91
+ const email = req.user.email; // from your session / auth middleware — not req.query
92
+ if (!email) {
93
+ return res.status(401).json({ error: "Not signed in" });
94
+ }
95
+
96
+ const basic = Buffer.from(
97
+ `${process.env.KNOWLAYER_CLIENT_ID}:${process.env.KNOWLAYER_CLIENT_SECRET}`,
98
+ ).toString("base64");
99
+
100
+ const upstream = await fetch("https://api.example.com/api/v1/teams/widget-session", {
101
+ method: "POST",
102
+ headers: {
103
+ Authorization: `Basic ${basic}`,
104
+ "Content-Type": "application/json",
105
+ },
106
+ body: JSON.stringify({ email }),
107
+ });
108
+
109
+ if (!upstream.ok) {
110
+ return res.status(502).json({ error: "KnowLayer session failed" });
111
+ }
112
+ const data = await upstream.json();
113
+ res.json({ token: data.token });
114
+ });
115
+ ```
116
+
117
+ ### Signed assertion (any host backend)
118
+
119
+ Use this when the host proves the signed-in user with a short-lived RS256 assertion. The widget API stays `getToken`. The host backend holds the signing key and the integration client secret. Contract and local verification: [docs/widget-integration.md](../../../docs/widget-integration.md). Host helpers: [examples/widget_integration/client.py](../../../examples/widget_integration/client.py).
120
+
121
+ ```tsx
122
+ <FloatingChat
123
+ apiUrl="https://api.example.com"
124
+ clientId="your-client-id"
125
+ getToken={async () => {
126
+ const res = await fetch("/api/knowlayer-session", { credentials: "include" });
127
+ if (!res.ok) throw new Error("Couldn't start the assistant. Please try again.");
128
+ const data = await res.json();
129
+ return { access_token: data.access_token ?? data.token, expires_in: data.expires_in };
130
+ }}
131
+ />
132
+ ```
133
+
134
+ The widget keeps that access token in memory, sends it as `Authorization: Bearer` on `POST /api/v1/teams/me/chat`, and asks `getToken` again after expiry. It does not mint user assertions or hold the host signing key.
135
+
136
+ ### KnowLayer dashboard (`getFirebaseIdToken`)
137
+
138
+ If the host app is already signed into KnowLayer (Firebase), pass `getFirebaseIdToken`. The widget exchanges it at `POST /api/v1/teams/widget-token` for a JWT carrying the user's team role. Do not also pass `getToken`.
139
+
140
+ ```tsx
141
+ import { FloatingChat } from "@scrimpify-software/rag-widgets";
142
+ import { getAuth } from "firebase/auth";
143
+
144
+ <FloatingChat
145
+ apiUrl="https://api.example.com"
146
+ clientId="your-client-id"
147
+ getFirebaseIdToken={async () => {
148
+ const user = getAuth().currentUser;
149
+ if (!user) throw new Error("Not signed in");
150
+ return user.getIdToken();
151
+ }}
152
+ />
153
+ ```
154
+
155
+ Exactly one mode: public (`clientId` only), `getToken`, or `getFirebaseIdToken`. Never both callbacks. Never `clientSecret` in the widget.
156
+
157
+ ### Signed out → signed in (Global docs, then Global + the user's teams)
158
+
159
+ Embed your organization's **Global Team** client ID and pass the sign-in callback **only while a user is signed in**:
160
+
161
+ ```tsx
162
+ const { user } = useAuth(); // your app's auth state
163
+
164
+ <FloatingChat
165
+ apiUrl="https://api.example.com"
166
+ clientId={GLOBAL_TEAM_CLIENT_ID}
167
+ getToken={user ? getKnowLayerToken : undefined}
168
+ // or: getFirebaseIdToken={user ? () => user.getIdToken() : undefined}
169
+ />
170
+ ```
171
+
172
+ - **Signed out:** answers come from Global Team documents only.
173
+ - **Signed in:** answers come from the Global Team **plus every team the user belongs to**, using the user's role on each team. The server works this out on every request, so removing someone from a team takes effect on their next question.
174
+ - When the callback appears or disappears, the widget drops its cached token, resets the conversation and reloads suggested questions — no page reload needed.
175
+ - A non-global team's client ID keeps answering from that one team, signed in or not.
176
+ - If a different user signs in within the same page, remount the widget (`key={user?.uid ?? "signed-out"}`) so the previous user's session is not reused.
177
+
178
+ Optional props: `signedInWelcomeMessage` (greeting while signed in) and `showScopeHint` (default `true`; shows "Public documents" / "Signed in · includes your teams").
179
+
180
+ > **Security:** Never put `clientSecret` in frontend code or embed snippets. Keep it on your server for `POST /api/v1/teams/widget-session` only.
181
+
182
+ ### Embedded Chat (inline panel)
183
+
184
+ ```tsx
185
+ import { EmbeddedChat } from "@scrimpify-software/rag-widgets";
186
+
187
+ function App() {
188
+ return (
189
+ <EmbeddedChat
190
+ apiUrl="https://api.example.com"
191
+ clientId="your-client-id"
192
+ title="Ask our docs"
193
+ height="600px"
194
+ theme="dark"
195
+ />
196
+ );
197
+ }
198
+ ```
199
+
200
+ ### Search Widget (one-shot Q&A)
201
+
202
+ ```tsx
203
+ import { SearchWidget } from "@scrimpify-software/rag-widgets";
204
+
205
+ function App() {
206
+ return (
207
+ <SearchWidget
208
+ apiUrl="https://api.example.com"
209
+ clientId="your-client-id"
210
+ placeholder="Search the knowledge base…"
211
+ />
212
+ );
213
+ }
214
+ ```
215
+
216
+ ## Authentication
217
+
218
+ | Mode | Widget props | Who mints the JWT |
219
+ |------|----------------|-------------------|
220
+ | Public | `apiUrl` + `clientId` | Widget → `POST /api/v1/teams/public-widget-session` (`X-KL-Client-Id`) |
221
+ | Authenticated (your backend) | `clientId` + `getToken` | Your server → `POST /api/v1/teams/widget-session` (Basic + `{ email }`) |
222
+ | KnowLayer dashboard | `clientId` + `getFirebaseIdToken` | Widget → `POST /api/v1/teams/widget-token` |
223
+
224
+ The widget caches the JWT in memory and refreshes it before expiry. Chat calls `POST /api/v1/teams/me/chat` with `Authorization: Bearer <widget-token>`.
225
+
226
+ If `getToken` fails, the widget **fails closed** — it does not fall back to a public session.
227
+
228
+ On HTTP 402 (the organization's query quota is exhausted) the widget shows "Chat quota is exhausted. Please contact your organization admin." Only answers generated from your documents count toward the quota; small talk and "no access" replies do not.
229
+
230
+ ## Citations
231
+
232
+ Every answer in Chat, Floating and Search shows the sources it was built from (collapsed as "N sources cited"):
233
+
234
+ - Only the chunks that were actually used — never your whole document list.
235
+ - One entry per document per team, keeping the best-matching chunk; a relevance badge when a score exists (vectorless answers have no score and are always listed); the section / clause when known; a 2-line snippet.
236
+ - When an answer draws on more than one team, each source is labelled with its team (`AWS · runbook.pdf`).
237
+ - No file links or downloads, so public visitors never receive document URLs.
238
+ - No citations on small talk, "no access" replies, or when the assistant is unavailable.
239
+
240
+ | Prop | Default | Description |
241
+ |------|---------|-------------|
242
+ | `showCitations` | `true` | Hide the sources panel entirely with `false`. |
243
+ | `citationMinScore` | `0.65` | Hide scored sources below this relevance (0–1). |
244
+
245
+ Rendering your own UI? `uniqueCitations(sources, { minScore })` and the `ChatSource` type are exported.
246
+
247
+ ## Props
248
+
249
+ ### Common Props
250
+
251
+ | Prop | Type | Required | Description |
252
+ |------|------|----------|-------------|
253
+ | `apiUrl` | `string` | Yes | Base URL of your KnowLayer RAG API |
254
+ | `clientId` | `string` | Yes | OAuth client ID (public). Never pass `clientSecret`. |
255
+ | `getToken` | `() => Promise<string \| { token, expires_in }>` | No | Your backend returns a widget JWT. Mutually exclusive with `getFirebaseIdToken`. |
256
+ | `getFirebaseIdToken` | `() => Promise<string>` | No | KnowLayer / Firebase ID token (dashboard). Mutually exclusive with `getToken`. |
257
+ | `theme` | `"light" \| "dark"` | No | Color theme (default: `"light"`) |
258
+ | `placeholder` | `string` | No | Input placeholder text |
259
+ | `showScopeHint` | `boolean` | No | Caption for what the widget answers from (default: `true`) |
260
+ | `showCitations` | `boolean` | No | Show the sources panel (default: `true`) |
261
+ | `citationMinScore` | `number` | No | Relevance cut-off for scored sources (default: `0.65`) |
262
+
263
+ ### FloatingChat Props
264
+
265
+ | Prop | Type | Default | Description |
266
+ |------|------|---------|-------------|
267
+ | `title` | `string` | `"KnowLayer Assistant"` | Chat window title |
268
+ | `welcomeMessage` | `string` | — | Initial greeting message |
269
+ | `signedInWelcomeMessage` | `string` | — | Greeting while a user is signed in |
270
+ | `position` | `"bottom-right" \| "bottom-left"` | `"bottom-right"` | Bubble position |
271
+ | `buttonSize` | `number` | — | Size of the floating button in px |
272
+ | `popupWidth` | `string` | — | Width of the chat popup |
273
+ | `popupHeight` | `string` | — | Height of the chat popup |
274
+ | `suggestedQuestions` | `string[]` | — | Pre-defined question chips |
275
+
276
+ ### EmbeddedChat Props
277
+
278
+ | Prop | Type | Default | Description |
279
+ |------|------|---------|-------------|
280
+ | `title` | `string` | `"KnowLayer Assistant"` | Chat panel title |
281
+ | `welcomeMessage` | `string` | — | Initial greeting message |
282
+ | `signedInWelcomeMessage` | `string` | — | Greeting while a user is signed in |
283
+ | `height` | `string` | `"500px"` | Panel height |
284
+ | `className` | `string` | — | Additional CSS class |
285
+ | `suggestedQuestions` | `string[]` | — | Pre-defined question chips |
286
+
287
+ ## TypeScript
288
+
289
+ All components and prop interfaces are fully typed and exported:
290
+
291
+ ```ts
292
+ import type {
293
+ KnowLayerWidgetProps,
294
+ KnowLayerChatType,
295
+ FloatingChatProps,
296
+ EmbeddedChatProps,
297
+ SearchWidgetProps,
298
+ ChatSource,
299
+ WidgetAuthMode,
300
+ GetTokenResult,
301
+ } from "@scrimpify-software/rag-widgets";
302
+ ```
303
+
304
+ ## License
305
+
306
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),a=require("react"),ee=require("react-dom"),te=3e4,M=600,ne=3600,re="KnowLayer widgets: getToken and getFirebaseIdToken are mutually exclusive.",oe=5e3;function ie(e,n){return e?"getToken":n?"firebase":"public"}function se(e,n){if(e&&typeof e=="object"&&"detail"in e){const r=e.detail;if(typeof r=="string"&&r.trim())return r}return n}function ae(e){return e.includes("eyJ")||e.length>300?"Couldn't start the assistant. Please try again.":e}function de(e){if(typeof e=="string"){if(!e)throw new Error("getToken returned an empty token.");return{token:e,expiresIn:M}}const n=e&&typeof e.token=="string"&&e.token?e.token:e&&typeof e.access_token=="string"?e.access_token:"";if(!n)throw new Error("getToken must return a token string or { token, expires_in }.");const r=typeof e.expires_in=="number"?e.expires_in:M;return{token:n,expiresIn:r}}async function K(e,n){if(!e.ok){const i=await e.json().catch(()=>({}));throw new Error(se(i,`Widget token request failed (${e.status})`))}const r=await e.json();if(!r||typeof r.token!="string"||!r.token)throw new Error("Widget token response missing token.");const s=typeof r.expires_in=="number"?r.expires_in:n;return{token:r.token,expiresIn:s}}function z({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s}){if(s&&r)throw new Error(re);const i=ie(s,r),f=`${e}|${n}|${i}`,g=a.useRef(s),k=a.useRef(r);g.current=s,k.current=r;const o=a.useRef(null),u=a.useRef(null),m=a.useRef(null),y=a.useRef(0),w=a.useCallback(()=>{o.current=null,u.current=null,m.current=null,y.current+=1},[]),x=a.useCallback(async()=>{const l=y.current,b=m.current;if(b&&b.key===f&&Date.now()-b.at<oe)throw new Error(b.message);try{let c;if(i==="getToken"&&g.current)c=de(await g.current());else if(i==="firebase"&&k.current){const h=await k.current(),j=await fetch(`${e}/api/v1/teams/widget-token`,{method:"POST",headers:{"X-KL-Client-Id":n,"X-Firebase-Id-Token":h}});c=await K(j,ne)}else{const h=await fetch(`${e}/api/v1/teams/public-widget-session`,{method:"POST",headers:{"X-KL-Client-Id":n}});c=await K(h,M)}return l!==y.current||(o.current={key:f,token:c.token,expiresAt:Date.now()+c.expiresIn*1e3},m.current=null),c.token}catch(c){const h=ae(c instanceof Error?c.message:"Couldn't start the assistant. Please try again.");throw l===y.current&&(m.current={key:f,at:Date.now(),message:h}),new Error(h)}},[e,n,i,f]);return{getWidgetToken:a.useCallback(async()=>{const l=o.current;if(l&&l.key===f&&l.expiresAt-te>Date.now())return l.token;const b=u.current;if(b&&b.key===f)return b.promise;const c=x().finally(()=>{var h;((h=u.current)==null?void 0:h.promise)===c&&(u.current=null)});return u.current={key:f,promise:c},c},[f,x]),invalidateWidgetToken:w,authMode:i}}const le="http://localhost:8000",A="Chat quota is exhausted. Please contact your organization admin.";function O(e){return e==="public"?"Public documents":"Signed in · includes your teams"}const ue="Hello! Ask me anything about your documentation.";let ce=0;function I(){return`msg_${Date.now()}_${++ce}`}async function q(e,n,r){return fetch(`${e}/api/v1/teams/me/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:r})})}function Q({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,welcomeMessage:i=ue,signedInWelcomeMessage:f}){const{getWidgetToken:g,invalidateWidgetToken:k,authMode:o}=z({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s}),u=o!=="public"&&f?f:i,[m,y]=a.useState(()=>[{id:I(),role:"assistant",content:u}]),[w,x]=a.useState(!1),[R,l]=a.useState(null),b=a.useRef(0),c=a.useCallback(()=>{b.current+=1,y([{id:I(),role:"assistant",content:u}]),l(null),x(!1)},[u]),h=a.useRef(o);a.useEffect(()=>{h.current!==o&&(h.current=o,c())},[o,c]);const j=a.useCallback(async C=>{const v=C.trim();if(!v||w)return;const T=b.current,S=()=>T===b.current,$={id:I(),role:"user",content:v};y(B=>[...B,$]),x(!0),l(null);try{const B=await g();let d=await q(e,B,v);if(d.status===401){k();const L=await g();d=await q(e,L,v)}if(!S())return;if(!d.ok){if(d.status===402){l(A),y(_=>[..._,{id:I(),role:"assistant",content:A}]);return}const L=await d.json().catch(()=>({}));throw new Error(L.detail||`Request failed (${d.status})`)}const E=await d.json();if(!S())return;const W=Array.isArray(E.sources)&&!E.llm_unavailable,p={id:I(),role:"assistant",content:E.answer??"No response received.",sources:W?E.sources:void 0};y(L=>[...L,p])}catch(B){if(!S())return;const d=B instanceof Error?B.message:"Something went wrong.",E=d.includes("eyJ")||d.length>300?"Couldn't start the assistant. Please try again.":d;l(E),y(W=>[...W,{id:I(),role:"assistant",content:"Sorry, I couldn't get a response. Please try again."}])}finally{S()&&x(!1)}},[e,g,k,w]);return{messages:m,isLoading:w,error:R,authMode:o,sendMessage:j,reset:c}}function X({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,suggestedQuestions:i}){const[f,g]=a.useState([]),{getWidgetToken:k,invalidateWidgetToken:o,authMode:u}=z({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s}),m=!!(i&&i.length>0);return a.useEffect(()=>{if(m)return;let y=!1;return g([]),(async()=>{const w=x=>fetch(`${e}/api/v1/teams/me/suggested-questions`,{headers:{Authorization:`Bearer ${x}`}});try{let x=await w(await k());if(x.status===401&&!y&&(o(),x=await w(await k())),!x.ok||y)return;const R=await x.json();if(y)return;const l=Array.isArray(R.questions)?R.questions.filter(b=>typeof b=="string"&&b.trim().length>0):[];g(l)}catch{}})(),()=>{y=!0}},[e,u,k,o,m]),m?i:f}const D=.65;function fe(e){const n=(e.team_id??"").toString().trim().toLowerCase(),r=n?`team:${n}|`:"",s=(e.filename??"").trim().toLowerCase();if(s)return`${r}file:${s}`;const i=(e.document_id??"").toString().trim().toLowerCase();return i?`${r}id:${i}`:`${r}text:${(e.text??"").slice(0,60)}`}function V(e,{minScore:n=D}={}){const r=new Map,s=[];for(const i of e){if(i.score!=null&&i.score<n)continue;const f=fe(i),g=r.get(f);if(!g){r.set(f,i),s.push(f);continue}(i.score??0)>(g.score??0)&&r.set(f,i)}return s.map(i=>r.get(i))}function pe(e){return new Set(e.map(r=>(r.team_id??"").toString()).filter(r=>r.length>0)).size>1}function xe(e){const n=(e.clause_number??"").toString().trim(),r=(e.section_title??"").trim();return n&&r?`§ ${n} ${r}`:n?`§ ${n}`:r||(e.title??"").trim()||null}function P({sources:e,colors:n,compact:r=!1,minScore:s=D}){const[i,f]=a.useState(!1),g=a.useMemo(()=>V(e,{minScore:s}),[e,s]),k=a.useMemo(()=>pe(g),[g]);if(g.length===0)return null;const o=r?11:12;return t.jsxs("div",{style:ge(n),children:[t.jsxs("button",{onClick:()=>f(u=>!u),style:he(n,o),children:[t.jsx(je,{size:r?12:14,color:n.textMuted}),t.jsxs("span",{children:[g.length," source",g.length>1?"s":""," cited"]}),t.jsx(Se,{direction:i?"up":"down",size:r?12:14,color:n.textMuted})]}),i&&t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",marginTop:6},children:g.map((u,m)=>{const y=u.filename??"Unknown source",w=k&&u.team_name?`${u.team_name} · ${y}`:y,x=xe(u);return t.jsxs("li",{style:ye(n,m>0),children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:be(n),children:m+1}),t.jsx("span",{title:w,style:{fontWeight:600,fontSize:o,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:w}),u.score!=null&&t.jsxs("span",{style:me(),children:[(u.score*100).toFixed(0),"%"]})]}),x&&t.jsx("p",{style:ke(n,o),children:x}),u.text&&t.jsx("p",{style:we(n,o),children:u.text.length>120?u.text.slice(0,120)+"…":u.text})]},`${u.team_id??""}-${u.filename??u.document_id??"source"}-${m}`)})})]})}function ge(e){return{marginTop:6,borderRadius:8,border:`1px solid ${e.border}`,background:e.cardBg,padding:"6px 10px"}}function he(e,n){return{display:"flex",alignItems:"center",gap:5,width:"100%",background:"none",border:"none",padding:0,cursor:"pointer",fontSize:n,fontWeight:500,color:e.textMuted}}function ye(e,n){return{padding:"6px 0",borderTop:n?`1px solid ${e.border}`:"none"}}function be(e){return{width:18,height:18,borderRadius:4,background:e.primary+"1a",color:e.primary,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,flexShrink:0}}function me(){return{fontSize:10,fontWeight:600,color:"#22c55e",background:"rgba(34,197,94,0.12)",borderRadius:999,padding:"1px 6px",flexShrink:0}}function ke(e,n){return{margin:"2px 0 0 24px",fontSize:n-1,fontWeight:500,color:e.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}function we(e,n){return{margin:"4px 0 0 24px",fontSize:n-1,lineHeight:1.45,color:e.textMuted,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}}function je({size:e,color:n}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),t.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}function Se({direction:e,size:n,color:r}){return t.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:r,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:"auto"},children:e==="down"?t.jsx("polyline",{points:"6 9 12 15 18 9"}):t.jsx("polyline",{points:"18 15 12 9 6 15"})})}function F({colors:e}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"6px 12px",fontSize:11,color:e.textMuted},children:[t.jsx("span",{children:"Powered by"}),t.jsx(ve,{color:e.primary}),t.jsx("span",{style:{fontWeight:600,color:e.text},children:"KnowLayer"})]})}function ve({color:e}){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),t.jsx("polyline",{points:"2 17 12 22 22 17"}),t.jsx("polyline",{points:"2 12 12 17 22 12"})]})}const Be={bg:"#ffffff",cardBg:"#f8fafc",border:"#e2e8f0",text:"#1e293b",textMuted:"#64748b",primary:"#2563eb",primaryText:"#ffffff",inputBg:"#ffffff",userBubbleBg:"#2563eb",userBubbleText:"#ffffff",assistantBubbleBg:"#f1f5f9",headerBg:"#ffffff",headerText:"#1e293b",dot:"#22c55e"},Re={bg:"#0f172a",cardBg:"#1e293b",border:"#334155",text:"#f1f5f9",textMuted:"#94a3b8",primary:"#3b82f6",primaryText:"#ffffff",inputBg:"#1e293b",userBubbleBg:"#3b82f6",userBubbleText:"#ffffff",assistantBubbleBg:"#334155",headerBg:"#1e293b",headerText:"#f1f5f9",dot:"#22c55e"};function H(e){return e==="dark"?Re:Be}function J(e){const n=e.split(`
2
+ `),r=[];for(let s=0;s<n.length;s++)s>0&&r.push(a.createElement("br",{key:`br_${s}`})),r.push(a.createElement(a.Fragment,{key:`line_${s}`},...Te(n[s])));return a.createElement(a.Fragment,null,...r)}function Te(e){const n=[],r=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g;let s=0,i,f=0;for(;(i=r.exec(e))!==null;)i.index>s&&n.push(e.slice(s,i.index)),i[2]!==void 0?n.push(a.createElement("strong",{key:`b_${f++}`},i[2])):i[3]!==void 0?n.push(a.createElement("em",{key:`i_${f++}`},i[3])):i[4]!==void 0&&n.push(a.createElement("code",{key:`c_${f++}`,style:{background:"rgba(0,0,0,0.08)",padding:"1px 4px",borderRadius:3,fontSize:"0.9em"}},i[4])),s=i.index+i[0].length;return s<e.length&&n.push(e.slice(s)),n.length===0&&n.push(""),n}function Y({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,title:i="KnowLayer Assistant",placeholder:f="Ask a question…",welcomeMessage:g,signedInWelcomeMessage:k,theme:o="light",position:u="bottom-right",buttonSize:m=56,popupWidth:y="380px",popupHeight:w="520px",suggestedQuestions:x,showScopeHint:R=!0,showCitations:l=!0,citationMinScore:b}){const[c,h]=a.useState(!1),j=H(o),C=X({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,suggestedQuestions:x});return ee.createPortal(t.jsxs(t.Fragment,{children:[c&&t.jsx(Ce,{apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,title:i,placeholder:f,welcomeMessage:g,signedInWelcomeMessage:k,colors:j,position:u,buttonSize:m,popupWidth:y,popupHeight:w,onClose:()=>h(!1),suggestedQuestions:C,showScopeHint:R,showCitations:l,citationMinScore:b}),t.jsx("button",{onClick:()=>h(v=>!v),style:Ee(j,u,m),"aria-label":c?"Close chat":"Open chat",children:c?t.jsx(G,{}):t.jsx($e,{})})]}),document.body)}function Ce({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,title:i,placeholder:f,welcomeMessage:g,signedInWelcomeMessage:k,colors:o,position:u,buttonSize:m,popupWidth:y,popupHeight:w,onClose:x,suggestedQuestions:R=[],showScopeHint:l,showCitations:b,citationMinScore:c}){const{messages:h,isLoading:j,error:C,authMode:v,sendMessage:T}=Q({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,welcomeMessage:g,signedInWelcomeMessage:k}),[S,$]=a.useState(""),B=a.useRef(null);a.useEffect(()=>{var p;(p=B.current)==null||p.scrollIntoView({behavior:"smooth"})},[h,j]);const d=p=>{p.preventDefault(),S.trim()&&(T(S),$(""))},E=m+16,W=u==="bottom-left"?{left:20,bottom:E}:{right:20,bottom:E};return t.jsxs("div",{style:{position:"fixed",...W,width:y,height:w,zIndex:2147483645,fontFamily:"system-ui, -apple-system, sans-serif",display:"flex",flexDirection:"column",borderRadius:16,border:`1px solid ${o.border}`,background:o.bg,color:o.text,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden",animation:"knowlayer-fadein 0.2s ease-out"},children:[t.jsx("style",{children:"@keyframes knowlayer-fadein { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:`1px solid ${o.border}`,background:o.headerBg},children:[t.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:o.dot,flexShrink:0}}),t.jsx("span",{style:{fontWeight:600,fontSize:14,flex:1},children:i}),l&&t.jsx("span",{style:{fontSize:10,color:o.textMuted},children:O(v)}),t.jsx("button",{onClick:x,style:{background:"none",border:"none",cursor:"pointer",color:o.textMuted,padding:4,display:"flex"},"aria-label":"Close",children:t.jsx(G,{})})]}),t.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:14},children:[h.map(p=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:p.role==="user"?"flex-end":"flex-start",marginBottom:10},children:[t.jsx("div",{style:{maxWidth:"82%",padding:"8px 12px",borderRadius:12,fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",wordBreak:"break-word",background:p.role==="user"?o.userBubbleBg:o.assistantBubbleBg,color:p.role==="user"?o.userBubbleText:o.text},children:p.role==="assistant"?J(p.content):p.content}),b&&p.role==="assistant"&&p.sources&&p.sources.length>0&&t.jsx("div",{style:{maxWidth:"82%"},children:t.jsx(P,{sources:p.sources,colors:o,compact:!0,minScore:c})})]},p.id)),j&&t.jsx("div",{style:{marginBottom:10},children:t.jsx("div",{style:{maxWidth:"82%",padding:"8px 12px",borderRadius:12,fontSize:13,background:o.assistantBubbleBg,color:o.textMuted},children:"Thinking…"})}),C&&t.jsx("div",{style:{padding:"6px 10px",borderRadius:8,background:"#fef2f2",border:"1px solid #fecaca",color:"#dc2626",fontSize:12,marginBottom:10},children:C}),t.jsx("div",{ref:B})]}),R.length>0&&h.length<=1&&t.jsxs("div",{style:{padding:"8px 12px",borderTop:`1px solid ${o.border}`,background:o.cardBg},children:[t.jsx("span",{style:{display:"block",fontSize:10,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",color:o.textMuted,marginBottom:5},children:"Try asking"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:R.map(p=>t.jsx("button",{type:"button",onClick:()=>{T(p)},style:{background:"none",border:`1px solid ${o.border}`,borderRadius:999,padding:"3px 8px",fontSize:11,color:o.textMuted,cursor:"pointer",whiteSpace:"nowrap"},children:p},p))})]}),t.jsxs("form",{onSubmit:d,style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderTop:`1px solid ${o.border}`,background:o.cardBg},children:[t.jsx("input",{value:S,onChange:p=>$(p.target.value),placeholder:f,style:{flex:1,padding:"7px 10px",borderRadius:8,border:`1px solid ${o.border}`,background:o.inputBg,color:o.text,fontSize:13,outline:"none"}}),t.jsx("button",{type:"submit",disabled:!S.trim()||j,style:{width:32,height:32,borderRadius:8,border:"none",background:!S.trim()||j?o.border:o.primary,color:o.primaryText,cursor:!S.trim()||j?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,opacity:!S.trim()||j?.5:1},children:t.jsx(Le,{})})]}),t.jsx(F,{colors:o})]})}function Ee(e,n,r){return{position:"fixed",...n==="bottom-left"?{left:20,bottom:20}:{right:20,bottom:20},width:r,height:r,borderRadius:"50%",border:"none",background:e.primary,color:e.primaryText,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 14px rgba(0,0,0,0.25)",zIndex:2147483646,transition:"transform 0.15s"}}function $e(){return t.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function G(){return t.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Le(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),t.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Z({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,title:i="KnowLayer Assistant",placeholder:f="Ask a question…",welcomeMessage:g,signedInWelcomeMessage:k,theme:o="light",height:u="500px",className:m,suggestedQuestions:y,showScopeHint:w=!0,showCitations:x=!0,citationMinScore:R}){const l=H(o),{messages:b,isLoading:c,error:h,authMode:j,sendMessage:C}=Q({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,welcomeMessage:g,signedInWelcomeMessage:k}),v=X({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,suggestedQuestions:y}),[T,S]=a.useState(""),$=a.useRef(null);a.useEffect(()=>{var d;(d=$.current)==null||d.scrollIntoView({behavior:"smooth"})},[b,c]);const B=d=>{d.preventDefault(),T.trim()&&(C(T),S(""))};return t.jsxs("div",{className:m,style:We(l,u),children:[t.jsxs("div",{style:Ie(l),children:[t.jsx("span",{style:_e(l)}),t.jsx("span",{style:{fontWeight:600,fontSize:14,flex:1},children:i}),w&&t.jsx("span",{style:{fontSize:11,color:l.textMuted},children:O(j)})]}),t.jsxs("div",{style:Me(l),children:[b.map(d=>t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:d.role==="user"?"flex-end":"flex-start",marginBottom:12},children:[t.jsx("div",{style:N(d.role,l),children:d.role==="assistant"?J(d.content):d.content}),x&&d.role==="assistant"&&d.sources&&d.sources.length>0&&t.jsx("div",{style:{maxWidth:"80%"},children:t.jsx(P,{sources:d.sources,colors:l,minScore:R})})]},d.id)),c&&t.jsx("div",{style:{marginBottom:12},children:t.jsx("div",{style:N("assistant",l),children:t.jsx("span",{style:{opacity:.6},children:"Thinking…"})})}),h&&t.jsx("div",{style:{padding:"8px 12px",borderRadius:8,background:"#fef2f2",border:"1px solid #fecaca",color:"#dc2626",fontSize:13,marginBottom:12},children:h}),t.jsx("div",{ref:$})]}),v.length>0&&b.length<=1&&t.jsxs("div",{style:De(l),children:[t.jsx("span",{style:Pe(l),children:"Try asking"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:v.map(d=>t.jsx("button",{type:"button",onClick:()=>{C(d)},style:Fe(l),children:d},d))})]}),t.jsxs("form",{onSubmit:B,style:Ae(l),children:[t.jsx("input",{value:T,onChange:d=>S(d.target.value),placeholder:f,style:ze(l)}),t.jsx("button",{type:"submit",disabled:!T.trim()||c,style:Oe(l,!T.trim()||c),children:t.jsx(He,{})})]}),t.jsx(F,{colors:l})]})}function We(e,n){return{fontFamily:"system-ui, -apple-system, sans-serif",display:"flex",flexDirection:"column",height:n,borderRadius:12,border:`1px solid ${e.border}`,background:e.bg,color:e.text,overflow:"hidden"}}function Ie(e){return{display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:`1px solid ${e.border}`,background:e.headerBg,color:e.headerText}}function _e(e){return{width:8,height:8,borderRadius:"50%",background:e.dot,flexShrink:0}}function Me(e){return{flex:1,minHeight:0,overflowY:"auto",padding:16,background:e.bg}}function N(e,n){const r=e==="user";return{maxWidth:"80%",padding:"10px 14px",borderRadius:12,fontSize:14,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",background:r?n.userBubbleBg:n.assistantBubbleBg,color:r?n.userBubbleText:n.text}}function Ae(e){return{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderTop:`1px solid ${e.border}`,background:e.cardBg}}function ze(e){return{flex:1,padding:"8px 12px",borderRadius:8,border:`1px solid ${e.border}`,background:e.inputBg,color:e.text,fontSize:14,outline:"none"}}function Oe(e,n){return{width:36,height:36,borderRadius:8,border:"none",background:n?e.border:e.primary,color:e.primaryText,cursor:n?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,opacity:n?.5:1,transition:"opacity 0.15s"}}function De(e){return{padding:"8px 14px",borderTop:`1px solid ${e.border}`,background:e.cardBg}}function Pe(e){return{display:"block",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",color:e.textMuted,marginBottom:6}}function Fe(e){return{background:"none",border:`1px solid ${e.border}`,borderRadius:999,padding:"4px 10px",fontSize:12,color:e.textMuted,cursor:"pointer",whiteSpace:"nowrap"}}function He(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),t.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function U({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s,welcomeMessage:i,placeholder:f="Ask a question…",theme:g="light",showScopeHint:k=!0,showCitations:o=!0,citationMinScore:u}){const[m,y]=a.useState(""),[w,x]=a.useState(null),[R,l]=a.useState([]),[b,c]=a.useState(!1),h=H(g),{getWidgetToken:j,invalidateWidgetToken:C,authMode:v}=z({apiUrl:e,clientId:n,getFirebaseIdToken:r,getToken:s}),T=a.useRef(0),S=a.useRef(v);a.useEffect(()=>{S.current!==v&&(S.current=v,T.current+=1,x(null),l([]),c(!1))},[v]);const $=async()=>{if(!m.trim())return;const B=++T.current,d=()=>B===T.current;c(!0),x(null),l([]);try{const E=await j(),W=_=>fetch(`${e}/api/v1/teams/me/chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_}`},body:JSON.stringify({query:m})});let p=await W(E);if(p.status===401){C();const _=await j();p=await W(_)}if(!d())return;if(!p.ok){if(p.status===402){x(A);return}x("Something went wrong.");return}const L=await p.json();if(!d())return;x(L.answer??"No response received."),Array.isArray(L.sources)&&!L.llm_unavailable&&l(L.sources)}catch{d()&&x("Something went wrong.")}finally{d()&&c(!1)}};return t.jsxs("div",{style:{fontFamily:"system-ui, sans-serif"},children:[i&&t.jsx("p",{style:{marginTop:0,marginBottom:8,fontSize:14,color:h.text},children:i}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsx("input",{type:"text",value:m,onChange:B=>y(B.target.value),onKeyDown:B=>B.key==="Enter"&&$(),placeholder:f,style:{flex:1,padding:"8px 12px",borderRadius:6,border:"1px solid #ccc",fontSize:14}}),t.jsx("button",{onClick:$,disabled:b,style:{padding:"8px 16px",borderRadius:6,border:"none",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:14},children:b?"…":"Ask"})]}),k&&t.jsx("div",{style:{marginTop:4,fontSize:11,color:h.textMuted},children:O(v)}),w&&t.jsx("div",{style:{marginTop:12,padding:12,borderRadius:6,background:"#f8fafc",border:"1px solid #e2e8f0",whiteSpace:"pre-wrap",fontSize:14},children:w}),o&&R.length>0&&t.jsx(P,{sources:R,colors:h,minScore:u}),t.jsx(F,{colors:h})]})}function Ke({chatType:e,apiUrl:n=le,...r}){switch(e){case"floating":return t.jsx(Y,{apiUrl:n,...r});case"embedded":return t.jsx(Z,{apiUrl:n,...r});case"search":return t.jsx(U,{apiUrl:n,...r})}}exports.CITATION_SCORE_THRESHOLD=D;exports.EmbeddedChat=Z;exports.FloatingChat=Y;exports.KnowLayerWidget=Ke;exports.SearchWidget=U;exports.uniqueCitations=V;
@@ -0,0 +1,125 @@
1
+ import { JSX } from 'react';
2
+ import { ReactPortal } from 'react';
3
+
4
+ export declare interface ChatSource {
5
+ text: string;
6
+ filename?: string | null;
7
+ document_id?: string | null;
8
+ /** Relevance 0–1. Absent for vectorless (tree search) sources. */
9
+ score?: number | null;
10
+ /** Present when the answer searched more than one team. */
11
+ team_id?: string | null;
12
+ team_name?: string | null;
13
+ section_title?: string | null;
14
+ clause_number?: string | null;
15
+ /** Vectorless tree node title / id. */
16
+ title?: string | null;
17
+ node_id?: string | null;
18
+ }
19
+
20
+ export declare const CITATION_SCORE_THRESHOLD = 0.65;
21
+
22
+ export declare function EmbeddedChat({ apiUrl, clientId, getFirebaseIdToken, getToken, title, placeholder, welcomeMessage, signedInWelcomeMessage, theme, height, className, suggestedQuestions: suggestedQuestionsProp, showScopeHint, showCitations, citationMinScore, }: EmbeddedChatProps): JSX.Element;
23
+
24
+ export declare interface EmbeddedChatProps {
25
+ apiUrl: string;
26
+ clientId: string;
27
+ getFirebaseIdToken?: () => Promise<string>;
28
+ getToken?: () => Promise<GetTokenResult>;
29
+ title?: string;
30
+ placeholder?: string;
31
+ welcomeMessage?: string;
32
+ /** Greeting while a user is signed in (defaults to welcomeMessage). */
33
+ signedInWelcomeMessage?: string;
34
+ theme?: "light" | "dark";
35
+ height?: string;
36
+ className?: string;
37
+ suggestedQuestions?: string[];
38
+ /** Show "Public documents" / "Signed in · includes your teams" under the title. */
39
+ showScopeHint?: boolean;
40
+ showCitations?: boolean;
41
+ /** Hide vector citations below this relevance (0–1). Unscored sources are always shown. */
42
+ citationMinScore?: number;
43
+ }
44
+
45
+ export declare function FloatingChat({ apiUrl, clientId, getFirebaseIdToken, getToken, title, placeholder, welcomeMessage, signedInWelcomeMessage, theme, position, buttonSize, popupWidth, popupHeight, suggestedQuestions: suggestedQuestionsProp, showScopeHint, showCitations, citationMinScore, }: FloatingChatProps): ReactPortal;
46
+
47
+ export declare interface FloatingChatProps {
48
+ apiUrl: string;
49
+ clientId: string;
50
+ getFirebaseIdToken?: () => Promise<string>;
51
+ getToken?: () => Promise<GetTokenResult>;
52
+ title?: string;
53
+ placeholder?: string;
54
+ welcomeMessage?: string;
55
+ /** Greeting while a user is signed in (defaults to welcomeMessage). */
56
+ signedInWelcomeMessage?: string;
57
+ theme?: "light" | "dark";
58
+ position?: "bottom-right" | "bottom-left";
59
+ buttonSize?: number;
60
+ popupWidth?: string;
61
+ popupHeight?: string;
62
+ suggestedQuestions?: string[];
63
+ /** Show "Public documents" / "Signed in · includes your teams" under the title. */
64
+ showScopeHint?: boolean;
65
+ showCitations?: boolean;
66
+ /** Hide vector citations below this relevance (0–1). Unscored sources are always shown. */
67
+ citationMinScore?: number;
68
+ }
69
+
70
+ export declare type GetTokenResult = string | WidgetTokenResponse;
71
+
72
+ export declare type KnowLayerChatType = "floating" | "embedded" | "search";
73
+
74
+ export declare function KnowLayerWidget({ chatType, apiUrl, ...rest }: KnowLayerWidgetProps): JSX.Element;
75
+
76
+ export declare interface KnowLayerWidgetProps {
77
+ clientId: string;
78
+ /** `floating` = chat bubble in the corner, `embedded` = inline chat panel, `search` = one-shot Q&A box. */
79
+ chatType: KnowLayerChatType;
80
+ welcomeMessage: string;
81
+ apiUrl?: string;
82
+ /** Customer-backend mint for signed-in users. Mutually exclusive with `getFirebaseIdToken`. */
83
+ getToken?: () => Promise<GetTokenResult>;
84
+ getFirebaseIdToken?: () => Promise<string>;
85
+ theme?: "light" | "dark";
86
+ }
87
+
88
+ export declare function SearchWidget({ apiUrl, clientId, getFirebaseIdToken, getToken, welcomeMessage, placeholder, theme, showScopeHint, showCitations, citationMinScore, }: SearchWidgetProps): JSX.Element;
89
+
90
+ export declare interface SearchWidgetProps {
91
+ apiUrl: string;
92
+ clientId: string;
93
+ /** Return a fresh Firebase ID token for the signed-in user (used to mint a widget access token). */
94
+ getFirebaseIdToken?: () => Promise<string>;
95
+ /** Customer-backend mint. Fail closed: never falls back to public session. */
96
+ getToken?: () => Promise<GetTokenResult>;
97
+ /** Intro text shown above the search box. */
98
+ welcomeMessage?: string;
99
+ placeholder?: string;
100
+ theme?: "light" | "dark";
101
+ /** Show "Public documents" / "Signed in · includes your teams" under the search box. */
102
+ showScopeHint?: boolean;
103
+ showCitations?: boolean;
104
+ /** Hide vector citations below this relevance (0–1). Unscored sources are always shown. */
105
+ citationMinScore?: number;
106
+ }
107
+
108
+ /** One citation per document per team. Keeps the highest-scoring chunk when several match. */
109
+ export declare function uniqueCitations(sources: ChatSource[], { minScore }?: UniqueCitationsOptions): ChatSource[];
110
+
111
+ declare interface UniqueCitationsOptions {
112
+ /** Hide scored (vector) sources below this relevance. Sources without a score are always kept. */
113
+ minScore?: number;
114
+ }
115
+
116
+ /** Which credential the widget is currently using. Changes when the host signs a user in or out. */
117
+ export declare type WidgetAuthMode = "public" | "firebase" | "getToken";
118
+
119
+ declare type WidgetTokenResponse = {
120
+ token?: string;
121
+ access_token?: string;
122
+ expires_in?: number;
123
+ };
124
+
125
+ export { }