@tbox.cn/app-agent-sdk-client 1.0.0-alpha.13 → 1.0.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/card-preview.js +1 -1
- package/dist/app/index.js +1 -1
- package/dist/chunk-2A3TBRT4.js +1 -0
- package/dist/chunk-5TUYEBYW.js +1 -0
- package/dist/{chunk-AW4ZSI4F.js → chunk-HECUPMFT.js} +1 -1
- package/dist/{chunk-YTXQ3WRK.js → chunk-PMVREUTT.js} +1 -1
- package/dist/chunk-SRHMZIHE.js +1 -0
- package/dist/client/card-preview.js +1 -1
- package/dist/client/index.d.ts +62 -13
- package/dist/client/index.js +1 -1
- package/package.json +4 -4
- package/dist/chunk-6VLQT22V.js +0 -1
- package/dist/chunk-HE3FQIAS.js +0 -1
- package/dist/chunk-RWUIBPQC.js +0 -1
package/dist/app/card-preview.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as o}from"../chunk-
|
|
1
|
+
import{i as o}from"../chunk-5TUYEBYW.js";import"../chunk-SRHMZIHE.js";import{d as t}from"../chunk-HECUPMFT.js";import"../chunk-2A3TBRT4.js";import{startApp as a}from"@tbox.cn/app-sdk-client/app";import{getRegisteredClientCards as i}from"@tbox.cn/app-sdk-client";import{jsx as n}from"react/jsx-runtime";function f(e={}){function p(){return n(o,{registry:i(),authClient:t()})}let r=e.wrap??e.config?.wrapPreview;return a({...e,...r?{wrap:r}:{},page:async()=>({default:p})})}export{f as startCardPreview};
|
package/dist/app/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,o as a,q as A}from"../chunk-
|
|
1
|
+
import{a as c,o as a,q as A}from"../chunk-PMVREUTT.js";import{d as l}from"../chunk-HECUPMFT.js";import"../chunk-2A3TBRT4.js";import{useCallback as u,useEffect as g,useMemo as f,useState as S}from"react";import{createLogger as h}from"@tbox.cn/app-sdk-core";import{startApp as x}from"@tbox.cn/app-sdk-client/app";import{jsx as d}from"react/jsx-runtime";var C=h("AgentAppShell");function b({config:t,children:n}){let[s,p]=S(null),e=f(()=>a().tts,[]);g(()=>{l().ensureAuth().then(()=>A().getTboxSession()).then(o=>{p(o),t.onSession?.(o)}).catch(o=>C.error("tbox session init failed:",o))},[t]);let r=u(async()=>{let o=A();o.clearTboxSession(),await l().refreshAuth();let i=await o.getTboxSession(!0);return p(i),t.onSession?.(i),{tts:e,...a(i,{tts:e,...t.adapters??{}}),refreshSession:r}},[e,t]),m=f(()=>s?{tts:e,...a(s,{tts:e,...t.adapters??{}}),refreshSession:r}:{tts:e,refreshSession:r},[s,e,r,t]);return d(c,{value:m,children:n})}function R(t){let{config:n,...s}=t,p=n.shell===!1?null:n.shell??b,e=p?r=>d(p,{config:n,children:r}):void 0;return x({...s,config:n,...e?{wrap:e}:{}})}export{b as AgentAppShell,R as startAgentApp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var E;function M(e){E=e}function _(){try{return E?.()}catch{return}}import{createClientLogger as O}from"@tbox.cn/app-sdk-client";import{nextKeepaliveAction as T,KEEPALIVE_MISS_LIMIT as A}from"@tbox.cn/app-contracts";var i=O("WS"),n=null,u=null,p=null,a=null,m=null,v=null,d=0,x=!0,f=25e3,c=null,y=0;function U(e){e.enabled!==void 0&&(x=e.enabled),e.intervalMs!==void 0&&(f=Math.max(100,e.intervalMs))}function $(e){m=e}function J(e){v=e}function j(){return v?v():null}var S=null;function V(e){S=e}var g=null;function q(e){g=e}var P="登录状态失效,无法连接对话服务,请重试",I="HELLO scope 拒绝:context.mall 形状非法(需 mallId 非空)";function N(e,l,r=3){if(!l)return{stop:!1,nextStreak:0};let t=e+1;return t>=r?{stop:!0,nextStreak:0}:{stop:!1,nextStreak:t}}function C(e,l){if(n&&(n.readyState===WebSocket.OPEN||n.readyState===WebSocket.CONNECTING))return;u=e,p=l??p;let r=m?m():null;r&&(n=new WebSocket(r),n.onopen=()=>{i.info("connected"),a&&(clearTimeout(a),a=null),L(),p?.()},n.onmessage=t=>{y=Date.now();let o=null;try{o=JSON.parse(t.data)}catch(s){i.error("parse error",s);return}if(o?.type!=="PONG"){if(o?.type==="PING"){h({type:"PONG",...o.ts!==void 0?{ts:o.ts}:{}});return}try{u?.(o)}catch(s){i.error("parse error",s)}}},n.onclose=t=>{if(i.info("disconnected",t.code?`code=${t.code}`:""),b(),n=null,t.code===4002){i.error("HELLO scope 拒绝(商圈不在白名单),停止重连"),g?.({code:t.code,message:I});return}let o=t.code===4001,{stop:s,nextStreak:H}=N(d,o);if(d=H,s){i.error("HELLO 连续鉴权失败,停止重连(请刷新页面重试)"),g?.({code:t.code,message:P});return}if(o){(S?S().catch(w=>i.warn("auth refresh failed:",w.message)):Promise.resolve()).finally(k);return}k()},n.onerror=t=>{i.error("error",t)})}function h(e){if(!n||n.readyState!==WebSocket.OPEN){i.warn("not connected, message dropped");return}n.send(JSON.stringify(e))}function z(){return!!n&&n.readyState===WebSocket.OPEN}function B(e,l=100){let r=Date.now()+e;return new Promise(t=>{let o=()=>{if(n&&n.readyState===WebSocket.OPEN){t(!0);return}if(Date.now()>=r){t(!1);return}setTimeout(o,l)};o()})}function Q(){a&&(clearTimeout(a),a=null),b(),u=null,d=0,n&&(n.onclose=null,n.close(),n=null)}function W(e=3e3){if(!x||!n||n.readyState!==WebSocket.OPEN)return;let l=T(Date.now()-y,f);if(l==="dead"){G(`keepalive stale (idle >= ${f*A}ms)`,e);return}l==="ping"&&h({type:"PING",ts:Date.now()})}function L(){y=Date.now(),x&&(c&&clearInterval(c),c=setInterval(()=>W(),f))}function b(){c&&(clearInterval(c),c=null)}function G(e,l=3e3){i.warn(`force reconnect: ${e}`),b();let r=n;n=null,r&&(r.onclose=null,r.onmessage=null,r.onopen=null,r.onerror=null,r.close()),d=0,k(l)}typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&W(0)});function k(e=3e3){a||!u||(a=setTimeout(()=>{a=null,u&&C(u)},e))}export{M as a,_ as b,U as c,$ as d,J as e,j as f,V as g,q as h,C as i,h as j,z as k,B as l,Q as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as Y}from"./chunk-SRHMZIHE.js";import{useCallback as U,useEffect as ve,useId as re,useMemo as ie,useRef as k,useState as C}from"react";import{CaretDown as we,CaretLeft as Se,CaretRight as Te,Copy as he}from"@phosphor-icons/react";import{CardRenderer as Ce}from"@tbox.cn/app-sdk-client";var fe="preview",q="表单提交需引擎运行,预览不支持",K=e=>`预览:已发送「${e}」`,Z=e=>`宿主效果 ×${e}(预览不执行)`;function Q(e){return new URLSearchParams(e).get("history")==="true"}function ee(e){return new URLSearchParams(e).get("controls")!=="false"}var J="(未声明)";function me(e){return[...new Set(e)].sort((t,o)=>t===o?0:t===J?1:o===J?-1:t.localeCompare(o))}function G(e,t={}){let o=me(e.cards.map(d=>d.moduleId)),l=t.module!==void 0&&t.module!=="all"&&!o.includes(t.module)?[...o,t.module]:o,n=t.module??"all",i=[...n==="all"?e.cards:e.cards.filter(d=>d.moduleId===n)].sort((d,S)=>{let b=d.order??Number.POSITIVE_INFINITY,T=S.order??Number.POSITIVE_INFINITY;return b!==T?b-T:d.cardType.localeCompare(S.cardType)}),v=i.map(d=>d.cardType),g=i.find(d=>d.cardType===t.card)??i[0],w=g?.cardType??"",m=g?.samples??[],P=t.sample!==void 0&&m.some(d=>d.label===t.sample)?t.sample:"初始态";return{modules:l,moduleId:n,cardTypes:v,candidateCards:i,cardType:w,selectedCard:g,samples:m,sampleLabel:P}}function be(e,t){return`preview-${e.replace(/[^a-zA-Z0-9_-]/g,"_")}-${t}`}function X(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 $(e,t){let o={};if(!t.noTokens)for(let l of e.actions)(!l.kind||l.kind==="moduleAction")&&(o[l.actionId]=fe);return{id:t.id,cardType:e.cardType,data:t.data,status:"ready",...e.actions.length?{actions:e.actions}:{},...Object.keys(o).length?{actionTokens:o}:{},...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 te(e,t,o){return $(e,{id:be(e.cardType,o),data:t.data,isHistory:!!t.isHistory,noTokens:!!t.noTokens,...t.envelope??{}})}function xe(e,t,o,l){if(o.ok!==!0||e.payload.id!==t||!o.card)return e;if(o.kind==="card"){let n=l(o.card.cardType),i=n?.samples[0];return!n||!i?e:{card:n,sample:i,payload:$(n,{id:o.card.id,data:o.card.data,isHistory:!1,noTokens:!1,...X(o.card)})}}return o.kind!=="update"?e:{...e,payload:$(e.card,{id:t,data:o.card.data,isHistory:!!e.sample.isHistory,noTokens:!!e.sample.noTokens,...X(o.card)})}}function oe(e,t,o,l,n){let i=e[t];if(!i||i.payload.id!==o)return e;let v=xe(i,o,l,n);return v===i?e:{...e,[t]:v}}function ne(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{Fragment as nt,jsx as s,jsxs as u}from"react/jsx-runtime";var Pe="客户端未装配模块——经 tbox-app-dev dev --module <模块> 装配后可见",Ae="服务端未注册卡片(模块未装配或全部被禁用)",Ie=e=>`模块「${e}」暂无示例卡片`,Re="鉴权失败:dev 环境依赖 dev-login(浏览器态自动登录);生产构建(NODE_ENV=production)预览面不挂载",ae=e=>`卡片目录拉取失败(HTTP ${e})`,ke="tbox 卡片预览",Le="isHistory 视角",Ee="全部模块";function le(e,t,o){let l=Math.max(0,e.samples.findIndex(i=>i.label===t)),n=e.samples[l];return n?{card:e,sample:n,payload:te(e,n,o??l)}:null}function ct(e){let{registry:t,authClient:o}=e,l=Object.keys(t).length===0,[n,i]=C(null),[v,g]=C(null),[w,m]=C("all"),[P,d]=C(!1),[S,b]=C({}),[T,H]=C([]),O=k(null),I=k(new Set),x=k(S);x.current=S;let F=k(n);F.current=n;let B=k(0),D=k(0),L=ie(()=>{try{let r=window.location.search,f=new URLSearchParams(r);return{module:f.get("module")??void 0,card:f.get("card")??void 0,sample:f.get("sample")??void 0,history:Q(r),controls:ee(r)}}catch{return{}}},[]),V=L.controls!==!1,y=U(r=>{let f=++B.current;H(p=>[...p,{id:f,text:r}]),setTimeout(()=>H(p=>p.filter(c=>c.id!==f)),3200)},[]);ve(()=>{let r=!1,f=Y((p,c,A)=>(a.current(p,c,A),{status:"rejected",reason:"offline"}));return(async()=>{try{let p=await o.ensureAuth();O.current=p.token;let c=await fetch("/_tbox/api/cards",{headers:p.token?{Authorization:`Bearer ${p.token}`}:{}});if(r)return;if(c.status===401||c.status===403){g(Re);return}if(!c.ok){g(ae(c.status));return}let A=await c.json();if(r)return;i(A);let _=G(A,L);m(_.moduleId);let z=Me(A.cards,_.cardType,_.sampleLabel);x.current=z,b(z),d(L.history===!0)}catch(p){r||g(`卡片目录拉取失败:${p.message}`)}})(),()=>{r=!0,f()}},[]);let E=U((r,f,p)=>{let c=ne(f);if(c.type==="openLink"){window.open(c.url,"_blank");return}if(c.type==="sendMessage"){y(K(c.value));return}if(c.type==="submitFormUnsupported"){y(q);return}if(c.type==="ignored")return;let A=Object.entries(x.current).find(([,R])=>R.payload.id===r),_=A?.[1];if(!A||!_||f.type!=="moduleAction"||I.current.has(r))return;I.current.add(r);let z=O.current;fetch("/_tbox/api/card-action",{method:"POST",headers:{"Content-Type":"application/json",...z?{Authorization:`Bearer ${z}`}:{}},body:JSON.stringify({cardType:_.card.cardType,actionId:f.actionId,surfaceId:r,...p!==void 0?{input:p}:{}})}).then(async R=>{let h=await R.json().catch(()=>null);if(!R.ok||!h||h.ok===!1){y(h?.error??ae(R.status));return}let ue=h,j=x.current,W=oe(j,A[0],r,ue,ge=>F.current?.cards.find(ye=>ye.cardType===ge));W!==j&&(x.current=W,b(W)),typeof h.text=="string"&&h.text&&y(h.text),Array.isArray(h.effects)&&h.effects.length>0&&y(Z(h.effects.length))}).catch(R=>y(`动作请求失败:${R.message}`)).finally(()=>I.current.delete(r))},[y]),a=k(E);a.current=E;let M=ie(()=>n?G(n,{module:w==="all"?void 0:w}):null,[n,w]),ce=U((r,f)=>{let p=x.current[r];if(!p)return;let c=le(p.card,f,p.card.samples.length+ ++D.current);c&&(x.current={...x.current,[r]:c},b(x.current))},[]),pe=U(r=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText){y("当前浏览器不支持复制");return}navigator.clipboard.writeText(r).then(()=>y(`已复制卡片 ID:${r}`)).catch(()=>y("复制失败,请手动复制"))},[y]);return u("div",{style:{minHeight:"100vh",background:"#f5f5f5",fontFamily:'-apple-system, "PingFang SC", sans-serif'},children:[V&&u("header",{style:Oe,children:[s("strong",{style:{fontSize:14,color:"#262626"},children:ke}),u("select",{"aria-label":"模块",style:ze,value:w,onChange:r=>m(r.target.value),children:[s("option",{value:"all",children:Ee}),(M?.modules??[]).map(r=>s("option",{value:r,children:r},r))]}),s("button",{type:"button",style:P?Fe:de,onClick:()=>d(r=>!r),children:Le})]}),u("main",{style:{maxWidth:1200,margin:"0 auto",padding:"12px 12px 48px"},children:[v&&s("div",{style:tt,children:v}),!v&&!n&&s("div",{style:N,children:"加载中…"}),n&&l&&s("div",{style:N,children:Pe}),n&&!l&&n.cards.length===0&&s("div",{style:N,children:Ae}),n&&!l&&n.cards.length>0&&M&&M.candidateCards.length===0&&s("div",{style:N,children:Ie(M.moduleId)}),n&&!l&&M&&s(_e,{cards:M.candidateCards,rows:S,registry:t,historyView:P,onSelectSample:ce,onCopyCardType:pe,onAction:E})]}),s("div",{style:{position:"fixed",right:16,bottom:24,display:"flex",flexDirection:"column",gap:8,zIndex:20},children:T.map(r=>s("div",{style:ot,children:r.text},r.id))})]})}function Me(e,t,o){let l={};for(let n of e){let i=le(n,n.cardType===t?o:void 0);i&&(l[n.cardType]=i)}return l}function _e(e){let{cards:t,rows:o,registry:l,historyView:n,onSelectSample:i,onCopyCardType:v,onAction:g}=e,w=t.filter(m=>o[m.cardType]);return s("div",{style:Ne,children:w.map((m,P)=>{let d=o[m.cardType];return s(He,{instance:d,isLast:P===w.length-1,registry:l,historyView:n,samples:d.card.samples,activeSampleLabel:d.sample.label,onSelectSample:S=>i(m.cardType,S),onCopyCardType:v,onAction:g},m.cardType)})})}function He(e){let{instance:t,isLast:o,registry:l,historyView:n,samples:i,activeSampleLabel:v,onSelectSample:g,onCopyCardType:w,onAction:m}=e,P=n?{...t.payload,isHistory:!0}:t.payload,d=Math.max(0,i.findIndex(a=>a.label===v)),S=i[d]??t.sample,b=i[d-1],T=i[d+1],H=re(),O=re(),[I,x]=C(null),[F,B]=C(!1),[D,L]=C(!1),[V,y]=C(!1),E=a=>{x(a.getBoundingClientRect().top<80?"bottom":"top")};return u("section",{style:o?Ue:Be,children:[u("header",{style:De,children:[s("div",{style:Ve,children:t.card.displayName}),u("span",{style:We,children:[u("button",{type:"button","aria-label":`复制卡片 ID:${t.card.cardType}`,"aria-describedby":I?H:void 0,style:$e,onMouseEnter:a=>E(a.currentTarget),onMouseLeave:()=>x(null),onFocus:a=>E(a.currentTarget),onBlur:()=>x(null),onClick:()=>w(t.card.cardType),children:[s(he,{size:14,"aria-hidden":"true"}),"复制卡片 ID"]}),I&&u("span",{id:H,role:"tooltip",style:Ge(I),children:[s("span",{style:{display:"block"},children:"复制卡片 ID"}),s("span",{style:{display:"block"},children:"用于定位卡片配置和代码"}),s("span",{style:je(I)})]})]})]}),i.length>0&&u("div",{style:Je,children:[u("label",{htmlFor:O,style:Xe,children:["展示状态(",u("span",{"aria-live":"polite",children:[d+1,"/",i.length]}),"):"]}),u("span",{style:qe(F),children:[s("span",{style:Ke,children:S.label}),s(we,{size:12,"aria-hidden":"true",style:Qe}),s("select",{id:O,style:Ze,value:S.label,onChange:a=>g(a.target.value),onFocus:()=>B(!0),onBlur:()=>B(!1),children:i.map(a=>u("option",{value:a.label,children:[a.issues?.length||a.envelopeError?"⚠ ":"",a.label]},a.label))})]})]}),(t.sample.issues?.length||t.sample.envelopeError)&&u("div",{style:Ye,children:[t.sample.issues?.length?`样本问题:${t.sample.issues.join(";")}`:null,t.sample.envelopeError&&t.sample.issues?.length?";":"",t.sample.envelopeError??""]}),u("div",{role:"group","aria-label":`${t.card.displayName}卡片预览`,tabIndex:0,style:et,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),onFocusCapture:()=>y(!0),onBlurCapture:a=>{a.currentTarget.contains(a.relatedTarget)||y(!1)},onKeyDown:a=>{a.target===a.currentTarget&&(a.key==="ArrowLeft"&&b?(a.preventDefault(),g(b.label)):a.key==="ArrowRight"&&T&&(a.preventDefault(),g(T.label)))},children:[s(Ce,{card:P,registry:l,onAction:a=>m(P.id,a)}),(D||V)&&i.length>1&&u(nt,{children:[s("button",{type:"button","aria-label":"卡片区域:上一个样本",title:"上一个样本",disabled:!b,onClick:()=>b&&g(b.label),style:se("left",!b),children:s(Se,{size:18,"aria-hidden":"true"})}),s("button",{type:"button","aria-label":"卡片区域:下一个样本",title:"下一个样本",disabled:!T,onClick:()=>T&&g(T.label),style:se("right",!T),children:s(Te,{size:18,"aria-hidden":"true"})})]})]})]})}var Oe={position:"sticky",top:0,zIndex:10,display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"10px 16px",background:"#fff",borderBottom:"1px solid #e8e8e8"},ze={fontSize:13,padding:"4px 8px",borderRadius:8,border:"1px solid #d9d9d9",background:"#fff",color:"#262626"},de={fontSize:13,padding:"4px 12px",borderRadius:18,border:"1px solid #d9d9d9",background:"#fff",color:"#262626",cursor:"pointer"},Fe={...de,borderColor:"#1677ff",color:"#1677ff"},Be={minWidth:0,paddingBottom:16,borderBottom:"1px solid #e8e8e8"},Ue={minWidth:0},Ne={display:"flex",flexDirection:"column",gap:16},De={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:8},Ve={flex:"1 1 auto",minWidth:0,color:"#262626",fontSize:14,fontWeight:600,lineHeight:"22px"},We={position:"relative",display:"inline-flex",flex:"0 0 auto"},$e={display:"inline-flex",alignItems:"center",gap:4,flex:"0 0 auto",minHeight:28,padding:"4px 0",border:0,background:"transparent",color:"#222dd9",fontSize:12,lineHeight:"20px",whiteSpace:"nowrap",cursor:"pointer"},Ge=e=>({position:"absolute",right:0,...e==="top"?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"},zIndex:10,width:184,maxWidth:"calc(100vw - 24px)",padding:"6px 8px",borderRadius:4,background:"#303030",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.18)",color:"#fff",fontSize:12,fontWeight:400,lineHeight:"18px",textAlign:"left",whiteSpace:"normal",pointerEvents:"none"}),je=e=>({position:"absolute",right:36,...e==="top"?{bottom:-4}:{top:-4},width:8,height:8,background:"#303030",transform:"rotate(45deg)"}),Ye={fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:"rgba(250,140,22,0.10)",color:"#d46b08",marginBottom:8},Je={display:"flex",alignItems:"center",gap:6,minHeight:28,marginBottom:10},Xe={flex:"0 0 auto",color:"#595959",fontSize:12,lineHeight:"20px"},qe=e=>({position:"relative",display:"inline-flex",alignItems:"center",gap:4,flex:"0 1 auto",minWidth:0,color:"#262626",fontSize:12,lineHeight:"20px",borderRadius:2,outline:e?"2px solid #222dd9":"none",outlineOffset:2}),Ke={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Ze={position:"absolute",inset:0,width:"100%",height:"100%",padding:0,border:0,appearance:"none",opacity:0,cursor:"pointer"},Qe={flex:"0 0 auto",color:"#8c8c8c",pointerEvents:"none"},et={position:"relative",minWidth:0},se=(e,t)=>({position:"absolute",top:"50%",[e]:8,zIndex:2,display:"grid",placeItems:"center",width:36,height:36,padding:0,border:"1px solid #e5e5e5",borderRadius:"50%",background:"#fff",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.16)",color:t?"#bfbfbf":"#262626",transform:"translateY(-50%)",cursor:t?"not-allowed":"pointer"}),tt={padding:"12px 14px",borderRadius:8,background:"rgba(255,77,79,0.08)",color:"#ff4d4f",fontSize:13,lineHeight:"20px"},N={padding:"12px 14px",borderRadius:8,background:"#fff",color:"#8c8c8c",fontSize:13,lineHeight:"20px",textAlign:"center"},ot={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{Pe as a,Ae as b,Ie as c,Re as d,ae as e,ke as f,Le as g,Ee as h,ct as i,Me as j,_e as k,He as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as P,e as O,g as $}from"./chunk-2A3TBRT4.js";import{createClientLogger as L}from"@tbox.cn/app-sdk-client";var T=L("ACTION"),U=0;function N(t){return`${t}_${Date.now()}_${U++}_${Math.random().toString(36).slice(2,8)}`}var b=null;function v(t){b=t}async function J(t,a,r={}){let s=r.baseUrl??"",l={action:t,payload:a,...r.sessionId&&{sessionId:r.sessionId},...r.idempotencyKey&&{idempotencyKey:r.idempotencyKey}},g=l.idempotencyKey?l:{...l,idempotencyKey:N(t)},A=r.token??(b?b():null),h={"Content-Type":"application/json"};A&&(h.Authorization=`Bearer ${A}`);let o;try{o=await fetch(`${s}/api/action`,{method:"POST",headers:h,body:JSON.stringify(g)})}catch(p){let k=p?.message||"网络错误";return T.warn(`POST /api/action action=${t} fetch 异常:${k}`),{success:!1,error:k}}let c;try{c=await o.json()}catch{return T.warn(`POST /api/action action=${t} 响应解析失败(HTTP ${o.status})`),{success:!1,error:`响应解析失败(HTTP ${o.status})`}}return o.status===409?(T.warn(`POST /api/action action=${t} 幂等键冲突:${c.error||"请勿重复提交"}`),{success:!1,error:c.error||"幂等键冲突:请勿重复提交",cached:!1}):o.status===200&&c.cached?{...c,cached:!0}:c}import{isInAlipayShell as j}from"@tbox.cn/app-sdk-client";import{getAuthCode as B}from"@tbox.cn/app-sdk-client";import{httpPost as _,httpGet as M,configureAuthToken as Y,configureAuthErrorHandler as z}from"@tbox.cn/app-sdk-client";import{createClientLogger as D}from"@tbox.cn/app-sdk-client";var i=D("AUTH");function x(t){if(typeof t!="object"||t===null)return!1;let{userId:a,source:r}=t;return typeof a=="string"&&a.length>0&&(r==="local"||r==="external"||r==="guest")}var y="tbox.auth.token",E="tbox.auth.scopeKey",I="tbox.auth.lastToken",S=null,w=null;function W(t={}){let a=t.loginPlatform??"alipay";return S?(w&&w.loginPlatform!==a&&i.warn(`createAuthClient 重复调用且选项不同(当前 ${w.loginPlatform} vs ${a}),返回首建单例(首建选项生效)`),S):(S=q({loginPlatform:a,...t.scopeKey?{scopeKey:t.scopeKey}:{}}),w={loginPlatform:a},S)}function ot(){return S??W()}function q(t={}){let a=t.loginPlatform??"alipay",r=t.scopeKey,s=null,l=null,g=null;function A(e){try{return typeof localStorage<"u"?localStorage.getItem(e):null}catch{return null}}function h(e,m){try{typeof localStorage<"u"&&localStorage.setItem(e,m)}catch{}}function o(e){try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}}async function c(){return s||l||(l=G().then(e=>(l=null,e),e=>{throw l=null,e}),l)}async function p(){return g||(s=null,g=c().finally(()=>{g=null}),g)}function k(){s=null,l=null,o(y)}function R(){return s}async function G(){if(r){let n;try{n=r()}catch{n=""}A(E)!==n&&(o(y),o(I)),h(E,n)}let e=A(y);if(e)try{let{status:n,data:d}=await M("/api/auth/me",{cache:"no-store",headers:{Authorization:`Bearer ${e}`}});if(n===200&&x(d?.identity))return i.info("identity from cached token:",d.identity.userId),C({token:e,identity:d.identity});i.warn("cached token invalid (status=%s), re-login",n),o(y)}catch(n){i.warn("/api/auth/me failed, re-login:",n.message),o(y)}let m=A(I);if(j()){i.info("alipay shell, starting getAuthCode login...");try{let{authCode:n}=await B(["auth_base"]),d=P(),{status:u,data:f}=await _("/api/auth/login",{method:"code",code:n,platform:a,...d?{context:d}:{},...m?{previousToken:m}:{}});if(u===200&&f?.token&&x(f?.identity))return h(y,f.token),h(I,f.token),i.info("identity via alipay login:",f.identity.userId),C({token:f.token,identity:f.identity});i.warn("alipay login failed: status=%s error=%s",u,f?.error??"(no body)")}catch(n){i.error("alipay login error:",n)}return K()}try{let n=P(),{status:d,data:u}=await _("/api/auth/login",{method:"browser",...n?{context:n}:{},...m?{previousToken:m}:{}});if(d===200&&u?.token&&x(u?.identity))return h(y,u.token),h(I,u.token),i.info("identity via browser login:",u.identity.userId),C({token:u.token,identity:u.identity});i.warn("browser login unavailable: status=%s error=%s(403 = 服务端 browserLoginMode 关闭或生产禁 mock)",d,u?.error??"(no body)")}catch(n){i.warn("browser login error:",n.message)}return K()}function K(){let e={userId:`anonymous_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"};return i.warn("fallback to anonymous:",e.userId),C({token:null,identity:e})}function C(e){return s=e,Y(()=>s?.token??null),O(()=>s?.token??null),v(()=>s?.token??null),z(()=>p()),$(()=>p()),e}async function H(){return(await c()).identity.userId}return{ensureAuth:c,refreshAuth:p,clearAuth:k,getAuthState:R,resolveUserId:H}}export{v as a,J as b,W as c,ot as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as x}from"./chunk-6VLQT22V.js";import{createContext as R,useContext as d}from"react";import{jsx as A}from"react/jsx-runtime";var p=R({});function L({value:o,children:e}){return A(p.Provider,{value:o,children:e})}var X=()=>d(p),H=()=>d(p).asr,N=()=>d(p).tts,O=()=>d(p).upload,$=()=>d(p).feedback,z=()=>d(p).refreshSession;import{httpPost as k}from"@tbox.cn/app-sdk-client";function l(o){return{"X-Tbox-Session-Id":o.tboxSessionId,"X-Tbox-Channel":o.channel,"X-Tbox-AppId":o.appId}}var c=class{constructor(e){this.session=e}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let e=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=e,this.audioChunks=[];let t=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",i=new MediaRecorder(e,{mimeType:t});this.mediaRecorder=i,i.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},i.start()}stopRecording(){return new Promise((e,t)=>{let i=this.mediaRecorder;if(!i||i.state==="inactive"){this.cleanup(),e("");return}i.onstop=async()=>{if(this.cancelled){this.cleanup(),e("");return}try{let s=new Blob(this.audioChunks,{type:i.mimeType}),a=await this.blobToBase64(s),{status:r,data:n}=await k("/api/tbox/asr",{base64_audio:a,audio_format:"webm",sample_rate:"16000"},{headers:l(this.session)});e(r===200&&n?.text?n.text:"")}catch(s){t(s)}finally{this.cleanup()}},i.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(e){return new Promise((t,i)=>{let s=new FileReader;s.onloadend=()=>t(s.result.split(",")[1]||""),s.onerror=i,s.readAsDataURL(e)})}cleanup(){this.mediaStream?.getTracks().forEach(e=>e.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as S}from"@tbox.cn/app-sdk-client";import{httpPost as C}from"@tbox.cn/app-sdk-client";var u=class{constructor(e){this.session=e}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await S("startRecord",{},"invoke")}async stopRecording(){let e=await S("stopRecord",{},"invoke");if(this.cancelled)return"";let t=e?.audioBase64;if(!t)return"";let{status:i,data:s}=await C("/api/tbox/asr",{base64_audio:t,audio_format:e.format||"mp3",sample_rate:"16000"},{headers:l(this.session)});return i===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,S("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as P}from"@tbox.cn/app-sdk-client";var w=P("asr"),h=class{bridge;browser;active;constructor(e){this.bridge=new u(e),this.browser=new c(e),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(e){w.warn("桥录音失败,降级到 H5 getUserMedia:",e),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as I}from"@tbox.cn/app-sdk-client";var m=class{constructor(e){this.session=e}session;onProgress;async upload(e,t){let i;typeof e=="string"?i=await(await fetch(e)).blob():i=e;let{status:s,data:a}=await I("/api/tbox/upload",i,{headers:{"Content-Type":i.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":t?.type||"file",...t?.name?{"X-Tbox-File-Name":encodeURIComponent(t.name)}:{}}});if(s!==200||!a?.fileId)throw new Error(`[tbox-upload] ${a?.errorCode??`HTTP_${s}`} ${a?.error??""}`.trim());return{fileId:a.fileId,url:"",mimeType:typeof a.fileType=="string"?a.fileType:void 0,safed:a.safed}}};import{httpPost as E}from"@tbox.cn/app-sdk-client";var f=class{constructor(e){this.session=e}session;async addTag(e,t){let{status:i,data:s}=await E("/api/tbox/feedback",{requestId:e,feedback:t},{headers:l(this.session)});return{success:i===200&&!!s?.success}}};var b=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(e){this.sampleRate=e.sampleRate,this.onPlayEnd=e.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(e){if(this.isStopped||!this.audioContext)return;let t=new Int16Array(e);if(t.length===0)return;let i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=t[n]/32768;let s=this.audioContext.createBuffer(1,i.length,this.sampleRate);s.getChannelData(0).set(i);let a=this.audioContext.createBufferSource();a.buffer=s,a.connect(this.audioContext.destination);let r=this.audioContext.currentTime;this.nextStartTime<r&&(this.nextStartTime=r),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,a.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 e=this.nextStartTime-this.audioContext.currentTime,t=Math.max(0,e*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},t)}}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 _}from"@tbox.cn/app-sdk-client";import{createClientLogger as F}from"@tbox.cn/app-sdk-client";var T=F("TTS"),g=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(e){return this.stop(),new Promise(t=>{this.speakResolve=t,this.startStreaming().then(()=>{this.sendText(e),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(e){return this.stateCallbacks.add(e),this._state!=="idle"&&e(this._state),()=>this.stateCallbacks.delete(e)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new b({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let e=_("/ws/tts"),t=x(),i=t?`${e}?token=${encodeURIComponent(t)}`:e;return new Promise((s,a)=>{let r=new WebSocket(i);r.binaryType="arraybuffer",this.socket=r,r.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},r.onmessage=n=>this.handleMessage(n.data),r.onclose=()=>{this.socket=null,this.player?.finish()},r.onerror=n=>{T.error("socket error",n),a(n),this.stop()}})}sendText(e){e&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:e}):this.pending+=e)}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(e){if(typeof e=="string"){try{let t=JSON.parse(e);switch(t.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":T.error("server error",t.error||t),this.stop();break}}catch{if(!this.player||e.length===0)return;this._state==="loading"&&this.setState("playing");let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);this.player.input(t)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(e))}sendMessage(e){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(e){this._state!==e&&(this._state=e,this.stateCallbacks.forEach(t=>t(e)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as D,isInAlipayShell as M}from"@tbox.cn/app-sdk-client";function Te(o,e){let t={};return e?.tts||(t.tts=new g),o&&(t.asr=M()||D()?new h(o):new c(o),t.upload=new m(o),t.feedback=new f(o)),e?{...t,...e}:t}import{httpGet as v}from"@tbox.cn/app-sdk-client";function U(){let o=null;async function e(s=!1){if(o&&!s)return o;o=null;let{status:a,data:r}=await v("/api/tbox/session",{cache:"no-store"});if(a!==200)throw new Error(`[tbox-session] fetch failed: ${a}`);return o=r,o}function t(){o=null}async function i(s){let a=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(a+=`&beforeId=${encodeURIComponent(s.beforeId)}`),v(a,{cache:"no-store"})}return{getTboxSession:e,clearTboxSession:t,listMessages:i}}var y=null;function Ae(){return y??=U(),y}function ke(){y=null}export{L as a,X as b,H as c,N as d,O as e,$ as f,z as g,c as h,u as i,h as j,m as k,f as l,b as m,g as n,Te as o,U as p,Ae as q,ke as r};
|
|
1
|
+
import{f as x}from"./chunk-2A3TBRT4.js";import{createContext as R,useContext as d}from"react";import{jsx as A}from"react/jsx-runtime";var p=R({});function L({value:o,children:e}){return A(p.Provider,{value:o,children:e})}var X=()=>d(p),H=()=>d(p).asr,N=()=>d(p).tts,O=()=>d(p).upload,$=()=>d(p).feedback,z=()=>d(p).refreshSession;import{httpPost as k}from"@tbox.cn/app-sdk-client";function l(o){return{"X-Tbox-Session-Id":o.tboxSessionId,"X-Tbox-Channel":o.channel,"X-Tbox-AppId":o.appId}}var c=class{constructor(e){this.session=e}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let e=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=e,this.audioChunks=[];let t=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",i=new MediaRecorder(e,{mimeType:t});this.mediaRecorder=i,i.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},i.start()}stopRecording(){return new Promise((e,t)=>{let i=this.mediaRecorder;if(!i||i.state==="inactive"){this.cleanup(),e("");return}i.onstop=async()=>{if(this.cancelled){this.cleanup(),e("");return}try{let s=new Blob(this.audioChunks,{type:i.mimeType}),a=await this.blobToBase64(s),{status:r,data:n}=await k("/api/tbox/asr",{base64_audio:a,audio_format:"webm",sample_rate:"16000"},{headers:l(this.session)});e(r===200&&n?.text?n.text:"")}catch(s){t(s)}finally{this.cleanup()}},i.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(e){return new Promise((t,i)=>{let s=new FileReader;s.onloadend=()=>t(s.result.split(",")[1]||""),s.onerror=i,s.readAsDataURL(e)})}cleanup(){this.mediaStream?.getTracks().forEach(e=>e.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as S}from"@tbox.cn/app-sdk-client";import{httpPost as C}from"@tbox.cn/app-sdk-client";var u=class{constructor(e){this.session=e}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await S("startRecord",{},"invoke")}async stopRecording(){let e=await S("stopRecord",{},"invoke");if(this.cancelled)return"";let t=e?.audioBase64;if(!t)return"";let{status:i,data:s}=await C("/api/tbox/asr",{base64_audio:t,audio_format:e.format||"mp3",sample_rate:"16000"},{headers:l(this.session)});return i===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,S("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as P}from"@tbox.cn/app-sdk-client";var w=P("asr"),h=class{bridge;browser;active;constructor(e){this.bridge=new u(e),this.browser=new c(e),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(e){w.warn("桥录音失败,降级到 H5 getUserMedia:",e),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as I}from"@tbox.cn/app-sdk-client";var m=class{constructor(e){this.session=e}session;onProgress;async upload(e,t){let i;typeof e=="string"?i=await(await fetch(e)).blob():i=e;let{status:s,data:a}=await I("/api/tbox/upload",i,{headers:{"Content-Type":i.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":t?.type||"file",...t?.name?{"X-Tbox-File-Name":encodeURIComponent(t.name)}:{}}});if(s!==200||!a?.fileId)throw new Error(`[tbox-upload] ${a?.errorCode??`HTTP_${s}`} ${a?.error??""}`.trim());return{fileId:a.fileId,url:"",mimeType:typeof a.fileType=="string"?a.fileType:void 0,safed:a.safed}}};import{httpPost as E}from"@tbox.cn/app-sdk-client";var f=class{constructor(e){this.session=e}session;async addTag(e,t){let{status:i,data:s}=await E("/api/tbox/feedback",{requestId:e,feedback:t},{headers:l(this.session)});return{success:i===200&&!!s?.success}}};var b=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(e){this.sampleRate=e.sampleRate,this.onPlayEnd=e.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(e){if(this.isStopped||!this.audioContext)return;let t=new Int16Array(e);if(t.length===0)return;let i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=t[n]/32768;let s=this.audioContext.createBuffer(1,i.length,this.sampleRate);s.getChannelData(0).set(i);let a=this.audioContext.createBufferSource();a.buffer=s,a.connect(this.audioContext.destination);let r=this.audioContext.currentTime;this.nextStartTime<r&&(this.nextStartTime=r),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,a.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 e=this.nextStartTime-this.audioContext.currentTime,t=Math.max(0,e*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},t)}}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 _}from"@tbox.cn/app-sdk-client";import{createClientLogger as F}from"@tbox.cn/app-sdk-client";var T=F("TTS"),g=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(e){return this.stop(),new Promise(t=>{this.speakResolve=t,this.startStreaming().then(()=>{this.sendText(e),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(e){return this.stateCallbacks.add(e),this._state!=="idle"&&e(this._state),()=>this.stateCallbacks.delete(e)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new b({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let e=_("/ws/tts"),t=x(),i=t?`${e}?token=${encodeURIComponent(t)}`:e;return new Promise((s,a)=>{let r=new WebSocket(i);r.binaryType="arraybuffer",this.socket=r,r.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},r.onmessage=n=>this.handleMessage(n.data),r.onclose=()=>{this.socket=null,this.player?.finish()},r.onerror=n=>{T.error("socket error",n),a(n),this.stop()}})}sendText(e){e&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:e}):this.pending+=e)}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(e){if(typeof e=="string"){try{let t=JSON.parse(e);switch(t.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":T.error("server error",t.error||t),this.stop();break}}catch{if(!this.player||e.length===0)return;this._state==="loading"&&this.setState("playing");let t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);this.player.input(t)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(e))}sendMessage(e){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(e){this._state!==e&&(this._state=e,this.stateCallbacks.forEach(t=>t(e)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as D,isInAlipayShell as M}from"@tbox.cn/app-sdk-client";function Te(o,e){let t={};return e?.tts||(t.tts=new g),o&&(t.asr=M()||D()?new h(o):new c(o),t.upload=new m(o),t.feedback=new f(o)),e?{...t,...e}:t}import{httpGet as v}from"@tbox.cn/app-sdk-client";function U(){let o=null;async function e(s=!1){if(o&&!s)return o;o=null;let{status:a,data:r}=await v("/api/tbox/session",{cache:"no-store"});if(a!==200)throw new Error(`[tbox-session] fetch failed: ${a}`);return o=r,o}function t(){o=null}async function i(s){let a=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(a+=`&beforeId=${encodeURIComponent(s.beforeId)}`),v(a,{cache:"no-store"})}return{getTboxSession:e,clearTboxSession:t,listMessages:i}}var y=null;function Ae(){return y??=U(),y}function ke(){y=null}export{L as a,X as b,H as c,N as d,O as e,$ as f,z as g,c as h,u as i,h as j,m as k,f as l,b as m,g as n,Te as o,U as p,Ae as q,ke as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as K,d as j,f as V,h as W,i as z,j as k,k as H,m as X}from"./chunk-2A3TBRT4.js";function J(t){return function(s,a,l){if(t.blockAll?.(s)===!0)return{status:"rejected",reason:"generating"};switch(a.type){case"sendMessage":case"submitForm":case"moduleAction":return t.canAct?.(s)===!1?{status:"rejected",reason:t.rejectReason?.(s)??"generating"}:t.sendToServer(s,a,l);case"openLink":return a.url&&t.openUrl?.(a.url),{status:"local"};case"toast":return a.content&&t.toast?.(a.content,a.tone),{status:"local"};case"closeCard":return t.closeCard?.(s),{status:"local"};default:return{status:"local"}}}}import{createClientLogger as ke}from"@tbox.cn/app-sdk-client";var Ee=ke("CARD");function Y(t,r){let s=a=>a.some(l=>l.id===r.id)?a.map(l=>l.id===r.id?r:l):[...a,r];return r.messageId?{...t,cardsByMessageId:{...t.cardsByMessageId,[r.messageId]:s(t.cardsByMessageId[r.messageId]||[])}}:{...t,orphanCards:s(t.orphanCards)}}function rt(t,r){let s={};for(let[a,l]of Object.entries(t.cardsByMessageId))s[a]=l.filter(i=>i.id!==r);return{cardsByMessageId:s,orphanCards:t.orphanCards.filter(a=>a.id!==r)}}function Q(t,r){let s=l=>{let i=l.findIndex(C=>C.id===r.id);if(i<0)return null;let f=[...l];return f[i]={...r,messageId:l[i].messageId,isHistory:l[i].isHistory,meta:{...l[i].meta,...r.meta,createdAt:l[i].meta?.createdAt??r.meta?.createdAt??Date.now(),...l[i].meta?.businessNo!==void 0?{businessNo:l[i].meta.businessNo}:{}}},f};for(let[l,i]of Object.entries(t.cardsByMessageId)){let f=s(i);if(f)return{...t,cardsByMessageId:{...t.cardsByMessageId,[l]:f}}}let a=s(t.orphanCards);return a?{...t,orphanCards:a}:(Ee.warn(`update 未命中卡实例:${r.id}(已隐藏/清空或非本连接下发)`),t)}import{TBOX_EFFECT_EVENT_NAME as at}from"@tbox.cn/app-contracts";import{requestPayment as Te}from"@tbox.cn/app-sdk-client";import{getAuthCode as Me}from"@tbox.cn/app-sdk-client";import{createClientLogger as Re}from"@tbox.cn/app-sdk-client";var B=Re("tbox:effect");function ee(t){if(t===null||typeof t!="object")return!1;let r=t;return typeof r.type=="string"&&r.type.length>0}function te(){let t=new Set;return r=>{let s=r.callback?.contextToken;return s?t.has(s)?!1:(t.add(s),!0):!0}}function se(t){return t!==null&&typeof t=="object"&&typeof t.code=="string"?String(t.code):"BRIDGE_ERROR"}function re(t){return se(t)==="BRIDGE_UNAVAILABLE"}function xe(t){return t==="9000"?"success":t==="6001"?"cancel":"failure"}async function we(t,r){try{let s=await r.requestPayment(t.orderInfo);return{status:xe(s.resultCode),paymentRef:t.paymentRef}}catch(s){return{status:re(s)?"unavailable":"failure",paymentRef:t.paymentRef}}}async function Pe(t,r){try{let s=await r.getAuthCode([...t.scopes]);return typeof s.authCode!="string"||!s.authCode.trim()?{status:"failure"}:{status:"success",authCode:s.authCode}}catch(s){let a=se(s);return re(s)?{status:"unavailable"}:a.includes("CANCEL")?{status:"cancel"}:{status:"failure"}}}function Z(t,r,s){if(t.callback)try{s({actionId:t.callback.actionId,contextToken:t.callback.contextToken,formData:{...r}})}catch(a){B.warn("结果回传失败:",a?.message)}}function oe(t){let r={requestPayment:t?.requestPayment??Te,getAuthCode:t?.getAuthCode??Me,sendModuleAction:t?.sendModuleAction??(()=>{B.warn("未注入 sendModuleAction,结果未回传")}),onSessionCredentialsRefreshed:t?.onSessionCredentialsRefreshed};return s=>{switch(s.type){case"payment":{we(s,r).then(a=>Z(s,a,r.sendModuleAction));return}case"authorization.alipay-user-profile":{Pe(s,r).then(a=>Z(s,a,r.sendModuleAction));return}case"session.credentials-refreshed":{r.onSessionCredentialsRefreshed?.(s.reason);return}default:B.warn(`宿主效果类型未在客户端执行:${String(s.type)}`)}}}import{parseSkillReminders as ve,buildSkillToolCallPayload as De,SKILL_NAME_PATTERN as ne,SKILL_TOOL_CALL_NAME as He}from"@tbox.cn/app-contracts";function ae(t){let r=t.query??"",s=ve(r),a=new Map;for(let l of Array.isArray(t.skills)?t.skills:[])l?.name&&ne.test(l.name)&&a.set(l.name,l);for(let l of s.skills)a.has(l)||a.set(l,{name:l});return{content:s.cleanedText,skills:[...a.values()]}}function ie(t,r){return t.filter(s=>s&&ne.test(s.name)).map((s,a)=>{let{args:l,result:i}=De(s);return{id:`skill-${r}-${a}`,name:He,args:l,result:i,status:"done"}})}import{buildPreToolToolCallPayload as _e,PRE_TOOL_CALL_NAME as Ne,PRE_TOOL_NAME_PATTERN as de}from"@tbox.cn/app-contracts";function Ue(t){return(Array.isArray(t.preTools)?t.preTools:[]).filter(r=>r?.toolName&&de.test(r.toolName))}function Be(t){let r=ae(t);return{content:r.content,skills:r.skills,preTools:Ue(t)}}function Le(t,r){let s=[];return(Array.isArray(t)?t:[]).filter(a=>a&&de.test(a.toolName)).forEach((a,l)=>{try{let{args:i,result:f}=_e(a);s.push({id:`pretool-${r}-${l}`,name:Ne,args:i,result:f,status:"done"})}catch{}}),s}function Oe(t,r){return[...Le(t.preTools,r),...ie(t.skills,r)]}function qe(t){if(!t)return;let r=new Date(t.replace(" ","T")).getTime();return Number.isNaN(r)?void 0:r}function Ge(t,r){let s=t.messageId??t.id??t.outerBusinessId??`hist-${r}`,a=t.createTime??qe(t.requestTime)??Date.now();return{key:s,createdAt:a}}function le(t){let r=0,s=i=>`${i}_${Date.now()}_${r++}`,a=[],l={};return t.forEach((i,f)=>{let{key:C,createdAt:I}=Ge(i,f),T=Be(i);if(i.query){let A={id:`history-user-${C}`,role:"user",content:T.content,status:"done",createdAt:I,...i.outerBusinessId&&{requestId:i.outerBusinessId},...i.conversationId&&{conversationId:i.conversationId}},E=i.multiModalInputs?.imageUrls;E&&E.length>0&&(A.mediaItems=E.map(e=>({id:s("history-img"),type:"image",src:e}))),a.push(A)}(i.answer||i.content||i.cards&&i.cards.length>0)&&a.push({id:`history-asst-${C}`,role:"assistant",content:i.answer||i.content||"",status:"done",createdAt:I,...i.outerBusinessId&&{requestId:i.outerBusinessId},...i.conversationId&&{conversationId:i.conversationId},...T.skills.length>0||T.preTools.length>0?{toolCalls:Oe(T,C)}:{}}),i.cards&&i.cards.length>0&&(l[`history-asst-${C}`]=i.cards.map(A=>({...A,isHistory:!0})))}),{messages:a,cardsByMessageId:l}}import{TBOX_CARD_EVENT_NAME as fe,TBOX_CARD_UPDATE_EVENT_NAME as $e,TBOX_EFFECT_EVENT_NAME as Fe,TBOX_NOTICE_EVENT_NAME as pe,TBOX_ACTION_SETTLED_EVENT_NAME as Ke}from"@tbox.cn/app-contracts";function ue(t={}){let r=t.timeoutMs??8e3,s=new Map,a=(l,i)=>{let f=s.get(l);return f?(s.delete(l),clearTimeout(f.timer),f.resolve(i),!0):!1};return{begin({requestId:l,surfaceId:i,kind:f}){return new Promise(C=>{let I=setTimeout(()=>{a(l,{status:"timeout"}),t.onTimeout?.()},r);I.unref?.(),s.set(l,{surfaceId:i,kind:f,resolve:C,timer:I})})},byRequestId(l,i){return a(l,{status:"settled",outcome:i})},bySurface(l,i){let f=!1;for(let[C,I]of[...s])I.surfaceId===l&&(f=a(C,{status:"settled",outcome:i})||f);return f},byRunStarted(){for(let[l,i]of[...s])i.kind==="run"&&a(l,{status:"run-started"})},byRunFailed(){for(let[l,i]of[...s])i.kind==="run"&&a(l,{status:"settled",outcome:"error"})},settleAll(l="noop"){for(let i of[...s.keys()])a(i,{status:"settled",outcome:l})},byDisconnect(){this.settleAll("noop")},size(){return s.size}}}var ce=0;function _(){return ce+=1,`act_${Date.now().toString(36)}_${ce.toString(36)}`}import{createClientLogger as P,setClientRunContext as L}from"@tbox.cn/app-sdk-client";import{isInAlipayShell as je}from"@tbox.cn/app-sdk-client";import{callJsapi as ge}from"@tbox.cn/app-sdk-client";import{resolveAlipayNavigation as Ve}from"@tbox.cn/app-sdk-client";var M=P("tbox"),me="网络连接不可用,请稍后重试",ye=P("CONVERSATION"),We=P("SESSION-UPGRADE"),ze=P("HISTORY"),Ce=P("FEEDBACK");function Xe(t){let r=String(t?.message||t||"");return/过期|expired|PARAM_INVALID|unauthorized|token/i.test(r)}var w=0,O=!1,N=null,b=null,q=!1;function Je(t){let r=t.messageId??t.id??t.outerBusinessId;return r?`id:${r}`:`content:${t.requestTime??t.createTime??""}:${t.query??""}:${t.answer??t.content??""}`}var x;function wt(t,r,s){return x?x(t,r,s):(M.warn("卡动作通道未注册(应用 chat store 未创建),动作已丢弃"),{status:"rejected",reason:"no-channel"})}function Ye(t){let r=x;return x=t,()=>{x===t&&(x=r)}}var Qe=0,R=t=>`${t}_${Date.now()}_${Qe++}`;function Ze(t,r,s){r(a=>({...a,...Y({cardsByMessageId:a.cardsByMessageId,orphanCards:a.orphanCards},s)})),t.onCardEvent?.({type:"render",cardId:s.id,cardType:s.cardType,...s.messageId!==void 0?{messageId:s.messageId}:{},ts:Date.now()})}function et(t,r,s,a){let l={cardsByMessageId:s().cardsByMessageId,orphanCards:s().orphanCards},i=Q(l,a);i!==l&&(r(f=>({...f,...i})),t.onCardEvent?.({type:"update",cardId:a.id,cardType:a.cardType,...a.messageId!==void 0?{messageId:a.messageId}:{},ts:Date.now()}))}function he(t){k(t().conversationEstablished?{type:"RESUME_CONVERSATION"}:{type:"NEW_CONVERSATION"})}function vt(t,r,s){j(t.getWsUrl),W(e=>{f.byDisconnect(),r({authBlocked:e.message}),t.toast(e.message,"error")});let a=te(),l=oe({sendModuleAction:({actionId:e,contextToken:n,formData:o})=>{k({type:"UI_ACTION",surfaceId:"",action:{type:"moduleAction",actionId:e,contextToken:n},formData:o})},...t.onSessionCredentialsRefreshed?{onSessionCredentialsRefreshed:t.onSessionCredentialsRefreshed}:{}}),i=t.onHostEffect??l,f=ue({onTimeout:()=>t.toast("操作可能未完成,可重试","info")}),C=()=>Array.isArray(s().helloAck?.features)&&s().helloAck?.features?.includes("action-settled")===!0,I=e=>{let{cardsByMessageId:n,orphanCards:o}=s();return[...Object.values(n).flat(),...o].find(c=>c.id===e)},T=J({canAct:e=>{if(s().isGenerating)return!1;let n=I(e);return!(n&&n.isHistory)},rejectReason:e=>{let n=I(e);return n&&n.isHistory?"history":"generating"},sendToServer:(e,n,o)=>{if(!H()){let g=I(e);return t.onCardEvent?.({type:"click",cardId:e,cardType:g?.cardType??"",ts:Date.now()}),t.toast(me,"error"),{status:"rejected",reason:"offline"}}let{addMessage:d}=s(),c=I(e);if(t.onCardEvent?.({type:"click",cardId:e,cardType:c?.cardType??"",ts:Date.now()}),n.type==="sendMessage"){n.visible!==!1&&d({id:R("user"),role:"user",content:n.displayText??n.value,status:"done",createdAt:Date.now()});let g=_(),m=f.begin({requestId:g,surfaceId:e,kind:"run"});return k({type:"UI_ACTION",surfaceId:e,action:n,requestId:g}),A=!0,{status:"sent",requestId:g,settled:m}}if(n.type==="submitForm"){let g=_(),m=f.begin({requestId:g,surfaceId:e,kind:"run"});return k({type:"UI_ACTION",surfaceId:e,action:n,formData:o??{},requestId:g}),A=!0,{status:"sent",requestId:g,settled:m}}let u=_(),p=f.begin({requestId:u,surfaceId:e,kind:"module"});return k({type:"UI_ACTION",surfaceId:e,action:n,formData:o??{},requestId:u}),{status:"sent",requestId:u,settled:p}},toast:(e,n)=>t.toast(e,n),openUrl:e=>{if(!(typeof window>"u")){if(e.startsWith("tel:")){window.location.href=e;return}if(je()){if(e.startsWith("alipays://")||e.startsWith("alipayrisk://")){let n=Ve(e,s().helloAck?.mallScope?.miniAppId);n?(M.info(`[openUrl] ${n.apiName} url=${e}`),ge(n.apiName,n.params).catch(o=>{M.warn(`[openUrl] ${n.apiName} failed url=${e}`,o),t.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error")})):(M.warn(`[openUrl] unresolved Alipay deep link url=${e}`),t.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error"))}else M.info(`[openUrl] ap.openURL url=${e}`),ge("ap.openURL",{url:e}).catch(n=>{M.warn(`[openUrl] ap.openURL failed url=${e}`,n),t.toast("当前无法打开该链接,请稍后再试","error")});return}window.open&&window.open(e,"_blank")}},closeCard:e=>s().hideCard(e)});Ye((e,n,o)=>s().sendUiAction(e,n,o));let A=!1,E=()=>{if(!t.platformApi||!t.authClient)throw new Error("会话方法需要 platformApi/authClient(createCoreChatState deps 未注入)");return{platformApi:t.platformApi,authClient:t.authClient}};return{userId:"",helloAck:null,authBlocked:null,messages:[],isGenerating:!1,currentRunId:null,streamingMsgId:null,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[],init:()=>{z(e=>{let n=s();switch(e.type){case"HELLO_ACK":{r({helloAck:{...e.mallScope?{mallScope:e.mallScope}:{},chatConfig:e.chatConfig,...e.toolDebug?{toolDebug:!0}:{},...e.features?{features:e.features}:{}},authBlocked:null});break}case"RUN_STARTED":{if(!A)break;A=!1,f.byRunStarted();let o=R("thinking");n.addMessage({id:o,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({isGenerating:!0,currentRunId:e.runId,streamingMsgId:o}),L({runId:e.runId,...e.threadId&&{conversationId:e.threadId}});break}case"CUSTOM":{if(e.name===fe){let o=e.value;Ze(t,r,o),typeof window<"u"&&window.dispatchEvent(new CustomEvent(fe,{detail:o}))}else if(e.name===Ke){let o=e.value;o&&typeof o.requestId=="string"&&f.byRequestId(o.requestId,o.outcome)}else if(e.name===$e){let o=e.value;et(t,r,s,o),!C()&&o?.id&&f.bySurface(o.id,"updated")}else if(e.name===Fe&&ee(e.value))a(e.value)&&i(e.value);else if(e.name===pe){let o=e.value;o?.text&&t.toast(o.text,o.level??"info"),!C()&&o?.surfaceId&&f.bySurface(o.surfaceId,o.level==="error"?"error":"notice"),typeof window<"u"&&o?.text&&window.dispatchEvent(new CustomEvent(pe,{detail:o}))}break}case"REASONING_START":{if(!s().isGenerating)break;if(!s().streamingMsgId){let o=R("thinking");n.addMessage({id:o,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({streamingMsgId:o})}break}case"REASONING_MESSAGE_CONTENT":{let{streamingMsgId:o}=s();if(!o)break;r(d=>({messages:d.messages.map(c=>c.id===o?{...c,reasoning:(c.reasoning||"")+e.delta}:c)}));break}case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"TOOL_CALL_START":{if(!s().isGenerating)break;let{streamingMsgId:o}=s();if(!o){let d=R("thinking");n.addMessage({id:d,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({streamingMsgId:d}),o=d}r(d=>({messages:d.messages.map(c=>c.id===o?{...c,toolCalls:[...c.toolCalls||[],{id:e.toolCallId,name:e.toolCallName,status:"calling"}]}:c)}));break}case"TOOL_CALL_ARGS":{let{streamingMsgId:o}=s();if(!o)break;r(d=>({messages:d.messages.map(c=>c.id===o?{...c,toolCalls:(c.toolCalls||[]).map(u=>u.id===e.toolCallId?{...u,args:(u.args||"")+e.delta}:u)}:c)}));break}case"TOOL_CALL_END":break;case"TOOL_CALL_RESULT":{let{streamingMsgId:o}=s();if(!o)break;r(d=>({messages:d.messages.map(c=>c.id===o?{...c,toolCalls:(c.toolCalls||[]).map(u=>u.id===e.toolCallId?{...u,result:e.content,status:e.isError?"error":"done",...e.isError?{error:e.errorMessage??"工具执行失败"}:{}}:u)}:c)}));break}case"TEXT_MESSAGE_START":{if(!s().isGenerating)break;let o=e.messageId,{streamingMsgId:d}=s();d?.startsWith("thinking_")?r(c=>({streamingMsgId:o,messages:c.messages.map(u=>u.id===d?{...u,id:o,status:"streaming"}:u)})):(n.addMessage({id:o,role:"assistant",content:"",status:"streaming",createdAt:Date.now()}),r({streamingMsgId:o}));break}case"TEXT_MESSAGE_CONTENT":{let{streamingMsgId:o}=s();o&&e.messageId===o&&s().appendDelta(o,e.delta);break}case"TEXT_MESSAGE_END":{let{streamingMsgId:o}=s();o&&(n.updateMessage(o,{status:"done"}),r({streamingMsgId:null}));break}case"RUN_FINISHED":{if(e.runId&&e.runId!==s().currentRunId)break;let o=e.rawEvent?.requestId;r(o?d=>{let c=[...d.messages];for(let u=c.length-1;u>=0;u--)if(c[u].role==="assistant"&&c[u].status==="done"){c[u]={...c[u],requestId:o,...e.threadId&&{conversationId:e.threadId}};break}return{isGenerating:!1,currentRunId:null,messages:c}}:{isGenerating:!1,currentRunId:null});{let d=0,c=s().messages.map(u=>u.role!=="assistant"||!u.toolCalls?.some(p=>p.status==="calling")?u:(d+=u.toolCalls.filter(p=>p.status==="calling").length,{...u,toolCalls:u.toolCalls.map(p=>p.status==="calling"?{...p,status:"error",error:"工具执行未返回结果"}:p)}));d>0&&(r({messages:c}),M.warn(`RUN_FINISHED:${d} 个工具未收到终态事件,已收敛为失败态`))}L(null);break}case"RUN_ERROR":{if(f.byRunFailed(),!s().isGenerating&&!s().currentRunId)break;let o=e.runId;if(o&&o!==s().currentRunId)break;let d=s().streamingMsgId,c=e.message||"请求失败,请重试",u=e.rawEvent?.requestId??o??s().currentRunId??void 0,p=e.threadId;r(g=>{let m=d?g.messages.find(y=>y.id===d):void 0,h={...m??{id:R("error"),role:"assistant",content:"",createdAt:Date.now()},status:"error",error:c,...u&&{requestId:m?.requestId??u},...p&&{conversationId:m?.conversationId??p},toolCalls:m?.toolCalls?.map(y=>y.status==="calling"?{...y,status:"error",error:"请求中断"}:y)};return{isGenerating:!1,currentRunId:null,streamingMsgId:null,messages:m?g.messages.map(y=>y.id===m.id?h:y):[...g.messages,h]}}),L(null);break}}},()=>{let e=V(),n=K();k({type:"HELLO",...e?{token:e}:{},...n?{context:n}:{}}),he(s)})},sendMessage:e=>{let{addMessage:n,isGenerating:o}=s();if(o)return;if(!H()){t.toast(me,"error");return}let d=typeof e=="string"?e:e.text,c=typeof e=="string"?void 0:e.mediaItems,u=typeof e=="string"?void 0:e.inputMethod;n({id:R("user"),role:"user",content:d,status:"done",createdAt:Date.now(),mediaItems:c,inputMethod:u}),k({type:"SEND_MESSAGE",content:d,mediaItems:c?.filter(p=>p.fileId).map(p=>({fileId:p.fileId,type:p.type,name:p.name,mimeType:p.mimeType})),inputMethod:u}),A=!0},sendUiAction:(e,n,o)=>T(e,n,o),hideCard:e=>{r(n=>{let o={};for(let[d,c]of Object.entries(n.cardsByMessageId))o[d]=c.filter(u=>u.id!==e);return{cardsByMessageId:o,orphanCards:n.orphanCards.filter(d=>d.id!==e)}})},destroy:()=>{f.settleAll("noop"),X()},clearChat:()=>{s().cancelGeneration(),A=!1,f.settleAll("noop"),r({messages:[],currentRunId:null,streamingMsgId:null,isGenerating:!1,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[]})},addMessage:e=>r(n=>({messages:[...n.messages,e]})),appendDelta:(e,n)=>r(o=>({messages:o.messages.map(d=>d.id===e?{...d,content:d.content+n}:d)})),updateMessage:(e,n)=>r(o=>({messages:o.messages.map(d=>d.id===e?{...d,...n}:d)})),setGenerating:e=>r({isGenerating:e}),cancelGeneration:()=>{A=!1,f.byRunFailed();let{streamingMsgId:e,isGenerating:n,currentRunId:o}=s();if(n){if(k({type:"CANCEL_RUN",...o&&{runId:o}}),e){let d=s().messages.find(c=>c.id===e);d&&!d.content?r(c=>({messages:c.messages.filter(u=>u.id!==e)})):r(c=>({messages:c.messages.map(u=>u.id===e?{...u,status:"done",toolCalls:u.toolCalls?.map(p=>p.status==="calling"?{...p,status:"done"}:p)}:u)}))}r({isGenerating:!1,currentRunId:null,streamingMsgId:null})}},setAuthBlocked:e=>r({authBlocked:e}),setUserId:e=>{s().userId&&s().userId!==e&&r({conversationEstablished:!1}),r({userId:e})},historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null,runtimeStatus:"bootstrapping",initConversation:async()=>{let{authClient:e}=E();if(N)return N;let n;N=new Promise(o=>{n=o});try{let o=s().userId,d=await e.resolveUserId();if(o&&o!==d&&(w++,r({conversationEstablished:!1}),r({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null})),r({userId:d}),!e.getAuthState()?.token){ye.warn("anonymous: skip WS init, expose recoverable auth failure"),r({runtimeStatus:"failed",conversationEstablished:!1}),s().setAuthBlocked("登录失败,暂时无法对话"),t.toast("登录失败,暂时无法对话","error");return}let c=H();s().init(),r({runtimeStatus:"ready"}),c&&he(s)}catch(o){ye.error("init error:",o),s().init(),r({runtimeStatus:"failed"})}finally{N=null,n()}},retryBootstrap:(e=!0)=>{let{authClient:n}=E();if(b)return b;let d=(async()=>{r({runtimeStatus:"bootstrapping"}),e&&n.clearAuth(),s().destroy(),await s().initConversation()})().finally(()=>{b===d&&(b=null)});return b=d,d},newConversation:async()=>{if(!O){O=!0;try{w++,s().clearChat(),r({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null}),await s().initConversation()}finally{O=!1}}},scheduleSessionUpgrade:()=>{let{authClient:e}=E();if(b)return b;if(s().isGenerating)return q=!0,Promise.resolve();let o=(async()=>{r({runtimeStatus:"bootstrapping"});try{e.clearAuth(),await e.ensureAuth(),s().destroy(),await s().initConversation()}catch(d){We.error("unexpected error:",d),r({runtimeStatus:"failed"})}finally{q=!1}})().finally(()=>{b===o&&(b=null)});return b=o,o},loadMoreHistory:async()=>{let{platformApi:e}=E(),{isLoadingHistory:n,historyHasMore:o,historyMessages:d,historyBeforeId:c}=s();if(n||!o)return;let u=w;r({isLoadingHistory:!0});let p=5,g=d.length===0?s().messages.find(h=>h.requestId)?.requestId:void 0,m=c??g;try{let{status:h,data:y}=await e.listMessages({pageSize:p,...m?{beforeId:m}:{}});if(u!==w)return;if(h===200&&y){let v=y.data||[],Ie=new Set(s().messages.map(S=>S.requestId).filter(Boolean)),G=new Set(s().historyEntryKeys),$=[],F=v.filter(S=>{let U=Je(S);return G.has(U)?!1:(G.add(U),$.push(U),!S.outerBusinessId||!Ie.has(S.outerBusinessId))}),D=[...v].reverse().find(S=>S.outerBusinessId)?.outerBusinessId??null,Ae=F.length>0||!!D&&D!==m,{messages:Se,cardsByMessageId:be}=le(F.reverse());r(S=>({historyMessages:[...Se,...S.historyMessages],historyHasMore:v.length>=p&&!!D&&Ae,isLoadingHistory:!1,historyEntryKeys:[...$,...S.historyEntryKeys],historyBeforeId:D,cardsByMessageId:{...S.cardsByMessageId,...be}}))}else r({isLoadingHistory:!1})}catch(h){if(ze.error("load more error:",h),u!==w)return;r({isLoadingHistory:!1})}},submitFeedback:async(e,n,o,d)=>{let c=s().messages.find(h=>h.id===e),u=c?.feedbackState??"none",p=c?.requestId;if(!p){Ce.warn("no requestId for message",e);return}let g=n==="cancel"?"none":n;s().updateMessage(e,{feedbackState:g});let m={like:"LIKE",dislike:"DISLIKE",cancel:"CANCEL"};try{(await o.addTag(p,m[n])).success||s().updateMessage(e,{feedbackState:u})}catch(h){if(Xe(h)&&d)try{let y=await d();if(y.feedback){(await y.feedback.addTag(p,m[n])).success||s().updateMessage(e,{feedbackState:u});return}}catch(y){Ce.error("retry failed:",y)}s().updateMessage(e,{feedbackState:u})}}}}function Dt(t){return t.subscribe((r,s)=>{q&&s.isGenerating&&!r.isGenerating&&t.getState().scheduleSessionUpgrade()})}export{J as a,Y as b,rt as c,ee as d,te as e,xe as f,we as g,Pe as h,oe as i,ae as j,ie as k,Ue as l,Be as m,Le as n,Oe as o,Ge as p,le as q,Xe as r,wt as s,Ye as t,vt as u,Dt as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l}from"../chunk-5TUYEBYW.js";import"../chunk-SRHMZIHE.js";import"../chunk-2A3TBRT4.js";export{d as AUTH_ERROR_MSG,i as CardPreviewPage,b as EMPTY_CATALOG_MSG,c as EMPTY_MODULE_MSG,a as EMPTY_REGISTRY_MSG,g as HISTORY_VIEW_LABEL,e as LOAD_ERROR_MSG,h as MODULE_ALL_LABEL,f as PAGE_TITLE,k as PreviewRows,l as PreviewSurface,j as buildPreviewRows};
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
export * from '@tbox.cn/app-sdk-client';
|
|
2
2
|
export { InferModuleCards } from '@tbox.cn/app-sdk-core';
|
|
3
|
-
import { TboxSessionData, HostEffect, Adapters, IASRAdapter, IFeedbackAdapter, ITTSAdapter, IUploadAdapter, HelloAckChatConfig, TboxCardPayload, UiAction, CardSnapshot, SkillRecord, PreToolRecord, HostEffectResult, UploadProgressCallback, UploadOptions, UploadResult } from '@tbox.cn/app-contracts';
|
|
3
|
+
import { TboxSessionData, HostEffect, ActionSettledOutcome, Adapters, IASRAdapter, IFeedbackAdapter, ITTSAdapter, IUploadAdapter, HelloAckChatConfig, ServerFeature, TboxCardPayload, UiAction, CardSnapshot, SkillRecord, PreToolRecord, HostEffectResult, UploadProgressCallback, UploadOptions, UploadResult } from '@tbox.cn/app-contracts';
|
|
4
4
|
export { Adapters, ChatUiSettings, IASRAdapter, IFeedbackAdapter, ITTSAdapter, IUploadAdapter, UploadOptions, UploadProgressCallback, UploadResult } from '@tbox.cn/app-contracts';
|
|
5
5
|
import { UseBoundStore, StoreApi } from 'zustand';
|
|
6
6
|
import { A as AuthClient } from '../auth-client-BzOwQV_4.js';
|
|
7
7
|
export { a as AuthClientOptions, b as AuthIdentity, c as AuthState, d as createAuthClient, g as getAuthClient } from '../auth-client-BzOwQV_4.js';
|
|
8
8
|
import * as react from 'react';
|
|
9
9
|
|
|
10
|
+
/** 配置 context 采集(应用装配点注入;返回 undefined 则调用方不携带 context) */
|
|
11
|
+
declare function configureHelloContext(getter: (() => Record<string, unknown> | undefined) | undefined): void;
|
|
12
|
+
/** 读取当前 context(采集器未注册/抛错 → undefined,fail-soft) */
|
|
13
|
+
declare function readHelloContext(): Record<string, unknown> | undefined;
|
|
14
|
+
|
|
10
15
|
/** 媒体 / 消息类型(SDK 核心 chat 协议类型) */
|
|
11
16
|
type MediaType = 'image' | 'video' | 'audio' | 'file';
|
|
12
17
|
type InputMethod = 'text' | 'voice' | 'image' | 'video' | 'audio' | 'file';
|
|
@@ -155,6 +160,47 @@ interface CardEventData {
|
|
|
155
160
|
ts: number;
|
|
156
161
|
}
|
|
157
162
|
|
|
163
|
+
/**
|
|
164
|
+
* 卡片动作结算:把「点了按钮之后,什么时候算结束」收敛成一次派发结果 + 一个 Promise。
|
|
165
|
+
*
|
|
166
|
+
* 为什么需要:moduleAction 不开启引擎 run,卡片刷新也可能只发新卡不带来源卡 id。
|
|
167
|
+
* 没有结束信号时按钮只能靠超时兜底(旧实现 20 秒),业务早已完成而按钮仍在转圈。
|
|
168
|
+
*
|
|
169
|
+
* 结算顺序(先到先得,结算后删除登记):
|
|
170
|
+
* 1. 服务端 tbox:action-settled(能力已声明时唯一权威);
|
|
171
|
+
* 2. 兼容路径——服务端未声明能力时,同 surfaceId 的 card-update / notice 即视为结束;
|
|
172
|
+
* 3. sendMessage / submitForm 派发后首个被消费的 RUN_STARTED;
|
|
173
|
+
* 4. clearChat 或断线——按 noop 结算;
|
|
174
|
+
* 5. 超时提示(缺省 8s)。
|
|
175
|
+
*/
|
|
176
|
+
/** 动作被拒的原因(本地即时返回,不进入挂起)。 */
|
|
177
|
+
type ActionRejectReason = 'offline' | 'generating' | 'history' | 'no-token' | 'no-channel';
|
|
178
|
+
/** 一次卡片动作的最终结局。 */
|
|
179
|
+
type ActionOutcome = {
|
|
180
|
+
status: 'settled';
|
|
181
|
+
outcome: ActionSettledOutcome;
|
|
182
|
+
} | {
|
|
183
|
+
status: 'run-started';
|
|
184
|
+
} | {
|
|
185
|
+
status: 'rejected';
|
|
186
|
+
reason: ActionRejectReason;
|
|
187
|
+
} | {
|
|
188
|
+
status: 'timeout';
|
|
189
|
+
} | {
|
|
190
|
+
status: 'local';
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* 派发结果:已上行则带 requestId 与结算 Promise;本地动作或被拒则直接是结局。
|
|
194
|
+
* 调用方(按钮组件)只需 `await dispatch.settled`(或 `dispatch.status === 'sent'` 判定)。
|
|
195
|
+
*/
|
|
196
|
+
type UiActionDispatch = {
|
|
197
|
+
status: 'sent';
|
|
198
|
+
requestId: string;
|
|
199
|
+
settled: Promise<ActionOutcome>;
|
|
200
|
+
} | Extract<ActionOutcome, {
|
|
201
|
+
status: 'rejected' | 'local';
|
|
202
|
+
}>;
|
|
203
|
+
|
|
158
204
|
interface AdapterContextValue extends Adapters {
|
|
159
205
|
/** 刷新 session 并返回重建后的 adapters,用于重试过期操作 */
|
|
160
206
|
refreshSession?: () => Promise<AdapterContextValue>;
|
|
@@ -170,9 +216,6 @@ declare const useUploadAdapter: () => IUploadAdapter | undefined;
|
|
|
170
216
|
declare const useFeedbackAdapter: () => IFeedbackAdapter | undefined;
|
|
171
217
|
declare const useRefreshSession: () => (() => Promise<AdapterContextValue>) | undefined;
|
|
172
218
|
|
|
173
|
-
/** 配置 context 采集(应用装配点注入;返回 undefined 则调用方不携带 context) */
|
|
174
|
-
declare function configureHelloContext(getter: (() => Record<string, unknown> | undefined) | undefined): void;
|
|
175
|
-
|
|
176
219
|
/**
|
|
177
220
|
* 核心 ChatStore:AG-UI 事件 → 消息流式拼接 / 工具调用 / 卡片 / reasoning 状态管理。
|
|
178
221
|
* app 侧通过 extend 注入业务方法(initConversation / loadMoreHistory / submitFeedback)。
|
|
@@ -184,8 +227,10 @@ declare function isSessionExpiredError(err: unknown): boolean;
|
|
|
184
227
|
* 模块卡组件提交动作(moduleAction/submitForm/sendMessage)。
|
|
185
228
|
* 模块卡编译期不依赖应用 store——经本函数走当前绑定的分发器
|
|
186
229
|
* (含 isGenerating/isHistory 门控)。未注册(应用未创建)时 warn 丢弃。
|
|
230
|
+
*
|
|
231
|
+
* 返回派发结果:已上行时 `settled` 在动作结束时兑现(回执、run 开始、被拒或超时)。
|
|
187
232
|
*/
|
|
188
|
-
declare function sendCardAction(surfaceId: string, action: UiAction, formData?: Record<string, unknown>):
|
|
233
|
+
declare function sendCardAction(surfaceId: string, action: UiAction, formData?: Record<string, unknown>): UiActionDispatch;
|
|
189
234
|
/**
|
|
190
235
|
* 绑定卡动作通道(返回 restore):替换当前分发器并恢复**前一绑定**
|
|
191
236
|
* (可能是 undefined——应用 store 未创建时)。dev 卡片预览页挂载时接管
|
|
@@ -193,7 +238,7 @@ declare function sendCardAction(surfaceId: string, action: UiAction, formData?:
|
|
|
193
238
|
* 使嵌套绑定与 React StrictMode 双 effect 天然幂等。
|
|
194
239
|
* createCoreChatState 构造期经此注册保底绑定(语义不变)。
|
|
195
240
|
*/
|
|
196
|
-
declare function bindCardActionChannel(dispatch: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) =>
|
|
241
|
+
declare function bindCardActionChannel(dispatch: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) => UiActionDispatch): () => void;
|
|
197
242
|
|
|
198
243
|
interface CoreChatState {
|
|
199
244
|
userId: string;
|
|
@@ -220,7 +265,7 @@ interface CoreChatState {
|
|
|
220
265
|
orphanCards: TboxCardPayload[];
|
|
221
266
|
init: () => void;
|
|
222
267
|
sendMessage: (input: string | ChatInputMessage) => void;
|
|
223
|
-
sendUiAction: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) =>
|
|
268
|
+
sendUiAction: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) => UiActionDispatch;
|
|
224
269
|
hideCard: (cardId: string) => void;
|
|
225
270
|
/** 连接与身份拆除(unmount/登出);会话清空用 clearChat()。 */
|
|
226
271
|
destroy: () => void;
|
|
@@ -262,6 +307,8 @@ interface HelloAckState {
|
|
|
262
307
|
chatConfig: HelloAckChatConfig;
|
|
263
308
|
/** 018 tool-debug:工具调试视图旗标(服务端 env 单源;仅开启时在场) */
|
|
264
309
|
toolDebug?: boolean;
|
|
310
|
+
/** 服务端能力声明(旧服务端不发 → 走兼容结算路径) */
|
|
311
|
+
features?: readonly ServerFeature[];
|
|
265
312
|
}
|
|
266
313
|
/**
|
|
267
314
|
* 创建核心状态对象(含方法),供 app 侧在同一个 create() 中合并使用。
|
|
@@ -454,14 +501,16 @@ declare function hideCard(state: CardStoreState, cardId: string): CardStoreState
|
|
|
454
501
|
* - blockAll:可选的应用级总闸(返回 true 丢弃一切动作);SDK chat-store 缺省不注入——
|
|
455
502
|
* 原 B2「历史卡全禁」已收窄为只禁写通道。
|
|
456
503
|
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
504
|
+
* 返回值:派发结果。写通道被门控拦下时返回 `rejected`,调用方据此立即恢复按钮,
|
|
505
|
+
* 不必等超时(旧实现只有 void,被丢弃的动作会让按钮空转)。
|
|
459
506
|
*/
|
|
460
507
|
interface CardActionHandlerDeps {
|
|
461
508
|
/** 发送到服务端(WS UI_ACTION 载荷;surfaceId 为卡片实例 id,formData 仅 submitForm 携带) */
|
|
462
|
-
sendToServer: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) =>
|
|
463
|
-
/** 生成中门控:返回 false
|
|
509
|
+
sendToServer: (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) => UiActionDispatch;
|
|
510
|
+
/** 生成中门控:返回 false 时拒绝 sendMessage/submitForm/moduleAction */
|
|
464
511
|
canAct?: (surfaceId: string) => boolean;
|
|
512
|
+
/** 卡级拒绝原因(用于填 rejected.reason;缺省按 generating 归类) */
|
|
513
|
+
rejectReason?: (surfaceId: string) => 'generating' | 'history';
|
|
465
514
|
/** 应用级总闸(可选):返回 true 时丢弃一切动作(含 openLink/toast/closeCard);SDK 缺省不注入 */
|
|
466
515
|
blockAll?: (surfaceId: string) => boolean;
|
|
467
516
|
/** 本地副作用 */
|
|
@@ -469,7 +518,7 @@ interface CardActionHandlerDeps {
|
|
|
469
518
|
openUrl?: (url: string) => void;
|
|
470
519
|
closeCard?: (cardId: string) => void;
|
|
471
520
|
}
|
|
472
|
-
type CardActionHandler = (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) =>
|
|
521
|
+
type CardActionHandler = (surfaceId: string, action: UiAction, formData?: Record<string, unknown>) => UiActionDispatch;
|
|
473
522
|
declare function createCardActionHandler(deps: CardActionHandlerDeps): CardActionHandler;
|
|
474
523
|
|
|
475
524
|
/**
|
|
@@ -742,4 +791,4 @@ declare function consumeAutoSendQuery(): string | null;
|
|
|
742
791
|
/** 编排:等 socket OPEN → 移交 send(isGenerating/isWsOpen 判定归 sendMessage 咽喉) */
|
|
743
792
|
declare function runAutoSend(text: string, send: (text: string) => void, timeoutMs?: number): Promise<void>;
|
|
744
793
|
|
|
745
|
-
export { type AdapterContextValue, AdapterProvider, AlipayASRAdapter, AudioStreamPlayer, AuthClient, BrowserASRAdapter, type CallActionOptions, type CallActionResult, type CardActionHandler, type CardActionHandlerDeps, type CardEventData, type CardHistoryLoader, type CardHistoryStore, type CardStoreState, type ChatInputMessage, type ChatMessage, type CoreChatState, type CoreChatStore, type CoreChatStoreDeps, FallbackASRAdapter, FeedbackAdapter, type HostEffectRunnerDeps, InMemoryCardHistoryLoader, type InputMethod, type ItemActionDraft, ItemActionsRow, type ListMessagesOptions, type ListMessagesResult, type MediaItem, type MediaType, type MessageRole, type MessageStatus, type PlatformApi, type PlatformHistoryMessage, TTSAdapter, type ToastFunction, type ToolCallInfo, UploadAdapter, type WsUrlResolver, __resetPlatformApiSingleton, bindCardActionChannel, buildHistoryToolCalls, buildPreToolToolCalls, buildSkillToolCalls, callAction, configureHelloContext, configureWsAuthErrorHandler, configureAuthToken as configureWsAuthToken, configureWsFatalCloseHandler, configureWsKeepalive, configureWsUrl, connect, consumeAutoSendQuery, convertHistoryMessages, createCardActionHandler, createCoreChatState, createEffectTokenDeduper, createHostEffectRunner, createPlatformAdapters, createPlatformApi, disconnect, executeAuthorizationEffect, executePaymentEffect, getAuthToken, getPlatformApi, hideCard, isHostEffect, isSessionExpiredError, isWsOpen, mapPaymentResultCode, resolveHistoryMessage, resolveHistoryMeta, resolveHistoryPreTools, resolveHistorySkills, runAutoSend, send, sendCardAction, setActionAuthTokenGetter, subscribeSessionUpgradeDrain, upsertCard, useASRAdapter, useAdapters, useFeedbackAdapter, useRefreshSession, useTTSAdapter, useUploadAdapter, waitForSocketOpen };
|
|
794
|
+
export { type ActionOutcome, type ActionRejectReason, type AdapterContextValue, AdapterProvider, AlipayASRAdapter, AudioStreamPlayer, AuthClient, BrowserASRAdapter, type CallActionOptions, type CallActionResult, type CardActionHandler, type CardActionHandlerDeps, type CardEventData, type CardHistoryLoader, type CardHistoryStore, type CardStoreState, type ChatInputMessage, type ChatMessage, type CoreChatState, type CoreChatStore, type CoreChatStoreDeps, FallbackASRAdapter, FeedbackAdapter, type HostEffectRunnerDeps, InMemoryCardHistoryLoader, type InputMethod, type ItemActionDraft, ItemActionsRow, type ListMessagesOptions, type ListMessagesResult, type MediaItem, type MediaType, type MessageRole, type MessageStatus, type PlatformApi, type PlatformHistoryMessage, TTSAdapter, type ToastFunction, type ToolCallInfo, type UiActionDispatch, UploadAdapter, type WsUrlResolver, __resetPlatformApiSingleton, bindCardActionChannel, buildHistoryToolCalls, buildPreToolToolCalls, buildSkillToolCalls, callAction, configureHelloContext, configureWsAuthErrorHandler, configureAuthToken as configureWsAuthToken, configureWsFatalCloseHandler, configureWsKeepalive, configureWsUrl, connect, consumeAutoSendQuery, convertHistoryMessages, createCardActionHandler, createCoreChatState, createEffectTokenDeduper, createHostEffectRunner, createPlatformAdapters, createPlatformApi, disconnect, executeAuthorizationEffect, executePaymentEffect, getAuthToken, getPlatformApi, hideCard, isHostEffect, isSessionExpiredError, isWsOpen, mapPaymentResultCode, readHelloContext, resolveHistoryMessage, resolveHistoryMeta, resolveHistoryPreTools, resolveHistorySkills, runAutoSend, send, sendCardAction, setActionAuthTokenGetter, subscribeSessionUpgradeDrain, upsertCard, useASRAdapter, useAdapters, useFeedbackAdapter, useRefreshSession, useTTSAdapter, useUploadAdapter, waitForSocketOpen };
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as G,b as K,c as j,d as J,e as X,f as Y,g as Z,h as se,i as ae,j as ne,k as ie,l as pe,m as le,n as de,o as ce,p as fe,q as ue,r as me}from"../chunk-PMVREUTT.js";import{a as k,b as H,c as R,d as I,e as w,f as M,g as U,h as D,i as E,j as L,k as O,l as F,m as N,n as W,o as V,p as _,q as Q,r as $,s as i,t as q,u as z,v as B}from"../chunk-SRHMZIHE.js";import{a as ee,b as te,c as re,d as oe}from"../chunk-HECUPMFT.js";import{a as m,b as x,c as y,d as A,e as C,f as h,g,h as S,i as b,j as T,k as P,l as p,m as v}from"../chunk-2A3TBRT4.js";export*from"@tbox.cn/app-sdk-client";import{jsx as c}from"react/jsx-runtime";function xe(r){let{actions:e,cardId:t,isHistory:o,className:a,chipClassName:n}=r;return!e||e.length===0?null:c("div",{className:`tbox-item-actions ${a??""}`.trim(),children:e.map((s,u)=>c("button",{type:"button",className:`tbox-chip ${n??""}`.trim(),disabled:o&&s.kind==="send",onClick:()=>{s.kind==="send"?i(t,{type:"sendMessage",value:s.value??s.label,...s.visibleValue?{displayText:s.visibleValue}:{},visible:!0}):i(t,{type:"openLink",url:s.url??""})},children:s.label},u))})}function ye(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var l=class{snapshots=new Map;async save(e,t){let o=this.snapshots.get(e)??[],a=o.findIndex(s=>s.id===t.id),n={id:t.id,cardType:t.cardType,data:t.data,status:t.status,schemaVersion:t.schemaVersion??1,meta:t.meta};a>=0?o[a]=n:o.push(n),this.snapshots.set(e,o)}async load(e){return(this.snapshots.get(e)??[]).map(o=>ye(o))}async clear(e){this.snapshots.delete(e)}};import{createClientLogger as Ae}from"@tbox.cn/app-sdk-client";var d=Ae("AUTO-SEND"),f=["query","prompt"];function Ce(r){let e=new URLSearchParams(r);for(let t of f){let o=e.get(t)?.trim();if(o)return o}return null}function he(r){let e=new URL(r);for(let t of f)e.searchParams.delete(t);return e.toString()}function ge(){if(typeof window>"u")return null;let r=Ce(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",he(window.location.href))}catch(e){d.warn("strip failed (URL retained; refresh may re-send):",e)}return r}async function Se(r,e,t=5e3){if(!await p(t)){d.warn("skipped:reason=socket-timeout");return}e(r),d.info("sent")}export{G as AdapterProvider,ae as AlipayASRAdapter,le as AudioStreamPlayer,se as BrowserASRAdapter,ne as FallbackASRAdapter,pe as FeedbackAdapter,l as InMemoryCardHistoryLoader,xe as ItemActionsRow,de as TTSAdapter,ie as UploadAdapter,me as __resetPlatformApiSingleton,q as bindCardActionChannel,V as buildHistoryToolCalls,W as buildPreToolToolCalls,O as buildSkillToolCalls,te as callAction,m as configureHelloContext,g as configureWsAuthErrorHandler,C as configureWsAuthToken,S as configureWsFatalCloseHandler,y as configureWsKeepalive,A as configureWsUrl,b as connect,ge as consumeAutoSendQuery,Q as convertHistoryMessages,re as createAuthClient,k as createCardActionHandler,z as createCoreChatState,w as createEffectTokenDeduper,E as createHostEffectRunner,ce as createPlatformAdapters,fe as createPlatformApi,v as disconnect,D as executeAuthorizationEffect,U as executePaymentEffect,oe as getAuthClient,h as getAuthToken,ue as getPlatformApi,R as hideCard,I as isHostEffect,$ as isSessionExpiredError,P as isWsOpen,M as mapPaymentResultCode,x as readHelloContext,N as resolveHistoryMessage,_ as resolveHistoryMeta,F as resolveHistoryPreTools,L as resolveHistorySkills,Se as runAutoSend,T as send,i as sendCardAction,ee as setActionAuthTokenGetter,B as subscribeSessionUpgradeDrain,H as upsertCard,j as useASRAdapter,K as useAdapters,Y as useFeedbackAdapter,Z as useRefreshSession,J as useTTSAdapter,X as useUploadAdapter,p as waitForSocketOpen};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-agent-sdk-client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.14",
|
|
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": {
|
|
@@ -45,9 +45,9 @@
|
|
|
45
45
|
"react": "18.3.1",
|
|
46
46
|
"react-dom": "18.3.1",
|
|
47
47
|
"zustand": "4.5.7",
|
|
48
|
-
"@tbox.cn/app-sdk-
|
|
49
|
-
"@tbox.cn/app-sdk-
|
|
50
|
-
"@tbox.cn/app-contracts": "1.0.0-alpha.
|
|
48
|
+
"@tbox.cn/app-sdk-client": "1.0.0-alpha.14",
|
|
49
|
+
"@tbox.cn/app-sdk-core": "1.0.0-alpha.14",
|
|
50
|
+
"@tbox.cn/app-contracts": "1.0.0-alpha.14"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/ws": "8.18.1",
|
package/dist/chunk-6VLQT22V.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createClientLogger as O}from"@tbox.cn/app-sdk-client";import{nextKeepaliveAction as T,KEEPALIVE_MISS_LIMIT as A}from"@tbox.cn/app-contracts";var i=O("WS"),n=null,u=null,p=null,a=null,m=null,v=null,d=0,x=!0,f=25e3,c=null,y=0;function R(e){e.enabled!==void 0&&(x=e.enabled),e.intervalMs!==void 0&&(f=Math.max(100,e.intervalMs))}function D(e){m=e}function K(e){v=e}function U(){return v?v():null}var S=null;function $(e){S=e}var g=null;function J(e){g=e}var P="登录状态失效,无法连接对话服务,请重试",I="HELLO scope 拒绝:context.mall 形状非法(需 mallId 非空)";function N(e,l,r=3){if(!l)return{stop:!1,nextStreak:0};let t=e+1;return t>=r?{stop:!0,nextStreak:0}:{stop:!1,nextStreak:t}}function C(e,l){if(n&&(n.readyState===WebSocket.OPEN||n.readyState===WebSocket.CONNECTING))return;u=e,p=l??p;let r=m?m():null;r&&(n=new WebSocket(r),n.onopen=()=>{i.info("connected"),a&&(clearTimeout(a),a=null),L(),p?.()},n.onmessage=t=>{y=Date.now();let o=null;try{o=JSON.parse(t.data)}catch(s){i.error("parse error",s);return}if(o?.type!=="PONG"){if(o?.type==="PING"){E({type:"PONG",...o.ts!==void 0?{ts:o.ts}:{}});return}try{u?.(o)}catch(s){i.error("parse error",s)}}},n.onclose=t=>{if(i.info("disconnected",t.code?`code=${t.code}`:""),b(),n=null,t.code===4002){i.error("HELLO scope 拒绝(商圈不在白名单),停止重连"),g?.({code:t.code,message:I});return}let o=t.code===4001,{stop:s,nextStreak:H}=N(d,o);if(d=H,s){i.error("HELLO 连续鉴权失败,停止重连(请刷新页面重试)"),g?.({code:t.code,message:P});return}if(o){(S?S().catch(w=>i.warn("auth refresh failed:",w.message)):Promise.resolve()).finally(k);return}k()},n.onerror=t=>{i.error("error",t)})}function E(e){if(!n||n.readyState!==WebSocket.OPEN){i.warn("not connected, message dropped");return}n.send(JSON.stringify(e))}function j(){return!!n&&n.readyState===WebSocket.OPEN}function V(e,l=100){let r=Date.now()+e;return new Promise(t=>{let o=()=>{if(n&&n.readyState===WebSocket.OPEN){t(!0);return}if(Date.now()>=r){t(!1);return}setTimeout(o,l)};o()})}function q(){a&&(clearTimeout(a),a=null),b(),u=null,d=0,n&&(n.onclose=null,n.close(),n=null)}function h(e=3e3){if(!x||!n||n.readyState!==WebSocket.OPEN)return;let l=T(Date.now()-y,f);if(l==="dead"){G(`keepalive stale (idle >= ${f*A}ms)`,e);return}l==="ping"&&E({type:"PING",ts:Date.now()})}function L(){y=Date.now(),x&&(c&&clearInterval(c),c=setInterval(()=>h(),f))}function b(){c&&(clearInterval(c),c=null)}function G(e,l=3e3){i.warn(`force reconnect: ${e}`),b();let r=n;n=null,r&&(r.onclose=null,r.onmessage=null,r.onopen=null,r.onerror=null,r.close()),d=0,k(l)}typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&h(0)});function k(e=3e3){a||!u||(a=setTimeout(()=>{a=null,u&&C(u)},e))}var W;function B(e){W=e}function Q(){try{return W?.()}catch{return}}export{R as a,D as b,K as c,U as d,$ as e,J as f,C as g,E as h,j as i,V as j,q as k,B as l,Q as m};
|
package/dist/chunk-HE3FQIAS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as j}from"./chunk-RWUIBPQC.js";import{useCallback as U,useEffect as ve,useId as re,useMemo as ie,useRef as k,useState as C}from"react";import{CaretDown as we,CaretLeft as Se,CaretRight as Te,Copy as he}from"@phosphor-icons/react";import{CardRenderer as Ce}from"@tbox.cn/app-sdk-client";var fe="preview",q="表单提交需引擎运行,预览不支持",K=e=>`预览:已发送「${e}」`,Z=e=>`宿主效果 ×${e}(预览不执行)`;function Q(e){return new URLSearchParams(e).get("history")==="true"}function ee(e){return new URLSearchParams(e).get("controls")!=="false"}var J="(未声明)";function me(e){return[...new Set(e)].sort((t,o)=>t===o?0:t===J?1:o===J?-1:t.localeCompare(o))}function G(e,t={}){let o=me(e.cards.map(d=>d.moduleId)),l=t.module!==void 0&&t.module!=="all"&&!o.includes(t.module)?[...o,t.module]:o,n=t.module??"all",i=[...n==="all"?e.cards:e.cards.filter(d=>d.moduleId===n)].sort((d,S)=>{let b=d.order??Number.POSITIVE_INFINITY,T=S.order??Number.POSITIVE_INFINITY;return b!==T?b-T:d.cardType.localeCompare(S.cardType)}),v=i.map(d=>d.cardType),g=i.find(d=>d.cardType===t.card)??i[0],w=g?.cardType??"",m=g?.samples??[],P=t.sample!==void 0&&m.some(d=>d.label===t.sample)?t.sample:"初始态";return{modules:l,moduleId:n,cardTypes:v,candidateCards:i,cardType:w,selectedCard:g,samples:m,sampleLabel:P}}function be(e,t){return`preview-${e.replace(/[^a-zA-Z0-9_-]/g,"_")}-${t}`}function X(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 $(e,t){let o={};if(!t.noTokens)for(let l of e.actions)(!l.kind||l.kind==="moduleAction")&&(o[l.actionId]=fe);return{id:t.id,cardType:e.cardType,data:t.data,status:"ready",...e.actions.length?{actions:e.actions}:{},...Object.keys(o).length?{actionTokens:o}:{},...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 te(e,t,o){return $(e,{id:be(e.cardType,o),data:t.data,isHistory:!!t.isHistory,noTokens:!!t.noTokens,...t.envelope??{}})}function xe(e,t,o,l){if(o.ok!==!0||e.payload.id!==t||!o.card)return e;if(o.kind==="card"){let n=l(o.card.cardType),i=n?.samples[0];return!n||!i?e:{card:n,sample:i,payload:$(n,{id:o.card.id,data:o.card.data,isHistory:!1,noTokens:!1,...X(o.card)})}}return o.kind!=="update"?e:{...e,payload:$(e.card,{id:t,data:o.card.data,isHistory:!!e.sample.isHistory,noTokens:!!e.sample.noTokens,...X(o.card)})}}function oe(e,t,o,l,n){let i=e[t];if(!i||i.payload.id!==o)return e;let v=xe(i,o,l,n);return v===i?e:{...e,[t]:v}}function ne(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{Fragment as nt,jsx as s,jsxs as u}from"react/jsx-runtime";var Pe="客户端未装配模块——经 tbox-app-dev dev --module <模块> 装配后可见",Ae="服务端未注册卡片(模块未装配或全部被禁用)",Ie=e=>`模块「${e}」暂无示例卡片`,Re="鉴权失败:dev 环境依赖 dev-login(浏览器态自动登录);生产构建(NODE_ENV=production)预览面不挂载",ae=e=>`卡片目录拉取失败(HTTP ${e})`,ke="tbox 卡片预览",Le="isHistory 视角",Ee="全部模块";function le(e,t,o){let l=Math.max(0,e.samples.findIndex(i=>i.label===t)),n=e.samples[l];return n?{card:e,sample:n,payload:te(e,n,o??l)}:null}function ct(e){let{registry:t,authClient:o}=e,l=Object.keys(t).length===0,[n,i]=C(null),[v,g]=C(null),[w,m]=C("all"),[P,d]=C(!1),[S,b]=C({}),[T,H]=C([]),O=k(null),I=k(new Set),x=k(S);x.current=S;let F=k(n);F.current=n;let B=k(0),D=k(0),L=ie(()=>{try{let r=window.location.search,f=new URLSearchParams(r);return{module:f.get("module")??void 0,card:f.get("card")??void 0,sample:f.get("sample")??void 0,history:Q(r),controls:ee(r)}}catch{return{}}},[]),V=L.controls!==!1,y=U(r=>{let f=++B.current;H(p=>[...p,{id:f,text:r}]),setTimeout(()=>H(p=>p.filter(c=>c.id!==f)),3200)},[]);ve(()=>{let r=!1,f=j((p,c,A)=>{a.current(p,c,A)});return(async()=>{try{let p=await o.ensureAuth();O.current=p.token;let c=await fetch("/_tbox/api/cards",{headers:p.token?{Authorization:`Bearer ${p.token}`}:{}});if(r)return;if(c.status===401||c.status===403){g(Re);return}if(!c.ok){g(ae(c.status));return}let A=await c.json();if(r)return;i(A);let _=G(A,L);m(_.moduleId);let z=Me(A.cards,_.cardType,_.sampleLabel);x.current=z,b(z),d(L.history===!0)}catch(p){r||g(`卡片目录拉取失败:${p.message}`)}})(),()=>{r=!0,f()}},[]);let E=U((r,f,p)=>{let c=ne(f);if(c.type==="openLink"){window.open(c.url,"_blank");return}if(c.type==="sendMessage"){y(K(c.value));return}if(c.type==="submitFormUnsupported"){y(q);return}if(c.type==="ignored")return;let A=Object.entries(x.current).find(([,R])=>R.payload.id===r),_=A?.[1];if(!A||!_||f.type!=="moduleAction"||I.current.has(r))return;I.current.add(r);let z=O.current;fetch("/_tbox/api/card-action",{method:"POST",headers:{"Content-Type":"application/json",...z?{Authorization:`Bearer ${z}`}:{}},body:JSON.stringify({cardType:_.card.cardType,actionId:f.actionId,surfaceId:r,...p!==void 0?{input:p}:{}})}).then(async R=>{let h=await R.json().catch(()=>null);if(!R.ok||!h||h.ok===!1){y(h?.error??ae(R.status));return}let ue=h,Y=x.current,W=oe(Y,A[0],r,ue,ge=>F.current?.cards.find(ye=>ye.cardType===ge));W!==Y&&(x.current=W,b(W)),typeof h.text=="string"&&h.text&&y(h.text),Array.isArray(h.effects)&&h.effects.length>0&&y(Z(h.effects.length))}).catch(R=>y(`动作请求失败:${R.message}`)).finally(()=>I.current.delete(r))},[y]),a=k(E);a.current=E;let M=ie(()=>n?G(n,{module:w==="all"?void 0:w}):null,[n,w]),ce=U((r,f)=>{let p=x.current[r];if(!p)return;let c=le(p.card,f,p.card.samples.length+ ++D.current);c&&(x.current={...x.current,[r]:c},b(x.current))},[]),pe=U(r=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText){y("当前浏览器不支持复制");return}navigator.clipboard.writeText(r).then(()=>y(`已复制卡片 ID:${r}`)).catch(()=>y("复制失败,请手动复制"))},[y]);return u("div",{style:{minHeight:"100vh",background:"#f5f5f5",fontFamily:'-apple-system, "PingFang SC", sans-serif'},children:[V&&u("header",{style:Oe,children:[s("strong",{style:{fontSize:14,color:"#262626"},children:ke}),u("select",{"aria-label":"模块",style:ze,value:w,onChange:r=>m(r.target.value),children:[s("option",{value:"all",children:Ee}),(M?.modules??[]).map(r=>s("option",{value:r,children:r},r))]}),s("button",{type:"button",style:P?Fe:de,onClick:()=>d(r=>!r),children:Le})]}),u("main",{style:{maxWidth:1200,margin:"0 auto",padding:"12px 12px 48px"},children:[v&&s("div",{style:tt,children:v}),!v&&!n&&s("div",{style:N,children:"加载中…"}),n&&l&&s("div",{style:N,children:Pe}),n&&!l&&n.cards.length===0&&s("div",{style:N,children:Ae}),n&&!l&&n.cards.length>0&&M&&M.candidateCards.length===0&&s("div",{style:N,children:Ie(M.moduleId)}),n&&!l&&M&&s(_e,{cards:M.candidateCards,rows:S,registry:t,historyView:P,onSelectSample:ce,onCopyCardType:pe,onAction:E})]}),s("div",{style:{position:"fixed",right:16,bottom:24,display:"flex",flexDirection:"column",gap:8,zIndex:20},children:T.map(r=>s("div",{style:ot,children:r.text},r.id))})]})}function Me(e,t,o){let l={};for(let n of e){let i=le(n,n.cardType===t?o:void 0);i&&(l[n.cardType]=i)}return l}function _e(e){let{cards:t,rows:o,registry:l,historyView:n,onSelectSample:i,onCopyCardType:v,onAction:g}=e,w=t.filter(m=>o[m.cardType]);return s("div",{style:Ne,children:w.map((m,P)=>{let d=o[m.cardType];return s(He,{instance:d,isLast:P===w.length-1,registry:l,historyView:n,samples:d.card.samples,activeSampleLabel:d.sample.label,onSelectSample:S=>i(m.cardType,S),onCopyCardType:v,onAction:g},m.cardType)})})}function He(e){let{instance:t,isLast:o,registry:l,historyView:n,samples:i,activeSampleLabel:v,onSelectSample:g,onCopyCardType:w,onAction:m}=e,P=n?{...t.payload,isHistory:!0}:t.payload,d=Math.max(0,i.findIndex(a=>a.label===v)),S=i[d]??t.sample,b=i[d-1],T=i[d+1],H=re(),O=re(),[I,x]=C(null),[F,B]=C(!1),[D,L]=C(!1),[V,y]=C(!1),E=a=>{x(a.getBoundingClientRect().top<80?"bottom":"top")};return u("section",{style:o?Ue:Be,children:[u("header",{style:De,children:[s("div",{style:Ve,children:t.card.displayName}),u("span",{style:We,children:[u("button",{type:"button","aria-label":`复制卡片 ID:${t.card.cardType}`,"aria-describedby":I?H:void 0,style:$e,onMouseEnter:a=>E(a.currentTarget),onMouseLeave:()=>x(null),onFocus:a=>E(a.currentTarget),onBlur:()=>x(null),onClick:()=>w(t.card.cardType),children:[s(he,{size:14,"aria-hidden":"true"}),"复制卡片 ID"]}),I&&u("span",{id:H,role:"tooltip",style:Ge(I),children:[s("span",{style:{display:"block"},children:"复制卡片 ID"}),s("span",{style:{display:"block"},children:"用于定位卡片配置和代码"}),s("span",{style:Ye(I)})]})]})]}),i.length>0&&u("div",{style:Je,children:[u("label",{htmlFor:O,style:Xe,children:["展示状态(",u("span",{"aria-live":"polite",children:[d+1,"/",i.length]}),"):"]}),u("span",{style:qe(F),children:[s("span",{style:Ke,children:S.label}),s(we,{size:12,"aria-hidden":"true",style:Qe}),s("select",{id:O,style:Ze,value:S.label,onChange:a=>g(a.target.value),onFocus:()=>B(!0),onBlur:()=>B(!1),children:i.map(a=>u("option",{value:a.label,children:[a.issues?.length||a.envelopeError?"⚠ ":"",a.label]},a.label))})]})]}),(t.sample.issues?.length||t.sample.envelopeError)&&u("div",{style:je,children:[t.sample.issues?.length?`样本问题:${t.sample.issues.join(";")}`:null,t.sample.envelopeError&&t.sample.issues?.length?";":"",t.sample.envelopeError??""]}),u("div",{role:"group","aria-label":`${t.card.displayName}卡片预览`,tabIndex:0,style:et,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),onFocusCapture:()=>y(!0),onBlurCapture:a=>{a.currentTarget.contains(a.relatedTarget)||y(!1)},onKeyDown:a=>{a.target===a.currentTarget&&(a.key==="ArrowLeft"&&b?(a.preventDefault(),g(b.label)):a.key==="ArrowRight"&&T&&(a.preventDefault(),g(T.label)))},children:[s(Ce,{card:P,registry:l,onAction:a=>m(P.id,a)}),(D||V)&&i.length>1&&u(nt,{children:[s("button",{type:"button","aria-label":"卡片区域:上一个样本",title:"上一个样本",disabled:!b,onClick:()=>b&&g(b.label),style:se("left",!b),children:s(Se,{size:18,"aria-hidden":"true"})}),s("button",{type:"button","aria-label":"卡片区域:下一个样本",title:"下一个样本",disabled:!T,onClick:()=>T&&g(T.label),style:se("right",!T),children:s(Te,{size:18,"aria-hidden":"true"})})]})]})]})}var Oe={position:"sticky",top:0,zIndex:10,display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"10px 16px",background:"#fff",borderBottom:"1px solid #e8e8e8"},ze={fontSize:13,padding:"4px 8px",borderRadius:8,border:"1px solid #d9d9d9",background:"#fff",color:"#262626"},de={fontSize:13,padding:"4px 12px",borderRadius:18,border:"1px solid #d9d9d9",background:"#fff",color:"#262626",cursor:"pointer"},Fe={...de,borderColor:"#1677ff",color:"#1677ff"},Be={minWidth:0,paddingBottom:16,borderBottom:"1px solid #e8e8e8"},Ue={minWidth:0},Ne={display:"flex",flexDirection:"column",gap:16},De={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:8},Ve={flex:"1 1 auto",minWidth:0,color:"#262626",fontSize:14,fontWeight:600,lineHeight:"22px"},We={position:"relative",display:"inline-flex",flex:"0 0 auto"},$e={display:"inline-flex",alignItems:"center",gap:4,flex:"0 0 auto",minHeight:28,padding:"4px 0",border:0,background:"transparent",color:"#222dd9",fontSize:12,lineHeight:"20px",whiteSpace:"nowrap",cursor:"pointer"},Ge=e=>({position:"absolute",right:0,...e==="top"?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"},zIndex:10,width:184,maxWidth:"calc(100vw - 24px)",padding:"6px 8px",borderRadius:4,background:"#303030",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.18)",color:"#fff",fontSize:12,fontWeight:400,lineHeight:"18px",textAlign:"left",whiteSpace:"normal",pointerEvents:"none"}),Ye=e=>({position:"absolute",right:36,...e==="top"?{bottom:-4}:{top:-4},width:8,height:8,background:"#303030",transform:"rotate(45deg)"}),je={fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:"rgba(250,140,22,0.10)",color:"#d46b08",marginBottom:8},Je={display:"flex",alignItems:"center",gap:6,minHeight:28,marginBottom:10},Xe={flex:"0 0 auto",color:"#595959",fontSize:12,lineHeight:"20px"},qe=e=>({position:"relative",display:"inline-flex",alignItems:"center",gap:4,flex:"0 1 auto",minWidth:0,color:"#262626",fontSize:12,lineHeight:"20px",borderRadius:2,outline:e?"2px solid #222dd9":"none",outlineOffset:2}),Ke={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Ze={position:"absolute",inset:0,width:"100%",height:"100%",padding:0,border:0,appearance:"none",opacity:0,cursor:"pointer"},Qe={flex:"0 0 auto",color:"#8c8c8c",pointerEvents:"none"},et={position:"relative",minWidth:0},se=(e,t)=>({position:"absolute",top:"50%",[e]:8,zIndex:2,display:"grid",placeItems:"center",width:36,height:36,padding:0,border:"1px solid #e5e5e5",borderRadius:"50%",background:"#fff",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.16)",color:t?"#bfbfbf":"#262626",transform:"translateY(-50%)",cursor:t?"not-allowed":"pointer"}),tt={padding:"12px 14px",borderRadius:8,background:"rgba(255,77,79,0.08)",color:"#ff4d4f",fontSize:13,lineHeight:"20px"},N={padding:"12px 14px",borderRadius:8,background:"#fff",color:"#8c8c8c",fontSize:13,lineHeight:"20px",textAlign:"center"},ot={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{Pe as a,Ae as b,Ie as c,Re as d,ae as e,ke as f,Le as g,Ee as h,ct as i,Me as j,_e as k,He as l};
|
package/dist/chunk-RWUIBPQC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as q,d as $,f as F,g as K,h as A,i as P,k as V,m as W}from"./chunk-6VLQT22V.js";function X(e){return function(s,i,u){if(e.blockAll?.(s)!==!0)switch(i.type){case"sendMessage":case"submitForm":case"moduleAction":{if(e.canAct?.(s)===!1)return;e.sendToServer(s,i,u);break}case"openLink":{if(!i.url)break;e.openUrl?.(i.url);break}case"toast":{i.content&&e.toast?.(i.content,i.tone);break}case"closeCard":{e.closeCard?.(s);break}}}}import{createClientLogger as he}from"@tbox.cn/app-sdk-client";var Ie=he("CARD");function j(e,r){let s=i=>i.some(u=>u.id===r.id)?i.map(u=>u.id===r.id?r:u):[...i,r];return r.messageId?{...e,cardsByMessageId:{...e.cardsByMessageId,[r.messageId]:s(e.cardsByMessageId[r.messageId]||[])}}:{...e,orphanCards:s(e.orphanCards)}}function Ye(e,r){let s={};for(let[i,u]of Object.entries(e.cardsByMessageId))s[i]=u.filter(c=>c.id!==r);return{cardsByMessageId:s,orphanCards:e.orphanCards.filter(i=>i.id!==r)}}function z(e,r){let s=u=>{let c=u.findIndex(E=>E.id===r.id);if(c<0)return null;let p=[...u];return p[c]={...r,messageId:u[c].messageId,isHistory:u[c].isHistory,meta:{...u[c].meta,...r.meta,createdAt:u[c].meta?.createdAt??r.meta?.createdAt??Date.now(),...u[c].meta?.businessNo!==void 0?{businessNo:u[c].meta.businessNo}:{}}},p};for(let[u,c]of Object.entries(e.cardsByMessageId)){let p=s(c);if(p)return{...e,cardsByMessageId:{...e.cardsByMessageId,[u]:p}}}let i=s(e.orphanCards);return i?{...e,orphanCards:i}:(Ie.warn(`update 未命中卡实例:${r.id}(已隐藏/清空或非本连接下发)`),e)}import{TBOX_EFFECT_EVENT_NAME as et}from"@tbox.cn/app-contracts";import{requestPayment as ke}from"@tbox.cn/app-sdk-client";import{getAuthCode as Ae}from"@tbox.cn/app-sdk-client";import{createClientLogger as Ee}from"@tbox.cn/app-sdk-client";var _=Ee("tbox:effect");function Y(e){if(e===null||typeof e!="object")return!1;let r=e;return typeof r.type=="string"&&r.type.length>0}function Q(){let e=new Set;return r=>{let s=r.callback?.contextToken;return s?e.has(s)?!1:(e.add(s),!0):!0}}function Z(e){return e!==null&&typeof e=="object"&&typeof e.code=="string"?String(e.code):"BRIDGE_ERROR"}function ee(e){return Z(e)==="BRIDGE_UNAVAILABLE"}function Se(e){return e==="9000"?"success":e==="6001"?"cancel":"failure"}async function be(e,r){try{let s=await r.requestPayment(e.orderInfo);return{status:Se(s.resultCode),paymentRef:e.paymentRef}}catch(s){return{status:ee(s)?"unavailable":"failure",paymentRef:e.paymentRef}}}async function Te(e,r){try{let s=await r.getAuthCode([...e.scopes]);return typeof s.authCode!="string"||!s.authCode.trim()?{status:"failure"}:{status:"success",authCode:s.authCode}}catch(s){let i=Z(s);return ee(s)?{status:"unavailable"}:i.includes("CANCEL")?{status:"cancel"}:{status:"failure"}}}function J(e,r,s){if(e.callback)try{s({actionId:e.callback.actionId,contextToken:e.callback.contextToken,formData:{...r}})}catch(i){_.warn("结果回传失败:",i?.message)}}function te(e){let r={requestPayment:e?.requestPayment??ke,getAuthCode:e?.getAuthCode??Ae,sendModuleAction:e?.sendModuleAction??(()=>{_.warn("未注入 sendModuleAction,结果未回传")}),onSessionCredentialsRefreshed:e?.onSessionCredentialsRefreshed};return s=>{switch(s.type){case"payment":{be(s,r).then(i=>J(s,i,r.sendModuleAction));return}case"authorization.alipay-user-profile":{Te(s,r).then(i=>J(s,i,r.sendModuleAction));return}case"session.credentials-refreshed":{r.onSessionCredentialsRefreshed?.(s.reason);return}default:_.warn(`宿主效果类型未在客户端执行:${String(s.type)}`)}}}import{parseSkillReminders as Me,buildSkillToolCallPayload as Re,SKILL_NAME_PATTERN as se,SKILL_TOOL_CALL_NAME as xe}from"@tbox.cn/app-contracts";function re(e){let r=e.query??"",s=Me(r),i=new Map;for(let u of Array.isArray(e.skills)?e.skills:[])u?.name&&se.test(u.name)&&i.set(u.name,u);for(let u of s.skills)i.has(u)||i.set(u,{name:u});return{content:s.cleanedText,skills:[...i.values()]}}function ae(e,r){return e.filter(s=>s&&se.test(s.name)).map((s,i)=>{let{args:u,result:c}=Re(s);return{id:`skill-${r}-${i}`,name:xe,args:u,result:c,status:"done"}})}import{buildPreToolToolCallPayload as we,PRE_TOOL_CALL_NAME as ve,PRE_TOOL_NAME_PATTERN as oe}from"@tbox.cn/app-contracts";function Pe(e){return(Array.isArray(e.preTools)?e.preTools:[]).filter(r=>r?.toolName&&oe.test(r.toolName))}function He(e){let r=re(e);return{content:r.content,skills:r.skills,preTools:Pe(e)}}function Ne(e,r){let s=[];return(Array.isArray(e)?e:[]).filter(i=>i&&oe.test(i.toolName)).forEach((i,u)=>{try{let{args:c,result:p}=we(i);s.push({id:`pretool-${r}-${u}`,name:ve,args:c,result:p,status:"done"})}catch{}}),s}function _e(e,r){return[...Ne(e.preTools,r),...ae(e.skills,r)]}function Be(e){if(!e)return;let r=new Date(e.replace(" ","T")).getTime();return Number.isNaN(r)?void 0:r}function De(e,r){let s=e.messageId??e.id??e.outerBusinessId??`hist-${r}`,i=e.createTime??Be(e.requestTime)??Date.now();return{key:s,createdAt:i}}function ne(e){let r=0,s=c=>`${c}_${Date.now()}_${r++}`,i=[],u={};return e.forEach((c,p)=>{let{key:E,createdAt:h}=De(c,p),k=He(c);if(c.query){let t={id:`history-user-${E}`,role:"user",content:k.content,status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId}},o=c.multiModalInputs?.imageUrls;o&&o.length>0&&(t.mediaItems=o.map(a=>({id:s("history-img"),type:"image",src:a}))),i.push(t)}(c.answer||c.content||c.cards&&c.cards.length>0)&&i.push({id:`history-asst-${E}`,role:"assistant",content:c.answer||c.content||"",status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId},...k.skills.length>0||k.preTools.length>0?{toolCalls:_e(k,E)}:{}}),c.cards&&c.cards.length>0&&(u[`history-asst-${E}`]=c.cards.map(t=>({...t,isHistory:!0})))}),{messages:i,cardsByMessageId:u}}import{TBOX_CARD_EVENT_NAME as ie,TBOX_CARD_UPDATE_EVENT_NAME as Le,TBOX_EFFECT_EVENT_NAME as Ue,TBOX_NOTICE_EVENT_NAME as de}from"@tbox.cn/app-contracts";import{createClientLogger as x,setClientRunContext as B}from"@tbox.cn/app-sdk-client";import{isInAlipayShell as Oe}from"@tbox.cn/app-sdk-client";import{callJsapi as le}from"@tbox.cn/app-sdk-client";import{resolveAlipayNavigation as Ge}from"@tbox.cn/app-sdk-client";var b=x("tbox"),ce="网络连接不可用,请稍后重试",ue=x("CONVERSATION"),qe=x("SESSION-UPGRADE"),$e=x("HISTORY"),fe=x("FEEDBACK");function Fe(e){let r=String(e?.message||e||"");return/过期|expired|PARAM_INVALID|unauthorized|token/i.test(r)}var R=0,D=!1,H=null,I=null,L=!1;function Ke(e){let r=e.messageId??e.id??e.outerBusinessId;return r?`id:${r}`:`content:${e.requestTime??e.createTime??""}:${e.query??""}:${e.answer??e.content??""}`}var M;function At(e,r,s){if(!M){b.warn("卡动作通道未注册(应用 chat store 未创建),动作已丢弃");return}M(e,r,s)}function Ve(e){let r=M;return M=e,()=>{M===e&&(M=r)}}var We=0,T=e=>`${e}_${Date.now()}_${We++}`;function Xe(e,r,s){r(i=>({...i,...j({cardsByMessageId:i.cardsByMessageId,orphanCards:i.orphanCards},s)})),e.onCardEvent?.({type:"render",cardId:s.id,cardType:s.cardType,...s.messageId!==void 0?{messageId:s.messageId}:{},ts:Date.now()})}function je(e,r,s,i){let u={cardsByMessageId:s().cardsByMessageId,orphanCards:s().orphanCards},c=z(u,i);c!==u&&(r(p=>({...p,...c})),e.onCardEvent?.({type:"update",cardId:i.id,cardType:i.cardType,...i.messageId!==void 0?{messageId:i.messageId}:{},ts:Date.now()}))}function ge(e){A(e().conversationEstablished?{type:"RESUME_CONVERSATION"}:{type:"NEW_CONVERSATION"})}function St(e,r,s){q(e.getWsUrl),F(t=>{r({authBlocked:t.message}),e.toast(t.message,"error")});let i=Q(),u=te({sendModuleAction:({actionId:t,contextToken:o,formData:a})=>{A({type:"UI_ACTION",surfaceId:"",action:{type:"moduleAction",actionId:t,contextToken:o},formData:a})},...e.onSessionCredentialsRefreshed?{onSessionCredentialsRefreshed:e.onSessionCredentialsRefreshed}:{}}),c=e.onHostEffect??u,p=t=>{let{cardsByMessageId:o,orphanCards:a}=s();return[...Object.values(o).flat(),...a].find(d=>d.id===t)},E=X({canAct:t=>{if(s().isGenerating)return!1;let o=p(t);return!(o&&o.isHistory)},sendToServer:(t,o,a)=>{if(!P()){let l=p(t);e.onCardEvent?.({type:"click",cardId:t,cardType:l?.cardType??"",ts:Date.now()}),e.toast(ce,"error");return}let{addMessage:n}=s(),d=p(t);if(e.onCardEvent?.({type:"click",cardId:t,cardType:d?.cardType??"",ts:Date.now()}),o.type==="sendMessage"){o.visible!==!1&&n({id:T("user"),role:"user",content:o.displayText??o.value,status:"done",createdAt:Date.now()}),A({type:"UI_ACTION",surfaceId:t,action:o}),h=!0;return}if(o.type==="submitForm"){A({type:"UI_ACTION",surfaceId:t,action:o,formData:a??{}}),h=!0;return}A({type:"UI_ACTION",surfaceId:t,action:o,formData:a??{}})},toast:(t,o)=>e.toast(t,o),openUrl:t=>{if(!(typeof window>"u")){if(t.startsWith("tel:")){window.location.href=t;return}if(Oe()){if(t.startsWith("alipays://")||t.startsWith("alipayrisk://")){let o=Ge(t,s().helloAck?.mallScope?.miniAppId);o?(b.info(`[openUrl] ${o.apiName} url=${t}`),le(o.apiName,o.params).catch(a=>{b.warn(`[openUrl] ${o.apiName} failed url=${t}`,a),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error")})):(b.warn(`[openUrl] unresolved Alipay deep link url=${t}`),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error"))}else b.info(`[openUrl] ap.openURL url=${t}`),le("ap.openURL",{url:t}).catch(o=>{b.warn(`[openUrl] ap.openURL failed url=${t}`,o),e.toast("当前无法打开该链接,请稍后再试","error")});return}window.open&&window.open(t,"_blank")}},closeCard:t=>s().hideCard(t)});Ve((t,o,a)=>{s().sendUiAction(t,o,a)});let h=!1,k=()=>{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:()=>{K(t=>{let o=s();switch(t.type){case"HELLO_ACK":{r({helloAck:{...t.mallScope?{mallScope:t.mallScope}:{},chatConfig:t.chatConfig,...t.toolDebug?{toolDebug:!0}:{}},authBlocked:null});break}case"RUN_STARTED":{if(!h)break;h=!1;let a=T("thinking");o.addMessage({id:a,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({isGenerating:!0,currentRunId:t.runId,streamingMsgId:a}),B({runId:t.runId,...t.threadId&&{conversationId:t.threadId}});break}case"CUSTOM":{if(t.name===ie){let a=t.value;Xe(e,r,a),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ie,{detail:a}))}else if(t.name===Le)je(e,r,s,t.value);else if(t.name===Ue&&Y(t.value))i(t.value)&&c(t.value);else if(t.name===de){let a=t.value;a?.text&&e.toast(a.text,a.level??"info"),typeof window<"u"&&a?.text&&window.dispatchEvent(new CustomEvent(de,{detail:a}))}break}case"REASONING_START":{if(!s().isGenerating)break;if(!s().streamingMsgId){let a=T("thinking");o.addMessage({id:a,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({streamingMsgId:a})}break}case"REASONING_MESSAGE_CONTENT":{let{streamingMsgId:a}=s();if(!a)break;r(n=>({messages:n.messages.map(d=>d.id===a?{...d,reasoning:(d.reasoning||"")+t.delta}:d)}));break}case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"TOOL_CALL_START":{if(!s().isGenerating)break;let{streamingMsgId:a}=s();if(!a){let n=T("thinking");o.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),r({streamingMsgId:n}),a=n}r(n=>({messages:n.messages.map(d=>d.id===a?{...d,toolCalls:[...d.toolCalls||[],{id:t.toolCallId,name:t.toolCallName,status:"calling"}]}:d)}));break}case"TOOL_CALL_ARGS":{let{streamingMsgId:a}=s();if(!a)break;r(n=>({messages:n.messages.map(d=>d.id===a?{...d,toolCalls:(d.toolCalls||[]).map(l=>l.id===t.toolCallId?{...l,args:(l.args||"")+t.delta}:l)}:d)}));break}case"TOOL_CALL_END":break;case"TOOL_CALL_RESULT":{let{streamingMsgId:a}=s();if(!a)break;r(n=>({messages:n.messages.map(d=>d.id===a?{...d,toolCalls:(d.toolCalls||[]).map(l=>l.id===t.toolCallId?{...l,result:t.content,status:t.isError?"error":"done",...t.isError?{error:t.errorMessage??"工具执行失败"}:{}}:l)}:d)}));break}case"TEXT_MESSAGE_START":{if(!s().isGenerating)break;let a=t.messageId,{streamingMsgId:n}=s();n?.startsWith("thinking_")?r(d=>({streamingMsgId:a,messages:d.messages.map(l=>l.id===n?{...l,id:a,status:"streaming"}:l)})):(o.addMessage({id:a,role:"assistant",content:"",status:"streaming",createdAt:Date.now()}),r({streamingMsgId:a}));break}case"TEXT_MESSAGE_CONTENT":{let{streamingMsgId:a}=s();a&&t.messageId===a&&s().appendDelta(a,t.delta);break}case"TEXT_MESSAGE_END":{let{streamingMsgId:a}=s();a&&(o.updateMessage(a,{status:"done"}),r({streamingMsgId:null}));break}case"RUN_FINISHED":{if(t.runId&&t.runId!==s().currentRunId)break;let a=t.rawEvent?.requestId;r(a?n=>{let d=[...n.messages];for(let l=d.length-1;l>=0;l--)if(d[l].role==="assistant"&&d[l].status==="done"){d[l]={...d[l],requestId:a,...t.threadId&&{conversationId:t.threadId}};break}return{isGenerating:!1,currentRunId:null,messages:d}}:{isGenerating:!1,currentRunId:null});{let n=0,d=s().messages.map(l=>l.role!=="assistant"||!l.toolCalls?.some(f=>f.status==="calling")?l:(n+=l.toolCalls.filter(f=>f.status==="calling").length,{...l,toolCalls:l.toolCalls.map(f=>f.status==="calling"?{...f,status:"error",error:"工具执行未返回结果"}:f)}));n>0&&(r({messages:d}),b.warn(`RUN_FINISHED:${n} 个工具未收到终态事件,已收敛为失败态`))}B(null);break}case"RUN_ERROR":{if(!s().isGenerating&&!s().currentRunId)break;let a=t.runId;if(a&&a!==s().currentRunId)break;let n=s().streamingMsgId,d=t.message||"请求失败,请重试",l=t.rawEvent?.requestId??a??s().currentRunId??void 0,f=t.threadId;r(S=>{let y=n?S.messages.find(g=>g.id===n):void 0,m={...y??{id:T("error"),role:"assistant",content:"",createdAt:Date.now()},status:"error",error:d,...l&&{requestId:y?.requestId??l},...f&&{conversationId:y?.conversationId??f},toolCalls:y?.toolCalls?.map(g=>g.status==="calling"?{...g,status:"error",error:"请求中断"}:g)};return{isGenerating:!1,currentRunId:null,streamingMsgId:null,messages:y?S.messages.map(g=>g.id===y.id?m:g):[...S.messages,m]}}),B(null);break}}},()=>{let t=$(),o=W();A({type:"HELLO",...t?{token:t}:{},...o?{context:o}:{}}),ge(s)})},sendMessage:t=>{let{addMessage:o,isGenerating:a}=s();if(a)return;if(!P()){e.toast(ce,"error");return}let n=typeof t=="string"?t:t.text,d=typeof t=="string"?void 0:t.mediaItems,l=typeof t=="string"?void 0:t.inputMethod;o({id:T("user"),role:"user",content:n,status:"done",createdAt:Date.now(),mediaItems:d,inputMethod:l}),A({type:"SEND_MESSAGE",content:n,mediaItems:d?.filter(f=>f.fileId).map(f=>({fileId:f.fileId,type:f.type,name:f.name,mimeType:f.mimeType})),inputMethod:l}),h=!0},sendUiAction:(t,o,a)=>{E(t,o,a)},hideCard:t=>{r(o=>{let a={};for(let[n,d]of Object.entries(o.cardsByMessageId))a[n]=d.filter(l=>l.id!==t);return{cardsByMessageId:a,orphanCards:o.orphanCards.filter(n=>n.id!==t)}})},destroy:()=>V(),clearChat:()=>{s().cancelGeneration(),h=!1,r({messages:[],currentRunId:null,streamingMsgId:null,isGenerating:!1,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[]})},addMessage:t=>r(o=>({messages:[...o.messages,t]})),appendDelta:(t,o)=>r(a=>({messages:a.messages.map(n=>n.id===t?{...n,content:n.content+o}:n)})),updateMessage:(t,o)=>r(a=>({messages:a.messages.map(n=>n.id===t?{...n,...o}:n)})),setGenerating:t=>r({isGenerating:t}),cancelGeneration:()=>{h=!1;let{streamingMsgId:t,isGenerating:o,currentRunId:a}=s();if(o){if(A({type:"CANCEL_RUN",...a&&{runId:a}}),t){let n=s().messages.find(d=>d.id===t);n&&!n.content?r(d=>({messages:d.messages.filter(l=>l.id!==t)})):r(d=>({messages:d.messages.map(l=>l.id===t?{...l,status:"done",toolCalls:l.toolCalls?.map(f=>f.status==="calling"?{...f,status:"done"}:f)}:l)}))}r({isGenerating:!1,currentRunId:null,streamingMsgId:null})}},setAuthBlocked:t=>r({authBlocked:t}),setUserId:t=>{s().userId&&s().userId!==t&&r({conversationEstablished:!1}),r({userId:t})},historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null,runtimeStatus:"bootstrapping",initConversation:async()=>{let{authClient:t}=k();if(H)return H;let o;H=new Promise(a=>{o=a});try{let a=s().userId,n=await t.resolveUserId();if(a&&a!==n&&(R++,r({conversationEstablished:!1}),r({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null})),r({userId:n}),!t.getAuthState()?.token){ue.warn("anonymous: skip WS init, expose recoverable auth failure"),r({runtimeStatus:"failed",conversationEstablished:!1}),s().setAuthBlocked("登录失败,暂时无法对话"),e.toast("登录失败,暂时无法对话","error");return}let d=P();s().init(),r({runtimeStatus:"ready"}),d&&ge(s)}catch(a){ue.error("init error:",a),s().init(),r({runtimeStatus:"failed"})}finally{H=null,o()}},retryBootstrap:(t=!0)=>{let{authClient:o}=k();if(I)return I;let n=(async()=>{r({runtimeStatus:"bootstrapping"}),t&&o.clearAuth(),s().destroy(),await s().initConversation()})().finally(()=>{I===n&&(I=null)});return I=n,n},newConversation:async()=>{if(!D){D=!0;try{R++,s().clearChat(),r({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null}),await s().initConversation()}finally{D=!1}}},scheduleSessionUpgrade:()=>{let{authClient:t}=k();if(I)return I;if(s().isGenerating)return L=!0,Promise.resolve();let a=(async()=>{r({runtimeStatus:"bootstrapping"});try{t.clearAuth(),await t.ensureAuth(),s().destroy(),await s().initConversation()}catch(n){qe.error("unexpected error:",n),r({runtimeStatus:"failed"})}finally{L=!1}})().finally(()=>{I===a&&(I=null)});return I=a,a},loadMoreHistory:async()=>{let{platformApi:t}=k(),{isLoadingHistory:o,historyHasMore:a,historyMessages:n,historyBeforeId:d}=s();if(o||!a)return;let l=R;r({isLoadingHistory:!0});let f=5,S=n.length===0?s().messages.find(m=>m.requestId)?.requestId:void 0,y=d??S;try{let{status:m,data:g}=await t.listMessages({pageSize:f,...y?{beforeId:y}:{}});if(l!==R)return;if(m===200&&g){let w=g.data||[],pe=new Set(s().messages.map(C=>C.requestId).filter(Boolean)),U=new Set(s().historyEntryKeys),O=[],G=w.filter(C=>{let N=Ke(C);return U.has(N)?!1:(U.add(N),O.push(N),!C.outerBusinessId||!pe.has(C.outerBusinessId))}),v=[...w].reverse().find(C=>C.outerBusinessId)?.outerBusinessId??null,ye=G.length>0||!!v&&v!==y,{messages:me,cardsByMessageId:Ce}=ne(G.reverse());r(C=>({historyMessages:[...me,...C.historyMessages],historyHasMore:w.length>=f&&!!v&&ye,isLoadingHistory:!1,historyEntryKeys:[...O,...C.historyEntryKeys],historyBeforeId:v,cardsByMessageId:{...C.cardsByMessageId,...Ce}}))}else r({isLoadingHistory:!1})}catch(m){if($e.error("load more error:",m),l!==R)return;r({isLoadingHistory:!1})}},submitFeedback:async(t,o,a,n)=>{let d=s().messages.find(m=>m.id===t),l=d?.feedbackState??"none",f=d?.requestId;if(!f){fe.warn("no requestId for message",t);return}let S=o==="cancel"?"none":o;s().updateMessage(t,{feedbackState:S});let y={like:"LIKE",dislike:"DISLIKE",cancel:"CANCEL"};try{(await a.addTag(f,y[o])).success||s().updateMessage(t,{feedbackState:l})}catch(m){if(Fe(m)&&n)try{let g=await n();if(g.feedback){(await g.feedback.addTag(f,y[o])).success||s().updateMessage(t,{feedbackState:l});return}}catch(g){fe.error("retry failed:",g)}s().updateMessage(t,{feedbackState:l})}}}}function bt(e){return e.subscribe((r,s)=>{L&&s.isGenerating&&!r.isGenerating&&e.getState().scheduleSessionUpgrade()})}export{X as a,j as b,Ye as c,Y as d,Q as e,Se as f,be as g,Te as h,te as i,re as j,ae as k,Pe as l,He as m,Ne as n,_e as o,De as p,ne as q,Fe as r,At as s,Ve as t,St as u,bt as v};
|