@inkeep/agents-ui 0.17.7 → 0.17.8

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 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),f=require("react"),w=require("react-markdown"),M=require("rehype-raw"),y=require("remark-gfm"),g=require("remark-supersub"),b=require("../../providers/markdown-provider.cjs"),S=require("../codeblock/index.cjs"),t=require("./components.cjs"),q=require("./rehype-inline-code-property.cjs");const C=({children:c,componentStyles:h,shouldOpenLinksInNewTab:d,onLinkClick:l,onCodeCopy:m,artifacts:x,...j})=>{if(!c)return null;const k={h1:({children:r})=>e.jsx(t.MarkdownH1,{children:r}),h2:({children:r})=>e.jsx(t.MarkdownH2,{children:r}),p:({children:r})=>e.jsx(t.MarkdownP,{children:r}),li:({children:r})=>e.jsx(t.MarkdownLi,{children:r}),ul:({children:r})=>e.jsx(t.MarkdownUl,{children:r}),hr:()=>e.jsx(t.MarkdownHr,{}),input:({type:r,checked:o,disabled:n,readOnly:s,required:a,value:i})=>e.jsx(t.MarkdownInput,{type:r,checked:o,disabled:n,readOnly:s,required:a,value:i}),ol:({children:r,node:o})=>{const n=o?.properties?.start,s=typeof n=="number"?n:void 0;return e.jsx(t.MarkdownOl,{style:{"--start":n?.toString()??"0"},start:s,children:r})},a:({children:r,href:o})=>{const n=f.Children.toArray(r),s=n[0],a=typeof s=="string"&&/^\(\d+\)$/.test(s)&&n.length===1,i=a?s.match(/\d+/):r,u=e.jsx(t.MarkdownLink,{isExternal:d,href:o,onClick:()=>{l?.(o,i?.toString())},children:i});return a?e.jsx(t.MarkdownSourceLink,{children:u}):u},img:({src:r,alt:o})=>e.jsx(t.MarkdownImg,{src:r,alt:o}),table:({children:r})=>e.jsx(t.MarkdownTable,{children:r}),th:({children:r,isHeader:o})=>o?e.jsx(t.MarkdownTh,{children:r}):e.jsx(t.MarkdownTd,{children:r}),pre:({children:r})=>e.jsx("pre",{children:r}),code:({children:r,inline:o,className:n})=>o?e.jsx(t.MarkdownCode,{children:r}):e.jsx(S.CodeBlock,{className:n,onCopy:m,children:r}),sub:({children:r})=>typeof r=="string"&&(r.startsWith(" ")||r.endsWith(" "))?e.jsxs(e.Fragment,{children:["~",r,"~"]}):e.jsx("sub",{children:r}),sup:({children:r})=>{if(r&&typeof r=="string"){const o=x?.find(n=>(n.data?.artifactSummary?.title||n.data?.name)===r);if(o){const n=o.data,s=n?.artifactSummary?.url,a=n?.artifactSummary?.title;if(!s)return null;const i=a||n?.name||r;return e.jsx(t.MarkdownSup,{children:e.jsx(t.MarkdownLink,{href:s,isExternal:d,onClick:()=>l?.(s,i),children:e.jsx("span",{children:i})})})}}return e.jsx("sup",{children:r})}},p=e.jsx(w,{remarkPlugins:[[y,{singleTilde:!1}],g],rehypePlugins:[M,q.rehypeInlineCodeProperty],components:k,disallowedElements:P,children:c.toString(),...j});return e.jsx(b.ChatMarkdownProvider,{componentStyles:h,children:p})},P=["script","iframe","frame","embed","meta","base","form","style","object"];exports.Markdown=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),f=require("react-markdown"),y=require("rehype-raw"),g=require("remark-gfm"),b=require("remark-supersub"),S=require("../../providers/markdown-provider.cjs"),q=require("../codeblock/index.cjs"),t=require("./components.cjs"),P=require("./rehype-inline-code-property.cjs");const C=[[g,{singleTilde:!1}],b],v=[y,P.rehypeInlineCodeProperty],j=l.memo(function({children:u,componentStyles:k,shouldOpenLinksInNewTab:c,onLinkClick:d,onCodeCopy:h,artifacts:m,...p}){const M=l.useMemo(()=>({h1:({children:r})=>e.jsx(t.MarkdownH1,{children:r}),h2:({children:r})=>e.jsx(t.MarkdownH2,{children:r}),p:({children:r})=>e.jsx(t.MarkdownP,{children:r}),li:({children:r})=>e.jsx(t.MarkdownLi,{children:r}),ul:({children:r})=>e.jsx(t.MarkdownUl,{children:r}),hr:()=>e.jsx(t.MarkdownHr,{}),input:({type:r,checked:o,disabled:n,readOnly:s,required:a,value:i})=>e.jsx(t.MarkdownInput,{type:r,checked:o,disabled:n,readOnly:s,required:a,value:i}),ol:({children:r,node:o})=>{const n=o?.properties?.start,s=typeof n=="number"?n:void 0;return e.jsx(t.MarkdownOl,{style:{"--start":n?.toString()??"0"},start:s,children:r})},a:({children:r,href:o})=>{const n=l.Children.toArray(r),s=n[0],a=typeof s=="string"&&/^\(\d+\)$/.test(s)&&n.length===1,i=a?s.match(/\d+/):r,x=e.jsx(t.MarkdownLink,{isExternal:c,href:o,onClick:()=>{d?.(o,i?.toString())},children:i});return a?e.jsx(t.MarkdownSourceLink,{children:x}):x},img:({src:r,alt:o})=>e.jsx(t.MarkdownImg,{src:r,alt:o}),table:({children:r})=>e.jsx(t.MarkdownTable,{children:r}),th:({children:r,isHeader:o})=>o?e.jsx(t.MarkdownTh,{children:r}):e.jsx(t.MarkdownTd,{children:r}),pre:({children:r})=>e.jsx("pre",{children:r}),code:({children:r,inline:o,className:n})=>o?e.jsx(t.MarkdownCode,{children:r}):e.jsx(q.CodeBlock,{className:n,onCopy:h,children:r}),sub:({children:r})=>typeof r=="string"&&(r.startsWith(" ")||r.endsWith(" "))?e.jsxs(e.Fragment,{children:["~",r,"~"]}):e.jsx("sub",{children:r}),sup:({children:r})=>{if(r&&typeof r=="string"){const o=m?.find(n=>(n.data?.artifactSummary?.title||n.data?.name)===r);if(o){const n=o.data,s=n?.artifactSummary?.url,a=n?.artifactSummary?.title;if(!s)return null;const i=a||n?.name||r;return e.jsx(t.MarkdownSup,{children:e.jsx(t.MarkdownLink,{href:s,isExternal:c,onClick:()=>d?.(s,i),children:e.jsx("span",{children:i})})})}}return e.jsx("sup",{children:r})}}),[c,d,h,m]);if(!u)return null;const w=e.jsx(f,{remarkPlugins:C,rehypePlugins:v,components:M,disallowedElements:R,children:u.toString(),...p});return e.jsx(S.ChatMarkdownProvider,{componentStyles:k,children:w})});j.displayName="Markdown";const R=["script","iframe","frame","embed","meta","base","form","style","object"];exports.Markdown=j;
@@ -1,4 +1,4 @@
1
- import { ComponentPropsWithRef } from 'react';
1
+ import { default as React } from 'react';
2
2
  import { CodeProps } from '../codeblock';
