From ffdf92ead699a8e1db80ecf7e32094f9aa8cb160 Mon Sep 17 00:00:00 2001 From: xmanrui <841206367@qq.com> Date: Wed, 19 Aug 2026 12:43:37 +0800 Subject: [PATCH] release: prepare dsh-im 0.11.0 --- lib/index.js | 4 ++-- package-lock.json | 4 ++-- package.json | 2 +- src/channels/discord/discord-api.mjs | 2 +- src/channels/weixin/weixin-api.mjs | 2 +- test/channels/weixin/weixin-api.test.mjs | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/index.js b/lib/index.js index 7ceda50..b7f70c1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -85,7 +85,7 @@ ${eG}`:["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=ate(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}},As=class extends Error{constructor(r,o){super(`${r}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=r,this.code=o?.code??"internal",this.details=o?.details??{}}},zc=class extends Error{constructor(r,o){super(o),this.name="HarnessInteractionError",this.code=r}},qt=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i;#o=null;#c;#l;#p;constructor({baseUrl:r,workspace:o,agentPreset:i,autostart:e=!1,dshBin:a="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(r),this.#A=o,this.#t=i??void 0,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g.trim(),this.#a=c.trim(),this.#i=l,this.#c=XAe(this.#e.origin),this.#l=this.#c.ownerships,this.#p=this.#c.claims}async rpc(r,o={},i=3e4,e={}){let a=e.rpcId??`${this.#I}-${oG()}`,A=AbortSignal.timeout(i),t=e.signal?AbortSignal.any([e.signal,A]):A,s=await this.#n(new URL(`/api/${r}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:r,payload:o}),signal:t});if(!s.ok)throw new Error(`Harness transport ${r} failed: HTTP ${s.status}`);let g=await s.json();if(g?.type!=="server-response"||g?.rpcId!==a)throw new Error(`Harness returned an invalid response for ${r}`);if(!g.result?.ok)throw new As(r,g.result?.error);return g.result.value}async health(r={}){return await this.rpc("host.describe",{},5e3,r),!0}async ensureRunning(r={}){try{return await this.health(r)}catch(e){if(!this.#r)throw e}if(!this.#o||this.#o.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#o=WAe(this.#g,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#A,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#o.on("error",a=>{console.error(`[${this.#a}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(r={}){await this.ensureRunning(r);let i={workspaceId:await this.workspaceId(r)};return this.#t!==void 0&&(i.agentPreset=this.#t),(await this.rpc("session.create",i,3e4,r)).sessionId}async executeCommand(r,o,i={}){if(typeof r!="string"||!r)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(r,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new As("commands.execute",e.failure):e}}async sessionExists(r,o={}){try{return await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof As&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(r,o,i={}){if(typeof r!="string"||!r)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),a=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:r,result:o}),signal:a});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 zc(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof r!="string"||!r)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(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(t){if(o.aborted)return;console.warn(`[${this.#a}] Harness interaction stream disconnected:`,t.message)}if(o.aborted)return;try{await wd(this.#s,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#h(r,o){let i=this.#l.get(r)??new Set;o.order=this.#c.nextOrder,this.#c.nextOrder+=1,i.add(o),this.#l.set(r,i)}#C(r,o){let i=this.#l.get(r);i?.delete(o),i?.size===0&&this.#l.delete(r);for(let[e,a]of this.#p)a.ownership===o&&this.#p.delete(e)}#d(r,o){for(let i of this.#l.get(r)??[])ite(i,o)}async#Q(r,o){let i=await this.rpc("session.history",{sessionId:r,maxMessages:50},3e4,{signal:o});this.#d(r,i.events??[])}#u(r,o,i){let e=this.#p.get(o);if(e&&this.#l.get(r)?.has(e.ownership))return e;let a=[...this.#l.get(r)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let t=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return t?{ownership:t,recovered:!0}:null}async ask(r,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=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:a});let g=await this.rpc("session.history",{sessionId:r,maxMessages:1},3e4,{signal:a}),c=Math.max(-1,...(g.events??[]).map(({event:m})=>m.seq??-1)),l=`${this.#I}-${oG()}`,p=new Vc({promptRpcId:l,afterSeq:c}),B=t||s?new AbortController:null,Q=B?a?AbortSignal.any([a,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(r,f);try{if(Q){let k,G=new Promise(K=>{k=K});y=this.watchInteractions(r,{signal:Q,onInteraction:t,onResolved:s,onOpen:k,ownership:f}),y.catch(()=>{}),await Promise.race([G,wd(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:r,mode:"queue",content:m,clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:l,signal:a});let R=Date.now()+e;for(;Date.now(){}),f&&this.#C(r,f)}}#B(r,{signal:o,onInteraction:i,onResolved:e,onOpen:a,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{a?.()}catch(F){console.warn(`[${this.#a}] ignored an interaction open callback failure:`,F.message)}A&&this.#Q(r,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(r,[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(r,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:r,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:r,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!==r)return;f?K(T):y.push(T)}catch(T){console.warn(`[${this.#a}] 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 Od=class extends qt{constructor(r){super({...r,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as ote}from"node:crypto";import{mkdir as nte,readFile as ste,rename as gte,unlink as cte,writeFile as Ite}from"node:fs/promises";import{dirname as lte}from"node:path";var Md=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function Pt(n){return typeof n=="string"&&n.trim()?n.trim():null}function sG(n){return(Pt(n)??"\u9489\u9489\u7528\u6237").slice(0,100)}function Ete(n,r){if(!n||typeof n!="object")return null;let o=Pt(n.requestId)??Pt(r),i=Pt(n.staffId),e=Pt(n.requestedAt)??Pt(n.lastSeenAt),a=Pt(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:sG(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function pte(n){if(!n||typeof n!="object")return structuredClone(Md);let r={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=Pt(e),t=Pt(a);A&&t&&(r[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,a]of i){let A=Ete(a,e);if(!A)continue;let t=Object.values(o).find(s=>s.staffId===A.staffId);(!t||t.lastSeenAtnew Date().toISOString()}={}){if(!Pt(r))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=r,this.#r=o,this.#g=i}async load(){try{this.#A=pte(JSON.parse(await ste(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(Md),await this.#n()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){let i=Pt(r),e=Pt(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#n()}async clearSession(r){let o=Pt(r);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#n())}async clearSessions(){this.#A.sessions={},await this.#n()}hasSeen(r){let o=Pt(r);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(r){let o=Pt(r);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((r,o)=>r.requestedAt.localeCompare(o.requestedAt)).map(r=>structuredClone(r))}pendingSender(r){let o=Pt(r),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(r,o,i){let e=r&&typeof r=="object"?r:{staffId:r,displayName:o,lastSeenAt:i},a=Pt(e.staffId);if(!a)throw new TypeError("staffId is required");let A=Pt(e.lastSeenAt)??Pt(e.requestedAt)??this.#g(),t=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:t?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:sG(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(r){let o=Pt(r);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#n(),!0)}async removePendingSenderByStaffId(r){let o=Pt(r),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 cte(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(Md)}async#n(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await nte(lte(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Ite(i,r,{encoding:"utf8",mode:384}),await gte(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{mkdir as Cte,readFile as hte,realpath as dte,rename as ute,stat as Bte,unlink as Qte,writeFile as fte}from"node:fs/promises";import{dirname as yte,isAbsolute as IG,resolve as RE}from"node:path";var eUe=Object.freeze({version:1,workspaces:Object.freeze({})});function _d(n){let r=new Error(n);return r.code=on,r}async function ID(n){return RE(await dte(n))}async function mte(n,r){if(n===r)return!0;try{return await ID(n)===await ID(r)}catch{return!1}}function ai(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function Ste(n){if(!n||n.version!==1||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let r={};for(let[o,i]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(o)||typeof i!="string"||!IG(i))return null;r[o]=RE(i)}return{version:1,workspaces:r}}async function gG(n){if(typeof n!="string"||!n.trim()||!IG(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 r=RE(n.trim()),o;try{o=await Bte(r)}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 r}var Cr=class{#e;#A;#t={};#r=new Map;#g=1;#n=new Map;#E=1;#s=new Map;#I=new WeakMap;#a=new Set;#i=Promise.resolve();#o=new Map;constructor(r,{defaultWorkspace:o=process.cwd()}={}){if(typeof r!="string"||!r)throw new TypeError("workspace store path is required");this.#e=r,this.#A=RE(o)}async load(){try{let r=Ste(JSON.parse(await hte(this.#e,"utf8")));if(!r)throw new Error("dsh-im workspace config is invalid");this.#t=r.workspaces}catch(r){if(r?.code!=="ENOENT")throw r;this.#t={}}this.#r.clear(),this.#g=1,this.#n.clear(),this.#E=1,this.#s.clear(),this.#a.clear();for(let r of Object.keys(this.#t))this.#r.set(r,this.#c()),this.#n.set(r,this.#l());return this}has(r){let o=ai(r);return Object.hasOwn(this.#t,o)&&!this.#s.has(o)}incarnationFor(r){return this.#n.get(ai(r))??null}workspaceFor(r){return this.#t[ai(r)]??this.#A}generationFor(r){return this.#r.get(ai(r))??null}async whenIdle(){await this.#i}async whenBotIdle(r){let o=ai(r);for(;;){let i=this.#o.get(o);if(!i||(await i,this.#o.get(o)===i))return}}async ensure(r,{workspace:o=this.#A}={}){let i=ai(r),e=RE(o);return this.#C(i,async()=>{if(this.#t[i])this.#r.has(i)||this.#r.set(i,this.#c());else{this.#t[i]=e,this.#r.set(i,this.#c()),this.#n.set(i,this.#l());try{await this.#d()}catch(a){throw delete this.#t[i],this.#r.delete(i),this.#n.delete(i),a}}return this.#t[i]})}async setWorkspace(r,o,{clearSessions:i,incarnation:e}={}){let a=ai(r);if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){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 gG(o);return this.#C(a,async()=>{if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){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(a))return A;let t=this.#t[a];this.#r.set(a,this.#c()),await i?.(),this.#t[a]=A;try{await this.#d()}catch(s){throw this.#t[a]=t,s}return A})}async bindWorkspaceSession(r,o,{conversationKey:i,sessionId:e,clearSessions:a,setSession:A,incarnation:t,expectedGeneration:s}={}){let g=ai(r);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof a!="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 ID(await gG(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 _d("The bot workspace changed before the session binding could be committed.");if(!await mte(c,this.workspaceFor(g))){let l=this.#t[g];this.#r.set(g,this.#c()),await a(),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.#r.get(g)}})}async invalidateSessions(r,{clearSessions:o}={}){let i=ai(r);return this.#C(i,async()=>{this.#r.set(i,this.#c()),await o?.()})}async beginRemoval(r,{clearSessions:o}={}){let i=ai(r);return this.#C(i,async()=>{let e=this.#s.get(i);if(e)return e;let a=Object.freeze({});this.#s.set(i,a),this.#I.set(a,{botId:i,incarnation:this.incarnationFor(i)}),this.#r.set(i,this.#c());try{await o?.()}catch(A){throw this.#s.get(i)===a&&this.#s.delete(i),A}return a})}async abortRemoval(r){let{botId:o}=this.#p(r);return this.#C(o,async()=>this.#s.get(o)!==r?!1:(this.#s.delete(o),Object.hasOwn(this.#t,o)&&(this.#r.set(o,this.#c()),this.#n.has(o)||this.#n.set(o,this.#l())),!0))}async finishRemoval(r){let{botId:o,incarnation:i}=this.#p(r);return this.#C(o,async()=>this.#s.get(o)!==r?{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(r){let o=ai(r);return this.#C(o,async()=>(this.#s.delete(o),this.#h(o)))}async remove(r){let o=await this.retireAfterConfigCommit(r);if(o.error)throw o.error;return o.removed}async reconcile(r){let o=new Set([...r].map(ai)),i=new Set([...Object.keys(this.#t),...this.#a]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(r){return!r||typeof r!="object"||!Array.isArray(r.bots)?r:{...r,bots:r.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId)}:o)}}#c(){let r=this.#g;return this.#g+=1,r}#l(){let r=this.#E;return this.#E+=1,r}#p(r){if(!r||typeof r!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#I.get(r);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#h(r){let o=Object.hasOwn(this.#t,r),i=o||this.#a.has(r);if(delete this.#t[r],this.#r.delete(r),this.#n.delete(r),!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.#a.add(r),{removed:o,persisted:!1,error:e,stale:!1}}}async#C(r,o){let i=this.#i.then(o,o),e=i.then(()=>{},()=>{});return this.#i=e,this.#o.set(r,e),e.finally(()=>{this.#o.get(r)===e&&this.#o.delete(r)}),i}async#d(){let r={version:1,workspaces:this.#t};await Cte(yte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await fte(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await ute(o,this.#e),this.#a.clear()}async#Q(){if(Object.keys(this.#t).length>0){await this.#d();return}try{await Qte(this.#e),this.#a.clear()}catch(r){if(r?.code!=="ENOENT")throw r;this.#a.clear()}}};function cG(n,r){return r&&typeof r.then=="function"?r.then(o=>n.decorateStatus(o)):n.decorateStatus(r)}function Dte(n){return Promise.resolve(n.status())}function Jr(n,{workspaces:r,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!r||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,a){let A=Reflect.get(e,a,e);return a===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await r.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function qr(n,{botId:r,workspaces:o,state:i}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let e=o.incarnationFor(r),a=()=>o.has(r)&&o.incarnationFor(r)===e,A=new Map,t=new Proxy(n,{get(g,c){if(c==="currentWorkspace")return()=>{if(!a()){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(r)};if(c==="assertWorkspaceScope")return()=>{if(!a()){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(!a()){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(!a()){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(!a()){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(r,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(!a()){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(r),f=await g.adoptWorkspaceSession(B);if(!a()){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(r))throw _d("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(r,f.workspace,{conversationKey:p,sessionId:B,clearSessions:()=>i.clearSessions(),setSession:(m,R)=>i.setSession(m,R),incarnation:e,expectedGeneration:Q});if(!a()){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(r))throw _d("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(r),!a()){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(r),Q=await g.createSession({...p,workspace:o.workspaceFor(r)});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(r);A.delete(p);let Q=()=>a()&&B===o.generationFor(r);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 _d("The bot workspace changed before this prompt started.");return g.ask(p,...f)}})};if(c==="sessionExists")return(p,...B)=>{if(!a())return!1;let Q=A.get(p);return Q!==void 0&&Q!==o.generationFor(r)?(A.delete(p),!1):g.sessionExists(p,...B)};if(c==="ask")return(p,...B)=>{let Q=A.get(p);if(A.delete(p),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this prompt started.");throw f.code=on,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),!a()||Q!==void 0&&Q!==o.generationFor(r)){let f=new Error("The bot workspace changed before this command started.");throw f.code=on,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===WS)return g;if(c==="sessionFor")return(p,...B)=>{if(!a())return null;let Q=g.sessionFor(p,...B);return Q&&!A.has(Q)&&A.set(Q,o.generationFor(r)),Q};if(c==="setSession")return(p,B,...Q)=>{let f=A.get(B);return!a()||f!==void 0&&f!==o.generationFor(r)?(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 Vr(n,{workspaces:r,stateFor:o}){if(!n||!r||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)})},a=(t,s)=>{let g=r.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 r.setWorkspace(t,s,{clearSessions:()=>l.clearSessions(),incarnation:g}),r.decorateStatus(await n.status())})},A=(t,s)=>e(t,async()=>{let g=await r.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 r.finishRemoval(g),r.decorateStatus(c)}catch(c){let l=await Dte(n).catch(()=>null);throw Array.isArray(l?.bots)&&!l.bots.some(B=>B?.botId===t)?await r.finishRemoval(g):await r.abortRemoval(g),c}});return new Proxy(n,{get(t,s){if(s==="updateWorkspace")return a;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)):cG(r,g.apply(t,c))}:(...c)=>cG(r,g.apply(t,c))}})}var lG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function wte(n){if(!Array.isArray(n)||n.length===0)return[...lG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...lG]}var Nd=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=wte(e),this.#g=Number.isFinite(a)&&a>=0?a: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(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.totals;if(io.invoke({namespace:"commands",method:"execute",args:{agentId:i,line:e},signal:a.signal})}}function bte(n,r){if(r!==void 0)return new URL(r);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 _te(n){let r=pg(n.dshHome??process.env.DSH_HOME??kE(Mte(),".dsh")),o=pg(n.dataDir??kE(r,"integrations","dsh-dingtalk"));return{root:o,config:pg(n.configPath??kE(o,"config.json")),bots:pg(n.botsDir??kE(o,"bots")),workspaces:pg(n.workspacesPath??kE(o,"workspaces.json"))}}async function ED(n,r={},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??hd,e=o.DeviceAuth??ud,a=o.StateStore??bd,A=o.HarnessClient??Od,t=o.Controller??ME,s=o.Runtime??NE,g=o.createConnectionSupervisor??lD,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=_te(r),p=await new i(l.config).load(),B=pg(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,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"?Jr(p,{workspaces:f}):p,k=o.deviceAuth??new e({baseUrl:r.registrationBaseUrl}),G=new Map,K=V=>pg(l.bots,V,"state.json"),x=async V=>{let U=G.get(V);return U||(U=await new a(K(V)).load(),G.set(V,U)),U},H=zr(n,o.commandExecutor),q=new A({baseUrl:bte(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.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=qr(q,{botId:V,workspaces:f,state:L});return new s({config:U,clientSecret:b,harness:X.harness,state:X.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,connectTimeoutMs:r.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 Ote(K(V))}catch(b){if(b?.code!=="ENOENT")throw b}}}),F=Vr(j,{workspaces:f,stateFor:x}),T=g({controller:F,harness:q,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:F,ready:T.ready,async close(){await T.close(),await F.close(),q.stopManagedProcess()}}}import Rte from"qrcode";var Nte=new Set(["loopback","trusted-host"]);function Wr(n){if(n===void 0)return"loopback";if(Nte.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as Tte}from"node:path";var da="bot.workspace.set";function Zr(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(r=>["botId","workspace"].includes(r))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&Tte(n.workspace.trim())}function Xr(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 pG="/dingtalk",xt=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:da,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),CG=Object.freeze(Object.values(xt)),kte=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function CD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ts(n,r){return CD(n)&&Object.keys(n).every(o=>r.includes(o))}function Cg(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function EG(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function vte(n,r){return CD(r)?n===xt.status?ts(r,[])?null:"connection.status does not accept fields.":n===xt.beginProvisioning?ts(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[xt.pollProvisioning,xt.cancelProvisioning].includes(n)?ts(r,["attemptId"])&&Cg(r.attemptId)?null:`${n} requires an attemptId.`:n===xt.bindCredentials?ts(r,["clientId","clientSecret"])&&EG(r.clientId,256)&&EG(r.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===xt.reconnectBot?ts(r,["botId","sendTest"])&&Cg(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===xt.deleteBot?ts(r,["botId","confirm"])&&Cg(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===xt.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===xt.approveSender?ts(r,["botId","requestId","confirm"])&&Cg(r.botId)&&Cg(r.requestId)&&r.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===xt.revokeSender?ts(r,["botId","senderKey","confirm"])&&Cg(r.botId)&&Cg(r.senderKey)&&r.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function Td(n){return{ok:!1,error:{code:"bad-request",message:n}}}function vE(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function Pte(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Wc(n){if(Array.isArray(n))return n.map(Wc);if(!CD(n))return n;let r={};for(let[o,i]of Object.entries(n))kte.has(o)||(r[o]=Wc(i));return r}async function Gte(n){return Rte.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function pD(n,r){return!n||typeof n.verificationUrl!="string"?Wc(n):Wc({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function hg(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await pD(o.provisioning,r)),Wc(o)}function Fte(n){for(let r of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[r]!="function")throw new TypeError(`A complete DingTalk controller is required (${r})`)}function hG(n,{encodeQr:r=Gte}={}){Fte(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return vE();if(!CG.includes(e))return Td("Unknown DingTalk endpoint.");let t=vte(e,a);if(t)return Td(t);try{let s;if(e===xt.status)s=await hg(await n.status(),i);else if(e===xt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),vE();s=await pD(g,i)}else if(e===xt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return Td("The provisioning attempt no longer exists.");s=await pD(g,i)}else if(e===xt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return Td("The provisioning attempt no longer exists.");s=Wc(s)}else if(e===xt.bindCredentials)s=await hg(await n.bindCredentials(a),i);else if(e===xt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return vE();let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await hg({...g,...c?{testMessage:c}:{}},i)}else if(e===xt.deleteBot)s=await hg(await n.deleteBot(a.botId),i);else if(e===xt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await hg(await n.updateWorkspace(a.botId,a.workspace),i)}else e===xt.approveSender?s=await hg(await n.approveSender(a.botId,a.requestId),i):s=await hg(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?vE():{ok:!0,value:s}}catch(s){let g=Xr(s);return A?.aborted?vE():g?{ok:!1,error:g}:Pte()}}}function Rd(n,r,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(pG,hG(r,o),{authority:Wr(i)})}async function dG(n,r={}){if(r?.controller)return Rd(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await ED(n,r,r.internals),i=Rd(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as Lte}from"node:crypto";import{mkdir as Ute,readFile as Hte,rename as Kte,unlink as Yte,writeFile as xte}from"node:fs/promises";import{dirname as jte}from"node:path";var hD=Object.freeze({version:1,bots:Object.freeze([])});function nn(n){return typeof n=="string"&&n.trim()?n.trim():null}function uG(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PE(n,{botPrefix:r,tokenRefPrefix:o}){let i=nn(n);if(!i)throw new TypeError("platformId is required");let e=Lte("sha256").update(i).digest("hex").slice(0,24);return{botId:`${r}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function kd(n,r){let o=nn(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:r:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Zc=class{#e;#A;#t;#r;#g;#n;#E=hD;#s=Promise.resolve();constructor(r,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=new RegExp(`^${uG(i)}_[a-f0-9]{24}$`),this.#n=new RegExp(`^${uG(e)}_[A-F0-9]{24}$`)}async load(){try{let r=this.#a(JSON.parse(await Hte(this.#e,"utf8")));if(!r)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#E=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#E=hD}return this}list(){return structuredClone(this.#E.bots)}get(r){let o=this.#E.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#E.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#I(r);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),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)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(r){if(!this.#g.test(r))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#i(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#s.then(async()=>{try{await Yte(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#E=hD});this.#s=r.then(()=>{},()=>{}),await r}#I(r){if(!r||typeof r!="object")return null;let o=nn(r.platformId),i=nn(r.botId),e=nn(r.tokenRef),a=nn(r.name);if(!o||!i||!e||!a||!this.#g.test(i)||!this.#n.test(e))return null;let A=PE(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:nn(r.username),createdAt:nn(r.createdAt)??new Date().toISOString(),connectedAt:nn(r.connectedAt)})}#a(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#I(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#i(r){let o,i=this.#s.then(async()=>{let e=[...this.#E.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#o(a),this.#E=a});return this.#s=i.then(()=>{},()=>{}),await i,o}async#o(r){await Ute(jte(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await xte(o,`${JSON.stringify(r,null,2)} -`,{encoding:"utf8",mode:384}),await Kte(o,this.#e)}};var BG=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function QG(n){return PE(n,BG)}function fG(n){return kd(n,"Discord\u673A\u5668\u4EBA")}var vd=class extends Zc{constructor(r){super(r,{channel:"Discord",...BG})}};function GE(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pd(n,r){return Object.freeze({code:n,message:r})}var Xc=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=new Map;#i=new Map;#o=new Map;#c=0;#l=!1;constructor({descriptor:r,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!r?.key||!r?.label||!r?.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(`${r.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${r.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${r.label} controller dependencies are incomplete`);this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let r of this.#t.list())await this.#Q(r.botId,async()=>{if(this.#l||this.#a.get(r.botId)?.status?.ready)return;let o=await this.#C(r.tokenRef);if(!o){this.#i.set(r.botId,Pd("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(r,o),this.#i.delete(r.botId)}catch(i){this.#i.set(r.botId,Pd("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 ${r.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({token:r}={}){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let o=GE(r);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=GE(i?.platformId),a=GE(i?.name);if(!e||!a)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:a,username:GE(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,Pd("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(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,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(r)}catch(e){throw this.#i.set(r,Pd("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 sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#Q(r,async()=>{let i=this.#a.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(`${this.#e.label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5`);throw a.code="test-target-unavailable",a}let e=`${o.name}\uFF08${this.#n(o.platformId)}\uFF09`;return await i.sendConnectionTest(Yr(e,`${this.#e.label}\u673A\u5668\u4EBA`)),{sent:!0}})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}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:r,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} state cleanup failed:`,e)}),this.#i.delete(r),this.#u()}),this.status()}status(){let r=this.#t.list().map(i=>{let e=this.#a.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#n(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`${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=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#a.keys()].map(r=>this.#h(r))))}async#p(r,o){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(r.botId),this.#l)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#E({botId:r.botId,config:r,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#a.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#a.delete(r.botId),e}}async#h(r){let o=this.#a.get(r);this.#a.delete(r),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} failed to stop cleanly:`,i)})}async#C(r){let o=await this.#A.resolve(r).catch(()=>{});return GE(o?.value)}async#d(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#Q(r,o){let a=(this.#o.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(r)===a&&this.#o.delete(r)});return this.#o.set(r,a),a}#u(){this.#c+=1}};var Jte="https://discord.com/api/v10/";function FE(n){return typeof n=="string"&&n.trim()?n.trim():null}function qte(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function Vte(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function $c(n,r){let o=FE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${r}`);return o}function zte(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var LE=class{#e;#A;#t;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=Jte}){if(!zte(r))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i)}getCurrentUser(r={}){return this.#r("users/@me",{...r,method:"GET"})}getGatewayBot(r={}){return this.#r("gateway/bot",{...r,method:"GET"})}createMessage({channelId:r,content:o,replyToMessageId:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:$c(i,"message id"),channel_id:$c(r,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:r,messageId:o,content:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages/${$c(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:r,signal:o}){return this.#r(`channels/${$c(r,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#r(r,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#A(new URL(r,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:qte(e,a),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.#r(r,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(FE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function yG(n,r={}){let i=await new LE({token:n,...r}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:FE(i.global_name)??FE(i.username)??"Discord\u673A\u5668\u4EBA",username:FE(i.username)}}var mG="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Pi(n){return typeof n=="string"?n.trim():""}function Wte(n,r,o){return r.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Mr(n)&&!!Pi(n.content)}function ka(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var lo=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;constructor({descriptor:r,bot:o,harness:i,state:e,status:a=ka(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!r?.key||!r?.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:r.key,logger:A})}get status(){return structuredClone(this.#g)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Pi(r?.conversationId),i=r?.kind==="group"?"group":"direct",e={...r,kind:i,conversationId:o},a=Pi(e.messageId),A=Pi(e.senderId);if(!a||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(a)||this.#o.has(a))return Promise.resolve();this.#o.add(a),e.kind==="direct"&&Va(this.#r,e.connectionTestTarget??e.replyTarget);let t=`${i}:${o}`,s=this.#a.get(t),g=this.#l.claimReply({key:t,actor:A,messageId:a,text:Mr(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#a.has(t),send:c=>this.#A.sendText(e.replyTarget,c)});if(g){let c;return c=g.process(async()=>this.#r.hasSeen(a)?!1:(await this.#r.markSeen(a),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(a),this.#c.delete(c)}),this.#c.add(c),c}if(s&&s.actor!==A)return this.#p(e,a,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#p(e,a,A,t);if(s){Wte(e,s,A)&&(s.claimedReplyMessageId=a);let l=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,a,A,t,s)).finally(()=>{this.#o.delete(a),s.claimedReplyMessageId===a&&(s.claimedReplyMessageId=null),s.queue===l&&(s.queue=null)});return s.queue=l,l}return this.#p(e,a,A,t)}#p(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(r,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&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.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:`${this.#e.label}\u673A\u5668\u4EBA`,send:(o,i)=>this.#A.sendText(o,i)})}async#h(r,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let A=r.replyTarget,t=Pi(r.content),s=null;try{if(this.#s?.throwIfAborted(),r.kind==="group"&&r.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let g=Mr(r);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 Kte(o,this.#e)}};var BG=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function QG(n){return PE(n,BG)}function fG(n){return kd(n,"Discord\u673A\u5668\u4EBA")}var vd=class extends Zc{constructor(r){super(r,{channel:"Discord",...BG})}};function GE(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pd(n,r){return Object.freeze({code:n,message:r})}var Xc=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=new Map;#i=new Map;#o=new Map;#c=0;#l=!1;constructor({descriptor:r,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!r?.key||!r?.label||!r?.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(`${r.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${r.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${r.label} controller dependencies are incomplete`);this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let r of this.#t.list())await this.#Q(r.botId,async()=>{if(this.#l||this.#a.get(r.botId)?.status?.ready)return;let o=await this.#C(r.tokenRef);if(!o){this.#i.set(r.botId,Pd("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(r,o),this.#i.delete(r.botId)}catch(i){this.#i.set(r.botId,Pd("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 ${r.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({token:r}={}){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);let o=GE(r);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=GE(i?.platformId),a=GE(i?.name);if(!e||!a)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:a,username:GE(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,Pd("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(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,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(r)}catch(e){throw this.#i.set(r,Pd("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 sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#Q(r,async()=>{let i=this.#a.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(`${this.#e.label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5`);throw a.code="test-target-unavailable",a}let e=`${o.name}\uFF08${this.#n(o.platformId)}\uFF09`;return await i.sendConnectionTest(Yr(e,`${this.#e.label}\u673A\u5668\u4EBA`)),{sent:!0}})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#Q(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}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:r,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} state cleanup failed:`,e)}),this.#i.delete(r),this.#u()}),this.status()}status(){let r=this.#t.list().map(i=>{let e=this.#a.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#i.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#n(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`${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=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#o.values()]),await Promise.allSettled([...this.#a.keys()].map(r=>this.#h(r))))}async#p(r,o){if(this.#l)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(r.botId),this.#l)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#E({botId:r.botId,config:r,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#a.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#a.delete(r.botId),e}}async#h(r){let o=this.#a.get(r);this.#a.delete(r),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#e.key}] bot ${r} failed to stop cleanly:`,i)})}async#C(r){let o=await this.#A.resolve(r).catch(()=>{});return GE(o?.value)}async#d(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#Q(r,o){let a=(this.#o.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#o.get(r)===a&&this.#o.delete(r)});return this.#o.set(r,a),a}#u(){this.#c+=1}};var Jte="https://discord.com/api/v10/";function FE(n){return typeof n=="string"&&n.trim()?n.trim():null}function qte(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function Vte(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function $c(n,r){let o=FE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${r}`);return o}function zte(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var LE=class{#e;#A;#t;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=Jte}){if(!zte(r))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i)}getCurrentUser(r={}){return this.#r("users/@me",{...r,method:"GET"})}getGatewayBot(r={}){return this.#r("gateway/bot",{...r,method:"GET"})}createMessage({channelId:r,content:o,replyToMessageId:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:$c(i,"message id"),channel_id:$c(r,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:r,messageId:o,content:i,signal:e}){return this.#r(`channels/${$c(r,"channel id")}/messages/${$c(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:r,signal:o}){return this.#r(`channels/${$c(r,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#r(r,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#A(new URL(r,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.11.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:qte(e,a),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.#r(r,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(FE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function yG(n,r={}){let i=await new LE({token:n,...r}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:FE(i.global_name)??FE(i.username)??"Discord\u673A\u5668\u4EBA",username:FE(i.username)}}var mG="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Pi(n){return typeof n=="string"?n.trim():""}function Wte(n,r,o){return r.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Mr(n)&&!!Pi(n.content)}function ka(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var lo=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;constructor({descriptor:r,bot:o,harness:i,state:e,status:a=ka(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!r?.key||!r?.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:r.key,logger:A})}get status(){return structuredClone(this.#g)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Pi(r?.conversationId),i=r?.kind==="group"?"group":"direct",e={...r,kind:i,conversationId:o},a=Pi(e.messageId),A=Pi(e.senderId);if(!a||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(a)||this.#o.has(a))return Promise.resolve();this.#o.add(a),e.kind==="direct"&&Va(this.#r,e.connectionTestTarget??e.replyTarget);let t=`${i}:${o}`,s=this.#a.get(t),g=this.#l.claimReply({key:t,actor:A,messageId:a,text:Mr(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#a.has(t),send:c=>this.#A.sendText(e.replyTarget,c)});if(g){let c;return c=g.process(async()=>this.#r.hasSeen(a)?!1:(await this.#r.markSeen(a),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#o.delete(a),this.#c.delete(c)}),this.#c.add(c),c}if(s&&s.actor!==A)return this.#p(e,a,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#p(e,a,A,t);if(s){Wte(e,s,A)&&(s.claimedReplyMessageId=a);let l=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,a,A,t,s)).finally(()=>{this.#o.delete(a),s.claimedReplyMessageId===a&&(s.claimedReplyMessageId=null),s.queue===l&&(s.queue=null)});return s.queue=l,l}return this.#p(e,a,A,t)}#p(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(r,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&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.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:`${this.#e.label}\u673A\u5668\u4EBA`,send:(o,i)=>this.#A.sendText(o,i)})}async#h(r,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}let A=r.replyTarget,t=Pi(r.content),s=null;try{if(this.#s?.throwIfAborted(),r.kind==="group"&&r.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let g=Mr(r);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 ti(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.#r.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 Ai(t,this.#t,this.#r,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 Wa(r,{signal:this.#s}):void 0,{answer:f}=await ha({harness:this.#t,state:this.#r,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:r.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=Za(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(r,o,i,e,a){if(this.#s?.aborted)return;let A=this.#a.get(e),t=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return t&&(!A||A!==a)?this.#B(r,o):this.#p(r,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString(),r.kind==="group"&&r.addressed!==!0){this.#g.messagesRejected+=1,this.#g.lastRejectedAt=new Date().toISOString();return}let s=r.replyTarget,g=Pi(r.content);if(!g||Mr(r)){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.#a.get(e);if(!c||c!==a||c.submitting)return t&&(!c||c!==a)?this.#B(r,o,{alreadyRecorded:!0}):this.#p(r,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.#a.get(e);if(!B||B!==a||B.submitting)return t&&(!B||B!==a)?this.#B(r,o,{alreadyRecorded:!0}):this.#p(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!p)return}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=Pi(r?.interactionId)||Pi(r?.rpcId);if(!Pi(r?.rpcId)||!t||!Pi(r?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#n.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(r.recovered===!0){await this.#D(r,`${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.#a.get(o);if(s?.interactionId===t){s.interaction=r,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(r,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#a.set(o,g),this.#i.set(t,o),await this.#u(g)}async#Q(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=Pi(r?.interactionId);if(r?.kind!=="question"||!o)return;let i=this.#i.get(o);i&&this.#f(i,o)}#u(r){if(r.presentationTask)return r.presentationTask;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(r.target,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})),r.needsPresentation=!1})();return r.presentationTask=i,i.then(()=>{r.presentationTask===i&&(r.presentationTask=null)},()=>{r.presentationTask===i&&(r.presentationTask=null)}),i}async#B(r,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#g.messagesReceived+=1,this.#g.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(r.replyTarget,mG)}catch(e){this.#n.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#y(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#f(r,o){return this.#y(r,o)!==null}async#D(r,o){try{await r.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(r){let o=this.#y(r);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 dD=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),Gd=class extends lo{constructor(r){super({descriptor:dD,...r})}};var UE=class extends Xc{constructor(r){super({...r,descriptor:dD,inspectToken:r.inspectToken??yG,deriveIdentity:QG,maskPlatformId:fG})}};var Fd=class extends qt{constructor(r){super({...r,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function ii(n,r){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>r;){let a=e.lastIndexOf(` `,r);a{l||g!==null||c||!s||(g=setTimeout(()=>{g=null;let Q=s;s=null;let f=ii(Q,r)[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=ii(Q,r),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";y!==p&&await e(t,y),p=y;for(let m of f.slice(1))await a(m)},cancel(){l=!0,s=null,g!==null&&clearTimeout(g),g=null}}}var Zte=4609,SG=Object.freeze([1e3,3e3,5e3,1e4,3e4]),Xte=new Set(["image/jpeg","image/png","image/webp","image/gif"]),$te=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),ere=Object.freeze(["cdn.discordapp.com"]);function Are(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return r.searchParams.set("v","10"),r.searchParams.set("encoding","json"),r.href}function uD(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Discord WebSocket does not support events")}function tre(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 rre(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 r=new Error(`Discord Gateway closed (${n||"unknown"})`);return r.code="discord-gateway-closed",r}function are(n,r){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${r}>`,"g"),"").trim()}function ire(n){let r=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(Xte.has(r))return r;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of $te)if(o.endsWith(i))return e;return null}function ore(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function nre(n,r){let o=ire(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:ore(n.size),load:i=>za(n.url,{...i,fetchImpl:r,allowedHosts:ere})}}function sre(n,r,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(r));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:are(n.content??"",r),images:Array.isArray(n.attachments)?n.attachments.map(a=>nre(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}var BD=class{#e;#A;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=ii(o,1900),e=null;for(let[a,A]of i.entries())e=await this.#e.createMessage({channelId:r.channelId,content:A,replyToMessageId:a===0?r.replyToMessageId:void 0,signal:this.#A});return e}sendTyping(r){return this.#e.sendTyping({channelId:r.channelId,signal:this.#A})}async openStream(r){return Ld({limit:1900,create:async i=>(await this.#e.createMessage({channelId:r.channelId,content:i,replyToMessageId:r.replyToMessageId,signal:this.#A})).id,edit:(i,e)=>this.#e.editMessage({channelId:r.channelId,messageId:i,content:e,signal:this.#A}),sendRemainder:i=>this.#e.createMessage({channelId:r.channelId,content:i,signal:this.#A})}).start()}};function gre(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...ka()}}var HE=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a;#i=gre();#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:r,token:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,createApi:s=l=>new LE(l),createWebSocket:g=l=>new WebSocket(l),random:c=Math.random}){if(!r||!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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g,this.#a=c}get status(){return structuredClone(this.#i)}async sendConnectionTest(r){if(!this.#i.ready||!this.#c){let o=new Error("Discord bot is not connected");throw o.code="test-target-unavailable",o}return this.#c.sendConnectionTest(r)}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 r=new AbortController;this.#l=r;let o=this.#s({token:this.#A});this.#o=o;try{let[i,e]=await Promise.all([o.getCurrentUser({signal:r.signal}),o.getGatewayBot({signal:r.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 a=new BD({api:o,signal:r.signal});this.#c=new Gd({bot:a,harness:this.#t,state:this.#r,status:this.#i,logger:this.#g,replyTimeoutMs:this.#n,signal:r.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(r){if(this.#m)return Promise.reject(new Error("Discord runtime is stopped"));let o=++this.#D,i=Are(r&&this.#C?this.#C:this.#h),e=this.#I(i);this.#p=e;let a=!1;return new Promise((A,t)=>{let s=()=>{if(a||o!==this.#D)return;a=!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()};uD(e,"message",g=>{if(o!==this.#D||this.#m)return;let c=tre(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),r&&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:Zte,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=sre(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)})}}}),uD(e,"close",(g={})=>{if(o!==this.#D)return;if(this.#T(),this.#p===e&&(this.#p=null),this.#m){a||t(new DOMException("Stopped","AbortError"));return}let c=rre(Number(g.code)||0);if(this.#i.ready=!1,this.#i.connectionState="connecting",this.#i.lastError=c.message,a||(a=!0,t(c)),c.code==="discord-401"||c.code==="discord-intents"){this.#i.connectionState="failed";return}this.#L()}),uD(e,"error",()=>{o!==this.#D||this.#m||(this.#i.lastError="Discord Gateway WebSocket error")})})}#O(r,o){r.readyState===1&&r.send(JSON.stringify(o))}#M(r,o,i){if(this.#T(),!Number.isFinite(r)||r<1e3){o.close(4e3,"Invalid heartbeat interval");return}this.#B=!0;let e=a=>{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(r)}},a),this.#u?.unref?.()};e(Math.floor(r*this.#a()))}#F(r){this.#B=!1,this.#O(r,{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 r=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())})},r),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 r=this.#p,o=this.#c;this.#p=null,this.#c=null,this.#o=null;try{r&&r.readyState<2&&r.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 cre,readFile as Ire,rename as lre,unlink as Ere,writeFile as pre}from"node:fs/promises";import{dirname as Cre}from"node:path";var Ud=Object.freeze({version:1,sessions:{},seenMessageIds:[],cursor:null});function hre(n){if(!n||typeof n!="object")return structuredClone(Ud);let r={};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&&(r[o]=i);return{version:1,sessions:r,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 Eo=class{#e;#A=structuredClone(Ud);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=hre(JSON.parse(await Ire(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(Ud),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}cursor(){return this.#A.cursor}async setCursor(r){if(!Number.isSafeInteger(r)||r<0)throw new TypeError("Invalid update cursor");this.#A.cursor=r,await this.#r()}snapshot(){return structuredClone(this.#A)}async remove(){try{await Ere(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(Ud)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await cre(Cre(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await pre(i,r,{encoding:"utf8",mode:384}),await lre(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var Hd=class extends Eo{};import{unlink as ure}from"node:fs/promises";import{homedir as Bre}from"node:os";import{join as KE,resolve as dg}from"node:path";var DG=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function dre(n){if(!Array.isArray(n)||n.length===0)return[...DG];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...DG]}var QD=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=null;#a=null;#i=0;#o=!1;#c=!1;#l;#p;constructor({channel:r,controller:o,harness:i,logger:e=console,retryDelaysMs:a,healthyIntervalMs:A=15e3,setTimeoutImpl:t=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!r)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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=dre(a),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.#a?.catch(()=>{}),this.#p?.(null),this.#p=null)}#h(r){this.#o||(this.#I=this.#E(()=>{this.#I=null,this.#C()},r),this.#I?.unref?.())}async#C(){if(this.#o||this.#a)return;let r=this.#d();this.#a=r;try{await r}finally{this.#a===r&&(this.#a=null)}}async#d(){try{if(await this.#t.ensureRunning(),this.#o)return;let r=await this.#A.initialize();if(this.#o)return;this.#p?.(r),this.#p=null;let{configured:o,connected:i}=r.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 yD(n,r){let o=dg(n.dshHome??process.env.DSH_HOME??KE(Bre(),".dsh")),i=dg(n.dataDir??KE(o,"integrations",`dsh-${r}`));return{config:dg(n.configPath??KE(i,"config.json")),bots:dg(n.botsDir??KE(i,"bots")),workspaces:dg(n.workspacesPath??KE(i,"workspaces.json"))}}async function Kd(n,r,o,i){let{channel:e,ConfigStore:a,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??a,l=o.StateStore??A,p=o.HarnessClient??t,B=o.Controller??s,Q=o.Runtime??g,f=o.createConnectionSupervisor??eI,y=typeof n.logger=="function"?n.logger(`dsh-im:${e}`):n.logger??console,m=yD(r,e),R=await new c(m.config).load(),k=dg(r.workspace??process.cwd()),G=o.WorkspaceStore??Cr,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"?Jr(R,{workspaces:K}):R,q=new Map,j=X=>dg(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=zr(n,o.commandExecutor),V=new p({baseUrl:fD(n.webServer,r.harnessBaseUrl),workspace:k,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.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=qr(V,{botId:X,workspaces:K,state:qe});return new Q({config:pe,token:me,harness:Se.harness,state:Se.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.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 ure(j(X))}catch(me){if(me?.code!=="ENOENT")throw me}}}),b=Vr(U,{workspaces:K,stateFor:F}),L=f({channel:e,controller:b,harness:V,logger:y,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:b,ready:L.ready,async close(){await L.close(),await b.close(),V.stopManagedProcess()}}}function mD(n,r={},o={}){return Kd(n,r,o,{channel:"discord",ConfigStore:vd,StateStore:Hd,HarnessClient:Fd,Controller:UE,Runtime:HE})}var ua=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:da}),Qre=Object.freeze(Object.values(ua)),fre=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]);function DD(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Yd(n,r){return DD(n)&&Object.keys(n).every(o=>r.includes(o))}function wG(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function yre(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function mre(n,r){return DD(r)?n===ua.status?Yd(r,[])?null:"connection.status does not accept fields.":n===ua.bindCredentials?Yd(r,["token"])&&yre(r.token)?null:"bot.bind-credentials requires a Bot Token.":n===ua.reconnectBot?Yd(r,["botId","sendTest"])&&wG(r.botId)&&(r.sendTest===void 0||typeof r.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===ua.deleteBot?Yd(r,["botId","confirm"])&&wG(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===ua.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown bot endpoint.":"Payload must be an object."}function SD(n){if(Array.isArray(n))return n.map(SD);if(!DD(n))return n;let r={};for(let[o,i]of Object.entries(n))fre.has(o)||(r[o]=SD(i));return r}function Sre(n,r){let o=Xr(r);return o||(r?.code==="webhook-configured"?{code:"webhook-configured",message:r.message}:r?.code==="telegram-401"||r?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:r?.code==="discord-intents"?{code:"discord-intents",message:r.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function wD(n,{channel:r}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${r} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!Qre.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${r} endpoint.`}};let a=mre(o,i);if(a)return{ok:!1,error:{code:"bad-request",message:a}};try{let A;if(o===ua.status)A=await n.status();else if(o===ua.bindCredentials)A=await n.bindCredentials(i);else if(o===ua.reconnectBot){if(A=await n.reconnectBot(i.botId),e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(i.sendTest===!0){let t=null;try{if(A?.bots?.find(s=>s?.botId===i.botId)?.connected!==!0){let s=new Error("Bot is not connected");throw s.code="test-target-unavailable",s}if(typeof n.sendConnectionTest!="function"){let s=new Error("Connection test is unavailable");throw s.code="test-target-unavailable",s}await n.sendConnectionTest(i.botId)}catch(s){t=s}A={...A,testMessage:Ot(t)}}}else if(o===ua.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:SD(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:Sre(r,A)}}}}function xd(n,r,{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,wD(r,{channel:o}),{authority:Wr(e)})}var OG="/discord",MG=ua,Dre=Object.freeze(Object.values(MG));function jd(n,r,o){return xd(n,r,{channel:"Discord",rpcChannel:OG,authority:o})}async function bG(n,r={}){if(r?.controller)return jd(n,r.controller,r.rpcAuthority);let o=await mD(n,r,r.internals??{}),i=jd(n,o.controller,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Discord bot connections"),i}var wre=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function Ore(n){let r=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:r,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function Mre(n){return typeof n.status!="function"?{}:await n.status()}function bre(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var Jd=class{#e;#A;#t;#r;#g=!1;#n=null;constructor({createProvisioningManager:r,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof r!="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.#r=r({onCredentials:a=>this.#E(a)}),!this.#r||typeof this.#r.start!="function"||typeof this.#r.status!="function"||typeof this.#r.cancel!="function")throw new TypeError("The provisioning manager must implement start/status/cancel")}async startRegistration(){return this.#n=null,await this.#r.start(structuredClone(this.#t)),this.status()}async cancelRegistration(){return await this.#r.cancel(),this.status()}async disconnect(){await this.#r.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 r=await this.#r.status(),o=await Mre(this.#A),i=bre(o),e=this.#g;if(typeof this.#e.configured=="function")try{e=await this.#e.configured()}catch{e=this.#g}let a="unconfigured";return i?a="connected":wre.has(r?.state)?a="registering":r?.state==="saving"?a="connecting":this.#n||r?.state==="error"?a="error":e&&(a="disconnected"),{phase:a,connected:i,configured:e,registration:r,connection:o,error:this.#n??r?.error??null}}async close(){await this.#r.cancel(),await this.#A.disconnect()}async#E(r){let o=Ore(r);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 OD(n){return new Jd(n)}import{homedir as ABe}from"node:os";import{join as xI,resolve as Bs}from"node:path";import{unlink as tBe}from"node:fs/promises";var yN={};er(yN,{AESCipher:()=>eC,AccessTokenError:()=>HI,Aily:()=>X_,AppType:()=>mo,CAppTicket:()=>$p,CTenantAccessToken:()=>Vp,CardActionHandler:()=>V_,Client:()=>MB,ClientAssertionError:()=>ea,DefaultCache:()=>DB,Domain:()=>So,EventDispatcher:()=>_B,LarkChannel:()=>PB,LarkChannelError:()=>It,LoggerLevel:()=>La,LoggerProxy:()=>us,WSClient:()=>TB,adaptDefault:()=>Bhe,adaptExpress:()=>Qhe,adaptKoa:()=>fhe,adaptKoaRouter:()=>yhe,createLarkChannel:()=>oue,defaultHttpInstance:()=>KI,defaultLogger:()=>fn,generateChallenge:()=>tC,internalCache:()=>AC,messageCard:()=>She,normalize:()=>d1,normalizeBotAdded:()=>C1,normalizeCardAction:()=>p1,normalizeComment:()=>h1,normalizeReaction:()=>IN,registerApp:()=>vhe,withAll:()=>Ehe,withHelpDeskCredential:()=>Che,withTenantKey:()=>phe,withTenantToken:()=>hhe,withUserAccessToken:()=>dhe});function YE(n,r){return function(){return n.apply(r,arguments)}}var{toString:_re}=Object.prototype,{getPrototypeOf:AI}=Object,{iterator:jE,toStringTag:TG}=Symbol,Vd=(({hasOwnProperty:n})=>(r,o)=>n.call(r,o))(Object.prototype),xE=(n,r)=>{let o=n,i=[];for(;o!=null&&o!==Object.prototype;){if(i.indexOf(o)!==-1)return!1;if(i.push(o),Vd(o,r))return!0;o=AI(o)}return!1},Nre=(n,r)=>n!=null&&xE(n,r)?n[r]:void 0,bD=(n=>r=>{let o=_re.call(r);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),oi=n=>(n=n.toLowerCase(),r=>bD(r)===n),zd=n=>r=>typeof r===n,{isArray:Bg}=Array,Qg=zd("undefined");function tI(n){return n!==null&&!Qg(n)&&n.constructor!==null&&!Qg(n.constructor)&&Ba(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var RG=oi("ArrayBuffer");function Tre(n){let r;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?r=ArrayBuffer.isView(n):r=n&&n.buffer&&RG(n.buffer),r}var Rre=zd("string"),Ba=zd("function"),kG=zd("number"),rI=n=>n!==null&&typeof n=="object",kre=n=>n===!0||n===!1,qd=n=>{if(!rI(n))return!1;let r=AI(n);return(r===null||r===Object.prototype||AI(r)===null)&&!xE(n,TG)&&!xE(n,jE)},vre=n=>{if(!rI(n)||tI(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},Pre=oi("Date"),Gre=oi("File"),Fre=n=>!!(n&&typeof n.uri<"u"),Lre=n=>n&&typeof n.getParts<"u",Ure=oi("Blob"),Hre=oi("FileList"),Kre=oi("Set"),Yre=n=>rI(n)&&Ba(n.pipe);function xre(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var _G=xre(),NG=typeof _G.FormData<"u"?_G.FormData:void 0,jre=n=>{if(!n)return!1;if(NG&&n instanceof NG)return!0;let r=AI(n);if(!r||r===Object.prototype||!Ba(n.append))return!1;let o=bD(n);return o==="formdata"||o==="object"&&Ba(n.toString)&&n.toString()==="[object FormData]"},Jre=oi("URLSearchParams"),[qre,Vre,zre,Wre]=["ReadableStream","Request","Response","Headers"].map(oi),Zre=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function JE(n,r,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),Bg(n))for(i=0,e=n.length;i0;)if(e=o[i],r===e.toLowerCase())return e;return null}var ug=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,PG=n=>!Qg(n)&&n!==ug;function MD(...n){let{caseless:r,skipUndefined:o}=PG(this)&&this||{},i={},e=(a,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let t=r&&typeof A=="string"&&vG(i,A)||A,s=Vd(i,t)?i[t]:void 0;qd(s)&&qd(a)?i[t]=MD(s,a):qd(a)?i[t]=MD({},a):Bg(a)?i[t]=a.slice():(!o||!Qg(a))&&(i[t]=a)};for(let a=0,A=n.length;a(JE(r,(e,a)=>{o&&Ba(e)?Object.defineProperty(n,a,{__proto__:null,value:YE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,a,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),$re=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),eae=(n,r,o,i)=>{n.prototype=Object.create(r.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:r.prototype}),o&&Object.assign(n.prototype,o)},Aae=(n,r,o,i)=>{let e,a,A,t={};if(r=r||{},n==null)return r;do{for(e=Object.getOwnPropertyNames(n),a=e.length;a-- >0;)A=e[a],(!i||i(A,n,r))&&!t[A]&&(r[A]=n[A],t[A]=!0);n=o!==!1&&AI(n)}while(n&&(!o||o(n,r))&&n!==Object.prototype);return r},tae=(n,r,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=r.length;let i=n.indexOf(r,o);return i!==-1&&i===o},rae=n=>{if(!n)return null;if(Bg(n))return n;let r=n.length;if(!kG(r))return null;let o=new Array(r);for(;r-- >0;)o[r]=n[r];return o},aae=(n=>r=>n&&r instanceof n)(typeof Uint8Array<"u"&&AI(Uint8Array)),iae=(n,r)=>{let i=(n&&n[jE]).call(n),e;for(;(e=i.next())&&!e.done;){let a=e.value;r.call(n,a[0],a[1])}},oae=(n,r)=>{let o,i=[];for(;(o=n.exec(r))!==null;)i.push(o);return i},nae=oi("HTMLFormElement"),sae=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:gae}=Object.prototype,cae=oi("RegExp"),GG=(n,r)=>{let o=Object.getOwnPropertyDescriptors(n),i={};JE(o,(e,a)=>{let A;(A=r(e,a,n))!==!1&&(i[a]=A||e)}),Object.defineProperties(n,i)},Iae=n=>{GG(n,(r,o)=>{if(Ba(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(Ba(i)){if(r.enumerable=!1,"writable"in r){r.writable=!1;return}r.set||(r.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},lae=(n,r)=>{let o={},i=e=>{e.forEach(a=>{o[a]=!0})};return Bg(n)?i(n):i(String(n).split(r)),o},Eae=()=>{},pae=(n,r)=>n!=null&&Number.isFinite(n=+n)?n:r;function Cae(n){return!!(n&&Ba(n.append)&&n[TG]==="FormData"&&n[jE])}var hae=n=>{let r=new WeakSet,o=i=>{if(rI(i)){if(r.has(i))return;if(tI(i))return i;if(!("toJSON"in i)){r.add(i);let e;if(Kre(i)){e=[];for(let a of i){let A=o(a);!Qg(A)&&e.push(A)}}else e=Bg(i)?[]:{},JE(i,(a,A)=>{let t=o(a);!Qg(t)&&(e[A]=t)});return r.delete(i),e}}return i};return o(n)},dae=oi("AsyncFunction"),uae=n=>n&&(rI(n)||Ba(n))&&Ba(n.then)&&Ba(n.catch),FG=((n,r)=>n?setImmediate:r?((o,i)=>(ug.addEventListener("message",({source:e,data:a})=>{e===ug&&a===o&&i.length&&i.shift()()},!1),e=>{i.push(e),ug.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",Ba(ug.postMessage)),Bae=typeof queueMicrotask<"u"?queueMicrotask.bind(ug):typeof process<"u"&&process.nextTick||FG,LG=n=>n!=null&&Ba(n[jE]),Qae=n=>n!=null&&xE(n,jE)&&LG(n),J={isArray:Bg,isArrayBuffer:RG,isBuffer:tI,isFormData:jre,isArrayBufferView:Tre,isString:Rre,isNumber:kG,isBoolean:kre,isObject:rI,isPlainObject:qd,isEmptyObject:vre,isReadableStream:qre,isRequest:Vre,isResponse:zre,isHeaders:Wre,isUndefined:Qg,isDate:Pre,isFile:Gre,isReactNativeBlob:Fre,isReactNative:Lre,isBlob:Ure,isRegExp:cae,isFunction:Ba,isStream:Yre,isURLSearchParams:Jre,isTypedArray:aae,isFileList:Hre,forEach:JE,merge:MD,extend:Xre,trim:Zre,stripBOM:$re,inherits:eae,toFlatObject:Aae,kindOf:bD,kindOfTest:oi,endsWith:tae,toArray:rae,forEachEntry:iae,matchAll:oae,isHTMLForm:nae,hasOwnProperty:Vd,hasOwnProp:Vd,hasOwnInPrototypeChain:xE,getSafeProp:Nre,reduceDescriptors:GG,freezeMethods:Iae,toObjectSet:lae,toCamelCase:sae,noop:Eae,toFiniteNumber:pae,findKey:vG,global:ug,isContextDefined:PG,isSpecCompliantForm:Cae,toJSONObject:hae,isAsyncFn:dae,isThenable:uae,setImmediate:FG,asap:Bae,isIterable:LG,isSafeIterable:Qae};var fae=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"]),UG=n=>{let r={},o,i,e;return n&&n.split(` @@ -186,7 +186,7 @@ ${a.join(` `,{encoding:"utf8",mode:384}),await rfe(o,this.#e)}};var TQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"wecom",logPrefix:"dsh-wecom"})}};var gfe="https://work.weixin.qq.com/ai/qc/generate",cfe="https://work.weixin.qq.com/ai/qc/query_result";function b3(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function qI(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ife(n){let r=qI(n);if(!r)return null;try{let o=new URL(r);return o.protocol==="https:"&&o.hostname==="work.weixin.qq.com"&&(!o.port||o.port==="443")?o.href:null}catch{return null}}function lfe(n,r){return n?AbortSignal.any([n,AbortSignal.timeout(r)]):AbortSignal.timeout(r)}async function _3(n,r,o){let i=await n(r,{method:"GET",redirect:"error",signal:lfe(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var RQ=class{#e;#A;#t;#r;constructor({fetch:r=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=b3()}={}){if(typeof r!="function")throw new TypeError("A fetch implementation is required");this.#e=r,this.#A=o,this.#t=i,this.#r=[1,2,3].includes(e)?e:b3()}async start({signal:r}={}){let o=new URL(gfe);o.searchParams.set("source",this.#t),o.searchParams.set("plat",String(this.#r));let i=await _3(this.#e,o,r),e=qI(i?.data?.scode),a=Ife(i?.data?.auth_url);if(!e||!a)throw new Error("Enterprise WeChat QR service returned invalid data");return{scode:e,verificationUrl:a,expiresAt:this.#A()+3e5,pollIntervalMs:3e3}}async poll({scode:r,signal:o}={}){let i=qI(r);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(cfe);e.searchParams.set("scode",i);let a=await _3(this.#e,e,o),A=qI(a?.data?.status)?.toLowerCase();if(A==="success"){let t=qI(a?.data?.bot_info?.botid),s=qI(a?.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 Efe,readFile as pfe,rename as Cfe,unlink as hfe,writeFile as dfe}from"node:fs/promises";import{dirname as ufe}from"node:path";var kQ=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function Bfe(n){if(!n||typeof n!="object")return structuredClone(kQ);let r={};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&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var vQ=class{#e;#A=structuredClone(kQ);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=Bfe(JSON.parse(await pfe(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(kQ),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}async remove(){try{await hfe(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(kQ)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await Efe(ufe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await dfe(i,r,{encoding:"utf8",mode:384}),await Cfe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as Qfe}from"node:crypto";var N3=new Set(["pending","connecting"]),QC=new Set(["connected","failed","cancelled","expired"]);function $g(n){return typeof n=="string"&&n.trim()?n.trim():null}function Da(n,r){return Object.freeze({code:n,message:r})}function ec(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 fC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=null;#i=new Map;#o=0;#c=!1;constructor({qrAuth:r,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.start!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#c)return this.status();for(let r of this.#t.list())await this.#B(r.botId,async()=>{let o=this.#E.get(r.botId)?.status;if(this.#c||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#Q(r.secretRef);if(!i){this.#s.set(r.botId,Da("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(r,i),this.#s.delete(r.botId)}catch{this.#s.set(r.botId,Da("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 ${r.botId} failed to initialize`)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("Enterprise WeChat controller is closed");this.#a&&await this.cancelProvisioning(this.#a);let r={id:Qfe(),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(r.id,r),this.#a=r.id,this.#f();try{let o=await this.#e.start({signal:r.controller.signal});if(r.scode=$g(o.scode),r.verificationUrl=$g(o.verificationUrl),r.expiresAt=Number(o.expiresAt),r.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!r.scode||!r.verificationUrl||!Number.isFinite(r.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#f(),ec(r)}catch(o){throw r.state=r.controller.signal.aborted?"cancelled":"failed",r.error=r.controller.signal.aborted?Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"):Da("qr-start-failed","\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),this.#y(r),o}}async registrationStatus(r){let o=this.#I.get(r);if(!o||QC.has(o.state))return ec(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),ec(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=Da("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),o.controller.abort(),this.#y(o),ec(o);if(!o.polling){let i=this.#l(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),ec(o)}async bindCredentials({botId:r,secret:o}={}){if(this.#c)throw new Error("Enterprise WeChat controller is closed");let i=$g(r),e=$g(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#a&&await this.cancelProvisioning(this.#a),this.#c)throw new Error("Enterprise WeChat controller is closed");let a=NQ(i);return await this.#B(a.botId,async()=>{if(this.#c)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),t=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#c)throw new Error("Enterprise WeChat controller is closed");let s={botId:a.botId,remoteBotId:i,secretRef:a.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#u(a.secretRef,t),g}try{await this.#C(s,e),this.#s.delete(a.botId)}catch{this.#s.set(a.botId,Da("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 ${a.botId} credential connection failed`)}this.#f()}),this.status()}async cancelProvisioning(r){let o=this.#I.get(r);return o?(QC.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),QC.has(o.state)||(o.state="cancelled"),o.error??=Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"),this.#y(o)),ec(o)):null}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(r,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(r)}catch(e){throw this.#s.set(r,Da("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 sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return this.#B(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA");return i.sendConnectionTest(Yr(`\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08${r0(o.remoteBotId)}\uFF09`))})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#B(r,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#d(r);try{await this.#A.unset(o.secretRef),await this.#t.remove(r)}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:r,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:wecom] bot ${r} state cleanup failed:`,e)}),this.#s.delete(r),this.#f()}),this.status()}status(){let r=this.#t.list().map(e=>{let a=this.#E.get(e.botId)?.status??null,A=a?.ready===!0&&a.wecomConnectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.wecomConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",appIdMasked:r0(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:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:structuredClone(this.#s.get(e.botId)??null)}}),o=r.filter(e=>e.connected).length,i=this.#a?this.#I.get(this.#a):null;return{schemaVersion:1,revision:this.#o,state:i&&N3.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&N3.has(i.state)?{provisioning:ec(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#a&&await this.cancelProvisioning(this.#a),await Promise.allSettled([...this.#i.values()]),await Promise.allSettled([...this.#E.keys()].map(r=>this.#d(r))))}async#l(r){try{let o=await this.#e.poll({scode:r.scode,signal:r.controller.signal});if(r.controller.signal.aborted||QC.has(r.state)||o.status==="waiting")return;if(o.status==="expired"){r.state="expired",r.error=Da("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),this.#y(r);return}if(o.status!=="success"){r.state="failed",r.error=Da("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(r);return}r.state="connecting",r.verificationUrl=null,r.expiresAt=null,r.scode=null,this.#f();let i=this.#p(r,o);r.transition=i,await i}catch{if(r.controller.signal.aborted)return;r.state="failed",r.error=Da("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(r)}}async#p(r,o){try{let i=$g(o.remoteBotId),e=$g(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");r.botId=await this.#h(r,{remoteBotId:i,secret:e}),r.state="connected",r.error=null}catch{r.controller.signal.aborted?(r.state="cancelled",r.error=Da("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Da("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(r)}}async#h(r,{remoteBotId:o,secret:i}){let e=NQ(o),a=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),t={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:a?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#B(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(r.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(r.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#C(t,i),this.#s.delete(e.botId)}catch(s){if(r.controller.signal.aborted)throw await this.#d(e.botId),a?await this.#t.save(a).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,Da("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(r,o){if(this.#c)throw new Error("Enterprise WeChat controller is closed");if(await this.#d(r.botId),this.#c)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:r.botId,config:r,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(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#E.delete(r.botId),e}}async#d(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:wecom] bot ${r} failed to stop cleanly:`,i)})}async#Q(r){let o=await this.#A.resolve(r).catch(()=>{});return $g(o?.value)}async#u(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#B(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#y(r){r.scode=null,r.verificationUrl=null,r.expiresAt=null,this.#a===r.id&&(this.#a=null),this.#f();let o=[...this.#I.values()].filter(i=>QC.has(i.state));for(;o.length>16;)this.#I.delete(o.shift().id)}#f(){this.#o+=1}};import{WSAuthFailureError as _fe,WSClient as Nfe,WSReconnectExhaustedError as Tfe}from"@wecom/aibot-node-sdk";import{generateReqId as ffe}from"@wecom/aibot-node-sdk";var yfe=["\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(` `),mfe=18e3,T3=5*1024*1024,v3=4,PQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function ys(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ac(n){return n?.body&&typeof n.body=="object"?n.body:{}}function R3(n){let r=Ac(n);return r.chattype==="group"?`group:${r.chatid}`:`direct:${r.from?.userid}`}function P3(n){let r=Ac(n),o="";return r.msgtype==="text"?o=typeof r.text?.content=="string"?r.text.content.trim():"":r.msgtype==="voice"?o=typeof r.voice?.content=="string"?r.voice.content.trim():"":r.msgtype==="mixed"&&Array.isArray(r.mixed?.msg_item)&&(o=r.mixed.msg_item.filter(i=>i?.msgtype==="text"&&typeof i.text?.content=="string").map(i=>i.text.content).join(` -`).trim()),r.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function Sfe(n){let r=Ac(n);return r.msgtype==="image"?[r.image]:r.msgtype!=="mixed"||!Array.isArray(r.mixed?.msg_item)?[]:r.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function Dfe(n,r){let o=ys(r?.url);if(!o)return null;let i=ys(r?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){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(a)&&s.length>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function k3(n,r){return{content:P3(n),images:Sfe(n).map(o=>Dfe(r,o)).filter(Boolean)}}function wfe(n,r){return Mr(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:r,maxBytes:T3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=T3}={}){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)>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function Ofe(n){return{...n,images:n.images.map(r=>({...r,async load(){throw new XA("image-queue-full",`Enterprise WeChat already has ${v3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function a0(n){return Ac(n).msgtype==="text"?P3(n):""}function GQ(n,r=mfe){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let t=Buffer.byteLength(A);e&&a+t>r?(i.push(e),e=A,a=t):(e+=A,a+=t)}return e&&i.push(e),i}function Mfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function bfe(n,r){return r.questions[r.index]&&ys(Ac(n).from?.userid)===r.actor&&ys(a0(n))}function i0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var FQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:r,harness:o,state:i,status:e=i0(),logger:a=console,replyTimeoutMs:A=6e5,generateStreamId:t=ffe,signal:s}){if(!r||typeof r.replyStream!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:"wecom",logger:a})}get status(){return structuredClone(this.#r)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ac(r),i=ys(o.msgid),e=ys(o.from?.userid),a=o.chattype==="group"?ys(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=R3(r);this.#o.add(i),o.chattype==="single"&&Va(this.#t,{chatId:a});let t=this.#a.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:a0(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#a.has(A),send:g=>this.#d(r,a,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#r.messagesReceived+=1,this.#r.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(r,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(r,i,A);if(t){bfe(r,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,i,e,a,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(r,i,A)}#h(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let A=k3(r,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=v3?(s=t,this.#p+=s,g=wfe(A,this.#s)):g=Ofe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,{alreadyRecorded:a,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.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}async#C(r,o){for(let i of GQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(r,{msgtype:"markdown",markdown:{content:i}})}async#d(r,o,i){this.#s?.throwIfAborted();let e=GQ(i);if(e.length!==0)try{await this.#e.replyStream(r,this.#E("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#C(o,i)}}async#Q(r,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Ac(r),a=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!a||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(a))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let s=i??k3(r,this.#e),g=s.content,c=Mr(s),l=R3(r),p=null,B=!1;try{if(!g&&!c){await this.#d(r,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(a);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(r,t,yfe),await this.#t.markSeen(a);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(r,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(a);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(r,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(a);return}let f=c?null:await ti(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(r,t,K);await this.#t.markSeen(a);return}let y=c?null:await Ai(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(r,t,y.message),await this.#t.markSeen(a);return}p=this.#E("stream");try{await this.#e.replyStream(r,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 Wa(s,{signal:this.#s}):void 0,{answer:R}=await ha({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=GQ(Mfe(K))[0];x&&await this.#e.replyStreamNonBlocking(r,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=GQ(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(r,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(a),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#r.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=Za(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(r,p,f,!0):await this.#d(r,t,f),await this.#t.markSeen(a)}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(r,o,i,e,a,A){if(this.#s?.aborted)return;let t=this.#a.get(a),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(r,o,e):this.#h(r,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=ys(a0(r));if(!g){await this.#d(r,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#a.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#r.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.#a.get(a);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.index{});return}if(this.#a.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(r,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(r,{key:o,actor:i,chatId:e,requiresMention:a}){if(r?.kind==="approval")return this.#l.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#C(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.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.#a.get(o);if(s?.interactionId===t){s.interaction=r,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 r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#a.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#C(r.chatId,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#d(r,i,PQ).catch(()=>{}))}#m(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);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 Rfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function kfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...i0()}}var yC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=kfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:r,secret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Nfe(c)}){if(!r||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#a)}async start(){if(this.#a.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let r=new AbortController;return this.#l=r,this.#p=r,this.#c=this.#h(r.signal).finally(()=>{this.#l===r&&(this.#l=null),this.#c=null}),this.#c}async#h(r){await this.#C(),r.throwIfAborted(),this.#a.startedAt=new Date().toISOString(),this.#a.wecomConnectionState="connecting",this.#a.lastError=null,await this.#t.ensureRunning(),this.#a.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 FQ({client:i,harness:this.#t,state:this.#r,status:this.#a,logger:this.#g,replyTimeoutMs:this.#n,signal:r});let e,a,A=!1,t=new Promise((Q,f)=>{e=Q,a=f}),s=()=>{if(this.#i!==i||r.aborted)return;A=!0;let Q=Date.now();this.#a.ready=!0,this.#a.wecomConnectionState="connected",this.#a.lastCheckedAt=Q,this.#a.lastConnectedAt=Q,this.#a.lastError=null,e()},g=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof _fe||Q instanceof Tfe;!A&&f&&a(Q),f&&(this.#a.ready=!1,this.#a.wecomConnectionState="failed"),this.#a.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)=>{r.addEventListener("abort",()=>f(r.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Rfe()),this.#E)})]),this.status}catch(Q){throw r.aborted?(await this.#C(),Q):(this.#a.ready=!1,this.#a.wecomConnectionState="failed",this.#a.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let r=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 r?.catch(()=>{}),this.status}async sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",send:async({chatId:o},i)=>{if(!this.#a.ready||!this.#i)throw new Error("Enterprise WeChat runtime is not connected");await this.#i.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async#C(){let r=this.#i,o=this.#o;this.#i=null,this.#o=null;try{r?.disconnect(),r?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#a.ready=!1,this.#a.wecomConnectionState="idle"}};var G3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vfe(n){if(!Array.isArray(n)||n.length===0)return[...G3];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...G3]}var LQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=vfe(e),this.#g=Number.isFinite(a)&&a>=0?a: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(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.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 Lfe(n){let r=tc(n.dshHome??process.env.DSH_HOME??mC(Gfe(),".dsh")),o=tc(n.dataDir??mC(r,"integrations","dsh-wecom"));return{config:tc(n.configPath??mC(o,"config.json")),bots:tc(n.botsDir??mC(o,"bots")),workspaces:tc(n.workspacesPath??mC(o,"workspaces.json"))}}async function n0(n,r={},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??_Q,e=o.StateStore??vQ,a=o.HarnessClient??TQ,A=o.Controller??fC,t=o.Runtime??yC,s=o.QrAuth??RQ,g=o.createConnectionSupervisor??o0,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Lfe(r),p=await new i(l.config).load(),B=tc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,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"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness",platform:r.qrPlatform}),k=new Map,G=T=>tc(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=zr(n,o.commandExecutor),H=new a({baseUrl:Ffe(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.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=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,maxReconnectAttempts:r.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 Pfe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import Ufe from"qrcode";var L3="/wecom",Nr=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:da}),U3=Object.freeze(Object.values(Nr)),Hfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function c0(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function VI(n,r){return c0(n)&&Object.keys(n).every(o=>r.includes(o))}function s0(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F3(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function Kfe(n,r){return c0(r)?n===Nr.status?VI(r,[])?null:"connection.status does not accept fields.":n===Nr.beginProvisioning?VI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Nr.pollProvisioning,Nr.cancelProvisioning].includes(n)?VI(r,["attemptId"])&&s0(r.attemptId)?null:`${n} requires an attemptId.`:n===Nr.bindCredentials?VI(r,["botId","secret"])&&F3(r.botId,512)&&F3(r.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Nr.reconnectBot?VI(r,["botId","sendTest"])&&s0(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Nr.deleteBot?VI(r,["botId","confirm"])&&s0(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Nr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function zI(n){if(Array.isArray(n))return n.map(zI);if(!c0(n))return n;let r={};for(let[o,i]of Object.entries(n))Hfe.has(o)||(r[o]=zI(i));return r}async function Yfe(n){return Ufe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function g0(n,r){return!n||typeof n.verificationUrl!="string"?zI(n):zI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function SC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await g0(o.provisioning,r)),zI(o)}function H3(n,{encodeQr:r=Yfe}={}){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 a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!U3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Kfe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Nr.status)s=await SC(await n.status(),i);else if(e===Nr.beginProvisioning)s=await g0(await n.startProvisioning(),i);else if(e===Nr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await g0(g,i)}else if(e===Nr.cancelProvisioning)s=zI(await n.cancelProvisioning(a.attemptId));else if(e===Nr.bindCredentials)s=await SC(await n.bindCredentials(a),i);else if(e===Nr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await SC({...g,...c?{testMessage:c}:{}},i)}else if(e===Nr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await SC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await SC(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Xr(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 UQ(n,r,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(L3,H3(r,o),{authority:Wr(i)})}async function K3(n,r={}){if(r?.controller)return UQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await n0(n,r,r.internals),i=UQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Rye}from"node:fs/promises";import{homedir as kye}from"node:os";import{join as bC,resolve as rc}from"node:path";import{createHash as nye}from"node:crypto";import{mkdir as sye,readFile as gye,rename as cye,unlink as Iye,writeFile as lye}from"node:fs/promises";import{dirname as Eye}from"node:path";import{createDecipheriv as xfe,randomBytes as jfe,randomUUID as Jfe}from"node:crypto";var KQ="https://ilinkai.weixin.qq.com/",qfe="2.4.6",Vfe="3",zfe="https://novac2c.cdn.weixin.qq.com/c2c",j3="novac2c.cdn.weixin.qq.com",Wfe="bot",Zfe=2<<16|1024|6,Xfe=15e3,Y3=35e3,$fe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(r,o,i={}){super(o,i),this.name="WeixinApiError",this.code=r,this.status=i.status}};function aa(n){return typeof n=="string"&&n.trim()?n.trim():null}function eye(n){let r=aa(n);return!r||r.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)?null:Buffer.from(r,"base64")}function Aye(n){let r=aa(n?.aeskey);if(r){if(!/^[0-9a-fA-F]{32}$/.test(r))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(r,"hex")}let o=eye(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 tye(n,r){let o=Buffer.from(n),i=Buffer.from(r);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=xfe("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 rye(n){let r=aa(n?.encrypt_query_param);if(r)return`${zfe}/download?encrypted_query_param=${encodeURIComponent(r)}`;let o=aa(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!==j3||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 I0(n,{fetchImpl:r=fetch}={}){if(typeof r!="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:a,maxBytes:A})=>{let t=Aye(e),s=rye(e.media),g=await za(s,{fetchImpl:r,signal:a,maxBytes:A+16,allowedHosts:[j3]});return tye(g,t)}})}return o}function l0(n){let r=n.toLowerCase().replace(/\.$/,"");return r==="weixin.qq.com"||r.endsWith(".weixin.qq.com")}function ZI(n){let r;try{r=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(r.protocol!=="https:"||!l0(r.hostname)||r.port!==""&&r.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 r.username="",r.password="",r.search="",r.hash="",r.pathname.endsWith("/")||(r.pathname+="/"),r.toString()}function aye(n){let r=aa(n);if(!r)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(r)}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:"||!l0(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 J3(){return{"iLink-App-Id":Wfe,"iLink-App-ClientVersion":String(Zfe)}}function iye(n){let r={...J3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(jfe(4).readUInt32BE(0)),"utf8").toString("base64")};return aa(n)&&(r.Authorization=`Bearer ${n.trim()}`),r}function HQ(){return{channel_version:qfe,bot_agent:"DeepSeekHarness/0.10.0"}}function x3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function WI(n,{method:r,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=Xfe,signal:t,authenticated:s=!0}){let g=ZI(o),c=new URL(i,g);if(!l0(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 x3(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:r,headers:s?iye(a):J3(),...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?x3(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 oye(n){if(!n||typeof n!="object"||!$fe.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 q3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(r){return I0(r,{fetchImpl:n})},async beginLogin({localTokens:r=[],botType:o=Vfe,signal:i}={}){let e=[...new Set(r.map(aa).filter(Boolean))].slice(-10),a=await WI(n,{method:"POST",baseUrl:KQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=aa(a?.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:aye(a.qrcode_img_content)}},async pollLogin({qrcode:r,baseUrl:o=KQ,verifyCode:i,signal:e}){let a=aa(r);if(!a)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(a)}`;aa(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await WI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y3,signal:e,authenticated:!1});return oye(t)},async getUpdates({baseUrl:r,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:a}){try{return await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:HQ()},token:o,timeoutMs:e??Y3,signal:a})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:r,token:o,toUserId:i,text:e,contextToken:a,runId:A,signal:t}){let s=aa(i),g=aa(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Jfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...aa(a)?{context_token:a.trim()}:{},...aa(A)?{run_id:A.trim()}:{}},base_info:HQ()}});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:r,token:o,signal:i}){let e=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}});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:r,token:o,signal:i}){return WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}})}})}function DC(n){for(let r of n?.item_list??[]){if(r?.type===1&&typeof r.text_item?.text=="string"){let o=r.text_item.text.trim();if(o)return o}if(r?.type===3&&typeof r.voice_item?.text=="string"){let o=r.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):aa(n?.client_id)}function V3(n,r=4e3){if(n.length<=r)return[n];let o=[],i=n;for(;i.length>r;){let e=i.lastIndexOf(` +`).trim()),r.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function Sfe(n){let r=Ac(n);return r.msgtype==="image"?[r.image]:r.msgtype!=="mixed"||!Array.isArray(r.mixed?.msg_item)?[]:r.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function Dfe(n,r){let o=ys(r?.url);if(!o)return null;let i=ys(r?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){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(a)&&s.length>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return{data:s,name:A?.filename}}}}function k3(n,r){return{content:P3(n),images:Sfe(n).map(o=>Dfe(r,o)).filter(Boolean)}}function wfe(n,r){return Mr(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:r,maxBytes:T3});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=T3}={}){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)>a)throw new XA("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,"\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002");return A}}})}:n}function Ofe(n){return{...n,images:n.images.map(r=>({...r,async load(){throw new XA("image-queue-full",`Enterprise WeChat already has ${v3} prefetched images`,"\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002")}}))}}function a0(n){return Ac(n).msgtype==="text"?P3(n):""}function GQ(n,r=mfe){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let t=Buffer.byteLength(A);e&&a+t>r?(i.push(e),e=A,a=t):(e+=A,a+=t)}return e&&i.push(e),i}function Mfe(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function bfe(n,r){return r.questions[r.index]&&ys(Ac(n).from?.userid)===r.actor&&ys(a0(n))}function i0(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var FQ=class{#e;#A;#t;#r;#g;#n;#E;#s;#I=new Map;#a=new Map;#i=new Map;#o=new Set;#c=new Set;#l;#p=0;constructor({client:r,harness:o,state:i,status:e=i0(),logger:a=console,replyTimeoutMs:A=6e5,generateStreamId:t=ffe,signal:s}){if(!r||typeof r.replyStream!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#l=new Ca({label:"wecom",logger:a})}get status(){return structuredClone(this.#r)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ac(r),i=ys(o.msgid),e=ys(o.from?.userid),a=o.chattype==="group"?ys(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#o.has(i))return Promise.resolve();let A=R3(r);this.#o.add(i),o.chattype==="single"&&Va(this.#t,{chatId:a});let t=this.#a.get(A),s=this.#l.claimReply({key:A,actor:e,messageId:i,text:a0(r),addressed:!0,hasPendingQuestion:!!t,questionCompletion:t?.submitting||t?.claimedReplyMessageId?t.queue:null,isQuestionPending:()=>this.#a.has(A),send:g=>this.#d(r,a,g)});if(s){let g;return g=s.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#r.messagesReceived+=1,this.#r.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(r,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#h(r,i,A);if(t){bfe(r,t)&&(t.claimedReplyMessageId=i);let c=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,i,e,a,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(r,i,A)}#h(r,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1}={}){let A=k3(r,this.#e),t=A.images.length,s=0,g=A;t>0&&(this.#p+t<=v3?(s=t,this.#p+=s,g=wfe(A,this.#s)):g=Ofe(A));let l=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#Q(r,{alreadyRecorded:a,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.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c])}async#C(r,o){for(let i of GQ(o))this.#s?.throwIfAborted(),await this.#e.sendMessage(r,{msgtype:"markdown",markdown:{content:i}})}async#d(r,o,i){this.#s?.throwIfAborted();let e=GQ(i);if(e.length!==0)try{await this.#e.replyStream(r,this.#E("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#C(o,i)}}async#Q(r,{alreadyRecorded:o=!1,preparedMessage:i}={}){if(this.#s?.aborted)return;let e=Ac(r),a=typeof e.msgid=="string"?e.msgid:"",A=typeof e.from?.userid=="string"?e.from.userid:"",t=e.chattype==="group"?e.chatid:A;if(!a||!A||!t||!["single","group"].includes(e.chattype))return;if(!o){if(this.#t.hasSeen(a))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let s=i??k3(r,this.#e),g=s.content,c=Mr(s),l=R3(r),p=null,B=!1;try{if(!g&&!c){await this.#d(r,t,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002"),await this.#t.markSeen(a);return}let Q=g.toLowerCase();if(!c&&Q==="/help"){await this.#d(r,t,yfe),await this.#t.markSeen(a);return}if(!c&&Q==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#d(r,t,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(a);return}if(!c&&Q==="/new"){await this.#t.clearSession(l),await this.#d(r,t,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(a);return}let f=c?null:await ti(g,this.#A,l);if(f){for(let K of f.messages??[f.message])await this.#d(r,t,K);await this.#t.markSeen(a);return}let y=c?null:await Ai(g,this.#A,this.#t,l,{signal:this.#s});if(y){await this.#d(r,t,y.message),await this.#t.markSeen(a);return}p=this.#E("stream");try{await this.#e.replyStream(r,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 Wa(s,{signal:this.#s}):void 0,{answer:R}=await ha({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=GQ(Mfe(K))[0];x&&await this.#e.replyStreamNonBlocking(r,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=GQ(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(r,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(a),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(Q){if(this.#s?.aborted)return;this.#r.lastError=Q?.message??String(Q),this.#g.error?.("[dsh-im:wecom] failed to process an inbound message");let f=Za(Q)??"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{B&&p?await this.#e.replyStream(r,p,f,!0):await this.#d(r,t,f),await this.#t.markSeen(a)}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(r,o,i,e,a,A){if(this.#s?.aborted)return;let t=this.#a.get(a),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#D(r,o,e):this.#h(r,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=ys(a0(r));if(!g){await this.#d(r,e,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#a.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#f(c)}catch{this.#r.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.#a.get(a);if(!p||p!==A||p.submitting){if(s&&(!p||p!==A)){await this.#d(r,e,PQ).catch(()=>{});return}return this.#h(r,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(ei(l,g)),c.index+=1,c.index{});return}if(this.#a.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#g.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#d(r,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#B(r,{key:o,actor:i,chatId:e,requiresMention:a}){if(r?.kind==="approval")return this.#l.handleRequested(r,{key:o,actor:i,requiresMention:a,send:c=>this.#C(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=typeof r?.interactionId=="string"?r.interactionId:r?.rpcId;if(typeof r?.rpcId!="string"||typeof t!="string"||typeof r.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Xa(c))){this.#g.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(r.recovered===!0){await r.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.#a.get(o);if(s?.interactionId===t){s.interaction=r,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 r.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#a.set(o,g),this.#i.set(g.interactionId,o),await this.#f(g)}async#y(r){if(r?.kind==="approval"){await this.#l.handleResolved(r);return}let o=r?.interactionId;if(r?.kind!=="question"||typeof o!="string")return;let i=this.#i.get(o);i&&this.#w(i,o)}#f(r){if(!r.needsPresentation)return Promise.resolve();if(r.presentationPromise)return r.presentationPromise;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=this.#C(r.chatId,$a(o,r.index,r.questions.length,{requiresMention:r.requiresMention})).then(()=>{r.needsPresentation=!1}).finally(()=>{r.presentationPromise===i&&(r.presentationPromise=null)});return r.presentationPromise=i,i}async#D(r,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#d(r,i,PQ).catch(()=>{}))}#m(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#i.delete(i.interactionId),i)}#w(r,o){return this.#m(r,o)!==null}async#N(r){let o=this.#m(r);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 Rfe(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function kfe(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...i0()}}var yC=class{#e;#A;#t;#r;#g;#n;#E;#s;#I;#a=kfe();#i=null;#o=null;#c=null;#l=null;#p=null;constructor({config:r,secret:o,harness:i,state:e,logger:a=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new Nfe(c)}){if(!r||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A,this.#E=t,this.#s=s,this.#I=g}get status(){return structuredClone(this.#a)}async start(){if(this.#a.ready&&this.#i)return this.status;if(this.#c)return this.#c;this.#p?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let r=new AbortController;return this.#l=r,this.#p=r,this.#c=this.#h(r.signal).finally(()=>{this.#l===r&&(this.#l=null),this.#c=null}),this.#c}async#h(r){await this.#C(),r.throwIfAborted(),this.#a.startedAt=new Date().toISOString(),this.#a.wecomConnectionState="connecting",this.#a.lastError=null,await this.#t.ensureRunning(),this.#a.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 FQ({client:i,harness:this.#t,state:this.#r,status:this.#a,logger:this.#g,replyTimeoutMs:this.#n,signal:r});let e,a,A=!1,t=new Promise((Q,f)=>{e=Q,a=f}),s=()=>{if(this.#i!==i||r.aborted)return;A=!0;let Q=Date.now();this.#a.ready=!0,this.#a.wecomConnectionState="connected",this.#a.lastCheckedAt=Q,this.#a.lastConnectedAt=Q,this.#a.lastError=null,e()},g=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},c=()=>{this.#i===i&&(this.#a.ready=!1,this.#a.wecomConnectionState="connecting",this.#a.lastCheckedAt=Date.now())},l=Q=>{if(this.#i!==i)return;let f=Q instanceof _fe||Q instanceof Tfe;!A&&f&&a(Q),f&&(this.#a.ready=!1,this.#a.wecomConnectionState="failed"),this.#a.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)=>{r.addEventListener("abort",()=>f(r.reason),{once:!0})}),new Promise((Q,f)=>{B=setTimeout(()=>f(Rfe()),this.#E)})]),this.status}catch(Q){throw r.aborted?(await this.#C(),Q):(this.#a.ready=!1,this.#a.wecomConnectionState="failed",this.#a.lastError=Q?.message??String(Q),await this.#C(),Q)}finally{clearTimeout(B)}}async stop(){let r=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 r?.catch(()=>{}),this.status}async sendConnectionTest(r){return Xn({state:this.#r,text:r,channelLabel:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",send:async({chatId:o},i)=>{if(!this.#a.ready||!this.#i)throw new Error("Enterprise WeChat runtime is not connected");await this.#i.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async#C(){let r=this.#i,o=this.#o;this.#i=null,this.#o=null;try{r?.disconnect(),r?.removeAllListeners?.()}catch{this.#g.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#a.ready=!1,this.#a.wecomConnectionState="idle"}};var G3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vfe(n){if(!Array.isArray(n)||n.length===0)return[...G3];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...G3]}var LQ=class{#e;#A;#t;#r;#g;#n;#E;#s=null;#I=null;#a=0;#i=!1;#o=!1;#c;#l;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=vfe(e),this.#g=Number.isFinite(a)&&a>=0?a: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(r){this.#i||(this.#s=this.#n(()=>{this.#s=null,this.#h()},r),this.#s?.unref?.())}async#h(){if(this.#i||this.#I)return;let r=this.#C();this.#I=r;try{await r}finally{this.#I===r&&(this.#I=null)}}async#C(){try{if(await this.#A.ensureRunning(),this.#i)return;let r=await this.#e.initialize();if(this.#i)return;this.#l?.(r),this.#l=null;let{configured:o,connected:i}=r.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 Lfe(n){let r=tc(n.dshHome??process.env.DSH_HOME??mC(Gfe(),".dsh")),o=tc(n.dataDir??mC(r,"integrations","dsh-wecom"));return{config:tc(n.configPath??mC(o,"config.json")),bots:tc(n.botsDir??mC(o,"bots")),workspaces:tc(n.workspacesPath??mC(o,"workspaces.json"))}}async function n0(n,r={},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??_Q,e=o.StateStore??vQ,a=o.HarnessClient??TQ,A=o.Controller??fC,t=o.Runtime??yC,s=o.QrAuth??RQ,g=o.createConnectionSupervisor??o0,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Lfe(r),p=await new i(l.config).load(),B=tc(r.workspace??process.cwd()),Q=o.WorkspaceStore??Cr,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"?Jr(p,{workspaces:f}):p,R=o.qrAuth??new s({source:r.qrSource??"deepseek-harness",platform:r.qrPlatform}),k=new Map,G=T=>tc(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=zr(n,o.commandExecutor),H=new a({baseUrl:Ffe(n.webServer,r.harnessBaseUrl),workspace:B,...r.agentPreset==null?{}:{agentPreset:r.agentPreset},autostart:!1,dshBin:r.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=qr(H,{botId:T,workspaces:f,state:b});return new t({config:V,secret:U,harness:L.harness,state:L.state,replyTimeoutMs:r.replyTimeoutMs??6e5,connectTimeoutMs:r.connectTimeoutMs??2e4,maxReconnectAttempts:r.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 Pfe(G(T))}catch(U){if(U?.code!=="ENOENT")throw U}}}),j=Vr(q,{workspaces:f,stateFor:K}),F=g({controller:j,harness:H,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:j,ready:F.ready,async close(){await F.close(),await j.close(),H.stopManagedProcess()}}}import Ufe from"qrcode";var L3="/wecom",Nr=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:da}),U3=Object.freeze(Object.values(Nr)),Hfe=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function c0(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function VI(n,r){return c0(n)&&Object.keys(n).every(o=>r.includes(o))}function s0(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F3(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function Kfe(n,r){return c0(r)?n===Nr.status?VI(r,[])?null:"connection.status does not accept fields.":n===Nr.beginProvisioning?VI(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Nr.pollProvisioning,Nr.cancelProvisioning].includes(n)?VI(r,["attemptId"])&&s0(r.attemptId)?null:`${n} requires an attemptId.`:n===Nr.bindCredentials?VI(r,["botId","secret"])&&F3(r.botId,512)&&F3(r.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Nr.reconnectBot?VI(r,["botId","sendTest"])&&s0(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Nr.deleteBot?VI(r,["botId","confirm"])&&s0(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Nr.setWorkspace?Zr(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function zI(n){if(Array.isArray(n))return n.map(zI);if(!c0(n))return n;let r={};for(let[o,i]of Object.entries(n))Hfe.has(o)||(r[o]=zI(i));return r}async function Yfe(n){return Ufe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function g0(n,r){return!n||typeof n.verificationUrl!="string"?zI(n):zI({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function SC(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await g0(o.provisioning,r)),zI(o)}function H3(n,{encodeQr:r=Yfe}={}){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 a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!U3.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Kfe(e,a);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Nr.status)s=await SC(await n.status(),i);else if(e===Nr.beginProvisioning)s=await g0(await n.startProvisioning(),i);else if(e===Nr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await g0(g,i)}else if(e===Nr.cancelProvisioning)s=zI(await n.cancelProvisioning(a.attemptId));else if(e===Nr.bindCredentials)s=await SC(await n.bindCredentials(a),i);else if(e===Nr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(p=>p?.botId===a.botId&&p?.connected===!0)||typeof n.sendConnectionTest!="function")c=Ot(kt("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Ot()}catch(p){c=Ot(p)}s=await SC({...g,...c?{testMessage:c}:{}},i)}else if(e===Nr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await SC(await n.updateWorkspace(a.botId,a.workspace),i)}else s=await SC(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=Xr(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 UQ(n,r,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(L3,H3(r,o),{authority:Wr(i)})}async function K3(n,r={}){if(r?.controller)return UQ(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await n0(n,r,r.internals),i=UQ(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as Rye}from"node:fs/promises";import{homedir as kye}from"node:os";import{join as bC,resolve as rc}from"node:path";import{createHash as nye}from"node:crypto";import{mkdir as sye,readFile as gye,rename as cye,unlink as Iye,writeFile as lye}from"node:fs/promises";import{dirname as Eye}from"node:path";import{createDecipheriv as xfe,randomBytes as jfe,randomUUID as Jfe}from"node:crypto";var KQ="https://ilinkai.weixin.qq.com/",qfe="2.4.6",Vfe="3",zfe="https://novac2c.cdn.weixin.qq.com/c2c",j3="novac2c.cdn.weixin.qq.com",Wfe="bot",Zfe=2<<16|1024|6,Xfe=15e3,Y3=35e3,$fe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),qA=class extends Error{constructor(r,o,i={}){super(o,i),this.name="WeixinApiError",this.code=r,this.status=i.status}};function aa(n){return typeof n=="string"&&n.trim()?n.trim():null}function eye(n){let r=aa(n);return!r||r.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(r)?null:Buffer.from(r,"base64")}function Aye(n){let r=aa(n?.aeskey);if(r){if(!/^[0-9a-fA-F]{32}$/.test(r))throw new qA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(r,"hex")}let o=eye(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 tye(n,r){let o=Buffer.from(n),i=Buffer.from(r);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=xfe("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 rye(n){let r=aa(n?.encrypt_query_param);if(r)return`${zfe}/download?encrypted_query_param=${encodeURIComponent(r)}`;let o=aa(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!==j3||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 I0(n,{fetchImpl:r=fetch}={}){if(typeof r!="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:a,maxBytes:A})=>{let t=Aye(e),s=rye(e.media),g=await za(s,{fetchImpl:r,signal:a,maxBytes:A+16,allowedHosts:[j3]});return tye(g,t)}})}return o}function l0(n){let r=n.toLowerCase().replace(/\.$/,"");return r==="weixin.qq.com"||r.endsWith(".weixin.qq.com")}function ZI(n){let r;try{r=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(r.protocol!=="https:"||!l0(r.hostname)||r.port!==""&&r.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 r.username="",r.password="",r.search="",r.hash="",r.pathname.endsWith("/")||(r.pathname+="/"),r.toString()}function aye(n){let r=aa(n);if(!r)throw new qA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(r)}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:"||!l0(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 J3(){return{"iLink-App-Id":Wfe,"iLink-App-ClientVersion":String(Zfe)}}function iye(n){let r={...J3(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(jfe(4).readUInt32BE(0)),"utf8").toString("base64")};return aa(n)&&(r.Authorization=`Bearer ${n.trim()}`),r}function HQ(){return{channel_version:qfe,bot_agent:"DeepSeekHarness/0.11.0"}}function x3(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function WI(n,{method:r,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=Xfe,signal:t,authenticated:s=!0}){let g=ZI(o),c=new URL(i,g);if(!l0(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 x3(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:r,headers:s?iye(a):J3(),...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?x3(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 oye(n){if(!n||typeof n!="object"||!$fe.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 q3({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({inboundImages(r){return I0(r,{fetchImpl:n})},async beginLogin({localTokens:r=[],botType:o=Vfe,signal:i}={}){let e=[...new Set(r.map(aa).filter(Boolean))].slice(-10),a=await WI(n,{method:"POST",baseUrl:KQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=aa(a?.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:aye(a.qrcode_img_content)}},async pollLogin({qrcode:r,baseUrl:o=KQ,verifyCode:i,signal:e}){let a=aa(r);if(!a)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(a)}`;aa(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await WI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y3,signal:e,authenticated:!1});return oye(t)},async getUpdates({baseUrl:r,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:a}){try{return await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:HQ()},token:o,timeoutMs:e??Y3,signal:a})}catch(A){if(A instanceof qA&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:r,token:o,toUserId:i,text:e,contextToken:a,runId:A,signal:t}){let s=aa(i),g=aa(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Jfe()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...aa(a)?{context_token:a.trim()}:{},...aa(A)?{run_id:A.trim()}:{}},base_info:HQ()}});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:r,token:o,signal:i}){let e=await WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}});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:r,token:o,signal:i}){return WI(n,{method:"POST",baseUrl:r,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:HQ()}})}})}function DC(n){for(let r of n?.item_list??[]){if(r?.type===1&&typeof r.text_item?.text=="string"){let o=r.text_item.text.trim();if(o)return o}if(r?.type===3&&typeof r.voice_item?.text=="string"){let o=r.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):aa(n?.client_id)}function V3(n,r=4e3){if(n.length<=r)return[n];let o=[],i=n;for(;i.length>r;){let e=i.lastIndexOf(` `,r);ea===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of r){if(o.has(a.botId)||i.has(a.accountId)||e.has(a.tokenRef))return null;o.add(a.botId),i.add(a.accountId),e.add(a.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(r)})}var YQ=class{#e;#A=p0;#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{let r=Cye(JSON.parse(await gye(this.#e,"utf8")));if(!r)throw new Error("dsh-weixin config contains invalid account data");this.#A=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=p0}return this}list(){return structuredClone(this.#A.accounts)}get(r){let o=this.#A.accounts.find(i=>i.botId===r);return o?structuredClone(o):null}getByAccountId(r){let o=this.#A.accounts.find(i=>i.accountId===r);return o?structuredClone(o):null}async save(r){let o=W3(r);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#r(i=>{let e=i.find(t=>t.accountId===o.accountId&&t.botId!==o.botId),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)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(r){if(!z3(r))throw new TypeError("Invalid Weixin bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#t.then(async()=>{try{await Iye(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=p0});this.#t=r.then(()=>{},()=>{}),await r}async#r(r){let o,i=this.#t.then(async()=>{let e=[...this.#A.accounts];o=r(e);let a=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#g(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#g(r){await sye(Eye(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await lye(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await cye(o,this.#e)}};var xQ=class extends qt{constructor(r){super({...r,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as hye,readFile as dye,rename as uye,unlink as Bye,writeFile as Qye}from"node:fs/promises";import{dirname as fye}from"node:path";var jQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function yye(n){if(!n||typeof n!="object")return structuredClone(jQ);let r={};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&&(r[o]=i);return{version:1,sessions:r,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:""}}var JQ=class{#e;#A=structuredClone(jQ);#t=Promise.resolve();constructor(r){this.#e=r}async load(){try{this.#A=yye(JSON.parse(await dye(this.#e,"utf8")))}catch(r){if(r?.code!=="ENOENT")throw r;this.#A=structuredClone(jQ),await this.#r()}return this}sessionFor(r){return this.#A.sessions[r]??null}async setSession(r,o){this.#A.sessions[r]=o,await this.#r()}async clearSession(r){delete this.#A.sessions[r],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(r){return this.#A.seenMessageIds.includes(r)}async markSeen(r){this.hasSeen(r)||(this.#A.seenMessageIds.push(r),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}getUpdatesBuf(){return this.#A.getUpdatesBuf}async setGetUpdatesBuf(r){typeof r!="string"||r===this.#A.getUpdatesBuf||(this.#A.getUpdatesBuf=r,await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await Bye(this.#e)}catch(r){if(r?.code!=="ENOENT")throw r}this.#A=structuredClone(jQ)}async#r(){let r=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await hye(fye(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await Qye(i,r,{encoding:"utf8",mode:384}),await uye(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as mye}from"node:crypto";var Z3=new Set(["starting","pending","scanned","needs_verification","connecting"]),qQ=new Set(["connected","expired","failed","cancelled"]),X3=5*6e4;function XI(n){return typeof n=="string"&&n.trim()?n.trim():null}function Sye(){return new DOMException("Provisioning was cancelled","AbortError")}function $3(n,r){let o=XI(n);return o?ZI(o.includes("://")?o:`https://${o}`):ZI(r)}function wC(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 Ua(n,r){return Object.freeze({code:n,message:r})}var OC=class{#e;#A;#t;#r;#g;#n;#E=new Map;#s=new Map;#I=new Map;#a=null;#i=new Map;#o=0;#c=!1;constructor({api:r,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!r||typeof r.beginLogin!="function"||typeof r.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=r,this.#A=o,this.#t=i,this.#r=e,this.#g=a,this.#n=A}async initialize(){if(this.#c)return this.status();for(let r of this.#t.list())this.#E.get(r.botId)?.status?.ready!==!0&&await this.#B(r.botId,async()=>{let i=this.#t.get(r.botId);if(!(!i||this.#c))try{let e=await this.#d(i.tokenRef);if(!e){this.#s.set(i.botId,Ua("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,Ua("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.#a&&await this.cancelProvisioning(this.#a);let r={id:mye(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+X3,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:KQ,error:null,botId:null,task:null};this.#I.set(r.id,r),this.#a=r.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:r.controller.signal});return this.#u(r),r.qrcode=i.qrcode,r.verificationUrl=i.qrcodeUrl,r.state="pending",r.expiresAt=Date.now()+X3,this.#f(),r.task=this.#l(r),wC(r)}catch(o){throw r.controller.signal.aborted?(r.state="cancelled",r.error=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Ua(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.#a===r.id&&(this.#a=null),this.#f(),o}}registrationStatus(r){return wC(this.#I.get(r))}async submitVerification(r,o){let i=this.#I.get(r);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=XI(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(),wC(i)}async cancelProvisioning(r){let o=this.#I.get(r);return o?(qQ.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),qQ.has(o.state)||(o.state="cancelled"),o.error??=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#a===o.id&&(this.#a=null),this.#f(),wC(o)):null}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return await this.#B(r,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(r)}catch(e){throw this.#s.set(r,Ua("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return this.#B(r,async()=>{let i=this.#E.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw kt("\u5FAE\u4FE1\u673A\u5668\u4EBA");return i.sendConnectionTest(Yr(`\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08${h0(o.accountId)}\uFF09`))})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error("Unknown Weixin account");return await this.#B(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#C(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}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:r,config:o})}catch(e){this.#n.warn?.(`[dsh-weixin] account ${r} state cleanup failed:`,e)}this.#s.delete(r),this.#f()}),this.status()}status(){let r=this.#t.list().map(e=>{let a=this.#E.get(e.botId)?.status??null,A=a?.ready===!0&&a.weixinConnectionState==="connected"&&a.harnessReachable===!0,t=A?"connected":a?.weixinConnectionState==="connecting"?"connecting":this.#s.has(e.botId)||a?.weixinConnectionState==="failed"?"error":"offline",s=this.#s.get(e.botId)??(t==="error"?Ua("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:h0(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:a?.lastCheckedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},error:s?structuredClone(s):null}}),o=r.filter(e=>e.connected).length,i=this.#a?this.#I.get(this.#a):null;return{schemaVersion:1,revision:this.#o,state:i&&Z3.has(i.state)?"provisioning":r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o},...i&&Z3.has(i.state)?{provisioning:wC(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#a&&await this.cancelProvisioning(this.#a),await Promise.allSettled([...this.#E.keys()].map(r=>this.#C(r))))}async#l(r){try{for(;!r.controller.signal.aborted&&Date.now(){r.verifyResolve=i,r.controller.signal.aborted&&i()}),r.verifyResolve=null,this.#u(r));let o=await this.#e.pollLogin({qrcode:r.qrcode,baseUrl:r.currentBaseUrl,verifyCode:r.pendingVerifyCode,signal:r.controller.signal});if(this.#u(r),o.status==="wait")r.state="pending";else if(o.status==="scaned")r.pendingVerifyCode=null,r.state="scanned";else if(o.status==="need_verifycode")r.pendingVerifyCode=null,r.state="needs_verification";else if(o.status==="verify_code_blocked"){r.state="failed",r.error=Ua("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"){r.state="expired",r.error=Ua("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002");break}else if(o.status==="scaned_but_redirect")r.currentBaseUrl=$3(o.redirect_host,r.currentBaseUrl),r.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?(r.state="connected",r.botId=i.botId,r.alreadyConnected=!0):(r.state="failed",r.error=Ua("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=XI(o.bot_token),e=XI(o.ilink_bot_id),a=XI(o.ilink_user_id);if(!i||!e||!a)throw new qA("incomplete-login","\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002");r.state="connecting",this.#f();let A=$3(o.baseurl,r.currentBaseUrl);r.botId=await this.#p(r,{token:i,accountId:e,ownerUserId:a,baseUrl:A}),r.state="connected",r.error=null;break}this.#f()}!r.controller.signal.aborted&&Date.now()>=r.expiresAt&&!qQ.has(r.state)&&(r.state="expired",r.error=Ua("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"))}catch(o){r.controller.signal.aborted||o?.name==="AbortError"?(r.state="cancelled",r.error=Ua("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(r.state="failed",r.error=Ua(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{r.pendingVerifyCode=null,r.verifyResolve?.(),r.verifyResolve=null,this.#a===r.id&&(this.#a=null),this.#f(),this.#y()}}async#p(r,{token:o,accountId:i,ownerUserId:e,baseUrl:a}){let A=C0(i),t=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:a,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(r),await this.#t.save(s),this.#u(r),await this.#h(s,o),this.#u(r),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(r,o){await this.#C(r.botId);let i=await this.#r({botId:r.botId,config:r,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(r.botId,i)}catch(e){throw await i.stop().catch(()=>{}),e}}async#C(r){let o=this.#E.get(r);this.#E.delete(r),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-weixin] account ${r} failed to stop cleanly:`,i)})}async#d(r){let o=await this.#A.resolve(r).catch(()=>{});return XI(o?.value)}async#Q(r,o){try{o?.value?await this.#A.set(r,o.value):await this.#A.unset(r)}catch(i){this.#n.error?.(`[dsh-weixin] failed to restore credential ${r}:`,i)}}#u(r){if(r.controller.signal.aborted||this.#a!==r.id)throw Sye()}#B(r,o){let a=(this.#i.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#i.get(r)===a&&this.#i.delete(r)});return this.#i.set(r,a),a}#y(){for(let[r,o]of this.#I)r!==this.#a&&qQ.has(o.state)&&this.#I.size>16&&this.#I.delete(r)}#f(){this.#o+=1}};var VQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",Dye=["\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 f54eb19..e1c60c5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@xmanrui/dsh-im", - "version": "0.10.0", + "version": "0.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@xmanrui/dsh-im", - "version": "0.10.0", + "version": "0.11.0", "license": "MIT", "dependencies": { "@tencent-connect/qqbot-connector": "1.2.0", diff --git a/package.json b/package.json index 2dc22ff..28be84e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@xmanrui/dsh-im", - "version": "0.10.0", + "version": "0.11.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 2919209..874c77c 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.10.0)', + 'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.11.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 ff2fa05..95201bd 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.10.0', + bot_agent: 'DeepSeekHarness/0.11.0', }; } diff --git a/test/channels/weixin/weixin-api.test.mjs b/test/channels/weixin/weixin-api.test.mjs index 5688bc4..4d7bd09 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.10.0'); + assert.equal(body.base_info.bot_agent, 'DeepSeekHarness/0.11.0'); assert.doesNotMatch(calls[0].init.body, /host-only-token/); });