@bikdotai/bik-component-library 0.0.720-beta.2 → 0.0.720-beta.5

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,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("../utils/guardrails.js"),s=require("./callToChatbot.js");exports.AIService=class{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e.__rest(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);i&&this.dispatchMessage({id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s})}))}makeSystemMessage(){return{role:"system",content:t.injectSafetyPrompt(this.system.systemPrompt)}}generate(s,i){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",n=arguments.length>3?arguments[3]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){const e=s.map((e=>({role:e.role,text:t.sanitizeUserInput(e.content)}))),o=[{role:"system",text:this.makeSystemMessage().content},...e];return this.generateWithRecursiveToolCalls(o,i,a,n)}))}generateWithRecursiveToolCalls(t,i,a,n){var o,r,l,c,d,h,u,p,m,y;return e.__awaiter(this,void 0,void 0,(function*(){const e=t.map((e=>({role:e.role,text:e.text})));let f,g=n,v=0;for(;v<this.maxToolCalls;){let t;v++;try{if(f)t=f,f=void 0;else{let n;if(1===v&&g){const t=[...e].reverse().find((e=>"user"===e.role));t&&(n=[{role:"user",content:t.text}])}t=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,g,this.system.functions,this.system.model,n,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(g=t.responseId,!t.toolCall){if(t.assistantText)if("json"===this.responseFormat){const e=null!==(o=t.parsed)&&void 0!==o?o:this.tryParseAssistantJson(t.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(r=this.onMessageReceived)||void 0===r||r.call(this,e)}else{const e=t.assistantText.trim();this.displayInUI&&e&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,t.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,t.assistantText);return{responseId:g}}const{name:n,args:b,toolCallId:I,callId:x}=t.toolCall;I&&e.push({role:"assistant",text:"",toolCallId:I,toolName:n,toolArgs:JSON.stringify(b)});try{const t="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:n,args:t}});const o=yield this.functionHandler(n,t);if(I?e.push({role:"tool",text:JSON.stringify(o),toolCallId:I}):e.push({role:"tool",text:JSON.stringify(o)}),x){const t="object"==typeof o&&null!==o?o:String(o),r=this.sanitizeToolOutput(n,t);try{const e="string"==typeof t?t:JSON.stringify(t);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:n,preview:e.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,g,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(g=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(u=c.parsed)&&void 0!==u?u:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(p=this.onMessageReceived)||void 0===p||p.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:g}}f=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:g}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:g}}))}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("../utils/guardrails.js"),s=require("./callToChatbot.js");exports.AIService=class{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e.__rest(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){console.log(`🤖 [AIService] dispatchParsedResponses called with ${e.length} items, displayInUI: ${this.displayInUI}`);const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);if(i){const e={id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s};console.log("📨 [AIService] Dispatching AI response:",{messageId:e.id,role:e.role,content:i.substring(0,100)+(i.length>100?"...":""),displayInUI:this.displayInUI}),this.dispatchMessage(e)}}))}makeSystemMessage(){return{role:"system",content:t.injectSafetyPrompt(this.system.systemPrompt)}}generate(s,i){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",n=arguments.length>3?arguments[3]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){const e=s.map((e=>({role:e.role,text:t.sanitizeUserInput(e.content)}))),o=[{role:"system",text:this.makeSystemMessage().content},...e];return this.generateWithRecursiveToolCalls(o,i,a,n)}))}generateWithRecursiveToolCalls(t,i,a,n){var o,r,l,c,d,h,p,u,m,y;return e.__awaiter(this,void 0,void 0,(function*(){const e=t.map((e=>({role:e.role,text:e.text})));let g,f=n,v=0;for(;v<this.maxToolCalls;){let t;v++;try{if(g)t=g,g=void 0;else{let n;if(1===v&&f){const t=[...e].reverse().find((e=>"user"===e.role));t&&(n=[{role:"user",content:t.text}])}t=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,n,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(f=t.responseId,!t.toolCall){if(t.assistantText)if("json"===this.responseFormat){const e=null!==(o=t.parsed)&&void 0!==o?o:this.tryParseAssistantJson(t.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(r=this.onMessageReceived)||void 0===r||r.call(this,e)}else{const e=t.assistantText.trim();this.displayInUI&&e&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,t.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,t.assistantText);return{responseId:f}}const{name:n,args:b,toolCallId:I,callId:x}=t.toolCall;I&&e.push({role:"assistant",text:"",toolCallId:I,toolName:n,toolArgs:JSON.stringify(b)});try{const t="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:n,args:t}});const o=yield this.functionHandler(n,t);if(I?e.push({role:"tool",text:JSON.stringify(o),toolCallId:I}):e.push({role:"tool",text:JSON.stringify(o)}),x){const t="object"==typeof o&&null!==o?o:String(o),r=this.sanitizeToolOutput(n,t);try{const e="string"==typeof t?t:JSON.stringify(t);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:n,preview:e.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(f=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(p=c.parsed)&&void 0!==p?p:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(u=this.onMessageReceived)||void 0===u||u.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:f}}g=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:f}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:f}}))}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("../types/ai.js");exports.callToChatbot=function(o){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",r=arguments.length>4?arguments[4]:void 0,l=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:t.DEFAULT_MODEL,u=arguments.length>8?arguments[8]:void 0,c=arguments.length>9?arguments[9]:void 0,p=arguments.length>10?arguments[10]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){if(!r)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const e=u&&u.length>0?u:function(e){return e.map((e=>{let{role:t,text:o}=e;return{role:t,content:o}}))}(o),t={input:e,intent:n,conversationId:i,systemId:s,previousResponseId:l,customFunctions:a,builtinTools:c,model:d,maxTokens:null!=p?p:4e3};return yield r(t)}))},exports.createExecutorApiAdapter=function(t,o){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return i=>e.__awaiter(this,void 0,void 0,(function*(){var e,s;const{input:r,model:l,maxTokens:a=4e3,previousResponseId:d,customFunctions:u,builtinTools:c,conversationId:p}=i,v={input:r,tools:[...(c||[]).map((e=>({type:e}))),...(h=u,h&&0!==h.length?h.map((e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))):[])],model:l,max_output_tokens:a,previous_response_id:d,conversation_id:p};var h;const g=`${o.replace(/\/$/,"")}${n}`,{status:m,data:_,error:f}=yield t.sendData({apiPath:g,apiMethod:"POST",requestBody:v});if(200!==m||!(null==_?void 0:_.success)){const t=(null===(s=null===(e=null==_?void 0:_.errors)||void 0===e?void 0:e[0])||void 0===s?void 0:s.message)||f;throw new Error("Backend error: "+(t?` - ${String(t)}`:""))}return function(e){const t={assistantText:e.assistantText,parsed:e.parsed,lastResponseId:e.lastResponseId,responseId:e.responseId};return e.toolCall&&(t.toolCall={name:e.toolCall.name,args:e.toolCall.args,toolCallId:e.toolCall.id,callId:e.toolCall.call_id}),t}(_.data)}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),o=require("../types/ai.js");exports.callToChatbot=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",r=arguments.length>4?arguments[4]:void 0,l=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:o.DEFAULT_MODEL,u=arguments.length>8?arguments[8]:void 0,p=arguments.length>9?arguments[9]:void 0,c=arguments.length>10?arguments[10]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){if(!r)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const e=u&&u.length>0?u:function(e){return e.map((e=>{let{role:o,text:t}=e;return{role:o,content:t}}))}(t),o={input:e,intent:n,conversationId:s,systemId:i,previousResponseId:l,customFunctions:a,builtinTools:p,model:d,maxTokens:null!=c?c:4e3};return yield r(o)}))},exports.createExecutorApiAdapter=function(o,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return s=>e.__awaiter(this,void 0,void 0,(function*(){var e,i,r,l;const{input:a,model:d,maxTokens:u=4e3,previousResponseId:p,customFunctions:c,builtinTools:v,conversationId:g}=s;console.log("🌐 [API Adapter] Making API call:",{conversationId:g,previousResponseId:p,inputMessages:a.length,model:d,maxTokens:u});const h={input:a,tools:[...(v||[]).map((e=>({type:e}))),...(_=c,_&&0!==_.length?_.map((e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))):[])],model:d,max_output_tokens:u,previous_response_id:p,conversation_id:g};var _;console.log("📡 [API Adapter] Backend request payload:",{conversation_id:h.conversation_id,previous_response_id:h.previous_response_id,input_count:h.input.length,tools_count:h.tools.length});const I=`${t.replace(/\/$/,"")}${n}`,{status:m,data:x,error:T}=yield o.sendData({apiPath:I,apiMethod:"POST",requestBody:h});if(200!==m||!(null==x?void 0:x.success)){const o=(null===(i=null===(e=null==x?void 0:x.errors)||void 0===e?void 0:e[0])||void 0===i?void 0:i.message)||T;throw console.error("❌ [API Adapter] Backend error:",{status:m,errorMessage:o,data:x}),new Error("Backend error: "+(o?` - ${String(o)}`:""))}const f=function(e){const o={assistantText:e.assistantText,parsed:e.parsed,lastResponseId:e.lastResponseId,responseId:e.responseId};return e.toolCall&&(o.toolCall={name:e.toolCall.name,args:e.toolCall.args,toolCallId:e.toolCall.id,callId:e.toolCall.call_id}),o}(x.data);return console.log("✅ [API Adapter] Backend response received:",{responseId:f.responseId,lastResponseId:f.lastResponseId,assistantText:(null===(r=f.assistantText)||void 0===r?void 0:r.substring(0,100))+((null===(l=f.assistantText)||void 0===l?void 0:l.length)>100?"...":""),hasToolCall:!!f.toolCall}),f}))};
@@ -4,3 +4,5 @@ export declare function saveSession(sessionId: string, record: SessionRecord): P
4
4
  export declare function loadSession(sessionId: string): Promise<SessionRecord | null>;
