@inkeep/agents-ui 0.0.0-dev-20260508202730 → 0.0.0-dev-20260508213807

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.
Files changed (21) hide show
  1. package/dist/node_modules/.pnpm/@hookform_resolvers@5.2.2_react-hook-form@7.70.0_react@19.3.0-canary-87ae75b3-20260128_/node_modules/@hookform/resolvers/zod/dist/zod.cjs +1 -0
  2. package/dist/node_modules/.pnpm/@hookform_resolvers@5.2.2_react-hook-form@7.70.0_react@19.3.0-canary-87ae75b3-20260128_/node_modules/@hookform/resolvers/zod/dist/zod.js +93 -0
  3. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.cjs +1 -0
  4. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js +49 -0
  5. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.cjs +1 -0
  6. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js +19 -0
  7. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.cjs +1 -0
  8. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js +28 -0
  9. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.cjs +1 -0
  10. package/dist/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js +23 -0
  11. package/dist/primitives/components/embedded-chat/use-inkeep-chat.cjs +2 -2
  12. package/dist/primitives/components/embedded-chat/use-inkeep-chat.d.ts +13 -0
  13. package/dist/primitives/components/embedded-chat/use-inkeep-chat.js +181 -183
  14. package/dist/styled/components/ask-user-form.cjs +1 -0
  15. package/dist/styled/components/ask-user-form.d.ts +96 -0
  16. package/dist/styled/components/ask-user-form.js +672 -0
  17. package/dist/styled/components/message.cjs +1 -1
  18. package/dist/styled/components/message.js +272 -210
  19. package/dist/styled/inkeep.css.cjs +78 -0
  20. package/dist/styled/inkeep.css.js +78 -0
  21. package/package.json +2 -1
