@bikdotai/bik-component-library 0.0.720-beta.1 → 0.0.720-beta.4

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){if(!this.displayInUI)return;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 o="BIKChatbotDB",s=1,t="sessions";let n=null;function r(){return e.__awaiter(this,void 0,void 0,(function*(){return n||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${o}`);const a=indexedDB.open(o,s);a.onerror=()=>{console.error("❌ [DB] Failed to open database:",a.error),r(a.error)},a.onsuccess=()=>{n=a.result,console.log("✅ [DB] Database opened successfully"),e(n)},a.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const o=e.target.result;if(!o.objectStoreNames.contains(t)){o.createObjectStore(t,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${t}`)}}}))}))}exports.loadSession=function(o){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield r();return new Promise(((s,n)=>{const r=e.transaction([t],"readonly").objectStore(t).get(o);r.onsuccess=()=>{const e=r.result;e?console.log("📁 [DB] Loaded session:",{sessionId:o,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}):console.log(`📁 [DB] No session found for sessionId: ${o}`),s(e||null)},r.onerror=()=>{console.error("❌ [DB] Failed to load session:",r.error),n(r.error)}}))}))},exports.saveSession=function(o,s){var n;return e.__awaiter(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:o,messageCount:s.messages.length,lastMessage:(null===(n=s.messages[s.messages.length-1])||void 0===n?void 0:n.role)||"none",updatedAt:new Date(s.updatedAt).toISOString()});const e=yield r();return new Promise(((n,r)=>{const a=e.transaction([t],"readwrite").objectStore(t).put(s);a.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: ${o}`),n()},a.onerror=()=>{console.error("❌ [DB] Failed to save session:",a.error),r(a.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(e.messages),y(null===(s=e.metadata)||void 0===s?void 0:s.lastResponseId))}))}),[c]);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=>{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}))},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"),a=require("../types/chat.js"),t=require("./aiService.js"),n=require("./db.js");exports.useAIChat=function(o){var i=this;let{system:l,conversationId:d,skipInitialization:g=!1,customFunctions:c,functionHandler:r,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:v,apiAdapter:b}=o;const[h,j]=e.useState((()=>a.createSessionRecord(d))),[O,A]=e.useState([]),[f,y]=e.useState(),[C,S]=e.useState(!1);e.useEffect((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${d}, displayInUI: ${m}`),n.loadSession(d).then((s=>{var e,a;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`),A(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)`),A(e)}y(null===(a=s.metadata)||void 0===a?void 0:a.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${d}`)}))}),[d,m]);const w=e.useMemo((()=>g?null:new t.AIService({system:Object.assign(Object.assign({},l),{handleCallback:(s,e)=>{var a;null===(a=l.handleCallback)||void 0===a||a.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 a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${a.messages.length}`),n.saveSession(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:f})})),a})),m?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),A((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:c,functionHandler:r,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:v,apiAdapter:b})),[l.id,g,v]);return{messages:O,conversation:h,sendMessage:function(e){let a=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:d,displayInUI:m}),A((e=>[...e,s])),j((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Total messages now: ${a.messages.length}`),n.saveSession(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:f})})),a})),S(!0);try{const e=yield w.generate([...O,s].map((s=>({role:s.role,content:s.content}))),d,a,f);(null==e?void 0:e.responseId)&&(y(e.responseId),j((s=>{const a=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return n.saveSession(a.sessionId,a),a})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",a={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};A((s=>[...s,a])),j((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,a]});return n.saveSession(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:f})})),e}))}finally{S(!1)}}))},isApiCallInProgress:C}};
@@ -1,3 +1,4 @@
1
+ /// <reference types="react" />
1
2
  export declare const Menus: ({
2
3
  displayName: string;
3
4
  key: number;
@@ -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 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){if(!this.displayInUI)return;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",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 f,g=n,v=0;for(;v<this.maxToolCalls;){let e;v++;try{if(f)e=f,f=void 0;else{let n;if(1===v&&g){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,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=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:g}}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,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{n 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 o="BIKChatbotDB",s=1,t="sessions";let n=null;function r(){return e(this,void 0,void 0,(function*(){return n||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${o}`);const a=indexedDB.open(o,s);a.onerror=()=>{console.error("❌ [DB] Failed to open database:",a.error),r(a.error)},a.onsuccess=()=>{n=a.result,console.log("✅ [DB] Database opened successfully"),e(n)},a.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const o=e.target.result;if(!o.objectStoreNames.contains(t)){o.createObjectStore(t,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${t}`)}}}))}))}function a(o,s){var n;return e(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:o,messageCount:s.messages.length,lastMessage:(null===(n=s.messages[s.messages.length-1])||void 0===n?void 0:n.role)||"none",updatedAt:new Date(s.updatedAt).toISOString()});const e=yield r();return new Promise(((n,r)=>{const a=e.transaction([t],"readwrite").objectStore(t).put(s);a.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: ${o}`),n()},a.onerror=()=>{console.error("❌ [DB] Failed to save session:",a.error),r(a.error)}}))}))}function d(o){return e(this,void 0,void 0,(function*(){const e=yield r();return new Promise(((s,n)=>{const r=e.transaction([t],"readonly").objectStore(t).get(o);r.onsuccess=()=>{const e=r.result;e?console.log("📁 [DB] Loaded session:",{sessionId:o,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}):console.log(`📁 [DB] No session found for sessionId: ${o}`),s(e||null)},r.onerror=()=>{console.error("❌ [DB] Failed to load session:",r.error),n(r.error)}}))}))}export{d as loadSession,a 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 c}from"./db.js";function r(r){var d=this;let{system:l,conversationId:m,skipInitialization:g=!1,customFunctions:p,functionHandler:b,responseFormat:j,onMessageReceived:u,displayInUI:O,maxToolCalls:I,maxTokens:v,apiAdapter:f}=r;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(s.messages),A(null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId))}))}),[m]);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=>{D((e=>[...e,s])),y((e=>{const t=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return c(t.sessionId,Object.assign(Object.assign({},t),{metadata:Object.assign(Object.assign({},t.metadata||{}),{lastResponseId:R})})),t}))},customFunctions:p,functionHandler:b,responseFormat:j,onMessageReceived:u,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 c(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 c(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 c(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:R})})),e}))}finally{x(!1)}}))},isApiCallInProgress:k}}export{r as useAIChat};
1
+ import{__awaiter as s}from"../../../_virtual/_tslib.js";import{useState as e,useEffect as a,useMemo as t}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:I,functionHandler:u,responseFormat:p,onMessageReceived:b,displayInUI:h,maxToolCalls:j,maxTokens:v,apiAdapter:O}=g;const[f,A]=e((()=>n(r))),[y,C]=e([]),[w,U]=e(),[R,$]=e(!1);a((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${r}, displayInUI: ${h}`),i(r).then((s=>{var e,a;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}),A(s),h)console.log(`👁️ [useAIChat] displayInUI=true - Loading ALL ${s.messages.length} messages to UI`),C(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)`),C(e)}U(null===(a=s.metadata)||void 0===a?void 0:a.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${r}`)}))}),[r,h]);const M=t((()=>m?null:new o({system:Object.assign(Object.assign({},c),{handleCallback:(s,e)=>{var a;null===(a=c.handleCallback)||void 0===a||a.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:h}),A((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${a.messages.length}`),l(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:w})})),a})),h?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),C((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:I,functionHandler:u,responseFormat:p,onMessageReceived:b,displayInUI:h,maxToolCalls:j,maxTokens:v,apiAdapter:O})),[c.id,m,v]);return{messages:y,conversation:f,sendMessage:function(e){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s(d,void 0,void 0,(function*(){if(!M)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:h}),C((e=>[...e,s])),A((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Total messages now: ${a.messages.length}`),l(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:w})})),a})),$(!0);try{const e=yield M.generate([...y,s].map((s=>({role:s.role,content:s.content}))),r,a,w);(null==e?void 0:e.responseId)&&(U(e.responseId),A((s=>{const a=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return l(a.sessionId,a),a})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",a={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};C((s=>[...s,a])),A((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,a]});return l(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:w})})),e}))}finally{$(!1)}}))},isApiCallInProgress:R}}export{g as useAIChat};
@@ -1,3 +1,4 @@
1
+ /// <reference types="react" />
1
2
  export declare const Menus: ({
2
3
  displayName: string;
3
4
  key: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bikdotai/bik-component-library",
3
- "version": "0.0.720-beta.1",
3
+ "version": "0.0.720-beta.4",
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",