@inkeep/cxkit-primitives 0.0.0-dev-20251216042053 → 0.0.0-dev-20251216053643

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.
@@ -1,4 +1,4 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("openai"),t=require("react"),Le=require("../../providers/config-provider.cjs"),xe=require("../../providers/conversation-provider.cjs"),Be=require("../../providers/chat-events-provider.cjs"),F=require("../../utils/get-message-metadata.cjs"),re=require("../../utils/reset-query-params.cjs"),Oe=require("../../providers/chat-form-provider.cjs"),De=require("../../providers/widget-provider.cjs"),Fe=require("../../hooks/use-media-query.cjs"),Te=require("./use-captcha.cjs"),Ke=require("../modal/modal-provider.cjs"),g=require("../../utils/generate-uid.cjs"),Qe=require("../../utils/tools/links-tool.cjs"),We=require("../../atoms/api/analytics/conversation.cjs"),Je=require("../../utils/misc.cjs"),ze=()=>{const{chatId:y,isSharedChat:ie,setConversation:ce,conversation:A,resetConversation:le}=xe.useInkeepConversation(),{baseSettings:q,aiChatSettings:T}=Le.useInkeepConfig(),{aiApiBaseUrl:K,shouldBypassCaptcha:Q,filters:W}=q,J=Ke.useModal(),{getSolution:ue,prefetchSolution:P,invalidateSolution:z}=Te.useCaptcha({fetchUrl:`${K}/v1/challenge`,shouldBypassCaptcha:Q,shouldMakeInitialRequest:J?J.isOpen:!0}),de=new ae({baseURL:`${K}/v1`,apiKey:q.apiKey??"",dangerouslyAllowBrowser:!0}),{onInputMessageChange:ge,getTools:me,prompts:pe,model:fe,filters:H,onToolCall:he}=T,[S,R]=t.useState(""),j=t.useRef(null);t.useEffect(()=>{ge?.(S)},[S]);const[m,l]=t.useState([]),[G,M]=t.useState(!1),[ve,w]=t.useState(!1),[ye,V]=t.useState(null),[L,X]=t.useState(null),[C,I]=t.useState([]),Se=e=>{I(s=>[...s,e])},[Me,Y]=t.useState({}),o=t.useRef([]),k=t.useRef(null),{logEvent:b}=Be.useChatEvents(),Z=pe?.map((e,s)=>({id:`system-${Date.now().toString()}-${g.generateUid(4)}-${s}`,role:"system",content:e})),[we,Ce]=t.useState(!!y);t.useEffect(()=>{if(y){const{apiKey:e,analyticsApiBaseUrl:s}=q;We.getConversation(y,e,s).then(a=>{if(a){b({eventName:"shared_chat_loaded",properties:{conversation:a}}),Ce(!1),ce({...a});const r=a.messages.map(p=>({...p,content:Je.parseIfJson(p.content)}));l(r),o.current=r}})}},[y]);const Ie=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${q.organizationDisplayName??"Administrator"}`;default:return`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("openai"),t=require("react"),Be=require("../../providers/config-provider.cjs"),Oe=require("../../providers/conversation-provider.cjs"),De=require("../../providers/chat-events-provider.cjs"),D=require("../../utils/get-message-metadata.cjs"),re=require("../../utils/reset-query-params.cjs"),Fe=require("../../providers/chat-form-provider.cjs"),Te=require("../../providers/widget-provider.cjs"),Ke=require("../../hooks/use-media-query.cjs"),Qe=require("./use-captcha.cjs"),We=require("../modal/modal-provider.cjs"),g=require("../../utils/generate-uid.cjs"),Je=require("../../utils/tools/links-tool.cjs"),ze=require("../../atoms/api/analytics/conversation.cjs"),He=require("../../utils/misc.cjs"),je=()=>{const{chatId:y,isSharedChat:ie,setConversation:ce,conversation:le,resetConversation:ue}=Oe.useInkeepConversation(),{baseSettings:q,aiChatSettings:F}=Be.useInkeepConfig(),{aiApiBaseUrl:T,shouldBypassCaptcha:K,filters:Q}=q,W=We.useModal(),{getSolution:de,prefetchSolution:P,invalidateSolution:J}=Qe.useCaptcha({fetchUrl:`${T}/v1/challenge`,shouldBypassCaptcha:K,shouldMakeInitialRequest:W?W.isOpen:!0}),ge=new ae({baseURL:`${T}/v1`,apiKey:q.apiKey??"",dangerouslyAllowBrowser:!0}),{onInputMessageChange:me,getTools:pe,prompts:fe,model:he,filters:z,onToolCall:ve}=F,[S,A]=t.useState(""),H=t.useRef(null);t.useEffect(()=>{me?.(S)},[S]);const[m,l]=t.useState([]),[j,w]=t.useState(!1),[ye,C]=t.useState(!1),[Se,G]=t.useState(null),[L,V]=t.useState(null),[M,I]=t.useState([]),we=e=>{I(s=>[...s,e])},[Ce,X]=t.useState({}),o=t.useRef([]),k=t.useRef(null),{logEvent:b,getLatestConversation:Y}=De.useChatEvents(),Z=fe?.map((e,s)=>({id:`system-${Date.now().toString()}-${g.generateUid(4)}-${s}`,role:"system",content:e})),[Me,Ie]=t.useState(!!y);t.useEffect(()=>{if(y){const{apiKey:e,analyticsApiBaseUrl:s}=q;ze.getConversation(y,e,s).then(a=>{if(a){b({eventName:"shared_chat_loaded",properties:{conversation:a}}),Ie(!1),ce({...a});const r=a.messages.map(p=>({...p,content:He.parseIfJson(p.content)}));l(r),o.current=r}})}},[y]);const ke=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${q.organizationDisplayName??"Administrator"}`;default:return`Hmm..
2
2
 
3
- It seems I might be having some issues right now. Please clear the chat and try again.`}},ee=e=>{V(e),l(s=>{const a=[...s],r=a[a.length-1];return r&&(r.content=Ie(e)),a}),M(!1),w(!1),z(),P()},x=!S.trim()&&!C.length||G,ke=e=>{e.key==="Enter"&&!e.shiftKey&&!x&&!e.nativeEvent.isComposing&&(e.preventDefault(),B())},be=e=>{const s=e.target.value;R(s)},B=async(e=S)=>{if(x&&(!e||e.trim().length===0))return;M(!0);const s=L?m.length===2:m.length===0,a=F.getMessageMetadata(L,C,s);let r;const p=F.serializeAttachments(C);C.length&&p?r=[{type:"text",text:p}]:r=e;const se={id:`${Date.now().toString()}-${g.generateUid(4)}-1`,role:"user",content:r,metadata:a},f=[...m.length?[]:Z,se];if(ie&&y){re.resetQueryParams();const u=o.current.map((i,E)=>({id:`${i.id}-${g.generateUid(6)}-${E}`,role:i.role,...i.role==="assistant"?{links:i.links??[]}:{},content:i.content,metadata:i.metadata,tool_calls:i.tool_calls}));l([...u,...f]),o.current=[...u,...f]}else l(u=>[...u,...f]),o.current=[...o.current,...f];I([]),R(""),b({eventName:"user_message_submitted",properties:{}},o.current);const ne=[Qe.provideLinksTool,...me?.({conversation:A})||[]];try{const u={model:fe,messages:o.current,stream:!0,tools:ne,tool_choice:"auto"},i=await ue(),E=i?btoa(JSON.stringify(i)):null,oe=W||H?JSON.stringify({...W,...H}):void 0,U={};!Q&&E&&(U["X-INKEEP-CHALLENGE-SOLUTION"]=E),oe&&(U["inkeep-filters"]=oe);const h=de.beta.chat.completions.stream(u,Object.keys(U).length>0?{headers:U}:void 0),n={id:`${Date.now().toString()}-${g.generateUid(4)}-2`,role:"assistant",content:"",links:[],tool_calls:[]};l(d=>[...d,n]),h.on("content",(d,_)=>{w(!0),n.content=_,l(N=>{const c=[...N],O=c.findIndex($=>$.id===n.id);return O===-1?[...c,n]:(c[O]={...n},c)})}),h.on("tool_calls.function.arguments.done",async d=>{const{name:_,arguments:N}=d,c=ne?.find(v=>v.function.name===_);if(!c)return;const $=("parse"in c.function?c.function.parse:JSON.parse)(N),Ue=c.function.function?.($,h),Ne=c.renderMessageButtons?.({args:$,execution:Ue})??[];_==="provideLinks"?n.links=$.links??[]:Y(v=>({...v,[n.id]:[...v[n.id]??[],...Ne]})),n.tool_calls?.push({id:"call_"+g.generateUid(24),type:"function",function:{name:_,arguments:N}}),l(v=>{const D=[...v],Ae=D.findIndex(Re=>Re.id===n.id);return D[Ae]={...n},D}),he?.(d,{conversation:{...A,messages:[...o.current,n]}})}),h.on("error",ee),h.finalChatCompletion().then(async()=>{o.current=[...o.current,n],k.current=null,M(!1),w(!1),P(),await b({eventName:"assistant_message_received",properties:{}},o.current),b({eventName:"assistant_answer_displayed",properties:{}})}).catch(d=>{d instanceof ae.APIUserAbortError||console.warn(d)}),k.current=h.controller}catch(u){ee(u),M(!1),w(!1)}},_e=()=>{k.current&&(k.current.abort(),k.current=null),M(!1),w(!1),P()},te=()=>{V(null),l([]),o.current=[],le(),Y({}),I([]),re.resetQueryParams(),X(null),z(),P(),b({eventName:"chat_clear_button_clicked",properties:{conversation:A}})},$e=e=>{X(e);const{initialReplyMessage:s,displayName:a}=e,r={id:m.length.toString()+g.generateUid(4),role:"user",content:a},p={id:(m.length+1).toString()+g.generateUid(4),role:"assistant",content:s,links:[]},f=[{id:`system-${Date.now().toString()}-${g.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
- ${F.serializeWorkflow(e)}`},...Z,r,p];l(f),I([])},{openForm:qe}=Oe.useChatForm(),Pe=De.useWidget();t.useImperativeHandle(T.chatFunctionsRef,()=>({submitMessage:B,updateInputMessage(e){R(e)},clearChat:te,openForm:e=>{Pe?.setView("chat"),qe(e)},focusInput:()=>{j.current?.focus()}}));const Ee=Fe.useMediaQuery("(max-width: 768px)");return{messages:m,input:S,isLoading:G,isStreaming:ve,isLoadingConversation:we,error:ye,isSubmitDisabled:x,handleInputChange:be,handleInputKeyDown:ke,handleSubmit:B,stop:_e,clear:te,handleWorkflow:$e,selectedWorkflow:L,messageAttachments:C,setMessageAttachments:I,addAttachment:Se,messageButtons:Me,isEmpty:m.length===0,inputRef:j,isMobile:Ee}};exports.useInkeepChat=ze;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`}},ee=e=>{G(e),l(s=>{const a=[...s],r=a[a.length-1];return r&&(r.content=ke(e)),a}),w(!1),C(!1),J(),P()},R=!S.trim()&&!M.length||j,be=e=>{e.key==="Enter"&&!e.shiftKey&&!R&&!e.nativeEvent.isComposing&&(e.preventDefault(),x())},_e=e=>{const s=e.target.value;A(s)},x=async(e=S)=>{if(R&&(!e||e.trim().length===0))return;w(!0);const s=L?m.length===2:m.length===0,a=D.getMessageMetadata(L,M,s);let r;const p=D.serializeAttachments(M);M.length&&p?r=[{type:"text",text:p}]:r=e;const se={id:`${Date.now().toString()}-${g.generateUid(4)}-1`,role:"user",content:r,metadata:a},f=[...m.length?[]:Z,se];if(ie&&y){re.resetQueryParams();const u=o.current.map((i,E)=>({id:`${i.id}-${g.generateUid(6)}-${E}`,role:i.role,...i.role==="assistant"?{links:i.links??[]}:{},content:i.content,metadata:i.metadata,tool_calls:i.tool_calls}));l([...u,...f]),o.current=[...u,...f]}else l(u=>[...u,...f]),o.current=[...o.current,...f];I([]),A(""),await b({eventName:"user_message_submitted",properties:{}},o.current);const Ne=Y(),ne=[Je.provideLinksTool,...pe?.({conversation:Ne})||[]];try{const u={model:he,messages:o.current,stream:!0,tools:ne,tool_choice:"auto"},i=await de(),E=i?btoa(JSON.stringify(i)):null,oe=Q||z?JSON.stringify({...Q,...z}):void 0,U={};!K&&E&&(U["X-INKEEP-CHALLENGE-SOLUTION"]=E),oe&&(U["inkeep-filters"]=oe);const h=ge.beta.chat.completions.stream(u,Object.keys(U).length>0?{headers:U}:void 0),n={id:`${Date.now().toString()}-${g.generateUid(4)}-2`,role:"assistant",content:"",links:[],tool_calls:[]};l(d=>[...d,n]),h.on("content",(d,_)=>{C(!0),n.content=_,l(N=>{const c=[...N],B=c.findIndex($=>$.id===n.id);return B===-1?[...c,n]:(c[B]={...n},c)})}),h.on("tool_calls.function.arguments.done",async d=>{const{name:_,arguments:N}=d,c=ne?.find(v=>v.function.name===_);if(!c)return;const $=("parse"in c.function?c.function.parse:JSON.parse)(N),Ae=c.function.function?.($,h),Le=c.renderMessageButtons?.({args:$,execution:Ae})??[];_==="provideLinks"?n.links=$.links??[]:X(v=>({...v,[n.id]:[...v[n.id]??[],...Le]})),n.tool_calls?.push({id:"call_"+g.generateUid(24),type:"function",function:{name:_,arguments:N}}),l(v=>{const O=[...v],Re=O.findIndex(xe=>xe.id===n.id);return O[Re]={...n},O}),ve?.(d,{conversation:{...Y(),messages:[...o.current,n]}})}),h.on("error",ee),h.finalChatCompletion().then(async()=>{o.current=[...o.current,n],k.current=null,w(!1),C(!1),P(),await b({eventName:"assistant_message_received",properties:{}},o.current),b({eventName:"assistant_answer_displayed",properties:{}})}).catch(d=>{d instanceof ae.APIUserAbortError||console.warn(d)}),k.current=h.controller}catch(u){ee(u),w(!1),C(!1)}},$e=()=>{k.current&&(k.current.abort(),k.current=null),w(!1),C(!1),P()},te=()=>{G(null),l([]),o.current=[],ue(),X({}),I([]),re.resetQueryParams(),V(null),J(),P(),b({eventName:"chat_clear_button_clicked",properties:{conversation:le}})},qe=e=>{V(e);const{initialReplyMessage:s,displayName:a}=e,r={id:m.length.toString()+g.generateUid(4),role:"user",content:a},p={id:(m.length+1).toString()+g.generateUid(4),role:"assistant",content:s,links:[]},f=[{id:`system-${Date.now().toString()}-${g.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
+ ${D.serializeWorkflow(e)}`},...Z,r,p];l(f),I([])},{openForm:Pe}=Fe.useChatForm(),Ee=Te.useWidget();t.useImperativeHandle(F.chatFunctionsRef,()=>({submitMessage:x,updateInputMessage(e){A(e)},clearChat:te,openForm:e=>{Ee?.setView("chat"),Pe(e)},focusInput:()=>{H.current?.focus()}}));const Ue=Ke.useMediaQuery("(max-width: 768px)");return{messages:m,input:S,isLoading:j,isStreaming:ye,isLoadingConversation:Me,error:Se,isSubmitDisabled:R,handleInputChange:_e,handleInputKeyDown:be,handleSubmit:x,stop:$e,clear:te,handleWorkflow:qe,selectedWorkflow:L,messageAttachments:M,setMessageAttachments:I,addAttachment:we,messageButtons:Ce,isEmpty:m.length===0,inputRef:H,isMobile:Ue}};exports.useInkeepChat=je;
@@ -1,68 +1,68 @@
1
1
  "use client";
