@tbox.cn/app-agent-sdk-client 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{createClientLogger as De}from"@tbox.cn/app-sdk-client";import{nextKeepaliveAction as Be,KEEPALIVE_MISS_LIMIT as Oe}from"@tbox.cn/app-contracts";var S=De("WS"),p=null,R=null,q=null,T=null,W=null,F=null,D=0,X=!0,B=25e3,v=null,j=0;function At(e){e.enabled!==void 0&&(X=e.enabled),e.intervalMs!==void 0&&(B=Math.max(100,e.intervalMs))}function ne(e){W=e}function Tt(e){F=e}function oe(){return F?F():null}var $=null;function Mt(e){$=e}var K=null;function ae(e){K=e}var Ue="登录状态失效,无法连接对话服务,请重试",Ge="HELLO scope 拒绝:context.mall 形状非法(需 mallId 非空)";function qe(e,s,t=3){if(!s)return{stop:!1,nextStreak:0};let o=e+1;return o>=t?{stop:!0,nextStreak:0}:{stop:!1,nextStreak:o}}function z(e,s){if(p&&(p.readyState===WebSocket.OPEN||p.readyState===WebSocket.CONNECTING))return;R=e,q=s??q;let t=W?W():null;t&&(p=new WebSocket(t),p.onopen=()=>{S.info("connected"),T&&(clearTimeout(T),T=null),We(),q?.()},p.onmessage=o=>{j=Date.now();let d=null;try{d=JSON.parse(o.data)}catch(c){S.error("parse error",c);return}if(d?.type!=="PONG"){if(d?.type==="PING"){k({type:"PONG",...d.ts!==void 0?{ts:d.ts}:{}});return}try{R?.(d)}catch(c){S.error("parse error",c)}}},p.onclose=o=>{if(S.info("disconnected",o.code?`code=${o.code}`:""),J(),p=null,o.code===4002){S.error("HELLO scope 拒绝(商圈不在白名单),停止重连"),K?.({code:o.code,message:Ge});return}let d=o.code===4001,{stop:c,nextStreak:g}=qe(D,d);if(D=g,c){S.error("HELLO 连续鉴权失败,停止重连(请刷新页面重试)"),K?.({code:o.code,message:Ue});return}if(d){($?$().catch(h=>S.warn("auth refresh failed:",h.message)):Promise.resolve()).finally(V);return}V()},p.onerror=o=>{S.error("error",o)})}function k(e){if(!p||p.readyState!==WebSocket.OPEN){S.warn("not connected, message dropped");return}p.send(JSON.stringify(e))}function O(){return!!p&&p.readyState===WebSocket.OPEN}function xt(e,s=100){let t=Date.now()+e;return new Promise(o=>{let d=()=>{if(p&&p.readyState===WebSocket.OPEN){o(!0);return}if(Date.now()>=t){o(!1);return}setTimeout(d,s)};d()})}function ie(){T&&(clearTimeout(T),T=null),J(),R=null,D=0,p&&(p.onclose=null,p.close(),p=null)}function le(e=3e3){if(!X||!p||p.readyState!==WebSocket.OPEN)return;let s=Be(Date.now()-j,B);if(s==="dead"){Fe(`keepalive stale (idle >= ${B*Oe}ms)`,e);return}s==="ping"&&k({type:"PING",ts:Date.now()})}function We(){j=Date.now(),X&&(v&&clearInterval(v),v=setInterval(()=>le(),B))}function J(){v&&(clearInterval(v),v=null)}function Fe(e,s=3e3){S.warn(`force reconnect: ${e}`),J();let t=p;p=null,t&&(t.onclose=null,t.onmessage=null,t.onopen=null,t.onerror=null,t.close()),D=0,V(s)}typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&le(0)});function V(e=3e3){T||!R||(T=setTimeout(()=>{T=null,R&&z(R)},e))}function de(e){return function(t,o,d){if(e.blockAll?.(t)!==!0)switch(o.type){case"sendMessage":case"submitForm":case"moduleAction":{if(e.canAct?.(t)===!1)return;e.sendToServer(t,o,d);break}case"openLink":{if(!o.url)break;e.openUrl?.(o.url);break}case"toast":{o.content&&e.toast?.(o.content,o.tone);break}case"closeCard":{e.closeCard?.(t);break}}}}import{createClientLogger as $e}from"@tbox.cn/app-sdk-client";var Ke=$e("CARD");function ce(e,s){let t=o=>o.some(d=>d.id===s.id)?o.map(d=>d.id===s.id?s:d):[...o,s];return s.messageId?{...e,cardsByMessageId:{...e.cardsByMessageId,[s.messageId]:t(e.cardsByMessageId[s.messageId]||[])}}:{...e,orphanCards:t(e.orphanCards)}}function Ht(e,s){let t={};for(let[o,d]of Object.entries(e.cardsByMessageId))t[o]=d.filter(c=>c.id!==s);return{cardsByMessageId:t,orphanCards:e.orphanCards.filter(o=>o.id!==s)}}function ue(e,s){let t=d=>{let c=d.findIndex(b=>b.id===s.id);if(c<0)return null;let g=[...d];return g[c]={...s,messageId:d[c].messageId,isHistory:d[c].isHistory,meta:{...d[c].meta,...s.meta,createdAt:d[c].meta?.createdAt??s.meta?.createdAt??Date.now(),...d[c].meta?.businessNo!==void 0?{businessNo:d[c].meta.businessNo}:{}}},g};for(let[d,c]of Object.entries(e.cardsByMessageId)){let g=t(c);if(g)return{...e,cardsByMessageId:{...e.cardsByMessageId,[d]:g}}}let o=t(e.orphanCards);return o?{...e,orphanCards:o}:(Ke.warn(`update 未命中卡实例:${s.id}(已隐藏/清空或非本连接下发)`),e)}import{TBOX_EFFECT_EVENT_NAME as _t}from"@tbox.cn/app-contracts";import{requestPayment as Ve}from"@tbox.cn/app-sdk-client";import{getAuthCode as Xe}from"@tbox.cn/app-sdk-client";import{createClientLogger as je}from"@tbox.cn/app-sdk-client";var Y=je("tbox:effect");function pe(e){if(e===null||typeof e!="object")return!1;let s=e;return typeof s.type=="string"&&s.type.length>0}function ge(){let e=new Set;return s=>{let t=s.callback?.contextToken;return t?e.has(t)?!1:(e.add(t),!0):!0}}function me(e){return e!==null&&typeof e=="object"&&typeof e.code=="string"?String(e.code):"BRIDGE_ERROR"}function ye(e){return me(e)==="BRIDGE_UNAVAILABLE"}function ze(e){return e==="9000"?"success":e==="6001"?"cancel":"failure"}async function Je(e,s){try{let t=await s.requestPayment(e.orderInfo);return{status:ze(t.resultCode),paymentRef:e.paymentRef}}catch(t){return{status:ye(t)?"unavailable":"failure",paymentRef:e.paymentRef}}}async function Ye(e,s){try{let t=await s.getAuthCode([...e.scopes]);return typeof t.authCode!="string"||!t.authCode.trim()?{status:"failure"}:{status:"success",authCode:t.authCode}}catch(t){let o=me(t);return ye(t)?{status:"unavailable"}:o.includes("CANCEL")?{status:"cancel"}:{status:"failure"}}}function fe(e,s,t){if(e.callback)try{t({actionId:e.callback.actionId,contextToken:e.callback.contextToken,formData:{...s}})}catch(o){Y.warn("结果回传失败:",o?.message)}}function Ce(e){let s={requestPayment:e?.requestPayment??Ve,getAuthCode:e?.getAuthCode??Xe,sendModuleAction:e?.sendModuleAction??(()=>{Y.warn("未注入 sendModuleAction,结果未回传")}),onSessionCredentialsRefreshed:e?.onSessionCredentialsRefreshed};return t=>{switch(t.type){case"payment":{Je(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"authorization.alipay-user-profile":{Ye(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"session.credentials-refreshed":{s.onSessionCredentialsRefreshed?.(t.reason);return}default:Y.warn(`宿主效果类型未在客户端执行:${String(t.type)}`)}}}import{parseSkillReminders as Qe,buildSkillToolCallPayload as Ze,SKILL_NAME_PATTERN as he,SKILL_TOOL_CALL_NAME as et}from"@tbox.cn/app-contracts";function Ie(e){let s=e.query??"",t=Qe(s),o=new Map;for(let d of Array.isArray(e.skills)?e.skills:[])d?.name&&he.test(d.name)&&o.set(d.name,d);for(let d of t.skills)o.has(d)||o.set(d,{name:d});return{content:t.cleanedText,skills:[...o.values()]}}function ke(e,s){return e.filter(t=>t&&he.test(t.name)).map((t,o)=>{let{args:d,result:c}=Ze(t);return{id:`skill-${s}-${o}`,name:et,args:d,result:c,status:"done"}})}import{buildPreToolToolCallPayload as tt,PRE_TOOL_CALL_NAME as rt,PRE_TOOL_NAME_PATTERN as Se}from"@tbox.cn/app-contracts";function st(e){return(Array.isArray(e.preTools)?e.preTools:[]).filter(s=>s?.toolName&&Se.test(s.toolName))}function nt(e){let s=Ie(e);return{content:s.content,skills:s.skills,preTools:st(e)}}function ot(e,s){let t=[];return(Array.isArray(e)?e:[]).filter(o=>o&&Se.test(o.toolName)).forEach((o,d)=>{try{let{args:c,result:g}=tt(o);t.push({id:`pretool-${s}-${d}`,name:rt,args:c,result:g,status:"done"})}catch{}}),t}function at(e,s){return[...ot(e.preTools,s),...ke(e.skills,s)]}function it(e){if(!e)return;let s=new Date(e.replace(" ","T")).getTime();return Number.isNaN(s)?void 0:s}function lt(e,s){let t=e.messageId??e.id??e.outerBusinessId??`hist-${s}`,o=e.createTime??it(e.requestTime)??Date.now();return{key:t,createdAt:o}}function Ee(e){let s=0,t=c=>`${c}_${Date.now()}_${s++}`,o=[],d={};return e.forEach((c,g)=>{let{key:b,createdAt:h}=lt(c,g),A=nt(c);if(c.query){let r={id:`history-user-${b}`,role:"user",content:A.content,status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId}},a=c.multiModalInputs?.imageUrls;a&&a.length>0&&(r.mediaItems=a.map(n=>({id:t("history-img"),type:"image",src:n}))),o.push(r)}(c.answer||c.content||c.cards&&c.cards.length>0)&&o.push({id:`history-asst-${b}`,role:"assistant",content:c.answer||c.content||"",status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId},...A.skills.length>0||A.preTools.length>0?{toolCalls:at(A,b)}:{}}),c.cards&&c.cards.length>0&&(d[`history-asst-${b}`]=c.cards.map(r=>({...r,isHistory:!0})))}),{messages:o,cardsByMessageId:d}}var be;function dt(e){be=e}function Ae(){try{return be?.()}catch{return}}import{TBOX_CARD_EVENT_NAME as Te,TBOX_CARD_UPDATE_EVENT_NAME as ct,TBOX_EFFECT_EVENT_NAME as ut,TBOX_NOTICE_EVENT_NAME as Me}from"@tbox.cn/app-contracts";import{createClientLogger as N,setClientRunContext as Q}from"@tbox.cn/app-sdk-client";import{isInAlipayShell as ft}from"@tbox.cn/app-sdk-client";import{callJsapi as xe}from"@tbox.cn/app-sdk-client";import{resolveAlipayNavigation as pt}from"@tbox.cn/app-sdk-client";var x=N("tbox"),Re="网络连接不可用,请稍后重试",ve=N("CONVERSATION"),gt=N("SESSION-UPGRADE"),mt=N("HISTORY"),we=N("FEEDBACK");function yt(e){let s=String(e?.message||e||"");return/过期|expired|PARAM_INVALID|unauthorized|token/i.test(s)}var P=0,Z=!1,U=null,E=null,ee=!1;function Ct(e){let s=e.messageId??e.id??e.outerBusinessId;return s?`id:${s}`:`content:${e.requestTime??e.createTime??""}:${e.query??""}:${e.answer??e.content??""}`}var H;function tr(e,s,t){if(!H){x.warn("卡动作通道未注册(应用 chat store 未创建),动作已丢弃");return}H(e,s,t)}function ht(e){let s=H;return H=e,()=>{H===e&&(H=s)}}var It=0,w=e=>`${e}_${Date.now()}_${It++}`;function kt(e,s,t){s(o=>({...o,...ce({cardsByMessageId:o.cardsByMessageId,orphanCards:o.orphanCards},t)})),e.onCardEvent?.({type:"render",cardId:t.id,cardType:t.cardType,...t.messageId!==void 0?{messageId:t.messageId}:{},ts:Date.now()})}function St(e,s,t,o){let d={cardsByMessageId:t().cardsByMessageId,orphanCards:t().orphanCards},c=ue(d,o);c!==d&&(s(g=>({...g,...c})),e.onCardEvent?.({type:"update",cardId:o.id,cardType:o.cardType,...o.messageId!==void 0?{messageId:o.messageId}:{},ts:Date.now()}))}function He(e){k(e().conversationEstablished?{type:"RESUME_CONVERSATION"}:{type:"NEW_CONVERSATION"})}function sr(e,s,t){ne(e.getWsUrl),ae(r=>{s({authBlocked:r.message}),e.toast(r.message,"error")});let o=ge(),d=Ce({sendModuleAction:({actionId:r,contextToken:a,formData:n})=>{k({type:"UI_ACTION",surfaceId:"",action:{type:"moduleAction",actionId:r,contextToken:a},formData:n})},...e.onSessionCredentialsRefreshed?{onSessionCredentialsRefreshed:e.onSessionCredentialsRefreshed}:{}}),c=e.onHostEffect??d,g=r=>{let{cardsByMessageId:a,orphanCards:n}=t();return[...Object.values(a).flat(),...n].find(l=>l.id===r)},b=de({canAct:r=>{if(t().isGenerating)return!1;let a=g(r);return!(a&&a.isHistory)},sendToServer:(r,a,n)=>{if(!O()){let u=g(r);e.onCardEvent?.({type:"click",cardId:r,cardType:u?.cardType??"",ts:Date.now()}),e.toast(Re,"error");return}let{addMessage:i}=t(),l=g(r);if(e.onCardEvent?.({type:"click",cardId:r,cardType:l?.cardType??"",ts:Date.now()}),a.type==="sendMessage"){a.visible!==!1&&i({id:w("user"),role:"user",content:a.displayText??a.value,status:"done",createdAt:Date.now()}),k({type:"UI_ACTION",surfaceId:r,action:a}),h=!0;return}if(a.type==="submitForm"){k({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}}),h=!0;return}k({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}})},toast:(r,a)=>e.toast(r,a),openUrl:r=>{if(!(typeof window>"u")){if(r.startsWith("tel:")){window.location.href=r;return}if(ft()){if(r.startsWith("alipays://")||r.startsWith("alipayrisk://")){let a=pt(r,t().helloAck?.mallScope?.miniAppId);a?(x.info(`[openUrl] ${a.apiName} url=${r}`),xe(a.apiName,a.params).catch(n=>{x.warn(`[openUrl] ${a.apiName} failed url=${r}`,n),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error")})):(x.warn(`[openUrl] unresolved Alipay deep link url=${r}`),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error"))}else x.info(`[openUrl] ap.openURL url=${r}`),xe("ap.openURL",{url:r}).catch(a=>{x.warn(`[openUrl] ap.openURL failed url=${r}`,a),e.toast("当前无法打开该链接,请稍后再试","error")});return}window.open&&window.open(r,"_blank")}},closeCard:r=>t().hideCard(r)});ht((r,a,n)=>{t().sendUiAction(r,a,n)});let h=!1,A=()=>{if(!e.platformApi||!e.authClient)throw new Error("会话方法需要 platformApi/authClient(createCoreChatState deps 未注入)");return{platformApi:e.platformApi,authClient:e.authClient}};return{userId:"",helloAck:null,authBlocked:null,messages:[],isGenerating:!1,currentRunId:null,streamingMsgId:null,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[],init:()=>{z(r=>{let a=t();switch(r.type){case"HELLO_ACK":{s({helloAck:{...r.mallScope?{mallScope:r.mallScope}:{},chatConfig:r.chatConfig,...r.toolDebug?{toolDebug:!0}:{}},authBlocked:null});break}case"RUN_STARTED":{if(!h)break;h=!1;let n=w("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({isGenerating:!0,currentRunId:r.runId,streamingMsgId:n}),Q({runId:r.runId,...r.threadId&&{conversationId:r.threadId}});break}case"CUSTOM":{if(r.name===Te){let n=r.value;kt(e,s,n),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Te,{detail:n}))}else if(r.name===ct)St(e,s,t,r.value);else if(r.name===ut&&pe(r.value))o(r.value)&&c(r.value);else if(r.name===Me){let n=r.value;n?.text&&e.toast(n.text,n.level??"info"),typeof window<"u"&&n?.text&&window.dispatchEvent(new CustomEvent(Me,{detail:n}))}break}case"REASONING_START":{if(!t().isGenerating)break;if(!t().streamingMsgId){let n=w("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:n})}break}case"REASONING_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,reasoning:(l.reasoning||"")+r.delta}:l)}));break}case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"TOOL_CALL_START":{if(!t().isGenerating)break;let{streamingMsgId:n}=t();if(!n){let i=w("thinking");a.addMessage({id:i,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:i}),n=i}s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:[...l.toolCalls||[],{id:r.toolCallId,name:r.toolCallName,status:"calling"}]}:l)}));break}case"TOOL_CALL_ARGS":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(u=>u.id===r.toolCallId?{...u,args:(u.args||"")+r.delta}:u)}:l)}));break}case"TOOL_CALL_END":break;case"TOOL_CALL_RESULT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(u=>u.id===r.toolCallId?{...u,result:r.content,status:r.isError?"error":"done",...r.isError?{error:r.errorMessage??"工具执行失败"}:{}}:u)}:l)}));break}case"TEXT_MESSAGE_START":{if(!t().isGenerating)break;let n=r.messageId,{streamingMsgId:i}=t();i?.startsWith("thinking_")?s(l=>({streamingMsgId:n,messages:l.messages.map(u=>u.id===i?{...u,id:n,status:"streaming"}:u)})):(a.addMessage({id:n,role:"assistant",content:"",status:"streaming",createdAt:Date.now()}),s({streamingMsgId:n}));break}case"TEXT_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();n&&r.messageId===n&&t().appendDelta(n,r.delta);break}case"TEXT_MESSAGE_END":{let{streamingMsgId:n}=t();n&&(a.updateMessage(n,{status:"done"}),s({streamingMsgId:null}));break}case"RUN_FINISHED":{if(r.runId&&r.runId!==t().currentRunId)break;let n=r.rawEvent?.requestId;s(n?i=>{let l=[...i.messages];for(let u=l.length-1;u>=0;u--)if(l[u].role==="assistant"&&l[u].status==="done"){l[u]={...l[u],requestId:n,...r.threadId&&{conversationId:r.threadId}};break}return{isGenerating:!1,currentRunId:null,messages:l}}:{isGenerating:!1,currentRunId:null});{let i=0,l=t().messages.map(u=>u.role!=="assistant"||!u.toolCalls?.some(f=>f.status==="calling")?u:(i+=u.toolCalls.filter(f=>f.status==="calling").length,{...u,toolCalls:u.toolCalls.map(f=>f.status==="calling"?{...f,status:"error",error:"工具执行未返回结果"}:f)}));i>0&&(s({messages:l}),x.warn(`RUN_FINISHED:${i} 个工具未收到终态事件,已收敛为失败态`))}Q(null);break}case"RUN_ERROR":{if(!t().isGenerating&&!t().currentRunId)break;let n=r.runId;if(n&&n!==t().currentRunId)break;let i=t().streamingMsgId,l=r.message||"请求失败,请重试",u=r.rawEvent?.requestId??n??t().currentRunId??void 0,f=r.threadId;s(M=>{let y=i?M.messages.find(m=>m.id===i):void 0,C={...y??{id:w("error"),role:"assistant",content:"",createdAt:Date.now()},status:"error",error:l,...u&&{requestId:y?.requestId??u},...f&&{conversationId:y?.conversationId??f},toolCalls:y?.toolCalls?.map(m=>m.status==="calling"?{...m,status:"error",error:"请求中断"}:m)};return{isGenerating:!1,currentRunId:null,streamingMsgId:null,messages:y?M.messages.map(m=>m.id===y.id?C:m):[...M.messages,C]}}),Q(null);break}}},()=>{let r=oe(),a=Ae();k({type:"HELLO",...r?{token:r}:{},...a?{context:a}:{}}),He(t)})},sendMessage:r=>{let{addMessage:a,isGenerating:n}=t();if(n)return;if(!O()){e.toast(Re,"error");return}let i=typeof r=="string"?r:r.text,l=typeof r=="string"?void 0:r.mediaItems,u=typeof r=="string"?void 0:r.inputMethod;a({id:w("user"),role:"user",content:i,status:"done",createdAt:Date.now(),mediaItems:l,inputMethod:u}),k({type:"SEND_MESSAGE",content:i,mediaItems:l?.filter(f=>f.fileId).map(f=>({fileId:f.fileId,type:f.type,name:f.name,mimeType:f.mimeType})),inputMethod:u}),h=!0},sendUiAction:(r,a,n)=>{b(r,a,n)},hideCard:r=>{s(a=>{let n={};for(let[i,l]of Object.entries(a.cardsByMessageId))n[i]=l.filter(u=>u.id!==r);return{cardsByMessageId:n,orphanCards:a.orphanCards.filter(i=>i.id!==r)}})},destroy:()=>ie(),clearChat:()=>{t().cancelGeneration(),h=!1,s({messages:[],currentRunId:null,streamingMsgId:null,isGenerating:!1,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[]})},addMessage:r=>s(a=>({messages:[...a.messages,r]})),appendDelta:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,content:i.content+a}:i)})),updateMessage:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,...a}:i)})),setGenerating:r=>s({isGenerating:r}),cancelGeneration:()=>{h=!1;let{streamingMsgId:r,isGenerating:a,currentRunId:n}=t();if(a){if(k({type:"CANCEL_RUN",...n&&{runId:n}}),r){let i=t().messages.find(l=>l.id===r);i&&!i.content?s(l=>({messages:l.messages.filter(u=>u.id!==r)})):s(l=>({messages:l.messages.map(u=>u.id===r?{...u,status:"done",toolCalls:u.toolCalls?.map(f=>f.status==="calling"?{...f,status:"done"}:f)}:u)}))}s({isGenerating:!1,currentRunId:null,streamingMsgId:null})}},setAuthBlocked:r=>s({authBlocked:r}),setUserId:r=>{t().userId&&t().userId!==r&&s({conversationEstablished:!1}),s({userId:r})},historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null,runtimeStatus:"bootstrapping",initConversation:async()=>{let{authClient:r}=A();if(U)return U;let a;U=new Promise(n=>{a=n});try{let n=t().userId,i=await r.resolveUserId();if(n&&n!==i&&(P++,s({conversationEstablished:!1}),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null})),s({userId:i}),!r.getAuthState()?.token){ve.warn("anonymous: skip WS init, expose recoverable auth failure"),s({runtimeStatus:"failed",conversationEstablished:!1}),t().setAuthBlocked("登录失败,暂时无法对话"),e.toast("登录失败,暂时无法对话","error");return}let l=O();t().init(),s({runtimeStatus:"ready"}),l&&He(t)}catch(n){ve.error("init error:",n),t().init(),s({runtimeStatus:"failed"})}finally{U=null,a()}},retryBootstrap:(r=!0)=>{let{authClient:a}=A();if(E)return E;let i=(async()=>{s({runtimeStatus:"bootstrapping"}),r&&a.clearAuth(),t().destroy(),await t().initConversation()})().finally(()=>{E===i&&(E=null)});return E=i,i},newConversation:async()=>{if(!Z){Z=!0;try{P++,t().clearChat(),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null}),await t().initConversation()}finally{Z=!1}}},scheduleSessionUpgrade:()=>{let{authClient:r}=A();if(E)return E;if(t().isGenerating)return ee=!0,Promise.resolve();let n=(async()=>{s({runtimeStatus:"bootstrapping"});try{r.clearAuth(),await r.ensureAuth(),t().destroy(),await t().initConversation()}catch(i){gt.error("unexpected error:",i),s({runtimeStatus:"failed"})}finally{ee=!1}})().finally(()=>{E===n&&(E=null)});return E=n,n},loadMoreHistory:async()=>{let{platformApi:r}=A(),{isLoadingHistory:a,historyHasMore:n,historyMessages:i,historyBeforeId:l}=t();if(a||!n)return;let u=P;s({isLoadingHistory:!0});let f=5,M=i.length===0?t().messages.find(C=>C.requestId)?.requestId:void 0,y=l??M;try{let{status:C,data:m}=await r.listMessages({pageSize:f,...y?{beforeId:y}:{}});if(u!==P)return;if(C===200&&m){let _=m.data||[],Pe=new Set(t().messages.map(I=>I.requestId).filter(Boolean)),te=new Set(t().historyEntryKeys),re=[],se=_.filter(I=>{let G=Ct(I);return te.has(G)?!1:(te.add(G),re.push(G),!I.outerBusinessId||!Pe.has(I.outerBusinessId))}),L=[..._].reverse().find(I=>I.outerBusinessId)?.outerBusinessId??null,Ne=se.length>0||!!L&&L!==y,{messages:_e,cardsByMessageId:Le}=Ee(se.reverse());s(I=>({historyMessages:[..._e,...I.historyMessages],historyHasMore:_.length>=f&&!!L&&Ne,isLoadingHistory:!1,historyEntryKeys:[...re,...I.historyEntryKeys],historyBeforeId:L,cardsByMessageId:{...I.cardsByMessageId,...Le}}))}else s({isLoadingHistory:!1})}catch(C){if(mt.error("load more error:",C),u!==P)return;s({isLoadingHistory:!1})}},submitFeedback:async(r,a,n,i)=>{let l=t().messages.find(C=>C.id===r),u=l?.feedbackState??"none",f=l?.requestId;if(!f){we.warn("no requestId for message",r);return}let M=a==="cancel"?"none":a;t().updateMessage(r,{feedbackState:M});let y={like:"LIKE",dislike:"DISLIKE",cancel:"CANCEL"};try{(await n.addTag(f,y[a])).success||t().updateMessage(r,{feedbackState:u})}catch(C){if(yt(C)&&i)try{let m=await i();if(m.feedback){(await m.feedback.addTag(f,y[a])).success||t().updateMessage(r,{feedbackState:u});return}}catch(m){we.error("retry failed:",m)}t().updateMessage(r,{feedbackState:u})}}}}function nr(e){return e.subscribe((s,t)=>{ee&&t.isGenerating&&!s.isGenerating&&e.getState().scheduleSessionUpgrade()})}export{At as a,ne as b,Tt as c,oe as d,Mt as e,ae as f,z as g,k as h,O as i,xt as j,ie as k,de as l,ce as m,Ht as n,pe as o,ge as p,ze as q,Je as r,Ye as s,Ce as t,Ie as u,ke as v,st as w,nt as x,ot as y,at as z,lt as A,Ee as B,dt as C,Ae as D,yt as E,tr as F,ht as G,sr as H,nr as I};
@@ -1 +1 @@
1
- import{G as j}from"../chunk-RQWCUVXR.js";import{useCallback as L,useEffect as xe,useMemo as te,useRef as A,useState as I}from"react";import{CardRenderer as ve}from"@tbox.cn/app-sdk-client";var ge="preview",Y="表单提交需引擎运行,预览不支持",J=e=>`预览:已发送「${e}」`,X=e=>`宿主效果 ×${e}(预览不执行)`;function q(e){return new URLSearchParams(e).get("history")==="true"}function K(e){return new URLSearchParams(e).get("controls")!=="false"}var G="(未声明)";function fe(e){return[...new Set(e)].sort((t,n)=>t===n?0:t===G?1:n===G?-1:t.localeCompare(n))}function z(e,t={}){let n=fe(e.cards.map(d=>d.moduleId)),i=t.module!==void 0&&t.module!=="all"&&!n.includes(t.module)?[...n,t.module]:n,r=t.module??"all",a=[...r==="all"?e.cards:e.cards.filter(d=>d.moduleId===r)].sort((d,x)=>{let v=d.order??Number.POSITIVE_INFINITY,C=x.order??Number.POSITIVE_INFINITY;return v!==C?v-C:d.cardType.localeCompare(x.cardType)}),y=a.map(d=>d.cardType),m=a.find(d=>d.cardType===t.card)??a[0],f=m?.cardType??"",g=m?.samples??[],b=t.sample!==void 0&&g.some(d=>d.label===t.sample)?t.sample:"初始态";return{modules:i,moduleId:r,cardTypes:y,candidateCards:a,cardType:f,selectedCard:m,samples:g,sampleLabel:b}}function me(e,t){return`preview-${e.replace(/[^a-zA-Z0-9_-]/g,"_")}-${t}`}function W(e){return{...e.title!==void 0?{title:e.title}:{},...e.subtitle!==void 0?{subtitle:e.subtitle}:{},...e.notices!==void 0?{notices:e.notices}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}}}function N(e,t){let n={};if(!t.noTokens)for(let i of e.actions)(!i.kind||i.kind==="moduleAction")&&(n[i.actionId]=ge);return{id:t.id,cardType:e.cardType,data:t.data,status:"ready",...e.actions.length?{actions:e.actions}:{},...Object.keys(n).length?{actionTokens:n}:{},...t.isHistory?{isHistory:!0}:{},...t.title!==void 0?{title:t.title}:{},...t.subtitle!==void 0?{subtitle:t.subtitle}:{},...t.notices!==void 0?{notices:t.notices}:{},...t.expiresAt!==void 0?{expiresAt:t.expiresAt}:{}}}function Z(e,t,n){return N(e,{id:me(e.cardType,n),data:t.data,isHistory:!!t.isHistory,noTokens:!!t.noTokens,...t.envelope??{}})}function be(e,t,n,i){if(n.ok!==!0||e.payload.id!==t||!n.card)return e;if(n.kind==="card"){let r=i(n.card.cardType),a=r?.samples[0];return!r||!a?e:{card:r,sample:a,payload:N(r,{id:n.card.id,data:n.card.data,isHistory:!1,noTokens:!1,...W(n.card)})}}return n.kind!=="update"?e:{...e,payload:N(e.card,{id:t,data:n.card.data,isHistory:!!e.sample.isHistory,noTokens:!!e.sample.noTokens,...W(n.card)})}}function Q(e,t,n,i,r){let a=e[t];if(!a||a.payload.id!==n)return e;let y=be(a,n,i,r);return y===a?e:{...e,[t]:y}}function ee(e){switch(e.type){case"moduleAction":return{type:"server"};case"openLink":return{type:"openLink",url:e.url};case"sendMessage":return{type:"sendMessage",value:e.value};case"submitForm":return{type:"submitFormUnsupported"};default:return{type:"ignored"}}}import{jsx as s,jsxs as u}from"react/jsx-runtime";var we="客户端未装配模块——经 tbox-app dev --module <模块> 装配后可见",Te="服务端未注册卡片(模块未装配或全部被禁用)",Se=e=>`模块「${e}」暂无示例卡片`,he="鉴权失败:dev 环境依赖 dev-login(浏览器态自动登录);生产构建(NODE_ENV=production)预览面不挂载",re=e=>`卡片目录拉取失败(HTTP ${e})`,Ce="tbox 卡片预览",Pe="isHistory 视角",Ae="全部模块";function oe(e,t,n){let i=Math.max(0,e.samples.findIndex(a=>a.label===t)),r=e.samples[i];return r?{card:e,sample:r,payload:Z(e,r,n??i)}:null}function Qe(e){let{registry:t,authClient:n}=e,i=Object.keys(t).length===0,[r,a]=I(null),[y,m]=I(null),[f,g]=I("all"),[b,d]=I(!1),[x,v]=I({}),[C,B]=I([]),F=A(null),M=A(new Set),S=A(x);S.current=x;let V=A(r);V.current=r;let ae=A(0),se=A(0),H=te(()=>{try{let o=window.location.search,p=new URLSearchParams(o);return{module:p.get("module")??void 0,card:p.get("card")??void 0,sample:p.get("sample")??void 0,history:q(o),controls:K(o)}}catch{return{}}},[]),de=H.controls!==!1,w=L(o=>{let p=++ae.current;B(l=>[...l,{id:p,text:o}]),setTimeout(()=>B(l=>l.filter(c=>c.id!==p)),3200)},[]);xe(()=>{let o=!1,p=j((l,c,h)=>{$.current(l,c,h)});return(async()=>{try{let l=await n.ensureAuth();F.current=l.token;let c=await fetch("/_tbox/api/cards",{headers:l.token?{Authorization:`Bearer ${l.token}`}:{}});if(o)return;if(c.status===401||c.status===403){m(he);return}if(!c.ok){m(re(c.status));return}let h=await c.json();if(o)return;a(h);let k=z(h,H);g(k.moduleId);let E=Re(h.cards,k.cardType,k.sampleLabel);S.current=E,v(E),d(H.history===!0)}catch(l){o||m(`卡片目录拉取失败:${l.message}`)}})(),()=>{o=!0,p()}},[]);let O=L((o,p,l)=>{let c=ee(p);if(c.type==="openLink"){window.open(c.url,"_blank");return}if(c.type==="sendMessage"){w(J(c.value));return}if(c.type==="submitFormUnsupported"){w(Y);return}if(c.type==="ignored")return;let h=Object.entries(S.current).find(([,P])=>P.payload.id===o),k=h?.[1];if(!h||!k||p.type!=="moduleAction"||M.current.has(o))return;M.current.add(o);let E=F.current;fetch("/_tbox/api/card-action",{method:"POST",headers:{"Content-Type":"application/json",...E?{Authorization:`Bearer ${E}`}:{}},body:JSON.stringify({cardType:k.card.cardType,actionId:p.actionId,surfaceId:o,...l!==void 0?{input:l}:{}})}).then(async P=>{let T=await P.json().catch(()=>null);if(!P.ok||!T||T.ok===!1){w(T?.error??re(P.status));return}let pe=T,D=S.current,U=Q(D,h[0],o,pe,ue=>V.current?.cards.find(ye=>ye.cardType===ue));U!==D&&(S.current=U,v(U)),typeof T.text=="string"&&T.text&&w(T.text),Array.isArray(T.effects)&&T.effects.length>0&&w(X(T.effects.length))}).catch(P=>w(`动作请求失败:${P.message}`)).finally(()=>M.current.delete(o))},[w]),$=A(O);$.current=O;let R=te(()=>r?z(r,{module:f==="all"?void 0:f}):null,[r,f]),ce=L((o,p)=>{let l=S.current[o];if(!l)return;let c=oe(l.card,p,l.card.samples.length+ ++se.current);c&&(S.current={...S.current,[o]:c},v(S.current))},[]),le=L(o=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText){w("当前浏览器不支持复制");return}navigator.clipboard.writeText(o).then(()=>w(`已复制卡型 ID:${o}`)).catch(()=>w("复制失败,请手动复制"))},[w]);return u("div",{style:{minHeight:"100vh",background:"#f5f5f5",fontFamily:'-apple-system, "PingFang SC", sans-serif'},children:[de&&u("header",{style:Ee,children:[s("strong",{style:{fontSize:14,color:"#262626"},children:Ce}),u("select",{"aria-label":"模块",style:Le,value:f,onChange:o=>g(o.target.value),children:[s("option",{value:"all",children:Ae}),(R?.modules??[]).map(o=>s("option",{value:o,children:o},o))]}),s("button",{type:"button",style:b?_e:ie,onClick:()=>d(o=>!o),children:Pe})]}),u("main",{style:{maxWidth:1200,margin:"0 auto",padding:"12px 12px 48px"},children:[y&&s("div",{style:We,children:y}),!y&&!r&&s("div",{style:_,children:"加载中…"}),r&&i&&s("div",{style:_,children:we}),r&&!i&&r.cards.length===0&&s("div",{style:_,children:Te}),r&&!i&&r.cards.length>0&&R&&R.candidateCards.length===0&&s("div",{style:_,children:Se(R.moduleId)}),r&&!i&&R&&s(ke,{cards:R.candidateCards,rows:x,registry:t,historyView:b,onSelectSample:ce,onCopyCardType:le,onAction:O})]}),s("div",{style:{position:"fixed",right:16,bottom:24,display:"flex",flexDirection:"column",gap:8,zIndex:20},children:C.map(o=>s("div",{style:Ye,children:o.text},o.id))})]})}function Re(e,t,n){let i={};for(let r of e){let a=oe(r,r.cardType===t?n:void 0);a&&(i[r.cardType]=a)}return i}function ke(e){let{cards:t,rows:n,registry:i,historyView:r,onSelectSample:a,onCopyCardType:y,onAction:m}=e;return s("div",{style:He,children:t.map(f=>{let g=n[f.cardType];return g?s(Ie,{instance:g,registry:i,historyView:r,samples:g.card.samples,activeSampleLabel:g.sample.label,onSelectSample:b=>a(f.cardType,b),onCopyCardType:y,onAction:m},f.cardType):null})})}function Ie(e){let{instance:t,registry:n,historyView:i,samples:r,activeSampleLabel:a,onSelectSample:y,onCopyCardType:m,onAction:f}=e,g=i?{...t.payload,isHistory:!0}:t.payload,b=Math.max(0,r.findIndex(C=>C.label===a)),d=r[b]??t.sample,x=r[b-1],v=r[b+1];return u("section",{style:Me,children:[u("header",{style:{marginBottom:8},children:[s("div",{style:{fontSize:14,fontWeight:600,color:"#262626",lineHeight:"22px"},children:t.card.displayName}),u("div",{style:Oe,children:[u("span",{style:Ue,title:t.card.cardType,children:["卡片id:",t.card.cardType]}),s("button",{type:"button","aria-label":`复制卡型 ID:${t.card.cardType}`,title:"复制卡型 ID",style:Ne,onClick:()=>m(t.card.cardType),children:u("span",{"aria-hidden":"true",style:ze,children:[s("span",{style:Be}),s("span",{style:Fe})]})})]})]}),r.length>0&&u("div",{style:$e,children:[u("div",{style:Ge,title:d.label,"aria-live":"polite",children:[d.issues?.length||d.envelopeError?"⚠ ":"",d.label]}),u("div",{style:De,children:[s("button",{type:"button","aria-label":"上一个样本",title:"上一个样本",disabled:!x,onClick:()=>x&&y(x.label),style:ne(!x),children:"‹"}),u("span",{style:je,children:[b+1," / ",r.length]}),s("button",{type:"button","aria-label":"下一个样本",title:"下一个样本",disabled:!v,onClick:()=>v&&y(v.label),style:ne(!v),children:"›"})]})]}),(t.sample.issues?.length||t.sample.envelopeError)&&u("div",{style:Ve,children:[t.sample.issues?.length?`样本问题:${t.sample.issues.join(";")}`:null,t.sample.envelopeError&&t.sample.issues?.length?";":"",t.sample.envelopeError??""]}),s(ve,{card:g,registry:n,onAction:C=>f(g.id,C)})]})}var Ee={position:"sticky",top:0,zIndex:10,display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"10px 16px",background:"#fff",borderBottom:"1px solid #e8e8e8"},Le={fontSize:13,padding:"4px 8px",borderRadius:8,border:"1px solid #d9d9d9",background:"#fff",color:"#262626"},ie={fontSize:13,padding:"4px 12px",borderRadius:18,border:"1px solid #d9d9d9",background:"#fff",color:"#262626",cursor:"pointer"},_e={...ie,borderColor:"#1677ff",color:"#1677ff"},Me={background:"#fff",borderRadius:8,padding:14,boxShadow:"0 1px 4px rgba(0,0,0,0.06)"},He={display:"flex",flexDirection:"column",gap:12},Oe={display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing.4, 4px)",minHeight:20,color:"var(--color.text.tertiary, #8c8c8c)",fontSize:12,lineHeight:"16px"},Ue={flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Ne={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto",width:20,height:20,padding:0,border:0,borderRadius:"var(--radius.4, 4px)",background:"transparent",color:"var(--color.text.tertiary, #8c8c8c)",cursor:"pointer"},ze={position:"relative",display:"inline-block",width:13,height:13},Be={position:"absolute",top:1,left:1,width:8,height:8,border:"1px solid currentColor",borderRadius:2,boxSizing:"border-box"},Fe={position:"absolute",right:1,bottom:1,width:8,height:8,border:"1px solid currentColor",borderRadius:2,background:"#fff",boxSizing:"border-box"},Ve={fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:"rgba(250,140,22,0.10)",color:"#d46b08",marginBottom:8},$e={display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing.12, 12px)",minHeight:24,marginBottom:10},De={display:"flex",alignItems:"center",gap:"var(--spacing.2, 2px)",flex:"0 0 auto",height:24},ne=e=>({width:24,height:24,padding:0,border:0,borderRadius:"var(--radius.4, 4px)",background:"transparent",color:e?"var(--color.text.disabled, #bfbfbf)":"var(--color.text.secondary, #404040)",fontSize:18,lineHeight:"22px",cursor:e?"not-allowed":"pointer"}),je={display:"flex",alignItems:"center",justifyContent:"center",minWidth:42,color:"var(--color.text.tertiary, #8c8c8c)",fontSize:12,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},Ge={flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--color.text.primary, #1f1f1f)",fontSize:12,fontWeight:"var(--font.weight.medium, 500)"},We={padding:"12px 14px",borderRadius:8,background:"rgba(255,77,79,0.08)",color:"#ff4d4f",fontSize:13,lineHeight:"20px"},_={padding:"12px 14px",borderRadius:8,background:"#fff",color:"#8c8c8c",fontSize:13,lineHeight:"20px",textAlign:"center"},Ye={maxWidth:320,padding:"8px 12px",borderRadius:8,background:"rgba(38,38,38,0.88)",color:"#fff",fontSize:13,lineHeight:"18px",boxShadow:"0 4px 12px rgba(0,0,0,0.18)"};export{he as AUTH_ERROR_MSG,Qe as CardPreviewPage,Te as EMPTY_CATALOG_MSG,Se as EMPTY_MODULE_MSG,we as EMPTY_REGISTRY_MSG,Pe as HISTORY_VIEW_LABEL,re as LOAD_ERROR_MSG,Ae as MODULE_ALL_LABEL,Ce as PAGE_TITLE,ke as PreviewRows,Ie as PreviewSurface,Re as buildPreviewRows};
1
+ import{G as j}from"../chunk-FA7CKDRJ.js";import{useCallback as L,useEffect as xe,useMemo as te,useRef as A,useState as I}from"react";import{CardRenderer as ve}from"@tbox.cn/app-sdk-client";var ge="preview",Y="表单提交需引擎运行,预览不支持",J=e=>`预览:已发送「${e}」`,X=e=>`宿主效果 ×${e}(预览不执行)`;function q(e){return new URLSearchParams(e).get("history")==="true"}function K(e){return new URLSearchParams(e).get("controls")!=="false"}var G="(未声明)";function fe(e){return[...new Set(e)].sort((t,n)=>t===n?0:t===G?1:n===G?-1:t.localeCompare(n))}function z(e,t={}){let n=fe(e.cards.map(d=>d.moduleId)),i=t.module!==void 0&&t.module!=="all"&&!n.includes(t.module)?[...n,t.module]:n,r=t.module??"all",a=[...r==="all"?e.cards:e.cards.filter(d=>d.moduleId===r)].sort((d,x)=>{let v=d.order??Number.POSITIVE_INFINITY,C=x.order??Number.POSITIVE_INFINITY;return v!==C?v-C:d.cardType.localeCompare(x.cardType)}),y=a.map(d=>d.cardType),m=a.find(d=>d.cardType===t.card)??a[0],f=m?.cardType??"",g=m?.samples??[],b=t.sample!==void 0&&g.some(d=>d.label===t.sample)?t.sample:"初始态";return{modules:i,moduleId:r,cardTypes:y,candidateCards:a,cardType:f,selectedCard:m,samples:g,sampleLabel:b}}function me(e,t){return`preview-${e.replace(/[^a-zA-Z0-9_-]/g,"_")}-${t}`}function W(e){return{...e.title!==void 0?{title:e.title}:{},...e.subtitle!==void 0?{subtitle:e.subtitle}:{},...e.notices!==void 0?{notices:e.notices}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}}}function N(e,t){let n={};if(!t.noTokens)for(let i of e.actions)(!i.kind||i.kind==="moduleAction")&&(n[i.actionId]=ge);return{id:t.id,cardType:e.cardType,data:t.data,status:"ready",...e.actions.length?{actions:e.actions}:{},...Object.keys(n).length?{actionTokens:n}:{},...t.isHistory?{isHistory:!0}:{},...t.title!==void 0?{title:t.title}:{},...t.subtitle!==void 0?{subtitle:t.subtitle}:{},...t.notices!==void 0?{notices:t.notices}:{},...t.expiresAt!==void 0?{expiresAt:t.expiresAt}:{}}}function Z(e,t,n){return N(e,{id:me(e.cardType,n),data:t.data,isHistory:!!t.isHistory,noTokens:!!t.noTokens,...t.envelope??{}})}function be(e,t,n,i){if(n.ok!==!0||e.payload.id!==t||!n.card)return e;if(n.kind==="card"){let r=i(n.card.cardType),a=r?.samples[0];return!r||!a?e:{card:r,sample:a,payload:N(r,{id:n.card.id,data:n.card.data,isHistory:!1,noTokens:!1,...W(n.card)})}}return n.kind!=="update"?e:{...e,payload:N(e.card,{id:t,data:n.card.data,isHistory:!!e.sample.isHistory,noTokens:!!e.sample.noTokens,...W(n.card)})}}function Q(e,t,n,i,r){let a=e[t];if(!a||a.payload.id!==n)return e;let y=be(a,n,i,r);return y===a?e:{...e,[t]:y}}function ee(e){switch(e.type){case"moduleAction":return{type:"server"};case"openLink":return{type:"openLink",url:e.url};case"sendMessage":return{type:"sendMessage",value:e.value};case"submitForm":return{type:"submitFormUnsupported"};default:return{type:"ignored"}}}import{jsx as s,jsxs as u}from"react/jsx-runtime";var we="客户端未装配模块——经 tbox-app dev --module <模块> 装配后可见",Te="服务端未注册卡片(模块未装配或全部被禁用)",Se=e=>`模块「${e}」暂无示例卡片`,he="鉴权失败:dev 环境依赖 dev-login(浏览器态自动登录);生产构建(NODE_ENV=production)预览面不挂载",re=e=>`卡片目录拉取失败(HTTP ${e})`,Ce="tbox 卡片预览",Pe="isHistory 视角",Ae="全部模块";function oe(e,t,n){let i=Math.max(0,e.samples.findIndex(a=>a.label===t)),r=e.samples[i];return r?{card:e,sample:r,payload:Z(e,r,n??i)}:null}function Qe(e){let{registry:t,authClient:n}=e,i=Object.keys(t).length===0,[r,a]=I(null),[y,m]=I(null),[f,g]=I("all"),[b,d]=I(!1),[x,v]=I({}),[C,B]=I([]),F=A(null),M=A(new Set),S=A(x);S.current=x;let V=A(r);V.current=r;let ae=A(0),se=A(0),H=te(()=>{try{let o=window.location.search,p=new URLSearchParams(o);return{module:p.get("module")??void 0,card:p.get("card")??void 0,sample:p.get("sample")??void 0,history:q(o),controls:K(o)}}catch{return{}}},[]),de=H.controls!==!1,w=L(o=>{let p=++ae.current;B(l=>[...l,{id:p,text:o}]),setTimeout(()=>B(l=>l.filter(c=>c.id!==p)),3200)},[]);xe(()=>{let o=!1,p=j((l,c,h)=>{$.current(l,c,h)});return(async()=>{try{let l=await n.ensureAuth();F.current=l.token;let c=await fetch("/_tbox/api/cards",{headers:l.token?{Authorization:`Bearer ${l.token}`}:{}});if(o)return;if(c.status===401||c.status===403){m(he);return}if(!c.ok){m(re(c.status));return}let h=await c.json();if(o)return;a(h);let k=z(h,H);g(k.moduleId);let E=Re(h.cards,k.cardType,k.sampleLabel);S.current=E,v(E),d(H.history===!0)}catch(l){o||m(`卡片目录拉取失败:${l.message}`)}})(),()=>{o=!0,p()}},[]);let O=L((o,p,l)=>{let c=ee(p);if(c.type==="openLink"){window.open(c.url,"_blank");return}if(c.type==="sendMessage"){w(J(c.value));return}if(c.type==="submitFormUnsupported"){w(Y);return}if(c.type==="ignored")return;let h=Object.entries(S.current).find(([,P])=>P.payload.id===o),k=h?.[1];if(!h||!k||p.type!=="moduleAction"||M.current.has(o))return;M.current.add(o);let E=F.current;fetch("/_tbox/api/card-action",{method:"POST",headers:{"Content-Type":"application/json",...E?{Authorization:`Bearer ${E}`}:{}},body:JSON.stringify({cardType:k.card.cardType,actionId:p.actionId,surfaceId:o,...l!==void 0?{input:l}:{}})}).then(async P=>{let T=await P.json().catch(()=>null);if(!P.ok||!T||T.ok===!1){w(T?.error??re(P.status));return}let pe=T,D=S.current,U=Q(D,h[0],o,pe,ue=>V.current?.cards.find(ye=>ye.cardType===ue));U!==D&&(S.current=U,v(U)),typeof T.text=="string"&&T.text&&w(T.text),Array.isArray(T.effects)&&T.effects.length>0&&w(X(T.effects.length))}).catch(P=>w(`动作请求失败:${P.message}`)).finally(()=>M.current.delete(o))},[w]),$=A(O);$.current=O;let R=te(()=>r?z(r,{module:f==="all"?void 0:f}):null,[r,f]),ce=L((o,p)=>{let l=S.current[o];if(!l)return;let c=oe(l.card,p,l.card.samples.length+ ++se.current);c&&(S.current={...S.current,[o]:c},v(S.current))},[]),le=L(o=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText){w("当前浏览器不支持复制");return}navigator.clipboard.writeText(o).then(()=>w(`已复制卡型 ID:${o}`)).catch(()=>w("复制失败,请手动复制"))},[w]);return u("div",{style:{minHeight:"100vh",background:"#f5f5f5",fontFamily:'-apple-system, "PingFang SC", sans-serif'},children:[de&&u("header",{style:Ee,children:[s("strong",{style:{fontSize:14,color:"#262626"},children:Ce}),u("select",{"aria-label":"模块",style:Le,value:f,onChange:o=>g(o.target.value),children:[s("option",{value:"all",children:Ae}),(R?.modules??[]).map(o=>s("option",{value:o,children:o},o))]}),s("button",{type:"button",style:b?_e:ie,onClick:()=>d(o=>!o),children:Pe})]}),u("main",{style:{maxWidth:1200,margin:"0 auto",padding:"12px 12px 48px"},children:[y&&s("div",{style:We,children:y}),!y&&!r&&s("div",{style:_,children:"加载中…"}),r&&i&&s("div",{style:_,children:we}),r&&!i&&r.cards.length===0&&s("div",{style:_,children:Te}),r&&!i&&r.cards.length>0&&R&&R.candidateCards.length===0&&s("div",{style:_,children:Se(R.moduleId)}),r&&!i&&R&&s(ke,{cards:R.candidateCards,rows:x,registry:t,historyView:b,onSelectSample:ce,onCopyCardType:le,onAction:O})]}),s("div",{style:{position:"fixed",right:16,bottom:24,display:"flex",flexDirection:"column",gap:8,zIndex:20},children:C.map(o=>s("div",{style:Ye,children:o.text},o.id))})]})}function Re(e,t,n){let i={};for(let r of e){let a=oe(r,r.cardType===t?n:void 0);a&&(i[r.cardType]=a)}return i}function ke(e){let{cards:t,rows:n,registry:i,historyView:r,onSelectSample:a,onCopyCardType:y,onAction:m}=e;return s("div",{style:He,children:t.map(f=>{let g=n[f.cardType];return g?s(Ie,{instance:g,registry:i,historyView:r,samples:g.card.samples,activeSampleLabel:g.sample.label,onSelectSample:b=>a(f.cardType,b),onCopyCardType:y,onAction:m},f.cardType):null})})}function Ie(e){let{instance:t,registry:n,historyView:i,samples:r,activeSampleLabel:a,onSelectSample:y,onCopyCardType:m,onAction:f}=e,g=i?{...t.payload,isHistory:!0}:t.payload,b=Math.max(0,r.findIndex(C=>C.label===a)),d=r[b]??t.sample,x=r[b-1],v=r[b+1];return u("section",{style:Me,children:[u("header",{style:{marginBottom:8},children:[s("div",{style:{fontSize:14,fontWeight:600,color:"#262626",lineHeight:"22px"},children:t.card.displayName}),u("div",{style:Oe,children:[u("span",{style:Ue,title:t.card.cardType,children:["卡片id:",t.card.cardType]}),s("button",{type:"button","aria-label":`复制卡型 ID:${t.card.cardType}`,title:"复制卡型 ID",style:Ne,onClick:()=>m(t.card.cardType),children:u("span",{"aria-hidden":"true",style:ze,children:[s("span",{style:Be}),s("span",{style:Fe})]})})]})]}),r.length>0&&u("div",{style:$e,children:[u("div",{style:Ge,title:d.label,"aria-live":"polite",children:[d.issues?.length||d.envelopeError?"⚠ ":"",d.label]}),u("div",{style:De,children:[s("button",{type:"button","aria-label":"上一个样本",title:"上一个样本",disabled:!x,onClick:()=>x&&y(x.label),style:ne(!x),children:"‹"}),u("span",{style:je,children:[b+1," / ",r.length]}),s("button",{type:"button","aria-label":"下一个样本",title:"下一个样本",disabled:!v,onClick:()=>v&&y(v.label),style:ne(!v),children:"›"})]})]}),(t.sample.issues?.length||t.sample.envelopeError)&&u("div",{style:Ve,children:[t.sample.issues?.length?`样本问题:${t.sample.issues.join(";")}`:null,t.sample.envelopeError&&t.sample.issues?.length?";":"",t.sample.envelopeError??""]}),s(ve,{card:g,registry:n,onAction:C=>f(g.id,C)})]})}var Ee={position:"sticky",top:0,zIndex:10,display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"10px 16px",background:"#fff",borderBottom:"1px solid #e8e8e8"},Le={fontSize:13,padding:"4px 8px",borderRadius:8,border:"1px solid #d9d9d9",background:"#fff",color:"#262626"},ie={fontSize:13,padding:"4px 12px",borderRadius:18,border:"1px solid #d9d9d9",background:"#fff",color:"#262626",cursor:"pointer"},_e={...ie,borderColor:"#1677ff",color:"#1677ff"},Me={background:"#fff",borderRadius:8,padding:14,boxShadow:"0 1px 4px rgba(0,0,0,0.06)"},He={display:"flex",flexDirection:"column",gap:12},Oe={display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing.4, 4px)",minHeight:20,color:"var(--color.text.tertiary, #8c8c8c)",fontSize:12,lineHeight:"16px"},Ue={flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Ne={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto",width:20,height:20,padding:0,border:0,borderRadius:"var(--radius.4, 4px)",background:"transparent",color:"var(--color.text.tertiary, #8c8c8c)",cursor:"pointer"},ze={position:"relative",display:"inline-block",width:13,height:13},Be={position:"absolute",top:1,left:1,width:8,height:8,border:"1px solid currentColor",borderRadius:2,boxSizing:"border-box"},Fe={position:"absolute",right:1,bottom:1,width:8,height:8,border:"1px solid currentColor",borderRadius:2,background:"#fff",boxSizing:"border-box"},Ve={fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:"rgba(250,140,22,0.10)",color:"#d46b08",marginBottom:8},$e={display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing.12, 12px)",minHeight:24,marginBottom:10},De={display:"flex",alignItems:"center",gap:"var(--spacing.2, 2px)",flex:"0 0 auto",height:24},ne=e=>({width:24,height:24,padding:0,border:0,borderRadius:"var(--radius.4, 4px)",background:"transparent",color:e?"var(--color.text.disabled, #bfbfbf)":"var(--color.text.secondary, #404040)",fontSize:18,lineHeight:"22px",cursor:e?"not-allowed":"pointer"}),je={display:"flex",alignItems:"center",justifyContent:"center",minWidth:42,color:"var(--color.text.tertiary, #8c8c8c)",fontSize:12,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},Ge={flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--color.text.primary, #1f1f1f)",fontSize:12,fontWeight:"var(--font.weight.medium, 500)"},We={padding:"12px 14px",borderRadius:8,background:"rgba(255,77,79,0.08)",color:"#ff4d4f",fontSize:13,lineHeight:"20px"},_={padding:"12px 14px",borderRadius:8,background:"#fff",color:"#8c8c8c",fontSize:13,lineHeight:"20px",textAlign:"center"},Ye={maxWidth:320,padding:"8px 12px",borderRadius:8,background:"rgba(38,38,38,0.88)",color:"#fff",fontSize:13,lineHeight:"18px",boxShadow:"0 4px 12px rgba(0,0,0,0.18)"};export{he as AUTH_ERROR_MSG,Qe as CardPreviewPage,Te as EMPTY_CATALOG_MSG,Se as EMPTY_MODULE_MSG,we as EMPTY_REGISTRY_MSG,Pe as HISTORY_VIEW_LABEL,re as LOAD_ERROR_MSG,Ae as MODULE_ALL_LABEL,Ce as PAGE_TITLE,ke as PreviewRows,Ie as PreviewSurface,Re as buildPreviewRows};
@@ -52,6 +52,13 @@ interface ChatMessage {
52
52
  inputMethod?: InputMethod;
53
53
  feedbackState?: 'none' | 'like' | 'dislike';
54
54
  requestId?: string;
55
+ /**
56
+ * 归属会话(服务端下发只读位,可观测用途:调试按钮 trace 查询 / 客户端日志 conv= 尾缀)。
57
+ * 恒与 requestId 同事件同点位落位——来源:run 事件 threadId(实时;ws-server 三入口以
58
+ * conversationId 作 threadKey 构造恒等,server 钉死测试 run-thread-id.test.ts)/
59
+ * 平台历史行 conversationId(历史)。会话 β 上行退役不受影响——本字段永不上行。
60
+ */
61
+ conversationId?: string;
55
62
  }
56
63
 
57
64
  /**
@@ -360,6 +367,8 @@ interface PlatformHistoryMessage {
360
367
  answer?: string;
361
368
  content?: string;
362
369
  outerBusinessId?: string;
370
+ /** 归属会话(平台行透传;可观测只读位,缺席 = 字段不落) */
371
+ conversationId?: string;
363
372
  createTime?: number;
364
373
  requestTime?: string;
365
374
  multiModalInputs?: Record<string, unknown>;
@@ -1 +1 @@
1
- import{A as kt,B as Rt,C as Pt,D as $,E as wt,F as U,G as It,H as Et,I as _t,a as ot,b as st,c as D,d as F,e as O,f as it,g as nt,h as at,i as lt,j as L,k as pt,l as dt,m as ct,n as ut,o as ht,p as ft,q as mt,r as yt,s as gt,t as St,u as xt,v as At,w as bt,x as Tt,y as Ct,z as vt}from"../chunk-RQWCUVXR.js";export*from"@tbox.cn/app-sdk-client";import{jsx as z}from"react/jsx-runtime";function Ut(r){let{actions:t,cardId:e,isHistory:o,className:s,chipClassName:i}=r;return!t||t.length===0?null:z("div",{className:`tbox-item-actions ${s??""}`.trim(),children:t.map((n,a)=>z("button",{type:"button",className:`tbox-chip ${i??""}`.trim(),disabled:o&&n.kind==="send",onClick:()=>{n.kind==="send"?U(e,{type:"sendMessage",value:n.value??n.label,...n.visibleValue?{displayText:n.visibleValue}:{},visible:!0}):U(e,{type:"openLink",url:n.url??""})},children:n.label},a))})}import{createContext as Mt,useContext as A}from"react";import{jsx as Bt}from"react/jsx-runtime";var y=Mt({});function Ht({value:r,children:t}){return Bt(y.Provider,{value:r,children:t})}var Dt=()=>A(y),Ft=()=>A(y).asr,Ot=()=>A(y).tts,Lt=()=>A(y).upload,$t=()=>A(y).feedback,Kt=()=>A(y).refreshSession;import{createClientLogger as Nt}from"@tbox.cn/app-sdk-client";var K=Nt("ACTION"),Wt=0;function Gt(r){return`${r}_${Date.now()}_${Wt++}_${Math.random().toString(36).slice(2,8)}`}var B=null;function N(r){B=r}async function Vt(r,t,e={}){let o=e.baseUrl??"",s={action:r,payload:t,...e.sessionId&&{sessionId:e.sessionId},...e.idempotencyKey&&{idempotencyKey:e.idempotencyKey}},i=s.idempotencyKey?s:{...s,idempotencyKey:Gt(r)},n=e.token??(B?B():null),a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let d;try{d=await fetch(`${o}/api/action`,{method:"POST",headers:a,body:JSON.stringify(i)})}catch(T){let E=T?.message||"网络错误";return K.warn(`POST /api/action action=${r} fetch 异常:${E}`),{success:!1,error:E}}let h;try{h=await d.json()}catch{return K.warn(`POST /api/action action=${r} 响应解析失败(HTTP ${d.status})`),{success:!1,error:`响应解析失败(HTTP ${d.status})`}}return d.status===409?(K.warn(`POST /api/action action=${r} 幂等键冲突:${h.error||"请勿重复提交"}`),{success:!1,error:h.error||"幂等键冲突:请勿重复提交",cached:!1}):d.status===200&&h.cached?{...h,cached:!0}:h}function Xt(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var W=class{snapshots=new Map;async save(t,e){let o=this.snapshots.get(t)??[],s=o.findIndex(n=>n.id===e.id),i={id:e.id,cardType:e.cardType,data:e.data,status:e.status,schemaVersion:e.schemaVersion??1,meta:e.meta};s>=0?o[s]=i:o.push(i),this.snapshots.set(t,o)}async load(t){return(this.snapshots.get(t)??[]).map(o=>Xt(o))}async clear(t){this.snapshots.delete(t)}};import{isInAlipayShell as zt}from"@tbox.cn/app-sdk-client";import{getAuthCode as Jt}from"@tbox.cn/app-sdk-client";import{httpPost as J,httpGet as Yt,configureAuthToken as qt,configureAuthErrorHandler as Qt}from"@tbox.cn/app-sdk-client";import{createClientLogger as jt}from"@tbox.cn/app-sdk-client";var c=jt("AUTH"),g="tbox.auth.token",Y="tbox.auth.scopeKey",M="tbox.auth.lastToken",C=null,H=null;function q(r={}){let t=r.loginPlatform??"alipay";return C?(H&&H.loginPlatform!==t&&c.warn(`createAuthClient 重复调用且选项不同(当前 ${H.loginPlatform} vs ${t}),返回首建单例(首建选项生效)`),C):(C=te({loginPlatform:t,...r.scopeKey?{scopeKey:r.scopeKey}:{}}),H={loginPlatform:t},C)}function Zt(){return C??q()}function te(r={}){let t=r.loginPlatform??"alipay",e=r.scopeKey,o=null,s=null,i=null;function n(l){try{return typeof localStorage<"u"?localStorage.getItem(l):null}catch{return null}}function a(l,x){try{typeof localStorage<"u"&&localStorage.setItem(l,x)}catch{}}function d(l){try{typeof localStorage<"u"&&localStorage.removeItem(l)}catch{}}async function h(){return o||s||(s=et().then(l=>(s=null,l),l=>{throw s=null,l}),s)}async function T(){return i||(o=null,i=h().finally(()=>{i=null}),i)}function E(){o=null,s=null,d(g)}function tt(){return o}async function et(){if(e){let p;try{p=e()}catch{p=""}n(Y)!==p&&(d(g),d(M)),a(Y,p)}let l=n(g);if(l)try{let{status:p,data:f}=await Yt("/api/auth/me",{cache:"no-store"});if(p===200&&f?.identity)return c.info("identity from cached token:",f.identity.userId),_({token:l,identity:f.identity});c.warn("cached token invalid (status=%s), re-login",p),d(g)}catch(p){c.warn("/api/auth/me failed, re-login:",p.message),d(g)}let x=n(M);if(zt()){c.info("alipay shell, starting getAuthCode login...");try{let{authCode:p}=await Jt(["auth_base"]),f=$(),{status:u,data:m}=await J("/api/auth/login",{method:"code",code:p,platform:t,...f?{context:f}:{},...x?{previousToken:x}:{}});if(u===200&&m?.token&&m?.identity)return a(g,m.token),a(M,m.token),c.info("identity via alipay login:",m.identity.userId),_({token:m.token,identity:m.identity});c.warn("alipay login failed: status=%s error=%s",u,m?.error??"(no body)")}catch(p){c.error("alipay login error:",p)}return X()}try{let p=$(),{status:f,data:u}=await J("/api/auth/login",{method:"browser",...p?{context:p}:{},...x?{previousToken:x}:{}});if(f===200&&u?.token&&u?.identity)return a(g,u.token),a(M,u.token),c.info("identity via browser login:",u.identity.userId),_({token:u.token,identity:u.identity});c.warn("browser login unavailable: status=%s error=%s(403 = 服务端 browserLoginMode 关闭或生产禁 mock)",f,u?.error??"(no body)")}catch(p){c.warn("browser login error:",p.message)}return X()}function X(){let l={userId:`anonymous_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"};return c.warn("fallback to anonymous:",l.userId),_({token:null,identity:l})}function _(l){return o=l,qt(()=>o?.token??null),D(()=>o?.token??null),N(()=>o?.token??null),Qt(()=>T()),O(()=>T()),l}async function rt(){return(await h()).identity.userId}return{ensureAuth:h,refreshAuth:T,clearAuth:E,getAuthState:tt,resolveUserId:rt}}import{httpPost as ee}from"@tbox.cn/app-sdk-client";function b(r){return{"X-Tbox-Session-Id":r.tboxSessionId,"X-Tbox-Channel":r.channel,"X-Tbox-AppId":r.appId}}var S=class{constructor(t){this.session=t}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let t=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=t,this.audioChunks=[];let e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",o=new MediaRecorder(t,{mimeType:e});this.mediaRecorder=o,o.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},o.start()}stopRecording(){return new Promise((t,e)=>{let o=this.mediaRecorder;if(!o||o.state==="inactive"){this.cleanup(),t("");return}o.onstop=async()=>{if(this.cancelled){this.cleanup(),t("");return}try{let s=new Blob(this.audioChunks,{type:o.mimeType}),i=await this.blobToBase64(s),{status:n,data:a}=await ee("/api/tbox/asr",{base64_audio:i,audio_format:"webm",sample_rate:"16000"},{headers:b(this.session)});t(n===200&&a?.text?a.text:"")}catch(s){e(s)}finally{this.cleanup()}},o.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(t){return new Promise((e,o)=>{let s=new FileReader;s.onloadend=()=>e(s.result.split(",")[1]||""),s.onerror=o,s.readAsDataURL(t)})}cleanup(){this.mediaStream?.getTracks().forEach(t=>t.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as G}from"@tbox.cn/app-sdk-client";import{httpPost as re}from"@tbox.cn/app-sdk-client";var v=class{constructor(t){this.session=t}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await G("startRecord",{},"invoke")}async stopRecording(){let t=await G("stopRecord",{},"invoke");if(this.cancelled)return"";let e=t?.audioBase64;if(!e)return"";let{status:o,data:s}=await re("/api/tbox/asr",{base64_audio:e,audio_format:t.format||"mp3",sample_rate:"16000"},{headers:b(this.session)});return o===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,G("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as oe}from"@tbox.cn/app-sdk-client";var se=oe("asr"),k=class{bridge;browser;active;constructor(t){this.bridge=new v(t),this.browser=new S(t),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(t){se.warn("桥录音失败,降级到 H5 getUserMedia:",t),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as ie}from"@tbox.cn/app-sdk-client";var R=class{constructor(t){this.session=t}session;onProgress;async upload(t,e){let o;typeof t=="string"?o=await(await fetch(t)).blob():o=t;let{status:s,data:i}=await ie("/api/tbox/upload",o,{headers:{"Content-Type":o.type||"application/octet-stream","X-Tbox-Session-Id":this.session.tboxSessionId,"X-Tbox-Channel":this.session.channel,"X-Tbox-AppId":this.session.appId,"X-Tbox-File-Type":e?.type||"file",...e?.name?{"X-Tbox-File-Name":encodeURIComponent(e.name)}:{}}});if(s!==200||!i?.fileId)throw new Error(`[tbox-upload] ${i?.errorCode??`HTTP_${s}`} ${i?.error??""}`.trim());return{fileId:i.fileId,url:"",mimeType:typeof i.fileType=="string"?i.fileType:void 0,safed:i.safed}}};import{httpPost as ne}from"@tbox.cn/app-sdk-client";var P=class{constructor(t){this.session=t}session;async addTag(t,e){let{status:o,data:s}=await ne("/api/tbox/feedback",{requestId:t,feedback:e},{headers:b(this.session)});return{success:o===200&&!!s?.success}}};var w=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(t){this.sampleRate=t.sampleRate,this.onPlayEnd=t.onPlayEnd}start(){this.isStopped=!1,this.inputCount=0,this.endedCount=0,this.totalInputCount=-1,this.playEndFired=!1,!this.audioContext&&(this.audioContext=new AudioContext({sampleRate:this.sampleRate}),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.nextStartTime=this.audioContext.currentTime)}input(t){if(this.isStopped||!this.audioContext)return;let e=new Int16Array(t);if(e.length===0)return;let o=new Float32Array(e.length);for(let a=0;a<e.length;a++)o[a]=e[a]/32768;let s=this.audioContext.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=this.audioContext.createBufferSource();i.buffer=s,i.connect(this.audioContext.destination);let n=this.audioContext.currentTime;this.nextStartTime<n&&(this.nextStartTime=n),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,i.onended=()=>{this.endedCount++,this.checkPlayEnd()}}finish(){if(this.totalInputCount=this.inputCount,this.totalInputCount===0){this.firePlayEnd();return}if(this.checkPlayEnd(),this.audioContext&&!this.isStopped&&!this.playEndFired){let t=this.nextStartTime-this.audioContext.currentTime,e=Math.max(0,t*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},e)}}stop(){this.isStopped=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null)}async pause(){this.isStopped||!this.audioContext||await this.audioContext.suspend()}async resume(){this.isStopped||!this.audioContext||await this.audioContext.resume()}checkPlayEnd(){this.totalInputCount>0&&this.endedCount>=this.totalInputCount&&!this.isStopped&&this.firePlayEnd()}firePlayEnd(){this.playEndFired||(this.playEndFired=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.onPlayEnd?.())}};import{getWsUrl as ae}from"@tbox.cn/app-sdk-client";import{createClientLogger as le}from"@tbox.cn/app-sdk-client";var Q=le("TTS"),I=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(t){return this.stop(),new Promise(e=>{this.speakResolve=e,this.startStreaming().then(()=>{this.sendText(t),this.finishStreaming()}).catch(()=>{this.setState("idle"),this.resolveSpeak()})})}pause(){this._state!=="playing"||!this.player||(this.player.pause(),this.setState("paused"))}resume(){this._state!=="paused"||!this.player||(this.player.resume(),this.setState("playing"))}stop(){this._canSend=!1,this.pending="",this.pendingFinish=!1,this.closeSocket(),this.player&&(this.player.stop(),this.player=null),this.setState("idle"),this.resolveSpeak()}onStateChange(t){return this.stateCallbacks.add(t),this._state!=="idle"&&t(this._state),()=>this.stateCallbacks.delete(t)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new w({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let t=ae("/ws/tts"),e=F(),o=e?`${t}?token=${encodeURIComponent(e)}`:t;return new Promise((s,i)=>{let n=new WebSocket(o);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},n.onmessage=a=>this.handleMessage(a.data),n.onclose=()=>{this.socket=null,this.player?.finish()},n.onerror=a=>{Q.error("socket error",a),i(a),this.stop()}})}sendText(t){t&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:t}):this.pending+=t)}finishStreaming(){this._canSend?(this.flushPending(),this.sendMessage({type:"TTS_FINISH"})):this.pendingFinish=!0}flushPending(){this.pending&&(this.sendMessage({type:"TTS_TEXT",text:this.pending}),this.pending="")}handleMessage(t){if(typeof t=="string"){try{let e=JSON.parse(t);switch(e.actionType){case"start_ack":this._canSend=!0,this.flushPending(),this.pendingFinish&&(this.pendingFinish=!1,this.sendMessage({type:"TTS_FINISH"}));break;case"completed":this.player?.finish(),this.closeSocket();break;case"failed":Q.error("server error",e.error||e),this.stop();break}}catch{if(!this.player||t.length===0)return;this._state==="loading"&&this.setState("playing");let e=new ArrayBuffer(t.length),o=new Uint8Array(e);for(let s=0;s<t.length;s++)o[s]=t.charCodeAt(s);this.player.input(e)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(t))}sendMessage(t){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(t))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(t){this._state!==t&&(this._state=t,this.stateCallbacks.forEach(e=>e(t)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as pe,isInAlipayShell as de}from"@tbox.cn/app-sdk-client";function ce(r,t){let e={};return t?.tts||(e.tts=new I),r&&(e.asr=de()||pe()?new k(r):new S(r),e.upload=new R(r),e.feedback=new P(r)),t?{...e,...t}:e}import{httpGet as j}from"@tbox.cn/app-sdk-client";function ue(){let r=null;async function t(s=!1){if(r&&!s)return r;r=null;let{status:i,data:n}=await j("/api/tbox/session",{cache:"no-store"});if(i!==200)throw new Error(`[tbox-session] fetch failed: ${i}`);return r=n,r}function e(){r=null}async function o(s){let i=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(i+=`&beforeId=${encodeURIComponent(s.beforeId)}`),j(i,{cache:"no-store"})}return{getTboxSession:t,clearTboxSession:e,listMessages:o}}import{createClientLogger as he}from"@tbox.cn/app-sdk-client";var V=he("AUTO-SEND"),Z=["query","prompt"];function fe(r){let t=new URLSearchParams(r);for(let e of Z){let o=t.get(e)?.trim();if(o)return o}return null}function me(r){let t=new URL(r);for(let e of Z)t.searchParams.delete(e);return t.toString()}function ye(){if(typeof window>"u")return null;let r=fe(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",me(window.location.href))}catch(t){V.warn("strip failed (URL retained; refresh may re-send):",t)}return r}async function ge(r,t,e=5e3){if(!await L(e)){V.warn("skipped:reason=socket-timeout");return}t(r),V.info("sent")}export{Ht as AdapterProvider,v as AlipayASRAdapter,w as AudioStreamPlayer,S as BrowserASRAdapter,k as FallbackASRAdapter,P as FeedbackAdapter,W as InMemoryCardHistoryLoader,Ut as ItemActionsRow,I as TTSAdapter,R as UploadAdapter,It as bindCardActionChannel,vt as buildHistoryToolCalls,Ct as buildPreToolToolCalls,At as buildSkillToolCalls,Vt as callAction,Pt as configureHelloContext,O as configureWsAuthErrorHandler,D as configureWsAuthToken,it as configureWsFatalCloseHandler,ot as configureWsKeepalive,st as configureWsUrl,nt as connect,ye as consumeAutoSendQuery,Rt as convertHistoryMessages,q as createAuthClient,dt as createCardActionHandler,Et as createCoreChatState,ft as createEffectTokenDeduper,St as createHostEffectRunner,ce as createPlatformAdapters,ue as createPlatformApi,pt as disconnect,gt as executeAuthorizationEffect,yt as executePaymentEffect,Zt as getAuthClient,F as getAuthToken,ut as hideCard,ht as isHostEffect,wt as isSessionExpiredError,lt as isWsOpen,mt as mapPaymentResultCode,Tt as resolveHistoryMessage,kt as resolveHistoryMeta,bt as resolveHistoryPreTools,xt as resolveHistorySkills,ge as runAutoSend,at as send,U as sendCardAction,N as setActionAuthTokenGetter,_t as subscribeSessionUpgradeDrain,ct as upsertCard,Ft as useASRAdapter,Dt as useAdapters,$t as useFeedbackAdapter,Kt as useRefreshSession,Ot as useTTSAdapter,Lt as useUploadAdapter,L as waitForSocketOpen};
1
+ import{A as kt,B as Rt,C as Pt,D as $,E as wt,F as U,G as It,H as Et,I as _t,a as ot,b as st,c as D,d as F,e as O,f as it,g as nt,h as at,i as lt,j as L,k as pt,l as dt,m as ct,n as ut,o as ht,p as ft,q as mt,r as yt,s as gt,t as St,u as xt,v as At,w as bt,x as Tt,y as Ct,z as vt}from"../chunk-FA7CKDRJ.js";export*from"@tbox.cn/app-sdk-client";import{jsx as z}from"react/jsx-runtime";function Ut(r){let{actions:t,cardId:e,isHistory:o,className:s,chipClassName:i}=r;return!t||t.length===0?null:z("div",{className:`tbox-item-actions ${s??""}`.trim(),children:t.map((n,a)=>z("button",{type:"button",className:`tbox-chip ${i??""}`.trim(),disabled:o&&n.kind==="send",onClick:()=>{n.kind==="send"?U(e,{type:"sendMessage",value:n.value??n.label,...n.visibleValue?{displayText:n.visibleValue}:{},visible:!0}):U(e,{type:"openLink",url:n.url??""})},children:n.label},a))})}import{createContext as Mt,useContext as A}from"react";import{jsx as Bt}from"react/jsx-runtime";var y=Mt({});function Ht({value:r,children:t}){return Bt(y.Provider,{value:r,children:t})}var Dt=()=>A(y),Ft=()=>A(y).asr,Ot=()=>A(y).tts,Lt=()=>A(y).upload,$t=()=>A(y).feedback,Kt=()=>A(y).refreshSession;import{createClientLogger as Nt}from"@tbox.cn/app-sdk-client";var K=Nt("ACTION"),Wt=0;function Gt(r){return`${r}_${Date.now()}_${Wt++}_${Math.random().toString(36).slice(2,8)}`}var B=null;function N(r){B=r}async function Vt(r,t,e={}){let o=e.baseUrl??"",s={action:r,payload:t,...e.sessionId&&{sessionId:e.sessionId},...e.idempotencyKey&&{idempotencyKey:e.idempotencyKey}},i=s.idempotencyKey?s:{...s,idempotencyKey:Gt(r)},n=e.token??(B?B():null),a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let d;try{d=await fetch(`${o}/api/action`,{method:"POST",headers:a,body:JSON.stringify(i)})}catch(T){let E=T?.message||"网络错误";return K.warn(`POST /api/action action=${r} fetch 异常:${E}`),{success:!1,error:E}}let h;try{h=await d.json()}catch{return K.warn(`POST /api/action action=${r} 响应解析失败(HTTP ${d.status})`),{success:!1,error:`响应解析失败(HTTP ${d.status})`}}return d.status===409?(K.warn(`POST /api/action action=${r} 幂等键冲突:${h.error||"请勿重复提交"}`),{success:!1,error:h.error||"幂等键冲突:请勿重复提交",cached:!1}):d.status===200&&h.cached?{...h,cached:!0}:h}function Xt(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var W=class{snapshots=new Map;async save(t,e){let o=this.snapshots.get(t)??[],s=o.findIndex(n=>n.id===e.id),i={id:e.id,cardType:e.cardType,data:e.data,status:e.status,schemaVersion:e.schemaVersion??1,meta:e.meta};s>=0?o[s]=i:o.push(i),this.snapshots.set(t,o)}async load(t){return(this.snapshots.get(t)??[]).map(o=>Xt(o))}async clear(t){this.snapshots.delete(t)}};import{isInAlipayShell as zt}from"@tbox.cn/app-sdk-client";import{getAuthCode as Jt}from"@tbox.cn/app-sdk-client";import{httpPost as J,httpGet as Yt,configureAuthToken as qt,configureAuthErrorHandler as Qt}from"@tbox.cn/app-sdk-client";import{createClientLogger as jt}from"@tbox.cn/app-sdk-client";var c=jt("AUTH"),g="tbox.auth.token",Y="tbox.auth.scopeKey",M="tbox.auth.lastToken",C=null,H=null;function q(r={}){let t=r.loginPlatform??"alipay";return C?(H&&H.loginPlatform!==t&&c.warn(`createAuthClient 重复调用且选项不同(当前 ${H.loginPlatform} vs ${t}),返回首建单例(首建选项生效)`),C):(C=te({loginPlatform:t,...r.scopeKey?{scopeKey:r.scopeKey}:{}}),H={loginPlatform:t},C)}function Zt(){return C??q()}function te(r={}){let t=r.loginPlatform??"alipay",e=r.scopeKey,o=null,s=null,i=null;function n(l){try{return typeof localStorage<"u"?localStorage.getItem(l):null}catch{return null}}function a(l,x){try{typeof localStorage<"u"&&localStorage.setItem(l,x)}catch{}}function d(l){try{typeof localStorage<"u"&&localStorage.removeItem(l)}catch{}}async function h(){return o||s||(s=et().then(l=>(s=null,l),l=>{throw s=null,l}),s)}async function T(){return i||(o=null,i=h().finally(()=>{i=null}),i)}function E(){o=null,s=null,d(g)}function tt(){return o}async function et(){if(e){let p;try{p=e()}catch{p=""}n(Y)!==p&&(d(g),d(M)),a(Y,p)}let l=n(g);if(l)try{let{status:p,data:f}=await Yt("/api/auth/me",{cache:"no-store"});if(p===200&&f?.identity)return c.info("identity from cached token:",f.identity.userId),_({token:l,identity:f.identity});c.warn("cached token invalid (status=%s), re-login",p),d(g)}catch(p){c.warn("/api/auth/me failed, re-login:",p.message),d(g)}let x=n(M);if(zt()){c.info("alipay shell, starting getAuthCode login...");try{let{authCode:p}=await Jt(["auth_base"]),f=$(),{status:u,data:m}=await J("/api/auth/login",{method:"code",code:p,platform:t,...f?{context:f}:{},...x?{previousToken:x}:{}});if(u===200&&m?.token&&m?.identity)return a(g,m.token),a(M,m.token),c.info("identity via alipay login:",m.identity.userId),_({token:m.token,identity:m.identity});c.warn("alipay login failed: status=%s error=%s",u,m?.error??"(no body)")}catch(p){c.error("alipay login error:",p)}return X()}try{let p=$(),{status:f,data:u}=await J("/api/auth/login",{method:"browser",...p?{context:p}:{},...x?{previousToken:x}:{}});if(f===200&&u?.token&&u?.identity)return a(g,u.token),a(M,u.token),c.info("identity via browser login:",u.identity.userId),_({token:u.token,identity:u.identity});c.warn("browser login unavailable: status=%s error=%s(403 = 服务端 browserLoginMode 关闭或生产禁 mock)",f,u?.error??"(no body)")}catch(p){c.warn("browser login error:",p.message)}return X()}function X(){let l={userId:`anonymous_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"};return c.warn("fallback to anonymous:",l.userId),_({token:null,identity:l})}function _(l){return o=l,qt(()=>o?.token??null),D(()=>o?.token??null),N(()=>o?.token??null),Qt(()=>T()),O(()=>T()),l}async function rt(){return(await h()).identity.userId}return{ensureAuth:h,refreshAuth:T,clearAuth:E,getAuthState:tt,resolveUserId:rt}}import{httpPost as ee}from"@tbox.cn/app-sdk-client";function b(r){return{"X-Tbox-Session-Id":r.tboxSessionId,"X-Tbox-Channel":r.channel,"X-Tbox-AppId":r.appId}}var S=class{constructor(t){this.session=t}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let t=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=t,this.audioChunks=[];let e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",o=new MediaRecorder(t,{mimeType:e});this.mediaRecorder=o,o.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},o.start()}stopRecording(){return new Promise((t,e)=>{let o=this.mediaRecorder;if(!o||o.state==="inactive"){this.cleanup(),t("");return}o.onstop=async()=>{if(this.cancelled){this.cleanup(),t("");return}try{let s=new Blob(this.audioChunks,{type:o.mimeType}),i=await this.blobToBase64(s),{status:n,data:a}=await ee("/api/tbox/asr",{base64_audio:i,audio_format:"webm",sample_rate:"16000"},{headers:b(this.session)});t(n===200&&a?.text?a.text:"")}catch(s){e(s)}finally{this.cleanup()}},o.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(t){return new Promise((e,o)=>{let s=new FileReader;s.onloadend=()=>e(s.result.split(",")[1]||""),s.onerror=o,s.readAsDataURL(t)})}cleanup(){this.mediaStream?.getTracks().forEach(t=>t.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as G}from"@tbox.cn/app-sdk-client";import{httpPost as re}from"@tbox.cn/app-sdk-client";var v=class{constructor(t){this.session=t}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await G("startRecord",{},"invoke")}async stopRecording(){let t=await G("stopRecord",{},"invoke");if(this.cancelled)return"";let e=t?.audioBase64;if(!e)return"";let{status:o,data:s}=await re("/api/tbox/asr",{base64_audio:e,audio_format:t.format||"mp3",sample_rate:"16000"},{headers:b(this.session)});return o===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,G("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as oe}from"@tbox.cn/app-sdk-client";var se=oe("asr"),k=class{bridge;browser;active;constructor(t){this.bridge=new v(t),this.browser=new S(t),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(t){se.warn("桥录音失败,降级到 H5 getUserMedia:",t),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as ie}from"@tbox.cn/app-sdk-client";var R=class{constructor(t){this.session=t}session;onProgress;async upload(t,e){let o;typeof t=="string"?o=await(await fetch(t)).blob():o=t;let{status:s,data:i}=await ie("/api/tbox/upload",o,{headers:{"Content-Type":o.type||"application/octet-stream","X-Tbox-Session-Id":this.session.tboxSessionId,"X-Tbox-Channel":this.session.channel,"X-Tbox-AppId":this.session.appId,"X-Tbox-File-Type":e?.type||"file",...e?.name?{"X-Tbox-File-Name":encodeURIComponent(e.name)}:{}}});if(s!==200||!i?.fileId)throw new Error(`[tbox-upload] ${i?.errorCode??`HTTP_${s}`} ${i?.error??""}`.trim());return{fileId:i.fileId,url:"",mimeType:typeof i.fileType=="string"?i.fileType:void 0,safed:i.safed}}};import{httpPost as ne}from"@tbox.cn/app-sdk-client";var P=class{constructor(t){this.session=t}session;async addTag(t,e){let{status:o,data:s}=await ne("/api/tbox/feedback",{requestId:t,feedback:e},{headers:b(this.session)});return{success:o===200&&!!s?.success}}};var w=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(t){this.sampleRate=t.sampleRate,this.onPlayEnd=t.onPlayEnd}start(){this.isStopped=!1,this.inputCount=0,this.endedCount=0,this.totalInputCount=-1,this.playEndFired=!1,!this.audioContext&&(this.audioContext=new AudioContext({sampleRate:this.sampleRate}),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.nextStartTime=this.audioContext.currentTime)}input(t){if(this.isStopped||!this.audioContext)return;let e=new Int16Array(t);if(e.length===0)return;let o=new Float32Array(e.length);for(let a=0;a<e.length;a++)o[a]=e[a]/32768;let s=this.audioContext.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=this.audioContext.createBufferSource();i.buffer=s,i.connect(this.audioContext.destination);let n=this.audioContext.currentTime;this.nextStartTime<n&&(this.nextStartTime=n),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,i.onended=()=>{this.endedCount++,this.checkPlayEnd()}}finish(){if(this.totalInputCount=this.inputCount,this.totalInputCount===0){this.firePlayEnd();return}if(this.checkPlayEnd(),this.audioContext&&!this.isStopped&&!this.playEndFired){let t=this.nextStartTime-this.audioContext.currentTime,e=Math.max(0,t*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},e)}}stop(){this.isStopped=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null)}async pause(){this.isStopped||!this.audioContext||await this.audioContext.suspend()}async resume(){this.isStopped||!this.audioContext||await this.audioContext.resume()}checkPlayEnd(){this.totalInputCount>0&&this.endedCount>=this.totalInputCount&&!this.isStopped&&this.firePlayEnd()}firePlayEnd(){this.playEndFired||(this.playEndFired=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.onPlayEnd?.())}};import{getWsUrl as ae}from"@tbox.cn/app-sdk-client";import{createClientLogger as le}from"@tbox.cn/app-sdk-client";var Q=le("TTS"),I=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(t){return this.stop(),new Promise(e=>{this.speakResolve=e,this.startStreaming().then(()=>{this.sendText(t),this.finishStreaming()}).catch(()=>{this.setState("idle"),this.resolveSpeak()})})}pause(){this._state!=="playing"||!this.player||(this.player.pause(),this.setState("paused"))}resume(){this._state!=="paused"||!this.player||(this.player.resume(),this.setState("playing"))}stop(){this._canSend=!1,this.pending="",this.pendingFinish=!1,this.closeSocket(),this.player&&(this.player.stop(),this.player=null),this.setState("idle"),this.resolveSpeak()}onStateChange(t){return this.stateCallbacks.add(t),this._state!=="idle"&&t(this._state),()=>this.stateCallbacks.delete(t)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new w({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let t=ae("/ws/tts"),e=F(),o=e?`${t}?token=${encodeURIComponent(e)}`:t;return new Promise((s,i)=>{let n=new WebSocket(o);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},n.onmessage=a=>this.handleMessage(a.data),n.onclose=()=>{this.socket=null,this.player?.finish()},n.onerror=a=>{Q.error("socket error",a),i(a),this.stop()}})}sendText(t){t&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:t}):this.pending+=t)}finishStreaming(){this._canSend?(this.flushPending(),this.sendMessage({type:"TTS_FINISH"})):this.pendingFinish=!0}flushPending(){this.pending&&(this.sendMessage({type:"TTS_TEXT",text:this.pending}),this.pending="")}handleMessage(t){if(typeof t=="string"){try{let e=JSON.parse(t);switch(e.actionType){case"start_ack":this._canSend=!0,this.flushPending(),this.pendingFinish&&(this.pendingFinish=!1,this.sendMessage({type:"TTS_FINISH"}));break;case"completed":this.player?.finish(),this.closeSocket();break;case"failed":Q.error("server error",e.error||e),this.stop();break}}catch{if(!this.player||t.length===0)return;this._state==="loading"&&this.setState("playing");let e=new ArrayBuffer(t.length),o=new Uint8Array(e);for(let s=0;s<t.length;s++)o[s]=t.charCodeAt(s);this.player.input(e)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(t))}sendMessage(t){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(t))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(t){this._state!==t&&(this._state=t,this.stateCallbacks.forEach(e=>e(t)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as pe,isInAlipayShell as de}from"@tbox.cn/app-sdk-client";function ce(r,t){let e={};return t?.tts||(e.tts=new I),r&&(e.asr=de()||pe()?new k(r):new S(r),e.upload=new R(r),e.feedback=new P(r)),t?{...e,...t}:e}import{httpGet as j}from"@tbox.cn/app-sdk-client";function ue(){let r=null;async function t(s=!1){if(r&&!s)return r;r=null;let{status:i,data:n}=await j("/api/tbox/session",{cache:"no-store"});if(i!==200)throw new Error(`[tbox-session] fetch failed: ${i}`);return r=n,r}function e(){r=null}async function o(s){let i=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(i+=`&beforeId=${encodeURIComponent(s.beforeId)}`),j(i,{cache:"no-store"})}return{getTboxSession:t,clearTboxSession:e,listMessages:o}}import{createClientLogger as he}from"@tbox.cn/app-sdk-client";var V=he("AUTO-SEND"),Z=["query","prompt"];function fe(r){let t=new URLSearchParams(r);for(let e of Z){let o=t.get(e)?.trim();if(o)return o}return null}function me(r){let t=new URL(r);for(let e of Z)t.searchParams.delete(e);return t.toString()}function ye(){if(typeof window>"u")return null;let r=fe(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",me(window.location.href))}catch(t){V.warn("strip failed (URL retained; refresh may re-send):",t)}return r}async function ge(r,t,e=5e3){if(!await L(e)){V.warn("skipped:reason=socket-timeout");return}t(r),V.info("sent")}export{Ht as AdapterProvider,v as AlipayASRAdapter,w as AudioStreamPlayer,S as BrowserASRAdapter,k as FallbackASRAdapter,P as FeedbackAdapter,W as InMemoryCardHistoryLoader,Ut as ItemActionsRow,I as TTSAdapter,R as UploadAdapter,It as bindCardActionChannel,vt as buildHistoryToolCalls,Ct as buildPreToolToolCalls,At as buildSkillToolCalls,Vt as callAction,Pt as configureHelloContext,O as configureWsAuthErrorHandler,D as configureWsAuthToken,it as configureWsFatalCloseHandler,ot as configureWsKeepalive,st as configureWsUrl,nt as connect,ye as consumeAutoSendQuery,Rt as convertHistoryMessages,q as createAuthClient,dt as createCardActionHandler,Et as createCoreChatState,ft as createEffectTokenDeduper,St as createHostEffectRunner,ce as createPlatformAdapters,ue as createPlatformApi,pt as disconnect,gt as executeAuthorizationEffect,yt as executePaymentEffect,Zt as getAuthClient,F as getAuthToken,ut as hideCard,ht as isHostEffect,wt as isSessionExpiredError,lt as isWsOpen,mt as mapPaymentResultCode,Tt as resolveHistoryMessage,kt as resolveHistoryMeta,bt as resolveHistoryPreTools,xt as resolveHistorySkills,ge as runAutoSend,at as send,U as sendCardAction,N as setActionAuthTokenGetter,_t as subscribeSessionUpgradeDrain,ct as upsertCard,Ft as useASRAdapter,Dt as useAdapters,$t as useFeedbackAdapter,Kt as useRefreshSession,Ot as useTTSAdapter,Lt as useUploadAdapter,L as waitForSocketOpen};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-agent-sdk-client",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "tbox agent 应用框架 client 轴:chat-store 状态域、WS、卡片运行时、能力适配器(asr/tts/upload/feedback)、历史/深链自动发送。通用底座(runtime/http/logger/bridge/卡片渲染基元)在 @tbox.cn/app-sdk-client。",
6
6
  "exports": {
@@ -1 +0,0 @@
1
- import{createClientLogger as De}from"@tbox.cn/app-sdk-client";import{nextKeepaliveAction as Be,KEEPALIVE_MISS_LIMIT as Oe}from"@tbox.cn/app-contracts";var I=De("WS"),p=null,R=null,q=null,T=null,W=null,F=null,D=0,X=!0,B=25e3,w=null,j=0;function At(e){e.enabled!==void 0&&(X=e.enabled),e.intervalMs!==void 0&&(B=Math.max(100,e.intervalMs))}function ne(e){W=e}function Tt(e){F=e}function oe(){return F?F():null}var $=null;function Mt(e){$=e}var K=null;function ae(e){K=e}var Ue="登录状态失效,无法连接对话服务,请重试",Ge="HELLO scope 拒绝:context.mall 形状非法(需 mallId 非空)";function qe(e,s,t=3){if(!s)return{stop:!1,nextStreak:0};let o=e+1;return o>=t?{stop:!0,nextStreak:0}:{stop:!1,nextStreak:o}}function z(e,s){if(p&&(p.readyState===WebSocket.OPEN||p.readyState===WebSocket.CONNECTING))return;R=e,q=s??q;let t=W?W():null;t&&(p=new WebSocket(t),p.onopen=()=>{I.info("connected"),T&&(clearTimeout(T),T=null),We(),q?.()},p.onmessage=o=>{j=Date.now();let d=null;try{d=JSON.parse(o.data)}catch(u){I.error("parse error",u);return}if(d?.type!=="PONG"){if(d?.type==="PING"){h({type:"PONG",...d.ts!==void 0?{ts:d.ts}:{}});return}try{R?.(d)}catch(u){I.error("parse error",u)}}},p.onclose=o=>{if(I.info("disconnected",o.code?`code=${o.code}`:""),J(),p=null,o.code===4002){I.error("HELLO scope 拒绝(商圈不在白名单),停止重连"),K?.({code:o.code,message:Ge});return}let d=o.code===4001,{stop:u,nextStreak:m}=qe(D,d);if(D=m,u){I.error("HELLO 连续鉴权失败,停止重连(请刷新页面重试)"),K?.({code:o.code,message:Ue});return}if(d){($?$().catch(y=>I.warn("auth refresh failed:",y.message)):Promise.resolve()).finally(V);return}V()},p.onerror=o=>{I.error("error",o)})}function h(e){if(!p||p.readyState!==WebSocket.OPEN){I.warn("not connected, message dropped");return}p.send(JSON.stringify(e))}function O(){return!!p&&p.readyState===WebSocket.OPEN}function xt(e,s=100){let t=Date.now()+e;return new Promise(o=>{let d=()=>{if(p&&p.readyState===WebSocket.OPEN){o(!0);return}if(Date.now()>=t){o(!1);return}setTimeout(d,s)};d()})}function ie(){T&&(clearTimeout(T),T=null),J(),R=null,D=0,p&&(p.onclose=null,p.close(),p=null)}function le(e=3e3){if(!X||!p||p.readyState!==WebSocket.OPEN)return;let s=Be(Date.now()-j,B);if(s==="dead"){Fe(`keepalive stale (idle >= ${B*Oe}ms)`,e);return}s==="ping"&&h({type:"PING",ts:Date.now()})}function We(){j=Date.now(),X&&(w&&clearInterval(w),w=setInterval(()=>le(),B))}function J(){w&&(clearInterval(w),w=null)}function Fe(e,s=3e3){I.warn(`force reconnect: ${e}`),J();let t=p;p=null,t&&(t.onclose=null,t.onmessage=null,t.onopen=null,t.onerror=null,t.close()),D=0,V(s)}typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&le(0)});function V(e=3e3){T||!R||(T=setTimeout(()=>{T=null,R&&z(R)},e))}function de(e){return function(t,o,d){if(e.blockAll?.(t)!==!0)switch(o.type){case"sendMessage":case"submitForm":case"moduleAction":{if(e.canAct?.(t)===!1)return;e.sendToServer(t,o,d);break}case"openLink":{if(!o.url)break;e.openUrl?.(o.url);break}case"toast":{o.content&&e.toast?.(o.content,o.tone);break}case"closeCard":{e.closeCard?.(t);break}}}}import{createClientLogger as $e}from"@tbox.cn/app-sdk-client";var Ke=$e("CARD");function ce(e,s){let t=o=>o.some(d=>d.id===s.id)?o.map(d=>d.id===s.id?s:d):[...o,s];return s.messageId?{...e,cardsByMessageId:{...e.cardsByMessageId,[s.messageId]:t(e.cardsByMessageId[s.messageId]||[])}}:{...e,orphanCards:t(e.orphanCards)}}function Ht(e,s){let t={};for(let[o,d]of Object.entries(e.cardsByMessageId))t[o]=d.filter(u=>u.id!==s);return{cardsByMessageId:t,orphanCards:e.orphanCards.filter(o=>o.id!==s)}}function ue(e,s){let t=d=>{let u=d.findIndex(S=>S.id===s.id);if(u<0)return null;let m=[...d];return m[u]={...s,messageId:d[u].messageId,isHistory:d[u].isHistory,meta:{...d[u].meta,...s.meta,createdAt:d[u].meta?.createdAt??s.meta?.createdAt??Date.now(),...d[u].meta?.businessNo!==void 0?{businessNo:d[u].meta.businessNo}:{}}},m};for(let[d,u]of Object.entries(e.cardsByMessageId)){let m=t(u);if(m)return{...e,cardsByMessageId:{...e.cardsByMessageId,[d]:m}}}let o=t(e.orphanCards);return o?{...e,orphanCards:o}:(Ke.warn(`update 未命中卡实例:${s.id}(已隐藏/清空或非本连接下发)`),e)}import{TBOX_EFFECT_EVENT_NAME as _t}from"@tbox.cn/app-contracts";import{requestPayment as Ve}from"@tbox.cn/app-sdk-client";import{getAuthCode as Xe}from"@tbox.cn/app-sdk-client";import{createClientLogger as je}from"@tbox.cn/app-sdk-client";var Y=je("tbox:effect");function pe(e){if(e===null||typeof e!="object")return!1;let s=e;return typeof s.type=="string"&&s.type.length>0}function ge(){let e=new Set;return s=>{let t=s.callback?.contextToken;return t?e.has(t)?!1:(e.add(t),!0):!0}}function me(e){return e!==null&&typeof e=="object"&&typeof e.code=="string"?String(e.code):"BRIDGE_ERROR"}function ye(e){return me(e)==="BRIDGE_UNAVAILABLE"}function ze(e){return e==="9000"?"success":e==="6001"?"cancel":"failure"}async function Je(e,s){try{let t=await s.requestPayment(e.orderInfo);return{status:ze(t.resultCode),paymentRef:e.paymentRef}}catch(t){return{status:ye(t)?"unavailable":"failure",paymentRef:e.paymentRef}}}async function Ye(e,s){try{let t=await s.getAuthCode([...e.scopes]);return typeof t.authCode!="string"||!t.authCode.trim()?{status:"failure"}:{status:"success",authCode:t.authCode}}catch(t){let o=me(t);return ye(t)?{status:"unavailable"}:o.includes("CANCEL")?{status:"cancel"}:{status:"failure"}}}function fe(e,s,t){if(e.callback)try{t({actionId:e.callback.actionId,contextToken:e.callback.contextToken,formData:{...s}})}catch(o){Y.warn("结果回传失败:",o?.message)}}function Ce(e){let s={requestPayment:e?.requestPayment??Ve,getAuthCode:e?.getAuthCode??Xe,sendModuleAction:e?.sendModuleAction??(()=>{Y.warn("未注入 sendModuleAction,结果未回传")}),onSessionCredentialsRefreshed:e?.onSessionCredentialsRefreshed};return t=>{switch(t.type){case"payment":{Je(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"authorization.alipay-user-profile":{Ye(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"session.credentials-refreshed":{s.onSessionCredentialsRefreshed?.(t.reason);return}default:Y.warn(`宿主效果类型未在客户端执行:${String(t.type)}`)}}}import{parseSkillReminders as Qe,buildSkillToolCallPayload as Ze,SKILL_NAME_PATTERN as he,SKILL_TOOL_CALL_NAME as et}from"@tbox.cn/app-contracts";function Ie(e){let s=e.query??"",t=Qe(s),o=new Map;for(let d of Array.isArray(e.skills)?e.skills:[])d?.name&&he.test(d.name)&&o.set(d.name,d);for(let d of t.skills)o.has(d)||o.set(d,{name:d});return{content:t.cleanedText,skills:[...o.values()]}}function ke(e,s){return e.filter(t=>t&&he.test(t.name)).map((t,o)=>{let{args:d,result:u}=Ze(t);return{id:`skill-${s}-${o}`,name:et,args:d,result:u,status:"done"}})}import{buildPreToolToolCallPayload as tt,PRE_TOOL_CALL_NAME as rt,PRE_TOOL_NAME_PATTERN as Se}from"@tbox.cn/app-contracts";function st(e){return(Array.isArray(e.preTools)?e.preTools:[]).filter(s=>s?.toolName&&Se.test(s.toolName))}function nt(e){let s=Ie(e);return{content:s.content,skills:s.skills,preTools:st(e)}}function ot(e,s){let t=[];return(Array.isArray(e)?e:[]).filter(o=>o&&Se.test(o.toolName)).forEach((o,d)=>{try{let{args:u,result:m}=tt(o);t.push({id:`pretool-${s}-${d}`,name:rt,args:u,result:m,status:"done"})}catch{}}),t}function at(e,s){return[...ot(e.preTools,s),...ke(e.skills,s)]}function it(e){if(!e)return;let s=new Date(e.replace(" ","T")).getTime();return Number.isNaN(s)?void 0:s}function lt(e,s){let t=e.messageId??e.id??e.outerBusinessId??`hist-${s}`,o=e.createTime??it(e.requestTime)??Date.now();return{key:t,createdAt:o}}function Ee(e){let s=0,t=u=>`${u}_${Date.now()}_${s++}`,o=[],d={};return e.forEach((u,m)=>{let{key:S,createdAt:y}=lt(u,m),E=nt(u);if(u.query){let r={id:`history-user-${S}`,role:"user",content:E.content,status:"done",createdAt:y,...u.outerBusinessId&&{requestId:u.outerBusinessId}},a=u.multiModalInputs?.imageUrls;a&&a.length>0&&(r.mediaItems=a.map(n=>({id:t("history-img"),type:"image",src:n}))),o.push(r)}(u.answer||u.content||u.cards&&u.cards.length>0)&&o.push({id:`history-asst-${S}`,role:"assistant",content:u.answer||u.content||"",status:"done",createdAt:y,...u.outerBusinessId&&{requestId:u.outerBusinessId},...E.skills.length>0||E.preTools.length>0?{toolCalls:at(E,S)}:{}}),u.cards&&u.cards.length>0&&(d[`history-asst-${S}`]=u.cards.map(r=>({...r,isHistory:!0})))}),{messages:o,cardsByMessageId:d}}var be;function dt(e){be=e}function Ae(){try{return be?.()}catch{return}}import{TBOX_CARD_EVENT_NAME as Te,TBOX_CARD_UPDATE_EVENT_NAME as ct,TBOX_EFFECT_EVENT_NAME as ut,TBOX_NOTICE_EVENT_NAME as Me}from"@tbox.cn/app-contracts";import{createClientLogger as N,setClientRunContext as Q}from"@tbox.cn/app-sdk-client";import{isInAlipayShell as ft}from"@tbox.cn/app-sdk-client";import{callJsapi as xe}from"@tbox.cn/app-sdk-client";import{resolveAlipayNavigation as pt}from"@tbox.cn/app-sdk-client";var x=N("tbox"),Re="网络连接不可用,请稍后重试",we=N("CONVERSATION"),gt=N("SESSION-UPGRADE"),mt=N("HISTORY"),ve=N("FEEDBACK");function yt(e){let s=String(e?.message||e||"");return/过期|expired|PARAM_INVALID|unauthorized|token/i.test(s)}var P=0,Z=!1,U=null,k=null,ee=!1;function Ct(e){let s=e.messageId??e.id??e.outerBusinessId;return s?`id:${s}`:`content:${e.requestTime??e.createTime??""}:${e.query??""}:${e.answer??e.content??""}`}var H;function tr(e,s,t){if(!H){x.warn("卡动作通道未注册(应用 chat store 未创建),动作已丢弃");return}H(e,s,t)}function ht(e){let s=H;return H=e,()=>{H===e&&(H=s)}}var It=0,v=e=>`${e}_${Date.now()}_${It++}`;function kt(e,s,t){s(o=>({...o,...ce({cardsByMessageId:o.cardsByMessageId,orphanCards:o.orphanCards},t)})),e.onCardEvent?.({type:"render",cardId:t.id,cardType:t.cardType,...t.messageId!==void 0?{messageId:t.messageId}:{},ts:Date.now()})}function St(e,s,t,o){let d={cardsByMessageId:t().cardsByMessageId,orphanCards:t().orphanCards},u=ue(d,o);u!==d&&(s(m=>({...m,...u})),e.onCardEvent?.({type:"update",cardId:o.id,cardType:o.cardType,...o.messageId!==void 0?{messageId:o.messageId}:{},ts:Date.now()}))}function He(e){h(e().conversationEstablished?{type:"RESUME_CONVERSATION"}:{type:"NEW_CONVERSATION"})}function sr(e,s,t){ne(e.getWsUrl),ae(r=>{s({authBlocked:r.message}),e.toast(r.message,"error")});let o=ge(),d=Ce({sendModuleAction:({actionId:r,contextToken:a,formData:n})=>{h({type:"UI_ACTION",surfaceId:"",action:{type:"moduleAction",actionId:r,contextToken:a},formData:n})},...e.onSessionCredentialsRefreshed?{onSessionCredentialsRefreshed:e.onSessionCredentialsRefreshed}:{}}),u=e.onHostEffect??d,m=r=>{let{cardsByMessageId:a,orphanCards:n}=t();return[...Object.values(a).flat(),...n].find(l=>l.id===r)},S=de({canAct:r=>{if(t().isGenerating)return!1;let a=m(r);return!(a&&a.isHistory)},sendToServer:(r,a,n)=>{if(!O()){let c=m(r);e.onCardEvent?.({type:"click",cardId:r,cardType:c?.cardType??"",ts:Date.now()}),e.toast(Re,"error");return}let{addMessage:i}=t(),l=m(r);if(e.onCardEvent?.({type:"click",cardId:r,cardType:l?.cardType??"",ts:Date.now()}),a.type==="sendMessage"){a.visible!==!1&&i({id:v("user"),role:"user",content:a.displayText??a.value,status:"done",createdAt:Date.now()}),h({type:"UI_ACTION",surfaceId:r,action:a}),y=!0;return}if(a.type==="submitForm"){h({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}}),y=!0;return}h({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}})},toast:(r,a)=>e.toast(r,a),openUrl:r=>{if(!(typeof window>"u")){if(r.startsWith("tel:")){window.location.href=r;return}if(ft()){if(r.startsWith("alipays://")||r.startsWith("alipayrisk://")){let a=pt(r,t().helloAck?.mallScope?.miniAppId);a?(x.info(`[openUrl] ${a.apiName} url=${r}`),xe(a.apiName,a.params).catch(n=>{x.warn(`[openUrl] ${a.apiName} failed url=${r}`,n),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error")})):(x.warn(`[openUrl] unresolved Alipay deep link url=${r}`),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error"))}else x.info(`[openUrl] ap.openURL url=${r}`),xe("ap.openURL",{url:r}).catch(a=>{x.warn(`[openUrl] ap.openURL failed url=${r}`,a),e.toast("当前无法打开该链接,请稍后再试","error")});return}window.open&&window.open(r,"_blank")}},closeCard:r=>t().hideCard(r)});ht((r,a,n)=>{t().sendUiAction(r,a,n)});let y=!1,E=()=>{if(!e.platformApi||!e.authClient)throw new Error("会话方法需要 platformApi/authClient(createCoreChatState deps 未注入)");return{platformApi:e.platformApi,authClient:e.authClient}};return{userId:"",helloAck:null,authBlocked:null,messages:[],isGenerating:!1,currentRunId:null,streamingMsgId:null,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[],init:()=>{z(r=>{let a=t();switch(r.type){case"HELLO_ACK":{s({helloAck:{...r.mallScope?{mallScope:r.mallScope}:{},chatConfig:r.chatConfig,...r.toolDebug?{toolDebug:!0}:{}},authBlocked:null});break}case"RUN_STARTED":{if(!y)break;y=!1;let n=v("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({isGenerating:!0,currentRunId:r.runId,streamingMsgId:n}),Q({runId:r.runId});break}case"CUSTOM":{if(r.name===Te){let n=r.value;kt(e,s,n),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Te,{detail:n}))}else if(r.name===ct)St(e,s,t,r.value);else if(r.name===ut&&pe(r.value))o(r.value)&&u(r.value);else if(r.name===Me){let n=r.value;n?.text&&e.toast(n.text,n.level??"info"),typeof window<"u"&&n?.text&&window.dispatchEvent(new CustomEvent(Me,{detail:n}))}break}case"REASONING_START":{if(!t().isGenerating)break;if(!t().streamingMsgId){let n=v("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:n})}break}case"REASONING_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,reasoning:(l.reasoning||"")+r.delta}:l)}));break}case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"TOOL_CALL_START":{if(!t().isGenerating)break;let{streamingMsgId:n}=t();if(!n){let i=v("thinking");a.addMessage({id:i,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:i}),n=i}s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:[...l.toolCalls||[],{id:r.toolCallId,name:r.toolCallName,status:"calling"}]}:l)}));break}case"TOOL_CALL_ARGS":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(c=>c.id===r.toolCallId?{...c,args:(c.args||"")+r.delta}:c)}:l)}));break}case"TOOL_CALL_END":break;case"TOOL_CALL_RESULT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(c=>c.id===r.toolCallId?{...c,result:r.content,status:r.isError?"error":"done",...r.isError?{error:r.errorMessage??"工具执行失败"}:{}}:c)}:l)}));break}case"TEXT_MESSAGE_START":{if(!t().isGenerating)break;let n=r.messageId,{streamingMsgId:i}=t();i?.startsWith("thinking_")?s(l=>({streamingMsgId:n,messages:l.messages.map(c=>c.id===i?{...c,id:n,status:"streaming"}:c)})):(a.addMessage({id:n,role:"assistant",content:"",status:"streaming",createdAt:Date.now()}),s({streamingMsgId:n}));break}case"TEXT_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();n&&r.messageId===n&&t().appendDelta(n,r.delta);break}case"TEXT_MESSAGE_END":{let{streamingMsgId:n}=t();n&&(a.updateMessage(n,{status:"done"}),s({streamingMsgId:null}));break}case"RUN_FINISHED":{if(r.runId&&r.runId!==t().currentRunId)break;let n=r.rawEvent?.requestId;s(n?i=>{let l=[...i.messages];for(let c=l.length-1;c>=0;c--)if(l[c].role==="assistant"&&l[c].status==="done"){l[c]={...l[c],requestId:n};break}return{isGenerating:!1,currentRunId:null,messages:l}}:{isGenerating:!1,currentRunId:null});{let i=0,l=t().messages.map(c=>c.role!=="assistant"||!c.toolCalls?.some(f=>f.status==="calling")?c:(i+=c.toolCalls.filter(f=>f.status==="calling").length,{...c,toolCalls:c.toolCalls.map(f=>f.status==="calling"?{...f,status:"error",error:"工具执行未返回结果"}:f)}));i>0&&(s({messages:l}),x.warn(`RUN_FINISHED:${i} 个工具未收到终态事件,已收敛为失败态`))}Q(null);break}case"RUN_ERROR":{if(!t().isGenerating&&!t().currentRunId)break;let n=r.runId;if(n&&n!==t().currentRunId)break;let i=t().streamingMsgId,l=r.message||"请求失败,请重试",c=r.rawEvent?.requestId??n??t().currentRunId??void 0;s(f=>{let b=i?f.messages.find(g=>g.id===i):void 0,A={...b??{id:v("error"),role:"assistant",content:"",createdAt:Date.now()},status:"error",error:l,...c&&{requestId:b?.requestId??c},toolCalls:b?.toolCalls?.map(g=>g.status==="calling"?{...g,status:"error",error:"请求中断"}:g)};return{isGenerating:!1,currentRunId:null,streamingMsgId:null,messages:b?f.messages.map(g=>g.id===b.id?A:g):[...f.messages,A]}}),Q(null);break}}},()=>{let r=oe(),a=Ae();h({type:"HELLO",...r?{token:r}:{},...a?{context:a}:{}}),He(t)})},sendMessage:r=>{let{addMessage:a,isGenerating:n}=t();if(n)return;if(!O()){e.toast(Re,"error");return}let i=typeof r=="string"?r:r.text,l=typeof r=="string"?void 0:r.mediaItems,c=typeof r=="string"?void 0:r.inputMethod;a({id:v("user"),role:"user",content:i,status:"done",createdAt:Date.now(),mediaItems:l,inputMethod:c}),h({type:"SEND_MESSAGE",content:i,mediaItems:l?.filter(f=>f.fileId).map(f=>({fileId:f.fileId,type:f.type,name:f.name,mimeType:f.mimeType})),inputMethod:c}),y=!0},sendUiAction:(r,a,n)=>{S(r,a,n)},hideCard:r=>{s(a=>{let n={};for(let[i,l]of Object.entries(a.cardsByMessageId))n[i]=l.filter(c=>c.id!==r);return{cardsByMessageId:n,orphanCards:a.orphanCards.filter(i=>i.id!==r)}})},destroy:()=>ie(),clearChat:()=>{t().cancelGeneration(),y=!1,s({messages:[],currentRunId:null,streamingMsgId:null,isGenerating:!1,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[]})},addMessage:r=>s(a=>({messages:[...a.messages,r]})),appendDelta:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,content:i.content+a}:i)})),updateMessage:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,...a}:i)})),setGenerating:r=>s({isGenerating:r}),cancelGeneration:()=>{y=!1;let{streamingMsgId:r,isGenerating:a,currentRunId:n}=t();if(a){if(h({type:"CANCEL_RUN",...n&&{runId:n}}),r){let i=t().messages.find(l=>l.id===r);i&&!i.content?s(l=>({messages:l.messages.filter(c=>c.id!==r)})):s(l=>({messages:l.messages.map(c=>c.id===r?{...c,status:"done",toolCalls:c.toolCalls?.map(f=>f.status==="calling"?{...f,status:"done"}:f)}:c)}))}s({isGenerating:!1,currentRunId:null,streamingMsgId:null})}},setAuthBlocked:r=>s({authBlocked:r}),setUserId:r=>{t().userId&&t().userId!==r&&s({conversationEstablished:!1}),s({userId:r})},historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null,runtimeStatus:"bootstrapping",initConversation:async()=>{let{authClient:r}=E();if(U)return U;let a;U=new Promise(n=>{a=n});try{let n=t().userId,i=await r.resolveUserId();if(n&&n!==i&&(P++,s({conversationEstablished:!1}),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null})),s({userId:i}),!r.getAuthState()?.token){we.warn("anonymous: skip WS init, expose recoverable auth failure"),s({runtimeStatus:"failed",conversationEstablished:!1}),t().setAuthBlocked("登录失败,暂时无法对话"),e.toast("登录失败,暂时无法对话","error");return}let l=O();t().init(),s({runtimeStatus:"ready"}),l&&He(t)}catch(n){we.error("init error:",n),t().init(),s({runtimeStatus:"failed"})}finally{U=null,a()}},retryBootstrap:(r=!0)=>{let{authClient:a}=E();if(k)return k;let i=(async()=>{s({runtimeStatus:"bootstrapping"}),r&&a.clearAuth(),t().destroy(),await t().initConversation()})().finally(()=>{k===i&&(k=null)});return k=i,i},newConversation:async()=>{if(!Z){Z=!0;try{P++,t().clearChat(),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null}),await t().initConversation()}finally{Z=!1}}},scheduleSessionUpgrade:()=>{let{authClient:r}=E();if(k)return k;if(t().isGenerating)return ee=!0,Promise.resolve();let n=(async()=>{s({runtimeStatus:"bootstrapping"});try{r.clearAuth(),await r.ensureAuth(),t().destroy(),await t().initConversation()}catch(i){gt.error("unexpected error:",i),s({runtimeStatus:"failed"})}finally{ee=!1}})().finally(()=>{k===n&&(k=null)});return k=n,n},loadMoreHistory:async()=>{let{platformApi:r}=E(),{isLoadingHistory:a,historyHasMore:n,historyMessages:i,historyBeforeId:l}=t();if(a||!n)return;let c=P;s({isLoadingHistory:!0});let f=5,b=i.length===0?t().messages.find(g=>g.requestId)?.requestId:void 0,A=l??b;try{let{status:g,data:M}=await r.listMessages({pageSize:f,...A?{beforeId:A}:{}});if(c!==P)return;if(g===200&&M){let _=M.data||[],Pe=new Set(t().messages.map(C=>C.requestId).filter(Boolean)),te=new Set(t().historyEntryKeys),re=[],se=_.filter(C=>{let G=Ct(C);return te.has(G)?!1:(te.add(G),re.push(G),!C.outerBusinessId||!Pe.has(C.outerBusinessId))}),L=[..._].reverse().find(C=>C.outerBusinessId)?.outerBusinessId??null,Ne=se.length>0||!!L&&L!==A,{messages:_e,cardsByMessageId:Le}=Ee(se.reverse());s(C=>({historyMessages:[..._e,...C.historyMessages],historyHasMore:_.length>=f&&!!L&&Ne,isLoadingHistory:!1,historyEntryKeys:[...re,...C.historyEntryKeys],historyBeforeId:L,cardsByMessageId:{...C.cardsByMessageId,...Le}}))}else s({isLoadingHistory:!1})}catch(g){if(mt.error("load more error:",g),c!==P)return;s({isLoadingHistory:!1})}},submitFeedback:async(r,a,n,i)=>{let l=t().messages.find(g=>g.id===r),c=l?.feedbackState??"none",f=l?.requestId;if(!f){ve.warn("no requestId for message",r);return}let b=a==="cancel"?"none":a;t().updateMessage(r,{feedbackState:b});let A={like:"LIKE",dislike:"DISLIKE",cancel:"CANCEL"};try{(await n.addTag(f,A[a])).success||t().updateMessage(r,{feedbackState:c})}catch(g){if(yt(g)&&i)try{let M=await i();if(M.feedback){(await M.feedback.addTag(f,A[a])).success||t().updateMessage(r,{feedbackState:c});return}}catch(M){ve.error("retry failed:",M)}t().updateMessage(r,{feedbackState:c})}}}}function nr(e){return e.subscribe((s,t)=>{ee&&t.isGenerating&&!s.isGenerating&&e.getState().scheduleSessionUpgrade()})}export{At as a,ne as b,Tt as c,oe as d,Mt as e,ae as f,z as g,h,O as i,xt as j,ie as k,de as l,ce as m,Ht as n,pe as o,ge as p,ze as q,Je as r,Ye as s,Ce as t,Ie as u,ke as v,st as w,nt as x,ot as y,at as z,lt as A,Ee as B,dt as C,Ae as D,yt as E,tr as F,ht as G,sr as H,nr as I};