5
5
  export declare function deleteSession(sessionId: string): Promise<void>;
6
6
  export declare function listSessions(): Promise<string[]>;
7
+ /** Get all sessions (useful for debugging) */
8
+ export declare function getAllSessions(): Promise<SessionRecord[]>;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),i=require("idb-keyval");const t="ai-session:";exports.loadSession=function(r){return e.__awaiter(this,void 0,void 0,(function*(){return(yield i.get(`${t}${r}`))||null}))},exports.saveSession=function(r,s){return e.__awaiter(this,void 0,void 0,(function*(){yield i.set(`${t}${r}`,s)}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js");const s="BIKChatbotDB",o=1,n="sessions";let t=null;function r(){return e.__awaiter(this,void 0,void 0,(function*(){return t||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${s}`);const i=indexedDB.open(s,o);i.onerror=()=>{console.error("❌ [DB] Failed to open database:",i.error),r(i.error)},i.onsuccess=()=>{t=i.result,console.log("✅ [DB] Database opened successfully"),e(t)},i.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const s=e.target.result;if(!s.objectStoreNames.contains(n)){s.createObjectStore(n,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${n}`)}}}))}))}exports.loadSession=function(s){return e.__awaiter(this,void 0,void 0,(function*(){console.log(`🔍 [DB] Loading session with sessionId: "${s}"`);const e=yield r();return new Promise(((o,t)=>{const r=e.transaction([n],"readonly").objectStore(n),i=r.get(s);i.onsuccess=()=>{const e=i.result;if(e)console.log("📁 [DB] Loaded session:",{sessionId:s,recordSessionId:e.sessionId,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()});else{console.log(`📁 [DB] No session found for sessionId: "${s}"`);const e=r.getAllKeys();e.onsuccess=()=>{console.log("🔍 [DB] All existing session keys:",e.result)}}o(e||null)},i.onerror=()=>{console.error("❌ [DB] Failed to load session:",i.error),t(i.error)}}))}))},exports.saveSession=function(s,o){var t;return e.__awaiter(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:s,recordSessionId:o.sessionId,sessionIdMatch:s===o.sessionId,messageCount:o.messages.length,lastMessage:(null===(t=o.messages[o.messages.length-1])||void 0===t?void 0:t.role)||"none",updatedAt:new Date(o.updatedAt).toISOString()});const e=yield r();return new Promise(((t,r)=>{const i=e.transaction([n],"readwrite").objectStore(n).put(o);i.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: "${s}" (record.sessionId: "${o.sessionId}")`),t()},i.onerror=()=>{console.error("❌ [DB] Failed to save session:",i.error),r(i.error)}}))}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),s=require("react"),t=require("../types/chat.js"),a=require("./aiService.js"),n=require("./db.js");exports.useAIChat=function(i){var o=this;let{system:r,conversationId:c,skipInitialization:d=!1,customFunctions:l,functionHandler:g,responseFormat:u,onMessageReceived:m,displayInUI:b,maxToolCalls:j,maxTokens:p,apiAdapter:O}=i;const[v,I]=s.useState((()=>t.createSessionRecord(c))),[S,f]=s.useState([]),[w,y]=s.useState(),[h,A]=s.useState(!1);s.useEffect((()=>{n.loadSession(c).then((e=>{var s;e&&(I(e),f(b?e.messages:e.messages.filter((e=>"user"===e.role))),y(null===(s=e.metadata)||void 0===s?void 0:s.lastResponseId))}))}),[c,b]);const R=s.useMemo((()=>d?null:new a.AIService({system:Object.assign(Object.assign({},r),{handleCallback:(e,s)=>{var t;null===(t=r.handleCallback)||void 0===t||t.call(r,e,s)}}),dispatchMessage:e=>{I((s=>{const t=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,e]});return n.saveSession(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:w})})),t})),b&&f((s=>[...s,e]))},customFunctions:l,functionHandler:g,responseFormat:u,onMessageReceived:m,displayInUI:b,maxToolCalls:j,maxTokens:p,apiAdapter:O})),[r.id,d,p]);return{messages:S,conversation:v,sendMessage:function(s){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return e.__awaiter(o,void 0,void 0,(function*(){if(!R)return;const e={id:`u-${Date.now()}`,role:"user",content:s,timestamp:Date.now()};f((s=>[...s,e])),I((s=>{const t=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,e]});return n.saveSession(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:w})})),t})),A(!0);try{const s=yield R.generate([...S,e].map((e=>({role:e.role,content:e.content}))),c,t,w);(null==s?void 0:s.responseId)&&(y(s.responseId),I((e=>{const t=Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:s.responseId})});return n.saveSession(t.sessionId,t),t})))}catch(e){const s=(null==e?void 0:e.message)||"Something went wrong. Please try again.",t={id:`err-${Date.now()}`,role:"system",content:s,timestamp:Date.now()};f((e=>[...e,t])),I((e=>{const s=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,t]});return n.saveSession(s.sessionId,Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:w})})),s}))}finally{A(!1)}}))},isApiCallInProgress:h}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("../../../_virtual/_tslib.js"),e=require("react"),t=require("../types/chat.js"),a=require("./aiService.js"),n=require("./db.js");exports.useAIChat=function(o){var i=this;let{system:l,conversationId:g,skipInitialization:d=!1,customFunctions:r,functionHandler:c,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:h,apiAdapter:v}=o;const[b,j]=e.useState((()=>t.createSessionRecord(g))),[A,O]=e.useState([]),[C,f]=e.useState(),[y,S]=e.useState(!1);e.useEffect((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${g}, displayInUI: ${m}`),n.loadSession(g).then((s=>{var e,t;if(s){if(console.log("📁 [useAIChat] Session loaded:",{sessionId:s.sessionId,totalMessages:s.messages.length,messageRoles:s.messages.map((s=>s.role)),lastResponseId:null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId}),j(s),m)console.log(`👁️ [useAIChat] displayInUI=true - Loading ALL ${s.messages.length} messages to UI`),O(s.messages);else{const e=s.messages.filter((s=>"user"===s.role));console.log(`🔇 [useAIChat] displayInUI=false - Loading only ${e.length} user messages to UI (${s.messages.length} total in session)`),O(e)}f(null===(t=s.metadata)||void 0===t?void 0:t.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${g}`)}))}),[g,m]);const w=e.useMemo((()=>d?null:new a.AIService({system:Object.assign(Object.assign({},l),{handleCallback:(s,e)=>{var t;null===(t=l.handleCallback)||void 0===t||t.call(l,s,e)}}),dispatchMessage:s=>{console.log("💬 [useAIChat] dispatchMessage called:",{messageId:s.id,role:s.role,content:s.content.substring(0,100)+(s.content.length>100?"...":""),displayInUI:m}),j((e=>{const t=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${t.messages.length}`),n.saveSession(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:C})})),t})),m?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),O((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:r,functionHandler:c,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:h,apiAdapter:v})),[l.id,d,h]);return{messages:A,conversation:b,sendMessage:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s.__awaiter(i,void 0,void 0,(function*(){if(!w)return void console.warn("⚠️ [useAIChat] sendMessage called but service is null");const s={id:`u-${Date.now()}`,role:"user",content:e,timestamp:Date.now()};console.log("📤 [useAIChat] Sending user message:",{messageId:s.id,content:e.substring(0,100)+(e.length>100?"...":""),conversationId:g,displayInUI:m,currentMessagesCount:A.length,currentLastResponseId:C}),O((e=>(console.log(`📝 [useAIChat] Adding user message to UI - Previous count: ${e.length}, New count: ${e.length+1}`),[...e,s]))),j((e=>{var t;console.log("🔄 [useAIChat] Current conversation state before update:",{sessionId:e.sessionId,currentMessageCount:e.messages.length,lastMessage:(null===(t=e.messages[e.messages.length-1])||void 0===t?void 0:t.role)||"none"});const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Previous: ${e.messages.length}, New total: ${a.messages.length}`),console.log("🔍 [useAIChat] Session update details:",{sessionId:a.sessionId,messageCount:a.messages.length,lastResponseId:C,hasMetadata:!!a.metadata}),n.saveSession(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:C})})),a})),S(!0);try{const e=yield w.generate([...A,s].map((s=>({role:s.role,content:s.content}))),g,t,C);(null==e?void 0:e.responseId)&&(f(e.responseId),j((s=>{const t=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return n.saveSession(t.sessionId,t),t})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",t={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};O((s=>[...s,t])),j((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,t]});return n.saveSession(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:C})})),e}))}finally{S(!1)}}))},isApiCallInProgress:y}};
@@ -1 +1 @@
1
- import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{injectSafetyPrompt as s,sanitizeUserInput as i}from"../utils/guardrails.js";import{callToChatbot as a}from"./callToChatbot.js";class o{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);i&&this.dispatchMessage({id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s})}))}makeSystemMessage(){return{role:"system",content:s(this.system.systemPrompt)}}generate(e,s){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",o=arguments.length>3?arguments[3]:void 0;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:i(e.content)}))),n=[{role:"system",text:this.makeSystemMessage().content},...t];return this.generateWithRecursiveToolCalls(n,s,a,o)}))}generateWithRecursiveToolCalls(e,s,i,o){var n,r,l,c,d,h,p,u,m,y;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:e.text})));let f,g=o,v=0;for(;v<this.maxToolCalls;){let e;v++;try{if(f)e=f,f=void 0;else{let o;if(1===v&&g){const e=[...t].reverse().find((e=>"user"===e.role));e&&(o=[{role:"user",content:e.text}])}e=yield a(t,i,s,this.system.id,this.apiAdapter,g,this.system.functions,this.system.model,o,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(g=e.responseId,!e.toolCall){if(e.assistantText)if("json"===this.responseFormat){const t=null!==(n=e.parsed)&&void 0!==n?n:this.tryParseAssistantJson(e.assistantText);if(null!=t){const e=Array.isArray(t)?t:[t];this.displayInUI&&this.dispatchParsedResponses(e),null===(r=this.onMessageReceived)||void 0===r||r.call(this,t)}else{const t=e.assistantText.trim();this.displayInUI&&t&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,e.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,e.assistantText);return{responseId:g}}const{name:o,args:b,toolCallId:I,callId:x}=e.toolCall;I&&t.push({role:"assistant",text:"",toolCallId:I,toolName:o,toolArgs:JSON.stringify(b)});try{const e="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:o,args:e}});const n=yield this.functionHandler(o,e);if(I?t.push({role:"tool",text:JSON.stringify(n),toolCallId:I}):t.push({role:"tool",text:JSON.stringify(n)}),x){const e="object"==typeof n&&null!==n?n:String(n),r=this.sanitizeToolOutput(o,e);try{const t="string"==typeof e?e:JSON.stringify(e);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:o,preview:t.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield a(t,i,s,this.system.id,this.apiAdapter,g,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(g=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(p=c.parsed)&&void 0!==p?p:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(u=this.onMessageReceived)||void 0===u||u.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:g}}f=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:g}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:g}}))}}export{o as AIService};
1
+ import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{injectSafetyPrompt as s,sanitizeUserInput as i}from"../utils/guardrails.js";import{callToChatbot as a}from"./callToChatbot.js";class n{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){console.log(`🤖 [AIService] dispatchParsedResponses called with ${e.length} items, displayInUI: ${this.displayInUI}`);const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);if(i){const e={id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s};console.log("📨 [AIService] Dispatching AI response:",{messageId:e.id,role:e.role,content:i.substring(0,100)+(i.length>100?"...":""),displayInUI:this.displayInUI}),this.dispatchMessage(e)}}))}makeSystemMessage(){return{role:"system",content:s(this.system.systemPrompt)}}generate(e,s){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",n=arguments.length>3?arguments[3]:void 0;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:i(e.content)}))),o=[{role:"system",text:this.makeSystemMessage().content},...t];return this.generateWithRecursiveToolCalls(o,s,a,n)}))}generateWithRecursiveToolCalls(e,s,i,n){var o,r,l,c,d,h,p,u,m,y;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:e.text})));let g,f=n,v=0;for(;v<this.maxToolCalls;){let e;v++;try{if(g)e=g,g=void 0;else{let n;if(1===v&&f){const e=[...t].reverse().find((e=>"user"===e.role));e&&(n=[{role:"user",content:e.text}])}e=yield a(t,i,s,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,n,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(f=e.responseId,!e.toolCall){if(e.assistantText)if("json"===this.responseFormat){const t=null!==(o=e.parsed)&&void 0!==o?o:this.tryParseAssistantJson(e.assistantText);if(null!=t){const e=Array.isArray(t)?t:[t];this.displayInUI&&this.dispatchParsedResponses(e),null===(r=this.onMessageReceived)||void 0===r||r.call(this,t)}else{const t=e.assistantText.trim();this.displayInUI&&t&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,e.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,e.assistantText);return{responseId:f}}const{name:n,args:b,toolCallId:I,callId:x}=e.toolCall;I&&t.push({role:"assistant",text:"",toolCallId:I,toolName:n,toolArgs:JSON.stringify(b)});try{const e="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:n,args:e}});const o=yield this.functionHandler(n,e);if(I?t.push({role:"tool",text:JSON.stringify(o),toolCallId:I}):t.push({role:"tool",text:JSON.stringify(o)}),x){const e="object"==typeof o&&null!==o?o:String(o),r=this.sanitizeToolOutput(n,e);try{const t="string"==typeof e?e:JSON.stringify(e);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:n,preview:t.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield a(t,i,s,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(f=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(p=c.parsed)&&void 0!==p?p:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(u=this.onMessageReceived)||void 0===u||u.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:f}}g=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:f}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:f}}))}}export{n as AIService};
@@ -1 +1 @@
1
- import{__awaiter as t}from"../../../_virtual/_tslib.js";import{DEFAULT_MODEL as o}from"../types/ai.js";function e(o,e){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return i=>t(this,void 0,void 0,(function*(){var t,s;const{input:l,model:r,maxTokens:a=4e3,previousResponseId:d,customFunctions:u,builtinTools:c,conversationId:p}=i,v={input:l,tools:[...(c||[]).map((t=>({type:t}))),...(m=u,m&&0!==m.length?m.map((t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))):[])],model:r,max_output_tokens:a,previous_response_id:d,conversation_id:p};var m;const h=`${e.replace(/\/$/,"")}${n}`,{status:g,data:f,error:I}=yield o.sendData({apiPath:h,apiMethod:"POST",requestBody:v});if(200!==g||!(null==f?void 0:f.success)){const o=(null===(s=null===(t=null==f?void 0:f.errors)||void 0===t?void 0:t[0])||void 0===s?void 0:s.message)||I;throw new Error("Backend error: "+(o?` - ${String(o)}`:""))}return function(t){const o={assistantText:t.assistantText,parsed:t.parsed,lastResponseId:t.lastResponseId,responseId:t.responseId};return t.toolCall&&(o.toolCall={name:t.toolCall.name,args:t.toolCall.args,toolCallId:t.toolCall.id,callId:t.toolCall.call_id}),o}(f.data)}))}function n(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",l=arguments.length>4?arguments[4]:void 0,r=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:o,u=arguments.length>8?arguments[8]:void 0,c=arguments.length>9?arguments[9]:void 0,p=arguments.length>10?arguments[10]:void 0;return t(this,void 0,void 0,(function*(){if(!l)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const t=u&&u.length>0?u:function(t){return t.map((t=>{let{role:o,text:e}=t;return{role:o,content:e}}))}(e),o={input:t,intent:n,conversationId:i,systemId:s,previousResponseId:r,customFunctions:a,builtinTools:c,model:d,maxTokens:null!=p?p:4e3};return yield l(o)}))}export{n as callToChatbot,e as createExecutorApiAdapter};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{DEFAULT_MODEL as o}from"../types/ai.js";function t(o,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return s=>e(this,void 0,void 0,(function*(){var e,i,l,r;const{input:a,model:d,maxTokens:u=4e3,previousResponseId:p,customFunctions:c,builtinTools:v,conversationId:g}=s;console.log("🌐 [API Adapter] Making API call:",{conversationId:g,previousResponseId:p,inputMessages:a.length,model:d,maxTokens:u});const h={input:a,tools:[...(v||[]).map((e=>({type:e}))),...(m=c,m&&0!==m.length?m.map((e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))):[])],model:d,max_output_tokens:u,previous_response_id:p,conversation_id:g};var m;console.log("📡 [API Adapter] Backend request payload:",{conversation_id:h.conversation_id,previous_response_id:h.previous_response_id,input_count:h.input.length,tools_count:h.tools.length});const I=`${t.replace(/\/$/,"")}${n}`,{status:_,data:f,error:x}=yield o.sendData({apiPath:I,apiMethod:"POST",requestBody:h});if(200!==_||!(null==f?void 0:f.success)){const o=(null===(i=null===(e=null==f?void 0:f.errors)||void 0===e?void 0:e[0])||void 0===i?void 0:i.message)||x;throw console.error("❌ [API Adapter] Backend error:",{status:_,errorMessage:o,data:f}),new Error("Backend error: "+(o?` - ${String(o)}`:""))}const T=function(e){const o={assistantText:e.assistantText,parsed:e.parsed,lastResponseId:e.lastResponseId,responseId:e.responseId};return e.toolCall&&(o.toolCall={name:e.toolCall.name,args:e.toolCall.args,toolCallId:e.toolCall.id,callId:e.toolCall.call_id}),o}(f.data);return console.log("✅ [API Adapter] Backend response received:",{responseId:T.responseId,lastResponseId:T.lastResponseId,assistantText:(null===(l=T.assistantText)||void 0===l?void 0:l.substring(0,100))+((null===(r=T.assistantText)||void 0===r?void 0:r.length)>100?"...":""),hasToolCall:!!T.toolCall}),T}))}function n(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",l=arguments.length>4?arguments[4]:void 0,r=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:o,u=arguments.length>8?arguments[8]:void 0,p=arguments.length>9?arguments[9]:void 0,c=arguments.length>10?arguments[10]:void 0;return e(this,void 0,void 0,(function*(){if(!l)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const e=u&&u.length>0?u:function(e){return e.map((e=>{let{role:o,text:t}=e;return{role:o,content:t}}))}(t),o={input:e,intent:n,conversationId:s,systemId:i,previousResponseId:r,customFunctions:a,builtinTools:p,model:d,maxTokens:null!=c?c:4e3};return yield l(o)}))}export{n as callToChatbot,t as createExecutorApiAdapter};
@@ -4,3 +4,5 @@ export declare function saveSession(sessionId: string, record: SessionRecord): P
4
4
  export declare function loadSession(sessionId: string): Promise<SessionRecord | null>;