2
- import Oe, { APIUserAbortError as Pe } from "openai";
3
- import { useState as l, useRef as K, useEffect as ae, useImperativeHandle as Re } from "react";
4
- import { useInkeepConfig as Ue } from "../../providers/config-provider.js";
5
- import { useInkeepConversation as Fe } from "../../providers/conversation-provider.js";
6
- import { useChatEvents as Ke } from "../../providers/chat-events-provider.js";
7
- import { getMessageMetadata as Te, serializeAttachments as We, serializeWorkflow as Je } from "../../utils/get-message-metadata.js";
2
+ import Re, { APIUserAbortError as Ue } from "openai";
3
+ import { useState as l, useRef as F, useEffect as ae, useImperativeHandle as Fe } from "react";
4
+ import { useInkeepConfig as Ke } from "../../providers/config-provider.js";
5
+ import { useInkeepConversation as Te } from "../../providers/conversation-provider.js";
6
+ import { useChatEvents as We } from "../../providers/chat-events-provider.js";
7
+ import { getMessageMetadata as Je, serializeAttachments as ze, serializeWorkflow as He } from "../../utils/get-message-metadata.js";
8
8
  import { resetQueryParams as re } from "../../utils/reset-query-params.js";
9
- import { useChatForm as ze } from "../../providers/chat-form-provider.js";
10
- import { useWidget as He } from "../../providers/widget-provider.js";
11
- import { useMediaQuery as Qe } from "../../hooks/use-media-query.js";
12
- import { useCaptcha as je } from "./use-captcha.js";
13
- import { useModal as qe } from "../modal/modal-provider.js";
9
+ import { useChatForm as Qe } from "../../providers/chat-form-provider.js";
10
+ import { useWidget as je } from "../../providers/widget-provider.js";
11
+ import { useMediaQuery as qe } from "../../hooks/use-media-query.js";
12
+ import { useCaptcha as Ge } from "./use-captcha.js";
13
+ import { useModal as Ve } from "../modal/modal-provider.js";
14
14
  import { generateUid as g } from "../../utils/generate-uid.js";
