From 6cb97c6a1141860dc34acfbc577b0e009e1a84b5 Mon Sep 17 00:00:00 2001 From: xmanrui <841206367@qq.com> Date: Tue, 18 Aug 2026 03:03:03 +0800 Subject: [PATCH] release: prepare dsh-im 0.7.0 --- lib/index.js | 4 ++-- package-lock.json | 4 ++-- package.json | 2 +- src/channels/discord/discord-api.mjs | 2 +- src/channels/weixin/weixin-api.mjs | 2 +- test/channels/weixin/weixin-api.test.mjs | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/index.js b/lib/index.js index 1e38960..4346cef 100644 --- a/lib/index.js +++ b/lib/index.js @@ -80,7 +80,7 @@ ${xv}`:["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=Eee(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}},Yh=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??{}}},xh=class{#A;#e;#t;#a;#s;#o;#I=null;constructor({baseUrl:a,workspace:o,agentPreset:i="standard",autostart:e=!1,dshBin:r="dsh",fetchImpl:A=fetch}){this.#A=new URL(a),this.#e=o,this.#t=i,this.#a=e,this.#s=r,this.#o=A}async rpc(a,o={},i=3e4,e={}){let r=e.rpcId??`dingtalk-${zv()}`,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 Yh(a,g.result?.error);return g.result.value}async health(a={}){return await this.rpc("host.describe",{},5e3,a),!0}async ensureRunning(a={}){try{return await this.health(a)}catch(e){if(!this.#a)throw e}if(!this.#I||this.#I.exitCode!==null){let e=this.#A.port||(this.#A.protocol==="https:"?"443":"80");this.#I=see(this.#s,["web","--host",this.#A.hostname,"--port",e],{cwd:this.#e,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#I.on("error",r=>{console.error("[dsh-dingtalk] failed to start Harness:",r.message)})}let o=Date.now()+6e4,i;for(;Date.now()t.path===o);return r?r.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(a={}){await this.ensureRunning(a);let o=await this.workspaceId(a);return(await this.rpc("session.create",{workspaceId:o,agentPreset:this.#t},3e4,a)).sessionId}async sessionExists(a,o={}){try{return await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof Yh&&i.code==="session-not-found")return!1;throw i}}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;await this.ensureRunning({signal:r});let t=await this.rpc("session.history",{sessionId:a,maxMessages:1},3e4,{signal:r}),s=Math.max(-1,...(t.events??[]).map(({event:C})=>C.seq??-1)),g=`dingtalk-${zv()}`,c=new CS({promptRpcId:g,afterSeq:s});await this.rpc("session.prompt",{sessionId:a,mode:"queue",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:g,signal:r});let l=Date.now()+e;for(;Date.now()[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,r]of i){let A=fee(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.#a=o,this.#s=i}async load(){try{this.#e=yee(JSON.parse(await hee(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(jh),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.#a()}`,staffId:r,displayName:Zv(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.#t;try{await Bee(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(jh)}async#o(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#t.then(async()=>{await pee(Qee(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await uee(i,a,{encoding:"utf8",mode:384}),await dee(i,this.#A)});this.#t=o.then(()=>{},()=>{}),await o}};import{mkdir as mee,readFile as See,realpath as Dee,rename as wee,stat as Oee,unlink as Mee,writeFile as bee}from"node:fs/promises";import{dirname as _ee,isAbsolute as eP,resolve as aE}from"node:path";var zGe=Object.freeze({version:1,workspaces:Object.freeze({})});function qh(n){let a=new Error(n);return a.code=Bc,a}async function pS(n){return aE(await Dee(n))}async function Nee(n,a){if(n===a)return!0;try{return await pS(n)===await pS(a)}catch{return!1}}function Fr(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function Tee(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"||!eP(i))return null;a[o]=aE(i)}return{version:1,workspaces:a}}async function Xv(n){if(typeof n!="string"||!n.trim()||!eP(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=aE(n.trim()),o;try{o=await Oee(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 ca=class{#A;#e;#t={};#a=new Map;#s=1;#o=new Map;#I=1;#g=new Map;#n=new WeakMap;#i=new Set;#r=Promise.resolve();#c=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=aE(o)}async load(){try{let a=Tee(JSON.parse(await See(this.#A,"utf8")));if(!a)throw new Error("dsh-im workspace config is invalid");this.#t=a.workspaces}catch(a){if(a?.code!=="ENOENT")throw a;this.#t={}}this.#a.clear(),this.#s=1,this.#o.clear(),this.#I=1,this.#g.clear(),this.#i.clear();for(let a of Object.keys(this.#t))this.#a.set(a,this.#l()),this.#o.set(a,this.#E());return this}has(a){let o=Fr(a);return Object.hasOwn(this.#t,o)&&!this.#g.has(o)}incarnationFor(a){return this.#o.get(Fr(a))??null}workspaceFor(a){return this.#t[Fr(a)]??this.#e}generationFor(a){return this.#a.get(Fr(a))??null}async whenIdle(){await this.#r}async whenBotIdle(a){let o=Fr(a);for(;;){let i=this.#c.get(o);if(!i||(await i,this.#c.get(o)===i))return}}async ensure(a,{workspace:o=this.#e}={}){let i=Fr(a),e=aE(o);return this.#p(i,async()=>{if(this.#t[i])this.#a.has(i)||this.#a.set(i,this.#l());else{this.#t[i]=e,this.#a.set(i,this.#l()),this.#o.set(i,this.#E());try{await this.#d()}catch(r){throw delete this.#t[i],this.#a.delete(i),this.#o.delete(i),r}}return this.#t[i]})}async setWorkspace(a,o,{clearSessions:i,incarnation:e}={}){let r=Fr(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 Xv(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.#t[r];this.#a.set(r,this.#l()),await i?.(),this.#t[r]=A;try{await this.#d()}catch(s){throw this.#t[r]=t,s}return A})}async bindWorkspaceSession(a,o,{conversationKey:i,sessionId:e,clearSessions:r,setSession:A,incarnation:t,expectedGeneration:s}={}){let g=Fr(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 pS(await Xv(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 qh("The bot workspace changed before the session binding could be committed.");if(!await Nee(c,this.workspaceFor(g))){let l=this.#t[g];this.#a.set(g,this.#l()),await r(),this.#t[g]=c;try{await this.#d()}catch(C){throw this.#t[g]=l,C}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#a.get(g)}})}async invalidateSessions(a,{clearSessions:o}={}){let i=Fr(a);return this.#p(i,async()=>{this.#a.set(i,this.#l()),await o?.()})}async beginRemoval(a,{clearSessions:o}={}){let i=Fr(a);return this.#p(i,async()=>{let e=this.#g.get(i);if(e)return e;let r=Object.freeze({});this.#g.set(i,r),this.#n.set(r,{botId:i,incarnation:this.incarnationFor(i)}),this.#a.set(i,this.#l());try{await o?.()}catch(A){throw this.#g.get(i)===r&&this.#g.delete(i),A}return r})}async abortRemoval(a){let{botId:o}=this.#C(a);return this.#p(o,async()=>this.#g.get(o)!==a?!1:(this.#g.delete(o),Object.hasOwn(this.#t,o)&&(this.#a.set(o,this.#l()),this.#o.has(o)||this.#o.set(o,this.#E())),!0))}async finishRemoval(a){let{botId:o,incarnation:i}=this.#C(a);return this.#p(o,async()=>this.#g.get(o)!==a?{removed:!1,persisted:!0,error:null,stale:!0}:this.incarnationFor(o)!==i?(this.#g.delete(o),{removed:!1,persisted:!0,error:null,stale:!0}):(this.#g.delete(o),this.#h(o)))}async retireAfterConfigCommit(a){let o=Fr(a);return this.#p(o,async()=>(this.#g.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(Fr)),i=new Set([...Object.keys(this.#t),...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)}}#l(){let a=this.#s;return this.#s+=1,a}#E(){let a=this.#I;return this.#I+=1,a}#C(a){if(!a||typeof a!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#n.get(a);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#h(a){let o=Object.hasOwn(this.#t,a),i=o||this.#i.has(a);if(delete this.#t[a],this.#a.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.#r.then(o,o),e=i.then(()=>{},()=>{});return this.#r=e,this.#c.set(a,e),e.finally(()=>{this.#c.get(a)===e&&this.#c.delete(a)}),i}async#d(){let a={version:1,workspaces:this.#t};await mee(_ee(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await bee(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await wee(o,this.#A),this.#i.clear()}async#u(){if(Object.keys(this.#t).length>0){await this.#d();return}try{await Mee(this.#A),this.#i.clear()}catch(a){if(a?.code!=="ENOENT")throw a;this.#i.clear()}}};function $v(n,a){return a&&typeof a.then=="function"?a.then(o=>n.decorateStatus(o)):n.decorateStatus(a)}function Ree(n){return Promise.resolve(n.status())}function Fa(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 La(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 qh("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 qh("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 qh("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=Bc,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 Ua(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 Ree(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)):$v(a,g.apply(t,c))}:(...c)=>$v(a,g.apply(t,c))}})}var AP=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function kee(n){if(!Array.isArray(n)||n.length===0)return[...AP];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...AP]}var Vh=class{#A;#e;#t;#a;#s;#o;#I;#g=null;#n=null;#i=0;#r=!1;#c=!1;#l;#E;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.#t=i,this.#a=kee(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#I=t,this.#l=new Promise(s=>{this.#E=s})}get ready(){return this.#l}start(){return this.#c||this.#r?this:(this.#c=!0,this.#C(0),this)}async close(){this.#r||(this.#r=!0,this.#g!==null&&this.#I(this.#g),this.#g=null,await this.#n?.catch(()=>{}),this.#E?.(null),this.#E=null)}#C(a){this.#r||(this.#g=this.#o(()=>{this.#g=null,this.#h()},a),this.#g?.unref?.())}async#h(){if(this.#r||this.#n)return;let a=this.#p();this.#n=a;try{await a}finally{this.#n===a&&(this.#n=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#r)return;let a=await this.#A.initialize();if(this.#r)return;this.#E?.(a),this.#E=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 Fee(n){let a=Us(n.dshHome??process.env.DSH_HOME??rE(Pee(),".dsh")),o=Us(n.dataDir??rE(a,"integrations","dsh-dingtalk"));return{root:o,config:Us(n.configPath??rE(o,"config.json")),bots:Us(n.botsDir??rE(o,"bots")),workspaces:Us(n.workspacesPath??rE(o,"workspaces.json"))}}async function dS(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??vh,e=o.DeviceAuth??Gh,r=o.StateStore??Jh,A=o.HarnessClient??xh,t=o.Controller??Zl,s=o.Runtime??AE,g=o.createConnectionSupervisor??hS,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,l=Fee(a),C=await new i(l.config).load(),u=Us(a.workspace??process.cwd()),Q=o.WorkspaceStore??ca,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(k=>k.botId)),await Promise.all(m.map(k=>f.ensure(k.botId)));let T=typeof C.remove=="function"?Fa(C,{workspaces:f}):C,R=o.deviceAuth??new e({baseUrl:a.registrationBaseUrl}),G=new Map,j=k=>Us(l.bots,k,"state.json"),x=async k=>{let $=G.get(k);return $||($=await new r(j(k)).load(),G.set(k,$)),$},H=new A({baseUrl:Gee(n.webServer,a.harnessBaseUrl),workspace:u,agentPreset:a.agentPreset??"standard",autostart:!1,dshBin:a.dshBin??"dsh"}),J=new t({deviceAuth:R,credentials:n.credentials,configStore:T,logger:c,createRuntime:async({botId:k,config:$,clientSecret:U})=>{let b=await x(k);await f.ensure(k);let L=La(H,{botId:k,workspaces:f,state:b});return new s({config:$,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?.(`[${k}]`,...ee),warn:(...ee)=>c.warn?.(`[${k}]`,...ee),info:(...ee)=>c.info?.(`[${k}]`,...ee),debug:(...ee)=>c.debug?.(`[${k}]`,...ee)}})},deleteState:async({botId:k})=>{let $=G.get(k);if(G.delete(k),$&&typeof $.remove=="function")await $.remove();else try{await vee(j(k))}catch(U){if(U?.code!=="ENOENT")throw U}}}),K=Ua(J,{workspaces:f,stateFor:x}),F=g({controller:K,harness:H,logger:c,retryDelaysMs:a.retryDelaysMs,healthyIntervalMs:a.healthyIntervalMs}).start();return{controller:K,ready:F.ready,async close(){await F.close(),await K.close(),H.stopManagedProcess()}}}import Hee from"qrcode";var Lee=new Set(["loopback","trusted-host"]);function Ha(n){if(n===void 0)return"loopback";if(Lee.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as Uee}from"node:path";var or="bot.workspace.set";function Ka(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&&Uee(n.workspace.trim())}function Ya(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 aP="/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"}),rP=Object.freeze(Object.values(Lt)),Kee=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function uS(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function _n(n,a){return uS(n)&&Object.keys(n).every(o=>a.includes(o))}function Hs(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function tP(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function Yee(n,a){return uS(a)?n===Lt.status?_n(a,[])?null:"connection.status does not accept fields.":n===Lt.beginProvisioning?_n(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Lt.pollProvisioning,Lt.cancelProvisioning].includes(n)?_n(a,["attemptId"])&&Hs(a.attemptId)?null:`${n} requires an attemptId.`:n===Lt.bindCredentials?_n(a,["clientId","clientSecret"])&&tP(a.clientId,256)&&tP(a.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Lt.reconnectBot?_n(a,["botId"])&&Hs(a.botId)?null:"bot.reconnect requires a botId.":n===Lt.deleteBot?_n(a,["botId","confirm"])&&Hs(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Lt.setWorkspace?Ka(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Lt.approveSender?_n(a,["botId","requestId","confirm"])&&Hs(a.botId)&&Hs(a.requestId)&&a.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Lt.revokeSender?_n(a,["botId","senderKey","confirm"])&&Hs(a.botId)&&Hs(a.senderKey)&&a.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function zh(n){return{ok:!1,error:{code:"bad-request",message:n}}}function Wh(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function xee(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function yc(n){if(Array.isArray(n))return n.map(yc);if(!uS(n))return n;let a={};for(let[o,i]of Object.entries(n))Kee.has(o)||(a[o]=yc(i));return a}async function jee(n){return Hee.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function BS(n,a){return!n||typeof n.verificationUrl!="string"?yc(n):yc({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function Ks(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await BS(o.provisioning,a)),yc(o)}function Jee(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 iP(n,{encodeQr:a=jee}={}){Jee(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 Wh();if(!rP.includes(e))return zh("Unknown DingTalk endpoint.");let t=Yee(e,r);if(t)return zh(t);try{let s;if(e===Lt.status)s=await Ks(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),Wh();s=await BS(g,i)}else if(e===Lt.pollProvisioning){let g=await n.registrationStatus(r.attemptId);if(!g)return zh("The provisioning attempt no longer exists.");s=await BS(g,i)}else if(e===Lt.cancelProvisioning){if(s=await n.cancelProvisioning(r.attemptId),!s)return zh("The provisioning attempt no longer exists.");s=yc(s)}else if(e===Lt.bindCredentials)s=await Ks(await n.bindCredentials(r),i);else if(e===Lt.reconnectBot)s=await Ks(await n.reconnectBot(r.botId),i);else if(e===Lt.deleteBot)s=await Ks(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 Ks(await n.updateWorkspace(r.botId,r.workspace),i)}else e===Lt.approveSender?s=await Ks(await n.approveSender(r.botId,r.requestId),i):s=await Ks(await n.revokeSender(r.botId,r.senderKey),i);return A?.aborted?Wh():{ok:!0,value:s}}catch(s){let g=Ya(s);return A?.aborted?Wh():g?{ok:!1,error:g}:xee()}}}function Zh(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(aP,iP(a,o),{authority:Ha(i)})}async function oP(n,a={}){if(a?.controller)return Zh(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await dS(n,a,a.internals),i=Zh(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as qee}from"node:crypto";import{mkdir as Vee,readFile as zee,rename as Wee,unlink as Zee,writeFile as Xee}from"node:fs/promises";import{dirname as $ee}from"node:path";var QS=Object.freeze({version:1,bots:Object.freeze([])});function Lo(n){return typeof n=="string"&&n.trim()?n.trim():null}function nP(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iE(n,{botPrefix:a,tokenRefPrefix:o}){let i=Lo(n);if(!i)throw new TypeError("platformId is required");let e=qee("sha256").update(i).digest("hex").slice(0,24);return{botId:`${a}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function Xh(n,a){let o=Lo(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 mc=class{#A;#e;#t;#a;#s;#o;#I=QS;#g=Promise.resolve();constructor(a,{channel:o,botPrefix:i,tokenRefPrefix:e}){this.#A=a,this.#e=o,this.#t=i,this.#a=e,this.#s=new RegExp(`^${nP(i)}_[a-f0-9]{24}$`),this.#o=new RegExp(`^${nP(e)}_[A-F0-9]{24}$`)}async load(){try{let a=this.#i(JSON.parse(await zee(this.#A,"utf8")));if(!a)throw new Error(`dsh-im ${this.#e} config contains invalid bot data`);this.#I=a}catch(a){if(a?.code!=="ENOENT")throw a;this.#I=QS}return this}list(){return structuredClone(this.#I.bots)}get(a){let o=this.#I.bots.find(i=>i.botId===a);return o?structuredClone(o):null}getByPlatformId(a){let o=this.#I.bots.find(i=>i.platformId===a);return o?structuredClone(o):null}async save(a){let o=this.#n(a);if(!o)throw new Error(`Refusing to persist incomplete ${this.#e} bot data`);return this.#r(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.#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.#g.then(async()=>{try{await Zee(this.#A)}catch(o){if(o?.code!=="ENOENT")throw o}this.#I=QS});this.#g=a.then(()=>{},()=>{}),await a}#n(a){if(!a||typeof a!="object")return null;let o=Lo(a.platformId),i=Lo(a.botId),e=Lo(a.tokenRef),r=Lo(a.name);if(!o||!i||!e||!r||!this.#s.test(i)||!this.#o.test(e))return null;let A=iE(o,{botPrefix:this.#t,tokenRefPrefix:this.#a});return A.botId!==i||A.tokenRef!==e?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:r,username:Lo(a.username),createdAt:Lo(a.createdAt)??new Date().toISOString(),connectedAt:Lo(a.connectedAt)})}#i(a){if(!a||a.version!==1||!Array.isArray(a.bots))return null;let o=a.bots.map(A=>this.#n(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#r(a){let o,i=this.#g.then(async()=>{let e=[...this.#I.bots];o=a(e);let r=Object.freeze({version:1,bots:Object.freeze(e)});await this.#c(r),this.#I=r});return this.#g=i.then(()=>{},()=>{}),await i,o}async#c(a){await Vee($ee(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await Xee(o,`${JSON.stringify(a,null,2)} -`,{encoding:"utf8",mode:384}),await Wee(o,this.#A)}};var sP=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function gP(n){return iE(n,sP)}function cP(n){return Xh(n,"Discord\u673A\u5668\u4EBA")}var $h=class extends mc{constructor(a){super(a,{channel:"Discord",...sP})}};function oE(n){return typeof n=="string"&&n.trim()?n.trim():null}function ed(n,a){return Object.freeze({code:n,message:a})}var Sc=class{#A;#e;#t;#a;#s;#o;#I;#g;#n;#i=new Map;#r=new Map;#c=new Map;#l=0;#E=!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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t,this.#g=s,this.#n=g}async initialize(){if(this.#E)return this.status();for(let a of this.#t.list())await this.#u(a.botId,async()=>{if(this.#E||this.#i.get(a.botId)?.status?.ready)return;let o=await this.#p(a.tokenRef);if(!o){this.#r.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.#r.delete(a.botId)}catch(i){this.#r.set(a.botId,ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#n.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.#E)throw new Error(`${this.#A.label} controller is closed`);let o=oE(a);if(!o)throw new TypeError(`${this.#A.label} Bot Token is required`);let i=await this.#a(o),e=oE(i?.platformId),r=oE(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.#E)throw new Error(`${this.#A.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#e.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:oE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#e.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#C(g,o),this.#r.delete(A.botId)}catch(c){this.#r.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.#n.warn?.(`[dsh-im:${this.#A.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(a){let o=this.#t.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.#r.delete(a)}catch(e){throw this.#r.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.#t.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.#t.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.#g({botId:a,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:${this.#A.key}] bot ${a} state cleanup failed:`,e)}),this.#r.delete(a),this.#B()}),this.status()}status(){let a=this.#t.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.#r.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.#r.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#l,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#E||(this.#E=!0,await Promise.allSettled([...this.#c.values()]),await Promise.allSettled([...this.#i.keys()].map(a=>this.#h(a))))}async#C(a,o){if(this.#E)throw new Error(`${this.#A.label} controller is closed`);if(await this.#h(a.botId),this.#E)throw new Error(`${this.#A.label} controller is closed`);let i=await this.#I({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.#n.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 oE(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.#c.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#c.get(a)===r&&this.#c.delete(a)});return this.#c.set(a,r),r}#B(){this.#l+=1}};var eAe="https://discord.com/api/v10/";function nE(n){return typeof n=="string"&&n.trim()?n.trim():null}function AAe(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function tAe(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 Dc(n,a){let o=nE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function aAe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var sE=class{#A;#e;#t;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=eAe}){if(!aAe(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.#t=new URL(i)}getCurrentUser(a={}){return this.#a("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#a("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#a(`channels/${Dc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:Dc(i,"message id"),channel_id:Dc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#a(`channels/${Dc(a,"channel id")}/messages/${Dc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#a(`channels/${Dc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#a(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#e(new URL(a,this.#t),{method:o,headers:{authorization:`Bot ${this.#A}`,"content-type":"application/json","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.6.0)"},...i===void 0?{}:{body:JSON.stringify(i)},signal:AAe(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 tAe(c,e),this.#a(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(nE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function IP(n,a={}){let i=await new sE({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:nE(i.global_name)??nE(i.username)??"Discord\u673A\u5668\u4EBA",username:nE(i.username)}}function Ad(n){return typeof n=="string"?n.trim():""}function mr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Ji=class{#A;#e;#t;#a;#s;#o;#I;#g=new Map;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=mr(),logger:A=console,replyTimeoutMs:t=6e5}){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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t}get status(){return structuredClone(this.#s)}accept(a){let o=Ad(a?.conversationId),i=a?.kind==="group"?"group":"direct",e=`${i}:${o}`,A=(this.#g.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#n({...a,kind:i,conversationId:o})).finally(()=>{this.#g.get(e)===A&&this.#g.delete(e)});return this.#g.set(e,A),A}async waitForIdle(){await Promise.allSettled([...this.#g.values()])}async#n(a){let o=Ad(a.messageId),i=Ad(a.senderId);if(!o||!i||!a.conversationId||a.senderIsBot===!0||this.#a.hasSeen(o))return;if(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 e=a.replyTarget,r=Ad(a.content);try{if(!r){await this.#e.sendText(e,"\u76EE\u524D\u4EC5\u652F\u6301\u6587\u5B57\u6D88\u606F\u3002"),await this.#a.markSeen(o);return}let A=r.toLowerCase();if(A==="/help"){await this.#e.sendText(e,[`${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 Wee(o,this.#A)}};var sP=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function gP(n){return iE(n,sP)}function cP(n){return Xh(n,"Discord\u673A\u5668\u4EBA")}var $h=class extends mc{constructor(a){super(a,{channel:"Discord",...sP})}};function oE(n){return typeof n=="string"&&n.trim()?n.trim():null}function ed(n,a){return Object.freeze({code:n,message:a})}var Sc=class{#A;#e;#t;#a;#s;#o;#I;#g;#n;#i=new Map;#r=new Map;#c=new Map;#l=0;#E=!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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t,this.#g=s,this.#n=g}async initialize(){if(this.#E)return this.status();for(let a of this.#t.list())await this.#u(a.botId,async()=>{if(this.#E||this.#i.get(a.botId)?.status?.ready)return;let o=await this.#p(a.tokenRef);if(!o){this.#r.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.#r.delete(a.botId)}catch(i){this.#r.set(a.botId,ed("connection-failed",`${this.#A.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#n.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.#E)throw new Error(`${this.#A.label} controller is closed`);let o=oE(a);if(!o)throw new TypeError(`${this.#A.label} Bot Token is required`);let i=await this.#a(o),e=oE(i?.platformId),r=oE(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.#E)throw new Error(`${this.#A.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#e.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:r,username:oE(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#e.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#d(A.tokenRef,s),c}try{await this.#C(g,o),this.#r.delete(A.botId)}catch(c){this.#r.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.#n.warn?.(`[dsh-im:${this.#A.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(a){let o=this.#t.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.#r.delete(a)}catch(e){throw this.#r.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.#t.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.#t.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.#g({botId:a,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:${this.#A.key}] bot ${a} state cleanup failed:`,e)}),this.#r.delete(a),this.#B()}),this.status()}status(){let a=this.#t.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.#r.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.#r.get(i.botId)??null)}}),o=a.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#l,state:a.length===0?"disconnected":o===a.length?"connected":o>0?"degraded":"offline",bots:a,totals:{configured:a.length,connected:o}}}async close(){this.#E||(this.#E=!0,await Promise.allSettled([...this.#c.values()]),await Promise.allSettled([...this.#i.keys()].map(a=>this.#h(a))))}async#C(a,o){if(this.#E)throw new Error(`${this.#A.label} controller is closed`);if(await this.#h(a.botId),this.#E)throw new Error(`${this.#A.label} controller is closed`);let i=await this.#I({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.#n.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 oE(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.#c.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#c.get(a)===r&&this.#c.delete(a)});return this.#c.set(a,r),r}#B(){this.#l+=1}};var eAe="https://discord.com/api/v10/";function nE(n){return typeof n=="string"&&n.trim()?n.trim():null}function AAe(n,a){let o=AbortSignal.timeout(a);return n?AbortSignal.any([n,o]):o}function tAe(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 Dc(n,a){let o=nE(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${a}`);return o}function aAe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var sE=class{#A;#e;#t;constructor({token:a,fetchImpl:o=fetch,baseUrl:i=eAe}){if(!aAe(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.#t=new URL(i)}getCurrentUser(a={}){return this.#a("users/@me",{...a,method:"GET"})}getGatewayBot(a={}){return this.#a("gateway/bot",{...a,method:"GET"})}createMessage({channelId:a,content:o,replyToMessageId:i,signal:e}){return this.#a(`channels/${Dc(a,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:Dc(i,"message id"),channel_id:Dc(a,"channel id"),fail_if_not_exists:!1}}:{}}})}editMessage({channelId:a,messageId:o,content:i,signal:e}){return this.#a(`channels/${Dc(a,"channel id")}/messages/${Dc(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:a,signal:o}){return this.#a(`channels/${Dc(a,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#a(a,{method:o,body:i,signal:e,timeoutMs:r=15e3,expectBody:A=!0,retry:t=!0}){let s;try{s=await this.#e(new URL(a,this.#t),{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:AAe(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 tAe(c,e),this.#a(a,{method:o,body:i,signal:e,timeoutMs:r,expectBody:A,retry:!1})}if(!s.ok){let c=new Error(nE(g?.message)??`Discord API failed with HTTP ${s.status}`);throw c.code=`discord-${s.status}`,c}return A?g:null}};async function IP(n,a={}){let i=await new sE({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:nE(i.global_name)??nE(i.username)??"Discord\u673A\u5668\u4EBA",username:nE(i.username)}}function Ad(n){return typeof n=="string"?n.trim():""}function mr(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Ji=class{#A;#e;#t;#a;#s;#o;#I;#g=new Map;constructor({descriptor:a,bot:o,harness:i,state:e,status:r=mr(),logger:A=console,replyTimeoutMs:t=6e5}){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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t}get status(){return structuredClone(this.#s)}accept(a){let o=Ad(a?.conversationId),i=a?.kind==="group"?"group":"direct",e=`${i}:${o}`,A=(this.#g.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#n({...a,kind:i,conversationId:o})).finally(()=>{this.#g.get(e)===A&&this.#g.delete(e)});return this.#g.set(e,A),A}async waitForIdle(){await Promise.allSettled([...this.#g.values()])}async#n(a){let o=Ad(a.messageId),i=Ad(a.senderId);if(!o||!i||!a.conversationId||a.senderIsBot===!0||this.#a.hasSeen(o))return;if(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 e=a.replyTarget,r=Ad(a.content);try{if(!r){await this.#e.sendText(e,"\u76EE\u524D\u4EC5\u652F\u6301\u6587\u5B57\u6D88\u606F\u3002"),await this.#a.markSeen(o);return}let A=r.toLowerCase();if(A==="/help"){await this.#e.sendText(e,[`${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(` `)),await this.#a.markSeen(o);return}if(A==="/status"){await this.#t.ensureRunning(),await this.#e.sendText(e,`${this.#A.label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002`),await this.#a.markSeen(o);return}let t=`${a.kind}:${a.conversationId}`,s=await Gr(r,this.#t,t);if(s){for(let C of s.messages??[s.message])await this.#e.sendText(e,C);await this.#a.markSeen(o);return}if(A==="/new"){await this.#a.clearSession(t),await this.#e.sendText(e,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#a.markSeen(o);return}await this.#e.sendTyping?.(e).catch(C=>{this.#o.warn?.(`[dsh-im:${this.#A.key}] typing indicator failed:`,C)});let g=null,c=!1;if(typeof this.#e.openStream=="function")try{g=await this.#e.openStream(e)}catch(C){this.#o.warn?.(`[dsh-im:${this.#A.key}] unable to start a streamed reply; using text:`,C)}let{answer:l}=await ir({harness:this.#t,state:this.#a,key:t,text:r,askOptions:{timeoutMs:this.#I,onUpdate:g?async C=>{let u=C.type==="text"?C.text:C.type==="tool"?`\u6B63\u5728\u4F7F\u7528${C.name}\u2026`:C.text;u&&await g.update(u)}:void 0}});if(g)try{await g.finish(l),c=!0}catch(C){g.cancel?.(),this.#o.warn?.(`[dsh-im:${this.#A.key}] streamed reply finalization failed; using text:`,C)}c||await this.#e.sendText(e,l),await this.#a.markSeen(o),this.#s.messagesReplied+=1,this.#s.lastReplyAt=new Date().toISOString(),this.#s.lastError=null}catch(A){this.#s.lastError=A?.message??String(A),this.#o.error?.(`[dsh-im:${this.#A.key}] failed to process a message:`,A);try{await this.#e.sendText(e,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#a.markSeen(o)}catch(t){this.#o.error?.(`[dsh-im:${this.#A.key}] failed to send the safe error reply:`,t)}}}};var fS=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),td=class extends Ji{constructor(a){super({descriptor:fS,...a})}};var gE=class extends Sc{constructor(a){super({...a,descriptor:fS,inspectToken:a.inspectToken??IP,deriveIdentity:gP,maskPlatformId:cP})}};import{spawn as rAe}from"node:child_process";import{randomUUID as lP}from"node:crypto";import{isAbsolute as iAe}from"node:path";var EP=n=>new Promise(a=>setTimeout(a,n));function oAe(n){return Array.isArray(n?.items)?n.items.flatMap(a=>typeof a?.path=="string"&&iAe(a.path)?[a.path]:[]):[]}function nAe(n,a){if(!Array.isArray(a?.items)||!Array.isArray(a?.archivedSessionIds))throw new Error("Harness returned an invalid response for workspace.list");let o=a.items.find(i=>i?.path===n);if(!o)return null;if(!Array.isArray(o.sessionIds)||o.sessionIds.some(i=>typeof i!="string"))throw new Error("Harness returned invalid session IDs for workspace.list");return o}function sAe(n,a,o){if(!Array.isArray(o?.items))throw new Error("Harness returned an invalid response for session.list");let i=new Set(a),e=new Map(o.items.flatMap(r=>typeof r?.sessionId=="string"?[[r.sessionId,r]]:[]));return{workspace:n.path,sessions:n.sessionIds.map(r=>{let A=e.get(r),t=A?.projections?.values?.title;return{sessionId:r,title:typeof t=="string"?t:null,archived:i.has(r),blank:A?.blank===!0,origin:A?.origin==="subagent"?"subagent":null,summaryAvailable:A!==void 0}})}}function gAe(n){return(n?.data?.message?.content??[]).filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(` `).trim()}var yS=class{#A;#e;#t=null;#a=null;#s=new Map;#o="";#I=!1;#g=null;constructor({promptRpcId:a,afterSeq:o=-1}){this.#A=a,this.#e=o}get finished(){return this.#I}get answer(){return this.#o.trim()}get reason(){return this.#g}consume(a){let o=null,i=[...a].map(e=>e?.event??e).filter(Boolean).sort((e,r)=>(e.seq??-1)-(r.seq??-1));for(let e of i){let r=e.seq??-1;if(!(r<=this.#e)){if(this.#e=r,e.type==="turn/start"&&(this.#t=e.data?.turn??null),e.type==="user/message"&&e.data?.source?.rpcId===this.#A){this.#a=this.#t;continue}if(this.#a!==null){if(e.type==="turn/end"){if(e.data?.turn!==this.#a)continue;this.#I=!0,this.#g=e.data?.reason??null,this.#t=null;continue}if(e.data?.turn===this.#a){if(e.type==="assistant/chunk"&&e.data?.chunk?.type==="text-delta"){let A=e.data?.step??0,t=e.data.chunk.index??0,s=`${A}:${t}`;this.#s.set(s,(this.#s.get(s)??"")+e.data.chunk.text);let g=`${A}:`,c=[...this.#s.entries()].filter(([l])=>l.startsWith(g)).sort(([l],[C])=>Number(l.split(":")[1])-Number(C.split(":")[1])).map(([,l])=>l).join(` `).trim();c&&c!==this.#o&&(this.#o=c,o={type:"text",text:c});continue}if(e.type==="assistant/message"){let A=gAe(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}},ad=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??{}}},xa=class{#A;#e;#t;#a;#s;#o=null;constructor({baseUrl:a,workspace:o,agentPreset:i="standard",autostart:e=!1,dshBin:r="dsh"}){this.#A=new URL(a),this.#e=o,this.#t=i,this.#a=e,this.#s=r}async rpc(a,o={},i=3e4,e={}){let r=e.rpcId??`weixin-${lP()}`,A=await fetch(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:AbortSignal.timeout(i)});if(!A.ok)throw new Error(`Harness transport ${a} failed: HTTP ${A.status}`);let t=await A.json();if(t?.type!=="server-response"||t?.rpcId!==r)throw new Error(`Harness returned an invalid response for ${a}`);if(!t.result?.ok)throw new ad(a,t.result?.error);return t.result.value}async health(){return await this.rpc("host.describe",{},5e3),!0}async ensureRunning(){try{return await this.health()}catch(i){if(!this.#a)throw i}if(!this.#o||this.#o.exitCode!==null){let i=this.#A.port||(this.#A.protocol==="https:"?"443":"80");this.#o=rAe(this.#s,["web","--host",this.#A.hostname,"--port",i],{cwd:this.#e,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#o.on("error",e=>{console.error("[dsh-weixin] failed to start Harness:",e.message)})}let a=Date.now()+6e4,o;for(;Date.now()A.path===o);return e?e.workspaceId:(await this.rpc("workspace.create",{path:o})).workspace.workspaceId}async createSession(a={}){await this.ensureRunning();let o=await this.workspaceId(a);return(await this.rpc("session.create",{workspaceId:o,agentPreset:this.#t})).sessionId}async sessionExists(a){try{return await this.rpc("session.history",{sessionId:a,maxMessages:1}),!0}catch(o){if(o instanceof ad&&o.code==="session-not-found")return!1;throw o}}async ask(a,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,r=typeof i.onUpdate=="function"?i.onUpdate:null;await this.ensureRunning();let A=await this.rpc("session.history",{sessionId:a,maxMessages:1}),t=Math.max(-1,...(A.events??[]).map(({event:l})=>l.seq??-1)),s=`weixin-${lP()}`,g=new yS({promptRpcId:s,afterSeq:t});await this.rpc("session.prompt",{sessionId:a,mode:"queue",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,{rpcId:s});let c=Date.now()+e;for(;Date.now()a;){let r=e.lastIndexOf(` @@ -184,7 +184,7 @@ ${r.join(` `,{encoding:"utf8",mode:384}),await PBe(o,this.#A)}};var Yu=class extends xa{};var KBe="https://work.weixin.qq.com/ai/qc/generate",YBe="https://work.weixin.qq.com/ai/qc/query_result";function u1(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function BI(n){return typeof n=="string"&&n.trim()?n.trim():null}function xBe(n){let a=BI(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 jBe(n,a){return n?AbortSignal.any([n,AbortSignal.timeout(a)]):AbortSignal.timeout(a)}async function Q1(n,a,o){let i=await n(a,{method:"GET",redirect:"error",signal:jBe(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var xu=class{#A;#e;#t;#a;constructor({fetch:a=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=u1()}={}){if(typeof a!="function")throw new TypeError("A fetch implementation is required");this.#A=a,this.#e=o,this.#t=i,this.#a=[1,2,3].includes(e)?e:u1()}async start({signal:a}={}){let o=new URL(KBe);o.searchParams.set("source",this.#t),o.searchParams.set("plat",String(this.#a));let i=await Q1(this.#A,o,a),e=BI(i?.data?.scode),r=xBe(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=BI(a);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(YBe);e.searchParams.set("scode",i);let r=await Q1(this.#A,e,o),A=BI(r?.data?.status)?.toLowerCase();if(A==="success"){let t=BI(r?.data?.bot_info?.botid),s=BI(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 JBe,readFile as qBe,rename as VBe,unlink as zBe,writeFile as WBe}from"node:fs/promises";import{dirname as ZBe}from"node:path";var ju=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function XBe(n){if(!n||typeof n!="object")return structuredClone(ju);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 Ju=class{#A;#e=structuredClone(ju);#t=Promise.resolve();constructor(a){this.#A=a}async load(){try{this.#e=XBe(JSON.parse(await qBe(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(ju),await this.#a()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){this.#e.sessions[a]=o,await this.#a()}async clearSession(a){delete this.#e.sessions[a],await this.#a()}async clearSessions(){this.#e.sessions={},await this.#a()}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.#a())}async remove(){try{await zBe(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(ju)}async#a(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#t.then(async()=>{await JBe(ZBe(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await WBe(i,a,{encoding:"utf8",mode:384}),await VBe(i,this.#A)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as $Be}from"node:crypto";var f1=new Set(["pending","connecting"]),HC=new Set(["connected","failed","cancelled","expired"]);function wg(n){return typeof n=="string"&&n.trim()?n.trim():null}function Cr(n,a){return Object.freeze({code:n,message:a})}function Og(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 KC=class{#A;#e;#t;#a;#s;#o;#I=new Map;#g=new Map;#n=new Map;#i=null;#r=new Map;#c=0;#l=!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.#t=i,this.#a=e,this.#s=r,this.#o=A}async initialize(){if(this.#l)return this.status();for(let a of this.#t.list())await this.#Q(a.botId,async()=>{let o=this.#I.get(a.botId)?.status;if(this.#l||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#u(a.secretRef);if(!i){this.#g.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.#g.delete(a.botId)}catch{this.#g.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.#l)throw new Error("Enterprise WeChat controller is closed");this.#i&&await this.cancelProvisioning(this.#i);let a={id:$Be(),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.#n.set(a.id,a),this.#i=a.id,this.#f();try{let o=await this.#A.start({signal:a.controller.signal});if(a.scode=wg(o.scode),a.verificationUrl=wg(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(),Og(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.#n.get(a);if(!o||HC.has(o.state))return Og(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),Og(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),Og(o);if(!o.polling){let i=this.#E(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),Og(o)}async bindCredentials({botId:a,secret:o}={}){if(this.#l)throw new Error("Enterprise WeChat controller is closed");let i=wg(a),e=wg(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#i&&await this.cancelProvisioning(this.#i),this.#l)throw new Error("Enterprise WeChat controller is closed");let r=Ku(i);return await this.#Q(r.botId,async()=>{if(this.#l)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),t=await this.#e.resolve(r.secretRef).catch(()=>{});if(this.#l)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.#t.save(s)}catch(g){throw await this.#B(r.secretRef,t),g}try{await this.#p(s,e),this.#g.delete(r.botId)}catch{this.#g.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.#n.get(a);return o?(HC.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),HC.has(o.state)||(o.state="cancelled"),o.error??=Cr("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"),this.#y(o)),Og(o)):null}async reconnectBot(a){let o=this.#t.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.#g.delete(a)}catch(e){throw this.#g.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.#t.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.#t.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.#g.delete(a),this.#f()}),this.status()}status(){let a=this.#t.list().map(e=>{let r=this.#I.get(e.botId)?.status??null,A=r?.ready===!0&&r.wecomConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.wecomConnectionState==="connecting"?"connecting":this.#g.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:d1(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.#g.get(e.botId)??null)}}),o=a.filter(e=>e.connected).length,i=this.#i?this.#n.get(this.#i):null;return{schemaVersion:1,revision:this.#c,state:i&&f1.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&&f1.has(i.state)?{provisioning:Og(i)}:{}}}async close(){this.#l||(this.#l=!0,this.#i&&await this.cancelProvisioning(this.#i),await Promise.allSettled([...this.#r.values()]),await Promise.allSettled([...this.#I.keys()].map(a=>this.#d(a))))}async#E(a){try{let o=await this.#A.poll({scode:a.scode,signal:a.controller.signal});if(a.controller.signal.aborted||HC.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=wg(o.remoteBotId),e=wg(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=Ku(o),r=this.#t.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.#t.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.#g.delete(e.botId)}catch(s){if(a.controller.signal.aborted)throw await this.#d(e.botId),r?await this.#t.save(r).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#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.#g.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.#l)throw new Error("Enterprise WeChat controller is closed");if(await this.#d(a.botId),this.#l)throw new Error("Enterprise WeChat controller is closed");let i=await this.#a({botId:a.botId,config:a,secret:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Enterprise WeChat runtime");this.#I.set(a.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#I.delete(a.botId),e}}async#d(a){let o=this.#I.get(a);this.#I.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 wg(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.#r.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#r.get(a)===r&&this.#r.delete(a)});return this.#r.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.#n.values()].filter(i=>HC.has(i.state));for(;o.length>16;)this.#n.delete(o.shift().id)}#f(){this.#c+=1}};import{WSAuthFailureError as iue,WSClient as oue,WSReconnectExhaustedError as nue}from"@wecom/aibot-node-sdk";import{generateReqId as eue}from"@wecom/aibot-node-sdk";var Aue=["\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(` `),tue=18e3;function nN(n){return n?.body&&typeof n.body=="object"?n.body:{}}function y1(n){let a=nN(n);return a.chattype==="group"?`group:${a.chatid}`:`direct:${a.from?.userid}`}function aue(n){let a=nN(n);return a.msgtype==="text"?typeof a.text?.content=="string"?a.text.content.trim():"":a.msgtype==="voice"?typeof a.voice?.content=="string"?a.voice.content.trim():"":a.msgtype==="mixed"&&Array.isArray(a.mixed?.msg_item)?a.mixed.msg_item.filter(o=>o?.msgtype==="text"&&typeof o.text?.content=="string").map(o=>o.text.content).join(` -`).trim():""}function qu(n,a=tue){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 rue(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function sN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Vu=class{#A;#e;#t;#a;#s;#o;#I;#g=new Map;constructor({client:a,harness:o,state:i,status:e=sN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=eue}){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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t}get status(){return structuredClone(this.#a)}accept(a){let o=y1(a),e=(this.#g.get(o)??Promise.resolve()).catch(()=>{}).then(()=>this.#r(a)).finally(()=>{this.#g.get(o)===e&&this.#g.delete(o)});return this.#g.set(o,e),e}async waitForIdle(){await Promise.allSettled([...this.#g.values()])}async#n(a,o){for(let i of qu(o))await this.#A.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#i(a,o,i){let e=qu(i);if(e.length!==0)try{await this.#A.replyStream(a,this.#I("stream"),e[0],!0);for(let r of e.slice(1))await this.#A.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#n(o,i)}}async#r(a){let o=nN(a),i=typeof o.msgid=="string"?o.msgid:"",e=typeof o.from?.userid=="string"?o.from.userid:"",r=o.chattype==="group"?o.chatid:e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let A=aue(a),t=null,s=!1;try{if(!A){await this.#i(a,r,"\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.#t.markSeen(i);return}let g=A.toLowerCase();if(g==="/help"){await this.#i(a,r,Aue),await this.#t.markSeen(i);return}if(g==="/status"){await this.#e.ensureRunning(),await this.#i(a,r,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(i);return}let c=y1(a);if(g==="/new"){await this.#t.clearSession(c),await this.#i(a,r,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(i);return}let l=await Gr(A,this.#e,c);if(l){for(let f of l.messages??[l.message])await this.#i(a,r,f);await this.#t.markSeen(i);return}t=this.#I("stream");try{await this.#A.replyStream(a,t,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),s=!0}catch(f){this.#s.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",f)}let{answer:C}=await ir({harness:this.#e,state:this.#t,key:c,text:A,askOptions:{timeoutMs:this.#o,onUpdate:s&&typeof this.#A.replyStreamNonBlocking=="function"?async f=>{let y=qu(rue(f))[0];y&&await this.#A.replyStreamNonBlocking(a,t,y,!1)}:void 0}}),u=qu(C||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),Q=!1;if(s&&u.length>0)try{await this.#A.replyStream(a,t,u[0],!0);for(let f of u.slice(1))await this.#A.sendMessage(r,{msgtype:"markdown",markdown:{content:f}});Q=!0}catch(f){this.#s.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",f)}Q||await this.#n(r,C),await this.#t.markSeen(i),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null}catch(g){this.#a.lastError=g?.message??String(g),this.#s.error?.("[dsh-im:wecom] failed to process an inbound message");try{s&&t?await this.#A.replyStream(a,t,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",!0):await this.#i(a,r,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#t.markSeen(i)}catch{this.#s.error?.("[dsh-im:wecom] failed to send the safe error reply")}}}};function sue(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function gue(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...sN()}}var YC=class{#A;#e;#t;#a;#s;#o;#I;#g;#n;#i=gue();#r=null;#c=null;#l=null;#E=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 oue(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#A=a,this.#e=o,this.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t,this.#g=s,this.#n=g}get status(){return structuredClone(this.#i)}async start(){if(this.#i.ready&&this.#r)return this.status;if(this.#l)return this.#l;let a=new AbortController;return this.#E=a,this.#l=this.#C(a.signal).finally(()=>{this.#E===a&&(this.#E=null),this.#l=null}),this.#l}async#C(a){await this.#h(),a.throwIfAborted(),this.#i.startedAt=new Date().toISOString(),this.#i.wecomConnectionState="connecting",this.#i.lastError=null,await this.#t.ensureRunning(),this.#i.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#n({botId:this.#A.remoteBotId,secret:this.#e,logger:o,maxReconnectAttempts:this.#g});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#r=i,this.#c=new Vu({client:i,harness:this.#t,state:this.#a,status:this.#i,logger:this.#s,replyTimeoutMs:this.#o});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#r!==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.#r===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},c=()=>{this.#r===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},l=Q=>{if(this.#r!==i)return;let f=Q instanceof iue||Q instanceof nue;!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.#c?.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(sue()),this.#I)})]),this.status}catch(Q){throw a.aborted?(await this.#h(),Q):(this.#i.ready=!1,this.#i.wecomConnectionState="failed",this.#i.lastError=Q?.message??String(Q),await this.#h(),Q)}finally{clearTimeout(u)}}async stop(){let a=this.#l;return this.#E?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),await this.#h(),await a?.catch(()=>{}),this.status}async#h(){let a=this.#r,o=this.#c;this.#r=null,this.#c=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 m1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function cue(n){if(!Array.isArray(n)||n.length===0)return[...m1];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...m1]}var zu=class{#A;#e;#t;#a;#s;#o;#I;#g=null;#n=null;#i=0;#r=!1;#c=!1;#l;#E;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.#t=i,this.#a=cue(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#I=t,this.#l=new Promise(s=>{this.#E=s})}get ready(){return this.#l}start(){return this.#c||this.#r?this:(this.#c=!0,this.#C(0),this)}async close(){this.#r||(this.#r=!0,this.#g!==null&&this.#I(this.#g),this.#g=null,await this.#n?.catch(()=>{}),this.#E?.(null),this.#E=null)}#C(a){this.#r||(this.#g=this.#o(()=>{this.#g=null,this.#h()},a),this.#g?.unref?.())}async#h(){if(this.#r||this.#n)return;let a=this.#p();this.#n=a;try{await a}finally{this.#n===a&&(this.#n=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#r)return;let a=await this.#A.initialize();if(this.#r)return;this.#E?.(a),this.#E=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 Cue(n){let a=Mg(n.dshHome??process.env.DSH_HOME??xC(lue(),".dsh")),o=Mg(n.dataDir??xC(a,"integrations","dsh-wecom"));return{config:Mg(n.configPath??xC(o,"config.json")),bots:Mg(n.botsDir??xC(o,"bots")),workspaces:Mg(n.workspacesPath??xC(o,"workspaces.json"))}}async function cN(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??Hu,e=o.StateStore??Ju,r=o.HarnessClient??Yu,A=o.Controller??KC,t=o.Runtime??YC,s=o.QrAuth??xu,g=o.createConnectionSupervisor??gN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Cue(a),C=await new i(l.config).load(),u=Mg(a.workspace??process.cwd()),Q=o.WorkspaceStore??ca,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:u}).load(),y=C.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof C.remove=="function"?Fa(C,{workspaces:f}):C,T=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),R=new Map,G=F=>Mg(l.bots,F,"state.json"),j=async F=>{let k=R.get(F);return k||(k=await new e(G(F)).load(),R.set(F,k)),k},x=new r({baseUrl:Eue(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:F,config:k,secret:$})=>{let U=await j(F);await f.ensure(F);let b=La(x,{botId:F,workspaces:f,state:U});return new t({config:k,secret:$,harness:b.harness,state:b.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...L)=>c.error?.(`[${F}]`,...L),warn:(...L)=>c.warn?.(`[${F}]`,...L),info:(...L)=>c.info?.(`[${F}]`,...L),debug:(...L)=>c.debug?.(`[${F}]`,...L)}})},deleteState:async({botId:F})=>{let k=R.get(F);if(R.delete(F),k&&typeof k.remove=="function")await k.remove();else try{await Iue(G(F))}catch($){if($?.code!=="ENOENT")throw $}}}),J=Ua(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 pue from"qrcode";var D1="/wecom",Da=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}),w1=Object.freeze(Object.values(Da)),hue=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function EN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function uI(n,a){return EN(n)&&Object.keys(n).every(o=>a.includes(o))}function IN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function S1(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function due(n,a){return EN(a)?n===Da.status?uI(a,[])?null:"connection.status does not accept fields.":n===Da.beginProvisioning?uI(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Da.pollProvisioning,Da.cancelProvisioning].includes(n)?uI(a,["attemptId"])&&IN(a.attemptId)?null:`${n} requires an attemptId.`:n===Da.bindCredentials?uI(a,["botId","secret"])&&S1(a.botId,512)&&S1(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Da.reconnectBot?uI(a,["botId"])&&IN(a.botId)?null:"bot.reconnect requires a botId.":n===Da.deleteBot?uI(a,["botId","confirm"])&&IN(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Da.setWorkspace?Ka(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function QI(n){if(Array.isArray(n))return n.map(QI);if(!EN(n))return n;let a={};for(let[o,i]of Object.entries(n))hue.has(o)||(a[o]=QI(i));return a}async function Bue(n){return pue.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function lN(n,a){return!n||typeof n.verificationUrl!="string"?QI(n):QI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function jC(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await lN(o.provisioning,a)),QI(o)}function O1(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(!w1.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=due(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Da.status)s=await jC(await n.status(),i);else if(e===Da.beginProvisioning)s=await lN(await n.startProvisioning(),i);else if(e===Da.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 lN(g,i)}else if(e===Da.cancelProvisioning)s=QI(await n.cancelProvisioning(r.attemptId));else if(e===Da.bindCredentials)s=await jC(await n.bindCredentials(r),i);else if(e===Da.reconnectBot)s=await jC(await n.reconnectBot(r.botId),i);else if(e===Da.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await jC(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await jC(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=Ya(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 Wu(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(D1,O1(a,o),{authority:Ha(i)})}async function M1(n,a={}){if(a?.controller)return Wu(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await cN(n,a,a.internals),i=Wu(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as $ue}from"node:fs/promises";import{homedir as eQe}from"node:os";import{join as zC,resolve as bg}from"node:path";import{createHash as _ue}from"node:crypto";import{mkdir as Nue,readFile as Tue,rename as Rue,unlink as kue,writeFile as vue}from"node:fs/promises";import{dirname as Pue}from"node:path";import{randomBytes as uue,randomUUID as Que}from"node:crypto";var Xu="https://ilinkai.weixin.qq.com/",fue="2.4.6",yue="3",mue="bot",Sue=2<<16|1024|6,Due=15e3,b1=35e3,wue=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),ct=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function wi(n){return typeof n=="string"&&n.trim()?n.trim():null}function CN(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function yI(n){let a;try{a=new URL(n)}catch{throw new ct("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!CN(a.hostname)||a.port!==""&&a.port!=="443")throw new ct("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 Oue(n){let a=wi(n);if(!a)throw new ct("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 ct("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!CN(o.hostname))throw new ct("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function N1(){return{"iLink-App-Id":mue,"iLink-App-ClientVersion":String(Sue)}}function Mue(n){let a={...N1(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(uue(4).readUInt32BE(0)),"utf8").toString("base64")};return wi(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function Zu(){return{channel_version:fue,bot_agent:"DeepSeekHarness/0.6.0"}}function _1(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function fI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=Due,signal:t,authenticated:s=!0}){let g=yI(o),c=new URL(i,g);if(!CN(c.hostname))throw new ct("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 _1(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?Mue(r):N1(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new ct("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 ct("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?_1(t):C?new ct("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof ct?f:new ct("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",u)}}function bue(n){if(!n||typeof n!="object"||!wue.has(n.status))throw new ct("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function T1({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({async beginLogin({localTokens:a=[],botType:o=yue,signal:i}={}){let e=[...new Set(a.map(wi).filter(Boolean))].slice(-10),r=await fI(n,{method:"POST",baseUrl:Xu,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=wi(r?.qrcode);if(!A)throw new ct("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Oue(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=Xu,verifyCode:i,signal:e}){let r=wi(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;wi(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await fI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:b1,signal:e,authenticated:!1});return bue(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:Zu()},token:o,timeoutMs:e??b1,signal:r})}catch(A){if(A instanceof ct&&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=wi(i),g=wi(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await fI(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-${Que()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...wi(r)?{context_token:r.trim()}:{},...wi(A)?{run_id:A.trim()}:{}},base_info:Zu()}});if(c?.ret!==void 0&&c.ret!==0)throw new ct("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 fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:Zu()}});if(e?.ret!==void 0&&e.ret!==0)throw new ct("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:Zu()}})}})}function R1(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 k1(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):wi(n?.client_id)}function v1(n,a=4e3){if(n.length<=a)return[n];let o=[],i=n;for(;i.length>a;){let e=i.lastIndexOf(` +`).trim():""}function qu(n,a=tue){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 rue(n){return n?.type==="text"?n.text:n?.type==="tool"?`\u6B63\u5728\u4F7F\u7528${n.name}\u2026`:n?.text}function sN(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var Vu=class{#A;#e;#t;#a;#s;#o;#I;#g=new Map;constructor({client:a,harness:o,state:i,status:e=sN(),logger:r=console,replyTimeoutMs:A=6e5,generateStreamId:t=eue}){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.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t}get status(){return structuredClone(this.#a)}accept(a){let o=y1(a),e=(this.#g.get(o)??Promise.resolve()).catch(()=>{}).then(()=>this.#r(a)).finally(()=>{this.#g.get(o)===e&&this.#g.delete(o)});return this.#g.set(o,e),e}async waitForIdle(){await Promise.allSettled([...this.#g.values()])}async#n(a,o){for(let i of qu(o))await this.#A.sendMessage(a,{msgtype:"markdown",markdown:{content:i}})}async#i(a,o,i){let e=qu(i);if(e.length!==0)try{await this.#A.replyStream(a,this.#I("stream"),e[0],!0);for(let r of e.slice(1))await this.#A.sendMessage(o,{msgtype:"markdown",markdown:{content:r}})}catch{await this.#n(o,i)}}async#r(a){let o=nN(a),i=typeof o.msgid=="string"?o.msgid:"",e=typeof o.from?.userid=="string"?o.from.userid:"",r=o.chattype==="group"?o.chatid:e;if(!i||!e||!r||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i))return;this.#a.messagesReceived+=1,this.#a.lastMessageAt=new Date().toISOString();let A=aue(a),t=null,s=!1;try{if(!A){await this.#i(a,r,"\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.#t.markSeen(i);return}let g=A.toLowerCase();if(g==="/help"){await this.#i(a,r,Aue),await this.#t.markSeen(i);return}if(g==="/status"){await this.#e.ensureRunning(),await this.#i(a,r,"\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),await this.#t.markSeen(i);return}let c=y1(a);if(g==="/new"){await this.#t.clearSession(c),await this.#i(a,r,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),await this.#t.markSeen(i);return}let l=await Gr(A,this.#e,c);if(l){for(let f of l.messages??[l.message])await this.#i(a,r,f);await this.#t.markSeen(i);return}t=this.#I("stream");try{await this.#A.replyStream(a,t,"\u6B63\u5728\u601D\u8003\u4E2D\u2026",!1),s=!0}catch(f){this.#s.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",f)}let{answer:C}=await ir({harness:this.#e,state:this.#t,key:c,text:A,askOptions:{timeoutMs:this.#o,onUpdate:s&&typeof this.#A.replyStreamNonBlocking=="function"?async f=>{let y=qu(rue(f))[0];y&&await this.#A.replyStreamNonBlocking(a,t,y,!1)}:void 0}}),u=qu(C||"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002"),Q=!1;if(s&&u.length>0)try{await this.#A.replyStream(a,t,u[0],!0);for(let f of u.slice(1))await this.#A.sendMessage(r,{msgtype:"markdown",markdown:{content:f}});Q=!0}catch(f){this.#s.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",f)}Q||await this.#n(r,C),await this.#t.markSeen(i),this.#a.messagesReplied+=1,this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null}catch(g){this.#a.lastError=g?.message??String(g),this.#s.error?.("[dsh-im:wecom] failed to process an inbound message");try{s&&t?await this.#A.replyStream(a,t,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",!0):await this.#i(a,r,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"),await this.#t.markSeen(i)}catch{this.#s.error?.("[dsh-im:wecom] failed to send the safe error reply")}}}};function sue(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function gue(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...sN()}}var YC=class{#A;#e;#t;#a;#s;#o;#I;#g;#n;#i=gue();#r=null;#c=null;#l=null;#E=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 oue(c)}){if(!a||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#A=a,this.#e=o,this.#t=i,this.#a=e,this.#s=r,this.#o=A,this.#I=t,this.#g=s,this.#n=g}get status(){return structuredClone(this.#i)}async start(){if(this.#i.ready&&this.#r)return this.status;if(this.#l)return this.#l;let a=new AbortController;return this.#E=a,this.#l=this.#C(a.signal).finally(()=>{this.#E===a&&(this.#E=null),this.#l=null}),this.#l}async#C(a){await this.#h(),a.throwIfAborted(),this.#i.startedAt=new Date().toISOString(),this.#i.wecomConnectionState="connecting",this.#i.lastError=null,await this.#t.ensureRunning(),this.#i.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#n({botId:this.#A.remoteBotId,secret:this.#e,logger:o,maxReconnectAttempts:this.#g});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#r=i,this.#c=new Vu({client:i,harness:this.#t,state:this.#a,status:this.#i,logger:this.#s,replyTimeoutMs:this.#o});let e,r,A=!1,t=new Promise((Q,f)=>{e=Q,r=f}),s=()=>{if(this.#r!==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.#r===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},c=()=>{this.#r===i&&(this.#i.ready=!1,this.#i.wecomConnectionState="connecting",this.#i.lastCheckedAt=Date.now())},l=Q=>{if(this.#r!==i)return;let f=Q instanceof iue||Q instanceof nue;!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.#c?.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(sue()),this.#I)})]),this.status}catch(Q){throw a.aborted?(await this.#h(),Q):(this.#i.ready=!1,this.#i.wecomConnectionState="failed",this.#i.lastError=Q?.message??String(Q),await this.#h(),Q)}finally{clearTimeout(u)}}async stop(){let a=this.#l;return this.#E?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),await this.#h(),await a?.catch(()=>{}),this.status}async#h(){let a=this.#r,o=this.#c;this.#r=null,this.#c=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 m1=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function cue(n){if(!Array.isArray(n)||n.length===0)return[...m1];let a=n.filter(o=>Number.isFinite(o)&&o>=0);return a.length>0?a:[...m1]}var zu=class{#A;#e;#t;#a;#s;#o;#I;#g=null;#n=null;#i=0;#r=!1;#c=!1;#l;#E;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.#t=i,this.#a=cue(e),this.#s=Number.isFinite(r)&&r>=0?r:15e3,this.#o=A,this.#I=t,this.#l=new Promise(s=>{this.#E=s})}get ready(){return this.#l}start(){return this.#c||this.#r?this:(this.#c=!0,this.#C(0),this)}async close(){this.#r||(this.#r=!0,this.#g!==null&&this.#I(this.#g),this.#g=null,await this.#n?.catch(()=>{}),this.#E?.(null),this.#E=null)}#C(a){this.#r||(this.#g=this.#o(()=>{this.#g=null,this.#h()},a),this.#g?.unref?.())}async#h(){if(this.#r||this.#n)return;let a=this.#p();this.#n=a;try{await a}finally{this.#n===a&&(this.#n=null)}}async#p(){try{if(await this.#e.ensureRunning(),this.#r)return;let a=await this.#A.initialize();if(this.#r)return;this.#E?.(a),this.#E=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 Cue(n){let a=Mg(n.dshHome??process.env.DSH_HOME??xC(lue(),".dsh")),o=Mg(n.dataDir??xC(a,"integrations","dsh-wecom"));return{config:Mg(n.configPath??xC(o,"config.json")),bots:Mg(n.botsDir??xC(o,"bots")),workspaces:Mg(n.workspacesPath??xC(o,"workspaces.json"))}}async function cN(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??Hu,e=o.StateStore??Ju,r=o.HarnessClient??Yu,A=o.Controller??KC,t=o.Runtime??YC,s=o.QrAuth??xu,g=o.createConnectionSupervisor??gN,c=typeof n.logger=="function"?n.logger("dsh-im:wecom"):n.logger??console,l=Cue(a),C=await new i(l.config).load(),u=Mg(a.workspace??process.cwd()),Q=o.WorkspaceStore??ca,f=o.workspaces??await new Q(l.workspaces,{defaultWorkspace:u}).load(),y=C.list();await f.reconcile(y.map(F=>F.botId)),await Promise.all(y.map(F=>f.ensure(F.botId)));let m=typeof C.remove=="function"?Fa(C,{workspaces:f}):C,T=o.qrAuth??new s({source:a.qrSource??"deepseek-harness",platform:a.qrPlatform}),R=new Map,G=F=>Mg(l.bots,F,"state.json"),j=async F=>{let k=R.get(F);return k||(k=await new e(G(F)).load(),R.set(F,k)),k},x=new r({baseUrl:Eue(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:F,config:k,secret:$})=>{let U=await j(F);await f.ensure(F);let b=La(x,{botId:F,workspaces:f,state:U});return new t({config:k,secret:$,harness:b.harness,state:b.state,replyTimeoutMs:a.replyTimeoutMs??6e5,connectTimeoutMs:a.connectTimeoutMs??2e4,maxReconnectAttempts:a.maxReconnectAttempts??10,logger:{error:(...L)=>c.error?.(`[${F}]`,...L),warn:(...L)=>c.warn?.(`[${F}]`,...L),info:(...L)=>c.info?.(`[${F}]`,...L),debug:(...L)=>c.debug?.(`[${F}]`,...L)}})},deleteState:async({botId:F})=>{let k=R.get(F);if(R.delete(F),k&&typeof k.remove=="function")await k.remove();else try{await Iue(G(F))}catch($){if($?.code!=="ENOENT")throw $}}}),J=Ua(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 pue from"qrcode";var D1="/wecom",Da=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}),w1=Object.freeze(Object.values(Da)),hue=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function EN(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function uI(n,a){return EN(n)&&Object.keys(n).every(o=>a.includes(o))}function IN(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function S1(n,a){return typeof n=="string"&&n.trim().length>0&&n.length<=a}function due(n,a){return EN(a)?n===Da.status?uI(a,[])?null:"connection.status does not accept fields.":n===Da.beginProvisioning?uI(a,["locale"])&&(a.locale===void 0||a.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Da.pollProvisioning,Da.cancelProvisioning].includes(n)?uI(a,["attemptId"])&&IN(a.attemptId)?null:`${n} requires an attemptId.`:n===Da.bindCredentials?uI(a,["botId","secret"])&&S1(a.botId,512)&&S1(a.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===Da.reconnectBot?uI(a,["botId"])&&IN(a.botId)?null:"bot.reconnect requires a botId.":n===Da.deleteBot?uI(a,["botId","confirm"])&&IN(a.botId)&&a.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Da.setWorkspace?Ka(a)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function QI(n){if(Array.isArray(n))return n.map(QI);if(!EN(n))return n;let a={};for(let[o,i]of Object.entries(n))hue.has(o)||(a[o]=QI(i));return a}async function Bue(n){return pue.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function lN(n,a){return!n||typeof n.verificationUrl!="string"?QI(n):QI({...n,qrCodeDataUrl:await a(n.verificationUrl)})}async function jC(n,a){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await lN(o.provisioning,a)),QI(o)}function O1(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(!w1.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let t=due(e,r);if(t)return{ok:!1,error:{code:"bad-request",message:t}};try{let s;if(e===Da.status)s=await jC(await n.status(),i);else if(e===Da.beginProvisioning)s=await lN(await n.startProvisioning(),i);else if(e===Da.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 lN(g,i)}else if(e===Da.cancelProvisioning)s=QI(await n.cancelProvisioning(r.attemptId));else if(e===Da.bindCredentials)s=await jC(await n.bindCredentials(r),i);else if(e===Da.reconnectBot)s=await jC(await n.reconnectBot(r.botId),i);else if(e===Da.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await jC(await n.updateWorkspace(r.botId,r.workspace),i)}else s=await jC(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=Ya(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 Wu(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(D1,O1(a,o),{authority:Ha(i)})}async function M1(n,a={}){if(a?.controller)return Wu(n,a.controller,a.rpcOptions,a.rpcAuthority);let o=await cN(n,a,a.internals),i=Wu(n,o.controller,a.rpcOptions,a.rpcAuthority);return n.effect(()=>async()=>o.close(),"dsh-im: close Enterprise WeChat bot connections"),i}import{unlink as $ue}from"node:fs/promises";import{homedir as eQe}from"node:os";import{join as zC,resolve as bg}from"node:path";import{createHash as _ue}from"node:crypto";import{mkdir as Nue,readFile as Tue,rename as Rue,unlink as kue,writeFile as vue}from"node:fs/promises";import{dirname as Pue}from"node:path";import{randomBytes as uue,randomUUID as Que}from"node:crypto";var Xu="https://ilinkai.weixin.qq.com/",fue="2.4.6",yue="3",mue="bot",Sue=2<<16|1024|6,Due=15e3,b1=35e3,wue=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),ct=class extends Error{constructor(a,o,i={}){super(o,i),this.name="WeixinApiError",this.code=a,this.status=i.status}};function wi(n){return typeof n=="string"&&n.trim()?n.trim():null}function CN(n){let a=n.toLowerCase().replace(/\.$/,"");return a==="weixin.qq.com"||a.endsWith(".weixin.qq.com")}function yI(n){let a;try{a=new URL(n)}catch{throw new ct("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(a.protocol!=="https:"||!CN(a.hostname)||a.port!==""&&a.port!=="443")throw new ct("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 Oue(n){let a=wi(n);if(!a)throw new ct("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 ct("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!CN(o.hostname))throw new ct("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function N1(){return{"iLink-App-Id":mue,"iLink-App-ClientVersion":String(Sue)}}function Mue(n){let a={...N1(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(uue(4).readUInt32BE(0)),"utf8").toString("base64")};return wi(n)&&(a.Authorization=`Bearer ${n.trim()}`),a}function Zu(){return{channel_version:fue,bot_agent:"DeepSeekHarness/0.7.0"}}function _1(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function fI(n,{method:a,baseUrl:o,endpoint:i,body:e,token:r,timeoutMs:A=Due,signal:t,authenticated:s=!0}){let g=yI(o),c=new URL(i,g);if(!CN(c.hostname))throw new ct("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 _1(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?Mue(r):N1(),...e===void 0?{}:{body:JSON.stringify(e)},signal:l.signal});if(!f.ok)throw new ct("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 ct("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(f){throw t?.aborted?_1(t):C?new ct("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:f}):f instanceof ct?f:new ct("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:f})}finally{Q&&clearTimeout(Q),t?.removeEventListener("abort",u)}}function bue(n){if(!n||typeof n!="object"||!wue.has(n.status))throw new ct("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function T1({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");return Object.freeze({async beginLogin({localTokens:a=[],botType:o=yue,signal:i}={}){let e=[...new Set(a.map(wi).filter(Boolean))].slice(-10),r=await fI(n,{method:"POST",baseUrl:Xu,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(o)}`,body:{local_token_list:e},timeoutMs:1e4,signal:i}),A=wi(r?.qrcode);if(!A)throw new ct("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:A,qrcodeUrl:Oue(r.qrcode_img_content)}},async pollLogin({qrcode:a,baseUrl:o=Xu,verifyCode:i,signal:e}){let r=wi(a);if(!r)throw new TypeError("qrcode is required");let A=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(r)}`;wi(i)&&(A+=`&verify_code=${encodeURIComponent(i.trim())}`);let t=await fI(n,{method:"GET",baseUrl:o,endpoint:A,timeoutMs:b1,signal:e,authenticated:!1});return bue(t)},async getUpdates({baseUrl:a,token:o,getUpdatesBuf:i="",timeoutMs:e,signal:r}){try{return await fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:i,base_info:Zu()},token:o,timeoutMs:e??b1,signal:r})}catch(A){if(A instanceof ct&&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=wi(i),g=wi(e);if(!s||!g)throw new TypeError("toUserId and text are required");let c=await fI(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-${Que()}`,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:g}}],...wi(r)?{context_token:r.trim()}:{},...wi(A)?{run_id:A.trim()}:{}},base_info:Zu()}});if(c?.ret!==void 0&&c.ret!==0)throw new ct("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 fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystart",token:o,signal:i,timeoutMs:1e4,body:{base_info:Zu()}});if(e?.ret!==void 0&&e.ret!==0)throw new ct("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return e},async notifyStop({baseUrl:a,token:o,signal:i}){return fI(n,{method:"POST",baseUrl:a,endpoint:"ilink/bot/msg/notifystop",token:o,signal:i,timeoutMs:1e4,body:{base_info:Zu()}})}})}function R1(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 k1(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):wi(n?.client_id)}function v1(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 $u=class{#A;#e=pN;#t=Promise.resolve();constructor(a){this.#A=a}async load(){try{let a=Fue(JSON.parse(await Tue(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=pN}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=F1(a);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#a(i=>{let e=i.find(t=>t.accountId===o.accountId&&t.botId!==o.botId),r=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||r)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(a){if(!P1(a))throw new TypeError("Invalid Weixin bot id");return this.#a(o=>{let i=o.findIndex(r=>r.botId===a);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let a=this.#t.then(async()=>{try{await kue(this.#A)}catch(o){if(o?.code!=="ENOENT")throw o}this.#e=pN});this.#t=a.then(()=>{},()=>{}),await a}async#a(a){let o,i=this.#t.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.#t=i.then(()=>{},()=>{}),await i,o}async#s(a){await Nue(Pue(this.#A),{recursive:!0,mode:448});let o=`${this.#A}.tmp`;await vue(o,`${JSON.stringify(a,null,2)} `,{encoding:"utf8",mode:384}),await Rue(o,this.#A)}};import{mkdir as Lue,readFile as Uue,rename as Hue,unlink as Kue,writeFile as Yue}from"node:fs/promises";import{dirname as xue}from"node:path";var eQ=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:""});function jue(n){if(!n||typeof n!="object")return structuredClone(eQ);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 AQ=class{#A;#e=structuredClone(eQ);#t=Promise.resolve();constructor(a){this.#A=a}async load(){try{this.#e=jue(JSON.parse(await Uue(this.#A,"utf8")))}catch(a){if(a?.code!=="ENOENT")throw a;this.#e=structuredClone(eQ),await this.#a()}return this}sessionFor(a){return this.#e.sessions[a]??null}async setSession(a,o){this.#e.sessions[a]=o,await this.#a()}async clearSession(a){delete this.#e.sessions[a],await this.#a()}async clearSessions(){this.#e.sessions={},await this.#a()}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.#a())}getUpdatesBuf(){return this.#e.getUpdatesBuf}async setGetUpdatesBuf(a){typeof a!="string"||a===this.#e.getUpdatesBuf||(this.#e.getUpdatesBuf=a,await this.#a())}snapshot(){return structuredClone(this.#e)}async remove(){try{await Kue(this.#A)}catch(a){if(a?.code!=="ENOENT")throw a}this.#e=structuredClone(eQ)}async#a(){let a=`${JSON.stringify(this.#e,null,2)} `,o=this.#t.then(async()=>{await Lue(xue(this.#A),{recursive:!0,mode:448});let i=`${this.#A}.tmp`;await Yue(i,a,{encoding:"utf8",mode:384}),await Hue(i,this.#A)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as Jue}from"node:crypto";var L1=new Set(["starting","pending","scanned","needs_verification","connecting"]),tQ=new Set(["connected","expired","failed","cancelled"]),U1=5*6e4;function mI(n){return typeof n=="string"&&n.trim()?n.trim():null}function que(){return new DOMException("Provisioning was cancelled","AbortError")}function H1(n,a){let o=mI(n);return o?yI(o.includes("://")?o:`https://${o}`):yI(a)}function JC(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 br(n,a){return Object.freeze({code:n,message:a})}var qC=class{#A;#e;#t;#a;#s;#o;#I=new Map;#g=new Map;#n=new Map;#i=null;#r=new Map;#c=0;#l=!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.#t=i,this.#a=e,this.#s=r,this.#o=A}async initialize(){if(this.#l)return this.status();for(let a of this.#t.list())this.#I.get(a.botId)?.status?.ready!==!0&&await this.#Q(a.botId,async()=>{let i=this.#t.get(a.botId);if(!(!i||this.#l))try{let e=await this.#d(i.tokenRef);if(!e){this.#g.set(i.botId,br("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.#g.delete(i.botId)}catch(e){this.#g.set(i.botId,br("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.#l)throw new Error("dsh-weixin controller is closed");this.#i&&await this.cancelProvisioning(this.#i);let a={id:Jue(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+U1,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:Xu,error:null,botId:null,task:null};this.#n.set(a.id,a),this.#i=a.id,this.#f();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#d(e.tokenRef)))).filter(Boolean),i=await this.#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()+U1,this.#f(),a.task=this.#E(a),JC(a)}catch(o){throw a.controller.signal.aborted?(a.state="cancelled",a.error=br("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=br(o instanceof ct?o.code:"qr-start-failed",o instanceof ct?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 JC(this.#n.get(a))}async submitVerification(a,o){let i=this.#n.get(a);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=mI(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(),JC(i)}async cancelProvisioning(a){let o=this.#n.get(a);return o?(tQ.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),tQ.has(o.state)||(o.state="cancelled"),o.error??=br("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#i===o.id&&(this.#i=null),this.#f(),JC(o)):null}async reconnectBot(a){let o=this.#t.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.#g.delete(a)}catch(e){throw this.#g.set(a,br("connection-failed","\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),e}finally{this.#f()}}),this.status()}async deleteBot(a){let o=this.#t.get(a);if(!o)throw new Error("Unknown Weixin account");return await this.#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.#t.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.#g.delete(a),this.#f()}),this.status()}status(){let a=this.#t.list().map(e=>{let r=this.#I.get(e.botId)?.status??null,A=r?.ready===!0&&r.weixinConnectionState==="connected"&&r.harnessReachable===!0,t=A?"connected":r?.weixinConnectionState==="connecting"?"connecting":this.#g.has(e.botId)||r?.weixinConnectionState==="failed"?"error":"offline",s=this.#g.get(e.botId)??(t==="error"?br("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:G1(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.#n.get(this.#i):null;return{schemaVersion:1,revision:this.#c,state:i&&L1.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&&L1.has(i.state)?{provisioning:JC(i)}:{}}}async close(){this.#l||(this.#l=!0,this.#i&&await this.cancelProvisioning(this.#i),await Promise.allSettled([...this.#I.keys()].map(a=>this.#p(a))))}async#E(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=br("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=br("expired","\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002");break}else if(o.status==="scaned_but_redirect")a.currentBaseUrl=H1(o.redirect_host,a.currentBaseUrl),a.state="scanned";else if(o.status==="binded_redirect"){let i=this.#t.list().find(e=>this.#I.get(e.botId)?.status?.ready===!0)??this.#t.list()[0];i?(a.state="connected",a.botId=i.botId,a.alreadyConnected=!0):(a.state="failed",a.error=br("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=mI(o.bot_token),e=mI(o.ilink_bot_id),r=mI(o.ilink_user_id);if(!i||!e||!r)throw new ct("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=H1(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&&!tQ.has(a.state)&&(a.state="expired",a.error=br("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=br("cancelled","\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):(a.state="failed",a.error=br(o instanceof ct?o.code:"activation-failed",o instanceof ct?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=hN(i),t=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:r,createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g=await this.#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.#t.save(s),this.#B(a),await this.#h(s,o),this.#B(a),this.#g.delete(A.botId),this.#f(),A.botId}catch(c){throw await this.#p(A.botId),t?await this.#t.save(t).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.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.#a({botId:a.botId,config:a,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError("createRuntime returned an invalid Weixin runtime");try{await i.start(),this.#I.set(a.botId,i)}catch(e){throw await i.stop().catch(()=>{}),e}}async#p(a){let o=this.#I.get(a);this.#I.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 mI(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 que()}#Q(a,o){let r=(this.#r.get(a)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#r.get(a)===r&&this.#r.delete(a)});return this.#r.set(a,r),r}#y(){for(let[a,o]of this.#n)a!==this.#i&&tQ.has(o.state)&&this.#n.size>16&&this.#n.delete(a)}#f(){this.#c+=1}};var Vue=["\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 a4780ee..3666ee0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@xmanrui/dsh-im", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@xmanrui/dsh-im", - "version": "0.6.0", + "version": "0.7.0", "license": "MIT", "dependencies": { "@tencent-connect/qqbot-connector": "1.2.0", diff --git a/package.json b/package.json index de7250c..95cb4e7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@xmanrui/dsh-im", - "version": "0.6.0", + "version": "0.7.0", "description": "通过扫码、App Manifest或机器人凭据把IM机器人接入DeepSeek Harness(支持飞书、微信、钉钉、企业微信、QQ、Slack、Telegram、Discord和WhatsApp)。", "license": "MIT", "type": "module", diff --git a/src/channels/discord/discord-api.mjs b/src/channels/discord/discord-api.mjs index f0c1720..43bdb3a 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.6.0)', + 'user-agent': 'DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.7.0)', }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: requestSignal(signal, timeoutMs), diff --git a/src/channels/weixin/weixin-api.mjs b/src/channels/weixin/weixin-api.mjs index 3c60365..9a96121 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.6.0', + bot_agent: 'DeepSeekHarness/0.7.0', }; } diff --git a/test/channels/weixin/weixin-api.test.mjs b/test/channels/weixin/weixin-api.test.mjs index aba16d7..30d36b5 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.6.0'); + assert.equal(body.base_info.bot_agent, 'DeepSeekHarness/0.7.0'); assert.doesNotMatch(calls[0].init.body, /host-only-token/); });