3
3
  import { MarkdownComponentID } from '../../utils/component-ids';
4
4
  import { ArtifactPart } from '../../../types/index.ts';
@@ -14,4 +14,16 @@ export interface MarkdownProps {
14
14
  onLinkClick?: (href: string | undefined, label: string | undefined) => void;
15
15
  artifacts?: ArtifactPart[];
16
16
  }
17
- export declare const Markdown: ({ children, componentStyles, shouldOpenLinksInNewTab, onLinkClick, onCodeCopy, artifacts, ...props }: ComponentPropsWithRef<"div"> & MarkdownProps) => import("react/jsx-runtime").JSX.Element | null;
17
+ /**
18
+ * react-markdown does no memoization of its own: it builds a fresh unified
19
+ * processor and runs a full parse + rehype pass in its render body on every
20
+ * render (rehype-raw in particular re-serializes and re-parses the tree). In a
21
+ * streaming chat that means every already-complete message re-parses its whole
22
+ * body on every token, so cost grows with conversation length.
23
+ *
24
+ * `memo` is what prevents that: messages that are not currently streaming pass
25
+ * an unchanged `text` and memoized callbacks, so they bail out before any
26
+ * parsing happens. Keep the props passed here referentially stable at the call
27
+ * site or the memo is defeated and the parse comes back.
28
+ */
29
+ export declare const Markdown: React.NamedExoticComponent<React.ClassAttributes<HTMLDivElement> & React.HTMLAttributes<HTMLDivElement> & MarkdownProps>;
@@ -1,113 +1,119 @@
1
- import { jsx as t, jsxs as M, Fragment as y } from "react/jsx-runtime";
2
- import g from "react";
3
- import b from "react-markdown";
4
- import S from "rehype-raw";
5
- import C from "remark-gfm";
6
- import x from "remark-supersub";
7
- import { ChatMarkdownProvider as P } from "../../providers/markdown-provider.js";
8
- import { CodeBlock as j } from "../codeblock/index.js";
9
- import { MarkdownSup as E, MarkdownLink as m, MarkdownCode as H, MarkdownTh as R, MarkdownTd as T, MarkdownTable as v, MarkdownImg as A, MarkdownSourceLink as I, MarkdownOl as W, MarkdownInput as _, MarkdownHr as B, MarkdownUl as D, MarkdownLi as F, MarkdownP as G, MarkdownH2 as L, MarkdownH1 as U } from "./components.js";
10
- import { rehypeInlineCodeProperty as V } from "./rehype-inline-code-property.js";
11
- const rr = ({
12
- children: d,
13
- componentStyles: h,
14
- shouldOpenLinksInNewTab: l,
1
+ import { jsx as t, jsxs as w, Fragment as y } from "react/jsx-runtime";
2
+ import g, { memo as b, useMemo as S } from "react";
3
+ import x from "react-markdown";
4
+ import C from "rehype-raw";
5
+ import P from "remark-gfm";
6
+ import j from "remark-supersub";
7
+ import { ChatMarkdownProvider as E } from "../../providers/markdown-provider.js";
8
+ import { CodeBlock as H } from "../codeblock/index.js";
9
+ import { MarkdownSup as R, MarkdownLink as h, MarkdownCode as v, MarkdownTh as A, MarkdownTd as T, MarkdownTable as W, MarkdownImg as _, MarkdownSourceLink as B, MarkdownOl as D, MarkdownInput as F, MarkdownHr as G, MarkdownUl as I, MarkdownLi as U, MarkdownP as V, MarkdownH2 as $, MarkdownH1 as q } from "./components.js";
10
+ import { rehypeInlineCodeProperty as z } from "./rehype-inline-code-property.js";
11
+ const J = [[P, { singleTilde: !1 }], j], K = [C, z], Q = b(function({
12
+ children: l,
13
+ componentStyles: f,
14
+ shouldOpenLinksInNewTab: d,
15
15
  onLinkClick: c,
16
- onCodeCopy: u,
17
- artifacts: f,
16
+ onCodeCopy: s,
17
+ artifacts: m,
18
18
  ...p
19
- }) => {
20
- if (!d) return null;
21
- const k = {
22
- h1: ({ children: r }) => /* @__PURE__ */ t(U, { children: r }),
23
- h2: ({ children: r }) => /* @__PURE__ */ t(L, { children: r }),
24
- p: ({ children: r }) => /* @__PURE__ */ t(G, { children: r }),
25
- li: ({ children: r }) => /* @__PURE__ */ t(F, { children: r }),
26
- ul: ({ children: r }) => /* @__PURE__ */ t(D, { children: r }),
27
- hr: () => /* @__PURE__ */ t(B, {}),
28
- input: ({ type: r, checked: e, disabled: n, readOnly: o, required: a, value: i }) => /* @__PURE__ */ t(
29
- _,
30
- {
31
- type: r,
32
- checked: e,
33
- disabled: n,
34
- readOnly: o,
35
- required: a,
36
- value: i
37
- }
38
- ),
39
- ol: ({ children: r, node: e }) => {
40
- const n = e?.properties?.start, o = typeof n == "number" ? n : void 0;
41
- return /* @__PURE__ */ t(
42
- W,
43
- {
44
- style: {
45
- "--start": n?.toString() ?? "0"
46
- },
47
- start: o,
48
- children: r
49
- }
50
- );
51
- },
52
- a: ({ children: r, href: e }) => {
53
- const n = g.Children.toArray(r), o = n[0], a = typeof o == "string" && /^\(\d+\)$/.test(o) && n.length === 1, i = a ? o.match(/\d+/) : r, s = /* @__PURE__ */ t(
54
- m,
19
+ }) {
20
+ const k = S(
21
+ () => ({
22
+ h1: ({ children: r }) => /* @__PURE__ */ t(q, { children: r }),
23
+ h2: ({ children: r }) => /* @__PURE__ */ t($, { children: r }),
24
+ p: ({ children: r }) => /* @__PURE__ */ t(V, { children: r }),
25
+ li: ({ children: r }) => /* @__PURE__ */ t(U, { children: r }),
26
+ ul: ({ children: r }) => /* @__PURE__ */ t(I, { children: r }),
27
+ hr: () => /* @__PURE__ */ t(G, {}),
28
+ input: ({ type: r, checked: e, disabled: n, readOnly: o, required: a, value: i }) => /* @__PURE__ */ t(
29
+ F,
55
30
  {
56
- isExternal: l,
57
- href: e,
58
- onClick: () => {
59
- c?.(e, i?.toString());
60
- },
61
- children: i
31
+ type: r,
32
+ checked: e,
33
+ disabled: n,
34
+ readOnly: o,
35
+ required: a,
36
+ value: i
62
37
  }
63
- );
64
- return a ? /* @__PURE__ */ t(I, { children: s }) : s;
65
- },
66
- img: ({ src: r, alt: e }) => /* @__PURE__ */ t(A, { src: r, alt: e }),
67
- table: ({ children: r }) => /* @__PURE__ */ t(v, { children: r }),
68
- th: ({ children: r, isHeader: e }) => e ? /* @__PURE__ */ t(R, { children: r }) : /* @__PURE__ */ t(T, { children: r }),
69
- pre: ({ children: r }) => /* @__PURE__ */ t("pre", { children: r }),
70
- code: ({ children: r, inline: e, className: n }) => e ? /* @__PURE__ */ t(H, { children: r }) : /* @__PURE__ */ t(j, { className: n, onCopy: u, children: r }),
71
- sub: ({ children: r }) => typeof r == "string" && (r.startsWith(" ") || r.endsWith(" ")) ? /* @__PURE__ */ M(y, { children: [
72
- "~",
73
- r,
74
- "~"
75
- ] }) : /* @__PURE__ */ t("sub", { children: r }),
76
- sup: ({ children: r }) => {
77
- if (r && typeof r == "string") {
78
- const e = f?.find(
79
- (n) => (n.data?.artifactSummary?.title || n.data?.name) === r
38
+ ),
39
+ ol: ({ children: r, node: e }) => {
40
+ const n = e?.properties?.start, o = typeof n == "number" ? n : void 0;
41
+ return /* @__PURE__ */ t(
42
+ D,
43
+ {
44
+ style: {
45
+ "--start": n?.toString() ?? "0"
46
+ },
47
+ start: o,
48
+ children: r
49
+ }
80
50
  );
81
- if (e) {
82
- const n = e.data, o = n?.artifactSummary?.url, a = n?.artifactSummary?.title;
83
- if (!o) return null;
84
- const i = a || n?.name || r;
85
- return /* @__PURE__ */ t(E, { children: /* @__PURE__ */ t(
86
- m,
87
- {
88
- href: o,
89
- isExternal: l,
90
- onClick: () => c?.(o, i),
91
- children: /* @__PURE__ */ t("span", { children: i })
92
- }
93
- ) });
51
+ },
52
+ a: ({ children: r, href: e }) => {
53
+ const n = g.Children.toArray(r), o = n[0], a = typeof o == "string" && /^\(\d+\)$/.test(o) && n.length === 1, i = a ? o.match(/\d+/) : r, u = /* @__PURE__ */ t(
54
+ h,
55
+ {
56
+ isExternal: d,
57
+ href: e,
58
+ onClick: () => {
59
+ c?.(e, i?.toString());
60
+ },
61
+ children: i
62
+ }
63
+ );
64
+ return a ? /* @__PURE__ */ t(B, { children: u }) : u;
65
+ },
66
+ img: ({ src: r, alt: e }) => /* @__PURE__ */ t(_, { src: r, alt: e }),
67
+ table: ({ children: r }) => /* @__PURE__ */ t(W, { children: r }),
68
+ th: ({ children: r, isHeader: e }) => e ? /* @__PURE__ */ t(A, { children: r }) : /* @__PURE__ */ t(T, { children: r }),
69
+ pre: ({ children: r }) => /* @__PURE__ */ t("pre", { children: r }),
70
+ code: ({ children: r, inline: e, className: n }) => e ? /* @__PURE__ */ t(v, { children: r }) : /* @__PURE__ */ t(H, { className: n, onCopy: s, children: r }),
71
+ sub: ({ children: r }) => typeof r == "string" && (r.startsWith(" ") || r.endsWith(" ")) ? /* @__PURE__ */ w(y, { children: [
72
+ "~",
73
+ r,
74
+ "~"
75
+ ] }) : /* @__PURE__ */ t("sub", { children: r }),
76
+ sup: ({ children: r }) => {
77
+ if (r && typeof r == "string") {
78
+ const e = m?.find(
79
+ (n) => (n.data?.artifactSummary?.title || n.data?.name) === r
80
+ );
81
+ if (e) {
82
+ const n = e.data, o = n?.artifactSummary?.url, a = n?.artifactSummary?.title;
83
+ if (!o) return null;
84
+ const i = a || n?.name || r;
85
+ return /* @__PURE__ */ t(R, { children: /* @__PURE__ */ t(
86
+ h,
87
+ {
88
+ href: o,
89
+ isExternal: d,
90
+ onClick: () => c?.(o, i),
91
+ children: /* @__PURE__ */ t("span", { children: i })
92
+ }
93
+ ) });
94
+ }
94
95
  }
96
+ return /* @__PURE__ */ t("sup", { children: r });
95
97
  }
96
- return /* @__PURE__ */ t("sup", { children: r });
97
- }
98
- }, w = /* @__PURE__ */ t(
99
- b,
98
+ }),
99
+ [d, c, s, m]
100
+ );
101
+ if (!l) return null;
102
+ const M = /* @__PURE__ */ t(
103
+ x,
100
104
  {
101
- remarkPlugins: [[C, { singleTilde: !1 }], x],
102
- rehypePlugins: [S, V],
105
+ remarkPlugins: J,
106
+ rehypePlugins: K,
103
107
  components: k,
104
- disallowedElements: $,
105
- children: d.toString(),
108
+ disallowedElements: X,
109
+ children: l.toString(),
106
110
  ...p
107
111
  }
108
112
  );
109
- return /* @__PURE__ */ t(P, { componentStyles: h, children: w });
110
- }, $ = [
113
+ return /* @__PURE__ */ t(E, { componentStyles: f, children: M });
114
+ });
115
+ Q.displayName = "Markdown";
116
+ const X = [
111
117
  "script",
112
118
  "iframe",
113
119
  "frame",
@@ -119,5 +125,5 @@ const rr = ({
119
125
  "object"
120
126
  ];
121
127
  export {
122
- rr as Markdown
128
+ Q as Markdown
123
129
  };
@@ -1,2 +1,2 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("@ai-sdk/react"),Ze=require("./file-upload-input.cjs"),et=require("ai"),t=require("react"),tt=require("../../providers/config-provider.cjs"),st=require("../../providers/chat-auth-provider.cjs"),rt=require("../../hooks/use-media-query.cjs"),nt=require("../../hooks/use-conversation-loader.cjs"),at=require("../../hooks/use-initial-conversation.cjs"),O=require("../../utils/generate-uid.cjs"),ot=require("../../providers/base-events-provider.cjs"),it=require("../../providers/chat-form-provider.cjs"),ct=require("../../providers/widget-provider.cjs"),ut=require("@radix-ui/react-use-controllable-state"),lt=require("../../hooks/use-streaming-events.cjs"),dt=require("../../hooks/use-input-notification.cjs"),s=require("./chat-error-helpers.cjs"),ft=()=>{const{baseSettings:se,aiChatSettings:R}=tt.useInkeepConfig(),[u="",v]=ut.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),{logEvent:m}=ot.useBaseEvents(),{setConversationId:we,emitToParent:k}=lt.useStreamingEvents(),re=t.useRef(u);t.useEffect(()=>{const e=re.current;re.current=u,e!==u&&m({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,m]);const[_,C]=t.useState(""),Oe=e=>C(e.target.value),{shouldBypassCaptcha:ke,filters:ne,userProperties:B,analyticsProperties:D}=se,{authToken:ae,isAuthenticated:S,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:F,invalidateCaptcha:f,effectiveAuthToken:le,applicableRefreshSession:Fe}=st.useChatAuth(),{onInputMessageChange:Le,filters:de,baseUrl:fe,agentUrl:Ne,context:pe,headers:ge,appId:L,apiKey:U,files:T}=R,he=t.useRef(F);he.current=F;const me=Ne||`${fe}/run/api/chat`,{loadConversation:Ee}=nt.useConversationLoader({baseUrl:fe,appId:L,authToken:le,getCaptchaHeader:F,invalidateCaptcha:f,refreshSession:Fe}),[Pe,Re]=t.useState(!1),G=t.useRef(null);G.current=ce;const $=t.useRef(null);$.current=ae;const K=t.useRef(void 0);K.current=B&&Object.keys(B).length>0?B:void 0;const H=t.useRef(void 0);H.current=D&&Object.keys(D).length>0?D:void 0;const y=t.useRef(0),N=t.useRef(null),W=t.useRef(null),E=t.useRef(void 0),xe=T?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
- `)??"";t.useEffect(()=>{E.current=T?.length?T:void 0},[xe]);const ve=t.useRef(ge);ve.current=ge;const z=t.useRef(void 0);z.current=ne||de?JSON.stringify({...ne,...de}):void 0;const qe=e=>{if(s.isNetworkError(e))return N.current?.files?.length?s.NETWORK_ERROR_WITH_FILES_MESSAGE:s.NETWORK_ERROR_MESSAGE;switch(s.resolveHttpStatusCode(e)){case 400:try{const r=JSON.parse(e.message??"");return r.detail??r.error?.message??s.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||s.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":s.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 413:return s.PAYLOAD_TOO_LARGE_MESSAGE;case 429:return s.RATE_LIMIT_MESSAGE;default:return s.DEFAULT_ERROR_MESSAGE}},[A,V]=t.useState([]),Be=t.useMemo(()=>new et.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??G.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...L?{"x-inkeep-app-id":L}:{},...e?{Authorization:`Bearer ${e}`}:{},...z.current?{"inkeep-filters":z.current}:{},...ve.current}},prepareSendMessagesRequest:async e=>{const l=await he.current(),r=e.messages[e.messages.length-1];return r||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:r?[r]:[],trigger:e.trigger,messageId:e.messageId,...K.current?{userProperties:K.current}:{},...H.current?{properties:H.current}:{}},headers:{...e.headers,...l}}},body:{requestContext:pe}}),[me,pe,L,U]),{messages:M,sendMessage:Y,addToolApprovalResponse:j,status:Se,setMessages:h,stop:P,error:x}=Xe.useChat({transport:Be,onData(e){k(e.type,e.data)},async onFinish({message:e}){k("completion",{conversationId:u}),await m({eventName:"assistant_message_received",properties:{conversationId:u,messageId:e.id}}),m({eventName:"assistant_answer_displayed",properties:{conversationId:u,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const l=ke||U?null:s.resolveStreamingAuthError(e);if(l!==null&&y.current<1){y.current++;const i=W.current,a=N.current;(async()=>{if(l==="session"&&oe){const o=await ie();if(!o)throw new Error("Auth token refresh failed");$.current=o}else if(l==="session"){const o=await ue();o&&(G.current=o)}else f();if(i){j(i);return}a&&(h(o=>{let c=[...o];return c.at(-1)?.role==="assistant"&&(c=c.slice(0,-1)),c.at(-1)?.role==="user"&&(c=c.slice(0,-1)),c}),Y({id:a.messageId,parts:[...a.content.trim()?[{type:"text",text:a.content}]:[],...a.files??[]]},{body:a.body}))})().catch(()=>{y.current=0,f(),h(o=>{const c=[...o],g=c[c.length-1];if(!g)return c;const d=s.DEFAULT_ERROR_MESSAGE;return g.role==="user"?c.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):g.parts=[{type:"text",text:d}],c})});return}y.current=0,l!==null&&f();const r=s.isRecoverableError(e)||s.isNetworkError(e),n=qe(e);if(m({eventName:"chat_error",properties:{conversationId:u,messageId:M.at(-1)?.id,error:e.message}}),r){const i=n===s.PAYLOAD_TOO_LARGE_MESSAGE?"Message too large":n===s.RATE_LIMIT_MESSAGE?"Rate limit reached":n===s.NETWORK_ERROR_MESSAGE||n===s.NETWORK_ERROR_WITH_FILES_MESSAGE?"Connection error":"Request failed";q({title:i,message:n},s.RECOVERABLE_NOTIFICATION_DURATION_MS),h(p=>{let o=[...p];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o});const a=N.current?.content;a&&C(a),Z.current=e;return}h(i=>{const a=[...i],p=a[a.length-1];return p&&(p.role==="user"?a.push({id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:n}]}):p.parts=[{type:"text",text:n}]),a})}}),ye=t.useRef(S);t.useEffect(()=>{const e=ye.current;ye.current=S,e!==S&&(P(),b(null),h([]),v(""),C(""),V([]),f())},[S,P,h,v,f]);const Ae=Se==="submitted",Q=Se==="streaming",De=t.useMemo(()=>{const e=i=>{if(!i||typeof i!="object")return!1;const a=i;return typeof a.type=="string"&&a.type.startsWith("tool-")},r=[...M??[]].reverse().find(i=>i.role==="assistant");if(!r)return!1;const n=r.parts?.at(-1);return!(!e(n)||n.state!=="output-available"||!n.approval?.id||Q)},[M,Q]),[Ue,J]=t.useState(!1),Ie=Q||De&&!Ue,_e=Ae||Ie,Ge=M.length===0,X=!_.trim()&&A.length===0||_e,$e=rt.useMediaQuery("(max-width: 768px)"),[Ke,b]=t.useState(null),Z=t.useRef(null);t.useEffect(()=>{if(x){if(Z.current===x){Z.current=null;return}b(x)}},[x]);const He=()=>b(null),{inputNotification:We,showInputNotification:q,clearInputNotification:ze}=dt.useInputNotification(),Ce=t.useRef(null);t.useEffect(()=>{Le?.(_)},[_]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=_)=>{if(X&&(!e||e.trim().length===0)&&A.length===0||!e.trim()&&!A.length&&!E.current?.length)return;if(s.estimateRequestBodyBytes({text:e,rawFileBytes:A.reduce((g,d)=>g+d.size,0),encodedPartsBytes:(E.current??[]).reduce((g,d)=>g+d.url.length,0)})>s.MAX_REQUEST_BODY_BYTES){q({title:"Message too large",message:s.PAYLOAD_TOO_LARGE_MESSAGE},s.RECOVERABLE_NOTIFICATION_DURATION_MS);return}const r=A;V([]),C(""),y.current=0,W.current=null,J(!1);let n=u;n||(n=`conv_${O.generateUid(16)}`,v(n));const i=O.generateUid(21);we(n),await m({eventName:"user_message_submitted",properties:{conversationId:n,messageId:i}});const a=E.current;E.current=void 0;let p=[];if(r.length>0)try{p=await Promise.all(r.map(g=>{const d=Ze.normalizeFileType(g);return new Promise((Je,be)=>{const w=new FileReader;w.onload=()=>{if(typeof w.result!="string"){be(new Error(`Failed to read file "${d.name}"`));return}Je({type:"file",url:w.result,mediaType:d.type,filename:d.name})},w.onerror=()=>be(new Error(`Failed to read file "${d.name}"`)),w.readAsDataURL(d)})}))}catch{q({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const o=p.length||a?.length?[...p,...a??[]]:void 0,c=[...e.trim()?[{type:"text",text:e}]:[],...o??[]];N.current={content:e,messageId:i,body:{conversationId:n},files:o},Y({id:i,parts:c},{body:{conversationId:n}})},Ye=t.useCallback(e=>{y.current=0,W.current=e,J(!1),j(e)},[j]),te=t.useCallback(()=>{J(!0),P().then(()=>{k("aborted",{conversationId:u})})},[P,u,k]),Te=()=>{He(),h([]),v(""),f(),E.current=T?.length?T:void 0,m({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},I=t.useCallback((e,l)=>{b(null),h(l),v(e),f(),E.current=void 0},[h,v,f]),Me=t.useCallback(async(e,l)=>{te(),I(e,[]),Re(!0);try{const r=await Ee(e,l);if(r===null)return!1;const i=r[r.length-1]?.role==="user"?[...r,{id:O.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:r;return I(e,i),!0}finally{l?.aborted||Re(!1)}},[I,Ee,te]);at.useInitialConversation({conversationId:R.conversationId,fetchedConversation:R.fetchedConversation,effectiveAuthToken:le,restoreSession:I,loadAndRestoreSession:Me,onLoadFailed:()=>I("",[])});const{openForm:je}=it.useChatForm(),Qe=ct.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){C(e)},clearChat:Te,openForm:e=>{Qe?.setView("chat"),je(e,void 0)},focusInput:()=>{Ce.current?.focus()}})),{messages:M,sendMessage:Y,addToolApprovalResponse:Ye,isLoading:Ae,isStreaming:Ie,isBusy:_e,error:Ke,setError:b,isSubmitDisabled:X,input:_,handleInputChange:Oe,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:Te,inputRef:Ce,isMobile:$e,files:A,setFiles:V,isNewChat:Ge,conversationId:u,restoreSession:I,loadAndRestoreSession:Me,isSessionLoading:Pe,authToken:S?ae:ce,refreshSession:S?ie:ue,getCaptchaHeader:F,invalidateCaptcha:f,inputNotification:We,showInputNotification:q,clearInputNotification:ze}};exports.useInkeepChat=ft;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("@ai-sdk/react"),Ze=require("./file-upload-input.cjs"),et=require("ai"),t=require("react"),tt=require("../../providers/config-provider.cjs"),st=require("../../providers/chat-auth-provider.cjs"),rt=require("../../hooks/use-media-query.cjs"),nt=require("../../hooks/use-conversation-loader.cjs"),at=require("../../hooks/use-initial-conversation.cjs"),w=require("../../utils/generate-uid.cjs"),ot=require("../../providers/base-events-provider.cjs"),it=require("../../providers/chat-form-provider.cjs"),ct=require("../../providers/widget-provider.cjs"),ut=require("@radix-ui/react-use-controllable-state"),lt=require("../../hooks/use-streaming-events.cjs"),dt=require("../../hooks/use-input-notification.cjs"),s=require("./chat-error-helpers.cjs"),ft=50,pt=()=>{const{baseSettings:se,aiChatSettings:R}=tt.useInkeepConfig(),[u="",v]=ut.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),{logEvent:m}=ot.useBaseEvents(),{setConversationId:Oe,emitToParent:k}=lt.useStreamingEvents(),re=t.useRef(u);t.useEffect(()=>{const e=re.current;re.current=u,e!==u&&m({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,m]);const[I,C]=t.useState(""),we=e=>C(e.target.value),{shouldBypassCaptcha:ke,filters:ne,userProperties:B,analyticsProperties:D}=se,{authToken:ae,isAuthenticated:S,isAuthConfigured:oe,refreshAuthToken:ie,sessionToken:ce,refreshSession:ue,getCaptchaHeader:F,invalidateCaptcha:f,effectiveAuthToken:le,applicableRefreshSession:Fe}=st.useChatAuth(),{onInputMessageChange:Le,filters:de,baseUrl:fe,agentUrl:Ne,context:pe,headers:ge,appId:L,apiKey:U,files:T}=R,he=t.useRef(F);he.current=F;const me=Ne||`${fe}/run/api/chat`,{loadConversation:Ee}=nt.useConversationLoader({baseUrl:fe,appId:L,authToken:le,getCaptchaHeader:F,invalidateCaptcha:f,refreshSession:Fe}),[Pe,Re]=t.useState(!1),G=t.useRef(null);G.current=ce;const $=t.useRef(null);$.current=ae;const K=t.useRef(void 0);K.current=B&&Object.keys(B).length>0?B:void 0;const H=t.useRef(void 0);H.current=D&&Object.keys(D).length>0?D:void 0;const y=t.useRef(0),N=t.useRef(null),W=t.useRef(null),E=t.useRef(void 0),xe=T?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
+ `)??"";t.useEffect(()=>{E.current=T?.length?T:void 0},[xe]);const ve=t.useRef(ge);ve.current=ge;const z=t.useRef(void 0);z.current=ne||de?JSON.stringify({...ne,...de}):void 0;const qe=e=>{if(s.isNetworkError(e))return N.current?.files?.length?s.NETWORK_ERROR_WITH_FILES_MESSAGE:s.NETWORK_ERROR_MESSAGE;switch(s.resolveHttpStatusCode(e)){case 400:try{const n=JSON.parse(e.message??"");return n.detail??n.error?.message??s.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||s.RECOVERABLE_FALLBACK_MESSAGE}case 401:return oe?"Authentication failed. Please try again.":s.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${se.organizationDisplayName??"Administrator"}`;case 413:return s.PAYLOAD_TOO_LARGE_MESSAGE;case 429:return s.RATE_LIMIT_MESSAGE;default:return s.DEFAULT_ERROR_MESSAGE}},[A,V]=t.useState([]),Be=t.useMemo(()=>new et.DefaultChatTransport({api:me,headers:()=>{const e=U??$.current??G.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...L?{"x-inkeep-app-id":L}:{},...e?{Authorization:`Bearer ${e}`}:{},...z.current?{"inkeep-filters":z.current}:{},...ve.current}},prepareSendMessagesRequest:async e=>{const l=await he.current(),n=e.messages[e.messages.length-1];return n||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:n?[n]:[],trigger:e.trigger,messageId:e.messageId,...K.current?{userProperties:K.current}:{},...H.current?{properties:H.current}:{}},headers:{...e.headers,...l}}},body:{requestContext:pe}}),[me,pe,L,U]),{messages:M,sendMessage:Y,addToolApprovalResponse:j,status:Se,setMessages:h,stop:P,error:x}=Xe.useChat({transport:Be,experimental_throttle:ft,onData(e){k(e.type,e.data)},async onFinish({message:e}){k("completion",{conversationId:u}),await m({eventName:"assistant_message_received",properties:{conversationId:u,messageId:e.id}}),m({eventName:"assistant_answer_displayed",properties:{conversationId:u,messageId:e.id}})},onError(e){console.error("onError",{code:e.code,message:e.message});const l=ke||U?null:s.resolveStreamingAuthError(e);if(l!==null&&y.current<1){y.current++;const i=W.current,r=N.current;(async()=>{if(l==="session"&&oe){const o=await ie();if(!o)throw new Error("Auth token refresh failed");$.current=o}else if(l==="session"){const o=await ue();o&&(G.current=o)}else f();if(i){j(i);return}r&&(h(o=>{let c=[...o];return c.at(-1)?.role==="assistant"&&(c=c.slice(0,-1)),c.at(-1)?.role==="user"&&(c=c.slice(0,-1)),c}),Y({id:r.messageId,parts:[...r.content.trim()?[{type:"text",text:r.content}]:[],...r.files??[]]},{body:r.body}))})().catch(()=>{y.current=0,f(),h(o=>{const c=[...o],g=c[c.length-1];if(!g)return c;const d=s.DEFAULT_ERROR_MESSAGE;return g.role==="user"?c.push({id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):c[c.length-1]={...g,parts:[{type:"text",text:d}]},c})});return}y.current=0,l!==null&&f();const n=s.isRecoverableError(e)||s.isNetworkError(e),a=qe(e);if(m({eventName:"chat_error",properties:{conversationId:u,messageId:M.at(-1)?.id,error:e.message}}),n){const i=a===s.PAYLOAD_TOO_LARGE_MESSAGE?"Message too large":a===s.RATE_LIMIT_MESSAGE?"Rate limit reached":a===s.NETWORK_ERROR_MESSAGE||a===s.NETWORK_ERROR_WITH_FILES_MESSAGE?"Connection error":"Request failed";q({title:i,message:a},s.RECOVERABLE_NOTIFICATION_DURATION_MS),h(p=>{let o=[...p];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o});const r=N.current?.content;r&&C(r),Z.current=e;return}h(i=>{const r=[...i],p=r[r.length-1];return p&&(p.role==="user"?r.push({id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:a}]}):r[r.length-1]={...p,parts:[{type:"text",text:a}]}),r})}}),ye=t.useRef(S);t.useEffect(()=>{const e=ye.current;ye.current=S,e!==S&&(P(),b(null),h([]),v(""),C(""),V([]),f())},[S,P,h,v,f]);const Ae=Se==="submitted",Q=Se==="streaming",De=t.useMemo(()=>{const e=i=>{if(!i||typeof i!="object")return!1;const r=i;return typeof r.type=="string"&&r.type.startsWith("tool-")},n=[...M??[]].reverse().find(i=>i.role==="assistant");if(!n)return!1;const a=n.parts?.at(-1);return!(!e(a)||a.state!=="output-available"||!a.approval?.id||Q)},[M,Q]),[Ue,J]=t.useState(!1),_e=Q||De&&!Ue,Ie=Ae||_e,Ge=M.length===0,X=!I.trim()&&A.length===0||Ie,$e=rt.useMediaQuery("(max-width: 768px)"),[Ke,b]=t.useState(null),Z=t.useRef(null);t.useEffect(()=>{if(x){if(Z.current===x){Z.current=null;return}b(x)}},[x]);const He=()=>b(null),{inputNotification:We,showInputNotification:q,clearInputNotification:ze}=dt.useInputNotification(),Ce=t.useRef(null);t.useEffect(()=>{Le?.(I)},[I]);const Ve=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),ee())},ee=async(e=I)=>{if(X&&(!e||e.trim().length===0)&&A.length===0||!e.trim()&&!A.length&&!E.current?.length)return;if(s.estimateRequestBodyBytes({text:e,rawFileBytes:A.reduce((g,d)=>g+d.size,0),encodedPartsBytes:(E.current??[]).reduce((g,d)=>g+d.url.length,0)})>s.MAX_REQUEST_BODY_BYTES){q({title:"Message too large",message:s.PAYLOAD_TOO_LARGE_MESSAGE},s.RECOVERABLE_NOTIFICATION_DURATION_MS);return}const n=A;V([]),C(""),y.current=0,W.current=null,J(!1);let a=u;a||(a=`conv_${w.generateUid(16)}`,v(a));const i=w.generateUid(21);Oe(a),await m({eventName:"user_message_submitted",properties:{conversationId:a,messageId:i}});const r=E.current;E.current=void 0;let p=[];if(n.length>0)try{p=await Promise.all(n.map(g=>{const d=Ze.normalizeFileType(g);return new Promise((Je,be)=>{const O=new FileReader;O.onload=()=>{if(typeof O.result!="string"){be(new Error(`Failed to read file "${d.name}"`));return}Je({type:"file",url:O.result,mediaType:d.type,filename:d.name})},O.onerror=()=>be(new Error(`Failed to read file "${d.name}"`)),O.readAsDataURL(d)})}))}catch{q({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}const o=p.length||r?.length?[...p,...r??[]]:void 0,c=[...e.trim()?[{type:"text",text:e}]:[],...o??[]];N.current={content:e,messageId:i,body:{conversationId:a},files:o},Y({id:i,parts:c},{body:{conversationId:a}})},Ye=t.useCallback(e=>{y.current=0,W.current=e,J(!1),j(e)},[j]),te=t.useCallback(()=>{J(!0),P().then(()=>{k("aborted",{conversationId:u})})},[P,u,k]),Te=()=>{He(),h([]),v(""),f(),E.current=T?.length?T:void 0,m({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},_=t.useCallback((e,l)=>{b(null),h(l),v(e),f(),E.current=void 0},[h,v,f]),Me=t.useCallback(async(e,l)=>{te(),_(e,[]),Re(!0);try{const n=await Ee(e,l);if(n===null)return!1;const i=n[n.length-1]?.role==="user"?[...n,{id:w.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:n;return _(e,i),!0}finally{l?.aborted||Re(!1)}},[_,Ee,te]);at.useInitialConversation({conversationId:R.conversationId,fetchedConversation:R.fetchedConversation,effectiveAuthToken:le,restoreSession:_,loadAndRestoreSession:Me,onLoadFailed:()=>_("",[])});const{openForm:je}=it.useChatForm(),Qe=ct.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:ee,updateInputMessage(e){C(e)},clearChat:Te,openForm:e=>{Qe?.setView("chat"),je(e,void 0)},focusInput:()=>{Ce.current?.focus()}})),{messages:M,sendMessage:Y,addToolApprovalResponse:Ye,isLoading:Ae,isStreaming:_e,isBusy:Ie,error:Ke,setError:b,isSubmitDisabled:X,input:I,handleInputChange:we,handleInputKeyDown:Ve,handleSubmit:ee,stop:te,clear:Te,inputRef:Ce,isMobile:$e,files:A,setFiles:V,isNewChat:Ge,conversationId:u,restoreSession:_,loadAndRestoreSession:Me,isSessionLoading:Pe,authToken:S?ae:ce,refreshSession:S?ie:ue,getCaptchaHeader:F,invalidateCaptcha:f,inputNotification:We,showInputNotification:q,clearInputNotification:ze}};exports.useInkeepChat=pt;