15
- import { provideLinksTool as Ge } from "../../utils/tools/links-tool.js";
16
- import { getConversation as Ve } from "../../atoms/api/analytics/conversation.js";
17
- import { parseIfJson as Xe } from "../../utils/misc.js";
18
- const dt = () => {
19
- const { chatId: w, isSharedChat: ie, setConversation: ce, conversation: B, resetConversation: le } = Fe(), { baseSettings: E, aiChatSettings: T } = Ue(), { aiApiBaseUrl: W, shouldBypassCaptcha: J, filters: z } = E, H = qe(), { getSolution: ue, prefetchSolution: N, invalidateSolution: Q } = je({
20
- fetchUrl: `${W}/v1/challenge`,
21
- shouldBypassCaptcha: J,
22
- shouldMakeInitialRequest: H ? H.isOpen : !0
23
- }), me = new Oe({
24
- baseURL: `${W}/v1`,
15
+ import { provideLinksTool as Xe } from "../../utils/tools/links-tool.js";
16
+ import { getConversation as Ye } from "../../atoms/api/analytics/conversation.js";
17
+ import { parseIfJson as Ze } from "../../utils/misc.js";
18
+ const ht = () => {
19
+ const { chatId: v, isSharedChat: ie, setConversation: ce, conversation: le, resetConversation: ue } = Te(), { baseSettings: E, aiChatSettings: K } = Ke(), { aiApiBaseUrl: T, shouldBypassCaptcha: W, filters: J } = E, z = Ve(), { getSolution: me, prefetchSolution: N, invalidateSolution: H } = Ge({
20
+ fetchUrl: `${T}/v1/challenge`,
21
+ shouldBypassCaptcha: W,
22
+ shouldMakeInitialRequest: z ? z.isOpen : !0
23
+ }), ge = new Re({
24
+ baseURL: `${T}/v1`,
25
25
  apiKey: E.apiKey ?? "",
26
26
  dangerouslyAllowBrowser: !0
27
27
  }), {
28
- onInputMessageChange: ge,
29
- getTools: pe,
30
- prompts: de,
31
- model: fe,
32
- filters: j,
33
- onToolCall: he
34
- } = T, [v, D] = l(""), q = K(null);
28
+ onInputMessageChange: pe,
29
+ getTools: de,
30
+ prompts: fe,
31
+ model: he,
32
+ filters: Q,
33
+ onToolCall: ye
34
+ } = K, [w, B] = l(""), j = F(null);
35
35
  ae(() => {
36
- ge?.(v);
37
- }, [v]);
38
- const [p, c] = l([]), [G, C] = l(!1), [ye, I] = l(!1), [we, V] = l(null), [O, X] = l(null), [M, S] = l([]), ve = (e) => {
36
+ pe?.(w);
37
+ }, [w]);
38
+ const [p, c] = l([]), [q, C] = l(!1), [ve, I] = l(!1), [we, G] = l(null), [D, V] = l(null), [M, S] = l([]), Ce = (e) => {
39
39
  S((t) => [...t, e]);
40
- }, [Ce, Y] = l({}), n = K([]), k = K(null), { logEvent: _ } = Ke(), Z = de?.map((e, t) => ({
40
+ }, [Ie, X] = l({}), n = F([]), k = F(null), { logEvent: _, getLatestConversation: Y } = We(), Z = fe?.map((e, t) => ({
41
41
  id: `system-${Date.now().toString()}-${g(4)}-${t}`,
42
42
  role: "system",
43
43
  content: e
44
- })), [Ie, Me] = l(!!w);
44
+ })), [Me, Se] = l(!!v);
45
45
  ae(() => {
46
- if (w) {
46
+ if (v) {
47
47
  const { apiKey: e, analyticsApiBaseUrl: t } = E;
48
- Ve(w, e, t).then((o) => {
48
+ Ye(v, e, t).then((o) => {
49
49
  if (o) {
50
50
  _({
51
51
  eventName: "shared_chat_loaded",
52
52
  properties: {
53
53
  conversation: o
54
54
  }
55
- }), Me(!1), ce({ ...o });
55
+ }), Se(!1), ce({ ...o });
56
56
  const a = o.messages.map((d) => ({
57
57
  ...d,
58
- content: Xe(d.content)
58
+ content: Ze(d.content)
59
59
  }));
60
60
  c(a), n.current = a;
61
61
  }
62
62
  });
63
63
  }
64
- }, [w]);
65
- const Se = (e) => {
64
+ }, [v]);
65
+ const ke = (e) => {
66
66
  switch (e.code) {
67
67
  case 400:
68
68
  return e.message;
@@ -74,21 +74,21 @@ const dt = () => {
74
74
  It seems I might be having some issues right now. Please clear the chat and try again.`;
75
75
  }
76
76
  }, ee = (e) => {
77
- V(e), c((t) => {
77
+ G(e), c((t) => {
78
78
  const o = [...t], a = o[o.length - 1];
79
- return a && (a.content = Se(e)), o;
80
- }), C(!1), I(!1), Q(), N();
81
- }, P = !v.trim() && !M.length || G, ke = (e) => {
82
- e.key === "Enter" && !e.shiftKey && !P && !e.nativeEvent.isComposing && (e.preventDefault(), R());
83
- }, _e = (e) => {
79
+ return a && (a.content = ke(e)), o;
80
+ }), C(!1), I(!1), H(), N();
81
+ }, O = !w.trim() && !M.length || q, _e = (e) => {
82
+ e.key === "Enter" && !e.shiftKey && !O && !e.nativeEvent.isComposing && (e.preventDefault(), P());
83
+ }, be = (e) => {
84
84
  const t = e.target.value;
85
- D(t);
86
- }, R = async (e = v) => {
87
- if (P && (!e || e.trim().length === 0)) return;
85
+ B(t);
86
+ }, P = async (e = w) => {
87
+ if (O && (!e || e.trim().length === 0)) return;
88
88
  C(!0);
89
- const t = O ? p.length === 2 : p.length === 0, o = Te(O, M, t);
89
+ const t = D ? p.length === 2 : p.length === 0, o = Je(D, M, t);
90
90
  let a;
91
- const d = We(M);
91
+ const d = ze(M);
92
92
  M.length && d ? a = [{ type: "text", text: d }] : a = e;
93
93
  const se = {
94
94
  id: `${Date.now().toString()}-${g(4)}-1`,
@@ -96,7 +96,7 @@ It seems I might be having some issues right now. Please clear the chat and try
96
96
  content: a,
97
97
  metadata: o
98
98
  }, f = [...p.length ? [] : Z, se];
99
- if (ie && w) {
99
+ if (ie && v) {
100
100
  re();
101
101
  const u = n.current.map((r, A) => ({
102
102
  id: `${r.id}-${g(6)}-${A}`,
@@ -109,29 +109,29 @@ It seems I might be having some issues right now. Please clear the chat and try
109
109
  c([...u, ...f]), n.current = [...u, ...f];
110
110
  } else
111
111
  c((u) => [...u, ...f]), n.current = [...n.current, ...f];
112
- S([]), D(""), _(
112
+ S([]), B(""), await _(
113
113
  {
114
114
  eventName: "user_message_submitted",
115
115
  properties: {}
116
116
  },
117
117
  n.current
118
118
  );
119
- const ne = [Ge, ...pe?.({ conversation: B }) || []];
119
+ const xe = Y(), ne = [Xe, ...de?.({ conversation: xe }) || []];
120
120
  try {
121
121
  const u = {
122
- model: fe,
122
+ model: he,
123
123
  messages: n.current,
124
124
  stream: !0,
125
125
  tools: ne,
126
126
  tool_choice: "auto"
127
- }, r = await ue(), A = r ? btoa(JSON.stringify(r)) : null, oe = z || j ? JSON.stringify({
128
- ...z,
129
- ...j
130
- }) : void 0, x = {};
131
- !J && A && (x["X-INKEEP-CHALLENGE-SOLUTION"] = A), oe && (x["inkeep-filters"] = oe);
132
- const h = me.beta.chat.completions.stream(
127
+ }, r = await me(), A = r ? btoa(JSON.stringify(r)) : null, oe = J || Q ? JSON.stringify({
128
+ ...J,
129
+ ...Q
130
+ }) : void 0, L = {};
131
+ !W && A && (L["X-INKEEP-CHALLENGE-SOLUTION"] = A), oe && (L["inkeep-filters"] = oe);
132
+ const h = ge.beta.chat.completions.stream(
133
133
  u,
134
- Object.keys(x).length > 0 ? { headers: x } : void 0
134
+ Object.keys(L).length > 0 ? { headers: L } : void 0
135
135
  ), s = {
136
136
  id: `${Date.now().toString()}-${g(4)}-2`,
137
137
  role: "assistant",
@@ -140,30 +140,30 @@ It seems I might be having some issues right now. Please clear the chat and try
140
140
  tool_calls: []
141
141
  };
142
142
  c((m) => [...m, s]), h.on("content", (m, b) => {
143
- I(!0), s.content = b, c((L) => {
144
- const i = [...L], U = i.findIndex(($) => $.id === s.id);
145
- return U === -1 ? [...i, s] : (i[U] = { ...s }, i);
143
+ I(!0), s.content = b, c((x) => {
144
+ const i = [...x], R = i.findIndex(($) => $.id === s.id);
145
+ return R === -1 ? [...i, s] : (i[R] = { ...s }, i);
146
146
  });
147
147
  }), h.on("tool_calls.function.arguments.done", async (m) => {
148
- const { name: b, arguments: L } = m, i = ne?.find((y) => y.function.name === b);
148
+ const { name: b, arguments: x } = m, i = ne?.find((y) => y.function.name === b);
149
149
  if (!i) return;
150
- const $ = ("parse" in i.function ? i.function.parse : JSON.parse)(L), xe = i.function.function?.($, h), Le = i.renderMessageButtons?.({ args: $, execution: xe }) ?? [];
151
- b === "provideLinks" ? s.links = $.links ?? [] : Y((y) => ({
150
+ const $ = ("parse" in i.function ? i.function.parse : JSON.parse)(x), Be = i.function.function?.($, h), De = i.renderMessageButtons?.({ args: $, execution: Be }) ?? [];
151
+ b === "provideLinks" ? s.links = $.links ?? [] : X((y) => ({
152
152
  ...y,
153
- [s.id]: [...y[s.id] ?? [], ...Le]
153
+ [s.id]: [...y[s.id] ?? [], ...De]
154
154
  })), s.tool_calls?.push({
155
155
  id: "call_" + g(24),
156
156
  type: "function",
157
157
  function: {
158
158
  name: b,
159
- arguments: L
159
+ arguments: x
160
160
  }
161
161
  }), c((y) => {
162
- const F = [...y], Be = F.findIndex((De) => De.id === s.id);
163
- return F[Be] = { ...s }, F;
164
- }), he?.(m, {
162
+ const U = [...y], Oe = U.findIndex((Pe) => Pe.id === s.id);
163
+ return U[Oe] = { ...s }, U;
164
+ }), ye?.(m, {
165
165
  conversation: {
166
- ...B,
166
+ ...Y(),
167
167
  messages: [...n.current, s]
168
168
  }
169
169
  });
@@ -179,22 +179,22 @@ It seems I might be having some issues right now. Please clear the chat and try
179
179
  properties: {}
180
180
  });
181
181
  }).catch((m) => {
182
- m instanceof Pe || console.warn(m);
182
+ m instanceof Ue || console.warn(m);
183
183
  }), k.current = h.controller;
184
184
  } catch (u) {
185
185
  ee(u), C(!1), I(!1);
186
186
  }
187
- }, be = () => {
187
+ }, $e = () => {
188
188
  k.current && (k.current.abort(), k.current = null), C(!1), I(!1), N();
189
189
  }, te = () => {
190
- V(null), c([]), n.current = [], le(), Y({}), S([]), re(), X(null), Q(), N(), _({
190
+ G(null), c([]), n.current = [], ue(), X({}), S([]), re(), V(null), H(), N(), _({
191
191
  eventName: "chat_clear_button_clicked",
192
192
  properties: {
193
- conversation: B
193
+ conversation: le
194
194
  }
195
195
  });
196
- }, $e = (e) => {
197
- X(e);
196
+ }, Ee = (e) => {
197
+ V(e);
198
198
  const { initialReplyMessage: t, displayName: o } = e, a = {
199
199
  id: p.length.toString() + g(4),
200
200
  role: "user",
@@ -208,48 +208,48 @@ It seems I might be having some issues right now. Please clear the chat and try
208
208
  id: `system-${Date.now().toString()}-${g(4)}-${e.id}`,
209
209
  role: "system",
210
210
  content: `Company has asked user to follow this guided workflow:
211
- ${Je(e)}`
211
+ ${He(e)}`
212
212
  }, ...Z, a, d];
213
213
  c(f), S([]);
214
- }, { openForm: Ee } = ze(), Ne = He();
215
- Re(T.chatFunctionsRef, () => ({
216
- submitMessage: R,
214
+ }, { openForm: Ne } = Qe(), Ae = je();
215
+ Fe(K.chatFunctionsRef, () => ({
216
+ submitMessage: P,
217
217
  updateInputMessage(e) {
218
- D(e);
218
+ B(e);
219
219
  },
220
220
  clearChat: te,
221
221
  openForm: (e) => {
222
- Ne?.setView("chat"), Ee(e);
222
+ Ae?.setView("chat"), Ne(e);
223
223
  },
224
224
  focusInput: () => {
225
- q.current?.focus();
225
+ j.current?.focus();
226
226
  }
227
227
  }));
228
- const Ae = Qe("(max-width: 768px)");
228
+ const Le = qe("(max-width: 768px)");
229
229
  return {
230
230
  messages: p,
231
- input: v,
232
- isLoading: G,
233
- isStreaming: ye,
234
- isLoadingConversation: Ie,
231
+ input: w,
232
+ isLoading: q,
233
+ isStreaming: ve,
234
+ isLoadingConversation: Me,
235
235
  error: we,
236
- isSubmitDisabled: P,
237
- handleInputChange: _e,
238
- handleInputKeyDown: ke,
239
- handleSubmit: R,
240
- stop: be,
236
+ isSubmitDisabled: O,
237
+ handleInputChange: be,
238
+ handleInputKeyDown: _e,
239
+ handleSubmit: P,
240
+ stop: $e,
241
241
  clear: te,
242
- handleWorkflow: $e,
243
- selectedWorkflow: O,
242
+ handleWorkflow: Ee,
243
+ selectedWorkflow: D,
244
244
  messageAttachments: M,
245
245
  setMessageAttachments: S,
246
- addAttachment: ve,
247
- messageButtons: Ce,
246
+ addAttachment: Ce,
247
+ messageButtons: Ie,
248
248
  isEmpty: p.length === 0,
249
- inputRef: q,
250
- isMobile: Ae
249
+ inputRef: j,
250
+ isMobile: Le
251
251
  };
252
252
  };
253
253
  export {
254
- dt as useInkeepChat
254
+ ht as useInkeepChat
255
255
  };
package/dist/index.d.cts CHANGED
@@ -404,6 +404,10 @@ export declare type ChatEventsContextValue = {
404
404
  * Log a conversation.
405
405
  */
406
406
  logConversation: (messages: Message[]) => Promise<ConversationResponse | undefined>;
407
+ /**
408
+ * Get the latest conversation state (useful for accessing the conversation after it's been logged).
409
+ */
410
+ getLatestConversation: () => ConversationResponse;
407
411
  };
408
412
 
409
413
  export declare const ChatEventsProvider: React.FC<{
package/dist/index.d.ts CHANGED
@@ -404,6 +404,10 @@ export declare type ChatEventsContextValue = {
404
404
  * Log a conversation.
405
405
  */
406
406
  logConversation: (messages: Message[]) => Promise<ConversationResponse | undefined>;
407
+ /**
408
+ * Get the latest conversation state (useful for accessing the conversation after it's been logged).
409
+ */
410
+ getLatestConversation: () => ConversationResponse;
407
411
  };
408
412
 
409
413
  export declare const ChatEventsProvider: React.FC<{
@@ -1 +1 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("react/jsx-runtime"),t=require("react"),A=require("../atoms/api/analytics/conversation.cjs"),L=require("./config-provider.cjs"),O=require("./conversation-provider.cjs"),m=require("./user-provider.cjs"),B=require("./base-events-provider.cjs"),M=require("../utils/generate-uid.cjs"),x=t.createContext(void 0),K=({children:a})=>{const{baseSettings:w,aiChatSettings:I}=L.useInkeepConfig(),{apiKey:E,analyticsApiBaseUrl:g,tags:f,privacyPreferences:{optOutAllAnalytics:c},env:v,analyticsProperties:u}=w,{conversationVisibility:P}=I,{userProperties:y}=m.useUser(),{logEvent:b}=B.useBaseEvents(),{conversation:d,setConversation:S,chatId:l,isSharedChat:C,setExternalChatId:q}=O.useInkeepConversation(),o=t.useRef(d),h=t.useRef(C?l:void 0);t.useEffect(()=>{o.current=d},[d]),t.useEffect(()=>{h.current=C?l:void 0},[l,C]);const p=t.useCallback(async r=>{const e=o.current;h.current&&(e.id="",q(void 0),h.current=void 0);const n=!c&&v!=="development";let s=Object.assign({},e,{messages:r});if(n){const i=await A.logConversation(e.id,{messages:r,tags:f,userProperties:y,properties:u,visibility:P},E,g);i&&(s=i)}else s.id="conv_"+M.generateUid(16);return s},[g,E,f,y,c,v,u,q,P]),j={logEvent:t.useCallback(async(r,e)=>{let n=o.current;if(e){const i=o.current.messages||[];(e.length!==i.length||e.some((k,R)=>k.id!==i[R]?.id))&&(n=await p(e),S(n),o.current=n)}const s={...r,properties:{conversation:n,...r.properties}};b(s)},[b,p,c,v,u]),logConversation:p};return U.jsx(x.Provider,{value:j,children:a})},T=()=>{const a=t.useContext(x);if(!a)throw new Error("useChatEvents must be used within a ChatEventsProvider");return a};exports.ChatEventsProvider=K;exports.useChatEvents=T;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),e=require("react"),O=require("../atoms/api/analytics/conversation.cjs"),m=require("./config-provider.cjs"),B=require("./conversation-provider.cjs"),M=require("./user-provider.cjs"),K=require("./base-events-provider.cjs"),T=require("../utils/generate-uid.cjs"),x=e.createContext(void 0),V=({children:c})=>{const{baseSettings:k,aiChatSettings:w}=m.useInkeepConfig(),{apiKey:p,analyticsApiBaseUrl:E,tags:f,privacyPreferences:{optOutAllAnalytics:a},env:u,analyticsProperties:v}=k,{conversationVisibility:P}=w,{userProperties:b}=M.useUser(),{logEvent:y}=K.useBaseEvents(),{conversation:l,setConversation:I,chatId:d,isSharedChat:C,setExternalChatId:q}=B.useInkeepConversation(),n=e.useRef(l),h=e.useRef(C?d:void 0);e.useEffect(()=>{n.current=l},[l]),e.useEffect(()=>{h.current=C?d:void 0},[d,C]);const g=e.useCallback(async o=>{const t=n.current;h.current&&(t.id="",q(void 0),h.current=void 0);const s=!a&&u!=="development";let r=Object.assign({},t,{messages:o});if(s){const i=await O.logConversation(t.id,{messages:o,tags:f,userProperties:b,properties:v,visibility:P},p,E);i&&(r=i)}else r.id="conv_"+T.generateUid(16);return r},[E,p,f,b,a,u,v,q,P]),S=e.useCallback(async(o,t)=>{let s=n.current;if(t){const i=n.current.messages||[];(t.length!==i.length||t.some((R,U)=>R.id!==i[U]?.id))&&(s=await g(t),I(s),n.current=s)}const r={...o,properties:{conversation:s,...o.properties}};y(r)},[y,g,a,u,v]),j=e.useCallback(()=>n.current,[]),L={logEvent:S,logConversation:g,getLatestConversation:j};return A.jsx(x.Provider,{value:L,children:c})},_=()=>{const c=e.useContext(x);if(!c)throw new Error("useChatEvents must be used within a ChatEventsProvider");return c};exports.ChatEventsProvider=V;exports.useChatEvents=_;
@@ -1,90 +1,91 @@
1
1
  "use client";
2
- import { jsx as B } from "react/jsx-runtime";
3
- import { useRef as b, useEffect as P, useCallback as w, createContext as O, useContext as K } from "react";
4
- import { logConversation as M } from "../atoms/api/analytics/conversation.js";
5
- import { useInkeepConfig as R } from "./config-provider.js";
6
- import { useInkeepConversation as V } from "./conversation-provider.js";
7
- import { useUser as _ } from "./user-provider.js";
8
- import { useBaseEvents as $ } from "./base-events-provider.js";
9
- import { generateUid as q } from "../utils/generate-uid.js";
10
- const I = O(void 0), X = ({ children: i }) => {
11
- const { baseSettings: k, aiChatSettings: A } = R(), {
2
+ import { jsx as K } from "react/jsx-runtime";
3
+ import { useRef as P, useEffect as w, useCallback as f, createContext as M, useContext as R } from "react";
4
+ import { logConversation as V } from "../atoms/api/analytics/conversation.js";
5
+ import { useInkeepConfig as _ } from "./config-provider.js";
6
+ import { useInkeepConversation as $ } from "./conversation-provider.js";
7
+ import { useUser as q } from "./user-provider.js";
8
+ import { useBaseEvents as z } from "./base-events-provider.js";
9
+ import { generateUid as D } from "../utils/generate-uid.js";
10
+ const I = M(void 0), Y = ({ children: i }) => {
11
+ const { baseSettings: L, aiChatSettings: k } = _(), {
12
12
  apiKey: h,
13
- analyticsApiBaseUrl: f,
14
- tags: m,
13
+ analyticsApiBaseUrl: m,
14
+ tags: g,
15
15
  privacyPreferences: { optOutAllAnalytics: a },
16
16
  env: c,
17
17
  analyticsProperties: v
18
- } = k, { conversationVisibility: g } = A, { userProperties: E } = _(), { logEvent: y } = $(), { conversation: u, setConversation: L, chatId: l, isSharedChat: d, setExternalChatId: x } = V(), n = b(u), p = b(d ? l : void 0);
19
- P(() => {
20
- n.current = u;
21
- }, [u]), P(() => {
22
- p.current = d ? l : void 0;
23
- }, [l, d]);
24
- const C = w(
18
+ } = L, { conversationVisibility: E } = k, { userProperties: y } = q(), { logEvent: x } = z(), { conversation: u, setConversation: A, chatId: l, isSharedChat: p, setExternalChatId: b } = $(), e = P(u), C = P(p ? l : void 0);
19
+ w(() => {
20
+ e.current = u;
21
+ }, [u]), w(() => {
22
+ C.current = p ? l : void 0;
23
+ }, [l, p]);
24
+ const d = f(
25
25
  async (o) => {
26
- const t = n.current;
27
- p.current && (t.id = "", x(void 0), p.current = void 0);
28
- const e = !a && c !== "development";
26
+ const t = e.current;
27
+ C.current && (t.id = "", b(void 0), C.current = void 0);
28
+ const n = !a && c !== "development";
29
29
  let r = Object.assign({}, t, { messages: o });
30
- if (e) {
31
- const s = await M(
30
+ if (n) {
31
+ const s = await V(
32
32
  t.id,
33
33
  {
34
34
  messages: o,
35
- tags: m,
36
- userProperties: E,
35
+ tags: g,
36
+ userProperties: y,
37
37
  properties: v,
38
- visibility: g
38
+ visibility: E
39
39
  },
40
40
  h,
41
- f
41
+ m
42
42
  );
43
43
  s && (r = s);
44
44
  } else
45
- r.id = "conv_" + q(16);
45
+ r.id = "conv_" + D(16);
46
46
  return r;
47
47
  },
48
48
  [
49
- f,
50
- h,
51
49
  m,
52
- E,
50
+ h,
51
+ g,
52
+ y,
53
53
  a,
54
54
  c,
55
55
  v,
56
- x,
57
- g
56
+ b,
57
+ E
58
58
  ]
59
- ), S = {
60
- logEvent: w(
61
- async (o, t) => {
62
- let e = n.current;
63
- if (t) {
64
- const s = n.current.messages || [];
65
- (t.length !== s.length || t.some((U, j) => U.id !== s[j]?.id)) && (e = await C(t), L(e), n.current = e);
59
+ ), S = f(
60
+ async (o, t) => {
61
+ let n = e.current;
62
+ if (t) {
63
+ const s = e.current.messages || [];
64
+ (t.length !== s.length || t.some((B, O) => B.id !== s[O]?.id)) && (n = await d(t), A(n), e.current = n);
65
+ }
66
+ const r = {
67
+ ...o,
68
+ properties: {
69
+ conversation: n,
70
+ ...o.properties
66
71
  }
67
- const r = {
68
- ...o,
69
- properties: {
70
- conversation: e,
71
- ...o.properties
72
- }
73
- };
74
- y(r);
75
- },
76
- [y, C, a, c, v]
77
- ),
78
- logConversation: C
72
+ };
73
+ x(r);
74
+ },
75
+ [x, d, a, c, v]
76
+ ), U = f(() => e.current, []), j = {
77
+ logEvent: S,
78
+ logConversation: d,
79
+ getLatestConversation: U
79
80
  };
80
- return /* @__PURE__ */ B(I.Provider, { value: S, children: i });
81
- }, Y = () => {
82
- const i = K(I);
81
+ return /* @__PURE__ */ K(I.Provider, { value: j, children: i });
82
+ }, Z = () => {
83
+ const i = R(I);
83
84
  if (!i)
84
85
  throw new Error("useChatEvents must be used within a ChatEventsProvider");
85
86
  return i;
86
87
  };
87
88
  export {
88
- X as ChatEventsProvider,
89
- Y as useChatEvents
89
+ Y as ChatEventsProvider,
90
+ Z as useChatEvents
90
91
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/cxkit-primitives",
3
- "version": "0.0.0-dev-20251216042053",
3
+ "version": "0.0.0-dev-20251216053643",
4
4
  "description": "",
5
5
  "license": "Inkeep, Inc. Customer License (IICL) v1.1",
6
6
  "homepage": "",
@@ -67,9 +67,9 @@
67
67
  "remark-gfm": "^4.0.1",
68
68
  "unist-util-visit": "^5.0.0",
69
69
  "use-sync-external-store": "^1.4.0",
70
- "@inkeep/cxkit-color-mode": "^0.0.0-dev-20251216042053",
71
- "@inkeep/cxkit-theme": "0.0.0-dev-20251216042053",
72
- "@inkeep/cxkit-types": "0.0.0-dev-20251216042053"
70
+ "@inkeep/cxkit-color-mode": "^0.0.0-dev-20251216053643",
71
+ "@inkeep/cxkit-theme": "0.0.0-dev-20251216053643",
72
+ "@inkeep/cxkit-types": "0.0.0-dev-20251216053643"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@biomejs/biome": "1.9.4",