@tbox.cn/app-agent-sdk-client 0.2.1 → 0.2.2
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/client/index.js +1 -1
- package/package.json +1 -1
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as kt,B as Rt,C as Pt,D as $,E as wt,F as U,G as It,H as Et,I as _t,a as ot,b as st,c as D,d as F,e as O,f as it,g as nt,h as at,i as lt,j as L,k as pt,l as dt,m as ct,n as ut,o as ht,p as ft,q as mt,r as yt,s as gt,t as St,u as xt,v as At,w as bt,x as Tt,y as Ct,z as vt}from"../chunk-FA7CKDRJ.js";export*from"@tbox.cn/app-sdk-client";import{jsx as z}from"react/jsx-runtime";function Ut(r){let{actions:t,cardId:e,isHistory:o,className:s,chipClassName:i}=r;return!t||t.length===0?null:z("div",{className:`tbox-item-actions ${s??""}`.trim(),children:t.map((n,a)=>z("button",{type:"button",className:`tbox-chip ${i??""}`.trim(),disabled:o&&n.kind==="send",onClick:()=>{n.kind==="send"?U(e,{type:"sendMessage",value:n.value??n.label,...n.visibleValue?{displayText:n.visibleValue}:{},visible:!0}):U(e,{type:"openLink",url:n.url??""})},children:n.label},a))})}import{createContext as Mt,useContext as A}from"react";import{jsx as Bt}from"react/jsx-runtime";var y=Mt({});function Ht({value:r,children:t}){return Bt(y.Provider,{value:r,children:t})}var Dt=()=>A(y),Ft=()=>A(y).asr,Ot=()=>A(y).tts,Lt=()=>A(y).upload,$t=()=>A(y).feedback,Kt=()=>A(y).refreshSession;import{createClientLogger as Nt}from"@tbox.cn/app-sdk-client";var K=Nt("ACTION"),Wt=0;function Gt(r){return`${r}_${Date.now()}_${Wt++}_${Math.random().toString(36).slice(2,8)}`}var B=null;function N(r){B=r}async function Vt(r,t,e={}){let o=e.baseUrl??"",s={action:r,payload:t,...e.sessionId&&{sessionId:e.sessionId},...e.idempotencyKey&&{idempotencyKey:e.idempotencyKey}},i=s.idempotencyKey?s:{...s,idempotencyKey:Gt(r)},n=e.token??(B?B():null),a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let d;try{d=await fetch(`${o}/api/action`,{method:"POST",headers:a,body:JSON.stringify(i)})}catch(T){let E=T?.message||"网络错误";return K.warn(`POST /api/action action=${r} fetch 异常:${E}`),{success:!1,error:E}}let h;try{h=await d.json()}catch{return K.warn(`POST /api/action action=${r} 响应解析失败(HTTP ${d.status})`),{success:!1,error:`响应解析失败(HTTP ${d.status})`}}return d.status===409?(K.warn(`POST /api/action action=${r} 幂等键冲突:${h.error||"请勿重复提交"}`),{success:!1,error:h.error||"幂等键冲突:请勿重复提交",cached:!1}):d.status===200&&h.cached?{...h,cached:!0}:h}function Xt(r){return{...r,data:r.data??{},isHistory:!0,status:r.status??"ready"}}var W=class{snapshots=new Map;async save(t,e){let o=this.snapshots.get(t)??[],s=o.findIndex(n=>n.id===e.id),i={id:e.id,cardType:e.cardType,data:e.data,status:e.status,schemaVersion:e.schemaVersion??1,meta:e.meta};s>=0?o[s]=i:o.push(i),this.snapshots.set(t,o)}async load(t){return(this.snapshots.get(t)??[]).map(o=>Xt(o))}async clear(t){this.snapshots.delete(t)}};import{isInAlipayShell as zt}from"@tbox.cn/app-sdk-client";import{getAuthCode as Jt}from"@tbox.cn/app-sdk-client";import{httpPost as J,httpGet as Yt,configureAuthToken as qt,configureAuthErrorHandler as Qt}from"@tbox.cn/app-sdk-client";import{createClientLogger as jt}from"@tbox.cn/app-sdk-client";var c=jt("AUTH"),g="tbox.auth.token",Y="tbox.auth.scopeKey",M="tbox.auth.lastToken",C=null,H=null;function q(r={}){let t=r.loginPlatform??"alipay";return C?(H&&H.loginPlatform!==t&&c.warn(`createAuthClient 重复调用且选项不同(当前 ${H.loginPlatform} vs ${t}),返回首建单例(首建选项生效)`),C):(C=te({loginPlatform:t,...r.scopeKey?{scopeKey:r.scopeKey}:{}}),H={loginPlatform:t},C)}function Zt(){return C??q()}function te(r={}){let t=r.loginPlatform??"alipay",e=r.scopeKey,o=null,s=null,i=null;function n(l){try{return typeof localStorage<"u"?localStorage.getItem(l):null}catch{return null}}function a(l,x){try{typeof localStorage<"u"&&localStorage.setItem(l,x)}catch{}}function d(l){try{typeof localStorage<"u"&&localStorage.removeItem(l)}catch{}}async function h(){return o||s||(s=et().then(l=>(s=null,l),l=>{throw s=null,l}),s)}async function T(){return i||(o=null,i=h().finally(()=>{i=null}),i)}function E(){o=null,s=null,d(g)}function tt(){return o}async function et(){if(e){let p;try{p=e()}catch{p=""}n(Y)!==p&&(d(g),d(M)),a(Y,p)}let l=n(g);if(l)try{let{status:p,data:f}=await Yt("/api/auth/me",{cache:"no-store"});if(p===200&&f?.identity)return c.info("identity from cached token:",f.identity.userId),_({token:l,identity:f.identity});c.warn("cached token invalid (status=%s), re-login",p),d(g)}catch(p){c.warn("/api/auth/me failed, re-login:",p.message),d(g)}let x=n(M);if(zt()){c.info("alipay shell, starting getAuthCode login...");try{let{authCode:p}=await Jt(["auth_base"]),f=$(),{status:u,data:m}=await J("/api/auth/login",{method:"code",code:p,platform:t,...f?{context:f}:{},...x?{previousToken:x}:{}});if(u===200&&m?.token&&m?.identity)return a(g,m.token),a(M,m.token),c.info("identity via alipay login:",m.identity.userId),_({token:m.token,identity:m.identity});c.warn("alipay login failed: status=%s error=%s",u,m?.error??"(no body)")}catch(p){c.error("alipay login error:",p)}return X()}try{let p=$(),{status:f,data:u}=await J("/api/auth/login",{method:"browser",...p?{context:p}:{},...x?{previousToken:x}:{}});if(f===200&&u?.token&&u?.identity)return a(g,u.token),a(M,u.token),c.info("identity via browser login:",u.identity.userId),_({token:u.token,identity:u.identity});c.warn("browser login unavailable: status=%s error=%s(403 = 服务端 browserLoginMode 关闭或生产禁 mock)",f,u?.error??"(no body)")}catch(p){c.warn("browser login error:",p.message)}return X()}function X(){let l={userId:`anonymous_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,source:"anonymous"};return c.warn("fallback to anonymous:",l.userId),_({token:null,identity:l})}function _(l){return o=l,qt(()=>o?.token??null),D(()=>o?.token??null),N(()=>o?.token??null),Qt(()=>T()),O(()=>T()),l}async function rt(){return(await h()).identity.userId}return{ensureAuth:h,refreshAuth:T,clearAuth:E,getAuthState:tt,resolveUserId:rt}}import{httpPost as ee}from"@tbox.cn/app-sdk-client";function b(r){return{"X-Tbox-Session-Id":r.tboxSessionId,"X-Tbox-Channel":r.channel,"X-Tbox-AppId":r.appId}}var S=class{constructor(t){this.session=t}session;mediaRecorder=null;mediaStream=null;audioChunks=[];cancelled=!1;async checkPermission(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),!0}catch{return!1}}async startRecording(){this.cancelled=!1;let t=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0}});this.mediaStream=t,this.audioChunks=[];let e=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",o=new MediaRecorder(t,{mimeType:e});this.mediaRecorder=o,o.ondataavailable=s=>{s.data.size>0&&this.audioChunks.push(s.data)},o.start()}stopRecording(){return new Promise((t,e)=>{let o=this.mediaRecorder;if(!o||o.state==="inactive"){this.cleanup(),t("");return}o.onstop=async()=>{if(this.cancelled){this.cleanup(),t("");return}try{let s=new Blob(this.audioChunks,{type:o.mimeType}),i=await this.blobToBase64(s),{status:n,data:a}=await ee("/api/tbox/asr",{base64_audio:i,audio_format:"webm",sample_rate:"16000"},{headers:b(this.session)});t(n===200&&a?.text?a.text:"")}catch(s){e(s)}finally{this.cleanup()}},o.stop()})}cancelRecording(){this.cancelled=!0,this.mediaRecorder?.stop(),this.cleanup()}blobToBase64(t){return new Promise((e,o)=>{let s=new FileReader;s.onloadend=()=>e(s.result.split(",")[1]||""),s.onerror=o,s.readAsDataURL(t)})}cleanup(){this.mediaStream?.getTracks().forEach(t=>t.stop()),this.mediaStream=null,this.mediaRecorder=null,this.audioChunks=[]}};import{callJsapi as G}from"@tbox.cn/app-sdk-client";import{httpPost as re}from"@tbox.cn/app-sdk-client";var v=class{constructor(t){this.session=t}session;cancelled=!1;async checkPermission(){return!0}async startRecording(){this.cancelled=!1,await G("startRecord",{},"invoke")}async stopRecording(){let t=await G("stopRecord",{},"invoke");if(this.cancelled)return"";let e=t?.audioBase64;if(!e)return"";let{status:o,data:s}=await re("/api/tbox/asr",{base64_audio:e,audio_format:t.format||"mp3",sample_rate:"16000"},{headers:b(this.session)});return o===200&&s?.text?s.text:""}cancelRecording(){this.cancelled=!0,G("stopRecord",{},"invoke").catch(()=>{})}};import{createClientLogger as oe}from"@tbox.cn/app-sdk-client";var se=oe("asr"),k=class{bridge;browser;active;constructor(t){this.bridge=new v(t),this.browser=new S(t),this.active=this.bridge}async checkPermission(){return!0}async startRecording(){try{await this.bridge.startRecording(),this.active=this.bridge}catch(t){se.warn("桥录音失败,降级到 H5 getUserMedia:",t),this.bridge.cancelRecording(),await this.browser.startRecording(),this.active=this.browser}}stopRecording(){return this.active.stopRecording()}cancelRecording(){this.active.cancelRecording()}};import{httpPostBinary as ie}from"@tbox.cn/app-sdk-client";var R=class{constructor(t){this.session=t}session;onProgress;async upload(t,e){let o;typeof t=="string"?o=await(await fetch(t)).blob():o=t;let{status:s,data:i}=await ie("/api/tbox/upload",o,{headers:{"Content-Type":o.type||"application/octet-stream","X-Tbox-Session-Id":this.session.tboxSessionId,"X-Tbox-Channel":this.session.channel,"X-Tbox-AppId":this.session.appId,"X-Tbox-File-Type":e?.type||"file",...e?.name?{"X-Tbox-File-Name":encodeURIComponent(e.name)}:{}}});if(s!==200||!i?.fileId)throw new Error(`[tbox-upload] ${i?.errorCode??`HTTP_${s}`} ${i?.error??""}`.trim());return{fileId:i.fileId,url:"",mimeType:typeof i.fileType=="string"?i.fileType:void 0,safed:i.safed}}};import{httpPost as ne}from"@tbox.cn/app-sdk-client";var P=class{constructor(t){this.session=t}session;async addTag(t,e){let{status:o,data:s}=await ne("/api/tbox/feedback",{requestId:t,feedback:e},{headers:b(this.session)});return{success:o===200&&!!s?.success}}};var w=class{sampleRate;isStopped=!1;onPlayEnd;audioContext=null;nextStartTime=0;inputCount=0;endedCount=0;totalInputCount=-1;fallbackTimer=null;playEndFired=!1;constructor(t){this.sampleRate=t.sampleRate,this.onPlayEnd=t.onPlayEnd}start(){this.isStopped=!1,this.inputCount=0,this.endedCount=0,this.totalInputCount=-1,this.playEndFired=!1,!this.audioContext&&(this.audioContext=new AudioContext({sampleRate:this.sampleRate}),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.nextStartTime=this.audioContext.currentTime)}input(t){if(this.isStopped||!this.audioContext)return;let e=new Int16Array(t);if(e.length===0)return;let o=new Float32Array(e.length);for(let a=0;a<e.length;a++)o[a]=e[a]/32768;let s=this.audioContext.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=this.audioContext.createBufferSource();i.buffer=s,i.connect(this.audioContext.destination);let n=this.audioContext.currentTime;this.nextStartTime<n&&(this.nextStartTime=n),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.inputCount++,i.onended=()=>{this.endedCount++,this.checkPlayEnd()}}finish(){if(this.totalInputCount=this.inputCount,this.totalInputCount===0){this.firePlayEnd();return}if(this.checkPlayEnd(),this.audioContext&&!this.isStopped&&!this.playEndFired){let t=this.nextStartTime-this.audioContext.currentTime,e=Math.max(0,t*1e3)+500;this.fallbackTimer=setTimeout(()=>{this.fallbackTimer=null,!this.isStopped&&!this.playEndFired&&this.firePlayEnd()},e)}}stop(){this.isStopped=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null)}async pause(){this.isStopped||!this.audioContext||await this.audioContext.suspend()}async resume(){this.isStopped||!this.audioContext||await this.audioContext.resume()}checkPlayEnd(){this.totalInputCount>0&&this.endedCount>=this.totalInputCount&&!this.isStopped&&this.firePlayEnd()}firePlayEnd(){this.playEndFired||(this.playEndFired=!0,this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.onPlayEnd?.())}};import{getWsUrl as ae}from"@tbox.cn/app-sdk-client";import{createClientLogger as le}from"@tbox.cn/app-sdk-client";var Q=le("TTS"),I=class{socket=null;player=null;_state="idle";_canSend=!1;pending="";pendingFinish=!1;stateCallbacks=new Set;speakResolve=null;async speak(t){return this.stop(),new Promise(e=>{this.speakResolve=e,this.startStreaming().then(()=>{this.sendText(t),this.finishStreaming()}).catch(()=>{this.setState("idle"),this.resolveSpeak()})})}pause(){this._state!=="playing"||!this.player||(this.player.pause(),this.setState("paused"))}resume(){this._state!=="paused"||!this.player||(this.player.resume(),this.setState("playing"))}stop(){this._canSend=!1,this.pending="",this.pendingFinish=!1,this.closeSocket(),this.player&&(this.player.stop(),this.player=null),this.setState("idle"),this.resolveSpeak()}onStateChange(t){return this.stateCallbacks.add(t),this._state!=="idle"&&t(this._state),()=>this.stateCallbacks.delete(t)}startStreaming(){this.setState("loading"),this._canSend=!1,this.pending="",this.pendingFinish=!1,this.player=new w({sampleRate:16e3,onPlayEnd:()=>{this.setState("idle"),this.resolveSpeak()}}),this.player.start();let t=ae("/ws/tts"),e=F(),o=e?`${t}?token=${encodeURIComponent(e)}`:t;return new Promise((s,i)=>{let n=new WebSocket(o);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.sendMessage({type:"START_TTS",config:{voiceCode:"lingyue",sampleRate:16e3,volume:50,speechRate:0,pitchRate:0}}),s()},n.onmessage=a=>this.handleMessage(a.data),n.onclose=()=>{this.socket=null,this.player?.finish()},n.onerror=a=>{Q.error("socket error",a),i(a),this.stop()}})}sendText(t){t&&(this._canSend?this.sendMessage({type:"TTS_TEXT",text:t}):this.pending+=t)}finishStreaming(){this._canSend?(this.flushPending(),this.sendMessage({type:"TTS_FINISH"})):this.pendingFinish=!0}flushPending(){this.pending&&(this.sendMessage({type:"TTS_TEXT",text:this.pending}),this.pending="")}handleMessage(t){if(typeof t=="string"){try{let e=JSON.parse(t);switch(e.actionType){case"start_ack":this._canSend=!0,this.flushPending(),this.pendingFinish&&(this.pendingFinish=!1,this.sendMessage({type:"TTS_FINISH"}));break;case"completed":this.player?.finish(),this.closeSocket();break;case"failed":Q.error("server error",e.error||e),this.stop();break}}catch{if(!this.player||t.length===0)return;this._state==="loading"&&this.setState("playing");let e=new ArrayBuffer(t.length),o=new Uint8Array(e);for(let s=0;s<t.length;s++)o[s]=t.charCodeAt(s);this.player.input(e)}return}this.player&&(this._state==="loading"&&this.setState("playing"),this.player.input(t))}sendMessage(t){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(t))}closeSocket(){this.socket&&(this.socket.onclose=null,this.socket.close(),this.socket=null)}setState(t){this._state!==t&&(this._state=t,this.stateCallbacks.forEach(e=>e(t)))}resolveSpeak(){this.speakResolve&&(this.speakResolve(),this.speakResolve=null)}};import{hasAlipayBridge as pe,isInAlipayShell as de}from"@tbox.cn/app-sdk-client";function ce(r,t){let e={};return t?.tts||(e.tts=new I),r&&(e.asr=de()||pe()?new k(r):new S(r),e.upload=new R(r),e.feedback=new P(r)),t?{...e,...t}:e}import{httpGet as j}from"@tbox.cn/app-sdk-client";function ue(){let r=null;async function t(s=!1){if(r&&!s)return r;r=null;let{status:i,data:n}=await j("/api/tbox/session",{cache:"no-store"});if(i!==200)throw new Error(`[tbox-session] fetch failed: ${i}`);return r=n,r}function e(){r=null}async function o(s){let i=`/api/conversation/messages?pageSize=${s.pageSize}`;return s.beforeId&&(i+=`&beforeId=${encodeURIComponent(s.beforeId)}`),j(i,{cache:"no-store"})}return{getTboxSession:t,clearTboxSession:e,listMessages:o}}import{createClientLogger as he}from"@tbox.cn/app-sdk-client";var V=he("AUTO-SEND"),Z=["query","prompt"];function fe(r){let t=new URLSearchParams(r);for(let e of Z){let o=t.get(e)?.trim();if(o)return o}return null}function me(r){let t=new URL(r);for(let e of Z)t.searchParams.delete(e);return t.toString()}function ye(){if(typeof window>"u")return null;let r=fe(window.location.search);if(!r)return null;try{window.history.replaceState(null,"",me(window.location.href))}catch(t){V.warn("strip failed (URL retained; refresh may re-send):",t)}return r}async function ge(r,t,e=5e3){if(!await L(e)){V.warn("skipped:reason=socket-timeout");return}t(r),V.info("sent")}export{Ht as AdapterProvider,v as AlipayASRAdapter,w as AudioStreamPlayer,S as BrowserASRAdapter,k as FallbackASRAdapter,P as FeedbackAdapter,W as InMemoryCardHistoryLoader,Ut as ItemActionsRow,I as TTSAdapter,R as UploadAdapter,It as bindCardActionChannel,vt as buildHistoryToolCalls,Ct as buildPreToolToolCalls,At as buildSkillToolCalls,Vt as callAction,Pt as configureHelloContext,O as configureWsAuthErrorHandler,D as configureWsAuthToken,it as configureWsFatalCloseHandler,ot as configureWsKeepalive,st as configureWsUrl,nt as connect,ye as consumeAutoSendQuery,Rt as convertHistoryMessages,q as createAuthClient,dt as createCardActionHandler,Et as createCoreChatState,ft as createEffectTokenDeduper,St as createHostEffectRunner,ce as createPlatformAdapters,ue as createPlatformApi,pt as disconnect,gt as executeAuthorizationEffect,yt as executePaymentEffect,Zt as getAuthClient,F as getAuthToken,ut as hideCard,ht as isHostEffect,wt as isSessionExpiredError,lt as isWsOpen,mt as mapPaymentResultCode,Tt as resolveHistoryMessage,kt as resolveHistoryMeta,bt as resolveHistoryPreTools,xt as resolveHistorySkills,ge as runAutoSend,at as send,U as sendCardAction,N as setActionAuthTokenGetter,_t as subscribeSessionUpgradeDrain,ct as upsertCard,Ft as useASRAdapter,Dt as useAdapters,$t as useFeedbackAdapter,Kt as useRefreshSession,Ot as useTTSAdapter,Lt as useUploadAdapter,L as waitForSocketOpen};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-agent-sdk-client",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
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": {
|