@tbox.cn/app-agent-sdk-client 0.2.2 → 1.0.0-alpha.10
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.d.ts +18 -0
- package/dist/app/card-preview.js +1 -0
- package/dist/app/index.d.ts +27 -0
- package/dist/app/index.js +1 -0
- package/dist/chunk-6VLQT22V.js +1 -0
- package/dist/chunk-AW4ZSI4F.js +1 -0
- package/dist/chunk-HE3FQIAS.js +1 -0
- package/dist/chunk-RWUIBPQC.js +1 -0
- package/dist/chunk-YTXQ3WRK.js +1 -0
- package/dist/client/card-preview.js +1 -1
- package/dist/client/index.d.ts +10 -1
- package/dist/client/index.js +1 -1
- package/package.json +13 -5
- package/dist/chunk-FA7CKDRJ.js +0 -1
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { AppConfig } from '@tbox.cn/app-sdk-client/app';
|
|
3
|
+
import { AppClientModule } from '@tbox.cn/app-sdk-client';
|
|
4
|
+
import { CardComponent } from '@tbox.cn/app-contracts';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 卡片预览平台页启动:注册模块/卡片后渲染 SDK 预览页。
|
|
8
|
+
* 使用独立子路径,避免主 entry 把预览代码带进主 bundle。
|
|
9
|
+
*/
|
|
10
|
+
declare function startCardPreview(options?: {
|
|
11
|
+
config?: AppConfig;
|
|
12
|
+
modules?: readonly AppClientModule[];
|
|
13
|
+
cards?: Record<string, CardComponent>;
|
|
14
|
+
/** 预览面的装配根;缺省取 `config.wrapPreview`。 */
|
|
15
|
+
wrap?: (page: ReactNode) => ReactNode;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
|
|
18
|
+
export { startCardPreview };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as o}from"../chunk-HE3FQIAS.js";import"../chunk-RWUIBPQC.js";import{d as t}from"../chunk-AW4ZSI4F.js";import"../chunk-6VLQT22V.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};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ComponentType, ReactNode } from 'react';
|
|
2
|
+
import { Adapters, TboxSessionData } from '@tbox.cn/app-contracts';
|
|
3
|
+
import { AppConfig, StartAppOptions } from '@tbox.cn/app-sdk-client/app';
|
|
4
|
+
|
|
5
|
+
interface AgentAppConfig extends AppConfig {
|
|
6
|
+
/** 默认 = AgentAppShell;false = 不包壳;组件 = 替换壳。 */
|
|
7
|
+
shell?: false | ComponentType<{
|
|
8
|
+
config: AgentAppConfig;
|
|
9
|
+
children: ReactNode;
|
|
10
|
+
}>;
|
|
11
|
+
/** 覆盖 createPlatformAdapters 的默认实现(ASR/TTS/upload/feedback)。 */
|
|
12
|
+
adapters?: Partial<Adapters>;
|
|
13
|
+
/** 首次会话与 refresh 后回调;抛错只记日志,不断链。 */
|
|
14
|
+
onSession?: (session: TboxSessionData) => void;
|
|
15
|
+
}
|
|
16
|
+
interface StartAgentAppOptions extends Omit<StartAppOptions, 'wrap'> {
|
|
17
|
+
config: AgentAppConfig;
|
|
18
|
+
}
|
|
19
|
+
/** 默认 Agent 壳:session 引导 + AdapterProvider + TTS 单实例 + refreshSession。 */
|
|
20
|
+
declare function AgentAppShell({ config, children, }: {
|
|
21
|
+
config: AgentAppConfig;
|
|
22
|
+
children: ReactNode;
|
|
23
|
+
}): JSX.Element;
|
|
24
|
+
/** Agent 应用启动:在通用 startApp 上注入默认 AgentAppShell。 */
|
|
25
|
+
declare function startAgentApp(options: StartAgentAppOptions): Promise<void>;
|
|
26
|
+
|
|
27
|
+
export { type AgentAppConfig, AgentAppShell, type StartAgentAppOptions, startAgentApp };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as c,o as a,q as A}from"../chunk-YTXQ3WRK.js";import{d as l}from"../chunk-AW4ZSI4F.js";import"../chunk-6VLQT22V.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
|
+
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as O,e as $,m as P}from"./chunk-6VLQT22V.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};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +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 +1 @@
|
|
|
1
|
-
import{G as j}from"../chunk-FA7CKDRJ.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{Re as AUTH_ERROR_MSG,ct as CardPreviewPage,Ae as EMPTY_CATALOG_MSG,Ie as EMPTY_MODULE_MSG,Pe as EMPTY_REGISTRY_MSG,Le as HISTORY_VIEW_LABEL,ae as LOAD_ERROR_MSG,Ee as MODULE_ALL_LABEL,ke as PAGE_TITLE,_e as PreviewRows,He as PreviewSurface,Me as buildPreviewRows};
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l}from"../chunk-HE3FQIAS.js";import"../chunk-RWUIBPQC.js";import"../chunk-6VLQT22V.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
|
@@ -92,6 +92,15 @@ interface PlatformApi {
|
|
|
92
92
|
listMessages(opts: ListMessagesOptions): Promise<ListMessagesResult>;
|
|
93
93
|
}
|
|
94
94
|
declare function createPlatformApi(): PlatformApi;
|
|
95
|
+
/**
|
|
96
|
+
* 应用级 PlatformApi 单例(与 getAuthClient 同语义)。
|
|
97
|
+
*
|
|
98
|
+
* 应用装配(app.config / startAgentApp)先建单例,shell 与 store 渲染期读取;
|
|
99
|
+
* 未建则按缺省首建。约束:模块勿在 import 期调用(延迟到渲染/请求期)。
|
|
100
|
+
*/
|
|
101
|
+
declare function getPlatformApi(): PlatformApi;
|
|
102
|
+
/** 测试专用:重置应用级单例(仅测试调用)。 */
|
|
103
|
+
declare function __resetPlatformApiSingleton(): void;
|
|
95
104
|
|
|
96
105
|
/**
|
|
97
106
|
* SDK client 侧依赖的 app 注入接口。
|
|
@@ -733,4 +742,4 @@ declare function consumeAutoSendQuery(): string | null;
|
|
|
733
742
|
/** 编排:等 socket OPEN → 移交 send(isGenerating/isWsOpen 判定归 sendMessage 咽喉) */
|
|
734
743
|
declare function runAutoSend(text: string, send: (text: string) => void, timeoutMs?: number): Promise<void>;
|
|
735
744
|
|
|
736
|
-
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, 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, hideCard, isHostEffect, isSessionExpiredError, isWsOpen, mapPaymentResultCode, resolveHistoryMessage, resolveHistoryMeta, resolveHistoryPreTools, resolveHistorySkills, runAutoSend, send, sendCardAction, setActionAuthTokenGetter, subscribeSessionUpgradeDrain, upsertCard, useASRAdapter, useAdapters, useFeedbackAdapter, useRefreshSession, useTTSAdapter, useUploadAdapter, waitForSocketOpen };
|
|
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 };
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as Rt,B as Pt,C as wt,D as $,E as It,F as U,G as Et,H as _t,I as Ut,a as st,b as it,c as D,d as F,e as O,f as nt,g as at,h as lt,i as pt,j as L,k as dt,l as ct,m as ut,n as ht,o as ft,p as mt,q as yt,r as gt,s as St,t as At,u as xt,v as bt,w as Tt,x as Ct,y as vt,z as kt}from"../chunk-FA7CKDRJ.js";export*from"@tbox.cn/app-sdk-client";import{jsx as J}from"react/jsx-runtime";function Mt(r){let{actions:t,cardId:e,isHistory:o,className:s,chipClassName:i}=r;return!t||t.length===0?null:J("div",{className:`tbox-item-actions ${s??""}`.trim(),children:t.map((n,a)=>J("button",{type:"button",className:`tbox-chip ${i??""}`.trim(),disabled:o&&n.kind==="send",onClick:()=>{n.kind==="send"?U(e,{type:"sendMessage",value:n.value??n.label,...n.visibleValue?{displayText:n.visibleValue}:{},visible:!0}):U(e,{type:"openLink",url:n.url??""})},children:n.label},a))})}import{createContext as Ht,useContext as x}from"react";import{jsx as Nt}from"react/jsx-runtime";var y=Ht({});function Dt({value:r,children:t}){return Nt(y.Provider,{value:r,children:t})}var Ft=()=>x(y),Ot=()=>x(y).asr,Lt=()=>x(y).tts,$t=()=>x(y).upload,Kt=()=>x(y).feedback,Bt=()=>x(y).refreshSession;import{createClientLogger as Wt}from"@tbox.cn/app-sdk-client";var K=Wt("ACTION"),Gt=0;function Vt(r){return`${r}_${Date.now()}_${Gt++}_${Math.random().toString(36).slice(2,8)}`}var B=null;function N(r){B=r}async function Xt(r,t,e={}){let o=e.baseUrl??"",s={action:r,payload:t,...e.sessionId&&{sessionId:e.sessionId},...e.idempotencyKey&&{idempotencyKey:e.idempotencyKey}},i=s.idempotencyKey?s:{...s,idempotencyKey:Vt(r)},n=e.token??(B?B():null),a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let d;try{d=await fetch(`${o}/api/action`,{method:"POST",headers:a,body:JSON.stringify(i)})}catch(T){let E=T?.message||"网络错误";return K.warn(`POST /api/action action=${r} fetch 异常:${E}`),{success:!1,error:E}}let h;try{h=await d.json()}catch{return K.warn(`POST /api/action action=${r} 响应解析失败(HTTP ${d.status})`),{success:!1,error:`响应解析失败(HTTP ${d.status})`}}return d.status===409?(K.warn(`POST /api/action action=${r} 幂等键冲突:${h.error||"请勿重复提交"}`),{success:!1,error:h.error||"幂等键冲突:请勿重复提交",cached:!1}):d.status===200&&h.cached?{...h,cached:!0}:h}function zt(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var W=class{snapshots=new Map;async save(t,e){let o=this.snapshots.get(t)??[],s=o.findIndex(n=>n.id===e.id),i={id:e.id,cardType:e.cardType,data:e.data,status:e.status,schemaVersion:e.schemaVersion??1,meta:e.meta};s>=0?o[s]=i:o.push(i),this.snapshots.set(t,o)}async load(t){return(this.snapshots.get(t)??[]).map(o=>zt(o))}async clear(t){this.snapshots.delete(t)}};import{isInAlipayShell as Jt}from"@tbox.cn/app-sdk-client";import{getAuthCode as Yt}from"@tbox.cn/app-sdk-client";import{httpPost as Y,httpGet as qt,configureAuthToken as Qt,configureAuthErrorHandler as jt}from"@tbox.cn/app-sdk-client";import{createClientLogger as Zt}from"@tbox.cn/app-sdk-client";var c=Zt("AUTH");function G(r){if(typeof r!="object"||r===null)return!1;let{userId:t,source:e}=r;return typeof t=="string"&&t.length>0&&(e==="local"||e==="external"||e==="guest")}var g="tbox.auth.token",q="tbox.auth.scopeKey",M="tbox.auth.lastToken",C=null,H=null;function Q(r={}){let t=r.loginPlatform??"alipay";return C?(H&&H.loginPlatform!==t&&c.warn(`createAuthClient 重复调用且选项不同(当前 ${H.loginPlatform} vs ${t}),返回首建单例(首建选项生效)`),C):(C=ee({loginPlatform:t,...r.scopeKey?{scopeKey:r.scopeKey}:{}}),H={loginPlatform:t},C)}function te(){return C??Q()}function ee(r={}){let t=r.loginPlatform??"alipay",e=r.scopeKey,o=null,s=null,i=null;function n(l){try{return typeof localStorage<"u"?localStorage.getItem(l):null}catch{return null}}function a(l,A){try{typeof localStorage<"u"&&localStorage.setItem(l,A)}catch{}}function d(l){try{typeof localStorage<"u"&&localStorage.removeItem(l)}catch{}}async function h(){return o||s||(s=rt().then(l=>(s=null,l),l=>{throw s=null,l}),s)}async function T(){return i||(o=null,i=h().finally(()=>{i=null}),i)}function E(){o=null,s=null,d(g)}function et(){return o}async function rt(){if(e){let p;try{p=e()}catch{p=""}n(q)!==p&&(d(g),d(M)),a(q,p)}let l=n(g);if(l)try{let{status:p,data:f}=await qt("/api/auth/me",{cache:"no-store",headers:{Authorization:`Bearer ${l}`}});if(p===200&&G(f?.identity))return c.info("identity from cached token:",f.identity.userId),_({token:l,identity:f.identity});c.warn("cached token invalid (status=%s), re-login",p),d(g)}catch(p){c.warn("/api/auth/me failed, re-login:",p.message),d(g)}let A=n(M);if(Jt()){c.info("alipay shell, starting getAuthCode login...");try{let{authCode:p}=await Yt(["auth_base"]),f=$(),{status:u,data:m}=await Y("/api/auth/login",{method:"code",code:p,platform:t,...f?{context:f}:{},...A?{previousToken:A}:{}});if(u===200&&m?.token&&G(m?.identity))return a(g,m.token),a(M,m.token),c.info("identity via alipay login:",m.identity.userId),_({token:m.token,identity:m.identity});c.warn("alipay login failed: status=%s error=%s",u,m?.error??"(no body)")}catch(p){c.error("alipay login error:",p)}return z()}try{let p=$(),{status:f,data:u}=await Y("/api/auth/login",{method:"browser",...p?{context:p}:{},...A?{previousToken:A}:{}});if(f===200&&u?.token&&G(u?.identity))return a(g,u.token),a(M,u.token),c.info("identity via browser login:",u.identity.userId),_({token:u.token,identity:u.identity});c.warn("browser login unavailable: status=%s error=%s(403 = 服务端 browserLoginMode 关闭或生产禁 mock)",f,u?.error??"(no body)")}catch(p){c.warn("browser login error:",p.message)}return z()}function z(){let l={userId:`anonymous_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"};return c.warn("fallback to anonymous:",l.userId),_({token:null,identity:l})}function _(l){return o=l,Qt(()=>o?.token??null),D(()=>o?.token??null),N(()=>o?.token??null),jt(()=>T()),O(()=>T()),l}async function ot(){return(await h()).identity.userId}return{ensureAuth:h,refreshAuth:T,clearAuth:E,getAuthState:et,resolveUserId:ot}}import{httpPost as re}from"@tbox.cn/app-sdk-client";function b(r){return{"X-Tbox-Session-Id":r.tboxSessionId,"X-Tbox-Channel":r.channel,"X-Tbox-AppId":r.appId}}var S=class{constructor(t){this.session=t}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let t=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=t,this.audioChunks=[];let e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",o=new MediaRecorder(t,{mimeType:e});this.mediaRecorder=o,o.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},o.start()}stopRecording(){return new Promise((t,e)=>{let o=this.mediaRecorder;if(!o||o.state==="inactive"){this.cleanup(),t("");return}o.onstop=async()=>{if(this.cancelled){this.cleanup(),t("");return}try{let s=new Blob(this.audioChunks,{type:o.mimeType}),i=await this.blobToBase64(s),{status:n,data:a}=await re("/api/tbox/asr",{base64_audio:i,audio_format:"webm",sample_rate:"16000"},{headers:b(this.session)});t(n===200&&a?.text?a.text:"")}catch(s){e(s)}finally{this.cleanup()}},o.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(t){return new Promise((e,o)=>{let s=new FileReader;s.onloadend=()=>e(s.result.split(",")[1]||""),s.onerror=o,s.readAsDataURL(t)})}cleanup(){this.mediaStream?.getTracks().forEach(t=>t.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as V}from"@tbox.cn/app-sdk-client";import{httpPost as oe}from"@tbox.cn/app-sdk-client";var v=class{constructor(t){this.session=t}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await V("startRecord",{},"invoke")}async stopRecording(){let t=await V("stopRecord",{},"invoke");if(this.cancelled)return"";let e=t?.audioBase64;if(!e)return"";let{status:o,data:s}=await oe("/api/tbox/asr",{base64_audio:e,audio_format:t.format||"mp3",sample_rate:"16000"},{headers:b(this.session)});return o===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,V("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as se}from"@tbox.cn/app-sdk-client";var ie=se("asr"),k=class{bridge;browser;active;constructor(t){this.bridge=new v(t),this.browser=new S(t),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(t){ie.warn("桥录音失败,降级到 H5 getUserMedia:",t),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as ne}from"@tbox.cn/app-sdk-client";var R=class{constructor(t){this.session=t}session;onProgress;async upload(t,e){let o;typeof t=="string"?o=await(await fetch(t)).blob():o=t;let{status:s,data:i}=await ne("/api/tbox/upload",o,{headers:{"Content-Type":o.type||"application/octet-stream","X-Tbox-Session-Id":this.session.tboxSessionId,"X-Tbox-Channel":this.session.channel,"X-Tbox-AppId":this.session.appId,"X-Tbox-File-Type":e?.type||"file",...e?.name?{"X-Tbox-File-Name":encodeURIComponent(e.name)}:{}}});if(s!==200||!i?.fileId)throw new Error(`[tbox-upload] ${i?.errorCode??`HTTP_${s}`} ${i?.error??""}`.trim());return{fileId:i.fileId,url:"",mimeType:typeof i.fileType=="string"?i.fileType:void 0,safed:i.safed}}};import{httpPost as ae}from"@tbox.cn/app-sdk-client";var P=class{constructor(t){this.session=t}session;async addTag(t,e){let{status:o,data:s}=await ae("/api/tbox/feedback",{requestId:t,feedback:e},{headers:b(this.session)});return{success:o===200&&!!s?.success}}};var w=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(t){this.sampleRate=t.sampleRate,this.onPlayEnd=t.onPlayEnd}start(){this.isStopped=!1,this.inputCount=0,this.endedCount=0,this.totalInputCount=-1,this.playEndFired=!1,!this.audioContext&&(this.audioContext=new AudioContext({sampleRate:this.sampleRate}),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.nextStartTime=this.audioContext.currentTime)}input(t){if(this.isStopped||!this.audioContext)return;let e=new Int16Array(t);if(e.length===0)return;let o=new Float32Array(e.length);for(let a=0;a<e.length;a++)o[a]=e[a]/32768;let s=this.audioContext.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=this.audioContext.createBufferSource();i.buffer=s,i.connect(this.audioContext.destination);let n=this.audioContext.currentTime;this.nextStartTime<n&&(this.nextStartTime=n),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,i.onended=()=>{this.endedCount++,this.checkPlayEnd()}}finish(){if(this.totalInputCount=this.inputCount,this.totalInputCount===0){this.firePlayEnd();return}if(this.checkPlayEnd(),this.audioContext&&!this.isStopped&&!this.playEndFired){let t=this.nextStartTime-this.audioContext.currentTime,e=Math.max(0,t*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},e)}}stop(){this.isStopped=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null)}async pause(){this.isStopped||!this.audioContext||await this.audioContext.suspend()}async resume(){this.isStopped||!this.audioContext||await this.audioContext.resume()}checkPlayEnd(){this.totalInputCount>0&&this.endedCount>=this.totalInputCount&&!this.isStopped&&this.firePlayEnd()}firePlayEnd(){this.playEndFired||(this.playEndFired=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.onPlayEnd?.())}};import{getWsUrl as le}from"@tbox.cn/app-sdk-client";import{createClientLogger as pe}from"@tbox.cn/app-sdk-client";var j=pe("TTS"),I=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(t){return this.stop(),new Promise(e=>{this.speakResolve=e,this.startStreaming().then(()=>{this.sendText(t),this.finishStreaming()}).catch(()=>{this.setState("idle"),this.resolveSpeak()})})}pause(){this._state!=="playing"||!this.player||(this.player.pause(),this.setState("paused"))}resume(){this._state!=="paused"||!this.player||(this.player.resume(),this.setState("playing"))}stop(){this._canSend=!1,this.pending="",this.pendingFinish=!1,this.closeSocket(),this.player&&(this.player.stop(),this.player=null),this.setState("idle"),this.resolveSpeak()}onStateChange(t){return this.stateCallbacks.add(t),this._state!=="idle"&&t(this._state),()=>this.stateCallbacks.delete(t)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new w({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let t=le("/ws/tts"),e=F(),o=e?`${t}?token=${encodeURIComponent(e)}`:t;return new Promise((s,i)=>{let n=new WebSocket(o);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},n.onmessage=a=>this.handleMessage(a.data),n.onclose=()=>{this.socket=null,this.player?.finish()},n.onerror=a=>{j.error("socket error",a),i(a),this.stop()}})}sendText(t){t&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:t}):this.pending+=t)}finishStreaming(){this._canSend?(this.flushPending(),this.sendMessage({type:"TTS_FINISH"})):this.pendingFinish=!0}flushPending(){this.pending&&(this.sendMessage({type:"TTS_TEXT",text:this.pending}),this.pending="")}handleMessage(t){if(typeof t=="string"){try{let e=JSON.parse(t);switch(e.actionType){case"start_ack":this._canSend=!0,this.flushPending(),this.pendingFinish&&(this.pendingFinish=!1,this.sendMessage({type:"TTS_FINISH"}));break;case"completed":this.player?.finish(),this.closeSocket();break;case"failed":j.error("server error",e.error||e),this.stop();break}}catch{if(!this.player||t.length===0)return;this._state==="loading"&&this.setState("playing");let e=new ArrayBuffer(t.length),o=new Uint8Array(e);for(let s=0;s<t.length;s++)o[s]=t.charCodeAt(s);this.player.input(e)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(t))}sendMessage(t){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(t))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(t){this._state!==t&&(this._state=t,this.stateCallbacks.forEach(e=>e(t)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as de,isInAlipayShell as ce}from"@tbox.cn/app-sdk-client";function ue(r,t){let e={};return t?.tts||(e.tts=new I),r&&(e.asr=ce()||de()?new k(r):new S(r),e.upload=new R(r),e.feedback=new P(r)),t?{...e,...t}:e}import{httpGet as Z}from"@tbox.cn/app-sdk-client";function he(){let r=null;async function t(s=!1){if(r&&!s)return r;r=null;let{status:i,data:n}=await Z("/api/tbox/session",{cache:"no-store"});if(i!==200)throw new Error(`[tbox-session] fetch failed: ${i}`);return r=n,r}function e(){r=null}async function o(s){let i=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(i+=`&beforeId=${encodeURIComponent(s.beforeId)}`),Z(i,{cache:"no-store"})}return{getTboxSession:t,clearTboxSession:e,listMessages:o}}import{createClientLogger as fe}from"@tbox.cn/app-sdk-client";var X=fe("AUTO-SEND"),tt=["query","prompt"];function me(r){let t=new URLSearchParams(r);for(let e of tt){let o=t.get(e)?.trim();if(o)return o}return null}function ye(r){let t=new URL(r);for(let e of tt)t.searchParams.delete(e);return t.toString()}function ge(){if(typeof window>"u")return null;let r=me(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",ye(window.location.href))}catch(t){X.warn("strip failed (URL retained; refresh may re-send):",t)}return r}async function Se(r,t,e=5e3){if(!await L(e)){X.warn("skipped:reason=socket-timeout");return}t(r),X.info("sent")}export{Dt as AdapterProvider,v as AlipayASRAdapter,w as AudioStreamPlayer,S as BrowserASRAdapter,k as FallbackASRAdapter,P as FeedbackAdapter,W as InMemoryCardHistoryLoader,Mt as ItemActionsRow,I as TTSAdapter,R as UploadAdapter,Et as bindCardActionChannel,kt as buildHistoryToolCalls,vt as buildPreToolToolCalls,bt as buildSkillToolCalls,Xt as callAction,wt as configureHelloContext,O as configureWsAuthErrorHandler,D as configureWsAuthToken,nt as configureWsFatalCloseHandler,st as configureWsKeepalive,it as configureWsUrl,at as connect,ge as consumeAutoSendQuery,Pt as convertHistoryMessages,Q as createAuthClient,ct as createCardActionHandler,_t as createCoreChatState,mt as createEffectTokenDeduper,At as createHostEffectRunner,ue as createPlatformAdapters,he as createPlatformApi,dt as disconnect,St as executeAuthorizationEffect,gt as executePaymentEffect,te as getAuthClient,F as getAuthToken,ht as hideCard,ft as isHostEffect,It as isSessionExpiredError,pt as isWsOpen,yt as mapPaymentResultCode,Ct as resolveHistoryMessage,Rt as resolveHistoryMeta,Tt as resolveHistoryPreTools,xt as resolveHistorySkills,Se as runAutoSend,lt as send,U as sendCardAction,N as setActionAuthTokenGetter,Ut as subscribeSessionUpgradeDrain,ut as upsertCard,Ot as useASRAdapter,Ft as useAdapters,Kt as useFeedbackAdapter,Bt as useRefreshSession,Lt as useTTSAdapter,$t as useUploadAdapter,L as waitForSocketOpen};
|
|
1
|
+
import{a as B,b as G,c as K,d as J,e as X,f as Y,g as Z,h as oe,i as se,j as ae,k as ne,l as ie,m as pe,n as de,o as le,p as ce,q as ue,r as fe}from"../chunk-YTXQ3WRK.js";import{a as P,b as v,c as k,d as H,e as I,f as w,g as R,h as M,i as U,j as E,k as D,l as L,m as O,n as F,o as N,p as W,q as V,r as Q,s as i,t as $,u as q,v as z}from"../chunk-RWUIBPQC.js";import{a as j,b as ee,c as te,d as re}from"../chunk-AW4ZSI4F.js";import{a as m,b as y,c as x,d as A,e as C,f as h,g,h as S,i as b,j as p,k as T,l as _}from"../chunk-6VLQT22V.js";export*from"@tbox.cn/app-sdk-client";import{jsx as c}from"react/jsx-runtime";function me(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,f)=>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},f))})}function ye(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var d=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 xe}from"@tbox.cn/app-sdk-client";var l=xe("AUTO-SEND"),u=["query","prompt"];function Ae(r){let e=new URLSearchParams(r);for(let t of u){let o=e.get(t)?.trim();if(o)return o}return null}function Ce(r){let e=new URL(r);for(let t of u)e.searchParams.delete(t);return e.toString()}function he(){if(typeof window>"u")return null;let r=Ae(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",Ce(window.location.href))}catch(e){l.warn("strip failed (URL retained; refresh may re-send):",e)}return r}async function ge(r,e,t=5e3){if(!await p(t)){l.warn("skipped:reason=socket-timeout");return}e(r),l.info("sent")}export{B as AdapterProvider,se as AlipayASRAdapter,pe as AudioStreamPlayer,oe as BrowserASRAdapter,ae as FallbackASRAdapter,ie as FeedbackAdapter,d as InMemoryCardHistoryLoader,me as ItemActionsRow,de as TTSAdapter,ne as UploadAdapter,fe as __resetPlatformApiSingleton,$ as bindCardActionChannel,N as buildHistoryToolCalls,F as buildPreToolToolCalls,D as buildSkillToolCalls,ee as callAction,_ as configureHelloContext,C as configureWsAuthErrorHandler,x as configureWsAuthToken,h as configureWsFatalCloseHandler,m as configureWsKeepalive,y as configureWsUrl,g as connect,he as consumeAutoSendQuery,V as convertHistoryMessages,te as createAuthClient,P as createCardActionHandler,q as createCoreChatState,I as createEffectTokenDeduper,U as createHostEffectRunner,le as createPlatformAdapters,ce as createPlatformApi,T as disconnect,M as executeAuthorizationEffect,R as executePaymentEffect,re as getAuthClient,A as getAuthToken,ue as getPlatformApi,k as hideCard,H as isHostEffect,Q as isSessionExpiredError,b as isWsOpen,w as mapPaymentResultCode,O as resolveHistoryMessage,W as resolveHistoryMeta,L as resolveHistoryPreTools,E as resolveHistorySkills,ge as runAutoSend,S as send,i as sendCardAction,j as setActionAuthTokenGetter,z as subscribeSessionUpgradeDrain,v as upsertCard,K as useASRAdapter,G 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": "0.
|
|
3
|
+
"version": "1.0.0-alpha.10",
|
|
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": {
|
|
@@ -16,6 +16,14 @@
|
|
|
16
16
|
"types": "./dist/client/card-preview.d.ts",
|
|
17
17
|
"import": "./dist/client/card-preview.js"
|
|
18
18
|
},
|
|
19
|
+
"./app": {
|
|
20
|
+
"types": "./dist/app/index.d.ts",
|
|
21
|
+
"import": "./dist/app/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./app/card-preview": {
|
|
24
|
+
"types": "./dist/app/card-preview.d.ts",
|
|
25
|
+
"import": "./dist/app/card-preview.js"
|
|
26
|
+
},
|
|
19
27
|
"./platform/code-inspect": {
|
|
20
28
|
"types": "./platform/code-inspect.d.cts",
|
|
21
29
|
"default": "./platform/code-inspect.cjs"
|
|
@@ -34,12 +42,12 @@
|
|
|
34
42
|
},
|
|
35
43
|
"dependencies": {
|
|
36
44
|
"@phosphor-icons/react": "2.1.10",
|
|
37
|
-
"@tbox.cn/app-contracts": "0.13.3",
|
|
38
|
-
"@tbox.cn/app-sdk-client": "0.21.4",
|
|
39
|
-
"@tbox.cn/app-sdk-core": "0.20.5",
|
|
40
45
|
"react": "18.3.1",
|
|
41
46
|
"react-dom": "18.3.1",
|
|
42
|
-
"zustand": "4.5.7"
|
|
47
|
+
"zustand": "4.5.7",
|
|
48
|
+
"@tbox.cn/app-sdk-core": "1.0.0-alpha.10",
|
|
49
|
+
"@tbox.cn/app-sdk-client": "1.0.0-alpha.10",
|
|
50
|
+
"@tbox.cn/app-contracts": "1.0.0-alpha.10"
|
|
43
51
|
},
|
|
44
52
|
"devDependencies": {
|
|
45
53
|
"@types/ws": "8.18.1",
|
package/dist/chunk-FA7CKDRJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createClientLogger as De}from"@tbox.cn/app-sdk-client";import{nextKeepaliveAction as Be,KEEPALIVE_MISS_LIMIT as Oe}from"@tbox.cn/app-contracts";var S=De("WS"),p=null,R=null,q=null,T=null,W=null,F=null,D=0,X=!0,B=25e3,v=null,j=0;function At(e){e.enabled!==void 0&&(X=e.enabled),e.intervalMs!==void 0&&(B=Math.max(100,e.intervalMs))}function ne(e){W=e}function Tt(e){F=e}function oe(){return F?F():null}var $=null;function Mt(e){$=e}var K=null;function ae(e){K=e}var Ue="登录状态失效,无法连接对话服务,请重试",Ge="HELLO scope 拒绝:context.mall 形状非法(需 mallId 非空)";function qe(e,s,t=3){if(!s)return{stop:!1,nextStreak:0};let o=e+1;return o>=t?{stop:!0,nextStreak:0}:{stop:!1,nextStreak:o}}function z(e,s){if(p&&(p.readyState===WebSocket.OPEN||p.readyState===WebSocket.CONNECTING))return;R=e,q=s??q;let t=W?W():null;t&&(p=new WebSocket(t),p.onopen=()=>{S.info("connected"),T&&(clearTimeout(T),T=null),We(),q?.()},p.onmessage=o=>{j=Date.now();let d=null;try{d=JSON.parse(o.data)}catch(c){S.error("parse error",c);return}if(d?.type!=="PONG"){if(d?.type==="PING"){k({type:"PONG",...d.ts!==void 0?{ts:d.ts}:{}});return}try{R?.(d)}catch(c){S.error("parse error",c)}}},p.onclose=o=>{if(S.info("disconnected",o.code?`code=${o.code}`:""),J(),p=null,o.code===4002){S.error("HELLO scope 拒绝(商圈不在白名单),停止重连"),K?.({code:o.code,message:Ge});return}let d=o.code===4001,{stop:c,nextStreak:g}=qe(D,d);if(D=g,c){S.error("HELLO 连续鉴权失败,停止重连(请刷新页面重试)"),K?.({code:o.code,message:Ue});return}if(d){($?$().catch(h=>S.warn("auth refresh failed:",h.message)):Promise.resolve()).finally(V);return}V()},p.onerror=o=>{S.error("error",o)})}function k(e){if(!p||p.readyState!==WebSocket.OPEN){S.warn("not connected, message dropped");return}p.send(JSON.stringify(e))}function O(){return!!p&&p.readyState===WebSocket.OPEN}function xt(e,s=100){let t=Date.now()+e;return new Promise(o=>{let d=()=>{if(p&&p.readyState===WebSocket.OPEN){o(!0);return}if(Date.now()>=t){o(!1);return}setTimeout(d,s)};d()})}function ie(){T&&(clearTimeout(T),T=null),J(),R=null,D=0,p&&(p.onclose=null,p.close(),p=null)}function le(e=3e3){if(!X||!p||p.readyState!==WebSocket.OPEN)return;let s=Be(Date.now()-j,B);if(s==="dead"){Fe(`keepalive stale (idle >= ${B*Oe}ms)`,e);return}s==="ping"&&k({type:"PING",ts:Date.now()})}function We(){j=Date.now(),X&&(v&&clearInterval(v),v=setInterval(()=>le(),B))}function J(){v&&(clearInterval(v),v=null)}function Fe(e,s=3e3){S.warn(`force reconnect: ${e}`),J();let t=p;p=null,t&&(t.onclose=null,t.onmessage=null,t.onopen=null,t.onerror=null,t.close()),D=0,V(s)}typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&le(0)});function V(e=3e3){T||!R||(T=setTimeout(()=>{T=null,R&&z(R)},e))}function de(e){return function(t,o,d){if(e.blockAll?.(t)!==!0)switch(o.type){case"sendMessage":case"submitForm":case"moduleAction":{if(e.canAct?.(t)===!1)return;e.sendToServer(t,o,d);break}case"openLink":{if(!o.url)break;e.openUrl?.(o.url);break}case"toast":{o.content&&e.toast?.(o.content,o.tone);break}case"closeCard":{e.closeCard?.(t);break}}}}import{createClientLogger as $e}from"@tbox.cn/app-sdk-client";var Ke=$e("CARD");function ce(e,s){let t=o=>o.some(d=>d.id===s.id)?o.map(d=>d.id===s.id?s:d):[...o,s];return s.messageId?{...e,cardsByMessageId:{...e.cardsByMessageId,[s.messageId]:t(e.cardsByMessageId[s.messageId]||[])}}:{...e,orphanCards:t(e.orphanCards)}}function Ht(e,s){let t={};for(let[o,d]of Object.entries(e.cardsByMessageId))t[o]=d.filter(c=>c.id!==s);return{cardsByMessageId:t,orphanCards:e.orphanCards.filter(o=>o.id!==s)}}function ue(e,s){let t=d=>{let c=d.findIndex(b=>b.id===s.id);if(c<0)return null;let g=[...d];return g[c]={...s,messageId:d[c].messageId,isHistory:d[c].isHistory,meta:{...d[c].meta,...s.meta,createdAt:d[c].meta?.createdAt??s.meta?.createdAt??Date.now(),...d[c].meta?.businessNo!==void 0?{businessNo:d[c].meta.businessNo}:{}}},g};for(let[d,c]of Object.entries(e.cardsByMessageId)){let g=t(c);if(g)return{...e,cardsByMessageId:{...e.cardsByMessageId,[d]:g}}}let o=t(e.orphanCards);return o?{...e,orphanCards:o}:(Ke.warn(`update 未命中卡实例:${s.id}(已隐藏/清空或非本连接下发)`),e)}import{TBOX_EFFECT_EVENT_NAME as _t}from"@tbox.cn/app-contracts";import{requestPayment as Ve}from"@tbox.cn/app-sdk-client";import{getAuthCode as Xe}from"@tbox.cn/app-sdk-client";import{createClientLogger as je}from"@tbox.cn/app-sdk-client";var Y=je("tbox:effect");function pe(e){if(e===null||typeof e!="object")return!1;let s=e;return typeof s.type=="string"&&s.type.length>0}function ge(){let e=new Set;return s=>{let t=s.callback?.contextToken;return t?e.has(t)?!1:(e.add(t),!0):!0}}function me(e){return e!==null&&typeof e=="object"&&typeof e.code=="string"?String(e.code):"BRIDGE_ERROR"}function ye(e){return me(e)==="BRIDGE_UNAVAILABLE"}function ze(e){return e==="9000"?"success":e==="6001"?"cancel":"failure"}async function Je(e,s){try{let t=await s.requestPayment(e.orderInfo);return{status:ze(t.resultCode),paymentRef:e.paymentRef}}catch(t){return{status:ye(t)?"unavailable":"failure",paymentRef:e.paymentRef}}}async function Ye(e,s){try{let t=await s.getAuthCode([...e.scopes]);return typeof t.authCode!="string"||!t.authCode.trim()?{status:"failure"}:{status:"success",authCode:t.authCode}}catch(t){let o=me(t);return ye(t)?{status:"unavailable"}:o.includes("CANCEL")?{status:"cancel"}:{status:"failure"}}}function fe(e,s,t){if(e.callback)try{t({actionId:e.callback.actionId,contextToken:e.callback.contextToken,formData:{...s}})}catch(o){Y.warn("结果回传失败:",o?.message)}}function Ce(e){let s={requestPayment:e?.requestPayment??Ve,getAuthCode:e?.getAuthCode??Xe,sendModuleAction:e?.sendModuleAction??(()=>{Y.warn("未注入 sendModuleAction,结果未回传")}),onSessionCredentialsRefreshed:e?.onSessionCredentialsRefreshed};return t=>{switch(t.type){case"payment":{Je(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"authorization.alipay-user-profile":{Ye(t,s).then(o=>fe(t,o,s.sendModuleAction));return}case"session.credentials-refreshed":{s.onSessionCredentialsRefreshed?.(t.reason);return}default:Y.warn(`宿主效果类型未在客户端执行:${String(t.type)}`)}}}import{parseSkillReminders as Qe,buildSkillToolCallPayload as Ze,SKILL_NAME_PATTERN as he,SKILL_TOOL_CALL_NAME as et}from"@tbox.cn/app-contracts";function Ie(e){let s=e.query??"",t=Qe(s),o=new Map;for(let d of Array.isArray(e.skills)?e.skills:[])d?.name&&he.test(d.name)&&o.set(d.name,d);for(let d of t.skills)o.has(d)||o.set(d,{name:d});return{content:t.cleanedText,skills:[...o.values()]}}function ke(e,s){return e.filter(t=>t&&he.test(t.name)).map((t,o)=>{let{args:d,result:c}=Ze(t);return{id:`skill-${s}-${o}`,name:et,args:d,result:c,status:"done"}})}import{buildPreToolToolCallPayload as tt,PRE_TOOL_CALL_NAME as rt,PRE_TOOL_NAME_PATTERN as Se}from"@tbox.cn/app-contracts";function st(e){return(Array.isArray(e.preTools)?e.preTools:[]).filter(s=>s?.toolName&&Se.test(s.toolName))}function nt(e){let s=Ie(e);return{content:s.content,skills:s.skills,preTools:st(e)}}function ot(e,s){let t=[];return(Array.isArray(e)?e:[]).filter(o=>o&&Se.test(o.toolName)).forEach((o,d)=>{try{let{args:c,result:g}=tt(o);t.push({id:`pretool-${s}-${d}`,name:rt,args:c,result:g,status:"done"})}catch{}}),t}function at(e,s){return[...ot(e.preTools,s),...ke(e.skills,s)]}function it(e){if(!e)return;let s=new Date(e.replace(" ","T")).getTime();return Number.isNaN(s)?void 0:s}function lt(e,s){let t=e.messageId??e.id??e.outerBusinessId??`hist-${s}`,o=e.createTime??it(e.requestTime)??Date.now();return{key:t,createdAt:o}}function Ee(e){let s=0,t=c=>`${c}_${Date.now()}_${s++}`,o=[],d={};return e.forEach((c,g)=>{let{key:b,createdAt:h}=lt(c,g),A=nt(c);if(c.query){let r={id:`history-user-${b}`,role:"user",content:A.content,status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId}},a=c.multiModalInputs?.imageUrls;a&&a.length>0&&(r.mediaItems=a.map(n=>({id:t("history-img"),type:"image",src:n}))),o.push(r)}(c.answer||c.content||c.cards&&c.cards.length>0)&&o.push({id:`history-asst-${b}`,role:"assistant",content:c.answer||c.content||"",status:"done",createdAt:h,...c.outerBusinessId&&{requestId:c.outerBusinessId},...c.conversationId&&{conversationId:c.conversationId},...A.skills.length>0||A.preTools.length>0?{toolCalls:at(A,b)}:{}}),c.cards&&c.cards.length>0&&(d[`history-asst-${b}`]=c.cards.map(r=>({...r,isHistory:!0})))}),{messages:o,cardsByMessageId:d}}var be;function dt(e){be=e}function Ae(){try{return be?.()}catch{return}}import{TBOX_CARD_EVENT_NAME as Te,TBOX_CARD_UPDATE_EVENT_NAME as ct,TBOX_EFFECT_EVENT_NAME as ut,TBOX_NOTICE_EVENT_NAME as Me}from"@tbox.cn/app-contracts";import{createClientLogger as N,setClientRunContext as Q}from"@tbox.cn/app-sdk-client";import{isInAlipayShell as ft}from"@tbox.cn/app-sdk-client";import{callJsapi as xe}from"@tbox.cn/app-sdk-client";import{resolveAlipayNavigation as pt}from"@tbox.cn/app-sdk-client";var x=N("tbox"),Re="网络连接不可用,请稍后重试",ve=N("CONVERSATION"),gt=N("SESSION-UPGRADE"),mt=N("HISTORY"),we=N("FEEDBACK");function yt(e){let s=String(e?.message||e||"");return/过期|expired|PARAM_INVALID|unauthorized|token/i.test(s)}var P=0,Z=!1,U=null,E=null,ee=!1;function Ct(e){let s=e.messageId??e.id??e.outerBusinessId;return s?`id:${s}`:`content:${e.requestTime??e.createTime??""}:${e.query??""}:${e.answer??e.content??""}`}var H;function tr(e,s,t){if(!H){x.warn("卡动作通道未注册(应用 chat store 未创建),动作已丢弃");return}H(e,s,t)}function ht(e){let s=H;return H=e,()=>{H===e&&(H=s)}}var It=0,w=e=>`${e}_${Date.now()}_${It++}`;function kt(e,s,t){s(o=>({...o,...ce({cardsByMessageId:o.cardsByMessageId,orphanCards:o.orphanCards},t)})),e.onCardEvent?.({type:"render",cardId:t.id,cardType:t.cardType,...t.messageId!==void 0?{messageId:t.messageId}:{},ts:Date.now()})}function St(e,s,t,o){let d={cardsByMessageId:t().cardsByMessageId,orphanCards:t().orphanCards},c=ue(d,o);c!==d&&(s(g=>({...g,...c})),e.onCardEvent?.({type:"update",cardId:o.id,cardType:o.cardType,...o.messageId!==void 0?{messageId:o.messageId}:{},ts:Date.now()}))}function He(e){k(e().conversationEstablished?{type:"RESUME_CONVERSATION"}:{type:"NEW_CONVERSATION"})}function sr(e,s,t){ne(e.getWsUrl),ae(r=>{s({authBlocked:r.message}),e.toast(r.message,"error")});let o=ge(),d=Ce({sendModuleAction:({actionId:r,contextToken:a,formData:n})=>{k({type:"UI_ACTION",surfaceId:"",action:{type:"moduleAction",actionId:r,contextToken:a},formData:n})},...e.onSessionCredentialsRefreshed?{onSessionCredentialsRefreshed:e.onSessionCredentialsRefreshed}:{}}),c=e.onHostEffect??d,g=r=>{let{cardsByMessageId:a,orphanCards:n}=t();return[...Object.values(a).flat(),...n].find(l=>l.id===r)},b=de({canAct:r=>{if(t().isGenerating)return!1;let a=g(r);return!(a&&a.isHistory)},sendToServer:(r,a,n)=>{if(!O()){let u=g(r);e.onCardEvent?.({type:"click",cardId:r,cardType:u?.cardType??"",ts:Date.now()}),e.toast(Re,"error");return}let{addMessage:i}=t(),l=g(r);if(e.onCardEvent?.({type:"click",cardId:r,cardType:l?.cardType??"",ts:Date.now()}),a.type==="sendMessage"){a.visible!==!1&&i({id:w("user"),role:"user",content:a.displayText??a.value,status:"done",createdAt:Date.now()}),k({type:"UI_ACTION",surfaceId:r,action:a}),h=!0;return}if(a.type==="submitForm"){k({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}}),h=!0;return}k({type:"UI_ACTION",surfaceId:r,action:a,formData:n??{}})},toast:(r,a)=>e.toast(r,a),openUrl:r=>{if(!(typeof window>"u")){if(r.startsWith("tel:")){window.location.href=r;return}if(ft()){if(r.startsWith("alipays://")||r.startsWith("alipayrisk://")){let a=pt(r,t().helloAck?.mallScope?.miniAppId);a?(x.info(`[openUrl] ${a.apiName} url=${r}`),xe(a.apiName,a.params).catch(n=>{x.warn(`[openUrl] ${a.apiName} failed url=${r}`,n),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error")})):(x.warn(`[openUrl] unresolved Alipay deep link url=${r}`),e.toast("当前无法打开该支付宝页面,请确认已在支付宝内打开","error"))}else x.info(`[openUrl] ap.openURL url=${r}`),xe("ap.openURL",{url:r}).catch(a=>{x.warn(`[openUrl] ap.openURL failed url=${r}`,a),e.toast("当前无法打开该链接,请稍后再试","error")});return}window.open&&window.open(r,"_blank")}},closeCard:r=>t().hideCard(r)});ht((r,a,n)=>{t().sendUiAction(r,a,n)});let h=!1,A=()=>{if(!e.platformApi||!e.authClient)throw new Error("会话方法需要 platformApi/authClient(createCoreChatState deps 未注入)");return{platformApi:e.platformApi,authClient:e.authClient}};return{userId:"",helloAck:null,authBlocked:null,messages:[],isGenerating:!1,currentRunId:null,streamingMsgId:null,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[],init:()=>{z(r=>{let a=t();switch(r.type){case"HELLO_ACK":{s({helloAck:{...r.mallScope?{mallScope:r.mallScope}:{},chatConfig:r.chatConfig,...r.toolDebug?{toolDebug:!0}:{}},authBlocked:null});break}case"RUN_STARTED":{if(!h)break;h=!1;let n=w("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({isGenerating:!0,currentRunId:r.runId,streamingMsgId:n}),Q({runId:r.runId,...r.threadId&&{conversationId:r.threadId}});break}case"CUSTOM":{if(r.name===Te){let n=r.value;kt(e,s,n),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Te,{detail:n}))}else if(r.name===ct)St(e,s,t,r.value);else if(r.name===ut&&pe(r.value))o(r.value)&&c(r.value);else if(r.name===Me){let n=r.value;n?.text&&e.toast(n.text,n.level??"info"),typeof window<"u"&&n?.text&&window.dispatchEvent(new CustomEvent(Me,{detail:n}))}break}case"REASONING_START":{if(!t().isGenerating)break;if(!t().streamingMsgId){let n=w("thinking");a.addMessage({id:n,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:n})}break}case"REASONING_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,reasoning:(l.reasoning||"")+r.delta}:l)}));break}case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"TOOL_CALL_START":{if(!t().isGenerating)break;let{streamingMsgId:n}=t();if(!n){let i=w("thinking");a.addMessage({id:i,role:"assistant",content:"",status:"thinking",createdAt:Date.now()}),s({streamingMsgId:i}),n=i}s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:[...l.toolCalls||[],{id:r.toolCallId,name:r.toolCallName,status:"calling"}]}:l)}));break}case"TOOL_CALL_ARGS":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(u=>u.id===r.toolCallId?{...u,args:(u.args||"")+r.delta}:u)}:l)}));break}case"TOOL_CALL_END":break;case"TOOL_CALL_RESULT":{let{streamingMsgId:n}=t();if(!n)break;s(i=>({messages:i.messages.map(l=>l.id===n?{...l,toolCalls:(l.toolCalls||[]).map(u=>u.id===r.toolCallId?{...u,result:r.content,status:r.isError?"error":"done",...r.isError?{error:r.errorMessage??"工具执行失败"}:{}}:u)}:l)}));break}case"TEXT_MESSAGE_START":{if(!t().isGenerating)break;let n=r.messageId,{streamingMsgId:i}=t();i?.startsWith("thinking_")?s(l=>({streamingMsgId:n,messages:l.messages.map(u=>u.id===i?{...u,id:n,status:"streaming"}:u)})):(a.addMessage({id:n,role:"assistant",content:"",status:"streaming",createdAt:Date.now()}),s({streamingMsgId:n}));break}case"TEXT_MESSAGE_CONTENT":{let{streamingMsgId:n}=t();n&&r.messageId===n&&t().appendDelta(n,r.delta);break}case"TEXT_MESSAGE_END":{let{streamingMsgId:n}=t();n&&(a.updateMessage(n,{status:"done"}),s({streamingMsgId:null}));break}case"RUN_FINISHED":{if(r.runId&&r.runId!==t().currentRunId)break;let n=r.rawEvent?.requestId;s(n?i=>{let l=[...i.messages];for(let u=l.length-1;u>=0;u--)if(l[u].role==="assistant"&&l[u].status==="done"){l[u]={...l[u],requestId:n,...r.threadId&&{conversationId:r.threadId}};break}return{isGenerating:!1,currentRunId:null,messages:l}}:{isGenerating:!1,currentRunId:null});{let i=0,l=t().messages.map(u=>u.role!=="assistant"||!u.toolCalls?.some(f=>f.status==="calling")?u:(i+=u.toolCalls.filter(f=>f.status==="calling").length,{...u,toolCalls:u.toolCalls.map(f=>f.status==="calling"?{...f,status:"error",error:"工具执行未返回结果"}:f)}));i>0&&(s({messages:l}),x.warn(`RUN_FINISHED:${i} 个工具未收到终态事件,已收敛为失败态`))}Q(null);break}case"RUN_ERROR":{if(!t().isGenerating&&!t().currentRunId)break;let n=r.runId;if(n&&n!==t().currentRunId)break;let i=t().streamingMsgId,l=r.message||"请求失败,请重试",u=r.rawEvent?.requestId??n??t().currentRunId??void 0,f=r.threadId;s(M=>{let y=i?M.messages.find(m=>m.id===i):void 0,C={...y??{id:w("error"),role:"assistant",content:"",createdAt:Date.now()},status:"error",error:l,...u&&{requestId:y?.requestId??u},...f&&{conversationId:y?.conversationId??f},toolCalls:y?.toolCalls?.map(m=>m.status==="calling"?{...m,status:"error",error:"请求中断"}:m)};return{isGenerating:!1,currentRunId:null,streamingMsgId:null,messages:y?M.messages.map(m=>m.id===y.id?C:m):[...M.messages,C]}}),Q(null);break}}},()=>{let r=oe(),a=Ae();k({type:"HELLO",...r?{token:r}:{},...a?{context:a}:{}}),He(t)})},sendMessage:r=>{let{addMessage:a,isGenerating:n}=t();if(n)return;if(!O()){e.toast(Re,"error");return}let i=typeof r=="string"?r:r.text,l=typeof r=="string"?void 0:r.mediaItems,u=typeof r=="string"?void 0:r.inputMethod;a({id:w("user"),role:"user",content:i,status:"done",createdAt:Date.now(),mediaItems:l,inputMethod:u}),k({type:"SEND_MESSAGE",content:i,mediaItems:l?.filter(f=>f.fileId).map(f=>({fileId:f.fileId,type:f.type,name:f.name,mimeType:f.mimeType})),inputMethod:u}),h=!0},sendUiAction:(r,a,n)=>{b(r,a,n)},hideCard:r=>{s(a=>{let n={};for(let[i,l]of Object.entries(a.cardsByMessageId))n[i]=l.filter(u=>u.id!==r);return{cardsByMessageId:n,orphanCards:a.orphanCards.filter(i=>i.id!==r)}})},destroy:()=>ie(),clearChat:()=>{t().cancelGeneration(),h=!1,s({messages:[],currentRunId:null,streamingMsgId:null,isGenerating:!1,conversationEstablished:!1,cardsByMessageId:{},orphanCards:[]})},addMessage:r=>s(a=>({messages:[...a.messages,r]})),appendDelta:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,content:i.content+a}:i)})),updateMessage:(r,a)=>s(n=>({messages:n.messages.map(i=>i.id===r?{...i,...a}:i)})),setGenerating:r=>s({isGenerating:r}),cancelGeneration:()=>{h=!1;let{streamingMsgId:r,isGenerating:a,currentRunId:n}=t();if(a){if(k({type:"CANCEL_RUN",...n&&{runId:n}}),r){let i=t().messages.find(l=>l.id===r);i&&!i.content?s(l=>({messages:l.messages.filter(u=>u.id!==r)})):s(l=>({messages:l.messages.map(u=>u.id===r?{...u,status:"done",toolCalls:u.toolCalls?.map(f=>f.status==="calling"?{...f,status:"done"}:f)}:u)}))}s({isGenerating:!1,currentRunId:null,streamingMsgId:null})}},setAuthBlocked:r=>s({authBlocked:r}),setUserId:r=>{t().userId&&t().userId!==r&&s({conversationEstablished:!1}),s({userId:r})},historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null,runtimeStatus:"bootstrapping",initConversation:async()=>{let{authClient:r}=A();if(U)return U;let a;U=new Promise(n=>{a=n});try{let n=t().userId,i=await r.resolveUserId();if(n&&n!==i&&(P++,s({conversationEstablished:!1}),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null})),s({userId:i}),!r.getAuthState()?.token){ve.warn("anonymous: skip WS init, expose recoverable auth failure"),s({runtimeStatus:"failed",conversationEstablished:!1}),t().setAuthBlocked("登录失败,暂时无法对话"),e.toast("登录失败,暂时无法对话","error");return}let l=O();t().init(),s({runtimeStatus:"ready"}),l&&He(t)}catch(n){ve.error("init error:",n),t().init(),s({runtimeStatus:"failed"})}finally{U=null,a()}},retryBootstrap:(r=!0)=>{let{authClient:a}=A();if(E)return E;let i=(async()=>{s({runtimeStatus:"bootstrapping"}),r&&a.clearAuth(),t().destroy(),await t().initConversation()})().finally(()=>{E===i&&(E=null)});return E=i,i},newConversation:async()=>{if(!Z){Z=!0;try{P++,t().clearChat(),s({historyMessages:[],historyHasMore:!0,isLoadingHistory:!1,historyEntryKeys:[],historyBeforeId:null}),await t().initConversation()}finally{Z=!1}}},scheduleSessionUpgrade:()=>{let{authClient:r}=A();if(E)return E;if(t().isGenerating)return ee=!0,Promise.resolve();let n=(async()=>{s({runtimeStatus:"bootstrapping"});try{r.clearAuth(),await r.ensureAuth(),t().destroy(),await t().initConversation()}catch(i){gt.error("unexpected error:",i),s({runtimeStatus:"failed"})}finally{ee=!1}})().finally(()=>{E===n&&(E=null)});return E=n,n},loadMoreHistory:async()=>{let{platformApi:r}=A(),{isLoadingHistory:a,historyHasMore:n,historyMessages:i,historyBeforeId:l}=t();if(a||!n)return;let u=P;s({isLoadingHistory:!0});let f=5,M=i.length===0?t().messages.find(C=>C.requestId)?.requestId:void 0,y=l??M;try{let{status:C,data:m}=await r.listMessages({pageSize:f,...y?{beforeId:y}:{}});if(u!==P)return;if(C===200&&m){let _=m.data||[],Pe=new Set(t().messages.map(I=>I.requestId).filter(Boolean)),te=new Set(t().historyEntryKeys),re=[],se=_.filter(I=>{let G=Ct(I);return te.has(G)?!1:(te.add(G),re.push(G),!I.outerBusinessId||!Pe.has(I.outerBusinessId))}),L=[..._].reverse().find(I=>I.outerBusinessId)?.outerBusinessId??null,Ne=se.length>0||!!L&&L!==y,{messages:_e,cardsByMessageId:Le}=Ee(se.reverse());s(I=>({historyMessages:[..._e,...I.historyMessages],historyHasMore:_.length>=f&&!!L&&Ne,isLoadingHistory:!1,historyEntryKeys:[...re,...I.historyEntryKeys],historyBeforeId:L,cardsByMessageId:{...I.cardsByMessageId,...Le}}))}else s({isLoadingHistory:!1})}catch(C){if(mt.error("load more error:",C),u!==P)return;s({isLoadingHistory:!1})}},submitFeedback:async(r,a,n,i)=>{let l=t().messages.find(C=>C.id===r),u=l?.feedbackState??"none",f=l?.requestId;if(!f){we.warn("no requestId for message",r);return}let M=a==="cancel"?"none":a;t().updateMessage(r,{feedbackState:M});let y={like:"LIKE",dislike:"DISLIKE",cancel:"CANCEL"};try{(await n.addTag(f,y[a])).success||t().updateMessage(r,{feedbackState:u})}catch(C){if(yt(C)&&i)try{let m=await i();if(m.feedback){(await m.feedback.addTag(f,y[a])).success||t().updateMessage(r,{feedbackState:u});return}}catch(m){we.error("retry failed:",m)}t().updateMessage(r,{feedbackState:u})}}}}function nr(e){return e.subscribe((s,t)=>{ee&&t.isGenerating&&!s.isGenerating&&e.getState().scheduleSessionUpgrade()})}export{At as a,ne as b,Tt as c,oe as d,Mt as e,ae as f,z as g,k as h,O as i,xt as j,ie as k,de as l,ce as m,Ht as n,pe as o,ge as p,ze as q,Je as r,Ye as s,Ce as t,Ie as u,ke as v,st as w,nt as x,ot as y,at as z,lt as A,Ee as B,dt as C,Ae as D,yt as E,tr as F,ht as G,sr as H,nr as I};
|