@inkeep/cxkit-primitives 0.5.35 → 0.5.37

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 Ee=require("openai"),t=require("react"),$e=require("../../atoms/api/analytics/conversation.cjs"),Ue=require("../../providers/config-provider.cjs"),Ne=require("../../providers/conversation-provider.cjs"),_e=require("../../providers/chat-events-provider.cjs"),D=require("../../utils/get-message-metadata.cjs"),Ae=require("../../utils/misc.cjs"),te=require("../../utils/reset-query-params.cjs"),Re=require("../../providers/chat-form-provider.cjs"),De=require("../../providers/widget-provider.cjs"),Le=require("../../hooks/use-media-query.cjs"),Oe=require("./use-captcha.cjs"),xe=require("../modal/modal-provider.cjs"),m=require("../../utils/generate-uid.cjs"),Fe=()=>{const{chatId:h,setConversation:se,conversation:ne,resetConversation:oe}=Ne.useInkeepConversation(),{baseSettings:k,aiChatSettings:L}=Ue.useInkeepConfig(),{aiApiBaseUrl:O,shouldBypassCaptcha:x,filters:F}=k,K=xe.useModal(),{getSolution:ae,prefetchSolution:b,invalidateSolution:T}=Oe.useCaptcha({fetchUrl:`${O}/v1/challenge`,shouldBypassCaptcha:x,shouldMakeInitialRequest:K?K.isOpen:!0}),re=new Ee({baseURL:`${O}/v1`,apiKey:k.apiKey,dangerouslyAllowBrowser:!0}),{onInputMessageChange:ie,tools:ce,prompts:le,model:ue,onToolCall:ge,filters:B}=L,[p,$]=t.useState(""),Q=t.useRef(null);t.useEffect(()=>{ie?.(p)},[p]);const[u,l]=t.useState([]),[W,f]=t.useState(!1),[de,v]=t.useState(!1),[me,J]=t.useState(null),[U,z]=t.useState(null),[y,S]=t.useState([]),he=e=>{S(s=>[...s,e])},[pe,H]=t.useState({}),i=t.useRef([]),C=t.useRef(null),{logEvent:q}=_e.useChatEvents(),j=le?.map((e,s)=>({id:`system-${Date.now().toString()}-${m.generateUid(4)}-${s}`,role:"system",content:e})),[fe,ve]=t.useState(!!h);t.useEffect(()=>{if(h){const{apiKey:e,analyticsApiBaseUrl:s}=k;$e.getConversation(h,e,s).then(n=>{if(n){q({eventName:"shared_chat_loaded",properties:{conversation:n}}),ve(!1),se({...n,id:""});const o=n.messages.map(c=>({id:Date.now().toString()+m.generateUid(4)+c.id,content:Ae.parseIfJson(c.content),role:c.role,links:c.links}));l(o),i.current=o}})}},[h]);const ye=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${k.organizationDisplayName??"Administrator"}`;default:return`Hmm..
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("openai"),t=require("react"),Ae=require("../../providers/config-provider.cjs"),Re=require("../../providers/conversation-provider.cjs"),Le=require("../../providers/chat-events-provider.cjs"),B=require("../../utils/get-message-metadata.cjs"),xe=require("../../utils/misc.cjs"),ae=require("../../utils/reset-query-params.cjs"),Be=require("../../providers/chat-form-provider.cjs"),De=require("../../providers/widget-provider.cjs"),Oe=require("../../hooks/use-media-query.cjs"),Fe=require("./use-captcha.cjs"),Ke=require("../modal/modal-provider.cjs"),u=require("../../utils/generate-uid.cjs"),Te=require("../../utils/tools/links-tool.cjs"),Qe=require("../../atoms/api/analytics/conversation.cjs"),We=()=>{const{chatId:f,setConversation:re,conversation:D,resetConversation:ie}=Re.useInkeepConversation(),{baseSettings:k,aiChatSettings:O}=Ae.useInkeepConfig(),{aiApiBaseUrl:F,shouldBypassCaptcha:K,filters:T}=k,Q=Ke.useModal(),{getSolution:ce,prefetchSolution:b,invalidateSolution:W}=Fe.useCaptcha({fetchUrl:`${F}/v1/challenge`,shouldBypassCaptcha:K,shouldMakeInitialRequest:Q?Q.isOpen:!0}),le=new _e({baseURL:`${F}/v1`,apiKey:k.apiKey,dangerouslyAllowBrowser:!0}),{onInputMessageChange:ue,getTools:ge,prompts:de,model:me,filters:J}=O,[p,N]=t.useState(""),z=t.useRef(null);t.useEffect(()=>{ue?.(p)},[p]);const[g,l]=t.useState([]),[H,h]=t.useState(!1),[fe,v]=t.useState(!1),[pe,j]=t.useState(null),[_,G]=t.useState(null),[y,S]=t.useState([]),he=e=>{S(s=>[...s,e])},[ve,V]=t.useState({}),i=t.useRef([]),C=t.useRef(null),{logEvent:q}=Le.useChatEvents(),X=de?.map((e,s)=>({id:`system-${Date.now().toString()}-${u.generateUid(4)}-${s}`,role:"system",content:e})),[ye,Se]=t.useState(!!f);t.useEffect(()=>{if(f){const{apiKey:e,analyticsApiBaseUrl:s}=k;Qe.getConversation(f,e,s).then(n=>{if(n){q({eventName:"shared_chat_loaded",properties:{conversation:n}}),Se(!1),re({...n,id:""});const a=n.messages.map(c=>({id:Date.now().toString()+u.generateUid(4)+c.id,content:xe.parseIfJson(c.content),role:c.role,links:c.links}));l(a),i.current=a}})}},[f]);const Ce=e=>{switch(e.code){case 400:return e.message;case 403:return`There seems to be a configuration error. Please contact ${k.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.`}},G=e=>{J(e),l(s=>{const n=[...s],o=n[n.length-1];return o&&(o.content=ye(e)),n}),f(!1),v(!1),T(),b()},N=!p.trim()&&!y.length||W,Se=e=>{e.key==="Enter"&&!e.shiftKey&&!N&&!e.nativeEvent.isComposing&&(e.preventDefault(),_())},Ce=e=>{const s=e.target.value;$(s)},_=async(e=p)=>{if(N&&(!e||e.trim().length===0))return;f(!0);const s=U?u.length===2:u.length===0,n=D.getMessageMetadata(U,y,s);let o;const c=D.serializeAttachments(y);y.length&&c?o=[{type:"text",text:c}]:o=e;const X={id:`${Date.now().toString()}-${m.generateUid(4)}-1`,role:"user",content:o,metadata:n},P=[...u.length?[]:j,X];h&&te.resetQueryParams(),l(M=>[...M,...P]),i.current=[...i.current,...P],S([]),$(""),q({eventName:"user_message_submitted",properties:{}},i.current);try{const M={model:ue,messages:i.current,stream:!0,tools:ce,tool_choice:"auto"},Y=await ae(),Z=Y?btoa(JSON.stringify(Y)):null,ee=F||B?JSON.stringify({...F,...B}):void 0,E={};!x&&Z&&(E["X-INKEEP-CHALLENGE-SOLUTION"]=Z),ee&&(E["inkeep-filters"]=ee);const w=re.beta.chat.completions.stream(M,Object.keys(E).length>0?{headers:E}:void 0),a={id:`${Date.now().toString()}-${m.generateUid(4)}-2`,role:"assistant",content:"",links:[]};l(g=>[...g,a]),w.on("content",(g,A)=>{v(!0),a.content=A,l(R=>{const r=[...R],d=r.findIndex(I=>I.id===a.id);return d===-1?[...r,a]:(r[d]={...a},r)})}),w.on("tool_calls.function.arguments.done",g=>{const{name:A,arguments:R}=g;if(A==="provideLinks"){const r=JSON.parse(R);r.links?.length>0&&(a.links=r.links,l(d=>{const I=[...d],qe=I.findIndex(Pe=>Pe.id===a.id);return I[qe]={...a},I}))}else{const r=ge?.(g);r&&H(d=>({...d,[a.id]:[...d[a.id]||[],r]}))}}),w.on("error",g=>{G(g)}),w.finalChatCompletion().then(()=>{i.current=[...i.current,a],C.current=null,f(!1),v(!1),b(),q({eventName:"assistant_message_received",properties:{}},i.current)}),C.current=w.controller}catch(M){G(M),f(!1),v(!1)}},Me=()=>{C.current&&(C.current.abort(),C.current=null),f(!1),v(!1),b()},V=()=>{J(null),l([]),i.current=[],oe(),H({}),S([]),te.resetQueryParams(),z(null),T(),b(),q({eventName:"chat_clear_button_clicked",properties:{conversation:ne}})},we=e=>{z(e);const{initialReplyMessage:s,displayName:n}=e,o={id:u.length.toString()+m.generateUid(4),role:"user",content:n},c={id:(u.length+1).toString()+m.generateUid(4),role:"assistant",content:s,links:[]},P=[{id:`system-${Date.now().toString()}-${m.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
- ${D.serializeWorkflow(e)}`},...j,o,c];l(P),S([])},{openForm:Ie}=Re.useChatForm(),ke=De.useWidget();t.useImperativeHandle(L.chatFunctionsRef,()=>({submitMessage:_,updateInputMessage(e){$(e)},clearChat:V,openForm:e=>{ke?.setView("chat"),Ie(e)},focusInput:()=>{Q.current?.focus()}}));const be=Le.useMediaQuery("(max-width: 768px)");return{messages:u,input:p,isLoading:W,isStreaming:de,isLoadingConversation:fe,error:me,isSubmitDisabled:N,handleInputChange:Ce,handleInputKeyDown:Se,handleSubmit:_,stop:Me,clear:V,handleWorkflow:we,selectedWorkflow:U,messageAttachments:y,setMessageAttachments:S,addAttachment:he,messageToolCalls:pe,isEmpty:u.length===0,inputRef:Q,isMobile:be}};exports.useInkeepChat=Fe;
3
+ It seems I might be having some issues right now. Please clear the chat and try again.`}},Y=e=>{j(e),l(s=>{const n=[...s],a=n[n.length-1];return a&&(a.content=Ce(e)),n}),h(!1),v(!1),W(),b()},A=!p.trim()&&!y.length||H,Me=e=>{e.key==="Enter"&&!e.shiftKey&&!A&&!e.nativeEvent.isComposing&&(e.preventDefault(),R())},we=e=>{const s=e.target.value;N(s)},R=async(e=p)=>{if(A&&(!e||e.trim().length===0))return;h(!0);const s=_?g.length===2:g.length===0,n=B.getMessageMetadata(_,y,s);let a;const c=B.serializeAttachments(y);y.length&&c?a=[{type:"text",text:c}]:a=e;const ee={id:`${Date.now().toString()}-${u.generateUid(4)}-1`,role:"user",content:a,metadata:n},P=[...g.length?[]:X,ee];f&&ae.resetQueryParams(),l(M=>[...M,...P]),i.current=[...i.current,...P],S([]),N(""),q({eventName:"user_message_submitted",properties:{}},i.current);const te=[Te.provideLinksTool,...ge?.({conversation:D})||[]];try{const M={model:me,messages:i.current,stream:!0,tools:te,tool_choice:"auto"},se=await ce(),ne=se?btoa(JSON.stringify(se)):null,oe=T||J?JSON.stringify({...T,...J}):void 0,E={};!K&&ne&&(E["X-INKEEP-CHALLENGE-SOLUTION"]=ne),oe&&(E["inkeep-filters"]=oe);const d=le.beta.chat.completions.stream(M,Object.keys(E).length>0?{headers:E}:void 0),o={id:`${Date.now().toString()}-${u.generateUid(4)}-2`,role:"assistant",content:"",links:[],toolCalls:[]};l(U=>[...U,o]),d.on("content",(U,w)=>{v(!0),o.content=w,l($=>{const r=[...$],L=r.findIndex(I=>I.id===o.id);return L===-1?[...r,o]:(r[L]={...o},r)})}),d.on("tool_calls.function.arguments.done",U=>{const{name:w,arguments:$}=U,r=te?.find(m=>m.function.name===w);if(!r)return;const I=("parse"in r.function?r.function.parse:JSON.parse)($),Ee=r.function.function?.(I,d),Ue=r.renderMessageButtons?.({args:I,execution:Ee})??[];w==="provideLinks"?o.links=I.links??[]:V(m=>({...m,[o.id]:[...m[o.id]??[],...Ue]})),o.toolCalls?.push({id:"call_"+u.generateUid(24),type:"function",function:{name:w,arguments:$}}),l(m=>{const x=[...m],$e=x.findIndex(Ne=>Ne.id===o.id);return x[$e]={...o},x})}),d.on("error",Y),d.finalChatCompletion().then(()=>{i.current=[...i.current,o],C.current=null,h(!1),v(!1),b(),q({eventName:"assistant_message_received",properties:{}},i.current)}),C.current=d.controller}catch(M){Y(M),h(!1),v(!1)}},Ie=()=>{C.current&&(C.current.abort(),C.current=null),h(!1),v(!1),b()},Z=()=>{j(null),l([]),i.current=[],ie(),V({}),S([]),ae.resetQueryParams(),G(null),W(),b(),q({eventName:"chat_clear_button_clicked",properties:{conversation:D}})},ke=e=>{G(e);const{initialReplyMessage:s,displayName:n}=e,a={id:g.length.toString()+u.generateUid(4),role:"user",content:n},c={id:(g.length+1).toString()+u.generateUid(4),role:"assistant",content:s,links:[]},P=[{id:`system-${Date.now().toString()}-${u.generateUid(4)}-${e.id}`,role:"system",content:`Company has asked user to follow this guided workflow:
4
+ ${B.serializeWorkflow(e)}`},...X,a,c];l(P),S([])},{openForm:be}=Be.useChatForm(),qe=De.useWidget();t.useImperativeHandle(O.chatFunctionsRef,()=>({submitMessage:R,updateInputMessage(e){N(e)},clearChat:Z,openForm:e=>{qe?.setView("chat"),be(e)},focusInput:()=>{z.current?.focus()}}));const Pe=Oe.useMediaQuery("(max-width: 768px)");return{messages:g,input:p,isLoading:H,isStreaming:fe,isLoadingConversation:ye,error:pe,isSubmitDisabled:A,handleInputChange:we,handleInputKeyDown:Me,handleSubmit:R,stop:Ie,clear:Z,handleWorkflow:ke,selectedWorkflow:_,messageAttachments:y,setMessageAttachments:S,addAttachment:he,messageButtons:ve,isEmpty:g.length===0,inputRef:z,isMobile:Pe}};exports.useInkeepChat=We;
@@ -1,69 +1,63 @@
1
1
  "use client";
2
- import _e from "openai";
3
- import { useState as c, useRef as R, useEffect as te, useImperativeHandle as Ae } from "react";
4
- import { getConversation as xe } from "../../atoms/api/analytics/conversation.js";
5
- import { useInkeepConfig as De } from "../../providers/config-provider.js";
6
- import { useInkeepConversation as Le } from "../../providers/conversation-provider.js";
7
- import { useChatEvents as Oe } from "../../providers/chat-events-provider.js";
8
- import { getMessageMetadata as Re, serializeAttachments as Pe, serializeWorkflow as Ue } from "../../utils/get-message-metadata.js";
9
- import { parseIfJson as Fe } from "../../utils/misc.js";
10
- import { resetQueryParams as se } from "../../utils/reset-query-params.js";
11
- import { useChatForm as Ke } from "../../providers/chat-form-provider.js";
12
- import { useWidget as Be } from "../../providers/widget-provider.js";
13
- import { useMediaQuery as Te } from "../../hooks/use-media-query.js";
14
- import { useCaptcha as We } from "./use-captcha.js";
15
- import { useModal as Je } from "../modal/modal-provider.js";
16
- import { generateUid as d } from "../../utils/generate-uid.js";
17
- const at = () => {
18
- const { chatId: p, setConversation: ne, conversation: oe, resetConversation: ae } = Le(), { baseSettings: k, aiChatSettings: P } = De(), { aiApiBaseUrl: U, shouldBypassCaptcha: F, filters: K } = k, B = Je(), { getSolution: re, prefetchSolution: b, invalidateSolution: T } = We({
19
- fetchUrl: `${U}/v1/challenge`,
20
- shouldBypassCaptcha: F,
21
- shouldMakeInitialRequest: B ? B.isOpen : !0
22
- }), ie = new _e({
23
- baseURL: `${U}/v1`,
2
+ import Be from "openai";
3
+ import { useState as c, useRef as P, useEffect as ae, useImperativeHandle as De } from "react";
4
+ import { useInkeepConfig as Oe } from "../../providers/config-provider.js";
5
+ import { useInkeepConversation as Re } from "../../providers/conversation-provider.js";
6
+ import { useChatEvents as Pe } from "../../providers/chat-events-provider.js";
7
+ import { getMessageMetadata as Ue, serializeAttachments as Fe, serializeWorkflow as Ke } from "../../utils/get-message-metadata.js";
8
+ import { parseIfJson as We } from "../../utils/misc.js";
9
+ import { resetQueryParams as re } from "../../utils/reset-query-params.js";
10
+ import { useChatForm as Je } from "../../providers/chat-form-provider.js";
11
+ import { useWidget as Te } from "../../providers/widget-provider.js";
12
+ import { useMediaQuery as ze } from "../../hooks/use-media-query.js";
13
+ import { useCaptcha as He } from "./use-captcha.js";
14
+ import { useModal as Qe } from "../modal/modal-provider.js";
15
+ import { generateUid as u } from "../../utils/generate-uid.js";
16
+ import { provideLinksTool as je } from "../../utils/tools/links-tool.js";
17
+ import { getConversation as qe } from "../../atoms/api/analytics/conversation.js";
18
+ const mt = () => {
19
+ const { chatId: d, setConversation: ie, conversation: U, resetConversation: ce } = Re(), { baseSettings: k, aiChatSettings: F } = Oe(), { aiApiBaseUrl: K, shouldBypassCaptcha: W, filters: J } = k, T = Qe(), { getSolution: le, prefetchSolution: b, invalidateSolution: z } = He({
20
+ fetchUrl: `${K}/v1/challenge`,
21
+ shouldBypassCaptcha: W,
22
+ shouldMakeInitialRequest: T ? T.isOpen : !0
23
+ }), ue = new Be({
24
+ baseURL: `${K}/v1`,
24
25
  apiKey: k.apiKey,
25
26
  dangerouslyAllowBrowser: !0
26
- }), {
27
- onInputMessageChange: ce,
28
- tools: le,
29
- prompts: ue,
30
- model: me,
31
- onToolCall: ge,
32
- filters: W
33
- } = P, [f, _] = c(""), J = R(null);
34
- te(() => {
35
- ce?.(f);
27
+ }), { onInputMessageChange: me, getTools: ge, prompts: pe, model: de, filters: H } = F, [f, x] = c(""), Q = P(null);
28
+ ae(() => {
29
+ me?.(f);
36
30
  }, [f]);
37
- const [u, l] = c([]), [z, h] = c(!1), [de, y] = c(!1), [pe, H] = c(null), [A, Q] = c(null), [C, w] = c([]), fe = (e) => {
31
+ const [m, l] = c([]), [j, h] = c(!1), [fe, y] = c(!1), [he, q] = c(null), [L, G] = c(null), [C, w] = c([]), ye = (e) => {
38
32
  w((t) => [...t, e]);
39
- }, [he, j] = c({}), r = R([]), I = R(null), { logEvent: $ } = Oe(), q = ue?.map((e, t) => ({
40
- id: `system-${Date.now().toString()}-${d(4)}-${t}`,
33
+ }, [Ce, V] = c({}), r = P([]), v = P(null), { logEvent: $ } = Pe(), X = pe?.map((e, t) => ({
34
+ id: `system-${Date.now().toString()}-${u(4)}-${t}`,
41
35
  role: "system",
42
36
  content: e
43
- })), [ye, Ce] = c(!!p);
44
- te(() => {
45
- if (p) {
37
+ })), [we, ve] = c(!!d);
38
+ ae(() => {
39
+ if (d) {
46
40
  const { apiKey: e, analyticsApiBaseUrl: t } = k;
47
- xe(p, e, t).then((s) => {
41
+ qe(d, e, t).then((s) => {
48
42
  if (s) {
49
43
  $({
50
44
  eventName: "shared_chat_loaded",
51
45
  properties: {
52
46
  conversation: s
53
47
  }
54
- }), Ce(!1), ne({ ...s, id: "" });
55
- const n = s.messages.map((i) => ({
56
- id: Date.now().toString() + d(4) + i.id,
57
- content: Fe(i.content),
48
+ }), ve(!1), ie({ ...s, id: "" });
49
+ const o = s.messages.map((i) => ({
50
+ id: Date.now().toString() + u(4) + i.id,
51
+ content: We(i.content),
58
52
  role: i.role,
59
53
  links: i.links
60
54
  }));
61
- l(n), r.current = n;
55
+ l(o), r.current = o;
62
56
  }
63
57
  });
64
58
  }
65
- }, [p]);
66
- const we = (e) => {
59
+ }, [d]);
60
+ const Ie = (e) => {
67
61
  switch (e.code) {
68
62
  case 400:
69
63
  return e.message;
@@ -74,159 +68,160 @@ const at = () => {
74
68
 
75
69
  It seems I might be having some issues right now. Please clear the chat and try again.`;
76
70
  }