5
5
  export declare function deleteSession(sessionId: string): Promise<void>;
6
6
  export declare function listSessions(): Promise<string[]>;
7
+ /** Get all sessions (useful for debugging) */
8
+ export declare function getAllSessions(): Promise<SessionRecord[]>;
@@ -1 +1 @@
1
- import{__awaiter as i}from"../../../_virtual/_tslib.js";import{set as o,get as t}from"idb-keyval";const n="ai-session:";function r(t,r){return i(this,void 0,void 0,(function*(){yield o(`${n}${t}`,r)}))}function u(o){return i(this,void 0,void 0,(function*(){return(yield t(`${n}${o}`))||null}))}export{u as loadSession,r as saveSession};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";const s="BIKChatbotDB",o=1,n="sessions";let t=null;function r(){return e(this,void 0,void 0,(function*(){return t||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${s}`);const i=indexedDB.open(s,o);i.onerror=()=>{console.error("❌ [DB] Failed to open database:",i.error),r(i.error)},i.onsuccess=()=>{t=i.result,console.log("✅ [DB] Database opened successfully"),e(t)},i.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const s=e.target.result;if(!s.objectStoreNames.contains(n)){s.createObjectStore(n,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${n}`)}}}))}))}function i(s,o){var t;return e(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:s,recordSessionId:o.sessionId,sessionIdMatch:s===o.sessionId,messageCount:o.messages.length,lastMessage:(null===(t=o.messages[o.messages.length-1])||void 0===t?void 0:t.role)||"none",updatedAt:new Date(o.updatedAt).toISOString()});const e=yield r();return new Promise(((t,r)=>{const i=e.transaction([n],"readwrite").objectStore(n).put(o);i.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: "${s}" (record.sessionId: "${o.sessionId}")`),t()},i.onerror=()=>{console.error("❌ [DB] Failed to save session:",i.error),r(i.error)}}))}))}function d(s){return e(this,void 0,void 0,(function*(){console.log(`🔍 [DB] Loading session with sessionId: "${s}"`);const e=yield r();return new Promise(((o,t)=>{const r=e.transaction([n],"readonly").objectStore(n),i=r.get(s);i.onsuccess=()=>{const e=i.result;if(e)console.log("📁 [DB] Loaded session:",{sessionId:s,recordSessionId:e.sessionId,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()});else{console.log(`📁 [DB] No session found for sessionId: "${s}"`);const e=r.getAllKeys();e.onsuccess=()=>{console.log("🔍 [DB] All existing session keys:",e.result)}}o(e||null)},i.onerror=()=>{console.error("❌ [DB] Failed to load session:",i.error),t(i.error)}}))}))}export{d as loadSession,i as saveSession};
@@ -1 +1 @@
1
- import{__awaiter as s}from"../../../_virtual/_tslib.js";import{useState as e,useEffect as t,useMemo as a}from"react";import{createSessionRecord as n}from"../types/chat.js";import{AIService as o}from"./aiService.js";import{loadSession as i,saveSession as r}from"./db.js";function c(c){var d=this;let{system:l,conversationId:m,skipInitialization:g=!1,customFunctions:p,functionHandler:u,responseFormat:b,onMessageReceived:j,displayInUI:O,maxToolCalls:I,maxTokens:v,apiAdapter:f}=c;const[w,y]=e((()=>n(m))),[h,D]=e([]),[R,A]=e(),[k,x]=e(!1);t((()=>{i(m).then((s=>{var e;s&&(y(s),D(O?s.messages:s.messages.filter((s=>"user"===s.role))),A(null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId))}))}),[m,O]);const C=a((()=>g?null:new o({system:Object.assign(Object.assign({},l),{handleCallback:(s,e)=>{var t;null===(t=l.handleCallback)||void 0===t||t.call(l,s,e)}}),dispatchMessage:s=>{y((e=>{const t=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return r(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:R})})),t})),O&&D((e=>[...e,s]))},customFunctions:p,functionHandler:u,responseFormat:b,onMessageReceived:j,displayInUI:O,maxToolCalls:I,maxTokens:v,apiAdapter:f})),[l.id,g,v]);return{messages:h,conversation:w,sendMessage:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s(d,void 0,void 0,(function*(){if(!C)return;const s={id:`u-${Date.now()}`,role:"user",content:e,timestamp:Date.now()};D((e=>[...e,s])),y((e=>{const t=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return r(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:R})})),t})),x(!0);try{const e=yield C.generate([...h,s].map((s=>({role:s.role,content:s.content}))),m,t,R);(null==e?void 0:e.responseId)&&(A(e.responseId),y((s=>{const t=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return r(t.sessionId,t),t})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",t={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};D((s=>[...s,t])),y((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,t]});return r(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:R})})),e}))}finally{x(!1)}}))},isApiCallInProgress:k}}export{c as useAIChat};
1
+ import{__awaiter as s}from"../../../_virtual/_tslib.js";import{useState as e,useEffect as t,useMemo as a}from"react";import{createSessionRecord as n}from"../types/chat.js";import{AIService as o}from"./aiService.js";import{loadSession as i,saveSession as l}from"./db.js";function g(g){var d=this;let{system:c,conversationId:r,skipInitialization:m=!1,customFunctions:u,functionHandler:I,responseFormat:p,onMessageReceived:h,displayInUI:b,maxToolCalls:v,maxTokens:j,apiAdapter:O}=g;const[A,C]=e((()=>n(r))),[f,y]=e([]),[w,U]=e(),[$,M]=e(!1);t((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${r}, displayInUI: ${b}`),i(r).then((s=>{var e,t;if(s){if(console.log("📁 [useAIChat] Session loaded:",{sessionId:s.sessionId,totalMessages:s.messages.length,messageRoles:s.messages.map((s=>s.role)),lastResponseId:null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId}),C(s),b)console.log(`👁️ [useAIChat] displayInUI=true - Loading ALL ${s.messages.length} messages to UI`),y(s.messages);else{const e=s.messages.filter((s=>"user"===s.role));console.log(`🔇 [useAIChat] displayInUI=false - Loading only ${e.length} user messages to UI (${s.messages.length} total in session)`),y(e)}U(null===(t=s.metadata)||void 0===t?void 0:t.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${r}`)}))}),[r,b]);const R=a((()=>m?null:new o({system:Object.assign(Object.assign({},c),{handleCallback:(s,e)=>{var t;null===(t=c.handleCallback)||void 0===t||t.call(c,s,e)}}),dispatchMessage:s=>{console.log("💬 [useAIChat] dispatchMessage called:",{messageId:s.id,role:s.role,content:s.content.substring(0,100)+(s.content.length>100?"...":""),displayInUI:b}),C((e=>{const t=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${t.messages.length}`),l(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:w})})),t})),b?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),y((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:u,functionHandler:I,responseFormat:p,onMessageReceived:h,displayInUI:b,maxToolCalls:v,maxTokens:j,apiAdapter:O})),[c.id,m,j]);return{messages:f,conversation:A,sendMessage:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s(d,void 0,void 0,(function*(){if(!R)return void console.warn("⚠️ [useAIChat] sendMessage called but service is null");const s={id:`u-${Date.now()}`,role:"user",content:e,timestamp:Date.now()};console.log("📤 [useAIChat] Sending user message:",{messageId:s.id,content:e.substring(0,100)+(e.length>100?"...":""),conversationId:r,displayInUI:b,currentMessagesCount:f.length,currentLastResponseId:w}),y((e=>(console.log(`📝 [useAIChat] Adding user message to UI - Previous count: ${e.length}, New count: ${e.length+1}`),[...e,s]))),C((e=>{var t;console.log("🔄 [useAIChat] Current conversation state before update:",{sessionId:e.sessionId,currentMessageCount:e.messages.length,lastMessage:(null===(t=e.messages[e.messages.length-1])||void 0===t?void 0:t.role)||"none"});const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Previous: ${e.messages.length}, New total: ${a.messages.length}`),console.log("🔍 [useAIChat] Session update details:",{sessionId:a.sessionId,messageCount:a.messages.length,lastResponseId:w,hasMetadata:!!a.metadata}),l(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:w})})),a})),M(!0);try{const e=yield R.generate([...f,s].map((s=>({role:s.role,content:s.content}))),r,t,w);(null==e?void 0:e.responseId)&&(U(e.responseId),C((s=>{const t=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return l(t.sessionId,t),t})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",t={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};y((s=>[...s,t])),C((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,t]});return l(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:w})})),e}))}finally{M(!1)}}))},isApiCallInProgress:$}}export{g as useAIChat};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bikdotai/bik-component-library",
3
- "version": "0.0.720-beta.2",
3
+ "version": "0.0.720-beta.5",
4
4
  "description": "Bik Component Library",
5
5
  "repository": {
6
6
  "type": "git",
@@ -59,7 +59,6 @@
59
59
  "chart.js": "^3.9.1",
60
60
  "chartjs-plugin-datalabels": "^2.2.0",
61
61
  "emoji-picker-react": "^4.4.9",
62
- "idb-keyval": "^6.2.2",
63
62
  "lodash": "^4.17.21",
64
63
  "phone": "^3.1.37",
65
64
  "react-beautiful-dnd": "^13.1.1",