diff --git a/lib/index.js b/lib/index.js index 88dddcf..3082957 100644 --- a/lib/index.js +++ b/lib/index.js @@ -84,7 +84,7 @@ ${FP}`:["session-not-registered","session-not-found"].includes(n?.code)?"\u672A\ `).trim();c&&c!==this.#n&&(this.#n=c,o={type:"text",text:c});continue}if(e.type==="assistant/message"){let A=jAe(e);A&&A!==this.#n&&(this.#n=A,o={type:"text",text:A});continue}e.type==="tool/call"?o={type:"tool",name:e.data?.name??"\u5DE5\u5177"}:e.type==="tool/result"&&(o={type:"status",text:"\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"})}}}}return o}},zn=class extends Error{constructor(a,o){super(`${a}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=a,this.code=o?.code??"internal",this.details=o?.details??{}}},xc=class extends Error{constructor(a,o){super(o),this.name="HarnessInteractionError",this.code=a}},jt=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r;#i;#o=null;#c;#l;#p;constructor({baseUrl:a,workspace:o,agentPreset:i="standard",autostart:e=!1,dshBin:r="dsh",fetchImpl:A=fetch,createWebSocket:t=p=>new WebSocket(p),interactionReconnectDelayMs:s=500,rpcIdPrefix:g="im",logPrefix:c="dsh-im",commandExecutor:l}){if(typeof t!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(s)||s<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof g!="string"||!g.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof c!="string"||!c.trim())throw new TypeError("logPrefix must be a non-empty string");if(l!==void 0&&typeof l!="function")throw new TypeError("commandExecutor must be a function");this.#e=new URL(a),this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g.trim(),this.#r=c.trim(),this.#i=l,this.#c=LAe(this.#e.origin),this.#l=this.#c.ownerships,this.#p=this.#c.claims}async rpc(a,o={},i=3e4,e={}){let r=e.rpcId??`${this.#I}-${xP()}`,A=AbortSignal.timeout(i),t=e.signal?AbortSignal.any([e.signal,A]):A,s=await this.#n(new URL(`/api/${a}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:r,method:a,payload:o}),signal:t});if(!s.ok)throw new Error(`Harness transport ${a} failed: HTTP ${s.status}`);let g=await s.json();if(g?.type!=="server-response"||g?.rpcId!==r)throw new Error(`Harness returned an invalid response for ${a}`);if(!g.result?.ok)throw new zn(a,g.result?.error);return g.result.value}async health(a={}){return await this.rpc("host.describe",{},5e3,a),!0}async ensureRunning(a={}){try{return await this.health(a)}catch(e){if(!this.#a)throw e}if(!this.#o||this.#o.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#o=GAe(this.#g,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#A,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#o.on("error",r=>{console.error(`[${this.#r}] failed to start Harness:`,r.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return r?r.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(a={}){await this.ensureRunning(a);let o=await this.workspaceId(a);return(await this.rpc("session.create",{workspaceId:o,agentPreset:this.#t},3e4,a)).sessionId}async executeCommand(a,o,i={}){if(typeof a!="string"||!a)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#i){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#i(a,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new zn("commands.execute",e.failure):e}}async sessionExists(a,o={}){try{return await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof zn&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(a,o,i={}){if(typeof a!="string"||!a)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),r=i.signal?AbortSignal.any([i.signal,e]):e,A=await this.#n(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-response",rpcId:a,result:o}),signal:r});if(!A.ok)throw new Error(`Harness transport respond failed: HTTP ${A.status}`);let t=await A.json();if(t?.accepted===!0)return t;if(t?.accepted!==!1||t.reason!=="bad-response"&&t.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=t.reason;throw new xc(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A}={}){if(typeof a!="string"||!a)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(r!==void 0&&typeof r!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#B(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A})}catch(t){if(o.aborted)return;console.warn(`[${this.#r}] Harness interaction stream disconnected:`,t.message)}if(o.aborted)return;try{await ud(this.#s,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#h(a,o){let i=this.#l.get(a)??new Set;o.order=this.#c.nextOrder,this.#c.nextOrder+=1,i.add(o),this.#l.set(a,i)}#C(a,o){let i=this.#l.get(a);i?.delete(o),i?.size===0&&this.#l.delete(a);for(let[e,r]of this.#p)r.ownership===o&&this.#p.delete(e)}#d(a,o){for(let i of this.#l.get(a)??[])JAe(i,o)}async#Q(a,o){let i=await this.rpc("session.history",{sessionId:a,maxMessages:50},3e4,{signal:o});this.#d(a,i.events??[])}#u(a,o,i){let e=this.#p.get(o);if(e&&this.#l.get(a)?.has(e.ownership))return e;let r=[...this.#l.get(a)??[]],A=r.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let t=r.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return t?{ownership:t,recovered:!0}:null}async ask(a,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,r=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,t=typeof i.onInteraction=="function"?i.onInteraction:void 0,s=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0;await this.ensureRunning({signal:r});let g=await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,{signal:r}),c=Math.max(-1,...(g.events??[]).map(({event:m})=>m.seq??-1)),l=`${this.#I}-${xP()}`,p=new Yc({promptRpcId:l,afterSeq:c}),B=t||s?new AbortController:null,Q=B?r?AbortSignal.any([r,B.signal]):B.signal:null,f=B?{promptRpcId:l,active:!1,started:!1,completed:!1,turn:null,openTurn:null,lastSeq:c,reconnect:null,order:-1,toolCalls:new Map}:null,y=null;f&&this.#h(a,f);try{if(Q){let k,G=new Promise(K=>{k=K});y=this.watchInteractions(a,{signal:Q,onInteraction:t,onResolved:s,onOpen:k,ownership:f}),y.catch(()=>{}),await Promise.race([G,ud(3e4,Q).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let m=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(m)||m.length===0)throw new TypeError("Harness prompt content is required");await this.rpc("session.prompt",{sessionId:a,mode:"queue",content:m,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:l,signal:r});let R=Date.now()+e;for(;Date.now(){}),f&&this.#C(a,f)}}#B(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A}){let t=new URL("/api/events.mux",this.#e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",new Promise((s,g)=>{let c;try{c=this.#E(t.toString())}catch(F){g(F);return}let l=!1,p=!1,B=null,Q=Promise.resolve(),f=A==null,y=[],m=F=>{p||(p=!0,c.removeEventListener("open",k),c.removeEventListener("message",x),c.removeEventListener("close",H),c.removeEventListener("error",q),o.removeEventListener("abort",j),A?.reconnect===R&&(A.reconnect=null),Q.then(()=>{let T=F??B;T?g(T):s()},g))},R=()=>{try{(c.readyState===0||c.readyState===1)&&c.close()}catch{}},k=()=>{l=!0,A&&(A.reconnect=R);try{r?.()}catch(F){console.warn(`[${this.#r}] ignored an interaction open callback failure:`,F.message)}A&&this.#Q(a,o).then(()=>{if(!p){f=!0;for(let F of y.splice(0))K(F)}}).catch(F=>{B??=F,R(),m(F)})},G=(F,T)=>{F&&(Q=Q.then(()=>F(T)).catch(V=>{B??=V,R(),m(B)}))},K=F=>{let T=F.payload;if(A&&T.type==="session/event"){this.#d(a,[T.event]);return}if(T.type==="question/requested"||T.type==="approval/requested"){let V=T.type==="question/requested"?"question":"approval",U=V==="question"?F.rpcId:T.approvalId,b=`${V}:${U}`;if(A){let X=this.#u(a,b,V);if(X?.ownership!==A)return;this.#p.set(b,X)}let L=V==="approval"&&A&&typeof T.callId=="string"?this.#p.get(b)?.ownership.toolCalls.get(T.callId):void 0;G(i,Object.freeze({kind:V,interactionId:U,rpcId:F.rpcId,sessionId:a,payload:T,recovered:A?this.#p.get(b)?.recovered===!0:!1,...L?{toolCall:L}:{},reconnect:R,respond:(X,pe={})=>this.respondInteraction(F.rpcId,X,{...pe,signal:pe.signal??o})}));return}if(T.type==="question/resolved"||T.type==="approval/resolved"){let V=T.type==="question/resolved"?"question":"approval",U=V==="question"?T.questionRpcId:T.approvalId,b=`${V}:${U}`;if(A){if(this.#p.get(b)?.ownership!==A)return;this.#p.delete(b)}G(e,Object.freeze({kind:V,interactionId:U,sessionId:a,outcome:T.outcome,payload:T}))}},x=F=>{try{if(typeof F.data!="string")throw new Error("binary WebSocket frame");let T=JSON.parse(F.data),V=T?.payload;if(T?.type!=="server-request"||typeof T.rpcId!="string"||!V||typeof V!="object"||T.method!==V.type)throw new Error("invalid server-request envelope");if(V.sessionId!==a)return;f?K(T):y.push(T)}catch(T){console.warn(`[${this.#r}] ignored a malformed Harness interaction frame:`,T.message)}},H=()=>m(l?null:new Error("Harness interaction WebSocket closed before opening")),q=()=>{m(new Error(l?"Harness interaction WebSocket failed":"Harness interaction WebSocket failed before opening")),R()},j=()=>{R(),m()};c.addEventListener("open",k),c.addEventListener("message",x),c.addEventListener("close",H,{once:!0}),c.addEventListener("error",q,{once:!0}),o.addEventListener("abort",j,{once:!0}),o.aborted&&j()})}stopManagedProcess(){this.#o?.exitCode===null&&this.#o.kill("SIGTERM")}};var Bd=class extends jt{constructor(a){super({...a,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as qAe}from"node:crypto";import{mkdir as VAe,readFile as zAe,rename as WAe,unlink as ZAe,writeFile as XAe}from"node:fs/promises";import{dirname as $Ae}from"node:path";var Qd=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function kt(n){return typeof n=="string"&&n.trim()?n.trim():null}function JP(n){return(kt(n)??"\u9489\u9489\u7528\u6237").slice(0,100)}function ete(n,a){if(!n||typeof n!="object")return null;let o=kt(n.requestId)??kt(a),i=kt(n.staffId),e=kt(n.requestedAt)??kt(n.lastSeenAt),r=kt(n.lastSeenAt)??e;return!o||!i||!e||!r?null:{requestId:o,staffId:i,displayName:JP(n.displayName??n.nick),requestedAt:e,lastSeenAt:r}}function Ate(n){if(!n||typeof n!="object")return structuredClone(Qd);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,r]of Object.entries(n.sessions)){let A=kt(e),t=kt(r);A&&t&&(a[A]=t)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,r]of i){let A=ete(r,e);if(!A)continue;let t=Object.values(o).find(s=>s.staffId===A.staffId);(!t||t.lastSeenAtnew Date().toISOString()}={}){if(!kt(a))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=a,this.#a=o,this.#g=i}async load(){try{this.#A=Ate(JSON.parse(await zAe(this.#e,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#A=structuredClone(Qd),await this.#n()}return this}sessionFor(a){return this.#A.sessions[a]??null}async setSession(a,o){let i=kt(a),e=kt(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#n()}async clearSession(a){let o=kt(a);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#n())}async clearSessions(){this.#A.sessions={},await this.#n()}hasSeen(a){let o=kt(a);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(a){let o=kt(a);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#n())}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((a,o)=>a.requestedAt.localeCompare(o.requestedAt)).map(a=>structuredClone(a))}pendingSender(a){let o=kt(a),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(a,o,i){let e=a&&typeof a=="object"?a:{staffId:a,displayName:o,lastSeenAt:i},r=kt(e.staffId);if(!r)throw new TypeError("staffId is required");let A=kt(e.lastSeenAt)??kt(e.requestedAt)??this.#g(),t=Object.values(this.#A.pendingSenders).find(g=>g.staffId===r),s={requestId:t?.requestId??`ding_sender_${this.#a()}`,staffId:r,displayName:JP(e.displayName??e.nick??o),requestedAt:t?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#n(),structuredClone(s)}async removePendingSender(a){let o=kt(a);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#n(),!0)}async removePendingSenderByStaffId(a){let o=kt(a),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await ZAe(this.#e)}catch(a){if(a?.code!=="ENOENT")throw a}this.#A=structuredClone(Qd)}async#n(){let a=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await VAe($Ae(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await XAe(i,a,{encoding:"utf8",mode:384}),await WAe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{mkdir as tte,readFile as ate,realpath as rte,rename as ite,stat as ote,unlink as nte,writeFile as ste}from"node:fs/promises";import{dirname as gte,isAbsolute as zP,resolve as wE}from"node:path";var N2e=Object.freeze({version:1,workspaces:Object.freeze({})});function yd(n){let a=new Error(n);return a.code=An,a}async function $S(n){return wE(await rte(n))}async function cte(n,a){if(n===a)return!0;try{return await $S(n)===await $S(a)}catch{return!1}}function ei(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function Ite(n){if(!n||n.version!==1||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let a={};for(let[o,i]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(o)||typeof i!="string"||!zP(i))return null;a[o]=wE(i)}return{version:1,workspaces:a}}async function qP(n){if(typeof n!="string"||!n.trim()||!zP(n.trim())){let i=new Error("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");throw i.code="workspace-not-absolute",i}let a=wE(n.trim()),o;try{o=await ote(a)}catch(i){let e=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002",{cause:i});throw e.code="workspace-not-found",e}if(!o.isDirectory()){let i=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");throw i.code="workspace-not-directory",i}return a}var Ea=class{#e;#A;#t={};#a=new Map;#g=1;#n=new Map;#E=1;#s=new Map;#I=new WeakMap;#r=new Set;#i=Promise.resolve();#o=new Map;constructor(a,{defaultWorkspace:o=process.cwd()}={}){if(typeof a!="string"||!a)throw new TypeError("workspace store path is required");this.#e=a,this.#A=wE(o)}async load(){try{let a=Ite(JSON.parse(await ate(this.#e,"utf8")));if(!a)throw new Error("dsh-im workspace config is invalid");this.#t=a.workspaces}catch(a){if(a?.code!=="ENOENT")throw a;this.#t={}}this.#a.clear(),this.#g=1,this.#n.clear(),this.#E=1,this.#s.clear(),this.#r.clear();for(let a of Object.keys(this.#t))this.#a.set(a,this.#c()),this.#n.set(a,this.#l());return this}has(a){let o=ei(a);return Object.hasOwn(this.#t,o)&&!this.#s.has(o)}incarnationFor(a){return this.#n.get(ei(a))??null}workspaceFor(a){return this.#t[ei(a)]??this.#A}generationFor(a){return this.#a.get(ei(a))??null}async whenIdle(){await this.#i}async whenBotIdle(a){let o=ei(a);for(;;){let i=this.#o.get(o);if(!i||(await i,this.#o.get(o)===i))return}}async ensure(a,{workspace:o=this.#A}={}){let i=ei(a),e=wE(o);return this.#C(i,async()=>{if(this.#t[i])this.#a.has(i)||this.#a.set(i,this.#c());else{this.#t[i]=e,this.#a.set(i,this.#c()),this.#n.set(i,this.#l());try{await this.#d()}catch(r){throw delete this.#t[i],this.#a.delete(i),this.#n.delete(i),r}}return this.#t[i]})}async setWorkspace(a,o,{clearSessions:i,incarnation:e}={}){let r=ei(a);if(!this.has(r)||e!==void 0&&e!==this.incarnationFor(r)){let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}let A=await qP(o);return this.#C(r,async()=>{if(!this.has(r)||e!==void 0&&e!==this.incarnationFor(r)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}if(A===this.workspaceFor(r))return A;let t=this.#t[r];this.#a.set(r,this.#c()),await i?.(),this.#t[r]=A;try{await this.#d()}catch(s){throw this.#t[r]=t,s}return A})}async bindWorkspaceSession(a,o,{conversationKey:i,sessionId:e,clearSessions:r,setSession:A,incarnation:t,expectedGeneration:s}={}){let g=ei(a);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof r!="function"||typeof A!="function")throw new TypeError("session state callbacks are required");if(!this.has(g)||t!==void 0&&t!==this.incarnationFor(g)){let l=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw l.code="workspace-bot-not-found",l}let c=await $S(await qP(o));return this.#C(g,async()=>{if(!this.has(g)||t!==void 0&&t!==this.incarnationFor(g)){let l=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw l.code="workspace-bot-not-found",l}if(s!==void 0&&s!==this.generationFor(g))throw yd("The bot workspace changed before the session binding could be committed.");if(!await cte(c,this.workspaceFor(g))){let l=this.#t[g];this.#a.set(g,this.#c()),await r(),this.#t[g]=c;try{await this.#d()}catch(p){throw this.#t[g]=l,p}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#a.get(g)}})}async invalidateSessions(a,{clearSessions:o}={}){let i=ei(a);return this.#C(i,async()=>{this.#a.set(i,this.#c()),await o?.()})}async beginRemoval(a,{clearSessions:o}={}){let i=ei(a);return this.#C(i,async()=>{let e=this.#s.get(i);if(e)return e;let r=Object.freeze({});this.#s.set(i,r),this.#I.set(r,{botId:i,incarnation:this.incarnationFor(i)}),this.#a.set(i,this.#c());try{await o?.()}catch(A){throw this.#s.get(i)===r&&this.#s.delete(i),A}return r})}async abortRemoval(a){let{botId:o}=this.#p(a);return this.#C(o,async()=>this.#s.get(o)!==a?!1:(this.#s.delete(o),Object.hasOwn(this.#t,o)&&(this.#a.set(o,this.#c()),this.#n.has(o)||this.#n.set(o,this.#l())),!0))}async finishRemoval(a){let{botId:o,incarnation:i}=this.#p(a);return this.#C(o,async()=>this.#s.get(o)!==a?{removed:!1,persisted:!0,error:null,stale:!0}:this.incarnationFor(o)!==i?(this.#s.delete(o),{removed:!1,persisted:!0,error:null,stale:!0}):(this.#s.delete(o),this.#h(o)))}async retireAfterConfigCommit(a){let o=ei(a);return this.#C(o,async()=>(this.#s.delete(o),this.#h(o)))}async remove(a){let o=await this.retireAfterConfigCommit(a);if(o.error)throw o.error;return o.removed}async reconcile(a){let o=new Set([...a].map(ei)),i=new Set([...Object.keys(this.#t),...this.#r]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(a){return!a||typeof a!="object"||!Array.isArray(a.bots)?a:{...a,bots:a.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId)}:o)}}#c(){let a=this.#g;return this.#g+=1,a}#l(){let a=this.#E;return this.#E+=1,a}#p(a){if(!a||typeof a!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#I.get(a);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#h(a){let o=Object.hasOwn(this.#t,a),i=o||this.#r.has(a);if(delete this.#t[a],this.#a.delete(a),this.#n.delete(a),!i)return{removed:!1,persisted:!0,error:null,stale:!1};try{return await this.#Q(),{removed:o,persisted:!0,error:null,stale:!1}}catch(e){return this.#r.add(a),{removed:o,persisted:!1,error:e,stale:!1}}}async#C(a,o){let i=this.#i.then(o,o),e=i.then(()=>{},()=>{});return this.#i=e,this.#o.set(a,e),e.finally(()=>{this.#o.get(a)===e&&this.#o.delete(a)}),i}async#d(){let a={version:1,workspaces:this.#t};await tte(gte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await ste(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await ite(o,this.#e),this.#r.clear()}async#Q(){if(Object.keys(this.#t).length>0){await this.#d();return}try{await nte(this.#e),this.#r.clear()}catch(a){if(a?.code!=="ENOENT")throw a;this.#r.clear()}}};function VP(n,a){return a&&typeof a.then=="function"?a.then(o=>n.decorateStatus(o)):n.decorateStatus(a)}function lte(n){return Promise.resolve(n.status())}function Ya(n,{workspaces:a,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!a||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,r){let A=Reflect.get(e,r,e);return r===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await a.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function xa(n,{botId:a,workspaces:o,state:i}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let e=o.incarnationFor(a),r=()=>o.has(a)&&o.incarnationFor(a)===e,A=new Map,t=new Proxy(n,{get(g,c){if(c==="currentWorkspace")return()=>{if(!r()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}return o.workspaceFor(a)};if(c==="assertWorkspaceScope")return()=>{if(!r()){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}};if((c==="listWorkspaces"||c==="listWorkspaceSessions")&&typeof g[c]=="function")return async(...p)=>{if(!r()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}let B=await g[c](...p);if(!r()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}return B};if(c==="switchWorkspace")return p=>{if(!r()){let B=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return B.code="workspace-bot-not-found",Promise.reject(B)}return o.setWorkspace(a,p,{clearSessions:()=>i.clearSessions(),incarnation:e})};if(c==="bindWorkspaceSession")return async(p,B)=>{if(typeof p!="string"||!p||typeof B!="string"||!B)throw new TypeError("conversationKey and sessionId are required");if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(typeof g.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let Q=o.generationFor(a),f=await g.adoptWorkspaceSession(B);if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(Q!==o.generationFor(a))throw yd("The bot workspace changed while the session was being adopted.");if(!f||typeof f!="object"||f.sessionId!==B||typeof f.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let y=await o.bindWorkspaceSession(a,f.workspace,{conversationKey:p,sessionId:B,clearSessions:()=>i.clearSessions(),setSession:(m,R)=>i.setSession(m,R),incarnation:e,expectedGeneration:Q});if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(y.generation!==o.generationFor(a))throw yd("The bot workspace changed before the session binding completed.");return A.set(B,y.generation),{...f,workspace:y.workspace,sessionId:y.sessionId}};if(c==="createSession")return async(p={})=>{if(await o.whenBotIdle(a),!r()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}let B=o.generationFor(a),Q=await g.createSession({...p,workspace:o.workspaceFor(a)});return A.set(Q,B),Q};if(c==="workspaceSession")return p=>{if(typeof p!="string"||!p)throw new TypeError("sessionId is required");let B=A.get(p)??o.generationFor(a);A.delete(p);let Q=()=>r()&&B===o.generationFor(a);return Object.freeze({sessionId:p,async sessionExists(...f){if(!Q())return!1;let y=await g.sessionExists(p,...f);return Q()&&y},ask(...f){if(!Q())throw yd("The bot workspace changed before this prompt started.");return g.ask(p,...f)}})};if(c==="sessionExists")return(p,...B)=>{if(!r())return!1;let Q=A.get(p);return Q!==void 0&&Q!==o.generationFor(a)?(A.delete(p),!1):g.sessionExists(p,...B)};if(c==="ask")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!r()||Q!==void 0&&Q!==o.generationFor(a)){let f=new Error("The bot workspace changed before this prompt started.");throw f.code=An,f}return g.ask(p,...B)};if(c==="executeCommand"&&typeof g.executeCommand=="function")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!r()||Q!==void 0&&Q!==o.generationFor(a)){let f=new Error("The bot workspace changed before this command started.");throw f.code=An,f}return g.executeCommand(p,...B)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}}),s=new Proxy(i,{get(g,c){if(c==="sessionFor")return(p,...B)=>{if(!r())return null;let Q=g.sessionFor(p,...B);return Q&&!A.has(Q)&&A.set(Q,o.generationFor(a)),Q};if(c==="setSession")return(p,B,...Q)=>{let f=A.get(B);return!r()||f!==void 0&&f!==o.generationFor(a)?(A.delete(B),!1):g.setSession(p,B,...Q)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}});return Object.freeze({harness:t,state:s})}function ja(n,{workspaces:a,stateFor:o}){if(!n||!a||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let i=new Map,e=(t,s)=>{let c=(i.get(t)??Promise.resolve()).catch(()=>{}).then(s);return i.set(t,c),c.finally(()=>{i.get(t)===c&&i.delete(t)})},r=(t,s)=>{let g=a.incarnationFor(t);return e(t,async()=>{if(!(await n.status())?.bots?.some(p=>p?.botId===t)){let p=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw p.code="workspace-bot-not-found",p}let l=await o(t);return await a.setWorkspace(t,s,{clearSessions:()=>l.clearSessions(),incarnation:g}),a.decorateStatus(await n.status())})},A=(t,s)=>e(t,async()=>{let g=await a.beginRemoval(t,{clearSessions:async()=>{try{let c=await o(t);if(!c||typeof c.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await c.clearSessions()}catch(c){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${t}:`,c?.message??c)}}});try{let c=await s();return await a.finishRemoval(g),a.decorateStatus(c)}catch(c){let l=await lte(n).catch(()=>null);throw Array.isArray(l?.bots)&&!l.bots.some(B=>B?.botId===t)?await a.finishRemoval(g):await a.abortRemoval(g),c}});return new Proxy(n,{get(t,s){if(s==="updateWorkspace")return r;let g=Reflect.get(t,s,t);return typeof g!="function"?g:s==="deleteBot"?(c,...l)=>A(c,()=>g.call(t,c,...l)):s==="disconnect"?async(...c)=>{let p=(await t.status())?.bots?.[0]?.botId;return p?A(p,()=>g.apply(t,c)):VP(a,g.apply(t,c))}:(...c)=>VP(a,g.apply(t,c))}})}var WP=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function Ete(n){if(!Array.isArray(n)||n.length===0)return[...WP];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...WP]}var md=class{#e;#A;#t;#a;#g;#n;#E;#s=null;#I=null;#r=0;#i=!1;#o=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=a,this.#A=o,this.#t=i,this.#a=Ete(e),this.#g=Number.isFinite(r)&&r>=0?r:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(a){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},a),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let a=this.#C();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let a=await this.#e.initialize();if(this.#i)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(io.invoke({namespace:"commands",method:"execute",args:{agentId:i,line:e},signal:r.signal})}}function hte(n,a){if(a!==void 0)return new URL(a);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-dingtalk requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function dte(n){let a=sg(n.dshHome??process.env.DSH_HOME??OE(Cte(),".dsh")),o=sg(n.dataDir??OE(a,"integrations","dsh-dingtalk"));return{root:o,config:sg(n.configPath??OE(o,"config.json")),bots:sg(n.botsDir??OE(o,"bots")),workspaces:sg(n.workspacesPath??OE(o,"workspaces.json"))}}async function AD(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-dingtalk requires ctx.webServer");let i=o.ConfigStore??sd,e=o.DeviceAuth??cd,r=o.StateStore??fd,A=o.HarnessClient??Bd,t=o.Controller??fE,s=o.Runtime??SE,g=o.createConnectionSupervisor??eD,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=dte(a),p=await new i(l.config).load(),B=sg(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ea,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=typeof p.list=="function",m=y?p.list():[];y&&await f.reconcile(m.map(V=>V.botId)),await Promise.all(m.map(V=>f.ensure(V.botId)));let R=typeof p.remove=="function"?Ya(p,{workspaces:f}):p,k=o.deviceAuth??new e({baseUrl:a.registrationBaseUrl}),G=new Map,K=V=>sg(l.bots,V,"state.json"),x=async V=>{let U=G.get(V);return U||(U=await new r(K(V)).load(),G.set(V,U)),U},H=Ja(n,o.commandExecutor),q=new A({baseUrl:hte(n.webServer,a.harnessBaseUrl),workspace:B,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh",...H?{commandExecutor:H}:{}}),j=new t({deviceAuth:k,credentials:n.credentials,configStore:R,logger:c,createRuntime:async({botId:V,config:U,clientSecret:b})=>{let L=await x(V);await f.ensure(V);let X=xa(q,{botId:V,workspaces:f,state:L});return new s({config:U,clientSecret:b,harness:X.harness,state:X.state,replyTimeoutMs:a.replyTimeoutMs??6e5,maxMessageChars:a.maxMessageChars??4e3,connectTimeoutMs:a.connectTimeoutMs??15e3,logger:{error:(...pe)=>c.error?.(`[${V}]`,...pe),warn:(...pe)=>c.warn?.(`[${V}]`,...pe),info:(...pe)=>c.info?.(`[${V}]`,...pe),debug:(...pe)=>c.debug?.(`[${V}]`,...pe)}})},deleteState:async({botId:V})=>{let U=G.get(V);if(G.delete(V),U&&typeof U.remove=="function")await U.remove();else try{await pte(K(V))}catch(b){if(b?.code!=="ENOENT")throw b}}}),F=ja(j,{workspaces:f,stateFor:x}),T=g({controller:F,harness:q,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:F,ready:T.ready,async close(){await T.close(),await F.close(),q.stopManagedProcess()}}}import Qte from"qrcode";var ute=new Set(["loopback","trusted-host"]);function qa(n){if(n===void 0)return"loopback";if(ute.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as Bte}from"node:path";var pr="bot.workspace.set";function Va(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(a=>["botId","workspace"].includes(a))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&Bte(n.workspace.trim())}function za(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found"].includes(n?.code)?{code:n.code,message:n.message}:null}var XP="/dingtalk",Kt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:pr,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),$P=Object.freeze(Object.values(Kt)),fte=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function aD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Wn(n,a){return aD(n)&&Object.keys(n).every(o=>a.includes(o))}function gg(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function ZP(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function yte(n,a){return aD(a)?n===Kt.status?Wn(a,[])?null:"connection.status does not accept fields.":n===Kt.beginProvisioning?Wn(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Kt.pollProvisioning,Kt.cancelProvisioning].includes(n)?Wn(a,["attemptId"])&&gg(a.attemptId)?null:`${n} requires an attemptId.`:n===Kt.bindCredentials?Wn(a,["clientId","clientSecret"])&&ZP(a.clientId,256)&&ZP(a.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Kt.reconnectBot?Wn(a,["botId"])&&gg(a.botId)?null:"bot.reconnect requires a botId.":n===Kt.deleteBot?Wn(a,["botId","confirm"])&&gg(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Kt.setWorkspace?Va(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Kt.approveSender?Wn(a,["botId","requestId","confirm"])&&gg(a.botId)&&gg(a.requestId)&&a.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Kt.revokeSender?Wn(a,["botId","senderKey","confirm"])&&gg(a.botId)&&gg(a.senderKey)&&a.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function Sd(n){return{ok:!1,error:{code:"bad-request",message:n}}}function Dd(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function mte(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function jc(n){if(Array.isArray(n))return n.map(jc);if(!aD(n))return n;let a={};for(let[o,i]of Object.entries(n))fte.has(o)||(a[o]=jc(i));return a}async function Ste(n){return Qte.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function tD(n,a){return!n||typeof n.verificationUrl!="string"?jc(n):jc({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function cg(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await tD(o.provisioning,a)),jc(o)}function Dte(n){for(let a of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[a]!="function")throw new TypeError(`A complete DingTalk controller is required (${a})`)}function eG(n,{encodeQr:a=Ste}={}){Dte(n);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return Dd();if(!$P.includes(e))return Sd("Unknown DingTalk endpoint.");let t=yte(e,r);if(t)return Sd(t);try{let s;if(e===Kt.status)s=await cg(await n.status(),i);else if(e===Kt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),Dd();s=await tD(g,i)}else if(e===Kt.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return Sd("The provisioning attempt no longer exists.");s=await tD(g,i)}else if(e===Kt.cancelProvisioning){if(s=await n.cancelProvisioning(r.attemptId),!s)return Sd("The provisioning attempt no longer exists.");s=jc(s)}else if(e===Kt.bindCredentials)s=await cg(await n.bindCredentials(r),i);else if(e===Kt.reconnectBot)s=await cg(await n.reconnectBot(r.botId),i);else if(e===Kt.deleteBot)s=await cg(await n.deleteBot(r.botId),i);else if(e===Kt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await cg(await n.updateWorkspace(r.botId,r.workspace),i)}else e===Kt.approveSender?s=await cg(await n.approveSender(r.botId,r.requestId),i):s=await cg(await n.revokeSender(r.botId,r.senderKey),i);return A?.aborted?Dd():{ok:!0,value:s}}catch(s){let g=za(s);return A?.aborted?Dd():g?{ok:!1,error:g}:mte()}}}function wd(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(XP,eG(a,o),{authority:qa(i)})}async function AG(n,a={}){if(a?.controller)return wd(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await AD(n,a,a.internals),i=wd(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as wte}from"node:crypto";import{mkdir as Ote,readFile as Mte,rename as bte,unlink as _te,writeFile as Nte}from"node:fs/promises";import{dirname as Tte}from"node:path";var rD=Object.freeze({version:1,bots:Object.freeze([])});function tn(n){return typeof n=="string"&&n.trim()?n.trim():null}function tG(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ME(n,{botPrefix:a,tokenRefPrefix:o}){let i=tn(n);if(!i)throw new TypeError("platformId is required");let e=wte("sha256").update(i).digest("hex").slice(0,24);return{botId:`${a}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function Od(n,a){let o=tn(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:a:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Jc=class{#e;#A;#t;#a;#g;#n;#E=rD;#s=Promise.resolve();constructor(a,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=new RegExp(`^${tG(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${tG(e)}_[A-F0-9]{24}$`)}async load(){try{let a=this.#r(JSON.parse(await Mte(this.#e,"utf8")));if(!a)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#E=a}catch(a){if(a?.code!=="ENOENT")throw a;this.#E=rD}return this}list(){return structuredClone(this.#E.bots)}get(a){let o=this.#E.bots.find(i=>i.botId===a);return o?structuredClone(o):null}getByPlatformId(a){let o=this.#E.bots.find(i=>i.platformId===a);return o?structuredClone(o):null}async save(a){let o=this.#I(a);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#i(i=>{let e=i.find(t=>t.platformId===o.platformId&&t.botId!==o.botId),r=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||r)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(a){if(!this.#g.test(a))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#i(o=>{let i=o.findIndex(r=>r.botId===a);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let a=this.#s.then(async()=>{try{await _te(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#E=rD});this.#s=a.then(()=>{},()=>{}),await a}#I(a){if(!a||typeof a!="object")return null;let o=tn(a.platformId),i=tn(a.botId),e=tn(a.tokenRef),r=tn(a.name);if(!o||!i||!e||!r||!this.#g.test(i)||!this.#n.test(e))return null;let A=ME(o,{botPrefix:this.#t,tokenRefPrefix:this.#a});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:r,username:tn(a.username),createdAt:tn(a.createdAt)??new Date().toISOString(),connectedAt:tn(a.connectedAt)})}#r(a){if(!a||a.version!==1||!Array.isArray(a.bots))return null;let o=a.bots.map(A=>this.#I(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,r=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||r.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),r.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#i(a){let o,i=this.#s.then(async()=>{let e=[...this.#E.bots];o=a(e);let r=Object.freeze({version:1,bots:Object.freeze(e)});await this.#o(r),this.#E=r});return this.#s=i.then(()=>{},()=>{}),await i,o}async#o(a){await Ote(Tte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Nte(o,`${JSON.stringify(a,null,2)} -`,{encoding:"utf8",mode:384}),await bte(o,this.#e)}};var aG=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function rG(n){return ME(n,aG)}function iG(n){return Od(n,"Discord\u673A\u5668\u4EBA")}var Md=class extends Jc{constructor(a){super(a,{channel:"Discord",...aG})}};function bE(n){return typeof n=="string"&&n.trim()?n.trim():null}function bd(n,a){return Object.freeze({code:n,message:a})}var qc=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r=new Map;#i=new Map;#o=new Map;#c=0;#l=!1;constructor({descriptor:a,credentials:o,configStore:i,inspectToken:e,deriveIdentity:r,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!a?.key||!a?.label||!a?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${a.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${a.label} requires a config store`);if(typeof e!="function"||typeof r!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${a.label} controller dependencies are incomplete`);this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let a of this.#t.list())await this.#Q(a.botId,async()=>{if(this.#l||this.#r.get(a.botId)?.status?.ready)return;let o=await this.#C(a.tokenRef);if(!o){this.#i.set(a.botId,bd("missing-token",`${this.#e.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#p(a,o),this.#i.delete(a.botId)}catch(i){this.#i.set(a.botId,bd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({token:a}={}){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let o=bE(a);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#a(o),e=bE(i?.platformId),r=bE(i?.name);if(!e||!r)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#g(e);return await this.#Q(A.botId,async()=>{if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:bE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#p(g,o),this.#i.delete(A.botId)}catch(c){this.#i.set(A.botId,bd("connection-failed",`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#u()}),this.status()}async reconnectBot(a){let o=this.#t.get(a);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(a,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#p(o,i),this.#i.delete(a)}catch(e){throw this.#i.set(a,bd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#u()}}),this.status()}async deleteBot(a){let o=this.#t.get(a);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(a,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(a);try{await this.#A.unset(o.tokenRef),await this.#t.remove(a)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#s({botId:a,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a} state cleanup failed:`,e)}),this.#i.delete(a),this.#u()}),this.status()}status(){let a=this.#t.list().map(i=>{let e=this.#r.get(i.botId)?.status??null,r=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=r?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:r,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#n(i.platformId)},health:{status:r?"healthy":A==="error"?"error":"offline",summary:r?`${this.#e.label}${this.#e.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#e.label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF`,lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#i.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#r.keys()].map(a=>this.#h(a))))}async#p(a,o){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(a.botId),this.#l)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#E({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#r.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#r.delete(a.botId),e}}async#h(a){let o=this.#r.get(a);this.#r.delete(a),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a} failed to stop cleanly:`,i)})}async#C(a){let o=await this.#A.resolve(a).catch(()=>{});return bE(o?.value)}async#d(a,o){o?.value?await this.#A.set(a,o.value).catch(()=>{}):await this.#A.unset(a).catch(()=>{})}#Q(a,o){let r=(this.#o.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(a)===r&&this.#o.delete(a)});return this.#o.set(a,r),r}#u(){this.#c+=1}};var Rte="https://discord.com/api/v10/";function _E(n){return typeof n=="string"&&n.trim()?n.trim():null}function kte(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function vte(n,a){return new Promise((o,i)=>{if(a?.aborted){i(a.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),a?.addEventListener("abort",()=>{clearTimeout(e),i(a.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Vc(n,a){let o=_E(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function Pte(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var NE=class{#e;#A;#t;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=Rte}){if(!Pte(a))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=a.trim(),this.#A=o,this.#t=new URL(i)}getCurrentUser(a={}){return this.#a("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#a("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#a(`channels/${Vc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:Vc(i,"message id"),channel_id:Vc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#a(`channels/${Vc(a,"channel id")}/messages/${Vc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#a(`channels/${Vc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#a(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#A(new URL(a,this.#t),{method:o,headers:{authorization:`Bot ${this.#e}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.9.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:kte(e,r),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Discord ${o} transport failed`)}let g=null;if(A||s.status===429||!s.ok)try{g=await s.json()}catch{if(A)throw new Error(`Discord ${o} returned invalid JSON`)}if(s.status===429&&t){let c=Math.min(1e4,Math.max(50,Number(g?.retry_after)*1e3||1e3));return await vte(c,e),this.#a(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(_E(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function oG(n,a={}){let i=await new NE({token:n,...a}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:_E(i.global_name)??_E(i.username)??"Discord\u673A\u5668\u4EBA",username:_E(i.username)}}var nG="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Ni(n){return typeof n=="string"?n.trim():""}function Gte(n,a,o){return a.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!wa(n)&&!!Ni(n.content)}function Nr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var so=class{#e;#A;#t;#a;#g;#n;#E;#s;#I=new Map;#r=new Map;#i=new Map;#o=new Set;#c=new Set;#l;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=Nr(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!a?.key||!a?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#l=new lr({label:a.key,logger:A})}get status(){return structuredClone(this.#g)}accept(a){if(this.#s?.aborted)return Promise.resolve();let o=Ni(a?.conversationId),i=a?.kind==="group"?"group":"direct",e={...a,kind:i,conversationId:o},r=Ni(e.messageId),A=Ni(e.senderId);if(!r||!A||!o||e.senderIsBot===!0||this.#a.hasSeen(r)||this.#o.has(r))return Promise.resolve();this.#o.add(r);let t=`${i}:${o}`,s=this.#r.get(t),g=this.#l.claimReply({key:t,actor:A,messageId:r,text:wa(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#r.has(t),send:c=>this.#A.sendText(e.replyTarget,c)});if(g){let c;return c=g.process(async()=>this.#a.hasSeen(r)?!1:(await this.#a.markSeen(r),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(r),this.#c.delete(c)}),this.#c.add(c),c}if(s&&s.actor!==A)return this.#p(e,r,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#p(e,r,A,t);if(s){Gte(e,s,A)&&(s.claimedReplyMessageId=r);let l=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,r,A,t,s)).finally(()=>{this.#o.delete(r),s.claimedReplyMessageId===r&&(s.claimedReplyMessageId=null),s.queue===l&&(s.queue=null)});return s.queue=l,l}return this.#p(e,r,A,t)}#p(a,o,i,e,{releaseMessageId:r=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(a,o,i,e,{alreadyRecorded:A})).finally(()=>{r&&this.#o.delete(o),this.#I.get(e)===s&&this.#I.delete(e)});return this.#I.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#r.values()].flatMap(a=>a.queue?[a.queue]:[]),...this.#c])}async#h(a,o,i,e,{alreadyRecorded:r=!1}={}){if(!r){if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let A=a.replyTarget,t=Ni(a.content),s=null;try{if(this.#s?.throwIfAborted(),a.kind==="group"&&a.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let g=wa(a);if(!t&&!g){await this.#A.sendText(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002");return}let c=t.toLowerCase();if(!g&&c==="/help"){await this.#A.sendText(A,[`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` +`,{encoding:"utf8",mode:384}),await bte(o,this.#e)}};var aG=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function rG(n){return ME(n,aG)}function iG(n){return Od(n,"Discord\u673A\u5668\u4EBA")}var Md=class extends Jc{constructor(a){super(a,{channel:"Discord",...aG})}};function bE(n){return typeof n=="string"&&n.trim()?n.trim():null}function bd(n,a){return Object.freeze({code:n,message:a})}var qc=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r=new Map;#i=new Map;#o=new Map;#c=0;#l=!1;constructor({descriptor:a,credentials:o,configStore:i,inspectToken:e,deriveIdentity:r,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!a?.key||!a?.label||!a?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${a.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${a.label} requires a config store`);if(typeof e!="function"||typeof r!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${a.label} controller dependencies are incomplete`);this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let a of this.#t.list())await this.#Q(a.botId,async()=>{if(this.#l||this.#r.get(a.botId)?.status?.ready)return;let o=await this.#C(a.tokenRef);if(!o){this.#i.set(a.botId,bd("missing-token",`${this.#e.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#p(a,o),this.#i.delete(a.botId)}catch(i){this.#i.set(a.botId,bd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({token:a}={}){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let o=bE(a);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#a(o),e=bE(i?.platformId),r=bE(i?.name);if(!e||!r)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#g(e);return await this.#Q(A.botId,async()=>{if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:bE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#p(g,o),this.#i.delete(A.botId)}catch(c){this.#i.set(A.botId,bd("connection-failed",`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#u()}),this.status()}async reconnectBot(a){let o=this.#t.get(a);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(a,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#p(o,i),this.#i.delete(a)}catch(e){throw this.#i.set(a,bd("connection-failed",`${this.#e.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#u()}}),this.status()}async deleteBot(a){let o=this.#t.get(a);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(a,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(a);try{await this.#A.unset(o.tokenRef),await this.#t.remove(a)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#s({botId:a,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a} state cleanup failed:`,e)}),this.#i.delete(a),this.#u()}),this.status()}status(){let a=this.#t.list().map(i=>{let e=this.#r.get(i.botId)?.status??null,r=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=r?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:r,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#n(i.platformId)},health:{status:r?"healthy":A==="error"?"error":"offline",summary:r?`${this.#e.label}${this.#e.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#e.label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF`,lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#i.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#r.keys()].map(a=>this.#h(a))))}async#p(a,o){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(a.botId),this.#l)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#E({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#r.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#r.delete(a.botId),e}}async#h(a){let o=this.#r.get(a);this.#r.delete(a),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${a} failed to stop cleanly:`,i)})}async#C(a){let o=await this.#A.resolve(a).catch(()=>{});return bE(o?.value)}async#d(a,o){o?.value?await this.#A.set(a,o.value).catch(()=>{}):await this.#A.unset(a).catch(()=>{})}#Q(a,o){let r=(this.#o.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(a)===r&&this.#o.delete(a)});return this.#o.set(a,r),r}#u(){this.#c+=1}};var Rte="https://discord.com/api/v10/";function _E(n){return typeof n=="string"&&n.trim()?n.trim():null}function kte(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function vte(n,a){return new Promise((o,i)=>{if(a?.aborted){i(a.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),a?.addEventListener("abort",()=>{clearTimeout(e),i(a.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Vc(n,a){let o=_E(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function Pte(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var NE=class{#e;#A;#t;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=Rte}){if(!Pte(a))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=a.trim(),this.#A=o,this.#t=new URL(i)}getCurrentUser(a={}){return this.#a("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#a("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#a(`channels/${Vc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:Vc(i,"message id"),channel_id:Vc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#a(`channels/${Vc(a,"channel id")}/messages/${Vc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#a(`channels/${Vc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#a(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#A(new URL(a,this.#t),{method:o,headers:{authorization:`Bot ${this.#e}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.10.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:kte(e,r),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Discord ${o} transport failed`)}let g=null;if(A||s.status===429||!s.ok)try{g=await s.json()}catch{if(A)throw new Error(`Discord ${o} returned invalid JSON`)}if(s.status===429&&t){let c=Math.min(1e4,Math.max(50,Number(g?.retry_after)*1e3||1e3));return await vte(c,e),this.#a(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(_E(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function oG(n,a={}){let i=await new NE({token:n,...a}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:_E(i.global_name)??_E(i.username)??"Discord\u673A\u5668\u4EBA",username:_E(i.username)}}var nG="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Ni(n){return typeof n=="string"?n.trim():""}function Gte(n,a,o){return a.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!wa(n)&&!!Ni(n.content)}function Nr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var so=class{#e;#A;#t;#a;#g;#n;#E;#s;#I=new Map;#r=new Map;#i=new Map;#o=new Set;#c=new Set;#l;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=Nr(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!a?.key||!a?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#l=new lr({label:a.key,logger:A})}get status(){return structuredClone(this.#g)}accept(a){if(this.#s?.aborted)return Promise.resolve();let o=Ni(a?.conversationId),i=a?.kind==="group"?"group":"direct",e={...a,kind:i,conversationId:o},r=Ni(e.messageId),A=Ni(e.senderId);if(!r||!A||!o||e.senderIsBot===!0||this.#a.hasSeen(r)||this.#o.has(r))return Promise.resolve();this.#o.add(r);let t=`${i}:${o}`,s=this.#r.get(t),g=this.#l.claimReply({key:t,actor:A,messageId:r,text:wa(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#r.has(t),send:c=>this.#A.sendText(e.replyTarget,c)});if(g){let c;return c=g.process(async()=>this.#a.hasSeen(r)?!1:(await this.#a.markSeen(r),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(r),this.#c.delete(c)}),this.#c.add(c),c}if(s&&s.actor!==A)return this.#p(e,r,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#p(e,r,A,t);if(s){Gte(e,s,A)&&(s.claimedReplyMessageId=r);let l=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,r,A,t,s)).finally(()=>{this.#o.delete(r),s.claimedReplyMessageId===r&&(s.claimedReplyMessageId=null),s.queue===l&&(s.queue=null)});return s.queue=l,l}return this.#p(e,r,A,t)}#p(a,o,i,e,{releaseMessageId:r=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(a,o,i,e,{alreadyRecorded:A})).finally(()=>{r&&this.#o.delete(o),this.#I.get(e)===s&&this.#I.delete(e)});return this.#I.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#r.values()].flatMap(a=>a.queue?[a.queue]:[]),...this.#c])}async#h(a,o,i,e,{alreadyRecorded:r=!1}={}){if(!r){if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let A=a.replyTarget,t=Ni(a.content),s=null;try{if(this.#s?.throwIfAborted(),a.kind==="group"&&a.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let g=wa(a);if(!t&&!g){await this.#A.sendText(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002");return}let c=t.toLowerCase();if(!g&&c==="/help"){await this.#A.sendText(A,[`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `));return}if(!g&&c==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#A.sendText(A,`${this.#e.label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002`);return}let l=g?null:await Xr(t,this.#t,e);if(l){for(let y of l.messages??[l.message])await this.#A.sendText(A,y);return}if(!g&&c==="/new"){await this.#a.clearSession(e),await this.#A.sendText(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002");return}let p=g?null:await Zr(t,this.#t,this.#a,e,{signal:this.#s});if(p){await this.#A.sendText(A,p.message);return}await this.#A.sendTyping?.(A).catch(y=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,y)});let B=!1;if(typeof this.#A.openStream=="function")try{s=await this.#A.openStream(A)}catch(y){this.#n.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,y)}let Q=g?await Jr(a,{signal:this.#s}):void 0,{answer:f}=await Er({harness:this.#t,state:this.#a,key:e,text:t,content:Q,createOptions:this.#s?{signal:this.#s}:void 0,existsOptions:this.#s?{signal:this.#s}:void 0,askOptions:{timeoutMs:this.#E,signal:this.#s,onUpdate:s?async y=>{let m=y.type==="text"?y.text:y.type==="tool"?`\u6B63\u5728\u4F7F\u7528${y.name}\u2026`:y.text;m&&await s.update(m)}:void 0,onInteraction:y=>this.#d(y,{key:e,actor:i,target:A,requiresMention:a.kind==="group"}),onInteractionResolved:y=>this.#Q(y)}});if(s)try{await s.finish(f),B=!0}catch(y){s.cancel?.(),this.#n.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,y)}B||await this.#A.sendText(A,f),this.#g.messagesReplied+=1,this.#g.lastReplyAt=new Date().toISOString(),this.#g.lastError=null}catch(g){if(s?.cancel?.(),this.#s?.aborted)return;this.#g.lastError=g?.message??String(g);let c=qr(g);if(c){try{await this.#A.sendText(A,c)}catch(l){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send the image error reply:`,l)}return}this.#n.error?.(`[dsh-im:${this.#e.key}] failed to process a message:`,g);try{await this.#A.sendText(A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}catch(l){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send the safe error reply:`,l)}}finally{await Promise.allSettled([this.#m(e),this.#l.closeRoute(e)])}}async#C(a,o,i,e,r){if(this.#s?.aborted)return;let A=this.#r.get(e),t=r.claimedReplyMessageId===o;if(!A||A!==r||A.submitting)return t&&(!A||A!==r)?this.#B(a,o):this.#p(a,o,i,e,{releaseMessageId:!1});if(this.#a.hasSeen(o))return;if(await this.#a.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),a.kind==="group"&&a.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let s=a.replyTarget,g=Ni(a.content);if(!g||wa(a)){try{await this.#A.sendText(s,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")}catch(p){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to reject a non-text interaction reply:`,p)}return}let c=this.#r.get(e);if(!c||c!==r||c.submitting)return t&&(!c||c!==r)?this.#B(a,o,{alreadyRecorded:!0}):this.#p(a,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let p=c.presentationTask!==null;try{await this.#u(c)}catch(Q){this.#g.lastError=`${this.#e.label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002`,this.#n.error?.(`[dsh-im:${this.#e.key}] failed to retry an interaction question:`,Q),c.interaction.reconnect?.();return}let B=this.#r.get(e);if(!B||B!==r||B.submitting)return t&&(!B||B!==r)?this.#B(a,o,{alreadyRecorded:!0}):this.#p(a,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!p)return}let l=c.questions[c.index];if(l){if(c.answers.push(Wr(l,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(a?.kind!=="question")return;let A=a?.payload?.questions,t=Ni(a?.interactionId)||Ni(a?.rpcId);if(!Ni(a?.rpcId)||!t||!Ni(a?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!Vr(c))){this.#n.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(a.recovered===!0){await this.#D(a,`${this.#e.label} safely cancelled an interaction left by an earlier client.`);try{await this.#A.sendText(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")}catch(c){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#r.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#u(s);return}if(this.#i.has(t))return;if(s){this.#n.warn?.(`[dsh-im:${this.#e.key}] cancelled a second pending Harness question`),await this.#D(a,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#r.set(o,g),this.#i.set(t,o),await this.#u(g)}async#Q(a){if(a?.kind==="approval"){await this.#l.handleResolved(a);return}let o=Ni(a?.interactionId);if(a?.kind!=="question"||!o)return;let i=this.#i.get(o);i&&this.#f(i,o)}#u(a){if(a.presentationTask)return a.presentationTask;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(a.target,zr(o,a.index,a.questions.length,{requiresMention:a.requiresMention})),a.needsPresentation=!1})();return a.presentationTask=i,i.then(()=>{a.presentationTask===i&&(a.presentationTask=null)},()=>{a.presentationTask===i&&(a.presentationTask=null)}),i}async#B(a,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(a.replyTarget,nG)}catch(e){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#y(a,o){let i=this.#r.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#r.delete(a),this.#i.delete(i.interactionId),i)}#f(a,o){return this.#y(a,o)!==null}async#D(a,o){try{await a.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#m(a){let o=this.#y(a);if(!(!o||o.kind!=="question"))try{await this.#D(o.interaction,`The ${this.#e.label} interaction ended before the user answered.`)}catch(i){this.#n.warn?.(`[dsh-im:${this.#e.key}] failed to cancel a pending Harness interaction:`,i)}}};var iD=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),_d=class extends so{constructor(a){super({descriptor:iD,...a})}};var TE=class extends qc{constructor(a){super({...a,descriptor:iD,inspectToken:a.inspectToken??oG,deriveIdentity:rG,maskPlatformId:iG})}};var Nd=class extends jt{constructor(a){super({...a,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function Ai(n,a){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>a;){let r=e.lastIndexOf(` `,a);r{l||g!==null||c||!s||(g=setTimeout(()=>{g=null;let Q=s;s=null;let f=Ai(Q,a)[0]??n;c=Promise.resolve(f===p?void 0:e(t,f)).then(()=>{p=f}).catch(y=>A.warn?.("[dsh-im] streamed message update failed:",y)).finally(()=>{c=null,B()})},o),g?.unref?.())};return{async start(){return t=await i(n),this},update(Q){l||typeof Q!="string"||!Q.trim()||(s=Q,B())},async finish(Q){if(l)throw new Error("Message stream is already closed");l=!0,g!==null&&clearTimeout(g),g=null,s=null,await c?.catch(()=>{});let f=Ai(Q,a),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";y!==p&&await e(t,y),p=y;for(let m of f.slice(1))await r(m)},cancel(){l=!0,s=null,g!==null&&clearTimeout(g),g=null}}}var Fte=4609,sG=Object.freeze([1e3,3e3,5e3,1e4,3e4]),Lte=new Set(["image/jpeg","image/png","image/webp","image/gif"]),Ute=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),Hte=Object.freeze(["cdn.discordapp.com"]);function Kte(n){let a=new URL(n);if(a.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return a.searchParams.set("v","10"),a.searchParams.set("encoding","json"),a.href}function oD(n,a,o){if(typeof n.addEventListener=="function")n.addEventListener(a,o);else if(typeof n.on=="function")n.on(a,o);else throw new TypeError("Discord WebSocket does not support events")}function Yte(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function xte(n){if(n===4004){let o=new Error("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002");return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002");return o.code="discord-intents",o}let a=new Error(`Discord Gateway closed (${n||"unknown"})`);return a.code="discord-gateway-closed",a}function jte(n,a){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${a}>`,"g"),"").trim()}function Jte(n){let a=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(Lte.has(a))return a;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of Ute)if(o.endsWith(i))return e;return null}function qte(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function Vte(n,a){let o=Jte(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:qte(n.size),load:i=>jr(n.url,{...i,fetchImpl:a,allowedHosts:Hte})}}function zte(n,a,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id)return null;let i=!n.guild_id,e=i||n.mentions?.some(r=>String(r?.id)===String(a));return{messageId:String(n.id),senderId:String(n.author.id),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:jte(n.content??"",a),images:Array.isArray(n.attachments)?n.attachments.map(r=>Vte(r,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)}}}var nD=class{#e;#A;constructor({api:a,signal:o}){this.#e=a,this.#A=o}async sendText(a,o){let i=Ai(o,1900),e=null;for(let[r,A]of i.entries())e=await this.#e.createMessage({channelId:a.channelId,content:A,replyToMessageId:r===0?a.replyToMessageId:void 0,signal:this.#A});return e}sendTyping(a){return this.#e.sendTyping({channelId:a.channelId,signal:this.#A})}async openStream(a){return Td({limit:1900,create:async i=>(await this.#e.createMessage({channelId:a.channelId,content:i,replyToMessageId:a.replyToMessageId,signal:this.#A})).id,edit:(i,e)=>this.#e.editMessage({channelId:a.channelId,messageId:i,content:e,signal:this.#A}),sendRemainder:i=>this.#e.createMessage({channelId:a.channelId,content:i,signal:this.#A})}).start()}};function Wte(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Nr()}}var RE=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r;#i=Wte();#o=null;#c=null;#l=null;#p=null;#h=null;#C=null;#d=null;#Q=null;#u=null;#B=!0;#y=null;#f=0;#D=0;#m=!0;#w=null;constructor({config:a,token:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,createApi:s=l=>new NE(l),createWebSocket:g=l=>new WebSocket(l),random:c=Math.random}){if(!a||!o||!i||!e)throw new TypeError("DiscordRuntime requires config, token, Harness, and state");if(typeof g!="function")throw new TypeError("DiscordRuntime requires WebSocket");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#r=c}get status(){return structuredClone(this.#i)}async start(){return this.#i.ready&&this.#p?this.status:this.#w?this.#w:(this.#w=this.#N().finally(()=>{this.#w=null}),this.#w)}async#N(){await this.stop(),this.#m=!1,this.#d=null,this.#C=null,this.#Q=null,this.#f=0,this.#i.startedAt=new Date().toISOString(),this.#i.connectionState="connecting",this.#i.lastError=null,await this.#t.ensureRunning(),this.#i.harnessReachable=!0;let a=new AbortController;this.#l=a;let o=this.#s({token:this.#A});this.#o=o;try{let[i,e]=await Promise.all([o.getCurrentUser({signal:a.signal}),o.getGatewayBot({signal:a.signal})]);if(String(i?.id??"")!==this.#e.platformId||i?.bot!==!0)throw new Error("Discord token identity does not match the saved bot");this.#h=e?.url;let r=new nD({api:o,signal:a.signal});this.#c=new _d({bot:r,harness:this.#t,state:this.#a,status:this.#i,logger:this.#g,replyTimeoutMs:this.#n,signal:a.signal});let A;try{await Promise.race([this.#S(!1),new Promise((t,s)=>{A=setTimeout(()=>s(new Error("Discord Gateway did not become ready in time")),this.#E)})])}finally{clearTimeout(A)}return this.status}catch(i){throw this.#i.ready=!1,this.#i.connectionState="failed",this.#i.lastError=i?.message??String(i),await this.stop(),i}}#S(a){if(this.#m)return Promise.reject(new Error("Discord runtime is stopped"));let o=++this.#D,i=Kte(a&&this.#C?this.#C:this.#h),e=this.#I(i);this.#p=e;let r=!1;return new Promise((A,t)=>{let s=()=>{if(r||o!==this.#D)return;r=!0,this.#f=0;let g=Date.now();this.#i.ready=!0,this.#i.connectionState="connected",this.#i.lastCheckedAt=g,this.#i.lastConnectedAt=g,this.#i.lastError=null,A()};oD(e,"message",g=>{if(o!==this.#D||this.#m)return;let c=Yte(g);if(!c)return;let l;try{l=JSON.parse(c)}catch{this.#g.warn?.("[dsh-im:discord] ignored malformed Gateway JSON");return}if(Number.isSafeInteger(l.s)&&(this.#Q=l.s),l.op===10){this.#M(l.d?.heartbeat_interval,e,o),a&&this.#d?this.#O(e,{op:6,d:{token:this.#A,session_id:this.#d,seq:this.#Q}}):this.#O(e,{op:2,d:{token:this.#A,intents:Fte,properties:{os:process.platform,browser:"dsh-im",device:"dsh-im"}}});return}if(l.op===11){this.#B=!0,this.#i.lastCheckedAt=Date.now();return}if(l.op===1){this.#F(e);return}if(l.op===7){e.close(4e3,"Reconnect requested");return}if(l.op===9){l.d!==!0&&(this.#d=null,this.#C=null,this.#Q=null),e.close(4e3,"Invalid session");return}if(l.op===0){if(l.t==="READY")this.#d=l.d?.session_id??null,this.#C=l.d?.resume_gateway_url??null,s();else if(l.t==="RESUMED")s();else if(l.t==="MESSAGE_CREATE"){let p=zte(l.d,this.#e.platformId),B=this.#c;p&&B&&B.accept(p).catch(Q=>{o!==this.#D||this.#m||this.#g.error?.(`[dsh-im:discord] bot ${this.#e.botId} message handling failed:`,Q)})}}}),oD(e,"close",(g={})=>{if(o!==this.#D)return;if(this.#T(),this.#p===e&&(this.#p=null),this.#m){r||t(new DOMException("Stopped","AbortError"));return}let c=xte(Number(g.code)||0);if(this.#i.ready=!1,this.#i.connectionState="connecting",this.#i.lastError=c.message,r||(r=!0,t(c)),c.code==="discord-401"||c.code==="discord-intents"){this.#i.connectionState="failed";return}this.#L()}),oD(e,"error",()=>{o!==this.#D||this.#m||(this.#i.lastError="Discord Gateway WebSocket error")})})}#O(a,o){a.readyState===1&&a.send(JSON.stringify(o))}#M(a,o,i){if(this.#T(),!Number.isFinite(a)||a<1e3){o.close(4e3,"Invalid heartbeat interval");return}this.#B=!0;let e=r=>{this.#u=setTimeout(()=>{if(!(this.#m||i!==this.#D||this.#p!==o)){if(!this.#B){o.close(4e3,"Heartbeat was not acknowledged");return}this.#F(o),e(a)}},r),this.#u?.unref?.()};e(Math.floor(a*this.#r()))}#F(a){this.#B=!1,this.#O(a,{op:1,d:this.#Q})}#T(){this.#u!==null&&clearTimeout(this.#u),this.#u=null,this.#B=!0}#L(){if(this.#m||this.#y!==null)return;let a=sG[Math.min(this.#f,sG.length-1)];this.#f+=1,this.#y=setTimeout(()=>{this.#y=null,this.#S(!!this.#d).catch(o=>{this.#m||(this.#g.warn?.("[dsh-im:discord] Gateway reconnect failed:",o),this.#L())})},a),this.#y?.unref?.()}async stop(){this.#m=!0,this.#D+=1,this.#l?.abort(),this.#l=null,this.#y!==null&&clearTimeout(this.#y),this.#y=null,this.#T();let a=this.#p,o=this.#c;this.#p=null,this.#c=null,this.#o=null;try{a&&a.readyState<2&&a.close(1e3,"Plugin stopped")}catch(i){this.#g.warn?.(`[dsh-im:discord] bot ${this.#e.botId} failed to close Gateway:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#i.ready=!1,this.#i.connectionState="idle",this.status}};import{mkdir as Zte,readFile as Xte,rename as $te,unlink as eae,writeFile as Aae}from"node:fs/promises";import{dirname as tae}from"node:path";var Rd=Object.freeze({version:1,sessions:{},seenMessageIds:[],cursor:null});function aae(n){if(!n||typeof n!="object")return structuredClone(Rd);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&o&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string"&&o).slice(-1e3):[],cursor:Number.isSafeInteger(n.cursor)&&n.cursor>=0?n.cursor:null}}var go=class{#e;#A=structuredClone(Rd);#t=Promise.resolve();constructor(a){this.#e=a}async load(){try{this.#A=aae(JSON.parse(await Xte(this.#e,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#A=structuredClone(Rd),await this.#a()}return this}sessionFor(a){return this.#A.sessions[a]??null}async setSession(a,o){this.#A.sessions[a]=o,await this.#a()}async clearSession(a){delete this.#A.sessions[a],await this.#a()}async clearSessions(){this.#A.sessions={},await this.#a()}hasSeen(a){return this.#A.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#A.seenMessageIds.push(a),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#a())}cursor(){return this.#A.cursor}async setCursor(a){if(!Number.isSafeInteger(a)||a<0)throw new TypeError("Invalid update cursor");this.#A.cursor=a,await this.#a()}snapshot(){return structuredClone(this.#A)}async remove(){try{await eae(this.#e)}catch(a){if(a?.code!=="ENOENT")throw a}this.#A=structuredClone(Rd)}async#a(){let a=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await Zte(tae(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Aae(i,a,{encoding:"utf8",mode:384}),await $te(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var kd=class extends go{};import{unlink as iae}from"node:fs/promises";import{homedir as oae}from"node:os";import{join as kE,resolve as Ig}from"node:path";var gG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function rae(n){if(!Array.isArray(n)||n.length===0)return[...gG];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...gG]}var sD=class{#e;#A;#t;#a;#g;#n;#E;#s;#I=null;#r=null;#i=0;#o=!1;#c=!1;#l;#p;constructor({channel:a,controller:o,harness:i,logger:e=console,retryDelaysMs:r,healthyIntervalMs:A=15e3,setTimeoutImpl:t=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!a)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=rae(r),this.#n=Number.isFinite(A)&&A>=0?A:15e3,this.#E=t,this.#s=s,this.#l=new Promise(g=>{this.#p=g})}get ready(){return this.#l}start(){return this.#c||this.#o?this:(this.#c=!0,this.#h(0),this)}async close(){this.#o||(this.#o=!0,this.#I!==null&&this.#s(this.#I),this.#I=null,await this.#r?.catch(()=>{}),this.#p?.(null),this.#p=null)}#h(a){this.#o||(this.#I=this.#E(()=>{this.#I=null,this.#C()},a),this.#I?.unref?.())}async#C(){if(this.#o||this.#r)return;let a=this.#d();this.#r=a;try{await a}finally{this.#r===a&&(this.#r=null)}}async#d(){try{if(await this.#t.ensureRunning(),this.#o)return;let a=await this.#A.initialize();if(this.#o)return;this.#p?.(a),this.#p=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im token channel requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function cD(n,a){let o=Ig(n.dshHome??process.env.DSH_HOME??kE(oae(),".dsh")),i=Ig(n.dataDir??kE(o,"integrations",`dsh-${a}`));return{config:Ig(n.configPath??kE(i,"config.json")),bots:Ig(n.botsDir??kE(i,"bots")),workspaces:Ig(n.workspacesPath??kE(i,"workspaces.json"))}}async function vd(n,a,o,i){let{channel:e,ConfigStore:r,StateStore:A,HarnessClient:t,Controller:s,Runtime:g}=i;if(!n?.credentials)throw new TypeError(`dsh-im ${e} requires ctx.credentials`);if(!n?.webServer)throw new TypeError(`dsh-im ${e} requires ctx.webServer`);let c=o.ConfigStore??r,l=o.StateStore??A,p=o.HarnessClient??t,B=o.Controller??s,Q=o.Runtime??g,f=o.createConnectionSupervisor??zc,y=typeof n.logger=="function"?n.logger(`dsh-im:${e}`):n.logger??console,m=cD(a,e),R=await new c(m.config).load(),k=Ig(a.workspace??process.cwd()),G=o.WorkspaceStore??Ea,K=o.workspaces??await new G(m.workspaces,{defaultWorkspace:k}).load(),x=R.list();await K.reconcile(x.map(X=>X.botId)),await Promise.all(x.map(X=>K.ensure(X.botId)));let H=typeof R.remove=="function"?Ya(R,{workspaces:K}):R,q=new Map,j=X=>Ig(m.bots,X,"state.json"),F=async X=>{let pe=q.get(X);return pe||(pe=await new l(j(X)).load(),q.set(X,pe)),pe},T=Ja(n,o.commandExecutor),V=new p({baseUrl:gD(n.webServer,a.harnessBaseUrl),workspace:k,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh",...T?{commandExecutor:T}:{}}),U=new B({credentials:n.credentials,configStore:H,logger:y,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:X,config:pe,token:me})=>{let qe=await F(X);await K.ensure(X);let Se=xa(V,{botId:X,workspaces:K,state:qe});return new Q({config:pe,token:me,harness:Se.harness,state:Se.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,logger:{error:(...Ge)=>y.error?.(`[${X}]`,...Ge),warn:(...Ge)=>y.warn?.(`[${X}]`,...Ge),info:(...Ge)=>y.info?.(`[${X}]`,...Ge),debug:(...Ge)=>y.debug?.(`[${X}]`,...Ge)}})},deleteState:async({botId:X})=>{let pe=q.get(X);if(q.delete(X),pe&&typeof pe.remove=="function")await pe.remove();else try{await iae(j(X))}catch(me){if(me?.code!=="ENOENT")throw me}}}),b=ja(U,{workspaces:K,stateFor:F}),L=f({channel:e,controller:b,harness:V,logger:y,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:b,ready:L.ready,async close(){await L.close(),await b.close(),V.stopManagedProcess()}}}function ID(n,a={},o={}){return vd(n,a,o,{channel:"discord",ConfigStore:Md,StateStore:kd,HarnessClient:Nd,Controller:TE,Runtime:RE})}var Cr=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:pr}),nae=Object.freeze(Object.values(Cr)),sae=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]);function ED(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Pd(n,a){return ED(n)&&Object.keys(n).every(o=>a.includes(o))}function cG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function gae(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function cae(n,a){return ED(a)?n===Cr.status?Pd(a,[])?null:"connection.status does not accept fields.":n===Cr.bindCredentials?Pd(a,["token"])&&gae(a.token)?null:"bot.bind-credentials requires a Bot Token.":n===Cr.reconnectBot?Pd(a,["botId"])&&cG(a.botId)?null:"bot.reconnect requires a botId.":n===Cr.deleteBot?Pd(a,["botId","confirm"])&&cG(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Cr.setWorkspace?Va(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown bot endpoint.":"Payload must be an object."}function lD(n){if(Array.isArray(n))return n.map(lD);if(!ED(n))return n;let a={};for(let[o,i]of Object.entries(n))sae.has(o)||(a[o]=lD(i));return a}function Iae(n,a){let o=za(a);return o||(a?.code==="webhook-configured"?{code:"webhook-configured",message:a.message}:a?.code==="telegram-401"||a?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:a?.code==="discord-intents"?{code:"discord-intents",message:a.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function pD(n,{channel:a}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${a} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!nae.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${a} endpoint.`}};let r=cae(o,i);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let A;if(o===Cr.status)A=await n.status();else if(o===Cr.bindCredentials)A=await n.bindCredentials(i);else if(o===Cr.reconnectBot)A=await n.reconnectBot(i.botId);else if(o===Cr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");A=await n.updateWorkspace(i.botId,i.workspace)}else A=await n.deleteBot(i.botId);return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:lD(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:Iae(a,A)}}}}function Gd(n,a,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,pD(a,{channel:o}),{authority:qa(e)})}var IG="/discord",lG=Cr,lae=Object.freeze(Object.values(lG));function Fd(n,a,o){return Gd(n,a,{channel:"Discord",rpcChannel:IG,authority:o})}async function EG(n,a={}){if(a?.controller)return Fd(n,a.controller,a.rpcAuthority);let o=await ID(n,a,a.internals??{}),i=Fd(n,o.controller,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Discord bot connections"),i}var Eae=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function pae(n){let a=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof a!="string"||a.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:a,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function Cae(n){return typeof n.status!="function"?{}:await n.status()}function hae(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var Ld=class{#e;#A;#t;#a;#g=!1;#n=null;constructor({createProvisioningManager:a,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof a!="function")throw new TypeError("createProvisioningManager is required");if(!o||typeof o.save!="function"||typeof o.clear!="function")throw new TypeError("credentialStore.save/clear are required");if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("connectionManager.connect/disconnect are required");if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registrationOptions must be an object");if(this.#e=o,this.#A=i,this.#t=structuredClone(e),this.#a=a({onCredentials:r=>this.#E(r)}),!this.#a||typeof this.#a.start!="function"||typeof this.#a.status!="function"||typeof this.#a.cancel!="function")throw new TypeError("The provisioning manager must implement start/status/cancel")}async startRegistration(){return this.#n=null,await this.#a.start(structuredClone(this.#t)),this.status()}async cancelRegistration(){return await this.#a.cancel(),this.status()}async disconnect(){await this.#a.cancel(),await this.#A.disconnect();try{await this.#e.clear(),this.#g=!1,this.#n=null}catch{this.#n={code:"credential_removal_failed",message:"Unable to remove the Feishu credentials."}}return this.status()}async status(){let a=await this.#a.status(),o=await Cae(this.#A),i=hae(o),e=this.#g;if(typeof this.#e.configured=="function")try{e=await this.#e.configured()}catch{e=this.#g}let r="unconfigured";return i?r="connected":Eae.has(a?.state)?r="registering":a?.state==="saving"?r="connecting":this.#n||a?.state==="error"?r="error":e&&(r="disconnected"),{phase:r,connected:i,configured:e,registration:a,connection:o,error:this.#n??a?.error??null}}async close(){await this.#a.cancel(),await this.#A.disconnect()}async#E(a){let o=pae(a);try{await this.#e.save(o),this.#g=!0,await this.#A.connect(o),this.#n=null}catch{throw this.#n={code:"connection_failed",message:"The bot was created, but its connection could not be started."},new Error("Unable to activate the Feishu connection.")}}};function CD(n){return new Ld(n)}import{homedir as Gue}from"node:os";import{join as FI,resolve as Es}from"node:path";import{unlink as Fue}from"node:fs/promises";var cN={};Xt(cN,{AESCipher:()=>Jp,AccessTokenError:()=>PI,Aily:()=>U_,AppType:()=>Bo,CAppTicket:()=>jp,CTenantAccessToken:()=>Up,CardActionHandler:()=>P_,Client:()=>fB,ClientAssertionError:()=>Za,DefaultCache:()=>uB,Domain:()=>Qo,EventDispatcher:()=>mB,LarkChannel:()=>bB,LarkChannelError:()=>It,LoggerLevel:()=>Pr,LoggerProxy:()=>ls,WSClient:()=>DB,adaptDefault:()=>ohe,adaptExpress:()=>nhe,adaptKoa:()=>she,adaptKoaRouter:()=>ghe,createLarkChannel:()=>qde,defaultHttpInstance:()=>GI,defaultLogger:()=>dn,generateChallenge:()=>Vp,internalCache:()=>qp,messageCard:()=>Ihe,normalize:()=>A1,normalizeBotAdded:()=>$x,normalizeCardAction:()=>Xx,normalizeComment:()=>e1,normalizeReaction:()=>$_,registerApp:()=>yhe,withAll:()=>ehe,withHelpDeskCredential:()=>the,withTenantKey:()=>Ahe,withTenantToken:()=>ahe,withUserAccessToken:()=>rhe});function vE(n,a){return function(){return n.apply(a,arguments)}}var{toString:dae}=Object.prototype,{getPrototypeOf:Wc}=Object,{iterator:GE,toStringTag:hG}=Symbol,Hd=(({hasOwnProperty:n})=>(a,o)=>n.call(a,o))(Object.prototype),PE=(n,a)=>{let o=n,i=[];for(;o!=null&&o!==Object.prototype;){if(i.indexOf(o)!==-1)return!1;if(i.push(o),Hd(o,a))return!0;o=Wc(o)}return!1},uae=(n,a)=>n!=null&&PE(n,a)?n[a]:void 0,dD=(n=>a=>{let o=dae.call(a);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),ti=n=>(n=n.toLowerCase(),a=>dD(a)===n),Kd=n=>a=>typeof a===n,{isArray:Eg}=Array,pg=Kd("undefined");function Zc(n){return n!==null&&!pg(n)&&n.constructor!==null&&!pg(n.constructor)&&hr(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var dG=ti("ArrayBuffer");function Bae(n){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(n):a=n&&n.buffer&&dG(n.buffer),a}var Qae=Kd("string"),hr=Kd("function"),uG=Kd("number"),Xc=n=>n!==null&&typeof n=="object",fae=n=>n===!0||n===!1,Ud=n=>{if(!Xc(n))return!1;let a=Wc(n);return(a===null||a===Object.prototype||Wc(a)===null)&&!PE(n,hG)&&!PE(n,GE)},yae=n=>{if(!Xc(n)||Zc(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},mae=ti("Date"),Sae=ti("File"),Dae=n=>!!(n&&typeof n.uri<"u"),wae=n=>n&&typeof n.getParts<"u",Oae=ti("Blob"),Mae=ti("FileList"),bae=ti("Set"),_ae=n=>Xc(n)&&hr(n.pipe);function Nae(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var pG=Nae(),CG=typeof pG.FormData<"u"?pG.FormData:void 0,Tae=n=>{if(!n)return!1;if(CG&&n instanceof CG)return!0;let a=Wc(n);if(!a||a===Object.prototype||!hr(n.append))return!1;let o=dD(n);return o==="formdata"||o==="object"&&hr(n.toString)&&n.toString()==="[object FormData]"},Rae=ti("URLSearchParams"),[kae,vae,Pae,Gae]=["ReadableStream","Request","Response","Headers"].map(ti),Fae=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function FE(n,a,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),Eg(n))for(i=0,e=n.length;i0;)if(e=o[i],a===e.toLowerCase())return e;return null}var lg=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,QG=n=>!pg(n)&&n!==lg;function hD(...n){let{caseless:a,skipUndefined:o}=QG(this)&&this||{},i={},e=(r,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let t=a&&typeof A=="string"&&BG(i,A)||A,s=Hd(i,t)?i[t]:void 0;Ud(s)&&Ud(r)?i[t]=hD(s,r):Ud(r)?i[t]=hD({},r):Eg(r)?i[t]=r.slice():(!o||!pg(r))&&(i[t]=r)};for(let r=0,A=n.length;r(FE(a,(e,r)=>{o&&hr(e)?Object.defineProperty(n,r,{__proto__:null,value:vE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,r,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),Uae=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),Hae=(n,a,o,i)=>{n.prototype=Object.create(a.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:a.prototype}),o&&Object.assign(n.prototype,o)},Kae=(n,a,o,i)=>{let e,r,A,t={};if(a=a||{},n==null)return a;do{for(e=Object.getOwnPropertyNames(n),r=e.length;r-- >0;)A=e[r],(!i||i(A,n,a))&&!t[A]&&(a[A]=n[A],t[A]=!0);n=o!==!1&&Wc(n)}while(n&&(!o||o(n,a))&&n!==Object.prototype);return a},Yae=(n,a,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=a.length;let i=n.indexOf(a,o);return i!==-1&&i===o},xae=n=>{if(!n)return null;if(Eg(n))return n;let a=n.length;if(!uG(a))return null;let o=new Array(a);for(;a-- >0;)o[a]=n[a];return o},jae=(n=>a=>n&&a instanceof n)(typeof Uint8Array<"u"&&Wc(Uint8Array)),Jae=(n,a)=>{let i=(n&&n[GE]).call(n),e;for(;(e=i.next())&&!e.done;){let r=e.value;a.call(n,r[0],r[1])}},qae=(n,a)=>{let o,i=[];for(;(o=n.exec(a))!==null;)i.push(o);return i},Vae=ti("HTMLFormElement"),zae=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:Wae}=Object.prototype,Zae=ti("RegExp"),fG=(n,a)=>{let o=Object.getOwnPropertyDescriptors(n),i={};FE(o,(e,r)=>{let A;(A=a(e,r,n))!==!1&&(i[r]=A||e)}),Object.defineProperties(n,i)},Xae=n=>{fG(n,(a,o)=>{if(hr(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(hr(i)){if(a.enumerable=!1,"writable"in a){a.writable=!1;return}a.set||(a.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},$ae=(n,a)=>{let o={},i=e=>{e.forEach(r=>{o[r]=!0})};return Eg(n)?i(n):i(String(n).split(a)),o},ere=()=>{},Are=(n,a)=>n!=null&&Number.isFinite(n=+n)?n:a;function tre(n){return!!(n&&hr(n.append)&&n[hG]==="FormData"&&n[GE])}var are=n=>{let a=new WeakSet,o=i=>{if(Xc(i)){if(a.has(i))return;if(Zc(i))return i;if(!("toJSON"in i)){a.add(i);let e;if(bae(i)){e=[];for(let r of i){let A=o(r);!pg(A)&&e.push(A)}}else e=Eg(i)?[]:{},FE(i,(r,A)=>{let t=o(r);!pg(t)&&(e[A]=t)});return a.delete(i),e}}return i};return o(n)},rre=ti("AsyncFunction"),ire=n=>n&&(Xc(n)||hr(n))&&hr(n.then)&&hr(n.catch),yG=((n,a)=>n?setImmediate:a?((o,i)=>(lg.addEventListener("message",({source:e,data:r})=>{e===lg&&r===o&&i.length&&i.shift()()},!1),e=>{i.push(e),lg.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",hr(lg.postMessage)),ore=typeof queueMicrotask<"u"?queueMicrotask.bind(lg):typeof process<"u"&&process.nextTick||yG,mG=n=>n!=null&&hr(n[GE]),nre=n=>n!=null&&PE(n,GE)&&mG(n),J={isArray:Eg,isArrayBuffer:dG,isBuffer:Zc,isFormData:Tae,isArrayBufferView:Bae,isString:Qae,isNumber:uG,isBoolean:fae,isObject:Xc,isPlainObject:Ud,isEmptyObject:yae,isReadableStream:kae,isRequest:vae,isResponse:Pae,isHeaders:Gae,isUndefined:pg,isDate:mae,isFile:Sae,isReactNativeBlob:Dae,isReactNative:wae,isBlob:Oae,isRegExp:Zae,isFunction:hr,isStream:_ae,isURLSearchParams:Rae,isTypedArray:jae,isFileList:Mae,forEach:FE,merge:hD,extend:Lae,trim:Fae,stripBOM:Uae,inherits:Hae,toFlatObject:Kae,kindOf:dD,kindOfTest:ti,endsWith:Yae,toArray:xae,forEachEntry:Jae,matchAll:qae,isHTMLForm:Vae,hasOwnProperty:Hd,hasOwnProp:Hd,hasOwnInPrototypeChain:PE,getSafeProp:uae,reduceDescriptors:fG,freezeMethods:Xae,toObjectSet:$ae,toCamelCase:zae,noop:ere,toFiniteNumber:Are,findKey:BG,global:lg,isContextDefined:QG,isSpecCompliantForm:tre,toJSONObject:are,isAsyncFn:rre,isThenable:ire,setImmediate:yG,asap:ore,isIterable:mG,isSafeIterable:nre};var sre=J.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),SG=n=>{let a={},o,i,e;return n&&n.split(` @@ -185,7 +185,7 @@ ${r.join(` `,{encoding:"utf8",mode:384}),await LQe(o,this.#e)}};var fQ=class extends jt{constructor(a){super({...a,rpcIdPrefix:"wecom",logPrefix:"dsh-wecom"})}};var jQe="https://work.weixin.qq.com/ai/qc/generate",JQe="https://work.weixin.qq.com/ai/qc/query_result";function C3(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function HI(n){return typeof n=="string"&&n.trim()?n.trim():null}function qQe(n){let a=HI(n);if(!a)return null;try{let o=new URL(a);return o.protocol==="https:"&&o.hostname==="work.weixin.qq.com"&&(!o.port||o.port==="443")?o.href:null}catch{return null}}function VQe(n,a){return n?AbortSignal.any([n,AbortSignal.timeout(a)]):AbortSignal.timeout(a)}async function h3(n,a,o){let i=await n(a,{method:"GET",redirect:"error",signal:VQe(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var yQ=class{#e;#A;#t;#a;constructor({fetch:a=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=C3()}={}){if(typeof a!="function")throw new TypeError("A fetch implementation is required");this.#e=a,this.#A=o,this.#t=i,this.#a=[1,2,3].includes(e)?e:C3()}async start({signal:a}={}){let o=new URL(jQe);o.searchParams.set("source",this.#t),o.searchParams.set("plat",String(this.#a));let i=await h3(this.#e,o,a),e=HI(i?.data?.scode),r=qQe(i?.data?.auth_url);if(!e||!r)throw new Error("Enterprise WeChat QR service returned invalid data");return{scode:e,verificationUrl:r,expiresAt:this.#A()+3e5,pollIntervalMs:3e3}}async poll({scode:a,signal:o}={}){let i=HI(a);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(JQe);e.searchParams.set("scode",i);let r=await h3(this.#e,e,o),A=HI(r?.data?.status)?.toLowerCase();if(A==="success"){let t=HI(r?.data?.bot_info?.botid),s=HI(r?.data?.bot_info?.secret);if(!t||!s)throw new Error("Enterprise WeChat QR result omitted bot credentials");return{status:"success",remoteBotId:t,secret:s}}return["expired","timeout"].includes(A)?{status:"expired"}:["fail","failed","error"].includes(A)?{status:"failed"}:{status:"waiting"}}};import{mkdir as zQe,readFile as WQe,rename as ZQe,unlink as XQe,writeFile as $Qe}from"node:fs/promises";import{dirname as efe}from"node:path";var mQ=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function Afe(n){if(!n||typeof n!="object")return structuredClone(mQ);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var SQ=class{#e;#A=structuredClone(mQ);#t=Promise.resolve();constructor(a){this.#e=a}async load(){try{this.#A=Afe(JSON.parse(await WQe(this.#e,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#A=structuredClone(mQ),await this.#a()}return this}sessionFor(a){return this.#A.sessions[a]??null}async setSession(a,o){this.#A.sessions[a]=o,await this.#a()}async clearSession(a){delete this.#A.sessions[a],await this.#a()}async clearSessions(){this.#A.sessions={},await this.#a()}hasSeen(a){return this.#A.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#A.seenMessageIds.push(a),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#a())}async remove(){try{await XQe(this.#e)}catch(a){if(a?.code!=="ENOENT")throw a}this.#A=structuredClone(mQ)}async#a(){let a=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await zQe(efe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await $Qe(i,a,{encoding:"utf8",mode:384}),await ZQe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as tfe}from"node:crypto";var d3=new Set(["pending","connecting"]),EC=new Set(["connected","failed","cancelled","expired"]);function Vg(n){return typeof n=="string"&&n.trim()?n.trim():null}function yr(n,a){return Object.freeze({code:n,message:a})}function zg(n){return n?{attemptId:n.id,status:n.state,pollIntervalMs:n.pollIntervalMs,qrRevision:n.qrRevision,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.botId?{botId:n.botId}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}var pC=class{#e;#A;#t;#a;#g;#n;#E=new Map;#s=new Map;#I=new Map;#r=null;#i=new Map;#o=0;#c=!1;constructor({qrAuth:a,credentials:o,configStore:i,createRuntime:e,deleteState:r=async()=>{},logger:A=console}){if(!a||typeof a.start!="function"||typeof a.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A}async initialize(){if(this.#c)return this.status();for(let a of this.#t.list())await this.#B(a.botId,async()=>{let o=this.#E.get(a.botId)?.status;if(this.#c||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#Q(a.secretRef);if(!i){this.#s.set(a.botId,yr("missing-secret","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u626B\u7801\u3002"));return}try{await this.#C(a,i),this.#s.delete(a.botId)}catch{this.#s.set(a.botId,yr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${a.botId} failed to initialize`)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("Enterprise WeChat controller is closed");this.#r&&await this.cancelProvisioning(this.#r);let a={id:tfe(),state:"pending",createdAt:Date.now(),expiresAt:null,pollIntervalMs:3e3,qrRevision:1,verificationUrl:null,scode:null,botId:null,error:null,controller:new AbortController,polling:null,transition:null};this.#I.set(a.id,a),this.#r=a.id,this.#f();try{let o=await this.#e.start({signal:a.controller.signal});if(a.scode=Vg(o.scode),a.verificationUrl=Vg(o.verificationUrl),a.expiresAt=Number(o.expiresAt),a.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!a.scode||!a.verificationUrl||!Number.isFinite(a.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#f(),zg(a)}catch(o){throw a.state=a.controller.signal.aborted?"cancelled":"failed",a.error=a.controller.signal.aborted?yr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"):yr("qr-start-failed","\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),this.#y(a),o}}async registrationStatus(a){let o=this.#I.get(a);if(!o||EC.has(o.state))return zg(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),zg(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=yr("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),o.controller.abort(),this.#y(o),zg(o);if(!o.polling){let i=this.#l(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),zg(o)}async bindCredentials({botId:a,secret:o}={}){if(this.#c)throw new Error("Enterprise WeChat controller is closed");let i=Vg(a),e=Vg(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#r&&await this.cancelProvisioning(this.#r),this.#c)throw new Error("Enterprise WeChat controller is closed");let r=QQ(i);return await this.#B(r.botId,async()=>{if(this.#c)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),t=await this.#A.resolve(r.secretRef).catch(()=>{});if(this.#c)throw new Error("Enterprise WeChat controller is closed");let s={botId:r.botId,remoteBotId:i,secretRef:r.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(r.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#u(r.secretRef,t),g}try{await this.#C(s,e),this.#s.delete(r.botId)}catch{this.#s.set(r.botId,yr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${r.botId} credential connection failed`)}this.#f()}),this.status()}async cancelProvisioning(a){let o=this.#I.get(a);return o?(EC.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),EC.has(o.state)||(o.state="cancelled"),o.error??=yr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"),this.#y(o)),zg(o)):null}async reconnectBot(a){let o=this.#t.get(a);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(a,async()=>{let i=await this.#Q(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#C(o,i),this.#s.delete(a)}catch(e){throw this.#s.set(a,yr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async deleteBot(a){let o=this.#t.get(a);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(a,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#d(a);try{await this.#A.unset(o.secretRef),await this.#t.remove(a)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#C(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#g({botId:a,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:wecom] bot ${a} state cleanup failed:`,e)}),this.#s.delete(a),this.#f()}),this.status()}status(){let a=this.#t.list().map(e=>{let r=this.#E.get(e.botId)?.status??null,A=r?.ready===!0&&r.wecomConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.wecomConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||r?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",appIdMasked:E3(e.remoteBotId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:r?.lastCheckedAt??null,lastConnectedAt:r?.lastConnectedAt??null},stats:{messagesReceived:r?.messagesReceived??0,messagesReplied:r?.messagesReplied??0},error:structuredClone(this.#s.get(e.botId)??null)}}),o=a.filter(e=>e.connected).length,i=this.#r?this.#I.get(this.#r):null;return{schemaVersion:1,revision:this.#o,state:i&&d3.has(i.state)?"provisioning":a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o},...i&&d3.has(i.state)?{provisioning:zg(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#r&&await this.cancelProvisioning(this.#r),await Promise.allSettled([...this.#i.values()]),await Promise.allSettled([...this.#E.keys()].map(a=>this.#d(a))))}async#l(a){try{let o=await this.#e.poll({scode:a.scode,signal:a.controller.signal});if(a.controller.signal.aborted||EC.has(a.state)||o.status==="waiting")return;if(o.status==="expired"){a.state="expired",a.error=yr("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),this.#y(a);return}if(o.status!=="success"){a.state="failed",a.error=yr("qr-connect-failed","\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#y(a);return}a.state="connecting",a.verificationUrl=null,a.expiresAt=null,a.scode=null,this.#f();let i=this.#p(a,o);a.transition=i,await i}catch{if(a.controller.signal.aborted)return;a.state="failed",a.error=yr("qr-connect-failed","\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#n.warn?.("[dsh-im:wecom] QR polling failed"),this.#y(a)}}async#p(a,o){try{let i=Vg(o.remoteBotId),e=Vg(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");a.botId=await this.#h(a,{remoteBotId:i,secret:e}),a.state="connected",a.error=null}catch{a.controller.signal.aborted?(a.state="cancelled",a.error=yr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=yr("activation-failed","\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002"),this.#n.error?.("[dsh-im:wecom] provisioning failed"))}finally{this.#y(a)}}async#h(a,{remoteBotId:o,secret:i}){let e=QQ(o),r=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),t={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#B(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(a.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(t)}catch(s){throw await this.#u(e.secretRef,A),s}try{if(a.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#C(t,i),this.#s.delete(e.botId)}catch(s){if(a.controller.signal.aborted)throw await this.#d(e.botId),r?await this.#t.save(r).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#g({botId:e.botId,config:t}).catch(c=>{this.#n.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#u(e.secretRef,A),s;this.#s.set(e.botId,yr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#n.warn?.(`[dsh-im:wecom] bot ${e.botId} activation connection failed`)}return this.#f(),e.botId})}async#C(a,o){if(this.#c)throw new Error("Enterprise WeChat controller is closed");if(await this.#d(a.botId),this.#c)throw new Error("Enterprise WeChat controller is closed");let i=await this.#a({botId:a.botId,config:a,secret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Enterprise WeChat runtime");this.#E.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#E.delete(a.botId),e}}async#d(a){let o=this.#E.get(a);this.#E.delete(a),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:wecom] bot ${a} failed to stop cleanly:`,i)})}async#Q(a){let o=await this.#A.resolve(a).catch(()=>{});return Vg(o?.value)}async#u(a,o){o?.value?await this.#A.set(a,o.value).catch(()=>{}):await this.#A.unset(a).catch(()=>{})}#B(a,o){let r=(this.#i.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(a)===r&&this.#i.delete(a)});return this.#i.set(a,r),r}#y(a){a.scode=null,a.verificationUrl=null,a.expiresAt=null,this.#r===a.id&&(this.#r=null),this.#f();let o=[...this.#I.values()].filter(i=>EC.has(i.state));for(;o.length>16;)this.#I.delete(o.shift().id)}#f(){this.#o+=1}};import{WSAuthFailureError as lfe,WSClient as Efe,WSReconnectExhaustedError as pfe}from"@wecom/aibot-node-sdk";import{generateReqId as afe}from"@wecom/aibot-node-sdk";var rfe=["\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `),ife=18e3,u3=5*1024*1024,f3=4,DQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function hs(n){return typeof n=="string"&&n.trim()?n.trim():null}function Wg(n){return n?.body&&typeof n.body=="object"?n.body:{}}function B3(n){let a=Wg(n);return a.chattype==="group"?`group:${a.chatid}`:`direct:${a.from?.userid}`}function y3(n){let a=Wg(n),o="";return a.msgtype==="text"?o=typeof a.text?.content=="string"?a.text.content.trim():"":a.msgtype==="voice"?o=typeof a.voice?.content=="string"?a.voice.content.trim():"":a.msgtype==="mixed"&&Array.isArray(a.mixed?.msg_item)&&(o=a.mixed.msg_item.filter(i=>i?.msgtype==="text"&&typeof i.text?.content=="string").map(i=>i.text.content).join(` -`).trim()),a.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function ofe(n){let a=Wg(n);return a.msgtype==="image"?[a.image]:a.msgtype!=="mixed"||!Array.isArray(a.mixed?.msg_item)?[]:a.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function nfe(n,a){let o=hs(a?.url);if(!o)return null;let i=hs(a?.aeskey)??void 0;return{async load({signal:e,maxBytes:r}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let t=A?.buffer;if(!Buffer.isBuffer(t)&&!(t instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(t);if(Number.isFinite(r)&&s.length>r)throw new at("image-too-large",`Enterprise WeChat image exceeds ${r} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function Q3(n,a){return{content:y3(n),images:ofe(n).map(o=>nfe(a,o)).filter(Boolean)}}function sfe(n,a){return wa(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:a,maxBytes:u3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:r=u3}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let t=A?.data??A?.buffer??A;if((Buffer.isBuffer(t)||t instanceof Uint8Array?t.length:0)>r)throw new at("image-too-large",`Enterprise WeChat image exceeds ${r} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function gfe(n){return{...n,images:n.images.map(a=>({...a,async load(){throw new at("image-queue-full",`Enterprise WeChat already has ${f3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function jN(n){return Wg(n).msgtype==="text"?y3(n):""}function wQ(n,a=ife){let o=String(n??"").trim();if(!o)return[];let i=[],e="",r=0;for(let A of o){let t=Buffer.byteLength(A);e&&r+t>a?(i.push(e),e=A,r=t):(e+=A,r+=t)}return e&&i.push(e),i}function cfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function Ife(n,a){return a.questions[a.index]&&hs(Wg(n).from?.userid)===a.actor&&hs(jN(n))}function JN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var OQ=class{#e;#A;#t;#a;#g;#n;#E;#s;#I=new Map;#r=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:a,harness:o,state:i,status:e=JN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=afe,signal:s}){if(!a||typeof a.replyStream!="function"||typeof a.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#l=new lr({label:"wecom",logger:r})}get status(){return structuredClone(this.#a)}accept(a){if(this.#s?.aborted)return Promise.resolve();let o=Wg(a),i=hs(o.msgid),e=hs(o.from?.userid),r=o.chattype==="group"?hs(o.chatid):e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=B3(a);this.#o.add(i);let t=this.#r.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:jN(a),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#r.has(A),send:g=>this.#d(a,r,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(i),this.#c.delete(g)}),this.#c.add(g),g}if(t&&t.actor!==e)return this.#h(a,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(a,i,A);if(t){Ife(a,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(a,i,e,r,A,t)).finally(()=>{this.#o.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#h(a,i,A)}#h(a,o,i,{releaseMessageId:e=!0,alreadyRecorded:r=!1}={}){let A=Q3(a,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=f3?(s=t,this.#p+=s,g=sfe(A,this.#s)):g=gfe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(a,{alreadyRecorded:r,preparedMessage:g})).finally(()=>{this.#p-=s,e&&this.#o.delete(o),this.#I.get(i)===l&&this.#I.delete(i)});return this.#I.set(i,l),l}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#r.values()].flatMap(a=>a.queue?[a.queue]:[]),...this.#c])}async#C(a,o){for(let i of wQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#d(a,o,i){this.#s?.throwIfAborted();let e=wQ(i);if(e.length!==0)try{await this.#e.replyStream(a,this.#E("stream"),e[0],!0);for(let r of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#C(o,i)}}async#Q(a,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Wg(a),r=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!r||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(r))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}let s=i??Q3(a,this.#e),g=s.content,c=wa(s),l=B3(a),p=null,B=!1;try{if(!g&&!c){await this.#d(a,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(r);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(a,t,rfe),await this.#t.markSeen(r);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(a,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(r);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(a,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(r);return}let f=c?null:await Xr(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(a,t,K);await this.#t.markSeen(r);return}let y=c?null:await Zr(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(a,t,y.message),await this.#t.markSeen(r);return}p=this.#E("stream");try{await this.#e.replyStream(a,p,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),B=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",K)}let m=c?await Jr(s,{signal:this.#s}):void 0,{answer:R}=await Er({harness:this.#A,state:this.#t,key:l,text:g,content:m,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#n,signal:this.#s,onUpdate:B&&typeof this.#e.replyStreamNonBlocking=="function"?async K=>{let x=wQ(cfe(K))[0];x&&await this.#e.replyStreamNonBlocking(a,p,x,!1)}:void 0,onInteraction:K=>this.#B(K,{key:l,actor:A,chatId:t,requiresMention:e.chattype==="group"}),onInteractionResolved:K=>this.#y(K)}}),k=wQ(R||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),G=!1;if(B&&k.length>0)try{await this.#e.replyStream(a,p,k[0],!0);for(let K of k.slice(1))await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:K}});G=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",K)}G||await this.#C(t,R),await this.#t.markSeen(r),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#a.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=qr(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(a,p,f,!0):await this.#d(a,t,f),await this.#t.markSeen(r)}catch{this.#g.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#N(l),this.#l.closeRoute(l)])}}async#u(a,o,i,e,r,A){if(this.#s?.aborted)return;let t=this.#r.get(r),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(a,o,e):this.#h(a,o,r,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let g=hs(jN(a));if(!g){await this.#d(a,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#r.get(r);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(a,e,DQ).catch(()=>{});return}return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#a.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#r.get(r);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(a,e,DQ).catch(()=>{});return}return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(Wr(l,g)),c.index+=1,c.index{});return}if(this.#r.get(r)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#a.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(a,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(a,{key:o,actor:i,chatId:e,requiresMention:r}){if(a?.kind==="approval")return this.#l.handleRequested(a,{key:o,actor:i,requiresMention:r,send:c=>this.#C(e,c)});if(a?.kind!=="question")return;let A=a?.payload?.questions,t=typeof a?.interactionId=="string"?a.interactionId:a?.rpcId;if(typeof a?.rpcId!="string"||typeof t!="string"||typeof a.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Vr(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(a.recovered===!0){await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#C(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#r.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#f(s);return}if(this.#i.has(t))return;if(s){this.#g.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#r.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(a){if(a?.kind==="approval"){await this.#l.handleResolved(a);return}let o=a?.interactionId;if(a?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(a){if(!a.needsPresentation)return Promise.resolve();if(a.presentationPromise)return a.presentationPromise;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=this.#C(a.chatId,zr(o,a.index,a.questions.length,{requiresMention:a.requiresMention})).then(()=>{a.needsPresentation=!1}).finally(()=>{a.presentationPromise===i&&(a.presentationPromise=null)});return a.presentationPromise=i,i}async#D(a,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),await this.#d(a,i,DQ).catch(()=>{}))}#m(a,o){let i=this.#r.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#r.delete(a),this.#i.delete(i.interactionId),i)}#w(a,o){return this.#m(a,o)!==null}async#N(a){let o=this.#m(a);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#g.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function Cfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function hfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...JN()}}var CC=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r=hfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:a,secret:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Efe(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#r)}async start(){if(this.#r.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let a=new AbortController;return this.#l=a,this.#p=a,this.#c=this.#h(a.signal).finally(()=>{this.#l===a&&(this.#l=null),this.#c=null}),this.#c}async#h(a){await this.#C(),a.throwIfAborted(),this.#r.startedAt=new Date().toISOString(),this.#r.wecomConnectionState="connecting",this.#r.lastError=null,await this.#t.ensureRunning(),this.#r.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#s});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#i=i,this.#o=new OQ({client:i,harness:this.#t,state:this.#a,status:this.#r,logger:this.#g,replyTimeoutMs:this.#n,signal:a});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#i!==i||a.aborted)return;A=!0;let Q=Date.now();this.#r.ready=!0,this.#r.wecomConnectionState="connected",this.#r.lastCheckedAt=Q,this.#r.lastConnectedAt=Q,this.#r.lastError=null,e()},g=()=>{this.#i===i&&(this.#r.ready=!1,this.#r.wecomConnectionState="connecting",this.#r.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#r.ready=!1,this.#r.wecomConnectionState="connecting",this.#r.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof lfe||Q instanceof pfe;!A&&f&&r(Q),f&&(this.#r.ready=!1,this.#r.wecomConnectionState="failed"),this.#r.lastError=f?Q.name:"connection-error",this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},p=Q=>this.#o?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",p);let B;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{a.addEventListener("abort",()=>f(a.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Cfe()),this.#E)})]),this.status}catch(Q){throw a.aborted?(await this.#C(),Q):(this.#r.ready=!1,this.#r.wecomConnectionState="failed",this.#r.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let a=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p=null,await this.#C(),await a?.catch(()=>{}),this.status}async#C(){let a=this.#i,o=this.#o;this.#i=null,this.#o=null;try{a?.disconnect(),a?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#r.ready=!1,this.#r.wecomConnectionState="idle"}};var m3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function dfe(n){if(!Array.isArray(n)||n.length===0)return[...m3];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...m3]}var MQ=class{#e;#A;#t;#a;#g;#n;#E;#s=null;#I=null;#r=0;#i=!1;#o=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=a,this.#A=o,this.#t=i,this.#a=dfe(e),this.#g=Number.isFinite(r)&&r>=0?r:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(a){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},a),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let a=this.#C();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let a=await this.#e.initialize();if(this.#i)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function ffe(n){let a=Zg(n.dshHome??process.env.DSH_HOME??hC(Bfe(),".dsh")),o=Zg(n.dataDir??hC(a,"integrations","dsh-wecom"));return{config:Zg(n.configPath??hC(o,"config.json")),bots:Zg(n.botsDir??hC(o,"bots")),workspaces:Zg(n.workspacesPath??hC(o,"workspaces.json"))}}async function VN(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??BQ,e=o.StateStore??SQ,r=o.HarnessClient??fQ,A=o.Controller??pC,t=o.Runtime??CC,s=o.QrAuth??yQ,g=o.createConnectionSupervisor??qN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=ffe(a),p=await new i(l.config).load(),B=Zg(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ea,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Ya(p,{workspaces:f}):p,R=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),k=new Map,G=T=>Zg(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=Ja(n,o.commandExecutor),H=new r({baseUrl:Qfe(n.webServer,a.harnessBaseUrl),workspace:B,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,secret:U})=>{let b=await K(T);await f.ensure(T);let L=xa(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await ufe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=ja(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import yfe from"qrcode";var D3="/wecom",ba=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:pr}),w3=Object.freeze(Object.values(ba)),mfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function ZN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function KI(n,a){return ZN(n)&&Object.keys(n).every(o=>a.includes(o))}function zN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function S3(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function Sfe(n,a){return ZN(a)?n===ba.status?KI(a,[])?null:"connection.status does not accept fields.":n===ba.beginProvisioning?KI(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[ba.pollProvisioning,ba.cancelProvisioning].includes(n)?KI(a,["attemptId"])&&zN(a.attemptId)?null:`${n} requires an attemptId.`:n===ba.bindCredentials?KI(a,["botId","secret"])&&S3(a.botId,512)&&S3(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===ba.reconnectBot?KI(a,["botId"])&&zN(a.botId)?null:"bot.reconnect requires a botId.":n===ba.deleteBot?KI(a,["botId","confirm"])&&zN(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ba.setWorkspace?Va(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function YI(n){if(Array.isArray(n))return n.map(YI);if(!ZN(n))return n;let a={};for(let[o,i]of Object.entries(n))mfe.has(o)||(a[o]=YI(i));return a}async function Dfe(n){return yfe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function WN(n,a){return!n||typeof n.verificationUrl!="string"?YI(n):YI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function dC(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await WN(o.provisioning,a)),YI(o)}function O3(n,{encodeQr:a=Dfe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!w3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Sfe(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===ba.status)s=await dC(await n.status(),i);else if(e===ba.beginProvisioning)s=await WN(await n.startProvisioning(),i);else if(e===ba.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await WN(g,i)}else if(e===ba.cancelProvisioning)s=YI(await n.cancelProvisioning(r.attemptId));else if(e===ba.bindCredentials)s=await dC(await n.bindCredentials(r),i);else if(e===ba.reconnectBot)s=await dC(await n.reconnectBot(r.botId),i);else if(e===ba.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await dC(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await dC(await n.deleteBot(r.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=za(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function bQ(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(D3,O3(a,o),{authority:qa(i)})}async function M3(n,a={}){if(a?.controller)return bQ(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await VN(n,a,a.internals),i=bQ(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Cye}from"node:fs/promises";import{homedir as hye}from"node:os";import{join as yC,resolve as Xg}from"node:path";import{createHash as Yfe}from"node:crypto";import{mkdir as xfe,readFile as jfe,rename as Jfe,unlink as qfe,writeFile as Vfe}from"node:fs/promises";import{dirname as zfe}from"node:path";import{createDecipheriv as wfe,randomBytes as Ofe,randomUUID as Mfe}from"node:crypto";var NQ="https://ilinkai.weixin.qq.com/",bfe="2.4.6",_fe="3",Nfe="https://novac2c.cdn.weixin.qq.com/c2c",N3="novac2c.cdn.weixin.qq.com",Tfe="bot",Rfe=2<<16|1024|6,kfe=15e3,b3=35e3,vfe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function Ar(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pfe(n){let a=Ar(n);return!a||a.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(a)?null:Buffer.from(a,"base64")}function Gfe(n){let a=Ar(n?.aeskey);if(a){if(!/^[0-9a-fA-F]{32}$/.test(a))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(a,"hex")}let o=Pfe(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function Ffe(n,a){let o=Buffer.from(n),i=Buffer.from(a);if(i.length!==16||o.length===0||o.length%16!==0)throw new qA("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=wfe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new qA("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function Lfe(n){let a=Ar(n?.encrypt_query_param);if(a)return`${Nfe}/download?encrypted_query_param=${encodeURIComponent(a)}`;let o=Ar(n?.full_url);if(!o)throw new qA("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new qA("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==N3||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new qA("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function XN(n,{fetchImpl:a=fetch}={}){if(typeof a!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:r,maxBytes:A})=>{let t=Gfe(e),s=Lfe(e.media),g=await jr(s,{fetchImpl:a,signal:r,maxBytes:A+16,allowedHosts:[N3]});return Ffe(g,t)}})}return o}function $N(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function jI(n){let a;try{a=new URL(n)}catch{throw new qA("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!$N(a.hostname)||a.port!==""&&a.port!=="443")throw new qA("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return a.username="",a.password="",a.search="",a.hash="",a.pathname.endsWith("/")||(a.pathname+="/"),a.toString()}function Ufe(n){let a=Ar(n);if(!a)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(a)}catch{throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!$N(o.hostname))throw new qA("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function T3(){return{"iLink-App-Id":Tfe,"iLink-App-ClientVersion":String(Rfe)}}function Hfe(n){let a={...T3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(Ofe(4).readUInt32BE(0)),"utf8").toString("base64")};return Ar(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function _Q(){return{channel_version:bfe,bot_agent:"DeepSeekHarness/0.9.0"}}function _3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function xI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=kfe,signal:t,authenticated:s=!0}){let g=jI(o),c=new URL(i,g);if(!$N(c.hostname))throw new qA("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,p=!1,B=()=>l.abort(t?.reason);if(t?.aborted)throw _3(t);t?.addEventListener("abort",B,{once:!0});let Q=A>0?setTimeout(()=>{p=!0,l.abort()},A):null;try{let f=await n(c,{method:a,headers:s?Hfe(r):T3(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new qA("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${f.status}\uFF09\u3002`,{status:f.status});try{return await f.json()}catch(y){throw new qA("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?_3(t):p?new qA("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof qA?f:new qA("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",B)}}function Kfe(n){if(!n||typeof n!="object"||!vfe.has(n.status))throw new qA("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function R3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(a){return XN(a,{fetchImpl:n})},async beginLogin({localTokens:a=[],botType:o=_fe,signal:i}={}){let e=[...new Set(a.map(Ar).filter(Boolean))].slice(-10),r=await xI(n,{method:"POST",baseUrl:NQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=Ar(r?.qrcode);if(!A)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Ufe(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=NQ,verifyCode:i,signal:e}){let r=Ar(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;Ar(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await xI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:b3,signal:e,authenticated:!1});return Kfe(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:_Q()},token:o,timeoutMs:e??b3,signal:r})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:a,token:o,toUserId:i,text:e,contextToken:r,runId:A,signal:t}){let s=Ar(i),g=Ar(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Mfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...Ar(r)?{context_token:r.trim()}:{},...Ar(A)?{run_id:A.trim()}:{}},base_info:_Q()}});if(c?.ret!==void 0&&c.ret!==0)throw new qA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:a,token:o,signal:i}){let e=await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:_Q()}});if(e?.ret!==void 0&&e.ret!==0)throw new qA("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:_Q()}})}})}function uC(n){for(let a of n?.item_list??[]){if(a?.type===1&&typeof a.text_item?.text=="string"){let o=a.text_item.text.trim();if(o)return o}if(a?.type===3&&typeof a.voice_item?.text=="string"){let o=a.voice_item.text.trim();if(o)return o}}return null}function e0(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Ar(n?.client_id)}function k3(n,a=4e3){if(n.length<=a)return[n];let o=[],i=n;for(;i.length>a;){let e=i.lastIndexOf(` +`).trim()),a.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function ofe(n){let a=Wg(n);return a.msgtype==="image"?[a.image]:a.msgtype!=="mixed"||!Array.isArray(a.mixed?.msg_item)?[]:a.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function nfe(n,a){let o=hs(a?.url);if(!o)return null;let i=hs(a?.aeskey)??void 0;return{async load({signal:e,maxBytes:r}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let t=A?.buffer;if(!Buffer.isBuffer(t)&&!(t instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(t);if(Number.isFinite(r)&&s.length>r)throw new at("image-too-large",`Enterprise WeChat image exceeds ${r} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function Q3(n,a){return{content:y3(n),images:ofe(n).map(o=>nfe(a,o)).filter(Boolean)}}function sfe(n,a){return wa(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:a,maxBytes:u3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:r=u3}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let t=A?.data??A?.buffer??A;if((Buffer.isBuffer(t)||t instanceof Uint8Array?t.length:0)>r)throw new at("image-too-large",`Enterprise WeChat image exceeds ${r} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function gfe(n){return{...n,images:n.images.map(a=>({...a,async load(){throw new at("image-queue-full",`Enterprise WeChat already has ${f3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function jN(n){return Wg(n).msgtype==="text"?y3(n):""}function wQ(n,a=ife){let o=String(n??"").trim();if(!o)return[];let i=[],e="",r=0;for(let A of o){let t=Buffer.byteLength(A);e&&r+t>a?(i.push(e),e=A,r=t):(e+=A,r+=t)}return e&&i.push(e),i}function cfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function Ife(n,a){return a.questions[a.index]&&hs(Wg(n).from?.userid)===a.actor&&hs(jN(n))}function JN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var OQ=class{#e;#A;#t;#a;#g;#n;#E;#s;#I=new Map;#r=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:a,harness:o,state:i,status:e=JN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=afe,signal:s}){if(!a||typeof a.replyStream!="function"||typeof a.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#l=new lr({label:"wecom",logger:r})}get status(){return structuredClone(this.#a)}accept(a){if(this.#s?.aborted)return Promise.resolve();let o=Wg(a),i=hs(o.msgid),e=hs(o.from?.userid),r=o.chattype==="group"?hs(o.chatid):e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=B3(a);this.#o.add(i);let t=this.#r.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:jN(a),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#r.has(A),send:g=>this.#d(a,r,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(i),this.#c.delete(g)}),this.#c.add(g),g}if(t&&t.actor!==e)return this.#h(a,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(a,i,A);if(t){Ife(a,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(a,i,e,r,A,t)).finally(()=>{this.#o.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===c&&(t.queue=null)});return t.queue=c,c}return this.#h(a,i,A)}#h(a,o,i,{releaseMessageId:e=!0,alreadyRecorded:r=!1}={}){let A=Q3(a,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=f3?(s=t,this.#p+=s,g=sfe(A,this.#s)):g=gfe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(a,{alreadyRecorded:r,preparedMessage:g})).finally(()=>{this.#p-=s,e&&this.#o.delete(o),this.#I.get(i)===l&&this.#I.delete(i)});return this.#I.set(i,l),l}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#r.values()].flatMap(a=>a.queue?[a.queue]:[]),...this.#c])}async#C(a,o){for(let i of wQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#d(a,o,i){this.#s?.throwIfAborted();let e=wQ(i);if(e.length!==0)try{await this.#e.replyStream(a,this.#E("stream"),e[0],!0);for(let r of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#C(o,i)}}async#Q(a,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Wg(a),r=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!r||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(r))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString()}let s=i??Q3(a,this.#e),g=s.content,c=wa(s),l=B3(a),p=null,B=!1;try{if(!g&&!c){await this.#d(a,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(r);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(a,t,rfe),await this.#t.markSeen(r);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(a,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(r);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(a,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(r);return}let f=c?null:await Xr(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(a,t,K);await this.#t.markSeen(r);return}let y=c?null:await Zr(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(a,t,y.message),await this.#t.markSeen(r);return}p=this.#E("stream");try{await this.#e.replyStream(a,p,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),B=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",K)}let m=c?await Jr(s,{signal:this.#s}):void 0,{answer:R}=await Er({harness:this.#A,state:this.#t,key:l,text:g,content:m,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#n,signal:this.#s,onUpdate:B&&typeof this.#e.replyStreamNonBlocking=="function"?async K=>{let x=wQ(cfe(K))[0];x&&await this.#e.replyStreamNonBlocking(a,p,x,!1)}:void 0,onInteraction:K=>this.#B(K,{key:l,actor:A,chatId:t,requiresMention:e.chattype==="group"}),onInteractionResolved:K=>this.#y(K)}}),k=wQ(R||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),G=!1;if(B&&k.length>0)try{await this.#e.replyStream(a,p,k[0],!0);for(let K of k.slice(1))await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:K}});G=!0}catch(K){this.#g.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",K)}G||await this.#C(t,R),await this.#t.markSeen(r),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#a.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=qr(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(a,p,f,!0):await this.#d(a,t,f),await this.#t.markSeen(r)}catch{this.#g.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#N(l),this.#l.closeRoute(l)])}}async#u(a,o,i,e,r,A){if(this.#s?.aborted)return;let t=this.#r.get(r),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(a,o,e):this.#h(a,o,r,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let g=hs(jN(a));if(!g){await this.#d(a,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#r.get(r);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(a,e,DQ).catch(()=>{});return}return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#a.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let p=this.#r.get(r);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(a,e,DQ).catch(()=>{});return}return this.#h(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(Wr(l,g)),c.index+=1,c.index{});return}if(this.#r.get(r)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#a.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(a,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(a,{key:o,actor:i,chatId:e,requiresMention:r}){if(a?.kind==="approval")return this.#l.handleRequested(a,{key:o,actor:i,requiresMention:r,send:c=>this.#C(e,c)});if(a?.kind!=="question")return;let A=a?.payload?.questions,t=typeof a?.interactionId=="string"?a.interactionId:a?.rpcId;if(typeof a?.rpcId!="string"||typeof t!="string"||typeof a.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Vr(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(a.recovered===!0){await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#C(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002").catch(()=>{});return}let s=this.#r.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#f(s);return}if(this.#i.has(t))return;if(s){this.#g.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#r.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(a){if(a?.kind==="approval"){await this.#l.handleResolved(a);return}let o=a?.interactionId;if(a?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(a){if(!a.needsPresentation)return Promise.resolve();if(a.presentationPromise)return a.presentationPromise;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=this.#C(a.chatId,zr(o,a.index,a.questions.length,{requiresMention:a.requiresMention})).then(()=>{a.needsPresentation=!1}).finally(()=>{a.presentationPromise===i&&(a.presentationPromise=null)});return a.presentationPromise=i,i}async#D(a,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString(),await this.#d(a,i,DQ).catch(()=>{}))}#m(a,o){let i=this.#r.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#r.delete(a),this.#i.delete(i.interactionId),i)}#w(a,o){return this.#m(a,o)!==null}async#N(a){let o=this.#m(a);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#g.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function Cfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function hfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...JN()}}var CC=class{#e;#A;#t;#a;#g;#n;#E;#s;#I;#r=hfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:a,secret:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Efe(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#r)}async start(){if(this.#r.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let a=new AbortController;return this.#l=a,this.#p=a,this.#c=this.#h(a.signal).finally(()=>{this.#l===a&&(this.#l=null),this.#c=null}),this.#c}async#h(a){await this.#C(),a.throwIfAborted(),this.#r.startedAt=new Date().toISOString(),this.#r.wecomConnectionState="connecting",this.#r.lastError=null,await this.#t.ensureRunning(),this.#r.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#s});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#i=i,this.#o=new OQ({client:i,harness:this.#t,state:this.#a,status:this.#r,logger:this.#g,replyTimeoutMs:this.#n,signal:a});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#i!==i||a.aborted)return;A=!0;let Q=Date.now();this.#r.ready=!0,this.#r.wecomConnectionState="connected",this.#r.lastCheckedAt=Q,this.#r.lastConnectedAt=Q,this.#r.lastError=null,e()},g=()=>{this.#i===i&&(this.#r.ready=!1,this.#r.wecomConnectionState="connecting",this.#r.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#r.ready=!1,this.#r.wecomConnectionState="connecting",this.#r.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof lfe||Q instanceof pfe;!A&&f&&r(Q),f&&(this.#r.ready=!1,this.#r.wecomConnectionState="failed"),this.#r.lastError=f?Q.name:"connection-error",this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},p=Q=>this.#o?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",p);let B;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{a.addEventListener("abort",()=>f(a.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Cfe()),this.#E)})]),this.status}catch(Q){throw a.aborted?(await this.#C(),Q):(this.#r.ready=!1,this.#r.wecomConnectionState="failed",this.#r.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let a=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#p=null,await this.#C(),await a?.catch(()=>{}),this.status}async#C(){let a=this.#i,o=this.#o;this.#i=null,this.#o=null;try{a?.disconnect(),a?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#r.ready=!1,this.#r.wecomConnectionState="idle"}};var m3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function dfe(n){if(!Array.isArray(n)||n.length===0)return[...m3];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...m3]}var MQ=class{#e;#A;#t;#a;#g;#n;#E;#s=null;#I=null;#r=0;#i=!1;#o=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=a,this.#A=o,this.#t=i,this.#a=dfe(e),this.#g=Number.isFinite(r)&&r>=0?r:15e3,this.#n=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#o||this.#i?this:(this.#o=!0,this.#p(0),this)}async close(){this.#i||(this.#i=!0,this.#s!==null&&this.#E(this.#s),this.#s=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#p(a){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},a),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let a=this.#C();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let a=await this.#e.initialize();if(this.#i)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function ffe(n){let a=Zg(n.dshHome??process.env.DSH_HOME??hC(Bfe(),".dsh")),o=Zg(n.dataDir??hC(a,"integrations","dsh-wecom"));return{config:Zg(n.configPath??hC(o,"config.json")),bots:Zg(n.botsDir??hC(o,"bots")),workspaces:Zg(n.workspacesPath??hC(o,"workspaces.json"))}}async function VN(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??BQ,e=o.StateStore??SQ,r=o.HarnessClient??fQ,A=o.Controller??pC,t=o.Runtime??CC,s=o.QrAuth??yQ,g=o.createConnectionSupervisor??qN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=ffe(a),p=await new i(l.config).load(),B=Zg(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ea,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:B}).load(),y=p.list();await f.reconcile(y.map(T=>T.botId)),await Promise.all(y.map(T=>f.ensure(T.botId)));let m=typeof p.remove=="function"?Ya(p,{workspaces:f}):p,R=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),k=new Map,G=T=>Zg(l.bots,T,"state.json"),K=async T=>{let V=k.get(T);return V||(V=await new e(G(T)).load(),k.set(T,V)),V},x=Ja(n,o.commandExecutor),H=new r({baseUrl:Qfe(n.webServer,a.harnessBaseUrl),workspace:B,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh",...x?{commandExecutor:x}:{}}),q=new A({qrAuth:R,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:T,config:V,secret:U})=>{let b=await K(T);await f.ensure(T);let L=xa(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...X)=>c.error?.(`[${T}]`,...X),warn:(...X)=>c.warn?.(`[${T}]`,...X),info:(...X)=>c.info?.(`[${T}]`,...X),debug:(...X)=>c.debug?.(`[${T}]`,...X)}})},deleteState:async({botId:T})=>{let V=k.get(T);if(k.delete(T),V&&typeof V.remove=="function")await V.remove();else try{await ufe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=ja(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import yfe from"qrcode";var D3="/wecom",ba=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:pr}),w3=Object.freeze(Object.values(ba)),mfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function ZN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function KI(n,a){return ZN(n)&&Object.keys(n).every(o=>a.includes(o))}function zN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function S3(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function Sfe(n,a){return ZN(a)?n===ba.status?KI(a,[])?null:"connection.status does not accept fields.":n===ba.beginProvisioning?KI(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[ba.pollProvisioning,ba.cancelProvisioning].includes(n)?KI(a,["attemptId"])&&zN(a.attemptId)?null:`${n} requires an attemptId.`:n===ba.bindCredentials?KI(a,["botId","secret"])&&S3(a.botId,512)&&S3(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===ba.reconnectBot?KI(a,["botId"])&&zN(a.botId)?null:"bot.reconnect requires a botId.":n===ba.deleteBot?KI(a,["botId","confirm"])&&zN(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ba.setWorkspace?Va(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function YI(n){if(Array.isArray(n))return n.map(YI);if(!ZN(n))return n;let a={};for(let[o,i]of Object.entries(n))mfe.has(o)||(a[o]=YI(i));return a}async function Dfe(n){return yfe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function WN(n,a){return!n||typeof n.verificationUrl!="string"?YI(n):YI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function dC(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await WN(o.provisioning,a)),YI(o)}function O3(n,{encodeQr:a=Dfe}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!w3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Sfe(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===ba.status)s=await dC(await n.status(),i);else if(e===ba.beginProvisioning)s=await WN(await n.startProvisioning(),i);else if(e===ba.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await WN(g,i)}else if(e===ba.cancelProvisioning)s=YI(await n.cancelProvisioning(r.attemptId));else if(e===ba.bindCredentials)s=await dC(await n.bindCredentials(r),i);else if(e===ba.reconnectBot)s=await dC(await n.reconnectBot(r.botId),i);else if(e===ba.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await dC(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await dC(await n.deleteBot(r.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=za(s);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:g??{code:"wecom-operation-failed",message:"\u4F01\u4E1A\u5FAE\u4FE1\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}}}function bQ(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(D3,O3(a,o),{authority:qa(i)})}async function M3(n,a={}){if(a?.controller)return bQ(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await VN(n,a,a.internals),i=bQ(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Cye}from"node:fs/promises";import{homedir as hye}from"node:os";import{join as yC,resolve as Xg}from"node:path";import{createHash as Yfe}from"node:crypto";import{mkdir as xfe,readFile as jfe,rename as Jfe,unlink as qfe,writeFile as Vfe}from"node:fs/promises";import{dirname as zfe}from"node:path";import{createDecipheriv as wfe,randomBytes as Ofe,randomUUID as Mfe}from"node:crypto";var NQ="https://ilinkai.weixin.qq.com/",bfe="2.4.6",_fe="3",Nfe="https://novac2c.cdn.weixin.qq.com/c2c",N3="novac2c.cdn.weixin.qq.com",Tfe="bot",Rfe=2<<16|1024|6,kfe=15e3,b3=35e3,vfe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function Ar(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pfe(n){let a=Ar(n);return!a||a.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(a)?null:Buffer.from(a,"base64")}function Gfe(n){let a=Ar(n?.aeskey);if(a){if(!/^[0-9a-fA-F]{32}$/.test(a))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(a,"hex")}let o=Pfe(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function Ffe(n,a){let o=Buffer.from(n),i=Buffer.from(a);if(i.length!==16||o.length===0||o.length%16!==0)throw new qA("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=wfe("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new qA("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function Lfe(n){let a=Ar(n?.encrypt_query_param);if(a)return`${Nfe}/download?encrypted_query_param=${encodeURIComponent(a)}`;let o=Ar(n?.full_url);if(!o)throw new qA("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new qA("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==N3||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new qA("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function XN(n,{fetchImpl:a=fetch}={}){if(typeof a!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:r,maxBytes:A})=>{let t=Gfe(e),s=Lfe(e.media),g=await jr(s,{fetchImpl:a,signal:r,maxBytes:A+16,allowedHosts:[N3]});return Ffe(g,t)}})}return o}function $N(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function jI(n){let a;try{a=new URL(n)}catch{throw new qA("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!$N(a.hostname)||a.port!==""&&a.port!=="443")throw new qA("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return a.username="",a.password="",a.search="",a.hash="",a.pathname.endsWith("/")||(a.pathname+="/"),a.toString()}function Ufe(n){let a=Ar(n);if(!a)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(a)}catch{throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!$N(o.hostname))throw new qA("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function T3(){return{"iLink-App-Id":Tfe,"iLink-App-ClientVersion":String(Rfe)}}function Hfe(n){let a={...T3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(Ofe(4).readUInt32BE(0)),"utf8").toString("base64")};return Ar(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function _Q(){return{channel_version:bfe,bot_agent:"DeepSeekHarness/0.10.0"}}function _3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function xI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=kfe,signal:t,authenticated:s=!0}){let g=jI(o),c=new URL(i,g);if(!$N(c.hostname))throw new qA("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,p=!1,B=()=>l.abort(t?.reason);if(t?.aborted)throw _3(t);t?.addEventListener("abort",B,{once:!0});let Q=A>0?setTimeout(()=>{p=!0,l.abort()},A):null;try{let f=await n(c,{method:a,headers:s?Hfe(r):T3(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new qA("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${f.status}\uFF09\u3002`,{status:f.status});try{return await f.json()}catch(y){throw new qA("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?_3(t):p?new qA("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof qA?f:new qA("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",B)}}function Kfe(n){if(!n||typeof n!="object"||!vfe.has(n.status))throw new qA("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function R3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(a){return XN(a,{fetchImpl:n})},async beginLogin({localTokens:a=[],botType:o=_fe,signal:i}={}){let e=[...new Set(a.map(Ar).filter(Boolean))].slice(-10),r=await xI(n,{method:"POST",baseUrl:NQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=Ar(r?.qrcode);if(!A)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Ufe(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=NQ,verifyCode:i,signal:e}){let r=Ar(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;Ar(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await xI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:b3,signal:e,authenticated:!1});return Kfe(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:_Q()},token:o,timeoutMs:e??b3,signal:r})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:a,token:o,toUserId:i,text:e,contextToken:r,runId:A,signal:t}){let s=Ar(i),g=Ar(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Mfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...Ar(r)?{context_token:r.trim()}:{},...Ar(A)?{run_id:A.trim()}:{}},base_info:_Q()}});if(c?.ret!==void 0&&c.ret!==0)throw new qA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:a,token:o,signal:i}){let e=await xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:_Q()}});if(e?.ret!==void 0&&e.ret!==0)throw new qA("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return xI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:_Q()}})}})}function uC(n){for(let a of n?.item_list??[]){if(a?.type===1&&typeof a.text_item?.text=="string"){let o=a.text_item.text.trim();if(o)return o}if(a?.type===3&&typeof a.voice_item?.text=="string"){let o=a.voice_item.text.trim();if(o)return o}}return null}function e0(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Ar(n?.client_id)}function k3(n,a=4e3){if(n.length<=a)return[n];let o=[],i=n;for(;i.length>a;){let e=i.lastIndexOf(` `,a);er===null))return null;let o=new Set,i=new Set,e=new Set;for(let r of a){if(o.has(r.botId)||i.has(r.accountId)||e.has(r.tokenRef))return null;o.add(r.botId),i.add(r.accountId),e.add(r.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(a)})}var TQ=class{#e;#A=A0;#t=Promise.resolve();constructor(a){this.#e=a}async load(){try{let a=Zfe(JSON.parse(await jfe(this.#e,"utf8")));if(!a)throw new Error("dsh-weixin config contains invalid account data");this.#A=a}catch(a){if(a?.code!=="ENOENT")throw a;this.#A=A0}return this}list(){return structuredClone(this.#A.accounts)}get(a){let o=this.#A.accounts.find(i=>i.botId===a);return o?structuredClone(o):null}getByAccountId(a){let o=this.#A.accounts.find(i=>i.accountId===a);return o?structuredClone(o):null}async save(a){let o=G3(a);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#a(i=>{let e=i.find(t=>t.accountId===o.accountId&&t.botId!==o.botId),r=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||r)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(a){if(!v3(a))throw new TypeError("Invalid Weixin bot id");return this.#a(o=>{let i=o.findIndex(r=>r.botId===a);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let a=this.#t.then(async()=>{try{await qfe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=A0});this.#t=a.then(()=>{},()=>{}),await a}async#a(a){let o,i=this.#t.then(async()=>{let e=[...this.#A.accounts];o=a(e);let r=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#g(r),this.#A=r});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(a){await xfe(zfe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await Vfe(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await Jfe(o,this.#e)}};var RQ=class extends jt{constructor(a){super({...a,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as Xfe,readFile as $fe,rename as eye,unlink as Aye,writeFile as tye}from"node:fs/promises";import{dirname as aye}from"node:path";var kQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function rye(n){if(!n||typeof n!="object")return structuredClone(kQ);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:""}}var vQ=class{#e;#A=structuredClone(kQ);#t=Promise.resolve();constructor(a){this.#e=a}async load(){try{this.#A=rye(JSON.parse(await $fe(this.#e,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#A=structuredClone(kQ),await this.#a()}return this}sessionFor(a){return this.#A.sessions[a]??null}async setSession(a,o){this.#A.sessions[a]=o,await this.#a()}async clearSession(a){delete this.#A.sessions[a],await this.#a()}async clearSessions(){this.#A.sessions={},await this.#a()}hasSeen(a){return this.#A.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#A.seenMessageIds.push(a),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#a())}getUpdatesBuf(){return this.#A.getUpdatesBuf}async setGetUpdatesBuf(a){typeof a!="string"||a===this.#A.getUpdatesBuf||(this.#A.getUpdatesBuf=a,await this.#a())}snapshot(){return structuredClone(this.#A)}async remove(){try{await Aye(this.#e)}catch(a){if(a?.code!=="ENOENT")throw a}this.#A=structuredClone(kQ)}async#a(){let a=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await Xfe(aye(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await tye(i,a,{encoding:"utf8",mode:384}),await eye(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as iye}from"node:crypto";var F3=new Set(["starting","pending","scanned","needs_verification","connecting"]),PQ=new Set(["connected","expired","failed","cancelled"]),L3=5*6e4;function JI(n){return typeof n=="string"&&n.trim()?n.trim():null}function oye(){return new DOMException("Provisioning was cancelled","AbortError")}function U3(n,a){let o=JI(n);return o?jI(o.includes("://")?o:`https://${o}`):jI(a)}function BC(n){return n?{attemptId:n.id,status:n.state,...n.verificationUrl?{verificationUrl:n.verificationUrl}:{},...n.expiresAt?{expiresAt:n.expiresAt}:{},pollIntervalMs:1e3,...n.state==="needs_verification"?{verificationRequired:!0}:{},...n.botId?{botId:n.botId}:{},...n.alreadyConnected?{alreadyConnected:!0}:{},...n.error?{error:structuredClone(n.error)}:{}}:null}function Gr(n,a){return Object.freeze({code:n,message:a})}var QC=class{#e;#A;#t;#a;#g;#n;#E=new Map;#s=new Map;#I=new Map;#r=null;#i=new Map;#o=0;#c=!1;constructor({api:a,credentials:o,configStore:i,createRuntime:e,deleteState:r=async()=>{},logger:A=console}){if(!a||typeof a.beginLogin!="function"||typeof a.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=a,this.#A=o,this.#t=i,this.#a=e,this.#g=r,this.#n=A}async initialize(){if(this.#c)return this.status();for(let a of this.#t.list())this.#E.get(a.botId)?.status?.ready!==!0&&await this.#B(a.botId,async()=>{let i=this.#t.get(a.botId);if(!(!i||this.#c))try{let e=await this.#d(i.tokenRef);if(!e){this.#s.set(i.botId,Gr("missing-token","\u767B\u5F55\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u8D26\u53F7\u540E\u91CD\u65B0\u626B\u7801\u3002"));return}await this.#h(i,e),this.#s.delete(i.botId)}catch(e){this.#s.set(i.botId,Gr("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#n.warn?.(`[dsh-weixin] account ${i.botId} failed to initialize:`,e)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("dsh-weixin controller is closed");this.#r&&await this.cancelProvisioning(this.#r);let a={id:iye(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+L3,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:NQ,error:null,botId:null,task:null};this.#I.set(a.id,a),this.#r=a.id,this.#f();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#d(e.tokenRef)))).filter(Boolean),i=await this.#e.beginLogin({localTokens:o,signal:a.controller.signal});return this.#u(a),a.qrcode=i.qrcode,a.verificationUrl=i.qrcodeUrl,a.state="pending",a.expiresAt=Date.now()+L3,this.#f(),a.task=this.#l(a),BC(a)}catch(o){throw a.controller.signal.aborted?(a.state="cancelled",a.error=Gr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=Gr(o instanceof qA?o.code:"qr-start-failed",o instanceof qA?o.message:"\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#r===a.id&&(this.#r=null),this.#f(),o}}registrationStatus(a){return BC(this.#I.get(a))}async submitVerification(a,o){let i=this.#I.get(a);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=JI(o);if(!e||!/^\d{4,8}$/.test(e))throw new TypeError("Verification code must contain 4 to 8 digits");return i.pendingVerifyCode=e,i.state="scanned",i.verifyResolve?.(),i.verifyResolve=null,this.#f(),BC(i)}async cancelProvisioning(a){let o=this.#I.get(a);return o?(PQ.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),PQ.has(o.state)||(o.state="cancelled"),o.error??=Gr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#r===o.id&&(this.#r=null),this.#f(),BC(o)):null}async reconnectBot(a){let o=this.#t.get(a);if(!o)throw new Error("Unknown Weixin account");return await this.#B(a,async()=>{let i=await this.#d(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#s.delete(a)}catch(e){throw this.#s.set(a,Gr("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async deleteBot(a){let o=this.#t.get(a);if(!o)throw new Error("Unknown Weixin account");return await this.#B(a,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#C(a);try{await this.#A.unset(o.tokenRef),await this.#t.remove(a)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the Weixin account safely.",{cause:e})}try{await this.#g({botId:a,config:o})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${a} state cleanup failed:`,e)}this.#s.delete(a),this.#f()}),this.status()}status(){let a=this.#t.list().map(e=>{let r=this.#E.get(e.botId)?.status??null,A=r?.ready===!0&&r.weixinConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.weixinConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||r?.weixinConnectionState==="failed"?"error":"offline",s=this.#s.get(e.botId)??(t==="error"?Gr("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"):null);return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u5FAE\u4FE1\u673A\u5668\u4EBA",accountIdMasked:P3(e.accountId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:r?.lastCheckedAt??null},stats:{messagesReceived:r?.messagesReceived??0,messagesReplied:r?.messagesReplied??0},error:s?structuredClone(s):null}}),o=a.filter(e=>e.connected).length,i=this.#r?this.#I.get(this.#r):null;return{schemaVersion:1,revision:this.#o,state:i&&F3.has(i.state)?"provisioning":a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o},...i&&F3.has(i.state)?{provisioning:BC(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#r&&await this.cancelProvisioning(this.#r),await Promise.allSettled([...this.#E.keys()].map(a=>this.#C(a))))}async#l(a){try{for(;!a.controller.signal.aborted&&Date.now(){a.verifyResolve=i,a.controller.signal.aborted&&i()}),a.verifyResolve=null,this.#u(a));let o=await this.#e.pollLogin({qrcode:a.qrcode,baseUrl:a.currentBaseUrl,verifyCode:a.pendingVerifyCode,signal:a.controller.signal});if(this.#u(a),o.status==="wait")a.state="pending";else if(o.status==="scaned")a.pendingVerifyCode=null,a.state="scanned";else if(o.status==="need_verifycode")a.pendingVerifyCode=null,a.state="needs_verification";else if(o.status==="verify_code_blocked"){a.state="failed",a.error=Gr("verification-blocked","\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002");break}else if(o.status==="expired"){a.state="expired",a.error=Gr("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002");break}else if(o.status==="scaned_but_redirect")a.currentBaseUrl=U3(o.redirect_host,a.currentBaseUrl),a.state="scanned";else if(o.status==="binded_redirect"){let i=this.#t.list().find(e=>this.#E.get(e.botId)?.status?.ready===!0)??this.#t.list()[0];i?(a.state="connected",a.botId=i.botId,a.alreadyConnected=!0):(a.state="failed",a.error=Gr("already-bound","\u8BE5\u5FAE\u4FE1\u8D26\u53F7\u5DF2\u7ED1\u5B9A\uFF0C\u4F46\u672C\u673A\u6CA1\u6709\u53EF\u6062\u590D\u7684\u51ED\u636E\u3002"));break}else if(o.status==="confirmed"){let i=JI(o.bot_token),e=JI(o.ilink_bot_id),r=JI(o.ilink_user_id);if(!i||!e||!r)throw new qA("incomplete-login","\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002");a.state="connecting",this.#f();let A=U3(o.baseurl,a.currentBaseUrl);a.botId=await this.#p(a,{token:i,accountId:e,ownerUserId:r,baseUrl:A}),a.state="connected",a.error=null;break}this.#f()}!a.controller.signal.aborted&&Date.now()>=a.expiresAt&&!PQ.has(a.state)&&(a.state="expired",a.error=Gr("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"))}catch(o){a.controller.signal.aborted||o?.name==="AbortError"?(a.state="cancelled",a.error=Gr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=Gr(o instanceof qA?o.code:"activation-failed",o instanceof qA?o.message:"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u51ED\u636E\u6216\u542F\u52A8\u6D88\u606F\u8FDE\u63A5\u3002"),this.#n.error?.("[dsh-weixin] provisioning failed:",o))}finally{a.pendingVerifyCode=null,a.verifyResolve?.(),a.verifyResolve=null,this.#r===a.id&&(this.#r=null),this.#f(),this.#y()}}async#p(a,{token:o,accountId:i,ownerUserId:e,baseUrl:r}){let A=t0(i),t=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:r,createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g=await this.#A.resolve(A.tokenRef).catch(()=>{});return this.#B(A.botId,async()=>{await this.#A.set(A.tokenRef,o);try{return this.#u(a),await this.#t.save(s),this.#u(a),await this.#h(s,o),this.#u(a),this.#s.delete(A.botId),this.#f(),A.botId}catch(c){throw await this.#C(A.botId),t?await this.#t.save(t).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.remove(A.botId).catch(()=>null)&&await this.#g({botId:A.botId,config:s}).catch(p=>{this.#n.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",p)}),await this.#Q(A.tokenRef,g),t&&g?.value&&await this.#h(t,g.value).catch(()=>{}),c}})}async#h(a,o){await this.#C(a.botId);let i=await this.#a({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Weixin runtime");try{await i.start(),this.#E.set(a.botId,i)}catch(e){throw await i.stop().catch(()=>{}),e}}async#C(a){let o=this.#E.get(a);this.#E.delete(a),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-weixin] account ${a} failed to stop cleanly:`,i)})}async#d(a){let o=await this.#A.resolve(a).catch(()=>{});return JI(o?.value)}async#Q(a,o){try{o?.value?await this.#A.set(a,o.value):await this.#A.unset(a)}catch(i){this.#n.error?.(`[dsh-weixin] failed to restore credential ${a}:`,i)}}#u(a){if(a.controller.signal.aborted||this.#r!==a.id)throw oye()}#B(a,o){let r=(this.#i.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(a)===r&&this.#i.delete(a)});return this.#i.set(a,r),r}#y(){for(let[a,o]of this.#I)a!==this.#r&&PQ.has(o.state)&&this.#I.size>16&&this.#I.delete(a)}#f(){this.#o+=1}};var GQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",nye=["\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` diff --git a/package-lock.json b/package-lock.json index 46ca5a6..f54eb19 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@xmanrui/dsh-im", - "version": "0.9.0", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@xmanrui/dsh-im", - "version": "0.9.0", + "version": "0.10.0", "license": "MIT", "dependencies": { "@tencent-connect/qqbot-connector": "1.2.0", diff --git a/package.json b/package.json index cd52848..2dc22ff 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@xmanrui/dsh-im", - "version": "0.9.0", + "version": "0.10.0", "description": "通过扫码、App Manifest或机器人凭据把IM机器人接入DeepSeek Harness(支持飞书、微信、钉钉、企业微信、QQ、Slack、Telegram、Discord和WhatsApp)。", "license": "MIT", "type": "module", diff --git a/src/channels/discord/discord-api.mjs b/src/channels/discord/discord-api.mjs index e4163c4..2919209 100644 --- a/src/channels/discord/discord-api.mjs +++ b/src/channels/discord/discord-api.mjs @@ -108,7 +108,7 @@ export class DiscordApi { headers: { authorization: `Bot ${this.#token}`, 'content-type': 'application/json', - 'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.9.0)', + 'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.10.0)', }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: requestSignal(signal, timeoutMs), diff --git a/src/channels/weixin/weixin-api.mjs b/src/channels/weixin/weixin-api.mjs index 33f1a4d..ff2fa05 100644 --- a/src/channels/weixin/weixin-api.mjs +++ b/src/channels/weixin/weixin-api.mjs @@ -184,7 +184,7 @@ function authenticatedHeaders(token) { function baseInfo() { return { channel_version: WEIXIN_PROTOCOL_VERSION, - bot_agent: 'DeepSeekHarness/0.9.0', + bot_agent: 'DeepSeekHarness/0.10.0', }; } diff --git a/test/channels/weixin/weixin-api.test.mjs b/test/channels/weixin/weixin-api.test.mjs index 3122cb5..5688bc4 100644 --- a/test/channels/weixin/weixin-api.test.mjs +++ b/test/channels/weixin/weixin-api.test.mjs @@ -167,7 +167,7 @@ test('sendText emits the iLink message envelope without reflecting the token in assert.equal(body.msg.context_token, 'message-context'); assert.equal(body.msg.item_list[0].text_item.text, 'Harness reply'); assert.equal(body.base_info.channel_version, '2.4.6'); - assert.equal(body.base_info.bot_agent, 'DeepSeekHarness/0.9.0'); + assert.equal(body.base_info.bot_agent, 'DeepSeekHarness/0.10.0'); assert.doesNotMatch(calls[0].init.body, /host-only-token/); });