@amaster.ai/copilot-client 1.1.8 → 1.1.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/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +83 -1
- package/dist/index.d.ts +83 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -133,4 +133,86 @@ type CopilotClient = {
|
|
|
133
133
|
};
|
|
134
134
|
declare function createCopilotClient(http: HttpClient, baseUrl?: string, getAccessToken?: () => string | null, getUserUid?: () => string | null): CopilotClient;
|
|
135
135
|
|
|
136
|
-
|
|
136
|
+
interface AutoVoiceReplyMessage {
|
|
137
|
+
messageId?: string;
|
|
138
|
+
role?: string;
|
|
139
|
+
kind: string;
|
|
140
|
+
content?: string;
|
|
141
|
+
}
|
|
142
|
+
interface AutoVoiceReplyConversation {
|
|
143
|
+
taskId: string;
|
|
144
|
+
status: string;
|
|
145
|
+
requestState?: string;
|
|
146
|
+
messages: AutoVoiceReplyMessage[];
|
|
147
|
+
}
|
|
148
|
+
interface AutoVoiceReplySourceSnapshot {
|
|
149
|
+
conversations: AutoVoiceReplyConversation[];
|
|
150
|
+
isLoading: boolean;
|
|
151
|
+
}
|
|
152
|
+
interface AutoVoiceReplySource {
|
|
153
|
+
subscribe(listener: () => void): () => void;
|
|
154
|
+
getSnapshot(): AutoVoiceReplySourceSnapshot;
|
|
155
|
+
}
|
|
156
|
+
interface AutoVoiceReplySpeechSnapshot {
|
|
157
|
+
status: "idle" | "connecting" | "speaking" | "error";
|
|
158
|
+
error?: string | null;
|
|
159
|
+
voice?: string | null;
|
|
160
|
+
}
|
|
161
|
+
interface AutoVoiceReplySpeechDriver {
|
|
162
|
+
subscribe(listener: () => void): () => void;
|
|
163
|
+
getSnapshot(): AutoVoiceReplySpeechSnapshot;
|
|
164
|
+
startStream(input: {
|
|
165
|
+
id: string;
|
|
166
|
+
voice?: string | null;
|
|
167
|
+
audioFormat?: "pcm" | "mp3" | "wav" | "opus";
|
|
168
|
+
sampleRate?: number;
|
|
169
|
+
}): Promise<void>;
|
|
170
|
+
appendText(input: {
|
|
171
|
+
id: string;
|
|
172
|
+
text: string;
|
|
173
|
+
}): Promise<void>;
|
|
174
|
+
commit(): void;
|
|
175
|
+
finish(): void;
|
|
176
|
+
stop(): void;
|
|
177
|
+
setVoice?(voice: string | null): void;
|
|
178
|
+
getVoice?(): string | null;
|
|
179
|
+
}
|
|
180
|
+
interface AutoVoiceReplyStorage {
|
|
181
|
+
getItem(key: string): string | null | undefined;
|
|
182
|
+
setItem(key: string, value: string): void;
|
|
183
|
+
}
|
|
184
|
+
interface AutoVoiceReplySnapshot {
|
|
185
|
+
enabled: boolean;
|
|
186
|
+
status: "idle" | "connecting" | "speaking" | "error";
|
|
187
|
+
connecting: boolean;
|
|
188
|
+
speaking: boolean;
|
|
189
|
+
voice: string | null;
|
|
190
|
+
activeTaskId: string | null;
|
|
191
|
+
suppressedTaskId: string | null;
|
|
192
|
+
error: string | null;
|
|
193
|
+
}
|
|
194
|
+
interface AutoVoiceReplyController {
|
|
195
|
+
subscribe(listener: () => void): () => void;
|
|
196
|
+
getSnapshot(): AutoVoiceReplySnapshot;
|
|
197
|
+
setEnabled(enabled: boolean): void;
|
|
198
|
+
toggleEnabled(): void;
|
|
199
|
+
toggleEnabledOrStop(): void;
|
|
200
|
+
stop(): void;
|
|
201
|
+
setVoice(voice: string | null): void;
|
|
202
|
+
getVoice(): string | null;
|
|
203
|
+
destroy(): void;
|
|
204
|
+
}
|
|
205
|
+
interface CreateAutoVoiceReplyControllerOptions {
|
|
206
|
+
source: AutoVoiceReplySource;
|
|
207
|
+
speech: AutoVoiceReplySpeechDriver;
|
|
208
|
+
storage?: AutoVoiceReplyStorage;
|
|
209
|
+
enabledStorageKey?: string;
|
|
210
|
+
defaultVoice?: string | null;
|
|
211
|
+
id?: string;
|
|
212
|
+
audioFormat?: "pcm" | "mp3" | "wav" | "opus";
|
|
213
|
+
sampleRate?: number;
|
|
214
|
+
preprocessText?: (text: string) => string;
|
|
215
|
+
}
|
|
216
|
+
declare function createAutoVoiceReplyController(options: CreateAutoVoiceReplyControllerOptions): AutoVoiceReplyController;
|
|
217
|
+
|
|
218
|
+
export { type AutoVoiceReplyController, type AutoVoiceReplyConversation, type AutoVoiceReplyMessage, type AutoVoiceReplySnapshot, type AutoVoiceReplySource, type AutoVoiceReplySourceSnapshot, type AutoVoiceReplySpeechDriver, type AutoVoiceReplySpeechSnapshot, type AutoVoiceReplyStorage, type Conversation, type ConversationController, type ConversationControllerOptions, type ConversationControllerSnapshot, type ConversationRequestState, type ConversationRuntimeError, type ConversationStrings, type CopilotClient, type CreateAutoVoiceReplyControllerOptions, type ErrorMessage, type FileContent, type HistoryState, type ImageContent, type MessageContent, type MessagesItem, type Role, type TextContent, type TextMessage, type ThoughtMessage, type ToolMessage, type UIRenderMessage, type UpdateMessageInput, createAutoVoiceReplyController, createCopilotClient };
|
package/dist/index.d.ts
CHANGED
|
@@ -133,4 +133,86 @@ type CopilotClient = {
|
|
|
133
133
|
};
|
|
134
134
|
declare function createCopilotClient(http: HttpClient, baseUrl?: string, getAccessToken?: () => string | null, getUserUid?: () => string | null): CopilotClient;
|
|
135
135
|
|
|
136
|
-
|
|
136
|
+
interface AutoVoiceReplyMessage {
|
|
137
|
+
messageId?: string;
|
|
138
|
+
role?: string;
|
|
139
|
+
kind: string;
|
|
140
|
+
content?: string;
|
|
141
|
+
}
|
|
142
|
+
interface AutoVoiceReplyConversation {
|
|
143
|
+
taskId: string;
|
|
144
|
+
status: string;
|
|
145
|
+
requestState?: string;
|
|
146
|
+
messages: AutoVoiceReplyMessage[];
|
|
147
|
+
}
|
|
148
|
+
interface AutoVoiceReplySourceSnapshot {
|
|
149
|
+
conversations: AutoVoiceReplyConversation[];
|
|
150
|
+
isLoading: boolean;
|
|
151
|
+
}
|
|
152
|
+
interface AutoVoiceReplySource {
|
|
153
|
+
subscribe(listener: () => void): () => void;
|
|
154
|
+
getSnapshot(): AutoVoiceReplySourceSnapshot;
|
|
155
|
+
}
|
|
156
|
+
interface AutoVoiceReplySpeechSnapshot {
|
|
157
|
+
status: "idle" | "connecting" | "speaking" | "error";
|
|
158
|
+
error?: string | null;
|
|
159
|
+
voice?: string | null;
|
|
160
|
+
}
|
|
161
|
+
interface AutoVoiceReplySpeechDriver {
|
|
162
|
+
subscribe(listener: () => void): () => void;
|
|
163
|
+
getSnapshot(): AutoVoiceReplySpeechSnapshot;
|
|
164
|
+
startStream(input: {
|
|
165
|
+
id: string;
|
|
166
|
+
voice?: string | null;
|
|
167
|
+
audioFormat?: "pcm" | "mp3" | "wav" | "opus";
|
|
168
|
+
sampleRate?: number;
|
|
169
|
+
}): Promise<void>;
|
|
170
|
+
appendText(input: {
|
|
171
|
+
id: string;
|
|
172
|
+
text: string;
|
|
173
|
+
}): Promise<void>;
|
|
174
|
+
commit(): void;
|
|
175
|
+
finish(): void;
|
|
176
|
+
stop(): void;
|
|
177
|
+
setVoice?(voice: string | null): void;
|
|
178
|
+
getVoice?(): string | null;
|
|
179
|
+
}
|
|
180
|
+
interface AutoVoiceReplyStorage {
|
|
181
|
+
getItem(key: string): string | null | undefined;
|
|
182
|
+
setItem(key: string, value: string): void;
|
|
183
|
+
}
|
|
184
|
+
interface AutoVoiceReplySnapshot {
|
|
185
|
+
enabled: boolean;
|
|
186
|
+
status: "idle" | "connecting" | "speaking" | "error";
|
|
187
|
+
connecting: boolean;
|
|
188
|
+
speaking: boolean;
|
|
189
|
+
voice: string | null;
|
|
190
|
+
activeTaskId: string | null;
|
|
191
|
+
suppressedTaskId: string | null;
|
|
192
|
+
error: string | null;
|
|
193
|
+
}
|
|
194
|
+
interface AutoVoiceReplyController {
|
|
195
|
+
subscribe(listener: () => void): () => void;
|
|
196
|
+
getSnapshot(): AutoVoiceReplySnapshot;
|
|
197
|
+
setEnabled(enabled: boolean): void;
|
|
198
|
+
toggleEnabled(): void;
|
|
199
|
+
toggleEnabledOrStop(): void;
|
|
200
|
+
stop(): void;
|
|
201
|
+
setVoice(voice: string | null): void;
|
|
202
|
+
getVoice(): string | null;
|
|
203
|
+
destroy(): void;
|
|
204
|
+
}
|
|
205
|
+
interface CreateAutoVoiceReplyControllerOptions {
|
|
206
|
+
source: AutoVoiceReplySource;
|
|
207
|
+
speech: AutoVoiceReplySpeechDriver;
|
|
208
|
+
storage?: AutoVoiceReplyStorage;
|
|
209
|
+
enabledStorageKey?: string;
|
|
210
|
+
defaultVoice?: string | null;
|
|
211
|
+
id?: string;
|
|
212
|
+
audioFormat?: "pcm" | "mp3" | "wav" | "opus";
|
|
213
|
+
sampleRate?: number;
|
|
214
|
+
preprocessText?: (text: string) => string;
|
|
215
|
+
}
|
|
216
|
+
declare function createAutoVoiceReplyController(options: CreateAutoVoiceReplyControllerOptions): AutoVoiceReplyController;
|
|
217
|
+
|
|
218
|
+
export { type AutoVoiceReplyController, type AutoVoiceReplyConversation, type AutoVoiceReplyMessage, type AutoVoiceReplySnapshot, type AutoVoiceReplySource, type AutoVoiceReplySourceSnapshot, type AutoVoiceReplySpeechDriver, type AutoVoiceReplySpeechSnapshot, type AutoVoiceReplyStorage, type Conversation, type ConversationController, type ConversationControllerOptions, type ConversationControllerSnapshot, type ConversationRequestState, type ConversationRuntimeError, type ConversationStrings, type CopilotClient, type CreateAutoVoiceReplyControllerOptions, type ErrorMessage, type FileContent, type HistoryState, type ImageContent, type MessageContent, type MessagesItem, type Role, type TextContent, type TextMessage, type ThoughtMessage, type ToolMessage, type UIRenderMessage, type UpdateMessageInput, createAutoVoiceReplyController, createCopilotClient };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {getMiniProgramRequest,resolveMiniProgramGlobals}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';import je from'miniprogram-text-decoder';var ae=class{constructor(){this.aborted=false;this.listeners=[];this.signal={aborted:false,addEventListener:(t,o)=>{this.listeners.push(o);}};}abort(){this.aborted||(this.aborted=true,this.signal.aborted=true,this.listeners.forEach(t=>t()));}};function ye(){return typeof AbortController<"u"?new AbortController:new ae}function m(){return new Date().toISOString()}function B(){return `msg-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function qe(e){return {...e}}function ie(e){return {...e,system:e.system?{...e.system}:void 0,runtimeError:e.runtimeError?{...e.runtimeError}:void 0,messages:e.messages.map(t=>qe(t))}}function le(e){return {starting:e.starting,isLoading:e.isLoading,isLoadingHistory:e.isLoadingHistory,historyState:{...e.historyState},conversations:e.order.map(t=>e.byId[t]).filter(t=>!!t).map(t=>ie(t))}}var X={"text-content":(e,t,o,a,l)=>{if(!o)return e;let u=e.messages.find(r=>r.messageId===o),d=t.text||"";return u&&"content"in u?{...e,messages:e.messages.map(r=>r.messageId===o?{...r,content:r.content+d}:r),lastUpdated:m()}:{...e,messages:[...e.messages,{messageId:o,role:a,kind:"text-content",content:d,timestamp:l?.timestamp||m()}],lastUpdated:m()}},thought:(e,t,o,a,l)=>{if(!o)return e;let u=t?.data?.description||"",d=e.messages.find(r=>r.messageId===o);return d&&"thought"in d?{...e,messages:e.messages.map(r=>r.messageId===o?{...r,thought:r.thought+u}:r),lastUpdated:m()}:{...e,messages:[...e.messages,{messageId:o,role:a,kind:"thought",thought:u,timestamp:l?.timestamp||m()}],lastUpdated:m()}},tool:(e,t,o,a,l)=>{let u=t?.data||{},d=u?.tool,r=d?.displayName||d?.name||"",f=u?.request,y=f?.callId;if(!y||!r)return e;let C=u?.status,h=e.messages.find(w=>w.messageId===y);return h&&"toolStatus"in h?{...e,messages:e.messages.map(w=>w.messageId===y?{...w,toolStatus:C||w.toolStatus}:w),lastUpdated:m()}:{...e,messages:[...e.messages,{messageId:y,role:a,kind:"tool",toolName:r,toolDescription:f?.args?.query||"",toolStatus:C||"pending",timestamp:l?.timestamp||m()}],lastUpdated:m()}},error:(e,t,o,a)=>{let l=t?.text||t?.data?.error||"\u53D1\u751F\u9519\u8BEF";return {...e,messages:[...e.messages,{messageId:o||`error-${Date.now()}`,role:a,kind:"error",content:l,timestamp:m()}],status:"error",lastUpdated:m()}},"ui-render":(e,t,o,a,l)=>{if(!o)return e;let u=e.messages.find(f=>f.messageId===o),r=(t?.data||{}).spec||{root:"",elements:{}};return u&&u.kind==="ui-render"?{...e,messages:e.messages.map(f=>f.messageId===o?{...f,spec:r}:f),lastUpdated:m()}:{...e,messages:[...e.messages,{messageId:o,role:a,kind:"ui-render",spec:r,timestamp:l?.timestamp||m()}],lastUpdated:m()}}};function ue(e,t){return e?.data?.tool?"tool":e?.data?.type==="ui"?"ui-render":e?.kind==="text"?"text-content":e?.data?.type==="though"||t?.coderAgent?.kind==="thought"?"thought":t?.error?"error":"unknown"}function Ce(){let e=resolveMiniProgramGlobals();return typeof e?.wx?.request=="function"||typeof e?.qq?.request=="function"}function he(){return typeof resolveMiniProgramGlobals()?.tt?.createEventSource=="function"}function Se(e,t){let a=(t.mode||"conversation")==="single-turn",l=!a,u=!a,d=()=>t.getContextId?.()??e.createContextId(a?"single-turn":"conversation"),r={byId:{},order:[],starting:true,isLoading:false,isLoadingHistory:false,historyState:{next:null,hasMore:false}},f=new Set,y=null,h=null,w="unknown",R="",T=null,q=false,D=d(),H=e.createScopedRuntime(D),x=null,c=()=>{if(q)return;let n=le(r);f.forEach(s=>s(n));},E=n=>{r.order=r.order.filter(s=>s!==n);},A=(n,s=true)=>{E(n),r.order=s?[...r.order,n]:[n,...r.order];},L=()=>{w="unknown",R="";},G=n=>{let s=n&&typeof n=="object"?n:{},i=String(s.message||s.errMsg||"").toLowerCase(),g=String(s.errorCode||""),I=String(s.errNo||"");return s.name==="TypeError"||/failed to fetch|fetch failed|timed out|disconnected|offline|断网/.test(i)||["600009","21101","21102","21103"].includes(g)||["600009","21101","21102","21103"].includes(I)},$=(n,s="stream")=>{let i=n&&typeof n=="object"?n:{},g=String(i.message||i.errMsg||"").toLowerCase();return {code:G(n)?"network":"unknown",message:g,retryable:true,source:s,timestamp:m()}},F=(n,s)=>{if(!n)return;let i=r.byId[n];i&&(r.byId[n]={...i,requestState:s.requestState??i.requestState,runtimeError:s.runtimeError===void 0?i.runtimeError:s.runtimeError,status:s.status??i.status,lastUpdated:m()});},j=n=>{F(n,{requestState:"idle",runtimeError:null});},K=()=>{r.byId={},r.order=[],r.historyState={next:null,hasMore:false};},J=n=>{r.isLoading=n,!n&&te();},me=()=>(D=d(),H=e.createScopedRuntime(D),D),ee=()=>{y?.abort(),y=null,j(x),J(false),c();},ge=()=>{L(),j(x),x&&F(x,{status:"completed"}),x=null,h=null,y=null,J(false),c();},W=n=>{r.byId[n.taskId]=n,A(n.taskId,true),c();},fe=n=>{r.byId[n]&&(delete r.byId[n],E(n),c());},Ue=()=>{W({taskId:"loading-placeholder",status:"working",messages:[{messageId:"loading-placeholder",role:"assistant",kind:"text-content",content:t.strings.thinking,timestamp:m()}],lastUpdated:m()});},te=()=>{fe("loading-placeholder");},re=({kind:n,taskId:s,part:i,status:g,handler:I,isHistory:p,historyId:b,messageId:S})=>{let M=S||R,k=g?.message?.role==="agent"?"assistant":"user";!S&&(n==="ui-render"||n!=="unknown"&&n!==w)&&(w=n,M=B(),R=M);let P=r.byId[s]??{taskId:s,status:p?"completed":"submitted",messages:[],role:k,historyId:b,lastUpdated:m()},v=I(P,i,M,k,g);r.byId[s]={...v,status:g?.state||P.status,lastUpdated:m()},p||A(s,true),c();},V=(n,s="stream",i=x)=>{F(i,{requestState:"error",runtimeError:$(n,s),status:"error"}),i&&x===i&&(x=null),J(false),c();},He=n=>{if(!n?.result)return;let s=n.result,{taskId:i,status:g,metadata:I,final:p}=s;if(p){ge();return}if(!i)return;h=i;let b=g?.message?.parts?.[0],S=ue(b,I),M=X[S];M&&(te(),re({kind:S,taskId:i,part:b,status:g,handler:M}));},Le=(n,s)=>{let{messageId:i,historyId:g}=n||{};if(!i)return;let I=n.parts?.[0],p=ue(I);if(p==="text-content"){let S=I.text||"";if(S=S.trim(),S.startsWith("<ui>")){let M=S.slice(4).trim();try{let k=JSON.parse(M);k.root&&k.elements&&re({kind:"ui-render",taskId:s,part:{kind:"data",data:{type:"ui",spec:k}},handler:X["ui-render"],isHistory:!0,historyId:g,messageId:i,status:{message:n}});}catch{}return}}let b=X[p];b&&re({kind:p,taskId:s,part:I,handler:b,isHistory:true,historyId:g,messageId:i,status:{message:n}});},Q=async(n,s,i=false,g=0,I=false,p=x)=>{x=p,ee(),L(),F(p,{requestState:"submitting",runtimeError:null,status:"submitted"});let b=ye();y=b,i&&(Ue(),J(true),c());let S=false,M=false,k=false,P=false,v=s?.taskId||null,_=H.sendMessage(n,{taskId:s?.taskId,signal:b.signal,preferMiniProgramRequest:I,onMessage:N=>{let oe=N?.result?.taskId,U=!!N?.result?.final;oe&&(v=oe),U&&(P=true),S=true,F(p,{requestState:U?"idle":"streaming",runtimeError:null,status:U?"completed":"working"}),He(N);},onClose:()=>{}});let ne=async()=>{if(he()&&!!getMiniProgramRequest()&&!k&&!P&&g<2){console.log("[recovering]"),F(p,{requestState:"recovering",runtimeError:null,status:"working"}),c();try{let U=await H.getChatStatus(v||void 0);if(U.working&&U.taskId)return h=U.taskId,await Q([],{taskId:U.taskId},!0,g+1,!0,p),!0;if(!S&&!v&&!U.taskId&&g<1)return await Q(n,s,!0,g+1,!0,p),!0}catch(U){return console.error("[ConversationController] recovery failed:",U),V(U,"recovery",p),true}}return false},se,pe=false;try{await _;}catch(N){N?.name==="AbortError"||b.signal.aborted?k=true:(M=true,se=N,console.error("[ConversationController] Stream error:",N));}finally{y===b&&(y=null),pe=await ne();}pe||(M?V(se,"stream",p):!S&&i&&!k?V(se,"send",p):k?(j(p),p&&x===p&&(x=null),J(false),c()):P&&r.isLoading?ge():!P&&r.isLoading&&V(void 0,"stream",p));};return {getSnapshot(){return le(r)},subscribe(n){return f.add(n),()=>{f.delete(n);}},async init(){if(!q)return T||(r.starting=true,c(),T=(async()=>{try{if(l&&await this.loadHistory(),u){let n=await H.getChatStatus();n.taskId&&n.working&&(h=n.taskId,await Q([],{taskId:n.taskId},!1));}}catch(n){console.error("[ConversationController] init failed:",n);}finally{r.starting=false,c(),T=null;}})(),T)},destroy(){q=true,ee(),f.clear();},async sendMessage(n){if(r.isLoading||!n.trim())return;a&&(this.abort(),K(),L(),h=null,me());let s=B();x=s,W({taskId:s,status:"submitted",requestState:"submitting",runtimeError:null,messages:[{messageId:B(),role:"user",kind:"text-content",content:n,timestamp:m()}],lastUpdated:m()});try{await Q([{role:"user",content:n}],void 0,!0,0,!1,s);}catch(i){if(i.name==="AbortError")return;V(i,"send",s);}},abort(){let n=y?.signal.aborted;ee(),L(),j(x),x=null,h=null,te(),n||Promise.resolve();},async cancelChat(n){let s=n||h;if(this.abort(),W({taskId:B(),status:"error",messages:[{messageId:`cancel-${Date.now()}`,role:"assistant",kind:"text-content",content:t.strings.cancelled,timestamp:m()}],lastUpdated:m()}),!!s)try{await H.cancelChat(s),h=null;}catch(i){console.error("[ConversationController] cancel failed:",i);}},resetConversation(n){if(this.abort(),K(),x=null,h=null,L(),a&&me(),n){let s=`conv-${Date.now()}`;r.byId[s]={taskId:s,status:"submitted",messages:[{messageId:`greeting-${Date.now()}`,role:"assistant",kind:"text-content",content:n,timestamp:m()}],lastUpdated:m()},r.order=[s];}c();},async startNewConversation(){W({taskId:B(),status:"submitted",messages:[],lastUpdated:m(),system:{level:"newConversation"}});try{await H.newConversation();}catch(n){console.error("[ConversationController] newConversation failed:",n);}},async loadHistory(n=20,s){r.isLoadingHistory=true,c();try{let i=await H.getHistory(n,s),g=i?.messages||[],I="",p="",b=[];g.forEach(S=>{let M=S.role==="agent"?"assistant":"user";M!==p&&(I=`history-conv-${B()}`,b.push(I),p=M),Le(S,I);}),r.order=[...b,...r.order.filter(S=>!b.includes(S))],r.historyState={next:i?.next||null,hasMore:i?.hasMore||!1};}catch(i){console.error("[ConversationController] loadHistory failed:",i);}finally{r.isLoadingHistory=false,c();}},async loadMoreHistory(){!r.historyState.hasMore||r.isLoadingHistory||!r.historyState.next||await this.loadHistory(20,r.historyState.next);},getConversation(n){let s=r.byId[n];return s?ie(s):void 0},clearConversation(n){fe(n);},removeMessage(n,s){let i=r.byId[n];i&&(r.byId[n]={...i,messages:i.messages.filter(g=>g.messageId!==s),lastUpdated:m()},A(n,true),c());},updateMessage(n){let{taskId:s,messageId:i,content:g,partial:I=false,status:p,response:b,metadata:S={}}=n,M=r.byId[s];if(!M)return;let k=M.messages.findIndex(ne=>ne.messageId===i);if(k===-1)return;let P=M.messages[k];if(!P)return;let v={...P,...S};g!==void 0&&("content"in v?v.content=I?`${v.content||""}${g}`:g:"thought"in v?v.thought=I?`${v.thought||""}${g}`:g:P.kind==="text-content"&&(v.content=I?`${P.content||""}${g}`:g)),("toolStatus"in v||p)&&(v.toolStatus=p||v.toolStatus),b!==void 0&&(v.response=b);let _=[...M.messages];_[k]=v,r.byId[s]={...M,messages:_,lastUpdated:m()},A(s,true),c();}}}function O(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let a=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?a:a&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let o=Math.random()*16|0;return (t==="x"?o:o&3|8).toString(16)})}function Ie(e){let t=/^www\.([\da-z-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(e);if(t?.[1])return t[1];let o=/^([\da-z-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(e);return o?.[1]?o[1]:null}function De(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-z-]+)(?:\/|$)/.exec(e);return t?.[1]?t[1]:Ie(window.location.hostname)}catch{return null}}var de=null,Fe=null;function Me(e){let t=e?Ie(e):De();return t||(de||(de=O()),de)}function be(e,t){return (o="conversation")=>{let a=getMiniProgramRequest(),l=Me();if(a){let r=e?e.replace(/^https?:\/\//,"").split("/")[0]:"";l=Me(r);}let u=t?.()??Fe??(Fe=`anonymous-${O()}`),d=`${l}:${u}`;return o==="single-turn"?`${d}:${O()}`:d}}function we(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function ve(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
2
|
-
`)}function
|
|
1
|
+
import {getMiniProgramRequest,resolveMiniProgramGlobals}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';import je from'miniprogram-text-decoder';var me=class{constructor(){this.aborted=false;this.listeners=[];this.signal={aborted:false,addEventListener:(t,r)=>{this.listeners.push(r);}};}abort(){this.aborted||(this.aborted=true,this.signal.aborted=true,this.listeners.forEach(t=>t()));}};function ve(){return typeof AbortController<"u"?new AbortController:new me}function f(){return new Date().toISOString()}function Q(){return `msg-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function De(e){return {...e}}function pe(e){return {...e,system:e.system?{...e.system}:void 0,runtimeError:e.runtimeError?{...e.runtimeError}:void 0,messages:e.messages.map(t=>De(t))}}function fe(e){return {starting:e.starting,isLoading:e.isLoading,isLoadingHistory:e.isLoadingHistory,historyState:{...e.historyState},conversations:e.order.map(t=>e.byId[t]).filter(t=>!!t).map(t=>pe(t))}}var oe={"text-content":(e,t,r,a,i)=>{if(!r)return e;let c=e.messages.find(n=>n.messageId===r),d=t.text||"";return c&&"content"in c?{...e,messages:e.messages.map(n=>n.messageId===r?{...n,content:n.content+d}:n),lastUpdated:f()}:{...e,messages:[...e.messages,{messageId:r,role:a,kind:"text-content",content:d,timestamp:i?.timestamp||f()}],lastUpdated:f()}},thought:(e,t,r,a,i)=>{if(!r)return e;let c=t?.data?.description||"",d=e.messages.find(n=>n.messageId===r);return d&&"thought"in d?{...e,messages:e.messages.map(n=>n.messageId===r?{...n,thought:n.thought+c}:n),lastUpdated:f()}:{...e,messages:[...e.messages,{messageId:r,role:a,kind:"thought",thought:c,timestamp:i?.timestamp||f()}],lastUpdated:f()}},tool:(e,t,r,a,i)=>{let c=t?.data||{},d=c?.tool,n=d?.displayName||d?.name||"",m=c?.request,y=m?.callId;if(!y||!n)return e;let x=c?.status,S=e.messages.find(b=>b.messageId===y);return S&&"toolStatus"in S?{...e,messages:e.messages.map(b=>b.messageId===y?{...b,toolStatus:x||b.toolStatus}:b),lastUpdated:f()}:{...e,messages:[...e.messages,{messageId:y,role:a,kind:"tool",toolName:n,toolDescription:m?.args?.query||"",toolStatus:x||"pending",timestamp:i?.timestamp||f()}],lastUpdated:f()}},error:(e,t,r,a)=>{let i=t?.text||t?.data?.error||"\u53D1\u751F\u9519\u8BEF";return {...e,messages:[...e.messages,{messageId:r||`error-${Date.now()}`,role:a,kind:"error",content:i,timestamp:f()}],status:"error",lastUpdated:f()}},"ui-render":(e,t,r,a,i)=>{if(!r)return e;let c=e.messages.find(m=>m.messageId===r),n=(t?.data||{}).spec||{root:"",elements:{}};return c&&c.kind==="ui-render"?{...e,messages:e.messages.map(m=>m.messageId===r?{...m,spec:n}:m),lastUpdated:f()}:{...e,messages:[...e.messages,{messageId:r,role:a,kind:"ui-render",spec:n,timestamp:i?.timestamp||f()}],lastUpdated:f()}}};function ye(e,t){return e?.data?.tool?"tool":e?.data?.type==="ui"?"ui-render":e?.kind==="text"?"text-content":e?.data?.type==="though"||t?.coderAgent?.kind==="thought"?"thought":t?.error?"error":"unknown"}function Fe(e,t){if(typeof e=="string"){let r=e.trim().toUpperCase();if(r==="TT"||r==="DOUYIN"||r==="WEAPP"||r==="WECHAT")return true}return t?typeof t.TT<"u"&&e===t.TT||typeof t.WEAPP<"u"&&e===t.WEAPP:false}function ae(){let e=resolveMiniProgramGlobals();return Fe(e?.Taro?.getEnv?.(),e?.Taro?.ENV_TYPE)?true:typeof e?.wx?.request=="function"||typeof e?.tt?.request=="function"||typeof e?.my?.request=="function"||typeof e?.swan?.request=="function"||typeof e?.qq?.request=="function"||typeof e?.jd?.request=="function"}function be(){let e=resolveMiniProgramGlobals();return !(typeof e?.tt?.request=="function"||typeof e?.tt?.createEventSource=="function")}function Me(){return typeof resolveMiniProgramGlobals()?.tt?.createEventSource=="function"}function Re(e,t){let a=(t.mode||"conversation")==="single-turn",i=!a,c=!a,d=()=>t.getContextId?.()??e.createContextId(a?"single-turn":"conversation"),n={byId:{},order:[],starting:true,isLoading:false,isLoadingHistory:false,historyState:{next:null,hasMore:false}},m=new Set,y=null,S=null,b="unknown",M="",P=null,R=false,D=d(),q=e.createScopedRuntime(D),h=null,g=()=>{if(R)return;let s=fe(n);m.forEach(o=>o(s));},H=s=>{n.order=n.order.filter(o=>o!==s);},k=(s,o=true)=>{H(s),n.order=o?[...n.order,s]:[s,...n.order];},I=()=>{b="unknown",M="";},z=s=>{let o=s&&typeof s=="object"?s:{},u=String(o.message||o.errMsg||"").toLowerCase(),p=String(o.errorCode||""),A=String(o.errNo||"");return o.name==="TypeError"||/failed to fetch|fetch failed|timed out|disconnected|offline|断网/.test(u)||["600009","21101","21102","21103"].includes(p)||["600009","21101","21102","21103"].includes(A)},_=(s,o="stream")=>{let u=s&&typeof s=="object"?s:{},p=String(u.message||u.errMsg||"").toLowerCase();return {code:z(s)?"network":"unknown",message:p,retryable:true,source:o,timestamp:f()}},L=(s,o)=>{if(!s)return;let u=n.byId[s];u&&(n.byId[s]={...u,requestState:o.requestState??u.requestState,runtimeError:o.runtimeError===void 0?u.runtimeError:o.runtimeError,status:o.status??u.status,lastUpdated:f()});},j=s=>{L(s,{requestState:"idle",runtimeError:null});},X=()=>{n.byId={},n.order=[],n.historyState={next:null,hasMore:false};},K=s=>{n.isLoading=s,!s&&ne();},G=()=>(D=d(),q=e.createScopedRuntime(D),D),Z=()=>{y?.abort(),y=null,j(h),K(false),g();},se=()=>{I(),j(h),h&&L(h,{status:"completed"}),h=null,S=null,y=null,K(false),g();},J=s=>{n.byId[s.taskId]=s,k(s.taskId,true),g();},re=s=>{n.byId[s]&&(delete n.byId[s],H(s),g());},ue=()=>{J({taskId:"loading-placeholder",status:"working",messages:[{messageId:"loading-placeholder",role:"assistant",kind:"text-content",content:t.strings.thinking,timestamp:f()}],lastUpdated:f()});},ne=()=>{re("loading-placeholder");},Y=({kind:s,taskId:o,part:u,status:p,handler:A,isHistory:C,historyId:E,messageId:T})=>{let w=T||M,O=p?.message?.role==="agent"?"assistant":"user";!T&&(s==="ui-render"||s!=="unknown"&&s!==b)&&(b=s,w=Q(),M=w);let $=n.byId[o]??{taskId:o,status:C?"completed":"submitted",messages:[],role:O,historyId:E,lastUpdated:f()},U=A($,u,w,O,p);n.byId[o]={...U,status:p?.state||$.status,lastUpdated:f()},C||k(o,true),g();},l=(s,o="stream",u=h)=>{L(u,{requestState:"error",runtimeError:_(s,o),status:"error"}),u&&h===u&&(h=null),K(false),g();},v=s=>{if(!s?.result)return;let o=s.result,{taskId:u,status:p,metadata:A,final:C}=o;if(C){se();return}if(!u)return;S=u;let E=p?.message?.parts?.[0],T=ye(E,A),w=oe[T];w&&(ne(),Y({kind:T,taskId:u,part:E,status:p,handler:w}));},F=(s,o)=>{let{messageId:u,historyId:p}=s||{};if(!u)return;let A=s.parts?.[0],C=ye(A);if(C==="text-content"){let T=A.text||"";if(T=T.trim(),T.startsWith("<ui>")){let w=T.slice(4).trim();try{let O=JSON.parse(w);O.root&&O.elements&&Y({kind:"ui-render",taskId:o,part:{kind:"data",data:{type:"ui",spec:O}},handler:oe["ui-render"],isHistory:!0,historyId:p,messageId:u,status:{message:s}});}catch{}return}}let E=oe[C];E&&Y({kind:C,taskId:o,part:A,handler:E,isHistory:true,historyId:p,messageId:u,status:{message:s}});},V=async(s,o,u=false,p=0,A=false,C=h)=>{h=C,Z(),I(),L(C,{requestState:"submitting",runtimeError:null,status:"submitted"});let E=ve();y=E,u&&(ue(),K(true),g());let T=false,w=false,O=false,$=false,U=o?.taskId||null,ee=q.sendMessage(s,{taskId:o?.taskId,signal:E.signal,preferMiniProgramRequest:A,onMessage:W=>{let ge=W?.result?.taskId,N=!!W?.result?.final;ge&&(U=ge),N&&($=true),T=true,L(C,{requestState:N?"idle":"streaming",runtimeError:null,status:N?"completed":"working"}),v(W);},onClose:()=>{}});let ce=async()=>{if(Me()&&!!getMiniProgramRequest()&&!O&&!$&&p<2){console.log("[recovering]"),L(C,{requestState:"recovering",runtimeError:null,status:"working"}),g();try{let N=await q.getChatStatus(U||void 0);if(N.working&&N.taskId)return S=N.taskId,await V([],{taskId:N.taskId},!0,p+1,!0,C),!0;if(!T&&!U&&!N.taskId&&p<1)return await V(s,o,!0,p+1,!0,C),!0}catch(N){return console.error("[ConversationController] recovery failed:",N),l(N,"recovery",C),true}}return false},de,Ce=false;try{await ee;}catch(W){W?.name==="AbortError"||E.signal.aborted?O=true:(w=true,de=W,console.error("[ConversationController] Stream error:",W));}finally{y===E&&(y=null),Ce=await ce();}Ce||(w?l(de,"stream",C):!T&&u&&!O?l(de,"send",C):O?(j(C),C&&h===C&&(h=null),K(false),g()):$&&n.isLoading?se():!$&&n.isLoading&&l(void 0,"stream",C));};return {getSnapshot(){return fe(n)},subscribe(s){return m.add(s),()=>{m.delete(s);}},async init(){if(!R)return P||(n.starting=true,g(),P=(async()=>{try{if(i&&await this.loadHistory(),c){let s=await q.getChatStatus();s.taskId&&s.working&&(S=s.taskId,await V([],{taskId:s.taskId},!1));}}catch(s){console.error("[ConversationController] init failed:",s);}finally{n.starting=false,g(),P=null;}})(),P)},destroy(){R=true,Z(),m.clear();},async sendMessage(s){if(n.isLoading||!s.trim())return;a&&(this.abort(),X(),I(),S=null,G());let o=Q();h=o,J({taskId:o,status:"submitted",requestState:"submitting",runtimeError:null,messages:[{messageId:Q(),role:"user",kind:"text-content",content:s,timestamp:f()}],lastUpdated:f()});try{await V([{role:"user",content:s}],void 0,!0,0,!1,o);}catch(u){if(u.name==="AbortError")return;l(u,"send",o);}},abort(){let s=y?.signal.aborted;Z(),I(),j(h),h=null,S=null,ne(),s||Promise.resolve();},async cancelChat(s){let o=s||S;if(this.abort(),J({taskId:Q(),status:"error",messages:[{messageId:`cancel-${Date.now()}`,role:"assistant",kind:"text-content",content:t.strings.cancelled,timestamp:f()}],lastUpdated:f()}),!!o)try{await q.cancelChat(o),S=null;}catch(u){console.error("[ConversationController] cancel failed:",u);}},resetConversation(s){if(this.abort(),X(),h=null,S=null,I(),a&&G(),s){let o=`conv-${Date.now()}`;n.byId[o]={taskId:o,status:"submitted",messages:[{messageId:`greeting-${Date.now()}`,role:"assistant",kind:"text-content",content:s,timestamp:f()}],lastUpdated:f()},n.order=[o];}g();},async startNewConversation(){J({taskId:Q(),status:"submitted",messages:[],lastUpdated:f(),system:{level:"newConversation"}});try{await q.newConversation();}catch(s){console.error("[ConversationController] newConversation failed:",s);}},async loadHistory(s=20,o){n.isLoadingHistory=true,g();try{let u=await q.getHistory(s,o),p=u?.messages||[],A="",C="",E=[];p.forEach(T=>{let w=T.role==="agent"?"assistant":"user";w!==C&&(A=`history-conv-${Q()}`,E.push(A),C=w),F(T,A);}),n.order=[...E,...n.order.filter(T=>!E.includes(T))],n.historyState={next:u?.next||null,hasMore:u?.hasMore||!1};}catch(u){console.error("[ConversationController] loadHistory failed:",u);}finally{n.isLoadingHistory=false,g();}},async loadMoreHistory(){!n.historyState.hasMore||n.isLoadingHistory||!n.historyState.next||await this.loadHistory(20,n.historyState.next);},getConversation(s){let o=n.byId[s];return o?pe(o):void 0},clearConversation(s){re(s);},removeMessage(s,o){let u=n.byId[s];u&&(n.byId[s]={...u,messages:u.messages.filter(p=>p.messageId!==o),lastUpdated:f()},k(s,true),g());},updateMessage(s){let{taskId:o,messageId:u,content:p,partial:A=false,status:C,response:E,metadata:T={}}=s,w=n.byId[o];if(!w)return;let O=w.messages.findIndex(ce=>ce.messageId===u);if(O===-1)return;let $=w.messages[O];if(!$)return;let U={...$,...T};p!==void 0&&("content"in U?U.content=A?`${U.content||""}${p}`:p:"thought"in U?U.thought=A?`${U.thought||""}${p}`:p:$.kind==="text-content"&&(U.content=A?`${$.content||""}${p}`:p)),("toolStatus"in U||C)&&(U.toolStatus=C||U.toolStatus),E!==void 0&&(U.response=E);let ee=[...w.messages];ee[O]=U,n.byId[o]={...w,messages:ee,lastUpdated:f()},k(o,true),g();}}}function B(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let a=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?a:a&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let r=Math.random()*16|0;return (t==="x"?r:r&3|8).toString(16)})}function ke(e){let t=/^www\.([\da-z-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(e);if(t?.[1])return t[1];let r=/^([\da-z-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(e);return r?.[1]?r[1]:null}function $e(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-z-]+)(?:\/|$)/.exec(e);return t?.[1]?t[1]:ke(window.location.hostname)}catch{return null}}var Se=null,Ne=null;function Ie(e){let t=e?ke(e):$e();return t||(Se||(Se=B()),Se)}function Te(e,t){return (r="conversation")=>{let a=ae(),i=Ie();if(a){let n=e?e.replace(/^https?:\/\//,"").split("/")[0]:"";i=Ie(n);}let c=t?.()??Ne??(Ne=`anonymous-${B()}`),d=`${i}:${c}`;return r==="single-turn"?`${d}:${B()}`:d}}function we(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function Ae(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
2
|
+
`)}function Ee(e){return {createContextId(t){return e.createContextId(t)},createScopedRuntime(t){return e.createRuntime(t)}}}function Pe({createContextId:e,postRpc:t,sendMessageStream:r}){return Ee({createContextId:e,createRuntime(a){return {async sendMessage(i,c){let{taskId:d,signal:n,onOpen:m,onMessage:y,onClose:x,preferMiniProgramRequest:S}=c,b=i.find(h=>h.role==="system"),M=i.filter(h=>h.role!=="system"),P=M[M.length-1],R=P?we(P.content):[{kind:"text",text:""}],D=b?Ae(b.content):void 0,q={jsonrpc:"2.0",id:B(),method:"message/stream",params:{message:{contextId:a,kind:"message",messageId:B(),role:"user",parts:R,...d?{taskId:d}:{},...D?{metadata:{systemPrompt:D}}:{}}}};await r(q,{onOpen:m,onMessage:y,onClose:x},n,S);},cancelChat(i){let c={jsonrpc:"2.0",id:B(),method:"tasks/cancel",params:{id:i}};return t(c)},async getHistory(i=50,c){try{let n=(await t({jsonrpc:"2.0",method:"messages/list",id:B(),params:{filter:{contextId:a},limit:i,...c?{next:c}:{}}}))?.data?.result||{},m=n?.messages||[],y=n?.next||"";return {messages:m,next:y,hasMore:!!y}}catch{return}},async newConversation(){try{await t({jsonrpc:"2.0",method:"messages/clear",id:B(),params:{contextId:a}});}catch{}},async getChatStatus(i){try{let c={jsonrpc:"2.0",id:B(),method:"tasks/get",params:i?{id:i}:{contextId:a}},n=(await t(c))?.data?.result;return {working:n?.status?.state==="working",taskId:n?.id,error:n?.error?.message||""}}catch(c){return {working:false,error:c?.message||""}}}}}})}function Ve(e){if(e instanceof Error)return e;if(e&&typeof e=="object"){let t=e,r=typeof t.errMsg=="string"&&t.errMsg||typeof t.message=="string"&&t.message||JSON.stringify(t),a=new Error(r);return (typeof t.errorCode=="number"||typeof t.errorCode=="string")&&(a.errorCode=t.errorCode),(typeof t.errNo=="number"||typeof t.errNo=="string")&&(a.errNo=t.errNo),a.raw=e,a}return new Error(String(e))}function ie(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let e=new Error("Aborted");return e.name="AbortError",e}function le(e){return createParser({onEvent:t=>{try{e.onMessage(JSON.parse(t.data));}catch(r){console.error("[copilot stream] failed to parse SSE event:",r,t.data);}}})}function Ue(e,t){if(e){if(e.aborted){t();return}e.addEventListener("abort",t);}}async function Le(e,t,r,a,i){let c={"Content-Type":"application/json",...r},d=await fetch(e,{method:"POST",headers:c,credentials:"include",body:JSON.stringify(t),signal:i});if(!d.ok)throw new Error(`Stream request failed: ${d.statusText||d.status}`);if(a.onOpen?.(),!d.body){a.onClose?.();return}let n=d.body.getReader(),m=new TextDecoder,y=le(a);try{for(;;){if(i?.aborted)throw ie();let{done:x,value:S}=await n.read();if(x)break;y.feed(m.decode(S,{stream:!0}));}}finally{a.onClose?.();}}function Be(e,t){if(!e)return "";let r=e instanceof Uint8Array?e:new Uint8Array(e);return r.length===0?"":t.decode(r,{stream:false})}async function he(e,t,r={},a,i){return new Promise((c,d)=>{let n=new Uint8Array(0),m=new je("utf-8",{fatal:false}),y=false,x=false,S=false,b=le(a),M=g=>{if(!x){if(x=true,g){d(Ve(g));return}a.onClose?.(),c();}},P=()=>{S||(S=true,a.onOpen?.());},R=g=>{g&&(P(),b.feed(g));},D=g=>{if(!(x||!g.data))try{y=!0;let H=new Uint8Array(g.data),k=new Uint8Array(n.length+H.length);k.set(n),k.set(H,n.length),n=k;let I=0;for(;I<n.length;){let z=n.subarray(I),_=m.decode(z,{stream:!1});if(_.length===0)break;if(_.includes("\uFFFD")){let L=_.lastIndexOf("\uFFFD")===0?0:_.indexOf("\uFFFD");if(L<=0)break;let j=_.slice(0,L);j&&R(j);let X=new TextEncoder().encode(j);I+=X.length;break}R(_),I+=z.length;}n=n.subarray(I);}catch(H){console.error("[mini stream] chunk process error:",H);}},q=g=>{P(),g.header?.["content-type"]?.includes("text/event-stream")===false&&console.warn("Warning: server did not return event-stream");},h=getMiniProgramRequest();if(!h){d(new Error("Mini-program request API not found"));return}try{let g=h({url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream",...r},data:typeof t=="string"?t:JSON.stringify(t),responseType:"arraybuffer",...be()?{enableChunked:!0}:{},success:H=>{if(!y&&H?.data){let k=Be(H.data,m);R(k);}if(n.length>0){let k=m.decode(n,{stream:!0});R(k);}M();},fail:H=>{M(H);}});Ue(i,()=>{g.abort?.(),M(ie());}),g.onChunkReceived?.(D),g.onHeadersReceived?.(q);}catch(g){M(g);}})}async function He(e,t,r,a,i,c=false){let d=r?.(),n=d?{Authorization:`Bearer ${d}`}:{},m=getMiniProgramRequest(),y=ae()&&!!m;if(c&&y){await he(e,t,n,a,i);return}if(y){await he(e,t,n,a,i);return}await Le(e,t,n,a,i);}function ze(e,t,r,a){let i="";try{i=process.env.TARO_APP_API_BASE_URL||process.env.VITE_API_BASE_URL||process.env.API_BASE_URL||"";}catch{}i=String(i||"").trim();let c=`${t||i}/api/proxy/builtin/platform/copilot`,d=x=>e.request({url:c,method:"POST",data:x}),n=Te(c,a);async function m(x,S,b,M){try{await He(c,x,r,S,b,M);}catch(P){if(b?.aborted)return;throw P}}let y=Pe({createContextId:n,postRpc:d,sendMessageStream:m});return {createConversationController(x){return Re(y,x)}}}var Ke=/[\n。!?.!?;;]/,We=/[,、,::]\s*$/;var qe=e=>{if(!e)return null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r&&r.role==="assistant"&&(r.kind==="text-content"||r.kind==="message")&&r.content?.trim())return r}return null},Ge=e=>{if(!e)return null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r&&r.role==="user"&&r.messageId)return r.messageId}return null},Oe=(e,t)=>{if(!e)return null;if(!t)return qe(e);let r=e.messages.findIndex(a=>a.messageId===t);if(r<0)return qe(e);for(let a=e.messages.length-1;a>r;a-=1){let i=e.messages[a];if(i&&i.role==="assistant"&&(i.kind==="text-content"||i.kind==="message")&&i.content?.trim())return i}return null},Je=e=>{for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&(r.requestState==="submitting"||r.requestState==="streaming"||r.requestState==="recovering"||r.status==="submitted"||r.status==="working"))return r}return null},Ye=(e,t)=>t&&e.find(r=>r.taskId===t)||null,Qe=(e,t)=>{let r=e.trimStart();if(!r)return {segments:[],remainder:""};if(t)return {segments:[r].filter(Boolean),remainder:""};let a=[],i=0;for(let d=0;d<r.length;d+=1){let n=r[d];if(!n||!Ke.test(n))continue;let m=r.slice(i,d+1).trim();m&&a.push(m),i=d+1;}let c=r.slice(i).trimStart();return c.length>=24&&We.test(c)&&(a.push(c.trim()),c=""),{segments:a,remainder:c}};function Xe(e){let{source:t,speech:r,storage:a,enabledStorageKey:i,defaultVoice:c=null,id:d="auto-voice-reply",audioFormat:n="pcm",sampleRate:m=24e3,preprocessText:y}=e,x=false,S=i?a?.getItem(i)==="true":false,b=t.getSnapshot().isLoading,M=null,P=null,R=null,D=false,q=null,h="",g="",H=Promise.resolve(),k=r.getVoice?.()??c,I={enabled:S,status:r.getSnapshot().status,connecting:r.getSnapshot().status==="connecting",speaking:r.getSnapshot().status==="speaking",voice:k,activeTaskId:M,suppressedTaskId:R,error:r.getSnapshot().error||null},z=new Set,_=()=>{let l=r.getSnapshot(),v={enabled:S,status:l.status,connecting:l.status==="connecting",speaking:l.status==="speaking",voice:k,activeTaskId:M,suppressedTaskId:R,error:l.error||null},F=I.enabled!==v.enabled||I.status!==v.status||I.connecting!==v.connecting||I.speaking!==v.speaking||I.voice!==v.voice||I.activeTaskId!==v.activeTaskId||I.suppressedTaskId!==v.suppressedTaskId||I.error!==v.error;return F&&(I=v),F},L=()=>{x||(_(),z.forEach(l=>l()));},j=()=>{i&&a?.setItem(i,S?"true":"false");},X=(l=null)=>{q=l,h="",g="",D=false;},K=()=>{M=null,P=null;},G=l=>{let v=l?.preserveRoundContext??false;h="",g="",q=null,D=false,v||K(),r.stop();},Z=l=>(H=H.then(()=>l(),()=>l()),H),se=async l=>{if(!(!l.length||x)){D||(await r.startStream({id:d,voice:k,audioFormat:n,sampleRate:m}),D=true);for(let v of l){if(x)return;let F=y?y(v):v;F.trim()&&(await r.appendText({id:d,text:F}),r.commit());}}},J=async(l,v)=>{let F=l.messageId||null,V=l.content||"";if(!V.trim())return;q!==F&&X(F);let s=h;if(s&&!V.startsWith(s)){h=V;return}let o=V.slice(s.length);if(h=V,!o&&!v)return;g+=o;let{segments:u,remainder:p}=Qe(g,v);g=p,u.length&&await se(u),v&&r.finish();},re=()=>{if(x)return;let l=t.getSnapshot();if(!S){b=l.isLoading;return}let v=Je(l.conversations),F=b;if(l.isLoading&&v){if(v.taskId!==M&&(M=v.taskId,P=Ge(v),R=null),R===v.taskId){b=l.isLoading,L();return}let V=Oe(v,P);V&&Z(()=>J(V,false));}else if(F&&!l.isLoading){let V=Ye(l.conversations,M);if(V&&R!==V.taskId){let s=Oe(V,P);s&&Z(()=>J(s,true));}V?.taskId===R&&(R=null),K();}b=l.isLoading,L();},ue=t.subscribe(re),ne=r.subscribe(()=>{if(x)return;let l=r.getVoice?.()??k??c;l!==k&&(k=l),L();}),Y={subscribe(l){return z.add(l),()=>{z.delete(l);}},getSnapshot(){return _(),I},setEnabled(l){S!==l&&(S=l,j(),S?(b=t.getSnapshot().isLoading,re()):(G(),R=null),L());},toggleEnabled(){Y.setEnabled(!S);},toggleEnabledOrStop(){let l=r.getSnapshot().status;if(l==="connecting"||l==="speaking"){R=M,G({preserveRoundContext:true}),L();return}Y.toggleEnabled();},stop(){R=M,G({preserveRoundContext:true}),L();},setVoice(l){k=l,r.setVoice?.(l),L();},getVoice(){return k},destroy(){x||(x=true,G(),R=null,ue(),ne(),z.clear());}};return Y}export{Xe as createAutoVoiceReplyController,ze as createCopilotClient};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|