@@ -0,0 +1 @@
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@hookform/resolvers"),m=require("react-hook-form"),v=require("../../../../../../zod@4.3.6/node_modules/zod/v4/core/parse.cjs"),p=require("../../../../../../zod@4.3.6/node_modules/zod/v4/core/errors.cjs");function h(n,i){try{var o=n()}catch(e){return i(e)}return o&&o.then?o.then(void 0,i):o}function y(n,i){for(var o={};n.length;){var e=n[0],a=e.code,s=e.message,r=e.path.join(".");if(!o[r])if("unionErrors"in e){var t=e.unionErrors[0].errors[0];o[r]={message:t.message,type:t.code}}else o[r]={message:s,type:a};if("unionErrors"in e&&e.unionErrors.forEach(function(l){return l.errors.forEach(function(f){return n.push(f)})}),i){var u=o[r].types,c=u&&u[e.code];o[r]=m.appendErrors(r,i,o,a,c?[].concat(c,e.message):e.message)}n.shift()}return o}function g(n,i){for(var o={};n.length;){var e=n[0],a=e.code,s=e.message,r=e.path.join(".");if(!o[r])if(e.code==="invalid_union"&&e.errors.length>0){var t=e.errors[0][0];o[r]={message:t.message,type:t.code}}else o[r]={message:s,type:a};if(e.code==="invalid_union"&&e.errors.forEach(function(l){return l.forEach(function(f){return n.push(f)})}),i){var u=o[r].types,c=u&&u[e.code];o[r]=m.appendErrors(r,i,o,a,c?[].concat(c,e.message):e.message)}n.shift()}return o}function E(n,i,o){if(o===void 0&&(o={}),(function(e){return"_def"in e&&typeof e._def=="object"&&"typeName"in e._def})(n))return function(e,a,s){try{return Promise.resolve(h(function(){return Promise.resolve(n[o.mode==="sync"?"parse":"parseAsync"](e,i)).then(function(r){return s.shouldUseNativeValidation&&d.validateFieldsNatively({},s),{errors:{},values:o.raw?Object.assign({},e):r}})},function(r){if((function(t){return Array.isArray(t?.issues)})(r))return{values:{},errors:d.toNestErrors(y(r.errors,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw r}))}catch(r){return Promise.reject(r)}};if((function(e){return"_zod"in e&&typeof e._zod=="object"})(n))return function(e,a,s){try{return Promise.resolve(h(function(){return Promise.resolve((o.mode==="sync"?v.parse:v.parseAsync)(n,e,i)).then(function(r){return s.shouldUseNativeValidation&&d.validateFieldsNatively({},s),{errors:{},values:o.raw?Object.assign({},e):r}})},function(r){if((function(t){return t instanceof p.$ZodError})(r))return{values:{},errors:d.toNestErrors(g(r.issues,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}exports.zodResolver=E;
@@ -0,0 +1,93 @@
1
+ "use client";
2
+ import { validateFieldsNatively as l, toNestErrors as m } from "@hookform/resolvers";
3
+ import { appendErrors as h } from "react-hook-form";
4
+ import { parse as p, parseAsync as y } from "../../../../../../zod@4.3.6/node_modules/zod/v4/core/parse.js";
5
+ import { $ZodError as g } from "../../../../../../zod@4.3.6/node_modules/zod/v4/core/errors.js";
6
+ function v(n, i) {
7
+ try {
8
+ var o = n();
9
+ } catch (r) {
10
+ return i(r);
11
+ }
12
+ return o && o.then ? o.then(void 0, i) : o;
13
+ }
14
+ function E(n, i) {
15
+ for (var o = {}; n.length; ) {
16
+ var r = n[0], a = r.code, s = r.message, e = r.path.join(".");
17
+ if (!o[e]) if ("unionErrors" in r) {
18
+ var t = r.unionErrors[0].errors[0];
19
+ o[e] = { message: t.message, type: t.code };
20
+ } else o[e] = { message: s, type: a };
21
+ if ("unionErrors" in r && r.unionErrors.forEach(function(f) {
22
+ return f.errors.forEach(function(d) {
23
+ return n.push(d);
24
+ });
25
+ }), i) {
26
+ var u = o[e].types, c = u && u[r.code];
27
+ o[e] = h(e, i, o, a, c ? [].concat(c, r.message) : r.message);
28
+ }
29
+ n.shift();
30
+ }
31
+ return o;
32
+ }
33
+ function j(n, i) {
34
+ for (var o = {}; n.length; ) {
35
+ var r = n[0], a = r.code, s = r.message, e = r.path.join(".");
36
+ if (!o[e]) if (r.code === "invalid_union" && r.errors.length > 0) {
37
+ var t = r.errors[0][0];
38
+ o[e] = { message: t.message, type: t.code };
39
+ } else o[e] = { message: s, type: a };
40
+ if (r.code === "invalid_union" && r.errors.forEach(function(f) {
41
+ return f.forEach(function(d) {
42
+ return n.push(d);
43
+ });
44
+ }), i) {
45
+ var u = o[e].types, c = u && u[r.code];
46
+ o[e] = h(e, i, o, a, c ? [].concat(c, r.message) : r.message);
47
+ }
48
+ n.shift();
49
+ }
50
+ return o;
51
+ }
52
+ function b(n, i, o) {
53
+ if (o === void 0 && (o = {}), (function(r) {
54
+ return "_def" in r && typeof r._def == "object" && "typeName" in r._def;
55
+ })(n)) return function(r, a, s) {
56
+ try {
57
+ return Promise.resolve(v(function() {
58
+ return Promise.resolve(n[o.mode === "sync" ? "parse" : "parseAsync"](r, i)).then(function(e) {
59
+ return s.shouldUseNativeValidation && l({}, s), { errors: {}, values: o.raw ? Object.assign({}, r) : e };
60
+ });
61
+ }, function(e) {
62
+ if ((function(t) {
63
+ return Array.isArray(t?.issues);
64
+ })(e)) return { values: {}, errors: m(E(e.errors, !s.shouldUseNativeValidation && s.criteriaMode === "all"), s) };
65
+ throw e;
66
+ }));
67
+ } catch (e) {
68
+ return Promise.reject(e);
69
+ }
70
+ };
71
+ if ((function(r) {
72
+ return "_zod" in r && typeof r._zod == "object";
73
+ })(n)) return function(r, a, s) {
74
+ try {
75
+ return Promise.resolve(v(function() {
76
+ return Promise.resolve((o.mode === "sync" ? p : y)(n, r, i)).then(function(e) {
77
+ return s.shouldUseNativeValidation && l({}, s), { errors: {}, values: o.raw ? Object.assign({}, r) : e };
78
+ });
79
+ }, function(e) {
80
+ if ((function(t) {
81
+ return t instanceof g;
82
+ })(e)) return { values: {}, errors: m(j(e.issues, !s.shouldUseNativeValidation && s.criteriaMode === "all"), s) };
83
+ throw e;
84
+ }));
85
+ } catch (e) {
86
+ return Promise.reject(e);
87
+ }
88
+ };
89
+ throw new Error("Invalid input: not a Zod schema");
90
+ }
91
+ export {
92
+ b as zodResolver
93
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function b(r,l,c){function f(e,o){if(e._zod||Object.defineProperty(e,"_zod",{value:{def:o,constr:n,traits:new Set},enumerable:!1}),e._zod.traits.has(r))return;e._zod.traits.add(r),l(e,o);const t=n.prototype,i=Object.keys(t);for(let s=0;s<i.length;s++){const d=i[s];d in e||(e[d]=t[d].bind(e))}}const y=c?.Parent??Object;class u extends y{}Object.defineProperty(u,"name",{value:r});function n(e){var o;const t=c?.Parent?new u:this;f(t,e),(o=t._zod).deferred??(o.deferred=[]);for(const i of t._zod.deferred)i();return t}return Object.defineProperty(n,"init",{value:f}),Object.defineProperty(n,Symbol.hasInstance,{value:e=>c?.Parent&&e instanceof c.Parent?!0:e?._zod?.traits?.has(r)}),Object.defineProperty(n,"name",{value:r}),n}class P extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const a={};function g(r){return a}exports.$ZodAsyncError=P;exports.$constructor=b;exports.config=g;exports.globalConfig=a;
@@ -0,0 +1,49 @@
1
+ function b(r, a, c) {
2
+ function f(e, o) {
3
+ if (e._zod || Object.defineProperty(e, "_zod", {
4
+ value: {
5
+ def: o,
6
+ constr: n,
7
+ traits: /* @__PURE__ */ new Set()
8
+ },
9
+ enumerable: !1
10
+ }), e._zod.traits.has(r))
11
+ return;
12
+ e._zod.traits.add(r), a(e, o);
13
+ const t = n.prototype, s = Object.keys(t);
14
+ for (let i = 0; i < s.length; i++) {
15
+ const d = s[i];
16
+ d in e || (e[d] = t[d].bind(e));
17
+ }
18
+ }
19
+ const l = c?.Parent ?? Object;
20
+ class u extends l {
21
+ }
22
+ Object.defineProperty(u, "name", { value: r });
23
+ function n(e) {
24
+ var o;
25
+ const t = c?.Parent ? new u() : this;
26
+ f(t, e), (o = t._zod).deferred ?? (o.deferred = []);
27
+ for (const s of t._zod.deferred)
28
+ s();
29
+ return t;
30
+ }
31
+ return Object.defineProperty(n, "init", { value: f }), Object.defineProperty(n, Symbol.hasInstance, {
32
+ value: (e) => c?.Parent && e instanceof c.Parent ? !0 : e?._zod?.traits?.has(r)
33
+ }), Object.defineProperty(n, "name", { value: r }), n;
34
+ }
35
+ class P extends Error {
36
+ constructor() {
37
+ super("Encountered Promise during synchronous parse. Use .parseAsync() instead.");
38
+ }
39
+ }
40
+ const y = {};
41
+ function p(r) {
42
+ return y;
43
+ }
44
+ export {
45
+ P as $ZodAsyncError,
46
+ b as $constructor,
47
+ p as config,
48
+ y as globalConfig
49
+ };
@@ -0,0 +1 @@
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./core.cjs"),a=require("./util.cjs"),t=(e,r)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:r,enumerable:!1}),e.message=JSON.stringify(r,a.jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},l=o.$constructor("$ZodError",t),c=o.$constructor("$ZodError",t,{Parent:Error});exports.$ZodError=l;exports.$ZodRealError=c;
@@ -0,0 +1,19 @@
1
+ "use client";
2
+ import { $constructor as o } from "./core.js";
3
+ import { jsonStringifyReplacer as t } from "./util.js";
4
+ const a = (e, r) => {
5
+ e.name = "$ZodError", Object.defineProperty(e, "_zod", {
6
+ value: e._zod,
7
+ enumerable: !1
8
+ }), Object.defineProperty(e, "issues", {
9
+ value: r,
10
+ enumerable: !1
11
+ }), e.message = JSON.stringify(r, t, 2), Object.defineProperty(e, "toString", {
12
+ value: () => e.message,
13
+ enumerable: !1
14
+ });
15
+ }, s = o("$ZodError", a), c = o("$ZodError", a, { Parent: Error });
16
+ export {
17
+ s as $ZodError,
18
+ c as $ZodRealError
19
+ };
@@ -0,0 +1 @@
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("./core.cjs"),f=require("./errors.cjs"),c=require("./util.cjs"),y=a=>(o,i,s,r)=>{const n=s?Object.assign(s,{async:!1}):{async:!1},e=o._zod.run({value:i,issues:[]},n);if(e instanceof Promise)throw new l.$ZodAsyncError;if(e.issues.length){const t=new(r?.Err??a)(e.issues.map(u=>c.finalizeIssue(u,n,l.config())));throw c.captureStackTrace(t,r?.callee),t}return e.value},g=y(f.$ZodRealError),p=a=>async(o,i,s,r)=>{const n=s?Object.assign(s,{async:!0}):{async:!0};let e=o._zod.run({value:i,issues:[]},n);if(e instanceof Promise&&(e=await e),e.issues.length){const t=new(r?.Err??a)(e.issues.map(u=>c.finalizeIssue(u,n,l.config())));throw c.captureStackTrace(t,r?.callee),t}return e.value},d=p(f.$ZodRealError);exports._parse=y;exports._parseAsync=p;exports.parse=g;exports.parseAsync=d;
@@ -0,0 +1,28 @@
1
+ "use client";
2
+ import { $ZodAsyncError as m, config as u } from "./core.js";
3
+ import { $ZodRealError as l } from "./errors.js";
4
+ import { finalizeIssue as f, captureStackTrace as p } from "./util.js";
5
+ const y = (o) => (c, a, e, r) => {
6
+ const n = e ? Object.assign(e, { async: !1 }) : { async: !1 }, s = c._zod.run({ value: a, issues: [] }, n);
7
+ if (s instanceof Promise)
8
+ throw new m();
9
+ if (s.issues.length) {
10
+ const t = new (r?.Err ?? o)(s.issues.map((i) => f(i, n, u())));
11
+ throw p(t, r?.callee), t;
12
+ }
13
+ return s.value;
14
+ }, E = /* @__PURE__ */ y(l), w = (o) => async (c, a, e, r) => {
15
+ const n = e ? Object.assign(e, { async: !0 }) : { async: !0 };
16
+ let s = c._zod.run({ value: a, issues: [] }, n);
17
+ if (s instanceof Promise && (s = await s), s.issues.length) {
18
+ const t = new (r?.Err ?? o)(s.issues.map((i) => f(i, n, u())));
19
+ throw p(t, r?.callee), t;
20
+ }
21
+ return s.value;
22
+ }, z = /* @__PURE__ */ w(l);
23
+ export {
24
+ y as _parse,
25
+ w as _parseAsync,
26
+ E as parse,
27
+ z as parseAsync
28
+ };
@@ -0,0 +1 @@
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function c(e,r){return typeof r=="bigint"?r.toString():r}const u="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function n(e){return typeof e=="string"?e:e?.message}function i(e,r,a){const t={...e,path:e.path??[]};if(!e.message){const o=n(e.inst?._zod.def?.error?.(e))??n(r?.error?.(e))??n(a.customError?.(e))??n(a.localeError?.(e))??"Invalid input";t.message=o}return delete t.inst,delete t.continue,r?.reportInput||delete t.input,t}exports.captureStackTrace=u;exports.finalizeIssue=i;exports.jsonStringifyReplacer=c;exports.unwrapMessage=n;
@@ -0,0 +1,23 @@
1
+ "use client";
2
+ function c(r, e) {
3
+ return typeof e == "bigint" ? e.toString() : e;
4
+ }
5
+ const u = "captureStackTrace" in Error ? Error.captureStackTrace : (...r) => {
6
+ };
7
+ function n(r) {
8
+ return typeof r == "string" ? r : r?.message;
9
+ }
10
+ function i(r, e, o) {
11
+ const t = { ...r, path: r.path ?? [] };
12
+ if (!r.message) {
13
+ const a = n(r.inst?._zod.def?.error?.(r)) ?? n(e?.error?.(r)) ?? n(o.customError?.(r)) ?? n(o.localeError?.(r)) ?? "Invalid input";
14
+ t.message = a;
15
+ }
16
+ return delete t.inst, delete t.continue, e?.reportInput || delete t.input, t;
17
+ }
18
+ export {
19
+ u as captureStackTrace,
20
+ i as finalizeIssue,
21
+ c as jsonStringifyReplacer,
22
+ n as unwrapMessage
23
+ };
@@ -1,2 +1,2 @@
1
- "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const st=require("@ai-sdk/react"),Me=require("./file-upload-input.cjs"),rt=require("ai"),t=require("react"),nt=require("../modal/modal-provider.cjs"),at=require("../../providers/chat-bubble-provider.cjs"),ot=require("../../providers/sidebar-chat-provider.cjs"),it=require("../../providers/config-provider.cjs"),ut=require("./use-captcha.cjs"),ct=require("../../hooks/use-media-query.cjs"),lt=require("../../hooks/use-anonymous-session.cjs"),dt=require("../../hooks/use-auth-token.cjs"),pt=require("../../hooks/use-conversation-loader.cjs"),ft=require("../../hooks/use-initial-conversation.cjs"),D=require("../../utils/generate-uid.cjs"),gt=require("../../providers/base-events-provider.cjs"),ht=require("../../providers/chat-form-provider.cjs"),mt=require("../../providers/widget-provider.cjs"),vt=require("@radix-ui/react-use-controllable-state"),yt=require("../../hooks/use-streaming-events.cjs"),Rt=require("../../hooks/use-input-notification.cjs"),p=require("./chat-error-helpers.cjs"),Ct=()=>{const{baseSettings:U,aiChatSettings:R}=it.useInkeepConfig(),[u="",m]=vt.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),Fe=nt.useModal(),_e=at.useOptionalChatBubble(),Oe=ot.useOptionalSidebarChat(),{logEvent:h}=gt.useBaseEvents(),{setConversationId:qe,emitToParent:_}=yt.useStreamingEvents(),ie=t.useRef(u);t.useEffect(()=>{const e=ie.current;ie.current=u,e!==u&&h({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,h]);const[C,S]=t.useState(""),xe=e=>S(e.target.value),{shouldBypassCaptcha:ue,filters:ce,privacyPreferences:Pe,userProperties:B,analyticsProperties:$}=U,{authToken:O,isLoading:Le,refreshToken:le}=dt.useAuthToken(),de=!!U.getAuthToken,f=!!O,{onInputMessageChange:Ne,filters:pe,baseUrl:q,agentUrl:De,context:fe,headers:ge,appId:E,apiKey:v,files:A}=R,Ue=Fe?.isOpen??_e?.isOpen??Oe?.isOpen??!0,{getCaptchaHeader:b,invalidate:l}=ut.useCaptcha({baseUrl:q,shouldBypassCaptcha:ue||!!v,shouldMakeInitialRequest:Ue}),he=t.useRef(b);he.current=b;const me=De||`${q}/run/api/chat`,{sessionToken:z,refreshSession:G}=lt.useAnonymousSession({baseUrl:q,appId:E,getCaptchaHeader:b,invalidateCaptcha:l,optOutAllAnalytics:Pe?.optOutAllAnalytics,enabled:!f&&!Le}),ve=v??(f?O:z),{loadConversation:ye}=pt.useConversationLoader({baseUrl:q,appId:E,authToken:ve,getCaptchaHeader:b,invalidateCaptcha:l,refreshSession:v||f?void 0:G}),[Be,Re]=t.useState(!1),H=t.useRef(null);H.current=z;const K=t.useRef(null);K.current=O;const j=t.useRef(void 0);j.current=B&&Object.keys(B).length>0?JSON.stringify(B):void 0;const J=t.useRef(void 0);J.current=$&&Object.keys($).length>0?JSON.stringify($):void 0;const y=t.useRef(0),V=t.useRef(null),Q=t.useRef(null),I=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(()=>{I.current=A?.length?A:void 0},[$e]);const Ce=t.useRef(ge);Ce.current=ge;const W=t.useRef(void 0);W.current=ce||pe?JSON.stringify({...ce,...pe}):void 0;const ze=e=>{switch(p.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??p.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||p.RECOVERABLE_FALLBACK_MESSAGE}case 401:return de?"Authentication failed. Please try again.":p.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${U.organizationDisplayName??"Administrator"}`;case 429:return p.RATE_LIMIT_MESSAGE;default:return p.DEFAULT_ERROR_MESSAGE}},[x,Z]=t.useState([]),Ge=t.useMemo(()=>new rt.DefaultChatTransport({api:me,headers:()=>{const e=v??K.current??H.current;return{"x-inkeep-client-timezone":Intl.DateTimeFormat().resolvedOptions().timeZone,"x-inkeep-client-timestamp":new Date().toISOString(),"x-inkeep-invocation-type":"chat_widget",...E?{"x-inkeep-app-id":E}:{},...e?{Authorization:`Bearer ${e}`}:{},...W.current?{"inkeep-filters":W.current}:{},...j.current?{"x-inkeep-user-properties":j.current}:{},...J.current?{"x-inkeep-properties":J.current}:{},...Ce.current}},prepareSendMessagesRequest:async e=>{const i=await he.current(),s=e.messages[e.messages.length-1];return s||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:s?[s]:[],trigger:e.trigger,messageId:e.messageId},headers:{...e.headers,...i}}},body:{requestContext:fe}}),[me,fe,E,v]),{messages:P,sendMessage:X,addToolApprovalResponse:Y,status:Se,setMessages:g,stop:L,error:N}=st.useChat({transport:Ge,onData(e){_(e.type,e.data)},async onFinish(){_("completion",{conversationId:u}),await h({eventName:"assistant_message_received",properties:{conversationId:u}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:u}})},onError(e){console.error("onError",{code:e.code,message:e.message});const i=ue||v?null:p.resolveStreamingAuthError(e);if(i!==null&&y.current<1){y.current++;const a=Q.current,r=V.current;(async()=>{if(i==="session"&&de){const c=await le();if(!c)throw new Error("Auth token refresh failed");K.current=c}else if(i==="session"){const c=await G();c&&(H.current=c)}else l();if(a){Y(a);return}r&&(g(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}),X(r.files?.length?{parts:[{type:"text",text:r.content},...r.files]}:{text:r.content},{body:r.body}))})().catch(()=>{y.current=0,l(),g(c=>{const n=[...c],w=n[n.length-1];if(!w)return n;const M=p.DEFAULT_ERROR_MESSAGE;return w.role==="user"?n.push({id:D.generateUid(16),role:"assistant",parts:[{type:"text",text:M}]}):w.parts=[{type:"text",text:M}],n})});return}y.current=0,i!==null&&l();const s=p.isRecoverableError(e),d=ze(e);if(h({eventName:"chat_error",properties:{conversationId:u,error:e.message}}),s){ne({title:"Request failed",message:d},p.RECOVERABLE_NOTIFICATION_DURATION_MS),g(r=>{let o=[...r];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o});const a=V.current?.content;a&&S(a),re.current=e;return}g(a=>{const r=[...a],o=r[r.length-1];return o&&(o.role==="user"?r.push({id:D.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):o.parts=[{type:"text",text:d}]),r})}}),Ee=t.useRef(f);t.useEffect(()=>{const e=Ee.current;Ee.current=f,e!==f&&(L(),T(null),g([]),m(""),S(""),Z([]),l())},[f,L,g,m,l]);const Ae=Se==="submitted",ee=Se==="streaming",He=t.useMemo(()=>{const e=a=>{if(!a||typeof a!="object")return!1;const r=a;return typeof r.type=="string"&&r.type.startsWith("tool-")},s=[...P??[]].reverse().find(a=>a.role==="assistant");if(!s)return!1;const d=s.parts?.at(-1);return!(!e(d)||d.state!=="output-available"||!d.approval?.id||ee)},[P,ee]),[Ke,te]=t.useState(!1),be=ee||He&&!Ke,Ie=Ae||be,je=P.length===0,se=!C.trim()&&x.length===0||Ie,Je=ct.useMediaQuery("(max-width: 768px)"),[Ve,T]=t.useState(null),re=t.useRef(null);t.useEffect(()=>{if(N){if(re.current===N){re.current=null;return}T(N)}},[N]);const Qe=()=>T(null),{inputNotification:We,showInputNotification:ne,clearInputNotification:Ze}=Rt.useInputNotification(),Te=t.useRef(null);t.useEffect(()=>{Ne?.(C)},[C]);const Xe=e=>{e.key==="Enter"&&!e.shiftKey&&!se&&!e.nativeEvent.isComposing&&(e.preventDefault(),ae())},ae=async(e=C)=>{if(se&&(!e||e.trim().length===0)&&x.length===0)return;const i=x;Z([]),S(""),y.current=0,Q.current=null,te(!1),await h({eventName:"user_message_submitted",properties:{conversationId:u}});let s=u;s||(s=`conv_${D.generateUid(16)}`,m(s)),qe(s);const d=I.current;I.current=void 0;let a,r;if(d?.length){let o;try{o=await Promise.all(i.map(c=>{const n=Me.normalizeFileType(c);return new Promise((w,M)=>{const F=new FileReader;F.onload=()=>{if(typeof F.result!="string"){M(new Error(`Failed to read file "${n.name}"`));return}w({type:"file",url:F.result,mediaType:n.type,filename:n.name})},F.onerror=()=>M(new Error(`Failed to read file "${n.name}"`)),F.readAsDataURL(n)})}))}catch{ne({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}r=[...o,...d],a=e.trim()?{parts:[{type:"text",text:e},...r]}:{parts:r}}else if(i.length>0){const o=new DataTransfer;for(const n of i)o.items.add(Me.normalizeFileType(n));const c=o.files;a=e.trim()?{text:e,files:c}:{files:c}}else a={text:e};V.current={content:e,body:{conversationId:s},files:r},X(a,{body:{conversationId:s}})},Ye=t.useCallback(e=>{y.current=0,Q.current=e,te(!1),Y(e)},[Y]),oe=t.useCallback(()=>{te(!0),L().then(()=>{_("aborted",{conversationId:u})})},[L,u,_]),ke=()=>{Qe(),g([]),m(""),l(),I.current=A?.length?A:void 0,h({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},k=t.useCallback((e,i)=>{T(null),g(i),m(e),l(),I.current=void 0},[g,m,l]),we=t.useCallback(async(e,i)=>{oe(),k(e,[]),Re(!0);try{const s=await ye(e,i);if(s===null)return!1;const a=s[s.length-1]?.role==="user"?[...s,{id:D.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 k(e,a),!0}finally{i?.aborted||Re(!1)}},[k,ye,oe]);ft.useInitialConversation({conversationId:R.conversationId,effectiveAuthToken:ve,loadAndRestoreSession:we,onLoadFailed:()=>k("",[])});const{openForm:et}=ht.useChatForm(),tt=mt.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:ae,updateInputMessage(e){S(e)},clearChat:ke,openForm:e=>{tt?.setView("chat"),et(e,void 0)},focusInput:()=>{Te.current?.focus()}})),{messages:P,sendMessage:X,addToolApprovalResponse:Ye,isLoading:Ae,isStreaming:be,isBusy:Ie,error:Ve,setError:T,isSubmitDisabled:se,input:C,handleInputChange:xe,handleInputKeyDown:Xe,handleSubmit:ae,stop:oe,clear:ke,inputRef:Te,isMobile:Je,files:x,setFiles:Z,isNewChat:je,conversationId:u,restoreSession:k,loadAndRestoreSession:we,isSessionLoading:Be,authToken:f?O:z,refreshSession:f?le:G,getCaptchaHeader:b,invalidateCaptcha:l,inputNotification:We,showInputNotification:ne,clearInputNotification:Ze}};exports.useInkeepChat=Ct;
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tt=require("@ai-sdk/react"),we=require("./file-upload-input.cjs"),st=require("ai"),t=require("react"),rt=require("../modal/modal-provider.cjs"),nt=require("../../providers/chat-bubble-provider.cjs"),at=require("../../providers/sidebar-chat-provider.cjs"),ot=require("../../providers/config-provider.cjs"),it=require("./use-captcha.cjs"),ut=require("../../hooks/use-media-query.cjs"),ct=require("../../hooks/use-anonymous-session.cjs"),lt=require("../../hooks/use-auth-token.cjs"),dt=require("../../hooks/use-conversation-loader.cjs"),pt=require("../../hooks/use-initial-conversation.cjs"),D=require("../../utils/generate-uid.cjs"),ft=require("../../providers/base-events-provider.cjs"),gt=require("../../providers/chat-form-provider.cjs"),ht=require("../../providers/widget-provider.cjs"),mt=require("@radix-ui/react-use-controllable-state"),vt=require("../../hooks/use-streaming-events.cjs"),yt=require("../../hooks/use-input-notification.cjs"),p=require("./chat-error-helpers.cjs"),Rt=()=>{const{baseSettings:U,aiChatSettings:R}=ot.useInkeepConfig(),[u="",m]=mt.useControllableState({prop:R.conversationIdOverride,defaultProp:R.conversationIdOverride??""}),ke=rt.useModal(),Me=nt.useOptionalChatBubble(),Fe=at.useOptionalSidebarChat(),{logEvent:h}=ft.useBaseEvents(),{setConversationId:_e,emitToParent:_}=vt.useStreamingEvents(),ae=t.useRef(u);t.useEffect(()=>{const e=ae.current;ae.current=u,e!==u&&h({eventName:"chat_conversation_changed",properties:{conversationId:u,previousConversationId:e}})},[u,h]);const[C,S]=t.useState(""),qe=e=>S(e.target.value),{shouldBypassCaptcha:oe,filters:ie,privacyPreferences:Oe,userProperties:B}=U,{authToken:q,isLoading:xe,refreshToken:ue}=lt.useAuthToken(),ce=!!U.getAuthToken,f=!!q,{onInputMessageChange:Pe,filters:le,baseUrl:O,agentUrl:Le,context:de,headers:pe,appId:E,apiKey:v,files:A}=R,Ne=ke?.isOpen??Me?.isOpen??Fe?.isOpen??!0,{getCaptchaHeader:b,invalidate:l}=it.useCaptcha({baseUrl:O,shouldBypassCaptcha:oe||!!v,shouldMakeInitialRequest:Ne}),fe=t.useRef(b);fe.current=b;const ge=Le||`${O}/run/api/chat`,{sessionToken:$,refreshSession:z}=ct.useAnonymousSession({baseUrl:O,appId:E,getCaptchaHeader:b,invalidateCaptcha:l,optOutAllAnalytics:Oe?.optOutAllAnalytics,enabled:!f&&!xe}),he=v??(f?q:$),{loadConversation:me}=dt.useConversationLoader({baseUrl:O,appId:E,authToken:he,getCaptchaHeader:b,invalidateCaptcha:l,refreshSession:v||f?void 0:z}),[De,ve]=t.useState(!1),G=t.useRef(null);G.current=$;const H=t.useRef(null);H.current=q;const K=t.useRef(void 0);K.current=B&&Object.keys(B).length>0?JSON.stringify(B):void 0;const y=t.useRef(0),V=t.useRef(null),j=t.useRef(null),I=t.useRef(void 0),Ue=A?.map(e=>`${e.filename??""}:${e.mediaType}:${e.url.length}:${e.url.slice(0,64)}:${e.url.slice(-32)}`).join(`
2
+ `)??"";t.useEffect(()=>{I.current=A?.length?A:void 0},[Ue]);const ye=t.useRef(pe);ye.current=pe;const J=t.useRef(void 0);J.current=ie||le?JSON.stringify({...ie,...le}):void 0;const Be=e=>{switch(p.resolveHttpStatusCode(e)){case 400:try{const s=JSON.parse(e.message??"");return s.detail??s.error?.message??p.RECOVERABLE_FALLBACK_MESSAGE}catch{return e.message?.trim()||p.RECOVERABLE_FALLBACK_MESSAGE}case 401:return ce?"Authentication failed. Please try again.":p.DEFAULT_ERROR_MESSAGE;case 403:return`There seems to be a configuration error. Please contact ${U.organizationDisplayName??"Administrator"}`;case 429:return p.RATE_LIMIT_MESSAGE;default:return p.DEFAULT_ERROR_MESSAGE}},[x,Q]=t.useState([]),$e=t.useMemo(()=>new st.DefaultChatTransport({api:ge,headers:()=>{const e=v??H.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",...E?{"x-inkeep-app-id":E}:{},...e?{Authorization:`Bearer ${e}`}:{},...J.current?{"inkeep-filters":J.current}:{},...K.current?{"x-inkeep-user-properties":K.current}:{},...ye.current}},prepareSendMessagesRequest:async e=>{const i=await fe.current(),s=e.messages[e.messages.length-1];return s||console.warn("[useInkeepChat] prepareSendMessagesRequest called with empty messages array"),{body:{...e.body,id:e.id,messages:s?[s]:[],trigger:e.trigger,messageId:e.messageId},headers:{...e.headers,...i}}},body:{requestContext:de}}),[ge,de,E,v]),{messages:P,sendMessage:W,addToolApprovalResponse:Z,addToolOutput:ze,status:Re,setMessages:g,stop:L,error:N}=tt.useChat({transport:$e,onData(e){_(e.type,e.data)},async onFinish(){_("completion",{conversationId:u}),await h({eventName:"assistant_message_received",properties:{conversationId:u}}),h({eventName:"assistant_answer_displayed",properties:{conversationId:u}})},onError(e){console.error("onError",{code:e.code,message:e.message});const i=oe||v?null:p.resolveStreamingAuthError(e);if(i!==null&&y.current<1){y.current++;const a=j.current,r=V.current;(async()=>{if(i==="session"&&ce){const c=await ue();if(!c)throw new Error("Auth token refresh failed");H.current=c}else if(i==="session"){const c=await z();c&&(G.current=c)}else l();if(a){Z(a);return}r&&(g(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}),W(r.files?.length?{parts:[{type:"text",text:r.content},...r.files]}:{text:r.content},{body:r.body}))})().catch(()=>{y.current=0,l(),g(c=>{const n=[...c],k=n[n.length-1];if(!k)return n;const M=p.DEFAULT_ERROR_MESSAGE;return k.role==="user"?n.push({id:D.generateUid(16),role:"assistant",parts:[{type:"text",text:M}]}):k.parts=[{type:"text",text:M}],n})});return}y.current=0,i!==null&&l();const s=p.isRecoverableError(e),d=Be(e);if(h({eventName:"chat_error",properties:{conversationId:u,error:e.message}}),s){se({title:"Request failed",message:d},p.RECOVERABLE_NOTIFICATION_DURATION_MS),g(r=>{let o=[...r];return o.at(-1)?.role==="assistant"&&(o=o.slice(0,-1)),o.at(-1)?.role==="user"&&(o=o.slice(0,-1)),o});const a=V.current?.content;a&&S(a),te.current=e;return}g(a=>{const r=[...a],o=r[r.length-1];return o&&(o.role==="user"?r.push({id:D.generateUid(16),role:"assistant",parts:[{type:"text",text:d}]}):o.parts=[{type:"text",text:d}]),r})}}),Ce=t.useRef(f);t.useEffect(()=>{const e=Ce.current;Ce.current=f,e!==f&&(L(),T(null),g([]),m(""),S(""),Q([]),l())},[f,L,g,m,l]);const Se=Re==="submitted",X=Re==="streaming",Ge=t.useMemo(()=>{const e=a=>{if(!a||typeof a!="object")return!1;const r=a;return typeof r.type=="string"&&r.type.startsWith("tool-")},s=[...P??[]].reverse().find(a=>a.role==="assistant");if(!s)return!1;const d=s.parts?.at(-1);return!(!e(d)||d.state!=="output-available"||!d.approval?.id||X)},[P,X]),[He,Y]=t.useState(!1),Ee=X||Ge&&!He,Ae=Se||Ee,Ke=P.length===0,ee=!C.trim()&&x.length===0||Ae,Ve=ut.useMediaQuery("(max-width: 768px)"),[je,T]=t.useState(null),te=t.useRef(null);t.useEffect(()=>{if(N){if(te.current===N){te.current=null;return}T(N)}},[N]);const Je=()=>T(null),{inputNotification:Qe,showInputNotification:se,clearInputNotification:We}=yt.useInputNotification(),be=t.useRef(null);t.useEffect(()=>{Pe?.(C)},[C]);const Ze=e=>{e.key==="Enter"&&!e.shiftKey&&!ee&&!e.nativeEvent.isComposing&&(e.preventDefault(),re())},re=async(e=C)=>{if(ee&&(!e||e.trim().length===0)&&x.length===0)return;const i=x;Q([]),S(""),y.current=0,j.current=null,Y(!1),await h({eventName:"user_message_submitted",properties:{conversationId:u}});let s=u;s||(s=`conv_${D.generateUid(16)}`,m(s)),_e(s);const d=I.current;I.current=void 0;let a,r;if(d?.length){let o;try{o=await Promise.all(i.map(c=>{const n=we.normalizeFileType(c);return new Promise((k,M)=>{const F=new FileReader;F.onload=()=>{if(typeof F.result!="string"){M(new Error(`Failed to read file "${n.name}"`));return}k({type:"file",url:F.result,mediaType:n.type,filename:n.name})},F.onerror=()=>M(new Error(`Failed to read file "${n.name}"`)),F.readAsDataURL(n)})}))}catch{se({title:"Failed to attach files",message:"Could not read one or more files. Please try again."});return}r=[...o,...d],a=e.trim()?{parts:[{type:"text",text:e},...r]}:{parts:r}}else if(i.length>0){const o=new DataTransfer;for(const n of i)o.items.add(we.normalizeFileType(n));const c=o.files;a=e.trim()?{text:e,files:c}:{files:c}}else a={text:e};V.current={content:e,body:{conversationId:s},files:r},W(a,{body:{conversationId:s}})},Xe=t.useCallback(e=>{y.current=0,j.current=e,Y(!1),Z(e)},[Z]),ne=t.useCallback(()=>{Y(!0),L().then(()=>{_("aborted",{conversationId:u})})},[L,u,_]),Ie=()=>{Je(),g([]),m(""),l(),I.current=A?.length?A:void 0,h({eventName:"chat_clear_button_clicked",properties:{conversationId:u}})},w=t.useCallback((e,i)=>{T(null),g(i),m(e),l(),I.current=void 0},[g,m,l]),Te=t.useCallback(async(e,i)=>{ne(),w(e,[]),ve(!0);try{const s=await me(e,i);if(s===null)return!1;const a=s[s.length-1]?.role==="user"?[...s,{id:D.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 w(e,a),!0}finally{i?.aborted||ve(!1)}},[w,me,ne]);pt.useInitialConversation({conversationId:R.conversationId,effectiveAuthToken:he,loadAndRestoreSession:Te,onLoadFailed:()=>w("",[])});const{openForm:Ye}=gt.useChatForm(),et=ht.useWidget();return t.useImperativeHandle(R.chatFunctionsRef,()=>({submitMessage:re,updateInputMessage(e){S(e)},clearChat:Ie,openForm:e=>{et?.setView("chat"),Ye(e,void 0)},focusInput:()=>{be.current?.focus()}})),{messages:P,sendMessage:W,addToolApprovalResponse:Xe,addToolOutput:ze,isLoading:Se,isStreaming:Ee,isBusy:Ae,error:je,setError:T,isSubmitDisabled:ee,input:C,handleInputChange:qe,handleInputKeyDown:Ze,handleSubmit:re,stop:ne,clear:Ie,inputRef:be,isMobile:Ve,files:x,setFiles:Q,isNewChat:Ke,conversationId:u,restoreSession:w,loadAndRestoreSession:Te,isSessionLoading:De,authToken:f?q:$,refreshSession:f?ue:z,getCaptchaHeader:b,invalidateCaptcha:l,inputNotification:Qe,showInputNotification:se,clearInputNotification:We}};exports.useInkeepChat=Rt;
@@ -27,6 +27,19 @@ export declare const useInkeepChat: () => {
27
27
  id: string;
28
28
  approved: boolean;
29
29
  }) => void;
30
+ addToolOutput: <TOOL extends string>({ state, tool, toolCallId, output, errorText, }: {
31
+ state?: "output-available";
32
+ tool: TOOL;
33
+ toolCallId: string;
34
+ output: unknown;
35
+ errorText?: never;
36
+ } | {
37
+ state: "output-error";
38
+ tool: TOOL;
39
+ toolCallId: string;
40
+ output?: never;
41
+ errorText: string;
42
+ }) => Promise<void>;
30
43
  isLoading: boolean;
31
44
  isStreaming: boolean;
32
45
  isBusy: boolean;