@inkeep/agents-ui 0.0.0-dev-20260501021535 → 0.0.0-dev-20260501182500
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node_modules/.pnpm/botid@1.5.11_next@16.2.4_@babel_core@7.29.0_@opentelemetry_api@1.9.1_react-dom@19.3.0-c_6ac35f5bf61166da3243b6cf36e09c95/node_modules/botid/dist/client/core/index.cjs +1 -0
- package/dist/node_modules/.pnpm/botid@1.5.11_next@16.2.4_@babel_core@7.29.0_@opentelemetry_api@1.9.1_react-dom@19.3.0-c_6ac35f5bf61166da3243b6cf36e09c95/node_modules/botid/dist/client/core/index.js +160 -0
- package/dist/primitives/components/embedded-chat/chat-error-helpers.d.ts +4 -2
- package/dist/primitives/components/embedded-chat/use-inkeep-chat.cjs +2 -2
- package/dist/primitives/components/embedded-chat/use-inkeep-chat.d.ts +0 -2
- package/dist/primitives/components/embedded-chat/use-inkeep-chat.js +237 -262
- package/dist/primitives/hooks/use-anonymous-session.cjs +1 -1
- package/dist/primitives/hooks/use-anonymous-session.d.ts +1 -3
- package/dist/primitives/hooks/use-anonymous-session.js +51 -56
- package/dist/primitives/hooks/use-conversation-loader.cjs +1 -1
- package/dist/primitives/hooks/use-conversation-loader.d.ts +1 -3
- package/dist/primitives/hooks/use-conversation-loader.js +15 -20
- package/dist/primitives/hooks/use-feedback-api.cjs +1 -1
- package/dist/primitives/hooks/use-feedback-api.d.ts +1 -3
- package/dist/primitives/hooks/use-feedback-api.js +16 -22
- package/dist/primitives/hooks/use-inkeep-api-client.cjs +1 -1
- package/dist/primitives/hooks/use-inkeep-api-client.d.ts +8 -11
- package/dist/primitives/hooks/use-inkeep-api-client.js +36 -64
- package/dist/primitives/providers/botid-initializer.cjs +1 -0
- package/dist/primitives/providers/botid-initializer.d.ts +15 -0
- package/dist/primitives/providers/botid-initializer.js +64 -0
- package/dist/primitives/providers/chat-history-provider.cjs +1 -1
- package/dist/primitives/providers/chat-history-provider.js +35 -39
- package/dist/primitives/providers/feedback-provider.cjs +1 -1
- package/dist/primitives/providers/feedback-provider.js +26 -35
- package/dist/primitives/providers/root-provider.cjs +1 -1
- package/dist/primitives/providers/root-provider.js +13 -9
- package/dist/primitives/utils/default-settings.cjs +1 -1
- package/dist/primitives/utils/default-settings.d.ts +1 -0
- package/dist/primitives/utils/default-settings.js +6 -5
- package/dist/types/config/ai.d.ts +8 -0
- package/package.json +2 -2
- package/dist/primitives/components/embedded-chat/use-captcha.cjs +0 -1
- package/dist/primitives/components/embedded-chat/use-captcha.d.ts +0 -30
- package/dist/primitives/components/embedded-chat/use-captcha.js +0 -67
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function v(o){return new Promise((e,s)=>{if(document.querySelector(`script[src="${o}"]`)){e();return}let r=document.createElement("script");r.src=o,r.async=!0,r.onload=()=>e(),r.onerror=n=>{console.error("Error loading script",n),s(n)},document.head.appendChild(r)})}var L="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/a-4-a/c.js",R=class m{#e;#t;#r=0;constructor(){let{promise:e,resolve:s}=m.#i();this.#e=e,this.#t=s,this.#n(),window.addEventListener("online",this.#s),window.addEventListener("visibilitychange",this.#s)}getChallenge=async()=>(await this.#a(),await this.#e.then(e=>typeof e=="function"?e():e));#s=()=>{if(document.hidden)return;let{promise:e,resolve:s}=m.#i();this.#e=e,this.#t=s,window.V_C=[],window.V_C.push=s;let r=document.querySelector('script[src*="c.js"]');r&&r.remove(),this.#r+=1};#n=()=>{if(window.V_C){let e=window.V_C.pop();e&&this.#t(e)}else window.V_C=[],window.V_C.push=this.#t};#a=()=>{let e=new URL(L,window.location.origin);return e.searchParams.set("i",String(this.#r)),e.searchParams.set("v",String(3)),e.searchParams.set("h",window.location.host),v(e.pathname+e.search)};#o=()=>{window.V_C=void 0};static#i(){let e,s;return{promise:new Promise((r,n)=>{e=r,s=n}),resolve:e,reject:s}}},q="/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3",H=class g{#e=!1;#t;constructor(e){this.#t=e}get loaded(){return this.#e}load=async()=>{this.#e||await this.#s()};#r=()=>{if(typeof globalThis.window>"u")throw new Error("KPSDK is not available in the server");if(!window.KPSDK)throw new Error("KPSDK is not loaded");let e=this.#t.map(s=>{let r=g.#n(s.path);return{domain:r.host,path:r.pathname,method:s.method}});try{window.KPSDK.configure(e)}catch(s){console.error("Error configuring KPSDK...",s)}};#s=async()=>{let e=`${q}/p.js`,s=this;return new Promise((r,n)=>{let a=()=>{document.removeEventListener("kpsdk-load",a),this.#r()},d=()=>{document.removeEventListener("kpsdk-ready",d),s.#e=!0,r()};document.addEventListener("kpsdk-load",a,{once:!0}),document.addEventListener("kpsdk-ready",d,{once:!0}),v(e).catch(h=>{document.removeEventListener("kpsdk-load",a),document.removeEventListener("kpsdk-ready",d),n(h)})})};static#n(e){let s;try{s=new URL(e)}catch{s=new URL(e,location.origin)}return s}},y=o=>{let e=o.replace(/[.?+^$[\]\\(){}|-]/g,"\\$&").split("*").join(".*");return new RegExp(`^${e}$`)},b=({path:o,pattern:e})=>o.search(e)!==-1;function x(o,e,s){let r=window.fetch;window.fetch=async(n,a)=>{let d=new URL(n instanceof Request?n.url:n,location.href),h=d.origin===location.origin,u=a?.method??(n instanceof Request?n.method:"GET"),l=s.find(i=>{let w=b({path:d.pathname,pattern:y(i.path)}),f=i.method.toLowerCase()===u.toLowerCase()||i.method==="*";return w&&f});if(l==null||!h)return r(n,a);let p=await o.getChallenge(),c=new Headers(a?.headers||(n instanceof Request?n.headers:void 0));c.set("x-is-human",JSON.stringify(p)),c.set("x-path",d.pathname),c.set("x-method",u);let t={...a,headers:c};return e.loaded||p.b!==0?r(n,t):p.d===1||l?.advancedOptions?.checkLevel==="deepAnalysis"?(await e.load(),window.fetch(n,t)):r(n,t)}}async function E(o,e,s){let r=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(a,d,h,u,l){return this._requestUrl=d.toString(),this._requestMethod=a,r.call(this,a,d,h??!0,u,l)},XMLHttpRequest.prototype.send=async function(a){let d=this._requestUrl;if(!d)return n.call(this,a);if(this._isReexecution)return n.call(this,a);let h=new URL(d,location.href),u=h.origin===location.origin,l=this._requestMethod??"GET",p=s.find(i=>{let w=b({path:h.pathname,pattern:y(i.path)}),f=i.method.toLowerCase()===l.toLowerCase()||i.method==="*";return w&&f});if(!p||!u)return n.call(this,a);let c=await o.getChallenge();if(this.setRequestHeader("x-is-human",JSON.stringify(c)),this.setRequestHeader("x-path",h.pathname),this.setRequestHeader("x-method",l),c.b!==0)return n.call(this,a);if(e.loaded)return n.call(this,a);if((c.d===1||p?.advancedOptions?.checkLevel==="deepAnalysis")&&await e.load(),!e.loaded)return n.call(this,a);this.setRequestHeader("x-is-human",JSON.stringify(c)),this.setRequestHeader("x-path",h.pathname),this.setRequestHeader("x-method",l);let t=new XMLHttpRequest;return t._isReexecution=!0,t.open(l,d,!0),t.setRequestHeader("x-is-human",JSON.stringify(c)),t.setRequestHeader("x-path",h.pathname),t.setRequestHeader("x-method",l),this.timeout&&(t.timeout=this.timeout),this.responseType&&(t.responseType=this.responseType),this.withCredentials&&(t.withCredentials=this.withCredentials),t.onreadystatechange=()=>{Object.defineProperty(this,"readyState",{value:t.readyState,writable:!0,configurable:!0}),t.readyState===XMLHttpRequest.DONE&&(Object.defineProperty(this,"status",{value:t.status,writable:!0,configurable:!0}),Object.defineProperty(this,"statusText",{value:t.statusText,writable:!0,configurable:!0}),Object.defineProperty(this,"response",{value:t.response,writable:!0,configurable:!0}),Object.defineProperty(this,"responseText",{value:t.responseText,writable:!0,configurable:!0}),Object.defineProperty(this,"responseXML",{value:t.responseXML,writable:!0,configurable:!0}),this.getAllResponseHeaders=()=>t.getAllResponseHeaders(),this.getResponseHeader=i=>t.getResponseHeader(i)),this.onreadystatechange&&this.onreadystatechange.call(this,new Event("readystatechange"))},t.onload=i=>{this.onload&&this.onload.call(this,i)},t.onerror=i=>{this.onerror&&this.onerror.call(this,i)},t.onabort=i=>{this.onabort&&this.onabort.call(this,i)},t.ontimeout=i=>{this.ontimeout&&this.ontimeout.call(this,i)},t.onloadstart=i=>{this.onloadstart&&this.onloadstart.call(this,i)},t.onloadend=i=>{this.onloadend&&this.onloadend.call(this,i)},t.onprogress=i=>{this.onprogress&&this.onprogress.call(this,i)},t.send(a)}}function k({protect:o=[]}){for(let r of o)if(r.advancedOptions?.checkLevel!==void 0&&r.advancedOptions.checkLevel!=="deepAnalysis"&&r.advancedOptions.checkLevel!=="basic")throw new Error(`Invalid checkLevel "${r.advancedOptions.checkLevel}" for route "${r.path}". Must be one of: deepAnalysis, basic`);let e=new R,s=new H(o);E(e,s,o).catch(r=>{console.error("Error patching XMLHttpRequest:",r)}),x(e,s,o)}exports.initBotId=k;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
function v(o) {
|
|
2
|
+
return new Promise((e, s) => {
|
|
3
|
+
if (document.querySelector(`script[src="${o}"]`)) {
|
|
4
|
+
e();
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
let r = document.createElement("script");
|
|
8
|
+
r.src = o, r.async = !0, r.onload = () => e(), r.onerror = (n) => {
|
|
9
|
+
console.error("Error loading script", n), s(n);
|
|
10
|
+
}, document.head.appendChild(r);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
var L = "/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/a-4-a/c.js", R = class m {
|
|
14
|
+
#e;
|
|
15
|
+
#t;
|
|
16
|
+
#r = 0;
|
|
17
|
+
constructor() {
|
|
18
|
+
let { promise: e, resolve: s } = m.#a();
|
|
19
|
+
this.#e = e, this.#t = s, this.#n(), window.addEventListener("online", this.#s), window.addEventListener("visibilitychange", this.#s);
|
|
20
|
+
}
|
|
21
|
+
getChallenge = async () => (await this.#i(), await this.#e.then((e) => typeof e == "function" ? e() : e));
|
|
22
|
+
#s = () => {
|
|
23
|
+
if (document.hidden) return;
|
|
24
|
+
let { promise: e, resolve: s } = m.#a();
|
|
25
|
+
this.#e = e, this.#t = s, window.V_C = [], window.V_C.push = s;
|
|
26
|
+
let r = document.querySelector('script[src*="c.js"]');
|
|
27
|
+
r && r.remove(), this.#r += 1;
|
|
28
|
+
};
|
|
29
|
+
#n = () => {
|
|
30
|
+
if (window.V_C) {
|
|
31
|
+
let e = window.V_C.pop();
|
|
32
|
+
e && this.#t(e);
|
|
33
|
+
} else window.V_C = [], window.V_C.push = this.#t;
|
|
34
|
+
};
|
|
35
|
+
#i = () => {
|
|
36
|
+
let e = new URL(L, window.location.origin);
|
|
37
|
+
return e.searchParams.set("i", String(this.#r)), e.searchParams.set("v", String(3)), e.searchParams.set("h", window.location.host), v(e.pathname + e.search);
|
|
38
|
+
};
|
|
39
|
+
#o = () => {
|
|
40
|
+
window.V_C = void 0;
|
|
41
|
+
};
|
|
42
|
+
static #a() {
|
|
43
|
+
let e, s;
|
|
44
|
+
return { promise: new Promise((r, n) => {
|
|
45
|
+
e = r, s = n;
|
|
46
|
+
}), resolve: e, reject: s };
|
|
47
|
+
}
|
|
48
|
+
}, q = "/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3", x = class g {
|
|
49
|
+
#e = !1;
|
|
50
|
+
#t;
|
|
51
|
+
constructor(e) {
|
|
52
|
+
this.#t = e;
|
|
53
|
+
}
|
|
54
|
+
get loaded() {
|
|
55
|
+
return this.#e;
|
|
56
|
+
}
|
|
57
|
+
load = async () => {
|
|
58
|
+
this.#e || await this.#s();
|
|
59
|
+
};
|
|
60
|
+
#r = () => {
|
|
61
|
+
if (typeof globalThis.window > "u") throw new Error("KPSDK is not available in the server");
|
|
62
|
+
if (!window.KPSDK) throw new Error("KPSDK is not loaded");
|
|
63
|
+
let e = this.#t.map((s) => {
|
|
64
|
+
let r = g.#n(s.path);
|
|
65
|
+
return { domain: r.host, path: r.pathname, method: s.method };
|
|
66
|
+
});
|
|
67
|
+
try {
|
|
68
|
+
window.KPSDK.configure(e);
|
|
69
|
+
} catch (s) {
|
|
70
|
+
console.error("Error configuring KPSDK...", s);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
#s = async () => {
|
|
74
|
+
let e = `${q}/p.js`, s = this;
|
|
75
|
+
return new Promise((r, n) => {
|
|
76
|
+
let i = () => {
|
|
77
|
+
document.removeEventListener("kpsdk-load", i), this.#r();
|
|
78
|
+
}, d = () => {
|
|
79
|
+
document.removeEventListener("kpsdk-ready", d), s.#e = !0, r();
|
|
80
|
+
};
|
|
81
|
+
document.addEventListener("kpsdk-load", i, { once: !0 }), document.addEventListener("kpsdk-ready", d, { once: !0 }), v(e).catch((h) => {
|
|
82
|
+
document.removeEventListener("kpsdk-load", i), document.removeEventListener("kpsdk-ready", d), n(h);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
static #n(e) {
|
|
87
|
+
let s;
|
|
88
|
+
try {
|
|
89
|
+
s = new URL(e);
|
|
90
|
+
} catch {
|
|
91
|
+
s = new URL(e, location.origin);
|
|
92
|
+
}
|
|
93
|
+
return s;
|
|
94
|
+
}
|
|
95
|
+
}, y = (o) => {
|
|
96
|
+
let e = o.replace(/[.?+^$[\]\\(){}|-]/g, "\\$&").split("*").join(".*");
|
|
97
|
+
return new RegExp(`^${e}$`);
|
|
98
|
+
}, b = ({ path: o, pattern: e }) => o.search(e) !== -1;
|
|
99
|
+
function H(o, e, s) {
|
|
100
|
+
let r = window.fetch;
|
|
101
|
+
window.fetch = async (n, i) => {
|
|
102
|
+
let d = new URL(n instanceof Request ? n.url : n, location.href), h = d.origin === location.origin, u = i?.method ?? (n instanceof Request ? n.method : "GET"), l = s.find((a) => {
|
|
103
|
+
let w = b({ path: d.pathname, pattern: y(a.path) }), f = a.method.toLowerCase() === u.toLowerCase() || a.method === "*";
|
|
104
|
+
return w && f;
|
|
105
|
+
});
|
|
106
|
+
if (l == null || !h) return r(n, i);
|
|
107
|
+
let p = await o.getChallenge(), c = new Headers(i?.headers || (n instanceof Request ? n.headers : void 0));
|
|
108
|
+
c.set("x-is-human", JSON.stringify(p)), c.set("x-path", d.pathname), c.set("x-method", u);
|
|
109
|
+
let t = { ...i, headers: c };
|
|
110
|
+
return e.loaded || p.b !== 0 ? r(n, t) : p.d === 1 || l?.advancedOptions?.checkLevel === "deepAnalysis" ? (await e.load(), window.fetch(n, t)) : r(n, t);
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async function E(o, e, s) {
|
|
114
|
+
let r = XMLHttpRequest.prototype.open, n = XMLHttpRequest.prototype.send;
|
|
115
|
+
XMLHttpRequest.prototype.open = function(i, d, h, u, l) {
|
|
116
|
+
return this._requestUrl = d.toString(), this._requestMethod = i, r.call(this, i, d, h ?? !0, u, l);
|
|
117
|
+
}, XMLHttpRequest.prototype.send = async function(i) {
|
|
118
|
+
let d = this._requestUrl;
|
|
119
|
+
if (!d) return n.call(this, i);
|
|
120
|
+
if (this._isReexecution) return n.call(this, i);
|
|
121
|
+
let h = new URL(d, location.href), u = h.origin === location.origin, l = this._requestMethod ?? "GET", p = s.find((a) => {
|
|
122
|
+
let w = b({ path: h.pathname, pattern: y(a.path) }), f = a.method.toLowerCase() === l.toLowerCase() || a.method === "*";
|
|
123
|
+
return w && f;
|
|
124
|
+
});
|
|
125
|
+
if (!p || !u) return n.call(this, i);
|
|
126
|
+
let c = await o.getChallenge();
|
|
127
|
+
if (this.setRequestHeader("x-is-human", JSON.stringify(c)), this.setRequestHeader("x-path", h.pathname), this.setRequestHeader("x-method", l), c.b !== 0) return n.call(this, i);
|
|
128
|
+
if (e.loaded) return n.call(this, i);
|
|
129
|
+
if ((c.d === 1 || p?.advancedOptions?.checkLevel === "deepAnalysis") && await e.load(), !e.loaded) return n.call(this, i);
|
|
130
|
+
this.setRequestHeader("x-is-human", JSON.stringify(c)), this.setRequestHeader("x-path", h.pathname), this.setRequestHeader("x-method", l);
|
|
131
|
+
let t = new XMLHttpRequest();
|
|
132
|
+
return t._isReexecution = !0, t.open(l, d, !0), t.setRequestHeader("x-is-human", JSON.stringify(c)), t.setRequestHeader("x-path", h.pathname), t.setRequestHeader("x-method", l), this.timeout && (t.timeout = this.timeout), this.responseType && (t.responseType = this.responseType), this.withCredentials && (t.withCredentials = this.withCredentials), t.onreadystatechange = () => {
|
|
133
|
+
Object.defineProperty(this, "readyState", { value: t.readyState, writable: !0, configurable: !0 }), t.readyState === XMLHttpRequest.DONE && (Object.defineProperty(this, "status", { value: t.status, writable: !0, configurable: !0 }), Object.defineProperty(this, "statusText", { value: t.statusText, writable: !0, configurable: !0 }), Object.defineProperty(this, "response", { value: t.response, writable: !0, configurable: !0 }), Object.defineProperty(this, "responseText", { value: t.responseText, writable: !0, configurable: !0 }), Object.defineProperty(this, "responseXML", { value: t.responseXML, writable: !0, configurable: !0 }), this.getAllResponseHeaders = () => t.getAllResponseHeaders(), this.getResponseHeader = (a) => t.getResponseHeader(a)), this.onreadystatechange && this.onreadystatechange.call(this, new Event("readystatechange"));
|
|
134
|
+
}, t.onload = (a) => {
|
|
135
|
+
this.onload && this.onload.call(this, a);
|
|
136
|
+
}, t.onerror = (a) => {
|
|
137
|
+
this.onerror && this.onerror.call(this, a);
|
|
138
|
+
}, t.onabort = (a) => {
|
|
139
|
+
this.onabort && this.onabort.call(this, a);
|
|
140
|
+
}, t.ontimeout = (a) => {
|
|
141
|
+
this.ontimeout && this.ontimeout.call(this, a);
|
|
142
|
+
}, t.onloadstart = (a) => {
|
|
143
|
+
this.onloadstart && this.onloadstart.call(this, a);
|
|
144
|
+
}, t.onloadend = (a) => {
|
|
145
|
+
this.onloadend && this.onloadend.call(this, a);
|
|
146
|
+
}, t.onprogress = (a) => {
|
|
147
|
+
this.onprogress && this.onprogress.call(this, a);
|
|
148
|
+
}, t.send(i);
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function k({ protect: o = [] }) {
|
|
152
|
+
for (let r of o) if (r.advancedOptions?.checkLevel !== void 0 && r.advancedOptions.checkLevel !== "deepAnalysis" && r.advancedOptions.checkLevel !== "basic") throw new Error(`Invalid checkLevel "${r.advancedOptions.checkLevel}" for route "${r.path}". Must be one of: deepAnalysis, basic`);
|
|
153
|
+
let e = new R(), s = new x(o);
|
|
154
|
+
E(e, s, o).catch((r) => {
|
|
155
|
+
console.error("Error patching XMLHttpRequest:", r);
|
|
156
|
+
}), H(e, s, o);
|
|
157
|
+
}
|
|
158
|
+
export {
|
|
159
|
+
k as initBotId
|
|
160
|
+
};
|
|
@@ -10,9 +10,11 @@ export interface ErrorWithCode extends Error {
|
|
|
10
10
|
*/
|
|
11
11
|
export declare function resolveHttpStatusCode(error: Error): number | null;
|
|
12
12
|
/**
|
|
13
|
-
* Classifies a streaming-transport error as a
|
|
13
|
+
* Classifies a streaming-transport error as a session auth failure, or null.
|
|
14
|
+
* Bot-protection failures (403) are not retried transparently — they surface
|
|
15
|
+
* to the user as a config error.
|
|
14
16
|
*/
|
|
15
|
-
export declare function resolveStreamingAuthError(error: Error): '
|
|
17
|
+
export declare function resolveStreamingAuthError(error: Error): 'session' | null;
|
|
16
18
|
/**
|
|
17
19
|
* Recoverable errors are input-validation failures where the user can fix
|
|
18
20
|
* their input and retry without clearing the conversation.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`)??"";t.useEffect(()=>{
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const je=require("@ai-sdk/react"),Ce=require("./file-upload-input.cjs"),He=require("ai"),t=require("react"),Je=require("../../providers/config-provider.cjs"),Qe=require("../../hooks/use-media-query.cjs"),We=require("../../hooks/use-anonymous-session.cjs"),Ze=require("../../hooks/use-auth-token.cjs"),Xe=require("../../hooks/use-conversation-loader.cjs"),Ye=require("../../hooks/use-initial-conversation.cjs"),P=require("../../utils/generate-uid.cjs"),et=require("../../providers/base-events-provider.cjs"),tt=require("../../providers/chat-form-provider.cjs"),st=require("../../providers/widget-provider.cjs"),rt=require("@radix-ui/react-use-controllable-state"),nt=require("../../hooks/use-streaming-events.cjs"),ot=require("../../hooks/use-input-notification.cjs"),d=require("./chat-error-helpers.cjs"),at=()=>{const{baseSettings:O,aiChatSettings:v}=Je.useInkeepConfig(),[u="",h]=rt.useControllableState({prop:v.conversationIdOverride,defaultProp:v.conversationIdOverride??""}),{logEvent:g}=et.useBaseEvents(),{setConversationId:Ie,emitToParent:M}=nt.useStreamingEvents(),re=t.useRef(u);t.useEffect(()=>{const e=re.current;re.current=u,e!==u&&g({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,g]);const[y,R]=t.useState(""),Te=e=>R(e.target.value),{filters:ne,privacyPreferences:be,userProperties:N}=O,{authToken:F,isLoading:ke,refreshToken:oe}=Ze.useAuthToken(),ae=!!O.getAuthToken,f=!!F,{onInputMessageChange:we,filters:ie,baseUrl:D,agentUrl:Me,context:ue,headers:ce,appId:S,apiKey:E,files:A}=v,le=Me||`${D}/run/api/chat`,{sessionToken:U,refreshSession:$}=We.useAnonymousSession({baseUrl:D,appId:S,optOutAllAnalytics:be?.optOutAllAnalytics,enabled:!f&&!ke}),de=E??(f?F:U),{loadConversation:fe}=Xe.useConversationLoader({baseUrl:D,appId:S,authToken:de,refreshSession:E||f?void 0:$}),[Fe,pe]=t.useState(!1),B=t.useRef(null);B.current=U;const z=t.useRef(null);z.current=F;const G=t.useRef(void 0);G.current=N&&Object.keys(N).length>0?JSON.stringify(N):void 0;const m=t.useRef(0),K=t.useRef(null),V=t.useRef(null),C=t.useRef(void 0),_e=A?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
|
|
2
|
+
`)??"";t.useEffect(()=>{C.current=A?.length?A:void 0},[_e]);const ge=t.useRef(ce);ge.current=ce;const j=t.useRef(void 0);j.current=ne||ie?JSON.stringify({...ne,...ie}):void 0;const xe=e=>{switch(d.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??d.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||d.RECOVERABLE_FALLBACK_MESSAGE}case 401:return ae?"Authentication failed. Please try again.":d.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${O.organizationDisplayName??"Administrator"}`;case 429:return d.RATE_LIMIT_MESSAGE;default:return d.DEFAULT_ERROR_MESSAGE}},[_,H]=t.useState([]),qe=t.useMemo(()=>new He.DefaultChatTransport({api:le,headers:()=>{const e=E??z.current??B.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...S?{"x-inkeep-app-id":S}:{},...e?{Authorization:`Bearer ${e}`}:{},...j.current?{"inkeep-filters":j.current}:{},...G.current?{"x-inkeep-user-properties":G.current}:{},...ge.current}},prepareSendMessagesRequest:e=>{const a=e.messages[e.messages.length-1];return a||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:a?[a]:[],trigger:e.trigger,messageId:e.messageId},headers:e.headers}},body:{requestContext:ue}}),[le,ue,S,E]),{messages:x,sendMessage:J,addToolApprovalResponse:Q,status:he,setMessages:p,stop:q,error:L}=je.useChat({transport:qe,onData(e){M(e.type,e.data)},async onFinish(){M("completion",{conversationId:u}),await g({eventName:"assistant_message_received",properties:{conversationId:u}}),g({eventName:"assistant_answer_displayed",properties:{conversationId:u}})},onError(e){console.error("onError",{code:e.code,message:e.message});const a=E?null:d.resolveStreamingAuthError(e);if(a!==null&&m.current<1){m.current++;const o=V.current,r=K.current;(async()=>{if(a==="session"&&ae){const c=await oe();if(!c)throw new Error("Auth token refresh failed");z.current=c}else if(a==="session"){const c=await $();c&&(B.current=c)}if(o){Q(o);return}r&&(p(c=>{let n=[...c];return n.at(-1)?.role==="assistant"&&(n=n.slice(0,-1)),n.at(-1)?.role==="user"&&(n=n.slice(0,-1)),n}),J(r.files?.length?{parts:[{type:"text",text:r.content},...r.files]}:{text:r.content},{body:r.body}))})().catch(()=>{m.current=0,p(c=>{const n=[...c],b=n[n.length-1];if(!b)return n;const k=d.DEFAULT_ERROR_MESSAGE;return b.role==="user"?n.push({id:P.generateUid(16),role:"assistant",parts:[{type:"text",text:k}]}):b.parts=[{type:"text",text:k}],n})});return}m.current=0;const s=d.isRecoverableError(e),l=xe(e);if(g({eventName:"chat_error",properties:{conversationId:u,error:e.message}}),s){ee({title:"Request failed",message:l},d.RECOVERABLE_NOTIFICATION_DURATION_MS),p(r=>{let i=[...r];return i.at(-1)?.role==="assistant"&&(i=i.slice(0,-1)),i.at(-1)?.role==="user"&&(i=i.slice(0,-1)),i});const o=K.current?.content;o&&R(o),Y.current=e;return}p(o=>{const r=[...o],i=r[r.length-1];return i&&(i.role==="user"?r.push({id:P.generateUid(16),role:"assistant",parts:[{type:"text",text:l}]}):i.parts=[{type:"text",text:l}]),r})}}),me=t.useRef(f);t.useEffect(()=>{const e=me.current;me.current=f,e!==f&&(q(),I(null),p([]),h(""),R(""),H([]))},[f,q,p,h]);const ve=he==="submitted",W=he==="streaming",Le=t.useMemo(()=>{const e=o=>{if(!o||typeof o!="object")return!1;const r=o;return typeof r.type=="string"&&r.type.startsWith("tool-")},s=[...x??[]].reverse().find(o=>o.role==="assistant");if(!s)return!1;const l=s.parts?.at(-1);return!(!e(l)||l.state!=="output-available"||!l.approval?.id||W)},[x,W]),[Pe,Z]=t.useState(!1),ye=W||Le&&!Pe,Re=ve||ye,Oe=x.length===0,X=!y.trim()&&_.length===0||Re,Ne=Qe.useMediaQuery("(max-width: 768px)"),[De,I]=t.useState(null),Y=t.useRef(null);t.useEffect(()=>{if(L){if(Y.current===L){Y.current=null;return}I(L)}},[L]);const Ue=()=>I(null),{inputNotification:$e,showInputNotification:ee,clearInputNotification:Be}=ot.useInputNotification(),Se=t.useRef(null);t.useEffect(()=>{we?.(y)},[y]);const ze=e=>{e.key==="Enter"&&!e.shiftKey&&!X&&!e.nativeEvent.isComposing&&(e.preventDefault(),te())},te=async(e=y)=>{if(X&&(!e||e.trim().length===0)&&_.length===0)return;const a=_;H([]),R(""),m.current=0,V.current=null,Z(!1),await g({eventName:"user_message_submitted",properties:{conversationId:u}});let s=u;s||(s=`conv_${P.generateUid(16)}`,h(s)),Ie(s);const l=C.current;C.current=void 0;let o,r;if(l?.length){let i;try{i=await Promise.all(a.map(c=>{const n=Ce.normalizeFileType(c);return new Promise((b,k)=>{const w=new FileReader;w.onload=()=>{if(typeof w.result!="string"){k(new Error(`Failed to read file "${n.name}"`));return}b({type:"file",url:w.result,mediaType:n.type,filename:n.name})},w.onerror=()=>k(new Error(`Failed to read file "${n.name}"`)),w.readAsDataURL(n)})}))}catch{ee({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}r=[...i,...l],o=e.trim()?{parts:[{type:"text",text:e},...r]}:{parts:r}}else if(a.length>0){const i=new DataTransfer;for(const n of a)i.items.add(Ce.normalizeFileType(n));const c=i.files;o=e.trim()?{text:e,files:c}:{files:c}}else o={text:e};K.current={content:e,body:{conversationId:s},files:r},J(o,{body:{conversationId:s}})},Ge=t.useCallback(e=>{m.current=0,V.current=e,Z(!1),Q(e)},[Q]),se=t.useCallback(()=>{Z(!0),q().then(()=>{M("aborted",{conversationId:u})})},[q,u,M]),Ee=()=>{Ue(),p([]),h(""),C.current=A?.length?A:void 0,g({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},T=t.useCallback((e,a)=>{I(null),p(a),h(e),C.current=void 0},[p,h]),Ae=t.useCallback(async(e,a)=>{se(),T(e,[]),pe(!0);try{const s=await fe(e,a);if(s===null)return!1;const o=s[s.length-1]?.role==="user"?[...s,{id:P.generateUid(16),role:"assistant",parts:[{type:"text",text:"This session was interrupted. Please check back in a few minutes or start a new conversation."}]}]:s;return T(e,o),!0}finally{a?.aborted||pe(!1)}},[T,fe,se]);Ye.useInitialConversation({conversationId:v.conversationId,effectiveAuthToken:de,loadAndRestoreSession:Ae,onLoadFailed:()=>T("",[])});const{openForm:Ke}=tt.useChatForm(),Ve=st.useWidget();return t.useImperativeHandle(v.chatFunctionsRef,()=>({submitMessage:te,updateInputMessage(e){R(e)},clearChat:Ee,openForm:e=>{Ve?.setView("chat"),Ke(e,void 0)},focusInput:()=>{Se.current?.focus()}})),{messages:x,sendMessage:J,addToolApprovalResponse:Ge,isLoading:ve,isStreaming:ye,isBusy:Re,error:De,setError:I,isSubmitDisabled:X,input:y,handleInputChange:Te,handleInputKeyDown:ze,handleSubmit:te,stop:se,clear:Ee,inputRef:Se,isMobile:Ne,files:_,setFiles:H,isNewChat:Oe,conversationId:u,restoreSession:T,loadAndRestoreSession:Ae,isSessionLoading:Fe,authToken:f?F:U,refreshSession:f?oe:$,inputNotification:$e,showInputNotification:ee,clearInputNotification:Be}};exports.useInkeepChat=at;
|
|
@@ -50,8 +50,6 @@ export declare const useInkeepChat: () => {
|
|
|
50
50
|
isSessionLoading: boolean;
|
|
51
51
|
authToken: string | null;
|
|
52
52
|
refreshSession: () => Promise<string | null>;
|
|
53
|
-
getCaptchaHeader: () => Promise<Record<string, string>>;
|
|
54
|
-
invalidateCaptcha: () => void;
|
|
55
53
|
inputNotification: InputNotification | null;
|
|
56
54
|
showInputNotification: (n: InputNotification, durationMs?: number) => void;
|
|
57
55
|
clearInputNotification: () => void;
|