From 2609ae20e8c9df4e0059d085631b31388e38223b Mon Sep 17 00:00:00 2001 From: xmanrui <841206367@qq.com> Date: Mon, 24 Aug 2026 02:34:35 +0800 Subject: [PATCH] fix(discord): request managed thread message content --- README.md | 2 +- lib/index.js | 2 +- src/channels/discord/discord-runtime.mjs | 2 +- test/channels/discord/discord.test.mjs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c9d81d5..77b4981 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Connect IM bots to DeepSeek Harness by scanning a QR code, using an App Manifest | QQ | 机器人需具备文件消息能力,并受 QQ 当日文件上传配额约束;额度耗尽时会明确提示稍后重试。 | | Slack | Bot Token 需有 `files:write`;实际大小上限由 Workspace 当前策略决定。已有 App 新增或变更 Scope 后,必须重新授权/安装 App 并重新连接机器人。 | | Telegram | 机器人必须能在当前聊天发送文档,实际可发送范围以 Bot API 返回为准。 | -| Discord | 机器人需有 **Send Messages**、**Create Public Threads**、**Send Messages in Threads** 和 **Read Message History** 权限;发送结果文件还需 **Attach Files**。实际附件额度由当前账号与服务器能力决定。 | +| Discord | Developer Portal 的 Bot 设置中需启用 **Message Content Intent**;机器人需有 **Send Messages**、**Create Public Threads**、**Send Messages in Threads** 和 **Read Message History** 权限;发送结果文件还需 **Attach Files**。实际附件额度由当前账号与服务器能力决定。 | | WhatsApp | 当前绑定会话需支持 Document Message,实际可发送范围以 WhatsApp/Baileys 返回为准。 | ## AI Office Connector diff --git a/lib/index.js b/lib/index.js index e04704e..ac59614 100644 --- a/lib/index.js +++ b/lib/index.js @@ -128,7 +128,7 @@ ${o}`:o}function Zi(n){return n instanceof Wi?n.userMessage:null}import{createHa `,{encoding:"utf8",mode:384}),await Jce(o,this.#e),this.#n.clear()}async#B(){if(Object.keys(this.#t).length>0||Object.keys(this.#r).length>0){await this.#u();return}try{await zce(this.#e),this.#n.clear()}catch(r){if(r?.code!=="ENOENT")throw r;this.#n.clear()}}};function mb(n){if(!n)return null;let r=typeof n=="function"?n():n;return r&&typeof r.then=="function"?r.then(pn):pn(r)}function SH(){let n=new Error("Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002");return n.code="agent-preset-unavailable",n}function hl(n){if(n())return;let r=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw r.code="workspace-bot-not-found",r}function yH(n,r,o){let i=e=>{let a=n.decorateStatus(e);if(!o||!a||typeof a!="object")return a;let A=s=>s?{...a,agentPresetCatalog:s}:a,t=mb(o);return t&&typeof t.then=="function"?t.then(A):A(t)};return r&&typeof r.then=="function"?r.then(i):i(r)}function $ce(n){return Promise.resolve(n.status())}function Ca(n,{workspaces:r,method:o="remove",botIdFromRemoved:i=e=>e?.botId}){if(!n||!r||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(e,a){let A=Reflect.get(e,a,e);return a===o?async(...t)=>{let s=await A.apply(e,t),g=s?i(s,t):null;return g&&await r.retireAfterConfigCommit(g),s}:typeof A=="function"?A.bind(e):A}})}function ua(n,{botId:r,workspaces:o,state:i,agentPresetCatalog:e}={}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let a=o.incarnationFor(r),A=()=>o.has(r)&&o.incarnationFor(r)===a,t=async(I=e)=>{let E;try{E=await mb(I)??pn(null)}catch(B){throw hl(A),B}return hl(A),{agentPreset:o.agentPresetFor(r),agentPresetCatalog:E}},s=new Map,g=new Proxy(n,{get(I,E){if(E==="agentPresetSettings")return async(f={})=>{f?.signal?.throwIfAborted(),hl(A);let Q=await t();return f?.signal?.throwIfAborted(),Q};if(E==="updateAgentPreset")return async(f,Q={})=>{Q?.signal?.throwIfAborted(),hl(A);let y=f==="--default"?null:ll(f),m=null;if(y&&({agentPresetCatalog:m}=await t(),Q?.signal?.throwIfAborted(),!m.items.some(_=>_.id===y)))throw SH();if(await o.setAgentPreset(r,y,{incarnation:a}),hl(A),m)return{agentPreset:o.agentPresetFor(r),agentPresetCatalog:m};try{return await t()}catch(_){if(_?.code==="workspace-bot-not-found")throw _;return hl(A),{agentPreset:o.agentPresetFor(r),agentPresetCatalog:pn(null)}}};if(E==="currentWorkspace")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}return o.workspaceFor(r)};if(E==="assertWorkspaceScope")return()=>{if(!A()){let f=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw f.code="workspace-bot-not-found",f}};if((E==="listWorkspaces"||E==="listWorkspaceSessions"||E==="listModels")&&typeof I[E]=="function")return async(...f)=>{if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=await I[E](...f);if(!A()){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}return Q};if(E==="switchWorkspace")return f=>{if(!A()){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");return Q.code="workspace-bot-not-found",Promise.reject(Q)}return o.setWorkspace(r,f,{clearSessions:()=>i.clearSessions(),incarnation:a})};if(E==="bindWorkspaceSession")return async(f,Q)=>{if(typeof f!="string"||!f||typeof Q!="string"||!Q)throw new TypeError("conversationKey and sessionId are required");if(!A()){let N=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw N.code="workspace-bot-not-found",N}if(typeof I.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let y=o.generationFor(r),m=await I.adoptWorkspaceSession(Q);if(!A()){let N=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw N.code="workspace-bot-not-found",N}if(y!==o.generationFor(r))throw Mc("The bot workspace changed while the session was being adopted.");if(!m||typeof m!="object"||m.sessionId!==Q||typeof m.workspace!="string")throw new TypeError("Harness returned an invalid adopted workspace session");let _=await o.bindWorkspaceSession(r,m.workspace,{conversationKey:f,sessionId:Q,clearSessions:()=>i.clearSessions(),setSession:(N,G)=>i.setSession(N,G),incarnation:a,expectedGeneration:y});if(!A()){let N=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw N.code="workspace-bot-not-found",N}if(_.generation!==o.generationFor(r))throw Mc("The bot workspace changed before the session binding completed.");return s.set(Q,_.generation),{...m,workspace:_.workspace,sessionId:_.sessionId}};if(E==="createSession")return async(f={})=>{if(await o.whenBotIdle(r),!A()){let _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}let Q=o.generationFor(r),y=o.agentPresetFor(r),m=await I.createSession({...f,workspace:o.workspaceFor(r),...y==null?{}:{agentPreset:y}});return s.set(m,Q),m};if(E==="workspaceSession")return f=>{if(typeof f!="string"||!f)throw new TypeError("sessionId is required");let Q=s.get(f)??o.generationFor(r);s.delete(f);let y=()=>A()&&Q===o.generationFor(r),m=async(N,G,Y)=>{if(!y())throw Mc(`The bot workspace changed before this ${Y} started.`);let x=await I[N](f,...G);if(!y())throw Mc(`The bot workspace changed while this ${Y} was running.`);return x},_=async(N,G,Y)=>{if(!y())throw Mc(`The bot workspace changed before this ${Y} started.`);return I[N](f,...G)};return Object.freeze({sessionId:f,async sessionExists(...N){if(!y())return!1;let G=await I.sessionExists(f,...N);return y()&&G},models(...N){return m("getSessionModels",N,"model listing")},selectModel(...N){return m("selectSessionModel",N,"model selection")},isRunning(...N){return m("isSessionRunning",N,"run-state check")},hasActiveTurn(...N){return m("hasActiveTurn",N,"turn ownership check")},stopActiveTurn(...N){return _("stopActiveTurn",N,"turn stop")},steerActiveTurn(...N){return _("steerActiveTurn",N,"turn steering")},ask(...N){if(!y())throw Mc("The bot workspace changed before this prompt started.");return I.ask(f,...N)}})};if(E==="sessionExists")return(f,...Q)=>{if(!A())return!1;let y=s.get(f);return y!==void 0&&y!==o.generationFor(r)?(s.delete(f),!1):I.sessionExists(f,...Q)};if(E==="ask")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(r)){let m=new Error("The bot workspace changed before this prompt started.");throw m.code=Va,m}return I.ask(f,...Q)};if(E==="executeCommand"&&typeof I.executeCommand=="function")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(r)){let m=new Error("The bot workspace changed before this command started.");throw m.code=Va,m}return I.executeCommand(f,...Q)};let B=Reflect.get(I,E,I);return typeof B=="function"?B.bind(I):B}}),c=new Proxy(i,{get(I,E){if(E===LO)return I;if(E==="sessionFor")return(f,...Q)=>{if(!A())return null;let y=I.sessionFor(f,...Q);return y&&!s.has(y)&&s.set(y,o.generationFor(r)),y};if(E==="setSession")return(f,Q,...y)=>{let m=s.get(Q);return!A()||m!==void 0&&m!==o.generationFor(r)?(s.delete(Q),!1):I.setSession(f,Q,...y)};let B=Reflect.get(I,E,I);return typeof B=="function"?B.bind(I):B}});return Object.freeze({harness:g,state:c})}function Ba(n,{workspaces:r,stateFor:o,agentPresetCatalog:i}={}){if(!n||!r||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let e=new Map,a=(c,I)=>{let B=(e.get(c)??Promise.resolve()).catch(()=>{}).then(I);return e.set(c,B),B.finally(()=>{e.get(c)===B&&e.delete(c)})},A=c=>yH(r,c,i),t=(c,I)=>{let E=r.incarnationFor(c);return a(c,async()=>{if(!(await n.status())?.bots?.some(Q=>Q?.botId===c)){let Q=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw Q.code="workspace-bot-not-found",Q}let f=await o(c);return await r.setWorkspace(c,I,{clearSessions:()=>f.clearSessions(),incarnation:E}),A(await n.status())})},s=(c,I)=>{let E=r.incarnationFor(c),B=ll(I);return a(c,async()=>{if(!(await n.status())?.bots?.some(y=>y?.botId===c)){let y=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw y.code="workspace-bot-not-found",y}let Q=B&&i?await mb(i):null;if(B&&i&&!Q?.items.some(y=>y.id===B))throw SH();return await r.setAgentPreset(c,B,{incarnation:E}),yH(r,await n.status(),Q??i)})},g=(c,I)=>a(c,async()=>{let E=await r.beginRemoval(c,{clearSessions:async()=>{try{let B=await o(c);if(!B||typeof B.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await B.clearSessions()}catch(B){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${c}:`,B?.message??B)}}});try{let B=await I();return await r.finishRemoval(E),A(B)}catch(B){let f=await $ce(n).catch(()=>null);throw Array.isArray(f?.bots)&&!f.bots.some(y=>y?.botId===c)?await r.finishRemoval(E):await r.abortRemoval(E),B}});return new Proxy(n,{get(c,I){if(I==="updateWorkspace")return t;if(I==="updateAgentPreset")return s;let E=Reflect.get(c,I,c);return typeof E!="function"?E:I==="deleteBot"?(B,...f)=>g(B,()=>E.call(c,B,...f)):I==="disconnect"?async(...B)=>{let Q=(await c.status())?.bots?.[0]?.botId;return Q?g(Q,()=>E.apply(c,B)):A(E.apply(c,B))}:(...B)=>A(E.apply(c,B))}})}var DH=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function eIe(n){if(!Array.isArray(n)||n.length===0)return[...DH];let r=n.filter(o=>Number.isFinite(o)&&o>=0);return r.length>0?r:[...DH]}var KB=class{#e;#A;#t;#r;#o;#i;#I;#s=null;#l=null;#a=0;#n=!1;#g=!1;#c;#p;constructor({controller:r,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:t=clearTimeout}){if(!r||typeof r.initialize!="function"||typeof r.status!="function")throw new TypeError("ConnectionSupervisor requires a controller");if(!o||typeof o.ensureRunning!="function")throw new TypeError("ConnectionSupervisor requires a Harness client");this.#e=r,this.#A=o,this.#t=i,this.#r=eIe(e),this.#o=Number.isFinite(a)&&a>=0?a:15e3,this.#i=A,this.#I=t,this.#c=new Promise(s=>{this.#p=s})}get ready(){return this.#c}start(){return this.#g||this.#n?this:(this.#g=!0,this.#h(0),this)}async close(){this.#n||(this.#n=!0,this.#s!==null&&this.#I(this.#s),this.#s=null,await this.#l?.catch(()=>{}),this.#p?.(null),this.#p=null)}#h(r){this.#n||(this.#s=this.#i(()=>{this.#s=null,this.#d()},r),this.#s?.unref?.())}async#d(){if(this.#n||this.#l)return;let r=this.#E();this.#l=r;try{await r}finally{this.#l===r&&(this.#l=null)}}async#E(){try{if(await this.#A.ensureRunning(),this.#n)return;let r=await this.#e.initialize();if(this.#n)return;this.#p?.(r),this.#p=null;let{configured:o,connected:i}=r.totals;if(io.invoke({namespace:"commands",method:"execute",args:{agentId:i,line:e},signal:a.signal})}}import{randomUUID as AIe}from"node:crypto";function tIe(n){if(typeof n?.get!="function")return;let r;try{r=n.get("agents")}catch{return}if(r!=null){if(typeof r.get!="function")throw new TypeError('dsh-im requires a callable AgentRegistry when ctx.get("agents") is present');return r}}function rIe(n,r,o){if(n?.status!=="running")return!1;let i=n?.session?.events;if(!Array.isArray(i))return!1;let e=null,a=!1;for(let A of i){if(A?.type==="turn/start"){e=A.data?.turn??null,a=!1;continue}if(A?.type==="turn/end"&&A.data?.turn===e){e=null,a=!1;continue}e===r&&A?.type==="user/message"&&A.data?.source?.rpcId===o&&(a=!0)}return e===r&&a}function wH(n){if(!n||typeof n!="object"||Object.isFrozen(n))return n;for(let r of Object.values(n))wH(r);return Object.freeze(n)}function aIe(n){return wH({id:AIe(),role:"user",content:[{type:"text",text:n}],source:{kind:"user"}})}function iIe(n){let r=new Error("Session is busy with an active turn or maintenance task",{cause:n});return r.code="agent-busy",r}function oIe(n){return({sessionId:r,expectedTurn:o,promptRpcId:i,action:e,text:a})=>{let A=n.get(r);if(A){if(!rIe(A,o,i))return!1;if(e==="stop")return A.cancel({kind:"user"},{keepInbox:!0}),!0;if(e==="steer")return typeof a!="string"||!a.trim()?!1:(A.inject(aIe(a)),!0);throw new TypeError(`Unsupported Harness control action: ${String(e)}`)}}}function nIe(n){return({sessionId:r,operation:o})=>{if(typeof o!="function")throw new TypeError("maintenance operation is required");let i=n.get(r);if(!i)return o();try{return i.runMaintenance(e=>{if(n.get(r)!==i){let a=new Error("Session agent changed before maintenance started");throw a.code="agent-unavailable",a}return o(e)})}catch(e){throw iIe(e)}}}function sIe(n){return({sessionId:r,workspace:o,files:i,signal:e})=>{let A=n.get(r)?.session?.header?.cwd,t=typeof A=="string"&&A?A:o;if(typeof t!="string"||!t)throw new Wi("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");return JU({files:i},{workspace:t,signal:e})}}function Qa(n,r={}){let{controlExecutor:o,sessionMaintenanceExecutor:i,fileIngressExecutor:e}=r;if(o!==void 0&&typeof o!="function")throw new TypeError("controlExecutor must be a function");if(i!==void 0&&typeof i!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("fileIngressExecutor must be a function");let a=o&&i&&e?void 0:tIe(n);return{controlExecutor:o??(a?oIe(a):void 0),sessionMaintenanceExecutor:i??(a?nIe(a):void 0),fileIngressExecutor:e??sIe(a??{get:()=>{}})}}function IIe(n,r){if(r!==void 0)return new URL(r);let o=n?.port;if(!Number.isInteger(o)||o<1||o>65535)throw new Error("dsh-dingtalk requires an initialized DSH webServer port");return new URL(`http://127.0.0.1:${o}`)}function lIe(n){let r=_c(n.dshHome??process.env.DSH_HOME??Dd(cIe(),".dsh")),o=_c(n.dataDir??Dd(r,"integrations","dsh-dingtalk"));return{root:o,config:_c(n.configPath??Dd(o,"config.json")),bots:_c(n.botsDir??Dd(o,"bots")),workspaces:_c(n.workspacesPath??Dd(o,"workspaces.json"))}}async function Db(n,r={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");if(!n?.webServer)throw new TypeError("dsh-dingtalk requires ctx.webServer");let i=o.ConfigStore??SB,e=o.DeviceAuth??wB,a=o.StateStore??HB,A=o.HarnessClient??LB,t=o.Controller??pd,s=o.Runtime??Qd,g=o.createConnectionSupervisor??Sb,c=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,I=()=>ha(n),E=lIe(r),B=await new i(E.config).load(),f=_c(r.workspace??process.cwd()),Q=o.WorkspaceStore??Kr,y=o.workspaces??await new Q(E.workspaces,{defaultWorkspace:f}).load(),m=typeof B.list=="function",_=m?B.list():[];m&&await y.reconcile(_.map(W=>W.botId)),await Promise.all(_.map(W=>y.ensure(W.botId,{defaultAgentPreset:r.agentPreset})));let N=typeof B.remove=="function"?Ca(B,{workspaces:y}):B,G=o.deviceAuth??new e({baseUrl:r.registrationBaseUrl}),Y=new Map,x=W=>_c(E.bots,W,"state.json"),K=async W=>{let se=Y.get(W);return se||(se=await new a(x(W)).load(),Y.set(W,se)),se},J=fa(n,o.commandExecutor),{controlExecutor:j,sessionMaintenanceExecutor:F,fileIngressExecutor:k}=Qa(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),z=new A({baseUrl:IIe(n.webServer,r.harnessBaseUrl),workspace:f,autostart:!1,dshBin:r.dshBin??"dsh",...J?{commandExecutor:J}:{},...j?{controlExecutor:j}:{},...F?{sessionMaintenanceExecutor:F}:{},...k?{fileIngressExecutor:k}:{}}),H=new t({deviceAuth:G,credentials:n.credentials,configStore:N,logger:c,createRuntime:async({botId:W,config:se,clientSecret:Qe})=>{let be=await K(W);await y.ensure(W,{defaultAgentPreset:r.agentPreset});let Be=ua(z,{botId:W,workspaces:y,state:be,agentPresetCatalog:I});return new s({config:se,clientSecret:Qe,harness:Be.harness,state:Be.state,replyTimeoutMs:r.replyTimeoutMs??6e5,maxMessageChars:r.maxMessageChars??4e3,connectTimeoutMs:r.connectTimeoutMs??15e3,logger:{error:(...De)=>c.error?.(`[${W}]`,...De),warn:(...De)=>c.warn?.(`[${W}]`,...De),info:(...De)=>c.info?.(`[${W}]`,...De),debug:(...De)=>c.debug?.(`[${W}]`,...De)}})},deleteState:async({botId:W})=>{let se=Y.get(W);if(Y.delete(W),se&&typeof se.remove=="function")await se.remove();else try{await gIe(x(W))}catch(Qe){if(Qe?.code!=="ENOENT")throw Qe}}}),M=Ba(H,{workspaces:y,stateFor:K,agentPresetCatalog:I}),v=g({controller:M,harness:z,logger:c,retryDelaysMs:r.retryDelaysMs,healthyIntervalMs:r.healthyIntervalMs}).start();return{controller:M,ready:v.ready,async close(){await v.close(),await M.close(),z.stopManagedProcess()}}}import hIe from"qrcode";var pIe=new Set(["loopback","trusted-host"]);function Cr(n){if(n===void 0)return"loopback";if(pIe.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as EIe}from"node:path";var $a="bot.workspace.set";function ya(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(r=>["botId","workspace"].includes(r))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&EIe(n.workspace.trim())}function ma(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found","agent-preset-invalid","agent-preset-unavailable"].includes(n?.code)?{code:n.code,message:n.message}:null}var ei="bot.preset.set";function dIe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Sa(n){return dIe(n)&&Object.keys(n).every(r=>["botId","agentPreset"].includes(r))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&(n.agentPreset===null||typeof n.agentPreset=="string"&&ab.test(n.agentPreset))}var bH="/dingtalk",Xt=Object.freeze({status:"connection.status",beginProvisioning:"provision.begin",pollProvisioning:"provision.poll",cancelProvisioning:"provision.cancel",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:$a,setAgentPreset:ei,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),MH=Object.freeze(Object.values(Xt)),CIe=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function Ob(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ig(n,r){return Ob(n)&&Object.keys(n).every(o=>r.includes(o))}function Nc(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function OH(n,r){return typeof n=="string"&&n.trim().length>0&&n.length<=r}function uIe(n,r){return Ob(r)?n===Xt.status?Ig(r,[])?null:"connection.status does not accept fields.":n===Xt.beginProvisioning?Ig(r,["locale"])&&(r.locale===void 0||r.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Xt.pollProvisioning,Xt.cancelProvisioning].includes(n)?Ig(r,["attemptId"])&&Nc(r.attemptId)?null:`${n} requires an attemptId.`:n===Xt.bindCredentials?Ig(r,["clientId","clientSecret"])&&OH(r.clientId,256)&&OH(r.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Xt.reconnectBot?Ig(r,["botId","sendTest"])&&Nc(r.botId)&&(r.sendTest===void 0||r.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Xt.deleteBot?Ig(r,["botId","confirm"])&&Nc(r.botId)&&r.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Xt.setWorkspace?ya(r)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Xt.setAgentPreset?Sa(r)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Xt.approveSender?Ig(r,["botId","requestId","confirm"])&&Nc(r.botId)&&Nc(r.requestId)&&r.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Xt.revokeSender?Ig(r,["botId","senderKey","confirm"])&&Nc(r.botId)&&Nc(r.senderKey)&&r.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function xB(n){return{ok:!1,error:{code:"bad-request",message:n}}}function wd(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function BIe(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Cl(n){if(Array.isArray(n))return n.map(Cl);if(!Ob(n))return n;let r={};for(let[o,i]of Object.entries(n))CIe.has(o)||(r[o]=Cl(i));return r}async function fIe(n){return hIe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function wb(n,r){return!n||typeof n.verificationUrl!="string"?Cl(n):Cl({...n,qrCodeDataUrl:await r(n.verificationUrl)})}async function lg(n,r){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await wb(o.provisioning,r)),Cl(o)}function QIe(n){for(let r of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[r]!="function")throw new TypeError(`A complete DingTalk controller is required (${r})`)}function _H(n,{encodeQr:r=fIe}={}){QIe(n);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>r(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return wd();if(!MH.includes(e))return xB("Unknown DingTalk endpoint.");let t=uIe(e,a);if(t)return xB(t);try{let s;if(e===Xt.status)s=await lg(await n.status(),i);else if(e===Xt.beginProvisioning){let g=await n.startProvisioning({signal:A});if(A?.aborted)return await n.cancelProvisioning(g.attemptId),wd();s=await wb(g,i)}else if(e===Xt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return xB("The provisioning attempt no longer exists.");s=await wb(g,i)}else if(e===Xt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return xB("The provisioning attempt no longer exists.");s=Cl(s)}else if(e===Xt.bindCredentials)s=await lg(await n.bindCredentials(a),i);else if(e===Xt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return wd();let c;if(a.sendTest===!0)if(!g?.bots?.some(E=>E?.botId===a.botId&&E?.connected===!0)||typeof n.sendConnectionTest!="function")c=Wt(ir("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=Wt()}catch(E){c=Wt(E)}s=await lg({...g,...c?{testMessage:c}:{}},i)}else if(e===Xt.deleteBot)s=await lg(await n.deleteBot(a.botId),i);else if(e===Xt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await lg(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Xt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await lg(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Xt.approveSender?s=await lg(await n.approveSender(a.botId,a.requestId),i):s=await lg(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?wd():{ok:!0,value:s}}catch(s){let g=ma(s);return A?.aborted?wd():g?{ok:!1,error:g}:BIe()}}}function YB(n,r,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(bH,_H(r,o),{authority:Cr(i)})}async function NH(n,r={}){if(r?.controller)return YB(n,r.controller,r.rpcOptions,r.rpcAuthority);let o=await Db(n,r,r.internals),i=YB(n,o.controller,r.rpcOptions,r.rpcAuthority);return n.effect(()=>async()=>{await o.close()},"dsh-dingtalk: close bot connections"),i}import{createHash as yIe}from"node:crypto";import{mkdir as mIe,readFile as SIe,rename as DIe,unlink as wIe,writeFile as OIe}from"node:fs/promises";import{dirname as bIe}from"node:path";var bb=Object.freeze({version:1,bots:Object.freeze([])});function Es(n){return typeof n=="string"&&n.trim()?n.trim():null}function TH(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Od(n,{botPrefix:r,tokenRefPrefix:o}){let i=Es(n);if(!i)throw new TypeError("platformId is required");let e=yIe("sha256").update(i).digest("hex").slice(0,24);return{botId:`${r}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function jB(n,r){let o=Es(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:r:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var ul=class{#e;#A;#t;#r;#o;#i;#I;#s=bb;#l=Promise.resolve();constructor(r,{channel:o,botPrefix:i,tokenRefPrefix:e,normalizeBotExtension:a=()=>({})}){if(typeof a!="function")throw new TypeError("normalizeBotExtension must be a function");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#o=a,this.#i=new RegExp(`^${TH(i)}_[a-f0-9]{24}$`),this.#I=new RegExp(`^${TH(e)}_[A-F0-9]{24}$`)}async load(){try{let r=this.#n(JSON.parse(await SIe(this.#e,"utf8")));if(!r)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#s=r}catch(r){if(r?.code!=="ENOENT")throw r;this.#s=bb}return this}list(){return structuredClone(this.#s.bots)}get(r){let o=this.#s.bots.find(i=>i.botId===r);return o?structuredClone(o):null}getByPlatformId(r){let o=this.#s.bots.find(i=>i.platformId===r);return o?structuredClone(o):null}async save(r){let o=this.#a(r);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#g(i=>{let e=i.find(t=>t.platformId===o.platformId&&t.botId!==o.botId),a=i.find(t=>t.tokenRef===o.tokenRef&&t.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(t=>t.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(r){if(!this.#i.test(r))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#g(o=>{let i=o.findIndex(a=>a.botId===r);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let r=this.#l.then(async()=>{try{await wIe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#s=bb});this.#l=r.then(()=>{},()=>{}),await r}#a(r){if(!r||typeof r!="object")return null;let o=Es(r.platformId),i=Es(r.botId),e=Es(r.tokenRef),a=Es(r.name);if(!o||!i||!e||!a||!this.#i.test(i)||!this.#I.test(e))return null;let A=Od(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});if(A.botId!==i||A.tokenRef!==e)return null;let t=this.#o(r);return!t||typeof t!="object"||Array.isArray(t)?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:Es(r.username),createdAt:Es(r.createdAt)??new Date().toISOString(),connectedAt:Es(r.connectedAt),...t})}#n(r){if(!r||r.version!==1||!Array.isArray(r.bots))return null;let o=r.bots.map(A=>this.#a(A));if(o.some(A=>A===null))return null;let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.botId)||e.has(A.platformId)||a.has(A.tokenRef))return null;i.add(A.botId),e.add(A.platformId),a.add(A.tokenRef)}return Object.freeze({version:1,bots:Object.freeze(o)})}async#g(r){let o,i=this.#l.then(async()=>{let e=[...this.#s.bots];o=r(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#c(a),this.#s=a});return this.#l=i.then(()=>{},()=>{}),await i,o}async#c(r){await mIe(bIe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await OIe(o,`${JSON.stringify(r,null,2)} `,{encoding:"utf8",mode:384}),await DIe(o,this.#e)}};var RH=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function kH(n){return Od(n,RH)}function vH(n){return jB(n,"Discord\u673A\u5668\u4EBA")}var JB=class extends ul{constructor(r){super(r,{channel:"Discord",...RH})}};function bd(n){return typeof n=="string"&&n.trim()?n.trim():null}function Md(n,r){return Object.freeze({code:n,message:r})}var Bl=class{#e;#A;#t;#r;#o;#i;#I;#s;#l;#a=new Map;#n=new Map;#g=new Map;#c=0;#p=!1;constructor({descriptor:r,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:t,deleteState:s=async()=>{},logger:g=console}){if(!r?.key||!r?.label||!r?.connectionLabel)throw new TypeError("TokenBotController requires a channel descriptor");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError(`${r.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${r.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof t!="function")throw new TypeError(`${r.label} controller dependencies are incomplete`);this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#o=a,this.#i=A,this.#I=t,this.#s=s,this.#l=g}async initialize(){if(this.#p)return this.status();for(let r of this.#t.list())await this.#u(r.botId,async()=>{if(this.#p||this.#a.get(r.botId)?.status?.ready)return;let o=await this.#E(r.tokenRef);if(!o){this.#n.set(r.botId,Md("missing-token",`${this.#e.label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002`));return}try{await this.#h(r,o),this.#n.delete(r.botId)}catch(i){this.#n.set(r.botId,Md("connection-failed",`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002`)),this.#l.warn?.(`[dsh-im:${this.#e.key}] bot ${r.botId} failed to initialize:`,i)}finally{this.#B()}});return this.status()}async bindCredentials({token:r}={}){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let o=bd(r);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=bd(i?.platformId),a=bd(i?.name);if(!e||!a)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#o(e);return await this.#u(A.botId,async()=>{if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let t=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:a,username:bd(i.username),createdAt:t?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(A.tokenRef,o);try{await this.#t.save(g)}catch(c){throw await this.#C(A.tokenRef,s),c}try{await this.#h(g,o),this.#n.delete(A.botId)}catch(c){this.#n.set(A.botId,Md("connection-failed",`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002`)),this.#l.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#B()}),this.status()}async reconnectBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#u(r,async()=>{let i=await this.#E(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#h(o,i),this.#n.delete(r)}catch(e){throw this.#n.set(r,Md("connection-failed",`${this.#e.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),e}finally{this.#B()}}),this.status()}async updateBotConfig(r,o){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);if(typeof o!="function")throw new TypeError("Bot config update must be a function");return await this.#u(r,async()=>{if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let i=this.#t.get(r);if(!i)throw new Error(`Unknown ${this.#e.label} bot`);let e=await this.#E(i.tokenRef);if(!e)throw new Error(`${this.#e.label} bot token is missing`);if(this.#p)throw new Error(`${this.#e.label} controller is closed`);let a=o(i),A=await this.#t.save(a);try{await this.#h(A,e),this.#n.delete(r)}catch(t){throw this.#n.set(r,Md("connection-failed",`${this.#e.label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`)),t}finally{this.#B()}}),this.status()}async sendConnectionTest(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#u(r,async()=>{let i=this.#a.get(r);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(`${this.#e.label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5`);throw a.code="test-target-unavailable",a}let e=`${o.name}\uFF08${this.#i(o.platformId)}\uFF09`;return await i.sendConnectionTest(la(e,`${this.#e.label}\u673A\u5668\u4EBA`)),{sent:!0}})}async deleteBot(r){let o=this.#t.get(r);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#u(r,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#d(r);try{await this.#A.unset(o.tokenRef),await this.#t.remove(r)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#s({botId:r,config:o}).catch(e=>{this.#l.warn?.(`[dsh-im:${this.#e.key}] bot ${r} state cleanup failed:`,e)}),this.#n.delete(r),this.#B()}),this.status()}status(){let r=this.#t.list().map(i=>{let e=this.#a.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#n.has(i.botId)||e?.connectionState==="failed"?"error":"offline";return{botId:i.botId,state:A,connected:a,configured:!0,bot:{name:i.name,username:i.username,idMasked:this.#i(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?`${this.#e.label}${this.#e.connectionLabel}\u8FD0\u884C\u6B63\u5E38`:A==="error"?`${this.#e.label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5`:`${this.#e.label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF`,lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},error:structuredClone(this.#n.get(i.botId)??null)}}),o=r.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#c,state:r.length===0?"disconnected":o===r.length?"connected":o>0?"degraded":"offline",bots:r,totals:{configured:r.length,connected:o}}}async close(){this.#p||(this.#p=!0,await Promise.allSettled([...this.#g.values()]),await Promise.allSettled([...this.#a.keys()].map(r=>this.#d(r))))}async#h(r,o){if(this.#p)throw new Error(`${this.#e.label} controller is closed`);if(await this.#d(r.botId),this.#p)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#I({botId:r.botId,config:r,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#a.set(r.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#a.delete(r.botId),e}}async#d(r){let o=this.#a.get(r);this.#a.delete(r),await o?.stop().catch(i=>{this.#l.warn?.(`[dsh-im:${this.#e.key}] bot ${r} failed to stop cleanly:`,i)})}async#E(r){let o=await this.#A.resolve(r).catch(()=>{});return bd(o?.value)}async#C(r,o){o?.value?await this.#A.set(r,o.value).catch(()=>{}):await this.#A.unset(r).catch(()=>{})}#u(r,o){let a=(this.#g.get(r)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#g.get(r)===a&&this.#g.delete(r)});return this.#g.set(r,a),a}#B(){this.#c+=1}};import{createHash as MIe}from"node:crypto";var _Ie="https://discord.com/api/v10/",NIe=12e4,TIe=new Set([50001,50013]),RIe=new Set([40005]);function ds(n){return typeof n=="string"&&n.trim()?n.trim():null}function PH(n,r){let o=AbortSignal.timeout(r);return n?AbortSignal.any([n,o]):o}function Mb(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function kIe(n,r){if(!Number.isInteger(n)||n<1)throw new TypeError(`${r} must be a positive integer`);return n}function GH(n,r){return r?.providerCode!==void 0&&(n.providerCode=r.providerCode),r?.retry_after!==void 0&&(n.retry_after=r.retry_after,n.retryAfter=r.retry_after),Number.isInteger(r?.status)&&(n.status=r.status),n}function vIe(n){let r=Number(n?.providerCode),o=Number(n?.status),i=ds(n?.message)??"",e="artifact-provider-rejected",a="Discord rejected the attachment.";o===401||o===403||TIe.has(r)?(e="artifact-permission-required",a="Discord denied permission to send the attachment."):o===413||RIe.has(r)||/(?:request|attachment|file).{0,24}too large/i.test(i)?(e="artifact-too-large",a="The attachment exceeds Discord's size limit."):o===429?(e="artifact-rate-limited",a="Discord rate-limited attachment delivery."):o>=500&&(e="artifact-delivery-uncertain",a="Discord attachment delivery result is uncertain.");let A=new Error(a,{cause:n});return A.code=e,GH(A,n)}function PIe(n){let r=new Error("Discord attachment delivery result is uncertain",{cause:n});return r.code="artifact-delivery-uncertain",GH(r,n)}function GIe(n,r){return new Promise((o,i)=>{if(r?.aborted){i(r.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),r?.addEventListener("abort",()=>{clearTimeout(e),i(r.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function $i(n,r){let o=ds(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${r}`);return o}function FIe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var _d=class{#e;#A;#t;#r;constructor({token:r,fetchImpl:o=fetch,baseUrl:i=_Ie,fileUploadTimeoutMs:e=NIe}){if(!FIe(r))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=r.trim(),this.#A=o,this.#t=new URL(i),this.#r=kIe(e,"fileUploadTimeoutMs")}getCurrentUser(r={}){return this.#o("users/@me",{...r,method:"GET"})}getGatewayBot(r={}){return this.#o("gateway/bot",{...r,method:"GET"})}getChannel({channelId:r,signal:o}={}){return this.#o(`channels/${$i(r,"channel id")}`,{method:"GET",signal:o})}startThreadFromMessage({channelId:r,messageId:o,name:i,signal:e}={}){let a=ds(i);if(!a||[...a].length>100)throw new TypeError("Discord thread name must contain 1-100 characters");if(e?.aborted)throw Mb(e);return this.#o(`channels/${$i(r,"channel id")}/messages/${$i(o,"message id")}/threads`,{method:"POST",signal:e,body:{name:a}})}createMessage({channelId:r,content:o,replyToMessageId:i,signal:e}){return this.#o(`channels/${$i(r,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:$i(i,"message id"),channel_id:$i(r,"channel id"),fail_if_not_exists:!1}}:{}}})}async createFileMessage({channelId:r,file:o,replyToMessageId:i,signal:e}){if(!o||typeof o!="object"||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A Discord attachment is required");let a=ds(o.deliveryKey)??ds(o.artifactId),A=a?MIe("sha256").update(a).digest("hex").slice(0,25):void 0,t=new FormData;t.append("payload_json",JSON.stringify({allowed_mentions:{parse:[],replied_user:!1},attachments:[{id:0,filename:o.fileName}],...A?{nonce:A,enforce_nonce:!0}:{},...i?{message_reference:{message_id:$i(i,"message id"),channel_id:$i(r,"channel id"),fail_if_not_exists:!1}}:{}})),t.append("files[0]",new Blob([o.bytes],{type:o.mediaType??"application/octet-stream"}),o.fileName);let s=$i(r,"channel id");if(e?.aborted)throw Mb(e);let g=PH(e,this.#r);try{return await this.#o(`channels/${s}/messages`,{method:"POST",signal:g,timeoutMs:this.#r,body:t,multipart:!0})}catch(c){throw e?.aborted?Mb(e):c?.code?.startsWith?.("discord-")?vIe(c):PIe(c)}}editMessage({channelId:r,messageId:o,content:i,signal:e}){return this.#o(`channels/${$i(r,"channel id")}/messages/${$i(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:r,signal:o}){return this.#o(`channels/${$i(r,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async#o(r,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:t=!0,multipart:s=!1}){let g;try{g=await this.#A(new URL(r,this.#t),{method:o,headers:{authorization:`Bot ${this.#e}`,...s?{}:{"content-type":"application/json"},"user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 1.1.0)"},...i===void 0?{}:{body:s?i:JSON.stringify(i)},signal:PH(e,a),redirect:"error"})}catch(I){throw I?.name==="AbortError"||I?.name==="TimeoutError"?I:new Error(`Discord ${o} transport failed`)}let c=null;if(A||g.status===429||!g.ok)try{c=await g.json()}catch{if(A){let I=new Error(`Discord ${o} returned invalid JSON`);throw I.status=g?.status,I}}if(g.status===429&&t){let I=Math.min(1e4,Math.max(50,Number(c?.retry_after)*1e3||1e3));return await GIe(I,e),this.#o(r,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1,multipart:s})}if(!g.ok){let I=new Error(ds(c?.message)??`Discord API failed with HTTP ${g.status}`);I.code=`discord-${g.status}`,I.status=g.status,(Number.isInteger(c?.code)||typeof c?.code=="string")&&(I.providerCode=c.code);let E=Number(c?.retry_after);throw Number.isFinite(E)&&E>=0&&(I.retry_after=E,I.retryAfter=E),I}return A?c:null}};async function FH(n,r={}){let i=await new _d({token:n,...r}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:ds(i.global_name)??ds(i.username)??"Discord\u673A\u5668\u4EBA",username:ds(i.username)}}var LH="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",LIe="\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002";function Ai(n){return typeof n=="string"?n.trim():""}function UIe(n,r,o){return r.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Er(n)&&!Zt(n)&&!!Ai(n.content)}function HIe(n,r,o){let i=String(n??"\u7ED3\u679C\u6587\u4EF6").replace(/[\r\n]+/g," ").trim().slice(0,255)||"\u7ED3\u679C\u6587\u4EF6";switch(r?.code){case"artifact-delivery-uncertain":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u7684\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u8BD5\u3002`;case"artifact-permission-required":return o?.key==="slack"?`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Slack \u5E94\u7528\u7F3A\u5C11 files:write \u6743\u9650\u3002\u8BF7\u66F4\u65B0 Manifest\u3001\u91CD\u65B0\u5B89\u88C5\u5E94\u7528\u5E76\u91CD\u65B0\u8FDE\u63A5\u673A\u5668\u4EBA\u540E\u91CD\u8BD5\u3002`:o?.key==="discord"?`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002`:o?.key==="telegram"?`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 Telegram \u4E0D\u5141\u8BB8\u673A\u5668\u4EBA\u5728\u5F53\u524D\u804A\u5929\u53D1\u9001\u6587\u6863\uFF0C\u8BF7\u68C0\u67E5\u804A\u5929\u6743\u9650\u3002`:`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u6E20\u9053\u6743\u9650\u3002`;case"artifact-too-large":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002`;case"artifact-empty":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002`;case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6216\u51C6\u5907\u53D1\u9001\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u4ECD\u53EF\u8BBF\u95EE\u540E\u91CD\u8BD5\u3002`;case"artifact-rate-limited":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`;case"artifact-provider-rejected":return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002`;default:return`\u7ED3\u679C\u6587\u4EF6\u300C${i}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002`}}function yi(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null}}var dn=class{#e;#A;#t;#r;#o;#i;#I;#s;#l=new Map;#a=new Map;#n=new Map;#g=new Set;#c=new Set;#p=new Set;#h;constructor({descriptor:r,bot:o,harness:i,state:e,status:a=yi(),logger:A=console,replyTimeoutMs:t=6e5,signal:s}){if(!r?.key||!r?.label)throw new TypeError("A channel descriptor is required");if(!o||typeof o.sendText!="function")throw new TypeError("A bot client is required");if(!i||!e)throw new TypeError("Harness client and state store are required");this.#e=r,this.#A=o,this.#t=i,this.#r=e,this.#o=a,this.#i=A,this.#I=t,this.#s=s,this.#h=new za({label:r.key,logger:A})}get status(){return structuredClone(this.#o)}accept(r){if(this.#s?.aborted)return Promise.resolve();let o=Ai(r?.conversationId),i=r?.kind==="group"?"group":"direct",e={...r,kind:i,conversationId:o},a=Ai(e.messageId),A=Ai(e.senderId);if(!a||!A||!o||e.senderIsBot===!0||this.#r.hasSeen(a)||this.#g.has(a))return Promise.resolve();this.#g.add(a),e.kind==="direct"&&Hi(this.#r,e.connectionTestTarget??e.replyTarget);let t=`${i}:${o}`,s=this.#a.get(t),g=Ai(e.content),c=Zt(e)?null:ui(g)?Ji:Bi(g)?zi:fi(g)?Vi:null;if(c&&(e.kind!=="group"||e.addressed===!0)){let E;return E=this.#E(e,a,t,c).finally(()=>{this.#g.delete(a),this.#p.delete(E)}),this.#p.add(E),E}let I=this.#h.claimReply({key:t,actor:A,messageId:a,text:Er(e)||Zt(e)?"":e.content,addressed:e.kind!=="group"||e.addressed===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#a.has(t),send:E=>this.#A.sendText(e.replyTarget,E)});if(I){let E;return E=I.process(async()=>this.#r.hasSeen(a)?!1:(await this.#r.markSeen(a),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#g.delete(a),this.#c.delete(E)}),this.#c.add(E),E}if(s&&s.actor!==A)return this.#d(e,a,A,t);if(s?.submitting||s?.claimedReplyMessageId)return this.#d(e,a,A,t);if(s){UIe(e,s,A)&&(s.claimedReplyMessageId=a);let B=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#B(e,a,A,t,s)).finally(()=>{this.#g.delete(a),s.claimedReplyMessageId===a&&(s.claimedReplyMessageId=null),s.queue===B&&(s.queue=null)});return s.queue=B,B}return this.#d(e,a,A,t)}#d(r,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#l.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#u(r,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#g.delete(o),this.#l.get(e)===s&&this.#l.delete(e)});return this.#l.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#l.values(),...[...this.#a.values()].flatMap(r=>r.queue?[r.queue]:[]),...this.#c,...this.#p])}async#E(r,o,i,e){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString();let a=r.replyTarget;try{let A=await e(Ai(r.content),this.#t,this.#r,i,{signal:this.#s,hasImages:Er(r),hasFiles:Zt(r),pendingInteraction:this.#a.has(i)||this.#h.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#M(i),this.#h.closeRoute(i)]);for(let t of A?.messages??[A?.message])t&&await this.#A.sendText(a,t);this.#o.lastError=null}catch(A){if(A?.code==="turn-stopped"||this.#s?.aborted)return;this.#o.lastError=A?.message??String(A),this.#i.error?.(`[dsh-im:${this.#e.key}] failed to process a command:`,A),await this.#A.sendText(a,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002").catch(()=>{})}}sendConnectionTest(r){return ng({state:this.#r,text:r,channelLabel:`${this.#e.label}\u673A\u5668\u4EBA`,send:(o,i)=>this.#A.sendText(o,i)})}async#C(r,o,i=[],e){let a=await Xi({artifacts:i,baseReceipt:e,deliveryId:o,channelKey:this.#e.key,signal:this.#s,sendImage:typeof this.#A.sendImage=="function"?A=>this.#A.sendImage(r,A):void 0,sendFile:typeof this.#A.sendFile=="function"?A=>this.#A.sendFile(r,A):void 0,sendFailureNotice:(A,t)=>this.#A.sendText(r,HIe(A?.fileName,t,this.#e)),logger:this.#i});return this.#o.artifactsSent=(this.#o.artifactsSent??0)+a.artifactsSent,this.#o.artifactSendErrors=(this.#o.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,userVisible:a.userVisible}}async#u(r,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString()}let A=r.replyTarget,t=Ai(r.content),s=null;try{if(this.#s?.throwIfAborted(),r.kind==="group"&&r.addressed!==!0){this.#o.messagesRejected+=1,this.#o.lastRejectedAt=new Date().toISOString();return}let g=Er(r),c=Zt(r);if(!t&&!g&&!c){await this.#A.sendText(A,"\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002");return}let I=t.toLowerCase();if(!g&&!c&&I==="/help"){await this.#A.sendText(A,[`${this.#e.label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002`,"","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587","/workspace \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2","/presetlist \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/help \u663E\u793A\u672C\u5E2E\u52A9"].join(` `));return}if(!g&&!c&&I==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#A.sendText(A,`${this.#e.label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002`);return}let E=!g&&!c?await qi(t,this.#t,e):null;if(E){for(let x of E.messages??[E.message])await this.#A.sendText(A,x);return}if(!g&&!c&&I==="/new"){await this.#r.clearSession(e),await this.#A.sendText(A,"\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002");return}let B=!g&&!c?await ji(t,this.#t,this.#r,e,{signal:this.#s}):null;if(B){await this.#A.sendText(A,B.message);return}await this.#A.sendTyping?.(A).catch(x=>{this.#i.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,x)});let f=!1;if(typeof this.#A.openStream=="function")try{s=await this.#A.openStream(A)}catch(x){this.#i.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,x)}let Q=g?await xi(r,{signal:this.#s}):void 0,{answer:y,artifacts:m=[]}=await Wa({harness:this.#t,state:this.#r,key:e,text:t,content:Q,createOptions:this.#s?{signal:this.#s}:void 0,existsOptions:this.#s?{signal:this.#s}:void 0,askOptions:{timeoutMs:this.#I,signal:this.#s,control:{owner:this,key:e},onUpdate:s?async x=>{let K=x.type==="text"?x.text:x.type==="tool"?`\u6B63\u5728\u4F7F\u7528${x.name}\u2026`:x.text;K&&await s.update(K)}:void 0,onInteraction:x=>this.#Q(x,{key:e,actor:i,target:A,requiresMention:r.kind==="group"&&r.requiresMention!==!1}),onInteractionResolved:x=>this.#m(x),files:r.files}}),_=!Ai(y)&&m.length>0?LIe:y,N=null,G=null;if(s)try{let x=await s.finish(_);f=!0,G=Ut({deliveryId:o,presentation:`${this.#e.key}-stream`,providerMessageIds:[...Za(s),...Za(x)]})}catch(x){s.cancel?.(),this.#i.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,x)}if(!f)try{let x=await this.#A.sendText(A,_);G=Ut({deliveryId:o,presentation:`${this.#e.key}-text`,providerMessageIds:Za(x)})}catch(x){N=x}let Y=await this.#C(A,o,m,G);if(N&&!Y.userVisible)throw N;return this.#o.messagesReplied+=1,this.#o.lastReplyAt=new Date().toISOString(),this.#o.lastError=null,Y.receipt}catch(g){if(g?.code==="turn-stopped"){if(s)try{await s.finish("\u5DF2\u505C\u6B62\u3002")}catch{s.cancel?.()}return}if(s?.cancel?.(),this.#s?.aborted)return;this.#o.lastError=g?.message??String(g);let c=Yi(g);if(c){try{await this.#A.sendText(A,c)}catch(E){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to send the image error reply:`,E)}return}let I=Zi(g);if(I){try{await this.#A.sendText(A,I)}catch(E){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to send the file error reply:`,E)}return}this.#i.error?.(`[dsh-im:${this.#e.key}] failed to process a message:`,g);try{await this.#A.sendText(A,"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}catch(E){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to send the safe error reply:`,E)}}finally{await Promise.allSettled([this.#M(e),this.#h.closeRoute(e)])}}async#B(r,o,i,e,a){if(this.#s?.aborted)return;let A=this.#a.get(e),t=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return t&&(!A||A!==a)?this.#y(r,o):this.#d(r,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),r.kind==="group"&&r.addressed!==!0){this.#o.messagesRejected+=1,this.#o.lastRejectedAt=new Date().toISOString();return}let s=r.replyTarget,g=Ai(r.content);if(!g||Er(r)||Zt(r)){try{await this.#A.sendText(s,"\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")}catch(E){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to reject a non-text interaction reply:`,E)}return}let c=this.#a.get(e);if(!c||c!==a||c.submitting)return t&&(!c||c!==a)?this.#y(r,o,{alreadyRecorded:!0}):this.#d(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let E=c.presentationTask!==null;try{await this.#f(c)}catch(f){this.#o.lastError=`${this.#e.label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002`,this.#i.error?.(`[dsh-im:${this.#e.key}] failed to retry an interaction question:`,f),c.interaction.reconnect?.();return}let B=this.#a.get(e);if(!B||B!==a||B.submitting)return t&&(!B||B!==a)?this.#y(r,o,{alreadyRecorded:!0}):this.#d(r,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!E)return}let I=c.questions[c.index];if(I){if(c.answers.push(qa(I,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(r?.kind!=="question")return;let A=r?.payload?.questions,t=Ai(r?.interactionId)||Ai(r?.rpcId);if(!Ai(r?.rpcId)||!t||!Ai(r?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!ja(c))){this.#i.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(r.recovered===!0){await this.#_(r,`${this.#e.label} safely cancelled an interaction left by an earlier client.`);try{await this.#A.sendText(e,"\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")}catch(c){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#a.get(o);if(s?.interactionId===t){s.interaction=r,s.needsPresentation&&await this.#f(s);return}if(this.#n.has(t))return;if(s){this.#i.warn?.(`[dsh-im:${this.#e.key}] cancelled a second pending Harness question`),await this.#_(r,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:t,sessionId:r.sessionId,interaction:r,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#a.set(o,g),this.#n.set(t,o),await this.#f(g)}async#m(r){if(r?.kind==="approval"){await this.#h.handleResolved(r);return}let o=Ai(r?.interactionId);if(r?.kind!=="question"||!o)return;let i=this.#n.get(o);i&&this.#w(i,o)}#f(r){if(r.presentationTask)return r.presentationTask;let o=r.questions[r.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(r.target,Ja(o,r.index,r.questions.length,{requiresMention:r.requiresMention})),r.needsPresentation=!1})();return r.presentationTask=i,i.then(()=>{r.presentationTask===i&&(r.presentationTask=null)},()=>{r.presentationTask===i&&(r.presentationTask=null)}),i}async#y(r,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(r.replyTarget,LH)}catch(e){this.#i.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#D(r,o){let i=this.#a.get(r);return!i||o!==void 0&&i.interactionId!==o?null:(this.#a.delete(r),this.#n.delete(i.interactionId),i)}#w(r,o){return this.#D(r,o)!==null}async#_(r,o){try{await r.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#M(r){let o=this.#D(r);if(!(!o||o.kind!=="question"))try{await this.#_(o.interaction,`The ${this.#e.label} interaction ended before the user answered.`)}catch(i){this.#i.warn?.(`[dsh-im:${this.#e.key}] failed to cancel a pending Harness interaction:`,i)}}};var _b=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5"}),qB=class extends dn{constructor(r){super({descriptor:_b,...r})}};var Nd=class extends Bl{constructor(r){super({...r,descriptor:_b,inspectToken:r.inspectToken??FH,deriveIdentity:kH,maskPlatformId:vH})}};var zB=class extends or{constructor(r){super({...r,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function eo(n,r){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>r;){let a=e.lastIndexOf(` -`,r);anull,logger:t=console}){let s,g=[],c=null,I=null,E=null,B=!1,f=n,Q=()=>{B||I!==null||E||!c||(I=setTimeout(()=>{I=null;let y=c;c=null;let m=eo(y,r)[0]??n;E=Promise.resolve(m===f?void 0:e(s,m)).then(()=>{f=m}).catch(_=>t.warn?.("[dsh-im] streamed message update failed:",_)).finally(()=>{E=null,Q()})},o),I?.unref?.())};return{get messageId(){return s},get providerMessageIds(){return[...g]},async start(){return s=await i(n),(typeof s=="string"&&s.trim()||Number.isSafeInteger(s))&&g.push(String(s)),this},update(y){B||typeof y!="string"||!y.trim()||(c=y,Q())},async finish(y){if(B)throw new Error("Message stream is already closed");B=!0,I!==null&&clearTimeout(I),I=null,c=null,await E?.catch(()=>{});let m=eo(y,r),_=m[0]??"\u5904\u7406\u5B8C\u6210\u3002";_!==f&&await e(s,_),f=_;for(let N of m.slice(1)){let G=await a(N),Y=A(G);(typeof Y=="string"&&Y.trim()||Number.isSafeInteger(Y))&&g.push(String(Y))}},cancel(){B=!0,c=null,I!==null&&clearTimeout(I),I=null}}}async function UH(n){try{await n?.body?.cancel?.()}catch{}}function KIe(n,r){return!Array.isArray(r)||r.some(o=>typeof o=="string"&&(n.hostname===o||o.startsWith(".")&&(n.hostname===o.slice(1)||n.hostname.endsWith(o))))}async function fl(n,{fetchImpl:r=fetch,headers:o,signal:i,allowedHosts:e}={}){let a=new URL(n);if(a.protocol!=="https:")throw new Error("File download URL must use HTTPS");if(!KIe(a,e))throw new Error("File download URL is not hosted by the messaging platform");let A=await r(a,{method:"GET",headers:o,signal:i,redirect:"manual"});if(Number.isInteger(A?.status)&&A.status>=300&&A.status<400){await UH(A);let t=new Error(`File download redirect was blocked (HTTP ${A.status})`);throw t.code="file-redirect-blocked",t}if(!A?.ok){await UH(A);let t=new Error(`File download failed with HTTP ${A?.status??"unknown"}`);throw t.code="file-http-error",t.status=A?.status,t}if(A.body?.[Symbol.asyncIterator])return{stream:A.body};if(typeof A.arrayBuffer=="function"){let t=Buffer.from(await A.arrayBuffer());return{stream:(async function*(){yield t})()}}throw new Error("File download returned no readable body")}var xIe=4609,HH=Object.freeze([1e3,3e3,5e3,1e4,3e4]),YIe=0,jIe=5,JIe=10,qIe=11,zIe=12,VIe=new Set([JIe,qIe,zIe]),WIe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),ZIe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),YH=Object.freeze(["cdn.discordapp.com"]);function XIe(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return r.searchParams.set("v","10"),r.searchParams.set("encoding","json"),r.href}function Nb(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Discord WebSocket does not support events")}function $Ie(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function ele(n){if(n===4004){let o=new Error("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002");return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002");return o.code="discord-intents",o}let r=new Error(`Discord Gateway closed (${n||"unknown"})`);return r.code="discord-gateway-closed",r}function jH(n,r){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${r}>`,"g"),"").trim()}function Ale(n,r){return[...jH(n?.content??"",r).replace(/\s+/g," ").trim()||"DeepSeek Harness"].slice(0,100).join("")}function kb(n){return VIe.has(Number(n?.type))}function JH(n,r){return kb(n)&&String(n?.id??"")===String(r?.id??"")&&String(n?.parent_id??"")===String(r?.channel_id??"")}function Tb(n,r){return n?.id&&r?.(n),n}function Tc(n,r,o,{created:i=!1,fallback:e=null,notice:a=null}={}){let A=String(r?.id??n.conversationId),t=kb(r),s=t&&(i||String(r?.owner_id??"")===String(o)),g=t&&r?.parent_id?String(r.parent_id):A;return{...n,conversationId:A,addressed:n.addressed||s,requiresMention:t?!s:n.kind==="group",replyTarget:{channelId:A,...!i&&n.replyTarget?.replyToMessageId?{replyToMessageId:n.replyTarget.replyToMessageId}:{},...a?{notice:a}:{}},connectionTestTarget:{channelId:A},conversationRoute:{peerId:g,...t?{threadId:A,managed:s}:{},...e?{fallback:e}:{}}}}function tle(n){let r=Number(n?.status);return!Number.isInteger(r)||r>=500}function KH(n){let r=new Error("Discord Thread creation result is uncertain",{cause:n});return r.code="discord-thread-create-uncertain",r}async function rle(n,r,{signal:o,onChannel:i}={}){try{let e=Tb(await n.getChannel({channelId:String(r.id),signal:o}),i);return JH(e,r)?e:null}catch(e){if(e?.status===404)return null;throw e}}async function xH(n,r,o){try{await n.createMessage({channelId:r.replyTarget.channelId,replyToMessageId:r.replyTarget.replyToMessageId,content:"Thread \u521B\u5EFA\u7ED3\u679C\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u3002\u82E5\u5DF2\u521B\u5EFA\uFF0C\u8BF7\u5728\u5BF9\u5E94 Thread \u4E2D\u91CD\u8BD5\uFF1B\u82E5\u672A\u521B\u5EFA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0 @\u673A\u5668\u4EBA\u3002",signal:o})}catch(i){if(o?.aborted)throw o.reason??i}}function qH(n){let r=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(WIe.has(r))return r;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of ZIe)if(o.endsWith(i))return e;return null}function zH(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function ale(n,r){let o=qH(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:zH(n.size),load:i=>Ki(n.url,{...i,fetchImpl:r,allowedHosts:YH})}}function ile(n,r){if(qH(n)||typeof n?.url!="string"||!n.url)return null;let o=typeof n.content_type=="string"&&n.content_type?n.content_type.split(";",1)[0].trim().toLowerCase():void 0;return{name:typeof n.filename=="string"&&n.filename?n.filename:String(n.id??"discord-file"),...o?{mediaType:o}:{},size:zH(n.size),load:({signal:i}={})=>fl(n.url,{fetchImpl:r,signal:i,allowedHosts:YH})}}function ole(n,r,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id||Number(n.type)===21)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(r));return{messageId:String(n.id),senderId:String(n.author.id),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:jH(n.content??"",r),images:Array.isArray(n.attachments)?n.attachments.map(a=>ale(a,o)).filter(Boolean):[],files:Array.isArray(n.attachments)?n.attachments.map(a=>ile(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}async function nle(n,r,{api:o,channel:i,fetchImpl:e=fetch,signal:a,onChannel:A}={}){let t=ole(n,r,{fetchImpl:e});if(!t||t.senderIsBot)return t;if(t.kind==="direct")return Tc(t,{id:t.conversationId,type:1},r);if(!o||typeof o.getChannel!="function")throw new TypeError("Discord route resolution requires the Discord API");let s=Tb(i??await o.getChannel({channelId:t.conversationId,signal:a}),A);if(kb(s)||!t.addressed)return Tc(t,s,r);let g=Number(s?.type);if(g!==YIe&&g!==jIe)return Tc(t,s,r,{fallback:"unsupported-channel",notice:"\u5F53\u524D\u9891\u9053\u4E0D\u652F\u6301\u81EA\u52A8\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"});let c;try{if(c=Tb(await o.startThreadFromMessage({channelId:t.conversationId,messageId:t.messageId,name:Ale(n,r),signal:a}),A),!JH(c,n))throw new Error("Discord returned an invalid thread for the source message")}catch(I){if(a?.aborted)throw a.reason??I;let E;try{E=await rle(o,n,{signal:a,onChannel:A})}catch(B){throw await xH(o,t,a),KH(B)}if(E)return Tc(t,E,r,{created:!0});if(tle(I))throw await xH(o,t,a),KH(I);return Tc(t,s,r,{fallback:"thread-create-failed",notice:"\u65E0\u6CD5\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"})}return Tc(t,c,r,{created:!0})}var Rb=class{#e;#A;#t=new WeakSet;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=!this.#t.has(r)&&r?.notice?String(r.notice):null,e=eo(i?`${i} +`,r);anull,logger:t=console}){let s,g=[],c=null,I=null,E=null,B=!1,f=n,Q=()=>{B||I!==null||E||!c||(I=setTimeout(()=>{I=null;let y=c;c=null;let m=eo(y,r)[0]??n;E=Promise.resolve(m===f?void 0:e(s,m)).then(()=>{f=m}).catch(_=>t.warn?.("[dsh-im] streamed message update failed:",_)).finally(()=>{E=null,Q()})},o),I?.unref?.())};return{get messageId(){return s},get providerMessageIds(){return[...g]},async start(){return s=await i(n),(typeof s=="string"&&s.trim()||Number.isSafeInteger(s))&&g.push(String(s)),this},update(y){B||typeof y!="string"||!y.trim()||(c=y,Q())},async finish(y){if(B)throw new Error("Message stream is already closed");B=!0,I!==null&&clearTimeout(I),I=null,c=null,await E?.catch(()=>{});let m=eo(y,r),_=m[0]??"\u5904\u7406\u5B8C\u6210\u3002";_!==f&&await e(s,_),f=_;for(let N of m.slice(1)){let G=await a(N),Y=A(G);(typeof Y=="string"&&Y.trim()||Number.isSafeInteger(Y))&&g.push(String(Y))}},cancel(){B=!0,c=null,I!==null&&clearTimeout(I),I=null}}}async function UH(n){try{await n?.body?.cancel?.()}catch{}}function KIe(n,r){return!Array.isArray(r)||r.some(o=>typeof o=="string"&&(n.hostname===o||o.startsWith(".")&&(n.hostname===o.slice(1)||n.hostname.endsWith(o))))}async function fl(n,{fetchImpl:r=fetch,headers:o,signal:i,allowedHosts:e}={}){let a=new URL(n);if(a.protocol!=="https:")throw new Error("File download URL must use HTTPS");if(!KIe(a,e))throw new Error("File download URL is not hosted by the messaging platform");let A=await r(a,{method:"GET",headers:o,signal:i,redirect:"manual"});if(Number.isInteger(A?.status)&&A.status>=300&&A.status<400){await UH(A);let t=new Error(`File download redirect was blocked (HTTP ${A.status})`);throw t.code="file-redirect-blocked",t}if(!A?.ok){await UH(A);let t=new Error(`File download failed with HTTP ${A?.status??"unknown"}`);throw t.code="file-http-error",t.status=A?.status,t}if(A.body?.[Symbol.asyncIterator])return{stream:A.body};if(typeof A.arrayBuffer=="function"){let t=Buffer.from(await A.arrayBuffer());return{stream:(async function*(){yield t})()}}throw new Error("File download returned no readable body")}var xIe=37377,HH=Object.freeze([1e3,3e3,5e3,1e4,3e4]),YIe=0,jIe=5,JIe=10,qIe=11,zIe=12,VIe=new Set([JIe,qIe,zIe]),WIe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),ZIe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]),YH=Object.freeze(["cdn.discordapp.com"]);function XIe(n){let r=new URL(n);if(r.protocol!=="wss:")throw new Error("Discord returned an insecure Gateway URL");return r.searchParams.set("v","10"),r.searchParams.set("encoding","json"),r.href}function Nb(n,r,o){if(typeof n.addEventListener=="function")n.addEventListener(r,o);else if(typeof n.on=="function")n.on(r,o);else throw new TypeError("Discord WebSocket does not support events")}function $Ie(n){return typeof n=="string"?n:typeof n?.data=="string"?n.data:Buffer.isBuffer(n)?n.toString("utf8"):Buffer.isBuffer(n?.data)?n.data.toString("utf8"):null}function ele(n){if(n===4004){let o=new Error("Discord Bot Token \u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199\u3002");return o.code="discord-401",o}if(n===4013||n===4014){let o=new Error("Discord Gateway Intents \u914D\u7F6E\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 Developer Portal \u7684 Bot \u8BBE\u7F6E\u3002");return o.code="discord-intents",o}let r=new Error(`Discord Gateway closed (${n||"unknown"})`);return r.code="discord-gateway-closed",r}function jH(n,r){return typeof n!="string"?"":n.replace(new RegExp(`<@!?${r}>`,"g"),"").trim()}function Ale(n,r){return[...jH(n?.content??"",r).replace(/\s+/g," ").trim()||"DeepSeek Harness"].slice(0,100).join("")}function kb(n){return VIe.has(Number(n?.type))}function JH(n,r){return kb(n)&&String(n?.id??"")===String(r?.id??"")&&String(n?.parent_id??"")===String(r?.channel_id??"")}function Tb(n,r){return n?.id&&r?.(n),n}function Tc(n,r,o,{created:i=!1,fallback:e=null,notice:a=null}={}){let A=String(r?.id??n.conversationId),t=kb(r),s=t&&(i||String(r?.owner_id??"")===String(o)),g=t&&r?.parent_id?String(r.parent_id):A;return{...n,conversationId:A,addressed:n.addressed||s,requiresMention:t?!s:n.kind==="group",replyTarget:{channelId:A,...!i&&n.replyTarget?.replyToMessageId?{replyToMessageId:n.replyTarget.replyToMessageId}:{},...a?{notice:a}:{}},connectionTestTarget:{channelId:A},conversationRoute:{peerId:g,...t?{threadId:A,managed:s}:{},...e?{fallback:e}:{}}}}function tle(n){let r=Number(n?.status);return!Number.isInteger(r)||r>=500}function KH(n){let r=new Error("Discord Thread creation result is uncertain",{cause:n});return r.code="discord-thread-create-uncertain",r}async function rle(n,r,{signal:o,onChannel:i}={}){try{let e=Tb(await n.getChannel({channelId:String(r.id),signal:o}),i);return JH(e,r)?e:null}catch(e){if(e?.status===404)return null;throw e}}async function xH(n,r,o){try{await n.createMessage({channelId:r.replyTarget.channelId,replyToMessageId:r.replyTarget.replyToMessageId,content:"Thread \u521B\u5EFA\u7ED3\u679C\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u3002\u82E5\u5DF2\u521B\u5EFA\uFF0C\u8BF7\u5728\u5BF9\u5E94 Thread \u4E2D\u91CD\u8BD5\uFF1B\u82E5\u672A\u521B\u5EFA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0 @\u673A\u5668\u4EBA\u3002",signal:o})}catch(i){if(o?.aborted)throw o.reason??i}}function qH(n){let r=typeof n?.content_type=="string"?n.content_type.split(";",1)[0].trim().toLowerCase():"";if(WIe.has(r))return r;let o=typeof n?.filename=="string"?n.filename.toLowerCase():"";for(let[i,e]of ZIe)if(o.endsWith(i))return e;return null}function zH(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function ale(n,r){let o=qH(n);return!o||typeof n?.url!="string"?null:{name:typeof n.filename=="string"?n.filename:void 0,mediaType:o,size:zH(n.size),load:i=>Ki(n.url,{...i,fetchImpl:r,allowedHosts:YH})}}function ile(n,r){if(qH(n)||typeof n?.url!="string"||!n.url)return null;let o=typeof n.content_type=="string"&&n.content_type?n.content_type.split(";",1)[0].trim().toLowerCase():void 0;return{name:typeof n.filename=="string"&&n.filename?n.filename:String(n.id??"discord-file"),...o?{mediaType:o}:{},size:zH(n.size),load:({signal:i}={})=>fl(n.url,{fetchImpl:r,signal:i,allowedHosts:YH})}}function ole(n,r,{fetchImpl:o=fetch}={}){if(!n?.id||!n?.channel_id||!n?.author?.id||Number(n.type)===21)return null;let i=!n.guild_id,e=i||n.mentions?.some(a=>String(a?.id)===String(r));return{messageId:String(n.id),senderId:String(n.author.id),senderIsBot:n.author.bot===!0,kind:i?"direct":"group",conversationId:String(n.channel_id),content:jH(n.content??"",r),images:Array.isArray(n.attachments)?n.attachments.map(a=>ale(a,o)).filter(Boolean):[],files:Array.isArray(n.attachments)?n.attachments.map(a=>ile(a,o)).filter(Boolean):[],addressed:e,replyTarget:{channelId:String(n.channel_id),replyToMessageId:String(n.id)},connectionTestTarget:{channelId:String(n.channel_id)}}}async function nle(n,r,{api:o,channel:i,fetchImpl:e=fetch,signal:a,onChannel:A}={}){let t=ole(n,r,{fetchImpl:e});if(!t||t.senderIsBot)return t;if(t.kind==="direct")return Tc(t,{id:t.conversationId,type:1},r);if(!o||typeof o.getChannel!="function")throw new TypeError("Discord route resolution requires the Discord API");let s=Tb(i??await o.getChannel({channelId:t.conversationId,signal:a}),A);if(kb(s)||!t.addressed)return Tc(t,s,r);let g=Number(s?.type);if(g!==YIe&&g!==jIe)return Tc(t,s,r,{fallback:"unsupported-channel",notice:"\u5F53\u524D\u9891\u9053\u4E0D\u652F\u6301\u81EA\u52A8\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"});let c;try{if(c=Tb(await o.startThreadFromMessage({channelId:t.conversationId,messageId:t.messageId,name:Ale(n,r),signal:a}),A),!JH(c,n))throw new Error("Discord returned an invalid thread for the source message")}catch(I){if(a?.aborted)throw a.reason??I;let E;try{E=await rle(o,n,{signal:a,onChannel:A})}catch(B){throw await xH(o,t,a),KH(B)}if(E)return Tc(t,E,r,{created:!0});if(tle(I))throw await xH(o,t,a),KH(I);return Tc(t,s,r,{fallback:"thread-create-failed",notice:"\u65E0\u6CD5\u521B\u5EFA Thread\uFF0C\u5DF2\u76F4\u63A5\u5728\u5F53\u524D\u9891\u9053\u56DE\u590D\u3002"})}return Tc(t,c,r,{created:!0})}var Rb=class{#e;#A;#t=new WeakSet;constructor({api:r,signal:o}){this.#e=r,this.#A=o}async sendText(r,o){let i=!this.#t.has(r)&&r?.notice?String(r.notice):null,e=eo(i?`${i} ${o}`:o,1900),a=[];for(let[A,t]of e.entries()){let s=await this.#e.createMessage({channelId:r.channelId,content:t,replyToMessageId:A===0?r.replyToMessageId:void 0,signal:this.#A});i&&A===0&&this.#t.add(r),typeof s?.id=="string"&&s.id&&a.push(s.id)}return{providerMessageIds:a}}sendTyping(r){return this.#e.sendTyping({channelId:r.channelId,signal:this.#A})}sendFile(r,o){return this.#e.createFileMessage({channelId:r.channelId,file:o,replyToMessageId:r.replyToMessageId,signal:this.#A})}async openStream(r){let o=!this.#t.has(r)&&r?.notice?String(r.notice):null,i=a=>o?`${o} diff --git a/src/channels/discord/discord-runtime.mjs b/src/channels/discord/discord-runtime.mjs index e90ee22..c18d1f0 100644 --- a/src/channels/discord/discord-runtime.mjs +++ b/src/channels/discord/discord-runtime.mjs @@ -4,7 +4,7 @@ import { fetchImageBuffer } from '../shared/image-prompt.mjs'; import { DiscordApi } from './discord-api.mjs'; import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs'; -const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12); +const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15); const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]); const GUILD_TEXT = 0; const GUILD_ANNOUNCEMENT = 5; diff --git a/test/channels/discord/discord.test.mjs b/test/channels/discord/discord.test.mjs index 8682605..96f45f5 100644 --- a/test/channels/discord/discord.test.mjs +++ b/test/channels/discord/discord.test.mjs @@ -1274,7 +1274,7 @@ test('Discord runtime identifies on Gateway v10 and becomes ready', async () => assert.equal(runtime.status.ready, true); const identify = socket.sent.find((packet) => packet.op === 2); assert.equal(identify.d.token, TOKEN); - assert.equal(identify.d.intents, 4_609); + assert.equal(identify.d.intents, 37_377); assert.equal(identify.d.properties.browser, 'dsh-im'); for (const [id, sequence] of [