diff --git a/lib/index.js b/lib/index.js index 576a0f4..f94c037 100644 --- a/lib/index.js +++ b/lib/index.js @@ -81,7 +81,7 @@ ${sP}`:["session-not-registered","session-not-found"].includes(n?.code)?"\u672A\ `).trim();c&&c!==this.#o&&(this.#o=c,o={type:"text",text:c});continue}if(e.type==="assistant/message"){let A=Mee(e);A&&A!==this.#o&&(this.#o=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}},Js=class extends Error{constructor(a,o){super(`${a}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=a,this.code=o?.code??"internal",this.details=o?.details??{}}},Nc=class extends Error{constructor(a,o){super(o),this.name="HarnessInteractionError",this.code=a}},Kt=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i;#t=null;#g;#c;#l;constructor({baseUrl:a,workspace:o,agentPreset:i="standard",autostart:e=!1,dshBin:r="dsh",fetchImpl:A=fetch,createWebSocket:t=l=>new WebSocket(l),interactionReconnectDelayMs:s=500,rpcIdPrefix:g="im",logPrefix:c="dsh-im"}){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");this.#A=new URL(a),this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g.trim(),this.#i=c.trim(),this.#g=See(this.#A.origin),this.#c=this.#g.ownerships,this.#l=this.#g.claims}async rpc(a,o={},i=3e4,e={}){let r=e.rpcId??`${this.#I}-${CP()}`,A=AbortSignal.timeout(i),t=e.signal?AbortSignal.any([e.signal,A]):A,s=await this.#o(new URL(`/api/${a}`,this.#A),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:r,method:a,payload:o}),signal:t});if(!s.ok)throw new Error(`Harness transport ${a} failed: HTTP ${s.status}`);let g=await s.json();if(g?.type!=="server-response"||g?.rpcId!==r)throw new Error(`Harness returned an invalid response for ${a}`);if(!g.result?.ok)throw new Js(a,g.result?.error);return g.result.value}async health(a={}){return await this.rpc("host.describe",{},5e3,a),!0}async ensureRunning(a={}){try{return await this.health(a)}catch(e){if(!this.#r)throw e}if(!this.#t||this.#t.exitCode!==null){let e=this.#A.port||(this.#A.protocol==="https:"?"443":"80");this.#t=yee(this.#s,["web","--host",this.#A.hostname,"--port",e],{cwd:this.#e,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#t.on("error",r=>{console.error(`[${this.#i}] failed to start Harness:`,r.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return r?r.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(a={}){await this.ensureRunning(a);let o=await this.workspaceId(a);return(await this.rpc("session.create",{workspaceId:o,agentPreset:this.#a},3e4,a)).sessionId}async sessionExists(a,o={}){try{return await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof Js&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(a,o,i={}){if(typeof a!="string"||!a)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),r=i.signal?AbortSignal.any([i.signal,e]):e,A=await this.#o(new URL("/api/respond",this.#A),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-response",rpcId:a,result:o}),signal:r});if(!A.ok)throw new Error(`Harness transport respond failed: HTTP ${A.status}`);let t=await A.json();if(t?.accepted===!0)return t;if(t?.accepted!==!1||t.reason!=="bad-response"&&t.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=t.reason;throw new Nc(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A}={}){if(typeof a!="string"||!a)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(r!==void 0&&typeof r!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#B(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A})}catch(t){if(o.aborted)return;console.warn(`[${this.#i}] Harness interaction stream disconnected:`,t.message)}if(o.aborted)return;try{await td(this.#n,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#C(a,o){let i=this.#c.get(a)??new Set;o.order=this.#g.nextOrder,this.#g.nextOrder+=1,i.add(o),this.#c.set(a,i)}#h(a,o){let i=this.#c.get(a);i?.delete(o),i?.size===0&&this.#c.delete(a);for(let[e,r]of this.#l)r.ownership===o&&this.#l.delete(e)}#p(a,o){for(let i of this.#c.get(a)??[])bee(i,o)}async#d(a,o){let i=await this.rpc("session.history",{sessionId:a,maxMessages:50},3e4,{signal:o});this.#p(a,i.events??[])}#u(a,o,i){let e=this.#l.get(o);if(e&&this.#c.get(a)?.has(e.ownership))return e;let r=[...this.#c.get(a)??[]],A=r.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};if(i!=="question")return null;let t=r.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return t?{ownership:t,recovered:!0}:null}async ask(a,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,r=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,t=typeof i.onInteraction=="function"?i.onInteraction:void 0,s=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0;await this.ensureRunning({signal:r});let g=await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,{signal:r}),c=Math.max(-1,...(g.events??[]).map(({event:m})=>m.seq??-1)),l=`${this.#I}-${CP()}`,C=new _c({promptRpcId:l,afterSeq:c}),u=t||s?new AbortController:null,Q=u?r?AbortSignal.any([r,u.signal]):u.signal:null,f=u?{promptRpcId:l,active:!1,started:!1,completed:!1,turn:null,openTurn:null,lastSeq:c,reconnect:null,order:-1}:null,y=null;f&&this.#C(a,f);try{if(Q){let T,k=new Promise(F=>{T=F});y=this.watchInteractions(a,{signal:Q,onInteraction:t,onResolved:s,onOpen:T,ownership:f}),y.catch(()=>{}),await Promise.race([k,td(3e4,Q).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}await this.rpc("session.prompt",{sessionId:a,mode:"queue",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:l,signal:r});let m=Date.now()+e;for(;Date.now(){}),f&&this.#h(a,f)}}#B(a,{signal:o,onInteraction:i,onResolved:e,onOpen:r,ownership:A}){let t=new URL("/api/events.mux",this.#A);return t.protocol=t.protocol==="https:"?"wss:":"ws:",new Promise((s,g)=>{let c;try{c=this.#E(t.toString())}catch(G){g(G);return}let l=!1,C=!1,u=null,Q=Promise.resolve(),f=A==null,y=[],m=G=>{C||(C=!0,c.removeEventListener("open",k),c.removeEventListener("message",x),c.removeEventListener("close",H),c.removeEventListener("error",J),o.removeEventListener("abort",K),A?.reconnect===T&&(A.reconnect=null),Q.then(()=>{let R=G??u;R?g(R):s()},g))},T=()=>{try{(c.readyState===0||c.readyState===1)&&c.close()}catch{}},k=()=>{l=!0,A&&(A.reconnect=T);try{r?.()}catch(G){console.warn(`[${this.#i}] ignored an interaction open callback failure:`,G.message)}A&&this.#d(a,o).then(()=>{if(!C){f=!0;for(let G of y.splice(0))j(G)}}).catch(G=>{u??=G,T(),m(G)})},F=(G,R)=>{G&&(Q=Q.then(()=>G(R)).catch(Z=>{u??=Z,T(),m(u)}))},j=G=>{let R=G.payload;if(A&&R.type==="session/event"){this.#p(a,[R.event]);return}if(R.type==="question/requested"||R.type==="approval/requested"){let Z=R.type==="question/requested"?"question":"approval",U=Z==="question"?G.rpcId:R.approvalId,b=`${Z}:${U}`;if(A){let L=this.#u(a,b,Z);if(L?.ownership!==A)return;this.#l.set(b,L)}F(i,Object.freeze({kind:Z,interactionId:U,rpcId:G.rpcId,sessionId:a,payload:R,recovered:A?this.#l.get(b)?.recovered===!0:!1,reconnect:T,respond:(L,ee={})=>this.respondInteraction(G.rpcId,L,{...ee,signal:ee.signal??o})}));return}if(R.type==="question/resolved"||R.type==="approval/resolved"){let Z=R.type==="question/resolved"?"question":"approval",U=Z==="question"?R.questionRpcId:R.approvalId,b=`${Z}:${U}`;if(A){if(this.#l.get(b)?.ownership!==A)return;this.#l.delete(b)}F(e,Object.freeze({kind:Z,interactionId:U,sessionId:a,outcome:R.outcome,payload:R}))}},x=G=>{try{if(typeof G.data!="string")throw new Error("binary WebSocket frame");let R=JSON.parse(G.data),Z=R?.payload;if(R?.type!=="server-request"||typeof R.rpcId!="string"||!Z||typeof Z!="object"||R.method!==Z.type)throw new Error("invalid server-request envelope");if(Z.sessionId!==a)return;f?j(R):y.push(R)}catch(R){console.warn(`[${this.#i}] ignored a malformed Harness interaction frame:`,R.message)}},H=()=>m(l?null:new Error("Harness interaction WebSocket closed before opening")),J=()=>{m(new Error(l?"Harness interaction WebSocket failed":"Harness interaction WebSocket failed before opening")),T()},K=()=>{T(),m()};c.addEventListener("open",k),c.addEventListener("message",x),c.addEventListener("close",H,{once:!0}),c.addEventListener("error",J,{once:!0}),o.addEventListener("abort",K,{once:!0}),o.aborted&&K()})}stopManagedProcess(){this.#t?.exitCode===null&&this.#t.kill("SIGTERM")}};var ad=class extends Kt{constructor(a){super({...a,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{randomUUID as _ee}from"node:crypto";import{mkdir as Nee,readFile as Tee,rename as Ree,unlink as kee,writeFile as vee}from"node:fs/promises";import{dirname as Pee}from"node:path";var rd=Object.freeze({version:1,sessions:{},seenMessageIds:[],pendingSenders:{}});function _t(n){return typeof n=="string"&&n.trim()?n.trim():null}function hP(n){return(_t(n)??"\u9489\u9489\u7528\u6237").slice(0,100)}function Gee(n,a){if(!n||typeof n!="object")return null;let o=_t(n.requestId)??_t(a),i=_t(n.staffId),e=_t(n.requestedAt)??_t(n.lastSeenAt),r=_t(n.lastSeenAt)??e;return!o||!i||!e||!r?null:{requestId:o,staffId:i,displayName:hP(n.displayName??n.nick),requestedAt:e,lastSeenAt:r}}function Fee(n){if(!n||typeof n!="object")return structuredClone(rd);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,r]of Object.entries(n.sessions)){let A=_t(e),t=_t(r);A&&t&&(a[A]=t)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,r]of i){let A=Gee(r,e);if(!A)continue;let t=Object.values(o).find(s=>s.staffId===A.staffId);(!t||t.lastSeenAtnew Date().toISOString()}={}){if(!_t(a))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#A=a,this.#r=o,this.#s=i}async load(){try{this.#e=Fee(JSON.parse(await Tee(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(rd),await this.#o()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){let i=_t(a),e=_t(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#e.sessions[i]=e,await this.#o()}async clearSession(a){let o=_t(a);!o||!(o in this.#e.sessions)||(delete this.#e.sessions[o],await this.#o())}async clearSessions(){this.#e.sessions={},await this.#o()}hasSeen(a){let o=_t(a);return!!(o&&this.#e.seenMessageIds.includes(o))}async markSeen(a){let o=_t(a);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#e.seenMessageIds.push(o),this.#e.seenMessageIds.length>1e3&&this.#e.seenMessageIds.splice(0,this.#e.seenMessageIds.length-1e3),await this.#o())}pendingSenders(){return Object.values(this.#e.pendingSenders).sort((a,o)=>a.requestedAt.localeCompare(o.requestedAt)).map(a=>structuredClone(a))}pendingSender(a){let o=_t(a),i=o?this.#e.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(a,o,i){let e=a&&typeof a=="object"?a:{staffId:a,displayName:o,lastSeenAt:i},r=_t(e.staffId);if(!r)throw new TypeError("staffId is required");let A=_t(e.lastSeenAt)??_t(e.requestedAt)??this.#s(),t=Object.values(this.#e.pendingSenders).find(g=>g.staffId===r),s={requestId:t?.requestId??`ding_sender_${this.#r()}`,staffId:r,displayName:hP(e.displayName??e.nick??o),requestedAt:t?.requestedAt??A,lastSeenAt:A};return this.#e.pendingSenders[s.requestId]=s,await this.#o(),structuredClone(s)}async removePendingSender(a){let o=_t(a);return!o||!this.#e.pendingSenders[o]?!1:(delete this.#e.pendingSenders[o],await this.#o(),!0)}async removePendingSenderByStaffId(a){let o=_t(a),i=o?Object.values(this.#e.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#e)}async remove(){await this.#a;try{await kee(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(rd)}async#o(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#a.then(async()=>{await Nee(Pee(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await vee(i,a,{encoding:"utf8",mode:384}),await Ree(i,this.#A)});this.#a=o.then(()=>{},()=>{}),await o}};import{mkdir as Lee,readFile as Uee,realpath as Hee,rename as Kee,stat as Yee,unlink as xee,writeFile as jee}from"node:fs/promises";import{dirname as Jee,isAbsolute as uP,resolve as EE}from"node:path";var CFe=Object.freeze({version:1,workspaces:Object.freeze({})});function od(n){let a=new Error(n);return a.code=Oc,a}async function NS(n){return EE(await Hee(n))}async function qee(n,a){if(n===a)return!0;try{return await NS(n)===await NS(a)}catch{return!1}}function Yr(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function Vee(n){if(!n||n.version!==1||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let a={};for(let[o,i]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(o)||typeof i!="string"||!uP(i))return null;a[o]=EE(i)}return{version:1,workspaces:a}}async function dP(n){if(typeof n!="string"||!n.trim()||!uP(n.trim())){let i=new Error("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");throw i.code="workspace-not-absolute",i}let a=EE(n.trim()),o;try{o=await Yee(a)}catch(i){let e=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002",{cause:i});throw e.code="workspace-not-found",e}if(!o.isDirectory()){let i=new Error("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");throw i.code="workspace-not-directory",i}return a}var Ia=class{#A;#e;#a={};#r=new Map;#s=1;#o=new Map;#E=1;#n=new Map;#I=new WeakMap;#i=new Set;#t=Promise.resolve();#g=new Map;constructor(a,{defaultWorkspace:o=process.cwd()}={}){if(typeof a!="string"||!a)throw new TypeError("workspace store path is required");this.#A=a,this.#e=EE(o)}async load(){try{let a=Vee(JSON.parse(await Uee(this.#A,"utf8")));if(!a)throw new Error("dsh-im workspace config is invalid");this.#a=a.workspaces}catch(a){if(a?.code!=="ENOENT")throw a;this.#a={}}this.#r.clear(),this.#s=1,this.#o.clear(),this.#E=1,this.#n.clear(),this.#i.clear();for(let a of Object.keys(this.#a))this.#r.set(a,this.#c()),this.#o.set(a,this.#l());return this}has(a){let o=Yr(a);return Object.hasOwn(this.#a,o)&&!this.#n.has(o)}incarnationFor(a){return this.#o.get(Yr(a))??null}workspaceFor(a){return this.#a[Yr(a)]??this.#e}generationFor(a){return this.#r.get(Yr(a))??null}async whenIdle(){await this.#t}async whenBotIdle(a){let o=Yr(a);for(;;){let i=this.#g.get(o);if(!i||(await i,this.#g.get(o)===i))return}}async ensure(a,{workspace:o=this.#e}={}){let i=Yr(a),e=EE(o);return this.#p(i,async()=>{if(this.#a[i])this.#r.has(i)||this.#r.set(i,this.#c());else{this.#a[i]=e,this.#r.set(i,this.#c()),this.#o.set(i,this.#l());try{await this.#d()}catch(r){throw delete this.#a[i],this.#r.delete(i),this.#o.delete(i),r}}return this.#a[i]})}async setWorkspace(a,o,{clearSessions:i,incarnation:e}={}){let r=Yr(a);if(!this.has(r)||e!==void 0&&e!==this.incarnationFor(r)){let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}let A=await dP(o);return this.#p(r,async()=>{if(!this.has(r)||e!==void 0&&e!==this.incarnationFor(r)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}if(A===this.workspaceFor(r))return A;let t=this.#a[r];this.#r.set(r,this.#c()),await i?.(),this.#a[r]=A;try{await this.#d()}catch(s){throw this.#a[r]=t,s}return A})}async bindWorkspaceSession(a,o,{conversationKey:i,sessionId:e,clearSessions:r,setSession:A,incarnation:t,expectedGeneration:s}={}){let g=Yr(a);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof r!="function"||typeof A!="function")throw new TypeError("session state callbacks are required");if(!this.has(g)||t!==void 0&&t!==this.incarnationFor(g)){let l=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw l.code="workspace-bot-not-found",l}let c=await NS(await dP(o));return this.#p(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 od("The bot workspace changed before the session binding could be committed.");if(!await qee(c,this.workspaceFor(g))){let l=this.#a[g];this.#r.set(g,this.#c()),await r(),this.#a[g]=c;try{await this.#d()}catch(C){throw this.#a[g]=l,C}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#r.get(g)}})}async invalidateSessions(a,{clearSessions:o}={}){let i=Yr(a);return this.#p(i,async()=>{this.#r.set(i,this.#c()),await o?.()})}async beginRemoval(a,{clearSessions:o}={}){let i=Yr(a);return this.#p(i,async()=>{let e=this.#n.get(i);if(e)return e;let r=Object.freeze({});this.#n.set(i,r),this.#I.set(r,{botId:i,incarnation:this.incarnationFor(i)}),this.#r.set(i,this.#c());try{await o?.()}catch(A){throw this.#n.get(i)===r&&this.#n.delete(i),A}return r})}async abortRemoval(a){let{botId:o}=this.#C(a);return this.#p(o,async()=>this.#n.get(o)!==a?!1:(this.#n.delete(o),Object.hasOwn(this.#a,o)&&(this.#r.set(o,this.#c()),this.#o.has(o)||this.#o.set(o,this.#l())),!0))}async finishRemoval(a){let{botId:o,incarnation:i}=this.#C(a);return this.#p(o,async()=>this.#n.get(o)!==a?{removed:!1,persisted:!0,error:null,stale:!0}:this.incarnationFor(o)!==i?(this.#n.delete(o),{removed:!1,persisted:!0,error:null,stale:!0}):(this.#n.delete(o),this.#h(o)))}async retireAfterConfigCommit(a){let o=Yr(a);return this.#p(o,async()=>(this.#n.delete(o),this.#h(o)))}async remove(a){let o=await this.retireAfterConfigCommit(a);if(o.error)throw o.error;return o.removed}async reconcile(a){let o=new Set([...a].map(Yr)),i=new Set([...Object.keys(this.#a),...this.#i]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(a){return!a||typeof a!="object"||!Array.isArray(a.bots)?a:{...a,bots:a.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId)}:o)}}#c(){let a=this.#s;return this.#s+=1,a}#l(){let a=this.#E;return this.#E+=1,a}#C(a){if(!a||typeof a!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#I.get(a);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#h(a){let o=Object.hasOwn(this.#a,a),i=o||this.#i.has(a);if(delete this.#a[a],this.#r.delete(a),this.#o.delete(a),!i)return{removed:!1,persisted:!0,error:null,stale:!1};try{return await this.#u(),{removed:o,persisted:!0,error:null,stale:!1}}catch(e){return this.#i.add(a),{removed:o,persisted:!1,error:e,stale:!1}}}async#p(a,o){let i=this.#t.then(o,o),e=i.then(()=>{},()=>{});return this.#t=e,this.#g.set(a,e),e.finally(()=>{this.#g.get(a)===e&&this.#g.delete(a)}),i}async#d(){let a={version:1,workspaces:this.#a};await Lee(Jee(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await jee(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await Kee(o,this.#A),this.#i.clear()}async#u(){if(Object.keys(this.#a).length>0){await this.#d();return}try{await xee(this.#A),this.#i.clear()}catch(a){if(a?.code!=="ENOENT")throw a;this.#i.clear()}}};function BP(n,a){return a&&typeof a.then=="function"?a.then(o=>n.decorateStatus(o)):n.decorateStatus(a)}function zee(n){return Promise.resolve(n.status())}function La(n,{workspaces:a,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!a||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,r){let A=Reflect.get(e,r,e);return r===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await a.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function Ua(n,{botId:a,workspaces:o,state:i}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let e=o.incarnationFor(a),r=()=>o.has(a)&&o.incarnationFor(a)===e,A=new Map,t=new Proxy(n,{get(g,c){if(c==="currentWorkspace")return()=>{if(!r()){let C=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw C.code="workspace-bot-not-found",C}return o.workspaceFor(a)};if(c==="assertWorkspaceScope")return()=>{if(!r()){let C=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw C.code="workspace-bot-not-found",C}};if((c==="listWorkspaces"||c==="listWorkspaceSessions")&&typeof g[c]=="function")return async(...C)=>{if(!r()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}let u=await g[c](...C);if(!r()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}return u};if(c==="switchWorkspace")return C=>{if(!r()){let u=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return u.code="workspace-bot-not-found",Promise.reject(u)}return o.setWorkspace(a,C,{clearSessions:()=>i.clearSessions(),incarnation:e})};if(c==="bindWorkspaceSession")return async(C,u)=>{if(typeof C!="string"||!C||typeof u!="string"||!u)throw new TypeError("conversationKey and sessionId are required");if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(typeof g.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let Q=o.generationFor(a),f=await g.adoptWorkspaceSession(u);if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(Q!==o.generationFor(a))throw od("The bot workspace changed while the session was being adopted.");if(!f||typeof f!="object"||f.sessionId!==u||typeof f.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let y=await o.bindWorkspaceSession(a,f.workspace,{conversationKey:C,sessionId:u,clearSessions:()=>i.clearSessions(),setSession:(m,T)=>i.setSession(m,T),incarnation:e,expectedGeneration:Q});if(!r()){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}if(y.generation!==o.generationFor(a))throw od("The bot workspace changed before the session binding completed.");return A.set(u,y.generation),{...f,workspace:y.workspace,sessionId:y.sessionId}};if(c==="createSession")return async(C={})=>{if(await o.whenBotIdle(a),!r()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}let u=o.generationFor(a),Q=await g.createSession({...C,workspace:o.workspaceFor(a)});return A.set(Q,u),Q};if(c==="workspaceSession")return C=>{if(typeof C!="string"||!C)throw new TypeError("sessionId is required");let u=A.get(C)??o.generationFor(a);A.delete(C);let Q=()=>r()&&u===o.generationFor(a);return Object.freeze({sessionId:C,async sessionExists(...f){if(!Q())return!1;let y=await g.sessionExists(C,...f);return Q()&&y},ask(...f){if(!Q())throw od("The bot workspace changed before this prompt started.");return g.ask(C,...f)}})};if(c==="sessionExists")return(C,...u)=>{if(!r())return!1;let Q=A.get(C);return Q!==void 0&&Q!==o.generationFor(a)?(A.delete(C),!1):g.sessionExists(C,...u)};if(c==="ask")return(C,...u)=>{let Q=A.get(C);if(A.delete(C),!r()||Q!==void 0&&Q!==o.generationFor(a)){let f=new Error("The bot workspace changed before this prompt started.");throw f.code=Oc,f}return g.ask(C,...u)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}}),s=new Proxy(i,{get(g,c){if(c==="sessionFor")return(C,...u)=>{if(!r())return null;let Q=g.sessionFor(C,...u);return Q&&!A.has(Q)&&A.set(Q,o.generationFor(a)),Q};if(c==="setSession")return(C,u,...Q)=>{let f=A.get(u);return!r()||f!==void 0&&f!==o.generationFor(a)?(A.delete(u),!1):g.setSession(C,u,...Q)};let l=Reflect.get(g,c,g);return typeof l=="function"?l.bind(g):l}});return Object.freeze({harness:t,state:s})}function Ha(n,{workspaces:a,stateFor:o}){if(!n||!a||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let i=new Map,e=(t,s)=>{let c=(i.get(t)??Promise.resolve()).catch(()=>{}).then(s);return i.set(t,c),c.finally(()=>{i.get(t)===c&&i.delete(t)})},r=(t,s)=>{let g=a.incarnationFor(t);return e(t,async()=>{if(!(await n.status())?.bots?.some(C=>C?.botId===t)){let C=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw C.code="workspace-bot-not-found",C}let l=await o(t);return await a.setWorkspace(t,s,{clearSessions:()=>l.clearSessions(),incarnation:g}),a.decorateStatus(await n.status())})},A=(t,s)=>e(t,async()=>{let g=await a.beginRemoval(t,{clearSessions:async()=>{try{let c=await o(t);if(!c||typeof c.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await c.clearSessions()}catch(c){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${t}:`,c?.message??c)}}});try{let c=await s();return await a.finishRemoval(g),a.decorateStatus(c)}catch(c){let l=await zee(n).catch(()=>null);throw Array.isArray(l?.bots)&&!l.bots.some(u=>u?.botId===t)?await a.finishRemoval(g):await a.abortRemoval(g),c}});return new Proxy(n,{get(t,s){if(s==="updateWorkspace")return r;let g=Reflect.get(t,s,t);return typeof g!="function"?g:s==="deleteBot"?(c,...l)=>A(c,()=>g.call(t,c,...l)):s==="disconnect"?async(...c)=>{let C=(await t.status())?.bots?.[0]?.botId;return C?A(C,()=>g.apply(t,c)):BP(a,g.apply(t,c))}:(...c)=>BP(a,g.apply(t,c))}})}var QP=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function Wee(n){if(!Array.isArray(n)||n.length===0)return[...QP];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...QP]}var nd=class{#A;#e;#a;#r;#s;#o;#E;#n=null;#I=null;#i=0;#t=!1;#g=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#A=a,this.#e=o,this.#a=i,this.#r=Wee(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#g||this.#t?this:(this.#g=!0,this.#C(0),this)}async close(){this.#t||(this.#t=!0,this.#n!==null&&this.#E(this.#n),this.#n=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#C(a){this.#t||(this.#n=this.#o(()=>{this.#n=null,this.#h()},a),this.#n?.unref?.())}async#h(){if(this.#t||this.#I)return;let a=this.#p();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#t)return;let a=await this.#A.initialize();if(this.#t)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-dingtalk requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function eAe(n){let a=qs(n.dshHome??process.env.DSH_HOME??CE(Xee(),".dsh")),o=qs(n.dataDir??CE(a,"integrations","dsh-dingtalk"));return{root:o,config:qs(n.configPath??CE(o,"config.json")),bots:qs(n.botsDir??CE(o,"bots")),workspaces:qs(n.workspacesPath??CE(o,"workspaces.json"))}}async function RS(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-dingtalk requires ctx.webServer");let i=o.ConfigStore??qh,e=o.DeviceAuth??zh,r=o.StateStore??id,A=o.HarnessClient??ad,t=o.Controller??sE,s=o.Runtime??IE,g=o.createConnectionSupervisor??TS,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=eAe(a),C=await new i(l.config).load(),u=qs(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ia,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:u}).load(),y=typeof C.list=="function",m=y?C.list():[];y&&await f.reconcile(m.map(R=>R.botId)),await Promise.all(m.map(R=>f.ensure(R.botId)));let T=typeof C.remove=="function"?La(C,{workspaces:f}):C,k=o.deviceAuth??new e({baseUrl:a.registrationBaseUrl}),F=new Map,j=R=>qs(l.bots,R,"state.json"),x=async R=>{let Z=F.get(R);return Z||(Z=await new r(j(R)).load(),F.set(R,Z)),Z},H=new A({baseUrl:$ee(n.webServer,a.harnessBaseUrl),workspace:u,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh"}),J=new t({deviceAuth:k,credentials:n.credentials,configStore:T,logger:c,createRuntime:async({botId:R,config:Z,clientSecret:U})=>{let b=await x(R);await f.ensure(R);let L=Ua(H,{botId:R,workspaces:f,state:b});return new s({config:Z,clientSecret:U,harness:L.harness,state:L.state,replyTimeoutMs:a.replyTimeoutMs??6e5,maxMessageChars:a.maxMessageChars??4e3,connectTimeoutMs:a.connectTimeoutMs??15e3,logger:{error:(...ee)=>c.error?.(`[${R}]`,...ee),warn:(...ee)=>c.warn?.(`[${R}]`,...ee),info:(...ee)=>c.info?.(`[${R}]`,...ee),debug:(...ee)=>c.debug?.(`[${R}]`,...ee)}})},deleteState:async({botId:R})=>{let Z=F.get(R);if(F.delete(R),Z&&typeof Z.remove=="function")await Z.remove();else try{await Zee(j(R))}catch(U){if(U?.code!=="ENOENT")throw U}}}),K=Ha(J,{workspaces:f,stateFor:x}),G=g({controller:K,harness:H,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:K,ready:G.ready,async close(){await G.close(),await K.close(),H.stopManagedProcess()}}}import aAe from"qrcode";var AAe=new Set(["loopback","trusted-host"]);function Ka(n){if(n===void 0)return"loopback";if(AAe.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as tAe}from"node:path";var or="bot.workspace.set";function Ya(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(a=>["botId","workspace"].includes(a))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&tAe(n.workspace.trim())}function xa(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 yP="/dingtalk",Lt=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:or,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),mP=Object.freeze(Object.values(Lt)),rAe=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function vS(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Pn(n,a){return vS(n)&&Object.keys(n).every(o=>a.includes(o))}function Vs(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function fP(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function iAe(n,a){return vS(a)?n===Lt.status?Pn(a,[])?null:"connection.status does not accept fields.":n===Lt.beginProvisioning?Pn(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Lt.pollProvisioning,Lt.cancelProvisioning].includes(n)?Pn(a,["attemptId"])&&Vs(a.attemptId)?null:`${n} requires an attemptId.`:n===Lt.bindCredentials?Pn(a,["clientId","clientSecret"])&&fP(a.clientId,256)&&fP(a.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Lt.reconnectBot?Pn(a,["botId"])&&Vs(a.botId)?null:"bot.reconnect requires a botId.":n===Lt.deleteBot?Pn(a,["botId","confirm"])&&Vs(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Lt.setWorkspace?Ya(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Lt.approveSender?Pn(a,["botId","requestId","confirm"])&&Vs(a.botId)&&Vs(a.requestId)&&a.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Lt.revokeSender?Pn(a,["botId","senderKey","confirm"])&&Vs(a.botId)&&Vs(a.senderKey)&&a.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function sd(n){return{ok:!1,error:{code:"bad-request",message:n}}}function gd(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function oAe(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Tc(n){if(Array.isArray(n))return n.map(Tc);if(!vS(n))return n;let a={};for(let[o,i]of Object.entries(n))rAe.has(o)||(a[o]=Tc(i));return a}async function nAe(n){return aAe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function kS(n,a){return!n||typeof n.verificationUrl!="string"?Tc(n):Tc({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function zs(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await kS(o.provisioning,a)),Tc(o)}function sAe(n){for(let a of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[a]!="function")throw new TypeError(`A complete DingTalk controller is required (${a})`)}function SP(n,{encodeQr:a=nAe}={}){sAe(n);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return gd();if(!mP.includes(e))return sd("Unknown DingTalk endpoint.");let t=iAe(e,r);if(t)return sd(t);try{let s;if(e===Lt.status)s=await zs(await n.status(),i);else if(e===Lt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),gd();s=await kS(g,i)}else if(e===Lt.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return sd("The provisioning attempt no longer exists.");s=await kS(g,i)}else if(e===Lt.cancelProvisioning){if(s=await n.cancelProvisioning(r.attemptId),!s)return sd("The provisioning attempt no longer exists.");s=Tc(s)}else if(e===Lt.bindCredentials)s=await zs(await n.bindCredentials(r),i);else if(e===Lt.reconnectBot)s=await zs(await n.reconnectBot(r.botId),i);else if(e===Lt.deleteBot)s=await zs(await n.deleteBot(r.botId),i);else if(e===Lt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await zs(await n.updateWorkspace(r.botId,r.workspace),i)}else e===Lt.approveSender?s=await zs(await n.approveSender(r.botId,r.requestId),i):s=await zs(await n.revokeSender(r.botId,r.senderKey),i);return A?.aborted?gd():{ok:!0,value:s}}catch(s){let g=xa(s);return A?.aborted?gd():g?{ok:!1,error:g}:oAe()}}}function cd(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(yP,SP(a,o),{authority:Ka(i)})}async function DP(n,a={}){if(a?.controller)return cd(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await RS(n,a,a.internals),i=cd(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as gAe}from"node:crypto";import{mkdir as cAe,readFile as IAe,rename as lAe,unlink as EAe,writeFile as CAe}from"node:fs/promises";import{dirname as pAe}from"node:path";var PS=Object.freeze({version:1,bots:Object.freeze([])});function jo(n){return typeof n=="string"&&n.trim()?n.trim():null}function wP(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pE(n,{botPrefix:a,tokenRefPrefix:o}){let i=jo(n);if(!i)throw new TypeError("platformId is required");let e=gAe("sha256").update(i).digest("hex").slice(0,24);return{botId:`${a}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function Id(n,a){let o=jo(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:a:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var Rc=class{#A;#e;#a;#r;#s;#o;#E=PS;#n=Promise.resolve();constructor(a,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=new RegExp(`^${wP(i)}_[a-f0-9]{24}$`),this.#o=new RegExp(`^${wP(e)}_[A-F0-9]{24}$`)}async load(){try{let a=this.#i(JSON.parse(await IAe(this.#A,"utf8")));if(!a)throw new Error(`dsh-im ${this.#e} config contains invalid bot data`);this.#E=a}catch(a){if(a?.code!=="ENOENT")throw a;this.#E=PS}return this}list(){return structuredClone(this.#E.bots)}get(a){let o=this.#E.bots.find(i=>i.botId===a);return o?structuredClone(o):null}getByPlatformId(a){let o=this.#E.bots.find(i=>i.platformId===a);return o?structuredClone(o):null}async save(a){let o=this.#I(a);if(!o)throw new Error(`Refusing to persist incomplete ${this.#e} bot data`);return this.#t(i=>{let e=i.find(t=>t.platformId===o.platformId&&t.botId!==o.botId),r=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||r)throw new Error(`Duplicate ${this.#e} bot identity`);let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(a){if(!this.#s.test(a))throw new TypeError(`Invalid ${this.#e} bot id`);return this.#t(o=>{let i=o.findIndex(r=>r.botId===a);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let a=this.#n.then(async()=>{try{await EAe(this.#A)}catch(o){if(o?.code!=="ENOENT")throw o}this.#E=PS});this.#n=a.then(()=>{},()=>{}),await a}#I(a){if(!a||typeof a!="object")return null;let o=jo(a.platformId),i=jo(a.botId),e=jo(a.tokenRef),r=jo(a.name);if(!o||!i||!e||!r||!this.#s.test(i)||!this.#o.test(e))return null;let A=pE(o,{botPrefix:this.#a,tokenRefPrefix:this.#r});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:r,username:jo(a.username),createdAt:jo(a.createdAt)??new Date().toISOString(),connectedAt:jo(a.connectedAt)})}#i(a){if(!a||a.version!==1||!Array.isArray(a.bots))return null;let o=a.bots.map(A=>this.#I(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,r=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||r.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),r.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#t(a){let o,i=this.#n.then(async()=>{let e=[...this.#E.bots];o=a(e);let r=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(r),this.#E=r});return this.#n=i.then(()=>{},()=>{}),await i,o}async#g(a){await cAe(pAe(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await CAe(o,`${JSON.stringify(a,null,2)} -`,{encoding:"utf8",mode:384}),await lAe(o,this.#A)}};var OP=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function MP(n){return pE(n,OP)}function bP(n){return Id(n,"Discord\u673A\u5668\u4EBA")}var ld=class extends Rc{constructor(a){super(a,{channel:"Discord",...OP})}};function hE(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ed(n,a){return Object.freeze({code:n,message:a})}var kc=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i=new Map;#t=new Map;#g=new Map;#c=0;#l=!1;constructor({descriptor:a,credentials:o,configStore:i,inspectToken:e,deriveIdentity:r,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!a?.key||!a?.label||!a?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${a.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${a.label} requires a config store`);if(typeof e!="function"||typeof r!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${a.label} controller dependencies are incomplete`);this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let a of this.#a.list())await this.#u(a.botId,async()=>{if(this.#l||this.#i.get(a.botId)?.status?.ready)return;let o=await this.#p(a.tokenRef);if(!o){this.#t.set(a.botId,Ed("missing-token",`${this.#A.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#C(a,o),this.#t.delete(a.botId)}catch(i){this.#t.set(a.botId,Ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a.botId} failed to initialize:`,i)}finally{this.#B()}});return this.status()}async bindCredentials({token:a}={}){if(this.#l)throw new Error(`${this.#A.label} controller is closed`);let o=hE(a);if(!o)throw new TypeError(`${this.#A.label} Bot Token is required`);let i=await this.#r(o),e=hE(i?.platformId),r=hE(i?.name);if(!e||!r)throw new Error(`${this.#A.label} returned an invalid bot identity`);let A=this.#s(e);return await this.#u(A.botId,async()=>{if(this.#l)throw new Error(`${this.#A.label} controller is closed`);let t=this.#a.getByPlatformId(e),s=await this.#e.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:hE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#e.set(A.tokenRef,o);try{await this.#a.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#C(g,o),this.#t.delete(A.botId)}catch(c){this.#t.set(A.botId,Ed("connection-failed",`${this.#A.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(a){let o=this.#a.get(a);if(!o)throw new Error(`Unknown ${this.#A.label} bot`);return await this.#u(a,async()=>{let i=await this.#p(o.tokenRef);if(!i)throw new Error(`${this.#A.label} bot token is missing`);try{await this.#C(o,i),this.#t.delete(a)}catch(e){throw this.#t.set(a,Ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#B()}}),this.status()}async deleteBot(a){let o=this.#a.get(a);if(!o)throw new Error(`Unknown ${this.#A.label} bot`);return await this.#u(a,async()=>{let i=await this.#e.resolve(o.tokenRef).catch(()=>{});await this.#h(a);try{await this.#e.unset(o.tokenRef),await this.#a.remove(a)}catch(e){throw i?.value&&(await this.#e.set(o.tokenRef,i.value).catch(()=>{}),await this.#C(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#A.label} bot safely.`,{cause:e})}await this.#n({botId:a,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a} state cleanup failed:`,e)}),this.#t.delete(a),this.#B()}),this.status()}status(){let a=this.#a.list().map(i=>{let e=this.#i.get(i.botId)?.status??null,r=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=r?"connected":e?.connectionState==="connecting"?"connecting":this.#t.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:r,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#o(i.platformId)},health:{status:r?"healthy":A==="error"?"error":"offline",summary:r?`${this.#A.label}${this.#A.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#A.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.#t.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#g.values()]),await Promise.allSettled([...this.#i.keys()].map(a=>this.#h(a))))}async#C(a,o){if(this.#l)throw new Error(`${this.#A.label} controller is closed`);if(await this.#h(a.botId),this.#l)throw new Error(`${this.#A.label} controller is closed`);let i=await this.#E({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#A.label} runtime`);this.#i.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#i.delete(a.botId),e}}async#h(a){let o=this.#i.get(a);this.#i.delete(a),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a} failed to stop cleanly:`,i)})}async#p(a){let o=await this.#e.resolve(a).catch(()=>{});return hE(o?.value)}async#d(a,o){o?.value?await this.#e.set(a,o.value).catch(()=>{}):await this.#e.unset(a).catch(()=>{})}#u(a,o){let r=(this.#g.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#g.get(a)===r&&this.#g.delete(a)});return this.#g.set(a,r),r}#B(){this.#c+=1}};var hAe="https://discord.com/api/v10/";function dE(n){return typeof n=="string"&&n.trim()?n.trim():null}function dAe(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function BAe(n,a){return new Promise((o,i)=>{if(a?.aborted){i(a.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),a?.addEventListener("abort",()=>{clearTimeout(e),i(a.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function vc(n,a){let o=dE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function uAe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var BE=class{#A;#e;#a;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=hAe}){if(!uAe(a))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#A=a.trim(),this.#e=o,this.#a=new URL(i)}getCurrentUser(a={}){return this.#r("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#r("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#r(`channels/${vc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:vc(i,"message id"),channel_id:vc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#r(`channels/${vc(a,"channel id")}/messages/${vc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#r(`channels/${vc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#r(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#e(new URL(a,this.#a),{method:o,headers:{authorization:`Bot ${this.#A}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.7.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:dAe(e,r),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Discord ${o} transport failed`)}let g=null;if(A||s.status===429||!s.ok)try{g=await s.json()}catch{if(A)throw new Error(`Discord ${o} returned invalid JSON`)}if(s.status===429&&t){let c=Math.min(1e4,Math.max(50,Number(g?.retry_after)*1e3||1e3));return await BAe(c,e),this.#r(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(dE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function _P(n,a={}){let i=await new BE({token:n,...a}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:dE(i.global_name)??dE(i.username)??"Discord\u673A\u5668\u4EBA",username:dE(i.username)}}var NP="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Qi(n){return typeof n=="string"?n.trim():""}function QAe(n,a,o){return a.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!!Qi(n.content)}function Sr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Xi=class{#A;#e;#a;#r;#s;#o;#E;#n;#I=new Map;#i=new Map;#t=new Map;#g=new Set;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=Sr(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!a?.key||!a?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s}get status(){return structuredClone(this.#s)}accept(a){if(this.#n?.aborted)return Promise.resolve();let o=Qi(a?.conversationId),i=a?.kind==="group"?"group":"direct",e={...a,kind:i,conversationId:o},r=Qi(e.messageId),A=Qi(e.senderId);if(!r||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(r)||this.#g.has(r))return Promise.resolve();this.#g.add(r);let t=`${i}:${o}`,s=this.#i.get(t);if(s&&s.actor!==A)return this.#c(e,r,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#c(e,r,A,t);if(s){QAe(e,s,A)&&(s.claimedReplyMessageId=r);let c=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,r,A,t,s)).finally(()=>{this.#g.delete(r),s.claimedReplyMessageId===r&&(s.claimedReplyMessageId=null),s.queue===c&&(s.queue=null)});return s.queue=c,c}return this.#c(e,r,A,t)}#c(a,o,i,e,{releaseMessageId:r=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#l(a,o,i,e,{alreadyRecorded:A})).finally(()=>{r&&this.#g.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.#i.values()].flatMap(a=>a.queue?[a.queue]:[])])}async#l(a,o,i,e,{alreadyRecorded:r=!1}={}){if(!r){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#s.messagesReceived+=1,this.#s.lastMessageAt=new Date().toISOString()}let A=a.replyTarget,t=Qi(a.content),s=null;try{if(this.#n?.throwIfAborted(),a.kind==="group"&&a.addressed!==!0){this.#s.messagesRejected+=1,this.#s.lastRejectedAt=new Date().toISOString();return}if(!t){await this.#e.sendText(A,"\u76EE\u524D\u4EC5\u652F\u6301\u6587\u5B57\u6D88\u606F\u3002");return}let g=t.toLowerCase();if(g==="/help"){await this.#e.sendText(A,[`${this.#A.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/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 \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 lAe(o,this.#A)}};var OP=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function MP(n){return pE(n,OP)}function bP(n){return Id(n,"Discord\u673A\u5668\u4EBA")}var ld=class extends Rc{constructor(a){super(a,{channel:"Discord",...OP})}};function hE(n){return typeof n=="string"&&n.trim()?n.trim():null}function Ed(n,a){return Object.freeze({code:n,message:a})}var kc=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i=new Map;#t=new Map;#g=new Map;#c=0;#l=!1;constructor({descriptor:a,credentials:o,configStore:i,inspectToken:e,deriveIdentity:r,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!a?.key||!a?.label||!a?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${a.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${a.label} requires a config store`);if(typeof e!="function"||typeof r!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${a.label} controller dependencies are incomplete`);this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g}async initialize(){if(this.#l)return this.status();for(let a of this.#a.list())await this.#u(a.botId,async()=>{if(this.#l||this.#i.get(a.botId)?.status?.ready)return;let o=await this.#p(a.tokenRef);if(!o){this.#t.set(a.botId,Ed("missing-token",`${this.#A.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#C(a,o),this.#t.delete(a.botId)}catch(i){this.#t.set(a.botId,Ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a.botId} failed to initialize:`,i)}finally{this.#B()}});return this.status()}async bindCredentials({token:a}={}){if(this.#l)throw new Error(`${this.#A.label} controller is closed`);let o=hE(a);if(!o)throw new TypeError(`${this.#A.label} Bot Token is required`);let i=await this.#r(o),e=hE(i?.platformId),r=hE(i?.name);if(!e||!r)throw new Error(`${this.#A.label} returned an invalid bot identity`);let A=this.#s(e);return await this.#u(A.botId,async()=>{if(this.#l)throw new Error(`${this.#A.label} controller is closed`);let t=this.#a.getByPlatformId(e),s=await this.#e.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:hE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#e.set(A.tokenRef,o);try{await this.#a.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#C(g,o),this.#t.delete(A.botId)}catch(c){this.#t.set(A.botId,Ed("connection-failed",`${this.#A.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(a){let o=this.#a.get(a);if(!o)throw new Error(`Unknown ${this.#A.label} bot`);return await this.#u(a,async()=>{let i=await this.#p(o.tokenRef);if(!i)throw new Error(`${this.#A.label} bot token is missing`);try{await this.#C(o,i),this.#t.delete(a)}catch(e){throw this.#t.set(a,Ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#B()}}),this.status()}async deleteBot(a){let o=this.#a.get(a);if(!o)throw new Error(`Unknown ${this.#A.label} bot`);return await this.#u(a,async()=>{let i=await this.#e.resolve(o.tokenRef).catch(()=>{});await this.#h(a);try{await this.#e.unset(o.tokenRef),await this.#a.remove(a)}catch(e){throw i?.value&&(await this.#e.set(o.tokenRef,i.value).catch(()=>{}),await this.#C(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#A.label} bot safely.`,{cause:e})}await this.#n({botId:a,config:o}).catch(e=>{this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a} state cleanup failed:`,e)}),this.#t.delete(a),this.#B()}),this.status()}status(){let a=this.#a.list().map(i=>{let e=this.#i.get(i.botId)?.status??null,r=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=r?"connected":e?.connectionState==="connecting"?"connecting":this.#t.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:r,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#o(i.platformId)},health:{status:r?"healthy":A==="error"?"error":"offline",summary:r?`${this.#A.label}${this.#A.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#A.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.#t.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#l||(this.#l=!0,await Promise.allSettled([...this.#g.values()]),await Promise.allSettled([...this.#i.keys()].map(a=>this.#h(a))))}async#C(a,o){if(this.#l)throw new Error(`${this.#A.label} controller is closed`);if(await this.#h(a.botId),this.#l)throw new Error(`${this.#A.label} controller is closed`);let i=await this.#E({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#A.label} runtime`);this.#i.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#i.delete(a.botId),e}}async#h(a){let o=this.#i.get(a);this.#i.delete(a),await o?.stop().catch(i=>{this.#I.warn?.(`[dsh-im:${this.#A.key}] bot ${a} failed to stop cleanly:`,i)})}async#p(a){let o=await this.#e.resolve(a).catch(()=>{});return hE(o?.value)}async#d(a,o){o?.value?await this.#e.set(a,o.value).catch(()=>{}):await this.#e.unset(a).catch(()=>{})}#u(a,o){let r=(this.#g.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#g.get(a)===r&&this.#g.delete(a)});return this.#g.set(a,r),r}#B(){this.#c+=1}};var hAe="https://discord.com/api/v10/";function dE(n){return typeof n=="string"&&n.trim()?n.trim():null}function dAe(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function BAe(n,a){return new Promise((o,i)=>{if(a?.aborted){i(a.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),a?.addEventListener("abort",()=>{clearTimeout(e),i(a.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function vc(n,a){let o=dE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function uAe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var BE=class{#A;#e;#a;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=hAe}){if(!uAe(a))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#A=a.trim(),this.#e=o,this.#a=new URL(i)}getCurrentUser(a={}){return this.#r("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#r("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#r(`channels/${vc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:vc(i,"message id"),channel_id:vc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#r(`channels/${vc(a,"channel id")}/messages/${vc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#r(`channels/${vc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#r(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#e(new URL(a,this.#a),{method:o,headers:{authorization:`Bot ${this.#A}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.7.1)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:dAe(e,r),redirect:"error"})}catch(c){throw c?.name==="AbortError"||c?.name==="TimeoutError"?c:new Error(`Discord ${o} transport failed`)}let g=null;if(A||s.status===429||!s.ok)try{g=await s.json()}catch{if(A)throw new Error(`Discord ${o} returned invalid JSON`)}if(s.status===429&&t){let c=Math.min(1e4,Math.max(50,Number(g?.retry_after)*1e3||1e3));return await BAe(c,e),this.#r(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(dE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function _P(n,a={}){let i=await new BE({token:n,...a}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:dE(i.global_name)??dE(i.username)??"Discord\u673A\u5668\u4EBA",username:dE(i.username)}}var NP="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function Qi(n){return typeof n=="string"?n.trim():""}function QAe(n,a,o){return a.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!!Qi(n.content)}function Sr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Xi=class{#A;#e;#a;#r;#s;#o;#E;#n;#I=new Map;#i=new Map;#t=new Map;#g=new Set;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=Sr(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!a?.key||!a?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s}get status(){return structuredClone(this.#s)}accept(a){if(this.#n?.aborted)return Promise.resolve();let o=Qi(a?.conversationId),i=a?.kind==="group"?"group":"direct",e={...a,kind:i,conversationId:o},r=Qi(e.messageId),A=Qi(e.senderId);if(!r||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(r)||this.#g.has(r))return Promise.resolve();this.#g.add(r);let t=`${i}:${o}`,s=this.#i.get(t);if(s&&s.actor!==A)return this.#c(e,r,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#c(e,r,A,t);if(s){QAe(e,s,A)&&(s.claimedReplyMessageId=r);let c=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#C(e,r,A,t,s)).finally(()=>{this.#g.delete(r),s.claimedReplyMessageId===r&&(s.claimedReplyMessageId=null),s.queue===c&&(s.queue=null)});return s.queue=c,c}return this.#c(e,r,A,t)}#c(a,o,i,e,{releaseMessageId:r=!0,alreadyRecorded:A=!1}={}){let s=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#l(a,o,i,e,{alreadyRecorded:A})).finally(()=>{r&&this.#g.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.#i.values()].flatMap(a=>a.queue?[a.queue]:[])])}async#l(a,o,i,e,{alreadyRecorded:r=!1}={}){if(!r){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#s.messagesReceived+=1,this.#s.lastMessageAt=new Date().toISOString()}let A=a.replyTarget,t=Qi(a.content),s=null;try{if(this.#n?.throwIfAborted(),a.kind==="group"&&a.addressed!==!0){this.#s.messagesRejected+=1,this.#s.lastRejectedAt=new Date().toISOString();return}if(!t){await this.#e.sendText(A,"\u76EE\u524D\u4EC5\u652F\u6301\u6587\u5B57\u6D88\u606F\u3002");return}let g=t.toLowerCase();if(g==="/help"){await this.#e.sendText(A,[`${this.#A.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/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 \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==="/status"){await this.#a.ensureRunning({signal:this.#n}),await this.#e.sendText(A,`${this.#A.label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002`);return}let c=await Kr(t,this.#a,e);if(c){for(let u of c.messages??[c.message])await this.#e.sendText(A,u);return}if(g==="/new"){await this.#r.clearSession(e),await this.#e.sendText(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002");return}await this.#e.sendTyping?.(A).catch(u=>{this.#o.warn?.(`[dsh-im:${this.#A.key}] typing indicator failed:`,u)});let l=!1;if(typeof this.#e.openStream=="function")try{s=await this.#e.openStream(A)}catch(u){this.#o.warn?.(`[dsh-im:${this.#A.key}] unable to start a streamed reply; using text:`,u)}let{answer:C}=await ir({harness:this.#a,state:this.#r,key:e,text:t,createOptions:this.#n?{signal:this.#n}:void 0,existsOptions:this.#n?{signal:this.#n}:void 0,askOptions:{timeoutMs:this.#E,signal:this.#n,onUpdate:s?async u=>{let Q=u.type==="text"?u.text:u.type==="tool"?`\u6B63\u5728\u4F7F\u7528${u.name}\u2026`:u.text;Q&&await s.update(Q)}:void 0,onInteraction:u=>this.#h(u,{key:e,actor:i,target:A,requiresMention:a.kind==="group"}),onInteractionResolved:u=>this.#p(u)}});if(s)try{await s.finish(C),l=!0}catch(u){s.cancel?.(),this.#o.warn?.(`[dsh-im:${this.#A.key}] streamed reply finalization failed; using text:`,u)}l||await this.#e.sendText(A,C),this.#s.messagesReplied+=1,this.#s.lastReplyAt=new Date().toISOString(),this.#s.lastError=null}catch(g){if(s?.cancel?.(),this.#n?.aborted)return;this.#s.lastError=g?.message??String(g),this.#o.error?.(`[dsh-im:${this.#A.key}] failed to process a message:`,g);try{await this.#e.sendText(A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}catch(c){this.#o.error?.(`[dsh-im:${this.#A.key}] failed to send the safe error reply:`,c)}}finally{await this.#f(e)}}async#C(a,o,i,e,r){if(this.#n?.aborted)return;let A=this.#i.get(e),t=r.claimedReplyMessageId===o;if(!A||A!==r||A.submitting)return t&&(!A||A!==r)?this.#u(a,o):this.#c(a,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#s.messagesReceived+=1,this.#s.lastMessageAt=new Date().toISOString(),a.kind==="group"&&a.addressed!==!0){this.#s.messagesRejected+=1,this.#s.lastRejectedAt=new Date().toISOString();return}let s=a.replyTarget,g=Qi(a.content);if(!g){try{await this.#e.sendText(s,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")}catch(C){this.#o.error?.(`[dsh-im:${this.#A.key}] failed to reject a non-text interaction reply:`,C)}return}let c=this.#i.get(e);if(!c||c!==r||c.submitting)return t&&(!c||c!==r)?this.#u(a,o,{alreadyRecorded:!0}):this.#c(a,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let C=c.presentationTask!==null;try{await this.#d(c)}catch(Q){this.#s.lastError=`${this.#A.label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002`,this.#o.error?.(`[dsh-im:${this.#A.key}] failed to retry an interaction question:`,Q),c.interaction.reconnect?.();return}let u=this.#i.get(e);if(!u||u!==r||u.submitting)return t&&(!u||u!==r)?this.#u(a,o,{alreadyRecorded:!0}):this.#c(a,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!C)return}let l=c.questions[c.index];if(l){if(c.answers.push(Hr(l,g)),c.index+=1,c.index!Lr(c))){this.#o.warn?.(`[dsh-im:${this.#A.key}] ignored an invalid Harness question interaction`);return}if(a.recovered===!0){await this.#y(a,`${this.#A.label} safely cancelled an interaction left by an earlier client.`);try{await this.#e.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.#o.error?.(`[dsh-im:${this.#A.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#i.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#d(s);return}if(this.#t.has(t))return;if(s){this.#o.warn?.(`[dsh-im:${this.#A.key}] cancelled a second pending Harness question`),await this.#y(a,`${this.#A.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#i.set(o,g),this.#t.set(t,o),await this.#d(g)}#p(a){let o=Qi(a?.interactionId);if(a?.kind!=="question"||!o)return;let i=this.#t.get(o);i&&this.#Q(i,o)}#d(a){if(a.presentationTask)return a.presentationTask;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#e.sendText(a.target,Ur(o,a.index,a.questions.length,{requiresMention:a.requiresMention})),a.needsPresentation=!1})();return a.presentationTask=i,i.then(()=>{a.presentationTask===i&&(a.presentationTask=null)},()=>{a.presentationTask===i&&(a.presentationTask=null)}),i}async#u(a,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#s.messagesReceived+=1,this.#s.lastMessageAt=new Date().toISOString()}try{await this.#e.sendText(a.replyTarget,NP)}catch(e){this.#o.error?.(`[dsh-im:${this.#A.key}] failed to send an expired interaction notice:`,e)}}#B(a,o){let i=this.#i.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(a),this.#t.delete(i.interactionId),i)}#Q(a,o){return this.#B(a,o)!==null}async#y(a,o){try{await a.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#f(a){let o=this.#B(a);if(!(!o||o.kind!=="question"))try{await this.#y(o.interaction,`The ${this.#A.label} interaction ended before the user answered.`)}catch(i){this.#o.warn?.(`[dsh-im:${this.#A.key}] failed to cancel a pending Harness interaction:`,i)}}};var GS=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),Cd=class extends Xi{constructor(a){super({descriptor:GS,...a})}};var uE=class extends kc{constructor(a){super({...a,descriptor:GS,inspectToken:a.inspectToken??_P,deriveIdentity:MP,maskPlatformId:bP})}};var pd=class extends Kt{constructor(a){super({...a,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function xr(n,a){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>a;){let r=e.lastIndexOf(` `,a);r{l||g!==null||c||!s||(g=setTimeout(()=>{g=null;let Q=s;s=null;let f=xr(Q,a)[0]??n;c=Promise.resolve(f===C?void 0:e(t,f)).then(()=>{C=f}).catch(y=>A.warn?.("[dsh-im] streamed message update failed:",y)).finally(()=>{c=null,u()})},o),g?.unref?.())};return{async start(){return t=await i(n),this},update(Q){l||typeof Q!="string"||!Q.trim()||(s=Q,u())},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=xr(Q,a),y=f[0]??"\u5904\u7406\u5B8C\u6210\u3002";y!==C&&await e(t,y),C=y;for(let m of f.slice(1))await r(m)},cancel(){l=!0,s=null,g!==null&&clearTimeout(g),g=null}}}var fAe=4609,TP=Object.freeze([1e3,3e3,5e3,1e4,3e4]);function yAe(n){let a=new URL(n);if(a.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return a.searchParams.set("v","10"),a.searchParams.set("encoding","json"),a.href}function FS(n,a,o){if(typeof n.addEventListener=="function")n.addEventListener(a,o);else if(typeof n.on=="function")n.on(a,o);else throw new TypeError("Discord WebSocket does not support events")}function mAe(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 SAe(n){if(n===4004){let o=new Error("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002");return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002");return o.code="discord-intents",o}let a=new Error(`Discord Gateway closed (${n||"unknown"})`);return a.code="discord-gateway-closed",a}function DAe(n,a){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${a}>`,"g"),"").trim()}function wAe(n,a){if(!n?.id||!n?.channel_id||!n?.author?.id)return null;let o=!n.guild_id,i=o||n.mentions?.some(e=>String(e?.id)===String(a));return{messageId:String(n.id),senderId:String(n.author.id),senderIsBot:n.author.bot===!0,kind:o?"direct":"group",conversationId:String(n.channel_id),content:DAe(n.content??"",a),addressed:i,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)}}}var LS=class{#A;#e;constructor({api:a,signal:o}){this.#A=a,this.#e=o}async sendText(a,o){let i=xr(o,1900),e=null;for(let[r,A]of i.entries())e=await this.#A.createMessage({channelId:a.channelId,content:A,replyToMessageId:r===0?a.replyToMessageId:void 0,signal:this.#e});return e}sendTyping(a){return this.#A.sendTyping({channelId:a.channelId,signal:this.#e})}async openStream(a){return hd({limit:1900,create:async i=>(await this.#A.createMessage({channelId:a.channelId,content:i,replyToMessageId:a.replyToMessageId,signal:this.#e})).id,edit:(i,e)=>this.#A.editMessage({channelId:a.channelId,messageId:i,content:e,signal:this.#e}),sendRemainder:i=>this.#A.createMessage({channelId:a.channelId,content:i,signal:this.#e})}).start()}};function OAe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...Sr()}}var QE=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i;#t=OAe();#g=null;#c=null;#l=null;#C=null;#h=null;#p=null;#d=null;#u=null;#B=null;#Q=!0;#y=null;#f=0;#D=0;#m=!0;#S=null;constructor({config:a,token:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,createApi:s=l=>new BE(l),createWebSocket:g=l=>new WebSocket(l),random:c=Math.random}){if(!a||!o||!i||!e)throw new TypeError("DiscordRuntime requires config, token, Harness, and state");if(typeof g!="function")throw new TypeError("DiscordRuntime requires WebSocket");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g,this.#i=c}get status(){return structuredClone(this.#t)}async start(){return this.#t.ready&&this.#C?this.status:this.#S?this.#S:(this.#S=this.#w().finally(()=>{this.#S=null}),this.#S)}async#w(){await this.stop(),this.#m=!1,this.#d=null,this.#p=null,this.#u=null,this.#f=0,this.#t.startedAt=new Date().toISOString(),this.#t.connectionState="connecting",this.#t.lastError=null,await this.#a.ensureRunning(),this.#t.harnessReachable=!0;let a=new AbortController;this.#l=a;let o=this.#n({token:this.#e});this.#g=o;try{let[i,e]=await Promise.all([o.getCurrentUser({signal:a.signal}),o.getGatewayBot({signal:a.signal})]);if(String(i?.id??"")!==this.#A.platformId||i?.bot!==!0)throw new Error("Discord token identity does not match the saved bot");this.#h=e?.url;let r=new LS({api:o,signal:a.signal});this.#c=new Cd({bot:r,harness:this.#a,state:this.#r,status:this.#t,logger:this.#s,replyTimeoutMs:this.#o,signal:a.signal});let A;try{await Promise.race([this.#O(!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.#t.ready=!1,this.#t.connectionState="failed",this.#t.lastError=i?.message??String(i),await this.stop(),i}}#O(a){if(this.#m)return Promise.reject(new Error("Discord runtime is stopped"));let o=++this.#D,i=yAe(a&&this.#p?this.#p:this.#h),e=this.#I(i);this.#C=e;let r=!1;return new Promise((A,t)=>{let s=()=>{if(r||o!==this.#D)return;r=!0,this.#f=0;let g=Date.now();this.#t.ready=!0,this.#t.connectionState="connected",this.#t.lastCheckedAt=g,this.#t.lastConnectedAt=g,this.#t.lastError=null,A()};FS(e,"message",g=>{if(o!==this.#D||this.#m)return;let c=mAe(g);if(!c)return;let l;try{l=JSON.parse(c)}catch{this.#s.warn?.("[dsh-im:discord] ignored malformed Gateway JSON");return}if(Number.isSafeInteger(l.s)&&(this.#u=l.s),l.op===10){this.#M(l.d?.heartbeat_interval,e,o),a&&this.#d?this.#T(e,{op:6,d:{token:this.#e,session_id:this.#d,seq:this.#u}}):this.#T(e,{op:2,d:{token:this.#e,intents:fAe,properties:{os:process.platform,browser:"dsh-im",device:"dsh-im"}}});return}if(l.op===11){this.#Q=!0,this.#t.lastCheckedAt=Date.now();return}if(l.op===1){this.#G(e);return}if(l.op===7){e.close(4e3,"Reconnect requested");return}if(l.op===9){l.d!==!0&&(this.#d=null,this.#p=null,this.#u=null),e.close(4e3,"Invalid session");return}if(l.op===0){if(l.t==="READY")this.#d=l.d?.session_id??null,this.#p=l.d?.resume_gateway_url??null,s();else if(l.t==="RESUMED")s();else if(l.t==="MESSAGE_CREATE"){let C=wAe(l.d,this.#A.platformId),u=this.#c;C&&u&&u.accept(C).catch(Q=>{o!==this.#D||this.#m||this.#s.error?.(`[dsh-im:discord] bot ${this.#A.botId} message handling failed:`,Q)})}}}),FS(e,"close",(g={})=>{if(o!==this.#D)return;if(this.#N(),this.#C===e&&(this.#C=null),this.#m){r||t(new DOMException("Stopped","AbortError"));return}let c=SAe(Number(g.code)||0);if(this.#t.ready=!1,this.#t.connectionState="connecting",this.#t.lastError=c.message,r||(r=!0,t(c)),c.code==="discord-401"||c.code==="discord-intents"){this.#t.connectionState="failed";return}this.#F()}),FS(e,"error",()=>{o!==this.#D||this.#m||(this.#t.lastError="Discord Gateway WebSocket error")})})}#T(a,o){a.readyState===1&&a.send(JSON.stringify(o))}#M(a,o,i){if(this.#N(),!Number.isFinite(a)||a<1e3){o.close(4e3,"Invalid heartbeat interval");return}this.#Q=!0;let e=r=>{this.#B=setTimeout(()=>{if(!(this.#m||i!==this.#D||this.#C!==o)){if(!this.#Q){o.close(4e3,"Heartbeat was not acknowledged");return}this.#G(o),e(a)}},r),this.#B?.unref?.()};e(Math.floor(a*this.#i()))}#G(a){this.#Q=!1,this.#T(a,{op:1,d:this.#u})}#N(){this.#B!==null&&clearTimeout(this.#B),this.#B=null,this.#Q=!0}#F(){if(this.#m||this.#y!==null)return;let a=TP[Math.min(this.#f,TP.length-1)];this.#f+=1,this.#y=setTimeout(()=>{this.#y=null,this.#O(!!this.#d).catch(o=>{this.#m||(this.#s.warn?.("[dsh-im:discord] Gateway reconnect failed:",o),this.#F())})},a),this.#y?.unref?.()}async stop(){this.#m=!0,this.#D+=1,this.#l?.abort(),this.#l=null,this.#y!==null&&clearTimeout(this.#y),this.#y=null,this.#N();let a=this.#C,o=this.#c;this.#C=null,this.#c=null,this.#g=null;try{a&&a.readyState<2&&a.close(1e3,"Plugin stopped")}catch(i){this.#s.warn?.(`[dsh-im:discord] bot ${this.#A.botId} failed to close Gateway:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#t.ready=!1,this.#t.connectionState="idle",this.status}};import{mkdir as MAe,readFile as bAe,rename as _Ae,unlink as NAe,writeFile as TAe}from"node:fs/promises";import{dirname as RAe}from"node:path";var dd=Object.freeze({version:1,sessions:{},seenMessageIds:[],cursor:null});function kAe(n){if(!n||typeof n!="object")return structuredClone(dd);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&o&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string"&&o).slice(-1e3):[],cursor:Number.isSafeInteger(n.cursor)&&n.cursor>=0?n.cursor:null}}var $i=class{#A;#e=structuredClone(dd);#a=Promise.resolve();constructor(a){this.#A=a}async load(){try{this.#e=kAe(JSON.parse(await bAe(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(dd),await this.#r()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){this.#e.sessions[a]=o,await this.#r()}async clearSession(a){delete this.#e.sessions[a],await this.#r()}async clearSessions(){this.#e.sessions={},await this.#r()}hasSeen(a){return this.#e.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#e.seenMessageIds.push(a),this.#e.seenMessageIds.length>1e3&&this.#e.seenMessageIds.splice(0,this.#e.seenMessageIds.length-1e3),await this.#r())}cursor(){return this.#e.cursor}async setCursor(a){if(!Number.isSafeInteger(a)||a<0)throw new TypeError("Invalid update cursor");this.#e.cursor=a,await this.#r()}snapshot(){return structuredClone(this.#e)}async remove(){try{await NAe(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(dd)}async#r(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#a.then(async()=>{await MAe(RAe(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await TAe(i,a,{encoding:"utf8",mode:384}),await _Ae(i,this.#A)});this.#a=o.then(()=>{},()=>{}),await o}};var Bd=class extends $i{};import{unlink as PAe}from"node:fs/promises";import{homedir as GAe}from"node:os";import{join as fE,resolve as Ws}from"node:path";var RP=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function vAe(n){if(!Array.isArray(n)||n.length===0)return[...RP];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...RP]}var US=class{#A;#e;#a;#r;#s;#o;#E;#n;#I=null;#i=null;#t=0;#g=!1;#c=!1;#l;#C;constructor({channel:a,controller:o,harness:i,logger:e=console,retryDelaysMs:r,healthyIntervalMs:A=15e3,setTimeoutImpl:t=setTimeout,clearTimeoutImpl:s=clearTimeout}){if(!a)throw new TypeError("TokenConnectionSupervisor requires a channel");if(!o||typeof o.initialize!="function"||typeof o.status!="function")throw new TypeError("TokenConnectionSupervisor requires a controller");if(!i||typeof i.ensureRunning!="function")throw new TypeError("TokenConnectionSupervisor requires a Harness client");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=vAe(r),this.#o=Number.isFinite(A)&&A>=0?A:15e3,this.#E=t,this.#n=s,this.#l=new Promise(g=>{this.#C=g})}get ready(){return this.#l}start(){return this.#c||this.#g?this:(this.#c=!0,this.#h(0),this)}async close(){this.#g||(this.#g=!0,this.#I!==null&&this.#n(this.#I),this.#I=null,await this.#i?.catch(()=>{}),this.#C?.(null),this.#C=null)}#h(a){this.#g||(this.#I=this.#E(()=>{this.#I=null,this.#p()},a),this.#I?.unref?.())}async#p(){if(this.#g||this.#i)return;let a=this.#d();this.#i=a;try{await a}finally{this.#i===a&&(this.#i=null)}}async#d(){try{if(await this.#a.ensureRunning(),this.#g)return;let a=await this.#e.initialize();if(this.#g)return;this.#C?.(a),this.#C=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im token channel requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function KS(n,a){let o=Ws(n.dshHome??process.env.DSH_HOME??fE(GAe(),".dsh")),i=Ws(n.dataDir??fE(o,"integrations",`dsh-${a}`));return{config:Ws(n.configPath??fE(i,"config.json")),bots:Ws(n.botsDir??fE(i,"bots")),workspaces:Ws(n.workspacesPath??fE(i,"workspaces.json"))}}async function ud(n,a,o,i){let{channel:e,ConfigStore:r,StateStore:A,HarnessClient:t,Controller:s,Runtime:g}=i;if(!n?.credentials)throw new TypeError(`dsh-im ${e} requires ctx.credentials`);if(!n?.webServer)throw new TypeError(`dsh-im ${e} requires ctx.webServer`);let c=o.ConfigStore??r,l=o.StateStore??A,C=o.HarnessClient??t,u=o.Controller??s,Q=o.Runtime??g,f=o.createConnectionSupervisor??Pc,y=typeof n.logger=="function"?n.logger(`dsh-im:${e}`):n.logger??console,m=KS(a,e),T=await new c(m.config).load(),k=Ws(a.workspace??process.cwd()),F=o.WorkspaceStore??Ia,j=o.workspaces??await new F(m.workspaces,{defaultWorkspace:k}).load(),x=T.list();await j.reconcile(x.map(L=>L.botId)),await Promise.all(x.map(L=>j.ensure(L.botId)));let H=typeof T.remove=="function"?La(T,{workspaces:j}):T,J=new Map,K=L=>Ws(m.bots,L,"state.json"),G=async L=>{let ee=J.get(L);return ee||(ee=await new l(K(L)).load(),J.set(L,ee)),ee},R=new C({baseUrl:HS(n.webServer,a.harnessBaseUrl),workspace:k,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh"}),Z=new u({credentials:n.credentials,configStore:H,logger:y,...o.inspectToken?{inspectToken:o.inspectToken}:{},createRuntime:async({botId:L,config:ee,token:fe})=>{let Se=await G(L);await j.ensure(L);let Le=Ua(R,{botId:L,workspaces:j,state:Se});return new Q({config:ee,token:fe,harness:Le.harness,state:Le.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,logger:{error:(...we)=>y.error?.(`[${L}]`,...we),warn:(...we)=>y.warn?.(`[${L}]`,...we),info:(...we)=>y.info?.(`[${L}]`,...we),debug:(...we)=>y.debug?.(`[${L}]`,...we)}})},deleteState:async({botId:L})=>{let ee=J.get(L);if(J.delete(L),ee&&typeof ee.remove=="function")await ee.remove();else try{await PAe(K(L))}catch(fe){if(fe?.code!=="ENOENT")throw fe}}}),U=Ha(Z,{workspaces:j,stateFor:G}),b=f({channel:e,controller:U,harness:R,logger:y,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:U,ready:b.ready,async close(){await b.close(),await U.close(),R.stopManagedProcess()}}}function YS(n,a={},o={}){return ud(n,a,o,{channel:"discord",ConfigStore:ld,StateStore:Bd,HarnessClient:pd,Controller:uE,Runtime:QE})}var nr=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:or}),FAe=Object.freeze(Object.values(nr)),LAe=new Set(["token","botToken","tokenRef","platformId","secret","secretRef"]);function jS(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Qd(n,a){return jS(n)&&Object.keys(n).every(o=>a.includes(o))}function kP(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function UAe(n){return typeof n=="string"&&n.trim().length>=20&&n.length<=4096}function HAe(n,a){return jS(a)?n===nr.status?Qd(a,[])?null:"connection.status does not accept fields.":n===nr.bindCredentials?Qd(a,["token"])&&UAe(a.token)?null:"bot.bind-credentials requires a Bot Token.":n===nr.reconnectBot?Qd(a,["botId"])&&kP(a.botId)?null:"bot.reconnect requires a botId.":n===nr.deleteBot?Qd(a,["botId","confirm"])&&kP(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===nr.setWorkspace?Ya(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown bot endpoint.":"Payload must be an object."}function xS(n){if(Array.isArray(n))return n.map(xS);if(!jS(n))return n;let a={};for(let[o,i]of Object.entries(n))LAe.has(o)||(a[o]=xS(i));return a}function KAe(n,a){let o=xa(a);return o||(a?.code==="webhook-configured"?{code:"webhook-configured",message:a.message}:a?.code==="telegram-401"||a?.code==="discord-401"?{code:"invalid-token",message:`${n} Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002`}:a?.code==="discord-intents"?{code:"discord-intents",message:a.message}:{code:`${n.toLowerCase()}-operation-failed`,message:`${n} \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`})}function JS(n,{channel:a}){for(let o of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[o]!="function")throw new TypeError(`A complete ${a} controller is required (${o})`);return async(o,i,e)=>{if(e?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!FAe.includes(o))return{ok:!1,error:{code:"bad-request",message:`Unknown ${a} endpoint.`}};let r=HAe(o,i);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let A;if(o===nr.status)A=await n.status();else if(o===nr.bindCredentials)A=await n.bindCredentials(i);else if(o===nr.reconnectBot)A=await n.reconnectBot(i.botId);else if(o===nr.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:xS(A)}}catch(A){return e?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:KAe(a,A)}}}}function fd(n,a,{channel:o,rpcChannel:i,authority:e}){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(i,JS(a,{channel:o}),{authority:Ka(e)})}var vP="/discord",PP=nr,YAe=Object.freeze(Object.values(PP));function yd(n,a,o){return fd(n,a,{channel:"Discord",rpcChannel:vP,authority:o})}async function GP(n,a={}){if(a?.controller)return yd(n,a.controller,a.rpcAuthority);let o=await YS(n,a,a.internals??{}),i=yd(n,o.controller,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Discord bot connections"),i}var xAe=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]);function jAe(n){let a=n?.client_id??n?.appId,o=n?.client_secret??n?.appSecret;if(typeof a!="string"||a.length===0||typeof o!="string"||o.length===0)throw new TypeError("Feishu registration returned invalid credentials");return{appId:a,appSecret:o,userInfo:n?.user_info??n?.userInfo}}async function JAe(n){return typeof n.status!="function"?{}:await n.status()}function qAe(n){return n?.connected===!0?!0:n?.ready===!0&&n?.feishuLongConnectionState==="connected"&&n?.harnessReachable===!0}var md=class{#A;#e;#a;#r;#s=!1;#o=null;constructor({createProvisioningManager:a,credentialStore:o,connectionManager:i,registrationOptions:e={}}={}){if(typeof a!="function")throw new TypeError("createProvisioningManager is required");if(!o||typeof o.save!="function"||typeof o.clear!="function")throw new TypeError("credentialStore.save/clear are required");if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("connectionManager.connect/disconnect are required");if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registrationOptions must be an object");if(this.#A=o,this.#e=i,this.#a=structuredClone(e),this.#r=a({onCredentials:r=>this.#E(r)}),!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.#o=null,await this.#r.start(structuredClone(this.#a)),this.status()}async cancelRegistration(){return await this.#r.cancel(),this.status()}async disconnect(){await this.#r.cancel(),await this.#e.disconnect();try{await this.#A.clear(),this.#s=!1,this.#o=null}catch{this.#o={code:"credential_removal_failed",message:"Unable to remove the Feishu credentials."}}return this.status()}async status(){let a=await this.#r.status(),o=await JAe(this.#e),i=qAe(o),e=this.#s;if(typeof this.#A.configured=="function")try{e=await this.#A.configured()}catch{e=this.#s}let r="unconfigured";return i?r="connected":xAe.has(a?.state)?r="registering":a?.state==="saving"?r="connecting":this.#o||a?.state==="error"?r="error":e&&(r="disconnected"),{phase:r,connected:i,configured:e,registration:a,connection:o,error:this.#o??a?.error??null}}async close(){await this.#r.cancel(),await this.#e.disconnect()}async#E(a){let o=jAe(a);try{await this.#A.save(o),this.#s=!0,await this.#e.connect(o),this.#o=null}catch{throw this.#o={code:"connection_failed",message:"The bot was created, but its connection could not be started."},new Error("Unable to activate the Feishu connection.")}}};function qS(n){return new md(n)}import{homedir as gde}from"node:os";import{join as DI,resolve as $n}from"node:path";import{unlink as cde}from"node:fs/promises";var K_={};zt(K_,{AESCipher:()=>RC,AccessTokenError:()=>mI,Aily:()=>B_,AppType:()=>so,CAppTicket:()=>TC,CTenantAccessToken:()=>OC,CardActionHandler:()=>C_,Client:()=>iu,ClientAssertionError:()=>Ja,DefaultCache:()=>tu,Domain:()=>go,EventDispatcher:()=>nu,LarkChannel:()=>Eu,LarkChannelError:()=>ct,LoggerLevel:()=>br,LoggerProxy:()=>Xn,WSClient:()=>gu,adaptDefault:()=>GCe,adaptExpress:()=>FCe,adaptKoa:()=>LCe,adaptKoaRouter:()=>UCe,createLarkChannel:()=>She,defaultHttpInstance:()=>SI,defaultLogger:()=>on,generateChallenge:()=>vC,internalCache:()=>kC,messageCard:()=>KCe,normalize:()=>Dx,normalizeBotAdded:()=>mx,normalizeCardAction:()=>yx,normalizeComment:()=>Sx,normalizeReaction:()=>N_,registerApp:()=>$Ce,withAll:()=>NCe,withHelpDeskCredential:()=>RCe,withTenantKey:()=>TCe,withTenantToken:()=>kCe,withUserAccessToken:()=>vCe});function yE(n,a){return function(){return n.apply(a,arguments)}}var{toString:VAe}=Object.prototype,{getPrototypeOf:Gc}=Object,{iterator:SE,toStringTag:UP}=Symbol,Dd=(({hasOwnProperty:n})=>(a,o)=>n.call(a,o))(Object.prototype),mE=(n,a)=>{let o=n,i=[];for(;o!=null&&o!==Object.prototype;){if(i.indexOf(o)!==-1)return!1;if(i.push(o),Dd(o,a))return!0;o=Gc(o)}return!1},zAe=(n,a)=>n!=null&&mE(n,a)?n[a]:void 0,zS=(n=>a=>{let o=VAe.call(a);return n[o]||(n[o]=o.slice(8,-1).toLowerCase())})(Object.create(null)),jr=n=>(n=n.toLowerCase(),a=>zS(a)===n),wd=n=>a=>typeof a===n,{isArray:Xs}=Array,$s=wd("undefined");function Fc(n){return n!==null&&!$s(n)&&n.constructor!==null&&!$s(n.constructor)&&sr(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}var HP=jr("ArrayBuffer");function WAe(n){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(n):a=n&&n.buffer&&HP(n.buffer),a}var ZAe=wd("string"),sr=wd("function"),KP=wd("number"),Lc=n=>n!==null&&typeof n=="object",XAe=n=>n===!0||n===!1,Sd=n=>{if(!Lc(n))return!1;let a=Gc(n);return(a===null||a===Object.prototype||Gc(a)===null)&&!mE(n,UP)&&!mE(n,SE)},$Ae=n=>{if(!Lc(n)||Fc(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},ete=jr("Date"),Ate=jr("File"),tte=n=>!!(n&&typeof n.uri<"u"),ate=n=>n&&typeof n.getParts<"u",rte=jr("Blob"),ite=jr("FileList"),ote=jr("Set"),nte=n=>Lc(n)&&sr(n.pipe);function ste(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var FP=ste(),LP=typeof FP.FormData<"u"?FP.FormData:void 0,gte=n=>{if(!n)return!1;if(LP&&n instanceof LP)return!0;let a=Gc(n);if(!a||a===Object.prototype||!sr(n.append))return!1;let o=zS(n);return o==="formdata"||o==="object"&&sr(n.toString)&&n.toString()==="[object FormData]"},cte=jr("URLSearchParams"),[Ite,lte,Ete,Cte]=["ReadableStream","Request","Response","Headers"].map(jr),pte=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function DE(n,a,{allOwnKeys:o=!1}={}){if(n===null||typeof n>"u")return;let i,e;if(typeof n!="object"&&(n=[n]),Xs(n))for(i=0,e=n.length;i0;)if(e=o[i],a===e.toLowerCase())return e;return null}var Zs=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,xP=n=>!$s(n)&&n!==Zs;function VS(...n){let{caseless:a,skipUndefined:o}=xP(this)&&this||{},i={},e=(r,A)=>{if(A==="__proto__"||A==="constructor"||A==="prototype")return;let t=a&&typeof A=="string"&&YP(i,A)||A,s=Dd(i,t)?i[t]:void 0;Sd(s)&&Sd(r)?i[t]=VS(s,r):Sd(r)?i[t]=VS({},r):Xs(r)?i[t]=r.slice():(!o||!$s(r))&&(i[t]=r)};for(let r=0,A=n.length;r(DE(a,(e,r)=>{o&&sr(e)?Object.defineProperty(n,r,{__proto__:null,value:yE(e,o),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,r,{__proto__:null,value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),n),dte=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),Bte=(n,a,o,i)=>{n.prototype=Object.create(a.prototype,i),Object.defineProperty(n.prototype,"constructor",{__proto__:null,value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{__proto__:null,value:a.prototype}),o&&Object.assign(n.prototype,o)},ute=(n,a,o,i)=>{let e,r,A,t={};if(a=a||{},n==null)return a;do{for(e=Object.getOwnPropertyNames(n),r=e.length;r-- >0;)A=e[r],(!i||i(A,n,a))&&!t[A]&&(a[A]=n[A],t[A]=!0);n=o!==!1&&Gc(n)}while(n&&(!o||o(n,a))&&n!==Object.prototype);return a},Qte=(n,a,o)=>{n=String(n),(o===void 0||o>n.length)&&(o=n.length),o-=a.length;let i=n.indexOf(a,o);return i!==-1&&i===o},fte=n=>{if(!n)return null;if(Xs(n))return n;let a=n.length;if(!KP(a))return null;let o=new Array(a);for(;a-- >0;)o[a]=n[a];return o},yte=(n=>a=>n&&a instanceof n)(typeof Uint8Array<"u"&&Gc(Uint8Array)),mte=(n,a)=>{let i=(n&&n[SE]).call(n),e;for(;(e=i.next())&&!e.done;){let r=e.value;a.call(n,r[0],r[1])}},Ste=(n,a)=>{let o,i=[];for(;(o=n.exec(a))!==null;)i.push(o);return i},Dte=jr("HTMLFormElement"),wte=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(o,i,e){return i.toUpperCase()+e}),{propertyIsEnumerable:Ote}=Object.prototype,Mte=jr("RegExp"),jP=(n,a)=>{let o=Object.getOwnPropertyDescriptors(n),i={};DE(o,(e,r)=>{let A;(A=a(e,r,n))!==!1&&(i[r]=A||e)}),Object.defineProperties(n,i)},bte=n=>{jP(n,(a,o)=>{if(sr(n)&&["arguments","caller","callee"].includes(o))return!1;let i=n[o];if(sr(i)){if(a.enumerable=!1,"writable"in a){a.writable=!1;return}a.set||(a.set=()=>{throw Error("Can not rewrite read-only method '"+o+"'")})}})},_te=(n,a)=>{let o={},i=e=>{e.forEach(r=>{o[r]=!0})};return Xs(n)?i(n):i(String(n).split(a)),o},Nte=()=>{},Tte=(n,a)=>n!=null&&Number.isFinite(n=+n)?n:a;function Rte(n){return!!(n&&sr(n.append)&&n[UP]==="FormData"&&n[SE])}var kte=n=>{let a=new WeakSet,o=i=>{if(Lc(i)){if(a.has(i))return;if(Fc(i))return i;if(!("toJSON"in i)){a.add(i);let e;if(ote(i)){e=[];for(let r of i){let A=o(r);!$s(A)&&e.push(A)}}else e=Xs(i)?[]:{},DE(i,(r,A)=>{let t=o(r);!$s(t)&&(e[A]=t)});return a.delete(i),e}}return i};return o(n)},vte=jr("AsyncFunction"),Pte=n=>n&&(Lc(n)||sr(n))&&sr(n.then)&&sr(n.catch),JP=((n,a)=>n?setImmediate:a?((o,i)=>(Zs.addEventListener("message",({source:e,data:r})=>{e===Zs&&r===o&&i.length&&i.shift()()},!1),e=>{i.push(e),Zs.postMessage(o,"*")}))(`axios@${Math.random()}`,[]):o=>setTimeout(o))(typeof setImmediate=="function",sr(Zs.postMessage)),Gte=typeof queueMicrotask<"u"?queueMicrotask.bind(Zs):typeof process<"u"&&process.nextTick||JP,qP=n=>n!=null&&sr(n[SE]),Fte=n=>n!=null&&mE(n,SE)&&qP(n),q={isArray:Xs,isArrayBuffer:HP,isBuffer:Fc,isFormData:gte,isArrayBufferView:WAe,isString:ZAe,isNumber:KP,isBoolean:XAe,isObject:Lc,isPlainObject:Sd,isEmptyObject:$Ae,isReadableStream:Ite,isRequest:lte,isResponse:Ete,isHeaders:Cte,isUndefined:$s,isDate:ete,isFile:Ate,isReactNativeBlob:tte,isReactNative:ate,isBlob:rte,isRegExp:Mte,isFunction:sr,isStream:nte,isURLSearchParams:cte,isTypedArray:yte,isFileList:ite,forEach:DE,merge:VS,extend:hte,trim:pte,stripBOM:dte,inherits:Bte,toFlatObject:ute,kindOf:zS,kindOfTest:jr,endsWith:Qte,toArray:fte,forEachEntry:mte,matchAll:Ste,isHTMLForm:Dte,hasOwnProperty:Dd,hasOwnProp:Dd,hasOwnInPrototypeChain:mE,getSafeProp:zAe,reduceDescriptors:jP,freezeMethods:bte,toObjectSet:_te,toCamelCase:wte,noop:Nte,toFiniteNumber:Tte,findKey:YP,global:Zs,isContextDefined:xP,isSpecCompliantForm:Rte,toJSONObject:kte,isAsyncFn:vte,isThenable:Pte,setImmediate:JP,asap:Gte,isIterable:qP,isSafeIterable:Fte};var Lte=q.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"]),VP=n=>{let a={},o,i,e;return n&&n.split(` @@ -181,7 +181,7 @@ ${r.join(` `,{encoding:"utf8",mode:384}),await qBe(o,this.#A)}};var tQ=class extends Kt{constructor(a){super({...a,rpcIdPrefix:"wecom",logPrefix:"dsh-wecom"})}};var $Be="https://work.weixin.qq.com/ai/qc/generate",eue="https://work.weixin.qq.com/ai/qc/query_result";function R1(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function MI(n){return typeof n=="string"&&n.trim()?n.trim():null}function Aue(n){let a=MI(n);if(!a)return null;try{let o=new URL(a);return o.protocol==="https:"&&o.hostname==="work.weixin.qq.com"&&(!o.port||o.port==="443")?o.href:null}catch{return null}}function tue(n,a){return n?AbortSignal.any([n,AbortSignal.timeout(a)]):AbortSignal.timeout(a)}async function k1(n,a,o){let i=await n(a,{method:"GET",redirect:"error",signal:tue(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var aQ=class{#A;#e;#a;#r;constructor({fetch:a=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=R1()}={}){if(typeof a!="function")throw new TypeError("A fetch implementation is required");this.#A=a,this.#e=o,this.#a=i,this.#r=[1,2,3].includes(e)?e:R1()}async start({signal:a}={}){let o=new URL($Be);o.searchParams.set("source",this.#a),o.searchParams.set("plat",String(this.#r));let i=await k1(this.#A,o,a),e=MI(i?.data?.scode),r=Aue(i?.data?.auth_url);if(!e||!r)throw new Error("Enterprise WeChat QR service returned invalid data");return{scode:e,verificationUrl:r,expiresAt:this.#e()+3e5,pollIntervalMs:3e3}}async poll({scode:a,signal:o}={}){let i=MI(a);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(eue);e.searchParams.set("scode",i);let r=await k1(this.#A,e,o),A=MI(r?.data?.status)?.toLowerCase();if(A==="success"){let t=MI(r?.data?.bot_info?.botid),s=MI(r?.data?.bot_info?.secret);if(!t||!s)throw new Error("Enterprise WeChat QR result omitted bot credentials");return{status:"success",remoteBotId:t,secret:s}}return["expired","timeout"].includes(A)?{status:"expired"}:["fail","failed","error"].includes(A)?{status:"failed"}:{status:"waiting"}}};import{mkdir as aue,readFile as rue,rename as iue,unlink as oue,writeFile as nue}from"node:fs/promises";import{dirname as sue}from"node:path";var rQ=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function gue(n){if(!n||typeof n!="object")return structuredClone(rQ);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var iQ=class{#A;#e=structuredClone(rQ);#a=Promise.resolve();constructor(a){this.#A=a}async load(){try{this.#e=gue(JSON.parse(await rue(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(rQ),await this.#r()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){this.#e.sessions[a]=o,await this.#r()}async clearSession(a){delete this.#e.sessions[a],await this.#r()}async clearSessions(){this.#e.sessions={},await this.#r()}hasSeen(a){return this.#e.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#e.seenMessageIds.push(a),this.#e.seenMessageIds.length>1e3&&this.#e.seenMessageIds.splice(0,this.#e.seenMessageIds.length-1e3),await this.#r())}async remove(){try{await oue(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(rQ)}async#r(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#a.then(async()=>{await aue(sue(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await nue(i,a,{encoding:"utf8",mode:384}),await iue(i,this.#A)});this.#a=o.then(()=>{},()=>{}),await o}};import{randomUUID as cue}from"node:crypto";var v1=new Set(["pending","connecting"]),XC=new Set(["connected","failed","cancelled","expired"]);function kg(n){return typeof n=="string"&&n.trim()?n.trim():null}function Cr(n,a){return Object.freeze({code:n,message:a})}function vg(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 $C=class{#A;#e;#a;#r;#s;#o;#E=new Map;#n=new Map;#I=new Map;#i=null;#t=new Map;#g=0;#c=!1;constructor({qrAuth:a,credentials:o,configStore:i,createRuntime:e,deleteState:r=async()=>{},logger:A=console}){if(!a||typeof a.start!="function"||typeof a.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A}async initialize(){if(this.#c)return this.status();for(let a of this.#a.list())await this.#Q(a.botId,async()=>{let o=this.#E.get(a.botId)?.status;if(this.#c||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#u(a.secretRef);if(!i){this.#n.set(a.botId,Cr("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.#p(a,i),this.#n.delete(a.botId)}catch{this.#n.set(a.botId,Cr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#o.warn?.(`[dsh-im:wecom] bot ${a.botId} failed to initialize`)}finally{this.#f()}});return this.status()}async startProvisioning(){if(this.#c)throw new Error("Enterprise WeChat controller is closed");this.#i&&await this.cancelProvisioning(this.#i);let a={id:cue(),state:"pending",createdAt:Date.now(),expiresAt:null,pollIntervalMs:3e3,qrRevision:1,verificationUrl:null,scode:null,botId:null,error:null,controller:new AbortController,polling:null,transition:null};this.#I.set(a.id,a),this.#i=a.id,this.#f();try{let o=await this.#A.start({signal:a.controller.signal});if(a.scode=kg(o.scode),a.verificationUrl=kg(o.verificationUrl),a.expiresAt=Number(o.expiresAt),a.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!a.scode||!a.verificationUrl||!Number.isFinite(a.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#f(),vg(a)}catch(o){throw a.state=a.controller.signal.aborted?"cancelled":"failed",a.error=a.controller.signal.aborted?Cr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"):Cr("qr-start-failed","\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),this.#y(a),o}}async registrationStatus(a){let o=this.#I.get(a);if(!o||XC.has(o.state))return vg(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),vg(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=Cr("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),o.controller.abort(),this.#y(o),vg(o);if(!o.polling){let i=this.#l(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),vg(o)}async bindCredentials({botId:a,secret:o}={}){if(this.#c)throw new Error("Enterprise WeChat controller is closed");let i=kg(a),e=kg(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#i&&await this.cancelProvisioning(this.#i),this.#c)throw new Error("Enterprise WeChat controller is closed");let r=AQ(i);return await this.#Q(r.botId,async()=>{if(this.#c)throw new Error("Enterprise WeChat controller is closed");let A=this.#a.getByRemoteBotId(i),t=await this.#e.resolve(r.secretRef).catch(()=>{});if(this.#c)throw new Error("Enterprise WeChat controller is closed");let s={botId:r.botId,remoteBotId:i,secretRef:r.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#e.set(r.secretRef,e);try{await this.#a.save(s)}catch(g){throw await this.#B(r.secretRef,t),g}try{await this.#p(s,e),this.#n.delete(r.botId)}catch{this.#n.set(r.botId,Cr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#o.warn?.(`[dsh-im:wecom] bot ${r.botId} credential connection failed`)}this.#f()}),this.status()}async cancelProvisioning(a){let o=this.#I.get(a);return o?(XC.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),XC.has(o.state)||(o.state="cancelled"),o.error??=Cr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"),this.#y(o)),vg(o)):null}async reconnectBot(a){let o=this.#a.get(a);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(a,async()=>{let i=await this.#u(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#p(o,i),this.#n.delete(a)}catch(e){throw this.#n.set(a,Cr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async deleteBot(a){let o=this.#a.get(a);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(a,async()=>{let i=await this.#e.resolve(o.secretRef).catch(()=>{});await this.#d(a);try{await this.#e.unset(o.secretRef),await this.#a.remove(a)}catch(e){throw i?.value&&(await this.#e.set(o.secretRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#s({botId:a,config:o}).catch(e=>{this.#o.warn?.(`[dsh-im:wecom] bot ${a} state cleanup failed:`,e)}),this.#n.delete(a),this.#f()}),this.status()}status(){let a=this.#a.list().map(e=>{let r=this.#E.get(e.botId)?.status??null,A=r?.ready===!0&&r.wecomConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.wecomConnectionState==="connecting"?"connecting":this.#n.has(e.botId)||r?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:t,connected:A,configured:!0,bot:{name:"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA",appIdMasked:N1(e.remoteBotId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:r?.lastCheckedAt??null,lastConnectedAt:r?.lastConnectedAt??null},stats:{messagesReceived:r?.messagesReceived??0,messagesReplied:r?.messagesReplied??0},error:structuredClone(this.#n.get(e.botId)??null)}}),o=a.filter(e=>e.connected).length,i=this.#i?this.#I.get(this.#i):null;return{schemaVersion:1,revision:this.#g,state:i&&v1.has(i.state)?"provisioning":a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o},...i&&v1.has(i.state)?{provisioning:vg(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#i&&await this.cancelProvisioning(this.#i),await Promise.allSettled([...this.#t.values()]),await Promise.allSettled([...this.#E.keys()].map(a=>this.#d(a))))}async#l(a){try{let o=await this.#A.poll({scode:a.scode,signal:a.controller.signal});if(a.controller.signal.aborted||XC.has(a.state)||o.status==="waiting")return;if(o.status==="expired"){a.state="expired",a.error=Cr("expired","\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"),this.#y(a);return}if(o.status!=="success"){a.state="failed",a.error=Cr("qr-connect-failed","\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"),this.#y(a);return}a.state="connecting",a.verificationUrl=null,a.expiresAt=null,a.scode=null,this.#f();let i=this.#C(a,o);a.transition=i,await i}catch{if(a.controller.signal.aborted)return;a.state="failed",a.error=Cr("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.#o.warn?.("[dsh-im:wecom] QR polling failed"),this.#y(a)}}async#C(a,o){try{let i=kg(o.remoteBotId),e=kg(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");a.botId=await this.#h(a,{remoteBotId:i,secret:e}),a.state="connected",a.error=null}catch{a.controller.signal.aborted?(a.state="cancelled",a.error=Cr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=Cr("activation-failed","\u4F01\u4E1A\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u63A5\u5165\u914D\u7F6E\u3002"),this.#o.error?.("[dsh-im:wecom] provisioning failed"))}finally{this.#y(a)}}async#h(a,{remoteBotId:o,secret:i}){let e=AQ(o),r=this.#a.getByRemoteBotId(o),A=await this.#e.resolve(e.secretRef).catch(()=>{}),t={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#Q(e.botId,async()=>{await this.#e.set(e.secretRef,i);try{if(a.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#a.save(t)}catch(s){throw await this.#B(e.secretRef,A),s}try{if(a.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#p(t,i),this.#n.delete(e.botId)}catch(s){if(a.controller.signal.aborted)throw await this.#d(e.botId),r?await this.#a.save(r).catch(()=>{}):await this.#a.remove(e.botId).catch(()=>null)&&await this.#s({botId:e.botId,config:t}).catch(c=>{this.#o.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#B(e.secretRef,A),s;this.#n.set(e.botId,Cr("connection-failed","\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u7ED1\u5B9A\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002")),this.#o.warn?.(`[dsh-im:wecom] bot ${e.botId} activation connection failed`)}return this.#f(),e.botId})}async#p(a,o){if(this.#c)throw new Error("Enterprise WeChat controller is closed");if(await this.#d(a.botId),this.#c)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:a.botId,config:a,secret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Enterprise WeChat runtime");this.#E.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#E.delete(a.botId),e}}async#d(a){let o=this.#E.get(a);this.#E.delete(a),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-im:wecom] bot ${a} failed to stop cleanly:`,i)})}async#u(a){let o=await this.#e.resolve(a).catch(()=>{});return kg(o?.value)}async#B(a,o){o?.value?await this.#e.set(a,o.value).catch(()=>{}):await this.#e.unset(a).catch(()=>{})}#Q(a,o){let r=(this.#t.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#t.get(a)===r&&this.#t.delete(a)});return this.#t.set(a,r),r}#y(a){a.scode=null,a.verificationUrl=null,a.expiresAt=null,this.#i===a.id&&(this.#i=null),this.#f();let o=[...this.#I.values()].filter(i=>XC.has(i.state));for(;o.length>16;)this.#I.delete(o.shift().id)}#f(){this.#g+=1}};import{WSAuthFailureError as hue,WSClient as due,WSReconnectExhaustedError as Bue}from"@wecom/aibot-node-sdk";import{generateReqId as Iue}from"@wecom/aibot-node-sdk";var lue=["\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/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 \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(` `),Eue=18e3,oQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002";function bI(n){return typeof n=="string"&&n.trim()?n.trim():null}function ep(n){return n?.body&&typeof n.body=="object"?n.body:{}}function P1(n){let a=ep(n);return a.chattype==="group"?`group:${a.chatid}`:`direct:${a.from?.userid}`}function mN(n){let a=ep(n),o="";return a.msgtype==="text"?o=typeof a.text?.content=="string"?a.text.content.trim():"":a.msgtype==="voice"?o=typeof a.voice?.content=="string"?a.voice.content.trim():"":a.msgtype==="mixed"&&Array.isArray(a.mixed?.msg_item)&&(o=a.mixed.msg_item.filter(i=>i?.msgtype==="text"&&typeof i.text?.content=="string").map(i=>i.text.content).join(` -`).trim()),a.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function nQ(n,a=Eue){let o=String(n??"").trim();if(!o)return[];let i=[],e="",r=0;for(let A of o){let t=Buffer.byteLength(A);e&&r+t>a?(i.push(e),e=A,r=t):(e+=A,r+=t)}return e&&i.push(e),i}function Cue(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function pue(n,a){return a.questions[a.index]&&bI(ep(n).from?.userid)===a.actor&&bI(mN(n))}function SN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var sQ=class{#A;#e;#a;#r;#s;#o;#E;#n;#I=new Map;#i=new Map;#t=new Map;#g=new Set;constructor({client:a,harness:o,state:i,status:e=SN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=Iue,signal:s}){if(!a||typeof a.replyStream!="function"||typeof a.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s}get status(){return structuredClone(this.#r)}accept(a){if(this.#n?.aborted)return Promise.resolve();let o=ep(a),i=bI(o.msgid),e=bI(o.from?.userid),r=o.chattype==="group"?bI(o.chatid):e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#a.hasSeen(i)||this.#g.has(i))return Promise.resolve();let A=P1(a);this.#g.add(i);let t=this.#i.get(A);if(t&&t.actor!==e)return this.#c(a,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#c(a,i,A);if(t){pue(a,t)&&(t.claimedReplyMessageId=i);let g=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#p(a,i,e,r,A,t)).finally(()=>{this.#g.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===g&&(t.queue=null)});return t.queue=g,g}return this.#c(a,i,A)}#c(a,o,i,{releaseMessageId:e=!0,alreadyRecorded:r=!1}={}){let t=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(a,{alreadyRecorded:r})).finally(()=>{e&&this.#g.delete(o),this.#I.get(i)===t&&this.#I.delete(i)});return this.#I.set(i,t),t}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#i.values()].flatMap(a=>a.queue?[a.queue]:[])])}async#l(a,o){for(let i of nQ(o))this.#n?.throwIfAborted(),await this.#A.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#C(a,o,i){this.#n?.throwIfAborted();let e=nQ(i);if(e.length!==0)try{await this.#A.replyStream(a,this.#E("stream"),e[0],!0);for(let r of e.slice(1))await this.#A.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#l(o,i)}}async#h(a,{alreadyRecorded:o=!1}={}){if(this.#n?.aborted)return;let i=ep(a),e=typeof i.msgid=="string"?i.msgid:"",r=typeof i.from?.userid=="string"?i.from.userid:"",A=i.chattype==="group"?i.chatid:r;if(!e||!r||!A||!["single","group"].includes(i.chattype))return;if(!o){if(this.#a.hasSeen(e))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let t=mN(a),s=P1(a),g=null,c=!1;try{if(!t){await this.#C(a,A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u8BED\u97F3\u8F6C\u5199\u548C\u56FE\u6587\u6DF7\u6392\u4E2D\u7684\u6587\u5B57\u6D88\u606F\u3002"),await this.#a.markSeen(e);return}let l=t.toLowerCase();if(l==="/help"){await this.#C(a,A,lue),await this.#a.markSeen(e);return}if(l==="/status"){await this.#e.ensureRunning({signal:this.#n}),await this.#C(a,A,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#a.markSeen(e);return}if(l==="/new"){await this.#a.clearSession(s),await this.#C(a,A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#a.markSeen(e);return}let C=await Kr(t,this.#e,s);if(C){for(let y of C.messages??[C.message])await this.#C(a,A,y);await this.#a.markSeen(e);return}g=this.#E("stream");try{await this.#A.replyStream(a,g,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),c=!0}catch(y){this.#s.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",y)}let{answer:u}=await ir({harness:this.#e,state:this.#a,key:s,text:t,createOptions:{signal:this.#n},existsOptions:{signal:this.#n},askOptions:{timeoutMs:this.#o,signal:this.#n,onUpdate:c&&typeof this.#A.replyStreamNonBlocking=="function"?async y=>{let m=nQ(Cue(y))[0];m&&await this.#A.replyStreamNonBlocking(a,g,m,!1)}:void 0,onInteraction:y=>this.#d(y,{key:s,actor:r,chatId:A,requiresMention:i.chattype==="group"}),onInteractionResolved:y=>this.#u(y)}}),Q=nQ(u||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),f=!1;if(c&&Q.length>0)try{await this.#A.replyStream(a,g,Q[0],!0);for(let y of Q.slice(1))await this.#A.sendMessage(A,{msgtype:"markdown",markdown:{content:y}});f=!0}catch(y){this.#s.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",y)}f||await this.#l(A,u),await this.#a.markSeen(e),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(l){if(this.#n?.aborted)return;this.#r.lastError=l?.message??String(l),this.#s.error?.("[dsh-im:wecom] failed to process an inbound message");try{c&&g?await this.#A.replyStream(a,g,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",!0):await this.#C(a,A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#a.markSeen(e)}catch{this.#s.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await this.#D(s)}}async#p(a,o,i,e,r,A){if(this.#n?.aborted)return;let t=this.#i.get(r),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#Q(a,o,e):this.#c(a,o,r,{releaseMessageId:!1});if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=bI(mN(a));if(!g){await this.#C(a,e,"\u8BF7\u7528\u6587\u5B57\u6216\u8BED\u97F3\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#i.get(r);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#C(a,e,oQ).catch(()=>{});return}return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#B(c)}catch{this.#r.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#s.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let C=this.#i.get(r);if(!C||C!==A||C.submitting){if(s&&(!C||C!==A)){await this.#C(a,e,oQ).catch(()=>{});return}return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(Hr(l,g)),c.index+=1,c.index{});return}if(this.#i.get(r)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#s.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#C(a,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#d(a,{key:o,actor:i,chatId:e,requiresMention:r}){if(a?.kind!=="question")return;let A=a?.payload?.questions,t=typeof a?.interactionId=="string"?a.interactionId:a?.rpcId;if(typeof a?.rpcId!="string"||typeof t!="string"||typeof a.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Lr(c))){this.#s.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(a.recovered===!0){await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#l(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.#i.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#B(s);return}if(this.#t.has(t))return;if(s){this.#s.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#i.set(o,g),this.#t.set(g.interactionId,o),await this.#B(g)}#u(a){let o=a?.interactionId;if(a?.kind!=="question"||typeof o!="string")return;let i=this.#t.get(o);i&&this.#f(i,o)}#B(a){if(!a.needsPresentation)return Promise.resolve();if(a.presentationPromise)return a.presentationPromise;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=this.#l(a.chatId,Ur(o,a.index,a.questions.length,{requiresMention:a.requiresMention})).then(()=>{a.needsPresentation=!1}).finally(()=>{a.presentationPromise===i&&(a.presentationPromise=null)});return a.presentationPromise=i,i}async#Q(a,o,i){this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#C(a,i,oQ).catch(()=>{}))}#y(a,o){let i=this.#i.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(a),this.#t.delete(i.interactionId),i)}#f(a,o){return this.#y(a,o)!==null}async#D(a){let o=this.#y(a);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#s.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function uue(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function Que(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...SN()}}var Ap=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i=Que();#t=null;#g=null;#c=null;#l=null;#C=null;constructor({config:a,secret:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new due(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g}get status(){return structuredClone(this.#i)}async start(){if(this.#i.ready&&this.#t)return this.status;if(this.#c)return this.#c;this.#C?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let a=new AbortController;return this.#l=a,this.#C=a,this.#c=this.#h(a.signal).finally(()=>{this.#l===a&&(this.#l=null),this.#c=null}),this.#c}async#h(a){await this.#p(),a.throwIfAborted(),this.#i.startedAt=new Date().toISOString(),this.#i.wecomConnectionState="connecting",this.#i.lastError=null,await this.#a.ensureRunning(),this.#i.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#A.remoteBotId,secret:this.#e,logger:o,maxReconnectAttempts:this.#n});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#t=i,this.#g=new sQ({client:i,harness:this.#a,state:this.#r,status:this.#i,logger:this.#s,replyTimeoutMs:this.#o,signal:a});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#t!==i||a.aborted)return;A=!0;let Q=Date.now();this.#i.ready=!0,this.#i.wecomConnectionState="connected",this.#i.lastCheckedAt=Q,this.#i.lastConnectedAt=Q,this.#i.lastError=null,e()},g=()=>{this.#t===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},c=()=>{this.#t===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},l=Q=>{if(this.#t!==i)return;let f=Q instanceof hue||Q instanceof Bue;!A&&f&&r(Q),f&&(this.#i.ready=!1,this.#i.wecomConnectionState="failed"),this.#i.lastError=f?Q.name:"connection-error",this.#s.warn?.(`[dsh-im:wecom] bot ${this.#A.botId} connection error`)},C=Q=>this.#g?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",C);let u;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{a.addEventListener("abort",()=>f(a.reason),{once:!0})}),new Promise((Q,f)=>{u=setTimeout(()=>f(uue()),this.#E)})]),this.status}catch(Q){throw a.aborted?(await this.#p(),Q):(this.#i.ready=!1,this.#i.wecomConnectionState="failed",this.#i.lastError=Q?.message??String(Q),await this.#p(),Q)}finally{clearTimeout(u)}}async stop(){let a=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#C?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#C=null,await this.#p(),await a?.catch(()=>{}),this.status}async#p(){let a=this.#t,o=this.#g;this.#t=null,this.#g=null;try{a?.disconnect(),a?.removeAllListeners?.()}catch{this.#s.warn?.(`[dsh-im:wecom] bot ${this.#A.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#i.ready=!1,this.#i.wecomConnectionState="idle"}};var G1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function fue(n){if(!Array.isArray(n)||n.length===0)return[...G1];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...G1]}var gQ=class{#A;#e;#a;#r;#s;#o;#E;#n=null;#I=null;#i=0;#t=!1;#g=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#A=a,this.#e=o,this.#a=i,this.#r=fue(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#g||this.#t?this:(this.#g=!0,this.#C(0),this)}async close(){this.#t||(this.#t=!0,this.#n!==null&&this.#E(this.#n),this.#n=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#C(a){this.#t||(this.#n=this.#o(()=>{this.#n=null,this.#h()},a),this.#n?.unref?.())}async#h(){if(this.#t||this.#I)return;let a=this.#p();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#t)return;let a=await this.#A.initialize();if(this.#t)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Due(n){let a=Pg(n.dshHome??process.env.DSH_HOME??tp(mue(),".dsh")),o=Pg(n.dataDir??tp(a,"integrations","dsh-wecom"));return{config:Pg(n.configPath??tp(o,"config.json")),bots:Pg(n.botsDir??tp(o,"bots")),workspaces:Pg(n.workspacesPath??tp(o,"workspaces.json"))}}async function wN(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??eQ,e=o.StateStore??iQ,r=o.HarnessClient??tQ,A=o.Controller??$C,t=o.Runtime??Ap,s=o.QrAuth??aQ,g=o.createConnectionSupervisor??DN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Due(a),C=await new i(l.config).load(),u=Pg(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ia,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:u}).load(),y=C.list();await f.reconcile(y.map(G=>G.botId)),await Promise.all(y.map(G=>f.ensure(G.botId)));let m=typeof C.remove=="function"?La(C,{workspaces:f}):C,T=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),k=new Map,F=G=>Pg(l.bots,G,"state.json"),j=async G=>{let R=k.get(G);return R||(R=await new e(F(G)).load(),k.set(G,R)),R},x=new r({baseUrl:Sue(n.webServer,a.harnessBaseUrl),workspace:u,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh"}),H=new A({qrAuth:T,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:G,config:R,secret:Z})=>{let U=await j(G);await f.ensure(G);let b=Ua(x,{botId:G,workspaces:f,state:U});return new t({config:R,secret:Z,harness:b.harness,state:b.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...L)=>c.error?.(`[${G}]`,...L),warn:(...L)=>c.warn?.(`[${G}]`,...L),info:(...L)=>c.info?.(`[${G}]`,...L),debug:(...L)=>c.debug?.(`[${G}]`,...L)}})},deleteState:async({botId:G})=>{let R=k.get(G);if(k.delete(G),R&&typeof R.remove=="function")await R.remove();else try{await yue(F(G))}catch(Z){if(Z?.code!=="ENOENT")throw Z}}}),J=Ha(H,{workspaces:f,stateFor:j}),K=g({controller:J,harness:x,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:J,ready:K.ready,async close(){await K.close(),await J.close(),x.stopManagedProcess()}}}import wue from"qrcode";var L1="/wecom",wa=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:or}),U1=Object.freeze(Object.values(wa)),Oue=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function bN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function _I(n,a){return bN(n)&&Object.keys(n).every(o=>a.includes(o))}function ON(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F1(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function Mue(n,a){return bN(a)?n===wa.status?_I(a,[])?null:"connection.status does not accept fields.":n===wa.beginProvisioning?_I(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[wa.pollProvisioning,wa.cancelProvisioning].includes(n)?_I(a,["attemptId"])&&ON(a.attemptId)?null:`${n} requires an attemptId.`:n===wa.bindCredentials?_I(a,["botId","secret"])&&F1(a.botId,512)&&F1(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===wa.reconnectBot?_I(a,["botId"])&&ON(a.botId)?null:"bot.reconnect requires a botId.":n===wa.deleteBot?_I(a,["botId","confirm"])&&ON(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===wa.setWorkspace?Ya(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function NI(n){if(Array.isArray(n))return n.map(NI);if(!bN(n))return n;let a={};for(let[o,i]of Object.entries(n))Oue.has(o)||(a[o]=NI(i));return a}async function bue(n){return wue.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function MN(n,a){return!n||typeof n.verificationUrl!="string"?NI(n):NI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function ap(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await MN(o.provisioning,a)),NI(o)}function H1(n,{encodeQr:a=bue}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!U1.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Mue(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===wa.status)s=await ap(await n.status(),i);else if(e===wa.beginProvisioning)s=await MN(await n.startProvisioning(),i);else if(e===wa.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await MN(g,i)}else if(e===wa.cancelProvisioning)s=NI(await n.cancelProvisioning(r.attemptId));else if(e===wa.bindCredentials)s=await ap(await n.bindCredentials(r),i);else if(e===wa.reconnectBot)s=await ap(await n.reconnectBot(r.botId),i);else if(e===wa.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ap(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await ap(await n.deleteBot(r.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=xa(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 cQ(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(L1,H1(a,o),{authority:Ka(i)})}async function K1(n,a={}){if(a?.controller)return cQ(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await wN(n,a,a.internals),i=cQ(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as EQe}from"node:fs/promises";import{homedir as CQe}from"node:os";import{join as np,resolve as Gg}from"node:path";import{createHash as Hue}from"node:crypto";import{mkdir as Kue,readFile as Yue,rename as xue,unlink as jue,writeFile as Jue}from"node:fs/promises";import{dirname as que}from"node:path";import{randomBytes as _ue,randomUUID as Nue}from"node:crypto";var lQ="https://ilinkai.weixin.qq.com/",Tue="2.4.6",Rue="3",kue="bot",vue=2<<16|1024|6,Pue=15e3,Y1=35e3,Gue=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),ot=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function Ni(n){return typeof n=="string"&&n.trim()?n.trim():null}function _N(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function RI(n){let a;try{a=new URL(n)}catch{throw new ot("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!_N(a.hostname)||a.port!==""&&a.port!=="443")throw new ot("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return a.username="",a.password="",a.search="",a.hash="",a.pathname.endsWith("/")||(a.pathname+="/"),a.toString()}function Fue(n){let a=Ni(n);if(!a)throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(a)}catch{throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!_N(o.hostname))throw new ot("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function j1(){return{"iLink-App-Id":kue,"iLink-App-ClientVersion":String(vue)}}function Lue(n){let a={...j1(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(_ue(4).readUInt32BE(0)),"utf8").toString("base64")};return Ni(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function IQ(){return{channel_version:Tue,bot_agent:"DeepSeekHarness/0.7.0"}}function x1(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function TI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=Pue,signal:t,authenticated:s=!0}){let g=RI(o),c=new URL(i,g);if(!_N(c.hostname))throw new ot("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,C=!1,u=()=>l.abort(t?.reason);if(t?.aborted)throw x1(t);t?.addEventListener("abort",u,{once:!0});let Q=A>0?setTimeout(()=>{C=!0,l.abort()},A):null;try{let f=await n(c,{method:a,headers:s?Lue(r):j1(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new ot("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 ot("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?x1(t):C?new ot("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof ot?f:new ot("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",u)}}function Uue(n){if(!n||typeof n!="object"||!Gue.has(n.status))throw new ot("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function J1({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({async beginLogin({localTokens:a=[],botType:o=Rue,signal:i}={}){let e=[...new Set(a.map(Ni).filter(Boolean))].slice(-10),r=await TI(n,{method:"POST",baseUrl:lQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=Ni(r?.qrcode);if(!A)throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Fue(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=lQ,verifyCode:i,signal:e}){let r=Ni(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;Ni(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await TI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y1,signal:e,authenticated:!1});return Uue(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:IQ()},token:o,timeoutMs:e??Y1,signal:r})}catch(A){if(A instanceof ot&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:a,token:o,toUserId:i,text:e,contextToken:r,runId:A,signal:t}){let s=Ni(i),g=Ni(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Nue()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...Ni(r)?{context_token:r.trim()}:{},...Ni(A)?{run_id:A.trim()}:{}},base_info:IQ()}});if(c?.ret!==void 0&&c.ret!==0)throw new ot("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:a,token:o,signal:i}){let e=await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:IQ()}});if(e?.ret!==void 0&&e.ret!==0)throw new ot("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:IQ()}})}})}function EQ(n){for(let a of n?.item_list??[]){if(a?.type===1&&typeof a.text_item?.text=="string"){let o=a.text_item.text.trim();if(o)return o}if(a?.type===3&&typeof a.voice_item?.text=="string"){let o=a.voice_item.text.trim();if(o)return o}}return null}function NN(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Ni(n?.client_id)}function q1(n,a=4e3){if(n.length<=a)return[n];let o=[],i=n;for(;i.length>a;){let e=i.lastIndexOf(` +`).trim()),a.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function nQ(n,a=Eue){let o=String(n??"").trim();if(!o)return[];let i=[],e="",r=0;for(let A of o){let t=Buffer.byteLength(A);e&&r+t>a?(i.push(e),e=A,r=t):(e+=A,r+=t)}return e&&i.push(e),i}function Cue(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function pue(n,a){return a.questions[a.index]&&bI(ep(n).from?.userid)===a.actor&&bI(mN(n))}function SN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var sQ=class{#A;#e;#a;#r;#s;#o;#E;#n;#I=new Map;#i=new Map;#t=new Map;#g=new Set;constructor({client:a,harness:o,state:i,status:e=SN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=Iue,signal:s}){if(!a||typeof a.replyStream!="function"||typeof a.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s}get status(){return structuredClone(this.#r)}accept(a){if(this.#n?.aborted)return Promise.resolve();let o=ep(a),i=bI(o.msgid),e=bI(o.from?.userid),r=o.chattype==="group"?bI(o.chatid):e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#a.hasSeen(i)||this.#g.has(i))return Promise.resolve();let A=P1(a);this.#g.add(i);let t=this.#i.get(A);if(t&&t.actor!==e)return this.#c(a,i,A);if(t?.submitting||t?.claimedReplyMessageId)return this.#c(a,i,A);if(t){pue(a,t)&&(t.claimedReplyMessageId=i);let g=(t.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#p(a,i,e,r,A,t)).finally(()=>{this.#g.delete(i),t.claimedReplyMessageId===i&&(t.claimedReplyMessageId=null),t.queue===g&&(t.queue=null)});return t.queue=g,g}return this.#c(a,i,A)}#c(a,o,i,{releaseMessageId:e=!0,alreadyRecorded:r=!1}={}){let t=(this.#I.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#h(a,{alreadyRecorded:r})).finally(()=>{e&&this.#g.delete(o),this.#I.get(i)===t&&this.#I.delete(i)});return this.#I.set(i,t),t}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#i.values()].flatMap(a=>a.queue?[a.queue]:[])])}async#l(a,o){for(let i of nQ(o))this.#n?.throwIfAborted(),await this.#A.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#C(a,o,i){this.#n?.throwIfAborted();let e=nQ(i);if(e.length!==0)try{await this.#A.replyStream(a,this.#E("stream"),e[0],!0);for(let r of e.slice(1))await this.#A.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#l(o,i)}}async#h(a,{alreadyRecorded:o=!1}={}){if(this.#n?.aborted)return;let i=ep(a),e=typeof i.msgid=="string"?i.msgid:"",r=typeof i.from?.userid=="string"?i.from.userid:"",A=i.chattype==="group"?i.chatid:r;if(!e||!r||!A||!["single","group"].includes(i.chattype))return;if(!o){if(this.#a.hasSeen(e))return;this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString()}let t=mN(a),s=P1(a),g=null,c=!1;try{if(!t){await this.#C(a,A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u8BED\u97F3\u8F6C\u5199\u548C\u56FE\u6587\u6DF7\u6392\u4E2D\u7684\u6587\u5B57\u6D88\u606F\u3002"),await this.#a.markSeen(e);return}let l=t.toLowerCase();if(l==="/help"){await this.#C(a,A,lue),await this.#a.markSeen(e);return}if(l==="/status"){await this.#e.ensureRunning({signal:this.#n}),await this.#C(a,A,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#a.markSeen(e);return}if(l==="/new"){await this.#a.clearSession(s),await this.#C(a,A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#a.markSeen(e);return}let C=await Kr(t,this.#e,s);if(C){for(let y of C.messages??[C.message])await this.#C(a,A,y);await this.#a.markSeen(e);return}g=this.#E("stream");try{await this.#A.replyStream(a,g,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),c=!0}catch(y){this.#s.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",y)}let{answer:u}=await ir({harness:this.#e,state:this.#a,key:s,text:t,createOptions:{signal:this.#n},existsOptions:{signal:this.#n},askOptions:{timeoutMs:this.#o,signal:this.#n,onUpdate:c&&typeof this.#A.replyStreamNonBlocking=="function"?async y=>{let m=nQ(Cue(y))[0];m&&await this.#A.replyStreamNonBlocking(a,g,m,!1)}:void 0,onInteraction:y=>this.#d(y,{key:s,actor:r,chatId:A,requiresMention:i.chattype==="group"}),onInteractionResolved:y=>this.#u(y)}}),Q=nQ(u||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),f=!1;if(c&&Q.length>0)try{await this.#A.replyStream(a,g,Q[0],!0);for(let y of Q.slice(1))await this.#A.sendMessage(A,{msgtype:"markdown",markdown:{content:y}});f=!0}catch(y){this.#s.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",y)}f||await this.#l(A,u),await this.#a.markSeen(e),this.#r.messagesReplied+=1,this.#r.lastReplyAt=new Date().toISOString(),this.#r.lastError=null}catch(l){if(this.#n?.aborted)return;this.#r.lastError=l?.message??String(l),this.#s.error?.("[dsh-im:wecom] failed to process an inbound message");try{c&&g?await this.#A.replyStream(a,g,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",!0):await this.#C(a,A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#a.markSeen(e)}catch{this.#s.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await this.#D(s)}}async#p(a,o,i,e,r,A){if(this.#n?.aborted)return;let t=this.#i.get(r),s=A.claimedReplyMessageId===o;if(!t||t!==A||t.submitting)return s&&(!t||t!==A)?this.#Q(a,o,e):this.#c(a,o,r,{releaseMessageId:!1});if(this.#a.hasSeen(o))return;await this.#a.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString();let g=bI(mN(a));if(!g){await this.#C(a,e,"\u8BF7\u7528\u6587\u5B57\u6216\u8BED\u97F3\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002").catch(()=>{});return}let c=this.#i.get(r);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#C(a,e,oQ).catch(()=>{});return}return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#B(c)}catch{this.#r.lastError="\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",this.#s.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let C=this.#i.get(r);if(!C||C!==A||C.submitting){if(s&&(!C||C!==A)){await this.#C(a,e,oQ).catch(()=>{});return}return this.#c(a,o,r,{releaseMessageId:!1,alreadyRecorded:!0})}}let l=c.questions[c.index];if(l){if(c.answers.push(Hr(l,g)),c.index+=1,c.index{});return}if(this.#i.get(r)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#r.lastError="\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002",this.#s.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#C(a,e,"\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002").catch(()=>{})}}}async#d(a,{key:o,actor:i,chatId:e,requiresMention:r}){if(a?.kind!=="question")return;let A=a?.payload?.questions,t=typeof a?.interactionId=="string"?a.interactionId:a?.rpcId;if(typeof a?.rpcId!="string"||typeof t!="string"||typeof a.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Lr(c))){this.#s.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(a.recovered===!0){await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#l(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.#i.get(o);if(s?.interactionId===t){s.interaction=a,s.needsPresentation&&await this.#B(s);return}if(this.#t.has(t))return;if(s){this.#s.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await a.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:t,sessionId:a.sessionId,interaction:a,actor:i,requiresMention:r,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#i.set(o,g),this.#t.set(g.interactionId,o),await this.#B(g)}#u(a){let o=a?.interactionId;if(a?.kind!=="question"||typeof o!="string")return;let i=this.#t.get(o);i&&this.#f(i,o)}#B(a){if(!a.needsPresentation)return Promise.resolve();if(a.presentationPromise)return a.presentationPromise;let o=a.questions[a.index];if(!o)return Promise.resolve();let i=this.#l(a.chatId,Ur(o,a.index,a.questions.length,{requiresMention:a.requiresMention})).then(()=>{a.needsPresentation=!1}).finally(()=>{a.presentationPromise===i&&(a.presentationPromise=null)});return a.presentationPromise=i,i}async#Q(a,o,i){this.#a.hasSeen(o)||(await this.#a.markSeen(o),this.#r.messagesReceived+=1,this.#r.lastMessageAt=new Date().toISOString(),await this.#C(a,i,oQ).catch(()=>{}))}#y(a,o){let i=this.#i.get(a);return!i||o!==void 0&&i.interactionId!==o?null:(this.#i.delete(a),this.#t.delete(i.interactionId),i)}#f(a,o){return this.#y(a,o)!==null}async#D(a){let o=this.#y(a);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#s.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function uue(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function Que(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...SN()}}var Ap=class{#A;#e;#a;#r;#s;#o;#E;#n;#I;#i=Que();#t=null;#g=null;#c=null;#l=null;#C=null;constructor({config:a,secret:o,harness:i,state:e,logger:r=console,replyTimeoutMs:A=6e5,connectTimeoutMs:t=2e4,maxReconnectAttempts:s=10,createClient:g=c=>new due(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A,this.#E=t,this.#n=s,this.#I=g}get status(){return structuredClone(this.#i)}async start(){if(this.#i.ready&&this.#t)return this.status;if(this.#c)return this.#c;this.#C?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let a=new AbortController;return this.#l=a,this.#C=a,this.#c=this.#h(a.signal).finally(()=>{this.#l===a&&(this.#l=null),this.#c=null}),this.#c}async#h(a){await this.#p(),a.throwIfAborted(),this.#i.startedAt=new Date().toISOString(),this.#i.wecomConnectionState="connecting",this.#i.lastError=null,await this.#a.ensureRunning(),this.#i.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#I({botId:this.#A.remoteBotId,secret:this.#e,logger:o,maxReconnectAttempts:this.#n});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#t=i,this.#g=new sQ({client:i,harness:this.#a,state:this.#r,status:this.#i,logger:this.#s,replyTimeoutMs:this.#o,signal:a});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#t!==i||a.aborted)return;A=!0;let Q=Date.now();this.#i.ready=!0,this.#i.wecomConnectionState="connected",this.#i.lastCheckedAt=Q,this.#i.lastConnectedAt=Q,this.#i.lastError=null,e()},g=()=>{this.#t===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},c=()=>{this.#t===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},l=Q=>{if(this.#t!==i)return;let f=Q instanceof hue||Q instanceof Bue;!A&&f&&r(Q),f&&(this.#i.ready=!1,this.#i.wecomConnectionState="failed"),this.#i.lastError=f?Q.name:"connection-error",this.#s.warn?.(`[dsh-im:wecom] bot ${this.#A.botId} connection error`)},C=Q=>this.#g?.accept(Q);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",l),i.on("message",C);let u;try{return i.connect(),await Promise.race([t,new Promise((Q,f)=>{a.addEventListener("abort",()=>f(a.reason),{once:!0})}),new Promise((Q,f)=>{u=setTimeout(()=>f(uue()),this.#E)})]),this.status}catch(Q){throw a.aborted?(await this.#p(),Q):(this.#i.ready=!1,this.#i.wecomConnectionState="failed",this.#i.lastError=Q?.message??String(Q),await this.#p(),Q)}finally{clearTimeout(u)}}async stop(){let a=this.#c;return this.#l?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#C?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#C=null,await this.#p(),await a?.catch(()=>{}),this.status}async#p(){let a=this.#t,o=this.#g;this.#t=null,this.#g=null;try{a?.disconnect(),a?.removeAllListeners?.()}catch{this.#s.warn?.(`[dsh-im:wecom] bot ${this.#A.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#i.ready=!1,this.#i.wecomConnectionState="idle"}};var G1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function fue(n){if(!Array.isArray(n)||n.length===0)return[...G1];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...G1]}var gQ=class{#A;#e;#a;#r;#s;#o;#E;#n=null;#I=null;#i=0;#t=!1;#g=!1;#c;#l;constructor({controller:a,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:r=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!a||typeof a.initialize!="function"||typeof a.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#A=a,this.#e=o,this.#a=i,this.#r=fue(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#E=t,this.#c=new Promise(s=>{this.#l=s})}get ready(){return this.#c}start(){return this.#g||this.#t?this:(this.#g=!0,this.#C(0),this)}async close(){this.#t||(this.#t=!0,this.#n!==null&&this.#E(this.#n),this.#n=null,await this.#I?.catch(()=>{}),this.#l?.(null),this.#l=null)}#C(a){this.#t||(this.#n=this.#o(()=>{this.#n=null,this.#h()},a),this.#n?.unref?.())}async#h(){if(this.#t||this.#I)return;let a=this.#p();this.#I=a;try{await a}finally{this.#I===a&&(this.#I=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#t)return;let a=await this.#A.initialize();if(this.#t)return;this.#l?.(a),this.#l=null;let{configured:o,connected:i}=a.totals;if(i65535)throw new Error("dsh-im Enterprise WeChat requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function Due(n){let a=Pg(n.dshHome??process.env.DSH_HOME??tp(mue(),".dsh")),o=Pg(n.dataDir??tp(a,"integrations","dsh-wecom"));return{config:Pg(n.configPath??tp(o,"config.json")),bots:Pg(n.botsDir??tp(o,"bots")),workspaces:Pg(n.workspacesPath??tp(o,"workspaces.json"))}}async function wN(n,a={},o={}){if(!n?.credentials)throw new TypeError("dsh-im Enterprise WeChat requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-im Enterprise WeChat requires ctx.webServer");let i=o.ConfigStore??eQ,e=o.StateStore??iQ,r=o.HarnessClient??tQ,A=o.Controller??$C,t=o.Runtime??Ap,s=o.QrAuth??aQ,g=o.createConnectionSupervisor??DN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Due(a),C=await new i(l.config).load(),u=Pg(a.workspace??process.cwd()),Q=o.WorkspaceStore??Ia,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:u}).load(),y=C.list();await f.reconcile(y.map(G=>G.botId)),await Promise.all(y.map(G=>f.ensure(G.botId)));let m=typeof C.remove=="function"?La(C,{workspaces:f}):C,T=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),k=new Map,F=G=>Pg(l.bots,G,"state.json"),j=async G=>{let R=k.get(G);return R||(R=await new e(F(G)).load(),k.set(G,R)),R},x=new r({baseUrl:Sue(n.webServer,a.harnessBaseUrl),workspace:u,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh"}),H=new A({qrAuth:T,credentials:n.credentials,configStore:m,logger:c,createRuntime:async({botId:G,config:R,secret:Z})=>{let U=await j(G);await f.ensure(G);let b=Ua(x,{botId:G,workspaces:f,state:U});return new t({config:R,secret:Z,harness:b.harness,state:b.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...L)=>c.error?.(`[${G}]`,...L),warn:(...L)=>c.warn?.(`[${G}]`,...L),info:(...L)=>c.info?.(`[${G}]`,...L),debug:(...L)=>c.debug?.(`[${G}]`,...L)}})},deleteState:async({botId:G})=>{let R=k.get(G);if(k.delete(G),R&&typeof R.remove=="function")await R.remove();else try{await yue(F(G))}catch(Z){if(Z?.code!=="ENOENT")throw Z}}}),J=Ha(H,{workspaces:f,stateFor:j}),K=g({controller:J,harness:x,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:J,ready:K.ready,async close(){await K.close(),await J.close(),x.stopManagedProcess()}}}import wue from"qrcode";var L1="/wecom",wa=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:or}),U1=Object.freeze(Object.values(wa)),Oue=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function bN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function _I(n,a){return bN(n)&&Object.keys(n).every(o=>a.includes(o))}function ON(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function F1(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function Mue(n,a){return bN(a)?n===wa.status?_I(a,[])?null:"connection.status does not accept fields.":n===wa.beginProvisioning?_I(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[wa.pollProvisioning,wa.cancelProvisioning].includes(n)?_I(a,["attemptId"])&&ON(a.attemptId)?null:`${n} requires an attemptId.`:n===wa.bindCredentials?_I(a,["botId","secret"])&&F1(a.botId,512)&&F1(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===wa.reconnectBot?_I(a,["botId"])&&ON(a.botId)?null:"bot.reconnect requires a botId.":n===wa.deleteBot?_I(a,["botId","confirm"])&&ON(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===wa.setWorkspace?Ya(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function NI(n){if(Array.isArray(n))return n.map(NI);if(!bN(n))return n;let a={};for(let[o,i]of Object.entries(n))Oue.has(o)||(a[o]=NI(i));return a}async function bue(n){return wue.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function MN(n,a){return!n||typeof n.verificationUrl!="string"?NI(n):NI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function ap(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await MN(o.provisioning,a)),NI(o)}function H1(n,{encodeQr:a=bue}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let r=o.get(e);return r||(o.size>=16&&o.delete(o.keys().next().value),r=Promise.resolve().then(()=>a(e)),o.set(e,r)),r};return async(e,r,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!U1.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=Mue(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===wa.status)s=await ap(await n.status(),i);else if(e===wa.beginProvisioning)s=await MN(await n.startProvisioning(),i);else if(e===wa.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await MN(g,i)}else if(e===wa.cancelProvisioning)s=NI(await n.cancelProvisioning(r.attemptId));else if(e===wa.bindCredentials)s=await ap(await n.bindCredentials(r),i);else if(e===wa.reconnectBot)s=await ap(await n.reconnectBot(r.botId),i);else if(e===wa.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await ap(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await ap(await n.deleteBot(r.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=xa(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 cQ(n,a,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(L1,H1(a,o),{authority:Ka(i)})}async function K1(n,a={}){if(a?.controller)return cQ(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await wN(n,a,a.internals),i=cQ(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as EQe}from"node:fs/promises";import{homedir as CQe}from"node:os";import{join as np,resolve as Gg}from"node:path";import{createHash as Hue}from"node:crypto";import{mkdir as Kue,readFile as Yue,rename as xue,unlink as jue,writeFile as Jue}from"node:fs/promises";import{dirname as que}from"node:path";import{randomBytes as _ue,randomUUID as Nue}from"node:crypto";var lQ="https://ilinkai.weixin.qq.com/",Tue="2.4.6",Rue="3",kue="bot",vue=2<<16|1024|6,Pue=15e3,Y1=35e3,Gue=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),ot=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function Ni(n){return typeof n=="string"&&n.trim()?n.trim():null}function _N(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function RI(n){let a;try{a=new URL(n)}catch{throw new ot("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!_N(a.hostname)||a.port!==""&&a.port!=="443")throw new ot("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return a.username="",a.password="",a.search="",a.hash="",a.pathname.endsWith("/")||(a.pathname+="/"),a.toString()}function Fue(n){let a=Ni(n);if(!a)throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(a)}catch{throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!_N(o.hostname))throw new ot("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function j1(){return{"iLink-App-Id":kue,"iLink-App-ClientVersion":String(vue)}}function Lue(n){let a={...j1(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(_ue(4).readUInt32BE(0)),"utf8").toString("base64")};return Ni(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function IQ(){return{channel_version:Tue,bot_agent:"DeepSeekHarness/0.7.1"}}function x1(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function TI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=Pue,signal:t,authenticated:s=!0}){let g=RI(o),c=new URL(i,g);if(!_N(c.hostname))throw new ot("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let l=new AbortController,C=!1,u=()=>l.abort(t?.reason);if(t?.aborted)throw x1(t);t?.addEventListener("abort",u,{once:!0});let Q=A>0?setTimeout(()=>{C=!0,l.abort()},A):null;try{let f=await n(c,{method:a,headers:s?Lue(r):j1(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new ot("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 ot("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?x1(t):C?new ot("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof ot?f:new ot("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",u)}}function Uue(n){if(!n||typeof n!="object"||!Gue.has(n.status))throw new ot("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function J1({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({async beginLogin({localTokens:a=[],botType:o=Rue,signal:i}={}){let e=[...new Set(a.map(Ni).filter(Boolean))].slice(-10),r=await TI(n,{method:"POST",baseUrl:lQ,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=Ni(r?.qrcode);if(!A)throw new ot("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Fue(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=lQ,verifyCode:i,signal:e}){let r=Ni(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;Ni(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await TI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:Y1,signal:e,authenticated:!1});return Uue(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:IQ()},token:o,timeoutMs:e??Y1,signal:r})}catch(A){if(A instanceof ot&&A.code==="timeout")return{ret:0,msgs:[],get_updates_buf:i};throw A}},async sendText({baseUrl:a,token:o,toUserId:i,text:e,contextToken:r,runId:A,signal:t}){let s=Ni(i),g=Ni(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/sendmessage",token:o,signal:t,body:{msg:{from_user_id:"",to_user_id:s,client_id:`dsh-weixin-${Nue()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...Ni(r)?{context_token:r.trim()}:{},...Ni(A)?{run_id:A.trim()}:{}},base_info:IQ()}});if(c?.ret!==void 0&&c.ret!==0)throw new ot("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async notifyStart({baseUrl:a,token:o,signal:i}){let e=await TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:IQ()}});if(e?.ret!==void 0&&e.ret!==0)throw new ot("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return TI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:IQ()}})}})}function EQ(n){for(let a of n?.item_list??[]){if(a?.type===1&&typeof a.text_item?.text=="string"){let o=a.text_item.text.trim();if(o)return o}if(a?.type===3&&typeof a.voice_item?.text=="string"){let o=a.voice_item.text.trim();if(o)return o}}return null}function NN(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):Ni(n?.client_id)}function q1(n,a=4e3){if(n.length<=a)return[n];let o=[],i=n;for(;i.length>a;){let e=i.lastIndexOf(` `,a);er===null))return null;let o=new Set,i=new Set,e=new Set;for(let r of a){if(o.has(r.botId)||i.has(r.accountId)||e.has(r.tokenRef))return null;o.add(r.botId),i.add(r.accountId),e.add(r.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(a)})}var CQ=class{#A;#e=TN;#a=Promise.resolve();constructor(a){this.#A=a}async load(){try{let a=zue(JSON.parse(await Yue(this.#A,"utf8")));if(!a)throw new Error("dsh-weixin config contains invalid account data");this.#e=a}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=TN}return this}list(){return structuredClone(this.#e.accounts)}get(a){let o=this.#e.accounts.find(i=>i.botId===a);return o?structuredClone(o):null}getByAccountId(a){let o=this.#e.accounts.find(i=>i.accountId===a);return o?structuredClone(o):null}async save(a){let o=W1(a);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),r=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||r)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(a){if(!V1(a))throw new TypeError("Invalid Weixin bot id");return this.#r(o=>{let i=o.findIndex(r=>r.botId===a);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let a=this.#a.then(async()=>{try{await jue(this.#A)}catch(o){if(o?.code!=="ENOENT")throw o}this.#e=TN});this.#a=a.then(()=>{},()=>{}),await a}async#r(a){let o,i=this.#a.then(async()=>{let e=[...this.#e.accounts];o=a(e);let r=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#s(r),this.#e=r});return this.#a=i.then(()=>{},()=>{}),await i,o}async#s(a){await Kue(que(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await Jue(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await xue(o,this.#A)}};var pQ=class extends Kt{constructor(a){super({...a,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as Wue,readFile as Zue,rename as Xue,unlink as $ue,writeFile as eQe}from"node:fs/promises";import{dirname as AQe}from"node:path";var hQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function tQe(n){if(!n||typeof n!="object")return structuredClone(hQ);let a={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[o,i]of Object.entries(n.sessions))typeof o=="string"&&typeof i=="string"&&i&&(a[o]=i);return{version:1,sessions:a,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:""}}var dQ=class{#A;#e=structuredClone(hQ);#a=Promise.resolve();constructor(a){this.#A=a}async load(){try{this.#e=tQe(JSON.parse(await Zue(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(hQ),await this.#r()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){this.#e.sessions[a]=o,await this.#r()}async clearSession(a){delete this.#e.sessions[a],await this.#r()}async clearSessions(){this.#e.sessions={},await this.#r()}hasSeen(a){return this.#e.seenMessageIds.includes(a)}async markSeen(a){this.hasSeen(a)||(this.#e.seenMessageIds.push(a),this.#e.seenMessageIds.length>1e3&&this.#e.seenMessageIds.splice(0,this.#e.seenMessageIds.length-1e3),await this.#r())}getUpdatesBuf(){return this.#e.getUpdatesBuf}async setGetUpdatesBuf(a){typeof a!="string"||a===this.#e.getUpdatesBuf||(this.#e.getUpdatesBuf=a,await this.#r())}snapshot(){return structuredClone(this.#e)}async remove(){try{await $ue(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(hQ)}async#r(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#a.then(async()=>{await Wue(AQe(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await eQe(i,a,{encoding:"utf8",mode:384}),await Xue(i,this.#A)});this.#a=o.then(()=>{},()=>{}),await o}};import{randomUUID as aQe}from"node:crypto";var Z1=new Set(["starting","pending","scanned","needs_verification","connecting"]),BQ=new Set(["connected","expired","failed","cancelled"]),X1=5*6e4;function kI(n){return typeof n=="string"&&n.trim()?n.trim():null}function rQe(){return new DOMException("Provisioning was cancelled","AbortError")}function $1(n,a){let o=kI(n);return o?RI(o.includes("://")?o:`https://${o}`):RI(a)}function rp(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 _r(n,a){return Object.freeze({code:n,message:a})}var ip=class{#A;#e;#a;#r;#s;#o;#E=new Map;#n=new Map;#I=new Map;#i=null;#t=new Map;#g=0;#c=!1;constructor({api:a,credentials:o,configStore:i,createRuntime:e,deleteState:r=async()=>{},logger:A=console}){if(!a||typeof a.beginLogin!="function"||typeof a.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#A=a,this.#e=o,this.#a=i,this.#r=e,this.#s=r,this.#o=A}async initialize(){if(this.#c)return this.status();for(let a of this.#a.list())this.#E.get(a.botId)?.status?.ready!==!0&&await this.#Q(a.botId,async()=>{let i=this.#a.get(a.botId);if(!(!i||this.#c))try{let e=await this.#d(i.tokenRef);if(!e){this.#n.set(i.botId,_r("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.#n.delete(i.botId)}catch(e){this.#n.set(i.botId,_r("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")),this.#o.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.#i&&await this.cancelProvisioning(this.#i);let a={id:aQe(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+X1,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:lQ,error:null,botId:null,task:null};this.#I.set(a.id,a),this.#i=a.id,this.#f();try{let o=(await Promise.all(this.#a.list().slice(-10).map(async e=>this.#d(e.tokenRef)))).filter(Boolean),i=await this.#A.beginLogin({localTokens:o,signal:a.controller.signal});return this.#B(a),a.qrcode=i.qrcode,a.verificationUrl=i.qrcodeUrl,a.state="pending",a.expiresAt=Date.now()+X1,this.#f(),a.task=this.#l(a),rp(a)}catch(o){throw a.controller.signal.aborted?(a.state="cancelled",a.error=_r("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=_r(o instanceof ot?o.code:"qr-start-failed",o instanceof ot?o.message:"\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#i===a.id&&(this.#i=null),this.#f(),o}}registrationStatus(a){return rp(this.#I.get(a))}async submitVerification(a,o){let i=this.#I.get(a);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=kI(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(),rp(i)}async cancelProvisioning(a){let o=this.#I.get(a);return o?(BQ.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),BQ.has(o.state)||(o.state="cancelled"),o.error??=_r("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#i===o.id&&(this.#i=null),this.#f(),rp(o)):null}async reconnectBot(a){let o=this.#a.get(a);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(a,async()=>{let i=await this.#d(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#n.delete(a)}catch(e){throw this.#n.set(a,_r("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async deleteBot(a){let o=this.#a.get(a);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(a,async()=>{let i=await this.#e.resolve(o.tokenRef).catch(()=>{});await this.#p(a);try{await this.#e.unset(o.tokenRef),await this.#a.remove(a)}catch(e){throw i?.value&&(await this.#e.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.#s({botId:a,config:o})}catch(e){this.#o.warn?.(`[dsh-weixin] account ${a} state cleanup failed:`,e)}this.#n.delete(a),this.#f()}),this.status()}status(){let a=this.#a.list().map(e=>{let r=this.#E.get(e.botId)?.status??null,A=r?.ready===!0&&r.weixinConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.weixinConnectionState==="connecting"?"connecting":this.#n.has(e.botId)||r?.weixinConnectionState==="failed"?"error":"offline",s=this.#n.get(e.botId)??(t==="error"?_r("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:z1(e.accountId)},health:{status:A?"healthy":t==="error"?"error":"offline",summary:A?"\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38":t==="error"?"\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",lastCheckedAt:r?.lastCheckedAt??null},stats:{messagesReceived:r?.messagesReceived??0,messagesReplied:r?.messagesReplied??0},error:s?structuredClone(s):null}}),o=a.filter(e=>e.connected).length,i=this.#i?this.#I.get(this.#i):null;return{schemaVersion:1,revision:this.#g,state:i&&Z1.has(i.state)?"provisioning":a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o},...i&&Z1.has(i.state)?{provisioning:rp(i)}:{}}}async close(){this.#c||(this.#c=!0,this.#i&&await this.cancelProvisioning(this.#i),await Promise.allSettled([...this.#E.keys()].map(a=>this.#p(a))))}async#l(a){try{for(;!a.controller.signal.aborted&&Date.now(){a.verifyResolve=i,a.controller.signal.aborted&&i()}),a.verifyResolve=null,this.#B(a));let o=await this.#A.pollLogin({qrcode:a.qrcode,baseUrl:a.currentBaseUrl,verifyCode:a.pendingVerifyCode,signal:a.controller.signal});if(this.#B(a),o.status==="wait")a.state="pending";else if(o.status==="scaned")a.pendingVerifyCode=null,a.state="scanned";else if(o.status==="need_verifycode")a.pendingVerifyCode=null,a.state="needs_verification";else if(o.status==="verify_code_blocked"){a.state="failed",a.error=_r("verification-blocked","\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002");break}else if(o.status==="expired"){a.state="expired",a.error=_r("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002");break}else if(o.status==="scaned_but_redirect")a.currentBaseUrl=$1(o.redirect_host,a.currentBaseUrl),a.state="scanned";else if(o.status==="binded_redirect"){let i=this.#a.list().find(e=>this.#E.get(e.botId)?.status?.ready===!0)??this.#a.list()[0];i?(a.state="connected",a.botId=i.botId,a.alreadyConnected=!0):(a.state="failed",a.error=_r("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=kI(o.bot_token),e=kI(o.ilink_bot_id),r=kI(o.ilink_user_id);if(!i||!e||!r)throw new ot("incomplete-login","\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002");a.state="connecting",this.#f();let A=$1(o.baseurl,a.currentBaseUrl);a.botId=await this.#C(a,{token:i,accountId:e,ownerUserId:r,baseUrl:A}),a.state="connected",a.error=null;break}this.#f()}!a.controller.signal.aborted&&Date.now()>=a.expiresAt&&!BQ.has(a.state)&&(a.state="expired",a.error=_r("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"))}catch(o){a.controller.signal.aborted||o?.name==="AbortError"?(a.state="cancelled",a.error=_r("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=_r(o instanceof ot?o.code:"activation-failed",o instanceof ot?o.message:"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u51ED\u636E\u6216\u542F\u52A8\u6D88\u606F\u8FDE\u63A5\u3002"),this.#o.error?.("[dsh-weixin] provisioning failed:",o))}finally{a.pendingVerifyCode=null,a.verifyResolve?.(),a.verifyResolve=null,this.#i===a.id&&(this.#i=null),this.#f(),this.#y()}}async#C(a,{token:o,accountId:i,ownerUserId:e,baseUrl:r}){let A=RN(i),t=this.#a.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:r,createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g=await this.#e.resolve(A.tokenRef).catch(()=>{});return this.#Q(A.botId,async()=>{await this.#e.set(A.tokenRef,o);try{return this.#B(a),await this.#a.save(s),this.#B(a),await this.#h(s,o),this.#B(a),this.#n.delete(A.botId),this.#f(),A.botId}catch(c){throw await this.#p(A.botId),t?await this.#a.save(t).catch(()=>{}):this.#a.get(A.botId)&&await this.#a.remove(A.botId).catch(()=>null)&&await this.#s({botId:A.botId,config:s}).catch(C=>{this.#o.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",C)}),await this.#u(A.tokenRef,g),t&&g?.value&&await this.#h(t,g.value).catch(()=>{}),c}})}async#h(a,o){await this.#p(a.botId);let i=await this.#r({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Weixin runtime");try{await i.start(),this.#E.set(a.botId,i)}catch(e){throw await i.stop().catch(()=>{}),e}}async#p(a){let o=this.#E.get(a);this.#E.delete(a),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-weixin] account ${a} failed to stop cleanly:`,i)})}async#d(a){let o=await this.#e.resolve(a).catch(()=>{});return kI(o?.value)}async#u(a,o){try{o?.value?await this.#e.set(a,o.value):await this.#e.unset(a)}catch(i){this.#o.error?.(`[dsh-weixin] failed to restore credential ${a}:`,i)}}#B(a){if(a.controller.signal.aborted||this.#i!==a.id)throw rQe()}#Q(a,o){let r=(this.#t.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#t.get(a)===r&&this.#t.delete(a)});return this.#t.set(a,r),r}#y(){for(let[a,o]of this.#I)a!==this.#i&&BQ.has(o.state)&&this.#I.size>16&&this.#I.delete(a)}#f(){this.#g+=1}};var uQ="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",iQe=["\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002","","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\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","/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 \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 3666ee0..9eddaf7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@xmanrui/dsh-im", - "version": "0.7.0", + "version": "0.7.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@xmanrui/dsh-im", - "version": "0.7.0", + "version": "0.7.1", "license": "MIT", "dependencies": { "@tencent-connect/qqbot-connector": "1.2.0", diff --git a/package.json b/package.json index 95cb4e7..9c0f5bf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@xmanrui/dsh-im", - "version": "0.7.0", + "version": "0.7.1", "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 43bdb3a..f760478 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.7.0)', + 'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.7.1)', }, ...(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 9a96121..e08b523 100644 --- a/src/channels/weixin/weixin-api.mjs +++ b/src/channels/weixin/weixin-api.mjs @@ -92,7 +92,7 @@ function authenticatedHeaders(token) { function baseInfo() { return { channel_version: WEIXIN_PROTOCOL_VERSION, - bot_agent: 'DeepSeekHarness/0.7.0', + bot_agent: 'DeepSeekHarness/0.7.1', }; } diff --git a/test/channels/weixin/weixin-api.test.mjs b/test/channels/weixin/weixin-api.test.mjs index 30d36b5..4e8d076 100644 --- a/test/channels/weixin/weixin-api.test.mjs +++ b/test/channels/weixin/weixin-api.test.mjs @@ -93,7 +93,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.7.0'); + assert.equal(body.base_info.bot_agent, 'DeepSeekHarness/0.7.1'); assert.doesNotMatch(calls[0].init.body, /host-only-token/); });