77
- }, G = (e) => {
78
- H(e), l((t) => {
79
- const s = [...t], n = s[s.length - 1];
80
- return n && (n.content = we(e)), s;
81
- }), h(!1), y(!1), T(), b();
82
- }, x = !f.trim() && !C.length || z, Ie = (e) => {
83
- e.key === "Enter" && !e.shiftKey && !x && !e.nativeEvent.isComposing && (e.preventDefault(), D());
84
- }, ve = (e) => {
71
+ }, Y = (e) => {
72
+ q(e), l((t) => {
73
+ const s = [...t], o = s[s.length - 1];
74
+ return o && (o.content = Ie(e)), s;
75
+ }), h(!1), y(!1), z(), b();
76
+ }, B = !f.trim() && !C.length || j, Me = (e) => {
77
+ e.key === "Enter" && !e.shiftKey && !B && !e.nativeEvent.isComposing && (e.preventDefault(), D());
78
+ }, Se = (e) => {
85
79
  const t = e.target.value;
86
- _(t);
80
+ x(t);
87
81
  }, D = async (e = f) => {
88
- if (x && (!e || e.trim().length === 0)) return;
82
+ if (B && (!e || e.trim().length === 0)) return;
89
83
  h(!0);
90
- const t = A ? u.length === 2 : u.length === 0, s = Re(A, C, t);
91
- let n;
92
- const i = Pe(C);
93
- C.length && i ? n = [{ type: "text", text: i }] : n = e;
94
- const X = {
95
- id: `${Date.now().toString()}-${d(4)}-1`,
84
+ const t = L ? m.length === 2 : m.length === 0, s = Ue(L, C, t);
85
+ let o;
86
+ const i = Fe(C);
87
+ C.length && i ? o = [{ type: "text", text: i }] : o = e;
88
+ const ee = {
89
+ id: `${Date.now().toString()}-${u(4)}-1`,
96
90
  role: "user",
97
- content: n,
91
+ content: o,
98
92
  metadata: s
99
- }, E = [...u.length ? [] : q, X];
100
- p && se(), l((v) => [...v, ...E]), r.current = [...r.current, ...E], w([]), _(""), $(
93
+ }, E = [...m.length ? [] : X, ee];
94
+ d && re(), l((I) => [...I, ...E]), r.current = [...r.current, ...E], w([]), x(""), $(
101
95
  {
102
96
  eventName: "user_message_submitted",
103
97
  properties: {}
104
98
  },
105
99
  r.current
106
100
  );
101
+ const te = [je, ...ge?.({ conversation: U }) || []];
107
102
  try {
108
- const v = {
109
- model: me,
103
+ const I = {
104
+ model: de,
110
105
  messages: r.current,
111
106
  stream: !0,
112
- tools: le,
107
+ tools: te,
113
108
  tool_choice: "auto"
114
- }, Y = await re(), Z = Y ? btoa(JSON.stringify(Y)) : null, ee = K || W ? JSON.stringify({
115
- ...K,
116
- ...W
109
+ }, se = await le(), ne = se ? btoa(JSON.stringify(se)) : null, oe = J || H ? JSON.stringify({
110
+ ...J,
111
+ ...H
117
112
  }) : void 0, N = {};
118
- !F && Z && (N["X-INKEEP-CHALLENGE-SOLUTION"] = Z), ee && (N["inkeep-filters"] = ee);
119
- const M = ie.beta.chat.completions.stream(
120
- v,
113
+ !W && ne && (N["X-INKEEP-CHALLENGE-SOLUTION"] = ne), oe && (N["inkeep-filters"] = oe);
114
+ const g = ue.beta.chat.completions.stream(
115
+ I,
121
116
  Object.keys(N).length > 0 ? { headers: N } : void 0
122
- ), o = {
123
- id: `${Date.now().toString()}-${d(4)}-2`,
117
+ ), n = {
118
+ id: `${Date.now().toString()}-${u(4)}-2`,
124
119
  role: "assistant",
125
120
  content: "",
126
- links: []
121
+ links: [],
122
+ toolCalls: []
127
123
  };
128
- l((m) => [...m, o]), M.on("content", (m, L) => {
129
- y(!0), o.content = L, l((O) => {
130
- const a = [...O], g = a.findIndex((S) => S.id === o.id);
131
- return g === -1 ? [...a, o] : (a[g] = { ...o }, a);
124
+ l((_) => [..._, n]), g.on("content", (_, M) => {
125
+ y(!0), n.content = M, l((A) => {
126
+ const a = [...A], O = a.findIndex((S) => S.id === n.id);
127
+ return O === -1 ? [...a, n] : (a[O] = { ...n }, a);
132
128
  });
133
- }), M.on("tool_calls.function.arguments.done", (m) => {
134
- const { name: L, arguments: O } = m;
135
- if (L === "provideLinks") {
136
- const a = JSON.parse(O);
137
- a.links?.length > 0 && (o.links = a.links, l((g) => {
138
- const S = [...g], Ee = S.findIndex((Ne) => Ne.id === o.id);
139
- return S[Ee] = { ...o }, S;
140
- }));
141
- } else {
142
- const a = ge?.(m);
143
- a && j((g) => ({
144
- ...g,
145
- [o.id]: [...g[o.id] || [], a]
146
- }));
147
- }
148
- }), M.on("error", (m) => {
149
- G(m);
150
- }), M.finalChatCompletion().then(() => {
151
- r.current = [...r.current, o], I.current = null, h(!1), y(!1), b(), $(
129
+ }), g.on("tool_calls.function.arguments.done", (_) => {
130
+ const { name: M, arguments: A } = _, a = te?.find((p) => p.function.name === M);
131
+ if (!a) return;
132
+ const S = ("parse" in a.function ? a.function.parse : JSON.parse)(A), _e = a.function.function?.(S, g), Ae = a.renderMessageButtons?.({ args: S, execution: _e }) ?? [];
133
+ M === "provideLinks" ? n.links = S.links ?? [] : V((p) => ({
134
+ ...p,
135
+ [n.id]: [...p[n.id] ?? [], ...Ae]
136
+ })), n.toolCalls?.push({
137
+ id: "call_" + u(24),
138
+ type: "function",
139
+ function: {
140
+ name: M,
141
+ arguments: A
142
+ }
143
+ }), l((p) => {
144
+ const R = [...p], xe = R.findIndex((Le) => Le.id === n.id);
145
+ return R[xe] = { ...n }, R;
146
+ });
147
+ }), g.on("error", Y), g.finalChatCompletion().then(() => {
148
+ r.current = [...r.current, n], v.current = null, h(!1), y(!1), b(), $(
152
149
  {
153
150
  eventName: "assistant_message_received",
154
151
  properties: {}
155
152
  },
156
153
  r.current
157
154
  );
158
- }), I.current = M.controller;
159
- } catch (v) {
160
- G(v), h(!1), y(!1);
155
+ }), v.current = g.controller;
156
+ } catch (I) {
157
+ Y(I), h(!1), y(!1);
161
158
  }
162
- }, Me = () => {
163
- I.current && (I.current.abort(), I.current = null), h(!1), y(!1), b();
164
- }, V = () => {
165
- H(null), l([]), r.current = [], ae(), j({}), w([]), se(), Q(null), T(), b(), $({
159
+ }, ke = () => {
160
+ v.current && (v.current.abort(), v.current = null), h(!1), y(!1), b();
161
+ }, Z = () => {
162
+ q(null), l([]), r.current = [], ce(), V({}), w([]), re(), G(null), z(), b(), $({
166
163
  eventName: "chat_clear_button_clicked",
167
164
  properties: {
168
- conversation: oe
165
+ conversation: U
169
166
  }
170
167
  });
171
- }, Se = (e) => {
172
- Q(e);
173
- const { initialReplyMessage: t, displayName: s } = e, n = {
174
- id: u.length.toString() + d(4),
168
+ }, be = (e) => {
169
+ G(e);
170
+ const { initialReplyMessage: t, displayName: s } = e, o = {
171
+ id: m.length.toString() + u(4),
175
172
  role: "user",
176
173
  content: s
177
174
  }, i = {
178
- id: (u.length + 1).toString() + d(4),
175
+ id: (m.length + 1).toString() + u(4),
179
176
  role: "assistant",
180
177
  content: t,
181
178
  links: []
182
179
  }, E = [{
183
- id: `system-${Date.now().toString()}-${d(4)}-${e.id}`,
180
+ id: `system-${Date.now().toString()}-${u(4)}-${e.id}`,
184
181
  role: "system",
185
182
  content: `Company has asked user to follow this guided workflow:
186
- ${Ue(
187
- e
188
- )}`
189
- }, ...q, n, i];
183
+ ${Ke(e)}`
184
+ }, ...X, o, i];
190
185
  l(E), w([]);
191
- }, { openForm: ke } = Ke(), be = Be();
192
- Ae(P.chatFunctionsRef, () => ({
186
+ }, { openForm: $e } = Je(), Ee = Te();
187
+ De(F.chatFunctionsRef, () => ({
193
188
  submitMessage: D,
194
189
  updateInputMessage(e) {
195
- _(e);
190
+ x(e);
196
191
  },
197
- clearChat: V,
192
+ clearChat: Z,
198
193
  openForm: (e) => {
199
- be?.setView("chat"), ke(e);
194
+ Ee?.setView("chat"), $e(e);
200
195
  },
201
196
  focusInput: () => {
202
- J.current?.focus();
197
+ Q.current?.focus();
203
198
  }
204
199
  }));
205
- const $e = Te("(max-width: 768px)");
200
+ const Ne = ze("(max-width: 768px)");
206
201
  return {
207
- messages: u,
202
+ messages: m,
208
203
  input: f,
209
- isLoading: z,
210
- isStreaming: de,
211
- isLoadingConversation: ye,
212
- error: pe,
213
- isSubmitDisabled: x,
214
- handleInputChange: ve,
215
- handleInputKeyDown: Ie,
204
+ isLoading: j,
205
+ isStreaming: fe,
206
+ isLoadingConversation: we,
207
+ error: he,
208
+ isSubmitDisabled: B,
209
+ handleInputChange: Se,
210
+ handleInputKeyDown: Me,
216
211
  handleSubmit: D,
217
- stop: Me,
218
- clear: V,
219
- handleWorkflow: Se,
220
- selectedWorkflow: A,
212
+ stop: ke,
213
+ clear: Z,
214
+ handleWorkflow: be,
215
+ selectedWorkflow: L,
221
216
  messageAttachments: C,
222
217
  setMessageAttachments: w,
223
- addAttachment: fe,
224
- messageToolCalls: he,
225
- isEmpty: u.length === 0,
226
- inputRef: J,
227
- isMobile: $e
218
+ addAttachment: ye,
219
+ messageButtons: Ce,
220
+ isEmpty: m.length === 0,
221
+ inputRef: Q,
222
+ isMobile: Ne
228
223
  };
229
224
  };
230
225
  export {
231
- at as useInkeepChat
226
+ mt as useInkeepChat
232
227
  };