@blueking/ai-blueking 2.2.2-beta.8 → 2.2.2-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/manager/business/chat-business-manager.d.ts +3 -0
- package/dist/manager/business/chat-business-manager.d.ts.map +1 -1
- package/dist/standalone/index.es.min.js +7 -4
- package/dist/standalone/index.iife.min.js +2 -2
- package/dist/standalone/index.umd.min.js +2 -2
- package/dist/vue2/index.es.min.js +7 -4
- package/dist/vue2/index.iife.min.js +3 -3
- package/dist/vue2/index.umd.min.js +3 -3
- package/dist/vue3/index.es.min.js +7 -4
- package/dist/vue3/index.iife.min.js +2 -2
- package/dist/vue3/index.umd.min.js +2 -2
- package/package.json +3 -3
|
@@ -3484,6 +3484,6 @@ Use Shift + Enter to enter a new line`:`输入 "/" 唤出 Skill
|
|
|
3484
3484
|
`)||``},null,8,[`content`])):((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,{key:1},(0,t.renderList)(Array.isArray(e.content)?e.content:[e.content],e=>((0,t.openBlock)(),(0,t.createBlock)(b7,{key:e,content:e},null,8,[`content`]))),128))],512),[[t.vShow,!r.value]])]))}}),KBt={class:`ai-key-value-content`},qBt={key:0,class:`ai-key-value-title`},JBt={class:`ai-key-value-content`},YBt={class:`item-key`},XBt={class:`item-value`},ZBt=(0,t.defineComponent)({__name:`key-value-content`,props:{content:{},title:{}},setup(e){return(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,KBt,[e.title?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,qBt,[(0,t.createVNode)((0,t.unref)(ikt)),(0,t.createTextVNode)(` `+(0,t.toDisplayString)(e.title),1)])):(0,t.createCommentVNode)(``,!0),(0,t.createElementVNode)(`div`,JBt,[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(e.content,e=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:e.key,class:`key-value-item`},[(0,t.createElementVNode)(`div`,YBt,(0,t.toDisplayString)(e.key),1),r[0]||=(0,t.createTextVNode)(` : `,-1),(0,t.createElementVNode)(`div`,XBt,(0,t.toDisplayString)(e.value),1)]))),128))])]))}}),QBt={class:`ai-text-content`},$Bt=(0,t.defineComponent)({__name:`text-content`,props:{content:{}},setup(e){return(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,QBt,(0,t.toDisplayString)(e.content),1))}}),eVt={class:`ai-user-message`},tVt={key:0,class:`ai-user-message-binary-files`},nVt={key:1,class:`ai-user-message-content`},rVt={class:`user-edit-footer`},iVt=(0,t.defineComponent)({__name:`user-message`,props:{content:{},id:{},messageId:{},name:{},onAction:{type:Function},property:{},role:{},status:{},tippyOptions:{},uid:{},messageToolsStatus:{},onInputConfirm:{type:Function},onShortcutConfirm:{type:Function}},setup(e){let n=e,r=rAt(),{copy:i}=c5(),a=(0,t.shallowRef)(!1),o=(0,t.shallowRef)(``),s=(0,t.useTemplateRef)(`chatInputRef`),l=(0,t.computed)(()=>{var e;let t=(e=n.property)==null||(e=e.extra)==null?void 0:e.cite;if(!(!t||typeof t==`string`))return t.title}),u=(0,t.computed)(()=>{var e;let t=(e=n.property)==null||(e=e.extra)==null?void 0:e.cite;return!t||typeof t==`string`?t:t.data}),d=(0,t.computed)(()=>{var e,t;if(!((e=n.property)!=null&&e.extra))return null;let{extra:r}=n.property,{shortcut:i,cite:a,context:o}=r||{};if(i)return i;if(a&&typeof a==`object`&&(t=a.data)!=null&&t.length){let e=[];for(let t of a.data){let n=o?.find(e=>e.__label===t.key);n!=null&&n.__key&&e.push({formItemProps:{label:n.__label,required:!!n.fillBack},props:{default:n.__value},key:n.__key,type:`textarea`})}return{components:e,name:a.title}}return null}),f=e=>!!e.url||wDt(e.mimeType||e.file?.type),p=(0,t.computed)(()=>Array.isArray(n.content)?n.content?.filter(e=>e.type===B8.Binary):[]),m=(0,t.computed)(()=>p.value.filter(e=>f(e))),h=(0,t.computed)(()=>p.value.filter(e=>!f(e))),g=(0,t.computed)(()=>n.content?typeof n.content==`string`?[n.content]:n.content.filter(e=>{var t;return e.type===B8.Text&&!!((t=e.text)!=null&&t.trim())}).map(e=>e.text):[]),_=function(){var e=r5(function*(e){e.id===`edit`?(g.value.length&&(o.value=g.value[0]??``,a.value=!0),p.value.length&&(a.value=!0)):e.id===`copy`&&i(typeof n.content==`string`?n.content:JSON.stringify(n.content||``)),yield n.onAction?.call(n,e)});return function(t){return e.apply(this,arguments)}}(),v=function(){var e=r5(function*(){var e,t;yield(e=s.value)==null||(t=e.triggerSendMessage)==null?void 0:t.call(e),a.value=!1});return function(){return e.apply(this,arguments)}}(),y=()=>{a.value=!1},b=()=>{a.value=!1},x=function(){var e=r5(function*(e){var t;(t=n.onShortcutConfirm)==null||t.call(n,e),a.value=!1});return function(t){return e.apply(this,arguments)}}(),S=function(){var e=r5(function*(e,t){var r;(r=n.onInputConfirm)==null||r.call(n,e,t),a.value=!1});return function(t,n){return e.apply(this,arguments)}}();return(n,i)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,eVt,[u.value&&typeof u.value==`string`?((0,t.openBlock)(),(0,t.createBlock)(IFt,{key:0,class:`ai-user-message-cite`,content:u.value},null,8,[`content`])):(0,t.createCommentVNode)(``,!0),a.value?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:2},[d.value?((0,t.openBlock)(),(0,t.createBlock)(Bkt,(0,t.mergeProps)({key:0},d.value,{class:`user-shortcut-render`,onClose:b,onSubmit:x}),null,16)):((0,t.openBlock)(),(0,t.createBlock)(iLt,{key:1,ref_key:`chatInputRef`,ref:s,modelValue:o.value,"onUpdate:modelValue":i[0]||=e=>o.value=e,class:`user-edit-input`,"default-upload-files":p.value,"on-send-message":S,"support-upload":(0,t.unref)(r)?.supportUpload.value??!1},{"send-icon":(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,rVt,[(0,t.createVNode)((0,t.unref)(Wo),{size:`small`,onClick:y},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`取消`)),1)]),_:1}),(0,t.createVNode)((0,t.unref)(Wo),{size:`small`,theme:`primary`,onClick:v},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`发送`)),1)]),_:1})])]),_:1},8,[`modelValue`,`default-upload-files`,`support-upload`]))],64)):((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:1},[p.value.length?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[m.value.length?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,tVt,[(0,t.createVNode)(Z7,{files:m.value,readonly:!0},null,8,[`files`])])):(0,t.createCommentVNode)(``,!0),((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(h.value,(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:e.url??n,class:`ai-user-message-binary-files`},[(0,t.createVNode)(Z7,{files:[e],readonly:!0},null,8,[`files`])]))),128))],64)):(0,t.createCommentVNode)(``,!0),u.value||g.value.length?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,nVt,[Array.isArray(u.value)?((0,t.openBlock)(),(0,t.createBlock)(ZBt,{key:0,content:u.value,title:l.value},null,8,[`content`,`title`])):e.content?((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,{key:1},(0,t.renderList)(g.value,(e,n)=>((0,t.openBlock)(),(0,t.createBlock)($Bt,{key:n,content:e},null,8,[`content`]))),128)):(0,t.createCommentVNode)(``,!0)])):(0,t.createCommentVNode)(``,!0),e.messageToolsStatus===(0,t.unref)(Y7).Hidden?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(GRt,{key:2,class:`ai-user-message-tools`,"message-tools":(0,t.unref)(nOt),"message-tools-status":e.messageToolsStatus,"on-action":_,"tippy-options":e.tippyOptions,"update-tools":[]},null,8,[`message-tools`,`message-tools-status`,`tippy-options`]))],64))]))}}),m9=(0,t.defineComponent)({__name:`message-render`,props:{messageToolsStatus:{},onInputConfirm:{type:Function},onShortcutConfirm:{type:Function},onAction:{type:Function},tippyOptions:{},message:{},onInterruptResume:{type:Function}},setup(e){let n=e,r=(0,t.useSlots)(),i=(0,t.computed)(()=>{switch(n.message.role){case V8.User:return(0,t.h)(iVt,$($({},n.message),{},{onAction:n.onAction,onInputConfirm:n.onInputConfirm,onShortcutConfirm:n.onShortcutConfirm,messageToolsStatus:n.messageToolsStatus,tippyOptions:n.tippyOptions}));case V8.Assistant:return(0,t.h)(vBt,n.message,{default:e=>(0,t.renderSlot)(r,`default`,e,()=>[(0,t.h)(S7,{content:n.message.content||``,status:n.message.status},r.codeHeader?{codeHeader:e=>r.codeHeader?.call(r,e)}:void 0)])});case V8.Info:return(0,t.h)(xBt,n.message);case V8.Reasoning:return(0,t.h)(GBt,n.message);case V8.Tool:return(0,t.h)(sBt,n.message);case V8.Activity:return(0,t.h)(eBt,$($({},n.message),{},{onInterruptResume:n.onInterruptResume}));case V8.Interrupt:return(0,t.h)(RBt,$($({},n.message),{},{onInterruptResume:n.onInterruptResume}),r.answeredQuestion?{answeredQuestion:e=>r.answeredQuestion?.call(r,e)}:void 0);case V8.Loading:return(0,t.h)(BBt,n.message);default:return null}});return(e,n)=>((0,t.openBlock)(),(0,t.createBlock)((0,t.resolveDynamicComponent)(i.value)))}}),aVt=[`id`,`data-message-group-id`,`onMouseenter`,`onMouseleave`],oVt=[`data-message-id`],sVt={class:`ai-message-fixed-bottom`},cVt=(0,t.defineComponent)({__name:`message-container`,props:(0,t.mergeModels)({enableSelection:{type:Boolean,default:!1},messageGroups:{},messages:{},messageStatus:{},messageTools:{},messageToolsStatus:{},messageToolsTippyOptions:{},onAgentAction:{},onAgentFeedback:{},onInterruptResume:{},onUserAction:{},renderMode:{},updateTools:{},onUserInputConfirm:{},onUserShortcutConfirm:{}},{selectedUserMessages:{required:!1},selectedUserMessagesModifiers:{}}),emits:(0,t.mergeModels)([`stopStreaming`],[`update:selectedUserMessages`]),setup(e){let n=e,r=(0,t.useModel)(e,`selectedUserMessages`),i=e=>{let t=e.id||e.uid;return t===void 0?void 0:String(t)},a=(0,t.useTemplateRef)(`messageContainerRef`),o=(0,t.useTemplateRef)(`messageContainerBottomRef`),{jumpToBottom:s,toScrollBottom:l,debouncedShowScrollBottomBtn:u}=Jkt(a,o);(0,t.onMounted)(()=>{var e;(e=n.messageGroups)!=null&&e.length&&(s(),requestAnimationFrame(()=>s()))});let{copy:d}=c5(),f=(e,t)=>{if(!(t!=null&&t.length))return e;let n=e.map(e=>{let n=t.find(t=>t.id===e.id);return n?$($({},e),n):e}),r=t.filter(t=>!e.some(e=>e.id===t.id));return[...n,...r].filter(e=>!e.hidden)},p=(0,t.computed)(()=>f(tOt,n.messageTools).filter(e=>n.renderMode!==G8.Test||e.id!==`share`)),m=(0,t.computed)(()=>f(rOt,n.updateTools)),h=(0,t.computed)(()=>n.renderMode===G8.Share?n.messageGroups.filter(e=>e.type!==V8.Loading):n.messageGroups),g=e=>{e.messages?.at(-1)?.role!==V8.Interrupt&&(e.isHover=!0)},_=(e,t)=>{let n=t.toElement??t.relatedTarget;n instanceof Element&&n.classList.contains(`ai-user-feedback`)||(e.isHover=!1)},v=(e,t)=>{var i;let a=e.type===V8.User;(i=n.messageGroups)==null||i.forEach((r,i)=>{if(r===e){r.checked=t;let e=a?n.messageGroups.at(i+1):n.messageGroups.at(i-1);e&&(e.checked=t)}}),r.value=n.messageGroups?.filter(e=>e.checked).map(e=>e.messages).flat()},y=function(){var e=r5(function*(e,t){return e.id===`copy`&&d(t.filter(e=>e.role!==V8.Reasoning).map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content||``)).join(`
|
|
3485
3485
|
`)),n.onAgentAction?.call(n,e,t)});return function(t,n){return e.apply(this,arguments)}}(),b=function(){var e=r5(function*(e,t){var r;(r=n.onUserAction)==null||r.call(n,e,t)});return function(t,n){return e.apply(this,arguments)}}(),x=function(){var e=r5(function*(e,t,r){var i;(i=n.onUserInputConfirm)==null||i.call(n,e,t,r)});return function(t,n,r){return e.apply(this,arguments)}}(),S=function(){var e=r5(function*(e,t){var r;(r=n.onUserShortcutConfirm)==null||r.call(n,e,t)});return function(t,n){return e.apply(this,arguments)}}();return(r,s)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{ref_key:`messageContainerRef`,ref:a,class:`ai-message-container`},[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(h.value,(a,o)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{id:a.uid,key:o,class:`message-group`,"data-message-group-id":a.uid,style:(0,t.normalizeStyle)({backgroundColor:a.checked?`#f5f7fa`:`transparent`}),onMouseenter:e=>g(a),onMouseleave:e=>_(a,e)},[(0,t.renderSlot)(r.$slots,`group`,(0,t.mergeProps)({ref_for:!0},{group:a}),()=>[e.enableSelection&&a.type!==(0,t.unref)(V8).Loading?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(cs),{key:0,class:`message-group-checkbox`,"model-value":a.checked,"onUpdate:modelValue":e=>v(a,e)},null,8,[`model-value`,`onUpdate:modelValue`])):(0,t.createCommentVNode)(``,!0),(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`message-group-messages`,{"message-group-enabled-selection":e.renderMode===(0,t.unref)(G8).Share||e.enableSelection&&a.type!==(0,t.unref)(V8).Loading}]),style:(0,t.normalizeStyle)({width:e.enableSelection&&a.type!==(0,t.unref)(V8).Loading?`calc(100% - 16px)`:`100%`})},[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(a.messages,(a,o)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:o,class:`ai-message-item`,"data-message-id":i(a)},[(0,t.renderSlot)(r.$slots,`default`,(0,t.mergeProps)({ref_for:!0},{message:a,messageToolsStatus:e.messageToolsStatus,onInterruptResume:n.onInterruptResume}),()=>[((0,t.openBlock)(),(0,t.createBlock)(m9,{key:o,message:a,"message-tools-status":e.messageToolsStatus,"on-action":e=>b(e,a),"on-input-confirm":(e,t)=>x(a,e,t),"on-interrupt-resume":n.onInterruptResume,"on-shortcut-confirm":e=>S(a,e),"tippy-options":e.messageToolsTippyOptions},(0,t.createSlots)({_:2},[r.$slots.answeredQuestion?{name:`answeredQuestion`,fn:(0,t.withCtx)(e=>[(0,t.renderSlot)(r.$slots,`answeredQuestion`,(0,t.mergeProps)({ref_for:!0},e))]),key:`0`}:void 0]),1032,[`message`,`message-tools-status`,`on-action`,`on-input-confirm`,`on-interrupt-resume`,`on-shortcut-confirm`,`tippy-options`]))])],8,oVt))),128)),e.renderMode!==(0,t.unref)(G8).Share&&!(e.enableSelection&&a.type!==(0,t.unref)(V8).Loading)&&!a.pause&&a.type===(0,t.unref)(V8).Assistant&&e.messageToolsStatus!==(0,t.unref)(Y7).Hidden?((0,t.openBlock)(),(0,t.createBlock)(GRt,{key:0,"message-tools":p.value,"message-tools-status":e.messageToolsStatus,"on-action":e=>y(e,a.messages),style:(0,t.normalizeStyle)({visibility:a.isHover?`visible`:`hidden`}),"tippy-options":n.messageToolsTippyOptions,"update-tools":m.value,onFeedback:(e,t,r)=>n.onAgentFeedback?.call(n,e,a.messages,t,r)},null,8,[`message-tools`,`message-tools-status`,`on-action`,`style`,`tippy-options`,`update-tools`,`onFeedback`])):(0,t.createCommentVNode)(``,!0)],6)])],44,aVt))),128)),(0,t.createElementVNode)(`div`,{ref_key:`messageContainerBottomRef`,ref:o,class:`message-container-bottom`,tabindex:`0`},null,512),(0,t.createElementVNode)(`div`,sVt,[(0,t.withDirectives)((0,t.createVNode)(hkt,{loading:e.messageStatus===(0,t.unref)(H8).StopLoading,title:e.messageStatus===(0,t.unref)(H8).StopLoading?(0,t.unref)(L8)(`正在停止`):(0,t.unref)(L8)(`停止生成`),onClick:s[0]||=e=>r.$emit(`stopStreaming`)},{icon:(0,t.withCtx)(()=>[(0,t.createVNode)((0,t.unref)(UOt))]),_:1},8,[`loading`,`title`]),[[t.vShow,e.renderMode!==(0,t.unref)(G8).Share&&(e.messageStatus===(0,t.unref)(H8).Streaming||e.messageStatus===(0,t.unref)(H8).StopLoading||e.messageStatus===(0,t.unref)(H8).Fetching||e.messageStatus===(0,t.unref)(H8).Pending)]]),(0,t.withDirectives)((0,t.createVNode)(hkt,{title:(0,t.unref)(L8)(`返回底部`),onClick:s[1]||=()=>(0,t.unref)(l)(`smooth`)},{icon:(0,t.withCtx)(()=>[(0,t.createVNode)((0,t.unref)(okt))]),_:1},8,[`title`]),[[t.vShow,(0,t.unref)(u)]])])],512))}}),lVt={class:`ai-execution-summary`},uVt={class:`ai-execution-summary-header`},dVt={class:`ai-execution-summary-content`},fVt=[`onMouseenter`],pVt={class:`content-item-header`},mVt={class:`content-item-title`},hVt={class:`content-item-messages`},gVt={key:0,class:`timeline-line`},_Vt={key:1,class:`ai-execution-summary-content-empty`},vVt={class:`ai-execution-summary-content-empty-text`},yVt=(0,t.defineComponent)({__name:`execution-summary`,props:{messageGroups:{}},emits:[`locateMessageGroup`,`updateKeyword`],setup(e,{emit:n}){let r=n,i=d5(),{keyword:a}=gAt(),o=(0,t.shallowRef)(void 0),s=e=>{if(!e)return``;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},l=e=>{r(`locateMessageGroup`,e.uid,e)},u=()=>{a.value=``,r(`updateKeyword`,``)};return(n,d)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,lVt,[(0,t.createElementVNode)(`div`,uVt,[(0,t.createVNode)((0,t.unref)(ts),{modelValue:(0,t.unref)(a),"onUpdate:modelValue":[d[0]||=e=>(0,t.isRef)(a)?a.value=e:null,d[1]||=e=>r(`updateKeyword`,e)],class:`ai-execution-summary-header-input`,clearable:``,placeholder:(0,t.unref)(L8)(`搜索 关键字`)},null,8,[`modelValue`,`placeholder`])]),(0,t.createElementVNode)(`div`,dVt,[e.messageGroups.length?((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,{key:0},(0,t.renderList)(e.messageGroups,(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:n.uid,class:`ai-execution-summary-content-item`,onMouseenter:e=>o.value=n.uid,onMouseleave:d[2]||=e=>o.value=void 0},[(0,t.createElementVNode)(`div`,pVt,[d[3]||=(0,t.createElementVNode)(`span`,{class:`timeline-dot`},null,-1),(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`span`,mVt,[(0,t.createTextVNode)((0,t.toDisplayString)(typeof n.userMessageTitle==`number`?s(n.userMessageTitle):n.userMessageTitle),1)])),[[(0,t.unref)(f5),$({},(0,t.unref)(i))]]),(0,t.withDirectives)((0,t.createVNode)((0,t.unref)(Wo),{class:`content-item-locate`,text:``,theme:`primary`,onClick:e=>l(n)},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`在对话中定位`)),1)]),_:1},8,[`onClick`]),[[t.vShow,o.value===n.uid]])]),(0,t.createElementVNode)(`div`,hVt,[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(n.messages,(e,n)=>((0,t.openBlock)(),(0,t.createBlock)(m9,{key:n,message:e},null,8,[`message`]))),128))]),r<e.messageGroups.length-1?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,gVt)):(0,t.createCommentVNode)(``,!0)],40,fVt))),128)):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,_Vt,[(0,t.createVNode)((0,t.unref)(Js),{class:`empty-exception`,type:`empty`}),(0,t.createElementVNode)(`div`,vVt,[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(a)?(0,t.unref)(L8)(`搜索结果为空`):(0,t.unref)(L8)(`暂无数据`))+` `,1),(0,t.unref)(a)?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Wo),{key:0,text:``,theme:`primary`,onClick:u},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`清空搜索`)),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])]))])]))}}),bVt={class:`ai-selection-footer`},xVt={class:`ai-selection-footer-left`},SVt={class:`select-all-text`},CVt={class:`ai-selection-footer-right`},wVt=(0,t.defineComponent)({__name:`selection-footer`,props:{isAllSelected:{type:Boolean},loading:{type:Boolean},selectedCount:{}},emits:[`cancel`,`confirm`,`toggle-all`],setup(e,{emit:n}){let r=n;return(n,i)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,bVt,[(0,t.createElementVNode)(`div`,xVt,[(0,t.createVNode)((0,t.unref)(cs),{"model-value":e.isAllSelected,"onUpdate:modelValue":i[0]||=e=>r(`toggle-all`,e)},null,8,[`model-value`]),(0,t.createElementVNode)(`span`,SVt,(0,t.toDisplayString)((0,t.unref)(L8)(`全选`)),1)]),(0,t.createElementVNode)(`div`,CVt,[(0,t.createVNode)((0,t.unref)(Wo),{disabled:e.loading,onClick:i[1]||=e=>r(`cancel`)},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`取消`)),1)]),_:1},8,[`disabled`]),(0,t.createVNode)((0,t.unref)(Wo),{disabled:e.selectedCount===0,loading:e.loading,theme:`primary`,onClick:i[2]||=e=>r(`confirm`)},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`确定`)),1)]),_:1},8,[`disabled`,`loading`])])]))}}),TVt=[`data-ai-size`],EVt={key:0,class:`ai-chat-container-loading`},DVt={class:`screen-wrapper`},OVt={key:1,class:`ai-welcome-content`},kVt={class:`ai-welcome-title`},AVt={key:0,class:`ai-welcome-remark`},jVt=(0,t.defineComponent)({__name:`chat-container`,props:(0,t.mergeModels)({chatLoading:{type:Boolean},commonTippyOptions:{},executionTabVisible:{type:Boolean,default:!0},getSideRenderComponent:{},getSideTabRenderComponent:{},onArtifactClick:{},onCustomTabChange:{},openingRemark:{},placement:{default:`left`},resizeProps:{},size:{default:`small`},welcomeTitle:{},defaultUploadFiles:{},inputMaxHeight:{},messageStatus:{},models:{},modelValue:{},onSendMessage:{},onStopSending:{},onUpload:{},placeholder:{},prompts:{},resources:{},sendDisabledTip:{},shortcutId:{},shortcuts:{},skills:{},supportUpload:{type:Boolean},tippyOptions:{},messages:{},messageTools:{},messageToolsStatus:{},onAgentAction:{},onAgentFeedback:{},onInterruptResume:{},onUserAction:{},renderMode:{},updateTools:{},onUserInputConfirm:{},onUserShortcutConfirm:{}},{renderMode:{required:!1,default:G8.Chat},renderModeModifiers:{},selectedShortcut:{required:!1},selectedShortcutModifiers:{},cite:{required:!1,default:``},citeModifiers:{},selectedModel:{required:!1},selectedModelModifiers:{}}),emits:(0,t.mergeModels)([`selectShortcut`,`deleteShortcut`,`update:modelValue`,`modelChange`,`stopStreaming`,`shortcutClose`,`shortcutSubmit`,`confirmShare`,`collapseChange`],[`update:renderMode`,`update:selectedShortcut`,`update:cite`,`update:selectedModel`]),setup(e,{expose:n,emit:r}){let i=ghe.TabPanel,a=e,o=(0,t.useModel)(e,`renderMode`),s=(0,t.useTemplateRef)(`fullScreenRef`),{isFullScreen:l,enter:u,exit:d}=eAt(s);_At({renderMode:o});let f=(0,t.computed)(()=>$($({collapsible:!1,immediate:!0,min:400},a.resizeProps),{},{placement:a.placement})),p=(0,t.computed)(()=>a.getSideRenderComponent?.call(a,t.h,b.value.data?.props??{})??b.value.data?.component);nAt({size:(0,t.computed)(()=>a.size??`small`),supportUpload:(0,t.computed)(()=>a.supportUpload??!1)}),(0,t.watch)(()=>a.size??`small`,e=>{typeof document<`u`&&(document.body.dataset.aiSize=e)},{immediate:!0});let m=(0,t.useModel)(e,`selectedShortcut`),h=(0,t.useModel)(e,`cite`),g=(0,t.useModel)(e,`selectedModel`),_=r;yAt({tippyOptions:(0,t.computed)(()=>a.commonTippyOptions??{})});let{displayTabs:v,tabs:y,selectedTab:b,isCollapse:x,addCustomTab:S,ensureCustomTab:C,removeCustomTab:w,selectCustomTab:T,resetCustomTab:E}=Qkt({executionTabVisible:()=>a.executionTabVisible,onTabChange:function(){var e=r5(function*(e){if(e.name===`file-artifact`)return;let t=b.value.data?.props||{loading:!0,data:{}};b.value.data=$($({},b.value.data),{},{props:t});let n=yield a.onCustomTabChange?.call(a,e);b.value.data=$($({},b.value.data),{},{props:$($({},t),{},{loading:!1,data:n})})});return function(t){return e.apply(this,arguments)}}()}),D=()=>{C({closable:!1,label:L8(`文件产物`),name:o5,order:-1})},O=(0,t.shallowRef)(``),k=(0,t.ref)([]),A=(0,t.shallowRef)(),j=(0,t.shallowRef)((()=>{let e=a.resizeProps?.initialDivide;return typeof e==`number`?e:400})()),M=(0,t.computed)(()=>`calc(100% - ${j.value}px)`),{messageGroups:N,executionGroups:P,sessionArtifacts:F,isShareMode:I,isAllSelected:L,onToggleShareAll:R,onCancelShare:ee,onConfirmShare:z,pendingApprovalTipText:B,activeUserQuestionInterrupt:V}=dAt({keyword:O,messages:(0,t.computed)(()=>a.messages),renderMode:(0,t.computed)(()=>o.value),selectedUserMessages:k}),te=(0,t.computed)(()=>y.value.some(e=>e.name===o5)),{activeArtifactId:ne,setActiveArtifactId:re}=Ukt({getOnArtifactClick:()=>a.onArtifactClick,onOpen:()=>{S({closable:!1,label:L8(`文件产物`),name:o5,order:-1})}});(0,t.watch)(F,e=>{if(!e.length){w(o5),re(``);return}D(),e.some(e=>e.outputId===ne.value)||re(e[0].outputId)},{immediate:!0}),(0,t.watch)(x,e=>{e&&(O.value=``,j.value=0),_(`collapseChange`,e,j.value)}),(0,t.watch)(()=>P.value,e=>{!e.length&&!O.value&&!te.value&&E()},{immediate:!0,deep:!1});let ie=(0,t.computed)(()=>{var e;return a.messageStatus===H8.StopLoading?H8.StopLoading:(e=N.value)!=null&&e.some(e=>e.messages.some(e=>e.id===`__loading__`))?H8.Fetching:a.messageStatus}),ae=()=>{m.value=null,_(`shortcutClose`)},H=e=>{_(`shortcutSubmit`,e)},oe=()=>{_(`deleteShortcut`)},se=e=>{_(`selectShortcut`,e)},ce=(e,t)=>{_(`update:modelValue`,e,t)},le=function(){var e=r5(function*(e,t){let n=V.value;return a.onSendMessage?.call(a,e,t,n?{payload:XLt(n),interrupt:n}:void 0)});return function(t,n){return e.apply(this,arguments)}}(),ue=()=>{x.value=!x.value},de=e=>{if(!e)return;let t=document.getElementById(e);if(!t){let t=N.value.find(t=>t.messages.some(t=>t.uid===e));if(t){var n;(n=document.getElementById(t.uid))==null||n.scrollIntoView({behavior:`smooth`})}return}t.scrollIntoView({behavior:`smooth`})},fe=e=>e===`execution`?COt:e===`file-artifact`?jOt:wOt,pe=e=>{T(y.value.find(t=>t.name===e))},me=e=>{O.value=e},he=function(){var e=r5(function*(e,t){if(e.id===`share`||e.triggerSelection){A.value=e,I.value=!0;return}return a.onAgentAction?.call(a,e,t)});return function(t,n){return e.apply(this,arguments)}}(),ge=()=>{_(`confirmShare`,z(),A.value),(0,t.nextTick)(()=>{I.value=!1,k.value=[],A.value=void 0})},_e=()=>{ee(),A.value=void 0},ve=e=>{j.value=e};return(0,t.onUnmounted)(()=>{E(),typeof document<`u`&&delete document.body.dataset.aiSize}),n({selectedTab:b,addCustomTab:S,removeCustomTab:w,selectCustomTab:T,enterShareMode:()=>{I.value=!0},exitShareMode:()=>{_e()}}),(n,r)=>{var a;return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:`ai-chat-container`,"data-ai-size":e.size,style:(0,t.normalizeStyle)({"--resize-main-width":M.value,borderTopColor:(0,t.unref)(x)?`transparent`:`#eaebf0`})},[e.chatLoading?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,EVt,[(0,t.createVNode)(yLt)])):((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(nhe),(0,t.mergeProps)({key:1,class:[`ai-chat-container-resize-layout`,{"ai-is-collapse":(0,t.unref)(x)||(0,t.unref)(v).length>0&&!((a=O.value)!=null&&a.length)&&(0,t.unref)(P)?.length<1&&!te.value}]},f.value,{onResizing:ve}),{aside:(0,t.withCtx)(()=>{var n,a,o,f;return[!(0,t.unref)(x)&&(0,t.unref)(v).length>0&&((n=(0,t.unref)(P))!=null&&n.length||(a=O.value)!=null&&a.length||te.value)?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:0,ref_key:`fullScreenRef`,ref:s,class:`ai-full-screen-wrapper`},[(0,t.createVNode)((0,t.unref)(ghe),{active:(0,t.unref)(b).name,class:`ai-chat-container-tab`,"label-height":40,type:`unborder-card`,onChange:pe},{setting:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,DVt,[(0,t.createVNode)(p5,{class:`screen-btn`,"tippy-options":$($({},e.commonTippyOptions),{},{appendTo:(0,t.unref)(l)?s.value:e.commonTippyOptions?.appendTo,content:(0,t.unref)(l)?(0,t.unref)(L8)(`退出全屏`):(0,t.unref)(L8)(`全屏`)})},{default:(0,t.withCtx)(()=>[(0,t.unref)(l)?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(ckt),{key:1,onClick:(0,t.unref)(d)},null,8,[`onClick`])):((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(skt),{key:0,onClick:(0,t.unref)(u)},null,8,[`onClick`]))]),_:1},8,[`tippy-options`])])]),default:(0,t.withCtx)(()=>[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)((0,t.unref)(v),n=>((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(i),{key:n.name,class:`ai-chat-container-tab-panel`,label:()=>(0,t.h)(`div`,{class:`ai-execution-summary-label`,onVnodeMounted:e=>{if((0,t.unref)(b).name===n.name){var r;(r=e.el)==null||r.scrollIntoView({behavior:`smooth`})}}},e.getSideTabRenderComponent?.call(e,t.h,n,{removeCustomTab:(0,t.unref)(w)})??[(0,t.h)(fe(n.name),{class:`ai-execution-summary-icon`}),(0,t.withDirectives)((0,t.h)(`span`,{class:`ai-execution-summary-label-text`},n.label??``),[[(0,t.unref)(f5),$($({},e.commonTippyOptions),{},{text:n.label??``})]]),n.closable!==!1&&n.name!==(0,t.unref)(`execution`)?(0,t.h)((0,t.unref)(e5),{class:`ai-execution-close-icon`,onClick:()=>{(0,t.unref)(w)(n.name)}}):null]),name:n.name},null,8,[`label`,`name`]))),128))]),_:1},8,[`active`]),(0,t.unref)(b)?.name===(0,t.unref)(`execution`)&&e.executionTabVisible!==!1?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[(0,t.unref)(x)?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(yVt,{key:0,"message-groups":(0,t.unref)(P),style:{height:`calc(100% - 40px)`},onLocateMessageGroup:de,onUpdateKeyword:me},null,8,[`message-groups`]))],64)):(0,t.unref)(b)?.name===(0,t.unref)(`file-artifact`)?((0,t.openBlock)(),(0,t.createBlock)(qLt,{key:1,"active-id":(0,t.unref)(ne),artifacts:(0,t.unref)(F),style:{height:`calc(100% - 40px)`},onSelect:(0,t.unref)(re)},null,8,[`active-id`,`artifacts`,`onSelect`])):(0,t.createCommentVNode)(``,!0),(0,t.unref)(b)&&(0,t.unref)(b).name!==(0,t.unref)(`file-artifact`)?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:(0,t.unref)(b).name,class:`ai-chat-container-message-slot`},[((0,t.openBlock)(),(0,t.createBlock)((0,t.resolveDynamicComponent)(p.value),(0,t.mergeProps)({key:(0,t.unref)(b).name},(o=(0,t.unref)(b))==null||(o=o.data)==null?void 0:o.props),{locateButton:(0,t.withCtx)(()=>[(0,t.createVNode)((0,t.unref)(Wo),{class:`ai-locate-button`,size:`small`,text:``,theme:`primary`,onClick:r[0]||=e=>{var n;return de((n=(0,t.unref)(b))==null||(n=n.data)==null?void 0:n.messageUid)}},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)((0,t.unref)(L8)(`在对话中定位`)),1)]),_:1})]),_:1},16))])):(0,t.createCommentVNode)(``,!0)],512)):(0,t.createCommentVNode)(``,!0),(0,t.unref)(v).length>0&&((f=(0,t.unref)(P))!=null&&f.length||te.value)?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:1,class:(0,t.normalizeClass)([`collapse-button`,{"is-right":e.placement===`right`,"is-collapsed":(0,t.unref)(x)}]),onClick:ue},[(0,t.createVNode)((0,t.unref)($8))],2)):(0,t.createCommentVNode)(``,!0)]}),main:(0,t.withCtx)(()=>{var i,a,s;return[(i=e.messages)!=null&&i.length?(0,t.renderSlot)(n.$slots,`default`,(0,t.normalizeProps)((0,t.mergeProps)({key:0},{messages:e.messages,messageStatus:e.messageStatus,messageGroups:(0,t.unref)(N),selectedUserMessages:k.value,messageToolsStatus:e.messageToolsStatus,isShareMode:(0,t.unref)(I),commonTippyOptions:e.commonTippyOptions,handleAgentAction:he,onAgentFeedback:e.onAgentFeedback,onInterruptResume:e.onInterruptResume,onUserAction:e.onUserAction,onUserInputConfirm:e.onUserInputConfirm,onUserShortcutConfirm:e.onUserShortcutConfirm})),()=>{var i;return[(i=e.messages)!=null&&i.length?((0,t.openBlock)(),(0,t.createBlock)(cVt,{key:0,"selected-user-messages":k.value,"onUpdate:selectedUserMessages":r[1]||=e=>k.value=e,"enable-selection":(0,t.unref)(I),"message-groups":(0,t.unref)(N),"message-status":ie.value,"message-tools":e.messageTools,"message-tools-status":e.messageToolsStatus,"message-tools-tippy-options":e.commonTippyOptions,messages:e.messages,"on-agent-action":he,"on-agent-feedback":e.onAgentFeedback,"on-interrupt-resume":e.onInterruptResume,"on-user-action":e.onUserAction,"on-user-input-confirm":e.onUserInputConfirm,"on-user-shortcut-confirm":e.onUserShortcutConfirm,"render-mode":o.value,"update-tools":e.updateTools,onStopStreaming:r[2]||=e=>_(`stopStreaming`)},{group:(0,t.withCtx)(({group:e})=>[(0,t.renderSlot)(n.$slots,`group`,(0,t.normalizeProps)((0,t.guardReactiveProps)({group:e})))]),default:(0,t.withCtx)(({message:e,messageToolsStatus:r,onInterruptResume:i})=>[(0,t.renderSlot)(n.$slots,`message`,(0,t.normalizeProps)((0,t.guardReactiveProps)({message:e,messageToolsStatus:r,onInterruptResume:i})))]),_:3},8,[`selected-user-messages`,`enable-selection`,`message-groups`,`message-status`,`message-tools`,`message-tools-status`,`message-tools-tippy-options`,`messages`,`on-agent-feedback`,`on-interrupt-resume`,`on-user-action`,`on-user-input-confirm`,`on-user-shortcut-confirm`,`render-mode`,`update-tools`])):(0,t.createCommentVNode)(``,!0)]}):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,OVt,[(0,t.renderSlot)(n.$slots,`welcome`,(0,t.normalizeProps)((0,t.guardReactiveProps)({openingRemark:e.openingRemark,welcomeTitle:e.welcomeTitle})),()=>[(0,t.createVNode)((0,t.unref)(pOt)),(0,t.createElementVNode)(`h2`,kVt,(0,t.toDisplayString)(e.welcomeTitle??(0,t.unref)(L8)(`你好,我是小鲸`)),1),e.openingRemark?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,AVt,[(0,t.createVNode)(S7,{content:e.openingRemark},null,8,[`content`])])):(0,t.createCommentVNode)(``,!0)])])),o.value===(0,t.unref)(G8).Share?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:2},[(0,t.unref)(I)?((0,t.openBlock)(),(0,t.createBlock)(wVt,{key:0,"is-all-selected":(0,t.unref)(L),loading:!1,"selected-count":k.value.length,onCancel:_e,onConfirm:ge,onToggleAll:(0,t.unref)(R)},null,8,[`is-all-selected`,`selected-count`,`onToggleAll`])):!((a=m.value)==null||(a=a.components)==null)&&a.length?((0,t.openBlock)(),(0,t.createBlock)(Bkt,(0,t.mergeProps)({key:1},m.value,{class:{"is-welcome-overlay":!((s=e.messages)!=null&&s.length)},onClose:ae,onSubmit:H}),null,16,[`class`])):((0,t.openBlock)(),(0,t.createBlock)(iLt,{key:2,cite:h.value,"onUpdate:cite":r[3]||=e=>h.value=e,"selected-model":g.value,"onUpdate:selectedModel":r[4]||=e=>g.value=e,"message-status":ie.value,"model-value":e.modelValue,models:e.models,"on-send-message":le,"on-stop-sending":e.onStopSending,"on-upload":e.onUpload,placeholder:e.placeholder,prompts:e.prompts,resources:e.resources,"send-disabled-tip":(0,t.unref)(B),"shortcut-id":m.value?.id,shortcuts:e.shortcuts,skills:e.skills,"support-upload":e.supportUpload,"tippy-options":e.commonTippyOptions,onDeleteShortcut:oe,onModelChange:r[5]||=e=>_(`modelChange`,e),onSelectShortcut:se,"onUpdate:modelValue":ce},{interrupt:(0,t.withCtx)(()=>[(0,t.unref)(V)?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(kRt),{key:0,interrupt:(0,t.unref)(V),"on-resume":e.onInterruptResume},{question:(0,t.withCtx)(({question:e,qIndex:r,answer:i,setAnswer:a,confirm:o})=>[(0,t.renderSlot)(n.$slots,`interruptQuestion`,(0,t.normalizeProps)((0,t.guardReactiveProps)({question:e,qIndex:r,answer:i,setAnswer:a,confirm:o})))]),_:3},8,[`interrupt`,`on-resume`])):(0,t.createCommentVNode)(``,!0),(0,t.unref)(B)?((0,t.openBlock)(),(0,t.createBlock)(sLt,{key:1,content:(0,t.unref)(B)},null,8,[`content`])):(0,t.createCommentVNode)(``,!0)]),_:3},8,[`cite`,`selected-model`,`message-status`,`model-value`,`models`,`on-stop-sending`,`on-upload`,`placeholder`,`prompts`,`resources`,`send-disabled-tip`,`shortcut-id`,`shortcuts`,`skills`,`support-upload`,`tippy-options`]))],64))]}),_:3},16,[`class`]))],12,TVt)}}}),MVt={class:`ai-image-preview-group`};$($({},{name:`ImagePreviewGroup`}),{},{__name:`image-preview-group`,props:{maskClosable:{type:Boolean,default:!0},onDownload:{type:Function,default:void 0},showInfo:{type:Boolean,default:!1}},setup(e){let n=new Map,r=(0,t.shallowRef)(!1),i=(0,t.shallowRef)([]),a=(0,t.shallowRef)(0);return(0,t.provide)(AFt,{register:(e,t)=>{n.set(e,t)},unregister:e=>{n.delete(e)},preview:e=>{let t=[...n.keys()],o=t.map(e=>n.get(e)()),s=t.indexOf(e);i.value=o,a.value=s>=0?s:0,r.value=!0}}),(n,o)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,MVt,[(0,t.renderSlot)(n.$slots,`default`),r.value?((0,t.openBlock)(),(0,t.createBlock)(X7,{key:0,current:a.value,"onUpdate:current":o[0]||=e=>a.value=e,visible:r.value,"onUpdate:visible":o[1]||=e=>r.value=e,images:i.value,"mask-closable":e.maskClosable,"on-download":e.onDownload,"show-info":e.showInfo},(0,t.createSlots)({_:2},[n.$slots.extra?{name:`extra`,fn:(0,t.withCtx)(()=>[(0,t.renderSlot)(n.$slots,`extra`)]),key:`0`}:void 0]),1032,[`current`,`visible`,`images`,`mask-closable`,`on-download`,`show-info`])):(0,t.createCommentVNode)(``,!0)]))}});var NVt=[`alt`,`src`],PVt={key:1,class:`ai-image-error`};$($({},{name:`AiImage`}),{},{__name:`image`,props:{alt:{default:``},height:{default:void 0},lazy:{type:Boolean,default:!1},onDownload:{},preview:{type:Boolean,default:!0},previewProps:{default:void 0},showInfo:{type:Boolean,default:!1},src:{},width:{default:void 0}},emits:[`load`,`error`,`preview`],setup(e,{expose:n,emit:r}){let i=e,a=r,o=Symbol(),s=(0,t.inject)(AFt,null),l=(0,t.ref)(),u=(0,t.shallowRef)(`loading`),d=(0,t.shallowRef)(!1),f=(0,t.shallowRef)(!i.lazy),p=null,m=(0,t.computed)(()=>i.previewProps?.src||i.src),h=()=>{let e=i.previewProps;return{url:m.value,name:e?.name,width:e?.width,height:e?.height,resolution:e?.resolution,downloadUrl:e?.downloadUrl}},g=(0,t.shallowRef)(0),_=(0,t.computed)(()=>{if(!i.lazy||f.value){let e=i.src;return g.value===0?e:`${e}${e.includes(`?`)?`&`:`?`}_t=${g.value}`}return``}),v=(0,t.computed)(()=>[h()]),y=(0,t.computed)(()=>{let e={};return i.width&&(e.width=typeof i.width==`number`?`${i.width}px`:i.width),i.height&&(e.height=typeof i.height==`number`?`${i.height}px`:i.height),e}),b={width:`100%`,height:`100%`,objectFit:`cover`},x=e=>{u.value=`loaded`,a(`load`,e)},S=e=>{u.value=`error`,a(`error`,e)},C=()=>{u.value=`loading`,g.value=Date.now()},w=()=>{!i.preview||u.value!==`loaded`||(s?s.preview(o):d.value=!0,a(`preview`))},T=()=>{!i.lazy||!l.value||(p=new IntersectionObserver(e=>{var t;(t=e[0])!=null&&t.isIntersecting&&(f.value=!0,p?.disconnect(),p=null)},{rootMargin:`200px`}),p.observe(l.value))},E=()=>{p?.disconnect(),p=null};return(0,t.onMounted)(()=>{T(),s?.register(o,h)}),(0,t.onBeforeUnmount)(()=>{E(),s?.unregister(o)}),n({previewVisible:d}),(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{ref_key:`containerRef`,ref:l,class:(0,t.normalizeClass)([`ai-image`,{"ai-image--error":u.value===`error`,"ai-image--preview":e.preview&&u.value===`loaded`}]),style:(0,t.normalizeStyle)(y.value),onClick:w},[u.value!==`error`&&_.value?((0,t.openBlock)(),(0,t.createElementBlock)(`img`,{key:0,alt:e.alt,class:`ai-image-inner`,src:_.value,style:b,onError:S,onLoad:x},null,40,NVt)):(0,t.createCommentVNode)(``,!0),u.value===`error`?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,PVt,[(0,t.createVNode)((0,t.unref)(_Ot),{class:`ai-image-error-icon`})])):(0,t.createCommentVNode)(``,!0),u.value===`error`?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:2,class:`ai-image-error-overlay`,onClick:C},[(0,t.createVNode)((0,t.unref)(BOt),{class:`ai-image-reload-icon`}),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(L8)(`重新加载`)),1)])):(0,t.createCommentVNode)(``,!0),(0,t.renderSlot)(n.$slots,`default`),!(0,t.unref)(s)&&e.preview&&d.value?((0,t.openBlock)(),(0,t.createBlock)(X7,{key:3,visible:d.value,"onUpdate:visible":r[0]||=e=>d.value=e,images:v.value,"on-download":e.onDownload,"show-info":e.showInfo},(0,t.createSlots)({_:2},[n.$slots.extra?{name:`extra`,fn:(0,t.withCtx)(()=>[(0,t.renderSlot)(n.$slots,`extra`)]),key:`0`}:void 0]),1032,[`visible`,`images`,`on-download`,`show-info`])):(0,t.createCommentVNode)(``,!0)],6))}});var FVt=`data:image/png;base64,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`,h9=function(e){return e.ArtifactsGenerated=`artifacts_generated`,e.FlowAgent=`flow_agent`,e.KnowledgeRag=`knowledge_rag`,e.ReferenceDocument=`reference_document`,e.Info=`info`,e.Interrupt=`interrupt`,e}({}),g9=function(e){return e.Activity=`activity`,e.Assistant=`assistant`,e.Developer=`developer`,e.Guide=`guide`,e.Hidden=`hidden`,e.HiddenAssistant=`hidden-assistant`,e.HiddenGuide=`hidden-guide`,e.HiddenSystem=`hidden-system`,e.HiddenUser=`hidden-user`,e.Info=`info`,e.Pause=`pause`,e.Placeholder=`placeholder`,e.Reasoning=`reasoning`,e.System=`system`,e.TemplateAssistant=`template-assistant`,e.TemplateGuide=`template-guide`,e.TemplateHidden=`template-hidden`,e.TemplateSystem=`template-system`,e.TemplateUser=`template-user`,e.Tool=`tool`,e.User=`user`,e.Interrupt=`interrupt`,e}({}),_9=function(e){return e.Complete=`complete`,e.Error=`error`,e.Pending=`pending`,e.Stop=`stop`,e.Streaming=`streaming`,e}({}),v9=function(e){return e.Binary=`binary`,e.Function=`function`,e.Text=`text`,e}({}),y9=function(e){return e.FlowNodeRetry=`flow_node_retry`,e.FlowNodeSkip=`flow_node_skip`,e.ApprovalCancel=`approval_cancel`,e}({}),IVt=()=>`temp_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,LVt=e=>{let n=(0,t.ref)([]),r=(0,t.ref)(!1),i=(0,t.ref)(!1),a=t=>(r.value=!0,e.http?.message.getMessages(t).then(e=>{n.value=e}).finally(()=>{r.value=!1})),o=()=>p(n.value),s=e=>{n.value=n.value.map(t=>t.messageId===e.messageId?e:t)},l=e=>{n.value.push(e)},u=()=>n.value.findLast(e=>[_9.Pending,_9.Streaming].includes(e.status)),d=e=>n.value.find(t=>t.messageId===e),f=async t=>{let r=IVt(),i={...t,id:r,messageId:r};n.value.push(i);try{let i=await e.http?.message.plusMessage(t);if(i){let e=n.value.findIndex(e=>e.messageId===r);if(e!==-1){let r={...i,...`property`in t&&t.property?{property:t.property}:{}};n.value[e]=r}}}catch(e){let t=n.value.findIndex(e=>e.messageId===r);throw t!==-1&&(n.value[t]={...n.value[t],status:_9.Error}),e}},p=async t=>{let r=t.reduce((e,t)=>(t.role===g9.User&&e.push(t.id),e),[]);if(r.length<=0)return;let a=[...n.value];n.value=n.value.filter(e=>!t.includes(e)),i.value=!0;try{await e.http?.message.batchDeleteMessages(r)}catch(e){throw n.value=a,e}finally{i.value=!1}};return{list:n,isListLoading:r,isDeleteLoading:i,getMessages:a,clearMessages:o,getCurrentLoadingMessage:u,getMessageByMessageId:d,modifyMessage:s,plusMessage:l,createAndPlusMessage:f,deleteMessages:p,shareMessages:async(t,n,r)=>{let i=n.reduce((e,t)=>(t.role===g9.User&&e.push(t.id),e),[]);if(!(i.length<=0))return e.http?.message.shareMessages(t,i,r)},getFlowAgentTaskInfo:t=>e.http?.message.getFlowAgentTaskInfo(t),getFlowAgentTaskNodeInfo:(t,n)=>e.http?.message.getFlowAgentTaskNodeInfo(t,n),reset:()=>{n.value=[],r.value=!1,i.value=!1}}},b9=function(e){return e.ArtifactsGenerated=`artifacts_generated`,e.FlowAgentEnd=`flow_agent_end`,e.FlowAgentResult=`flow_agent_result`,e.FlowAgentStart=`flow_agent_start`,e.FlowAgentUpdate=`flow_agent_update`,e.FlowAgentRestart=`flow_agent_restart`,e.Info=`info`,e.KnowledgeRagEnd=`knowledge_rag_end`,e.KnowledgeRagResult=`knowledge_rag_result`,e.KnowledgeRagStart=`knowledge_rag_start`,e.KnowledgeRagTextContent=`knowledge_rag_text_content`,e.ReferenceDocument=`reference_document`,e.TempMessage=`temp_message`,e.ApprovalResult=`approval_result`,e}({}),x9=function(e){return e.ActivityDelta=`ACTIVITY_DELTA`,e.ActivitySnapshot=`ACTIVITY_SNAPSHOT`,e.Custom=`CUSTOM`,e.MessagesSnapshot=`MESSAGES_SNAPSHOT`,e.Raw=`RAW`,e.RunError=`RUN_ERROR`,e.RunFinished=`RUN_FINISHED`,e.RunStarted=`RUN_STARTED`,e.StateDelta=`STATE_DELTA`,e.StateSnapshot=`STATE_SNAPSHOT`,e.StepFinished=`STEP_FINISHED`,e.StepStarted=`STEP_STARTED`,e.TextMessageChunk=`TEXT_MESSAGE_CHUNK`,e.TextMessageContent=`TEXT_MESSAGE_CONTENT`,e.TextMessageEnd=`TEXT_MESSAGE_END`,e.TextMessageStart=`TEXT_MESSAGE_START`,e.ThinkingEnd=`THINKING_END`,e.ThinkingStart=`THINKING_START`,e.ThinkingTextMessageContent=`THINKING_TEXT_MESSAGE_CONTENT`,e.ThinkingTextMessageEnd=`THINKING_TEXT_MESSAGE_END`,e.ThinkingTextMessageStart=`THINKING_TEXT_MESSAGE_START`,e.ToolCallArgs=`TOOL_CALL_ARGS`,e.ToolCallChunk=`TOOL_CALL_CHUNK`,e.ToolCallEnd=`TOOL_CALL_END`,e.ToolCallResult=`TOOL_CALL_RESULT`,e.ToolCallStart=`TOOL_CALL_START`,e}({}),RVt=function(e){return e.Blocked=`BLOCKED`,e.Created=`CREATED`,e.Failed=`FAILED`,e.Finished=`FINISHED`,e.LoopReady=`LOOP_READY`,e.Ready=`READY`,e.Revoked=`REVOKED`,e.RollBackFailed=`ROLL_BACK_FAILED`,e.RollBackSuccess=`ROLL_BACK_SUCCESS`,e.RollingBack=`ROLLING_BACK`,e.Running=`RUNNING`,e.Suspended=`SUSPENDED`,e}({}),S9=function(e){return e.Success=`success`,e.Interrupt=`interrupt`,e}({}),zVt=function(e){return e.Abandoned=`abandoned`,e.Approved=`approved`,e.Cancelled=`cancelled`,e.Draft=`draft`,e.Expired=`expired`,e.Rejected=`rejected`,e.Pending=`pending`,e}({}),C9=function(e){return e.Resolved=`resolved`,e.Cancelled=`cancelled`,e}({}),w9=class{messageModule;onDoneCallback;onErrorCallback;onMessageCallback;onStartCallback;constructor(e){this.onDoneCallback=e?.onDone,this.onErrorCallback=e?.onError,this.onMessageCallback=e?.onMessage,this.onStartCallback=e?.onStart}handleActivityDeltaEvent(e){}handleActivitySnapshotEvent(e){if(e.activityType===h9.Info){let t=this.messageModule.getMessageByMessageId(e.messageId);t?.role===g9.Info&&(t.content=e.content);return}if(e.activityType===h9.Interrupt){let t=this.messageModule.getCurrentLoadingMessage();t?.role===g9.Interrupt&&(t.content=e.content,t.status=_9.Complete)}}handleArtifactsGeneratedCustomEvent(e){let t=this.messageModule.list.value.findLast(e=>e.role===g9.Assistant);if(t){let n=e.value;t.property??={},t.property.artifacts=n.artifacts}}handleCustomEvent(e){switch(e.name){case b9.ArtifactsGenerated:this.handleArtifactsGeneratedCustomEvent(e);break;case b9.FlowAgentStart:this.handleFlowAgentStartCustomEvent(e);break;case b9.FlowAgentResult:this.handleFlowAgentResultCustomEvent(e);break;case b9.FlowAgentEnd:this.handleFlowAgentEndCustomEvent(e);break;case b9.FlowAgentRestart:this.handleFlowAgentRestartCustomEvent(e);break;case b9.ReferenceDocument:this.handleReferenceDocumentCustomEvent(e);break;case b9.KnowledgeRagStart:this.handleKnowledgeRagStartCustomEvent(e);break;case b9.KnowledgeRagTextContent:this.handleKnowledgeRagTextContentCustomEvent(e);break;case b9.KnowledgeRagResult:this.handleKnowledgeRagResultCustomEvent(e);break;case b9.KnowledgeRagEnd:this.handleKnowledgeRagEndCustomEvent(e);break;case b9.TempMessage:this.handleTempMessageCustomEvent(e);break;case b9.ApprovalResult:this.handleApprovalResultCustomEvent(e);break;case b9.FlowAgentUpdate:this.handleFlowAgentUpdateCustomEvent(e);break;case b9.Info:this.handleInfoCustomEvent(e);break;default:break}}handleFlowAgentEndCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();if(t&&t.role===g9.Activity&&t.activityType===h9.FlowAgent){t.status=_9.Complete;let n=e.value;this.messageModule.plusMessage({role:g9.Assistant,content:n.map(e=>e.task_outputs.join(`
|
|
3486
3486
|
`)).join(`
|
|
3487
|
-
`),status:_9.Complete})}}handleFlowAgentRestartCustomEvent(e){let t=e.value;this.messageModule.list.value.forEach(e=>{e.role===g9.Activity&&e.activityType===h9.FlowAgent&&e.content[0].task_id===t[0].task_id&&(e.status=_9.Streaming)})}handleFlowAgentResultCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.FlowAgent&&(t.content=e.value)}handleFlowAgentStartCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Activity,activityType:h9.FlowAgent,content:t.map(e=>({nodes:{},task_id:e.task_id,task_name:``,task_outputs:[],task_state:RVt.Created})),status:_9.Streaming})}handleFlowAgentUpdateCustomEvent(e){let t=e.value;this.messageModule.list.value.forEach(e=>{e.role===g9.Activity&&e.activityType===h9.FlowAgent&&e.content[0].task_id===t[0].task_id&&(e.content=t)})}handleInfoCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Info,messageId:t.messageId,content:t.content,status:_9.Complete})}handleKnowledgeRagEndCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag&&(t.status=_9.Complete)}handleKnowledgeRagResultCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag&&(t.content.referenceDocument=e.value)}handleKnowledgeRagStartCustomEvent(e){this.messageModule.plusMessage({role:g9.Activity,activityType:h9.KnowledgeRag,content:{content:``,referenceDocument:[]},status:_9.Streaming})}handleKnowledgeRagTextContentCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();if(t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag){let n=e.value;t.content.content=n.cover?n.chunk.content:t.content.content+n.chunk.content}}handleMessagesSnapshotEvent(e){e.messages&&e.messages.length>0&&(this.messageModule.list.value=e.messages)}handleRawEvent(e){}handleReferenceDocumentCustomEvent(e){this.messageModule.plusMessage({role:g9.Activity,activityType:h9.ReferenceDocument,content:e.value,status:_9.Complete})}handleRunErrorEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&(t.status=_9.Complete),this.messageModule.plusMessage({role:g9.Assistant,content:e.message,status:_9.Error})}handleRunFinishedEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&(t.status=_9.Complete),e.outcome?.type===S9.Interrupt&&this.messageModule.plusMessage({role:g9.Interrupt,content:e,status:_9.Pending}),e.outcome?.type===S9.Success&&t?.role===g9.Interrupt&&(t.content=e)}handleRunStartedEvent(e){}handleStateDeltaEvent(e){}handleStateSnapshotEvent(e){}handleStepFinishedEvent(e){}handleStepStartedEvent(e){}handleTempMessageCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Assistant,content:t.message,status:t.status})}handleApprovalResultCustomEvent(e){let t=e.value,n=this.messageModule.getCurrentLoadingMessage();n&&(n.content=t,n.status=_9.Complete)}handleTextMessageChunkEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t?t.content+=e.delta||``:this.messageModule.plusMessage({role:e.role,content:e.delta||``,status:_9.Complete,messageId:e.messageId})}handleTextMessageContentEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);t&&(t.content+=e.delta)}handleTextMessageEndEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);t&&(t.status=_9.Complete)}handleTextMessageStartEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);if(t){t.content=``,t.status=_9.Streaming;return}this.messageModule.plusMessage({role:e.role,content:``,status:_9.Streaming,messageId:e.messageId})}handleThinkingEndEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&(t.duration=e.duration,t.status=_9.Complete)}handleThinkingStartEvent(e){this.messageModule.plusMessage({role:g9.Reasoning,content:[],status:_9.Streaming})}handleThinkingTextMessageContentEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&(t.content[t.content.length-1]+=e.delta)}handleThinkingTextMessageEndEvent(e){}handleThinkingTextMessageStartEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&t.content.push(``)}handleToolCallArgsEvent(e){this.messageModule.list.value.forEach(t=>{t.role===g9.Assistant&&t.toolCalls&&t.toolCalls.forEach(t=>{t.id===e.toolCallId&&(t.function.arguments+=e.delta)})})}handleToolCallChunkEvent(e){}handleToolCallEndEvent(e){this.messageModule.list.value.forEach(t=>{t.role===g9.Assistant&&t.toolCalls&&t.toolCalls.some(t=>t.id===e.toolCallId)&&(t.status=_9.Complete)})}handleToolCallResultEvent(e){this.messageModule.plusMessage({role:g9.Tool,content:e.content,duration:e.duration,status:e.isError?_9.Error:_9.Complete,toolCallId:e.toolCallId,messageId:e.messageId})}handleToolCallStartEvent(e){this.messageModule.plusMessage({role:g9.Assistant,content:``,status:_9.Streaming,toolCalls:[{id:e.toolCallId,type:v9.Function,function:{mcpName:e.mcpName,name:e.toolCallName,arguments:``,description:e.description}}]})}injectMessageModule(e){this.messageModule=e}onDone(){this.onDoneCallback?.()}onError(e){this.messageModule?.plusMessage({role:g9.Assistant,content:e.message,status:_9.Error}),this.onErrorCallback?.(e)}onMessage(e){let t=e;switch(this.onMessageCallback?.(t),t.type){case x9.ActivityDelta:this.handleActivityDeltaEvent(t);break;case x9.ActivitySnapshot:this.handleActivitySnapshotEvent(t);break;case x9.Custom:this.handleCustomEvent(t);break;case x9.MessagesSnapshot:this.handleMessagesSnapshotEvent(t);break;case x9.Raw:this.handleRawEvent(t);break;case x9.RunError:this.handleRunErrorEvent(t);break;case x9.RunFinished:this.handleRunFinishedEvent(t);break;case x9.RunStarted:this.handleRunStartedEvent(t);break;case x9.StateDelta:this.handleStateDeltaEvent(t);break;case x9.StateSnapshot:this.handleStateSnapshotEvent(t);break;case x9.StepFinished:this.handleStepFinishedEvent(t);break;case x9.StepStarted:this.handleStepStartedEvent(t);break;case x9.TextMessageChunk:this.handleTextMessageChunkEvent(t);break;case x9.TextMessageContent:this.handleTextMessageContentEvent(t);break;case x9.TextMessageEnd:this.handleTextMessageEndEvent(t);break;case x9.TextMessageStart:this.handleTextMessageStartEvent(t);break;case x9.ThinkingEnd:this.handleThinkingEndEvent(t);break;case x9.ThinkingStart:this.handleThinkingStartEvent(t);break;case x9.ThinkingTextMessageContent:this.handleThinkingTextMessageContentEvent(t);break;case x9.ThinkingTextMessageEnd:this.handleThinkingTextMessageEndEvent(t);break;case x9.ThinkingTextMessageStart:this.handleThinkingTextMessageStartEvent(t);break;case x9.ToolCallArgs:this.handleToolCallArgsEvent(t);break;case x9.ToolCallChunk:this.handleToolCallChunkEvent(t);break;case x9.ToolCallEnd:this.handleToolCallEndEvent(t);break;case x9.ToolCallResult:this.handleToolCallResultEvent(t);break;case x9.ToolCallStart:this.handleToolCallStartEvent(t);break;default:break}}onStart(){this.onStartCallback?.()}},T9=function(e){return e.Running=`running`,e.Finished=`finished`,e.Failed=`failed`,e.Cancelled=`cancelled`,e}({}),BVt=5,VVt=1e3,HVt=8e3,UVt=e=>Math.min(VVt*2**(e-1),HVt),WVt=e=>{if(e.name===`AbortError`)return!1;let t=e.response?.status,n=e.message.match(/status code (\d+)/i),r=t??(n?Number(n[1]):void 0);if(r!==void 0){if(r===408||r===429)return!0;if(r>=400&&r<500)return!1;if(r>=500)return!0}return!0},GVt=(e,n)=>{let r=(0,t.ref)(null),i=(0,t.ref)(!1),a=(0,t.ref)(!1),o=(0,t.ref)([]),s=(0,t.ref)(!1),l=n||new w9,u=null,d=null,f=null,p=!1,m=0,h=!1,g=0,_=null,v=null,y=null,b=(t,n)=>{s.value=!0;let r=e.http?.agent.getLlms(t,n);return r?r.then(e=>(o.value=e,e)).catch(e=>{throw o.value=[],e}).finally(()=>{s.value=!1}):(s.value=!1,o.value=[],Promise.resolve([]))},x=()=>(i.value=!0,e.http?.agent.getAgentInfo().then(e=>{r.value=e}).finally(()=>{i.value=!1})),S=(t,n)=>{let r=t.promptSetting?.content?.at(-1);r?.role===g9.Pause&&e.message?.createAndPlusMessage({role:g9.Assistant,content:r.content,status:_9.Complete,sessionCode:n,property:{extra:{pause:!0}}})},C=(t,n,r,i,a)=>e.http?.message.userOperation(t,n,r,i).then(()=>{n===y9.ApprovalCancel?(P(),N(t,a)):A({sessionCode:t,config:i,model:a})}),w=(e=!1)=>{if(_&&=(clearTimeout(_),null),v){let t=v;v=null,t(e)}},T=e=>new Promise(t=>{v=t,_=setTimeout(()=>{_=null,v=null,t(!0)},e)}),E=()=>{p=!1,m=0,h=!1,w(!1)},D=()=>{let t=e.message?.list.value;if(t?.length)for(;t.length>0;){let e=t[t.length-1];if(e.role===g9.User)break;if(e.status===_9.Streaming||e.status===_9.Pending){t.pop();continue}break}},O=t=>t===e.session?.current?.value?.sessionCode,k=async(t,n)=>{let r=()=>n===g&&!p;if(!r()||!O(t))return`failed`;try{await e.session?.getSession(t)}catch{}if(!r()||!O(t))return`failed`;if(e.session?.current.value?.status!==T9.Running)return`finished`;if(m>=BVt||(m+=1,a.value=!0,!await T(UVt(m))||!r()||!O(t)))return`failed`;if(e.session?.current.value?.status!==T9.Running)return`finished`;if(!r())return`failed`;D();let i=e.message?.list.value.at(-1)?.id,o=y;return A({sessionCode:t,model:o?.model,url:o?.url,config:o?.config,lastMessageId:i===void 0?void 0:String(i),isReconnect:!0}),`reconnected`},A=async({sessionCode:t,model:n,url:r,config:i,resume:o,input:s,lastMessageId:d,isReconnect:f=!1})=>{f||E(),y={sessionCode:t,model:n,url:r,config:i};let m=++g,_=u;u=new AbortController,_?.abort?.();let v=()=>m===g;l instanceof w9&&l.injectMessageModule(e.message),s&&e.message?.list.value.push({role:g9.User,content:s,status:_9.Complete,sessionCode:t});let b=()=>{v()&&(a.value=!1,l.onDone?.call(l),s&&e.http?.message?.getMessages(t).then(t=>{let n=e.message?.list.value.findLast(e=>e.role===g9.User),r=t.findLast(e=>e.role===g9.User);n&&r&&(n.id=r.id)}),N(t))},x=e=>{v()&&(a.value=!1,l.onError?.call(l,e))},S=()=>{if(v()&&!p){if(h){b();return}k(t,m).then(e=>{if(v()&&e!==`reconnected`){if(e===`finished`){b();return}if(p||!O(t)){a.value=!1;return}x(Error(`Connection lost, please try again`))}})}},C=e=>{if(!(!v()||p)){if(!WVt(e)){x(e);return}k(t,m).then(n=>{if(v()&&n!==`reconnected`){if(n===`finished`){b();return}if(p||!O(t)){a.value=!1;return}x(e)}})}},w=e=>{v()&&(e?.type===x9.RunFinished&&(h=!0),l.onMessage?.call(l,e))},T=()=>{v()&&(a.value=!0,l.onStart?.call(l))};e.http?.fetchClient.streamRequest({url:r||`chat_completion/`,method:`POST`,data:{session_code:t,model:n,input:s,execute_kwargs:{stream:!0,persist_input:!!s,last_message_id:d,resume:o}},...i,controller:u,onDone:S,onError:C,onMessage:w,onStart:T}).catch(()=>{})},j=async(t,n,r,i,a,o)=>{await e.message?.createAndPlusMessage({role:g9.User,content:t,status:_9.Complete,sessionCode:n,...a&&{property:a}}),A({sessionCode:n,model:o,url:r,config:i})},M=(t,n,r,i)=>{if(e.session?.current.value?.status===T9.Running){let a=e.message?.list.value.at(-1)?.id;A({sessionCode:t,model:i,url:n,config:r,lastMessageId:a})}},N=(t,n)=>{let r=e.message?.list.value.at(-1),i=r?.content?.outcome?.type===S9.Interrupt?r.content.outcome.interrupts.find(e=>[zVt.Pending,zVt.Draft].includes(e.metadata?.ticket?.status)):void 0;r?.role===g9.Interrupt&&i&&(P(),d=new AbortController,e.http?.session.isResumeSession(t,{controller:d}).then(r=>{r?A({sessionCode:t,model:n,resume:{interruptId:i.id,status:C9.Resolved}}):f=setTimeout(()=>{t===e.session?.current?.value?.sessionCode&&N(t,n)},1e4)}))},P=()=>{clearTimeout(f),f=null,d?.abort?.(),d=null},F=()=>{p=!0,g+=1,w(!1),P(),a.value=!1,u?.abort?.(),u=null};return{info:r,isInfoLoading:i,isChatting:a,models:o,isModelsLoading:s,chat:j,handleRole:S,resendMessage:async(t,n,r,i,a,o)=>{let s=e.message?.list.value||[],l=s.findIndex(e=>String(e.id)===t);if(l===-1)throw Error(`Message not found: ${t}`);let u=s[l];if(u.role!==g9.User)throw Error(`Can only resend user messages`);let d=u.content,f=u.property,p=r??d,m=s.slice(l),h=e.message?.deleteMessages(m),g=e.message?.createAndPlusMessage({role:g9.User,content:p,status:_9.Complete,sessionCode:n,...f&&{property:f}});A({sessionCode:n,model:o,url:i,config:a}),Promise.all([h,g]).catch(e=>{console.error(`[resendMessage] API error:`,e)})},resumeStreamingChat:M,abortChat:F,stopChat:async t=>e.http.message?.stopChat(t),getAgentInfo:x,getLlms:b,reset:e=>{F(),l=e||new w9,r.value=null,i.value=!1,a.value=!1,o.value=[],s.value=!1,y=null,m=0,h=!1},pollResumeSession:N,clearLongPollTimer:P,userOperationStreamRequest:C,streamRequest:A}};function KVt(e){return(0,t.isRef)(e)}function E9(e){if(e==null)return;let n=e,r=0;for(;r<32;){if(r+=1,typeof n==`function`){n=n();continue}if(KVt(n)){n=(0,t.unref)(n);continue}break}return r>=32&&console.warn(`[chat-helper] resolveRequestValue: exceeded max unwrap depth`),n}var qVt=class{handlers=[];clear(){this.handlers=[]}eject(e){this.handlers[e]&&(this.handlers[e]=null)}forEach(e){this.handlers.forEach(t=>{t!==null&&e(t)})}use(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1}},JVt=class e{defaults;interceptors;globalErrorHandler;ignoreErrorPatterns=[];constructor(e={}){this.defaults=j9({method:`GET`,headers:{"Content-Type":`application/json`},timeout:3e4,responseType:`json`,credentials:`include`,mode:`cors`,validateStatus:e=>e>=200&&e<300},e),this.interceptors={request:new qVt,response:new qVt}}onError(e,t){this.globalErrorHandler=e,t?.ignoreErrors&&(this.ignoreErrorPatterns=t.ignoreErrors)}shouldIgnoreError(e){let t=e.config?.url||``,n=e.config?.baseURL||``,r=n&&!t.startsWith(`http`)?n+t:t;return this.ignoreErrorPatterns.some(e=>typeof e==`string`?t.includes(e)||r.includes(e):e.test(t)||e.test(r))}dispatchError(e){this.globalErrorHandler&&!this.shouldIgnoreError(e)&&this.globalErrorHandler(e)}applyResponseErrorInterceptors(e){let t=e;return this.interceptors.response.forEach(e=>{e.rejected&&(t=e.rejected(t))}),t}create(t){return new e(j9(this.defaults,t||{}))}delete(e,t,n){return this.request({...n,url:e,method:`DELETE`,params:t})}get(e,t,n){return this.request({...n,url:e,method:`GET`,params:t})}head(e,t,n){return this.request({...n,url:e,method:`HEAD`,params:t})}options(e,t,n){return this.request({...n,url:e,method:`OPTIONS`,params:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,data:t})}post(e,t,n){return this.request({...n,url:e,method:`POST`,data:t})}prepareRequest(e,t=!1){let n=j9(this.defaults,e);this.interceptors.request.forEach(e=>{if(e.fulfilled)try{n=e.fulfilled(n)}catch(t){throw e.rejected?e.rejected(t):t}});let r=n.url||``;n.baseURL&&!r.startsWith(`http`)&&(r=n.baseURL+r),r=YVt(r,n.params);let i=A9(n.data),a=new Headers(A9(n.headers));t&&!a.has(`Accept`)&&a.set(`Accept`,`text/event-stream`),i!=null&&(n.transformRequest?i=n.transformRequest(i,A9(n.headers)):a.get(`Content-Type`)?.includes(`application/json`)&&typeof i==`object`&&!(i instanceof FormData)&&!(i instanceof Blob)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)));let o=n.controller??new AbortController,s={method:n.method,credentials:n.credentials,mode:n.mode,headers:a,body:i,signal:o.signal};return{url:r,requestConfig:n,fetchConfig:s,controller:o}}put(e,t,n){return this.request({...n,url:e,method:`PUT`,data:t})}async request(e){let{url:t,fetchConfig:n,requestConfig:r,controller:i}=this.prepareRequest(e),a=!1,o=r.timeout&&r.timeout>0?setTimeout(()=>{a=!0,i.abort()},r.timeout):void 0;try{let e=await fetch(t,n);o&&clearTimeout(o);let i,a=r.responseType||`json`;try{switch(a){case`json`:i=await e.json();break;case`text`:i=await e.text();break;case`blob`:i=await e.blob();break;case`arrayBuffer`:i=await e.arrayBuffer();break;case`formData`:i=await e.formData();break;default:i=await e.json()}}catch{i=null}r.transformResponse&&(i=r.transformResponse(i));let s={data:i,status:e.status,statusText:e.statusText,headers:e.headers,config:r};if(!(r.validateStatus||this.defaults.validateStatus)(e.status)){let{code:t,message:n}=D9(s.data,`Request failed with status code ${e.status}`);throw k9(n,r,t,s)}let l=s;this.interceptors.response.forEach(e=>{if(e.fulfilled)try{l=e.fulfilled(l)}catch(t){throw e.rejected?e.rejected(t):t}}),l instanceof Promise&&(l=await l);let u=l.data;if(!u)return;if(![0,`success`].includes(u.code)){let{code:e,message:t}=D9(u,`Request failed with code ${u.code}`);throw k9(t,r,e,l)}return u.data}catch(e){if(o&&clearTimeout(o),e instanceof Error&&e.name===`AbortError`&&!a){console.warn(`User canceled request`,e.message);return}let t=a?k9(`timeout of ${r.timeout}ms exceeded`,r,`ECONNABORTED`,void 0):e.isAxiosError===!0?e:k9(e.message,r,e.code,void 0);throw this.dispatchError(t),this.applyResponseErrorInterceptors(t)}}stream(e,t){return this.streamRequest({...t,url:e})}async streamRequest(e){let t=!1,n=e.onError,r=e=>{if(!t){let n=e;n.config||=s,this.dispatchError(n),t=!0}n?.(e)},i={...e,onError:r},{url:a,fetchConfig:o,requestConfig:s,controller:l}=this.prepareRequest(i,!0),u,d=()=>{u?.cancel().catch(()=>{})};try{let e=await fetch(a,o);if(!(s.validateStatus||this.defaults.validateStatus)(e.status)){let t=null;try{t=await e.json()}catch{t=null}let{code:n,message:i}=D9(t,`Request failed with status code ${e.status}`);r(k9(i,s,n,void 0));return}if(i.onStart?.(),u=e.body?.pipeThrough(new window.TextDecoderStream).getReader(),!u){r(Error(`IResponse body is not readable`));return}if(l.signal.addEventListener(`abort`,d,{once:!0}),l.signal.aborted){d(),i.onDone?.();return}let t=``,n=e=>{try{return JSON.parse(e),!0}catch{return!1}};for(;;){let{value:e,done:r}=await u.read();if(r){i.onDone?.();break}(t+e.toString()).split(`
|
|
3488
|
-
`).forEach(e=>{let r=e.replace(`data:`,``).trim();if(n(r)){let e=JSON.parse(r);i.onMessage?.(e),t=``}else r&&(t=r)})}}catch(e){if(e instanceof Error){if(e.name===`AbortError`){i.onDone?.();return}r(e)}throw e}finally{l.signal.removeEventListener(`abort`,d)}}};function YVt(e,t){if(!t)return e;let n=new URLSearchParams;Object.keys(t).forEach(e=>{let r=t[e];r!=null&&(Array.isArray(r)?r.forEach(t=>n.append(e,String(t))):n.append(e,String(r)))});let r=n.toString();return r?`${e}${e.includes(`?`)?`&`:`?`}${r}`:e}function D9(e,t){let n=`ERR_BAD_RESPONSE`;if(!e||typeof e!=`object`)return{code:n,message:t};let r=e;return r.error?.message?{code:r.error.code??n,data:r.error.data,message:O9(r.error.message,t)}:r.message?{code:r.code??n,data:r.data,message:O9(r.message,t)}:r.detail?{code:r.code??n,data:r.data,message:O9(r.detail,t)}:{code:r.code??n,data:r.data,message:t}}function O9(e,t){if(typeof e==`string`)return e||t;try{return JSON.stringify(e)||t}catch{return t}}function k9(e,t,n,r){let i=Error(e);return i.config=t,i.code=String(n),i.response=r,i.isAxiosError=!0,i}function A9(e){return E9(e)}function XVt(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function j9(e,t){let n={...e};for(let r in t){let i=t[r];if(XVt(i)){let t=e[r];n[r]=j9(t||{},i)}else n[r]=i}return n}new JVt;var ZVt=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),QVt=new Set([`GET`,`HEAD`,`OPTIONS`]);function $Vt(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function eHt(e,t){let{headers:n,data:r}=t.requestData;!n&&!r||e.interceptors.request.use(e=>{let t=e,i=(e.method??`GET`).toUpperCase();if(n){let r=E9(n);if(r&&Object.keys(r).length>0){let n=E9(e.headers)??{};t={...t,headers:{...n,...r}}}}if(r){let n=E9(r);if(n&&Object.keys(n).length>0){if(ZVt.has(i)){let r=E9(e.data);r==null?t={...t,data:n}:$Vt(r)?t={...t,data:{...n,...r}}:console.warn(`[chat-helper] requestData.data 无法注入:当前请求体不是普通对象(FormData/Blob/string 等),已跳过合并。`,{method:i,existingType:typeof r})}else if(QVt.has(i)){let r=e.params??{};t={...t,params:{...n,...r}}}}}return t})}var tHt=e=>{let t=new JVt({baseURL:e.requestData.urlPrefix});return eHt(t,e),e.interceptors?.request&&t.interceptors.request.use(e.interceptors.request),e.interceptors?.response&&t.interceptors.response.use(e.interceptors.response),{fetchClient:t,reset:e=>{t.defaults.baseURL=e.requestData.urlPrefix,t.interceptors.request.clear(),t.interceptors.response.clear(),eHt(t,e),e.interceptors?.request&&t.interceptors.request.use(e.interceptors.request),e.interceptors?.response&&t.interceptors.response.use(e.interceptors.response)}}},nHt=e=>({conversationSettings:{openingRemark:e?.conversation_settings?.opening_remark,predefinedQuestions:e?.conversation_settings?.predefined_questions,commands:e?.conversation_settings?.commands?.map(e=>({id:e.id,name:e.name,alias:e.alias,icon:e.icon,components:e.components.map(e=>({type:e.type,name:e.name,key:e.key,placeholder:e.placeholder,default:e.default,required:e.required,fillBack:e.fill_back,fillRegx:e.fill_regx,rows:e.rows,min:e.min,max:e.max,options:e.options})),content:e.content,agentId:e.agent_id,status:e.status,supportUpload:e.support_upload})),enableChatSession:e?.conversation_settings?.enable_chat_session},promptSetting:e?.prompt_setting?{content:e.prompt_setting.content,supportUpload:e.prompt_setting.support_upload}:void 0,agentName:e?.agent_name,relatedSkills:e?.related_skills?.map(e=>({id:e.id,skill_name:e.skill_name,skill_code:e.skill_code,description:e.description,icon:e.icon})),chatGroup:e?.chat_group?{enabled:e.chat_group.enabled,staff:e.chat_group.staff,username:e.chat_group.username}:void 0,saasUrl:e?.saas_url,resources:e?.resources}),rHt=e=>({id:e.id??0,llm_code:e.llm_code,llm_name:e.llm_name,llm_type:e.llm_type??`chat.completion`,icon:e.icon??``,description:e.description??``,base_model:e.base_model,max_token_size:e.max_token_size??0,property:e.property??{},space_auth_mode:e.space_auth_mode??``,user_auth_mode:e.user_auth_mode??``,tag_names:e.tag_names}),iHt=e=>Array.isArray(e)?e.map(rHt):[],aHt=e=>({getAgentInfo:t=>e.get(`agent/info/`,void 0,t).then(nHt),getLlms:(t,n)=>{let r={llm_type:t?.llm_type??`chat.completion`};return t?.fuzzy&&(r.fuzzy=t.fuzzy),t?.supports&&(r.supports=t.supports),e.get(`llms/`,r,n).then(iHt)}}),M9=e=>{let t={id:e.id,messageId:e.message_id,name:e.name,role:e.role,sessionCode:e.session_code,status:e.status};switch(e.role){case g9.Activity:{let n=e,r=e=>e.map(e=>({name:e.name,originFileUrl:e.origin_file_url,url:e.url})),i;switch(n.activity_type){case h9.ReferenceDocument:i=r(n.content);break;case h9.KnowledgeRag:{let e=n.content;i={content:e.content,referenceDocument:r(e.reference_document)};break}case h9.FlowAgent:case h9.ArtifactsGenerated:default:i=n.content;break}return{...t,activityType:n.activity_type,content:i,property:n.property,role:n.role}}case g9.Assistant:{let n=e;return{...t,content:n.content,property:n.property,role:n.role,toolCalls:n.tool_calls?.map(e=>({function:{arguments:e.function.arguments,name:e.function.name,description:e.function.description,mcpName:e.function.mcp_name},id:e.id,type:e.type}))}}case g9.Developer:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Guide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Hidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Info:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Pause:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Placeholder:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Reasoning:{let n=e;return{...t,content:n.content,duration:n.duration,role:n.role}}case g9.System:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateHidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Tool:{let n=e;return{...t,content:n.content,duration:n.duration,error:n.error,role:n.role,toolCallId:n.tool_call_id}}case g9.User:{let n=e,r=n.content;return{...t,content:Array.isArray(r)?r.map(e=>{if(e.type===v9.Binary){let t=e;return{data:t.data,filename:t.filename,id:t.id,mimeType:t.mime_type,type:t.type,url:t.url}}return e}):r,property:n.property,role:n.role}}case g9.Interrupt:return{...t,...e}}},oHt=e=>{let t={id:e.id,message_id:e.messageId,name:e.name,role:e.role,session_code:e.sessionCode,status:e.status};switch(e.role){case g9.Activity:{let n=e,r=e=>e.map(e=>({name:e.name,origin_file_url:e.originFileUrl,url:e.url})),i;switch(n.activityType){case h9.ReferenceDocument:i=r(n.content);break;case h9.KnowledgeRag:{let e=n.content;i={content:e.content,reference_document:r(e.referenceDocument)};break}case h9.FlowAgent:case h9.ArtifactsGenerated:default:i=n.content;break}return{...t,activity_type:n.activityType,content:i,property:n.property,role:n.role}}case g9.Assistant:{let n=e;return{...t,property:n.property,content:n.content,role:n.role,tool_calls:n.toolCalls?.map(e=>({function:{arguments:e.function.arguments,name:e.function.name,description:e.function.description,mcp_name:e.function.mcpName},id:e.id,type:e.type}))}}case g9.Developer:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Guide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Hidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Info:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Pause:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Placeholder:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Reasoning:{let n=e;return{...t,content:n.content,duration:n.duration,role:n.role}}case g9.System:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateHidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Tool:{let n=e;return{...t,content:n.content,duration:n.duration,error:n.error,role:n.role,tool_call_id:n.toolCallId}}case g9.User:{let n=e,r=n.content;return{...t,content:Array.isArray(r)?r.map(e=>{if(e.type===v9.Binary){let t=e;return{data:t.data,filename:t.filename,id:t.id,mime_type:t.mimeType,type:t.type,url:t.url}}return e}):r,property:n.property,role:n.role}}case g9.Interrupt:return{...t,...e}}},sHt=e=>({getMessages:(t,n,r)=>e.get(`session_content/content/`,{session_code:t,limit:n},r).then(e=>e.map(M9)),plusMessage:(t,n)=>e.post(`session_content/`,oHt(t),n).then(M9),modifyMessage:(t,n)=>e.put(`session_content/${t.id}/`,oHt(t),n).then(M9),deleteMessage:(t,n)=>e.delete(`session_content/${t}/`,void 0,n),batchDeleteMessages:(t,n)=>e.post(`session_content/batch_delete/`,{ids:t},n),shareMessages:(t,n,r,i)=>e.post(`share/`,{session_code:t,content_ids:n,...r?{expired_at:r}:{}},i),stopChat:(t,n)=>e.post(`session_content/stop/`,{session_code:t},n),getFlowAgentTaskInfo:(t,n)=>e.get(`flow_agent/${t}/task_info/`,void 0,n),getFlowAgentTaskNodeInfo:(t,n,r)=>e.get(`flow_agent/${t}/task_node_info/${n}/`,void 0,r),retryFlowAgentTaskNode:(t,n,r,i)=>e.post(`flow_agent/${t}/node/${n}/retry/`,{task_id:r},i),skipFlowAgentTaskNode:(t,n,r,i)=>e.post(`flow_agent/${t}/node/${n}/skip/`,{task_id:r},i),userOperation:(t,n,r,i)=>e.post(`user_operation/`,{session_code:t,operation:n,payload:r},i)}),N9=e=>({sessionCode:e.session_code,sessionContentCount:e.session_content_count,sessionName:e.session_name,isTemporary:e.is_temporary,model:e.model,comment:e.comment,rate:e.rate,updatedAt:e.updated_at,createdAt:e.created_at,status:e.status,roleInfo:e.role_info?{collectionId:e.role_info.collection_id,collectionName:e.role_info.collection_name,content:e.role_info.content,variables:e.role_info.variables}:void 0,sessionProperty:{isAutoClear:e.session_property?.is_auto_clear,isAutoCalcPrompt:e.session_property?.is_auto_clac_prompt,labels:e.session_property?.labels}}),cHt=e=>({session_code:e.sessionCode,session_content_count:e.sessionContentCount,session_name:e.sessionName,is_temporary:e.isTemporary,model:e.model,comment:e.comment,rate:e.rate,updated_at:e.updatedAt,created_at:e.createdAt,status:e.status,role_info:e.roleInfo?{collection_id:e.roleInfo.collectionId,collection_name:e.roleInfo.collectionName,content:e.roleInfo.content,variables:e.roleInfo.variables}:void 0,session_property:{is_auto_clear:e.sessionProperty?.isAutoClear,is_auto_clac_prompt:e.sessionProperty?.isAutoCalcPrompt,labels:e.sessionProperty?.labels}}),lHt=e=>({session_code:e.sessionCode,session_content_ids:e.sessionContentIds,rate:e.rate,comment:e.comment,labels:e.labels}),uHt=e=>({sessionCode:e.session_code,sessionContentIds:e.session_content_ids,rate:e.rate,comment:e.comment,labels:e.lables}),dHt=`upload_file`,fHt=20,pHt=600,mHt=2e4,hHt=e=>{if(Array.isArray(e))return{page:1,numPages:1,count:e.length,results:e.map(N9)};let t=Array.isArray(e?.results)?e.results:[];return{page:e?.page??1,numPages:e?.num_pages??1,count:e?.count??t.length,results:t.map(N9)}},gHt=e=>{let t=e.split(`.`).pop();if(!t||t===e)return``;let n=t.replace(/[^A-Za-z0-9]/g,``).slice(0,20).toLowerCase();return n?`.${n}`:``},_Ht=e=>`${dHt}_${`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}${gHt(e.name)}`,vHt=e=>`attachment; filename="${e}"`,yHt=e=>({clearSession:(t,n)=>e.post(`chat_completion/${t}/clear/`,void 0,n),getSessions:(t,n)=>e.get(`session/`,{page:t?.page??1,page_size:t?.page_size??fHt},n).then(hHt),plusSession:(t,n)=>e.post(`session/`,cHt(t),n).then(e=>N9(e)),modifySession:(t,n)=>e.put(`session/${t.sessionCode}/`,cHt(t),n).then(e=>N9(e)),deleteSession:(t,n)=>e.delete(`session/${t}/`,void 0,n),batchDeleteSessions:(t,n)=>e.post(`session/batch_delete/`,{session_codes:t},n),getSession:(t,n)=>e.get(`session/${t}/`,void 0,n).then(e=>N9(e)),postSessionFeedback:(t,n)=>e.post(`session_feedback/`,lHt(t),n).then(e=>uHt(e)),getSessionFeedbackReasons:(t,n)=>e.get(`session_feedback/reasons/`,{rate:t},n),renameSession:(t,n)=>e.post(`session/${t}/ai_rename/`,void 0,n).then(e=>N9(e)),uploadFile:(t,n,r)=>{let i=_Ht(n),a=encodeURIComponent(i),o=E9(r?.headers)??{};return n.arrayBuffer().then(n=>e.post(`session/${t}/upload/${a}/`,n,{...r,headers:{...o,"Content-Disposition":vHt(i)}}))},getPvFileDownloadUrl:(t,n,r,i)=>{let a=r?.expiresIn??pHt,o=r?.timeout??mHt;return e.get(`session/${t}/pv_files/download_url/`,{expires_in:a,path:n},{...i,timeout:i?.timeout??o})},isResumeSession:(t,n)=>e.get(`session/${t}/is_resume/`,void 0,n)}),bHt=e=>({agent:aHt(e),session:yHt(e),message:sHt(e),fetchClient:e}),xHt=e=>{let{fetchClient:t,reset:n}=tHt(e);return{...bHt(t),reset:n,onError:t.onError.bind(t)}},SHt=()=>({agent:null,http:null,message:null,session:null,registerAgent(e){this.agent=e},registerHttp(e){this.http=e},registerMessage(e){this.message=e},registerSession(e){this.session=e}}),CHt=20,wHt=e=>{let n=(0,t.ref)([]),r=(0,t.ref)(null),i=(0,t.ref)(0),a=(0,t.ref)(0),o=(0,t.ref)(0),s=(0,t.ref)(!1),l=(0,t.ref)(!1),u=(0,t.ref)(!1),d=(0,t.ref)(!1),f=(0,t.ref)(!1),p=(0,t.ref)(!1),m=(0,t.ref)(!1),h=(0,t.ref)(!1),g=(0,t.computed)(()=>i.value>0&&i.value<a.value),_=e=>{n.value=n.value.map(t=>t.sessionCode===e.sessionCode?{...t,...e}:t),r.value?.sessionCode===e.sessionCode&&(r.value=n.value.find(t=>t.sessionCode===e.sessionCode)??{...r.value,...e})},v=t=>{l.value=!0;let r={page:t?.page??1,page_size:t?.page_size??CHt};return e.http?.session.getSessions(r).then(e=>{n.value=e.results,i.value=e.page,a.value=e.numPages,o.value=e.count}).finally(()=>{l.value=!1})},y=async(t=CHt)=>{if(!(!g.value||l.value||u.value)){u.value=!0;try{let r=await e.http?.session.getSessions({page:i.value+1,page_size:t});if(!r)return;let s=new Set(n.value.map(e=>e.sessionCode)),l=r.results.filter(e=>!s.has(e.sessionCode));n.value=[...n.value,...l],i.value=r.page,a.value=r.numPages,o.value=r.count}finally{u.value=!1}}},b=async(t,i)=>{e.agent?.abortChat();let a=i?.loadMessages!==!1,o=n.value.find(e=>e.sessionCode===t);!a&&o?r.value=o:await x(t),a?(await e.message?.getMessages(t),e.agent?.resumeStreamingChat(t),e.agent?.pollResumeSession(t)):e.message&&(e.message.list.value=[])},x=t=>(s.value=!0,e.http?.session.getSession(t).then(e=>{r.value=e}).finally(()=>{s.value=!1}));return{list:n,current:r,page:i,numPages:a,count:o,hasMore:g,isCurrentLoading:s,isListLoading:l,isLoadingMore:u,isCreateLoading:d,isUpdateLoading:f,isDeleteLoading:p,isBatchDeleteLoading:m,getSessions:v,loadMoreSessions:y,chooseSession:b,getSession:x,createSession:async(t,r)=>{d.value=!0;try{let i=await e.http?.session.plusSession(t);i&&(n.value.unshift(i),o.value+=1,await b(i.sessionCode,{loadMessages:r?.loadMessages??!1}))}finally{d.value=!1}},updateSession:t=>(f.value=!0,e.http?.session.modifySession(t).then(e=>{_(e)}).finally(()=>{f.value=!1})),deleteSession:async t=>{p.value=!0;try{await e.http?.session.deleteSession(t),n.value=n.value.filter(e=>e.sessionCode!==t),o.value=Math.max(0,o.value-1),r.value?.sessionCode===t&&n.value[0]?.sessionCode&&await b(n.value[0].sessionCode)}finally{p.value=!1}},batchDeleteSessions:async t=>{if(t.length!==0){m.value=!0;try{await e.http?.session.batchDeleteSessions(t);let i=new Set(t),a=n.value.length;n.value=n.value.filter(e=>!i.has(e.sessionCode));let s=a-n.value.length;o.value=Math.max(0,o.value-s),r.value&&i.has(r.value.sessionCode)&&(n.value.length>0?await b(n.value[0].sessionCode):(r.value=null,e.message&&(e.message.list.value=[])))}finally{m.value=!1}}},postSessionFeedback:t=>e.http?.session.postSessionFeedback(t),getSessionFeedbackReasons:t=>e.http?.session.getSessionFeedbackReasons(t),renameSession:t=>(h.value=!0,e.http?.session.renameSession(t).then(e=>(_({sessionCode:e.sessionCode,sessionName:e.sessionName}),e)).finally(()=>{h.value=!1})),uploadFile:(t,n)=>e.http?.session.uploadFile(t,n),getPvFileDownloadUrl:(t,n,r)=>e.http?.session.getPvFileDownloadUrl(t,n,r),reset:()=>{n.value=[],r.value=null,i.value=0,a.value=0,o.value=0,s.value=!1,l.value=!1,u.value=!1,d.value=!1,f.value=!1,p.value=!1,m.value=!1,h.value=!1}}},P9=e=>{let t=SHt(),n=xHt(e),r=GVt(t,e.protocol),i=LVt(t),a=wHt(t);return t.registerHttp(n),t.registerMessage(i),t.registerAgent(r),t.registerSession(a),{agent:r,session:a,message:i,http:n,reset:e=>{n.reset(e),r.reset(e.protocol),i.reset(),a.reset()},onError:n.onError}},THt=new Set([`context_type`,`__label`,`__key`,`__value`]);function EHt(e,n){return{urlPrefix:e,headers:()=>E9((0,t.toValue)(n)?.headers),data:()=>E9((0,t.toValue)(n)?.data)}}function DHt(e){return e?Array.isArray(e)?e.map(e=>{if(e.__key)return e;let t=Object.entries(e).filter(([e])=>!THt.has(e));if(t.length===0)return e;let[n,r]=t[0];return{...e,[n]:r,context_type:e.context_type??`input`,__label:e.__label??n,__key:e.__key??n,__value:e.__value??r}}):Object.entries(e).map(([e,t])=>({[e]:t,context_type:`input`,__label:e,__key:e,__value:t})):[]}function F9(e,t){if(!t)return e;let n=t()?.context;if(!n)return e;let r=DHt(n);return r.length===0?e:OHt(e,r)}function OHt(e,t){if(t.length===0)return e??{};let n=e??{},r=n.extra??{},i=r.context??[],a=new Set(t.map(e=>e.__key).filter(Boolean)),o=i.filter(e=>{let t=e.__key;return!t||!a.has(t)});return{...n,extra:{...r,context:[...o,...t]}}}function kHt(e){return e.some(e=>{if(!(`property`in e))return!0;let{property:t}=e;return!t?.extra?.pause})}function I9(e,t){let n=null;for(let r of e)if(r.role===`user`&&r.id!==void 0&&(n=r),r===t)break;return n}function AHt(e,t){let n=I9(e,t);if(n?.id!==void 0)return typeof n.id==`number`?n.id:Number(n.id)}function jHt(e){if(!e)return[];if(typeof e!=`string`)return[{type:`text`,content:e}];let t=[],n=/```custom-component\s*\n([\s\S]*?)\n```/g,r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r){let n=e.slice(r,i.index).trim();n&&t.push({type:`text`,content:n})}try{let e=JSON.parse(i[1]);t.push({type:`custom`,data:e,raw:i[1]})}catch{t.push({type:`text`,content:i[0]})}r=i.index+i[0].length}if(r<e.length){let n=e.slice(r).trim();n&&t.push({type:`text`,content:n})}return t}var MHt=e=>{if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);if(e&&typeof e==`object`){let{message:t}=e;if(typeof t==`string`&&t)return Error(t);try{return Error(JSON.stringify(e)??String(e))}catch{return Error(String(e))}}return Error(String(e))},NHt=e=>{let t=document.cookie.match(RegExp(`(^| )${e}=([^;]*)(;|$)`));return t?t[2]:``},PHt=e=>e.endsWith(`/`)?e:`${e}/`,L9=e=>{if(!e)return e;try{let t=new URL(e,window.location.origin);return t.protocol=window.location.protocol,PHt(t.toString())}catch(t){return console.warn(`Failed to normalize URL:`,t),PHt(e)}};async function FHt(e){if(typeof navigator<`u`&&`clipboard`in navigator)try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.style.opacity=`0`,document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand(`copy`)}catch{return!1}finally{document.body.removeChild(t)}}function IHt(){let e=window.navigator.userAgent.toLowerCase(),t=window.navigator.platform.toLowerCase();return t.includes(`mac`)||e.includes(`mac`)?`mac`:t.includes(`win`)||e.includes(`win`)?`windows`:t.includes(`linux`)||e.includes(`linux`)?`linux`:`unknown`}function LHt(){return RHt()?`Cmd + I`:`Ctrl + I`}function RHt(){return IHt()===`mac`}function zHt(e){let t=RHt()?e.metaKey:e.ctrlKey,n=e.key.toLowerCase()===`i`;return t&&n&&!e.shiftKey&&!e.altKey}var BHt=NHt(`blueking_language`)||`zh-cn`,VHt={小鲸:`BK GPT`,关闭:`close`,发送:`Send`,请输入:`Please input`,昨天:`yesterday`,"3天前":`3 days ago`,"5天前":`5 days ago`,"1周前":`1 week ago`,更早:`Older`,删除:`Delete`,恢复默认大小:`Restore default size`,"AI 小鲸":`AI BK GPT`,新增会话:`New chat`,历史会话:`History session`,停止生成:`Stop generating`,复制:`Copy`,编辑:`Edit`,今天:`Today`,搜索会话名称:`Search session name`,重命名:`Rename`,自动生成命名:`Auto generate name`,分享会话:`Share session`,无智能体使用权限:`No permission to use this agent`,暂无使用权限:`No permission`,请输入新的会话名称:`Please enter new session name`,"确认删除会话 ?":`Confirm delete session?`,搜索为空:`No search results`,暂无对话:`No conversations`,"加载中...":`Loading...`,转人工:`Transfer to human`,缩小高度:`Shrink height`,全选:`Select all`,取消:`Cancel`,确定:`Confirm`,分享链接已复制到剪贴板:`Share link copied to clipboard`,请求失败:`Request failed`,当前已是新会话:`Already in a new session`,"正在创建会话...":`Creating session...`},HHt={重命名:`重命名`,自动生成命名:`自动生成命名`,分享会话:`分享会话`,全选:`全选`,取消:`取消`,确定:`确定`,分享链接已复制到剪贴板:`分享链接已复制到剪贴板`,请求失败:`请求失败`},R9=e=>BHt===`en`?VHt[e]||e:HHt[e]||e;function UHt(e){let{triggerRef:n,panelComponent:r,panelProps:i={},tippyOptions:a={}}=e,o=(0,t.ref)(null),s=null,l=()=>(s||=document.createElement(`div`),(0,t.render)((0,t.h)(r,{...i,onClose:p}),s),s),u=e=>{let t=e.target,r=n.value;if(r&&r.contains(t))return;let i=document.querySelector(`.tippy-box[data-theme~="history-panel"]`);if(i&&i.contains(t))return;let a=document.querySelector(`.tippy-box[data-theme~="more-menu-light"]`);a&&a.contains(t)||o.value?.state.isVisible&&o.value.hide()},d=()=>{if(!n.value||o.value)return;let e={placement:`bottom-end`,offset:[0,8],appendTo:document.querySelector(`.ai-blueking-container-wrapper`)||document.body};o.value=uu(n.value,{content:l(),interactive:!0,trigger:`manual`,theme:`light history-panel`,arrow:!1,hideOnClick:!1,animation:`scale`,duration:200,delay:[0,0],...e,...a,onShow:()=>{o.value&&s&&o.value.setContent(l()),setTimeout(()=>{document.addEventListener(`click`,u,!1)},0)},onHidden:()=>{document.removeEventListener(`click`,u,!1)}})},f=()=>{o.value||d(),o.value?.show()},p=()=>{o.value?.hide()},m=()=>{o.value||d(),o.value?.state.isVisible?p():f()},h=e=>{e.stopPropagation(),m()},g=()=>{o.value&&=(o.value.destroy(),null),s&&=((0,t.render)(null,s),null),document.removeEventListener(`click`,u,!1)};return(0,t.onBeforeUnmount)(()=>{g()}),{show:f,hide:p,toggle:m,handleTriggerClick:h,destroy:g,isVisible:()=>o.value?.state.isVisible??!1}}var WHt={class:`history-group`},GHt={class:`history-group-title`},KHt={class:`history-group-list`},qHt=(0,t.defineComponent)({__name:`history-group`,props:{currentSessionCode:{},sessions:{},title:{}},setup(e){let n=e;return(e,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,WHt,[(0,t.createElementVNode)(`div`,GHt,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(n.title),1)]),(0,t.createElementVNode)(`div`,KHt,[(0,t.renderSlot)(e.$slots,`default`,{},void 0,!0)])]))}}),z9=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},JHt=z9(qHt,[[`__scopeId`,`data-v-3b603cb6`]]),YHt={class:`history-item-actions`},XHt=z9((0,t.defineComponent)({__name:`history-item`,props:{isActive:{type:Boolean},isEditing:{type:Boolean},session:{}},emits:[`click`,`delete`,`edit`,`rename-cancel`,`rename-confirm`],setup(e,{emit:n}){let r=e,i=n,a=yhe,o=(0,t.ref)(null),s=(0,t.ref)(``);(0,t.watch)(()=>r.isEditing,e=>{e&&(s.value=r.session.sessionName,(0,t.nextTick)(()=>{if(o.value)try{let e=o.value;e&&typeof e.focus==`function`&&e.focus();let t=e.$el?.querySelector(`input`);t&&typeof t.select==`function`&&t.select()}catch(e){console.warn(`Failed to focus edit input:`,e)}}))});let l=()=>{r.isEditing||i(`click`,r.session)},u=()=>{i(`edit`,r.session)},d=()=>{i(`delete`,r.session.sessionCode)},f=()=>{let e=s.value.trim();e&&e!==r.session.sessionName?i(`rename-confirm`,r.session.sessionCode,e):i(`rename-cancel`)},p=()=>{i(`rename-cancel`)},m=(e,t)=>{t.key===`Enter`?f():t.key===`Escape`&&p()};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:(0,t.normalizeClass)([`history-item`,{active:r.isActive}]),onClick:l},[r.isEditing?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(ts),{key:1,ref_key:`editInputRef`,ref:o,modelValue:s.value,"onUpdate:modelValue":n[1]||=e=>s.value=e,style:{width:`100%`,height:`28px`},onBlur:f,onKeyup:m,onClick:n[2]||=(0,t.withModifiers)(()=>{},[`stop`])},null,8,[`modelValue`])):((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[(0,t.createVNode)((0,t.unref)(kde),{style:{width:`calc(100% - 42px)`}},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(r.session.sessionName),1)]),_:1}),(0,t.createElementVNode)(`span`,YHt,[(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-bianji`,onClick:(0,t.withModifiers)(u,[`stop`])},null,512),[[(0,t.unref)(a),{content:(0,t.unref)(R9)(`编辑`),boundary:`parent`}]]),(0,t.createVNode)((0,t.unref)(zme),{title:(0,t.unref)(R9)(`确认删除会话 ?`),content:`删除操作无法撤回,请谨慎操作!`,"confirm-config":{theme:`danger`},trigger:`click`,boundary:`parent`,onConfirm:d},{default:(0,t.withCtx)(()=>[(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-shanchu`,onClick:n[0]||=(0,t.withModifiers)(()=>{},[`stop`])},null,512),[[(0,t.unref)(a),{content:(0,t.unref)(R9)(`删除`),boundary:`parent`}]])]),_:1},8,[`title`])])],64))],2))}}),[[`__scopeId`,`data-v-fea14d3a`]]),ZHt={class:`history-search`},QHt={class:`input-icon`},$Ht=z9((0,t.defineComponent)({__name:`history-search`,props:{modelValue:{default:``},placeholder:{default:``}},emits:[`update:modelValue`],setup(e,{emit:n}){let r=e,i=n,a=e=>{i(`update:modelValue`,e)};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,ZHt,[(0,t.createVNode)((0,t.unref)(ts),{"model-value":r.modelValue,behavior:`simplicity`,placeholder:r.placeholder||(0,t.unref)(R9)(`搜索会话名称`),style:{height:`22px`},"onUpdate:modelValue":a},{suffix:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`span`,QHt,[(0,t.createVNode)((0,t.unref)(Ja))])]),_:1},8,[`model-value`,`placeholder`])]))}}),[[`__scopeId`,`data-v-e7ff40b2`]]),eUt={class:`history-dropdown-header`},tUt={class:`history-dropdown-header-title`},nUt={class:`history-dropdown-content`},rUt={key:0,class:`history-dropdown-loading`},iUt={class:`history-dropdown-loading-dots`},aUt=40,oUt=z9((0,t.defineComponent)({__name:`index`,props:{sessionBusinessManager:{}},emits:[`close`,`session-delete`,`session-rename`,`session-switch`],setup(e,{emit:n}){let r=e,i=n,a=(0,t.ref)(``),o=(0,t.ref)(null),s=(0,t.computed)(()=>r.sessionBusinessManager.currentSession.value?.sessionCode),l=(0,t.computed)(()=>r.sessionBusinessManager.isLoadingMore.value),u=e=>{let t=e.target;t.scrollHeight-t.scrollTop-t.clientHeight>aUt||r.sessionBusinessManager.hasMoreSessions.value&&(r.sessionBusinessManager.isLoadingMore.value||r.sessionBusinessManager.loadMoreSessions())},d=(0,t.computed)(()=>{let e={today:{key:`today`,alias:R9(`今天`),sessionList:[]},yesterday:{key:`yesterday`,alias:R9(`昨天`),sessionList:[]},"3days":{key:`3days`,alias:R9(`3天前`),sessionList:[]},"5days":{key:`5days`,alias:R9(`5天前`),sessionList:[]},"1week":{key:`1week`,alias:R9(`1周前`),sessionList:[]},before:{key:`before`,alias:R9(`更早`),sessionList:[]}},t=r.sessionBusinessManager.sessionList.value.filter(e=>e.sessionName.toLowerCase().includes(a.value.toLowerCase())),n=new Date,i=new Date(n);i.setDate(i.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-3);let s=new Date(n);s.setDate(n.getDate()-5);let l=new Date(n);l.setDate(n.getDate()-7);for(let r of t){let t=new Date(r.createdAt||``),a=t.toDateString();a===n.toDateString()?e.today.sessionList.push(r):a===i.toDateString()?e.yesterday.sessionList.push(r):t>=o&&t>s?e[`3days`].sessionList.push(r):t>=s&&t>l?e[`5days`].sessionList.push(r):t>=l?e[`1week`].sessionList.push(r):e.before.sessionList.push(r)}for(let t of Object.values(e))t.sessionList.sort((e,t)=>{let n=new Date(e.createdAt||0).getTime();return new Date(t.createdAt||0).getTime()-n});return Object.values(e).filter(e=>e.sessionList.length>0)}),f=e=>s.value===e,p=e=>{f(e.sessionCode)||(i(`session-switch`,e.sessionCode),i(`close`))},m=e=>{o.value=e.sessionCode},h=e=>{i(`session-delete`,e)},g=(e,t)=>{let n=r.sessionBusinessManager.sessionList.value.find(t=>t.sessionCode===e);n&&(n.sessionName=t),o.value=null,i(`session-rename`,e,t)},_=()=>{o.value=null};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:`bkai-history-dropdown`,onScroll:u},[(0,t.createElementVNode)(`div`,eUt,[(0,t.createElementVNode)(`h1`,tUt,(0,t.toDisplayString)((0,t.unref)(R9)(`历史会话`)),1),(0,t.createVNode)($Ht,{modelValue:a.value,"onUpdate:modelValue":n[0]||=e=>a.value=e,placeholder:(0,t.unref)(R9)(`搜索会话名称`)},null,8,[`modelValue`,`placeholder`])]),(0,t.createElementVNode)(`div`,nUt,[d.value.length>0?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(d.value,e=>((0,t.openBlock)(),(0,t.createBlock)(JHt,{key:e.key,"current-session-code":s.value,sessions:e.sessionList,title:e.alias},{default:(0,t.withCtx)(()=>[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(e.sessionList,e=>((0,t.openBlock)(),(0,t.createBlock)(XHt,{key:e.sessionCode,"is-active":f(e.sessionCode),"is-editing":o.value===e.sessionCode,session:e,onClick:p,onDelete:h,onEdit:m,onRenameCancel:_,onRenameConfirm:g},null,8,[`is-active`,`is-editing`,`session`]))),128))]),_:2},1032,[`current-session-code`,`sessions`,`title`]))),128)),l.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,rUt,[(0,t.createElementVNode)(`span`,iUt,[((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(3,e=>(0,t.createElementVNode)(`i`,{key:e,class:`history-dropdown-loading-dot`,style:(0,t.normalizeStyle)({"--dot-index":e-1})},null,4)),64))])])):(0,t.createCommentVNode)(`v-if`,!0)],64)):((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Js),{key:1,description:a.value?(0,t.unref)(R9)(`搜索为空`):(0,t.unref)(R9)(`暂无对话`),scene:`part`,style:{"margin-top":`100px`},type:a.value?`search-empty`:`empty`},null,8,[`description`,`type`]))])],32))}}),[[`__scopeId`,`data-v-bf2401b6`]]);function sUt(e){return e.sessionBusinessManager?UHt({triggerRef:e.triggerRef,panelComponent:oUt,panelProps:{sessionBusinessManager:e.sessionBusinessManager,onSessionSwitch:e.onSessionSwitch,onSessionDelete:e.onSessionDelete,onSessionRename:e.onSessionRename},tippyOptions:{placement:`bottom-end`,offset:[0,8],appendTo:()=>document.querySelector(`.ai-blueking-panel`)||document.body}}):{handleTriggerClick:()=>{},show:()=>{},hide:()=>{},toggle:()=>{},destroy:()=>{},isVisible:()=>!1}}var cUt={class:`left-section`},lUt={class:`logo`},uUt=[`src`],dUt={key:0,class:`rename-tooltip`},fUt={class:`rename-content`},pUt={key:0,class:`tippy-dropdown-menu`},mUt={key:1,class:`bkai-icon bkai-auto-refresh-line`},hUt={class:`right-section`},gUt=z9((0,t.defineComponent)({__name:`index`,props:{title:{default:``},agentName:{default:``},sessionName:{default:``},isCompressionHeight:{type:Boolean,default:!1},draggable:{type:Boolean,default:!0},showHistoryIcon:{type:Boolean,default:!0},showNewChatIcon:{type:Boolean,default:!0},showCompressionIcon:{type:Boolean,default:!0},showMoreIcon:{type:Boolean,default:!0},enableChatSession:{type:Boolean,default:!0},hasPermission:{type:Boolean,default:!0},chatGroup:{default:()=>({enabled:!1,staff:[],username:``})},hasSessionContents:{type:Boolean},autoGenerateLoading:{type:Boolean},dropdownMenuConfig:{default:()=>({showRename:!0,showAutoGenerate:!0,showShare:!1})},sessionBusinessManager:{default:void 0},selectedLlmCode:{default:void 0},renderMode:{default:G8.Chat}},emits:[`close`,`toggle-compression`,`new-chat`,`history-click`,`auto-generate-name`,`help-click`,`rename`,`share`,`history-session-switch`,`history-session-delete`,`history-session-rename`,`new-chat-created`],setup(e,{expose:n,emit:r}){let i=e,a=r,o=yhe,s=(0,t.ref)(null),l=(0,t.ref)(null),u=(0,t.useTemplateRef)(`moreMenuTippyRef`),d=(0,t.ref)(!1),f=(0,t.ref)(``),p=(0,t.ref)(null),m=(0,t.ref)(!1),h=()=>document.querySelector(`.ai-blueking-panel`)||document.body,g=null,_=()=>{!l.value||!i.sessionBusinessManager||(g=sUt({triggerRef:l,sessionBusinessManager:i.sessionBusinessManager,onSessionSwitch:e=>a(`history-session-switch`,e),onSessionDelete:e=>a(`history-session-delete`,e),onSessionRename:(e,t)=>a(`history-session-rename`,e,t)}))},v=(0,t.computed)(()=>i.hasPermission?i.enableChatSession?i.title||`${i.agentName||``}-${i.sessionName||``}`:i.agentName:R9(`无智能体使用权限`)),y=(0,t.computed)(()=>i.isCompressionHeight?`bkai-morenchicun`:`bkai-yasuo`),b=(0,t.computed)(()=>i.isCompressionHeight?R9(`恢复默认尺寸`):R9(`缩小高度`)),x=(0,t.computed)(()=>i.hasPermission),S=e=>x.value?e:R9(`暂无使用权限`),C=()=>({cursor:x.value?`pointer`:`not-allowed`}),w=(0,t.ref)(!1),T=async()=>{if(!w.value){w.value=!0;try{if(i.sessionBusinessManager)try{let e=await i.sessionBusinessManager.createNewSession({model:i.selectedLlmCode});e&&a(`new-chat-created`,{sessionCode:e.sessionCode,sessionName:e.sessionName,createdAt:e.createdAt})}catch(e){console.error(`Failed to create new session:`,e),nc({theme:`error`,message:R9(`创建会话失败`)})}a(`new-chat`)}finally{w.value=!1}}},E=e=>{e.stopPropagation(),i.sessionBusinessManager?(g||_(),g&&g.handleTriggerClick(e)):a(`history-click`,e)},D=()=>{a(`help-click`)},O=e=>{e.stopPropagation(),g&&g.isVisible()&&g.hide(),u.value&&(m.value?u.value.hide():u.value.show())},k=()=>{u.value?.hide(),M()},A=()=>{!i.hasSessionContents||i.autoGenerateLoading||a(`auto-generate-name`)},j=()=>{i.hasSessionContents&&(u.value?.hide(),a(`share`))},M=()=>{document.removeEventListener(`click`,I),f.value=i.sessionName||``,d.value=!0,setTimeout(()=>{document.addEventListener(`click`,I)},100),setTimeout(()=>{if(p.value)try{let e=p.value;e&&typeof e.focus==`function`&&e.focus();let t=e.$el?.querySelector(`input`);t&&typeof t.select==`function`&&t.select()}catch(e){console.warn(`Failed to focus rename input:`,e)}},100)},N=()=>{let e=f.value.trim();if(!e){P();return}a(`rename`,e),d.value=!1,f.value=``},P=()=>{d.value=!1,f.value=``},F=(e,t)=>{f.value=e,t.key===`Enter`?N():t.key===`Escape`&&P()},I=e=>{if(!d.value)return;let t=e.target,n=document.querySelector(`.rename-tooltip`);n&&!n.contains(t)&&P()};return(0,t.watch)(()=>i.autoGenerateLoading,(e,t)=>{t&&!e&&m.value&&u.value?.hide()}),(0,t.onMounted)(()=>{i.sessionBusinessManager&&_(),document.addEventListener(`click`,I)}),(0,t.onBeforeUnmount)(()=>{g&&=(g.destroy(),null),document.removeEventListener(`click`,I)}),n({headerRef:s,historyIconRef:l}),(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{ref_key:`headerRef`,ref:s,class:(0,t.normalizeClass)([`ai-header drag-handle`,{draggable:i.draggable}])},[(0,t.createElementVNode)(`div`,cUt,[(0,t.createElementVNode)(`div`,lUt,[(0,t.createElementVNode)(`img`,{alt:`logo`,src:(0,t.unref)(FVt)},null,8,uUt)]),(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`title`,{"title-with-tooltip":d.value}])},[(0,t.createTextVNode)((0,t.toDisplayString)(v.value)+` `,1),(0,t.createCommentVNode)(` 重命名 tooltip 直接绑定在 title 上 `),d.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,dUt,[(0,t.createElementVNode)(`div`,fUt,[(0,t.createVNode)((0,t.unref)(ts),{ref_key:`renameInputRef`,ref:p,modelValue:f.value,"onUpdate:modelValue":r[0]||=e=>f.value=e,class:`rename-input`,placeholder:(0,t.unref)(R9)(`请输入新的会话名称`),onKeyup:F},null,8,[`modelValue`,`placeholder`]),(0,t.createElementVNode)(`div`,{class:`rename-buttons`},[(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-check-1 rename-btn confirm-btn`,onClick:N}),(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-close rename-btn cancel-btn`,onClick:P})])])])):(0,t.createCommentVNode)(`v-if`,!0)],2),(0,t.createCommentVNode)(` 更多图标下拉菜单 - 使用 vue-tippy `),i.showMoreIcon&&x.value?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Kl),{key:0,ref_key:`moreMenuTippyRef`,ref:u,arrow:!1,"append-to":h,offset:[0,4],interactive:``,placement:`bottom-start`,theme:`ai-blueking-light more-menu-light light`,trigger:`manual`,onHidden:r[1]||=e=>m.value=!1,onShown:r[2]||=e=>m.value=!0},{content:(0,t.withCtx)(()=>[m.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,pUt,[i.dropdownMenuConfig?.showRename?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:0,class:`tippy-menu-item`,onClick:k},[r[7]||=(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-bianji`},null,-1),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`重命名`)),1)])):(0,t.createCommentVNode)(`v-if`,!0),i.dropdownMenuConfig?.showAutoGenerate?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:1,class:(0,t.normalizeClass)([`tippy-menu-item`,{disabled:!i.hasSessionContents||i.autoGenerateLoading}]),onClick:A},[i.autoGenerateLoading?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Io),{key:0,mode:`spin`,size:`mini`,theme:`primary`})):((0,t.openBlock)(),(0,t.createElementBlock)(`i`,mUt)),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`自动生成命名`)),1)],2)),[[(0,t.unref)(Jl),{content:i.hasSessionContents?``:(0,t.unref)(R9)(`请先发起会话`),theme:`ai-blueking-tooltip`,arrow:!0,delay:[300,0],appendTo:h}]]):(0,t.createCommentVNode)(`v-if`,!0),i.dropdownMenuConfig?.showShare&&i.renderMode!==(0,t.unref)(G8).Test?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:2,class:(0,t.normalizeClass)([`tippy-menu-item`,{disabled:!i.hasSessionContents}]),onClick:j},[r[8]||=(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-fenxiang`},null,-1),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`分享会话`)),1)],2)),[[(0,t.unref)(Jl),{content:i.hasSessionContents?``:(0,t.unref)(R9)(`请先发起会话`),theme:`ai-blueking-tooltip`,arrow:!0,delay:[300,0],appendTo:h}]]):(0,t.createCommentVNode)(`v-if`,!0)])):(0,t.createCommentVNode)(`v-if`,!0)]),default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`span`,{class:`bkai-icon bkai-more`,onClick:O})]),_:1},512)):(0,t.createCommentVNode)(`v-if`,!0)]),(0,t.renderSlot)(n.$slots,`headerLeft`,{},void 0,!0),(0,t.createElementVNode)(`div`,hUt,[(0,t.createCommentVNode)(` 新增会话按钮 `),i.showNewChatIcon&&e.enableChatSession!==!1?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:0,class:(0,t.normalizeClass)([`bkai-icon`,`bkai-xinzengliaotian`,{disabled:!x.value||w.value||!e.hasSessionContents}]),style:(0,t.normalizeStyle)(C()),onClick:r[3]||=t=>x.value&&!w.value&&e.hasSessionContents?T():void 0},null,6)),[[(0,t.unref)(o),{content:w.value?(0,t.unref)(R9)(`正在创建会话...`):e.hasSessionContents?S((0,t.unref)(R9)(`新增会话`)):(0,t.unref)(R9)(`当前已是新会话`),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),(0,t.createCommentVNode)(` 历史会话按钮 `),i.showHistoryIcon&&e.enableChatSession!==!1?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:1,ref_key:`historyIconRef`,ref:l,class:(0,t.normalizeClass)([`bkai-icon`,`bkai-history`,{disabled:!x.value}]),style:(0,t.normalizeStyle)(C()),onClick:r[4]||=e=>x.value?E(e):void 0},null,6)),[[(0,t.unref)(o),{content:S((0,t.unref)(R9)(`历史会话`)),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),e.chatGroup?.enabled?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:2,class:`bkai-icon bkai-zhushou`,onClick:D},null,512)),[[(0,t.unref)(o),{content:(0,t.unref)(R9)(`转人工`),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),i.showCompressionIcon?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:3,class:(0,t.normalizeClass)([`bkai-icon`,y.value]),onClick:r[5]||=e=>a(`toggle-compression`)},null,2)),[[(0,t.unref)(o),{content:b.value,boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-close-line-2`,onClick:r[6]||=e=>a(`close`)},null,512),[[(0,t.unref)(o),{content:(0,t.unref)(R9)(`关闭`),boundary:`parent`}]])])],2))}}),[[`__scopeId`,`data-v-6dcebb8e`]]);function _Ut(e){let t=L9(e);fetch(t,{method:`GET`,credentials:`include`}).catch(()=>{})}async function vUt(e,t={}){let{enableModelSelect:n=!0}=t,r=[e.agent.getAgentInfo(),e.session.getSessions()];n&&typeof e.agent.getLlms==`function`&&r.push(e.agent.getLlms().catch(e=>{console.error(`[runAgentBootstrap] Failed to load models:`,e)})),await Promise.all(r);let i=e.agent.info.value?.saasUrl;i&&_Ut(i)}var yUt=class{_isGenerating;_isModelsLoading;_isStopLoading;_models;_selectedLlmCode;_selectedModelName;_selectedModelSupportsVision;agentModule;config;eventEmitter;messageModule;sessionModule;hasValidSelection(){let e=this._selectedLlmCode.value;return!!e&&this._models.value.some(t=>t.llm_code===e)}isSessionPending(){return this.sessionModule!=null&&this.sessionModule.current.value==null}applySessionModel(e){let t=this._models.value;if(t.length===0){this._selectedLlmCode.value=void 0;return}if(this.isSessionPending())return;if(e&&t.some(t=>t.llm_code===e)){this._selectedLlmCode.value=e;return}if(this.hasValidSelection())return;let n=t.find(e=>e.property?.default)??t[0];this._selectedLlmCode.value=n?.llm_code}async persistSessionModel(e){let t=this.sessionModule?.current.value;if(!(!t?.sessionCode||!e)&&t.model!==e)try{await this.sessionModule.updateSession({...t,model:e})}catch(e){console.error(`[ChatBusinessManager] Failed to persist session model:`,e),this.emit(`chat-error`,{action:`persistSessionModel`,error:e})}}resolveChatModel(e){return(e??this._selectedLlmCode.value)||void 0}autoRenameSessionIfNeeded(e){let t=this.sessionModule;if(!t||this.messageModule.list.value.length!==1)return;let n=t.renameSession(e);n&&n.then(n=>{let r=t.list.value.find(t=>t.sessionCode===e)??(t.current?.value?.sessionCode===e?t.current.value:null),i=n?.sessionName??r?.sessionName;i&&this.config.onSessionRenamed?.(i,e)}).catch(e=>{console.error(`[ChatBusinessManager] Auto rename session failed:`,e)})}emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e,n,r=null,i=null,a={}){this.agentModule=e,this.messageModule=n,this.sessionModule=r,this.eventEmitter=i,this.config=a,this._isGenerating=(0,t.ref)(!1),this._isStopLoading=(0,t.ref)(!1),this._isModelsLoading=(0,t.ref)(!1),this._models=(0,t.ref)([]),this._selectedLlmCode=(0,t.ref)(void 0),this._selectedModelName=(0,t.computed)(()=>{let e=this._selectedLlmCode.value;return e?this._models.value.find(t=>t.llm_code===e)?.llm_name??``:``}),this._selectedModelSupportsVision=(0,t.computed)(()=>{let e=this._selectedLlmCode.value;return e?!!this._models.value.find(t=>t.llm_code===e)?.property?.support_vision:!1}),this.sessionModule&&(0,t.watch)(()=>this.sessionModule.current.value?.sessionCode,()=>{this.applySessionModel(this.sessionModule.current.value?.model)})}get isGenerating(){return this._isGenerating}get isStopLoading(){return this._isStopLoading}get isMessagesLoading(){return this.messageModule.isListLoading}get models(){return this._models}get isModelsLoading(){return this._isModelsLoading}get selectedLlmCode(){return this._selectedLlmCode}get selectedModelName(){return this._selectedModelName}get selectedModelSupportsVision(){return this._selectedModelSupportsVision}get messages(){return this.messageModule.list}async loadModels(e={}){this._isModelsLoading.value=!0;try{let t=this.agentModule.models?.value;if(!e.force&&Array.isArray(t)&&t.length>0)this._models.value=[...t];else if(typeof this.agentModule.getLlms==`function`){let e=await this.agentModule.getLlms();this._models.value=Array.isArray(e)?e:[]}else this._models.value=[];this.applySessionModel(this.sessionModule?.current.value?.model)}catch(e){console.error(`[ChatBusinessManager] Failed to load models:`,e),this._models.value=[],this._selectedLlmCode.value=void 0}finally{this._isModelsLoading.value=!1}}setModels(e){this._models.value=e,this.applySessionModel(this.sessionModule?.current.value?.model)}setSelectedModelByName(e){if(!e){this._selectedLlmCode.value=void 0;return}let t=this._models.value.find(t=>t.llm_name===e);this._selectedLlmCode.value=t?.llm_code,this.persistSessionModel(t?.llm_code)}setSelectedModel(e){this._selectedLlmCode.value=e?.llm_code,this.persistSessionModel(e?.llm_code)}get openingRemark(){return this.config.openingRemark||``}get predefinedQuestions(){return this.config.predefinedQuestions||[]}async batchDeleteMessages(e){try{await this.messageModule.deleteMessages(e);let t=e.map(e=>e.id).filter(Boolean);this.emit(`messages-batch-deleted`,{messageIds:t})}catch(e){throw console.error(`Failed to batch delete messages:`,e),this.emit(`chat-error`,{action:`batch-delete-messages`,error:e}),e}}async deleteMessage(e){try{await this.messageModule.deleteMessages([e]),this.emit(`message-deleted`,{messageId:e.id})}catch(e){throw console.error(`Failed to delete message:`,e),this.emit(`chat-error`,{action:`delete-message`,error:e}),e}}handleStreamEnd(){this._isGenerating.value=!1,this.emit(`receive-end`,{})}handleStreamError(e){this._isGenerating.value=!1,this.emit(`receive-error`,{error:e})}handleStreamStart(){this._isGenerating.value=!0,this.emit(`receive-start`,{})}async regenerateFromAIMessages(e,t){try{if(!e||e.length===0)throw Error(`No AI messages provided`);let n=this.messages.value,r=I9(n,e[0]);if(!r)throw Error(`No user message found before AI messages`);let i=r.id;if(i===void 0)throw Error(`User message has no id`);await this.regenerateMessage(String(i),t)}catch(e){throw console.error(`Failed to regenerate from AI messages:`,e),this.emit(`chat-error`,{action:`regenerate`,error:e}),e}}async regenerateMessage(e,t){try{let n=this.messages.value,r=n.findIndex(t=>String(t.id)===e);if(r===-1)throw Error(`Message not found: ${e}`);let i=n[r];if(i.role!==g9.User)throw Error(`Can only regenerate from user messages`);let a=n.slice(r),o=typeof i.content==`string`?i.content:JSON.stringify(i.content),s=i.property;this._isGenerating.value=!0;let l=this.messageModule.deleteMessages(a);this.agentModule.chat(o,t,void 0,void 0,s,this.resolveChatModel()),this.emit(`chat-regenerate`,{messageId:e}),l.catch(e=>{console.error(`[regenerateMessage] Delete API error:`,e)})}catch(e){throw console.error(`Failed to regenerate message:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`regenerate`,error:e}),e}}async resendMessageWithProperty(e,t,n,r){try{let i=this.messages.value,a=i.findIndex(t=>String(t.id)===e);if(a===-1)throw Error(`Message not found: ${e}`);if(i[a].role!==g9.User)throw Error(`Can only resend user messages`);let o=i.slice(a);this._isGenerating.value=!0;let s=this.messageModule.deleteMessages(o);this.agentModule.chat(n,t,void 0,void 0,r,this.resolveChatModel()),this.emit(`chat-resend`,{messageId:e}),s.catch(e=>{console.error(`[resendMessageWithProperty] Delete API error:`,e)})}catch(e){throw console.error(`Failed to resend message with property:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`resend`,error:e}),e}}async retryMessage(e){try{console.warn(`retryMessage not implemented yet`),this.emit(`chat-retry`,{messageId:e})}catch(e){throw console.error(`Failed to retry message:`,e),this.emit(`chat-error`,{action:`retry`,error:e}),e}}async sendMessage(e,t,n={}){try{if(!t)throw Error(`No active session. Please create or select a session first.`);this._isGenerating.value=!0,this.emit(`send-message`,{content:e}),await this.agentModule.chat(e,t,void 0,void 0,n.property,this.resolveChatModel(n.model)),this.autoRenameSessionIfNeeded(t)}catch(e){throw console.error(`Failed to send message:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`send`,error:e}),e}}async stopGeneration(){let e=this.sessionModule?.current?.value?.sessionCode??``;this._isStopLoading.value=!0;try{this.agentModule.abortChat(),await this.agentModule.stopChat(e),this._isGenerating.value=!1,this.emit(`stop`,{})}catch(e){throw console.error(`Failed to stop generation:`,e),this.emit(`chat-error`,{action:`stop`,error:e}),e}finally{this._isStopLoading.value=!1}}},B9=class{agentModule;config;eventEmitter;messageModule;sessionModule;emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e,t=null,n=null,r={},i=null){this.sessionModule=e,this.agentModule=t,this.eventEmitter=n,this.config=r,this.messageModule=i}get currentSession(){return this.sessionModule.current}get isCreateLoading(){return this.sessionModule.isCreateLoading}get isCurrentLoading(){return this.sessionModule.isCurrentLoading}get isDeleteLoading(){return this.sessionModule.isDeleteLoading}get isListLoading(){return this.sessionModule.isListLoading}get isLoadingMore(){return this.sessionModule.isLoadingMore}get isUpdateLoading(){return this.sessionModule.isUpdateLoading}get hasMoreSessions(){return this.sessionModule.hasMore}get sessionCount(){return this.sessionModule.count}get sessionList(){return this.sessionModule.list}async createNewSession(e){let t=this.currentSession.value;if(t?.sessionCode&&this.isCurrentSessionEmpty(t))return null;await this.loadSessions();let n=this.sessionList.value;if(n.length>0){let r=n[0];if(r.sessionCode===t?.sessionCode?this.isCurrentSessionEmpty(r):this.isSessionEmpty(r))return await this.syncSessionModelIfNeeded(e?.model,r),await this.switchSession(r.sessionCode,{loadMessages:!1}),null}return await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode(),model:e?.model}),this.sessionModule.current.value}generateSessionCode(){return`new_session_${Date.now()}`}async syncSessionModelIfNeeded(e,t){if(!e)return;let n=t??this.sessionModule.current.value;!n?.sessionCode||n.model===e||await this.sessionModule.updateSession({...n,model:e})}async createSession(e={}){if(this.config.enableChatSession===!1)throw Error(`Chat session is disabled`);try{let t={sessionName:e.name||`新会话`,sessionCode:e.sessionCode||`session_${Date.now()}`,isTemporary:e.isTemporary||!1,...e.model?{model:e.model}:{},sessionProperty:{labels:e.labels}};await this.sessionModule.createSession(t);let n=this.agentModule?.info.value;n&&this.agentModule?.handleRole(n,t.sessionCode),this.emit(`session-created`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to create session:`,e),this.emit(`session-error`,{action:`create`,error:e}),e}}async deleteSession(e){try{await this.sessionModule.deleteSession(e),this.emit(`session-deleted`,{sessionCode:e})}catch(e){throw console.error(`Failed to delete session:`,e),this.emit(`session-error`,{action:`delete`,error:e}),e}}async getSession(e){try{await this.sessionModule.getSession(e)}catch(e){throw console.error(`Failed to get session:`,e),this.emit(`session-error`,{action:`get`,error:e}),e}}isSessionEmpty(e){let t=this.findSession(e.sessionCode)?.sessionContentCount??e.sessionContentCount;return t==null?!1:t===0}isCurrentSessionEmpty(e){return this.messageModule&&kHt(this.messageModule.list.value)?!1:this.isSessionEmpty(e)}findSession(e){return this.sessionList.value.find(t=>t.sessionCode===e)}async loadRecentSession(e){try{if(this.currentSession.value?.sessionCode)return;e?.skipLoadSessions||await this.loadSessions();let t=this.sessionList.value;if(this.config.initialSessionCode){let e=this.findSession(this.config.initialSessionCode);await this.switchSession(this.config.initialSessionCode,{loadMessages:e?!this.isSessionEmpty(e):!0});return}if(t.length>0){let n=t[0],r=(n.sessionContentCount??0)>0,i=e?.alwaysCreateNewSession??this.config.alwaysCreateNewSession??!1;r||i?await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode()}):await this.switchSession(n.sessionCode,{loadMessages:!1});return}await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode()})}catch(e){throw console.error(`Failed to load recent session:`,e),e}}async loadSessions(){try{await this.sessionModule.getSessions(),this.emit(`sessions-loaded`,{sessions:this.sessionList.value})}catch(e){throw console.error(`Failed to load sessions:`,e),this.emit(`session-error`,{action:`load`,error:e}),e}}async loadMoreSessions(){try{await this.sessionModule.loadMoreSessions()}catch(e){throw console.error(`Failed to load more sessions:`,e),this.emit(`session-error`,{action:`loadMore`,error:e}),e}}async switchSession(e,t){try{await this.sessionModule.chooseSession(e,t),this.emit(`session-switched`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to switch session:`,e),this.emit(`session-error`,{action:`switch`,error:e}),e}}async updateSessionName(e,t){try{let n=this.sessionList.value.find(t=>t.sessionCode===e);if(!n)throw Error(`Session not found: ${e}`);await this.sessionModule.updateSession({...n,sessionName:t}),this.emit(`session-updated`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to update session name:`,e),this.emit(`session-error`,{action:`update`,error:e}),e}}},bUt=class{messageModule;sessionModule;constructor(e,t){this.messageModule=e,this.sessionModule=t}async shareMessages(e){if(e.length===0)throw Error(`No messages to share`);let t=this.sessionModule.current?.value?.sessionCode;if(!t)throw Error(`No active session`);let n=await this.messageModule.shareMessages(t,e);if(!n)throw Error(`Share failed: no result returned`);return{shareUrl:`${n.share_page}share-page/${n.share_token}`,userMessageIds:e.map(e=>String(e.id))}}},V9=class{_agentShortcuts;_effectiveShortcuts;_propsShortcuts;eventEmitter;emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e=null,n=[]){this._propsShortcuts=(0,t.ref)(n),this._agentShortcuts=(0,t.ref)([]),this.eventEmitter=e,this._effectiveShortcuts=(0,t.computed)(()=>this._propsShortcuts.value.length>0?this._propsShortcuts.value:this._agentShortcuts.value.length>0?this._agentShortcuts.value:[])}get count(){return this._effectiveShortcuts.value.length}get effectiveShortcuts(){return this._effectiveShortcuts}get hasShortcuts(){return this._effectiveShortcuts.value.length>0}get shortcuts(){return this._effectiveShortcuts}addShortcut(e){this._propsShortcuts.value.push(e)}clear(){this._propsShortcuts.value=[],this._agentShortcuts.value=[]}filterByTextLength(e,t){return!e||e.length>t?[]:this._effectiveShortcuts.value}filterShortcuts(e,t){return t?this._effectiveShortcuts.value.filter(n=>t(n,e)):this._effectiveShortcuts.value}getShortcutById(e){return this._effectiveShortcuts.value.find(t=>t.id===e)}handleShortcutClick(e,t,n=`main`){this.emit(`shortcut-click`,{shortcut:e,selectedText:t,source:n})}limitShortcuts(e){return this._effectiveShortcuts.value.slice(0,e)}removeShortcut(e){this._propsShortcuts.value=this._propsShortcuts.value.filter(t=>t.id!==e)}setAgentShortcuts(e){this._agentShortcuts.value=e}setShortcuts(e){this._propsShortcuts.value=e}},xUt=class{_isCompressed;_isDraggingOrResizing;_nimbusMinimized;_panelVisible;_positionAndSize;cleanupFunctions;config;containerRef=null;debugMode;listeners;onceListeners;constructor(e={}){this.config=e,this.listeners=new Map,this.onceListeners=new Map,this.debugMode=e.debug??!1,this.cleanupFunctions=[],this._panelVisible=(0,t.ref)(e.initialPanelVisible??!1),this._nimbusMinimized=(0,t.ref)(e.initialNimbusMinimized??!1),this._isDraggingOrResizing=(0,t.ref)(!1),this._isCompressed=(0,t.ref)(!1),this._positionAndSize=(0,t.ref)({x:0,y:0,width:400,height:window.innerHeight})}get container(){return{updatePosition:this.updatePosition.bind(this),updateSize:this.updateSize.bind(this),updatePositionAndSize:this.updatePositionAndSize.bind(this),toggleCompression:this.toggleCompression.bind(this),expandForSidePanel:this.expandForSidePanel.bind(this),collapseSidePanel:this.collapseSidePanel.bind(this),positionAndSize:(0,t.computed)(()=>this.containerRef?.positionAndSize?.value??this._positionAndSize.value),isCompressed:(0,t.computed)(()=>this._isCompressed.value),isSidePanelExpanded:(0,t.computed)(()=>this.containerRef?.isSidePanelExpanded?.value??!1)}}get isCompressed(){return this._isCompressed}get isDraggingOrResizing(){return this._isDraggingOrResizing}get nimbus(){return{minimize:this.minimizeNimbus.bind(this),restore:this.restoreNimbus.bind(this),toggle:this.toggleNimbus.bind(this),isMinimized:(0,t.computed)(()=>this._nimbusMinimized.value)}}get nimbusMinimized(){return this._nimbusMinimized}get panel(){return{show:this.showPanel.bind(this),hide:this.hidePanel.bind(this),toggle:this.togglePanel.bind(this),isVisible:(0,t.computed)(()=>this._panelVisible.value)}}get panelVisible(){return this._panelVisible}get state(){return{panelVisible:this._panelVisible,nimbusMinimized:this._nimbusMinimized,isDraggingOrResizing:this._isDraggingOrResizing,positionAndSize:this._positionAndSize}}collapseSidePanel(){this.containerRef?.collapseSidePanel&&this.containerRef.collapseSidePanel()}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],this.debugMode&&console.debug(`[ComponentManager] Destroyed`)}emit(e,t){this.debugMode&&console.debug(`[ComponentManager] Emitting "${e}"`,t);let n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(t){console.error(`[ComponentManager] Error in listener for "${e}":`,t)}});let r=this.onceListeners.get(e);if(r&&r.size>0){let n=Array.from(r);this.onceListeners.delete(e),n.forEach(n=>{try{n(t)}catch(t){console.error(`[ComponentManager] Error in once listener for "${e}":`,t)}})}}emitInternal(e,t){this.emit(e,t)}expandForSidePanel(e){this.containerRef?.expandForSidePanel&&this.containerRef.expandForSidePanel(e)}getConfig(){return this.config}getRegisteredEvents(){let e=new Set;return this.listeners.forEach((t,n)=>e.add(n)),this.onceListeners.forEach((t,n)=>e.add(n)),Array.from(e)}handleDragging(e){this._isDraggingOrResizing.value=!0,this._positionAndSize.value=e,this.emit(`dragging`,e)}handleDragStop(e){this._isDraggingOrResizing.value=!1,this._positionAndSize.value=e,this.emit(`drag-stop`,e)}handleNimbusClick(){this.emit(`nimbus-click`,{}),this.showPanel()}handlePopupClick(){this.emit(`popup-click`,{}),this.showPanel()}handlePopupShortcutClick(e){this.emit(`popup-shortcut-click`,{shortcut:e}),this.emit(`shortcut-click`,{shortcut:e,source:`popup`})}handleResizeStop(e){this._isDraggingOrResizing.value=!1,this._positionAndSize.value=e,this.emit(`resize-stop`,e)}handleResizing(e){this._isDraggingOrResizing.value=!0,this._positionAndSize.value=e,this.emit(`resizing`,e)}handleShortcutClick(e,t){this.emit(`shortcut-click`,{shortcut:e,source:t})}hasListeners(e){return this.listenerCount(e)>0}hidePanel(){this._panelVisible.value=!1,this.emit(`panel-hide`,{})}listenerCount(e){return(this.listeners.get(e)?.size??0)+(this.onceListeners.get(e)?.size??0)}minimizeNimbus(){this._nimbusMinimized.value=!0,this.emit(`nimbus-minimize`,{})}off(e,t){t?(this.listeners.get(e)?.delete(t),this.onceListeners.get(e)?.delete(t),this.debugMode&&console.debug(`[ComponentManager] Unsubscribed from "${e}", remaining: ${this.listenerCount(e)}`)):(this.listeners.delete(e),this.onceListeners.delete(e),this.debugMode&&console.debug(`[ComponentManager] Removed all listeners for "${e}"`))}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.debugMode&&console.debug(`[ComponentManager] Subscribed to "${e}", total: ${this.listenerCount(e)}`),()=>{this.off(e,t)}}once(e,t){return this.onceListeners.has(e)||this.onceListeners.set(e,new Set),this.onceListeners.get(e).add(t),this.debugMode&&console.debug(`[ComponentManager] Subscribed once to "${e}"`),()=>{this.onceListeners.get(e)?.delete(t)}}restoreNimbus(){this._nimbusMinimized.value=!1,this.emit(`nimbus-restore`,{})}setCompressed(e){this._isCompressed.value=e}setContainerRef(e){this.containerRef=e,e?.isCompressed&&(this._isCompressed.value=e.isCompressed.value)}setDebugMode(e){this.debugMode=e}setDraggingOrResizing(e){this._isDraggingOrResizing.value=e}showPanel(e){this._panelVisible.value=!0,this.emit(`panel-show`,{sessionCode:e})}toggleCompression(){this.containerRef?this.containerRef.toggleCompression():this._isCompressed.value=!this._isCompressed.value}toggleNimbus(){this._nimbusMinimized.value?this.restoreNimbus():this.minimizeNimbus()}togglePanel(){this._panelVisible.value?this.hidePanel():this.showPanel()}updatePosition(e,t){this._positionAndSize.value={...this._positionAndSize.value,x:e,y:t}}updatePositionAndSize(e,t,n,r){this._positionAndSize.value={x:e,y:t,width:n,height:r}}updateSize(e,t){this._positionAndSize.value={...this._positionAndSize.value,width:e,height:t}}};function SUt(e){return new xUt(e)}var CUt={"panel-show":`show`,"panel-hide":`close`,"panel-toggle":null,"nimbus-click":null,"nimbus-minimize":null,"nimbus-restore":null,"popup-click":null,"popup-shortcut-click":null,dragging:`dragging`,resizing:`resizing`,"drag-stop":`drag-stop`,"resize-stop":`resize-stop`,"compression-toggle":null,"side-panel-expand":null,"side-panel-collapse":null,"send-message":`send-message`,"receive-start":`receive-start`,"receive-text":`receive-text`,"receive-end":`receive-end`,"receive-error":null,stop:`stop`,"chat-regenerate":null,"chat-retry":null,"message-deleted":null,"messages-batch-deleted":null,"session-created":null,"session-switched":null,"session-deleted":null,"session-updated":null,"sessions-loaded":null,"session-initialized":`session-initialized`,"session-error":null,"shortcut-click":`shortcut-click`,"chat-error":null,"sdk-error":`sdk-error`,"new-chat":`new-chat`,"new-chat-created":`new-chat-created`,"history-click":`history-click`,"auto-generate-name":`auto-generate-name`,"help-click":`help-click`,rename:`rename`,share:`share`,close:`close`,"toggle-compression":null,"transfer-messages":`transfer-messages`,"share-messages":`share-messages`,"agent-info-loaded":null,error:null};function wUt(e,t){switch(e){case`send-message`:return[t.content];case`rename`:return[t.newName,t.sessionCode];case`history-click`:return[t.event];case`dragging`:case`resizing`:case`drag-stop`:case`resize-stop`:case`shortcut-click`:case`session-initialized`:case`sdk-error`:case`transfer-messages`:case`share-messages`:case`new-chat-created`:return[t];case`panel-show`:case`panel-hide`:case`receive-start`:case`receive-text`:case`receive-end`:case`stop`:case`new-chat`:case`auto-generate-name`:case`help-click`:case`share`:case`close`:return[];default:return[t]}}var TUt=class{_selectedMessageIds;_isSelectionMode;_editingSessionCode;_loadingStates;constructor(){this._selectedMessageIds=(0,t.ref)(new Set),this._isSelectionMode=(0,t.ref)(!1),this._editingSessionCode=(0,t.ref)(null),this._loadingStates=(0,t.reactive)({})}get isSelectionMode(){return this._isSelectionMode}get editingSessionCode(){return this._editingSessionCode}toggleSelectionMode(){this._isSelectionMode.value=!this._isSelectionMode.value,this._isSelectionMode.value||this.clearSelection()}enableSelectionMode(){this._isSelectionMode.value=!0}disableSelectionMode(){this._isSelectionMode.value=!1,this.clearSelection()}toggleMessageSelection(e){this._selectedMessageIds.value.has(e)?this._selectedMessageIds.value.delete(e):this._selectedMessageIds.value.add(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}selectMessage(e){this._selectedMessageIds.value.add(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}deselectMessage(e){this._selectedMessageIds.value.delete(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}isMessageSelected(e){return this._selectedMessageIds.value.has(e)}clearSelection(){this._selectedMessageIds.value.clear(),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}selectAllMessages(e){this._selectedMessageIds.value=new Set(e)}get selectedMessages(){return Array.from(this._selectedMessageIds.value)}get selectedCount(){return this._selectedMessageIds.value.size}get hasSelection(){return this._selectedMessageIds.value.size>0}startEditingSession(e){this._editingSessionCode.value=e}stopEditingSession(){this._editingSessionCode.value=null}isEditingSession(e){return e?this._editingSessionCode.value===e:this._editingSessionCode.value!==null}setLoading(e,t){this._loadingStates[e]=t}isLoading(e){return this._loadingStates[e]??!1}clearLoadingStates(){Object.keys(this._loadingStates).forEach(e=>{this._loadingStates[e]=!1})}reset(){this.clearSelection(),this.disableSelectionMode(),this.stopEditingSession(),this.clearLoadingStates()}},EUt=class extends Error{constructor(){super(`[ChatBot] Initialization was superseded by a newer init`),this.name=`ChatBotInitStaleError`}};function DUt(e){let{props:n,emit:r,reportError:i,managerErrorBridge:a}=e,o=(0,t.shallowRef)(null),s=(0,t.shallowRef)(null),l=(0,t.shallowRef)(null),u=(0,t.shallowRef)(null),d=(0,t.ref)(!1),f=(0,t.ref)(!n.chatHelper),p=(0,t.ref)(null),m=(0,t.computed)(()=>d.value),h=()=>n.chatHelper?!n.chatHelper.agent||!n.chatHelper.session||!n.chatHelper.message?{valid:!1,error:`[ChatBot] Invalid chatHelper: missing required modules (agent, session, message)`}:{valid:!0}:n.url?{valid:!0}:{valid:!1,error:`[ChatBot] Neither chatHelper nor url provided. Component requires at least one.`},g=()=>{let e=h();if(!e.valid)return console.error(e.error),p.value=Error(e.error),null;if(n.chatHelper)return n.chatHelper;let a=new w9({onStart:()=>{r(`receive-start`)},onMessage:e=>{r(`receive-text`)},onDone:()=>{r(`receive-end`)},onError:e=>{i(e,`Stream error`)}}),o=P9({requestData:EHt(L9(n.url),()=>(0,t.toValue)(n.requestOptions)),protocol:a});return a.injectMessageModule(o.message),o},_=e=>{if(e)try{e.agent.abortChat(),e.agent.clearLongPollTimer?.()}catch{}},v=0,y=null,b=null,x=null,S=e=>{x&&=(e?x.reject(e):x.resolve(),null),y=null},C=e=>{if(e!==v)throw new EUt},w=async e=>{let t=o.value;d.value=!1,p.value=null,f.value=!n.chatHelper,_(t),C(e),o.value=null,s.value=null,l.value=null,u.value=null;let m=g();if(!m)throw p.value??Error(`[ChatBot] Failed to create chatHelper`);let h=new B9(m.session,m.agent,a,{enableChatSession:!0,autoSwitchToInitialSession:!!n.sessionCode,loadRecentSessionOnMount:n.autoLoad,initialSessionCode:n.sessionCode,alwaysCreateNewSession:n.alwaysCreateNewSession},m.message),v=new yUt(m.agent,m.message,m.session,a,{openingRemark:n.helloText,predefinedQuestions:n.prompts,placeholder:n.placeholder,onSessionRenamed:(e,t)=>r(`rename`,e,t)}),y=new V9(null,n.shortcuts||[]);o.value=m,s.value=h,l.value=v,u.value=y;try{f.value&&(await vUt(m,{enableModelSelect:n.enableModelSelect!==!1&&!n.models?.length}),C(e),await h.loadRecentSession({skipLoadSessions:!0}),C(e)),n.enableModelSelect!==!1&&(n.models?.length?v.setModels(n.models):await v.loadModels(),C(e)),C(e),d.value=!0,r(`agent-info-loaded`,m)}catch(t){throw C(e),p.value=i(t,`Failed to initialize ChatBot`),t}},T=()=>{S(new EUt),b=null;let e=++v;y=new Promise((t,n)=>{x={resolve:t,reject:n},w(e).then(()=>{x&&=(b=Promise.resolve(),x.resolve(),null)}).catch(e=>{x&&=(x.reject(MHt(e)),null)}).finally(()=>{e===v&&(y=null)})}),y.catch(()=>{})};return(0,t.watch)([()=>n.url,()=>n.chatHelper],()=>T(),{immediate:!0}),(0,t.onBeforeUnmount)(()=>{S(),_(o.value)}),{chatHelper:o,isStandaloneMode:f,isInitialized:d,isReady:m,initError:p,whenReady:()=>d.value?(b||=Promise.resolve(),b):p.value?Promise.reject(p.value):y||Promise.resolve(),chatBusinessManager:l,sessionBusinessManager:s,shortcutManager:u}}function OUt(e){let{props:n,chatHelper:r,chatBusinessManager:i,sessionBusinessManager:a,shortcutManager:o,isStandaloneMode:s,isInitialized:l,selectedShortcut:u}=e,d=(0,t.computed)(()=>i.value?.isStopLoading.value?H8.StopLoading:((n.chatHelper||r.value)?.agent)?.isChatting?.value?H8.Streaming:H8.Complete),f=(0,t.computed)(()=>d.value===H8.Streaming?Y7.Disabled:void 0),p=(0,t.computed)(()=>i.value?.messages.value??[]),m=(0,t.computed)(()=>i.value?.isMessagesLoading.value??!1);return{messageStatus:d,messageToolsStatus:f,messages:p,isMessagesLoading:m,isGenerating:(0,t.computed)(()=>i.value?.isGenerating.value??!1),currentSession:(0,t.computed)(()=>a.value?.currentSession.value??null),isWelcomeState:(0,t.computed)(()=>s.value&&!l.value?!1:!m.value&&p.value.length===0),openingRemark:(0,t.computed)(()=>r.value?.agent.info.value?.conversationSettings?.openingRemark||``),effectiveResources:(0,t.computed)(()=>n.resources?.length?n.resources:r.value?.agent.info.value?.resources??[]),effectivePrompts:(0,t.computed)(()=>n.prompts?.length?n.prompts:r.value?.agent.info.value?.conversationSettings?.predefinedQuestions??[]),effectiveSkills:(0,t.computed)(()=>n.skills?.length?n.skills:(r.value?.agent.info.value?.relatedSkills??[]).map(e=>({skill_name:e.skill_name,skill_code:e.skill_code,description:e.description,icon:e.icon}))),effectiveSupportUpload:(0,t.computed)(()=>u.value?.supportUpload?u.value.supportUpload.vision===!0:i.value?.selectedModelSupportsVision.value??!1),chatbotStyle:(0,t.computed)(()=>({height:typeof n.height==`number`?`${n.height}px`:n.height,maxWidth:typeof n.maxWidth==`number`?`${n.maxWidth}px`:n.maxWidth})),filteredShortcuts:(0,t.computed)(()=>o.value?.shortcuts.value??[])}}var kUt=new Set([`chat-error`,`receive-error`,`session-error`]);function AUt(e,n={}){let r=new WeakSet,i=(i,a)=>{let o=MHt(i);return r.has(o)?o:(r.add(o),console.error(a?`[ChatBot] ${a}:`:`[ChatBot] error:`,i),e(`error`,o),(0,t.toValue)(n.errorToast)!==!1&&nc({message:o.message||R9(`请求失败`),theme:`error`}),o)};return{managerErrorBridge:{emit:(e,t)=>{kUt.has(e)&&i(t?.error)}},reportError:i}}var jUt={[W8.ApprovalCancel]:y9.ApprovalCancel,[W8.FlowNodeRetry]:y9.FlowNodeRetry,[W8.FlowNodeSkip]:y9.FlowNodeSkip};function MUt(e){return`operation`in e}function NUt(e){return`interruptId`in e&&`reason`in e&&e.reason===z8.UserQuestion}function PUt(e){return e===`cancelled`?C9.Cancelled:C9.Resolved}function FUt(e){let t=e?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot resume interrupt: no active session`);return t}function IUt(e){return{interruptId:e.interruptId,status:PUt(e.status),payload:e.payload}}function LUt(e){let{chatHelper:t,reportError:n}=e,r=async e=>{let n=t.value;if(!n)throw Error(`[ChatBot] Cannot resume interrupt: chatHelper not initialized`);if(!MUt(e))throw Error(`[ChatBot] Unsupported interrupt resume payload`);let r=FUt(n);if(e.operation===W8.ApprovalRefresh){n.agent.pollResumeSession(r);return}let i=jUt[e.operation];if(!i)throw Error(`[ChatBot] Unsupported interrupt resume operation: ${e.operation}`);let a=n.agent;if(e.operation===W8.ApprovalCancel){await a.userOperationStreamRequest(r,i,{interrupt_id:e.payload.interrupt_id});return}(e.operation===W8.FlowNodeRetry||e.operation===W8.FlowNodeSkip)&&await a.userOperationStreamRequest(r,i,{node_id:e.payload.node_id,task_id:String(e.payload.task_id)})},i=async(e,n)=>{let r=t.value;if(!r)throw Error(`[ChatBot] Cannot resume interrupt: chatHelper not initialized`);let i=FUt(r);await r.agent.streamRequest({sessionCode:i,resume:IUt(e),...n?{input:n}:{}})};return{handleInterruptResume:async(e,t)=>{try{if(MUt(e)){await r(e);return}if(NUt(e)){await i(e);return}throw Error(`[ChatBot] Unsupported interrupt resume payload`)}catch(e){n(e,`Failed to handle interrupt resume`)}},resumeUserQuestionWithInput:async(e,t)=>{try{if(!t.payload||!NUt(t.payload))throw Error(`[ChatBot] Invalid user question resume options`);let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`[ChatBot] User question free text input is empty`);await i(t.payload,n)}catch(e){n(e,`Failed to resume user question with input`)}}}}function RUt(e){let{emit:n,chatHelper:r,chatBusinessManager:i,getRequestOptions:a,reportError:o,resumeUserQuestionWithInput:s,selectedShortcut:l,selectedResources:u}=e,d=(0,t.shallowRef)([[]]),f=(0,t.shallowRef)(``),p=(e,t)=>{d.value=e,u.value=t},m=async(e,t={})=>{if(!i.value||!r.value)throw Error(`[ChatBot] Cannot send message: chatBusinessManager not initialized`);let o=r.value.session.current?.value?.sessionCode;if(!o)throw Error(`[ChatBot] Cannot send message: no active session`);d.value=[[]],f.value=``,u.value=[],n(`send-message`,typeof e==`string`?e:``);let s=F9(t.property,a);await i.value.sendMessage(e,o,{...t,...s?{property:s}:{}})},h=async e=>{let t=r.value?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot upload: no active session`);let n=await r.value.session.uploadFile(t,e);if(!n?.download_url)throw Error(`[ChatBot] Upload failed: no download URL returned`);return n},g=async e=>{let t=r.value?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot resolve artifact URL: no active session`);let n=await r.value.session.getPvFileDownloadUrl(t,e.outputId);return{download_url:n?.download_url,preview_url:n?.preview_url}},_=async(e,t,n)=>{try{if(n?.payload&&s){d.value=[[]],f.value=``,u.value=[],await s(e,n);return}let t={};f.value&&(t.cite=f.value),l.value&&(t.command=l.value.id),u.value.length&&(t.resources=u.value),await m(e,Object.keys(t).length?{property:{extra:t}}:{})}catch(e){o(e,`Failed to send message`)}},v=async()=>{await y()},y=async()=>{if(!i.value){console.error(`[ChatBot] Cannot stop generation: chatBusinessManager not initialized`);return}try{await i.value.stopGeneration(),n(`stop`)}catch(e){o(e,`Failed to stop generation`)}};return{userInput:d,cite:f,handleUpdateModelValue:p,doSendMessage:m,handleSendMessage:_,handleArtifactClick:g,handleUpload:h,handleStopSending:v,stopGeneration:y}}var zUt=e=>!e||e.id===`share`;function BUt(e){let{emit:t,chatHelper:n,isStandaloneMode:r}=e,i=async e=>{if(!(!n.value||e.length===0))try{await FHt((await new bUt(n.value.message,n.value.session).shareMessages(e)).shareUrl),nc({message:`分享链接已复制到剪贴板`,theme:`success`})}catch(e){console.error(`[ChatBot] Failed to share messages:`,e),nc({message:`分享失败,请重试`,theme:`error`})}};return{handleConfirmShare:async(e,n)=>{r.value&&zUt(n)&&await i(e),t(`confirm-share`,e,n)}}}function VUt(e){let{props:n,emit:r,shortcutManager:i,doSendMessage:a,reportError:o,selectedShortcut:s}=e,l=(0,t.computed)(()=>i.value?.effectiveShortcuts.value??[]),u=(e,t)=>{let n=e,r;if(r=n.enable_fill_back&&n.fill_back_component_key?n.fill_back_component_key:n.components?.find(e=>e.fillBack)?.key,r&&t){let e=n.components?.map(e=>e.key===r?{...e,default:t}:{...e,default:e.default??void 0});s.value={...n,components:e,formModel:{...n.formModel,[r]:t}}}else s.value={...n,formModel:{...n.formModel}}},d=(e,t)=>{let n=e.components||[];return{extra:{cite:{type:`structured`,title:e.alias||e.name,data:n.map(e=>({key:e.name||e.key,value:String(t[e.key]??``)}))},command:e.id,context:n.map(e=>({[e.key]:t[e.key],context_type:e.type,__label:e.name||e.key,__key:e.key,__value:t[e.key]}))}}},f=e=>{let t=e.property?.extra;return t?.shortcut?t.shortcut:t?.command?l.value.find(e=>e.id===t.command)??null:null},p=(e,t)=>{u(e,t),r(`shortcut-click`,{shortcut:e,source:`main`})},m=()=>{s.value=null};return(0,t.watch)(()=>n.shortcuts,e=>{i.value?.setShortcuts(e||[])},{immediate:!0}),(0,t.watch)(()=>e.chatHelper.value?.agent.info.value?.conversationSettings?.commands,e=>{e&&i.value?.setAgentShortcuts(e)},{immediate:!0}),{effectiveShortcuts:l,selectShortcutWithText:u,buildShortcutProperty:d,getShortcutFromMessage:f,handleSelectShortcut:p,handleCloseShortcut:m,handleShortcutSubmit:async e=>{if(!s.value){console.error(`[ChatBot] No selected shortcut`);return}let t=d(s.value,e),n=s.value.name,r=s.value;m();try{await a(n,{property:t})}catch(e){s.value=r,o(e,`Failed to submit shortcut`)}},sendShortcutDirectly:async(e,t)=>{let n=e,r={...n.formModel},i=n.components||[];for(let e of i)e.key in r||(r[e.key]=e.default??``);let s;s=n.enable_fill_back&&n.fill_back_component_key?n.fill_back_component_key:i.find(e=>e.fillBack)?.key,s&&t&&(r[s]=t);let l=d(n,r),u=n.name;try{await a(u,{property:l})}catch(e){o(e,`Failed to send shortcut directly`)}}}}function HUt(e){let{emit:t,chatHelper:n,chatBusinessManager:r,cite:i,focusInput:a,getShortcutFromMessage:o,buildShortcutProperty:s,getRequestOptions:l,reportError:u,stopGeneration:d}=e,f=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot delete messages: chatBusinessManager not initialized`);return}try{let t=r.value.messages.value,i=I9(t,e[0]);if(!i){console.error(`[ChatBot] No user message found before AI messages`);return}let a=[i,...e];await n.value.message.deleteMessages(a)}catch(e){u(e,`Failed to delete messages`)}},p=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot regenerate: chatBusinessManager not initialized`);return}let t=n.value.session.current?.value?.sessionCode;if(!t){console.error(`[ChatBot] Cannot regenerate: no active session`);return}try{await r.value.regenerateFromAIMessages(e,t)}catch(e){u(e,`Failed to regenerate`)}},m=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot delete message: chatHelper not initialized`);return}try{let t=r.value.messages.value,i=t.findIndex(t=>t===e);if(i===-1){console.error(`[ChatBot] User message not found in messages list`);return}let a=[];for(let e=i+1;e<t.length;e++){let n=t[e];if(n.role===V8.User)break;a.push(n)}let o=[e,...a];await n.value.message.deleteMessages(o)}catch(e){u(e,`Failed to delete user message`)}};return{handleAgentAction:async(e,r)=>{if(e.id===`cite`){i.value=r.filter(e=>e.role!==V8.Reasoning).map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content||``)).join(`
|
|
3487
|
+
`),status:_9.Complete})}}handleFlowAgentRestartCustomEvent(e){let t=e.value;this.messageModule.list.value.forEach(e=>{e.role===g9.Activity&&e.activityType===h9.FlowAgent&&e.content[0].task_id===t[0].task_id&&(e.status=_9.Streaming)})}handleFlowAgentResultCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.FlowAgent&&(t.content=e.value)}handleFlowAgentStartCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Activity,activityType:h9.FlowAgent,content:t.map(e=>({nodes:{},task_id:e.task_id,task_name:``,task_outputs:[],task_state:RVt.Created})),status:_9.Streaming})}handleFlowAgentUpdateCustomEvent(e){let t=e.value;this.messageModule.list.value.forEach(e=>{e.role===g9.Activity&&e.activityType===h9.FlowAgent&&e.content[0].task_id===t[0].task_id&&(e.content=t)})}handleInfoCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Info,messageId:t.messageId,content:t.content,status:_9.Complete})}handleKnowledgeRagEndCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag&&(t.status=_9.Complete)}handleKnowledgeRagResultCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag&&(t.content.referenceDocument=e.value)}handleKnowledgeRagStartCustomEvent(e){this.messageModule.plusMessage({role:g9.Activity,activityType:h9.KnowledgeRag,content:{content:``,referenceDocument:[]},status:_9.Streaming})}handleKnowledgeRagTextContentCustomEvent(e){let t=this.messageModule.getCurrentLoadingMessage();if(t&&t.role===g9.Activity&&t.activityType===h9.KnowledgeRag){let n=e.value;t.content.content=n.cover?n.chunk.content:t.content.content+n.chunk.content}}handleMessagesSnapshotEvent(e){e.messages&&e.messages.length>0&&(this.messageModule.list.value=e.messages)}handleRawEvent(e){}handleReferenceDocumentCustomEvent(e){this.messageModule.plusMessage({role:g9.Activity,activityType:h9.ReferenceDocument,content:e.value,status:_9.Complete})}handleRunErrorEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&(t.status=_9.Complete),this.messageModule.plusMessage({role:g9.Assistant,content:e.message,status:_9.Error})}handleRunFinishedEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&(t.status=_9.Complete),e.outcome?.type===S9.Interrupt&&this.messageModule.plusMessage({role:g9.Interrupt,content:e,status:_9.Pending}),e.outcome?.type===S9.Success&&t?.role===g9.Interrupt&&(t.content=e)}handleRunStartedEvent(e){}handleStateDeltaEvent(e){}handleStateSnapshotEvent(e){}handleStepFinishedEvent(e){}handleStepStartedEvent(e){}handleTempMessageCustomEvent(e){let t=e.value;this.messageModule.plusMessage({role:g9.Assistant,content:t.message,status:t.status})}handleApprovalResultCustomEvent(e){let t=e.value,n=this.messageModule.getCurrentLoadingMessage();n&&(n.content=t,n.status=_9.Complete)}handleTextMessageChunkEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t?t.content+=e.delta||``:this.messageModule.plusMessage({role:e.role,content:e.delta||``,status:_9.Complete,messageId:e.messageId})}handleTextMessageContentEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);t&&(t.content+=e.delta)}handleTextMessageEndEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);t&&(t.status=_9.Complete)}handleTextMessageStartEvent(e){let t=this.messageModule.getMessageByMessageId(e.messageId);if(t){t.content=``,t.status=_9.Streaming;return}this.messageModule.plusMessage({role:e.role,content:``,status:_9.Streaming,messageId:e.messageId})}handleThinkingEndEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&(t.duration=e.duration,t.status=_9.Complete)}handleThinkingStartEvent(e){this.messageModule.plusMessage({role:g9.Reasoning,content:[],status:_9.Streaming})}handleThinkingTextMessageContentEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&(t.content[t.content.length-1]+=e.delta)}handleThinkingTextMessageEndEvent(e){}handleThinkingTextMessageStartEvent(e){let t=this.messageModule.getCurrentLoadingMessage();t&&t.role===g9.Reasoning&&t.content.push(``)}handleToolCallArgsEvent(e){this.messageModule.list.value.forEach(t=>{t.role===g9.Assistant&&t.toolCalls&&t.toolCalls.forEach(t=>{t.id===e.toolCallId&&(t.function.arguments+=e.delta)})})}handleToolCallChunkEvent(e){}handleToolCallEndEvent(e){this.messageModule.list.value.forEach(t=>{t.role===g9.Assistant&&t.toolCalls&&t.toolCalls.some(t=>t.id===e.toolCallId)&&(t.status=_9.Complete)})}handleToolCallResultEvent(e){this.messageModule.plusMessage({role:g9.Tool,content:e.content,duration:e.duration,status:e.isError?_9.Error:_9.Complete,toolCallId:e.toolCallId,messageId:e.messageId})}handleToolCallStartEvent(e){this.messageModule.plusMessage({role:g9.Assistant,content:``,status:_9.Streaming,toolCalls:[{id:e.toolCallId,type:v9.Function,function:{mcpName:e.mcpName,name:e.toolCallName,arguments:``,description:e.description}}]})}injectMessageModule(e){this.messageModule=e}onDone(){this.onDoneCallback?.()}onError(e){this.messageModule?.plusMessage({role:g9.Assistant,content:e.message,status:_9.Error}),this.onErrorCallback?.(e)}onMessage(e){let t=e;switch(this.onMessageCallback?.(t),t.type){case x9.ActivityDelta:this.handleActivityDeltaEvent(t);break;case x9.ActivitySnapshot:this.handleActivitySnapshotEvent(t);break;case x9.Custom:this.handleCustomEvent(t);break;case x9.MessagesSnapshot:this.handleMessagesSnapshotEvent(t);break;case x9.Raw:this.handleRawEvent(t);break;case x9.RunError:this.handleRunErrorEvent(t);break;case x9.RunFinished:this.handleRunFinishedEvent(t);break;case x9.RunStarted:this.handleRunStartedEvent(t);break;case x9.StateDelta:this.handleStateDeltaEvent(t);break;case x9.StateSnapshot:this.handleStateSnapshotEvent(t);break;case x9.StepFinished:this.handleStepFinishedEvent(t);break;case x9.StepStarted:this.handleStepStartedEvent(t);break;case x9.TextMessageChunk:this.handleTextMessageChunkEvent(t);break;case x9.TextMessageContent:this.handleTextMessageContentEvent(t);break;case x9.TextMessageEnd:this.handleTextMessageEndEvent(t);break;case x9.TextMessageStart:this.handleTextMessageStartEvent(t);break;case x9.ThinkingEnd:this.handleThinkingEndEvent(t);break;case x9.ThinkingStart:this.handleThinkingStartEvent(t);break;case x9.ThinkingTextMessageContent:this.handleThinkingTextMessageContentEvent(t);break;case x9.ThinkingTextMessageEnd:this.handleThinkingTextMessageEndEvent(t);break;case x9.ThinkingTextMessageStart:this.handleThinkingTextMessageStartEvent(t);break;case x9.ToolCallArgs:this.handleToolCallArgsEvent(t);break;case x9.ToolCallChunk:this.handleToolCallChunkEvent(t);break;case x9.ToolCallEnd:this.handleToolCallEndEvent(t);break;case x9.ToolCallResult:this.handleToolCallResultEvent(t);break;case x9.ToolCallStart:this.handleToolCallStartEvent(t);break;default:break}}onStart(){this.onStartCallback?.()}},T9=function(e){return e.Running=`running`,e.Finished=`finished`,e.Failed=`failed`,e.Cancelled=`cancelled`,e}({}),BVt=5,VVt=1e3,HVt=8e3,UVt=e=>Math.min(VVt*2**(e-1),HVt),WVt=e=>{if(e.name===`AbortError`)return!1;let t=e.response?.status,n=e.message.match(/status code (\d+)/i),r=t??(n?Number(n[1]):void 0);if(r!==void 0){if(r===408||r===429)return!0;if(r>=400&&r<500)return!1;if(r>=500)return!0}return!0},GVt=(e,n)=>{let r=(0,t.ref)(null),i=(0,t.ref)(!1),a=(0,t.ref)(!1),o=(0,t.ref)([]),s=(0,t.ref)(!1),l=n||new w9,u=null,d=null,f=null,p=!1,m=0,h=!1,g=0,_=null,v=null,y=null,b=(t,n)=>{s.value=!0;let r=e.http?.agent.getLlms(t,n);return r?r.then(e=>(o.value=e,e)).catch(e=>{throw o.value=[],e}).finally(()=>{s.value=!1}):(s.value=!1,o.value=[],Promise.resolve([]))},x=()=>(i.value=!0,e.http?.agent.getAgentInfo().then(e=>{r.value=e}).finally(()=>{i.value=!1})),S=(t,n)=>{let r=t.promptSetting?.content?.at(-1);r?.role===g9.Pause&&e.message?.createAndPlusMessage({role:g9.Assistant,content:r.content,status:_9.Complete,sessionCode:n,property:{extra:{pause:!0}}})},C=(t,n,r,i,a)=>e.http?.message.userOperation(t,n,r,i).then(()=>{n===y9.ApprovalCancel?(P(),N(t,a)):A({sessionCode:t,config:i,model:a})}),w=(e=!1)=>{if(_&&=(clearTimeout(_),null),v){let t=v;v=null,t(e)}},T=e=>new Promise(t=>{v=t,_=setTimeout(()=>{_=null,v=null,t(!0)},e)}),E=()=>{p=!1,m=0,h=!1,w(!1)},D=()=>{let t=e.message?.list.value;if(t?.length)for(;t.length>0;){let e=t[t.length-1];if(e.role===g9.User)break;if(e.status===_9.Streaming||e.status===_9.Pending){t.pop();continue}break}},O=t=>t===e.session?.current?.value?.sessionCode,k=async(t,n)=>{let r=()=>n===g&&!p;if(!r()||!O(t))return`failed`;try{await e.session?.getSession(t)}catch{}if(!r()||!O(t))return`failed`;if(e.session?.current.value?.status!==T9.Running)return`finished`;if(m>=BVt||(m+=1,a.value=!0,!await T(UVt(m))||!r()||!O(t)))return`failed`;if(e.session?.current.value?.status!==T9.Running)return`finished`;if(!r())return`failed`;D();let i=e.message?.list.value.at(-1)?.id,o=y;return A({sessionCode:t,model:o?.model,url:o?.url,config:o?.config,lastMessageId:i===void 0?void 0:String(i),isReconnect:!0}),`reconnected`},A=async({sessionCode:t,model:n,url:r,config:i,resume:o,input:s,lastMessageId:d,isReconnect:f=!1})=>{f||E(),y={sessionCode:t,model:n,url:r,config:i};let m=++g,_=u;u=new AbortController,_?.abort?.();let v=()=>m===g;l instanceof w9&&l.injectMessageModule(e.message),s&&e.message?.list.value.push({role:g9.User,content:s,status:_9.Complete,sessionCode:t});let b=()=>{v()&&(a.value=!1,l.onDone?.call(l),s&&e.http?.message?.getMessages(t).then(t=>{let n=e.message?.list.value.findLast(e=>e.role===g9.User),r=t.findLast(e=>e.role===g9.User);n&&r&&(n.id=r.id)}),N(t))},x=e=>{v()&&(a.value=!1,l.onError?.call(l,e))},S=()=>{if(v()&&!p){if(h){b();return}k(t,m).then(e=>{if(v()&&e!==`reconnected`){if(e===`finished`){b();return}if(p||!O(t)){a.value=!1;return}x(Error(`Connection lost, please try again`))}})}},C=e=>{if(!(!v()||p)){if(!WVt(e)){x(e);return}k(t,m).then(n=>{if(v()&&n!==`reconnected`){if(n===`finished`){b();return}if(p||!O(t)){a.value=!1;return}x(e)}})}},w=e=>{if(!v())return;let t=e;(t?.type===x9.RunFinished||t?.type===x9.RunError)&&(h=!0),l.onMessage?.call(l,e)},T=()=>{v()&&(a.value=!0,l.onStart?.call(l))};e.http?.fetchClient.streamRequest({url:r||`chat_completion/`,method:`POST`,data:{session_code:t,model:n,input:s,execute_kwargs:{stream:!0,persist_input:!!s,last_message_id:d,resume:o}},...i,controller:u,onDone:S,onError:C,onMessage:w,onStart:T}).catch(()=>{})},j=async(t,n,r,i,a,o)=>{await e.message?.createAndPlusMessage({role:g9.User,content:t,status:_9.Complete,sessionCode:n,...a&&{property:a}}),A({sessionCode:n,model:o,url:r,config:i})},M=(t,n,r,i)=>{if(e.session?.current.value?.status===T9.Running){let a=e.message?.list.value.at(-1)?.id;A({sessionCode:t,model:i,url:n,config:r,lastMessageId:a})}},N=(t,n)=>{let r=e.message?.list.value.at(-1),i=r?.content?.outcome?.type===S9.Interrupt?r.content.outcome.interrupts.find(e=>[zVt.Pending,zVt.Draft].includes(e.metadata?.ticket?.status)):void 0;r?.role===g9.Interrupt&&i&&(P(),d=new AbortController,e.http?.session.isResumeSession(t,{controller:d}).then(r=>{r?A({sessionCode:t,model:n,resume:{interruptId:i.id,status:C9.Resolved}}):f=setTimeout(()=>{t===e.session?.current?.value?.sessionCode&&N(t,n)},1e4)}))},P=()=>{clearTimeout(f),f=null,d?.abort?.(),d=null},F=()=>{p=!0,g+=1,w(!1),P(),a.value=!1,u?.abort?.(),u=null};return{info:r,isInfoLoading:i,isChatting:a,models:o,isModelsLoading:s,chat:j,handleRole:S,resendMessage:async(t,n,r,i,a,o)=>{let s=e.message?.list.value||[],l=s.findIndex(e=>String(e.id)===t);if(l===-1)throw Error(`Message not found: ${t}`);let u=s[l];if(u.role!==g9.User)throw Error(`Can only resend user messages`);let d=u.content,f=u.property,p=r??d,m=s.slice(l),h=e.message?.deleteMessages(m),g=e.message?.createAndPlusMessage({role:g9.User,content:p,status:_9.Complete,sessionCode:n,...f&&{property:f}});A({sessionCode:n,model:o,url:i,config:a}),Promise.all([h,g]).catch(e=>{console.error(`[resendMessage] API error:`,e)})},resumeStreamingChat:M,abortChat:F,stopChat:async t=>e.http.message?.stopChat(t),getAgentInfo:x,getLlms:b,reset:e=>{F(),l=e||new w9,r.value=null,i.value=!1,a.value=!1,o.value=[],s.value=!1,y=null,m=0,h=!1},pollResumeSession:N,clearLongPollTimer:P,userOperationStreamRequest:C,streamRequest:A}};function KVt(e){return(0,t.isRef)(e)}function E9(e){if(e==null)return;let n=e,r=0;for(;r<32;){if(r+=1,typeof n==`function`){n=n();continue}if(KVt(n)){n=(0,t.unref)(n);continue}break}return r>=32&&console.warn(`[chat-helper] resolveRequestValue: exceeded max unwrap depth`),n}var qVt=class{handlers=[];clear(){this.handlers=[]}eject(e){this.handlers[e]&&(this.handlers[e]=null)}forEach(e){this.handlers.forEach(t=>{t!==null&&e(t)})}use(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1}},JVt=class e{defaults;interceptors;globalErrorHandler;ignoreErrorPatterns=[];constructor(e={}){this.defaults=j9({method:`GET`,headers:{"Content-Type":`application/json`},timeout:3e4,responseType:`json`,credentials:`include`,mode:`cors`,validateStatus:e=>e>=200&&e<300},e),this.interceptors={request:new qVt,response:new qVt}}onError(e,t){this.globalErrorHandler=e,t?.ignoreErrors&&(this.ignoreErrorPatterns=t.ignoreErrors)}shouldIgnoreError(e){let t=e.config?.url||``,n=e.config?.baseURL||``,r=n&&!t.startsWith(`http`)?n+t:t;return this.ignoreErrorPatterns.some(e=>typeof e==`string`?t.includes(e)||r.includes(e):e.test(t)||e.test(r))}dispatchError(e){this.globalErrorHandler&&!this.shouldIgnoreError(e)&&this.globalErrorHandler(e)}applyResponseErrorInterceptors(e){let t=e;return this.interceptors.response.forEach(e=>{e.rejected&&(t=e.rejected(t))}),t}create(t){return new e(j9(this.defaults,t||{}))}delete(e,t,n){return this.request({...n,url:e,method:`DELETE`,params:t})}get(e,t,n){return this.request({...n,url:e,method:`GET`,params:t})}head(e,t,n){return this.request({...n,url:e,method:`HEAD`,params:t})}options(e,t,n){return this.request({...n,url:e,method:`OPTIONS`,params:t})}patch(e,t,n){return this.request({...n,url:e,method:`PATCH`,data:t})}post(e,t,n){return this.request({...n,url:e,method:`POST`,data:t})}prepareRequest(e,t=!1){let n=j9(this.defaults,e);this.interceptors.request.forEach(e=>{if(e.fulfilled)try{n=e.fulfilled(n)}catch(t){throw e.rejected?e.rejected(t):t}});let r=n.url||``;n.baseURL&&!r.startsWith(`http`)&&(r=n.baseURL+r),r=YVt(r,n.params);let i=A9(n.data),a=new Headers(A9(n.headers));t&&!a.has(`Accept`)&&a.set(`Accept`,`text/event-stream`),i!=null&&(n.transformRequest?i=n.transformRequest(i,A9(n.headers)):a.get(`Content-Type`)?.includes(`application/json`)&&typeof i==`object`&&!(i instanceof FormData)&&!(i instanceof Blob)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)));let o=n.controller??new AbortController,s={method:n.method,credentials:n.credentials,mode:n.mode,headers:a,body:i,signal:o.signal};return{url:r,requestConfig:n,fetchConfig:s,controller:o}}put(e,t,n){return this.request({...n,url:e,method:`PUT`,data:t})}async request(e){let{url:t,fetchConfig:n,requestConfig:r,controller:i}=this.prepareRequest(e),a=!1,o=r.timeout&&r.timeout>0?setTimeout(()=>{a=!0,i.abort()},r.timeout):void 0;try{let e=await fetch(t,n);o&&clearTimeout(o);let i,a=r.responseType||`json`;try{switch(a){case`json`:i=await e.json();break;case`text`:i=await e.text();break;case`blob`:i=await e.blob();break;case`arrayBuffer`:i=await e.arrayBuffer();break;case`formData`:i=await e.formData();break;default:i=await e.json()}}catch{i=null}r.transformResponse&&(i=r.transformResponse(i));let s={data:i,status:e.status,statusText:e.statusText,headers:e.headers,config:r};if(!(r.validateStatus||this.defaults.validateStatus)(e.status)){let{code:t,message:n}=D9(s.data,`Request failed with status code ${e.status}`);throw k9(n,r,t,s)}let l=s;this.interceptors.response.forEach(e=>{if(e.fulfilled)try{l=e.fulfilled(l)}catch(t){throw e.rejected?e.rejected(t):t}}),l instanceof Promise&&(l=await l);let u=l.data;if(!u)return;if(![0,`success`].includes(u.code)){let{code:e,message:t}=D9(u,`Request failed with code ${u.code}`);throw k9(t,r,e,l)}return u.data}catch(e){if(o&&clearTimeout(o),e instanceof Error&&e.name===`AbortError`&&!a){console.warn(`User canceled request`,e.message);return}let t=a?k9(`timeout of ${r.timeout}ms exceeded`,r,`ECONNABORTED`,void 0):e.isAxiosError===!0?e:k9(e.message,r,e.code,void 0);throw this.dispatchError(t),this.applyResponseErrorInterceptors(t)}}stream(e,t){return this.streamRequest({...t,url:e})}async streamRequest(e){let t=!1,n=e.onError,r=e=>{if(!t){let n=e;n.config||=s,this.dispatchError(n),t=!0}n?.(e)},i={...e,onError:r},{url:a,fetchConfig:o,requestConfig:s,controller:l}=this.prepareRequest(i,!0),u,d=()=>{u?.cancel().catch(()=>{})};try{let e=await fetch(a,o);if(!(s.validateStatus||this.defaults.validateStatus)(e.status)){let t=null;try{t=await e.json()}catch{t=null}let{code:n,message:i}=D9(t,`Request failed with status code ${e.status}`);r(k9(i,s,n,void 0));return}if(i.onStart?.(),u=e.body?.pipeThrough(new window.TextDecoderStream).getReader(),!u){r(Error(`IResponse body is not readable`));return}if(l.signal.addEventListener(`abort`,d,{once:!0}),l.signal.aborted){d(),i.onDone?.();return}let t=``,n=e=>{try{return JSON.parse(e),!0}catch{return!1}};for(;;){let{value:e,done:r}=await u.read();if(r){i.onDone?.();break}(t+e.toString()).split(`
|
|
3488
|
+
`).forEach(e=>{let r=e.replace(`data:`,``).trim();if(n(r)){let e=JSON.parse(r);i.onMessage?.(e),t=``}else r&&(t=r)})}}catch(e){if(e instanceof Error){if(e.name===`AbortError`){i.onDone?.();return}r(e)}throw e}finally{l.signal.removeEventListener(`abort`,d)}}};function YVt(e,t){if(!t)return e;let n=new URLSearchParams;Object.keys(t).forEach(e=>{let r=t[e];r!=null&&(Array.isArray(r)?r.forEach(t=>n.append(e,String(t))):n.append(e,String(r)))});let r=n.toString();return r?`${e}${e.includes(`?`)?`&`:`?`}${r}`:e}function D9(e,t){let n=`ERR_BAD_RESPONSE`;if(!e||typeof e!=`object`)return{code:n,message:t};let r=e;return r.error?.message?{code:r.error.code??n,data:r.error.data,message:O9(r.error.message,t)}:r.message?{code:r.code??n,data:r.data,message:O9(r.message,t)}:r.detail?{code:r.code??n,data:r.data,message:O9(r.detail,t)}:{code:r.code??n,data:r.data,message:t}}function O9(e,t){if(typeof e==`string`)return e||t;try{return JSON.stringify(e)||t}catch{return t}}function k9(e,t,n,r){let i=Error(e);return i.config=t,i.code=String(n),i.response=r,i.isAxiosError=!0,i}function A9(e){return E9(e)}function XVt(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function j9(e,t){let n={...e};for(let r in t){let i=t[r];if(XVt(i)){let t=e[r];n[r]=j9(t||{},i)}else n[r]=i}return n}new JVt;var ZVt=new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),QVt=new Set([`GET`,`HEAD`,`OPTIONS`]);function $Vt(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function eHt(e,t){let{headers:n,data:r}=t.requestData;!n&&!r||e.interceptors.request.use(e=>{let t=e,i=(e.method??`GET`).toUpperCase();if(n){let r=E9(n);if(r&&Object.keys(r).length>0){let n=E9(e.headers)??{};t={...t,headers:{...n,...r}}}}if(r){let n=E9(r);if(n&&Object.keys(n).length>0){if(ZVt.has(i)){let r=E9(e.data);r==null?t={...t,data:n}:$Vt(r)?t={...t,data:{...n,...r}}:console.warn(`[chat-helper] requestData.data 无法注入:当前请求体不是普通对象(FormData/Blob/string 等),已跳过合并。`,{method:i,existingType:typeof r})}else if(QVt.has(i)){let r=e.params??{};t={...t,params:{...n,...r}}}}}return t})}var tHt=e=>{let t=new JVt({baseURL:e.requestData.urlPrefix});return eHt(t,e),e.interceptors?.request&&t.interceptors.request.use(e.interceptors.request),e.interceptors?.response&&t.interceptors.response.use(e.interceptors.response),{fetchClient:t,reset:e=>{t.defaults.baseURL=e.requestData.urlPrefix,t.interceptors.request.clear(),t.interceptors.response.clear(),eHt(t,e),e.interceptors?.request&&t.interceptors.request.use(e.interceptors.request),e.interceptors?.response&&t.interceptors.response.use(e.interceptors.response)}}},nHt=e=>({conversationSettings:{openingRemark:e?.conversation_settings?.opening_remark,predefinedQuestions:e?.conversation_settings?.predefined_questions,commands:e?.conversation_settings?.commands?.map(e=>({id:e.id,name:e.name,alias:e.alias,icon:e.icon,components:e.components.map(e=>({type:e.type,name:e.name,key:e.key,placeholder:e.placeholder,default:e.default,required:e.required,fillBack:e.fill_back,fillRegx:e.fill_regx,rows:e.rows,min:e.min,max:e.max,options:e.options})),content:e.content,agentId:e.agent_id,status:e.status,supportUpload:e.support_upload})),enableChatSession:e?.conversation_settings?.enable_chat_session},promptSetting:e?.prompt_setting?{content:e.prompt_setting.content,supportUpload:e.prompt_setting.support_upload}:void 0,agentName:e?.agent_name,relatedSkills:e?.related_skills?.map(e=>({id:e.id,skill_name:e.skill_name,skill_code:e.skill_code,description:e.description,icon:e.icon})),chatGroup:e?.chat_group?{enabled:e.chat_group.enabled,staff:e.chat_group.staff,username:e.chat_group.username}:void 0,saasUrl:e?.saas_url,resources:e?.resources}),rHt=e=>({id:e.id??0,llm_code:e.llm_code,llm_name:e.llm_name,llm_type:e.llm_type??`chat.completion`,icon:e.icon??``,description:e.description??``,base_model:e.base_model,max_token_size:e.max_token_size??0,property:e.property??{},space_auth_mode:e.space_auth_mode??``,user_auth_mode:e.user_auth_mode??``,tag_names:e.tag_names}),iHt=e=>Array.isArray(e)?e.map(rHt):[],aHt=e=>({getAgentInfo:t=>e.get(`agent/info/`,void 0,t).then(nHt),getLlms:(t,n)=>{let r={llm_type:t?.llm_type??`chat.completion`};return t?.fuzzy&&(r.fuzzy=t.fuzzy),t?.supports&&(r.supports=t.supports),e.get(`llms/`,r,n).then(iHt)}}),M9=e=>{let t={id:e.id,messageId:e.message_id,name:e.name,role:e.role,sessionCode:e.session_code,status:e.status};switch(e.role){case g9.Activity:{let n=e,r=e=>e.map(e=>({name:e.name,originFileUrl:e.origin_file_url,url:e.url})),i;switch(n.activity_type){case h9.ReferenceDocument:i=r(n.content);break;case h9.KnowledgeRag:{let e=n.content;i={content:e.content,referenceDocument:r(e.reference_document)};break}case h9.FlowAgent:case h9.ArtifactsGenerated:default:i=n.content;break}return{...t,activityType:n.activity_type,content:i,property:n.property,role:n.role}}case g9.Assistant:{let n=e;return{...t,content:n.content,property:n.property,role:n.role,toolCalls:n.tool_calls?.map(e=>({function:{arguments:e.function.arguments,name:e.function.name,description:e.function.description,mcpName:e.function.mcp_name},id:e.id,type:e.type}))}}case g9.Developer:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Guide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Hidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Info:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Pause:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Placeholder:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Reasoning:{let n=e;return{...t,content:n.content,duration:n.duration,role:n.role}}case g9.System:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateHidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Tool:{let n=e;return{...t,content:n.content,duration:n.duration,error:n.error,role:n.role,toolCallId:n.tool_call_id}}case g9.User:{let n=e,r=n.content;return{...t,content:Array.isArray(r)?r.map(e=>{if(e.type===v9.Binary){let t=e;return{data:t.data,filename:t.filename,id:t.id,mimeType:t.mime_type,type:t.type,url:t.url}}return e}):r,property:n.property,role:n.role}}case g9.Interrupt:return{...t,...e}}},oHt=e=>{let t={id:e.id,message_id:e.messageId,name:e.name,role:e.role,session_code:e.sessionCode,status:e.status};switch(e.role){case g9.Activity:{let n=e,r=e=>e.map(e=>({name:e.name,origin_file_url:e.originFileUrl,url:e.url})),i;switch(n.activityType){case h9.ReferenceDocument:i=r(n.content);break;case h9.KnowledgeRag:{let e=n.content;i={content:e.content,reference_document:r(e.referenceDocument)};break}case h9.FlowAgent:case h9.ArtifactsGenerated:default:i=n.content;break}return{...t,activity_type:n.activityType,content:i,property:n.property,role:n.role}}case g9.Assistant:{let n=e;return{...t,property:n.property,content:n.content,role:n.role,tool_calls:n.toolCalls?.map(e=>({function:{arguments:e.function.arguments,name:e.function.name,description:e.function.description,mcp_name:e.function.mcpName},id:e.id,type:e.type}))}}case g9.Developer:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Guide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Hidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.HiddenUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Info:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Pause:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Placeholder:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Reasoning:{let n=e;return{...t,content:n.content,duration:n.duration,role:n.role}}case g9.System:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateAssistant:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateGuide:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateHidden:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateSystem:{let n=e;return{...t,content:n.content,role:n.role}}case g9.TemplateUser:{let n=e;return{...t,content:n.content,role:n.role}}case g9.Tool:{let n=e;return{...t,content:n.content,duration:n.duration,error:n.error,role:n.role,tool_call_id:n.toolCallId}}case g9.User:{let n=e,r=n.content;return{...t,content:Array.isArray(r)?r.map(e=>{if(e.type===v9.Binary){let t=e;return{data:t.data,filename:t.filename,id:t.id,mime_type:t.mimeType,type:t.type,url:t.url}}return e}):r,property:n.property,role:n.role}}case g9.Interrupt:return{...t,...e}}},sHt=e=>({getMessages:(t,n,r,i)=>e.get(`session_content/content/`,{session_code:t,limit:n,fuzzy:i},r).then(e=>e.map(M9)),plusMessage:(t,n)=>e.post(`session_content/`,oHt(t),n).then(M9),modifyMessage:(t,n)=>e.put(`session_content/${t.id}/`,oHt(t),n).then(M9),deleteMessage:(t,n)=>e.delete(`session_content/${t}/`,void 0,n),batchDeleteMessages:(t,n)=>e.post(`session_content/batch_delete/`,{ids:t},n),shareMessages:(t,n,r,i)=>e.post(`share/`,{session_code:t,content_ids:n,...r?{expired_at:r}:{}},i),stopChat:(t,n)=>e.post(`session_content/stop/`,{session_code:t},n),getFlowAgentTaskInfo:(t,n)=>e.get(`flow_agent/${t}/task_info/`,void 0,n),getFlowAgentTaskNodeInfo:(t,n,r)=>e.get(`flow_agent/${t}/task_node_info/${n}/`,void 0,r),retryFlowAgentTaskNode:(t,n,r,i)=>e.post(`flow_agent/${t}/node/${n}/retry/`,{task_id:r},i),skipFlowAgentTaskNode:(t,n,r,i)=>e.post(`flow_agent/${t}/node/${n}/skip/`,{task_id:r},i),userOperation:(t,n,r,i)=>e.post(`user_operation/`,{session_code:t,operation:n,payload:r},i)}),N9=e=>({sessionCode:e.session_code,sessionContentCount:e.session_content_count,sessionName:e.session_name,isTemporary:e.is_temporary,model:e.model,comment:e.comment,rate:e.rate,updatedAt:e.updated_at,createdAt:e.created_at,status:e.status,roleInfo:e.role_info?{collectionId:e.role_info.collection_id,collectionName:e.role_info.collection_name,content:e.role_info.content,variables:e.role_info.variables}:void 0,sessionProperty:{isAutoClear:e.session_property?.is_auto_clear,isAutoCalcPrompt:e.session_property?.is_auto_clac_prompt,labels:e.session_property?.labels}}),cHt=e=>({session_code:e.sessionCode,session_content_count:e.sessionContentCount,session_name:e.sessionName,is_temporary:e.isTemporary,model:e.model,comment:e.comment,rate:e.rate,updated_at:e.updatedAt,created_at:e.createdAt,status:e.status,role_info:e.roleInfo?{collection_id:e.roleInfo.collectionId,collection_name:e.roleInfo.collectionName,content:e.roleInfo.content,variables:e.roleInfo.variables}:void 0,session_property:{is_auto_clear:e.sessionProperty?.isAutoClear,is_auto_clac_prompt:e.sessionProperty?.isAutoCalcPrompt,labels:e.sessionProperty?.labels}}),lHt=e=>({session_code:e.sessionCode,session_content_ids:e.sessionContentIds,rate:e.rate,comment:e.comment,labels:e.labels}),uHt=e=>({sessionCode:e.session_code,sessionContentIds:e.session_content_ids,rate:e.rate,comment:e.comment,labels:e.lables}),dHt=`upload_file`,fHt=20,pHt=600,mHt=2e4,hHt=e=>{if(Array.isArray(e))return{page:1,numPages:1,count:e.length,results:e.map(N9)};let t=Array.isArray(e?.results)?e.results:[];return{page:e?.page??1,numPages:e?.num_pages??1,count:e?.count??t.length,results:t.map(N9)}},gHt=e=>{let t=e.split(`.`).pop();if(!t||t===e)return``;let n=t.replace(/[^A-Za-z0-9]/g,``).slice(0,20).toLowerCase();return n?`.${n}`:``},_Ht=e=>`${dHt}_${`${Date.now()}_${Math.random().toString(36).slice(2,8)}`}${gHt(e.name)}`,vHt=e=>`attachment; filename="${e}"`,yHt=e=>({clearSession:(t,n)=>e.post(`chat_completion/${t}/clear/`,void 0,n),getSessions:(t,n)=>e.get(`session/`,{page:t?.page??1,page_size:t?.page_size??fHt},n).then(hHt),plusSession:(t,n)=>e.post(`session/`,cHt(t),n).then(e=>N9(e)),modifySession:(t,n)=>e.put(`session/${t.sessionCode}/`,cHt(t),n).then(e=>N9(e)),deleteSession:(t,n)=>e.delete(`session/${t}/`,void 0,n),batchDeleteSessions:(t,n)=>e.post(`session/batch_delete/`,{session_codes:t},n),getSession:(t,n)=>e.get(`session/${t}/`,void 0,n).then(e=>N9(e)),postSessionFeedback:(t,n)=>e.post(`session_feedback/`,lHt(t),n).then(e=>uHt(e)),getSessionFeedbackReasons:(t,n)=>e.get(`session_feedback/reasons/`,{rate:t},n),renameSession:(t,n)=>e.post(`session/${t}/ai_rename/`,void 0,n).then(e=>N9(e)),uploadFile:(t,n,r)=>{let i=_Ht(n),a=encodeURIComponent(i),o=E9(r?.headers)??{};return n.arrayBuffer().then(n=>e.post(`session/${t}/upload/${a}/`,n,{...r,headers:{...o,"Content-Disposition":vHt(i)}}))},getPvFileDownloadUrl:(t,n,r,i)=>{let a=r?.expiresIn??pHt,o=r?.timeout??mHt;return e.get(`session/${t}/pv_files/download_url/`,{expires_in:a,path:n},{...i,timeout:i?.timeout??o})},isResumeSession:(t,n)=>e.get(`session/${t}/is_resume/`,void 0,n)}),bHt=e=>({agent:aHt(e),session:yHt(e),message:sHt(e),fetchClient:e}),xHt=e=>{let{fetchClient:t,reset:n}=tHt(e);return{...bHt(t),reset:n,onError:t.onError.bind(t)}},SHt=()=>({agent:null,http:null,message:null,session:null,registerAgent(e){this.agent=e},registerHttp(e){this.http=e},registerMessage(e){this.message=e},registerSession(e){this.session=e}}),CHt=20,wHt=e=>{let n=(0,t.ref)([]),r=(0,t.ref)(null),i=(0,t.ref)(0),a=(0,t.ref)(0),o=(0,t.ref)(0),s=(0,t.ref)(!1),l=(0,t.ref)(!1),u=(0,t.ref)(!1),d=(0,t.ref)(!1),f=(0,t.ref)(!1),p=(0,t.ref)(!1),m=(0,t.ref)(!1),h=(0,t.ref)(!1),g=(0,t.computed)(()=>i.value>0&&i.value<a.value),_=e=>{n.value=n.value.map(t=>t.sessionCode===e.sessionCode?{...t,...e}:t),r.value?.sessionCode===e.sessionCode&&(r.value=n.value.find(t=>t.sessionCode===e.sessionCode)??{...r.value,...e})},v=t=>{l.value=!0;let r={page:t?.page??1,page_size:t?.page_size??CHt};return e.http?.session.getSessions(r).then(e=>{n.value=e.results,i.value=e.page,a.value=e.numPages,o.value=e.count}).finally(()=>{l.value=!1})},y=async(t=CHt)=>{if(!(!g.value||l.value||u.value)){u.value=!0;try{let r=await e.http?.session.getSessions({page:i.value+1,page_size:t});if(!r)return;let s=new Set(n.value.map(e=>e.sessionCode)),l=r.results.filter(e=>!s.has(e.sessionCode));n.value=[...n.value,...l],i.value=r.page,a.value=r.numPages,o.value=r.count}finally{u.value=!1}}},b=async(t,i)=>{e.agent?.abortChat();let a=i?.loadMessages!==!1,o=n.value.find(e=>e.sessionCode===t);!a&&o?r.value=o:await x(t),a?(await e.message?.getMessages(t),e.agent?.resumeStreamingChat(t),e.agent?.pollResumeSession(t)):e.message&&(e.message.list.value=[])},x=t=>(s.value=!0,e.http?.session.getSession(t).then(e=>{r.value=e}).finally(()=>{s.value=!1}));return{list:n,current:r,page:i,numPages:a,count:o,hasMore:g,isCurrentLoading:s,isListLoading:l,isLoadingMore:u,isCreateLoading:d,isUpdateLoading:f,isDeleteLoading:p,isBatchDeleteLoading:m,getSessions:v,loadMoreSessions:y,chooseSession:b,getSession:x,createSession:async(t,r)=>{d.value=!0;try{let i=await e.http?.session.plusSession(t);i&&(n.value.unshift(i),o.value+=1,await b(i.sessionCode,{loadMessages:r?.loadMessages??!1}))}finally{d.value=!1}},updateSession:t=>(f.value=!0,e.http?.session.modifySession(t).then(e=>{_(e)}).finally(()=>{f.value=!1})),deleteSession:async t=>{p.value=!0;try{await e.http?.session.deleteSession(t),n.value=n.value.filter(e=>e.sessionCode!==t),o.value=Math.max(0,o.value-1),r.value?.sessionCode===t&&n.value[0]?.sessionCode&&await b(n.value[0].sessionCode)}finally{p.value=!1}},batchDeleteSessions:async t=>{if(t.length!==0){m.value=!0;try{await e.http?.session.batchDeleteSessions(t);let i=new Set(t),a=n.value.length;n.value=n.value.filter(e=>!i.has(e.sessionCode));let s=a-n.value.length;o.value=Math.max(0,o.value-s),r.value&&i.has(r.value.sessionCode)&&(n.value.length>0?await b(n.value[0].sessionCode):(r.value=null,e.message&&(e.message.list.value=[])))}finally{m.value=!1}}},postSessionFeedback:t=>e.http?.session.postSessionFeedback(t),getSessionFeedbackReasons:t=>e.http?.session.getSessionFeedbackReasons(t),renameSession:t=>(h.value=!0,e.http?.session.renameSession(t).then(e=>(_({sessionCode:e.sessionCode,sessionName:e.sessionName}),e)).finally(()=>{h.value=!1})),uploadFile:(t,n)=>e.http?.session.uploadFile(t,n),getPvFileDownloadUrl:(t,n,r)=>e.http?.session.getPvFileDownloadUrl(t,n,r),reset:()=>{n.value=[],r.value=null,i.value=0,a.value=0,o.value=0,s.value=!1,l.value=!1,u.value=!1,d.value=!1,f.value=!1,p.value=!1,m.value=!1,h.value=!1}}},P9=e=>{let t=SHt(),n=xHt(e),r=GVt(t,e.protocol),i=LVt(t),a=wHt(t);return t.registerHttp(n),t.registerMessage(i),t.registerAgent(r),t.registerSession(a),{agent:r,session:a,message:i,http:n,reset:e=>{n.reset(e),r.reset(e.protocol),i.reset(),a.reset()},onError:n.onError}},THt=new Set([`context_type`,`__label`,`__key`,`__value`]);function EHt(e,n){return{urlPrefix:e,headers:()=>E9((0,t.toValue)(n)?.headers),data:()=>E9((0,t.toValue)(n)?.data)}}function DHt(e){return e?Array.isArray(e)?e.map(e=>{if(e.__key)return e;let t=Object.entries(e).filter(([e])=>!THt.has(e));if(t.length===0)return e;let[n,r]=t[0];return{...e,[n]:r,context_type:e.context_type??`input`,__label:e.__label??n,__key:e.__key??n,__value:e.__value??r}}):Object.entries(e).map(([e,t])=>({[e]:t,context_type:`input`,__label:e,__key:e,__value:t})):[]}function F9(e,t){if(!t)return e;let n=t()?.context;if(!n)return e;let r=DHt(n);return r.length===0?e:OHt(e,r)}function OHt(e,t){if(t.length===0)return e??{};let n=e??{},r=n.extra??{},i=r.context??[],a=new Set(t.map(e=>e.__key).filter(Boolean)),o=i.filter(e=>{let t=e.__key;return!t||!a.has(t)});return{...n,extra:{...r,context:[...o,...t]}}}function kHt(e){return e.some(e=>{if(!(`property`in e))return!0;let{property:t}=e;return!t?.extra?.pause})}function I9(e,t){let n=null;for(let r of e)if(r.role===`user`&&r.id!==void 0&&(n=r),r===t)break;return n}function AHt(e,t){let n=I9(e,t);if(n?.id!==void 0)return typeof n.id==`number`?n.id:Number(n.id)}function jHt(e){if(!e)return[];if(typeof e!=`string`)return[{type:`text`,content:e}];let t=[],n=/```custom-component\s*\n([\s\S]*?)\n```/g,r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r){let n=e.slice(r,i.index).trim();n&&t.push({type:`text`,content:n})}try{let e=JSON.parse(i[1]);t.push({type:`custom`,data:e,raw:i[1]})}catch{t.push({type:`text`,content:i[0]})}r=i.index+i[0].length}if(r<e.length){let n=e.slice(r).trim();n&&t.push({type:`text`,content:n})}return t}var MHt=e=>{if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);if(e&&typeof e==`object`){let{message:t}=e;if(typeof t==`string`&&t)return Error(t);try{return Error(JSON.stringify(e)??String(e))}catch{return Error(String(e))}}return Error(String(e))},NHt=e=>{let t=document.cookie.match(RegExp(`(^| )${e}=([^;]*)(;|$)`));return t?t[2]:``},PHt=e=>e.endsWith(`/`)?e:`${e}/`,L9=e=>{if(!e)return e;try{let t=new URL(e,window.location.origin);return t.protocol=window.location.protocol,PHt(t.toString())}catch(t){return console.warn(`Failed to normalize URL:`,t),PHt(e)}};async function FHt(e){if(typeof navigator<`u`&&`clipboard`in navigator)try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.style.opacity=`0`,document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand(`copy`)}catch{return!1}finally{document.body.removeChild(t)}}function IHt(){let e=window.navigator.userAgent.toLowerCase(),t=window.navigator.platform.toLowerCase();return t.includes(`mac`)||e.includes(`mac`)?`mac`:t.includes(`win`)||e.includes(`win`)?`windows`:t.includes(`linux`)||e.includes(`linux`)?`linux`:`unknown`}function LHt(){return RHt()?`Cmd + I`:`Ctrl + I`}function RHt(){return IHt()===`mac`}function zHt(e){let t=RHt()?e.metaKey:e.ctrlKey,n=e.key.toLowerCase()===`i`;return t&&n&&!e.shiftKey&&!e.altKey}var BHt=NHt(`blueking_language`)||`zh-cn`,VHt={小鲸:`BK GPT`,关闭:`close`,发送:`Send`,请输入:`Please input`,昨天:`yesterday`,"3天前":`3 days ago`,"5天前":`5 days ago`,"1周前":`1 week ago`,更早:`Older`,删除:`Delete`,恢复默认大小:`Restore default size`,"AI 小鲸":`AI BK GPT`,新增会话:`New chat`,历史会话:`History session`,停止生成:`Stop generating`,复制:`Copy`,编辑:`Edit`,今天:`Today`,搜索会话名称:`Search session name`,重命名:`Rename`,自动生成命名:`Auto generate name`,分享会话:`Share session`,无智能体使用权限:`No permission to use this agent`,暂无使用权限:`No permission`,请输入新的会话名称:`Please enter new session name`,"确认删除会话 ?":`Confirm delete session?`,搜索为空:`No search results`,暂无对话:`No conversations`,"加载中...":`Loading...`,转人工:`Transfer to human`,缩小高度:`Shrink height`,全选:`Select all`,取消:`Cancel`,确定:`Confirm`,分享链接已复制到剪贴板:`Share link copied to clipboard`,请求失败:`Request failed`,当前已是新会话:`Already in a new session`,"正在创建会话...":`Creating session...`},HHt={重命名:`重命名`,自动生成命名:`自动生成命名`,分享会话:`分享会话`,全选:`全选`,取消:`取消`,确定:`确定`,分享链接已复制到剪贴板:`分享链接已复制到剪贴板`,请求失败:`请求失败`},R9=e=>BHt===`en`?VHt[e]||e:HHt[e]||e;function UHt(e){let{triggerRef:n,panelComponent:r,panelProps:i={},tippyOptions:a={}}=e,o=(0,t.ref)(null),s=null,l=()=>(s||=document.createElement(`div`),(0,t.render)((0,t.h)(r,{...i,onClose:p}),s),s),u=e=>{let t=e.target,r=n.value;if(r&&r.contains(t))return;let i=document.querySelector(`.tippy-box[data-theme~="history-panel"]`);if(i&&i.contains(t))return;let a=document.querySelector(`.tippy-box[data-theme~="more-menu-light"]`);a&&a.contains(t)||o.value?.state.isVisible&&o.value.hide()},d=()=>{if(!n.value||o.value)return;let e={placement:`bottom-end`,offset:[0,8],appendTo:document.querySelector(`.ai-blueking-container-wrapper`)||document.body};o.value=uu(n.value,{content:l(),interactive:!0,trigger:`manual`,theme:`light history-panel`,arrow:!1,hideOnClick:!1,animation:`scale`,duration:200,delay:[0,0],...e,...a,onShow:()=>{o.value&&s&&o.value.setContent(l()),setTimeout(()=>{document.addEventListener(`click`,u,!1)},0)},onHidden:()=>{document.removeEventListener(`click`,u,!1)}})},f=()=>{o.value||d(),o.value?.show()},p=()=>{o.value?.hide()},m=()=>{o.value||d(),o.value?.state.isVisible?p():f()},h=e=>{e.stopPropagation(),m()},g=()=>{o.value&&=(o.value.destroy(),null),s&&=((0,t.render)(null,s),null),document.removeEventListener(`click`,u,!1)};return(0,t.onBeforeUnmount)(()=>{g()}),{show:f,hide:p,toggle:m,handleTriggerClick:h,destroy:g,isVisible:()=>o.value?.state.isVisible??!1}}var WHt={class:`history-group`},GHt={class:`history-group-title`},KHt={class:`history-group-list`},qHt=(0,t.defineComponent)({__name:`history-group`,props:{currentSessionCode:{},sessions:{},title:{}},setup(e){let n=e;return(e,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,WHt,[(0,t.createElementVNode)(`div`,GHt,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(n.title),1)]),(0,t.createElementVNode)(`div`,KHt,[(0,t.renderSlot)(e.$slots,`default`,{},void 0,!0)])]))}}),z9=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},JHt=z9(qHt,[[`__scopeId`,`data-v-3b603cb6`]]),YHt={class:`history-item-actions`},XHt=z9((0,t.defineComponent)({__name:`history-item`,props:{isActive:{type:Boolean},isEditing:{type:Boolean},session:{}},emits:[`click`,`delete`,`edit`,`rename-cancel`,`rename-confirm`],setup(e,{emit:n}){let r=e,i=n,a=yhe,o=(0,t.ref)(null),s=(0,t.ref)(``);(0,t.watch)(()=>r.isEditing,e=>{e&&(s.value=r.session.sessionName,(0,t.nextTick)(()=>{if(o.value)try{let e=o.value;e&&typeof e.focus==`function`&&e.focus();let t=e.$el?.querySelector(`input`);t&&typeof t.select==`function`&&t.select()}catch(e){console.warn(`Failed to focus edit input:`,e)}}))});let l=()=>{r.isEditing||i(`click`,r.session)},u=()=>{i(`edit`,r.session)},d=()=>{i(`delete`,r.session.sessionCode)},f=()=>{let e=s.value.trim();e&&e!==r.session.sessionName?i(`rename-confirm`,r.session.sessionCode,e):i(`rename-cancel`)},p=()=>{i(`rename-cancel`)},m=(e,t)=>{t.key===`Enter`?f():t.key===`Escape`&&p()};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:(0,t.normalizeClass)([`history-item`,{active:r.isActive}]),onClick:l},[r.isEditing?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(ts),{key:1,ref_key:`editInputRef`,ref:o,modelValue:s.value,"onUpdate:modelValue":n[1]||=e=>s.value=e,style:{width:`100%`,height:`28px`},onBlur:f,onKeyup:m,onClick:n[2]||=(0,t.withModifiers)(()=>{},[`stop`])},null,8,[`modelValue`])):((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[(0,t.createVNode)((0,t.unref)(kde),{style:{width:`calc(100% - 42px)`}},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(r.session.sessionName),1)]),_:1}),(0,t.createElementVNode)(`span`,YHt,[(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-bianji`,onClick:(0,t.withModifiers)(u,[`stop`])},null,512),[[(0,t.unref)(a),{content:(0,t.unref)(R9)(`编辑`),boundary:`parent`}]]),(0,t.createVNode)((0,t.unref)(zme),{title:(0,t.unref)(R9)(`确认删除会话 ?`),content:`删除操作无法撤回,请谨慎操作!`,"confirm-config":{theme:`danger`},trigger:`click`,boundary:`parent`,onConfirm:d},{default:(0,t.withCtx)(()=>[(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-shanchu`,onClick:n[0]||=(0,t.withModifiers)(()=>{},[`stop`])},null,512),[[(0,t.unref)(a),{content:(0,t.unref)(R9)(`删除`),boundary:`parent`}]])]),_:1},8,[`title`])])],64))],2))}}),[[`__scopeId`,`data-v-fea14d3a`]]),ZHt={class:`history-search`},QHt={class:`input-icon`},$Ht=z9((0,t.defineComponent)({__name:`history-search`,props:{modelValue:{default:``},placeholder:{default:``}},emits:[`update:modelValue`],setup(e,{emit:n}){let r=e,i=n,a=e=>{i(`update:modelValue`,e)};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,ZHt,[(0,t.createVNode)((0,t.unref)(ts),{"model-value":r.modelValue,behavior:`simplicity`,placeholder:r.placeholder||(0,t.unref)(R9)(`搜索会话名称`),style:{height:`22px`},"onUpdate:modelValue":a},{suffix:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`span`,QHt,[(0,t.createVNode)((0,t.unref)(Ja))])]),_:1},8,[`model-value`,`placeholder`])]))}}),[[`__scopeId`,`data-v-e7ff40b2`]]),eUt={class:`history-dropdown-header`},tUt={class:`history-dropdown-header-title`},nUt={class:`history-dropdown-content`},rUt={key:0,class:`history-dropdown-loading`},iUt={class:`history-dropdown-loading-dots`},aUt=40,oUt=z9((0,t.defineComponent)({__name:`index`,props:{sessionBusinessManager:{}},emits:[`close`,`session-delete`,`session-rename`,`session-switch`],setup(e,{emit:n}){let r=e,i=n,a=(0,t.ref)(``),o=(0,t.ref)(null),s=(0,t.computed)(()=>r.sessionBusinessManager.currentSession.value?.sessionCode),l=(0,t.computed)(()=>r.sessionBusinessManager.isLoadingMore.value),u=e=>{let t=e.target;t.scrollHeight-t.scrollTop-t.clientHeight>aUt||r.sessionBusinessManager.hasMoreSessions.value&&(r.sessionBusinessManager.isLoadingMore.value||r.sessionBusinessManager.loadMoreSessions())},d=(0,t.computed)(()=>{let e={today:{key:`today`,alias:R9(`今天`),sessionList:[]},yesterday:{key:`yesterday`,alias:R9(`昨天`),sessionList:[]},"3days":{key:`3days`,alias:R9(`3天前`),sessionList:[]},"5days":{key:`5days`,alias:R9(`5天前`),sessionList:[]},"1week":{key:`1week`,alias:R9(`1周前`),sessionList:[]},before:{key:`before`,alias:R9(`更早`),sessionList:[]}},t=r.sessionBusinessManager.sessionList.value.filter(e=>e.sessionName.toLowerCase().includes(a.value.toLowerCase())),n=new Date,i=new Date(n);i.setDate(i.getDate()-1);let o=new Date(n);o.setDate(n.getDate()-3);let s=new Date(n);s.setDate(n.getDate()-5);let l=new Date(n);l.setDate(n.getDate()-7);for(let r of t){let t=new Date(r.createdAt||``),a=t.toDateString();a===n.toDateString()?e.today.sessionList.push(r):a===i.toDateString()?e.yesterday.sessionList.push(r):t>=o&&t>s?e[`3days`].sessionList.push(r):t>=s&&t>l?e[`5days`].sessionList.push(r):t>=l?e[`1week`].sessionList.push(r):e.before.sessionList.push(r)}for(let t of Object.values(e))t.sessionList.sort((e,t)=>{let n=new Date(e.createdAt||0).getTime();return new Date(t.createdAt||0).getTime()-n});return Object.values(e).filter(e=>e.sessionList.length>0)}),f=e=>s.value===e,p=e=>{f(e.sessionCode)||(i(`session-switch`,e.sessionCode),i(`close`))},m=e=>{o.value=e.sessionCode},h=e=>{i(`session-delete`,e)},g=(e,t)=>{let n=r.sessionBusinessManager.sessionList.value.find(t=>t.sessionCode===e);n&&(n.sessionName=t),o.value=null,i(`session-rename`,e,t)},_=()=>{o.value=null};return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:`bkai-history-dropdown`,onScroll:u},[(0,t.createElementVNode)(`div`,eUt,[(0,t.createElementVNode)(`h1`,tUt,(0,t.toDisplayString)((0,t.unref)(R9)(`历史会话`)),1),(0,t.createVNode)($Ht,{modelValue:a.value,"onUpdate:modelValue":n[0]||=e=>a.value=e,placeholder:(0,t.unref)(R9)(`搜索会话名称`)},null,8,[`modelValue`,`placeholder`])]),(0,t.createElementVNode)(`div`,nUt,[d.value.length>0?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:0},[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(d.value,e=>((0,t.openBlock)(),(0,t.createBlock)(JHt,{key:e.key,"current-session-code":s.value,sessions:e.sessionList,title:e.alias},{default:(0,t.withCtx)(()=>[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(e.sessionList,e=>((0,t.openBlock)(),(0,t.createBlock)(XHt,{key:e.sessionCode,"is-active":f(e.sessionCode),"is-editing":o.value===e.sessionCode,session:e,onClick:p,onDelete:h,onEdit:m,onRenameCancel:_,onRenameConfirm:g},null,8,[`is-active`,`is-editing`,`session`]))),128))]),_:2},1032,[`current-session-code`,`sessions`,`title`]))),128)),l.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,rUt,[(0,t.createElementVNode)(`span`,iUt,[((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(3,e=>(0,t.createElementVNode)(`i`,{key:e,class:`history-dropdown-loading-dot`,style:(0,t.normalizeStyle)({"--dot-index":e-1})},null,4)),64))])])):(0,t.createCommentVNode)(`v-if`,!0)],64)):((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Js),{key:1,description:a.value?(0,t.unref)(R9)(`搜索为空`):(0,t.unref)(R9)(`暂无对话`),scene:`part`,style:{"margin-top":`100px`},type:a.value?`search-empty`:`empty`},null,8,[`description`,`type`]))])],32))}}),[[`__scopeId`,`data-v-bf2401b6`]]);function sUt(e){return e.sessionBusinessManager?UHt({triggerRef:e.triggerRef,panelComponent:oUt,panelProps:{sessionBusinessManager:e.sessionBusinessManager,onSessionSwitch:e.onSessionSwitch,onSessionDelete:e.onSessionDelete,onSessionRename:e.onSessionRename},tippyOptions:{placement:`bottom-end`,offset:[0,8],appendTo:()=>document.querySelector(`.ai-blueking-panel`)||document.body}}):{handleTriggerClick:()=>{},show:()=>{},hide:()=>{},toggle:()=>{},destroy:()=>{},isVisible:()=>!1}}var cUt={class:`left-section`},lUt={class:`logo`},uUt=[`src`],dUt={key:0,class:`rename-tooltip`},fUt={class:`rename-content`},pUt={key:0,class:`tippy-dropdown-menu`},mUt={key:1,class:`bkai-icon bkai-auto-refresh-line`},hUt={class:`right-section`},gUt=z9((0,t.defineComponent)({__name:`index`,props:{title:{default:``},agentName:{default:``},sessionName:{default:``},isCompressionHeight:{type:Boolean,default:!1},draggable:{type:Boolean,default:!0},showHistoryIcon:{type:Boolean,default:!0},showNewChatIcon:{type:Boolean,default:!0},showCompressionIcon:{type:Boolean,default:!0},showMoreIcon:{type:Boolean,default:!0},enableChatSession:{type:Boolean,default:!0},hasPermission:{type:Boolean,default:!0},chatGroup:{default:()=>({enabled:!1,staff:[],username:``})},hasSessionContents:{type:Boolean},autoGenerateLoading:{type:Boolean},dropdownMenuConfig:{default:()=>({showRename:!0,showAutoGenerate:!0,showShare:!1})},sessionBusinessManager:{default:void 0},selectedLlmCode:{default:void 0},renderMode:{default:G8.Chat}},emits:[`close`,`toggle-compression`,`new-chat`,`history-click`,`auto-generate-name`,`help-click`,`rename`,`share`,`history-session-switch`,`history-session-delete`,`history-session-rename`,`new-chat-created`],setup(e,{expose:n,emit:r}){let i=e,a=r,o=yhe,s=(0,t.ref)(null),l=(0,t.ref)(null),u=(0,t.useTemplateRef)(`moreMenuTippyRef`),d=(0,t.ref)(!1),f=(0,t.ref)(``),p=(0,t.ref)(null),m=(0,t.ref)(!1),h=()=>document.querySelector(`.ai-blueking-panel`)||document.body,g=null,_=()=>{!l.value||!i.sessionBusinessManager||(g=sUt({triggerRef:l,sessionBusinessManager:i.sessionBusinessManager,onSessionSwitch:e=>a(`history-session-switch`,e),onSessionDelete:e=>a(`history-session-delete`,e),onSessionRename:(e,t)=>a(`history-session-rename`,e,t)}))},v=(0,t.computed)(()=>i.hasPermission?i.enableChatSession?i.title||`${i.agentName||``}-${i.sessionName||``}`:i.agentName:R9(`无智能体使用权限`)),y=(0,t.computed)(()=>i.isCompressionHeight?`bkai-morenchicun`:`bkai-yasuo`),b=(0,t.computed)(()=>i.isCompressionHeight?R9(`恢复默认尺寸`):R9(`缩小高度`)),x=(0,t.computed)(()=>i.hasPermission),S=e=>x.value?e:R9(`暂无使用权限`),C=()=>({cursor:x.value?`pointer`:`not-allowed`}),w=(0,t.ref)(!1),T=async()=>{if(!w.value){w.value=!0;try{if(i.sessionBusinessManager)try{let e=await i.sessionBusinessManager.createNewSession({model:i.selectedLlmCode});e&&a(`new-chat-created`,{sessionCode:e.sessionCode,sessionName:e.sessionName,createdAt:e.createdAt})}catch(e){console.error(`Failed to create new session:`,e),nc({theme:`error`,message:R9(`创建会话失败`)})}a(`new-chat`)}finally{w.value=!1}}},E=e=>{e.stopPropagation(),i.sessionBusinessManager?(g||_(),g&&g.handleTriggerClick(e)):a(`history-click`,e)},D=()=>{a(`help-click`)},O=e=>{e.stopPropagation(),g&&g.isVisible()&&g.hide(),u.value&&(m.value?u.value.hide():u.value.show())},k=()=>{u.value?.hide(),M()},A=()=>{!i.hasSessionContents||i.autoGenerateLoading||a(`auto-generate-name`)},j=()=>{i.hasSessionContents&&(u.value?.hide(),a(`share`))},M=()=>{document.removeEventListener(`click`,I),f.value=i.sessionName||``,d.value=!0,setTimeout(()=>{document.addEventListener(`click`,I)},100),setTimeout(()=>{if(p.value)try{let e=p.value;e&&typeof e.focus==`function`&&e.focus();let t=e.$el?.querySelector(`input`);t&&typeof t.select==`function`&&t.select()}catch(e){console.warn(`Failed to focus rename input:`,e)}},100)},N=()=>{let e=f.value.trim();if(!e){P();return}a(`rename`,e),d.value=!1,f.value=``},P=()=>{d.value=!1,f.value=``},F=(e,t)=>{f.value=e,t.key===`Enter`?N():t.key===`Escape`&&P()},I=e=>{if(!d.value)return;let t=e.target,n=document.querySelector(`.rename-tooltip`);n&&!n.contains(t)&&P()};return(0,t.watch)(()=>i.autoGenerateLoading,(e,t)=>{t&&!e&&m.value&&u.value?.hide()}),(0,t.onMounted)(()=>{i.sessionBusinessManager&&_(),document.addEventListener(`click`,I)}),(0,t.onBeforeUnmount)(()=>{g&&=(g.destroy(),null),document.removeEventListener(`click`,I)}),n({headerRef:s,historyIconRef:l}),(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{ref_key:`headerRef`,ref:s,class:(0,t.normalizeClass)([`ai-header drag-handle`,{draggable:i.draggable}])},[(0,t.createElementVNode)(`div`,cUt,[(0,t.createElementVNode)(`div`,lUt,[(0,t.createElementVNode)(`img`,{alt:`logo`,src:(0,t.unref)(FVt)},null,8,uUt)]),(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`title`,{"title-with-tooltip":d.value}])},[(0,t.createTextVNode)((0,t.toDisplayString)(v.value)+` `,1),(0,t.createCommentVNode)(` 重命名 tooltip 直接绑定在 title 上 `),d.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,dUt,[(0,t.createElementVNode)(`div`,fUt,[(0,t.createVNode)((0,t.unref)(ts),{ref_key:`renameInputRef`,ref:p,modelValue:f.value,"onUpdate:modelValue":r[0]||=e=>f.value=e,class:`rename-input`,placeholder:(0,t.unref)(R9)(`请输入新的会话名称`),onKeyup:F},null,8,[`modelValue`,`placeholder`]),(0,t.createElementVNode)(`div`,{class:`rename-buttons`},[(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-check-1 rename-btn confirm-btn`,onClick:N}),(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-close rename-btn cancel-btn`,onClick:P})])])])):(0,t.createCommentVNode)(`v-if`,!0)],2),(0,t.createCommentVNode)(` 更多图标下拉菜单 - 使用 vue-tippy `),i.showMoreIcon&&x.value?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Kl),{key:0,ref_key:`moreMenuTippyRef`,ref:u,arrow:!1,"append-to":h,offset:[0,4],interactive:``,placement:`bottom-start`,theme:`ai-blueking-light more-menu-light light`,trigger:`manual`,onHidden:r[1]||=e=>m.value=!1,onShown:r[2]||=e=>m.value=!0},{content:(0,t.withCtx)(()=>[m.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,pUt,[i.dropdownMenuConfig?.showRename?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:0,class:`tippy-menu-item`,onClick:k},[r[7]||=(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-bianji`},null,-1),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`重命名`)),1)])):(0,t.createCommentVNode)(`v-if`,!0),i.dropdownMenuConfig?.showAutoGenerate?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:1,class:(0,t.normalizeClass)([`tippy-menu-item`,{disabled:!i.hasSessionContents||i.autoGenerateLoading}]),onClick:A},[i.autoGenerateLoading?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Io),{key:0,mode:`spin`,size:`mini`,theme:`primary`})):((0,t.openBlock)(),(0,t.createElementBlock)(`i`,mUt)),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`自动生成命名`)),1)],2)),[[(0,t.unref)(Jl),{content:i.hasSessionContents?``:(0,t.unref)(R9)(`请先发起会话`),theme:`ai-blueking-tooltip`,arrow:!0,delay:[300,0],appendTo:h}]]):(0,t.createCommentVNode)(`v-if`,!0),i.dropdownMenuConfig?.showShare&&i.renderMode!==(0,t.unref)(G8).Test?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:2,class:(0,t.normalizeClass)([`tippy-menu-item`,{disabled:!i.hasSessionContents}]),onClick:j},[r[8]||=(0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-fenxiang`},null,-1),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)((0,t.unref)(R9)(`分享会话`)),1)],2)),[[(0,t.unref)(Jl),{content:i.hasSessionContents?``:(0,t.unref)(R9)(`请先发起会话`),theme:`ai-blueking-tooltip`,arrow:!0,delay:[300,0],appendTo:h}]]):(0,t.createCommentVNode)(`v-if`,!0)])):(0,t.createCommentVNode)(`v-if`,!0)]),default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`span`,{class:`bkai-icon bkai-more`,onClick:O})]),_:1},512)):(0,t.createCommentVNode)(`v-if`,!0)]),(0,t.renderSlot)(n.$slots,`headerLeft`,{},void 0,!0),(0,t.createElementVNode)(`div`,hUt,[(0,t.createCommentVNode)(` 新增会话按钮 `),i.showNewChatIcon&&e.enableChatSession!==!1?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:0,class:(0,t.normalizeClass)([`bkai-icon`,`bkai-xinzengliaotian`,{disabled:!x.value||w.value||!e.hasSessionContents}]),style:(0,t.normalizeStyle)(C()),onClick:r[3]||=t=>x.value&&!w.value&&e.hasSessionContents?T():void 0},null,6)),[[(0,t.unref)(o),{content:w.value?(0,t.unref)(R9)(`正在创建会话...`):e.hasSessionContents?S((0,t.unref)(R9)(`新增会话`)):(0,t.unref)(R9)(`当前已是新会话`),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),(0,t.createCommentVNode)(` 历史会话按钮 `),i.showHistoryIcon&&e.enableChatSession!==!1?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:1,ref_key:`historyIconRef`,ref:l,class:(0,t.normalizeClass)([`bkai-icon`,`bkai-history`,{disabled:!x.value}]),style:(0,t.normalizeStyle)(C()),onClick:r[4]||=e=>x.value?E(e):void 0},null,6)),[[(0,t.unref)(o),{content:S((0,t.unref)(R9)(`历史会话`)),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),e.chatGroup?.enabled?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:2,class:`bkai-icon bkai-zhushou`,onClick:D},null,512)),[[(0,t.unref)(o),{content:(0,t.unref)(R9)(`转人工`),boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),i.showCompressionIcon?(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createElementBlock)(`i`,{key:3,class:(0,t.normalizeClass)([`bkai-icon`,y.value]),onClick:r[5]||=e=>a(`toggle-compression`)},null,2)),[[(0,t.unref)(o),{content:b.value,boundary:`parent`}]]):(0,t.createCommentVNode)(`v-if`,!0),(0,t.withDirectives)((0,t.createElementVNode)(`i`,{class:`bkai-icon bkai-close-line-2`,onClick:r[6]||=e=>a(`close`)},null,512),[[(0,t.unref)(o),{content:(0,t.unref)(R9)(`关闭`),boundary:`parent`}]])])],2))}}),[[`__scopeId`,`data-v-6dcebb8e`]]);function _Ut(e){let t=L9(e);fetch(t,{method:`GET`,credentials:`include`}).catch(()=>{})}async function vUt(e,t={}){let{enableModelSelect:n=!0}=t,r=[e.agent.getAgentInfo(),e.session.getSessions()];n&&typeof e.agent.getLlms==`function`&&r.push(e.agent.getLlms().catch(e=>{console.error(`[runAgentBootstrap] Failed to load models:`,e)})),await Promise.all(r);let i=e.agent.info.value?.saasUrl;i&&_Ut(i)}var yUt=class{_isGenerating;_isModelsLoading;_isStopLoading;_models;_selectedLlmCode;_selectedModelName;_selectedModelSupportsVision;agentModule;config;eventEmitter;messageModule;sessionModule;hasValidSelection(){let e=this._selectedLlmCode.value;return!!e&&this._models.value.some(t=>t.llm_code===e)}isSessionPending(){return this.sessionModule!=null&&this.sessionModule.current.value==null}applySessionModel(e){let t=this._models.value;if(t.length===0){this._selectedLlmCode.value=void 0;return}if(this.isSessionPending())return;if(e&&t.some(t=>t.llm_code===e)){this._selectedLlmCode.value=e;return}if(this.hasValidSelection())return;let n=t.find(e=>e.property?.default)??t[0];this._selectedLlmCode.value=n?.llm_code}async persistSessionModel(e){let t=this.sessionModule?.current.value;if(!(!t?.sessionCode||!e)&&t.model!==e)try{await this.sessionModule.updateSession({...t,model:e})}catch(e){console.error(`[ChatBusinessManager] Failed to persist session model:`,e),this.emit(`chat-error`,{action:`persistSessionModel`,error:e})}}resolveChatModel(e){return(e??this._selectedLlmCode.value)||void 0}autoRenameSessionIfNeeded(e){let t=this.sessionModule;if(!t||this.messageModule.list.value.length!==1)return;let n=t.renameSession(e);n&&n.then(n=>{let r=t.list.value.find(t=>t.sessionCode===e)??(t.current?.value?.sessionCode===e?t.current.value:null),i=n?.sessionName??r?.sessionName;i&&this.config.onSessionRenamed?.(i,e)}).catch(e=>{console.error(`[ChatBusinessManager] Auto rename session failed:`,e)})}emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e,n,r=null,i=null,a={}){this.agentModule=e,this.messageModule=n,this.sessionModule=r,this.eventEmitter=i,this.config=a,this._isGenerating=(0,t.ref)(!1),this._isStopLoading=(0,t.ref)(!1),this._isModelsLoading=(0,t.ref)(!1),this._models=(0,t.ref)([]),this._selectedLlmCode=(0,t.ref)(void 0),this._selectedModelName=(0,t.computed)(()=>{let e=this._selectedLlmCode.value;return e?this._models.value.find(t=>t.llm_code===e)?.llm_name??``:``}),this._selectedModelSupportsVision=(0,t.computed)(()=>{let e=this._selectedLlmCode.value;return e?!!this._models.value.find(t=>t.llm_code===e)?.property?.support_vision:!1}),this.sessionModule&&(0,t.watch)(()=>this.sessionModule.current.value?.sessionCode,()=>{this.applySessionModel(this.sessionModule.current.value?.model)})}get isGenerating(){return this._isGenerating}get isStopLoading(){return this._isStopLoading}get isMessagesLoading(){return this.messageModule.isListLoading}get models(){return this._models}get isModelsLoading(){return this._isModelsLoading}get selectedLlmCode(){return this._selectedLlmCode}get selectedModelName(){return this._selectedModelName}get selectedModelSupportsVision(){return this._selectedModelSupportsVision}get messages(){return this.messageModule.list}async loadModels(e={}){this._isModelsLoading.value=!0;try{let t=this.agentModule.models?.value;if(!e.force&&Array.isArray(t)&&t.length>0)this._models.value=[...t];else if(typeof this.agentModule.getLlms==`function`){let e=await this.agentModule.getLlms();this._models.value=Array.isArray(e)?e:[]}else this._models.value=[];this.applySessionModel(this.sessionModule?.current.value?.model)}catch(e){console.error(`[ChatBusinessManager] Failed to load models:`,e),this._models.value=[],this._selectedLlmCode.value=void 0}finally{this._isModelsLoading.value=!1}}setModels(e){this._models.value=e,this.applySessionModel(this.sessionModule?.current.value?.model)}setSelectedModelByName(e){if(!e){this._selectedLlmCode.value=void 0;return}let t=this._models.value.find(t=>t.llm_name===e);this._selectedLlmCode.value=t?.llm_code,this.persistSessionModel(t?.llm_code)}setSelectedModel(e){this._selectedLlmCode.value=e?.llm_code,this.persistSessionModel(e?.llm_code)}get openingRemark(){return this.config.openingRemark||``}get predefinedQuestions(){return this.config.predefinedQuestions||[]}async batchDeleteMessages(e){try{await this.messageModule.deleteMessages(e);let t=e.map(e=>e.id).filter(Boolean);this.emit(`messages-batch-deleted`,{messageIds:t})}catch(e){throw console.error(`Failed to batch delete messages:`,e),this.emit(`chat-error`,{action:`batch-delete-messages`,error:e}),e}}async deleteMessage(e){try{await this.messageModule.deleteMessages([e]),this.emit(`message-deleted`,{messageId:e.id})}catch(e){throw console.error(`Failed to delete message:`,e),this.emit(`chat-error`,{action:`delete-message`,error:e}),e}}handleStreamEnd(){this._isGenerating.value=!1,this.emit(`receive-end`,{})}handleStreamError(e){this._isGenerating.value=!1,this.emit(`receive-error`,{error:e})}handleStreamStart(){this._isGenerating.value=!0,this.emit(`receive-start`,{})}async regenerateFromAIMessages(e,t){try{if(!e||e.length===0)throw Error(`No AI messages provided`);let n=this.messages.value,r=I9(n,e[0]);if(!r)throw Error(`No user message found before AI messages`);let i=r.id;if(i===void 0)throw Error(`User message has no id`);await this.regenerateMessage(String(i),t)}catch(e){throw console.error(`Failed to regenerate from AI messages:`,e),this.emit(`chat-error`,{action:`regenerate`,error:e}),e}}async regenerateMessage(e,t){try{let n=this.messages.value,r=n.findIndex(t=>String(t.id)===e);if(r===-1)throw Error(`Message not found: ${e}`);let i=n[r];if(i.role!==g9.User)throw Error(`Can only regenerate from user messages`);let a=n.slice(r),o=typeof i.content==`string`?i.content:JSON.stringify(i.content),s=i.property;this._isGenerating.value=!0;let l=this.messageModule.deleteMessages(a);this.agentModule.chat(o,t,void 0,void 0,s,this.resolveChatModel()),this.emit(`chat-regenerate`,{messageId:e}),l.catch(e=>{console.error(`[regenerateMessage] Delete API error:`,e)})}catch(e){throw console.error(`Failed to regenerate message:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`regenerate`,error:e}),e}}async resendMessageWithProperty(e,t,n,r){try{let i=this.messages.value,a=i.findIndex(t=>String(t.id)===e);if(a===-1)throw Error(`Message not found: ${e}`);if(i[a].role!==g9.User)throw Error(`Can only resend user messages`);let o=i.slice(a);this._isGenerating.value=!0;let s=this.messageModule.deleteMessages(o);this.agentModule.chat(n,t,void 0,void 0,r,this.resolveChatModel()),this.emit(`chat-resend`,{messageId:e}),s.catch(e=>{console.error(`[resendMessageWithProperty] Delete API error:`,e)})}catch(e){throw console.error(`Failed to resend message with property:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`resend`,error:e}),e}}async retryMessage(e){try{console.warn(`retryMessage not implemented yet`),this.emit(`chat-retry`,{messageId:e})}catch(e){throw console.error(`Failed to retry message:`,e),this.emit(`chat-error`,{action:`retry`,error:e}),e}}async sendMessage(e,t,n={}){try{if(!t)throw Error(`No active session. Please create or select a session first.`);this._isGenerating.value=!0,this.emit(`send-message`,{content:e}),await this.agentModule.chat(e,t,void 0,void 0,n.property,this.resolveChatModel(n.model)),this.autoRenameSessionIfNeeded(t)}catch(e){throw console.error(`Failed to send message:`,e),this._isGenerating.value=!1,this.emit(`chat-error`,{action:`send`,error:e}),e}}async stopGeneration(){let e=this.sessionModule?.current?.value?.sessionCode??``;this._isStopLoading.value=!0;try{await this.agentModule.stopChat(e),this._isGenerating.value=!1,this.emit(`stop`,{})}catch(e){throw console.error(`Failed to stop generation:`,e),this.emit(`chat-error`,{action:`stop`,error:e}),e}finally{this._isStopLoading.value=!1}}},B9=class{agentModule;config;eventEmitter;messageModule;sessionModule;emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e,t=null,n=null,r={},i=null){this.sessionModule=e,this.agentModule=t,this.eventEmitter=n,this.config=r,this.messageModule=i}get currentSession(){return this.sessionModule.current}get isCreateLoading(){return this.sessionModule.isCreateLoading}get isCurrentLoading(){return this.sessionModule.isCurrentLoading}get isDeleteLoading(){return this.sessionModule.isDeleteLoading}get isListLoading(){return this.sessionModule.isListLoading}get isLoadingMore(){return this.sessionModule.isLoadingMore}get isUpdateLoading(){return this.sessionModule.isUpdateLoading}get hasMoreSessions(){return this.sessionModule.hasMore}get sessionCount(){return this.sessionModule.count}get sessionList(){return this.sessionModule.list}async createNewSession(e){let t=this.currentSession.value;if(t?.sessionCode&&this.isCurrentSessionEmpty(t))return null;await this.loadSessions();let n=this.sessionList.value;if(n.length>0){let r=n[0];if(r.sessionCode===t?.sessionCode?this.isCurrentSessionEmpty(r):this.isSessionEmpty(r))return await this.syncSessionModelIfNeeded(e?.model,r),await this.switchSession(r.sessionCode,{loadMessages:!1}),null}return await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode(),model:e?.model}),this.sessionModule.current.value}generateSessionCode(){return`new_session_${Date.now()}`}async syncSessionModelIfNeeded(e,t){if(!e)return;let n=t??this.sessionModule.current.value;!n?.sessionCode||n.model===e||await this.sessionModule.updateSession({...n,model:e})}async createSession(e={}){if(this.config.enableChatSession===!1)throw Error(`Chat session is disabled`);try{let t={sessionName:e.name||`新会话`,sessionCode:e.sessionCode||`session_${Date.now()}`,isTemporary:e.isTemporary||!1,...e.model?{model:e.model}:{},sessionProperty:{labels:e.labels}};await this.sessionModule.createSession(t);let n=this.agentModule?.info.value;n&&this.agentModule?.handleRole(n,t.sessionCode),this.emit(`session-created`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to create session:`,e),this.emit(`session-error`,{action:`create`,error:e}),e}}async deleteSession(e){try{await this.sessionModule.deleteSession(e),this.emit(`session-deleted`,{sessionCode:e})}catch(e){throw console.error(`Failed to delete session:`,e),this.emit(`session-error`,{action:`delete`,error:e}),e}}async getSession(e){try{await this.sessionModule.getSession(e)}catch(e){throw console.error(`Failed to get session:`,e),this.emit(`session-error`,{action:`get`,error:e}),e}}isSessionEmpty(e){let t=this.findSession(e.sessionCode)?.sessionContentCount??e.sessionContentCount;return t==null?!1:t===0}isCurrentSessionEmpty(e){return this.messageModule&&kHt(this.messageModule.list.value)?!1:this.isSessionEmpty(e)}findSession(e){return this.sessionList.value.find(t=>t.sessionCode===e)}async loadRecentSession(e){try{if(this.currentSession.value?.sessionCode)return;e?.skipLoadSessions||await this.loadSessions();let t=this.sessionList.value;if(this.config.initialSessionCode){let e=this.findSession(this.config.initialSessionCode);await this.switchSession(this.config.initialSessionCode,{loadMessages:e?!this.isSessionEmpty(e):!0});return}if(t.length>0){let n=t[0],r=(n.sessionContentCount??0)>0,i=e?.alwaysCreateNewSession??this.config.alwaysCreateNewSession??!1;r||i?await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode()}):await this.switchSession(n.sessionCode,{loadMessages:!1});return}await this.createSession({name:`新会话`,sessionCode:this.generateSessionCode()})}catch(e){throw console.error(`Failed to load recent session:`,e),e}}async loadSessions(){try{await this.sessionModule.getSessions(),this.emit(`sessions-loaded`,{sessions:this.sessionList.value})}catch(e){throw console.error(`Failed to load sessions:`,e),this.emit(`session-error`,{action:`load`,error:e}),e}}async loadMoreSessions(){try{await this.sessionModule.loadMoreSessions()}catch(e){throw console.error(`Failed to load more sessions:`,e),this.emit(`session-error`,{action:`loadMore`,error:e}),e}}async switchSession(e,t){try{await this.sessionModule.chooseSession(e,t),this.emit(`session-switched`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to switch session:`,e),this.emit(`session-error`,{action:`switch`,error:e}),e}}async updateSessionName(e,t){try{let n=this.sessionList.value.find(t=>t.sessionCode===e);if(!n)throw Error(`Session not found: ${e}`);await this.sessionModule.updateSession({...n,sessionName:t}),this.emit(`session-updated`,{session:this.sessionModule.current.value})}catch(e){throw console.error(`Failed to update session name:`,e),this.emit(`session-error`,{action:`update`,error:e}),e}}},bUt=class{messageModule;sessionModule;constructor(e,t){this.messageModule=e,this.sessionModule=t}async shareMessages(e){if(e.length===0)throw Error(`No messages to share`);let t=this.sessionModule.current?.value?.sessionCode;if(!t)throw Error(`No active session`);let n=await this.messageModule.shareMessages(t,e);if(!n)throw Error(`Share failed: no result returned`);return{shareUrl:`${n.share_page}share-page/${n.share_token}`,userMessageIds:e.map(e=>String(e.id))}}},V9=class{_agentShortcuts;_effectiveShortcuts;_propsShortcuts;eventEmitter;emit(e,t){this.eventEmitter?.emit(e,t)}constructor(e=null,n=[]){this._propsShortcuts=(0,t.ref)(n),this._agentShortcuts=(0,t.ref)([]),this.eventEmitter=e,this._effectiveShortcuts=(0,t.computed)(()=>this._propsShortcuts.value.length>0?this._propsShortcuts.value:this._agentShortcuts.value.length>0?this._agentShortcuts.value:[])}get count(){return this._effectiveShortcuts.value.length}get effectiveShortcuts(){return this._effectiveShortcuts}get hasShortcuts(){return this._effectiveShortcuts.value.length>0}get shortcuts(){return this._effectiveShortcuts}addShortcut(e){this._propsShortcuts.value.push(e)}clear(){this._propsShortcuts.value=[],this._agentShortcuts.value=[]}filterByTextLength(e,t){return!e||e.length>t?[]:this._effectiveShortcuts.value}filterShortcuts(e,t){return t?this._effectiveShortcuts.value.filter(n=>t(n,e)):this._effectiveShortcuts.value}getShortcutById(e){return this._effectiveShortcuts.value.find(t=>t.id===e)}handleShortcutClick(e,t,n=`main`){this.emit(`shortcut-click`,{shortcut:e,selectedText:t,source:n})}limitShortcuts(e){return this._effectiveShortcuts.value.slice(0,e)}removeShortcut(e){this._propsShortcuts.value=this._propsShortcuts.value.filter(t=>t.id!==e)}setAgentShortcuts(e){this._agentShortcuts.value=e}setShortcuts(e){this._propsShortcuts.value=e}},xUt=class{_isCompressed;_isDraggingOrResizing;_nimbusMinimized;_panelVisible;_positionAndSize;cleanupFunctions;config;containerRef=null;debugMode;listeners;onceListeners;constructor(e={}){this.config=e,this.listeners=new Map,this.onceListeners=new Map,this.debugMode=e.debug??!1,this.cleanupFunctions=[],this._panelVisible=(0,t.ref)(e.initialPanelVisible??!1),this._nimbusMinimized=(0,t.ref)(e.initialNimbusMinimized??!1),this._isDraggingOrResizing=(0,t.ref)(!1),this._isCompressed=(0,t.ref)(!1),this._positionAndSize=(0,t.ref)({x:0,y:0,width:400,height:window.innerHeight})}get container(){return{updatePosition:this.updatePosition.bind(this),updateSize:this.updateSize.bind(this),updatePositionAndSize:this.updatePositionAndSize.bind(this),toggleCompression:this.toggleCompression.bind(this),expandForSidePanel:this.expandForSidePanel.bind(this),collapseSidePanel:this.collapseSidePanel.bind(this),positionAndSize:(0,t.computed)(()=>this.containerRef?.positionAndSize?.value??this._positionAndSize.value),isCompressed:(0,t.computed)(()=>this._isCompressed.value),isSidePanelExpanded:(0,t.computed)(()=>this.containerRef?.isSidePanelExpanded?.value??!1)}}get isCompressed(){return this._isCompressed}get isDraggingOrResizing(){return this._isDraggingOrResizing}get nimbus(){return{minimize:this.minimizeNimbus.bind(this),restore:this.restoreNimbus.bind(this),toggle:this.toggleNimbus.bind(this),isMinimized:(0,t.computed)(()=>this._nimbusMinimized.value)}}get nimbusMinimized(){return this._nimbusMinimized}get panel(){return{show:this.showPanel.bind(this),hide:this.hidePanel.bind(this),toggle:this.togglePanel.bind(this),isVisible:(0,t.computed)(()=>this._panelVisible.value)}}get panelVisible(){return this._panelVisible}get state(){return{panelVisible:this._panelVisible,nimbusMinimized:this._nimbusMinimized,isDraggingOrResizing:this._isDraggingOrResizing,positionAndSize:this._positionAndSize}}collapseSidePanel(){this.containerRef?.collapseSidePanel&&this.containerRef.collapseSidePanel()}destroy(){this.listeners.clear(),this.onceListeners.clear(),this.cleanupFunctions.forEach(e=>e()),this.cleanupFunctions=[],this.debugMode&&console.debug(`[ComponentManager] Destroyed`)}emit(e,t){this.debugMode&&console.debug(`[ComponentManager] Emitting "${e}"`,t);let n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(t){console.error(`[ComponentManager] Error in listener for "${e}":`,t)}});let r=this.onceListeners.get(e);if(r&&r.size>0){let n=Array.from(r);this.onceListeners.delete(e),n.forEach(n=>{try{n(t)}catch(t){console.error(`[ComponentManager] Error in once listener for "${e}":`,t)}})}}emitInternal(e,t){this.emit(e,t)}expandForSidePanel(e){this.containerRef?.expandForSidePanel&&this.containerRef.expandForSidePanel(e)}getConfig(){return this.config}getRegisteredEvents(){let e=new Set;return this.listeners.forEach((t,n)=>e.add(n)),this.onceListeners.forEach((t,n)=>e.add(n)),Array.from(e)}handleDragging(e){this._isDraggingOrResizing.value=!0,this._positionAndSize.value=e,this.emit(`dragging`,e)}handleDragStop(e){this._isDraggingOrResizing.value=!1,this._positionAndSize.value=e,this.emit(`drag-stop`,e)}handleNimbusClick(){this.emit(`nimbus-click`,{}),this.showPanel()}handlePopupClick(){this.emit(`popup-click`,{}),this.showPanel()}handlePopupShortcutClick(e){this.emit(`popup-shortcut-click`,{shortcut:e}),this.emit(`shortcut-click`,{shortcut:e,source:`popup`})}handleResizeStop(e){this._isDraggingOrResizing.value=!1,this._positionAndSize.value=e,this.emit(`resize-stop`,e)}handleResizing(e){this._isDraggingOrResizing.value=!0,this._positionAndSize.value=e,this.emit(`resizing`,e)}handleShortcutClick(e,t){this.emit(`shortcut-click`,{shortcut:e,source:t})}hasListeners(e){return this.listenerCount(e)>0}hidePanel(){this._panelVisible.value=!1,this.emit(`panel-hide`,{})}listenerCount(e){return(this.listeners.get(e)?.size??0)+(this.onceListeners.get(e)?.size??0)}minimizeNimbus(){this._nimbusMinimized.value=!0,this.emit(`nimbus-minimize`,{})}off(e,t){t?(this.listeners.get(e)?.delete(t),this.onceListeners.get(e)?.delete(t),this.debugMode&&console.debug(`[ComponentManager] Unsubscribed from "${e}", remaining: ${this.listenerCount(e)}`)):(this.listeners.delete(e),this.onceListeners.delete(e),this.debugMode&&console.debug(`[ComponentManager] Removed all listeners for "${e}"`))}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.debugMode&&console.debug(`[ComponentManager] Subscribed to "${e}", total: ${this.listenerCount(e)}`),()=>{this.off(e,t)}}once(e,t){return this.onceListeners.has(e)||this.onceListeners.set(e,new Set),this.onceListeners.get(e).add(t),this.debugMode&&console.debug(`[ComponentManager] Subscribed once to "${e}"`),()=>{this.onceListeners.get(e)?.delete(t)}}restoreNimbus(){this._nimbusMinimized.value=!1,this.emit(`nimbus-restore`,{})}setCompressed(e){this._isCompressed.value=e}setContainerRef(e){this.containerRef=e,e?.isCompressed&&(this._isCompressed.value=e.isCompressed.value)}setDebugMode(e){this.debugMode=e}setDraggingOrResizing(e){this._isDraggingOrResizing.value=e}showPanel(e){this._panelVisible.value=!0,this.emit(`panel-show`,{sessionCode:e})}toggleCompression(){this.containerRef?this.containerRef.toggleCompression():this._isCompressed.value=!this._isCompressed.value}toggleNimbus(){this._nimbusMinimized.value?this.restoreNimbus():this.minimizeNimbus()}togglePanel(){this._panelVisible.value?this.hidePanel():this.showPanel()}updatePosition(e,t){this._positionAndSize.value={...this._positionAndSize.value,x:e,y:t}}updatePositionAndSize(e,t,n,r){this._positionAndSize.value={x:e,y:t,width:n,height:r}}updateSize(e,t){this._positionAndSize.value={...this._positionAndSize.value,width:e,height:t}}};function SUt(e){return new xUt(e)}var CUt={"panel-show":`show`,"panel-hide":`close`,"panel-toggle":null,"nimbus-click":null,"nimbus-minimize":null,"nimbus-restore":null,"popup-click":null,"popup-shortcut-click":null,dragging:`dragging`,resizing:`resizing`,"drag-stop":`drag-stop`,"resize-stop":`resize-stop`,"compression-toggle":null,"side-panel-expand":null,"side-panel-collapse":null,"send-message":`send-message`,"receive-start":`receive-start`,"receive-text":`receive-text`,"receive-end":`receive-end`,"receive-error":null,stop:`stop`,"chat-regenerate":null,"chat-retry":null,"message-deleted":null,"messages-batch-deleted":null,"session-created":null,"session-switched":null,"session-deleted":null,"session-updated":null,"sessions-loaded":null,"session-initialized":`session-initialized`,"session-error":null,"shortcut-click":`shortcut-click`,"chat-error":null,"sdk-error":`sdk-error`,"new-chat":`new-chat`,"new-chat-created":`new-chat-created`,"history-click":`history-click`,"auto-generate-name":`auto-generate-name`,"help-click":`help-click`,rename:`rename`,share:`share`,close:`close`,"toggle-compression":null,"transfer-messages":`transfer-messages`,"share-messages":`share-messages`,"agent-info-loaded":null,error:null};function wUt(e,t){switch(e){case`send-message`:return[t.content];case`rename`:return[t.newName,t.sessionCode];case`history-click`:return[t.event];case`dragging`:case`resizing`:case`drag-stop`:case`resize-stop`:case`shortcut-click`:case`session-initialized`:case`sdk-error`:case`transfer-messages`:case`share-messages`:case`new-chat-created`:return[t];case`panel-show`:case`panel-hide`:case`receive-start`:case`receive-text`:case`receive-end`:case`stop`:case`new-chat`:case`auto-generate-name`:case`help-click`:case`share`:case`close`:return[];default:return[t]}}var TUt=class{_selectedMessageIds;_isSelectionMode;_editingSessionCode;_loadingStates;constructor(){this._selectedMessageIds=(0,t.ref)(new Set),this._isSelectionMode=(0,t.ref)(!1),this._editingSessionCode=(0,t.ref)(null),this._loadingStates=(0,t.reactive)({})}get isSelectionMode(){return this._isSelectionMode}get editingSessionCode(){return this._editingSessionCode}toggleSelectionMode(){this._isSelectionMode.value=!this._isSelectionMode.value,this._isSelectionMode.value||this.clearSelection()}enableSelectionMode(){this._isSelectionMode.value=!0}disableSelectionMode(){this._isSelectionMode.value=!1,this.clearSelection()}toggleMessageSelection(e){this._selectedMessageIds.value.has(e)?this._selectedMessageIds.value.delete(e):this._selectedMessageIds.value.add(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}selectMessage(e){this._selectedMessageIds.value.add(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}deselectMessage(e){this._selectedMessageIds.value.delete(e),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}isMessageSelected(e){return this._selectedMessageIds.value.has(e)}clearSelection(){this._selectedMessageIds.value.clear(),this._selectedMessageIds.value=new Set(this._selectedMessageIds.value)}selectAllMessages(e){this._selectedMessageIds.value=new Set(e)}get selectedMessages(){return Array.from(this._selectedMessageIds.value)}get selectedCount(){return this._selectedMessageIds.value.size}get hasSelection(){return this._selectedMessageIds.value.size>0}startEditingSession(e){this._editingSessionCode.value=e}stopEditingSession(){this._editingSessionCode.value=null}isEditingSession(e){return e?this._editingSessionCode.value===e:this._editingSessionCode.value!==null}setLoading(e,t){this._loadingStates[e]=t}isLoading(e){return this._loadingStates[e]??!1}clearLoadingStates(){Object.keys(this._loadingStates).forEach(e=>{this._loadingStates[e]=!1})}reset(){this.clearSelection(),this.disableSelectionMode(),this.stopEditingSession(),this.clearLoadingStates()}},EUt=class extends Error{constructor(){super(`[ChatBot] Initialization was superseded by a newer init`),this.name=`ChatBotInitStaleError`}};function DUt(e){let{props:n,emit:r,reportError:i,managerErrorBridge:a}=e,o=(0,t.shallowRef)(null),s=(0,t.shallowRef)(null),l=(0,t.shallowRef)(null),u=(0,t.shallowRef)(null),d=(0,t.ref)(!1),f=(0,t.ref)(!n.chatHelper),p=(0,t.ref)(null),m=(0,t.computed)(()=>d.value),h=()=>n.chatHelper?!n.chatHelper.agent||!n.chatHelper.session||!n.chatHelper.message?{valid:!1,error:`[ChatBot] Invalid chatHelper: missing required modules (agent, session, message)`}:{valid:!0}:n.url?{valid:!0}:{valid:!1,error:`[ChatBot] Neither chatHelper nor url provided. Component requires at least one.`},g=()=>{let e=h();if(!e.valid)return console.error(e.error),p.value=Error(e.error),null;if(n.chatHelper)return n.chatHelper;let a=new w9({onStart:()=>{r(`receive-start`)},onMessage:e=>{r(`receive-text`)},onDone:()=>{r(`receive-end`)},onError:e=>{i(e,`Stream error`)}}),o=P9({requestData:EHt(L9(n.url),()=>(0,t.toValue)(n.requestOptions)),protocol:a});return a.injectMessageModule(o.message),o},_=e=>{if(e)try{e.agent.abortChat(),e.agent.clearLongPollTimer?.()}catch{}},v=0,y=null,b=null,x=null,S=e=>{x&&=(e?x.reject(e):x.resolve(),null),y=null},C=e=>{if(e!==v)throw new EUt},w=async e=>{let t=o.value;d.value=!1,p.value=null,f.value=!n.chatHelper,_(t),C(e),o.value=null,s.value=null,l.value=null,u.value=null;let m=g();if(!m)throw p.value??Error(`[ChatBot] Failed to create chatHelper`);let h=new B9(m.session,m.agent,a,{enableChatSession:!0,autoSwitchToInitialSession:!!n.sessionCode,loadRecentSessionOnMount:n.autoLoad,initialSessionCode:n.sessionCode,alwaysCreateNewSession:n.alwaysCreateNewSession},m.message),v=new yUt(m.agent,m.message,m.session,a,{openingRemark:n.helloText,predefinedQuestions:n.prompts,placeholder:n.placeholder,onSessionRenamed:(e,t)=>r(`rename`,e,t)}),y=new V9(null,n.shortcuts||[]);o.value=m,s.value=h,l.value=v,u.value=y;try{f.value&&(await vUt(m,{enableModelSelect:n.enableModelSelect!==!1&&!n.models?.length}),C(e),await h.loadRecentSession({skipLoadSessions:!0}),C(e)),n.enableModelSelect!==!1&&(n.models?.length?v.setModels(n.models):await v.loadModels(),C(e)),C(e),d.value=!0,r(`agent-info-loaded`,m)}catch(t){throw C(e),p.value=i(t,`Failed to initialize ChatBot`),t}},T=()=>{S(new EUt),b=null;let e=++v;y=new Promise((t,n)=>{x={resolve:t,reject:n},w(e).then(()=>{x&&=(b=Promise.resolve(),x.resolve(),null)}).catch(e=>{x&&=(x.reject(MHt(e)),null)}).finally(()=>{e===v&&(y=null)})}),y.catch(()=>{})};return(0,t.watch)([()=>n.url,()=>n.chatHelper],()=>T(),{immediate:!0}),(0,t.onBeforeUnmount)(()=>{S(),_(o.value)}),{chatHelper:o,isStandaloneMode:f,isInitialized:d,isReady:m,initError:p,whenReady:()=>d.value?(b||=Promise.resolve(),b):p.value?Promise.reject(p.value):y||Promise.resolve(),chatBusinessManager:l,sessionBusinessManager:s,shortcutManager:u}}function OUt(e){let{props:n,chatHelper:r,chatBusinessManager:i,sessionBusinessManager:a,shortcutManager:o,isStandaloneMode:s,isInitialized:l,selectedShortcut:u}=e,d=(0,t.computed)(()=>i.value?.isStopLoading.value?H8.StopLoading:((n.chatHelper||r.value)?.agent)?.isChatting?.value?H8.Streaming:H8.Complete),f=(0,t.computed)(()=>d.value===H8.Streaming?Y7.Disabled:void 0),p=(0,t.computed)(()=>i.value?.messages.value??[]),m=(0,t.computed)(()=>i.value?.isMessagesLoading.value??!1);return{messageStatus:d,messageToolsStatus:f,messages:p,isMessagesLoading:m,isGenerating:(0,t.computed)(()=>i.value?.isGenerating.value??!1),currentSession:(0,t.computed)(()=>a.value?.currentSession.value??null),isWelcomeState:(0,t.computed)(()=>s.value&&!l.value?!1:!m.value&&p.value.length===0),openingRemark:(0,t.computed)(()=>r.value?.agent.info.value?.conversationSettings?.openingRemark||``),effectiveResources:(0,t.computed)(()=>n.resources?.length?n.resources:r.value?.agent.info.value?.resources??[]),effectivePrompts:(0,t.computed)(()=>n.prompts?.length?n.prompts:r.value?.agent.info.value?.conversationSettings?.predefinedQuestions??[]),effectiveSkills:(0,t.computed)(()=>n.skills?.length?n.skills:(r.value?.agent.info.value?.relatedSkills??[]).map(e=>({skill_name:e.skill_name,skill_code:e.skill_code,description:e.description,icon:e.icon}))),effectiveSupportUpload:(0,t.computed)(()=>u.value?.supportUpload?u.value.supportUpload.vision===!0:i.value?.selectedModelSupportsVision.value??!1),chatbotStyle:(0,t.computed)(()=>({height:typeof n.height==`number`?`${n.height}px`:n.height,maxWidth:typeof n.maxWidth==`number`?`${n.maxWidth}px`:n.maxWidth})),filteredShortcuts:(0,t.computed)(()=>o.value?.shortcuts.value??[])}}var kUt=new Set([`chat-error`,`receive-error`,`session-error`]);function AUt(e,n={}){let r=new WeakSet,i=(i,a)=>{let o=MHt(i);return r.has(o)?o:(r.add(o),console.error(a?`[ChatBot] ${a}:`:`[ChatBot] error:`,i),e(`error`,o),(0,t.toValue)(n.errorToast)!==!1&&nc({message:o.message||R9(`请求失败`),theme:`error`}),o)};return{managerErrorBridge:{emit:(e,t)=>{kUt.has(e)&&i(t?.error)}},reportError:i}}var jUt={[W8.ApprovalCancel]:y9.ApprovalCancel,[W8.FlowNodeRetry]:y9.FlowNodeRetry,[W8.FlowNodeSkip]:y9.FlowNodeSkip};function MUt(e){return`operation`in e}function NUt(e){return`interruptId`in e&&`reason`in e&&e.reason===z8.UserQuestion}function PUt(e){return e===`cancelled`?C9.Cancelled:C9.Resolved}function FUt(e){let t=e?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot resume interrupt: no active session`);return t}function IUt(e){return{interruptId:e.interruptId,status:PUt(e.status),payload:e.payload}}function LUt(e){let{chatHelper:t,reportError:n}=e,r=async e=>{let n=t.value;if(!n)throw Error(`[ChatBot] Cannot resume interrupt: chatHelper not initialized`);if(!MUt(e))throw Error(`[ChatBot] Unsupported interrupt resume payload`);let r=FUt(n);if(e.operation===W8.ApprovalRefresh){n.agent.pollResumeSession(r);return}let i=jUt[e.operation];if(!i)throw Error(`[ChatBot] Unsupported interrupt resume operation: ${e.operation}`);let a=n.agent;if(e.operation===W8.ApprovalCancel){await a.userOperationStreamRequest(r,i,{interrupt_id:e.payload.interrupt_id});return}(e.operation===W8.FlowNodeRetry||e.operation===W8.FlowNodeSkip)&&await a.userOperationStreamRequest(r,i,{node_id:e.payload.node_id,task_id:String(e.payload.task_id)})},i=async(e,n)=>{let r=t.value;if(!r)throw Error(`[ChatBot] Cannot resume interrupt: chatHelper not initialized`);let i=FUt(r);await r.agent.streamRequest({sessionCode:i,resume:IUt(e),...n?{input:n}:{}})};return{handleInterruptResume:async(e,t)=>{try{if(MUt(e)){await r(e);return}if(NUt(e)){await i(e);return}throw Error(`[ChatBot] Unsupported interrupt resume payload`)}catch(e){n(e,`Failed to handle interrupt resume`)}},resumeUserQuestionWithInput:async(e,t)=>{try{if(!t.payload||!NUt(t.payload))throw Error(`[ChatBot] Invalid user question resume options`);let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`[ChatBot] User question free text input is empty`);await i(t.payload,n)}catch(e){n(e,`Failed to resume user question with input`)}}}}function RUt(e){let{emit:n,chatHelper:r,chatBusinessManager:i,getRequestOptions:a,reportError:o,resumeUserQuestionWithInput:s,selectedShortcut:l,selectedResources:u}=e,d=(0,t.shallowRef)([[]]),f=(0,t.shallowRef)(``),p=(e,t)=>{d.value=e,u.value=t},m=async(e,t={})=>{if(!i.value||!r.value)throw Error(`[ChatBot] Cannot send message: chatBusinessManager not initialized`);let o=r.value.session.current?.value?.sessionCode;if(!o)throw Error(`[ChatBot] Cannot send message: no active session`);d.value=[[]],f.value=``,u.value=[],n(`send-message`,typeof e==`string`?e:``);let s=F9(t.property,a);await i.value.sendMessage(e,o,{...t,...s?{property:s}:{}})},h=async e=>{let t=r.value?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot upload: no active session`);let n=await r.value.session.uploadFile(t,e);if(!n?.download_url)throw Error(`[ChatBot] Upload failed: no download URL returned`);return n},g=async e=>{let t=r.value?.session.current?.value?.sessionCode;if(!t)throw Error(`[ChatBot] Cannot resolve artifact URL: no active session`);let n=await r.value.session.getPvFileDownloadUrl(t,e.outputId);return{download_url:n?.download_url,preview_url:n?.preview_url}},_=async(e,t,n)=>{try{if(n?.payload&&s){d.value=[[]],f.value=``,u.value=[],await s(e,n);return}let t={};f.value&&(t.cite=f.value),l.value&&(t.command=l.value.id),u.value.length&&(t.resources=u.value),await m(e,Object.keys(t).length?{property:{extra:t}}:{})}catch(e){o(e,`Failed to send message`)}},v=async()=>{await y()},y=async()=>{if(!i.value){console.error(`[ChatBot] Cannot stop generation: chatBusinessManager not initialized`);return}try{await i.value.stopGeneration(),n(`stop`)}catch(e){o(e,`Failed to stop generation`)}};return{userInput:d,cite:f,handleUpdateModelValue:p,doSendMessage:m,handleSendMessage:_,handleArtifactClick:g,handleUpload:h,handleStopSending:v,stopGeneration:y}}var zUt=e=>!e||e.id===`share`;function BUt(e){let{emit:t,chatHelper:n,isStandaloneMode:r}=e,i=async e=>{if(!(!n.value||e.length===0))try{await FHt((await new bUt(n.value.message,n.value.session).shareMessages(e)).shareUrl),nc({message:`分享链接已复制到剪贴板`,theme:`success`})}catch(e){console.error(`[ChatBot] Failed to share messages:`,e),nc({message:`分享失败,请重试`,theme:`error`})}};return{handleConfirmShare:async(e,n)=>{r.value&&zUt(n)&&await i(e),t(`confirm-share`,e,n)}}}function VUt(e){let{props:n,emit:r,shortcutManager:i,doSendMessage:a,reportError:o,selectedShortcut:s}=e,l=(0,t.computed)(()=>i.value?.effectiveShortcuts.value??[]),u=(e,t)=>{let n=e,r;if(r=n.enable_fill_back&&n.fill_back_component_key?n.fill_back_component_key:n.components?.find(e=>e.fillBack)?.key,r&&t){let e=n.components?.map(e=>e.key===r?{...e,default:t}:{...e,default:e.default??void 0});s.value={...n,components:e,formModel:{...n.formModel,[r]:t}}}else s.value={...n,formModel:{...n.formModel}}},d=(e,t)=>{let n=e.components||[];return{extra:{cite:{type:`structured`,title:e.alias||e.name,data:n.map(e=>({key:e.name||e.key,value:String(t[e.key]??``)}))},command:e.id,context:n.map(e=>({[e.key]:t[e.key],context_type:e.type,__label:e.name||e.key,__key:e.key,__value:t[e.key]}))}}},f=e=>{let t=e.property?.extra;return t?.shortcut?t.shortcut:t?.command?l.value.find(e=>e.id===t.command)??null:null},p=(e,t)=>{u(e,t),r(`shortcut-click`,{shortcut:e,source:`main`})},m=()=>{s.value=null};return(0,t.watch)(()=>n.shortcuts,e=>{i.value?.setShortcuts(e||[])},{immediate:!0}),(0,t.watch)(()=>e.chatHelper.value?.agent.info.value?.conversationSettings?.commands,e=>{e&&i.value?.setAgentShortcuts(e)},{immediate:!0}),{effectiveShortcuts:l,selectShortcutWithText:u,buildShortcutProperty:d,getShortcutFromMessage:f,handleSelectShortcut:p,handleCloseShortcut:m,handleShortcutSubmit:async e=>{if(!s.value){console.error(`[ChatBot] No selected shortcut`);return}let t=d(s.value,e),n=s.value.name,r=s.value;m();try{await a(n,{property:t})}catch(e){s.value=r,o(e,`Failed to submit shortcut`)}},sendShortcutDirectly:async(e,t)=>{let n=e,r={...n.formModel},i=n.components||[];for(let e of i)e.key in r||(r[e.key]=e.default??``);let s;s=n.enable_fill_back&&n.fill_back_component_key?n.fill_back_component_key:i.find(e=>e.fillBack)?.key,s&&t&&(r[s]=t);let l=d(n,r),u=n.name;try{await a(u,{property:l})}catch(e){o(e,`Failed to send shortcut directly`)}}}}function HUt(e){let{emit:t,chatHelper:n,chatBusinessManager:r,cite:i,focusInput:a,getShortcutFromMessage:o,buildShortcutProperty:s,getRequestOptions:l,reportError:u,stopGeneration:d}=e,f=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot delete messages: chatBusinessManager not initialized`);return}try{let t=r.value.messages.value,i=I9(t,e[0]);if(!i){console.error(`[ChatBot] No user message found before AI messages`);return}let a=[i,...e];await n.value.message.deleteMessages(a)}catch(e){u(e,`Failed to delete messages`)}},p=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot regenerate: chatBusinessManager not initialized`);return}let t=n.value.session.current?.value?.sessionCode;if(!t){console.error(`[ChatBot] Cannot regenerate: no active session`);return}try{await r.value.regenerateFromAIMessages(e,t)}catch(e){u(e,`Failed to regenerate`)}},m=async e=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot delete message: chatHelper not initialized`);return}try{let t=r.value.messages.value,i=t.findIndex(t=>t===e);if(i===-1){console.error(`[ChatBot] User message not found in messages list`);return}let a=[];for(let e=i+1;e<t.length;e++){let n=t[e];if(n.role===V8.User)break;a.push(n)}let o=[e,...a];await n.value.message.deleteMessages(o)}catch(e){u(e,`Failed to delete user message`)}};return{handleAgentAction:async(e,r)=>{if(e.id===`cite`){i.value=r.filter(e=>e.role!==V8.Reasoning).map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content||``)).join(`
|
|
3489
3489
|
`),a();return}if(e.id===`rebuild`){await p(r);return}if(e.id===`delete`){await f(r);return}if(e.id===`like`||e.id===`unlike`){let t=e.id===`like`?5:0;try{return await n.value?.session.getSessionFeedbackReasons(t)||[]}catch(e){return console.error(`[ChatBot] Failed to get feedback reasons:`,e),[]}}t(`agent-action`,e,r)},handleAgentFeedback:async(e,i,a,o)=>{if(!n.value){console.error(`[ChatBot] Cannot submit feedback: chatHelper not initialized`);return}let s=n.value.session.current?.value?.sessionCode;if(!s){console.error(`[ChatBot] Cannot submit feedback: no active session`);return}let l=AHt(r.value?.messages.value||[],i[0]);if(l===void 0){console.error(`[ChatBot] Cannot submit feedback: no user message found`);return}let d=e.id===`like`?5:0;try{await n.value.session.postSessionFeedback({sessionCode:s,sessionContentIds:[l],rate:d,labels:a,comment:o}),t(`feedback`,e,i[0],a,o)}catch(e){u(e,`Failed to submit feedback`)}},handleUserAction:async(e,t)=>{if(e.id===`delete`){await m(t);return}if(e.id===`cite`){i.value=typeof t.content==`string`?t.content:JSON.stringify(t.content||``),a();return}console.log(`handleUserAction`,e,t)},handleUserInputConfirm:async(e,t,i)=>{if(!n.value){console.error(`[ChatBot] Cannot edit message: chatHelper not initialized`);return}let a=n.value.session.current?.value?.sessionCode;if(!a){console.error(`[ChatBot] Cannot edit message: no active session`);return}let o=e.id;if(o===void 0){console.error(`[ChatBot] Cannot edit message: message has no id`);return}try{let n=e.property,i=F9(n,l);await r.value?.resendMessageWithProperty(String(o),a,typeof t==`string`?t:``,i)}catch(e){u(e,`Failed to edit and resend message`)}},handleUserShortcutConfirm:async(e,t)=>{if(!r.value||!n.value){console.error(`[ChatBot] Cannot edit shortcut message: chatHelper not initialized`);return}let i=n.value.session.current?.value?.sessionCode;if(!i){console.error(`[ChatBot] Cannot edit shortcut message: no active session`);return}let a=e.id;if(a===void 0){console.error(`[ChatBot] Cannot edit shortcut message: message has no id`);return}try{let n=o(e);if(!n){console.error(`[ChatBot] Cannot edit shortcut message: shortcut not found`);return}let u=F9(s(n,t),l),d=String(t.input??``);await r.value.resendMessageWithProperty(String(a),i,d,u)}catch(e){u(e,`Failed to edit shortcut message`)}},handleStopStreaming:d}}var UUt=(0,t.defineComponent)({__name:`chat-bot`,props:{autoLoad:{type:Boolean,default:!0},alwaysCreateNewSession:{type:Boolean},chatHelper:{default:void 0},enableSelection:{type:Boolean,default:!1},enableModelSelect:{type:Boolean,default:!0},errorToast:{type:Boolean,default:!0},models:{default:void 0},executionTabVisible:{type:Boolean},renderMode:{default:G8.Chat},extCls:{},height:{},helloText:{},useAgentName:{type:Boolean,default:!1},maxWidth:{},messageToolsTippyOptions:{},messageTools:{},updateTools:{},placeholder:{},prompts:{},requestOptions:{},resources:{default:()=>[]},sessionCode:{},shareLoading:{type:Boolean,default:!1},shortcuts:{default:()=>[]},skills:{},url:{default:``},placement:{default:`left`},resizeProps:{},size:{},getSideRenderComponent:{},getSideTabRenderComponent:{},onCustomTabChange:{}},emits:[`agent-action`,`agent-info-loaded`,`cancel-share`,`confirm-share`,`error`,`execution-panel-change`,`feedback`,`receive-end`,`receive-start`,`receive-text`,`rename`,`request-share`,`send-message`,`session-switched`,`shortcut-click`,`stop`],setup(e,{expose:n,emit:r}){let i=e,a={initialDivide:560,min:400},o=(0,t.computed)(()=>({...a,...i.resizeProps})),s=r,l=(0,t.useSlots)(),u=(0,t.ref)(),d=(0,t.ref)(),f=(0,t.shallowRef)([]),p=(0,t.ref)(null),m=(0,t.computed)({get:()=>i.renderMode??G8.Chat,set:()=>{}}),h=(0,t.computed)(()=>T.value?.selectedLlmCode.value),g=()=>{d.value?.focus?.()},{reportError:_,managerErrorBridge:v}=AUt(s,{errorToast:()=>i.errorToast}),{chatHelper:y,isStandaloneMode:b,isInitialized:x,isReady:S,initError:C,whenReady:w,chatBusinessManager:T,sessionBusinessManager:E,shortcutManager:D}=DUt({props:i,emit:s,reportError:_,managerErrorBridge:v}),{handleInterruptResume:O,resumeUserQuestionWithInput:k}=LUt({chatHelper:y,reportError:_}),{userInput:A,cite:j,handleUpdateModelValue:M,doSendMessage:N,handleSendMessage:P,handleUpload:F,handleArtifactClick:I,handleStopSending:L,stopGeneration:R}=RUt({emit:s,chatHelper:y,chatBusinessManager:T,getRequestOptions:()=>i.requestOptions,reportError:_,resumeUserQuestionWithInput:k,selectedShortcut:p,selectedResources:f}),{handleSelectShortcut:ee,handleCloseShortcut:z,handleShortcutSubmit:B,selectShortcutWithText:V,getShortcutFromMessage:te,buildShortcutProperty:ne,sendShortcutDirectly:re}=VUt({props:i,emit:s,chatHelper:y,shortcutManager:D,doSendMessage:N,reportError:_,selectedShortcut:p}),{messageStatus:ie,messageToolsStatus:ae,messages:H,isMessagesLoading:oe,isGenerating:se,currentSession:ce,isWelcomeState:le,openingRemark:ue,effectiveResources:de,effectivePrompts:fe,effectiveSkills:pe,effectiveSupportUpload:me,chatbotStyle:he,filteredShortcuts:ge}=OUt({props:i,chatHelper:y,chatBusinessManager:T,sessionBusinessManager:E,shortcutManager:D,isStandaloneMode:b,isInitialized:x,selectedShortcut:p}),{handleAgentAction:_e,handleAgentFeedback:ve,handleUserAction:ye,handleUserInputConfirm:be,handleUserShortcutConfirm:xe,handleStopStreaming:Se}=HUt({emit:s,chatHelper:y,chatBusinessManager:T,cite:j,focusInput:g,getShortcutFromMessage:te,buildShortcutProperty:ne,getRequestOptions:()=>i.requestOptions,reportError:_,stopGeneration:R}),Ce=(0,t.computed)(()=>!x.value||oe.value),we=(0,t.computed)(()=>{if(i.useAgentName)return y.value?.agent.info.value?.agentName||void 0}),Te=(0,t.computed)(()=>{if(i.enableModelSelect===!1)return;let e=T.value?.models.value??[];return e.length>0?e:void 0}),Ee=(0,t.computed)({get:()=>T.value?.selectedModelName.value??``,set:e=>{T.value?.setSelectedModelByName(e)}}),De=e=>{T.value?.setSelectedModel(e)};(0,t.watch)(()=>i.models,e=>{i.enableModelSelect===!1||!T.value||e?.length&&T.value.setModels(e)});let{handleConfirmShare:Oe}=BUt({emit:s,chatHelper:y,isStandaloneMode:b}),ke=(e,t)=>{s(`execution-panel-change`,e,t)},Ae=async e=>{if(i.onCustomTabChange)return i.onCustomTabChange(e);let t=e.data?.props;if(t?.task_id!=null&&t?.node_id)return y.value?.message.getFlowAgentTaskNodeInfo(t.task_id,t.node_id)};return n({sendMessage:e=>P(e,[[]]),stopGeneration:R,switchSession:async e=>{if(!E.value){console.error(`[ChatBot] Cannot switch session: sessionBusinessManager not initialized`);return}try{await E.value.switchSession(e),s(`session-switched`,E.value.currentSession.value)}catch(e){_(e,`Failed to switch session`)}},messages:H,currentSession:ce,isGenerating:se,get isReady(){return S.value},whenReady:w,getChatHelper:()=>y.value,setCiteText:e=>{j.value=e},focusInput:g,enterShareMode:()=>u.value?.enterShareMode(),exitShareMode:()=>u.value?.exitShareMode(),selectShortcut:(e,t)=>{V(e,t)},sendShortcut:(e,t)=>re(e,t),updateAgentInfo:async()=>{let e=y.value;if(!e)return null;try{await e.agent.getAgentInfo();let t=e.agent.info.value??null;return t?.conversationSettings?.commands&&D.value?.setAgentShortcuts(t.conversationSettings.commands),t}catch(e){return _(e,`Failed to update agentInfo`),null}},selectedLlmCode:h}),(n,r)=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{class:(0,t.normalizeClass)([`ai-chatbot`,i.extCls,{"welcome-state":(0,t.unref)(le)}]),style:(0,t.normalizeStyle)((0,t.unref)(he))},[(0,t.createVNode)((0,t.unref)(jVt),{ref_key:`chatContainerRef`,ref:u,cite:(0,t.unref)(j),"onUpdate:cite":r[0]||=e=>(0,t.isRef)(j)?j.value=e:null,"selected-shortcut":p.value,"onUpdate:selectedShortcut":r[1]||=e=>p.value=e,"selected-model":Ee.value,"onUpdate:selectedModel":r[2]||=e=>Ee.value=e,"render-mode":m.value,"onUpdate:renderMode":r[3]||=e=>m.value=e,"chat-loading":Ce.value,"common-tippy-options":e.messageToolsTippyOptions,"execution-tab-visible":i.executionTabVisible,"message-status":(0,t.unref)(ie),"message-tools":i.messageTools,"message-tools-status":(0,t.unref)(ae),messages:(0,t.unref)(H),"model-value":(0,t.unref)(A),models:Te.value,"on-agent-action":(0,t.unref)(_e),"on-agent-feedback":(0,t.unref)(ve),"on-interrupt-resume":(0,t.unref)(O),"get-side-render-component":i.getSideRenderComponent,"get-side-tab-render-component":i.getSideTabRenderComponent,"on-custom-tab-change":Ae,"on-send-message":(0,t.unref)(P),"on-stop-sending":(0,t.unref)(L),"on-artifact-click":(0,t.unref)(I),"on-upload":(0,t.unref)(F),"on-user-action":(0,t.unref)(ye),"on-user-input-confirm":(0,t.unref)(be),"on-user-shortcut-confirm":(0,t.unref)(xe),"opening-remark":(0,t.unref)(ue),placeholder:i.placeholder,placement:i.placement,"welcome-title":we.value,prompts:(0,t.unref)(fe),"resize-props":o.value,size:i.size,resources:(0,t.unref)(de),"shortcut-id":p.value?.id,shortcuts:(0,t.unref)(ge),skills:(0,t.unref)(pe),"support-upload":(0,t.unref)(me),"update-tools":i.updateTools,onCollapseChange:ke,onConfirmShare:(0,t.unref)(Oe),onDeleteShortcut:(0,t.unref)(z),onModelChange:De,onSelectShortcut:(0,t.unref)(ee),onShortcutClose:(0,t.unref)(z),onShortcutSubmit:(0,t.unref)(B),onStopStreaming:(0,t.unref)(Se),"onUpdate:modelValue":(0,t.unref)(M)},(0,t.createSlots)({message:(0,t.withCtx)(({message:r,messageToolsStatus:i,onInterruptResume:a})=>[(0,t.createCommentVNode)(` 消费方提供了 #message slot 时,优先使用消费方的渲染 `),(0,t.unref)(l).message?(0,t.renderSlot)(n.$slots,`message`,{key:0,message:r,messageToolsStatus:i,onInterruptResume:a}):((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:1},[(0,t.createCommentVNode)(` 否则使用默认的 MessageRender `),(0,t.createVNode)((0,t.unref)(m9),{message:r,"message-tools-status":i,"on-action":e=>(0,t.unref)(ye)(e,r),"on-input-confirm":(e,n)=>(0,t.unref)(be)(r,e,n),"on-interrupt-resume":a,"on-shortcut-confirm":e=>(0,t.unref)(xe)(r,e),"tippy-options":e.messageToolsTippyOptions},(0,t.createSlots)({_:2},[n.$slots.codeHeader?{name:`codeHeader`,fn:(0,t.withCtx)(e=>[(0,t.renderSlot)(n.$slots,`codeHeader`,(0,t.normalizeProps)((0,t.guardReactiveProps)(e)))]),key:`0`}:void 0]),1032,[`message`,`message-tools-status`,`on-action`,`on-input-confirm`,`on-interrupt-resume`,`on-shortcut-confirm`,`tippy-options`])],2112))]),_:2},[n.$slots.welcome?{name:`welcome`,fn:(0,t.withCtx)(e=>[(0,t.renderSlot)(n.$slots,`welcome`,(0,t.normalizeProps)((0,t.guardReactiveProps)(e)))]),key:`0`}:void 0]),1032,`cite.selected-shortcut.selected-model.render-mode.chat-loading.common-tippy-options.execution-tab-visible.message-status.message-tools.message-tools-status.messages.model-value.models.on-agent-action.on-agent-feedback.on-interrupt-resume.get-side-render-component.get-side-tab-render-component.on-send-message.on-stop-sending.on-artifact-click.on-upload.on-user-action.on-user-input-confirm.on-user-shortcut-confirm.opening-remark.placeholder.placement.welcome-title.prompts.resize-props.size.resources.shortcut-id.shortcuts.skills.support-upload.update-tools.onConfirmShare.onDeleteShortcut.onSelectShortcut.onShortcutClose.onShortcutSubmit.onStopStreaming.onUpdate:modelValue`.split(`.`))],6))}}),H9=function(e){return e.ERROR=`error`,e.IDLE=`idle`,e.LOADING_AGENT=`loading_agent`,e.READY=`ready`,e}({});function WUt(e){let{url:n,requestOptions:r,autoInit:i=!0,protocolCallbacks:a,enableModelSelect:o=!0}=e,s=(0,t.toValue)(n);if(!s)throw Error(`[useChatBootstrap] url is required`);let l=(0,t.ref)(H9.IDLE),u=(0,t.ref)(null),d=(0,t.ref)(!1),f=new Map,p=new w9({onStart:()=>{a?.onStart?.()},onMessage:e=>{a?.onMessage?.(e)},onDone:()=>{a?.onDone?.()},onError:e=>{a?.onError?.(e)}}),m=P9({requestData:EHt(s,r),protocol:p});p.injectMessageModule(m.message);let h=(0,t.computed)(()=>l.value===H9.LOADING_AGENT),g=(0,t.computed)(()=>l.value===H9.READY),_=(0,t.computed)(()=>m.agent.info.value??null),v=(0,t.computed)(()=>_.value?.agentName??``),y=(0,t.computed)(()=>m.session.current.value??null),b=(0,t.computed)(()=>m.session.list.value??[]),x=null,S=0,C=async e=>{u.value=null;try{if(l.value=H9.LOADING_AGENT,await vUt(m,{enableModelSelect:o}),e!==S)return;l.value=H9.READY,d.value=!0}catch(t){if(e!==S)return;throw console.error(`[useChatBootstrap] Initialization failed:`,t),u.value=t,l.value=H9.ERROR,t}},w=async()=>{if(d.value)return;if(x)return x;let e=S;return x=C(e).finally(()=>{e===S&&(x=null)}),x},T=()=>{S+=1,l.value=H9.IDLE,u.value=null,d.value=!1,x=null},E=async()=>{T(),await w()},D=async e=>{T();let t=m.http;t?.updateConfig?t.updateConfig({urlPrefix:e}):console.warn(`[useChatBootstrap] chatHelper.http.updateConfig is not implemented yet, URL change may not take effect`),await w()};return(0,t.watch)(()=>(0,t.toValue)(n),(e,t)=>{e&&e!==t&&t&&D(e).catch(()=>{})}),i&&Promise.resolve().then(()=>{w().catch(()=>{})}),{chatHelper:m,protocol:p,phase:l,isInitializing:h,isReady:g,error:u,agentInfo:_,agentName:v,currentSession:y,sessionList:b,initialize:w,retry:E,updateConfig:D,registerExtension:(e,t)=>{f.set(e,t)},getExtension:e=>f.get(e)}}function GUt(e){return{sendMessage:t=>e(`send-message`,{content:t}),receiveStart:()=>e(`receive-start`,{}),receiveText:()=>e(`receive-text`,{}),receiveEnd:()=>e(`receive-end`,{}),stop:()=>e(`stop`,{}),newChat:()=>e(`new-chat`,{}),newChatCreated:t=>e(`new-chat-created`,{session:t}),historyClick:t=>e(`history-click`,{event:t}),autoGenerateName:()=>e(`auto-generate-name`,{}),helpClick:()=>e(`help-click`,{}),rename:(t,n)=>e(`rename`,{newName:t,sessionCode:n}),share:()=>e(`share`,{}),transferMessages:t=>e(`transfer-messages`,{messageIds:t}),shareMessages:t=>e(`share-messages`,{messageIds:t})}}function KUt(e){let{componentManager:n,emit:r,debug:i=!1}=e,a=[],o=()=>{for(let[e,t]of Object.entries(CUt)){if(t===null)continue;let o=n.on(e,n=>{let a=wUt(e,n);i&&console.debug(`[useEventBridge] ${e} -> ${t}`,a),r(t,...a)});a.push(o)}},s=(e,t)=>{i&&console.debug(`[useEventBridge] Forwarding to manager: ${e}`,t),n.emit(e,t)},l=(e,...t)=>{i&&console.debug(`[useEventBridge] Direct emit: ${e}`,t),r(e,...t)},u=()=>{a.forEach(e=>e()),a.length=0};return o(),(0,t.onUnmounted)(()=>{u()}),{forwardToManager:s,emitDirect:l,cleanup:u}}function qUt(e){let{props:n,emit:r}=e,i=(0,t.ref)(),a=(0,t.ref)(),o=(0,t.computed)(()=>L9(n.url??``)),s=SUt({initialPanelVisible:!1,initialNimbusMinimized:n.defaultMinimize,enablePopup:n.enablePopup,enableNimbus:!n.hideNimbus,enableDraggable:n.draggable}),l=s.panelVisible,u=s.nimbusMinimized,{forwardToManager:d}=KUt({componentManager:s,emit:r}),f=GUt(d),p=new WeakSet,m=null,h=null,g=()=>{m&&=(clearTimeout(m.timer),null)},_=e=>{let{apiName:t,error:r,action:i,source:a,shouldToast:o=!0}=e,l=r instanceof Error?r.message:String(r),u=r instanceof Error?r:null;u&&p.has(u)||(u&&p.add(u),a!==`http`&&u&&m?.error===u&&g(),console.error(`[AIBlueking] ${t} error:`,r),o&&n.errorToast!==!1&&nc({message:l||R9(`请求失败`),theme:`error`}),s.emitInternal(`sdk-error`,{apiName:t,action:i,source:a,code:-1,message:l,data:r}))},v=e=>{g();let t=h??(S.value?`chat`:`init`);m={error:e,timer:setTimeout(()=>{m=null,_({apiName:t,error:e,source:`http`})},0)}},y=async(e,t)=>{let n=h;h=e;try{return await t()}finally{h=n}},b=e=>{_({apiName:`chat`,error:e,source:`business`})},{chatHelper:x,isReady:S,error:C,agentInfo:w,agentName:T,currentSession:E,initialize:D}=WUt({url:o,requestOptions:()=>(0,t.toValue)(n.requestOptions),autoInit:!0,enableModelSelect:n.enableModelSelect!==!1,protocolCallbacks:{onStart:()=>{f.receiveStart()},onMessage:()=>{f.receiveText()},onDone:()=>{f.receiveEnd()},onError:e=>{_({apiName:`chat`,error:e,source:`protocol`})}}}),O=x;O.onError?.(e=>{v(e)},{ignoreErrors:n.ignoreErrors});let k=new B9(O.session,O.agent,null,{enableChatSession:n.enableChatSession,initialSessionCode:n.initialSessionCode,alwaysCreateNewSession:n.alwaysCreateNewSession},O.message),A=new bUt(O.message,O.session),j=new V9(null,n.shortcuts||[]),M=null,N=()=>n.loadRecentSessionOnMount?(M||=k.loadRecentSession({skipLoadSessions:!0}).finally(()=>{M=null}),M):Promise.resolve(),P=async()=>{await y(`init`,async()=>{await D(),await N()})},F={appendTo:e=>{let t=e.closest(`.draggable-container-content`);return console.log(`[ai-blueking] appendTo called, ref:`,e),console.log(`[ai-blueking] appendTo closest result:`,t),t??document.body}},I=(0,t.computed)(()=>s.isCompressed.value),L=(0,t.computed)(()=>T.value),R=(0,t.computed)(()=>O.message.list.value.length===0),ee=(0,t.computed)(()=>n.resources?.length?n.resources:w.value?.resources??[]),z=(0,t.computed)(()=>n.prompts?.length?n.prompts:w.value?.conversationSettings?.predefinedQuestions??[]),B=(0,t.computed)(()=>(w.value?.relatedSkills??[]).map(e=>({skill_name:e.skill_name,skill_code:e.skill_code,description:e.description,icon:e.icon})));(0,t.watch)(()=>C.value,e=>{e&&(g(),_({apiName:`init`,error:e,source:`http`}))});let V=e=>{e.conversationSettings?.commands&&j.setAgentShortcuts(e.conversationSettings.commands)},te=async()=>{try{await O.agent.getAgentInfo();let e=w.value;return e&&V(e),e}catch(e){return _({apiName:`getAgentInfo`,error:e,source:`http`}),null}};(0,t.watch)(()=>S.value,async e=>{if(e&&w.value&&(V(w.value),w.value.conversationSettings&&d(`session-initialized`,{openingRemark:w.value.conversationSettings.openingRemark||``,predefinedQuestions:w.value.conversationSettings.predefinedQuestions||[]}),n.loadRecentSessionOnMount))try{await N()}catch(e){console.error(`[AIBlueking] Failed to load recent session:`,e)}},{immediate:!0}),(0,t.watch)(()=>n.shortcuts,e=>{j.setShortcuts(e||[])},{immediate:!0});let ne=e=>{zHt(e)&&(e.preventDefault(),l.value?s.hidePanel():s.showPanel())};return(0,t.onMounted)(async()=>{i.value&&s.setContainerRef(i.value),window.addEventListener(`keydown`,ne)}),(0,t.onBeforeUnmount)(()=>{g(),window.removeEventListener(`keydown`,ne),s.destroy()}),{chatHelper:O,componentManager:s,sessionBusinessManager:k,shareBusinessManager:A,shortcutManager:j,forwarders:f,forwardToManager:d,chatBotRef:a,draggableContainerRef:i,panelVisible:l,nimbusMinimized:u,normalizedUrl:o,agentInfo:w,agentName:L,currentSession:E,isCompressed:I,isWelcomeState:R,messageToolsTippyOptions:F,agentResources:ee,agentPrompts:z,agentSkills:B,handleError:b,reportSdkError:_,ensureSessionReady:P,updateAgentInfo:te}}function JUt(e){let{shortcutManager:n,chatBotRef:r,forwardToManager:i,show:a,props:o}=e,s=(0,t.ref)(!1),l=(0,t.ref)(``);return{aiSelectionVisible:s,selectedText:l,filteredPopupShortcuts:(0,t.computed)(()=>{let e=n.effectiveShortcuts.value;return typeof o.shortcutFilter==`function`&&l.value?e.filter(e=>o.shortcutFilter?.(e,l.value)):e}),handleSelectionChange:e=>{l.value=e},handleAiSelectionShortcut:async(e,t)=>{s.value=!1,await a(),r.value&&(e.components?.length?r.value.selectShortcut(e,t):(r.value.selectShortcut(e),r.value.setCiteText(t),r.value.focusInput())),i(`shortcut-click`,{shortcut:e,source:`popup`})}}}function YUt(e,n=!1){let r=window.innerHeight-48-40,i=window.innerWidth-48-16,a=(0,t.ref)(i),o=(0,t.ref)(r),s=(0,t.ref)(0),l=(0,t.ref)(n),u=(0,t.ref)(!1),d=(0,t.ref)(!1),f=0,p=e=>{e?a.value=window.innerWidth-12:a.value=i},m=(e,t)=>{o.value=t,s.value=t-r},h=()=>{(0,t.nextTick)(()=>{o.value=window.innerHeight-48-40+s.value,l.value?a.value=window.innerWidth-12:a.value=window.innerWidth-48-16})};return(0,t.onMounted)(()=>{window.addEventListener(`resize`,h),h()}),(0,t.onUnmounted)(()=>{window.removeEventListener(`resize`,h)}),{nimbusWidth:48,nimbusHeight:48,nimbusLeft:a,nimbusTop:o,isMinimize:l,isHovering:u,isDragging:d,handleNimbusDragging:m,handleNimbusMinimize:p,handleClick:()=>{if(d.value){d.value=!1;return}e(`click`)},handleMinimize:()=>{l.value=!l.value,e(`minimize`,l.value),l.value?a.value=window.innerWidth-12:a.value=window.innerWidth-60},handleDragging:(e,t)=>{a.value=e,o.value=t},handleMouseEnter:()=>{u.value=!0},handleMouseLeave:()=>{u.value=!1},handleMouseDown:()=>{f=Date.now(),d.value=!1},handleMouseUp:()=>{Date.now()-f>200&&(d.value=!0)}}}var XUt=560;function ZUt(e){let{componentManager:t,chatBotRef:n,forwarders:r,forwardToManager:i,beforeNimbusClick:a,ensureSessionReady:o}=e,s=async e=>{t.showPanel(e),o&&await o(),e&&n.value&&await n.value.switchSession(e)},l=async e=>{await s(e)},u=()=>{t.hidePanel()};return{show:s,handleShow:l,hide:u,handleClose:()=>{u()},handleNimbusClick:async()=>{if(a&&await a()===!1){t.emit(`nimbus-click`,{});return}t.handleNimbusClick()},handleDragging:e=>{t.handleDragging(e)},handleResizing:e=>{t.handleResizing(e)},handleDragStop:e=>{t.handleDragStop(e)},handleResizeStop:e=>{t.handleResizeStop(e)},handleToggleCompression:()=>{t.container.toggleCompression()},handleCompressionChange:e=>{t.setCompressed(e)},handleExecutionPanelChange:(e,n)=>{if(e)t.collapseSidePanel();else{let e=Math.max(XUt,n??0);t.expandForSidePanel(e)}},sendMessage:async e=>{n.value&&await n.value.sendMessage(e)},handleReceiveStart:()=>{r.receiveStart()},handleReceiveText:()=>{r.receiveText()},handleReceiveEnd:()=>{r.receiveEnd()},handleStop:()=>{r.stop()},stopGeneration:()=>{n.value&&n.value.stopGeneration()},updatePosition:(e,n)=>{t.container.updatePosition(e,n)},updateSize:(e,n)=>{t.container.updateSize(e,n)},updatePositionAndSize:(e,n,r,i)=>{t.container.updatePositionAndSize(e,n,r,i)},setCiteText:e=>{n.value&&n.value.setCiteText(e)},focusInput:()=>{n.value&&n.value.focusInput()},selectShortcut:(e,t)=>{n.value&&n.value.selectShortcut(e,t)},sendShortcut:(e,t)=>n.value?n.value.sendShortcut(e,t):Promise.resolve(),getChatHelper:()=>n.value?n.value.getChatHelper():null,handleShortcutClick:e=>{i(`shortcut-click`,e)}}}function QUt(e){let{chatHelper:n,sessionBusinessManager:r,chatBotRef:i,forwarders:a,reportSdkError:o,currentSession:s}=e,l=(0,t.ref)(``),u=(0,t.ref)(!0),d=(0,t.ref)(!1),f=(0,t.ref)(!1),p=()=>kHt(n.message.list.value);(0,t.watch)(()=>s.value,e=>{e&&(l.value=e.sessionName||``,d.value=(e.sessionContentCount??0)>0||p())},{immediate:!0}),(0,t.watch)(()=>n.message.list.value.length,()=>{d.value=p()});let m=async()=>{i.value?.exitShareMode(),a.newChat()},h=e=>{a.newChatCreated(e)},g=e=>{a.historyClick(e)},_=async e=>{try{i.value?.exitShareMode(),await r.switchSession(e)}catch(e){console.error(`[AIBlueking] Failed to switch history session:`,e),o({apiName:`session`,action:`historySwitch`,error:e,source:`business`})}},v=async e=>{try{await r.deleteSession(e)}catch(e){console.error(`[AIBlueking] Failed to delete history session:`,e),o({apiName:`session`,action:`historyDelete`,error:e,source:`business`})}},y=async(e,t)=>{try{await r.updateSessionName(e,t)}catch(e){console.error(`[AIBlueking] Failed to rename history session:`,e),o({apiName:`session`,action:`historyRename`,error:e,source:`business`})}},b=async()=>{let e=n.session.current?.value?.sessionCode;if(!e){console.error(`[AIBlueking] Cannot auto-generate name: no active session`);return}f.value=!0;try{await n.session.renameSession(e);let t=n.session.list.value.find(t=>t.sessionCode===e);t&&(l.value=t.sessionName||``)}catch(e){console.error(`[AIBlueking] Failed to auto-generate session name:`,e),o({apiName:`session`,action:`autoGenerateName`,error:e,source:`business`})}finally{f.value=!1}a.autoGenerateName()},x=()=>{a.helpClick()},S=async e=>{let t=n.session.current?.value;if(!t){console.error(`[AIBlueking] Cannot rename: no active session`);return}try{await n.session.updateSession({...t,sessionName:e}),l.value=e}catch(e){console.error(`[AIBlueking] Failed to rename session:`,e),o({apiName:`session`,action:`rename`,error:e,source:`business`})}a.rename(e,t.sessionCode)},C=(e,t)=>{s.value?.sessionCode===t&&(l.value=e),a.rename(e,t)},w=e=>{e&&(l.value=e.sessionName||``,d.value=(e.sessionContentCount??0)>0||p())},T=()=>i.value?.selectedLlmCode;return{sessionName:l,hasPermission:u,hasSessionContents:d,autoGenerateLoading:f,handleNewChat:m,handleNewChatCreated:h,handleHistoryClick:g,handleHistorySessionSwitch:_,handleHistorySessionDelete:v,handleHistorySessionRename:y,handleAutoGenerateName:b,handleHelpClick:x,handleRename:S,handleSessionRenamed:C,handleSessionSwitched:w,addNewSession:async e=>{e?await r.createSession({...e,model:e.model??T()}):await r.createNewSession({model:T()})},switchToSession:async e=>{i.value&&await i.value.switchSession(e)},updateSessionName:async(e,t)=>{try{await r.updateSessionName(e,t),l.value=t}catch(e){console.error(`[AIBlueking] Failed to update session name:`,e),o({apiName:`session`,action:`updateSessionName`,error:e,source:`business`})}}}}function $Ut(e){let{shareBusinessManager:n,chatBotRef:r,emit:i,forwarders:a,reportSdkError:o}=e,s=(0,t.ref)(!1);return{isShareLoading:s,handleShare:()=>{r.value?.enterShareMode(),a.share()},handleCancelShare:()=>{r.value?.exitShareMode()},handleConfirmShare:async(e,t)=>{if(!zUt(t)){r.value?.exitShareMode(),i(`confirm-share`,e,t);return}s.value=!0;try{let{shareUrl:o,userMessageIds:s}=await n.shareMessages(e);await FHt(o),nc({message:R9(`分享链接已复制到剪贴板`),theme:`success`}),r.value?.exitShareMode(),a.shareMessages(s),i(`confirm-share`,e,t)}catch(e){console.error(`[AIBlueking] Failed to share messages:`,e),o({apiName:`share`,action:`confirmShare`,error:e,source:`business`})}finally{s.value=!1}}}}function eWt(e={}){let n=(0,t.ref)([]),r=(t,r,i={})=>{try{let a=typeof t==`string`?document.querySelector(t):t;if(!a)return console.warn(`Tooltip target not found: ${t}`),null;let o=uu(a,{content:r,placement:`top`,arrow:!0,delay:[300,0],theme:`ai-blueking-tooltip`,...e,...i});return n.value.push(o),o}catch(e){return console.error(`Failed to create tooltip:`,e),null}},i=(e,t,n={})=>{let i=document.querySelectorAll(e),a=[];return i.forEach(e=>{let i=r(e,t,n);i&&a.push(i)}),a},a=e=>{let t=[];return e.forEach(({element:e,content:n,options:i})=>{let a=r(e,n,i);a&&t.push(a)}),t},o=()=>{n.value.forEach(e=>{e.destroy()}),n.value=[]};return(0,t.onBeforeUnmount)(()=>{o()}),{instances:n,createTooltip:r,createTooltipsForSelector:i,createMultipleTooltips:a,destroyAll:o,updateContent:(e,t)=>{e.setContent(t)},destroyInstance:e=>{e.destroy()}}}var tWt={url:``,title:``,extCls:``,hideNimbus:!1,hideHeader:!1,enablePopup:!0,draggable:!0,enableChatSession:!0,enableModelSelect:!0,renderMode:G8.Chat,defaultWidth:400,defaultHeight:void 0,defaultTop:0,defaultLeft:void 0,maxWidth:1e3,miniPadding:0,nimbusSize:`normal`,defaultMinimize:!1,shortcuts:()=>[],shortcutLimit:3,shortcutFilter:void 0,hideDefaultTrigger:!1,requestOptions:()=>({}),teleportTo:`body`,placeholder:void 0,helloText:R9(`你好,我是小鲸`),useAgentName:!1,disabledInput:!1,showHistoryIcon:!0,showNewChatIcon:!0,showCompressionIcon:!0,showMoreIcon:!0,initialSessionCode:``,autoSwitchToInitialSession:!1,alwaysCreateNewSession:!1,loadRecentSessionOnMount:!0,prompts:()=>[],dropdownMenuConfig:()=>({showRename:!0,showAutoGenerate:!0,showShare:!0}),defaultChatInputPosition:void 0,errorToast:!0,ignoreErrors:()=>[]},nWt=class extends w9{eventEmitter;constructor(e={}){super({onStart:e.onStart,onMessage:e.onMessage,onDone:e.onDone,onError:e.onError}),this.eventEmitter=e.eventEmitter}handleRunErrorEvent(e){super.handleRunErrorEvent(e),this.eventEmitter?.emit(`run-error`,{event:e})}handleTextMessageChunkEvent(e){super.handleTextMessageChunkEvent(e),this.eventEmitter?.emit(`text-chunk`,{event:e})}handleThinkingEndEvent(e){super.handleThinkingEndEvent(e),this.eventEmitter?.emit(`thinking-end`,{event:e})}handleThinkingStartEvent(e){super.handleThinkingStartEvent(e),this.eventEmitter?.emit(`thinking-start`,{event:e})}handleToolCallEndEvent(e){super.handleToolCallEndEvent(e),this.eventEmitter?.emit(`tool-call-end`,{event:e})}handleToolCallStartEvent(e){super.handleToolCallStartEvent(e),this.eventEmitter?.emit(`tool-call-start`,{event:e})}};function rWt(e={}){let{eventEmitter:t,onStart:n,onMessage:r,onDone:i,onError:a,onTextChunk:o}=e;return new w9({onStart:()=>{t?.emit(`receive-start`,{}),n?.()},onMessage:e=>{t?.emit(`receive-message`,{event:e}),e.type===`TextMessageChunk`&&o&&o(e),r?.(e)},onDone:()=>{t?.emit(`receive-end`,{}),i?.()},onError:e=>{t?.emit(`receive-error`,{error:e}),a?.(e)}})}function iWt(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function U9(e,t,n,r=1){let[i,a]=typeof r==`number`?[r,r]:r;return[Math.round(t/i/e[0])*e[0],Math.round(n/a/e[1])*e[1]]}function W9(e,t,n){return e-t-n}function G9(e,t,n){return e-t-n}function K9(e,t,n){return t!==null&&e<t?t:n!==null&&n<e?n:e}function aWt(e,t,n){let r=e,i=[`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`].find(e=>iWt(r[e]));if(!iWt(r[i]))return!1;do{if(r[i](t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function oWt(e){let t=window.getComputedStyle(e);return[parseFloat(t.getPropertyValue(`width`),10),parseFloat(t.getPropertyValue(`height`),10)]}function q9(e,t,n){e&&(e.attachEvent?e.attachEvent(`on`+t,n):e.addEventListener?e.addEventListener(t,n,!0):e[`on`+t]=n)}function J9(e,t,n){e&&(e.detachEvent?e.detachEvent(`on`+t,n):e.removeEventListener?e.removeEventListener(t,n,!0):e[`on`+t]=null)}var sWt=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},Y9={mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`},touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`}},cWt={userSelect:`none`,MozUserSelect:`none`,WebkitUserSelect:`none`,MsUserSelect:`none`},lWt={userSelect:`auto`,MozUserSelect:`auto`,WebkitUserSelect:`auto`,MsUserSelect:`auto`},X9=Y9.mouse,uWt={replace:!0,name:`vue-draggable-resizable`,props:{className:{type:String,default:`vdr`},classNameDraggable:{type:String,default:`draggable`},classNameResizable:{type:String,default:`resizable`},classNameDragging:{type:String,default:`dragging`},classNameResizing:{type:String,default:`resizing`},classNameActive:{type:String,default:`active`},classNameHandle:{type:String,default:`handle`},disableUserSelect:{type:Boolean,default:!0},enableNativeDrag:{type:Boolean,default:!1},preventDeactivation:{type:Boolean,default:!1},active:{type:Boolean,default:!1},draggable:{type:Boolean,default:!0},resizable:{type:Boolean,default:!0},lockAspectRatio:{type:Boolean,default:!1},w:{type:[Number,String],default:200,validator:e=>typeof e==`number`?e>0:e===`auto`},h:{type:[Number,String],default:200,validator:e=>typeof e==`number`?e>0:e===`auto`},minWidth:{type:Number,default:0,validator:e=>e>=0},minHeight:{type:Number,default:0,validator:e=>e>=0},maxWidth:{type:Number,default:null,validator:e=>e>=0},maxHeight:{type:Number,default:null,validator:e=>e>=0},x:{type:Number,default:0},y:{type:Number,default:0},z:{type:[String,Number],default:`auto`,validator:e=>typeof e==`string`?e===`auto`:e>=0},handles:{type:Array,default:()=>[`tl`,`tm`,`tr`,`mr`,`br`,`bm`,`bl`,`ml`],validator:e=>{let t=new Set([`tl`,`tm`,`tr`,`mr`,`br`,`bm`,`bl`,`ml`]);return new Set(e.filter(e=>t.has(e))).size===e.length}},dragHandle:{type:String,default:null},dragCancel:{type:String,default:null},axis:{type:String,default:`both`,validator:e=>[`x`,`y`,`both`].includes(e)},grid:{type:Array,default:()=>[1,1]},parent:{type:Boolean,default:!1},scale:{type:[Number,Array],default:1,validator:e=>typeof e==`number`?e>0:e.length===2&&e[0]>0&&e[1]>0},onDragStart:{type:Function,default:()=>!0},onDrag:{type:Function,default:()=>!0},onResizeStart:{type:Function,default:()=>!0},onResize:{type:Function,default:()=>!0}},data:function(){return{left:this.x,top:this.y,right:null,bottom:null,width:null,height:null,widthTouched:!1,heightTouched:!1,aspectFactor:null,parentWidth:null,parentHeight:null,handle:null,enabled:this.active,resizing:!1,dragging:!1,dragEnable:!1,resizeEnable:!1,zIndex:this.z}},created:function(){this.maxWidth&&this.minWidth>this.maxWidth&&console.warn(`[Vdr warn]: Invalid prop: minWidth cannot be greater than maxWidth`),this.maxHeight&&this.minHeight>this.maxHeight&&console.warn(`[Vdr warn]: Invalid prop: minHeight cannot be greater than maxHeight`),this.resetBoundsAndMouseState()},mounted:function(){this.enableNativeDrag||(this.$el.ondragstart=()=>!1);let[e,t]=this.getParentSize();this.parentWidth=e,this.parentHeight=t;let[n,r]=oWt(this.$el);this.aspectFactor=(this.w===`auto`?n:this.w)/(this.h===`auto`?r:this.h),this.width=this.w===`auto`?n:this.w,this.height=this.h===`auto`?r:this.h,this.right=this.parentWidth-this.width-this.left,this.bottom=this.parentHeight-this.height-this.top,this.active&&this.$emit(`activated`),q9(document.documentElement,`mousedown`,this.deselect),q9(document.documentElement,`touchend touchcancel`,this.deselect),q9(window,`resize`,this.checkParentSize)},beforeUnmount:function(){J9(document.documentElement,`mousedown`,this.deselect),J9(document.documentElement,`touchstart`,this.handleUp),J9(document.documentElement,`mousemove`,this.move),J9(document.documentElement,`touchmove`,this.move),J9(document.documentElement,`mouseup`,this.handleUp),J9(document.documentElement,`touchend touchcancel`,this.deselect),J9(window,`resize`,this.checkParentSize)},methods:{resetBoundsAndMouseState(){this.mouseClickPosition={mouseX:0,mouseY:0,x:0,y:0,w:0,h:0},this.bounds={minLeft:null,maxLeft:null,minRight:null,maxRight:null,minTop:null,maxTop:null,minBottom:null,maxBottom:null}},checkParentSize(){if(this.parent){let[e,t]=this.getParentSize();this.parentWidth=e,this.parentHeight=t,this.right=this.parentWidth-this.width-this.left,this.bottom=this.parentHeight-this.height-this.top}},getParentSize(){if(this.parent){let e=window.getComputedStyle(this.$el.parentNode,null);return[parseInt(e.getPropertyValue(`width`),10),parseInt(e.getPropertyValue(`height`),10)]}return[null,null]},elementTouchDown(e){X9=Y9.touch,this.elementDown(e)},elementMouseDown(e){X9=Y9.mouse,this.elementDown(e)},elementDown(e){if(e instanceof MouseEvent&&e.button!==0)return;let t=e.target||e.srcElement;if(this.$el.contains(t)){if(this.onDragStart(e)===!1)return;if(this.dragHandle&&!aWt(t,this.dragHandle,this.$el)||this.dragCancel&&aWt(t,this.dragCancel,this.$el)){this.dragging=!1;return}this.enabled||(this.enabled=!0,this.$emit(`activated`),this.$emit(`update:active`,!0)),this.draggable&&(this.dragEnable=!0),this.mouseClickPosition.mouseX=e.touches?e.touches[0].pageX:e.pageX,this.mouseClickPosition.mouseY=e.touches?e.touches[0].pageY:e.pageY,this.mouseClickPosition.left=this.left,this.mouseClickPosition.right=this.right,this.mouseClickPosition.top=this.top,this.mouseClickPosition.bottom=this.bottom,this.parent&&(this.bounds=this.calcDragLimits()),q9(document.documentElement,X9.move,this.move),q9(document.documentElement,X9.stop,this.handleUp)}},calcDragLimits(){return{minLeft:this.left%this.grid[0],maxLeft:Math.floor((this.parentWidth-this.width-this.left)/this.grid[0])*this.grid[0]+this.left,minRight:this.right%this.grid[0],maxRight:Math.floor((this.parentWidth-this.width-this.right)/this.grid[0])*this.grid[0]+this.right,minTop:this.top%this.grid[1],maxTop:Math.floor((this.parentHeight-this.height-this.top)/this.grid[1])*this.grid[1]+this.top,minBottom:this.bottom%this.grid[1],maxBottom:Math.floor((this.parentHeight-this.height-this.bottom)/this.grid[1])*this.grid[1]+this.bottom}},deselect(e){let t=e.target||e.srcElement,n=RegExp(this.className+`-([trmbl]{2})`,``);!this.$el.contains(t)&&!n.test(t.className)&&(this.enabled&&!this.preventDeactivation&&(this.enabled=!1,this.$emit(`deactivated`),this.$emit(`update:active`,!1)),J9(document.documentElement,X9.move,this.handleResize)),this.resetBoundsAndMouseState()},handleTouchDown(e,t){X9=Y9.touch,this.handleDown(e,t)},handleDown(e,t){t instanceof MouseEvent&&t.which!==1||this.onResizeStart(e,t)!==!1&&(t.stopPropagation&&t.stopPropagation(),this.lockAspectRatio&&!e.includes(`m`)?this.handle=`m`+e.substring(1):this.handle=e,this.resizeEnable=!0,this.mouseClickPosition.mouseX=t.touches?t.touches[0].pageX:t.pageX,this.mouseClickPosition.mouseY=t.touches?t.touches[0].pageY:t.pageY,this.mouseClickPosition.left=this.left,this.mouseClickPosition.right=this.right,this.mouseClickPosition.top=this.top,this.mouseClickPosition.bottom=this.bottom,this.bounds=this.calcResizeLimits(),q9(document.documentElement,X9.move,this.handleResize),q9(document.documentElement,X9.stop,this.handleUp))},calcResizeLimits(){let e=this.minW,t=this.minH,n=this.maxW,r=this.maxH,i=this.aspectFactor,[a,o]=this.grid,s=this.width,l=this.height,u=this.left,d=this.top,f=this.right,p=this.bottom;this.lockAspectRatio&&(e/t>i?t=e/i:e=i*t,n&&r?(n=Math.min(n,i*r),r=Math.min(r,n/i)):n?r=n/i:r&&(n=i*r)),n-=n%a,r-=r%o;let m={minLeft:null,maxLeft:null,minTop:null,maxTop:null,minRight:null,maxRight:null,minBottom:null,maxBottom:null};return this.parent?(m.minLeft=u%a,m.maxLeft=u+Math.floor((s-e)/a)*a,m.minTop=d%o,m.maxTop=d+Math.floor((l-t)/o)*o,m.minRight=f%a,m.maxRight=f+Math.floor((s-e)/a)*a,m.minBottom=p%o,m.maxBottom=p+Math.floor((l-t)/o)*o,n&&(m.minLeft=Math.max(m.minLeft,this.parentWidth-f-n),m.minRight=Math.max(m.minRight,this.parentWidth-u-n)),r&&(m.minTop=Math.max(m.minTop,this.parentHeight-p-r),m.minBottom=Math.max(m.minBottom,this.parentHeight-d-r)),this.lockAspectRatio&&(m.minLeft=Math.max(m.minLeft,u-d*i),m.minTop=Math.max(m.minTop,d-u/i),m.minRight=Math.max(m.minRight,f-p*i),m.minBottom=Math.max(m.minBottom,p-f/i))):(m.minLeft=null,m.maxLeft=u+Math.floor((s-e)/a)*a,m.minTop=null,m.maxTop=d+Math.floor((l-t)/o)*o,m.minRight=null,m.maxRight=f+Math.floor((s-e)/a)*a,m.minBottom=null,m.maxBottom=p+Math.floor((l-t)/o)*o,n&&(m.minLeft=-(f+n),m.minRight=-(u+n)),r&&(m.minTop=-(p+r),m.minBottom=-(d+r)),this.lockAspectRatio&&n&&r&&(m.minLeft=Math.min(m.minLeft,-(f+n)),m.minTop=Math.min(m.minTop,-(r+p)),m.minRight=Math.min(m.minRight,-u-n),m.minBottom=Math.min(m.minBottom,-d-r))),m},move(e){this.resizing?this.handleResize(e):this.dragEnable&&this.handleDrag(e)},handleDrag(e){let t=this.axis,n=this.grid,r=this.bounds,i=this.mouseClickPosition,[a,o]=U9(n,t&&t!==`y`?i.mouseX-(e.touches?e.touches[0].pageX:e.pageX):0,t&&t!==`x`?i.mouseY-(e.touches?e.touches[0].pageY:e.pageY):0,this.scale),s=K9(i.left-a,r.minLeft,r.maxLeft),l=K9(i.top-o,r.minTop,r.maxTop);if(this.onDrag(s,l)===!1)return;let u=K9(i.right+a,r.minRight,r.maxRight),d=K9(i.bottom+o,r.minBottom,r.maxBottom);this.left=s,this.top=l,this.right=u,this.bottom=d,this.$emit(`dragging`,this.left,this.top),this.dragging=!0},moveHorizontally(e){let[t,n]=U9(this.grid,e,this.top,1),r=K9(t,this.bounds.minLeft,this.bounds.maxLeft);this.left=r,this.right=this.parentWidth-this.width-r},moveVertically(e){let[t,n]=U9(this.grid,this.left,e,1),r=K9(n,this.bounds.minTop,this.bounds.maxTop);this.top=r,this.bottom=this.parentHeight-this.height-r},handleResize(e){let t=this.left,n=this.top,r=this.right,i=this.bottom,a=this.mouseClickPosition,o=this.aspectFactor,s=a.mouseX-(e.touches?e.touches[0].pageX:e.pageX),l=a.mouseY-(e.touches?e.touches[0].pageY:e.pageY);!this.widthTouched&&s&&(this.widthTouched=!0),!this.heightTouched&&l&&(this.heightTouched=!0);let[u,d]=U9(this.grid,s,l,this.scale);this.handle.includes(`b`)?(i=K9(a.bottom+d,this.bounds.minBottom,this.bounds.maxBottom),this.lockAspectRatio&&this.resizingOnY&&(r=this.right-(this.bottom-i)*o)):this.handle.includes(`t`)&&(n=K9(a.top-d,this.bounds.minTop,this.bounds.maxTop),this.lockAspectRatio&&this.resizingOnY&&(t=this.left-(this.top-n)*o)),this.handle.includes(`r`)?(r=K9(a.right+u,this.bounds.minRight,this.bounds.maxRight),this.lockAspectRatio&&this.resizingOnX&&(i=this.bottom-(this.right-r)/o)):this.handle.includes(`l`)&&(t=K9(a.left-u,this.bounds.minLeft,this.bounds.maxLeft),this.lockAspectRatio&&this.resizingOnX&&(n=this.top-(this.left-t)/o));let f=W9(this.parentWidth,t,r),p=G9(this.parentHeight,n,i);this.onResize(this.handle,t,n,f,p)!==!1&&(this.left=t,this.top=n,this.right=r,this.bottom=i,this.width=f,this.height=p,this.$emit(`resizing`,this.left,this.top,this.width,this.height),this.resizing=!0)},changeWidth(e){let[t,n]=U9(this.grid,e,0,1),r=K9(this.parentWidth-t-this.left,this.bounds.minRight,this.bounds.maxRight),i=this.bottom;this.lockAspectRatio&&(i=this.bottom-(this.right-r)/this.aspectFactor);let a=W9(this.parentWidth,this.left,r),o=G9(this.parentHeight,this.top,i);this.right=r,this.bottom=i,this.width=a,this.height=o},changeHeight(e){let[t,n]=U9(this.grid,0,e,1),r=K9(this.parentHeight-n-this.top,this.bounds.minBottom,this.bounds.maxBottom),i=this.right;this.lockAspectRatio&&(i=this.right-(this.bottom-r)*this.aspectFactor);let a=W9(this.parentWidth,this.left,i),o=G9(this.parentHeight,this.top,r);this.right=i,this.bottom=r,this.width=a,this.height=o},handleUp(e){this.handle=null,this.resetBoundsAndMouseState(),this.dragEnable=!1,this.resizeEnable=!1,this.resizing&&(this.resizing=!1,this.$emit(`resizeStop`,this.left,this.top,this.width,this.height)),this.dragging&&(this.dragging=!1,this.$emit(`dragStop`,this.left,this.top)),J9(document.documentElement,X9.move,this.handleResize)}},computed:{style(){return{transform:`translate(${this.left}px, ${this.top}px)`,width:this.computedWidth,height:this.computedHeight,zIndex:this.zIndex,...this.dragging&&this.disableUserSelect?cWt:lWt}},actualHandles(){return this.resizable?this.handles:[]},computedWidth(){return this.w===`auto`&&!this.widthTouched?`auto`:this.width+`px`},computedHeight(){return this.h===`auto`&&!this.heightTouched?`auto`:this.height+`px`},minW(){return this.minWidth},minH(){return this.minHeight},maxW(){return this.maxWidth},maxH(){return this.maxHeight},resizingOnX(){return!!this.handle&&(this.handle.includes(`l`)||this.handle.includes(`r`))},resizingOnY(){return!!this.handle&&(this.handle.includes(`t`)||this.handle.includes(`b`))},isCornerHandle(){return!!this.handle&&[`tl`,`tr`,`br`,`bl`].includes(this.handle)}},watch:{active(e){this.enabled=e,e?this.$emit(`activated`):this.$emit(`deactivated`)},z(e){(e>=0||e===`auto`)&&(this.zIndex=e)},x(e){this.resizing||this.dragging||(this.parent&&(this.bounds=this.calcDragLimits()),this.moveHorizontally(e))},y(e){this.resizing||this.dragging||(this.parent&&(this.bounds=this.calcDragLimits()),this.moveVertically(e))},lockAspectRatio(e){e?this.aspectFactor=this.width/this.height:this.aspectFactor=void 0},w(e){this.resizing||this.dragging||(this.parent&&(this.bounds=this.calcResizeLimits()),this.changeWidth(e))},h(e){this.resizing||this.dragging||(this.parent&&(this.bounds=this.calcResizeLimits()),this.changeHeight(e))}}},dWt=[`onMousedown`,`onTouchstart`];function fWt(e,n,r,i,a,o){return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,{style:(0,t.normalizeStyle)(o.style),class:(0,t.normalizeClass)([{[r.classNameActive]:e.enabled,[r.classNameDragging]:e.dragging,[r.classNameResizing]:e.resizing,[r.classNameDraggable]:r.draggable,[r.classNameResizable]:r.resizable},r.className]),onMousedown:n[0]||=(...e)=>o.elementMouseDown&&o.elementMouseDown(...e),onTouchstart:n[1]||=(...e)=>o.elementTouchDown&&o.elementTouchDown(...e)},[((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,null,(0,t.renderList)(o.actualHandles,n=>((0,t.openBlock)(),(0,t.createElementBlock)(`div`,{key:n,class:(0,t.normalizeClass)([r.classNameHandle,r.classNameHandle+`-`+n]),style:(0,t.normalizeStyle)({display:e.enabled?`block`:`none`}),onMousedown:(0,t.withModifiers)(e=>o.handleDown(n,e),[`stop`,`prevent`]),onTouchstart:(0,t.withModifiers)(e=>o.handleTouchDown(n,e),[`stop`,`prevent`])},[(0,t.renderSlot)(e.$slots,n)],46,dWt))),128)),(0,t.renderSlot)(e.$slots,`default`)],38)}var Z9=sWt(uWt,[[`render`,fWt]]);function Q9(e){Q9.installed||(Q9.installed=!0,e.component(`VueDraggableResizable`,Z9))}var pWt={install:Q9},$9=null;typeof window<`u`?$9=window.Vue:typeof global<`u`&&($9=global.Vue),$9&&$9.use(pWt);function mWt(e={},n){let r=e.initWidth||400,i=e.minWidth||400,a=e.minHeight||400,o=e.maxWidthPercent||40,s=e.compressedHeight||800,l=e.compressedPadding===void 0?0:e.compressedPadding,u=(0,t.ref)(e.defaultLeft===void 0?window.innerWidth-r:e.defaultLeft),d=(0,t.ref)(e.defaultTop===void 0?0:e.defaultTop),f=(0,t.ref)(e.defaultHeight===void 0?window.innerHeight-(e.defaultTop===void 0?0:e.defaultTop):e.defaultHeight),p=(0,t.ref)(r),m=(0,t.ref)(d.value),h=(0,t.ref)(u.value),g=(0,t.ref)(p.value),_=(0,t.ref)(f.value),v=(0,t.ref)(Math.max(window.innerWidth*(o/100),g.value)),y=(0,t.ref)(!1),b=(0,t.ref)(0),x=null,S=null,C=(0,t.ref)(!1),w=e=>{let t=window.innerWidth,n={...e};return n.width>t&&(n.width=t),n.x+n.width>t&&(n.x=t-n.width),n.x<0&&(n.x=0),n},T=()=>({x:h.value,y:m.value,width:g.value,height:_.value}),E=(e,t)=>{h.value=e,m.value=t,b.value=e-(window.innerWidth-g.value),n?.onDragging?.(T())},D=(e,t,r,i)=>{h.value=e,m.value=t,g.value=Math.min(r,v.value),_.value=i,n?.onResizing?.(T())},O=(e,t)=>{h.value=e,m.value=t,b.value=e-(window.innerWidth-g.value),C.value&&(S=T()),n?.onDragStop?.(T())},k=(e,t,r,i)=>{h.value=e,m.value=t,g.value=Math.min(r,v.value),_.value=i,C.value&&(S=T()),n?.onResizeStop?.(T())},A=()=>{v.value=Math.max(window.innerWidth*(o/100),g.value),(0,t.nextTick)(()=>{if(y.value)h.value=window.innerWidth-g.value-l,m.value=window.innerHeight-s-l;else{let e=window.innerWidth-g.value-b.value;h.value=Math.max(0,e),setTimeout(()=>{_.value=window.innerHeight-m.value},0)}g.value>v.value&&(g.value=v.value)})},j=()=>{y.value?(m.value=d.value,(0,t.nextTick)(()=>{_.value=f.value,h.value=u.value,g.value=p.value})):(m.value=window.innerHeight-s-l,h.value=u.value-l,g.value=r,_.value=s),y.value=!y.value},M=(e,t)=>{h.value=e,m.value=t,b.value=e-(window.innerWidth-g.value)},N=(e,t)=>{g.value=Math.max(i,Math.min(e,v.value)),_.value=Math.max(a,t)};return(0,t.onMounted)(()=>{window.addEventListener(`resize`,A)}),(0,t.onBeforeUnmount)(()=>{window.removeEventListener(`resize`,A)}),{minWidth:i,minHeight:a,maxWidth:v,top:m,left:h,width:g,height:_,isCompressed:y,isSidePanelExpanded:C,handleDragging:E,handleResizing:D,handleDragStop:O,handleResizeStop:k,toggleCompression:j,updatePosition:M,updateSize:N,updatePositionAndSize:(e,t,n,r)=>{M(e,t),N(n,r)},expandForSidePanel:e=>{if(C.value)return;let n=T();x={...n},C.value=!0;let r=n.x+n.width,i=S?.width??n.width+e,a=w({x:r-i,y:n.y,width:i,height:n.height});M(a.x,a.y),(0,t.nextTick)(()=>{N(a.width,a.height)})},collapseSidePanel:()=>{if(!C.value)return;let e=T();S={...e},C.value=!1;let n=e.x+e.width,r=x?.width??e.width,i=w({x:n-r,y:e.y,width:r,height:e.height});N(i.width,i.height),(0,t.nextTick)(()=>{M(i.x,i.y)})}}}var hWt={class:`draggable-container-content`},gWt=z9((0,t.defineComponent)({__name:`draggable-container`,props:{className:{default:``},compressedHeight:{default:800},compressedPadding:{default:0},defaultHeight:{default:void 0},defaultWidth:{default:400},defaultX:{default:void 0},defaultY:{default:0},draggable:{type:Boolean,default:!0},dragHandle:{default:`.drag-handle`},maxWidth:{default:void 0},maxWidthPercent:{default:80},minHeight:{default:400},minWidth:{default:400},resizable:{type:Boolean,default:!0},teleportTo:{default:`body`},visible:{type:Boolean,default:!1}},emits:[`dragging`,`resizing`,`drag-stop`,`resize-stop`,`compression-change`],setup(e,{expose:n,emit:r}){let i=e,a=r,o=(0,t.ref)(!1),{minWidth:s,minHeight:l,maxWidth:u,top:d,left:f,width:p,height:m,isCompressed:h,isSidePanelExpanded:g,handleDragging:_,handleResizing:v,handleDragStop:y,handleResizeStop:b,toggleCompression:x,updatePosition:S,updateSize:C,updatePositionAndSize:w,expandForSidePanel:T,collapseSidePanel:E}=mWt({initWidth:i.defaultWidth,minWidth:i.minWidth,minHeight:i.minHeight,maxWidthPercent:i.maxWidthPercent,compressedHeight:i.compressedHeight,defaultHeight:i.defaultHeight,defaultTop:i.defaultY,defaultLeft:i.defaultX,compressedPadding:i.compressedPadding},{onDragStop:e=>a(`drag-stop`,e),onResizeStop:e=>a(`resize-stop`,e),onDragging:e=>a(`dragging`,e),onResizing:e=>a(`resizing`,e)}),D=(0,t.computed)(()=>({"--draggable-max-width":typeof i.maxWidth==`number`?`${i.maxWidth}px`:i.maxWidth??`${u.value}px`})),O=(0,t.computed)(()=>({x:f.value,y:d.value,width:p.value,height:m.value})),k=()=>{document.querySelectorAll(`iframe`).forEach(e=>{e.style.pointerEvents=`none`})},A=()=>{document.querySelectorAll(`iframe`).forEach(e=>{e.style.pointerEvents=``})},j=(e,t)=>{o.value||(o.value=!0,k()),_(e,t)},M=(e,t,n,r)=>{o.value||(o.value=!0,k()),v(e,t,n,r)},N=(e,t)=>{y(e,t),o.value=!1,A()},P=(e,t,n,r)=>{b(e,t,n,r),o.value=!1,A()};return(0,t.watch)(h,e=>{a(`compression-change`,e)}),n({updatePosition:S,updateSize:C,updatePositionAndSize:w,toggleCompression:x,expandForSidePanel:T,collapseSidePanel:E,positionAndSize:O,isCompressed:h,isSidePanelExpanded:g}),(e,n)=>(0,t.withDirectives)(((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Z9),{ref:`draggableRef`,active:i.visible,class:(0,t.normalizeClass)([`draggable-container-wrapper`,i.className]),"class-name":`draggable-container-inner`,"drag-handle":i.dragHandle,draggable:i.draggable,h:(0,t.unref)(m),"max-width":(0,t.unref)(u),"min-height":(0,t.unref)(l),"min-width":(0,t.unref)(s),parent:!0,"prevent-deactivation":!0,resizable:i.resizable,style:(0,t.normalizeStyle)(D.value),w:(0,t.unref)(p),x:(0,t.unref)(f),y:(0,t.unref)(d),onDragStop:N,onDragging:j,onResizeStop:P,onResizing:M},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,hWt,[(0,t.renderSlot)(e.$slots,`default`,{},void 0,!0)])]),_:3},8,[`active`,`class`,`drag-handle`,`draggable`,`h`,`max-width`,`min-height`,`min-width`,`resizable`,`style`,`w`,`x`,`y`])),[[t.vShow,i.visible]])}}),[[`__scopeId`,`data-v-1118456b`]]),_Wt={class:`nimbus-bkai-wrapper`},vWt=[`width`,`height`,`src`],yWt=z9((0,t.defineComponent)({name:`NimbusButton`,__name:`nimbus`,props:{isPanelShow:{type:Boolean},isMinimize:{type:Boolean},size:{default:`normal`}},emits:[`click`,`minimize`,`update:isMinimize`],setup(e,{emit:n}){(0,t.useCssVars)(e=>({v05a8b16e:`${o.value.container}px`,v4e1cf4ca:`${o.value.wrapper}px`,v5ab0c513:`${o.value.mini.right}px`,v40c13a80:`${o.value.mini.size}px`,v0d35a9ef:`${o.value.mini.fontSize}px`}));let r=e,i=n,a={small:{container:40,wrapper:32,img:24,mini:{size:14,fontSize:10,right:-4}},normal:{container:48,wrapper:40,img:32,mini:{size:16,fontSize:12,right:-6}},large:{container:56,wrapper:48,img:40,mini:{size:18,fontSize:14,right:-6}}},o=(0,t.computed)(()=>a[r.size]),s=(0,t.ref)(null),l=(0,t.ref)(null),{nimbusLeft:u,nimbusTop:d,isMinimize:f,handleClick:p,handleMinimize:m,handleDragging:h,handleMouseEnter:g,handleMouseLeave:_,handleMouseDown:v,handleMouseUp:y}=YUt(i,r.isMinimize);(0,t.watch)(f,e=>{i(`update:isMinimize`,e)});let b=(0,t.computed)(()=>f.value?R9(`恢复默认大小`):R9(`最小化,将缩成锚点`)),{createTooltip:x,destroyAll:S}=eWt({theme:`ai-blueking`,delay:[0,0]}),C=()=>{(0,t.nextTick)(()=>{w()})},w=()=>{S(),s.value&&!f.value&&x(s.value,LHt(),{placement:`left`}),l.value&&x(l.value,b.value,{placement:`top`})};return(0,t.watch)(()=>f.value,()=>{(0,t.nextTick)(()=>{w()})}),(0,t.onMounted)(()=>{(0,t.nextTick)(()=>{w()}),window.addEventListener(`resize`,C)}),(0,t.onBeforeUnmount)(()=>{window.removeEventListener(`resize`,C)}),(n,r)=>((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Z9),{active:!e.isPanelShow,axis:`y`,draggable:!0,h:o.value.container,parent:!0,"prevent-deactivation":!0,resizable:!1,w:o.value.container,x:(0,t.unref)(u),y:(0,t.unref)(d),onDragging:(0,t.unref)(h)},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,{ref_key:`nimbusContainerRef`,ref:s,class:(0,t.normalizeClass)([`nimbus-container`,{"is-minimize":(0,t.unref)(f)}]),onClick:r[1]||=(...e)=>(0,t.unref)(p)&&(0,t.unref)(p)(...e),onMousedown:r[2]||=(...e)=>(0,t.unref)(v)&&(0,t.unref)(v)(...e),onMouseenter:r[3]||=(...e)=>(0,t.unref)(g)&&(0,t.unref)(g)(...e),onMouseleave:r[4]||=(...e)=>(0,t.unref)(_)&&(0,t.unref)(_)(...e),onMouseup:r[5]||=(...e)=>(0,t.unref)(y)&&(0,t.unref)(y)(...e)},[(0,t.createElementVNode)(`div`,_Wt,[(0,t.createElementVNode)(`img`,{width:o.value.img,height:o.value.img,src:(0,t.unref)(FVt),alt:`nimbus`},null,8,vWt)]),(0,t.createElementVNode)(`i`,{ref_key:`minimizeButtonRef`,ref:l,class:(0,t.normalizeClass)([`nimbus-mini bkai-icon`,(0,t.unref)(f)?`bkai-yinyong`:`bkai-minus-line`]),onClick:r[0]||=(0,t.withModifiers)((...e)=>(0,t.unref)(m)&&(0,t.unref)(m)(...e),[`stop`])},null,2)],34)]),_:1},8,[`active`,`h`,`w`,`x`,`y`,`onDragging`]))}}),[[`__scopeId`,`data-v-26b6f3ea`]]),bWt=z9((0,t.defineComponent)({inheritAttrs:!1,__name:`ai-blueking`,props:(0,t.mergeDefaults)({alwaysCreateNewSession:{type:Boolean},autoSwitchToInitialSession:{type:Boolean},defaultChatInputPosition:{},defaultHeight:{},defaultLeft:{},defaultMinimize:{type:Boolean},defaultTop:{},defaultWidth:{},disabledInput:{type:Boolean},draggable:{type:Boolean},dropdownMenuConfig:{},enableChatSession:{type:Boolean},enableModelSelect:{type:Boolean},models:{},enablePopup:{type:Boolean},errorToast:{type:Boolean},executionTabVisible:{type:Boolean},extCls:{},getSideRenderComponent:{type:Function},getSideTabRenderComponent:{type:Function},helloText:{},messageTools:{},updateTools:{},hideDefaultTrigger:{type:Boolean},hideHeader:{type:Boolean},hideNimbus:{type:Boolean},ignoreErrors:{},initialSessionCode:{},loadRecentSessionOnMount:{type:Boolean},maxWidth:{},miniPadding:{},nimbusSize:{},onCustomTabChange:{type:Function},placeholder:{},prompts:{},renderMode:{},requestOptions:{},resources:{},shortcutLimit:{},shortcuts:{},showCompressionIcon:{type:Boolean},showHistoryIcon:{type:Boolean},showMoreIcon:{type:Boolean},showNewChatIcon:{type:Boolean},teleportTo:{},title:{},url:{},useAgentName:{type:Boolean},beforeNimbusClick:{type:Function},shortcutFilter:{type:Function},resizeProps:{},size:{}},tWt),emits:[`show`,`close`,`dragging`,`resizing`,`drag-stop`,`resize-stop`,`send-message`,`receive-start`,`receive-text`,`receive-end`,`stop`,`shortcut-click`,`session-initialized`,`sdk-error`,`transfer-messages`,`share-messages`,`confirm-share`,`agent-action`,`new-chat`,`new-chat-created`,`history-click`,`auto-generate-name`,`help-click`,`rename`,`share`],setup(e,{expose:n,emit:r}){let i=e,a=r,o=(0,t.useAttrs)(),{chatHelper:s,componentManager:l,sessionBusinessManager:u,shareBusinessManager:d,shortcutManager:f,forwarders:p,forwardToManager:m,chatBotRef:h,draggableContainerRef:g,panelVisible:_,nimbusMinimized:v,normalizedUrl:y,agentName:b,currentSession:x,isCompressed:S,isWelcomeState:C,messageToolsTippyOptions:w,agentResources:T,agentPrompts:E,agentSkills:D,handleError:O,reportSdkError:k,ensureSessionReady:A,updateAgentInfo:j}=qUt({props:i,emit:a}),M=(0,t.computed)(()=>h.value?.selectedLlmCode),{show:N,hide:P,handleShow:F,handleClose:I,handleNimbusClick:L,handleDragging:R,handleResizing:ee,handleDragStop:z,handleResizeStop:B,handleToggleCompression:V,handleCompressionChange:te,handleExecutionPanelChange:ne,sendMessage:re,handleReceiveStart:ie,handleReceiveText:ae,handleReceiveEnd:H,handleStop:oe,stopGeneration:se,setCiteText:ce,focusInput:le,selectShortcut:ue,sendShortcut:de,getChatHelper:fe,updatePosition:pe,updateSize:me,updatePositionAndSize:he,handleShortcutClick:ge}=ZUt({componentManager:l,chatBotRef:h,forwarders:p,forwardToManager:m,beforeNimbusClick:i.beforeNimbusClick,ensureSessionReady:A}),{sessionName:_e,hasPermission:ve,hasSessionContents:ye,autoGenerateLoading:be,handleNewChat:xe,handleNewChatCreated:Se,handleHistoryClick:Ce,handleHistorySessionSwitch:we,handleHistorySessionDelete:Te,handleHistorySessionRename:Ee,handleAutoGenerateName:De,handleHelpClick:Oe,handleRename:ke,handleSessionRenamed:Ae,handleSessionSwitched:je,addNewSession:Me,switchToSession:Ne,updateSessionName:Pe}=QUt({chatHelper:s,sessionBusinessManager:u,chatBotRef:h,forwarders:p,reportSdkError:k,currentSession:x}),{isShareLoading:Fe,handleShare:Ie,handleCancelShare:Le,handleConfirmShare:Re}=$Ut({shareBusinessManager:d,chatBotRef:h,emit:(e,t,n)=>a(e,t,n),forwarders:p,reportSdkError:k}),{aiSelectionVisible:ze,filteredPopupShortcuts:Be,handleSelectionChange:Ve,handleAiSelectionShortcut:He}=JUt({shortcutManager:f,chatBotRef:h,forwardToManager:m,show:N,props:i}),Ue=e=>{ye.value=!0,p.sendMessage(e)};return n({show:N,handleShow:F,handleClose:I,hide:P,sendMessage:re,selectShortcut:ue,sendShortcut:de,getChatHelper:fe,stopGeneration:se,addNewSession:Me,switchToSession:Ne,updateSessionName:Pe,updatePosition:pe,updateSize:me,updatePositionAndSize:he,setCiteText:ce,focusInput:le,updateAgentInfo:j}),(e,n)=>((0,t.openBlock)(),(0,t.createBlock)(t.Teleport,{to:i.teleportTo},[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`ai-blueking-v2`,i.extCls,(0,t.unref)(o).class])},[(0,t.createCommentVNode)(` 可拖拽容器 `),(0,t.createVNode)((0,t.unref)(gWt),{ref_key:`draggableContainerRef`,ref:g,"compressed-padding":i.miniPadding,"default-height":i.defaultHeight,"default-width":i.defaultWidth,"default-x":i.defaultLeft,"default-y":i.defaultTop,"drag-handle":`.drag-handle`,draggable:i.draggable,"max-width":i.maxWidth,"max-width-percent":80,visible:(0,t.unref)(_),onCompressionChange:(0,t.unref)(te),onDragStop:(0,t.unref)(z),onDragging:(0,t.unref)(R),onResizeStop:(0,t.unref)(B),onResizing:(0,t.unref)(ee)},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`ai-blueking-panel`,{"has-messages":!(0,t.unref)(C)}])},[(0,t.createCommentVNode)(` 独立的 Header 组件 `),i.hideHeader?(0,t.createCommentVNode)(`v-if`,!0):((0,t.openBlock)(),(0,t.createBlock)(gUt,{key:0,"agent-name":(0,t.unref)(b),"chat-helper":(0,t.unref)(s),draggable:i.draggable,"dropdown-menu-config":i.dropdownMenuConfig,"enable-chat-session":i.enableChatSession,"has-permission":(0,t.unref)(ve),"has-session-contents":(0,t.unref)(ye),"auto-generate-loading":(0,t.unref)(be),"is-compression-height":(0,t.unref)(S),"render-mode":i.renderMode,"session-business-manager":(0,t.unref)(u),"selected-llm-code":M.value,"session-name":(0,t.unref)(_e),"show-compression-icon":i.showCompressionIcon,"show-history-icon":i.showHistoryIcon,"show-more-icon":i.showMoreIcon,"show-new-chat-icon":i.showNewChatIcon,title:i.title,onAutoGenerateName:(0,t.unref)(De),onClose:(0,t.unref)(I),onHelpClick:(0,t.unref)(Oe),onHistoryClick:(0,t.unref)(Ce),onHistorySessionDelete:(0,t.unref)(Te),onHistorySessionRename:(0,t.unref)(Ee),onHistorySessionSwitch:(0,t.unref)(we),onNewChat:(0,t.unref)(xe),onNewChatCreated:(0,t.unref)(Se),onRename:(0,t.unref)(ke),onShare:(0,t.unref)(Ie),onToggleCompression:(0,t.unref)(V)},(0,t.createSlots)({_:2},[e.$slots.headerLeft?{name:`headerLeft`,fn:(0,t.withCtx)(()=>[(0,t.renderSlot)(e.$slots,`headerLeft`,{},void 0,!0)]),key:`0`}:void 0]),1032,`agent-name.chat-helper.draggable.dropdown-menu-config.enable-chat-session.has-permission.has-session-contents.auto-generate-loading.is-compression-height.render-mode.session-business-manager.selected-llm-code.session-name.show-compression-icon.show-history-icon.show-more-icon.show-new-chat-icon.title.onAutoGenerateName.onClose.onHelpClick.onHistoryClick.onHistorySessionDelete.onHistorySessionRename.onHistorySessionSwitch.onNewChat.onNewChatCreated.onRename.onShare.onToggleCompression`.split(`.`))),(0,t.createCommentVNode)(` ChatBot 核心组件(仅聊天区域) `),(0,t.createVNode)(UUt,{ref_key:`chatBotRef`,ref:h,"always-create-new-session":i.alwaysCreateNewSession,"auto-load":i.loadRecentSessionOnMount,"chat-helper":(0,t.unref)(s),"enable-model-select":i.enableModelSelect,"error-toast":!1,"execution-tab-visible":i.executionTabVisible,"hello-text":i.helloText,"message-tools":i.messageTools,"message-tools-tippy-options":(0,t.unref)(w),models:i.models,placeholder:i.placeholder,prompts:(0,t.unref)(E),"render-mode":i.renderMode,"request-options":i.requestOptions,"use-agent-name":i.useAgentName,"get-side-render-component":i.getSideRenderComponent,"get-side-tab-render-component":i.getSideTabRenderComponent,"on-custom-tab-change":i.onCustomTabChange,"resize-props":i.resizeProps,size:i.size,resources:(0,t.unref)(T),"session-code":i.initialSessionCode,"share-loading":(0,t.unref)(Fe),shortcuts:i.shortcuts,skills:(0,t.unref)(D),style:(0,t.normalizeStyle)({height:i.hideHeader?`100%`:`calc(100% - 48px)`}),"update-tools":i.updateTools,url:(0,t.unref)(y),onAgentAction:n[0]||=(e,t)=>a(`agent-action`,e,t),onCancelShare:(0,t.unref)(Le),onConfirmShare:n[1]||=(e,n)=>(0,t.unref)(Re)(e,n),onError:n[2]||=e=>(0,t.unref)(O)(e),onExecutionPanelChange:(0,t.unref)(ne),onReceiveEnd:(0,t.unref)(H),onReceiveStart:(0,t.unref)(ie),onReceiveText:(0,t.unref)(ae),onRename:(0,t.unref)(Ae),onRequestShare:(0,t.unref)(Ie),onSendMessage:n[3]||=e=>Ue(e),onSessionSwitched:n[4]||=e=>(0,t.unref)(je)(e),onShortcutClick:(0,t.unref)(ge),onStop:(0,t.unref)(oe)},(0,t.createSlots)({_:2},[e.$slots.welcome?{name:`welcome`,fn:(0,t.withCtx)(n=>[(0,t.renderSlot)(e.$slots,`welcome`,(0,t.normalizeProps)((0,t.guardReactiveProps)(n)),void 0,!0)]),key:`0`}:void 0,e.$slots.codeHeader?{name:`codeHeader`,fn:(0,t.withCtx)(n=>[(0,t.renderSlot)(e.$slots,`codeHeader`,(0,t.normalizeProps)((0,t.guardReactiveProps)(n)),void 0,!0)]),key:`1`}:void 0,e.$slots.message?{name:`message`,fn:(0,t.withCtx)(({message:n,messageToolsStatus:r,onInterruptResume:i})=>[(0,t.renderSlot)(e.$slots,`message`,{message:n,messageToolsStatus:r,onInterruptResume:i},void 0,!0)]),key:`2`}:void 0]),1032,`always-create-new-session.auto-load.chat-helper.enable-model-select.execution-tab-visible.hello-text.message-tools.message-tools-tippy-options.models.placeholder.prompts.render-mode.request-options.use-agent-name.get-side-render-component.get-side-tab-render-component.on-custom-tab-change.resize-props.size.resources.session-code.share-loading.shortcuts.skills.style.update-tools.url.onCancelShare.onExecutionPanelChange.onReceiveEnd.onReceiveStart.onReceiveText.onRename.onRequestShare.onShortcutClick.onStop`.split(`.`))],2)]),_:3},8,[`compressed-padding`,`default-height`,`default-width`,`default-x`,`default-y`,`draggable`,`max-width`,`visible`,`onCompressionChange`,`onDragStop`,`onDragging`,`onResizeStop`,`onResizing`]),(0,t.createCommentVNode)(` Nimbus 悬浮球 `),i.hideNimbus?(0,t.createCommentVNode)(`v-if`,!0):((0,t.openBlock)(),(0,t.createBlock)(yWt,{key:0,"is-minimize":(0,t.unref)(v),"onUpdate:isMinimize":n[5]||=e=>(0,t.isRef)(v)?v.value=e:null,"is-panel-show":(0,t.unref)(_),"onUpdate:isPanelShow":n[6]||=e=>(0,t.isRef)(_)?_.value=e:null,"default-minimize":i.defaultMinimize,size:i.nimbusSize,onClick:(0,t.unref)(L)},null,8,[`is-minimize`,`is-panel-show`,`default-minimize`,`size`,`onClick`])),(0,t.createCommentVNode)(` 划词选择弹窗(使用 chat-x 的 AiSelection 组件) `),i.enablePopup?((0,t.openBlock)(),(0,t.createBlock)((0,t.unref)(Ekt),{key:1,visible:(0,t.unref)(ze),"onUpdate:visible":n[7]||=e=>(0,t.isRef)(ze)?ze.value=e:null,"exclude-selectors":[`.draggable-container-wrapper`],"max-shortcut-count":i.shortcutLimit,shortcuts:(0,t.unref)(Be),onSelectShortcut:(0,t.unref)(He),onSelectionChange:(0,t.unref)(Ve)},null,8,[`visible`,`max-shortcut-count`,`shortcuts`,`onSelectShortcut`,`onSelectionChange`])):(0,t.createCommentVNode)(`v-if`,!0)],2)],8,[`to`]))}}),[[`__scopeId`,`data-v-2d3264be`]]);return e.AGUIProtocol=w9,e.AIBlueking=bWt,e.default=bWt,e.BluekingProtocol=nWt,e.BootstrapPhase=H9,e.ChatBot=UUt,e.ChatBusinessManager=yUt,e.ComponentManager=xUt,e.DraggableContainer=gWt,e.MessageContentType=B8,e.RenderMode=G8,e.SessionBusinessManager=B9,e.ShortcutManager=V9,e.UIStateManager=TUt,e.createBluekingProtocol=rWt,e.createComponentManager=SUt,e.defaultProps=tWt,e.parseCustomBlocks=jHt,e.useChatBootstrap=WUt,e.useChatHelper=P9,e.useDraggable=mWt,e})({},Vue);
|