diff --git a/README.en.md b/README.en.md index a6a25b8..23f2885 100644 --- a/README.en.md +++ b/README.en.md @@ -170,8 +170,8 @@ See the [Proactive Delivery Guide](PROACTIVE_DELIVERY.en.md) ([简体中文](PRO | `/cancel` | Cancel batch input and discard its collected messages. | | `/repair` | In a Feishu direct chat, incrementally repair the card callback and permissions required for media and the native Slash Command panel. | | `/compact` | Immediately compact older context in the Session bound to the current chat. | -| `/workspace ` | Switch the current bot's Harness workspace by `/workspacelist` index or absolute path. | -| `/workspacelist` | List workspace absolute paths that still exist on the current Harness Host. | +| `/workspace `, `/ws ` | Switch the current bot's Harness workspace by `/workspacelist` index or absolute path. | +| `/workspacelist`, `/workspaces`, `/wsl` | List workspace absolute paths that still exist on the current Harness Host. | | `/sessionlist [workspace number or absolute path]`, `/sessions [...]` | Equivalent aliases that list every registered session ID and title in the selected workspace; omit the argument to use the current workspace. | | `/sessionlist --limit N`, `/sessions --limit N` | List the first N sessions in the current workspace's existing order; N must be a positive integer. | | `/session ` | Bind the current chat to an existing Harness session. | diff --git a/README.md b/README.md index c2e9f1d..c9af3ee 100644 --- a/README.md +++ b/README.md @@ -173,8 +173,8 @@ dsh web | `/cancel` | 取消批量输入并丢弃已收集的消息。 | | `/repair` | 在飞书私聊中增量修复卡片回调,并补全媒体与原生 Slash Command 面板所需的权限。 | | `/compact` | 立即压缩当前聊天绑定会话的较早上下文。 | -| `/workspace <工作区序号或绝对路径>` | 按 `/workspacelist` 序号或绝对路径切换当前机器人的 Harness 工作区。 | -| `/workspacelist` | 列出当前 Harness Host 上仍然存在的工作区绝对路径。 | +| `/workspace <工作区序号或绝对路径>`、`/ws <工作区序号或绝对路径>` | 按 `/workspacelist` 序号或绝对路径切换当前机器人的 Harness 工作区。 | +| `/workspacelist`、`/workspaces`、`/wsl` | 列出当前 Harness Host 上仍然存在的工作区绝对路径。 | | `/sessionlist [工作区序号或绝对路径]`、`/sessions [...]` | 两个等价命令;列出指定工作区登记的所有会话 ID 和标题,省略参数时使用当前工作区。 | | `/sessionlist --limit N`、`/sessions --limit N` | 列出当前工作区现有顺序中的前 N 个会话;N 必须是正整数。 | | `/session ` | 将当前聊天绑定到指定的已有 Harness 会话。 | diff --git a/docs/bot-commands.md b/docs/bot-commands.md index e92c277..e4f58c2 100644 --- a/docs/bot-commands.md +++ b/docs/bot-commands.md @@ -1,10 +1,10 @@ # Command details -Example: send `/models`, then `/model 2` to switch to the second model in the list; send `/reasoninglist`, then `/reasoning 2` to switch to the current model's second reasoning effort; send `/presetlist`, then `/preset 2` to select the second Agent Preset for this bot. Other examples: `/help`, `/new`, `/status`, `/version`, `/model deepseek-official/deepseek-v4-pro max`, `/reasoning --default`, `/preset marketing-jeep`, `/preset --default`, `/steer inspect only the configuration file`, `/stop`, `/compact`, `/workspace /Users/alice/projects/my-app`, `/sessionlist 2`, `/sessionlist /Users/alice/projects/my-app`, `/session session-id`, `/history`, or `/history 5` +Example: send `/models`, then `/model 2` to switch to the second model in the list; send `/reasoninglist`, then `/reasoning 2` to switch to the current model's second reasoning effort; send `/presetlist`, then `/preset 2` to select the second Agent Preset for this bot. Other examples: `/help`, `/new`, `/status`, `/version`, `/model deepseek-official/deepseek-v4-pro max`, `/reasoning --default`, `/preset marketing-jeep`, `/preset --default`, `/steer inspect only the configuration file`, `/stop`, `/compact`, `/workspace /Users/alice/projects/my-app`, `/ws 2`, `/wsl`, `/sessionlist 2`, `/sessionlist /Users/alice/projects/my-app`, `/session session-id`, `/history`, or `/history 5` If the Slack desktop app has no native Slash Command registered with the same name, it intercepts messages that begin directly with `/`. Send the command with one leading space instead, for example ` /presetlist`, ` /preset 2`, ` /history`, or ` /history 10`; the plugin command layer trims surrounding whitespace, so it executes exactly like the unspaced form. -**Feishu `/` command panel**: On startup the Feishu bot registers its common commands (`menu`, `new`, `help`, `status`, `compact`, `sessionlist`, `workspacelist`, `watch`, `unwatch`, `watchlist`, `archived`) as native Slash Commands through the `app_slash_commands` OpenAPI, so typing `/` in a Feishu direct-message input box pops the command panel and tapping a command triggers it. The command list is owned and pushed by dsh-im; it does not depend on the dsh/Harness backend. Apps created through the built-in QR flow request `application:app_slash_command:read` and `application:app_slash_command:write` by default; existing apps can add them incrementally through **Complete permissions** or `/repair`, followed by any publishing steps Feishu requires. The Feishu client also caches the list for a few minutes. This is best-effort and never blocks message delivery. +**Feishu `/` command panel**: On startup the Feishu bot registers its common commands (`menu`, `new`, `help`, `status`, `compact`, `sessionlist`, `workspacelist`, `workspaces`, `wsl`, `ws`, `watch`, `unwatch`, `watchlist`, `archived`) as native Slash Commands through the `app_slash_commands` OpenAPI, so typing `/` in a Feishu direct-message input box pops the command panel and tapping a command triggers it. The command list is owned and pushed by dsh-im; it does not depend on the dsh/Harness backend. Apps created through the built-in QR flow request `application:app_slash_command:read` and `application:app_slash_command:write` by default; existing apps can add them incrementally through **Complete permissions** or `/repair`, followed by any publishing steps Feishu requires. The Feishu client also caches the list for a few minutes. This is best-effort and never blocks message delivery. - `/help` takes no arguments and never creates a Session. It returns the complete command list supported by the current bot. - `/status` takes no arguments, never prompts the model, and does not change the Session binding. It confirms that the current bot can reach DeepSeek Harness. @@ -24,7 +24,7 @@ If the Slack desktop app has no native Slash Command registered with the same na - Feishu `/repair` is available only in a direct chat and follows the current bot's channel access policy just like every other command; the plugin defines no separate administrator role. It incrementally adds the currently missing `card.action.trigger`, `im:message:readonly`, `im:resource`, `application:app_slash_command:read`, and `application:app_slash_command:write`, while the confirmation page shows only items the app is currently missing. The authorization page must be opened by an account that can access the target app in Feishu Open Platform. Bare `/repair` starts repair; if an older attempt is still awaiting authorization, it invalidates that one-time link before generating a new one. Use `/repair qr` for the current link's QR code, `/repair status` to inspect the attempt, `/repair verify` to refresh verification, and `/repair cancel` to cancel it; none of these four supplemental commands starts another authorization. Once Feishu has accepted the update and the bot is waiting for the test-button callback, a second repair is not started concurrently. - `/compact` acts only on the Harness Session already bound to the current chat and is never sent to the model. The bot reports the applicable status when the chat has no Session yet, the Session is generating a reply, or there is no compactable history. - The path must be an existing absolute directory. The bot returns an actionable error and the correct usage when validation fails. -- `/workspacelist` takes no arguments. It combines the Harness global registry with the current bot's path. When that current path still exists and is safe to display, it appears first and is marked as current. `/workspace N` switches using the freshly resolved list order at execution time; absolute paths remain supported. +- `/workspacelist`, `/workspaces`, and `/wsl` are equivalent and take no arguments. They combine the Harness global registry with the current bot's path. When that current path still exists and is safe to display, it appears first and is marked as current. `/workspace N` and `/ws N` switch using the freshly resolved list order at execution time; absolute paths remain supported. - `/sessionlist` and `/sessions` are equivalent. A numeric argument uses the same freshly resolved order as `/workspacelist` at command execution time. An absolute path can also select a workspace directly, and the result echoes the resolved path. - `/sessionlist --limit N` and `/sessions --limit N` limit only that command's response. They do not change any global or bot setting, and omitting `--limit` still lists every session. - Both session-list aliases include every session registered to the selected workspace. Archived sessions are marked as archived; blank and subagent sessions are included when they belong to that workspace; sessions without a title are shown as `No title yet`. Any listed ID can be passed directly to `/session Session ID`. diff --git a/docs/机器人命令.md b/docs/机器人命令.md index 0682faa..c80dfb3 100644 --- a/docs/机器人命令.md +++ b/docs/机器人命令.md @@ -1,10 +1,10 @@ # 命令说明 -示例:先发送 `/models`,再发送 `/model 2` 切换到列表中的第 2 个模型;先发送 `/reasoninglist`,再发送 `/reasoning 2` 切换到当前模型的第 2 个推理等级;先发送 `/presetlist`,再发送 `/preset 2` 为当前机器人选择第 2 个 Agent Preset。其他命令示例:`/help`、`/new`、`/status`、`/version`、`/model deepseek-official/deepseek-v4-pro max`、`/reasoning --default`、`/preset marketing-jeep`、`/preset --default`、`/steer 只检查配置文件`、`/stop`、`/compact`、`/workspace /Users/alice/projects/my-app`、`/sessionlist 2`、`/sessionlist /Users/alice/projects/my-app`、`/session session-id`、`/history` 或 `/history 5` +示例:先发送 `/models`,再发送 `/model 2` 切换到列表中的第 2 个模型;先发送 `/reasoninglist`,再发送 `/reasoning 2` 切换到当前模型的第 2 个推理等级;先发送 `/presetlist`,再发送 `/preset 2` 为当前机器人选择第 2 个 Agent Preset。其他命令示例:`/help`、`/new`、`/status`、`/version`、`/model deepseek-official/deepseek-v4-pro max`、`/reasoning --default`、`/preset marketing-jeep`、`/preset --default`、`/steer 只检查配置文件`、`/stop`、`/compact`、`/workspace /Users/alice/projects/my-app`、`/ws 2`、`/wsl`、`/sessionlist 2`、`/sessionlist /Users/alice/projects/my-app`、`/session session-id`、`/history` 或 `/history 5` Slack 桌面端若未注册同名的原生 Slash Command,会拦截直接以 `/` 开头的消息。此时请加一个前导空格发送,例如 ` /presetlist`、` /preset 2`、` /history` 或 ` /history 10`;插件命令层会去除首尾空白,执行效果与无空格命令相同。 -**飞书输入框的 `/` 命令面板**:机器人启动时,dsh-im 会调用飞书 `app_slash_commands` OpenAPI,把常用命令(`menu`、`new`、`help`、`status`、`compact`、`sessionlist`、`workspacelist`、`watch`、`unwatch`、`watchlist`、`archived`)注册成原生 Slash Command,这样在飞书单聊输入框输入 `/` 会弹出命令面板,点选即触发。命令列表由 dsh-im 自己持有并推送注册,不依赖 dsh/Harness 后端。扫码新建的应用会默认申请 `application:app_slash_command:read` 和 `application:app_slash_command:write`;已有应用可通过“补全权限”或私聊 `/repair` 增量补全并按飞书提示发布。注册后飞书客户端约有几分钟缓存延迟。该能力是尽力而为的,注册失败不会影响机器人消息收发。 +**飞书输入框的 `/` 命令面板**:机器人启动时,dsh-im 会调用飞书 `app_slash_commands` OpenAPI,把常用命令(`menu`、`new`、`help`、`status`、`compact`、`sessionlist`、`workspacelist`、`workspaces`、`wsl`、`ws`、`watch`、`unwatch`、`watchlist`、`archived`)注册成原生 Slash Command,这样在飞书单聊输入框输入 `/` 会弹出命令面板,点选即触发。命令列表由 dsh-im 自己持有并推送注册,不依赖 dsh/Harness 后端。扫码新建的应用会默认申请 `application:app_slash_command:read` 和 `application:app_slash_command:write`;已有应用可通过“补全权限”或私聊 `/repair` 增量补全并按飞书提示发布。注册后飞书客户端约有几分钟缓存延迟。该能力是尽力而为的,注册失败不会影响机器人消息收发。 - `/help` 不需要参数,也不会创建会话;它会返回当前机器人支持的完整命令列表。 - `/status` 不需要参数,也不会向模型发送消息或改变会话绑定;它用于确认当前机器人能够连接 DeepSeek Harness。 @@ -24,7 +24,7 @@ Slack 桌面端若未注册同名的原生 Slash Command,会拦截直接以 `/ - 飞书 `/repair` 仅在私聊中可用,并与其他命令一样只服从当前飞书机器人的渠道访问策略;插件不另行区分管理员和普通用户。它增量补全当前缺少的 `card.action.trigger`、`im:message:readonly`、`im:resource`、`application:app_slash_command:read` 和 `application:app_slash_command:write`,确认页只显示当前应用缺少的项。授权页必须由在飞书开放平台中有权访问目标应用的账号打开。普通 `/repair` 会启动修复;若旧任务仍在等待授权,会先作废旧的一次性链接再生成新链接。发送 `/repair qr` 获取当前链接的二维码,`/repair status` 查询当前任务,`/repair verify` 重新查询验证状态,`/repair cancel` 取消任务;这四个补充命令均不会另起授权。平台已接受更新、正在等待测试按钮回调时,不会并发启动第二次修复。 - `/compact` 只作用于当前聊天已经绑定的 Harness 会话,不会把命令发送给模型。当前聊天尚未创建会话、会话正在生成回复或没有可压缩历史时,机器人会直接返回对应状态。 - 只接受已经存在的绝对目录;路径无效时机器人会返回具体提示和正确用法。 -- `/workspacelist` 不需要参数。它合并 Harness 全局登记项与当前机器人的路径;当前路径仍存在且可安全显示时会排在首位并标记为“当前”。`/workspace N` 会在执行时按最新列表顺序切换,也可继续使用绝对路径。 +- `/workspacelist`、`/workspaces` 和 `/wsl` 不需要参数且完全等价。它们合并 Harness 全局登记项与当前机器人的路径;当前路径仍存在且可安全显示时会排在首位并标记为“当前”。`/workspace N` 与 `/ws N` 都会在执行时按最新列表顺序切换,也可继续使用绝对路径。 - `/sessionlist` 和 `/sessions` 完全等价。数字参数按命令执行时与 `/workspacelist` 相同的最新顺序解析;也可使用绝对路径直接指定工作区。结果会回显最终选中的路径。 - `/sessionlist --limit N` 和 `/sessions --limit N` 只限制本次命令的返回条数,不改变任何全局或机器人配置。未指定 `--limit` 时仍列出全部会话。 - 两个会话列表命令都会列出该工作区登记的所有会话。已归档会话会标记为“已归档”;空白会话和子代理会话在它们归属该工作区时也会列出;没有标题的会话显示为“暂无标题”。结果中的 ID 可直接用于 `/session Session ID`。 diff --git a/lib/index.js b/lib/index.js index 99a0667..6cc4b6a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -75,7 +75,7 @@ ${m}`,F="",L="",q=Math.min(R,r);nK(f)&&(F+=Pce(f,x,r),_=_.slice(f.length),q-=f.l ${m}${F} ${T}`),Q.pop(),`{${F}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function I(B,f,Q){switch(typeof f){case"string":return bI(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(B),typeof f!="object")return I(B,f,Q);if(f===null)return"null"}if(Q.indexOf(f)!==-1)return o;let y="",m=f.length!==void 0;if(m&&Array.isArray(f)){if(f.length===0)return"[]";if(Ar){let z=f.length-r-1;y+=`,"... ${Qd(z)} not stringified"`}return Q.pop(),`[${y}]`}let T=Object.keys(f),_=T.length;if(_===0)return"{}";if(Ar){let F=_-r;y+=`${R}"...":"${Qd(F)} not stringified"`}return Q.pop(),`{${y}}`}case"number":return isFinite(f)?String(f):t?t(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(i)return String(f);default:return t?t(f):void 0}}function d(B,f,Q){if(arguments.length>1){let y="";if(typeof Q=="number"?y=" ".repeat(Math.min(Q,10)):typeof Q=="string"&&(y=Q.slice(0,10)),f!=null){if(typeof f=="function")return s("",{"":B},[],f,y,"");if(Array.isArray(f))return g("",B,[],KZe(f),y,"")}if(y.length!==0)return c("",B,[],y,"")}return I("",B,[])}return d}});var xce=ee((wGA,Kce)=>{"use strict";var cK=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Hce}=CM(),YZe=Hce.info;function jZe(n,t){n=n||[],t=t||{dedupe:!1};let o=Object.create(Hce);o.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(I=>{o[I]=t.levels[I]});let i={write:e,add:r,remove:s,emit:a,flushSync:A,end:g,minLevel:0,lastId:0,streams:[],clone:c,[cK]:!0,streamLevels:o};return Array.isArray(n)?n.forEach(r,i):r.call(i,n),n=null,i;function e(I){let d,B=this.lastLevel,{streams:f}=this,Q=0,y;for(let m=JZe(f.length,t.dedupe);zZe(m,f.length,t.dedupe);m=qZe(m,t.dedupe))if(d=f[m],d.level<=B){if(Q!==0&&Q!==d.level)break;if(y=d.stream,y[cK]){let{lastTime:T,lastMsg:_,lastObj:R,lastLogger:x}=this;y.lastLevel=B,y.lastTime=T,y.lastMsg=_,y.lastObj=R,y.lastLogger=x}y.write(I),t.dedupe&&(Q=d.level)}else if(!t.dedupe)break}function a(...I){for(let{stream:d}of this.streams)typeof d.emit=="function"&&d.emit(...I)}function A(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync()}function r(I){if(!I)return i;let d=typeof I.write=="function"||I.stream,B=I.write?I:I.stream;if(!d)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:Q}=this,y;typeof I.levelVal=="number"?y=I.levelVal:typeof I.level=="string"?y=Q[I.level]:typeof I.level=="number"?y=I.level:y=YZe;let m={stream:B,level:y,levelVal:void 0,id:++i.lastId};return f.unshift(m),f.sort(Uce),this.minLevel=f[0].level,i}function s(I){let{streams:d}=this,B=d.findIndex(f=>f.id===I);return B>=0&&(d.splice(B,1),d.sort(Uce),this.minLevel=d.length>0?d[0].level:-1),i}function g(){for(let{stream:I}of this.streams)typeof I.flushSync=="function"&&I.flushSync(),I.end()}function c(I){let d=new Array(this.streams.length);for(let B=0;B=0:n{"use strict";var VZe=$e("node:os"),Zce=TH(),WZe=NH(),ZZe=vH(),Xce=Pge(),XZe=vce(),$ce=DE(),{configure:$Ze}=Lce(),{assertDefaultLevelFound:e9e,mappings:eIe,genLsCache:A9e,genLevelComparison:t9e,assertLevelComparison:r9e}=AK(),{DEFAULT_LEVELS:AIe,SORTING_ORDER:a9e}=CM(),{createArgsNormalizer:i9e,asChindings:o9e,buildSafeSonicBoom:Yce,buildFormatters:n9e,stringify:IK,normalizeDestFileDescriptor:jce,noop:s9e}=uM(),{version:g9e}=tK(),{chindingsSym:Jce,redactFmtSym:c9e,serializersSym:qce,timeSym:I9e,timeSliceIndexSym:l9e,streamSym:d9e,stringifySym:zce,stringifySafeSym:lK,stringifiersSym:Vce,setLevelSym:p9e,endSym:h9e,formatOptsSym:E9e,messageKeySym:u9e,errorKeySym:C9e,nestedKeySym:B9e,mixinSym:f9e,levelCompSym:Q9e,useOnlyCustomLevelsSym:y9e,formattersSym:Wce,hooksSym:m9e,nestedKeyStrSym:S9e,mixinMergeStrategySym:w9e,msgPrefixSym:D9e}=$ce,{epochTime:tIe,nullTime:O9e}=Xce,{pid:b9e}=process,M9e=VZe.hostname(),_9e=Zce.err,T9e={level:"info",levelComparison:a9e.ASC,levels:AIe,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:b9e,hostname:M9e},serializers:Object.assign(Object.create(null),{err:_9e}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:tIe,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},N9e=i9e(T9e),R9e=Object.assign(Object.create(null),Zce);function dK(...n){let t={},{opts:o,stream:i}=N9e(t,WZe(),...n);o.level&&typeof o.level=="string"&&AIe[o.level.toLowerCase()]!==void 0&&(o.level=o.level.toLowerCase());let{redact:e,crlf:a,serializers:A,timestamp:r,messageKey:s,errorKey:g,nestedKey:c,base:I,name:d,level:B,customLevels:f,levelComparison:Q,mixin:y,mixinMergeStrategy:m,useOnlyCustomLevels:T,formatters:_,hooks:R,depthLimit:x,edgeLimit:F,onChild:L,msgPrefix:q}=o,z=$Ze({maximumDepth:x,maximumBreadth:F}),H=n9e(_.level,_.bindings,_.log),G=IK.bind({[lK]:z}),V=e?ZZe(e,G):{},U=e?{stringify:V[c9e]}:{stringify:G},N="}"+(a?`\r `:` -`),k=o9e.bind(null,{[Jce]:"",[qce]:A,[Vce]:V,[zce]:IK,[lK]:z,[Wce]:H}),J="";I!==null&&(d===void 0?J=k(I):J=k(Object.assign({},I,{name:d})));let X=r instanceof Function?r:r?tIe:O9e,ie=X().indexOf(":")+1;if(T&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(q&&typeof q!="string")throw Error(`Unknown msgPrefix type "${typeof q}" - expected "string"`);e9e(B,f,T);let we=eIe(f,T);typeof i.emit=="function"&&i.emit("message",{code:"PINO_CONFIG",config:{levels:we,messageKey:s,errorKey:g}}),r9e(Q);let oe=t9e(Q);return Object.assign(t,{levels:we,[Q9e]:oe,[y9e]:T,[d9e]:i,[I9e]:X,[l9e]:ie,[zce]:IK,[lK]:z,[Vce]:V,[h9e]:N,[E9e]:U,[u9e]:s,[C9e]:g,[B9e]:c,[S9e]:c?`,${JSON.stringify(c)}:{`:"",[qce]:A,[f9e]:y,[w9e]:m,[Jce]:J,[Wce]:H,[m9e]:R,silent:s9e,onChild:L,[D9e]:q}),Object.setPrototypeOf(t,XZe()),A9e(t),t[p9e](B),t}dn.exports=dK;dn.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=jce(n.dest||process.stdout.fd),Yce(n)):Yce({dest:jce(n),minLength:0});dn.exports.transport=VH();dn.exports.multistream=xce();dn.exports.levels=eIe();dn.exports.stdSerializers=R9e;dn.exports.stdTimeFunctions=Object.assign({},Xce);dn.exports.symbols=$ce;dn.exports.version=g9e;dn.exports.default=dK;dn.exports.pino=dK});import{unlink as dBe}from"node:fs/promises";import{homedir as pBe}from"node:os";import{join as iu,resolve as KI}from"node:path";import{createHash as Wle,randomUUID as Nx}from"node:crypto";import{mkdir as Zle,readFile as Xle,rename as $le,unlink as Tx,writeFile as ede}from"node:fs/promises";import{dirname as Ade}from"node:path";var hx={"\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002":"This question has already been answered from another client; no further reply is needed.","\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002":"Task completed.",\u7ED3\u679C\u6587\u4EF6:"result file","\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The delivery result of the result file "{name}" could not be confirmed. Please check whether it already arrived in the chat before retrying.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but the Slack app is missing the files:write permission. Please update the Manifest, reinstall the app, reconnect the bot, and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002":'The result file "{name}" was generated, but the bot is missing the Discord Send Messages, Attach Files, or Read Message History permission.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but Telegram does not allow the bot to send documents in this chat. Please check the chat permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but the bot does not have permission to send files. Please check the channel permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" exceeds the size limit of this channel and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" is empty and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" cannot be read or prepared for sending right now. Please make sure the file is still accessible and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was temporarily rate-limited by this channel and could not be sent. Please try again later.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002":'The result file "{name}" was generated, but this channel rejected the file or file message.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but this channel could not send it right now. Please try again later.',"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Failed to process the message. Please try again later.","\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002":"This card has ended. Please check the next message.","\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002":'Tool call "{name}" did not succeed. Check the tool configuration or try again later.',"\u65E0\u6CD5\u8FDE\u63A5\u5904\u7406\u670D\u52A1\uFF0C\u6D88\u606F\u5C1A\u672A\u63D0\u4EA4\u3002\u8BF7\u786E\u8BA4 DeepSeek Harness \u6B63\u5728\u8FD0\u884C\u540E\u91CD\u8BD5\u3002":"Could not connect to the processing service, so the message was not submitted. Make sure DeepSeek Harness is running, then try again.","\u5904\u7406\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u6D88\u606F\u5C1A\u672A\u5F00\u59CB\u5904\u7406\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The processing service timed out before the message started. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u4EFB\u52A1\u72B6\u6001\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The task status could not be confirmed and the task may have started. Wait or send /stop before submitting it again.","\u6D88\u606F\u63D0\u4EA4\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /status \u67E5\u770B\u72B6\u6001\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The message submission could not be confirmed and the task may have started. Wait or send /status before submitting it again.","\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8FDB\u5EA6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Task progress is temporarily unavailable and the task may still be running. Wait or send /stop before submitting it again.","\u5904\u7406\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u8FDE\u63A5\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u3001\u4EE3\u7406\u6216\u8BBF\u95EE\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The processing service rejected the bot connection. Ask an administrator to check the Harness address, proxy, or access settings.","\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u7684\u63A5\u53E3\u4E0D\u517C\u5BB9\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u5E76\u66F4\u65B0\u76F8\u5173\u7248\u672C\u3002":"The bot and DeepSeek Harness use incompatible APIs. Ask an administrator to check the Harness address and update the related components.","DeepSeek Harness \u6682\u65F6\u65E0\u6CD5\u5B8C\u6210\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"DeepSeek Harness could not complete the request. Please try again later.","\u7B49\u5F85\u6A21\u578B\u56DE\u590D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Waiting for the model reply timed out and the task may still be running. Wait or send /stop before submitting it again.","\u6A21\u578B\u51ED\u636E\u7F3A\u5931\u6216\u5DF2\u5931\u6548\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5\u6A21\u578B\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The model credentials are missing or invalid. Ask an administrator to check the model settings.","\u6A21\u578B\u989D\u5EA6\u6216\u4F59\u989D\u4E0D\u8DB3\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7BA1\u7406\u5458\u8865\u5145\u989D\u5EA6\u6216\u5207\u6362\u6A21\u578B\u540E\u91CD\u8BD5\u3002":"The model quota or balance is insufficient. Ask an administrator to add quota or switch models, then try again.","\u6A21\u578B\u670D\u52A1\u6B63\u5728\u9650\u6D41\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is rate-limiting requests. Please try again later.","\u5F53\u524D\u4F1A\u8BDD\u5185\u5BB9\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\u3002\u8BF7\u53D1\u9001 /compact \u6216 /new \u540E\u91CD\u8BD5\u3002":"This conversation exceeds the model context limit. Send /compact or /new, then try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u4F7F\u7528 /model \u5207\u6362\u6A21\u578B\u3002":"The current model does not exist or is unavailable. Send /models and use /model to switch models.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u53D1\u9001 /models\uFF0C\u5E76\u4F7F\u7528 /model \u91CD\u65B0\u9009\u62E9\u3002":"The current model does not exist or does not support the selected settings. Send /models and use /model to choose again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8FD9\u7C7B\u5185\u5BB9\u6216\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u8C03\u6574\u5185\u5BB9\u3001\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support this content or the selected settings. Adjust the content, model, or reasoning effort and try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u5207\u6362\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support the selected settings. Switch the model or reasoning effort, then try again.","\u6A21\u578B\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service timed out and the task did not finish. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unreachable and the task did not finish. Please try again later.","\u6A21\u578B\u670D\u52A1\u6682\u65F6\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unavailable and the task did not finish. Please try again later.","\u6A21\u578B\u56DE\u590D\u4E2D\u65AD\u6216\u683C\u5F0F\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The model reply was interrupted or malformed, so the task did not finish. Please try again.","\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u53EF\u663E\u793A\u7684\u5185\u5BB9\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5207\u6362\u6A21\u578B\u3002":"The model returned no displayable content. Try again, or switch models if this keeps happening.","\u6A21\u578B\u62D2\u7EDD\u5904\u7406\u5F53\u524D\u5185\u5BB9\u3002\u8BF7\u8C03\u6574\u95EE\u9898\u5185\u5BB9\u540E\u91CD\u8BD5\u3002":"The model rejected the current content. Revise the request and try again.","\u6A21\u578B\u8FBE\u5230\u8F93\u51FA\u957F\u5EA6\u4E0A\u9650\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u7ED3\u679C\u3002\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u540E\u91CD\u8BD5\u3002":"The model reached its output limit without producing a displayable result. Reduce the task scope and try again.","\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u65E0\u6CD5\u5728\u5F53\u524D\u6E20\u9053\u5B8C\u6210\u7684\u64CD\u4F5C\u3002\u8BF7\u5728 DeepSeek Harness \u4E2D\u5904\u7406\u540E\u518D\u8BD5\u3002":"The task is waiting for an action that cannot be completed in this channel. Handle it in DeepSeek Harness, then try again.","\u4EFB\u52A1\u88AB\u610F\u5916\u4E2D\u65AD\uFF0C\u672C\u6B21\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The task was unexpectedly interrupted and did not finish. Please try again.","\u5F53\u524D\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\u3002\u8BF7\u53D1\u9001 /new \u521B\u5EFA\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002":"The current Session no longer exists. Send /new to create one, then try again.","\u5F53\u524D\u4F1A\u8BDD\u4ECD\u5728\u5904\u7406\u4E0A\u4E00\u9879\u4EFB\u52A1\u3002\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /stop \u540E\u91CD\u8BD5\u3002":"The current Session is still processing the previous task. Wait for it to finish, or send /stop before trying again.","\u5DE5\u4F5C\u533A\u6216\u4F1A\u8BDD\u72B6\u6001\u521A\u521A\u53D1\u751F\u53D8\u5316\u3002\u8BF7\u91CD\u65B0\u53D1\u9001\u8FD9\u6761\u6D88\u606F\u3002":"The Workspace or Session state just changed. Please send this message again.","\u5F53\u524D\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5DE5\u4F5C\u533A\u540E\u91CD\u8BD5\u3002":"The current Workspace does not exist or is unavailable. Select another Workspace and try again.","\u5F53\u524D Agent Preset \u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /presetlist \u540E\u91CD\u65B0\u9009\u62E9\u3002":"The current Agent Preset does not exist or is unavailable. Send /presetlist and select another one.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u6CA1\u6709\u53D1\u9001\u6743\u9650\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u68C0\u67E5\u6E20\u9053\u6743\u9650\u6216\u91CD\u65B0\u7ED1\u5B9A\u673A\u5668\u4EBA\u3002":"The reply was generated, but the bot cannot send it. Ask an administrator to check channel permissions or reconnect the bot.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6B63\u5728\u9650\u6D41\uFF0C\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel is rate-limiting messages. Please try again later.","\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u7ECF\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Reply delivery could not be confirmed. Check whether it already arrived before submitting the task again.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel could not send it. Please try again later.","\u5F53\u524D\u6D88\u606F\u5305\u542B\u65E0\u6CD5\u5904\u7406\u7684\u56FE\u7247\u6216\u6587\u4EF6\u3002\u8BF7\u8C03\u6574\u540E\u91CD\u65B0\u53D1\u9001\u3002":"This message contains an image or file that cannot be processed. Adjust it and send it again.","\u4EFB\u52A1\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u65E0\u6CD5\u786E\u5B9A\u539F\u56E0\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5C06\u53C2\u8003\u53F7\u63D0\u4F9B\u7ED9\u7BA1\u7406\u5458\u3002":"The task did not finish and the cause could not be determined. Try again; if it persists, give the reference ID to an administrator.","\u9519\u8BEF\u7801\uFF1A{code}\uFF1B\u53C2\u8003\u53F7\uFF1A{referenceId}":"Error code: {code}; reference: {referenceId}","{label}\u673A\u5668\u4EBA":"{label} bot","\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002":"Only text and image messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002":"Only text, image, and file messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002":"Only text, image, file, and voice-transcription messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002":"Only text, image, file, and voice messages already transcribed to text by WeChat are supported at the moment.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text or an image directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, or a file directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, a file, or a voice message already transcribed to text to continue the current session.","{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002":"The {label} bot is connected to DeepSeek Harness.","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD":"/new Start a brand-new session","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587":"/compact Compact the earlier context of the current session","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A":"/workspace Switch workspace","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84":"/workspacelist List absolute workspace paths","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist [workspace index or absolute path] List session IDs and titles","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist or /sessions [workspace index or absolute path] List session IDs and titles","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD":"/sessionlist --limit N List only the first N sessions in the current workspace","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD":"/session Bind this chat to the specified session","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B":"/models List all available models by index","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7":"/reasoninglist or /reasonings List reasoning efforts for the current model by index","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7":"/reasoning [index, effort ID, or --default] Show or switch the current reasoning effort","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] Show or switch the model of the current session","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] [reasoning effort ID] Show or switch the current Session model","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2":"Example: send /models first, then /model 2","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]":"Example: send /models first, then /model 2 [reasoning effort ID]","/presetlist \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist List available Agent Presets by index","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist or /presets List available Agent Presets by index","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset":"/preset [index or full ID] Show or set the Agent Preset of this bot","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:":"Numeric-only ID: /preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4":"/preset --default Follow the Host default","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1":"/stop Stop the current task","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1":"/steer Steer the current task","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001":"/status Check the connection status","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C":"/version Show the plugin version","/help \u663E\u793A\u672C\u5E2E\u52A9":"/help Show this help","{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002":"The {label} bot is connected to DeepSeek Harness and working normally.","{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002":"{label} bot credentials are missing. Remove the bot and connect it again.","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The {label} connection is not ready yet. The plugin will retry automatically.","{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002":"The {label} bot is connected, but its message connection is not ready yet.","{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The {label} connection is still not ready. Please try again later.","{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5":"The {label} bot is not connected yet","{name}\uFF08{id}\uFF09":"{name} ({id})","{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38":"The {label}{connectionLabel} is running normally","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The {label} connection is not ready. The plugin will retry automatically","{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The {label} connection is currently offline","\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002":"A new session has started. Please send your question.","\u6B63\u5728\u4F7F\u7528{name}\u2026":"Using {name}\u2026","\u5DF2\u505C\u6B62\u3002":"Stopped.","\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002":"Please answer the current question with text.","{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002":"Failed to send the {label} interaction question.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002":"Failed to submit the answer.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002":"Failed to submit the answer. Please resend your answer to the current question.","\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":"A pending question left over in this Session was detected. It has been safely cancelled, and your latest message is being processed."};var Ex={"\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09":"Usage: /session Session ID or the session index in the current Workspace (/session N)","\u7528\u6CD5\uFF1A\n/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD\n/sessionlist --limit N \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD\uFF08N \u4E3A\u6B63\u6574\u6570\uFF09\n/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD":`Usage: +`),k=o9e.bind(null,{[Jce]:"",[qce]:A,[Vce]:V,[zce]:IK,[lK]:z,[Wce]:H}),J="";I!==null&&(d===void 0?J=k(I):J=k(Object.assign({},I,{name:d})));let X=r instanceof Function?r:r?tIe:O9e,ie=X().indexOf(":")+1;if(T&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(q&&typeof q!="string")throw Error(`Unknown msgPrefix type "${typeof q}" - expected "string"`);e9e(B,f,T);let we=eIe(f,T);typeof i.emit=="function"&&i.emit("message",{code:"PINO_CONFIG",config:{levels:we,messageKey:s,errorKey:g}}),r9e(Q);let oe=t9e(Q);return Object.assign(t,{levels:we,[Q9e]:oe,[y9e]:T,[d9e]:i,[I9e]:X,[l9e]:ie,[zce]:IK,[lK]:z,[Vce]:V,[h9e]:N,[E9e]:U,[u9e]:s,[C9e]:g,[B9e]:c,[S9e]:c?`,${JSON.stringify(c)}:{`:"",[qce]:A,[f9e]:y,[w9e]:m,[Jce]:J,[Wce]:H,[m9e]:R,silent:s9e,onChild:L,[D9e]:q}),Object.setPrototypeOf(t,XZe()),A9e(t),t[p9e](B),t}dn.exports=dK;dn.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=jce(n.dest||process.stdout.fd),Yce(n)):Yce({dest:jce(n),minLength:0});dn.exports.transport=VH();dn.exports.multistream=xce();dn.exports.levels=eIe();dn.exports.stdSerializers=R9e;dn.exports.stdTimeFunctions=Object.assign({},Xce);dn.exports.symbols=$ce;dn.exports.version=g9e;dn.exports.default=dK;dn.exports.pino=dK});import{unlink as dBe}from"node:fs/promises";import{homedir as pBe}from"node:os";import{join as iu,resolve as KI}from"node:path";import{createHash as Wle,randomUUID as Nx}from"node:crypto";import{mkdir as Zle,readFile as Xle,rename as $le,unlink as Tx,writeFile as ede}from"node:fs/promises";import{dirname as Ade}from"node:path";var hx={"\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002":"This question has already been answered from another client; no further reply is needed.","\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002":"Task completed.",\u7ED3\u679C\u6587\u4EF6:"result file","\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The delivery result of the result file "{name}" could not be confirmed. Please check whether it already arrived in the chat before retrying.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but the Slack app is missing the files:write permission. Please update the Manifest, reinstall the app, reconnect the bot, and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002":'The result file "{name}" was generated, but the bot is missing the Discord Send Messages, Attach Files, or Read Message History permission.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but Telegram does not allow the bot to send documents in this chat. Please check the chat permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" was generated, but the bot does not have permission to send files. Please check the channel permissions.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" exceeds the size limit of this channel and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002":'The result file "{name}" is empty and was not sent.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\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":'The result file "{name}" cannot be read or prepared for sending right now. Please make sure the file is still accessible and try again.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was temporarily rate-limited by this channel and could not be sent. Please try again later.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002":'The result file "{name}" was generated, but this channel rejected the file or file message.',"\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":'The result file "{name}" was generated, but this channel could not send it right now. Please try again later.',"\u6D88\u606F\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Failed to process the message. Please try again later.","\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002":"This card has ended. Please check the next message.","\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002":'Tool call "{name}" did not succeed. Check the tool configuration or try again later.',"\u65E0\u6CD5\u8FDE\u63A5\u5904\u7406\u670D\u52A1\uFF0C\u6D88\u606F\u5C1A\u672A\u63D0\u4EA4\u3002\u8BF7\u786E\u8BA4 DeepSeek Harness \u6B63\u5728\u8FD0\u884C\u540E\u91CD\u8BD5\u3002":"Could not connect to the processing service, so the message was not submitted. Make sure DeepSeek Harness is running, then try again.","\u5904\u7406\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u6D88\u606F\u5C1A\u672A\u5F00\u59CB\u5904\u7406\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The processing service timed out before the message started. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u4EFB\u52A1\u72B6\u6001\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The task status could not be confirmed and the task may have started. Wait or send /stop before submitting it again.","\u6D88\u606F\u63D0\u4EA4\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u7ECF\u5F00\u59CB\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /status \u67E5\u770B\u72B6\u6001\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"The message submission could not be confirmed and the task may have started. Wait or send /status before submitting it again.","\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8FDB\u5EA6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Task progress is temporarily unavailable and the task may still be running. Wait or send /stop before submitting it again.","\u5904\u7406\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u8FDE\u63A5\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u3001\u4EE3\u7406\u6216\u8BBF\u95EE\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The processing service rejected the bot connection. Ask an administrator to check the Harness address, proxy, or access settings.","\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u7684\u63A5\u53E3\u4E0D\u517C\u5BB9\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5 Harness \u5730\u5740\u5E76\u66F4\u65B0\u76F8\u5173\u7248\u672C\u3002":"The bot and DeepSeek Harness use incompatible APIs. Ask an administrator to check the Harness address and update the related components.","DeepSeek Harness \u6682\u65F6\u65E0\u6CD5\u5B8C\u6210\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"DeepSeek Harness could not complete the request. Please try again later.","\u7B49\u5F85\u6A21\u578B\u56DE\u590D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\u3002\u8BF7\u5148\u7B49\u5F85\u6216\u53D1\u9001 /stop\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Waiting for the model reply timed out and the task may still be running. Wait or send /stop before submitting it again.","\u6A21\u578B\u51ED\u636E\u7F3A\u5931\u6216\u5DF2\u5931\u6548\u3002\u8BF7\u7BA1\u7406\u5458\u68C0\u67E5\u6A21\u578B\u914D\u7F6E\u540E\u91CD\u8BD5\u3002":"The model credentials are missing or invalid. Ask an administrator to check the model settings.","\u6A21\u578B\u989D\u5EA6\u6216\u4F59\u989D\u4E0D\u8DB3\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7BA1\u7406\u5458\u8865\u5145\u989D\u5EA6\u6216\u5207\u6362\u6A21\u578B\u540E\u91CD\u8BD5\u3002":"The model quota or balance is insufficient. Ask an administrator to add quota or switch models, then try again.","\u6A21\u578B\u670D\u52A1\u6B63\u5728\u9650\u6D41\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is rate-limiting requests. Please try again later.","\u5F53\u524D\u4F1A\u8BDD\u5185\u5BB9\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\u3002\u8BF7\u53D1\u9001 /compact \u6216 /new \u540E\u91CD\u8BD5\u3002":"This conversation exceeds the model context limit. Send /compact or /new, then try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u4F7F\u7528 /model \u5207\u6362\u6A21\u578B\u3002":"The current model does not exist or is unavailable. Send /models and use /model to switch models.","\u5F53\u524D\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u53D1\u9001 /models\uFF0C\u5E76\u4F7F\u7528 /model \u91CD\u65B0\u9009\u62E9\u3002":"The current model does not exist or does not support the selected settings. Send /models and use /model to choose again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8FD9\u7C7B\u5185\u5BB9\u6216\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u8C03\u6574\u5185\u5BB9\u3001\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support this content or the selected settings. Adjust the content, model, or reasoning effort and try again.","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6240\u9009\u914D\u7F6E\u3002\u8BF7\u5207\u6362\u6A21\u578B\u6216\u63A8\u7406\u7B49\u7EA7\u540E\u91CD\u8BD5\u3002":"The current model does not support the selected settings. Switch the model or reasoning effort, then try again.","\u6A21\u578B\u670D\u52A1\u54CD\u5E94\u8D85\u65F6\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service timed out and the task did not finish. Please try again later.","\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unreachable and the task did not finish. Please try again later.","\u6A21\u578B\u670D\u52A1\u6682\u65F6\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The model service is temporarily unavailable and the task did not finish. Please try again later.","\u6A21\u578B\u56DE\u590D\u4E2D\u65AD\u6216\u683C\u5F0F\u5F02\u5E38\uFF0C\u672C\u6B21\u4EFB\u52A1\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The model reply was interrupted or malformed, so the task did not finish. Please try again.","\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u53EF\u663E\u793A\u7684\u5185\u5BB9\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5207\u6362\u6A21\u578B\u3002":"The model returned no displayable content. Try again, or switch models if this keeps happening.","\u6A21\u578B\u62D2\u7EDD\u5904\u7406\u5F53\u524D\u5185\u5BB9\u3002\u8BF7\u8C03\u6574\u95EE\u9898\u5185\u5BB9\u540E\u91CD\u8BD5\u3002":"The model rejected the current content. Revise the request and try again.","\u6A21\u578B\u8FBE\u5230\u8F93\u51FA\u957F\u5EA6\u4E0A\u9650\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u7ED3\u679C\u3002\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u540E\u91CD\u8BD5\u3002":"The model reached its output limit without producing a displayable result. Reduce the task scope and try again.","\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u65E0\u6CD5\u5728\u5F53\u524D\u6E20\u9053\u5B8C\u6210\u7684\u64CD\u4F5C\u3002\u8BF7\u5728 DeepSeek Harness \u4E2D\u5904\u7406\u540E\u518D\u8BD5\u3002":"The task is waiting for an action that cannot be completed in this channel. Handle it in DeepSeek Harness, then try again.","\u4EFB\u52A1\u88AB\u610F\u5916\u4E2D\u65AD\uFF0C\u672C\u6B21\u672A\u5B8C\u6210\u3002\u8BF7\u91CD\u8BD5\u3002":"The task was unexpectedly interrupted and did not finish. Please try again.","\u5F53\u524D\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\u3002\u8BF7\u53D1\u9001 /new \u521B\u5EFA\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5\u3002":"The current Session no longer exists. Send /new to create one, then try again.","\u5F53\u524D\u4F1A\u8BDD\u4ECD\u5728\u5904\u7406\u4E0A\u4E00\u9879\u4EFB\u52A1\u3002\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /stop \u540E\u91CD\u8BD5\u3002":"The current Session is still processing the previous task. Wait for it to finish, or send /stop before trying again.","\u5DE5\u4F5C\u533A\u6216\u4F1A\u8BDD\u72B6\u6001\u521A\u521A\u53D1\u751F\u53D8\u5316\u3002\u8BF7\u91CD\u65B0\u53D1\u9001\u8FD9\u6761\u6D88\u606F\u3002":"The Workspace or Session state just changed. Please send this message again.","\u5F53\u524D\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5DE5\u4F5C\u533A\u540E\u91CD\u8BD5\u3002":"The current Workspace does not exist or is unavailable. Select another Workspace and try again.","\u5F53\u524D Agent Preset \u4E0D\u5B58\u5728\u6216\u6682\u4E0D\u53EF\u7528\u3002\u8BF7\u53D1\u9001 /presetlist \u540E\u91CD\u65B0\u9009\u62E9\u3002":"The current Agent Preset does not exist or is unavailable. Send /presetlist and select another one.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u6CA1\u6709\u53D1\u9001\u6743\u9650\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u68C0\u67E5\u6E20\u9053\u6743\u9650\u6216\u91CD\u65B0\u7ED1\u5B9A\u673A\u5668\u4EBA\u3002":"The reply was generated, but the bot cannot send it. Ask an administrator to check channel permissions or reconnect the bot.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6B63\u5728\u9650\u6D41\uFF0C\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel is rate-limiting messages. Please try again later.","\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002\u8BF7\u5148\u68C0\u67E5\u804A\u5929\u5185\u662F\u5426\u5DF2\u7ECF\u6536\u5230\uFF0C\u4E0D\u8981\u7ACB\u5373\u91CD\u590D\u63D0\u4EA4\u3002":"Reply delivery could not be confirmed. Check whether it already arrived before submitting the task again.","\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u65E0\u6CD5\u53D1\u9001\u3002\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The reply was generated, but this channel could not send it. Please try again later.","\u5F53\u524D\u6D88\u606F\u5305\u542B\u65E0\u6CD5\u5904\u7406\u7684\u56FE\u7247\u6216\u6587\u4EF6\u3002\u8BF7\u8C03\u6574\u540E\u91CD\u65B0\u53D1\u9001\u3002":"This message contains an image or file that cannot be processed. Adjust it and send it again.","\u4EFB\u52A1\u672A\u5B8C\u6210\uFF0C\u6682\u65F6\u65E0\u6CD5\u786E\u5B9A\u539F\u56E0\u3002\u8BF7\u91CD\u8BD5\uFF1B\u82E5\u6301\u7EED\u53D1\u751F\uFF0C\u8BF7\u5C06\u53C2\u8003\u53F7\u63D0\u4F9B\u7ED9\u7BA1\u7406\u5458\u3002":"The task did not finish and the cause could not be determined. Try again; if it persists, give the reference ID to an administrator.","\u9519\u8BEF\u7801\uFF1A{code}\uFF1B\u53C2\u8003\u53F7\uFF1A{referenceId}":"Error code: {code}; reference: {referenceId}","{label}\u673A\u5668\u4EBA":"{label} bot","\u76EE\u524D\u652F\u6301\u6587\u5B57\u548C\u56FE\u7247\u6D88\u606F\u3002":"Only text and image messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002":"Only text, image, and file messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002":"Only text, image, file, and voice-transcription messages are supported at the moment.","\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002":"Only text, image, file, and voice messages already transcribed to text by WeChat are supported at the moment.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u6216\u56FE\u7247\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text or an image directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, or a file directly to continue the current session.","\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002":"Send text, an image, a file, or a voice message already transcribed to text to continue the current session.","{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002":"The {label} bot is connected to DeepSeek Harness.","/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD":"/new Start a brand-new session","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587":"/compact Compact the earlier context of the current session","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A":"/workspace Switch workspace","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84":"/workspacelist List absolute workspace paths","/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D":"/ws, /wsl, /workspaces Workspace command aliases","/sessionlist [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist [workspace index or absolute path] List session IDs and titles","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898":"/sessionlist or /sessions [workspace index or absolute path] List session IDs and titles","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD":"/sessionlist --limit N List only the first N sessions in the current workspace","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD":"/session Bind this chat to the specified session","/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B":"/models List all available models by index","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7":"/reasoninglist or /reasonings List reasoning efforts for the current model by index","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7":"/reasoning [index, effort ID, or --default] Show or switch the current reasoning effort","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] Show or switch the model of the current session","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B":"/model [index or full model ID] [reasoning effort ID] Show or switch the current Session model","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2":"Example: send /models first, then /model 2","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]":"Example: send /models first, then /model 2 [reasoning effort ID]","/presetlist \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist List available Agent Presets by index","/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset":"/presetlist or /presets List available Agent Presets by index","/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset":"/preset [index or full ID] Show or set the Agent Preset of this bot","\u7EAF\u6570\u5B57 ID\uFF1A/preset id:":"Numeric-only ID: /preset id:","/preset --default \u8DDF\u968F Host \u9ED8\u8BA4":"/preset --default Follow the Host default","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1":"/stop Stop the current task","/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1":"/steer Steer the current task","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001":"/status Check the connection status","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C":"/version Show the plugin version","/help \u663E\u793A\u672C\u5E2E\u52A9":"/help Show this help","{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002":"The {label} bot is connected to DeepSeek Harness and working normally.","{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002":"{label} bot credentials are missing. Remove the bot and connect it again.","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002":"The {label} connection is not ready yet. The plugin will retry automatically.","{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002":"The {label} bot is connected, but its message connection is not ready yet.","{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"The {label} connection is still not ready. Please try again later.","{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5":"The {label} bot is not connected yet","{name}\uFF08{id}\uFF09":"{name} ({id})","{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38":"The {label}{connectionLabel} is running normally","{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5":"The {label} connection is not ready. The plugin will retry automatically","{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF":"The {label} connection is currently offline","\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002":"A new session has started. Please send your question.","\u6B63\u5728\u4F7F\u7528{name}\u2026":"Using {name}\u2026","\u5DF2\u505C\u6B62\u3002":"Stopped.","\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002":"Please answer the current question with text.","{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002":"Failed to send the {label} interaction question.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002":"Failed to submit the answer.","\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002":"Failed to submit the answer. Please resend your answer to the current question.","\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":"A pending question left over in this Session was detected. It has been safely cancelled, and your latest message is being processed."};var Ex={"\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09":"Usage: /session Session ID or the session index in the current Workspace (/session N)","\u7528\u6CD5\uFF1A\n/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD\n/sessionlist --limit N \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD\uFF08N \u4E3A\u6B63\u6574\u6570\uFF09\n/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD\n/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD":`Usage: /sessionlist List Sessions in the current Workspace /sessionlist --limit N List the first N Sessions in the current Workspace (N must be a positive integer) /sessionlist Workspace index List Sessions by /workspacelist index @@ -147,7 +147,7 @@ ${n}`:n)}function g_(n,t,o){return{cardParamMap:{flowStatus:t,msgContent:jE(n,o) `:`${e}
`}).join("")}function c_(n,t){if(!n||typeof n!="object"||n.errcode!==0)throw new ct("registration-rejected",`\u9489\u9489\u626B\u7801${t}\u5931\u8D25\u3002`);return n}function I_(n,t){let o=Number(n);return Number.isFinite(o)&&o>0?o:t}function iY({fetchImpl:n=fetch,registrationBaseUrl:t=process.env.DINGTALK_REGISTRATION_BASE_URL||Xx,registrationSource:o=process.env.DINGTALK_REGISTRATION_SOURCE||Lde,now:i=()=>Date.now(),cardMinIntervalMs:e=50,cardBackoffMs:a=1e3,delay:A=Vde}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");if(typeof i!="function")throw new TypeError("now must be a function");if(!Number.isFinite(e)||e<0)throw new TypeError("cardMinIntervalMs must be a non-negative number");if(!Number.isFinite(a)||a<0)throw new TypeError("cardBackoffMs must be a non-negative number");if(typeof A!="function")throw new TypeError("delay must be a function");let r=l_(t,{label:"\u9489\u9489\u6CE8\u518C\u670D\u52A1",requireSubdomain:!1}),s=new URL(Fde),g=WA(o);if(!g)throw new TypeError("registrationSource is required");let c=new Map,I=new Map,d=new Map,B=Promise.resolve(),f=0,Q=(L,q)=>new URL(q.replace(/^\//,""),L);async function y({clientId:L,clientSecret:q,signal:z,requestKind:H="normal"}){let G=WA(L),V=WA(q);if(!G||!V)throw new TypeError("clientId and clientSecret are required");let U=c.get(G);if(U&&U.expiresAt>i())return U.token;let N=H==="reaction"?d:I;if(N.has(G))return N.get(G);let J=(async()=>{let X=await fn(n,Q(s,"v1.0/oauth2/accessToken"),{body:{appKey:G,appSecret:V},signal:z,action:"\u9274\u6743"}),ie=WA(X?.accessToken);if(!ie)throw new ct("invalid-access-token","\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u8BBF\u95EE\u4EE4\u724C\u3002");let we=I_(X?.expireIn??X?.expiresIn,7200),oe=Math.max(1e3,(we-60)*1e3);return c.set(G,{token:ie,expiresAt:i()+oe}),ie})().finally(()=>N.delete(G));return N.set(G,J),J}async function m({clientId:L,clientSecret:q,robotCode:z,messageId:H,conversationId:G,reactionName:V=kI,signal:U},N){let k=WA(L),J=WA(q),X=WA(z)??k,ie=WA(H),we=WA(G),oe=WA(V);if(!k||!J)throw new TypeError("clientId and clientSecret are required");if(!X)throw new TypeError("robotCode is required");if(!ie||!we)throw new TypeError("messageId and conversationId are required");if(!oe)throw new TypeError("reactionName is required");let Se=await y({clientId:k,clientSecret:J,signal:U,requestKind:"reaction"}),Be=await fn(n,Q(s,`v1.0/robot/emotion/${N}`),{body:{robotCode:X,openMsgId:ie,openConversationId:we,emotionType:2,emotionName:oe,textEmotion:{emotionId:xde,emotionName:oe,text:oe,backgroundId:Yde}},headers:{"x-acs-dingtalk-access-token":Se},signal:U,timeoutMs:Kde,action:N==="reply"?"\u6D88\u606F\u72B6\u6001\u6DFB\u52A0":"\u6D88\u606F\u72B6\u6001\u64A4\u56DE"}),ke=Be?.success===!1?JE(Be?.code??Be?.errcode)??"rejected":DQ(Be);if(ke)throw new ct("reaction-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6D88\u606F\u72B6\u6001\u8BF7\u6C42\u3002",{providerCode:ke});return!0}async function T({clientId:L,clientSecret:q,robotCode:z,downloadCode:H,signal:G,kind:V}){let U=WA(z),N=WA(H);if(!U||!N)throw new TypeError("robotCode and downloadCode are required");let k=await y({clientId:L,clientSecret:q,signal:G}),J;try{J=await fn(n,Q(s,"v1.0/robot/messageFiles/download"),{body:{downloadCode:N,robotCode:U},headers:{"x-acs-dingtalk-access-token":k},signal:G,action:`${V==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740`})}catch(ie){throw G?.aborted?ie:new ct(`${V}-download-address-failed`,`\u9489\u9489${V==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u83B7\u53D6\u5931\u8D25\u3002`,{cause:ie,status:ie?.status,providerCode:ie?.providerCode})}let X=WA(J?.downloadUrl??J?.download_url);if(!X)throw new ct(`invalid-${V}-download`,`\u9489\u9489\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE${V==="image"?"\u56FE\u7247":"\u6587\u4EF6"}\u4E0B\u8F7D\u5730\u5740\u3002`);return zde(X)}function _(L){let q=async()=>{let H=Math.max(0,f-i());H>0&&await A(H,L),f=Math.max(f,i())+e},z=B.then(q,q);return B=z.catch(()=>{}),z}async function R(L,q){await _(q.signal);try{return await fn(n,Q(s,L),q)}catch(z){if(!(z instanceof ct)||z.status!==403)throw z;return await A(a,q.signal),await _(q.signal),fn(n,Q(s,L),q)}}async function x({clientId:L,clientSecret:q,cardInstanceId:z,text:H,target:G,signal:V}){let U=WA(z),N=WA(H);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let J={"x-acs-dingtalk-access-token":await y({clientId:L,clientSecret:q,signal:V})},X=[R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:xE(),key:"msgContent",content:jE(N,G),isFull:!0,isFinalize:!1,isError:!0},headers:J,signal:V,action:"AI Card \u5931\u8D25\u6536\u53E3"}),R("v1.0/card/instances",{method:"PUT",body:{outTrackId:U,cardData:g_(N,"5",G),cardUpdateOptions:{updateCardDataByKey:!0}},headers:J,signal:V,action:"AI Card \u5931\u8D25\u72B6\u6001"})],ie=await Promise.allSettled(X);if(ie.every(({status:we})=>we==="rejected"))throw ie[0].reason;return!0}async function F({clientId:L,clientSecret:q,target:z,file:H,signal:G},{uploadType:V,messageKey:U,createMessageParams:N}){if(!H||typeof H!="object"||typeof H.fileName!="string"||!H.fileName||!Buffer.isBuffer(H.bytes))throw new TypeError("A DingTalk file is required");let k=eY(z),J;try{J=await y({clientId:L,clientSecret:q,signal:G})}catch(ve){if(G?.aborted)throw ts(G);let aA=Number(ve?.status),fe=ve?.code==="http-error"&&aA>=400&&aA<500?"artifact-provider-rejected":"artifact-provider-failed";throw YE(ve,{fallback:fe})}let X=new URL("media/upload",Xx);X.searchParams.set("access_token",J),X.searchParams.set("type",V);let ie=new FormData;ie.append("media",new Blob([H.bytes],{type:H.mediaType??"application/octet-stream"}),H.fileName);let we;try{we=await Wde(n,X,{body:ie,signal:G})}catch(ve){if(G?.aborted)throw ts(G);let aA=Number(ve?.status),fe=ve?.code==="http-error"&&aA>=400&&aA<500?"artifact-provider-rejected":"artifact-provider-failed";throw YE(ve,{fallback:fe})}let oe=DQ(we),Se=WA(we?.media_id);if(oe||!Se)throw YE(new ct("upload-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u3002",{providerCode:oe??"missing-media-id"}));G?.throwIfAborted();let Be={robotCode:k.robotCode,msgKey:U,msgParam:JSON.stringify(N(Se,H)),...k.type==="group"?{openConversationId:k.openConversationId}:{userIds:[k.userId]}},ke=k.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",Re;try{Re=await fn(n,Q(s,ke),{body:Be,headers:{"x-acs-dingtalk-access-token":J},signal:G,action:"\u6587\u4EF6\u6D88\u606F\u53D1\u9001"})}catch(ve){throw qde(ve,G)}let We=DQ(Re);if(We)throw YE(new ct("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:We}));return Re}return Object.freeze({async beginRegistration({signal:L}={}){let q=c_(await fn(n,Q(r,"app/registration/init"),{body:{source:g},signal:L,action:"\u521D\u59CB\u5316"}),"\u521D\u59CB\u5316"),z=WA(q.nonce);if(!z)throw new ct("invalid-registration","\u9489\u9489\u626B\u7801\u521D\u59CB\u5316\u7F3A\u5C11 nonce\u3002");let H=c_(await fn(n,Q(r,"app/registration/begin"),{body:{nonce:z},signal:L,action:"\u521B\u5EFA"}),"\u521B\u5EFA"),G=WA(H.device_code),V=WA(H.verification_uri_complete);if(!G||!V)throw new ct("invalid-registration","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u7684\u4FE1\u606F\u4E0D\u5B8C\u6574\u3002");let U=l_(V,{label:"\u9489\u9489\u626B\u7801",requireSubdomain:!1}).toString();return{deviceCode:G,userCode:WA(H.user_code)??void 0,verificationUri:WA(H.verification_uri)??void 0,verificationUriComplete:U,expiresInSeconds:I_(H.expires_in,7200),intervalSeconds:I_(H.interval,5)}},async pollRegistration({deviceCode:L,signal:q}={}){let z=WA(L);if(!z)throw new TypeError("deviceCode is required");let H=c_(await fn(n,Q(r,"app/registration/poll"),{body:{device_code:z},signal:q,action:"\u72B6\u6001\u67E5\u8BE2"}),"\u72B6\u6001\u67E5\u8BE2"),G=WA(H.status)?.toUpperCase();if(!G||!jde.has(G))throw new ct("invalid-registration-status","\u9489\u9489\u626B\u7801\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u72B6\u6001\u3002");let V={status:G,failReason:WA(H.fail_reason)??void 0};if(G==="SUCCESS"&&(V.clientId=WA(H.client_id)??void 0,V.clientSecret=WA(H.client_secret)??void 0,!V.clientId||!V.clientSecret))throw new ct("missing-credentials","\u9489\u9489\u626B\u7801\u5DF2\u786E\u8BA4\uFF0C\u4F46\u6CA1\u6709\u8FD4\u56DE\u673A\u5668\u4EBA\u51ED\u636E\u3002");return V},accessToken:y,async addReaction(L){return m(L,"reply")},async recallReaction(L){return m(L,"recall")},async addThinkingReaction(L){return m({...L,reactionName:kI},"reply")},async recallThinkingReaction(L){return m({...L,reactionName:kI},"recall")},async downloadImage({clientId:L,clientSecret:q,robotCode:z,downloadCode:H,signal:G,maxBytes:V}){let U=await T({clientId:L,clientSecret:q,robotCode:z,downloadCode:H,signal:G,kind:"image"});try{return await bo(U,{fetchImpl:n,signal:G,maxBytes:V})}catch(N){throw G?.aborted||N instanceof ft?N:new ct("image-content-download-failed","\u9489\u9489\u56FE\u7247\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:N})}},async downloadFile({clientId:L,clientSecret:q,robotCode:z,downloadCode:H,signal:G}){let V=await T({clientId:L,clientSecret:q,robotCode:z,downloadCode:H,signal:G,kind:"file"});if(V.protocol!=="https:")throw new ct("invalid-file-download","\u9489\u9489\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0B\u8F7D\u5730\u5740\u3002");try{let U=await n(V,{method:"GET",redirect:"follow",signal:G});if(!U?.ok)throw await U?.body?.cancel?.().catch?.(()=>{}),new ct("file-content-download-failed",`\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${U?.status??"unknown"}\uFF09\u3002`,{status:U?.status});return Buffer.from(await U.arrayBuffer())}catch(U){throw G?.aborted?ts(G):U instanceof ct?U:new ct("file-content-download-failed","\u9489\u9489\u6587\u4EF6\u5185\u5BB9\u4E0B\u8F7D\u5931\u8D25\u3002",{cause:U})}},async createAiCard({clientId:L,clientSecret:q,target:z,initialText:H,signal:G}){let V=WA(L),U=WA(q),N=WA(H);if(!V||!U)throw new TypeError("clientId and clientSecret are required");if(!N)throw new TypeError("initialText is required");let k=Xde(z),J=await y({clientId:V,clientSecret:U,signal:G}),X=`dsh_${xE()}`,ie={"x-acs-dingtalk-access-token":J},we=!1;try{await R("v1.0/card/instances",{body:{cardTemplateId:Ude,outTrackId:X,cardData:{cardParamMap:{config:JSON.stringify({autoLayout:!0})}},callbackType:"STREAM",cardAtUserIds:k.atUserIds?Object.keys(k.atUserIds):void 0,imGroupOpenSpaceModel:{supportForward:!0},imRobotOpenSpaceModel:{supportForward:!0}},headers:ie,signal:G,action:"AI Card \u521B\u5EFA"}),await R("v1.0/card/instances/deliver",{body:$de(X,k,V),headers:ie,signal:G,action:"AI Card \u6295\u653E"}),we=!0,await R("v1.0/card/instances",{method:"PUT",body:{outTrackId:X,cardData:g_(N,"2",k)},headers:ie,signal:G,action:"AI Card \u542F\u52A8"}),await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:X,guid:xE(),key:"msgContent",content:jE(N,k).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:ie,signal:G,action:"AI Card \u542F\u52A8"})}catch(oe){if(we){let Se=AbortSignal.timeout(5e3);await x({clientId:V,clientSecret:U,cardInstanceId:X,text:w("\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002"),target:k,signal:Se}).catch(()=>{})}throw oe}return{cardInstanceId:X}},async updateAiCard({clientId:L,clientSecret:q,cardInstanceId:z,text:H,target:G,signal:V}){let U=WA(z),N=WA(H);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let k=await y({clientId:L,clientSecret:q,signal:V});return await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:xE(),key:"msgContent",content:jE(N,G).replace(/\n+$/,""),isFull:!0,isFinalize:!1,isError:!1},headers:{"x-acs-dingtalk-access-token":k},signal:V,action:"AI Card \u66F4\u65B0"}),!0},async finishAiCard({clientId:L,clientSecret:q,cardInstanceId:z,text:H,target:G,signal:V}){let U=WA(z),N=WA(H);if(!U)throw new TypeError("cardInstanceId is required");if(!N)throw new TypeError("text is required");let J={"x-acs-dingtalk-access-token":await y({clientId:L,clientSecret:q,signal:V})},X=jE(N,G);await R("v1.0/card/streaming",{method:"PUT",body:{outTrackId:U,guid:xE(),key:"msgContent",content:X,isFull:!0,isFinalize:!0,isError:!1},headers:J,signal:V,action:"AI Card \u5B8C\u6210"});let ie=!0,we={method:"PUT",body:{outTrackId:U,cardData:g_(N,"3",G),cardUpdateOptions:{updateCardDataByKey:!0}},headers:J,signal:V,action:"AI Card \u6536\u53E3"};try{await R("v1.0/card/instances",we)}catch{try{await R("v1.0/card/instances",we)}catch{ie=!1}}return{delivered:!0,completed:ie}},failAiCard:x,async sendText({clientId:L,clientSecret:q,sessionWebhook:z,text:H,at:G,signal:V}){let U=WA(H);if(!U)throw new TypeError("text is required");let N=lc(z),k=await y({clientId:L,clientSecret:q,signal:V}),J=G&&typeof G=="object"&&(Array.isArray(G.atUserIds)&&G.atUserIds.length>0||Array.isArray(G.atMobiles)&&G.atMobiles.length>0||G.isAtAll===!0)?{at:G}:{},X=await fn(n,N,{body:{msgtype:"text",text:{content:U},...J},headers:{"x-acs-dingtalk-access-token":k},signal:V,action:"\u6D88\u606F\u56DE\u590D"});if(X?.errcode!==void 0&&X.errcode!==0||X?.code!==void 0&&X.code!==0)throw new ct("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002");return!0},async sendRobotText({clientId:L,clientSecret:q,target:z,text:H,signal:G}){if(typeof H!="string"||!H.trim())throw new TypeError("text is required");let V=H,U=eY(z),N=await y({clientId:L,clientSecret:q,signal:G}),k={robotCode:U.robotCode,msgKey:"sampleText",msgParam:JSON.stringify({content:V}),...U.type==="group"?{openConversationId:U.openConversationId}:{userIds:[U.userId]}},J=U.type==="group"?"v1.0/robot/groupMessages/send":"v1.0/robot/oToMessages/batchSend",X=await fn(n,Q(s,J),{body:k,headers:{"x-acs-dingtalk-access-token":N},signal:G,action:"\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u53D1\u9001"}),ie=DQ(X);if(ie)throw new ct("send-rejected","\u9489\u9489\u670D\u52A1\u62D2\u7EDD\u4E86\u4E3B\u52A8\u6587\u5B57\u6D88\u606F\u3002",{providerCode:ie});return X},async sendFile(L){return F(L,{uploadType:"file",messageKey:"sampleFile",createMessageParams:(q,z)=>({mediaId:q,fileName:z.fileName,fileType:Zde(z.fileName)})})},async sendImage(L){return F(L,{uploadType:"image",messageKey:"sampleImageMsg",createMessageParams:q=>({photoURL:q})})},clearAccessToken(L){let q=WA(L);q&&c.delete(q)}})}var Ape=500,tpe="\u5361\u7247\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u67E5\u770B\u540E\u7EED\u6D88\u606F\u3002";function d_(n,t){if(typeof n!="string")throw new TypeError(`${t} must be a string`);return n}function oY(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} is required`);return n.trim()}function nY({api:n,clientId:t,clientSecret:o,target:i,signal:e,logger:a=console,updateIntervalMs:A=Ape,clock:r=()=>Date.now(),timer:s={setTimeout:(g,c)=>globalThis.setTimeout(g,c),clearTimeout:g=>globalThis.clearTimeout(g)}}={}){if(!n||typeof n.createAiCard!="function"||typeof n.updateAiCard!="function"||typeof n.finishAiCard!="function")throw new TypeError("DingTalk AI Card API is required");let g=oY(t,"clientId"),c=oY(o,"clientSecret");if(i==null)throw new TypeError("target is required");if(!Number.isFinite(A)||A<0)throw new TypeError("updateIntervalMs must be a non-negative number");if(typeof r!="function")throw new TypeError("clock must be a function");if(typeof s?.setTimeout!="function"||typeof s?.clearTimeout!="function")throw new TypeError("timer must provide setTimeout and clearTimeout");let I=()=>{let N=r();if(!Number.isFinite(N))throw new TypeError("clock must return a finite timestamp");return N};I();let d=e?.aborted?"aborted":"idle",B=null,f=null,Q=null,y=null,m=null,T=null,_=0,R=()=>{Q!==null&&(s.clearTimeout(Q),Q=null)},x=()=>e?.removeEventListener("abort",z),F=N=>{d=N,f=null,R(),x()},L=()=>!B||typeof n.failAiCard!="function"?Promise.resolve(!1):(T||(T=n.failAiCard({...B,text:w(tpe),signal:AbortSignal.timeout(5e3)}).then(()=>!0,()=>!1)),T),q=N=>{d==="failed"||d==="finished"||d==="aborted"||(L(),F("failed"),a?.error?.(`[dsh-dingtalk] AI Card ${N} failed`))};function z(){d==="finished"||d==="failed"||d==="aborted"||(L(),F("aborted"))}d!=="aborted"&&e?.addEventListener("abort",z,{once:!0});let H=()=>{if(d!=="active"||y||f===null)return;let N=Math.max(0,_+A-I());if(N>0){Q=s.setTimeout(()=>{Q=null,H()},N);return}let k=f;f=null,y=(async()=>{try{await n.updateAiCard({...B,text:k,finished:!1}),_=I()}catch{if(e?.aborted||d==="aborted")return;q("update")}})().finally(()=>{y=null,d==="active"&&f!==null&&H()})};return Object.freeze({start:async N=>{if(d_(N,"initialText"),d!=="idle")return!1;d="starting";try{let k=await n.createAiCard({clientId:g,clientSecret:c,target:i,initialText:N,signal:e}),J=typeof k?.cardInstanceId=="string"?k.cardInstanceId.trim():"";if(!J)throw new TypeError("DingTalk did not return a card instance id");return B=Object.freeze({clientId:g,clientSecret:c,target:i,cardInstanceId:J,signal:e}),d!=="starting"?(L(),!1):(_=I(),d="active",!0)}catch{return e?.aborted||d==="aborted"?(F("aborted"),!1):(q("creation"),!1)}},push:N=>{d_(N,"progressText"),d==="active"&&(f=N,!Q&&!y&&H())},finish:N=>{if(d_(N,"finalText"),d==="finished")return Promise.resolve(!0);if(d==="finishing")return m;if(d!=="active")return Promise.resolve(!1);d="finishing",f=null,R();let k=y;return m=(async()=>{if(k&&await k,d!=="finishing")return!1;try{return await n.finishAiCard({...B,text:N}),d!=="finishing"?!1:(F("finished"),!0)}catch{return e?.aborted||d==="aborted"?(F("aborted"),!1):(q("finish"),!1)}})(),m},get providerMessageIds(){return B?.cardInstanceId?[B.cardInstanceId]:[]}})}function OQ(n){return typeof n=="string"&&n.trim()?n.trim():null}function Di(n){return n&&typeof n.id=="string"&&typeof n.question=="string"&&(n.header===void 0||typeof n.header=="string")&&(n.detail===void 0||typeof n.detail=="string")&&(n.multiSelect===void 0||typeof n.multiSelect=="boolean")&&(n.options===void 0||Array.isArray(n.options)&&n.options.every(t=>t&&typeof t.label=="string"&&(t.description===void 0||typeof t.description=="string")))}function Oi(n,t,o,{requiresMention:i=!1}={}){let e=[],a=o>1?`\uFF08${t+1}/${o}\uFF09`:"";e.push(w("DeepSeek Harness \u9700\u8981\u4F60\u8865\u5145\u4FE1\u606F{progress}\uFF1A",{progress:a})),OQ(n.header)&&e.push("",n.header.trim()),e.push("",OQ(n.question)??w("\u8BF7\u8F93\u5165\u4F60\u7684\u56DE\u7B54\u3002")),OQ(n.detail)&&e.push("",n.detail.trim());let A=Array.isArray(n.options)?n.options:[];return A.length>0?(e.push(""),A.forEach((r,s)=>{let g=typeof r?.label=="string"?r.label:"",c=OQ(r?.description);e.push(`${s+1}. ${g}${c?` \u2014 ${c}`:""}`)}),e.push("",n.multiSelect===!0?w("\u8BF7\u56DE\u590D\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF1B\u591A\u9009\u7528\u9017\u53F7\u5206\u9694\uFF0C\u4E5F\u53EF\u8865\u5145\u5176\u4ED6\u5185\u5BB9\u3002"):w("\u8BF7\u56DE\u590D\u4E00\u4E2A\u9009\u9879\u5E8F\u53F7\u6216\u6587\u5B57\uFF0C\u4E5F\u53EF\u76F4\u63A5\u8F93\u5165\u5176\u4ED6\u7B54\u6848\u3002"))):e.push("",w("\u8BF7\u76F4\u63A5\u56DE\u590D\u4F60\u7684\u7B54\u6848\u3002")),i&&e.push("",w("\u7FA4\u804A\u4E2D\u8BF7 @\u673A\u5668\u4EBA \u540E\u53D1\u9001\u7B54\u6848\u3002")),e.join(` `)}function sY(n,t){let o=n.trim();if(!o)return null;if(/^\d+$/.test(o)){let e=t[Number(o)-1];return typeof e?.label=="string"?e.label:null}let i=t.find(e=>e?.label===o);return typeof i?.label=="string"?i.label:null}function bi(n,t){let o=Array.isArray(n.options)?n.options:[];if(o.length===0)return{id:n.id,selected:[],custom:t};let i=sY(t,o);if(n.multiSelect!==!0)return i?{id:n.id,selected:[i]}:{id:n.id,selected:[],custom:t};if(i)return{id:n.id,selected:[i]};let e=[],a=[];for(let A of t.split(/[,,、;;\n]+/)){let r=A.trim();if(!r)continue;let s=sY(r,o);s?e.includes(s)||e.push(s):a.push(r)}return{id:n.id,selected:e,...a.length>0?{custom:a.join("\u3001")}:{}}}var rpe=new Map([["\u6279\u51C6","allowed-once"],["\u540C\u610F","allowed-once"],["yes","allowed-once"],["\u62D2\u7EDD","rejected"],["\u4E0D\u540C\u610F","rejected"],["no","rejected"]]),p_="\u8BF7\u7CBE\u51C6\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\uFF08\u4E5F\u652F\u6301\uFF1A\u540C\u610F / \u4E0D\u540C\u610F / yes / no\uFF09\u3002",ape="\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u95EE\u9898\uFF0C\u518D\u7CBE\u51C6\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\u3002",_d="\u8BE5\u5BA1\u6279\u5DF2\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u590D\u3002",ipe=5*6e4,ope=2048;function Ka(n){return typeof n=="string"?n.trim():""}function h_(n){return Ka(n).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")}function npe(n){return rpe.get(Ka(n).toLowerCase())??null}function cY(n){return n?.type==="approval/requested"&&!!Ka(n.sessionId)&&!!Ka(n.approvalId)&&!!Ka(n.toolName)&&(n.callId===void 0||!!Ka(n.callId))&&(n.reason===void 0||typeof n.reason=="string")}function spe(n){let t=n?.arguments;if(t!==null&&typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return null}if(typeof t!="string")return null;let o=h_(t);if(!o)return t===""?"{}":null;try{return JSON.stringify(JSON.parse(o),null,2)}catch{return o}}function E_(n,{toolCall:t,requiresMention:o=!1,maxArgumentsLength:i=6e3}={}){if(!cY(n))return null;let e=Ka(n.callId);if(!e||Ka(t?.callId)!==e||Ka(t?.name)!==Ka(n.toolName))return null;let a=spe(t);if(!a||a.length>i)return null;let A=[w("DeepSeek Harness \u9700\u8981\u4F60\u7684\u5BA1\u6279\uFF1A"),"",w("\u5DE5\u5177\uFF1A{tool}",{tool:h_(n.toolName)}),w("\u64CD\u4F5C\u53C2\u6570\uFF1A"),a],r=h_(n.reason);return r&&A.push(w("\u539F\u56E0\uFF1A{reason}",{reason:r})),A.push("",w(p_)),o&&A.push("",w("\u7FA4\u804A\u4E2D\u8BF7 @\u673A\u5668\u4EBA \u540E\u53D1\u9001\u5BA1\u6279\u51B3\u5B9A\u3002")),A.join(` `)}function gY(n,t){return{ok:!0,value:{sessionId:n.sessionId,approvalId:n.approvalId,outcome:t}}}function bQ(n){return n==="allowed-once"?w("\u5DF2\u6279\u51C6\uFF0C\u4EC5\u5BF9\u672C\u6B21\u64CD\u4F5C\u6709\u6548\u3002"):n==="rejected"?w("\u5DF2\u62D2\u7EDD\u6B64\u6B21\u64CD\u4F5C\u3002"):w(_d)}var Mi=class{#e;#A;#t=new Map;#r=new Map;#l=new Map;constructor({label:t="IM",logger:o=console}={}){this.#e=t,this.#A=o}hasPending(t){return this.#r.get(t)?.items.some(o=>!o.inactive)===!0}claimReply({key:t,actor:o,text:i,addressed:e=!0,hasPendingQuestion:a=!1,questionCompletion:A,isQuestionPending:r,send:s}){let c=this.#r.get(t)?.items[0],I=npe(i),d=(f,Q=!1)=>({...Q?{resolved:!0}:{},process:async y=>{typeof y=="function"&&await y()===!1||await s(f)}}),B=a&&c&&A&&typeof A.then=="function";return a&&!B?null:!c||c.inactive?(this.#l.get(t)??0)<=Date.now()?(this.#l.delete(t),null):I?d(w(_d),!0):null:c.actor!==o||c.requiresMention&&e!==!0?I?d(w("\u53EA\u6709\u53D1\u8D77\u5F53\u524D\u4EFB\u52A1\u7684\u7528\u6237\u53EF\u4EE5\u5904\u7406\u8FD9\u6761\u5BA1\u6279\u3002")):null:{process:async f=>{let Q=c.presented,m=(c.replyTail??Promise.resolve()).catch(()=>{}).then(async()=>{if(!(typeof f=="function"&&await f()===!1)){if(B){if(await A.catch(()=>{}),c.inactive||c.resolving)return;if(typeof r=="function"&&r()){await s(w(ape));return}}if(await c.activationTask?.catch(()=>{}),await c.presentationTask?.catch(()=>{}),c.inactive||c.resolving){await s(w(_d));return}if(c.send=s,!Q||!c.presented){if(c.presented||await this.#o(c),c.inactive||c.resolving)return;await s(w(p_));return}if(c.submitting){await s(w("\u5BA1\u6279\u51B3\u5B9A\u6B63\u5728\u63D0\u4EA4\uFF0C\u8BF7\u7A0D\u5019\u3002"));return}if(!I){await s(w(p_));return}await this.#i(c,I)}});c.replyTail=m;try{await m}finally{c.replyTail===m&&(c.replyTail=null)}}}}async handleRequested(t,o){if(t?.kind!=="approval")return!1;let i=t.payload,e=Ka(i?.approvalId);if(!Ka(t.rpcId)||!Ka(t.sessionId)||!e||!cY(i)||i.sessionId!==t.sessionId||typeof t.respond!="function")return this.#A.warn?.(`[dsh-im:${this.#e}] ignored an invalid Harness approval`),!0;if(t.recovered===!0)return await this.#c(t,i),!0;let a=this.#t.get(e);if(a)return a.interaction=t,a.toolCall=t.toolCall,a.presented||await this.#o(a),!0;let A=o?.send,r=Ka(o?.key),s=Ka(o?.actor);if(!r||!s||typeof A!="function")return this.#A.warn?.(`[dsh-im:${this.#e}] ignored an approval without a reply route`),await this.#c(t,i),!0;let g=E_(i,{toolCall:t.toolCall,requiresMention:o.requiresMention===!0});if(!g){let d=await this.#c(t,i);return await A(d?w("\u65E0\u6CD5\u5B8C\u6574\u5C55\u793A\u8FD9\u6B21\u64CD\u4F5C\uFF0C\u5DF2\u5B89\u5168\u62D2\u7EDD\u6B64\u6B21\u5BA1\u6279\u3002"):w(_d)),!0}let c={approvalId:e,sessionId:t.sessionId,interaction:t,toolCall:t.toolCall,key:r,actor:s,requiresMention:o.requiresMention===!0,send:A,text:g,presented:!1,presentationTask:null,deliveryCompleted:!1,replyTail:null,submitting:!1,inactive:!1,resolving:!1,closedOutcome:null,resolutionNotified:!1,activationTask:null};this.#t.set(e,c);let I=this.#r.get(r)??{items:[]};return I.items.push(c),this.#r.set(r,I),I.items[0]===c&&await this.#o(c),!0}async handleResolved(t){if(t?.kind!=="approval")return!1;let o=this.#t.get(Ka(t.interactionId));if(!o||(o.resolving=!0,o.activationTask&&await o.activationTask.catch(()=>{}),o.inactive||this.#t.get(o.approvalId)!==o))return!0;let i=o.presentationTask,e=o.presented||i,a=o.send,A=this.#s(o);return await this.#a(A,async()=>{let r=o.presented;i&&(r=await i.then(()=>!0,()=>!1)),e&&r&&(o.resolutionNotified=!0,await a(bQ(t.outcome)).catch(()=>{}))}),!0}async closeRoute(t){let o=this.#r.get(t);if(!o)return;let i=[...o.items];for(let e of i)this.#s(e);await Promise.all(i.map(async e=>{try{await e.interaction.respond(gY(e,"rejected"),{signal:AbortSignal.timeout(5e3)}),e.closedOutcome="rejected",(e.presented||e.deliveryCompleted)&&!e.resolutionNotified&&(e.resolutionNotified=!0,await e.send(bQ("rejected")).catch(()=>{}))}catch(a){a?.code==="interaction-not-pending"?(e.closedOutcome="resolved",(e.presented||e.deliveryCompleted)&&!e.resolutionNotified&&(e.resolutionNotified=!0,await e.send(w(_d)).catch(()=>{}))):this.#A.warn?.(`[dsh-im:${this.#e}] failed to reject a closing approval:`,a)}}))}async#o(t){if(this.#r.get(t.key)?.items[0]!==t||t.inactive||t.resolving||t.presented||(await t.activationTask?.catch(()=>{}),this.#r.get(t.key)?.items[0]!==t||t.inactive||t.resolving||t.presented))return;if(t.presentationTask)return t.presentationTask;let o=Promise.resolve().then(()=>t.send(t.text));t.presentationTask=o;try{await o,t.deliveryCompleted=!0,t.inactive?t.closedOutcome&&!t.resolutionNotified&&(t.resolutionNotified=!0,await t.send(bQ(t.closedOutcome)).catch(()=>{})):t.presented=!0}finally{t.presentationTask===o&&(t.presentationTask=null)}}async#i(t,o){t.submitting=!0;try{await t.interaction.respond(gY(t,o))}catch(a){if(a?.code==="interaction-not-pending"){let A=t.send,r=this.#s(t);await this.#a(r,async()=>{t.resolutionNotified||await A(w(_d)).catch(()=>{})});return}if(t.inactive)return;t.submitting=!1,this.#A.error?.(`[dsh-im:${this.#e}] failed to submit an approval:`,a),await t.send(w("\u5BA1\u6279\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u56DE\u590D\u300C\u6279\u51C6\u300D\u6216\u300C\u62D2\u7EDD\u300D\u3002")).catch(()=>{});return}let i=t.send,e=this.#s(t);await this.#a(e,async()=>{t.resolutionNotified||await i(bQ(o)).catch(()=>{})})}async#a(t,o){let i,e=new Promise(a=>{i=a});t&&(t.activationTask=e);try{await o()}finally{i(),t?.activationTask===e&&(t.activationTask=null)}await this.#n(t)}async#n(t){if(t)try{await this.#o(t)}catch(o){this.#A.error?.(`[dsh-im:${this.#e}] failed to present the next approval:`,o);try{t.interaction.reconnect?.()}catch{}}}#s(t){if(t.inactive)return null;t.inactive=!0,this.#d(t.key),this.#t.delete(t.approvalId);let o=this.#r.get(t.key);if(!o)return null;let i=o.items[0]===t,e=o.items.indexOf(t);return e!==-1&&o.items.splice(e,1),o.items.length===0?(this.#r.delete(t.key),null):i?o.items[0]:null}#d(t){let o=Date.now();for(let[i,e]of this.#l)e<=o&&this.#l.delete(i);for(this.#l.delete(t),this.#l.set(t,o+ipe);this.#l.size>ope;)this.#l.delete(this.#l.keys().next().value)}async#c(t,o){try{return await t.respond({ok:!0,value:{sessionId:t.sessionId,approvalId:o.approvalId,outcome:"rejected"}},{signal:AbortSignal.timeout(5e3)}),!0}catch(i){if(i?.code==="interaction-not-pending")return!1;throw i}}};var u_=new WeakMap;function gpe(n){let t=u_.get(n);return t||(t=new Map,u_.set(n,t)),t}async function ng(n,t,o){let i=typeof n;if(i!=="object"&&i!=="function"||n===null)throw new TypeError("state is required");if(typeof t!="string"||!t)throw new TypeError("conversation key is required");if(typeof o!="function")throw new TypeError("operation is required");let e=gpe(n),a=e.get(t)??Promise.resolve(),A,r=new Promise(s=>{A=s});e.set(t,r),await a;try{return await o()}finally{A(),e.get(t)===r&&(e.delete(t),e.size===0&&u_.delete(n))}}var cpe=/(?:\u001b\]|\u009d)(?:(?!\u0007|\u001b\\)[\s\S])*(?:\u0007|\u001b\\|$)/gu,Ipe=/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/gu,lpe=/\u001b[@-_]/gu,dpe=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu,ppe=/[\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/gu,hpe=/^(?:[\s\S]*?<\/dsh_im_source>\s*)?(?:[\s\S]*?<\/dsh_im_source_guidance>\s*)?(?:[\s\S]*?<\/dsh_im_reply_to>\s*)?/u,Epe=new Intl.Segmenter(void 0,{granularity:"grapheme"});function C_(n){return n.replace(cpe,"").replace(Ipe,"").replace(lpe,"").replace(dpe,"").replace(ppe,"").replace(/\s+/gu," ").trim()}function B_(n,t=60){if(Buffer.byteLength(n,"utf8")<=t)return n;let o="\u2026",i=t-Buffer.byteLength(o,"utf8"),e="";for(let{segment:a}of Epe.segment(n)){if(Buffer.byteLength(e+a,"utf8")>i)break;e+=a}return`${e.trimEnd()}${o}`}function upe(n){return typeof n=="string"?n:Array.isArray(n)?n.filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(` -`):""}function Cpe(n){let t=n?.name??n?.filename??n?.fileName;return typeof t!="string"?"":t.replaceAll("\\","/").split("/").at(-1)?.replace(/[\u0000-\u001f\u007f]/gu,"").trim()??""}function IY({text:n,content:t,files:o}={}){let i=typeof n=="string"?C_(n):"";if(i)return B_(i);let e=C_(upe(t).replace(hpe,""));if(e)return B_(e);let a=Array.isArray(o)?o.map(Cpe).find(Boolean):"",A=a?C_(a):"";return A?B_(A):null}var Sa="workspace-session-stale";function lY(n,t){if(typeof n.workspaceSession=="function")return n.workspaceSession(t);let o={sessionId:t,sessionExists:(...i)=>n.sessionExists(t,...i),models:(...i)=>n.getSessionModels(t,...i),selectModel:(...i)=>n.selectSessionModel(t,...i),isRunning:(...i)=>n.isSessionRunning(t,...i),hasActiveTurn:(...i)=>n.hasActiveTurn(t,...i),stopActiveTurn:(...i)=>n.stopActiveTurn(t,...i),steerActiveTurn:(...i)=>n.steerActiveTurn(t,...i),ask:(...i)=>n.ask(t,...i)};return typeof n.renameSession=="function"&&(o.renameTitle=(...i)=>n.renameSession(t,...i)),Object.freeze(o)}async function Bpe(n,t){return t===void 0?n.sessionExists():n.sessionExists(t)}async function fpe(n,t){return t===void 0?n.createSession():n.createSession(t)}async function _i({harness:n,state:t,key:o,text:i,content:e,contextEnhanced:a=!1,createOptions:A,existsOptions:r,askOptions:s}){let g=a?IY({text:i,content:e,files:typeof s=="object"?s?.files:void 0}):null,c=A?.signal??(typeof s=="object"?s?.signal:void 0),I=c?{signal:c}:void 0;for(;;)try{let d=await ng(t,o,async()=>{let m=t.sessionFor(o),T=m?lY(n,m):null;if(!T||!await Bpe(T,r)){if(m=await fpe(n,A),await t.setSession(o,m)===!1)return null;if(T=lY(n,m),g&&typeof T.renameTitle=="function")try{await T.renameTitle(g,I)}catch(_){if(_?.code===Sa||I?.signal?.aborted)throw _;console.warn("[dsh-im] unable to set the initial Session title:",_?.message??_)}}return{sessionId:m,session:T}});if(!d)continue;let B=[],f=typeof s=="object"&&typeof s?.onArtifact=="function"?s.onArtifact:null,Q=typeof s=="number"?{timeoutMs:s}:{...s};Q.onArtifact=async m=>{B.push(m),await f?.(m)};let y=await d.session.ask(e??i,Q);return{sessionId:d.sessionId,answer:y,...B.length>0?{artifacts:B}:{}}}catch(d){if(d?.code!==Sa)throw d}}var pY=/^\/compact(?=$|\s)([\s\S]*)$/i,Qpe="\u7528\u6CD5\uFF1A/compact\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",dY=new Map([["No compactable history yet.","\u6682\u65E0\u53EF\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55\u3002"],["Compaction is unavailable because this process has an active compaction, or the agent is not idle.","\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\u6216\u6267\u884C\u538B\u7F29\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"],["Compaction cancelled.","\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"],["The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.","\u538B\u7F29\u671F\u95F4\u4F1A\u8BDD\u5386\u53F2\u53D1\u751F\u53D8\u5316\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u8BD5\u3002"],["Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.","\u672A\u80FD\u751F\u6210\u6709\u6548\u7684\u538B\u7F29\u6458\u8981\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\u3002"],["Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.","\u4E0A\u4E0B\u6587\u538B\u7F29\u672A\u6B63\u5E38\u5B8C\u6210\uFF0C\u90E8\u5206\u4F1A\u8BDD\u5386\u53F2\u53EF\u80FD\u5DF2\u53D8\u5316\uFF0C\u8BF7\u68C0\u67E5\u4F1A\u8BDD\u540E\u518D\u91CD\u8BD5\u3002"],["Compaction finished, but the session could not be saved.","\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29\uFF0C\u4F46\u4F1A\u8BDD\u4FDD\u5B58\u5931\u8D25\u3002"]]);function vI(n){return{handled:!0,message:n,messages:[n]}}function ype(n){if(!n||typeof n!="object"||!["success","error"].includes(n.kind)||n.text!==void 0&&typeof n.text!="string")throw new TypeError("Harness returned an invalid /compact result");let t=n.text?.trim()??"",o=/^Compacted (\d+) history items \(~(\d+) tokens\)\.$/u.exec(t);return o?w("\u5DF2\u538B\u7F29 {count} \u6761\u5386\u53F2\u8BB0\u5F55\uFF08\u7EA6 {tokens} \u4E2A token\uFF09\u3002",{count:o[1],tokens:o[2]}):dY.has(t)?w(dY.get(t)):t||(n.kind==="success"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\u3002"))}function mpe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u542F\u4F1A\u8BDD\u3002"):t==="agent-busy"?w("\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):t==="cancelled"||n?.name==="AbortError"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"):t===Sa||t==="workspace-bot-not-found"?w("\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002"):t==="commands-unavailable"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u4ECE\u673A\u5668\u4EBA\u6267\u884C\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}async function Ti(n,t,o,i,e={}){if(!f_(n))return null;if(pY.exec(n.trim())[1].trim())return vI(w(Qpe));if(typeof o?.sessionFor!="function")return vI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u53EF\u7528\u7684\u4F1A\u8BDD\u72B6\u6001\u3002"));let A=o.sessionFor(i);if(typeof A!="string"||!A)return vI(w("\u5F53\u524D\u804A\u5929\u8FD8\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u4E00\u6761\u6D88\u606F\u3002"));if(typeof t?.executeCommand!="function")return vI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6682\u4E0D\u652F\u6301\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"));try{let r=await t.executeCommand(A,"/compact",e);return vI(r===void 0?w("\u5F53\u524D Harness \u672A\u6CE8\u518C /compact \u547D\u4EE4\uFF0C\u8BF7\u786E\u8BA4\u4E0A\u4E0B\u6587\u538B\u7F29\u7EC4\u4EF6\u5DF2\u542F\u7528\u3002"):ype(r?.result))}catch(r){return vI(mpe(r))}}function f_(n){return typeof n=="string"&&pY.test(n.trim())}import{isDeepStrictEqual as Ppe}from"node:util";import{realpath as uY,stat as CY}from"node:fs/promises";import{isAbsolute as BY,resolve as Spe}from"node:path";var fY=/^\/workspace(?:\s+([\s\S]+))?$/i,QY=/^\/workspacelist(?:\s+([\s\S]+))?$/i,yY=/^\/(?:sessionlist|sessions)(?:\s+([\s\S]+))?$/i,mY=/^\/session(?=$|\s)/i,wpe=/^\/session[ \t]+([^\s]+)$/i,Dpe=4096,Ope=1800,bpe=256,SY=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,Mpe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu,wY="\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09",PI=["\u7528\u6CD5\uFF1A","/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD","/sessionlist --limit N \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD\uFF08N \u4E3A\u6B63\u6574\u6570\uFF09","/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD","/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD"].join(` +`):""}function Cpe(n){let t=n?.name??n?.filename??n?.fileName;return typeof t!="string"?"":t.replaceAll("\\","/").split("/").at(-1)?.replace(/[\u0000-\u001f\u007f]/gu,"").trim()??""}function IY({text:n,content:t,files:o}={}){let i=typeof n=="string"?C_(n):"";if(i)return B_(i);let e=C_(upe(t).replace(hpe,""));if(e)return B_(e);let a=Array.isArray(o)?o.map(Cpe).find(Boolean):"",A=a?C_(a):"";return A?B_(A):null}var Sa="workspace-session-stale";function lY(n,t){if(typeof n.workspaceSession=="function")return n.workspaceSession(t);let o={sessionId:t,sessionExists:(...i)=>n.sessionExists(t,...i),models:(...i)=>n.getSessionModels(t,...i),selectModel:(...i)=>n.selectSessionModel(t,...i),isRunning:(...i)=>n.isSessionRunning(t,...i),hasActiveTurn:(...i)=>n.hasActiveTurn(t,...i),stopActiveTurn:(...i)=>n.stopActiveTurn(t,...i),steerActiveTurn:(...i)=>n.steerActiveTurn(t,...i),ask:(...i)=>n.ask(t,...i)};return typeof n.renameSession=="function"&&(o.renameTitle=(...i)=>n.renameSession(t,...i)),Object.freeze(o)}async function Bpe(n,t){return t===void 0?n.sessionExists():n.sessionExists(t)}async function fpe(n,t){return t===void 0?n.createSession():n.createSession(t)}async function _i({harness:n,state:t,key:o,text:i,content:e,contextEnhanced:a=!1,createOptions:A,existsOptions:r,askOptions:s}){let g=a?IY({text:i,content:e,files:typeof s=="object"?s?.files:void 0}):null,c=A?.signal??(typeof s=="object"?s?.signal:void 0),I=c?{signal:c}:void 0;for(;;)try{let d=await ng(t,o,async()=>{let m=t.sessionFor(o),T=m?lY(n,m):null;if(!T||!await Bpe(T,r)){if(m=await fpe(n,A),await t.setSession(o,m)===!1)return null;if(T=lY(n,m),g&&typeof T.renameTitle=="function")try{await T.renameTitle(g,I)}catch(_){if(_?.code===Sa||I?.signal?.aborted)throw _;console.warn("[dsh-im] unable to set the initial Session title:",_?.message??_)}}return{sessionId:m,session:T}});if(!d)continue;let B=[],f=typeof s=="object"&&typeof s?.onArtifact=="function"?s.onArtifact:null,Q=typeof s=="number"?{timeoutMs:s}:{...s};Q.onArtifact=async m=>{B.push(m),await f?.(m)};let y=await d.session.ask(e??i,Q);return{sessionId:d.sessionId,answer:y,...B.length>0?{artifacts:B}:{}}}catch(d){if(d?.code!==Sa)throw d}}var pY=/^\/compact(?=$|\s)([\s\S]*)$/i,Qpe="\u7528\u6CD5\uFF1A/compact\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",dY=new Map([["No compactable history yet.","\u6682\u65E0\u53EF\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55\u3002"],["Compaction is unavailable because this process has an active compaction, or the agent is not idle.","\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\u6216\u6267\u884C\u538B\u7F29\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"],["Compaction cancelled.","\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"],["The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.","\u538B\u7F29\u671F\u95F4\u4F1A\u8BDD\u5386\u53F2\u53D1\u751F\u53D8\u5316\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u8BD5\u3002"],["Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.","\u672A\u80FD\u751F\u6210\u6709\u6548\u7684\u538B\u7F29\u6458\u8981\uFF0C\u672C\u6B21\u672A\u4FEE\u6539\u4F1A\u8BDD\u3002"],["Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.","\u4E0A\u4E0B\u6587\u538B\u7F29\u672A\u6B63\u5E38\u5B8C\u6210\uFF0C\u90E8\u5206\u4F1A\u8BDD\u5386\u53F2\u53EF\u80FD\u5DF2\u53D8\u5316\uFF0C\u8BF7\u68C0\u67E5\u4F1A\u8BDD\u540E\u518D\u91CD\u8BD5\u3002"],["Compaction finished, but the session could not be saved.","\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29\uFF0C\u4F46\u4F1A\u8BDD\u4FDD\u5B58\u5931\u8D25\u3002"]]);function vI(n){return{handled:!0,message:n,messages:[n]}}function ype(n){if(!n||typeof n!="object"||!["success","error"].includes(n.kind)||n.text!==void 0&&typeof n.text!="string")throw new TypeError("Harness returned an invalid /compact result");let t=n.text?.trim()??"",o=/^Compacted (\d+) history items \(~(\d+) tokens\)\.$/u.exec(t);return o?w("\u5DF2\u538B\u7F29 {count} \u6761\u5386\u53F2\u8BB0\u5F55\uFF08\u7EA6 {tokens} \u4E2A token\uFF09\u3002",{count:o[1],tokens:o[2]}):dY.has(t)?w(dY.get(t)):t||(n.kind==="success"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\u3002"))}function mpe(n){let t=n?.code??n?.failure?.code;return t==="session-not-found"?w("\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u5DF2\u4E0D\u5B58\u5728\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u542F\u4F1A\u8BDD\u3002"):t==="agent-busy"?w("\u5F53\u524D\u4F1A\u8BDD\u6B63\u5728\u751F\u6210\u56DE\u590D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):t==="cancelled"||n?.name==="AbortError"?w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u53D6\u6D88\u3002"):t===Sa||t==="workspace-bot-not-found"?w("\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002"):t==="commands-unavailable"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u4ECE\u673A\u5668\u4EBA\u6267\u884C\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"):w("\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}async function Ti(n,t,o,i,e={}){if(!f_(n))return null;if(pY.exec(n.trim())[1].trim())return vI(w(Qpe));if(typeof o?.sessionFor!="function")return vI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6CA1\u6709\u53EF\u7528\u7684\u4F1A\u8BDD\u72B6\u6001\u3002"));let A=o.sessionFor(i);if(typeof A!="string"||!A)return vI(w("\u5F53\u524D\u804A\u5929\u8FD8\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u4E00\u6761\u6D88\u606F\u3002"));if(typeof t?.executeCommand!="function")return vI(w("\u5F53\u524D\u673A\u5668\u4EBA\u6682\u4E0D\u652F\u6301\u4E0A\u4E0B\u6587\u538B\u7F29\u3002"));try{let r=await t.executeCommand(A,"/compact",e);return vI(r===void 0?w("\u5F53\u524D Harness \u672A\u6CE8\u518C /compact \u547D\u4EE4\uFF0C\u8BF7\u786E\u8BA4\u4E0A\u4E0B\u6587\u538B\u7F29\u7EC4\u4EF6\u5DF2\u542F\u7528\u3002"):ype(r?.result))}catch(r){return vI(mpe(r))}}function f_(n){return typeof n=="string"&&pY.test(n.trim())}import{isDeepStrictEqual as Ppe}from"node:util";import{realpath as uY,stat as CY}from"node:fs/promises";import{isAbsolute as BY,resolve as Spe}from"node:path";var fY=/^\/(?:workspace|ws)(?:\s+([\s\S]+))?$/i,QY=/^\/(?:workspacelist|workspaces|wsl)(?:\s+([\s\S]+))?$/i,yY=/^\/(?:sessionlist|sessions)(?:\s+([\s\S]+))?$/i,mY=/^\/session(?=$|\s)/i,wpe=/^\/session[ \t]+([^\s]+)$/i,Dpe=4096,Ope=1800,bpe=256,SY=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u,Mpe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu,wY="\u7528\u6CD5\uFF1A/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7\uFF08/session N\uFF09",PI=["\u7528\u6CD5\uFF1A","/sessionlist \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u4F1A\u8BDD","/sessionlist --limit N \u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD\uFF08N \u4E3A\u6B63\u6574\u6570\uFF09","/sessionlist \u5DE5\u4F5C\u533A\u5E8F\u53F7 \u6309 /workspacelist \u5E8F\u53F7\u5217\u51FA\u4F1A\u8BDD","/sessionlist \u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84 \u5217\u51FA\u6307\u5B9A\u5DE5\u4F5C\u533A\u4F1A\u8BDD"].join(` `);function _t(n,t=[n]){return{handled:!0,message:n,messages:t}}function Td(n){return typeof n!="string"||n.length>Dpe||!BY(n)||SY.test(n)?null:Spe(n)}function MQ(n){return typeof n!="string"?"":n.replace(Mpe," ").replace(/\s+/gu," ").trim()}function hY(n){return typeof n=="string"&&n.length>0&&n.length<=bpe&&!new RegExp("\\p{White_Space}","u").test(n)&&!SY.test(n)}function m_(n){let t=typeof n=="string"?n.trim():"";if(!t)return{selector:"",limit:null};if(!t.toLowerCase().startsWith("--limit"))return{selector:t,limit:null};let o=/^--limit[ \t]+(\d+)$/iu.exec(t),i=o?Number(o[1]):null;return!Number.isSafeInteger(i)||i<1?{error:w(PI)}:{selector:"",limit:i}}async function Q_(n){let t=await Promise.all(n.map(async o=>{let i=Td(o);if(!i)return null;try{return(await CY(i)).isDirectory()?Td(await uY(i)):null}catch{return null}}));return[...new Set(t.filter(Boolean))]}async function y_(n){if(typeof n!="string"||!BY(n.trim()))return{error:w(`\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002 {usage}`,{usage:w(PI)})};let t=Td(n.trim());if(!t)return{error:w(`\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5305\u542B\u4E0D\u652F\u6301\u7684\u5B57\u7B26\u6216\u957F\u5EA6\u8D85\u8FC7\u9650\u5236\u3002 {usage}`,{usage:w(PI)})};let o;try{o=await CY(t)}catch{return{error:w(`\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002 @@ -221,7 +221,7 @@ ${o}`);return[w("\u4EE5\u4E0B\u662F\u7528\u6237\u901A\u8FC7\u6279\u91CF\u8F93\u5 ${o}`:o}function vo(n){return n instanceof ko?n.userMessage:null}import{createHash as p1,randomUUID as h1}from"node:crypto";import{constants as zE}from"node:fs";import{copyFile as sEe,lstat as g1,mkdtemp as gEe,open as E1,realpath as cEe,unlink as u1}from"node:fs/promises";import{tmpdir as IEe}from"node:os";import{basename as lEe,extname as dEe,isAbsolute as pEe,join as C1,resolve as hEe}from"node:path";var PQ="dsh_im_return_file",vQ="dsh-im-outbound-artifact",H_=64*1024,EEe=new Map([[".csv","text/csv"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".gif","image/gif"],[".html","text/html"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".json","application/json"],[".md","text/markdown"],[".pdf","application/pdf"],[".png","image/png"],[".rar","application/vnd.rar"],[".txt","text/plain"],[".webp","image/webp"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".xml","application/xml"],[".zip","application/zip"]]),dg=new WeakMap,B1=new WeakMap,VE=new WeakMap,c1;function uEe(){return c1??=gEe(C1(IEe(),"dsh-im-outbound-")),c1}function lg(n,t){let o=new Error(t);return o.code=n,o}function I1(n){let t=n?.session?.events;if(!Array.isArray(t))return null;let o=null;for(let i of t)i?.type==="turn/start"?o=Number.isInteger(i.data?.turn)?i.data.turn:null:i?.type==="turn/end"&&i.data?.turn===o&&(o=null);return Number.isInteger(o)&&o>=0?o:null}function l1(n){let t=n?.id??n?.header?.id;return typeof t=="string"&&t?t:null}function Ig(n,t){return`${n}\0${t}`}function d1(n,t){return`${n}\0${t}`}function CEe(n){let t=String(n??"").replace(/[\u0000-\u001f\u007f]/g," ").replace(new RegExp("\\p{Cf}","gu"),"").replace(/\s+/g," ").trim();return t?[...t].slice(0,255).join(""):"result.bin"}function BEe(n){return EEe.get(dEe(n).toLowerCase())??"application/octet-stream"}function fEe(n){return p1("sha256").update(n).digest("hex")}function QEe(n,t){return typeof n?.dev=="bigint"&&typeof n?.ino=="bigint"&&typeof n?.size=="bigint"&&typeof n?.mtimeNs=="bigint"&&typeof n?.ctimeNs=="bigint"&&n.dev===t?.dev&&n.ino===t?.ino&&n.size===t?.size&&n.mtimeNs===t?.mtimeNs&&n.ctimeNs===t?.ctimeNs}async function yEe(n,t){let o;try{o=await E1(n,zE.O_RDONLY);let i=p1("sha256"),e=o.createReadStream({autoClose:!1,highWaterMark:H_,...t?{signal:t}:{}});for await(let a of e)t?.throwIfAborted(),i.update(a);return i.digest("hex")}finally{await o?.close().catch(()=>{})}}async function mEe(n,t,{signal:o,errorCode:i="artifact-changed",errorMessage:e="The result file changed while it was being read."}={}){let a=()=>lg(i,e);if(!Number.isSafeInteger(t)||t<0)throw a();o?.throwIfAborted();let A;try{A=Buffer.allocUnsafe(t)}catch{throw a()}if(typeof n?.createReadStream=="function"){let g=n.createReadStream({autoClose:!1,start:0,end:t,highWaterMark:H_,...o?{signal:o}:{}}),c=0;for await(let I of g){o?.throwIfAborted();let d=Buffer.isBuffer(I)?I:Buffer.from(I);if(c+d.length>t)throw a();d.copy(A,c),c+=d.length}if(c!==t)throw a();return A}let r=0;for(;rg)throw a();r+=I}o?.throwIfAborted();let s=Buffer.allocUnsafe(1);if((await n.read(s,0,1,t))?.bytesRead!==0)throw a();return A}async function SEe(n,t,o){o?.throwIfAborted();let i;try{let e=pEe(t)?t:hEe(n,t),a=await cEe(e);if(!(await g1(a,{bigint:!0})).isFile())throw lg("artifact-not-file","The requested path is not a file.");let r=await uEe();i=C1(r,`${h1()}.artifact`),await sEe(a,i,zE.COPYFILE_EXCL),o?.throwIfAborted();let s=await g1(i,{bigint:!0}),g=Number(s.size);if(!s.isFile()||!Number.isSafeInteger(g)||g<0)throw lg("artifact-unavailable","The file could not be prepared for delivery.");let c=CEe(lEe(e));return Object.freeze({fileName:c,mediaType:BEe(c),size:g,digest:await yEe(i,o),storagePath:i})}catch(e){throw i&&await u1(i).catch(()=>{}),e?.code?.startsWith?.("artifact-")?e:o?.aborted?o.reason??e:lg("artifact-unavailable","The requested file is unavailable.")}}function f1(n){return Object.freeze({artifactId:n.artifactId,fileName:n.fileName,size:n.size})}function kQ(n){return n.artifactId}function is(n){let t=dg.get(n);if(!t)return;if(t.releaseRequested=!0,t.materializing>0){t.cleanupRequested=!0;return}let o=[...VE.get(n)??[]];if(o.length>0){t.cleanupDeferred||(t.cleanupDeferred=!0,Promise.allSettled(o).finally(()=>{t.cleanupDeferred=!1,is(n)}));return}dg.delete(n),VE.delete(n),t.onCleanup?.(),u1(t.path).catch(()=>{})}var K_=class{#e=new Map;#A=new Map;#t=new Map;#r=new Map;#l=new Map;#o=new Map;#i=new Map;#a=new Map;#n;constructor({uuid:t=h1}={}){if(typeof t!="function")throw new TypeError("uuid must be a function");this.#n=t}openConsumer(t,o){if(typeof t!="string"||!t||typeof o!="string"||!o)throw new TypeError("sessionId and promptRpcId are required");let i=d1(t,o),e={sessionId:t,promptRpcId:o,turn:null,released:!1};return this.#o.set(i,e),()=>{if(!e.released&&(e.released=!0,this.#o.get(i)===e&&this.#o.delete(i),e.turn!==null)){let a=Ig(t,e.turn);this.#i.get(a)===e&&this.#i.delete(a),this.discard(t,e.turn)}}}observeSessionEvent(t,o){let i=l1(t);if(!i||!o||typeof o!="object")return;if(o.type==="turn/start"){let A=o.data?.turn;Number.isInteger(A)&&A>=0&&this.#a.set(i,A);return}if(o.type==="user/message"){let A=o.data?.source?.rpcId,r=this.#a.get(i)??I1({session:t});if(typeof A!="string"||!A||!Number.isInteger(r))return;this.#a.set(i,r);let s=this.#o.get(d1(i,A));if(!s||s.released)return;s.turn=r,this.#i.set(Ig(i,r),s);return}if(o.type!=="turn/end")return;let e=o.data?.turn;if(!Number.isInteger(e)||e<0)return;this.#a.get(i)===e&&this.#a.delete(i);let a=this.#i.get(Ig(i,e));(!a||a.released)&&this.discard(i,e)}disposeSession(t){let o=l1(t);if(!o)return;let i=`${o}\0`,e=new Set;for(let a of[this.#e,this.#A])for(let[A,r]of a)if(A.startsWith(i)){for(let s of r.values())e.add(s);a.delete(A)}for(let[a,A]of this.#o)a.startsWith(i)&&(A.released=!0,this.#o.delete(a));for(let a of this.#i.keys())a.startsWith(i)&&this.#i.delete(a);this.#a.delete(o);for(let a of e)is(a)}async stage(t,o){let i=t?.path;if(typeof i!="string"||!i.trim())throw new TypeError("A file path is required.");let e=o?.agent,a=e?.session?.header?.id,A=e?.session?.header?.cwd,r=I1(e);if(typeof a!="string"||!a||typeof A!="string"||!A||r===null)throw lg("artifact-context-required","A live Harness Session is required to return a file.");let s=await SEe(A,i,o?.signal),{storagePath:g,...c}=s,I=Object.freeze({kind:vQ,schemaVersion:1,artifactId:this.#n(),deliveryKey:this.#n(),...c,source:"managed-temp",registeredBy:Object.freeze({kind:"tool-result",eventId:typeof o?.callId=="string"?o.callId:"unknown",toolName:PQ}),origin:Object.freeze({sessionId:a,turn:r,callId:typeof o?.callId=="string"?o.callId:null}),createdAt:Date.now()});dg.set(I,{path:g,materializing:0,materialized:!1,releaseRequested:!1,cleanupRequested:!1,cleanupDeferred:!1,onCleanup:()=>this.#c(I)});let d=Ig(a,r),B=this.#A.get(d);return B||(B=new Map,this.#A.set(d,B)),B.set(kQ(I),I),I}commit(t){if(t?.kind!==vQ||!dg.has(t))return null;let o=Ig(t.origin.sessionId,t.origin.turn),i=kQ(t),e=this.#A.get(o);if(e?.get(i)!==t)return null;e.delete(i),e.size===0&&this.#A.delete(o);let a=this.#e.get(o);return a||(a=new Map,this.#e.set(o,a)),a.set(i,t),f1(t)}release(t){if(t?.kind!==vQ)return;let o=Ig(t.origin.sessionId,t.origin.turn),i=kQ(t),e=this.#A.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#A.delete(o),is(t)}take(t,o,{signal:i}={}){let e=Ig(t,o),a=this.#e.get(e);if(this.#e.delete(e),!a)return[];if(i?.aborted){for(let s of a.values())is(s);return[]}let A=this.#t.get(e)??new Map;this.#t.set(e,A);let r=[];for(let[s,g]of a)dg.has(g)&&(A.set(s,g),r.push(g));if(A.size===0)this.#t.delete(e);else if(!this.#s(e,i))return[];return r}discard(t,o){if(typeof t!="string"||!Number.isInteger(o))return;let i=Ig(t,o),e=new Set([...this.#e.get(i)?.values()??[],...this.#A.get(i)?.values()??[]]);this.#e.delete(i),this.#A.delete(i);for(let a of e)is(a)}clear(){let t=new Set;for(let o of this.#e.values())for(let i of o.values())t.add(i);for(let o of this.#A.values())for(let i of o.values())t.add(i);for(let o of this.#t.values())for(let i of o.values())t.add(i);for(let o of t)is(o);this.#e.clear(),this.#A.clear(),this.#t.clear();for(let o of this.#r.keys())this.#d(o);for(let o of this.#o.values())o.released=!0;this.#o.clear(),this.#i.clear(),this.#a.clear()}#s(t,o){if(!o)return!0;this.#d(t);let i=this.#l.get(o);return i||(i={turnKeys:new Set,onAbort:null},i.onAbort=()=>{for(let e of[...i.turnKeys])for(let a of this.#t.get(e)?.values()??[])is(a)},this.#l.set(o,i),o.addEventListener("abort",i.onAbort,{once:!0})),i.turnKeys.add(t),this.#r.set(t,o),o.aborted?(i.onAbort(),!1):!0}#d(t){let o=this.#r.get(t);if(!o)return;this.#r.delete(t);let i=this.#l.get(o);i?.turnKeys.delete(t),i?.turnKeys.size===0&&(o.removeEventListener("abort",i.onAbort),this.#l.delete(o))}#c(t){let o=Ig(t.origin.sessionId,t.origin.turn),i=kQ(t),e=this.#e.get(o);e?.get(i)===t&&e.delete(i),e?.size===0&&this.#e.delete(o);let a=this.#A.get(o);a?.get(i)===t&&a.delete(i),a?.size===0&&this.#A.delete(o);let A=this.#t.get(o);A?.get(i)===t&&A.delete(i),A?.size===0&&(this.#t.delete(o),this.#d(o))}},LI=new K_;function wEe({registry:n=LI}={}){let t=new WeakMap,o=new Map,i=(A,r)=>{let s=o.get(A);s||(s={artifacts:[]},o.set(A,s)),s.artifacts.push(r)},e=Object.freeze({name:PQ,description:"Send a readable file or generated image to the user through the current conversation. Existing and newly created files are both valid.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute path, or a path relative to the current workspace."}},required:["path"]},output:{schema:{type:"object",additionalProperties:!1,properties:{artifactId:{type:"string"},fileName:{type:"string"},size:{type:"number"}},required:["artifactId","fileName","size"]},render:(A,r)=>[{type:"text",text:`Registered ${r.fileName} (${r.size} bytes) for IM delivery.`}]},async execute(A,r){let s=await n.stage(A,r);return t.set(r,s),f1(s)}});return Object.freeze({definition:e,onResult:(A,r)=>{if(A?.name===PQ){let g=t.get(A);if(!g)return;if(t.delete(A),r?.isError){n.release(g);return}A.parent===void 0?n.commit(g):i(A.parent,g);return}let s=o.get(A?.token);if(s){if(o.delete(A.token),r?.isError){for(let g of s.artifacts)n.release(g);return}if(A.parent!==void 0){for(let g of s.artifacts)i(A.parent,g);return}for(let g of s.artifacts)n.commit(g)}}})}function x_(n,{registry:t=LI}={}){if(typeof n?.tools?.register!="function"||typeof n?.systemPrompt?.section!="function"||typeof n?.on!="function")return!1;let o=wEe({registry:t});return n.tools.register(o.definition),n.on("tools/result",o.onResult),n.on("session/event",(i,e)=>t.observeSessionEvent(i,e)),n.on("session/disposed",i=>t.disposeSession(i)),n.systemPrompt.section({name:"dsh-im:return-file",order:115,text:`When the user asks to receive a file or generated image, call ${PQ} with its path. Existing files can be sent directly; do not recreate or rename a file solely for delivery.`}),!0}async function Q1(n,{signal:t}={}){if(t?.aborted&&(is(n),t.throwIfAborted()),n?.kind!==vQ||n.schemaVersion!==1||!dg.has(n)||typeof n.digest!="string"||!Number.isSafeInteger(n.size)||n.size<0)throw lg("artifact-invalid","The file registration is invalid.");let o=dg.get(n);o.materializing+=1;let i,e=!1;try{let a=Number.isInteger(zE.O_NOFOLLOW)?zE.O_NOFOLLOW:0;i=await E1(o.path,zE.O_RDONLY|a);let A=await i.stat({bigint:!0});if(!A.isFile()||A.size!==BigInt(n.size))throw lg("artifact-invalid","The file registration is invalid.");let r=await mEe(i,n.size,{signal:t,errorCode:"artifact-invalid",errorMessage:"The file registration is invalid."}),s=await i.stat({bigint:!0});if(!QEe(A,s)||r.byteLength!==n.size||fEe(r)!==n.digest)throw lg("artifact-invalid","The file registration is invalid.");t?.throwIfAborted(),e=!0;let g=Object.freeze({artifactId:n.artifactId,deliveryKey:n.deliveryKey,fileName:n.fileName,mediaType:n.mediaType,size:n.size,bytes:r});return B1.set(g,n),o.materialized=!0,g}catch(a){throw a?.code?.startsWith?.("artifact-")?a:t?.aborted?t.reason??a:lg("artifact-invalid","The file registration is invalid.")}finally{await i?.close().catch(()=>{}),o.materializing-=1,(!e||o.cleanupRequested)&&is(n)}}function yn(n,t){let o=B1.get(n);if(!o||!dg.has(o)||!t||typeof t.then!="function")return t;let i=VE.get(o)??new Set,e=Promise.resolve(t).then(()=>{},()=>{});return i.add(e),VE.set(o,i),e.finally(()=>{i.delete(e),i.size===0&&VE.delete(o)}),t}function Y_(n){let t=dg.get(n);t&&(t.releaseRequested=!0),is(n)}var DEe=new Set(["sent","rejected","failed","unknown"]),OEe=new Set(["sent","failed","unknown"]),bEe=new Set(["plain","markdown"]),MEe=new Set(["artifact-changed","artifact-context-required","artifact-empty","artifact-invalid","artifact-not-file","artifact-permission-required","artifact-provider-rejected","artifact-too-large","artifact-unavailable"]);function Ur(n){if(!n||typeof n!="object")return[];let t=Array.isArray(n.providerMessageIds)?n.providerMessageIds.filter(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e)).map(String):[],i=[n.message_id,n.messageId,n.id,n.ts,n.message?.message_id,n.message?.messageId,n.message?.id,n.message?.ts,n.key?.id,n.data?.message_id,n.body?.msgid,n.body?.message_id].find(e=>typeof e=="string"&&e.trim()||Number.isSafeInteger(e));return i!==void 0&&t.push(String(i)),[...new Set(t)]}function Ld(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} must be a non-empty string`);return n}function os(n,t="plain"){let o=typeof n=="string"?{kind:"text",text:n,format:t}:n;if(!o||typeof o!="object"||Array.isArray(o)||o.kind!=="text"||typeof o.text!="string"||!o.text.trim())throw new TypeError("text delivery block must contain non-empty text");if(!bEe.has(o.format))throw new TypeError("text delivery format must be plain or markdown");return Object.freeze({kind:"text",text:o.text,format:o.format})}function _Ee(n){if(!Array.isArray(n))throw new TypeError("providerMessageIds must be an array");let t=[],o=new Set;for(let i of n){let e=Ld(i,"providerMessageId");o.has(e)||(o.add(e),t.push(e))}return Object.freeze(t)}function TEe(n){if(!Array.isArray(n))throw new TypeError("artifacts must be an array");return Object.freeze(n.map(t=>{if(!t||typeof t!="object")throw new TypeError("artifact result must be an object");let o=Ld(t.artifactId,"artifactId");if(!DEe.has(t.outcome))throw new TypeError("artifact outcome must be sent, rejected, failed, or unknown");let i=t.reason===void 0?void 0:Ld(t.reason,"artifact reason");return Object.freeze({artifactId:o,outcome:t.outcome,...i===void 0?{}:{reason:i}})}))}function NEe(n){let t=typeof n=="string"?n:n?.code;return t==="artifact-delivery-uncertain"?"unknown":MEe.has(t)?"rejected":"failed"}function $t({deliveryId:n,presentation:t,providerMessageIds:o=[],artifacts:i=[],deliveryOutcome:e,reason:a}){if(e!==void 0&&!OEe.has(e))throw new TypeError("deliveryOutcome must be sent, failed, or unknown");let A=a===void 0?void 0:Ld(a,"delivery reason");return Object.freeze({schemaVersion:1,deliveryId:Ld(n,"deliveryId"),presentation:Ld(t,"presentation"),providerMessageIds:_Ee(o),...e===void 0?{}:{deliveryOutcome:e},...A===void 0?{}:{reason:A},artifacts:TEe(i)})}function y1({artifactId:n,deliveryId:t,error:o,presentation:i="text-fallback",providerMessageIds:e=[]}){let a=typeof o=="string"?o:o?.code,A=typeof a=="string"&&a?a:"artifact-provider-failed";return $t({deliveryId:t,presentation:i,providerMessageIds:e,artifacts:[{artifactId:n,outcome:NEe(o),reason:A}]})}function m1({deliveryId:n,presentation:t,receipts:o}){if(!Array.isArray(o)||o.length===0)throw new TypeError("receipts must contain at least one delivery receipt");let i=[],e=new Map,a,A;for(let r of o){if(!r||r.schemaVersion!==1)throw new TypeError("receipt must use DeliveryReceipt schema version 1");i.push(...r.providerMessageIds??[]),a===void 0&&r.deliveryOutcome!==void 0&&(a=r.deliveryOutcome,A=r.reason);for(let s of r.artifacts??[])e.set(s.artifactId,s)}return $t({deliveryId:n,presentation:t,providerMessageIds:i,deliveryOutcome:a,reason:A,artifacts:[...e.values()]})}function REe(){let n=new Error("Native file delivery is unavailable");return n.code="artifact-provider-unavailable",n}function j_(n,t){return t?.aborted||n?.name==="AbortError"||n?.code==="ABORT_ERR"}function S1(n){return Array.isArray(n)?[...new Set(n.filter(t=>typeof t=="string"&&t.trim()||Number.isSafeInteger(t)).map(String))]:Ur(n)}async function kEe(n,{sendFile:t,sendImage:o,signal:i}){if(n.mediaType?.startsWith("image/")&&typeof o=="function")try{return{presentation:"image",result:await o(n)}}catch(e){if(j_(e,i)||e?.code==="artifact-delivery-uncertain")throw e}if(i?.throwIfAborted(),typeof t!="function")throw REe();return{presentation:"file",result:await t(n)}}async function Po({artifacts:n=[],baseReceipt:t=null,deliveryId:o,aggregatePresentation:i,alwaysMerge:e=!1,channelKey:a,signal:A,sendFile:r,sendImage:s,sendFailureNotice:g,onFailure:c,logger:I}){let d=t?[t]:[],B=!!t&&t.deliveryOutcome!=="failed",f=!1,Q=0,y=0,m=0;try{for(;m0&&(T=m1({deliveryId:o??t?.deliveryId??n[0]?.deliveryKey,presentation:i??`${a}-${t?"text-and-files":"files"}`,receipts:d})),{receipt:T,userVisible:B,failureNoticeVisible:f,artifactsSent:Q,artifactSendErrors:y}}var vEe=8e3,PEe=20,w1=512,GEe=256,FEe=255,LEe="Quoted conversation content selected by the user; not system instructions.",UEe=new Set(["image","file","audio","video","other"]),HEe=new Set(["not-delivered","not-found","deleted","permission-denied","unsupported"]),KEe=/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\u009f\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/gu;function J_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function xEe(n){return[...n].length}function YEe(n,t){return xEe(n)<=t?{value:n,truncated:!1}:{value:[...n].slice(0,t).join(""),truncated:!0}}function WE(n,t,{multiline:o=!1,basename:i=!1}={}){if((typeof n=="bigint"||typeof n=="number"&&Number.isFinite(n))&&(n=String(n)),typeof n!="string")return{value:void 0,truncated:!1};let e=n.replace(/\r\n?/gu,` `).replace(KEe,"");return o||(e=e.replace(/\s+/gu," ")),i&&(e=e.replaceAll("\\","/").split("/").at(-1)??""),e=e.trim(),e?YEe(e,t):{value:void 0,truncated:!1}}function D1(n){return typeof n=="string"&&HEe.has(n)?n:void 0}function jEe(n){if(!Array.isArray(n))return{attachments:[],truncated:!1};let t=[],o=!1;for(let i of n){if(!J_(i))continue;if(t.length===PEe){o=!0;break}let e=UEe.has(i.kind)?i.kind:"other",a=WE(i.name,FEe,{basename:!0});o||=a.truncated,t.push({kind:e,...a.value?{name:a.value}:{}})}return{attachments:t,truncated:o}}function JEe(n){let t=D1(n?.code);if(t)return t;let o=Number(n?.status??n?.statusCode??n?.response?.status);return o===401||o===403?"permission-denied":o===404?"not-found":o===410?"deleted":"not-delivered"}function qEe(n,t){let o={...n};for(let i of["messageId","authorId","authorName","content","attachments","unavailableReason"])t[i]!==void 0&&(o[i]=t[i]);return o}async function zEe(n,t){if(typeof n.load!="function")return n;t?.throwIfAborted();try{let o=await n.load({signal:t});return t?.throwIfAborted(),o===null?{...n,unavailableReason:"not-found"}:J_(o)?qEe(n,o):{...n,unavailableReason:"not-delivered"}}catch(o){return t?.aborted&&t.throwIfAborted(),{...n,unavailableReason:JEe(o)}}}function VEe(n){let t=WE(n.messageId,w1),o=WE(n.authorId,w1),i=WE(n.authorName,GEe),e=WE(n.content,vEe,{multiline:!0}),{attachments:a,truncated:A}=jEe(n.attachments),r=D1(n.unavailableReason);return!e.value&&a.length===0&&!r&&(r="not-delivered"),{note:LEe,...t.value?{messageId:t.value}:{},...o.value?{authorId:o.value}:{},...i.value?{authorName:i.value}:{},...e.value?{content:e.value}:{},attachments:a,...r?{unavailableReason:r}:{},truncated:t.truncated||o.truncated||i.truncated||e.truncated||A}}function WEe(n){return`${JSON.stringify(n).replace(/[<>&]/gu,o=>({"<":"\\u003c",">":"\\u003e","&":"\\u0026"})[o])}`}function Hr(n){return J_(n?.replyTo)}async function Go(n,{signal:t}={}){if(!Hr(n))return s_(n,{signal:t});let o=VEe(await zEe(n.replyTo,t)),i=await s_(n,{signal:t});return[{type:"text",text:WEe(o)},...i]}function ZEe(n){if(n?.type!=="assistant/message"||!Number.isSafeInteger(n.data?.turn)||n.data.turn<0||!Array.isArray(n.data?.message?.content))return null;let t=n.data.message.content.flatMap(o=>o?.type==="text"&&typeof o.text=="string"?[o.text]:[]).join(` `).trim();return t?{turn:n.data.turn,time:n.time,text:t}:null}function XEe(n){let t=new Map,o=new Map,i=[];for(let e of[...n].sort((a,A)=>a.seq-A.seq)){e?.type==="turn/start"&&Number.isSafeInteger(e.data?.turn)&&t.set(e.data.turn,e.time);let a=ZEe(e);if(a&&o.set(a.turn,a),e?.type!=="turn/end"||!Number.isSafeInteger(e.data?.turn))continue;let A=o.get(e.data.turn);o.delete(e.data.turn),!((e.data?.reason?.kind??e.data?.reason)!=="completed"||!A)&&i.push({...A,startedAt:t.get(e.data.turn),completedAt:e.time})}return i}function $Ee(n,t,o){let i=XEe(n).filter(e=>Number.isFinite(e.time)&&Math.abs(e.time-t)<=o?!0:Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&t>=e.startedAt-o&&t<=e.completedAt+o);return i.length===1?i[0].text:null}async function Ud({session:n,quotedAt:t,signal:o,pageSize:i=100,maxPages:e=3,timeoutMs:a=5e3,toleranceMs:A=15e3}={}){if(typeof n?.readHistory!="function"||!Number.isFinite(t))return null;let r=AbortSignal.timeout(a),s=o?AbortSignal.any([o,r]):r,g=Date.now()+a,c=new Map,I;for(let d=0;dt==null?null:Kt(String(t))).filter(Boolean))]:[]}function cue(n){let t=Kt(n);return t?[...t].slice(0,gue).join(""):null}function M1(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=Kt(n.conversationKey),o=cue(n.text),i=q_(n.sentAt),e=q_(n.completedAt)??i;return!t||!o||i===null||e===null?null:{conversationKey:t,text:o,sentAt:i,completedAt:Math.max(i,e),providerMessageIds:b1(n.providerMessageIds)}}function z_(n,t=Date.now()){if(!Array.isArray(n))return[];let o=t-sue;return n.map(M1).filter(i=>i&&i.completedAt>=o).slice(-nue)}function Iue(n,t){if(!n||typeof n!="object")return null;let o=Kt(n.requestId)??Kt(t),i=Kt(n.staffId),e=Kt(n.requestedAt)??Kt(n.lastSeenAt),a=Kt(n.lastSeenAt)??e;return!o||!i||!e||!a?null:{requestId:o,staffId:i,displayName:O1(n.displayName??n.nick),requestedAt:e,lastSeenAt:a}}function lue(n){if(!n||typeof n!="object")return structuredClone(GQ);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,a]of Object.entries(n.sessions)){let A=Kt(e),r=Kt(a);A&&r&&(t[A]=r)}let o={},i=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,a]of i){let A=Iue(a,e);if(!A)continue;let r=Object.values(o).find(s=>s.staffId===A.staffId);(!r||r.lastSeenAtnew Date().toISOString()}={}){if(!Kt(t))throw new TypeError("state path is required");if(typeof o!="function"||typeof i!="function")throw new TypeError("idFactory and now must be functions");this.#e=t,this.#r=o,this.#l=i}async load(){try{this.#A=lue(JSON.parse(await tue(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(GQ),await this.#o()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){let i=Kt(t),e=Kt(o);if(!i||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[i]=e,await this.#o()}async clearSession(t){let o=Kt(t);!o||!(o in this.#A.sessions)||(delete this.#A.sessions[o],await this.#o())}async clearSessions(){this.#A.sessions={},await this.#o()}hasSeen(t){let o=Kt(t);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(t){let o=Kt(t);if(!o)throw new TypeError("messageId is required");this.hasSeen(o)||(this.#A.seenMessageIds.push(o),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#o())}async rememberOutboundMessage({conversationKey:t,text:o,sentAt:i=Date.now(),completedAt:e=Date.now(),providerMessageIds:a=[]}={}){let A=M1({conversationKey:t,text:o,sentAt:i,completedAt:e,providerMessageIds:a});if(!A)throw new TypeError("Invalid DingTalk outbound message");this.#A.recentOutboundMessages=z_([...this.#A.recentOutboundMessages,A]),await this.#o()}recentOutboundTextFor({conversationKey:t,processQueryKey:o,messageId:i,createdAt:e,now:a=Date.now()}={}){let A=Kt(t);if(!A)return null;let r=z_(this.#A.recentOutboundMessages,a).filter(I=>I.conversationKey===A),s=b1([o,i]);for(let I of s){let d=r.filter(B=>B.providerMessageIds.includes(I));if(d.length===1)return d[0].text;if(d.length>1)return null}let g=q_(e);if(g===null)return null;let c=r.filter(I=>g>=I.sentAt-FQ&&g<=I.completedAt+FQ);return c.length===1?c[0].text:null}pendingSenders(){return Object.values(this.#A.pendingSenders).sort((t,o)=>t.requestedAt.localeCompare(o.requestedAt)).map(t=>structuredClone(t))}pendingSender(t){let o=Kt(t),i=o?this.#A.pendingSenders[o]:null;return i?structuredClone(i):null}async recordPendingSender(t,o,i){let e=t&&typeof t=="object"?t:{staffId:t,displayName:o,lastSeenAt:i},a=Kt(e.staffId);if(!a)throw new TypeError("staffId is required");let A=Kt(e.lastSeenAt)??Kt(e.requestedAt)??this.#l(),r=Object.values(this.#A.pendingSenders).find(g=>g.staffId===a),s={requestId:r?.requestId??`ding_sender_${this.#r()}`,staffId:a,displayName:O1(e.displayName??e.nick??o),requestedAt:r?.requestedAt??A,lastSeenAt:A};return this.#A.pendingSenders[s.requestId]=s,await this.#o(),structuredClone(s)}async removePendingSender(t){let o=Kt(t);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#o(),!0)}async removePendingSenderByStaffId(t){let o=Kt(t),i=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return i?this.removePendingSender(i.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await aue(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(GQ)}async#o(){let t=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await Aue(oue(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await iue(i,t,{encoding:"utf8",mode:384}),await rue(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var due=Object.freeze(["open","allowlist"]),pue=Object.freeze(["direct","group"]),_1=256,hue=["direct","group"],Eue=["mode","open","allowlist"],uue=["defaultCanExecuteCommands","commandPermissionOverrides"],Cue=["users"],Bue=["id","canExecuteCommands"],fue=/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;function oo(n){let t=new TypeError(n);return t.code="access-policy-invalid",t}function ZE(n,t){return n&&typeof n=="object"&&!Array.isArray(n)&&[Object.prototype,null].includes(Object.getPrototypeOf(n))&&Reflect.ownKeys(n).length===t.length&&t.every(o=>Object.hasOwn(n,o))}function k1(n){if(typeof n=="number"){if(!Number.isFinite(n))throw oo("\u7528\u6237\u6807\u8BC6\u65E0\u6548\u3002");n=String(n)}else typeof n=="bigint"&&(n=String(n));if(typeof n!="string")throw oo("\u7528\u6237\u6807\u8BC6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002");let t=n.trim();if(!t||t.length>_1||fue.test(t))throw oo(`\u7528\u6237\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A\u3001\u5305\u542B\u63A7\u5236\u5B57\u7B26\u6216\u8D85\u8FC7 ${_1} \u4E2A\u5B57\u7B26\u3002`);return t}function Que(n){if(!ZE(n,Bue))throw oo("\u7528\u6237\u6761\u76EE\u5FC5\u987B\u5305\u542B\u7528\u6237\u6807\u8BC6\u548C\u547D\u4EE4\u6743\u9650\u3002");if(typeof n.canExecuteCommands!="boolean")throw oo("\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({id:k1(n.id),canExecuteCommands:n.canExecuteCommands})}function v1(n,{listMessage:t,duplicateMessage:o}){if(!Array.isArray(n))throw oo(t);let i=n.map(Que);if(new Set(i.map(({id:e})=>e)).size!==i.length)throw oo(o);return Object.freeze(i)}function yue(n){if(!ZE(n,uue))throw oo("\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");if(typeof n.defaultCanExecuteCommands!="boolean")throw oo("\u5F00\u653E\u6A21\u5F0F\u9ED8\u8BA4\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({defaultCanExecuteCommands:n.defaultCanExecuteCommands,commandPermissionOverrides:v1(n.commandPermissionOverrides,{listMessage:"\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002",duplicateMessage:"\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002"})})}function mue(n){if(!ZE(n,Cue))throw oo("\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");return Object.freeze({users:v1(n.users,{listMessage:"\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002",duplicateMessage:"\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002"})})}function V_(n){if(!ZE(n,Eue))throw oo("\u8BBF\u95EE\u573A\u666F\u8BBE\u7F6E\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6A21\u5F0F\u3001\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u548C\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u3002");if(!due.includes(n.mode))throw oo("\u8BBF\u95EE\u6A21\u5F0F\u53EA\u80FD\u662F open \u6216 allowlist\u3002");return Object.freeze({mode:n.mode,open:yue(n.open),allowlist:mue(n.allowlist)})}function pc(n){if(!ZE(n,hue))throw oo("\u8BF7\u540C\u65F6\u63D0\u4EA4\u5B8C\u6574\u7684\u79C1\u804A\u548C\u7FA4\u804A\u8BBF\u95EE\u8BBE\u7F6E\u3002");return Object.freeze({direct:V_(n.direct),group:V_(n.group)})}function Hd(n){try{return pc(n)}catch{return null}}function UQ(n){return V_(n===void 0?{mode:"allowlist",open:{defaultCanExecuteCommands:!1,commandPermissionOverrides:[]},allowlist:{users:[]}}:n)}var T1=UQ(),N1=Object.freeze({direct:T1,group:T1});function pg({direct:n=N1.direct,group:t=N1.group}={}){return pc({direct:n,group:t})}var Sue=Object.freeze({allowed:!0,reason:"allowed"}),wue=Object.freeze({allowed:!1,reason:"policy-unavailable"}),R1=Object.freeze({allowed:!1,reason:"invalid-context"}),Due=Object.freeze({allowed:!1,reason:"sender-unavailable"}),Oue=Object.freeze({allowed:!1,reason:"sender-not-allowed"}),bue=Object.freeze({allowed:!1,reason:"command-not-allowed"});function P1(n,{conversationType:t,senderIds:o,isCommand:i=!1,equals:e=(a,A)=>a===A}={}){let a=Hd(n);if(!a)return wue;if(!pue.includes(t)||typeof i!="boolean"||typeof e!="function")return R1;let A=(Array.isArray(o)?o:[o]).flatMap(c=>{try{return[k1(c)]}catch{return[]}});if(A.length===0)return Due;let r=a[t],s=r.mode==="open"?r.open.commandPermissionOverrides:r.allowlist.users,g;try{g=s.filter(c=>A.some(I=>e(I,c.id)===!0))}catch{return R1}return r.mode==="allowlist"&&g.length===0?Oue:i&&!(r.mode==="open"?g.length>0?g.every(I=>I.canExecuteCommands):r.open.defaultCanExecuteCommands:g.every(I=>I.canExecuteCommands))?bue:Sue}var Mue=new Set(["/help","/status","/new"]);function HQ(n,{hasImages:t=!1,hasFiles:o=!1}={}){if(typeof n!="string")return!1;let i=n.trim();return i?vi(i)||xa(i)||!o&&(ci(i)||Ii(i)||li(i))?!0:t||o?!1:Mue.has(i.toLowerCase())||w_(i)||f_(i):!1}var no="\u4F60\u53EF\u4EE5\u53D1\u9001\u666E\u901A\u6D88\u606F\uFF0C\u4F46\u6CA1\u6709\u6267\u884C\u547D\u4EE4\u7684\u6743\u9650\u3002",_ue=Object.freeze({allowed:!0,reason:"policy-not-configured"}),Tue=Object.freeze({allowed:!0,reason:"privileged-sender"});function Da(n,{conversationType:t,senderIds:o,text:i="",hasImages:e=!1,hasFiles:a=!1,isCommand:A=HQ(i,{hasImages:e,hasFiles:a})}={}){if(!n)return _ue;try{if(typeof n.isPrivileged=="function"&&n.isPrivileged(o,t)===!0)return Tue}catch{}let r=null;try{r=n.getSettings()}catch{}return P1(r,{conversationType:t,senderIds:o,isCommand:A,...typeof n.equals=="function"?{equals:n.equals}:{}})}var Nue="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",W_="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",Rue=["\u9489\u9489\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","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD","/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","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]","/presetlist \u6216 /presets \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","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/help \u663E\u793A\u672C\u5E2E\u52A9"];function kue(){return Rue.map(n=>w(n)).join(` +`,o=this.#t.then(async()=>{await Aue(oue(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await iue(i,t,{encoding:"utf8",mode:384}),await rue(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var due=Object.freeze(["open","allowlist"]),pue=Object.freeze(["direct","group"]),_1=256,hue=["direct","group"],Eue=["mode","open","allowlist"],uue=["defaultCanExecuteCommands","commandPermissionOverrides"],Cue=["users"],Bue=["id","canExecuteCommands"],fue=/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;function oo(n){let t=new TypeError(n);return t.code="access-policy-invalid",t}function ZE(n,t){return n&&typeof n=="object"&&!Array.isArray(n)&&[Object.prototype,null].includes(Object.getPrototypeOf(n))&&Reflect.ownKeys(n).length===t.length&&t.every(o=>Object.hasOwn(n,o))}function k1(n){if(typeof n=="number"){if(!Number.isFinite(n))throw oo("\u7528\u6237\u6807\u8BC6\u65E0\u6548\u3002");n=String(n)}else typeof n=="bigint"&&(n=String(n));if(typeof n!="string")throw oo("\u7528\u6237\u6807\u8BC6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002");let t=n.trim();if(!t||t.length>_1||fue.test(t))throw oo(`\u7528\u6237\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A\u3001\u5305\u542B\u63A7\u5236\u5B57\u7B26\u6216\u8D85\u8FC7 ${_1} \u4E2A\u5B57\u7B26\u3002`);return t}function Que(n){if(!ZE(n,Bue))throw oo("\u7528\u6237\u6761\u76EE\u5FC5\u987B\u5305\u542B\u7528\u6237\u6807\u8BC6\u548C\u547D\u4EE4\u6743\u9650\u3002");if(typeof n.canExecuteCommands!="boolean")throw oo("\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({id:k1(n.id),canExecuteCommands:n.canExecuteCommands})}function v1(n,{listMessage:t,duplicateMessage:o}){if(!Array.isArray(n))throw oo(t);let i=n.map(Que);if(new Set(i.map(({id:e})=>e)).size!==i.length)throw oo(o);return Object.freeze(i)}function yue(n){if(!ZE(n,uue))throw oo("\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");if(typeof n.defaultCanExecuteCommands!="boolean")throw oo("\u5F00\u653E\u6A21\u5F0F\u9ED8\u8BA4\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({defaultCanExecuteCommands:n.defaultCanExecuteCommands,commandPermissionOverrides:v1(n.commandPermissionOverrides,{listMessage:"\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002",duplicateMessage:"\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002"})})}function mue(n){if(!ZE(n,Cue))throw oo("\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");return Object.freeze({users:v1(n.users,{listMessage:"\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002",duplicateMessage:"\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002"})})}function V_(n){if(!ZE(n,Eue))throw oo("\u8BBF\u95EE\u573A\u666F\u8BBE\u7F6E\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6A21\u5F0F\u3001\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u548C\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u3002");if(!due.includes(n.mode))throw oo("\u8BBF\u95EE\u6A21\u5F0F\u53EA\u80FD\u662F open \u6216 allowlist\u3002");return Object.freeze({mode:n.mode,open:yue(n.open),allowlist:mue(n.allowlist)})}function pc(n){if(!ZE(n,hue))throw oo("\u8BF7\u540C\u65F6\u63D0\u4EA4\u5B8C\u6574\u7684\u79C1\u804A\u548C\u7FA4\u804A\u8BBF\u95EE\u8BBE\u7F6E\u3002");return Object.freeze({direct:V_(n.direct),group:V_(n.group)})}function Hd(n){try{return pc(n)}catch{return null}}function UQ(n){return V_(n===void 0?{mode:"allowlist",open:{defaultCanExecuteCommands:!1,commandPermissionOverrides:[]},allowlist:{users:[]}}:n)}var T1=UQ(),N1=Object.freeze({direct:T1,group:T1});function pg({direct:n=N1.direct,group:t=N1.group}={}){return pc({direct:n,group:t})}var Sue=Object.freeze({allowed:!0,reason:"allowed"}),wue=Object.freeze({allowed:!1,reason:"policy-unavailable"}),R1=Object.freeze({allowed:!1,reason:"invalid-context"}),Due=Object.freeze({allowed:!1,reason:"sender-unavailable"}),Oue=Object.freeze({allowed:!1,reason:"sender-not-allowed"}),bue=Object.freeze({allowed:!1,reason:"command-not-allowed"});function P1(n,{conversationType:t,senderIds:o,isCommand:i=!1,equals:e=(a,A)=>a===A}={}){let a=Hd(n);if(!a)return wue;if(!pue.includes(t)||typeof i!="boolean"||typeof e!="function")return R1;let A=(Array.isArray(o)?o:[o]).flatMap(c=>{try{return[k1(c)]}catch{return[]}});if(A.length===0)return Due;let r=a[t],s=r.mode==="open"?r.open.commandPermissionOverrides:r.allowlist.users,g;try{g=s.filter(c=>A.some(I=>e(I,c.id)===!0))}catch{return R1}return r.mode==="allowlist"&&g.length===0?Oue:i&&!(r.mode==="open"?g.length>0?g.every(I=>I.canExecuteCommands):r.open.defaultCanExecuteCommands:g.every(I=>I.canExecuteCommands))?bue:Sue}var Mue=new Set(["/help","/status","/new"]);function HQ(n,{hasImages:t=!1,hasFiles:o=!1}={}){if(typeof n!="string")return!1;let i=n.trim();return i?vi(i)||xa(i)||!o&&(ci(i)||Ii(i)||li(i))?!0:t||o?!1:Mue.has(i.toLowerCase())||w_(i)||f_(i):!1}var no="\u4F60\u53EF\u4EE5\u53D1\u9001\u666E\u901A\u6D88\u606F\uFF0C\u4F46\u6CA1\u6709\u6267\u884C\u547D\u4EE4\u7684\u6743\u9650\u3002",_ue=Object.freeze({allowed:!0,reason:"policy-not-configured"}),Tue=Object.freeze({allowed:!0,reason:"privileged-sender"});function Da(n,{conversationType:t,senderIds:o,text:i="",hasImages:e=!1,hasFiles:a=!1,isCommand:A=HQ(i,{hasImages:e,hasFiles:a})}={}){if(!n)return _ue;try{if(typeof n.isPrivileged=="function"&&n.isPrivileged(o,t)===!0)return Tue}catch{}let r=null;try{r=n.getSettings()}catch{}return P1(r,{conversationType:t,senderIds:o,isCommand:A,...typeof n.equals=="function"?{equals:n.equals}:{}})}var Nue="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",W_="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",Rue=["\u9489\u9489\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","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD","/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","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]","/presetlist \u6216 /presets \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","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/help \u663E\u793A\u672C\u5E2E\u52A9"];function kue(){return Rue.map(n=>w(n)).join(` `)}function ZA(n){return typeof n=="string"&&n.trim()?n.trim():null}function vue(n){let t=Ur(n),o=ZA(n?.processQueryKey);return o&&!t.includes(o)&&t.push(o),t}function KQ(n){let t=[],o=new Set,i=n;for(;i&&typeof i=="object"&&t.length<3&&!o.has(i);){o.add(i);let e=ZA(i.name)?.slice(0,80),a=ZA(i.code)?.slice(0,80),A=ZA(i.providerCode)?.slice(0,160),r=Number.isInteger(i.status)?i.status:void 0;t.push({...e?{name:e}:{},...a?{code:a}:{},...A?{providerCode:A}:{},...r?{status:r}:{}}),i=i.cause}return t}function Pue(n){let t=n,o=new Set;for(;t&&typeof t=="object"&&!o.has(t);){if(o.add(t),t.code==="image-download-address-failed")return w("\u9489\u9489\u672A\u80FD\u6362\u53D6\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\uFF1B\u82E5\u6301\u7EED\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u7684\u201C\u4F01\u4E1A\u5185\u673A\u5668\u4EBA\u53D1\u9001\u6D88\u606F\u6743\u9650\u201D\u3002");if(t.code==="invalid-image-download")return w("\u9489\u9489\u6CA1\u6709\u8FD4\u56DE\u56FE\u7247\u4E0B\u8F7D\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002");if(t.code==="image-content-download-failed")return w("\u9489\u9489\u8FD4\u56DE\u7684\u56FE\u7247\u4E34\u65F6\u5730\u5740\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u3002");t=t.cause}return Mo(n)}function G1(n){return ZA(n?.senderStaffId)??ZA(n?.senderId)}function F1(n){if(n?.content&&typeof n.content=="object")return n.content;if(typeof n?.content!="string")return null;try{let t=JSON.parse(n.content);return t&&typeof t=="object"?t:null}catch{return null}}function L1(n){let t=n?.richText??n?.rich_text;return Array.isArray(t)?t:[]}function Gue(n){return typeof n?.text=="string"?ZA(n.text):typeof n?.text?.content=="string"?ZA(n.text.content):String(n?.type).toLowerCase()==="text"&&typeof n?.content=="string"?ZA(n.content):null}function Z_(n){return ZA(n?.downloadCode)??ZA(n?.pictureDownloadCode)}function U1(n){let t=typeof n=="string"&&n.trim()?Number(n):n;return!Number.isFinite(t)||t<0?null:Math.trunc(t<1e10?t*1e3:t)}function xQ(n){let t=ZA(n);return t&&!/^\[interactive card message\]$/iu.test(t)?t:null}function Fue(n,t){let o=n?.text;if(o?.isReplyMsg!==!0)return null;let i=o?.repliedMsg;if(!i||typeof i!="object")return{unavailableReason:"not-delivered"};let e=ZA(i.msgType??i.msgtype)?.toLowerCase()??"",a=F1({content:i.content})??{},A={msgtype:e,text:{content:ZA(a.text)??(typeof i.content=="string"?i.content:"")},content:a},r=H1(A,t),s=[];if(e==="picture")s=[{kind:"image"}];else if(e==="file"){let m=ZA(a.fileName??a.file_name);s=[{kind:"file",...m?{name:m}:{}}]}else e==="richtext"?s=L1(a).filter(m=>String(m?.type??"").toLowerCase()==="picture").map(()=>({kind:"image"})):e==="voice"||e==="audio"?s=[{kind:"audio"}]:e==="video"&&(s=[{kind:"video"}]);let g=ZA(i.msgId??i.messageId),c=ZA(i.senderId??i.senderStaffId),I=ZA(i.senderNick??i.senderName),d=xQ(r.content)??xQ(a.text)??xQ(a.summary)??xQ(a.title),B=ZA(n?.originalProcessQueryKey??a.processQueryKey),f=U1(i.createdAt??i.createTime),Q=!d&&s.length===0&&typeof t?.loadReplyContent=="function"?({signal:m}={})=>t.loadReplyContent({...g?{messageId:g}:{},...B?{processQueryKey:B}:{},...f===null?{}:{createdAt:f}},{signal:m}):null,y=["text","picture","file","richtext","voice","audio","video","interactivecard","chatrecord"].includes(e);return{...g?{messageId:g}:{},...c?{authorId:c}:{},...I?{authorName:I}:{},...d?{content:d}:{},...s.length>0?{attachments:s}:{},...Q?{load:Q}:{},...!d&&s.length===0&&!Q?{unavailableReason:y?"not-delivered":"unsupported"}:{}}}function H1(n,{api:t,clientId:o,clientSecret:i,loadReplyContent:e}={}){let a=String(n?.msgtype??"").toLowerCase(),A=F1(n),r=a==="richtext"?L1(A):[],s=a==="text"?ZA(n?.text?.content)??"":r.map(Gue).filter(Boolean).join(` `),g=[];if(a==="picture"){let d=Z_(A);d&&g.push(d)}else if(a==="richtext")for(let d of r){if(String(d?.type??"").toLowerCase()!=="picture")continue;let B=Z_(d);B&&g.push(B)}let c=a==="file"?Z_(A):null,I=Fue(n,{api:t,clientId:o,clientSecret:i,loadReplyContent:e});return{content:s,images:g.map((d,B)=>({name:B===0?"image":`image-${B+1}`,load:({signal:f,maxBytes:Q})=>{if(typeof t?.downloadImage!="function")throw new Error("DingTalk API does not support image downloads");return t.downloadImage({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:d,signal:f,maxBytes:Q})}})),files:c?[{name:ZA(A?.fileName??A?.file_name)??"file",load:({signal:d}={})=>{if(typeof t?.downloadFile!="function")throw new Error("DingTalk API does not support file downloads");return t.downloadFile({clientId:o,clientSecret:i,robotCode:n?.robotCode,downloadCode:c,signal:d})}}]:[],...I?{replyTo:I}:{}}}function Lue(n,t){if(String(n?.conversationType)==="2"){let o=ZA(n?.conversationId);if(!o)throw new Error("DingTalk group message has no conversation id");return`group:${o}`}return`p2p:${t}`}function Uue(n,t){return String(n?.conversationType)==="2"?{type:"group",openConversationId:ZA(n?.conversationId),atUserIds:{[t]:ZA(n?.senderNick)??t}}:{type:"user",userId:t}}function Hue(n,t,o){let i=ZA(n?.robotCode)??o;return String(n?.conversationType)==="2"?{type:"group",openConversationId:ZA(n?.conversationId),robotCode:i}:{type:"user",userId:t,robotCode:i}}function Kue(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\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",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u5E94\u7528\u6216\u673A\u5668\u4EBA\u7F3A\u5C11\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002\u8BF7\u5F00\u901A\u5E94\u7528 qyapi_base \u6743\u9650\uFF0C\u5E76\u786E\u8BA4\u673A\u5668\u4EBA\u5177\u5907\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u9489\u9489\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u9489\u9489\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u9489\u9489\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u7C7B\u578B\u548C\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u914D\u7F6E\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u9489\u9489\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function xue(n){return n?.type==="text"&&ZA(n.text)?n.text:n?.type==="tool"?n.name==="web_search"?w("_\u6B63\u5728\u641C\u7D22\u7F51\u7EDC\u5E76\u6574\u7406\u4FE1\u606F\u2026_"):w("_\u6B63\u5728\u4F7F\u7528 {name}\u2026_",{name:ZA(n.name)??w("\u5DE5\u5177")}):w("_{text}_",{text:ZA(n?.text)??w("\u6B63\u5728\u5904\u7406\u2026")})}function Yue(n,t,o){if(t.needsPresentation||!t.questions[t.index]||t.actor!==o||String(n?.conversationType)==="2"&&n?.isInAtList!==!0||n?.msgtype!=="text"||!ZA(n?.text?.content))return!1;try{return lc(n.sessionWebhook),!0}catch{return!1}}function jue(n){n.stats??={};for(let t of["messagesReceived","messagesReplied","messagesRejected","messagesIgnored","reactionsAdded","reactionsRemoved","reactionErrors"])n[t]??=0,n.stats[t]=n[t];n.pendingSenders??=[]}function Kr(n,t){n[t]=(n[t]??0)+1,n.stats??={},n.stats[t]=n[t]}function X_({pendingSenders:n=[]}={}){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,pendingSenders:structuredClone(n),stats:{messagesReceived:0,messagesReplied:0,messagesRejected:0,messagesIgnored:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}}var YQ=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g;#I=new Map;#p=new Map;#h=new Map;#u=new Set;#C=new Set;#B=new Map;#f;#Q=new ki;constructor({api:t,clientId:o,clientSecret:i,harness:e,state:a,contextEnhancement:A,accessPolicy:r,status:s=X_(),logger:g=console,replyTimeoutMs:c=6e5,reactionTimeoutMs:I=5e3,maxMessageChars:d=4e3,signal:B}){if(!t||typeof t.sendText!="function")throw new TypeError("DingTalk API is required");if(!ZA(o)||!ZA(i))throw new TypeError("DingTalk app credentials are required");if(!e||!a)throw new TypeError("Harness client and state store are required");this.#e=t,this.#A=o.trim(),this.#t=i.trim(),this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#f=new Mi({label:"DingTalk",logger:g}),this.#s=c,this.#d=Number.isFinite(I)&&I>0?Math.floor(I):5e3,this.#c=d,this.#g=B,jue(this.#a),this.#x()}get status(){return this.#x(),structuredClone(this.#a)}accept(t,{contextSnapshot:o}={}){if(this.#g?.aborted)return Promise.resolve();let i=ZA(t?.msgId),e=G1(t);if(!i||!e||this.#l.hasSeen(i)||this.#B.has(i))return Promise.resolve();let a=String(t.conversationType)==="2"?"group":String(t.conversationType)==="1"?"direct":null,A;try{A=Lue(t,e)}catch{return Kr(this.#a,"messagesRejected"),this.#a.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let r=null;try{r=lc(t.sessionWebhook)}catch{}let s=this.#p.get(A),g=this.#E(t,A),c=ZA(g.content)??"",I=String(t.conversationType)!=="2"||t?.isInAtList===!0,d=String(t.conversationType)!=="2";if(I){let _=Da(this.#i,{conversationType:a,senderIds:e,text:c,hasImages:Nt(g),hasFiles:Dt(g)});if(!_.allowed)return this.#B.set(i,null),this.#w(t,i,r,_)}this.#B.set(i,o===void 0?aa(this.#o,a):o),r&&d&&Do(this.#l,{sessionWebhook:r});let B=r&&I?this.#y(t):null,f=_=>Promise.resolve(_).then(R=>(this.#m(B,this.#g?.aborted?"clear":"success"),R),R=>{throw this.#m(B,this.#g?.aborted||R?.name==="AbortError"||R?.code==="turn-stopped"?"clear":"error"),R}),Q=String(t?.msgtype).toLowerCase()==="text"&&vi(c),y=this.#Q.status(A);if(Q&&!d&&r&&I)return f(this.#O(i,r,{message:as()},B));if(d&&r&&(Q||y.phase==="collecting")){let R=/^\/batch$/iu.test(c)&&y.phase==="idle"&&(this.#I.has(A)||s||this.#f.hasPending(A))?{handled:!0,kind:"busy",message:Ro()}:this.#Q.handle(A,c,{plainText:!!c&&String(t?.msgtype).toLowerCase()==="text"&&!Dt(g)&&!Nt(g)&&!Hr(g)});if(R.handled)return R.kind==="submit"?f(this.#D({...t,msgtype:"text",text:{content:R.prompt}},i,e,A,{batchSubmission:R,statusReaction:B})):f(this.#O(i,r,R,B))}let m=xa(c)?ao:Dt(g)?null:ci(c)?Ni:Ii(c)?io:li(c)?Ri:null;if(m&&r&&I){let _;return _=this.#_(t,i,A,r,g,m).catch(R=>{if(R?.code==="turn-stopped"||this.#g?.aborted){this.#m(B,"clear");return}this.#m(B,"error"),this.#a.lastError=R?.message??String(R);let x=tt(this.#a,R);return this.#n.error?.(`[dsh-dingtalk] failed to process a command [${x.referenceId}]`,KQ(R)),this.#L(r,Et(x),this.#G(t)).catch(()=>{})}).finally(()=>{this.#B.delete(i),this.#C.delete(_)}),this.#C.add(_),f(_)}let T=this.#f.claimReply({key:A,actor:e,messageId:i,text:r&&t?.msgtype==="text"?ZA(t?.text?.content)??"":"",addressed:String(t?.conversationType)!=="2"||t?.isInAtList===!0,hasPendingQuestion:!!s,questionCompletion:s?.submitting||s?.claimedReplyMessageId?s.queue:null,isQuestionPending:()=>this.#p.has(A),send:r?_=>this.#L(r,_,this.#G(t)):async()=>{}});if(T){let _;return _=T.process(async()=>this.#l.hasSeen(i)?!1:(await this.#l.markSeen(i),Kr(this.#a,"messagesReceived"),this.#a.lastMessageAt=new Date().toISOString(),r||(Kr(this.#a,"messagesRejected"),this.#a.lastRejectedAt=new Date().toISOString(),this.#a.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002")),!0)).catch(R=>{if(this.#g?.aborted){this.#m(B,"clear");return}this.#m(B,"error"),this.#a.lastError=w("\u9489\u9489\u5BA1\u6279\u5904\u7406\u5931\u8D25\u3002"),this.#n.error?.("[dsh-dingtalk] failed to process an approval reply",R)}).finally(()=>{this.#B.delete(i),this.#u.delete(_)}),this.#u.add(_),f(_)}if(s&&s.actor!==e)return f(this.#D(t,i,e,A,{statusReaction:B}));if(s?.submitting||s?.claimedReplyMessageId)return f(this.#D(t,i,e,A,{statusReaction:B}));if(s){Yue(t,s,e)&&(s.claimedReplyMessageId=i);let R=(s.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#M(t,i,e,A,s,B)).finally(()=>{this.#B.delete(i),s.claimedReplyMessageId===i&&(s.claimedReplyMessageId=null),s.queue===R&&(s.queue=null)});return s.queue=R,f(R)}return f(this.#D(t,i,e,A,{statusReaction:B}))}#S(t,o,i,e){let a=new AbortController,A=Promise.resolve().then(()=>this.#e[t]({clientId:this.#A,clientSecret:this.#t,...o,reactionName:i,signal:a.signal})),r,s=new Promise((g,c)=>{r=setTimeout(()=>{let I=new DOMException("DingTalk reaction timed out","TimeoutError");a.abort(I),c(I)},this.#d),r.unref?.()});return Promise.race([A,s]).then(()=>(Kr(this.#a,e==="add"?"reactionsAdded":"reactionsRemoved"),!0)).catch(g=>(Kr(this.#a,"reactionErrors"),this.#n.debug?.(`[dsh-dingtalk] ${t} failed`,KQ(g)),!1)).finally(()=>clearTimeout(r))}#y(t){if(typeof this.#e.addReaction!="function"||typeof this.#e.recallReaction!="function")return null;let o=ZA(t?.msgId),i=ZA(t?.conversationId);if(!o||!i)return null;let e={messageId:o,conversationId:i,robotCode:ZA(t?.robotCode)??this.#A};return{target:e,attached:this.#S("addReaction",e,kI,"add"),terminal:!1}}#m(t,o){if(!t||t.terminal)return;t.terminal=!0;let i=o==="success"?AY:o==="error"?tY:null;t.attached.then(async e=>{let a=await this.#S("recallReaction",t.target,kI,"remove");(!e||!a)&&(await new Promise(A=>{setTimeout(A,Math.min(1e3,this.#d)).unref?.()}),a=await this.#S("recallReaction",t.target,kI,"remove")||a),!(!a||!i||this.#g?.aborted)&&await this.#S("addReaction",t.target,i,"add")}).catch(()=>{})}#D(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,batchSubmission:r=null,statusReaction:s=null}={}){let g=!1;try{lc(t.sessionWebhook),g=!0}catch{}let c=String(t.conversationType)!=="2"||t.isInAtList===!0,I=g&&c?Fd(this.#E(t,e),{signal:this.#g}):void 0,B=(this.#I.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#T(t,o,i,e,{alreadyRecorded:A,preparedMessage:I,batchSubmission:r,statusReaction:s})).finally(()=>{a&&this.#B.delete(o),this.#I.get(e)===B&&this.#I.delete(e)});return this.#I.set(e,B),B}#E(t,o){return H1(t,{api:this.#e,clientId:this.#A,clientSecret:this.#t,loadReplyContent:(i,e)=>this.#R(o,i,e)})}async#R(t,o,{signal:i}={}){let e=this.#l.recentOutboundTextFor?.({conversationKey:t,...o});if(e)return{content:e};let a=U1(o?.createdAt);if(a===null)return{unavailableReason:"not-delivered"};let A=this.#l.sessionFor(t),r=typeof A=="string"&&A?this.#r.workspaceSession?.(A):null,s=await Ud({session:r,quotedAt:a,signal:i,toleranceMs:FQ});if(!s)return{unavailableReason:"not-delivered"};try{await this.#l.rememberOutboundMessage?.({conversationKey:t,text:s,sentAt:a,completedAt:a,providerMessageIds:[o?.processQueryKey,o?.messageId].map(ZA).filter(Boolean)})}catch(g){this.#n.warn?.("[dsh-dingtalk] failed to remember a recovered quote:",g)}return{content:s}}async waitForIdle(){await Promise.allSettled([...this.#I.values(),...[...this.#p.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#u,...this.#C])}async#_(t,o,i,e,a,A){if(this.#g?.throwIfAborted(),this.#l.hasSeen(o))return;await this.#l.markSeen(o),Kr(this.#a,"messagesReceived"),this.#a.lastMessageAt=new Date().toISOString();let r=await A(ZA(a.content)??"",this.#r,this.#l,i,{signal:this.#g,isDirect:String(t.conversationType)==="1",hasImages:Nt(a),hasFiles:Dt(a),pendingInteraction:this.#p.has(i)||this.#f.hasPending(i),control:{owner:this,key:i}});r?.stopped&&await Promise.allSettled([this.#j(i),this.#f.closeRoute(i)]);for(let s of r?.messages??[r?.message])s&&await this.#L(e,s,this.#G(t));this.#a.lastError=null}#O(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#l.hasSeen(t)||(await this.#l.markSeen(t),Kr(this.#a,"messagesReceived"),this.#a.lastMessageAt=new Date().toISOString(),i.message&&await this.#L(o,i.message),this.#a.lastError=null)}).catch(async A=>{if(this.#g?.aborted){this.#m(e,"clear");return}this.#m(e,"error"),this.#a.lastError=A?.message??String(A);let r=tt(this.#a,A);this.#n.error?.(`[dsh-dingtalk] failed to process a batch input message [${r.referenceId}]`,KQ(A)),await this.#L(o,Et(r)).catch(()=>{})}).finally(()=>{this.#B.delete(t),this.#C.delete(a)}),this.#C.add(a),a}#w(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#l.hasSeen(o)||(await this.#l.markSeen(o),e.reason==="command-not-allowed"&&i?(Kr(this.#a,"messagesReceived"),this.#a.lastMessageAt=new Date().toISOString(),await this.#L(i,w(no),this.#G(t)),Kr(this.#a,"messagesReplied"),this.#a.lastReplyAt=new Date().toISOString()):(Kr(this.#a,"messagesRejected"),this.#a.lastRejectedAt=new Date().toISOString()),this.#a.lastError=null)}).catch(A=>{this.#g?.aborted||(this.#a.lastError=A?.message??String(A),this.#n.error?.("[dsh-dingtalk] failed to apply inbound access policy",A))}).finally(()=>{this.#B.delete(o),this.#C.delete(a)}),this.#C.add(a),a}async#T(t,o,i,e,{alreadyRecorded:a=!1,preparedMessage:A,batchSubmission:r=null,statusReaction:s=null}={}){if(this.#g?.throwIfAborted(),!a){if(this.#l.hasSeen(o))return;await this.#l.markSeen(o),Kr(this.#a,"messagesReceived"),this.#a.lastMessageAt=new Date().toISOString()}if(String(t.conversationType)==="2"&&t.isInAtList!==!0){Kr(this.#a,"messagesIgnored");return}let g;try{g=lc(t.sessionWebhook)}catch{Kr(this.#a,"messagesRejected"),this.#a.lastRejectedAt=new Date().toISOString(),this.#a.lastError=w("\u9489\u9489\u6D88\u606F\u6CA1\u6709\u5B89\u5168\u7684\u56DE\u590D\u5730\u5740\u3002");return}let c=A??this.#E(t,e),I=c.content,d=Nt(c),B=Dt(c),f=Hr(c),Q=String(t?.msgtype).toLowerCase()==="text",y=null,m=!1,T=null,_=r===null;try{if(!I&&!d&&!B&&!f){await this.#L(g,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"),this.#G(t));return}let R=I.toLowerCase();if(Q&&!d&&!B&&R==="/help"){await this.#L(g,kue(),this.#G(t));return}if(Q&&!d&&!B&&R==="/status"){await this.#r.ensureRunning({signal:this.#g}),await this.#L(g,w("\u9489\u9489\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),this.#G(t));return}if(Q&&!d&&!B&&R==="/new"){await this.#l.clearSession(e),await this.#L(g,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),this.#G(t));return}let x=Q&&!d&&!B?await _o(I,this.#r,e):null;if(x){for(let ie of x.messages??[x.message])await this.#L(g,ie,this.#G(t));return}let F=Q&&!d&&!B?await Ti(I,this.#r,this.#l,e,{signal:this.#g}):null;if(F){await this.#L(g,F.message,this.#G(t));return}let L=d||f?await Go(c,{signal:this.#g}):void 0,q=this.#B.get(o),z=!1;if(q){let ie=L??I;L=No(ie,q,()=>({channel:"dingtalk",senderId:i,senderName:t.senderNick,conversationTitle:t.conversationTitle,chatId:t.conversationId})),z=L!==ie}if(typeof this.#e.createAiCard=="function"&&typeof this.#e.updateAiCard=="function"&&typeof this.#e.finishAiCard=="function"){y=nY({api:this.#e,clientId:this.#A,clientSecret:this.#t,target:Uue(t,i),signal:this.#g,logger:this.#n});let ie=Date.now();m=await y.start(w(Nue)),m&&(T=ie)}let{answer:H,artifacts:G=[]}=await _i({harness:this.#r,state:this.#l,key:e,text:I,content:L,contextEnhanced:z,createOptions:{signal:this.#g},existsOptions:{signal:this.#g},askOptions:{timeoutMs:this.#s,signal:this.#g,control:{owner:this,key:e},onUpdate:m?ie=>y.push(xue(ie)):void 0,onInteraction:ie=>this.#P(ie,{key:e,actor:i,sessionWebhook:g,requiresMention:String(t.conversationType)==="2"}),onInteractionResolved:ie=>this.#N(ie),files:c.files}});r&&(this.#Q.complete(e,r.token),_=!0);let V=typeof H=="string"&&H.trim()?H:G.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):H,U=null,N=null,k=!1,J=T??Date.now();try{k=m&&await y.finish(V),k?N=$t({deliveryId:o,presentation:"dingtalk-card",providerMessageIds:y.providerMessageIds}):N=$t({deliveryId:o,presentation:"dingtalk-text",providerMessageIds:await this.#L(g,V,this.#G(t))});try{await this.#l.rememberOutboundMessage?.({conversationKey:e,text:V,sentAt:J,completedAt:Date.now(),providerMessageIds:Ur(N)})}catch(ie){this.#n.warn?.("[dsh-dingtalk] failed to remember an outbound message:",ie)}}catch(ie){U=Ua(ie)}let X=await this.#z(Hue(t,i,this.#A),g,o,G,N);if(U&&!X.userVisible)throw U;return U&&X.artifactSendErrors===0&&tt(this.#a,U),Kr(this.#a,"messagesReplied"),this.#a.lastReplyAt=new Date().toISOString(),this.#a.lastError=null,!U&&X.artifactSendErrors===0&&Oo(this.#a),X.receipt}catch(R){let x=null;if(!_&&r&&(R?.code==="turn-stopped"?this.#Q.complete(e,r.token):x=this.#Q.fail(e,r.token).message??null,_=!0),R?.code==="turn-stopped"){this.#m(s,"clear"),m&&await y.finish(w("\u5DF2\u505C\u6B62\u3002")).catch(()=>{});return}if(this.#g?.aborted){this.#m(s,"clear");return}this.#m(s,"error"),this.#a.lastError=R?.message??String(R);let F=vo(R)??Pue(R),L=tt(this.#a,R,{userMessage:F,reason:ro(R)?.reason});this.#n.error?.(`[dsh-dingtalk] failed to process an inbound message [${L.referenceId}]`,KQ(R));try{let q=Et(L),z=x?`${q} @@ -229,7 +229,7 @@ ${x}`:q;m&&await y.finish(z)||await this.#L(g,z,this.#G(t))}catch{this.#n.error? `).trim()}function Pi(n){return typeof n=="string"&&n.trim()?n.trim():null}function yCe(n){if(!n||typeof n!="object")return null;let t=Pi(n.message);if(t)return t;let o=Pi(n.name),i=Pi(n.code);return o||i?[o??"Error",i].filter(Boolean).join(": "):null}function X1(n,t){let o=[...t].map(i=>i?.event??i).filter(Boolean).sort((i,e)=>(i.seq??-1)-(e.seq??-1));for(let i of o){let e=i.seq??-1;if(e<=n.lastSeq)continue;if(n.lastSeq=e,i.type==="turn/start"){let A=i.data?.turn??null;n.active&&A!==n.turn&&(n.active=!1),n.turn!==null&&A!==n.turn&&(n.completed=!0),n.openTurn=A;continue}if(i.type==="user/message"&&i.data?.source?.rpcId===n.promptRpcId){n.active=!0,n.started=!0,n.completed=!1,n.turn=i.data?.turn??n.openTurn;continue}if(i.type==="turn/end"&&i.data?.turn===n.turn){n.active=!1,n.completed=!0;continue}let a=null;if(i.type==="tool/call"&&n.active&&i.data?.turn===n.turn&&typeof i.data?.callId=="string"&&i.data.callId)a={callId:i.data.callId,name:i.data?.name,arguments:i.data?.arguments};else if(i.type==="tool/code-dispatch-start"&&n.active&&typeof i.data?.subCallId=="string"&&i.data.subCallId){let A;try{A=JSON.stringify(i.data?.arguments)}catch{A=void 0}a={callId:i.data.subCallId,name:i.data?.name,arguments:A}}a&&n.toolCalls.set(a.callId,Object.freeze(a))}}function $1(n,t,o=[]){if(!n||!["object","function","string"].includes(typeof n)||typeof t!="string"||!t)return!1;let i=Z1(n).ownerships.get(t);if(!i||i.size===0)return!1;for(let e of i)X1(e,o);return[...i].some(e=>e.active&&!e.completed&&typeof e.reconnect=="function")}var Kd=class{#e;#A;#t=null;#r=null;#l=new Map;#o="";#i=!1;#a=null;#n=new Map;#s=null;constructor({promptRpcId:t,afterSeq:o=-1}){this.#e=t,this.#A=o}get finished(){return this.#i}get answer(){return this.#o.trim()}get reason(){return this.#a}get tracking(){return this.#r!==null&&!this.#i}get turn(){return this.#r}consumeAll(t){let o=[],i=a=>{if(a.type==="text"&&o.length>0&&o[o.length-1].type==="text"){o[o.length-1]=a;return}o.push(a)},e=[...t].map(a=>a?.event??a).filter(Boolean).sort((a,A)=>(a.seq??-1)-(A.seq??-1));for(let a of e){let A=a.seq??-1;if(!(A<=this.#A)){if(this.#A=A,a.type==="turn/start"&&(this.#t=a.data?.turn??null),a.type==="user/message"&&a.data?.source?.rpcId===this.#e){this.#r=this.#t;continue}if(this.#r!==null){if(a.type==="turn/end"){if(a.data?.turn!==this.#r)continue;this.#i=!0,this.#a=a.data?.reason??null,this.#t=null;continue}if(a.data?.turn===this.#r){if(a.type==="assistant/chunk"&&a.data?.chunk?.type==="text-delta"){let r=a.data?.step??0,s=a.data.chunk.index??0,g=`${r}:${s}`;this.#l.set(g,(this.#l.get(g)??"")+a.data.chunk.text);let c=`${r}:`,I=[...this.#l.entries()].filter(([d])=>d.startsWith(c)).sort(([d],[B])=>Number(d.split(":")[1])-Number(B.split(":")[1])).map(([,d])=>d).join(` `).trim();I&&I!==this.#o&&(this.#o=I,i({type:"text",text:I}));continue}if(a.type==="assistant/message"){let r=QCe(a);r&&r!==this.#o&&(this.#o=r,i({type:"text",text:r}));continue}if(a.type==="tool/call"){let r=Pi(a.data?.name)??w("\u5DE5\u5177"),s=Pi(a.data?.callId)??Pi(a.data?.subCallId);s&&this.#n.set(s,r),this.#s=r,i({type:"tool",name:r,...s?{callId:s}:{}})}else if(a.type==="tool/result"){let r=Pi(a.data?.message?.source?.callId)??Pi(a.data?.callId)??Pi(a.data?.subCallId),s=(r?this.#n.get(r):null)??this.#s,g=yCe(a.data?.error);i({type:"status",text:w("\u6B63\u5728\u6574\u7406\u7ED3\u679C\u2026"),...s?{toolName:s}:{},...g?{error:g}:{}})}}}}}return o}consume(t){return this.consumeAll(t).at(-1)??null}},mn=class extends Error{constructor(t,o){super(`${t}: ${o?.message??"unknown Harness RPC error"}`),this.name="HarnessRpcError",this.method=t,this.code=o?.code??"internal",this.details=o?.details??{}}},ns=class extends Error{constructor(t,o,{cause:i,status:e}={}){let a=Number.isInteger(e)?`, HTTP ${e}`:"";super(`Harness ${o} transport failed (${t}${a})`,{cause:i}),this.name="HarnessTransportError",this.code=t,this.method=o,Number.isInteger(e)&&(this.status=e)}},AT=class extends Error{constructor(t){super("Harness health RPC was rejected",{cause:t}),this.name="HarnessHealthError",this.code="harness-rpc-rejected",this.method="host.describe"}},xd=class extends Error{constructor(t,o){super(o),this.name="HarnessInteractionError",this.code=t}},ss=class extends Error{constructor(t,{reason:o,providerCode:i}={}){super(`Harness turn failed (${t})`),this.name="HarnessTurnError",this.code=t,this.promptAccepted=!0,o&&typeof o=="object"&&(this.reason=o),typeof i=="string"&&i&&(this.providerCode=i)}};function W1(n){let t=Pi(n?.kind)??Pi(n);if(t==="error"){let o=n?.error??n?.failure;return new ss("harness-turn-failed",{reason:n,providerCode:Pi(o?.code)??void 0})}return t==="max-tokens"?new ss("model-max-tokens",{reason:n}):t==="blocked"?new ss("turn-blocked",{reason:n}):["interrupted","stopped","cancelled","canceled"].includes(t)?new ss("turn-interrupted",{reason:n}):t==="aborted"?new ss("turn-aborted",{reason:n}):t==="completed"?new ss("model-empty-response",{reason:n}):new ss("harness-turn-failed",{reason:n})}function mCe(n){return n==null?!0:(Pi(n?.kind)??Pi(n))==="completed"}var Qr=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g;#I;#p;#h=null;#u;#C;#B;#f;constructor({baseUrl:t,apiProxy:o,interactionScope:i=o,workspace:e,agentPreset:a,autostart:A=!1,dshBin:r="dsh",fetchImpl:s=fetch,createWebSocket:g=m=>new WebSocket(m),interactionReconnectDelayMs:c=500,rpcIdPrefix:I="im",logPrefix:d="dsh-im",commandExecutor:B,controlExecutor:f,sessionMaintenanceExecutor:Q,fileIngressExecutor:y}){if(typeof g!="function")throw new TypeError("createWebSocket must be a function");if(!Number.isFinite(c)||c<0)throw new TypeError("interactionReconnectDelayMs must be a non-negative number");if(typeof I!="string"||!I.trim())throw new TypeError("rpcIdPrefix must be a non-empty string");if(typeof d!="string"||!d.trim())throw new TypeError("logPrefix must be a non-empty string");if(B!==void 0&&typeof B!="function")throw new TypeError("commandExecutor must be a function");if(f!==void 0&&typeof f!="function")throw new TypeError("controlExecutor must be a function");if(Q!==void 0&&typeof Q!="function")throw new TypeError("sessionMaintenanceExecutor must be a function");if(y!==void 0&&typeof y!="function")throw new TypeError("fileIngressExecutor must be a function");if(this.#e=t===void 0?null:new URL(t),this.#A=this.#e?null:o,!this.#e&&(!this.#A||typeof this.#A!="object"))throw new TypeError("HarnessClient requires the current Host apiProxy or an explicit baseUrl");if(this.#A&&(!i||!["object","function"].includes(typeof i)))throw new TypeError("interactionScope must identify the current Host");this.#t=e,this.#r=a??void 0,this.#l=!!(this.#e&&A),this.#o=r,this.#i=s,this.#a=g,this.#n=c,this.#s=I.trim(),this.#d=d.trim(),this.#c=B,this.#g=f,this.#I=Q,this.#p=y,this.#u=Z1(this.#e?.origin??i),this.#C=this.#u.ownerships,this.#B=this.#u.claims,this.#f=this.#u.controls}async rpc(t,o={},i=3e4,e={}){let a=e.rpcId??`${this.#s}-${$_()}`,A=AbortSignal.timeout(i),r=e.signal?AbortSignal.any([e.signal,A]):A,s;try{if(this.#A){let[g,c,I]=t.split("."),d={host:"host",workspace:"workspace",session:"sessions",llm:"llm"}[g],B=d&&this.#A[d];if(I!==void 0||!Object.hasOwn(B??{},c)||typeof B[c]!="function")throw new ns("harness-api-not-found",t);s={type:"server-response",...await J1(()=>B[c]({rpcId:a,payload:o},r),r)}}else{let g=await this.#i(new URL(`/api/${t}`,this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:a,method:t,payload:o}),signal:r});if(!g.ok){let c=await pCe(g,this.#e.hostname);throw new ns(c,t,{status:g.status})}try{s=await g.json()}catch(c){throw new ns("harness-response-invalid",t,{cause:c})}}}catch(g){throw e.signal?.aborted||g instanceof ns?g:new ns(A.aborted?"harness-timeout":"harness-connect-failed",t,{cause:g})}if(s?.type!=="server-response"||s?.rpcId!==a)throw new ns("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid response for ${t}`)});if(!s.result||typeof s.result!="object"||typeof s.result.ok!="boolean")throw new ns("harness-response-invalid",t,{cause:new Error(`Harness returned an invalid result for ${t}`)});if(!s.result?.ok)throw new mn(t,s.result?.error);return s.result.value}async health(t={}){try{return await this.rpc("host.describe",{},5e3,t),!0}catch(o){throw o instanceof mn?new AT(o):o}}async ensureRunning(t={}){try{return await this.health(t)}catch(e){if(!this.#l)throw e}if(!this.#h||this.#h.exitCode!==null){let e=this.#e.port||(this.#e.protocol==="https:"?"443":"80");this.#h=nCe(this.#o,["web","--host",this.#e.hostname,"--port",e],{cwd:this.#t,env:process.env,stdio:["ignore","inherit","inherit"]}),this.#h.on("error",a=>{console.error(`[${this.#d}] failed to start Harness:`,a.message)})}let o=Date.now()+6e4,i;for(;Date.now(){let r=A&&i.signal?AbortSignal.any([A,i.signal]):A??i.signal;return this.rpc("session.selectModel",{sessionId:t,provider:o.provider,model:o.model,...o.reasoningEffort===void 0?{}:{reasoningEffort:o.reasoningEffort}},3e4,r?{...i,signal:r}:i)},a=this.#I?await this.#I({sessionId:t,operation:e}):await e();if(!a||typeof a!="object"||!eT(a.selected))throw new Error("Harness returned an invalid response for session.selectModel");return a}async isSessionRunning(t,o={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");await this.ensureRunning(o);let i=await this.rpc("session.list",{},3e4,o);if(!i||typeof i!="object"||!Array.isArray(i.items))throw new Error("Harness returned an invalid response for session.list");for(let e of i.items)if(!e||typeof e!="object"||typeof e.sessionId!="string"||!e.sessionId||typeof e.running!="boolean")throw new Error("Harness returned an invalid response for session.list");return i.items.find(e=>e.sessionId===t)?.running??!1}async adoptWorkspaceSession(t,o={}){return Y1(this,t,o)}async workspaceId(t={}){let{workspace:o=this.#t,...i}=t,{items:e}=await this.rpc("workspace.list",{},3e4,i),a=e.find(r=>r.path===o);return a?a.workspaceId:(await this.rpc("workspace.create",{path:o},3e4,i)).workspace.workspaceId}async createSession(t={}){let{agentPreset:o,...i}=t;await this.ensureRunning(i);let a={workspaceId:await this.workspaceId(i)},A=o!==void 0?o:this.#r;return A!=null&&(a.agentPreset=A),(await this.rpc("session.create",a,3e4,i)).sessionId}async renameSession(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o.trim())throw new TypeError("session title is required");return this.rpc("session.rename",{sessionId:t,title:o},3e4,i)}async executeCommand(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o)throw new TypeError("command line is required");if(!this.#c){let e=new Error("Harness command execution is unavailable");throw e.code="commands-unavailable",e}try{return await this.#c(t,o,i)}catch(e){throw e?.failure&&typeof e.failure=="object"?new mn("commands.execute",e.failure):e}}async readSessionHistory(t,{maxMessages:o=50,beforeSeq:i,timeoutMs:e=1e4,...a}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!Number.isSafeInteger(o)||o<1||i!==void 0&&(!Number.isSafeInteger(i)||i<0))throw new TypeError("Invalid history pagination");return this.rpc("session.history",{sessionId:t,maxMessages:o,...i===void 0?{}:{beforeSeq:i}},e,a)}async sessionExists(t,o={}){try{return await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,o),!0}catch(i){if(i instanceof mn&&i.code==="session-not-found")return!1;throw i}}async respondInteraction(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("rpcId is required");if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new TypeError("A Harness RPC result is required");let e=AbortSignal.timeout(i.timeoutMs??3e4),a=i.signal?AbortSignal.any([i.signal,e]):e,A={type:"client-response",rpcId:t,result:o},r;if(this.#A)r=await J1(()=>this.#A.respond(A),a);else{let g=await this.#i(new URL("/api/respond",this.#e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(A),signal:a});if(!g.ok)throw new Error(`Harness transport respond failed: HTTP ${g.status}`);r=await g.json()}if(r?.accepted===!0)return r;if(r?.accepted!==!1||r.reason!=="bad-response"&&r.reason!=="not-pending")throw new Error("Harness returned an invalid interaction response receipt");let s=r.reason;throw new xd(`interaction-${s}`,`Harness interaction response was rejected (${s})`)}async watchInteractions(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(!o||typeof o.addEventListener!="function")throw new TypeError("watchInteractions requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onInteraction must be a function");if(e!==void 0&&typeof e!="function")throw new TypeError("onResolved must be a function");if(a!==void 0&&typeof a!="function")throw new TypeError("onOpen must be a function");for(;!o.aborted;){try{await this.#M(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A})}catch(r){if(o.aborted)return;console.warn(`[${this.#d}] Harness interaction stream disconnected:`,r.message)}if(o.aborted)return;try{await Au(this.#n,o)}catch{if(o.aborted)return;throw new Error("Harness interaction reconnect wait failed")}}}#Q(t,o){let i=this.#C.get(t)??new Set;o.order=this.#u.nextOrder,this.#u.nextOrder+=1,i.add(o),this.#C.set(t,i)}#S(t,o){let i=this.#C.get(t);i?.delete(o),i?.size===0&&this.#C.delete(t);for(let[e,a]of this.#B)a.ownership===o&&this.#B.delete(e)}#y(t){if(!t.control)return;let o=this.#f.get(t.control.owner);o||(o=new Map,this.#f.set(t.control.owner,o));let i=o.get(t.control.key)??new Set;i.add(t),o.set(t.control.key,i)}#m(t){if(!t.control)return;let o=this.#f.get(t.control.owner),i=o?.get(t.control.key);i?.delete(t),i?.size===0&&o.delete(t.control.key),o?.size===0&&this.#f.delete(t.control.owner)}#D(t,o){let i=q1(o);return i?[...this.#f.get(i.owner)?.get(i.key)??[]].filter(a=>a.sessionId===t).sort((a,A)=>a.order-A.order):[]}#E(t,o){return this.#D(t,o).find(i=>i.started&&i.active&&!i.completed&&i.turn!==null)??null}async#R(t,o,i){let e=this.#D(t,o);if(e.length===0)return null;try{let a=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,i);this.#_(t,a.events??[])}catch(a){if(!(a instanceof mn)||a.code!=="session-not-found")throw a;for(let A of e)A.active=!1,A.completed=!0;return null}return this.#E(t,o)}async hasActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");return!!await this.#R(t,o,i)}async stopActiveTurn(t,o,i={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");let e=await this.#R(t,o,i);if(!e)return!1;if(e.stopRequested)return!0;if(this.#E(t,o)!==e)return!1;e.stopRequested=!0;try{if(this.#g){let a=this.#g({sessionId:t,expectedTurn:e.turn,promptRpcId:e.promptRpcId,action:"stop"});if(a&&typeof a.then=="function")throw new TypeError("controlExecutor must return synchronously");if(a!==void 0){if(typeof a!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return a||(e.stopRequested=!1),a}}return await this.rpc("session.cancel",{sessionId:t,keepInbox:!0},3e4,i),!0}catch(a){if(this.#E(t,o)===e&&(e.stopRequested=!1),a instanceof mn&&a.code==="session-not-found")return!1;throw a}}async steerActiveTurn(t,o,i,e={}){if(typeof t!="string"||!t)throw new TypeError("sessionId is required");if(typeof o!="string"||!o.trim())throw new TypeError("Steering text is required");let a=await this.#R(t,i,e);if(!a||a.stopRequested||this.#E(t,i)!==a)return!1;if(this.#g){let A=this.#g({sessionId:t,expectedTurn:a.turn,promptRpcId:a.promptRpcId,action:"steer",text:o});if(A&&typeof A.then=="function")throw new TypeError("controlExecutor must return synchronously");if(A!==void 0){if(typeof A!="boolean")throw new TypeError("controlExecutor must return a boolean or undefined");return A}}return await this.rpc("session.prompt",{sessionId:t,mode:"steer",content:[{type:"text",text:o}],clientTimeZone:Intl.DateTimeFormat().resolvedOptions().timeZone},3e4,e),!0}#_(t,o){for(let i of this.#C.get(t)??[])X1(i,o)}async#O(t,o){let i=await this.rpc("session.history",{sessionId:t,maxMessages:50},3e4,{signal:o});this.#_(t,i.events??[])}#w(t,o,i){let e=this.#B.get(o);if(e&&this.#C.get(t)?.has(e.ownership))return e;let a=[...this.#C.get(t)??[]],A=a.filter(s=>s.active).sort((s,g)=>s.order-g.order);if(A.length>0)return{ownership:A[0],recovered:!1};let r=a.filter(s=>!s.started&&!s.completed).sort((s,g)=>s.order-g.order)[0]??null;return r?{ownership:r,recovered:!0}:null}async#T(t,o,i){if(!this.#p)throw new ko("inbound-file-ingress-unavailable","Harness file ingress is unavailable in this Host process.");let a=(await this.rpc("session.list",{},3e4,{signal:i}))?.items?.find(A=>A?.sessionId===t)?.cwd;return this.#p({sessionId:t,workspace:a,files:o,signal:i})}async ask(t,o,i={}){typeof i=="number"&&(i={timeoutMs:i});let e=i.timeoutMs??6e5,a=i.signal,A=typeof i.onUpdate=="function"?i.onUpdate:null,r=i.progressMode==="all"?"all":"latest",s=typeof i.onArtifact=="function"?i.onArtifact:null,g=typeof i.onInteraction=="function"?i.onInteraction:void 0,c=typeof i.onInteractionResolved=="function"?i.onInteractionResolved:void 0,I=q1(i.control),d=Array.isArray(i.files)?i.files.filter(Boolean):[];await this.ensureRunning({signal:a});let B=await this.rpc("session.history",{sessionId:t,maxMessages:1},3e4,{signal:a}),f=Math.max(-1,...(B.events??[]).map(({event:V})=>V.seq??-1)),Q=`${this.#s}-${$_()}`,y=new Kd({promptRpcId:Q,afterSeq:f}),m=g||c?new AbortController:null,T=m?a?AbortSignal.any([a,m.signal]):m.signal:null,_=m||I?{sessionId:t,promptRpcId:Q,active:!1,started:!1,completed:!1,stopRequested:!1,turn:null,openTurn:null,lastSeq:f,reconnect:null,order:-1,toolCalls:new Map,control:I}:null,R=null,x=!1,F=0,L=[],q=!1,z=!1,H=async()=>{if(!s||x||y.turn===null)return F;x=!0;let V=LI.take(t,y.turn,{signal:a});for(let U of V)try{await s(U),F+=1}catch(N){LI.release(U),console.warn(`[${this.#d}] ignored an artifact handoff failure:`,N.message)}return F};_&&(this.#Q(t,_),this.#y(_));let G=LI.openConsumer(t,Q);try{let V=o;if(d.length>0){let J=await this.#T(t,d,a);L.push(J),o=U_(o,J)}if(T){let J,X=new Promise(ie=>{J=ie});R=this.watchInteractions(t,{signal:T,onInteraction:g,onResolved:c,onOpen:J,ownership:_}),R.catch(()=>{}),await Promise.race([X,Au(3e4,T).then(()=>{throw new Error("Harness interaction stream did not open within 30 seconds")})])}let U=typeof o=="string"?[{type:"text",text:o}]:o;if(!Array.isArray(U)||U.length===0)throw new TypeError("Harness prompt content is required");let N=Intl.DateTimeFormat().resolvedOptions().timeZone,k=J=>this.rpc("session.prompt",{sessionId:t,mode:"queue",content:J,clientTimeZone:N},3e4,{rpcId:Q,signal:a});try{await k(U)}catch(J){let X=Zx(J)?Vx(U):[];if(X.length===0)throw J;let ie;try{ie=await this.#T(t,X,a)}catch(Se){throw a?.aborted?a.reason??Se:(console.warn(`[${this.#d}] unable to restage rejected images as workspace files:`,Se?.message??String(Se)),J)}L.push(ie);let oe=U_([...Wx(typeof V=="string"?[{type:"text",text:V}]:V),{type:"text",text:w(qx)}],{files:L.flatMap(Se=>Se?.files??[])});await k(oe)}q=!0;try{let J=Date.now()+e;for(;Date.now()0)return"";throw _?.stopRequested?V1():W1(y.reason)}throw new ss("harness-reply-timeout")}catch(J){if(!_?.stopRequested)throw J;if(y.answer)return y.answer;throw J?.code==="turn-stopped"?J:V1()}}finally{if(!q||z)for(let V of L)try{await V?.cleanup?.()}catch(U){console.warn(`[${this.#d}] unable to clean inbound files:`,U.message)}G(),_&&(this.#m(_),this.#S(t,_)),y.turn!==null&&LI.discard(t,y.turn),m?.abort(new DOMException("Harness turn finished","AbortError")),R&&await R.catch(()=>{})}}async#M(t,{signal:o,onInteraction:i,onResolved:e,onOpen:a,ownership:A}){let r=!1,s=null,g=Promise.resolve(),c=A==null,I=[],d=()=>{},B=m=>{d=m,A&&(A.reconnect=d);try{a?.()}catch(T){console.warn(`[${this.#d}] ignored an interaction open callback failure:`,T.message)}A&&this.#O(t,o).then(()=>{if(!r){c=!0;for(let T of I.splice(0))Q(T)}}).catch(T=>{s??=T,d()})},f=(m,T)=>{m&&(g=g.then(()=>m(T)).catch(_=>{s??=_,d()}))},Q=m=>{let T=m.payload;if(A&&T.type==="session/event"){this.#_(t,[T.event]);return}if(T.type==="question/requested"||T.type==="approval/requested"){let _=T.type==="question/requested"?"question":"approval",R=_==="question"?m.rpcId:T.approvalId,x=`${_}:${R}`;if(A){let L=this.#w(t,x,_);if(L?.ownership!==A)return;this.#B.set(x,L)}let F=_==="approval"&&A&&typeof T.callId=="string"?this.#B.get(x)?.ownership.toolCalls.get(T.callId):void 0;f(i,Object.freeze({kind:_,interactionId:R,rpcId:m.rpcId,sessionId:t,payload:T,recovered:A?this.#B.get(x)?.recovered===!0:!1,...F?{toolCall:F}:{},reconnect:d,respond:(L,q={})=>this.respondInteraction(m.rpcId,L,{...q,signal:q.signal??o})}));return}if(T.type==="question/resolved"||T.type==="approval/resolved"){let _=T.type==="question/resolved"?"question":"approval",R=_==="question"?T.questionRpcId:T.approvalId,x=`${_}:${R}`;if(A){if(this.#B.get(x)?.ownership!==A)return;this.#B.delete(x)}f(e,Object.freeze({kind:_,interactionId:R,sessionId:t,outcome:T.outcome,payload:T}))}},y=m=>{try{let T=m?.payload;if(m?.type!=="server-request"||typeof m.rpcId!="string"||!T||typeof T!="object"||m.method!==T.type)throw new Error("invalid server-request envelope");if(T.sessionId!==t)return;c?Q(m):I.push(m)}catch(T){console.warn(`[${this.#d}] ignored a malformed Harness interaction frame:`,T.message)}};try{await this.#P({signal:o,onOpen:B,onEnvelope:y})}finally{r=!0,A?.reconnect===d&&(A.reconnect=null),o.aborted||await g}if(!o.aborted&&s)throw s}async watchHarnessEvents({signal:t,onSessionEvent:o,onReconnect:i}={}){if(typeof o!="function")throw new TypeError("watchHarnessEvents requires onSessionEvent");if(!t||typeof t.addEventListener!="function")throw new TypeError("watchHarnessEvents requires an AbortSignal");if(i!==void 0&&typeof i!="function")throw new TypeError("onReconnect must be a function");for(;!t.aborted;){try{await this.#P({signal:t,onOpen:()=>{try{i?.()}catch(e){console.warn(`[${this.#d}] mux reconnect hook failed:`,e.message)}},onEnvelope:e=>{try{let a=e?.payload;if(e?.type!=="server-request"||!a||typeof a!="object"||e.method!==a.type||a.type!=="session/event"||typeof a.sessionId!="string"||!a.event||typeof a.event!="object")return;o({sessionId:a.sessionId,event:a.event})}catch(a){console.warn(`[${this.#d}] ignored a malformed global mux frame:`,a.message)}}})}catch(e){if(t.aborted)return;console.warn(`[${this.#d}] Harness event mux disconnected:`,e.message)}if(t.aborted)return;try{await Au(this.#n,t)}catch{if(t.aborted)return;throw new Error("Harness event mux reconnect wait failed")}}}#P(t){return j1({apiProxy:this.#A,baseUrl:this.#e,createWebSocket:this.#a,rpcId:`${this.#s}-${$_()}`,...t,onMalformed:o=>{console.warn(`[${this.#d}] ignored a malformed Harness mux frame:`,o.message)}})}stopManagedProcess(){this.#h?.exitCode===null&&this.#h.kill("SIGTERM")}};var JQ=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"dingtalk",logPrefix:"dsh-dingtalk"})}};import{mkdir as SCe,readFile as wCe,realpath as DCe,rename as OCe,stat as bCe,unlink as MCe,writeFile as _Ce}from"node:fs/promises";import{dirname as TCe,isAbsolute as t3,resolve as ru}from"node:path";var otA=Object.freeze({version:1,workspaces:Object.freeze({})});function UI(n){let t=new Error(n);return t.code=Sa,t}async function tT(n){return ru(await DCe(n))}async function NCe(n,t){if(n===t)return!0;try{return await tT(n)===await tT(t)}catch{return!1}}function jt(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n))throw new TypeError("Invalid bot id");return n}function di(n,t,o){let i=new Error(t,o);return i.code=n,i}function qQ(n){if(typeof n!="string"||!/^[A-Za-z0-9._:@-]{1,128}$/.test(n))throw di("invalid-target","Invalid target id");return n}function RCe(n){if(!n||typeof n!="object"||Array.isArray(n))throw di("invalid-target","Invalid target route");try{let t=JSON.stringify(n);if(t===void 0)throw new TypeError("route is not JSON");let o=JSON.parse(t);if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError("route is not an object");return o}catch(t){throw di("invalid-target","Invalid target route",{cause:t})}}function HI(n,{targetId:t}={}){if(!n||typeof n!="object"||Array.isArray(n))throw di("invalid-target","Invalid delivery target");let o=t===void 0?new Set(["targetId","name","kind","route"]):new Set(["name","kind","route"]);if(Object.keys(n).some(a=>!o.has(a)))throw di("invalid-target","Invalid delivery target");let i=qQ(t??n.targetId);if(typeof n.kind!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n.kind))throw di("invalid-target","Invalid target kind");let e;if(n.name!==void 0){if(typeof n.name!="string"||!n.name.trim()||n.name.trim().length>80)throw di("invalid-target","Invalid target name");e=n.name.trim()}return{targetId:i,...e===void 0?{}:{name:e},kind:n.kind,route:RCe(n.route)}}function kCe(n){let t=Object.create(null);if(n===void 0)return t;if(!n||typeof n!="object"||Array.isArray(n))return null;try{for(let[o,i]of Object.entries(n)){if(jt(o),!i||typeof i!="object"||Array.isArray(i))return null;let e=Object.create(null);for(let[a,A]of Object.entries(i)){let r=HI(A,{targetId:a}),{targetId:s,...g}=r;e[a]=g}t[o]=e}}catch{return null}return t}function vCe(n,t){let o=Object.create(null);if(n===void 0)return o;if(!n||typeof n!="object"||Array.isArray(n)){for(let i of Object.keys(t))o[i]=null;return o}for(let[i,e]of Object.entries(n))try{jt(i),o[i]=Hd(e)}catch{}return o}function PCe(n){if(!n||![1,2].includes(n.version)||!n.workspaces||typeof n.workspaces!="object"||Array.isArray(n.workspaces))return null;let t={};for(let[r,s]of Object.entries(n.workspaces)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(r)||typeof s!="string"||!t3(s))return null;t[r]=ru(s)}let o={};if(n.agentPresets!==void 0){if(!n.agentPresets||typeof n.agentPresets!="object"||Array.isArray(n.agentPresets))return null;for(let[r,s]of Object.entries(n.agentPresets)){if(!/^[A-Za-z0-9_-]{1,128}$/.test(r))return null;try{let g=vd(s);if(!g)return null;o[r]=g}catch{return null}}}let i=Object.create(null);if(n.contextEnhancement&&typeof n.contextEnhancement=="object"&&!Array.isArray(n.contextEnhancement))for(let[r,s]of Object.entries(n.contextEnhancement))/^[A-Za-z0-9_-]{1,128}$/.test(r)&&(i[r]=Gd(s));if(n.version===1&&n.deliveryTargets!==void 0)return null;let e=kCe(n.deliveryTargets);if(!e)return null;let a=vCe(n.accessPolicies,t);return{version:n.accessPolicies===void 0?n.version:2,workspaces:t,agentPresets:o,contextEnhancement:i,deliveryTargets:e,accessPolicies:a}}function GCe({version:n,workspaces:t,agentPresets:o,contextEnhancement:i,deliveryTargets:e,accessPolicies:a}){let A={version:n,workspaces:t};return Object.keys(o).length>0&&(A.agentPresets=o),Object.keys(i).length>0&&(A.contextEnhancement=i),n>=2&&Object.keys(e).length>0&&(A.deliveryTargets=e),n>=2&&Object.keys(a).length>0&&(A.accessPolicies=a),A}async function FCe(n,t){await SCe(TCe(n),{recursive:!0,mode:448});let o=`${n}.tmp`;await _Ce(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await OCe(o,n)}async function e3(n){if(typeof n!="string"||!n.trim()||!t3(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 t=ru(n.trim()),o;try{o=await bCe(t)}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 t}var oa=class{#e;#A;#t=1;#r={};#l={};#o={};#i=Object.create(null);#a=Object.create(null);#n=new Map;#s=1;#d=new Map;#c=1;#g=new Map;#I=new WeakMap;#p=new Set;#h=Promise.resolve();#u=new Map;constructor(t,{defaultWorkspace:o=process.cwd()}={}){if(typeof t!="string"||!t)throw new TypeError("workspace store path is required");this.#e=t,this.#A=ru(o)}async load(){try{let t=PCe(JSON.parse(await wCe(this.#e,"utf8")));if(!t)throw new Error("dsh-im workspace config is invalid");this.#t=t.version,this.#r=t.workspaces,this.#l=t.agentPresets,this.#o=t.contextEnhancement,this.#i=t.deliveryTargets,this.#a=t.accessPolicies}catch(t){if(t?.code!=="ENOENT")throw t;this.#t=1,this.#r={},this.#l={},this.#o={},this.#i=Object.create(null),this.#a=Object.create(null)}this.#n.clear(),this.#s=1,this.#d.clear(),this.#c=1,this.#g.clear(),this.#p.clear();for(let t of Object.keys(this.#r))this.#n.set(t,this.#C()),this.#d.set(t,this.#B());return this}has(t){let o=jt(t);return Object.hasOwn(this.#r,o)&&!this.#g.has(o)}incarnationFor(t){return this.#d.get(jt(t))??null}workspaceFor(t){return this.#r[jt(t)]??this.#A}agentPresetFor(t){return this.#l[jt(t)]??null}contextEnhancementFor(t){let o=jt(t);return this.has(o)&&Object.hasOwn(this.#o,o)?this.#o[o]:P_}accessPolicyFor(t){let o=jt(t);return this.has(o)&&Object.hasOwn(this.#a,o)?this.#a[o]:null}listDeliveryTargets(t){let o=jt(t);if(!this.has(o))throw di("unknown-bot","Unknown bot");return Object.entries(this.#i[o]??{}).map(([i,e])=>HI(e,{targetId:i})).sort((i,e)=>i.targetId.localeCompare(e.targetId))}deliveryTargetFor(t,o){let i=jt(t),e=qQ(o);if(!this.has(i))throw di("unknown-bot","Unknown bot");let a=this.#i[i]?.[e];return a?HI(a,{targetId:e}):null}async createDeliveryTarget(t,o){let i=jt(t),e=HI(o);return this.#S(i,async()=>{if(!this.has(i))throw di("unknown-bot","Unknown bot");if(Object.hasOwn(this.#i[i]??{},e.targetId))throw di("target-conflict","Target already exists");let{targetId:a,...A}=e,r={...this.#i,[i]:{...this.#i[i]??{},[a]:A}};return await this.#y(this.#o,r,2),this.#i=r,this.#t=2,HI(A,{targetId:a})})}async updateDeliveryTarget(t,o,i){let e=jt(t),a=qQ(o),A=HI(i,{targetId:a});return this.#S(e,async()=>{if(!this.has(e))throw di("unknown-bot","Unknown bot");if(!Object.hasOwn(this.#i[e]??{},a))throw di("unknown-target","Unknown target");let{targetId:r,...s}=A,g={...this.#i,[e]:{...this.#i[e],[a]:s}};return await this.#y(this.#o,g,2),this.#i=g,this.#t=2,HI(s,{targetId:a})})}async deleteDeliveryTarget(t,o){let i=jt(t),e=qQ(o);return this.#S(i,async()=>{if(!this.has(i))throw di("unknown-bot","Unknown bot");if(!Object.hasOwn(this.#i[i]??{},e))throw di("unknown-target","Unknown target");let a={...this.#i[i]};delete a[e];let A={...this.#i};return Object.keys(a).length>0?A[i]=a:delete A[i],await this.#y(this.#o,A,2),this.#i=A,this.#t=2,!0})}generationFor(t){return this.#n.get(jt(t))??null}async whenIdle(){await this.#h}async whenBotIdle(t){let o=jt(t);for(;;){let i=this.#u.get(o);if(!i||(await i,this.#u.get(o)===i))return}}async ensure(t,{workspace:o=this.#A,defaultAgentPreset:i,initialAccessPolicy:e}={}){let a=jt(t),A=ru(o);return this.#S(a,async()=>{let r=!this.#r[a],s=e!==void 0&&!Object.hasOwn(this.#a,a);if(r||s){let g=s?pc(e):void 0,c=r?vd(i):null,I=Object.hasOwn(this.#l,a),d=this.#l[a],B=s?{...this.#a,[a]:g}:this.#a;r&&(this.#r[a]=A,c&&(this.#l[a]=c),this.#n.set(a,this.#C()),this.#d.set(a,this.#B()));let f=s?2:this.#t;try{await this.#y(this.#o,this.#i,f,B)}catch(Q){throw r&&(delete this.#r[a],I?this.#l[a]=d:delete this.#l[a],this.#n.delete(a),this.#d.delete(a)),Q}this.#a=B,this.#t=f}else this.#n.has(a)||this.#n.set(a,this.#C());return this.#r[a]})}async setWorkspace(t,o,{clearSessions:i,incarnation:e}={}){let a=jt(t);if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let r=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw r.code="workspace-bot-not-found",r}let A=await e3(o);return this.#S(a,async()=>{if(!this.has(a)||e!==void 0&&e!==this.incarnationFor(a)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}if(A===this.workspaceFor(a))return A;let r=this.#r[a];this.#n.set(a,this.#C()),await i?.(),this.#r[a]=A;try{await this.#y()}catch(s){throw this.#r[a]=r,s}return A})}async setAgentPreset(t,o,{incarnation:i}={}){let e=jt(t);if(!this.has(e)||i!==void 0&&i!==this.incarnationFor(e)){let A=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw A.code="workspace-bot-not-found",A}let a=vd(o);return this.#S(e,async()=>{if(!this.has(e)||i!==void 0&&i!==this.incarnationFor(e)){let r=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw r.code="workspace-bot-not-found",r}let A=this.#l[e]??null;if(A===a)return a;a?this.#l[e]=a:delete this.#l[e];try{await this.#y()}catch(r){throw A?this.#l[e]=A:delete this.#l[e],r}return a})}async setContextEnhancement(t,o,{incarnation:i}={}){let e=jt(t),a=i===void 0?this.incarnationFor(e):i,A=FI(o);return this.#S(e,async()=>{if(!this.has(e)||a!==this.incarnationFor(e)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}let r={...this.#o,[e]:A};return await this.#y(r),this.#o=r,A})}async setAccessPolicy(t,o,{incarnation:i}={}){let e=jt(t),a=i===void 0?this.incarnationFor(e):i,A=pc(o);return this.#S(e,async()=>{if(!this.has(e)||a!==this.incarnationFor(e)){let s=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw s.code="workspace-bot-not-found",s}let r={...this.#a,[e]:A};return await this.#y(this.#o,this.#i,2,r),this.#a=r,this.#t=2,A})}async bindWorkspaceSession(t,o,{conversationKey:i,sessionId:e,clearSessions:a,setSession:A,incarnation:r,expectedGeneration:s}={}){let g=jt(t);if(typeof i!="string"||!i||typeof e!="string"||!e)throw new TypeError("conversationKey and sessionId are required");if(typeof a!="function"||typeof A!="function")throw new TypeError("session state callbacks are required");if(!this.has(g)||r!==void 0&&r!==this.incarnationFor(g)){let I=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw I.code="workspace-bot-not-found",I}let c=await tT(await e3(o));return this.#S(g,async()=>{if(!this.has(g)||r!==void 0&&r!==this.incarnationFor(g)){let I=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw I.code="workspace-bot-not-found",I}if(s!==void 0&&s!==this.generationFor(g))throw UI("The bot workspace changed before the session binding could be committed.");if(!await NCe(c,this.workspaceFor(g))){let I=this.#r[g];this.#n.set(g,this.#C()),await a(),this.#r[g]=c;try{await this.#y()}catch(d){throw this.#r[g]=I,d}}return await A(i,e),{workspace:c,sessionId:e,generation:this.#n.get(g)}})}async invalidateSessions(t,{clearSessions:o}={}){let i=jt(t);return this.#S(i,async()=>{this.#n.set(i,this.#C()),await o?.()})}async beginRemoval(t,{clearSessions:o}={}){let i=jt(t);return this.#S(i,async()=>{let e=this.#g.get(i);if(e)return e;let a=Object.freeze({});this.#g.set(i,a),this.#I.set(a,{botId:i,incarnation:this.incarnationFor(i)}),this.#n.set(i,this.#C());try{await o?.()}catch(A){throw this.#g.get(i)===a&&this.#g.delete(i),A}return a})}async abortRemoval(t){let{botId:o}=this.#f(t);return this.#S(o,async()=>this.#g.get(o)!==t?!1:(this.#g.delete(o),Object.hasOwn(this.#r,o)&&(this.#n.set(o,this.#C()),this.#d.has(o)||this.#d.set(o,this.#B())),!0))}async finishRemoval(t){let{botId:o,incarnation:i}=this.#f(t);return this.#S(o,async()=>this.#g.get(o)!==t?{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.#Q(o)))}async retireAfterConfigCommit(t){let o=jt(t);return this.#S(o,async()=>(this.#g.delete(o),this.#Q(o)))}flushPendingRemoval(t){if(this.#p.has(t))return this.#S(t,async()=>{this.#p.has(t)&&await this.#m()})}async remove(t){let o=await this.retireAfterConfigCommit(t);if(o.error)throw o.error;return o.removed}async reconcile(t){let o=new Set([...t].map(jt)),i=new Set([...Object.keys(this.#r),...Object.keys(this.#l),...Object.keys(this.#o),...Object.keys(this.#i),...Object.keys(this.#a),...this.#p]);for(let e of i)o.has(e)||await this.remove(e)}decorateStatus(t){return!t||typeof t!="object"||!Array.isArray(t.bots)?t:{...t,bots:t.bots.map(o=>o?.botId?{...o,workspace:this.workspaceFor(o.botId),agentPreset:this.agentPresetFor(o.botId),contextEnhancement:this.contextEnhancementFor(o.botId),accessPolicy:this.accessPolicyFor(o.botId)}:o)}}#C(){let t=this.#s;return this.#s+=1,t}#B(){let t=this.#c;return this.#c+=1,t}#f(t){if(!t||typeof t!="object")throw new TypeError("Invalid workspace removal transaction");let o=this.#I.get(t);if(!o)throw new TypeError("Invalid workspace removal transaction");return o}async#Q(t){let o=Object.hasOwn(this.#r,t),i=Object.hasOwn(this.#l,t),e=Object.hasOwn(this.#o,t),a=Object.hasOwn(this.#i,t),A=Object.hasOwn(this.#a,t),r=o||i||e||a||A||this.#p.has(t);if(delete this.#r[t],delete this.#l[t],delete this.#o[t],delete this.#i[t],delete this.#a[t],this.#n.delete(t),this.#d.delete(t),!r)return{removed:!1,persisted:!0,error:null,stale:!1};try{return await this.#m(),{removed:o,persisted:!0,error:null,stale:!1}}catch(s){return this.#p.add(t),{removed:o,persisted:!1,error:s,stale:!1}}}async#S(t,o){let i=this.#h.then(o,o),e=i.then(()=>{},()=>{});return this.#h=e,this.#u.set(t,e),e.finally(()=>{this.#u.get(t)===e&&this.#u.delete(t)}),i}async#y(t=this.#o,o=this.#i,i=this.#t,e=this.#a){await FCe(this.#e,GCe({version:i,workspaces:this.#r,agentPresets:this.#l,contextEnhancement:t,deliveryTargets:o,accessPolicies:e})),this.#p.clear()}async#m(){if(Object.keys(this.#r).length>0||Object.keys(this.#l).length>0||Object.keys(this.#o).length>0||Object.keys(this.#i).length>0||Object.keys(this.#a).length>0){await this.#y();return}try{await MCe(this.#e),this.#p.clear()}catch(t){if(t?.code!=="ENOENT")throw t;this.#p.clear()}}};function tu(n){if(!n)return null;let t=typeof n=="function"?n():n;return t&&typeof t.then=="function"?t.then(rs):rs(t)}function r3(){let n=new Error("Agent Preset \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\u3002");return n.code="agent-preset-unavailable",n}function Yd(n){if(n())return;let t=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw t.code="workspace-bot-not-found",t}function A3(n,t,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,r=tu(o);return r&&typeof r.then=="function"?r.then(A):A(r)};return t&&typeof t.then=="function"?t.then(i):i(t)}function LCe(n){return Promise.resolve(n.status())}function ja(n,{workspaces:t,method:o="remove",botIdFromRemoved:i=A=>A?.botId,saveMethod:e="save",botIdFromSave:a=A=>A?.botId}){if(!n||!t||typeof n[o]!="function")throw new TypeError("configStore removal observer dependencies are required");return new Proxy(n,{get(A,r){let s=Reflect.get(A,r,A);return r===o?async(...g)=>{let c=await s.apply(A,g),I=c?i(c,g):null;return I&&await t.retireAfterConfigCommit(I),c}:r===e&&typeof s=="function"?(...g)=>{let c=t.flushPendingRemoval(a(g[0],g));return c?c.then(()=>s.apply(A,g)):s.apply(A,g)}:typeof s=="function"?s.bind(A):s}})}function Ja(n,{botId:t,workspaces:o,state:i,agentPresetCatalog:e}={}){if(!n||!o||!i)throw new TypeError("harness, workspaces, and state are required");let a=o.incarnationFor(t),A=()=>o.has(t)&&o.incarnationFor(t)===a,r=async(I=e)=>{let d;try{d=await tu(I)??rs(null)}catch(B){throw Yd(A),B}return Yd(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:d}},s=new Map,g=new Proxy(n,{get(I,d){if(d==="agentPresetSettings")return async(f={})=>{f?.signal?.throwIfAborted(),Yd(A);let Q=await r();return f?.signal?.throwIfAborted(),Q};if(d==="updateAgentPreset")return async(f,Q={})=>{Q?.signal?.throwIfAborted(),Yd(A);let y=f==="--default"?null:vd(f),m=null;if(y&&({agentPresetCatalog:m}=await r(),Q?.signal?.throwIfAborted(),!m.items.some(T=>T.id===y)))throw r3();if(await o.setAgentPreset(t,y,{incarnation:a}),Yd(A),m)return{agentPreset:o.agentPresetFor(t),agentPresetCatalog:m};try{return await r()}catch(T){if(T?.code==="workspace-bot-not-found")throw T;return Yd(A),{agentPreset:o.agentPresetFor(t),agentPresetCatalog:rs(null)}}};if(d==="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(t)};if(d==="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((d==="listWorkspaces"||d==="listWorkspaceSessions"||d==="listModels")&&typeof I[d]=="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[d](...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(d==="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(t,f,{clearSessions:()=>i.clearSessions(),incarnation:a})};if(d==="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 _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}if(typeof I.adoptWorkspaceSession!="function")throw new TypeError("Harness does not support adopting workspace sessions");let y=o.generationFor(t),m=await I.adoptWorkspaceSession(Q);if(!A()){let _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}if(y!==o.generationFor(t))throw UI("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 T=await o.bindWorkspaceSession(t,m.workspace,{conversationKey:f,sessionId:Q,clearSessions:()=>i.clearSessions(),setSession:(_,R)=>i.setSession(_,R),incarnation:a,expectedGeneration:y});if(!A()){let _=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw _.code="workspace-bot-not-found",_}if(T.generation!==o.generationFor(t))throw UI("The bot workspace changed before the session binding completed.");return s.set(Q,T.generation),{...m,workspace:T.workspace,sessionId:T.sessionId}};if(d==="createSession")return async(f={})=>{if(await o.whenBotIdle(t),!A()){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}let Q=o.generationFor(t),y=o.agentPresetFor(t),m=await I.createSession({...f,workspace:o.workspaceFor(t),...y==null?{}:{agentPreset:y}});return s.set(m,Q),m};if(d==="workspaceSession")return f=>{if(typeof f!="string"||!f)throw new TypeError("sessionId is required");let Q=s.get(f)??o.generationFor(t);s.delete(f);let y=()=>A()&&Q===o.generationFor(t),m=async(_,R,x)=>{if(!y())throw UI(`The bot workspace changed before this ${x} started.`);let F=await I[_](f,...R);if(!y())throw UI(`The bot workspace changed while this ${x} was running.`);return F},T=async(_,R,x)=>{if(!y())throw UI(`The bot workspace changed before this ${x} started.`);return I[_](f,...R)};return Object.freeze({sessionId:f,async sessionExists(..._){if(!y())return!1;let R=await I.sessionExists(f,..._);return y()&&R},models(..._){return m("getSessionModels",_,"model listing")},readHistory(..._){return m("readSessionHistory",_,"history read")},...typeof I.renameSession=="function"?{renameTitle(..._){return T("renameSession",_,"title rename")}}:{},selectModel(..._){return m("selectSessionModel",_,"model selection")},isRunning(..._){return m("isSessionRunning",_,"run-state check")},hasActiveTurn(..._){return m("hasActiveTurn",_,"turn ownership check")},stopActiveTurn(..._){return T("stopActiveTurn",_,"turn stop")},steerActiveTurn(..._){return T("steerActiveTurn",_,"turn steering")},ask(..._){if(!y())throw UI("The bot workspace changed before this prompt started.");return I.ask(f,..._)}})};if(d==="sessionExists")return(f,...Q)=>{if(!A())return!1;let y=s.get(f);return y!==void 0&&y!==o.generationFor(t)?(s.delete(f),!1):I.sessionExists(f,...Q)};if(d==="ask")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this prompt started.");throw m.code=Sa,m}return I.ask(f,...Q)};if(d==="executeCommand"&&typeof I.executeCommand=="function")return(f,...Q)=>{let y=s.get(f);if(s.delete(f),!A()||y!==void 0&&y!==o.generationFor(t)){let m=new Error("The bot workspace changed before this command started.");throw m.code=Sa,m}return I.executeCommand(f,...Q)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}}),c=new Proxy(i,{get(I,d){if(d===a_)return I;if(d==="sessionFor")return(f,...Q)=>{if(!A())return null;let y=I.sessionFor(f,...Q);return y&&!s.has(y)&&s.set(y,o.generationFor(t)),y};if(d==="setSession")return(f,Q,...y)=>{let m=s.get(Q);return!A()||m!==void 0&&m!==o.generationFor(t)?(s.delete(Q),!1):I.setSession(f,Q,...y)};let B=Reflect.get(I,d,I);return typeof B=="function"?B.bind(I):B}});return Object.freeze({harness:g,state:c})}function qa(n,{workspaces:t,stateFor:o,agentPresetCatalog:i}={}){if(!n||!t||typeof o!="function")throw new TypeError("controller, workspaces, and stateFor are required");let e=new Map,a=(d,B)=>{let Q=(e.get(d)??Promise.resolve()).catch(()=>{}).then(B);return e.set(d,Q),Q.finally(()=>{e.get(d)===Q&&e.delete(d)})},A=d=>A3(t,d,i),r=(d,B)=>{let f=t.incarnationFor(d);return a(d,async()=>{if(!(await n.status())?.bots?.some(m=>m?.botId===d)){let m=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw m.code="workspace-bot-not-found",m}let y=await o(d);return await t.setWorkspace(d,B,{clearSessions:()=>y.clearSessions(),incarnation:f}),A(await n.status())})},s=(d,B)=>{let f=t.incarnationFor(d),Q=vd(B);return a(d,async()=>{if(!(await n.status())?.bots?.some(T=>T?.botId===d)){let T=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw T.code="workspace-bot-not-found",T}let m=Q&&i?await tu(i):null;if(Q&&i&&!m?.items.some(T=>T.id===Q))throw r3();return await t.setAgentPreset(d,Q,{incarnation:f}),A3(t,await n.status(),m??i)})},g=(d,B,f)=>{let Q=t.incarnationFor(d),y=FI(B);return a(d,async()=>{let m=await n.status();if(!m?.bots?.some(F=>F?.botId===d)){let F=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw F.code="workspace-bot-not-found",F}let T=await tu(i),_=t.decorateStatus(m),R={..._,bots:_.bots.map(F=>F?.botId===d?{...F,contextEnhancement:y}:F),...T?{agentPresetCatalog:T}:{}},x=f?await f(R):R;return await t.setContextEnhancement(d,y,{incarnation:Q}),x})},c=(d,B,f)=>{let Q=t.incarnationFor(d),y=pc(B);return a(d,async()=>{let m=await n.status();if(!m?.bots?.some(F=>F?.botId===d)){let F=new Error("\u627E\u4E0D\u5230\u8981\u4FEE\u6539\u7684\u673A\u5668\u4EBA\u3002");throw F.code="workspace-bot-not-found",F}let T=await tu(i),_=t.decorateStatus(m),R={..._,bots:_.bots.map(F=>F?.botId===d?{...F,accessPolicy:y}:F),...T?{agentPresetCatalog:T}:{}},x=f?await f(R):R;return await t.setAccessPolicy(d,y,{incarnation:Q}),x})},I=(d,B)=>a(d,async()=>{let f=await t.beginRemoval(d,{clearSessions:async()=>{try{let Q=await o(d);if(!Q||typeof Q.clearSessions!="function")throw new TypeError("bot state does not support session cleanup");await Q.clearSessions()}catch(Q){console.warn(`[dsh-im] ignored session cleanup failure while deleting bot ${d}:`,Q?.message??Q)}}});try{let Q=await B();return await t.finishRemoval(f),A(Q)}catch(Q){let y=await LCe(n).catch(()=>null);throw Array.isArray(y?.bots)&&!y.bots.some(T=>T?.botId===d)?await t.finishRemoval(f):await t.abortRemoval(f),Q}});return new Proxy(n,{get(d,B){if(B==="updateWorkspace")return r;if(B==="updateAgentPreset")return s;if(B==="updateContextEnhancement")return g;if(B==="updateAccessPolicy")return c;let f=Reflect.get(d,B,d);return typeof f!="function"?f:B==="deleteBot"?(Q,...y)=>I(Q,()=>f.call(d,Q,...y)):B==="disconnect"?async(...Q)=>{let m=(await d.status())?.bots?.[0]?.botId;return m?I(m,()=>f.apply(d,Q)):A(f.apply(d,Q))}:(...Q)=>A(f.apply(d,Q))}})}var a3=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function UCe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function HCe(n){return typeof n=="string"&&n.length>0&&n.length<=512&&n.trim()===n&&!/[\s:\u0000-\u001f\u007f]/u.test(n)}function rT(n,t){let o=`${t}:`;if(!n.startsWith(o))return null;let i=n.slice(o.length);return HCe(i)?i:null}function au(n,t){for(let[o,i,e]of t){let a=rT(n,o);if(a)return{kind:i,route:{[e]:a}}}return null}function KCe(n){let t=rT(n,"p2p");return t?.startsWith("ou_")?{kind:"user",route:{openId:t}}:au(n,[["group","group","chatId"]])}function xCe(n){let t=rT(n,"direct");if(t&&/^[A-Za-z0-9_-]{1,128}$/.test(t))return{kind:"conversation",route:{channelId:t}};let o=/^group:([^:]+):(\d{1,20}(?:\.\d{1,20})?)$/.exec(n);return!o||!/^[A-Za-z0-9_-]{1,128}$/.test(o[1])?null:{kind:"thread",route:{channelId:o[1],threadTs:o[2]}}}function YCe(n){let t=/^(direct|group):(-?\d+)(?::([1-9]\d*))?$/.exec(n);if(!t)return null;let o=Number(t[2]);if(!Number.isSafeInteger(o)||t[1]==="direct"&&t[3]!==void 0)return null;if(t[3]===void 0)return{kind:"chat",route:{chatId:t[2]}};let i=Number(t[3]);return!Number.isSafeInteger(i)||i<=0?null:{kind:"topic",route:{chatId:t[2],messageThreadId:i}}}function jCe(n){let t=/^(?:direct|group):(\d{1,32})$/.exec(n);return t?{kind:"channel",route:{channelId:t[1]}}:null}function JCe(n){let t=/^direct:(\d{5,32}@(s\.whatsapp\.net|lid))$/.exec(n);if(t)return{kind:"user",route:{jid:t[1]}};let o=/^group:(\d{5,32}(?:-\d{1,32})?@g\.us)$/.exec(n);return o?{kind:"group",route:{jid:o[1]}}:null}function qCe(n,t){if(!a3.has(n)||typeof t!="string")return null;switch(n){case"weixin":return au(t,[["p2p","user","toUserId"]]);case"feishu":return KCe(t);case"dingtalk":return au(t,[["p2p","user","userId"],["group","group","openConversationId"]]);case"wecom":return au(t,[["direct","user","chatId"],["group","group","chatId"]]);case"qq":return au(t,[["c2c","user","userOpenId"],["group","group","groupOpenId"]]);case"slack":return xCe(t);case"telegram":return YCe(t);case"discord":return jCe(t);case"whatsapp":return JCe(t);default:return null}}function i3(n,t){if(!a3.has(n)||!UCe(t))return[];let o=[],i=new Set;for(let e of Object.keys(t)){let a=qCe(n,e);if(!a)continue;let A=JSON.stringify(a);i.has(A)||(i.add(A),o.push(a))}return o}var zCe=new Set(["weixin","feishu","dingtalk","wecom","qq","slack","telegram","discord","whatsapp"]);function VQ(n){return zCe.has(n)}function Ec(n){let t=new Error(n);return t.code="invalid-target",t}function VCe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function aT(n,t,o){if(!VCe(n))throw Ec(`${o} must be an object`);if(Object.keys(n).find(e=>!t.includes(e))!==void 0)throw Ec(`${o} contains an unknown field`)}function zQ(n,t){if(typeof n!="string"||!n||n.trim()!==n)throw Ec(`${t} must be a non-empty string without surrounding whitespace`);return n}function WCe(n){if(typeof n!="string"||!n.trim()||n.trim().length>80)throw Ec("target.name must contain 1 to 80 characters");return n.trim()}function hc(n,t){aT(n,t,"route");let o={};for(let i of t)o[i]=zQ(n[i],`route.${i}`);return o}function hg(n,t){if(!t.includes(n))throw Ec("target kind is not supported by this channel");return n}function ZCe(n,t,o){switch(n){case"weixin":return hg(t,["user"]),hc(o,["toUserId"]);case"feishu":return hg(t,["user","group"]),hc(o,t==="user"?["openId"]:["chatId"]);case"dingtalk":return hg(t,["user","group"]),hc(o,t==="user"?["userId"]:["openConversationId"]);case"wecom":return hg(t,["user","group"]),hc(o,["chatId"]);case"qq":return hg(t,["user","group"]),hc(o,t==="user"?["userOpenId"]:["groupOpenId"]);case"slack":return hg(t,["conversation","thread"]),hc(o,t==="conversation"?["channelId"]:["channelId","threadTs"]);case"telegram":{hg(t,["chat","topic"]),aT(o,t==="chat"?["chatId"]:["chatId","messageThreadId"],"route");let i=zQ(o.chatId,"route.chatId");if(!/^-?\d+$/.test(i))throw Ec("route.chatId must be a decimal string");if(t==="chat")return{chatId:i};if(!Number.isSafeInteger(o.messageThreadId)||o.messageThreadId<=0)throw Ec("route.messageThreadId must be a positive integer");return{chatId:i,messageThreadId:o.messageThreadId}}case"discord":return hg(t,["channel"]),hc(o,["channelId"]);case"whatsapp":{hg(t,["user","group"]);let i=hc(o,["jid"]);if(!(t==="user"?/^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(i.jid):/^\d{5,32}(?:-\d{1,32})?@g\.us$/.test(i.jid)))throw Ec(`route.jid must be a ${t} WhatsApp JID`);return i}default:throw new TypeError(`Unsupported delivery channel: ${n}`)}}function jd(n,t,{targetIdRequired:o=!0}={}){if(!VQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);aT(t,o?["targetId","name","kind","route"]:["name","kind","route"],"target");let i={};return o&&(i.targetId=zQ(t.targetId,"target.targetId")),t.name!==void 0&&(i.name=WCe(t.name)),i.kind=zQ(t.kind,"target.kind"),i.route=ZCe(n,i.kind,t.route),i}function za({channel:n,workspaces:t,coreController:o,stateFor:i}){if(!VQ(n))throw new TypeError(`Unsupported delivery channel: ${n}`);if(!t||typeof t!="object")throw new TypeError("delivery adapter requires a workspace store");if(!o||typeof o!="object")throw new TypeError("delivery adapter requires a proactive text controller");if(typeof i!="function")throw new TypeError("delivery adapter requires a bot state getter");return Object.freeze({channel:n,ownsBot:e=>t.has(e),listTargets:e=>t.listDeliveryTargets(e),async listSuggestions(e){let a=await i(e);if(!a||typeof a.snapshot!="function")throw new TypeError("delivery suggestion state cannot be inspected");return i3(n,a.snapshot()?.sessions).map(r=>jd(n,r,{targetIdRequired:!1}))},createTarget:(e,a)=>t.createDeliveryTarget(e,jd(n,a)),updateTarget:(e,a,A)=>t.updateDeliveryTarget(e,a,jd(n,A,{targetIdRequired:!1})),deleteTarget:(e,a)=>t.deleteDeliveryTarget(e,a),async sendText(e,a,A,r={}){let s=jd(n,a);if(typeof o.sendProactiveText!="function")throw new TypeError("delivery controller cannot send proactive text");return await o.sendProactiveText(e,s,A,r),{sent:!0}}})}var o3=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function XCe(n){if(!Array.isArray(n)||n.length===0)return[...o3];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...o3]}var WQ=class{#e;#A;#t;#r;#l;#o;#i;#a=null;#n=null;#s=0;#d=!1;#c=!1;#g;#I;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.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=t,this.#A=o,this.#t=i,this.#r=XCe(e),this.#l=Number.isFinite(a)&&a>=0?a:15e3,this.#o=A,this.#i=r,this.#g=new Promise(s=>{this.#I=s})}get ready(){return this.#g}start(){return this.#c||this.#d?this:(this.#c=!0,this.#p(0),this)}async close(){this.#d||(this.#d=!0,this.#a!==null&&this.#i(this.#a),this.#a=null,await this.#n?.catch(()=>{}),this.#I?.(null),this.#I=null)}#p(t){this.#d||(this.#a=this.#o(()=>{this.#a=null,this.#h()},t),this.#a?.unref?.())}async#h(){if(this.#d||this.#n)return;let t=this.#u();this.#n=t;try{await t}finally{this.#n===t&&(this.#n=null)}}async#u(){try{if(await this.#A.ensureRunning(),this.#d)return;let t=await this.#e.initialize();if(this.#d)return;this.#I?.(t),this.#I=null;let{configured:o,connected:i}=t.totals;if(i{let A={namespace:"commands",method:"execute",args:{agentId:i,line:e,images:[]},signal:a.signal};try{return await o.invoke(A)}catch(r){if(r?.name!=="TypertGatewayError"||r.code!=="arguments-invalid"||r.endpoint!=="commands/execute"||r.message!=='typert gateway: commands/execute: args fields do not match the descriptor: unexpected "images"')throw r;return a.signal?.throwIfAborted(),o.invoke({...A,args:{agentId:i,line:e}})}}}}import{randomUUID as oT}from"node:crypto";var ZQ=new WeakMap;function $Ce(n){let t=n?.failure;return t&&typeof t=="object"&&typeof t.code=="string"&&typeof t.message=="string"?{code:t.code,message:t.message,details:t.details&&typeof t.details=="object"?t.details:{}}:n?.name==="AbortError"||n?.name==="RemoteInvocationCancelled"?{code:"cancelled",message:n instanceof Error?n.message:"Harness request was cancelled",details:{}}:{code:"internal",message:n instanceof Error?n.message:String(n),details:{}}}function Fo(n,t){return Promise.resolve().then(t).then(o=>({rpcId:n.rpcId,result:{ok:!0,value:o}}),o=>({rpcId:n.rpcId,result:{ok:!1,error:$Ce(o)}}))}function n3(n,t,o,i){return{namespace:n,method:t,args:o,...i===void 0?{}:{signal:i}}}function XQ(n,t){let o=new Error(n);return o.name="UserQuestionError",o.code=t,o}function eBe(n,t){return!n||typeof n!="object"||n.sessionId!==t.sessionId||!n.answer||typeof n.answer!="object"||!Array.isArray(n.answer.answers)||n.answer.answers.length!==t.questions.length?!1:n.answer.answers.every((o,i)=>{let e=t.questions[i];if(!o||typeof o!="object"||o.id!==e.id||!Array.isArray(o.selected)||o.selected.some(r=>typeof r!="string")||new Set(o.selected).size!==o.selected.length||o.custom!==void 0&&typeof o.custom!="string")return!1;let a=o.custom?.trim();if(a!==void 0&&!a||e.multiSelect!==!0&&(a!==void 0&&o.selected.length>0||o.selected.length>1))return!1;let A=new Set(e.options?.map(r=>r.label)??[]);return o.selected.every(r=>A.has(r))})}function ABe(n){if(n?.type==="event"&&n.event&&typeof n.event=="object")return[{event:n.event}];let t=n?.type==="chunks"?n.event:null;if(!t||typeof t!="object")throw new Error("Harness returned an invalid session history record");let{data:o}=t,i=t.type,e=i==="chunkrow/tool-call-chunks"?o?.args:o?.texts;if(!o||!Array.isArray(e)||e.length===0||e.some(A=>typeof A!="string")||!Array.isArray(o.dt)||o.dt.length!==e.length-1)throw new Error("Harness returned an invalid packed session chunk");let a=t.time;return e.map((A,r)=>{r>0&&(a+=o.dt[r-1]);let s;if(i==="chunkrow/text-chunks")s={type:"text-delta",index:o.index,text:A};else if(i==="chunkrow/reasoning-chunks")s={type:"reasoning-delta",index:o.index,text:A};else if(i==="chunkrow/tool-call-chunks")s={type:"tool-call-delta",index:o.index,id:o.id,...Object.hasOwn(o,"name")?{name:o.name}:{},argumentsDelta:A};else throw new Error(`Harness returned an unsupported packed session chunk: ${String(i)}`);return{event:{type:"assistant/chunk",seq:t.seq+r,time:a,data:{turn:o.turn,step:o.step,chunk:s}}}})}function s3(n){if(!Array.isArray(n))throw new Error("Harness returned invalid session history records");return n.flatMap(ABe)}var nT=class{#e=[];#A=null;#t=!1;#r;#l;#o;constructor(t,o){this.#r=t,this.#o=o,this.#l=()=>this.close(),t?.addEventListener("abort",this.#l,{once:!0}),t?.aborted&&this.close()}push(t){if(!this.#t)if(this.#A){let o=this.#A;this.#A=null,o({value:t,done:!1})}else this.#e.push(t)}next(){return this.#e.length>0?Promise.resolve({value:this.#e.shift(),done:!1}):this.#t?Promise.resolve({value:void 0,done:!0}):new Promise(t=>{this.#A=t})}return(){return this.close(),Promise.resolve({value:void 0,done:!0})}close(){if(!this.#t&&(this.#t=!0,this.#r?.removeEventListener("abort",this.#l),this.#o?.(),this.#o=null,this.#A)){let t=this.#A;this.#A=null,t({value:void 0,done:!0})}}[Symbol.asyncIterator](){return this}},sT=class{#e;#A;#t=new Set;#r=new Map;#l=new Map;#o=new Map;#i=[];#a=!1;constructor(t,o,i){this.#e=o,this.#A=i,this.host=Object.freeze({describe:e=>Fo(e,()=>({ready:!0,transport:"typert"}))}),this.workspace=Object.freeze({list:(e,a)=>Fo(e,()=>this.#d(a)),create:(e,a)=>Fo(e,()=>this.#n("workspace","create",{request:e.payload},a))}),this.sessions=Object.freeze({list:(e,a)=>Fo(e,()=>this.#n("session","list",{_request:e.payload},a)),create:(e,a)=>Fo(e,()=>this.#n("session","create",{request:e.payload},a)),history:(e,a)=>Fo(e,()=>this.#g(e.payload,a)),prompt:(e,a)=>Fo(e,()=>this.#n("session","prompt",{request:{requestId:e.rpcId,...e.payload}},a)),rename:(e,a)=>Fo(e,()=>this.#n("session","rename",{request:e.payload},a)),cancel:(e,a)=>Fo(e,()=>this.#n("session","cancel",{request:{sessionId:e.payload.sessionId}},a)),models:(e,a)=>Fo(e,()=>this.#h(e.payload.sessionId,a)),selectModel:(e,a)=>Fo(e,()=>this.#n("session","selectModel",{request:e.payload},a))}),this.llm=Object.freeze({models:(e,a)=>Fo(e,async()=>{let A=await this.#p(a);return{groups:A.groups,failures:A.failures}})}),this.events=Object.freeze({mux:(e,a)=>this.#u(a)}),this.respond=e=>Promise.resolve(this.#m(e)),typeof t?.on=="function"&&(this.#i.push(t.on("session/event",(e,a)=>{let A=e?.id;typeof A!="string"||!a||typeof a!="object"||(Number.isSafeInteger(a.seq)&&this.#I(A,a.seq),this.#C({type:"session/event",sessionId:A,event:a}))},{global:!0})),this.#i.push(t.on("approval/request",(e,a)=>this.#y(e,a),{global:!0,prepend:!0})),this.#i.push(t.on("user-questions/request",(e,a)=>this.#Q(e,a),{global:!0,prepend:!0})))}async#n(t,o,i,e){return this.#e.invoke(n3(t,o,i,e))}async#s(t,o,i,e){let a=new AbortController,A=e?AbortSignal.any([e,a.signal]):a.signal,r;try{r=(await this.#e.stream(n3(t,o,i,A)))[Symbol.asyncIterator]();let g=await r.next();if(g.done)throw new Error(`Harness ${t}.${o} stream ended before its baseline`);return g.value}finally{a.abort(new DOMException("Baseline received","AbortError")),await Promise.resolve(r?.return?.()).catch(()=>{})}}async#d(t){let o=await this.#s("workspace","follow",{},t);if(o?.type!=="baseline"||!o.value||typeof o.value!="object")throw new Error("Harness workspace.follow returned no baseline");return o.value}async#c(t,o,i){let e=await this.#s("session","follow",{request:{address:{kind:"session",sessionId:t},maxMessages:o}},i);if(e?.type!=="snapshot"||!Number.isSafeInteger(e.cursor))throw new Error("Harness session.follow returned no snapshot");return this.#I(t,e.cursor),e}async#g(t,o){let{sessionId:i,maxMessages:e=50,beforeSeq:a}=t,A=this.#o.get(i);if(A===void 0){let s=await this.#c(i,e,o);if(A=this.#o.get(i)??s.cursor,a===void 0&&A===s.cursor)return{events:s3(s.records),hasMore:s.hasMore===!0,...s.projections===void 0?{}:{projections:s.projections}}}let r=await this.#n("session","page",{request:{address:{kind:"session",sessionId:i},throughSeq:A,maxMessages:e,...a===void 0?{}:{beforeSeq:a}}},o);return{events:s3(r.records),hasMore:r.hasMore===!0}}#I(t,o){let i=this.#o.get(t);(i===void 0||o>i)&&this.#o.set(t,o)}#p(t){return this.#n("session","modelCatalog",{},t)}async#h(t,o){let[i,e]=await Promise.all([this.#p(o),this.#n("session","list",{_request:{}},o)]),a=e?.items?.find(s=>s?.sessionId===t);if(!a){let s=new Error(`session "${t}" not found`);throw s.failure={code:"session-not-found",message:s.message,details:{sessionId:t}},s}let A=a.projections?.values?.modelSelection,r=A?.next??A?.lastUsed??i.default;return{current:r,routable:i.routableProviders.includes(r.provider),groups:i.groups,failures:i.failures}}#u(t){let o;o=new nT(t,()=>this.#t.delete(o)),this.#t.add(o);for(let i of this.#r.values())o.push(this.#f(i));for(let i of this.#l.values())o.push(this.#S(i));return o}#C(t,o=oT()){let i={rpcId:o,payload:t};for(let e of this.#t)e.push(i)}#B(t){let o=t?.session?.id??t?.id;return typeof o!="string"||!t?.session||!Array.isArray(t.session.events)?null:$1(this.#A,o,t.session.events)?{sessionId:o,session:t.session}:null}#f(t){return{rpcId:t.rpcId,payload:{type:"question/requested",sessionId:t.sessionId,questions:t.questions}}}#Q(t,o){let i=this.#B(t?.agent);return i?t.signal?.aborted?Promise.reject(XQ("ask_user_question was aborted before the user answered","ASK_ABORTED")):new Promise((e,a)=>{let A={rpcId:oT(),sessionId:i.sessionId,questions:t.questions,signal:t.signal,settle:(s,g)=>{this.#r.delete(A.rpcId)&&(t.signal?.removeEventListener("abort",r),this.#C({type:"question/resolved",sessionId:A.sessionId,questionRpcId:A.rpcId,outcome:s}),s==="answered"?e(g):a(g))}},r=()=>A.settle("cancelled",XQ("ask_user_question was aborted before the user answered","ASK_ABORTED"));this.#r.set(A.rpcId,A),t.signal?.addEventListener("abort",r,{once:!0}),this.#C(this.#f(A).payload,A.rpcId)}):o()}#S(t){return{rpcId:t.rpcId,payload:{type:"approval/requested",sessionId:t.sessionId,approvalId:t.approvalId,toolName:t.toolName,...t.callId===void 0?{}:{callId:t.callId},...t.reason===void 0?{}:{reason:t.reason}}}}#y(t,o){let i=this.#B(t?.agent);if(!i)return o();if(t.signal?.aborted)return Promise.resolve("cancelled");let e=new Set([...this.#l.values()].map(r=>r.approvalId)),a=new Set,A;for(let r=i.session.events.length-1;r>=0;r-=1){let s=i.session.events[r];if(s.type==="approval/decided")a.add(s.data?.id);else if(s.type==="approval/asked"){let g=s.data?.id;if(!g||a.has(g)||e.has(g)||(t.callId??null)!==(s.data?.callId??null))continue;A=g;break}}return A===void 0?o():new Promise(r=>{let s={rpcId:oT(),sessionId:i.sessionId,approvalId:A,toolName:t.toolName,callId:t.callId,reason:t.reason,settle:c=>{this.#l.delete(s.rpcId)&&(t.signal?.removeEventListener("abort",g),this.#C({type:"approval/resolved",sessionId:s.sessionId,approvalId:s.approvalId,outcome:c}),r(c))}},g=()=>s.settle("cancelled");this.#l.set(s.rpcId,s),t.signal?.addEventListener("abort",g,{once:!0}),this.#C(this.#S(s).payload,s.rpcId)})}#m(t){let o=this.#l.get(t?.rpcId);if(o){let a=t?.result?.value;return t?.result?.ok!==!0||!a||typeof a!="object"||a.sessionId!==o.sessionId||a.approvalId!==o.approvalId||a.outcome!=="allowed-once"&&a.outcome!=="rejected"?{accepted:!1,reason:"bad-response"}:(o.settle(a.outcome),{accepted:!0})}let i=this.#r.get(t?.rpcId);if(!i)return{accepted:!1,reason:"not-pending"};if(t?.result?.ok!==!0)return t?.result?.error?.code!=="cancelled"?{accepted:!1,reason:"bad-response"}:(i.settle("cancelled",XQ("the user cancelled ask_user_question","ASK_CANCELLED")),{accepted:!0});if(!eBe(t.result.value,i))return{accepted:!1,reason:"bad-response"};let e={answers:t.result.value.answer.answers.map(a=>({id:a.id,selected:[...a.selected],...a.custom===void 0?{}:{custom:a.custom}}))};return i.settle("answered",e),{accepted:!0}}dispose(){if(!this.#a){this.#a=!0;for(let t of[...this.#t])t.close();for(let t of[...this.#l.values()])t.settle("cancelled");for(let t of[...this.#r.values()])t.settle("cancelled",XQ("dsh-im interaction adapter was disposed","ASK_ABORTED"));for(let t of this.#i.splice(0).reverse())t?.()}}};function g3(n){let t=n?.root??n;if(!t||!["object","function"].includes(typeof t))throw new TypeError("dsh-im requires a Cordis Host context");let o=ZQ.get(t);if(o)return o;let i=n?.typertGateway;if(!i||typeof i.invoke!="function"||typeof i.stream!="function")throw new TypeError("dsh-im requires the modern Host Typert gateway");let e=new sT(n,i,t);return ZQ.set(t,e),typeof n.effect=="function"&&n.effect(()=>()=>{ZQ.get(t)===e&&ZQ.delete(t),e.dispose()},"dsh-im: modern Harness compatibility API"),e}function tBe(n,t){return n&&Object.hasOwn(n,t)?n[t]:typeof n?.get=="function"?n.get(t):void 0}function na(n,t={}){return t.harnessBaseUrl!==void 0?{baseUrl:new URL(t.harnessBaseUrl)}:{apiProxy:tBe(n,"apiProxy")??g3(n),interactionScope:n.root??n}}import{randomUUID as rBe}from"node:crypto";function aBe(n){if(typeof n?.get!="function")return;let t;try{t=n.get("agents")}catch{return}if(t!=null){if(typeof t.get!="function")throw new TypeError('dsh-im requires a callable AgentRegistry when ctx.get("agents") is present');return t}}function iBe(n,t,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===t&&A?.type==="user/message"&&A.data?.source?.rpcId===o&&(a=!0)}return e===t&&a}function c3(n){if(!n||typeof n!="object"||Object.isFrozen(n))return n;for(let t of Object.values(n))c3(t);return Object.freeze(n)}function oBe(n){return c3({id:rBe(),role:"user",content:[{type:"text",text:n}],source:{kind:"user"}})}function nBe(n){let t=new Error("Session is busy with an active turn or maintenance task",{cause:n});return t.code="agent-busy",t}function sBe(n){return({sessionId:t,expectedTurn:o,promptRpcId:i,action:e,text:a})=>{let A=n.get(t);if(A){if(!iBe(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(oBe(a)),!0);throw new TypeError(`Unsupported Harness control action: ${String(e)}`)}}}function gBe(n){return({sessionId:t,operation:o})=>{if(typeof o!="function")throw new TypeError("maintenance operation is required");let i=n.get(t);if(!i)return o();try{return i.runMaintenance(e=>{if(n.get(t)!==i){let a=new Error("Session agent changed before maintenance started");throw a.code="agent-unavailable",a}return o(e)})}catch(e){throw nBe(e)}}}function cBe(n){return({sessionId:t,workspace:o,files:i,signal:e})=>{let A=n.get(t)?.session?.header?.cwd,r=typeof A=="string"&&A?A:o;if(typeof r!="string"||!r)throw new ko("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");return s1({files:i},{workspace:r,signal:e})}}function Wa(n,t={}){let{controlExecutor:o,sessionMaintenanceExecutor:i,fileIngressExecutor:e}=t;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:aBe(n);return{controlExecutor:o??(a?sBe(a):void 0),sessionMaintenanceExecutor:i??(a?gBe(a):void 0),fileIngressExecutor:e??cBe(a??{get:()=>{}})}}function I3(n){return n.map(t=>({id:t,canExecuteCommands:!0}))}function Eg(n=[]){return UQ({mode:"open",open:{defaultCanExecuteCommands:!0,commandPermissionOverrides:[]},allowlist:{users:I3(n)}})}function uc(n=[]){return UQ({mode:"allowlist",open:{defaultCanExecuteCommands:!1,commandPermissionOverrides:[]},allowlist:{users:I3(n)}})}function ug(n){return[...new Set((Array.isArray(n)?n:[n]).filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="bigint").map(t=>String(t).trim()).filter(Boolean))]}function IBe(n){return ug(n).map(t=>`${t.replace(/^\+/,"")}@s.whatsapp.net`)}function cr(n,t={}){let o=String(n??"").trim().toLowerCase();if(o==="weixin")return pg({direct:uc(),group:uc()});if(o==="feishu"){let e=ug(t.ownerOpenIds??t.ownerOpenId).includes("*")?Eg():uc();return pg({direct:e,group:e})}if(o==="qq"){let i=ug(t.ownerUserOpenid);return pg({direct:i.includes("*")?Eg():uc(),group:Eg()})}if(o==="telegram"){let i=ug(t.allowedUsers);return(t.accessMode??"compatible")==="private-allowlist"?pg({direct:uc(i),group:uc()}):pg({direct:Eg(i),group:Eg()})}if(o==="whatsapp"){let i=t.accessMode??"self-only",e=IBe(t.allowedNumbers);return i==="open"?pg({direct:Eg(e),group:Eg()}):pg({direct:uc(i==="private-allowlist"?e:[]),group:uc()})}if(["dingtalk","wecom","slack","discord"].includes(o))return pg({direct:Eg(),group:Eg()});throw new TypeError(`Unsupported access-policy channel: ${n}`)}function lBe(n,t={}){let o=String(n??"").trim().toLowerCase();if(o==="weixin")return ug(t.ownerUserId);if(o==="feishu")return ug(t.ownerOpenIds??t.ownerOpenId).filter(i=>i!=="*");if(o==="dingtalk"){let i=Array.isArray(t.approvedSenders)?t.approvedSenders:[];return ug(i.map(e=>e?.staffId))}return o==="qq"?ug(t.ownerUserOpenid).filter(i=>i!=="*"):o==="whatsapp"?ug(t.accountJid):[]}function Za(n,t,{channel:o,config:i,equals:e}={}){if(!n||typeof n.accessPolicyFor!="function")throw new TypeError("A workspace store with access policies is required");let a=new Set(lBe(o,i)),A=typeof e=="function"?e:(r,s)=>r===s;return Object.freeze({botId:t,getSettings:()=>n.accessPolicyFor(t),isPrivileged(r,s){if(!["direct","group"].includes(s))return!1;let g=Array.isArray(r)?r:[r];try{return g.some(c=>typeof c=="string"&&[...a].some(I=>A(c.trim(),I)===!0))}catch{return!1}}})}function hBe(n){let t=KI(n.dshHome??process.env.DSH_HOME??iu(pBe(),".dsh")),o=KI(n.dataDir??iu(t,"integrations","dsh-dingtalk"));return{root:o,config:KI(n.configPath??iu(o,"config.json")),bots:KI(n.botsDir??iu(o,"bots")),workspaces:KI(n.workspacesPath??iu(o,"workspaces.json"))}}async function gT(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-dingtalk requires ctx.credentials");let i=na(n,t),e=o.ConfigStore??yQ,a=o.DeviceAuth??SQ,A=o.StateStore??LQ,r=o.HarnessClient??JQ,s=o.Controller??KE,g=o.Runtime??XE,c=o.createConnectionSupervisor??iT,I=typeof n.logger=="function"?n.logger("dsh-dingtalk"):n.logger??console,d=()=>Ya(n),B=hBe(t),f=await new e(B.config).load(),Q=KI(t.workspace??process.cwd()),y=o.WorkspaceStore??oa,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),T=typeof f.list=="function",_=T?f.list():[];T&&await m.reconcile(_.map(X=>X.botId)),await Promise.all(_.map(X=>m.ensure(X.botId,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("dingtalk",X)})));let R=typeof f.remove=="function"?ja(f,{workspaces:m}):f,x=o.deviceAuth??new a({baseUrl:t.registrationBaseUrl}),F=new Map,L=X=>KI(B.bots,X,"state.json"),q=async X=>{let ie=F.get(X);return ie||(ie=await new A(L(X)).load(),F.set(X,ie)),ie},z=Va(n,o.commandExecutor),{controlExecutor:H,sessionMaintenanceExecutor:G,fileIngressExecutor:V}=Wa(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),U=new r({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...z?{commandExecutor:z}:{},...H?{controlExecutor:H}:{},...G?{sessionMaintenanceExecutor:G}:{},...V?{fileIngressExecutor:V}:{}}),N=new s({deviceAuth:x,credentials:n.credentials,configStore:R,logger:I,createRuntime:async({botId:X,config:ie,clientSecret:we})=>{let oe=await q(X);await m.ensure(X,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("dingtalk",ie)});let Se=Ja(U,{botId:X,workspaces:m,state:oe,agentPresetCatalog:d});return new g({config:ie,clientSecret:we,harness:Se.harness,state:Se.state,contextEnhancement:{botId:X,getSettings:()=>m.contextEnhancementFor(X)},accessPolicy:Za(m,X,{channel:"dingtalk",config:ie}),replyTimeoutMs:t.replyTimeoutMs??6e5,maxMessageChars:t.maxMessageChars??4e3,connectTimeoutMs:t.connectTimeoutMs??15e3,logger:{error:(...Be)=>I.error?.(`[${X}]`,...Be),warn:(...Be)=>I.warn?.(`[${X}]`,...Be),info:(...Be)=>I.info?.(`[${X}]`,...Be),debug:(...Be)=>I.debug?.(`[${X}]`,...Be)}})},deleteState:async({botId:X})=>{let ie=F.get(X);if(F.delete(X),ie&&typeof ie.remove=="function")await ie.remove();else try{await dBe(L(X))}catch(we){if(we?.code!=="ENOENT")throw we}}}),k=qa(N,{workspaces:m,stateFor:q,agentPresetCatalog:d}),J=c({controller:k,harness:U,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:k,deliveryAdapter:za({channel:"dingtalk",workspaces:m,coreController:N,stateFor:q}),ready:J.ready,async close(){await J.close(),await k.close(),U.stopManagedProcess()}}}import BBe from"qrcode";var Gi="bot.context-enhancement.set";function Xa(n){try{return!n||typeof n!="object"||Array.isArray(n)||Reflect.ownKeys(n).length!==2||!Object.hasOwn(n,"botId")||!Object.hasOwn(n,"config")||typeof n.botId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)?!1:(FI(n.config),!0)}catch{return!1}}var $a="bot.access-policy.set";function ei(n){try{return!n||typeof n!="object"||Array.isArray(n)||Reflect.ownKeys(n).length!==2||!Object.hasOwn(n,"botId")||!Object.hasOwn(n,"policy")||typeof n.botId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)?!1:(pc(n.policy),!0)}catch{return!1}}var EBe=new Set(["loopback","trusted-host"]);function yr(n){if(n===void 0)return"loopback";if(EBe.has(n))return n;throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"')}import{isAbsolute as uBe}from"node:path";var Fi="bot.workspace.set";function Ai(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).every(t=>["botId","workspace"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&typeof n.workspace=="string"&&n.workspace.length<=4096&&uBe(n.workspace.trim())}function ti(n){return["workspace-not-absolute","workspace-not-found","workspace-not-directory","workspace-bot-not-found","agent-preset-invalid","agent-preset-unavailable","context-enhancement-invalid"].includes(n?.code)?{code:n.code,message:n.message}:null}var Li="bot.preset.set";function CBe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ri(n){return CBe(n)&&Object.keys(n).every(t=>["botId","agentPreset"].includes(t))&&typeof n.botId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n.botId)&&(n.agentPreset===null||typeof n.agentPreset=="string"&&T_.test(n.agentPreset))}var d3="/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:Fi,setAgentPreset:Li,setContextEnhancement:Gi,setAccessPolicy:$a,approveSender:"bot.sender.approve",revokeSender:"bot.sender.revoke"}),p3=Object.freeze(Object.values(Lt)),fBe=new Set(["clientSecret","client_secret","deviceCode","device_code","secretRef","staffId","senderStaffId","verificationUrl","verificationUri","userCode"]);function IT(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Cc(n,t){return IT(n)&&Object.keys(n).every(o=>t.includes(o))}function xI(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function l3(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function QBe(n,t){return IT(t)?n===Lt.status?Cc(t,[])?null:"connection.status does not accept fields.":n===Lt.beginProvisioning?Cc(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[Lt.pollProvisioning,Lt.cancelProvisioning].includes(n)?Cc(t,["attemptId"])&&xI(t.attemptId)?null:`${n} requires an attemptId.`:n===Lt.bindCredentials?Cc(t,["clientId","clientSecret"])&&l3(t.clientId,256)&&l3(t.clientSecret,1024)?null:"bot.bind-credentials requires Client ID and Client Secret.":n===Lt.reconnectBot?Cc(t,["botId","sendTest"])&&xI(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===Lt.deleteBot?Cc(t,["botId","confirm"])&&xI(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===Lt.setWorkspace?Ai(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===Lt.setAgentPreset?ri(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===Lt.setContextEnhancement?Xa(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===Lt.setAccessPolicy?ei(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u8BBF\u95EE\u8BBE\u7F6E\u3002":n===Lt.approveSender?Cc(t,["botId","requestId","confirm"])&&xI(t.botId)&&xI(t.requestId)&&t.confirm===!0?null:"bot.sender.approve requires botId, requestId, and confirm=true.":n===Lt.revokeSender?Cc(t,["botId","senderKey","confirm"])&&xI(t.botId)&&xI(t.senderKey)&&t.confirm===!0?null:"bot.sender.revoke requires botId, senderKey, and confirm=true.":"Unknown DingTalk endpoint.":"Payload must be an object."}function $Q(n){return{ok:!1,error:{code:"bad-request",message:n}}}function ou(){return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}}function yBe(){return{ok:!1,error:{code:"dingtalk-operation-failed",message:"\u9489\u9489\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}}}function Jd(n){if(Array.isArray(n))return n.map(Jd);if(!IT(n))return n;let t={};for(let[o,i]of Object.entries(n))fBe.has(o)||(t[o]=Jd(i));return t}async function mBe(n){return BBe.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function cT(n,t){return!n||typeof n.verificationUrl!="string"?Jd(n):Jd({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function gs(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await cT(o.provisioning,t)),Jd(o)}function SBe(n){for(let t of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot","approveSender","revokeSender"])if(typeof n?.[t]!="function")throw new TypeError(`A complete DingTalk controller is required (${t})`)}function h3(n,{encodeQr:t=mBe}={}){SBe(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(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return ou();if(!p3.includes(e))return $Q("Unknown DingTalk endpoint.");let r=QBe(e,a);if(r)return $Q(r);try{let s;if(e===Lt.status)s=await gs(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),ou();s=await cT(g,i)}else if(e===Lt.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return $Q("The provisioning attempt no longer exists.");s=await cT(g,i)}else if(e===Lt.cancelProvisioning){if(s=await n.cancelProvisioning(a.attemptId),!s)return $Q("The provisioning attempt no longer exists.");s=Jd(s)}else if(e===Lt.bindCredentials)s=await gs(await n.bindCredentials(a),i);else if(e===Lt.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return ou();let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=gr(fr("\u9489\u9489\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=gr()}catch(d){c=gr(d)}s=await gs({...g,...c?{testMessage:c}:{}},i)}else if(e===Lt.deleteBot)s=await gs(await n.deleteBot(a.botId),i);else if(e===Lt.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await gs(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===Lt.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>gs(g,i))}else if(e===Lt.setAccessPolicy){if(typeof n.updateAccessPolicy!="function")throw new Error("Access policy update is unavailable");s=await n.updateAccessPolicy(a.botId,a.policy,g=>gs(g,i))}else if(e===Lt.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await gs(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else e===Lt.approveSender?s=await gs(await n.approveSender(a.botId,a.requestId),i):s=await gs(await n.revokeSender(a.botId,a.senderKey),i);return A?.aborted?ou():{ok:!0,value:s}}catch(s){let g=ti(s);return A?.aborted?ou():g?{ok:!1,error:g}:yBe()}}}function ey(n,t,o,i){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(d3,h3(t,o),{authority:yr(i)})}async function E3(n,t={}){if(t?.controller)return ey(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await gT(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=ey(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-dingtalk: close bot connections"),e}import{createHash as wBe}from"node:crypto";import{mkdir as DBe,readFile as OBe,rename as bBe,unlink as MBe,writeFile as _Be}from"node:fs/promises";import{dirname as TBe}from"node:path";var lT=Object.freeze({version:1,bots:Object.freeze([])});function Cg(n){return typeof n=="string"&&n.trim()?n.trim():null}function u3(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nu(n,{botPrefix:t,tokenRefPrefix:o}){let i=Cg(n);if(!i)throw new TypeError("platformId is required");let e=wBe("sha256").update(i).digest("hex").slice(0,24);return{botId:`${t}_${e}`,tokenRef:`${o}_${e.toUpperCase()}`}}function Ay(n,t){let o=Cg(n)??"";return o.length<=10?o?`${o.slice(0,3)}\u2022\u2022\u2022`:t:`${o.slice(0,6)}\u2022\u2022\u2022\u2022${o.slice(-4)}`}var qd=class{#e;#A;#t;#r;#l;#o;#i;#a=lT;#n=Promise.resolve();constructor(t,{channel:o,botPrefix:i,tokenRefPrefix:e,normalizeBotExtension:a=()=>({})}){if(typeof a!="function")throw new TypeError("normalizeBotExtension must be a function");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=new RegExp(`^${u3(i)}_[a-f0-9]{24}$`),this.#i=new RegExp(`^${u3(e)}_[A-F0-9]{24}$`)}async load(){try{let t=this.#d(JSON.parse(await OBe(this.#e,"utf8")));if(!t)throw new Error(`dsh-im ${this.#A} config contains invalid bot data`);this.#a=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#a=lT}return this}list(){return structuredClone(this.#a.bots)}get(t){let o=this.#a.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByPlatformId(t){let o=this.#a.bots.find(i=>i.platformId===t);return o?structuredClone(o):null}async save(t){let o=this.#s(t);if(!o)throw new Error(`Refusing to persist incomplete ${this.#A} bot data`);return this.#c(i=>{let e=i.find(r=>r.platformId===o.platformId&&r.botId!==o.botId),a=i.find(r=>r.tokenRef===o.tokenRef&&r.botId!==o.botId);if(e||a)throw new Error(`Duplicate ${this.#A} bot identity`);let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!this.#o.test(t))throw new TypeError(`Invalid ${this.#A} bot id`);return this.#c(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#n.then(async()=>{try{await MBe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#a=lT});this.#n=t.then(()=>{},()=>{}),await t}#s(t){if(!t||typeof t!="object")return null;let o=Cg(t.platformId),i=Cg(t.botId),e=Cg(t.tokenRef),a=Cg(t.name);if(!o||!i||!e||!a||!this.#o.test(i)||!this.#i.test(e))return null;let A=nu(o,{botPrefix:this.#t,tokenRefPrefix:this.#r});if(A.botId!==i||A.tokenRef!==e)return null;let r=this.#l(t);return!r||typeof r!="object"||Array.isArray(r)?null:Object.freeze({botId:i,platformId:o,tokenRef:e,name:a,username:Cg(t.username),createdAt:Cg(t.createdAt)??new Date().toISOString(),connectedAt:Cg(t.connectedAt),...r})}#d(t){if(!t||t.version!==1||!Array.isArray(t.bots))return null;let o=t.bots.map(A=>this.#s(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#c(t){let o,i=this.#n.then(async()=>{let e=[...this.#a.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#g(a),this.#a=a});return this.#n=i.then(()=>{},()=>{}),await i,o}async#g(t){await DBe(TBe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await _Be(o,`${JSON.stringify(t,null,2)} -`,{encoding:"utf8",mode:384}),await bBe(o,this.#e)}};var C3=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function B3(n){return nu(n,C3)}function f3(n){return Ay(n,w("Discord\u673A\u5668\u4EBA"))}var ty=class extends qd{constructor(t){super(t,{channel:"Discord",...C3})}};function su(n){return typeof n=="string"&&n.trim()?n.trim():null}function gu(n,t){return Object.freeze({code:n,message:t})}var zd=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s=new Map;#d=new Map;#c=new Map;#g=0;#I=!1;constructor({descriptor:t,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:r,deleteState:s=async()=>{},logger:g=console}){if(!t?.key||!t?.label||!t?.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(`${t.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${t.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof r!="function")throw new TypeError(`${t.label} controller dependencies are incomplete`);this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g}async initialize(){if(this.#I)return this.status();for(let t of this.#t.list())await this.#B(t.botId,async()=>{if(this.#I||this.#s.get(t.botId)?.status?.ready)return;let o=await this.#u(t.tokenRef);if(!o){this.#d.set(t.botId,gu("missing-token",w("{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002",{label:this.#e.label})));return}try{await this.#p(t,o),this.#d.delete(t.botId)}catch(i){this.#d.set(t.botId,gu("connection-failed",w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002",{label:this.#e.label}))),this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t.botId} failed to initialize:`,i)}finally{this.#f()}});return this.status()}async bindCredentials({token:t}={}){if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let o=su(t);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=su(i?.platformId),a=su(i?.name);if(!e||!a)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#l(e);return await this.#B(A.botId,async()=>{if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let r=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:a,username:su(i.username),createdAt:r?.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.#p(g,o),this.#d.delete(A.botId)}catch(c){this.#d.set(A.botId,gu("connection-failed",w("{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002",{label:this.#e.label}))),this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#f()}),this.status()}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#B(t,async()=>{let i=await this.#u(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#p(o,i),this.#d.delete(t)}catch(e){throw this.#d.set(t,gu("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),e}finally{this.#f()}}),this.status()}async updateBotConfig(t,o){if(this.#I)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.#B(t,async()=>{if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let i=this.#t.get(t);if(!i)throw new Error(`Unknown ${this.#e.label} bot`);let e=await this.#u(i.tokenRef);if(!e)throw new Error(`${this.#e.label} bot token is missing`);if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let a=o(i),A=await this.#t.save(a);try{await this.#p(A,e),this.#d.delete(t)}catch(r){throw this.#d.set(t,gu("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),r}finally{this.#f()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#B(t,async()=>{let i=this.#s.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw a.code="test-target-unavailable",a}let e=w("{name}\uFF08{id}\uFF09",{name:o.name,id:this.#o(o.platformId)});return await i.sendConnectionTest(La(e,w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error(`Unknown ${this.#e.label} bot`);return this.#B(t,async()=>{let A=this.#s.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#B(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#a({botId:t,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t} state cleanup failed:`,e)}),this.#d.delete(t),this.#f()}),this.status()}status(){let t=this.#t.list().map(i=>{let e=this.#s.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#d.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.#o(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w("{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38",{label:this.#e.label,connectionLabel:w(this.#e.connectionLabel)}):A==="error"?w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5",{label:this.#e.label}):w("{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",{label:this.#e.label}),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Aa(e?.lastMessageError),error:structuredClone(this.#d.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#g,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#I||(this.#I=!0,await Promise.allSettled([...this.#c.values()]),await Promise.allSettled([...this.#s.keys()].map(t=>this.#h(t))))}async#p(t,o){if(this.#I)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(t.botId),this.#I)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#i({botId:t.botId,config:t,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#s.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#s.delete(t.botId),e}}async#h(t){let o=this.#s.get(t);this.#s.delete(t),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t} failed to stop cleanly:`,i)})}async#u(t){let o=await this.#A.resolve(t).catch(()=>{});return su(o?.value)}async#C(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#B(t,o){let a=(this.#c.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#c.get(t)===a&&this.#c.delete(t)});return this.#c.set(t,a),a}#f(){this.#g+=1}};import{createHash as NBe}from"node:crypto";var RBe="https://discord.com/api/v10/",kBe=12e4,vBe=new Set([50001,50013]),PBe=new Set([40005]);function cs(n){return typeof n=="string"&&n.trim()?n.trim():null}function Q3(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function dT(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function GBe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function m3(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function FBe(n){let t=Number(n?.providerCode),o=Number(n?.status),i=cs(n?.message)??"",e="artifact-provider-rejected",a="Discord rejected the attachment.";o===401||o===403||vBe.has(t)?(e="artifact-permission-required",a="Discord denied permission to send the attachment."):o===413||PBe.has(t)||/(?: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,m3(A,n)}function LBe(n){let t=new Error("Discord attachment delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",m3(t,n)}function UBe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function sa(n,t){let o=cs(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${t}`);return o}function y3(n){let t=cs(n);if(!t)throw new TypeError("A Discord reaction emoji is required");return t}function HBe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var cu=class{#e;#A;#t;#r;constructor({token:t,fetchImpl:o=fetch,baseUrl:i=RBe,fileUploadTimeoutMs:e=kBe}){if(!HBe(t))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=t.trim(),this.#A=o,this.#t=new URL(i),this.#r=GBe(e,"fileUploadTimeoutMs")}getCurrentUser(t={}){return this.#l("users/@me",{...t,method:"GET"})}getGatewayBot(t={}){return this.#l("gateway/bot",{...t,method:"GET"})}getChannel({channelId:t,signal:o}={}){return this.#l(`channels/${sa(t,"channel id")}`,{method:"GET",signal:o})}getMessage({channelId:t,messageId:o,signal:i}={}){return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}`,{method:"GET",signal:i})}startThreadFromMessage({channelId:t,messageId:o,name:i,signal:e}={}){let a=cs(i);if(!a||[...a].length>100)throw new TypeError("Discord thread name must contain 1-100 characters");if(e?.aborted)throw dT(e);return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/threads`,{method:"POST",signal:e,body:{name:a}})}createMessage({channelId:t,content:o,replyToMessageId:i,signal:e}){return this.#l(`channels/${sa(t,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:sa(i,"message id"),channel_id:sa(t,"channel id"),fail_if_not_exists:!1}}:{}}})}async createFileMessage({channelId:t,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=cs(o.deliveryKey)??cs(o.artifactId),A=a?NBe("sha256").update(a).digest("hex").slice(0,25):void 0,r=new FormData;r.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:sa(i,"message id"),channel_id:sa(t,"channel id"),fail_if_not_exists:!1}}:{}})),r.append("files[0]",new Blob([o.bytes],{type:o.mediaType??"application/octet-stream"}),o.fileName);let s=sa(t,"channel id");if(e?.aborted)throw dT(e);let g=Q3(e,this.#r);try{return await this.#l(`channels/${s}/messages`,{method:"POST",signal:g,timeoutMs:this.#r,body:r,multipart:!0})}catch(c){throw e?.aborted?dT(e):c?.code?.startsWith?.("discord-")?FBe(c):LBe(c)}}editMessage({channelId:t,messageId:o,content:i,signal:e}){return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:t,signal:o}){return this.#l(`channels/${sa(t,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async addOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=y3(i);return await this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"PUT",signal:e,expectBody:!1,retry:!1}),a}removeOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=y3(i);return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"DELETE",signal:e,expectBody:!1,retry:!1})}async#l(t,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:r=!0,multipart:s=!1}){let g;try{g=await this.#A(new URL(t,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:Q3(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&&r){let I=Math.min(1e4,Math.max(50,Number(c?.retry_after)*1e3||1e3));return await UBe(I,e),this.#l(t,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1,multipart:s})}if(!g.ok){let I=new Error(cs(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 d=Number(c?.retry_after);throw Number.isFinite(d)&&d>=0&&(I.retry_after=d,I.retryAfter=d),I}return A?c:null}};async function S3(n,t={}){let i=await new cu({token:n,...t}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:cs(i.global_name)??cs(i.username)??w("Discord\u673A\u5668\u4EBA"),username:cs(i.username)}}var KBe=Object.freeze({success(){},error(){},clear(){},settled:()=>Promise.resolve()});function w3(n,t){!n||typeof n!="object"||(n[t]=(n[t]??0)+1)}async function xBe(n,t){let o=AbortSignal.timeout(t),i,e=new Promise((a,A)=>{i=()=>A(o.reason??new DOMException("Timed out","TimeoutError")),o.addEventListener("abort",i,{once:!0})});try{return await Promise.race([n(o),e])}finally{o.removeEventListener("abort",i)}}function ry({adapter:n,target:t,reactions:o,status:i,logger:e=console,label:a="channel",timeoutMs:A=2e3}={}){if(!t||typeof n?.addReaction!="function"||typeof n?.removeReaction!="function"||typeof o?.processing!="string"||!o.processing||!Number.isSafeInteger(A)||A<=0)return KBe;let r=null,s=!1,g=async(B,f)=>{try{let Q=await xBe(f,A);return w3(i,B==="add"?"reactionsAdded":"reactionsRemoved"),{ok:!0,value:Q}}catch(Q){return w3(i,"reactionErrors"),e.warn?.(`[dsh-im:${a}] status reaction ${B} failed:`,Q?.message??Q?.name??String(Q)),{ok:!1,value:null}}},c=async B=>{if(r!==null){let Q=r;r=null,await g("remove",y=>n.removeReaction(t,Q,{signal:y}))}if(typeof B!="string"||!B)return;let f=await g("add",Q=>n.addReaction(t,B,{signal:Q}));f.ok&&f.value!==void 0&&f.value!==null&&(r=f.value)},I=c(o.processing),d=B=>{s||(s=!0,I=I.then(()=>c(B),()=>c(B)),I.catch(()=>{}))};return Object.freeze({success:()=>d(o.success),error:()=>d(o.error),clear:()=>d(null),settled:()=>I})}var D3="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",YBe="\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002";function pi(n){return typeof n=="string"?n.trim():""}function jBe(n,t,o){return t.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Nt(n)&&!Dt(n)&&!!pi(n.content)}function JBe(n,t,o){let i=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim().slice(0,255)||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-permission-required":return o?.key==="slack"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i}):o?.key==="discord"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002",{name:i}):o?.key==="telegram"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i}):w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:i});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i})}}function so(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}var Is=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d=new Map;#c=new Map;#g=new Map;#I=new Map;#p=new Set;#h=new Set;#u;#C=new ki;constructor({descriptor:t,bot:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,status:r=so(),logger:s=console,replyTimeoutMs:g=6e5,signal:c}){if(!t?.key||!t?.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=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#u=new Mi({label:t.key,logger:s})}get status(){return structuredClone(this.#i)}accept(t,{contextSnapshot:o,accessDecision:i}={}){if(this.#s?.aborted)return Promise.resolve();let e=pi(t?.conversationId),a=t?.kind==="group"?"group":"direct",A={...t,kind:a,conversationId:e},r=pi(A.messageId),s=pi(A.senderId);if(!r||!s||!e||A.senderIsBot===!0||this.#r.hasSeen(r)||this.#I.has(r))return Promise.resolve();if(a==="group"&&A.addressed!==!0)return this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString(),this.#I.set(r,null),this.#f(A,r,null);if(this.#o||i){let I=Nt(A),d=Dt(A),B=i??Da(this.#o,{conversationType:a,senderIds:[s,pi(A.senderAlternateId)].filter(Boolean),text:A.content,hasImages:I,hasFiles:d});if(!B.allowed)return this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString(),this.#I.set(r,null),this.#f(A,r,B.reason==="command-not-allowed"?w(no):null,{recordReceived:B.reason==="command-not-allowed"})}this.#I.set(r,o===void 0?aa(this.#l,t?.kind):o);let g=ry({adapter:this.#A,target:A.kind==="direct"||A.addressed===!0?A.reactionTarget:null,reactions:this.#e.reactions,status:this.#i,logger:this.#a,label:this.#e.key});A.statusReaction=g;let c=this.#B(A,r,s);return c.then(()=>g.success(),()=>g.error()),c}#B(t,o,i){t.kind==="direct"&&Do(this.#r,t.connectionTestTarget??t.replyTarget);let e=`${t.kind}:${t.conversationId}`,a=this.#c.get(e),A=pi(t.content),r=vi(A);if(r&&t.kind==="group"&&t.addressed===!0)return this.#f(t,o,as());if(r&&t.kind==="direct"){if(/^\/batch$/iu.test(A)&&(this.#d.has(e)||a||this.#u.hasPending(e)))return this.#f(t,o,Ro());let d=this.#C.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Nt(t)&&!Dt(t)&&!Hr(t)});if(d.handled)return d.kind==="submit"?this.#Q({...t,content:d.prompt,batchSubmission:{token:d.token}},o,i,e):this.#f(t,o,d.message)}else if(t.kind==="direct"&&this.#C.status(e).phase==="collecting"){let I=this.#C.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Nt(t)&&!Dt(t)&&!Hr(t)});if(I.handled)return this.#f(t,o,I.message)}let g=t.kind==="direct"&&this.#C.status(e).phase==="collecting"?null:xa(A)?ao:Dt(t)?null:ci(A)?Ni:Ii(A)?io:li(A)?Ri:null;if(g&&(t.kind!=="group"||t.addressed===!0)){let I;return I=this.#S(t,o,e,g).finally(()=>{this.#I.delete(o),this.#h.delete(I)}),this.#h.add(I),I}let c=this.#u.claimReply({key:e,actor:i,messageId:o,text:Nt(t)||Dt(t)?"":t.content,addressed:t.kind!=="group"||t.addressed===!0,hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#c.has(e),send:I=>this.#A.sendText(t.replyTarget,I)});if(c){let I;return I=c.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#I.delete(o),this.#p.delete(I)}),this.#p.add(I),I}if(a&&a.actor!==i)return this.#Q(t,o,i,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#Q(t,o,i,e);if(a){jBe(t,a,i)&&(a.claimedReplyMessageId=o);let d=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#D(t,o,i,e,a)).finally(()=>{this.#I.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===d&&(a.queue=null)});return a.queue=d,d}return this.#Q(t,o,i,e)}#f(t,o,i,{recordReceived:e=!0}={}){let a;return a=(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),e&&(this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()),i&&await this.#A.sendText(t.replyTarget,i),this.#i.lastError=null)})().catch(async A=>{if(this.#s?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#i.lastError=A?.message??String(A);let r=tt(this.#i,A);this.#a.error?.(`[dsh-im:${this.#e.key}] failed to process a batch input message [${r.referenceId}]:`,A)}).finally(()=>{this.#I.delete(o),this.#h.delete(a)}),this.#h.add(a),a}#Q(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#d.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#m(t,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#I.delete(o),this.#d.get(e)===s&&this.#d.delete(e)});return this.#d.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#d.values(),...[...this.#c.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#p,...this.#h])}async#S(t,o,i,e){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let a=t.replyTarget;try{let A=await e(pi(t.content),this.#t,this.#r,i,{signal:this.#s,isDirect:t.kind==="direct",hasImages:Nt(t),hasFiles:Dt(t),pendingInteraction:this.#c.has(i)||this.#u.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#P(i),this.#u.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#A.sendText(a,r);this.#i.lastError=null}catch(A){if(A?.code==="turn-stopped"||this.#s?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#i.lastError=A?.message??String(A);let r=tt(this.#i,A);this.#a.error?.(`[dsh-im:${this.#e.key}] failed to process a command [${r.referenceId}]:`,A),await this.#A.sendText(a,Et(r)).catch(()=>{})}}sendConnectionTest(t){return cc({state:this.#r,text:t,channelLabel:w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}),send:(o,i)=>this.#A.sendText(o,i)})}sendProactiveText(t,o,{signal:i}={}){return i?.throwIfAborted(),this.#A.sendText(t,o)}async#y(t,o,i=[],e){let a=await Po({artifacts:i,baseReceipt:e,deliveryId:o,channelKey:this.#e.key,signal:this.#s,sendImage:typeof this.#A.sendImage=="function"?A=>this.#A.sendImage(t,A):void 0,sendFile:typeof this.#A.sendFile=="function"?A=>this.#A.sendFile(t,A):void 0,onFailure:(A,r)=>tt(this.#i,r,{userMessage:JBe(A?.fileName,r,this.#e),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#A.sendText(t,Et(s)),logger:this.#a});return this.#i.artifactsSent=(this.#i.artifactsSent??0)+a.artifactsSent,this.#i.artifactSendErrors=(this.#i.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,userVisible:a.userVisible,artifactSendErrors:a.artifactSendErrors}}async#m(t,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}let A=t.replyTarget,r=pi(t.content),s=t.batchSubmission,g=null,c=!1;try{if(this.#s?.throwIfAborted(),t.kind==="group"&&t.addressed!==!0){this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString();return}let I=Nt(t),d=Dt(t),B=Hr(t);if(!r&&!I&&!d&&!B){await this.#A.sendText(A,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"));return}let f=r.toLowerCase();if(!I&&!d&&f==="/help"){await this.#A.sendText(A,[w("{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002",{label:this.#e.label}),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` +`,{encoding:"utf8",mode:384}),await bBe(o,this.#e)}};var C3=Object.freeze({botPrefix:"discord",tokenRefPrefix:"DSH_DISCORD_BOT_TOKEN"});function B3(n){return nu(n,C3)}function f3(n){return Ay(n,w("Discord\u673A\u5668\u4EBA"))}var ty=class extends qd{constructor(t){super(t,{channel:"Discord",...C3})}};function su(n){return typeof n=="string"&&n.trim()?n.trim():null}function gu(n,t){return Object.freeze({code:n,message:t})}var zd=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s=new Map;#d=new Map;#c=new Map;#g=0;#I=!1;constructor({descriptor:t,credentials:o,configStore:i,inspectToken:e,deriveIdentity:a,maskPlatformId:A,createRuntime:r,deleteState:s=async()=>{},logger:g=console}){if(!t?.key||!t?.label||!t?.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(`${t.label} requires the DSH credential provider`);if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError(`${t.label} requires a config store`);if(typeof e!="function"||typeof a!="function"||typeof A!="function"||typeof r!="function")throw new TypeError(`${t.label} controller dependencies are incomplete`);this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g}async initialize(){if(this.#I)return this.status();for(let t of this.#t.list())await this.#B(t.botId,async()=>{if(this.#I||this.#s.get(t.botId)?.status?.ready)return;let o=await this.#u(t.tokenRef);if(!o){this.#d.set(t.botId,gu("missing-token",w("{label}\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002",{label:this.#e.label})));return}try{await this.#p(t,o),this.#d.delete(t.botId)}catch(i){this.#d.set(t.botId,gu("connection-failed",w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002",{label:this.#e.label}))),this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t.botId} failed to initialize:`,i)}finally{this.#f()}});return this.status()}async bindCredentials({token:t}={}){if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let o=su(t);if(!o)throw new TypeError(`${this.#e.label} Bot Token is required`);let i=await this.#r(o),e=su(i?.platformId),a=su(i?.name);if(!e||!a)throw new Error(`${this.#e.label} returned an invalid bot identity`);let A=this.#l(e);return await this.#B(A.botId,async()=>{if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let r=this.#t.getByPlatformId(e),s=await this.#A.resolve(A.tokenRef).catch(()=>{}),g={botId:A.botId,platformId:e,tokenRef:A.tokenRef,name:a,username:su(i.username),createdAt:r?.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.#p(g,o),this.#d.delete(A.botId)}catch(c){this.#d.set(A.botId,gu("connection-failed",w("{label}\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0C\u6D88\u606F\u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002",{label:this.#e.label}))),this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${A.botId} credential connection failed:`,c)}this.#f()}),this.status()}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#B(t,async()=>{let i=await this.#u(o.tokenRef);if(!i)throw new Error(`${this.#e.label} bot token is missing`);try{await this.#p(o,i),this.#d.delete(t)}catch(e){throw this.#d.set(t,gu("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),e}finally{this.#f()}}),this.status()}async updateBotConfig(t,o){if(this.#I)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.#B(t,async()=>{if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let i=this.#t.get(t);if(!i)throw new Error(`Unknown ${this.#e.label} bot`);let e=await this.#u(i.tokenRef);if(!e)throw new Error(`${this.#e.label} bot token is missing`);if(this.#I)throw new Error(`${this.#e.label} controller is closed`);let a=o(i),A=await this.#t.save(a);try{await this.#p(A,e),this.#d.delete(t)}catch(r){throw this.#d.set(t,gu("connection-failed",w("{label}\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{label:this.#e.label}))),r}finally{this.#f()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return this.#B(t,async()=>{let i=this.#s.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let a=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw a.code="test-target-unavailable",a}let e=w("{name}\uFF08{id}\uFF09",{name:o.name,id:this.#o(o.platformId)});return await i.sendConnectionTest(La(e,w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error(`Unknown ${this.#e.label} bot`);return this.#B(t,async()=>{let A=this.#s.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("{label}\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5",{label:this.#e.label}));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error(`Unknown ${this.#e.label} bot`);return await this.#B(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#h(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#p(o,i.value).catch(()=>{})),new Error(`Unable to remove the ${this.#e.label} bot safely.`,{cause:e})}await this.#a({botId:t,config:o}).catch(e=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t} state cleanup failed:`,e)}),this.#d.delete(t),this.#f()}),this.status()}status(){let t=this.#t.list().map(i=>{let e=this.#s.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#d.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.#o(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w("{label}{connectionLabel}\u8FD0\u884C\u6B63\u5E38",{label:this.#e.label,connectionLabel:w(this.#e.connectionLabel)}):A==="error"?w("{label}\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5",{label:this.#e.label}):w("{label}\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF",{label:this.#e.label}),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Aa(e?.lastMessageError),error:structuredClone(this.#d.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#g,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#I||(this.#I=!0,await Promise.allSettled([...this.#c.values()]),await Promise.allSettled([...this.#s.keys()].map(t=>this.#h(t))))}async#p(t,o){if(this.#I)throw new Error(`${this.#e.label} controller is closed`);if(await this.#h(t.botId),this.#I)throw new Error(`${this.#e.label} controller is closed`);let i=await this.#i({botId:t.botId,config:t,token:o});if(!i||typeof i.start!="function"||typeof i.stop!="function")throw new TypeError(`createRuntime returned an invalid ${this.#e.label} runtime`);this.#s.set(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#s.delete(t.botId),e}}async#h(t){let o=this.#s.get(t);this.#s.delete(t),await o?.stop().catch(i=>{this.#n.warn?.(`[dsh-im:${this.#e.key}] bot ${t} failed to stop cleanly:`,i)})}async#u(t){let o=await this.#A.resolve(t).catch(()=>{});return su(o?.value)}async#C(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#B(t,o){let a=(this.#c.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#c.get(t)===a&&this.#c.delete(t)});return this.#c.set(t,a),a}#f(){this.#g+=1}};import{createHash as NBe}from"node:crypto";var RBe="https://discord.com/api/v10/",kBe=12e4,vBe=new Set([50001,50013]),PBe=new Set([40005]);function cs(n){return typeof n=="string"&&n.trim()?n.trim():null}function Q3(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function dT(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function GBe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function m3(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function FBe(n){let t=Number(n?.providerCode),o=Number(n?.status),i=cs(n?.message)??"",e="artifact-provider-rejected",a="Discord rejected the attachment.";o===401||o===403||vBe.has(t)?(e="artifact-permission-required",a="Discord denied permission to send the attachment."):o===413||PBe.has(t)||/(?: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,m3(A,n)}function LBe(n){let t=new Error("Discord attachment delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",m3(t,n)}function UBe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function sa(n,t){let o=cs(n);if(!o||!/^\d{5,30}$/.test(o))throw new TypeError(`Invalid Discord ${t}`);return o}function y3(n){let t=cs(n);if(!t)throw new TypeError("A Discord reaction emoji is required");return t}function HBe(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/.test(n.trim())}var cu=class{#e;#A;#t;#r;constructor({token:t,fetchImpl:o=fetch,baseUrl:i=RBe,fileUploadTimeoutMs:e=kBe}){if(!HBe(t))throw new TypeError("Discord Bot Token is invalid");if(typeof o!="function")throw new TypeError("DiscordApi requires fetch");this.#e=t.trim(),this.#A=o,this.#t=new URL(i),this.#r=GBe(e,"fileUploadTimeoutMs")}getCurrentUser(t={}){return this.#l("users/@me",{...t,method:"GET"})}getGatewayBot(t={}){return this.#l("gateway/bot",{...t,method:"GET"})}getChannel({channelId:t,signal:o}={}){return this.#l(`channels/${sa(t,"channel id")}`,{method:"GET",signal:o})}getMessage({channelId:t,messageId:o,signal:i}={}){return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}`,{method:"GET",signal:i})}startThreadFromMessage({channelId:t,messageId:o,name:i,signal:e}={}){let a=cs(i);if(!a||[...a].length>100)throw new TypeError("Discord thread name must contain 1-100 characters");if(e?.aborted)throw dT(e);return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/threads`,{method:"POST",signal:e,body:{name:a}})}createMessage({channelId:t,content:o,replyToMessageId:i,signal:e}){return this.#l(`channels/${sa(t,"channel id")}/messages`,{method:"POST",signal:e,body:{content:o,allowed_mentions:{parse:[],replied_user:!1},...i?{message_reference:{message_id:sa(i,"message id"),channel_id:sa(t,"channel id"),fail_if_not_exists:!1}}:{}}})}async createFileMessage({channelId:t,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=cs(o.deliveryKey)??cs(o.artifactId),A=a?NBe("sha256").update(a).digest("hex").slice(0,25):void 0,r=new FormData;r.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:sa(i,"message id"),channel_id:sa(t,"channel id"),fail_if_not_exists:!1}}:{}})),r.append("files[0]",new Blob([o.bytes],{type:o.mediaType??"application/octet-stream"}),o.fileName);let s=sa(t,"channel id");if(e?.aborted)throw dT(e);let g=Q3(e,this.#r);try{return await this.#l(`channels/${s}/messages`,{method:"POST",signal:g,timeoutMs:this.#r,body:r,multipart:!0})}catch(c){throw e?.aborted?dT(e):c?.code?.startsWith?.("discord-")?FBe(c):LBe(c)}}editMessage({channelId:t,messageId:o,content:i,signal:e}){return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}`,{method:"PATCH",signal:e,body:{content:i,allowed_mentions:{parse:[],replied_user:!1}}})}sendTyping({channelId:t,signal:o}){return this.#l(`channels/${sa(t,"channel id")}/typing`,{method:"POST",signal:o,expectBody:!1})}async addOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=y3(i);return await this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"PUT",signal:e,expectBody:!1,retry:!1}),a}removeOwnReaction({channelId:t,messageId:o,emoji:i,signal:e}={}){let a=y3(i);return this.#l(`channels/${sa(t,"channel id")}/messages/${sa(o,"message id")}/reactions/${encodeURIComponent(a)}/@me`,{method:"DELETE",signal:e,expectBody:!1,retry:!1})}async#l(t,{method:o,body:i,signal:e,timeoutMs:a=15e3,expectBody:A=!0,retry:r=!0,multipart:s=!1}){let g;try{g=await this.#A(new URL(t,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:Q3(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&&r){let I=Math.min(1e4,Math.max(50,Number(c?.retry_after)*1e3||1e3));return await UBe(I,e),this.#l(t,{method:o,body:i,signal:e,timeoutMs:a,expectBody:A,retry:!1,multipart:s})}if(!g.ok){let I=new Error(cs(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 d=Number(c?.retry_after);throw Number.isFinite(d)&&d>=0&&(I.retry_after=d,I.retryAfter=d),I}return A?c:null}};async function S3(n,t={}){let i=await new cu({token:n,...t}).getCurrentUser();if(!i?.id||i?.bot!==!0)throw new Error("Discord token does not belong to a bot");return{platformId:String(i.id),name:cs(i.global_name)??cs(i.username)??w("Discord\u673A\u5668\u4EBA"),username:cs(i.username)}}var KBe=Object.freeze({success(){},error(){},clear(){},settled:()=>Promise.resolve()});function w3(n,t){!n||typeof n!="object"||(n[t]=(n[t]??0)+1)}async function xBe(n,t){let o=AbortSignal.timeout(t),i,e=new Promise((a,A)=>{i=()=>A(o.reason??new DOMException("Timed out","TimeoutError")),o.addEventListener("abort",i,{once:!0})});try{return await Promise.race([n(o),e])}finally{o.removeEventListener("abort",i)}}function ry({adapter:n,target:t,reactions:o,status:i,logger:e=console,label:a="channel",timeoutMs:A=2e3}={}){if(!t||typeof n?.addReaction!="function"||typeof n?.removeReaction!="function"||typeof o?.processing!="string"||!o.processing||!Number.isSafeInteger(A)||A<=0)return KBe;let r=null,s=!1,g=async(B,f)=>{try{let Q=await xBe(f,A);return w3(i,B==="add"?"reactionsAdded":"reactionsRemoved"),{ok:!0,value:Q}}catch(Q){return w3(i,"reactionErrors"),e.warn?.(`[dsh-im:${a}] status reaction ${B} failed:`,Q?.message??Q?.name??String(Q)),{ok:!1,value:null}}},c=async B=>{if(r!==null){let Q=r;r=null,await g("remove",y=>n.removeReaction(t,Q,{signal:y}))}if(typeof B!="string"||!B)return;let f=await g("add",Q=>n.addReaction(t,B,{signal:Q}));f.ok&&f.value!==void 0&&f.value!==null&&(r=f.value)},I=c(o.processing),d=B=>{s||(s=!0,I=I.then(()=>c(B),()=>c(B)),I.catch(()=>{}))};return Object.freeze({success:()=>d(o.success),error:()=>d(o.error),clear:()=>d(null),settled:()=>I})}var D3="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",YBe="\u4EFB\u52A1\u5DF2\u5B8C\u6210\u3002";function pi(n){return typeof n=="string"?n.trim():""}function jBe(n,t,o){return t.actor===o&&(n.kind!=="group"||n.addressed===!0)&&!Nt(n)&&!Dt(n)&&!!pi(n.content)}function JBe(n,t,o){let i=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim().slice(0,255)||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-permission-required":return o?.key==="slack"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i}):o?.key==="discord"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11 Discord \u7684 Send Messages\u3001Attach Files \u6216 Read Message History \u6743\u9650\u3002",{name:i}):o?.key==="telegram"?w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i}):w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u6E20\u9053\u5927\u5C0F\u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u672A\u53D1\u9001\u3002",{name:i});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:i});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5F53\u524D\u6E20\u9053\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:i});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D\u6E20\u9053\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:i})}}function so(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0}}var Is=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d=new Map;#c=new Map;#g=new Map;#I=new Map;#p=new Set;#h=new Set;#u;#C=new ki;constructor({descriptor:t,bot:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,status:r=so(),logger:s=console,replyTimeoutMs:g=6e5,signal:c}){if(!t?.key||!t?.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=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#u=new Mi({label:t.key,logger:s})}get status(){return structuredClone(this.#i)}accept(t,{contextSnapshot:o,accessDecision:i}={}){if(this.#s?.aborted)return Promise.resolve();let e=pi(t?.conversationId),a=t?.kind==="group"?"group":"direct",A={...t,kind:a,conversationId:e},r=pi(A.messageId),s=pi(A.senderId);if(!r||!s||!e||A.senderIsBot===!0||this.#r.hasSeen(r)||this.#I.has(r))return Promise.resolve();if(a==="group"&&A.addressed!==!0)return this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString(),this.#I.set(r,null),this.#f(A,r,null);if(this.#o||i){let I=Nt(A),d=Dt(A),B=i??Da(this.#o,{conversationType:a,senderIds:[s,pi(A.senderAlternateId)].filter(Boolean),text:A.content,hasImages:I,hasFiles:d});if(!B.allowed)return this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString(),this.#I.set(r,null),this.#f(A,r,B.reason==="command-not-allowed"?w(no):null,{recordReceived:B.reason==="command-not-allowed"})}this.#I.set(r,o===void 0?aa(this.#l,t?.kind):o);let g=ry({adapter:this.#A,target:A.kind==="direct"||A.addressed===!0?A.reactionTarget:null,reactions:this.#e.reactions,status:this.#i,logger:this.#a,label:this.#e.key});A.statusReaction=g;let c=this.#B(A,r,s);return c.then(()=>g.success(),()=>g.error()),c}#B(t,o,i){t.kind==="direct"&&Do(this.#r,t.connectionTestTarget??t.replyTarget);let e=`${t.kind}:${t.conversationId}`,a=this.#c.get(e),A=pi(t.content),r=vi(A);if(r&&t.kind==="group"&&t.addressed===!0)return this.#f(t,o,as());if(r&&t.kind==="direct"){if(/^\/batch$/iu.test(A)&&(this.#d.has(e)||a||this.#u.hasPending(e)))return this.#f(t,o,Ro());let d=this.#C.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Nt(t)&&!Dt(t)&&!Hr(t)});if(d.handled)return d.kind==="submit"?this.#Q({...t,content:d.prompt,batchSubmission:{token:d.token}},o,i,e):this.#f(t,o,d.message)}else if(t.kind==="direct"&&this.#C.status(e).phase==="collecting"){let I=this.#C.handle(e,A,{plainText:!!A&&t.plainText!==!1&&!Nt(t)&&!Dt(t)&&!Hr(t)});if(I.handled)return this.#f(t,o,I.message)}let g=t.kind==="direct"&&this.#C.status(e).phase==="collecting"?null:xa(A)?ao:Dt(t)?null:ci(A)?Ni:Ii(A)?io:li(A)?Ri:null;if(g&&(t.kind!=="group"||t.addressed===!0)){let I;return I=this.#S(t,o,e,g).finally(()=>{this.#I.delete(o),this.#h.delete(I)}),this.#h.add(I),I}let c=this.#u.claimReply({key:e,actor:i,messageId:o,text:Nt(t)||Dt(t)?"":t.content,addressed:t.kind!=="group"||t.addressed===!0,hasPendingQuestion:!!a,questionCompletion:a?.submitting||a?.claimedReplyMessageId?a.queue:null,isQuestionPending:()=>this.#c.has(e),send:I=>this.#A.sendText(t.replyTarget,I)});if(c){let I;return I=c.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#I.delete(o),this.#p.delete(I)}),this.#p.add(I),I}if(a&&a.actor!==i)return this.#Q(t,o,i,e);if(a?.submitting||a?.claimedReplyMessageId)return this.#Q(t,o,i,e);if(a){jBe(t,a,i)&&(a.claimedReplyMessageId=o);let d=(a.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#D(t,o,i,e,a)).finally(()=>{this.#I.delete(o),a.claimedReplyMessageId===o&&(a.claimedReplyMessageId=null),a.queue===d&&(a.queue=null)});return a.queue=d,d}return this.#Q(t,o,i,e)}#f(t,o,i,{recordReceived:e=!0}={}){let a;return a=(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),e&&(this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()),i&&await this.#A.sendText(t.replyTarget,i),this.#i.lastError=null)})().catch(async A=>{if(this.#s?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#i.lastError=A?.message??String(A);let r=tt(this.#i,A);this.#a.error?.(`[dsh-im:${this.#e.key}] failed to process a batch input message [${r.referenceId}]:`,A)}).finally(()=>{this.#I.delete(o),this.#h.delete(a)}),this.#h.add(a),a}#Q(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1}={}){let s=(this.#d.get(e)??Promise.resolve()).catch(()=>{}).then(()=>this.#m(t,o,i,e,{alreadyRecorded:A})).finally(()=>{a&&this.#I.delete(o),this.#d.get(e)===s&&this.#d.delete(e)});return this.#d.set(e,s),s}async waitForIdle(){await Promise.allSettled([...this.#d.values(),...[...this.#c.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#p,...this.#h])}async#S(t,o,i,e){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let a=t.replyTarget;try{let A=await e(pi(t.content),this.#t,this.#r,i,{signal:this.#s,isDirect:t.kind==="direct",hasImages:Nt(t),hasFiles:Dt(t),pendingInteraction:this.#c.has(i)||this.#u.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#P(i),this.#u.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#A.sendText(a,r);this.#i.lastError=null}catch(A){if(A?.code==="turn-stopped"||this.#s?.aborted){t.statusReaction?.clear();return}t.statusReaction?.error(),this.#i.lastError=A?.message??String(A);let r=tt(this.#i,A);this.#a.error?.(`[dsh-im:${this.#e.key}] failed to process a command [${r.referenceId}]:`,A),await this.#A.sendText(a,Et(r)).catch(()=>{})}}sendConnectionTest(t){return cc({state:this.#r,text:t,channelLabel:w("{label}\u673A\u5668\u4EBA",{label:this.#e.label}),send:(o,i)=>this.#A.sendText(o,i)})}sendProactiveText(t,o,{signal:i}={}){return i?.throwIfAborted(),this.#A.sendText(t,o)}async#y(t,o,i=[],e){let a=await Po({artifacts:i,baseReceipt:e,deliveryId:o,channelKey:this.#e.key,signal:this.#s,sendImage:typeof this.#A.sendImage=="function"?A=>this.#A.sendImage(t,A):void 0,sendFile:typeof this.#A.sendFile=="function"?A=>this.#A.sendFile(t,A):void 0,onFailure:(A,r)=>tt(this.#i,r,{userMessage:JBe(A?.fileName,r,this.#e),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#A.sendText(t,Et(s)),logger:this.#a});return this.#i.artifactsSent=(this.#i.artifactsSent??0)+a.artifactsSent,this.#i.artifactSendErrors=(this.#i.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,userVisible:a.userVisible,artifactSendErrors:a.artifactSendErrors}}async#m(t,o,i,e,{alreadyRecorded:a=!1}={}){if(!a){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}let A=t.replyTarget,r=pi(t.content),s=t.batchSubmission,g=null,c=!1;try{if(this.#s?.throwIfAborted(),t.kind==="group"&&t.addressed!==!0){this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString();return}let I=Nt(t),d=Dt(t),B=Hr(t);if(!r&&!I&&!d&&!B){await this.#A.sendText(A,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002"));return}let f=r.toLowerCase();if(!I&&!d&&f==="/help"){await this.#A.sendText(A,[w("{label}\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002",{label:this.#e.label}),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `));return}if(!I&&!d&&f==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#A.sendText(A,w("{label}\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002",{label:this.#e.label}));return}let Q=!I&&!d?await _o(r,this.#t,e):null;if(Q){for(let N of Q.messages??[Q.message])await this.#A.sendText(A,N);return}if(!I&&!d&&f==="/new"){await this.#r.clearSession(e),await this.#A.sendText(A,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"));return}let y=!I&&!d?await Ti(r,this.#t,this.#r,e,{signal:this.#s}):null;if(y){await this.#A.sendText(A,y.message);return}await this.#A.sendTyping?.(A).catch(N=>{this.#a.warn?.(`[dsh-im:${this.#e.key}] typing indicator failed:`,N)});let m=!1;if(typeof this.#A.openDeliveryStream=="function")try{g=await this.#A.openDeliveryStream(A),c=!0}catch(N){this.#a.warn?.(`[dsh-im:${this.#e.key}] unable to start a semantic reply stream; using final delivery:`,N)}else if(typeof this.#A.openStream=="function")try{g=await this.#A.openStream(A)}catch(N){this.#a.warn?.(`[dsh-im:${this.#e.key}] unable to start a streamed reply; using text:`,N)}let T=I||B?await Go(t,{signal:this.#s}):void 0,_=this.#I.get(o),R=!1;if(_){let N=T??r,k=t.contextSource?.();T=No(N,_,()=>({channel:this.#e.key,senderId:i,senderName:k?.senderName,conversationTitle:k?.conversationTitle,chatId:k?.chatId??t.conversationId,threadId:k?.threadId})),R=T!==N}let{answer:x,artifacts:F=[]}=await _i({harness:this.#t,state:this.#r,key:e,text:r,content:T,contextEnhanced:R,createOptions:this.#s?{signal:this.#s}:void 0,existsOptions:this.#s?{signal:this.#s}:void 0,askOptions:{timeoutMs:this.#n,signal:this.#s,control:{owner:this,key:e},onUpdate:g?async N=>{let k=N.type==="text"?N.text:N.type==="tool"?w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:N.name}):N.text;if(k){let J=N.type==="text"?"markdown":"plain";await g.update(c?os(k,J):k)}}:void 0,onInteraction:N=>this.#E(N,{key:e,actor:i,target:A,requiresMention:t.kind==="group"&&t.requiresMention!==!1}),onInteractionResolved:N=>this.#R(N),files:t.files}});s&&this.#C.complete(e,s.token);let L=!pi(x)&&F.length>0,q=L?w(YBe):x,z=L?"plain":"markdown",H=null,G=null;if(g)try{let N=await g.finish(c?os(q,z):q);m=!0,G=$t({deliveryId:o,presentation:N?.presentation??g.presentation??`${this.#e.key}-stream`,providerMessageIds:[...Ur(g),...Ur(N)],deliveryOutcome:N?.deliveryOutcome,reason:N?.reason})}catch(N){g.cancel?.(),this.#a.warn?.(`[dsh-im:${this.#e.key}] streamed reply finalization failed; using text:`,N)}if(!m)try{let N=typeof this.#A.sendDelivery=="function"?await this.#A.sendDelivery(A,os(q,z)):await this.#A.sendText(A,q);G=$t({deliveryId:o,presentation:N?.presentation??`${this.#e.key}-text`,providerMessageIds:Ur(N),deliveryOutcome:N?.deliveryOutcome,reason:N?.reason})}catch(N){H=Ua(N)}let V=G?.deliveryOutcome==="unknown";G?.deliveryOutcome==="failed"?H=Ua(new Error(`Final text delivery failed (${G.reason??"unknown"})`),{uncertain:!1}):V&&(H=Ua(new Error(`Final text delivery outcome is unknown (${G.reason??"unknown"})`)));let U=await this.#y(A,o,F,G);if(H&&(!U.userVisible||V))throw H.deliveryReceipt=U.receipt,H;return H&&U.artifactSendErrors===0&&tt(this.#i,H),U.userVisible&&(this.#i.messagesReplied+=1,this.#i.lastReplyAt=new Date().toISOString(),this.#i.lastError=null,!H&&U.artifactSendErrors===0&&Oo(this.#i)),U.receipt}catch(I){let d=I?.code==="turn-stopped";s&&d&&this.#C.complete(e,s.token);let B=s&&!d?this.#C.fail(e,s.token):null;if(d){if(t.statusReaction?.clear(),g)try{await g.finish(w("\u5DF2\u505C\u6B62\u3002"))}catch{g.cancel?.()}return}if(this.#s?.aborted){t.statusReaction?.clear(),g?.cancel?.();return}t.statusReaction?.error(),this.#i.lastError=I?.message??String(I);let f=async _=>{let R=typeof g?.fail=="function"?"fail":typeof g?.finish=="function"?"finish":null;if(!R)return!1;try{let x=await g[R](_);return R==="fail"?!!x&&x.deliveryOutcome!=="failed":x!==!1&&x?.deliveryOutcome!=="failed"}catch(x){return this.#a.warn?.(`[dsh-im:${this.#e.key}] unable to finalize the failed stream:`,x),!1}},Q=Mo(I),y=vo(I),m=tt(this.#i,I,{userMessage:y??Q,reason:ro(I)?.reason}),T=B?.retained?`${Et(m)} ${B.message}`:Et(m);if(this.#a.error?.(`[dsh-im:${this.#e.key}] failed to process a message [${m.referenceId}]:`,I),await f(T))return I.deliveryReceipt;g?.cancel?.();try{await this.#A.sendText(A,T)}catch(_){this.#a.error?.(`[dsh-im:${this.#e.key}] failed to send the safe error reply:`,_)}return I.deliveryReceipt}finally{await Promise.allSettled([this.#P(e),this.#u.closeRoute(e)])}}async#D(t,o,i,e,a){if(this.#s?.aborted){t.statusReaction?.clear();return}let A=this.#c.get(e),r=a.claimedReplyMessageId===o;if(!A||A!==a||A.submitting)return r&&(!A||A!==a)?this.#O(t,o):this.#Q(t,o,i,e,{releaseMessageId:!1});if(this.#r.hasSeen(o))return;if(await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),t.kind==="group"&&t.addressed!==!0){this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString();return}let s=t.replyTarget,g=pi(t.content);if(!g||Nt(t)||Dt(t)){try{await this.#A.sendText(s,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002"))}catch(d){this.#a.error?.(`[dsh-im:${this.#e.key}] failed to reject a non-text interaction reply:`,d)}return}let c=this.#c.get(e);if(!c||c!==a||c.submitting)return r&&(!c||c!==a)?this.#O(t,o,{alreadyRecorded:!0}):this.#Q(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(c.target=s,c.needsPresentation){let d=c.presentationTask!==null;try{await this.#_(c)}catch(f){t.statusReaction?.error(),this.#i.lastError=w("{label}\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002",{label:this.#e.label}),this.#a.error?.(`[dsh-im:${this.#e.key}] failed to retry an interaction question:`,f),c.interaction.reconnect?.();return}let B=this.#c.get(e);if(!B||B!==a||B.submitting)return r&&(!B||B!==a)?this.#O(t,o,{alreadyRecorded:!0}):this.#Q(t,o,i,e,{releaseMessageId:!1,alreadyRecorded:!0});if(!d)return}let I=c.questions[c.index];if(I){if(c.answers.push(bi(I,g)),c.index+=1,c.indexthis.#A.sendText(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=pi(t?.interactionId)||pi(t?.rpcId);if(!pi(t?.rpcId)||!r||!pi(t?.sessionId)||!Array.isArray(A)||A.length===0||A.some(c=>!Di(c))){this.#a.warn?.(`[dsh-im:${this.#e.key}] ignored an invalid Harness question interaction`);return}if(t.recovered===!0){await this.#M(t,`${this.#e.label} safely cancelled an interaction left by an earlier client.`);try{await this.#A.sendText(e,w("\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.#a.error?.(`[dsh-im:${this.#e.key}] failed to send an interaction recovery notice:`,c)}return}let s=this.#c.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#_(s);return}if(this.#g.has(r))return;if(s){this.#a.warn?.(`[dsh-im:${this.#e.key}] cancelled a second pending Harness question`),await this.#M(t,`${this.#e.label} is already handling another user interaction.`);return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,target:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationTask:null};this.#c.set(o,g),this.#g.set(r,o),await this.#_(g)}async#R(t){if(t?.kind==="approval"){await this.#u.handleResolved(t);return}let o=pi(t?.interactionId);if(t?.kind!=="question"||!o)return;let i=this.#g.get(o);i&&this.#T(i,o)}#_(t){if(t.presentationTask)return t.presentationTask;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=(async()=>{await this.#A.sendText(t.target,Oi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})),t.needsPresentation=!1})();return t.presentationTask=i,i.then(()=>{t.presentationTask===i&&(t.presentationTask=null)},()=>{t.presentationTask===i&&(t.presentationTask=null)}),i}async#O(t,o,{alreadyRecorded:i=!1}={}){if(!i){if(this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}try{await this.#A.sendText(t.replyTarget,w(D3))}catch(e){this.#a.error?.(`[dsh-im:${this.#e.key}] failed to send an expired interaction notice:`,e)}}#w(t,o){let i=this.#c.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#c.delete(t),this.#g.delete(i.interactionId),i)}#T(t,o){return this.#w(t,o)!==null}async#M(t,o){try{await t.respond({ok:!1,error:{code:"cancelled",message:o,details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){if(i?.code!=="interaction-not-pending")throw i}}async#P(t){let o=this.#w(t);if(!(!o||o.kind!=="question"))try{await this.#M(o.interaction,`The ${this.#e.label} interaction ended before the user answered.`)}catch(i){this.#a.warn?.(`[dsh-im:${this.#e.key}] failed to cancel a pending Harness interaction:`,i)}}};var pT=Object.freeze({key:"discord",label:"Discord",connectionLabel:" Gateway \u957F\u8FDE\u63A5",reactions:Object.freeze({processing:"\u{1F440}",success:"\u2705",error:"\u274C"})}),ay=class extends Is{constructor(t){super({descriptor:pT,...t})}};var Iu=class extends zd{constructor(t){super({...t,descriptor:pT,inspectToken:t.inspectToken??S3,deriveIdentity:B3,maskPlatformId:f3})}};var iy=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"discord",logPrefix:"dsh-discord"})}};function ls(n,t){let o=typeof n=="string"?n.trim():"";if(!o)return[];let i=[],e=o;for(;e.length>t;){let a=e.lastIndexOf(` @@ -346,17 +346,17 @@ ${a.join(` **1**\u5DE5\u4F5C\u533A\u5217\u8868 \xB7 **2**\u65B0\u4F1A\u8BDD \xB7 **3**\u4F1A\u8BDD\u5217\u8868 \xB7 **4**\u72B6\u6001 **5**\u{1F527}\u8865\u5168\u6743\u9650 \xB7 **6**\u5E2E\u52A9`))}),qo(w("\u{1F916} \u52A9\u624B\u4E2D\u5FC3"),B)}function Z6(n){let{items:t,defaultId:o}=n,i=n._currentId,e=t.find(s=>s.id===i),a=t.find(s=>s.id===o),A=i===null?w("\u8DDF\u968F Host \u9ED8\u8BA4{default}",{default:a?`\uFF08${a.label}\uFF09`:""}):e?`${e.label}\uFF08${e.id}\uFF09`:w("{id}\uFF08\u5DF2\u4E0D\u53EF\u7528\uFF09",{id:i}),r=[{tag:"div",text:Bt(w("**\u5F53\u524D**\uFF1A{value}",{value:A}))},{tag:"div",text:Bt(w("**Host \u9ED8\u8BA4**\uFF1A{value}",{value:a?`${a.label}\uFF08${a.id}\uFF09`:w("\u672A\u8BBE\u7F6E")}))},{tag:"hr"}];if(t.length>=1){let s=t.map(g=>({text:{tag:"plain_text",content:`${g.label}\uFF08${g.id}\uFF09${g.id===i?" \u2713":""}`},value:g.id}));r.push({tag:"select_static",name:"preset_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u9884\u8BBE")},initial_index:i===null?0:zp(s,i),options:s,behaviors:[{type:"callback",value:{action:"preset_pick"}}]},{tag:"hr"},fl(w("\u{1F504} \u8DDF\u968F\u9ED8\u8BA4"),"preset_default",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu"))}else r.push({tag:"div",text:Bt(w("\u5F53\u524D\u6CA1\u6709\u53EF\u9009\u62E9\u7684\u9884\u8BBE\u3002"))},Ql());return qo(w("\u{1F916} \u9884\u8BBE\u5217\u8868"),r)}function X6(n){let{groups:t,current:o}=n,i=o?`${o.provider}/${o.model}`:null,e=[{tag:"div",text:Bt(w("**\u5F53\u524D\u6A21\u578B**\uFF1A{model}",{model:i||w("\u672A\u8BBE\u7F6E")}))},{tag:"hr"}],a=0;for(let A of t)a+=A.models.length;if(a===0)e.push({tag:"div",text:Bt(w("\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u6A21\u578B\u3002"))},Ql());else{for(let r of t){let s=r.models.map(g=>{let c=`${r.id}/${g.id}`;return`${c}${c===i?" \u2713":""}`});e.push({tag:"div",text:Bt(`**${r.name}** ${s.join(` -`)}`)})}let A=[];for(let r of t)for(let s of r.models)A.push({value:`${r.id}/${s.id}`,text:{tag:"plain_text",content:`${r.name} - ${s.name}`}});e.push({tag:"hr"},{tag:"select_static",name:"model_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u6A21\u578B")},initial_index:i===null?0:zp(A,i),options:A.map(r=>({text:{tag:"plain_text",content:`${r.text.content}${r.value===i?" \u2713":""}`},value:r.value})),behaviors:[{type:"callback",value:{action:"model_pick"}}]},{tag:"hr"},Ql())}return qo(w("\u{1F9E0} \u6A21\u578B\u5217\u8868"),e)}function $6(n){let t=[{tag:"div",text:Bt(w("{icon} \u98DE\u4E66\u673A\u5668\u4EBA{state}",{icon:n.connected?"\u2705":"\u274C",state:n.connected?w("\u5DF2\u8FDE\u63A5"):w("\u672A\u8FDE\u63A5")}))},{tag:"div",text:Bt(w("\u{1F4C2} \u5DE5\u4F5C\u533A\uFF1A`{workspace}`",{workspace:n.workspace||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F916} \u9884\u8BBE\uFF1A{preset}",{preset:n.preset||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F9E0} \u6A21\u578B\uFF1A{model}",{model:n.model||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F4AC} \u4F1A\u8BDD\uFF1A{count} \u4E2A",{count:n.sessionCount}))},{tag:"hr"},Ql()];return qo(w("\u{1F4CA} \u7CFB\u7EDF\u72B6\u6001"),t)}function e5(){return["\u{1F916} \u52A9\u624B\u83DC\u5355\uFF08\u56DE\u590D\u6570\u5B57\u5373\u53EF\uFF0C\u65E0\u9700\u8BB0\u547D\u4EE4\uFF09","","\u{1F4CB} \u4F1A\u8BDD / \u5DE5\u4F5C\u533A","/sessionlist \u6216 /sessions \u5217\u51FA\u5DE5\u4F5C\u533A\u4F1A\u8BDD","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD","/session ID \u7ED1\u5B9A\u5DF2\u6709\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/new \u5F00\u542F\u5168\u65B0\u4F1A\u8BDD","","\u{1F4CA} \u72B6\u6001 / \u538B\u7F29","/status \u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/archived on/off \u4F1A\u8BDD\u5217\u8868\u663E\u793A/\u9690\u85CF\u5F52\u6863","","\u{1F441} \u5173\u6CE8","/watch ID \u5173\u6CE8\u4F1A\u8BDD\uFF08\u5B8C\u6210\u540E\u63A8\u9001\uFF09","/watchlist \u5173\u6CE8\u5217\u8868","/unwatch ID \u53D6\u6D88\u5173\u6CE8","","\u{1F916} \u9884\u8BBE / \u6A21\u578B","/presetlist \u6216 /presets \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","/models \u5217\u51FA\u6A21\u578B","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","","\u{1F4E6} \u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF09","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","","\u{1F3AE} \u4EFB\u52A1\u63A7\u5236","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","/steer \u6307\u4EE4 \u7ED9 Agent \u8865\u5145\u6307\u4EE4","/repair \u8865\u5168\u98DE\u4E66\u6743\u9650\u4E0E\u5361\u7247\u56DE\u8C03"].map(n=>w(n)).join(` +`)}`)})}let A=[];for(let r of t)for(let s of r.models)A.push({value:`${r.id}/${s.id}`,text:{tag:"plain_text",content:`${r.name} - ${s.name}`}});e.push({tag:"hr"},{tag:"select_static",name:"model_pick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u6A21\u578B")},initial_index:i===null?0:zp(A,i),options:A.map(r=>({text:{tag:"plain_text",content:`${r.text.content}${r.value===i?" \u2713":""}`},value:r.value})),behaviors:[{type:"callback",value:{action:"model_pick"}}]},{tag:"hr"},Ql())}return qo(w("\u{1F9E0} \u6A21\u578B\u5217\u8868"),e)}function $6(n){let t=[{tag:"div",text:Bt(w("{icon} \u98DE\u4E66\u673A\u5668\u4EBA{state}",{icon:n.connected?"\u2705":"\u274C",state:n.connected?w("\u5DF2\u8FDE\u63A5"):w("\u672A\u8FDE\u63A5")}))},{tag:"div",text:Bt(w("\u{1F4C2} \u5DE5\u4F5C\u533A\uFF1A`{workspace}`",{workspace:n.workspace||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F916} \u9884\u8BBE\uFF1A{preset}",{preset:n.preset||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F9E0} \u6A21\u578B\uFF1A{model}",{model:n.model||w("\u672A\u8BBE\u7F6E")}))},{tag:"div",text:Bt(w("\u{1F4AC} \u4F1A\u8BDD\uFF1A{count} \u4E2A",{count:n.sessionCount}))},{tag:"hr"},Ql()];return qo(w("\u{1F4CA} \u7CFB\u7EDF\u72B6\u6001"),t)}function e5(){return["\u{1F916} \u52A9\u624B\u83DC\u5355\uFF08\u56DE\u590D\u6570\u5B57\u5373\u53EF\uFF0C\u65E0\u9700\u8BB0\u547D\u4EE4\uFF09","","\u{1F4CB} \u4F1A\u8BDD / \u5DE5\u4F5C\u533A","/sessionlist \u6216 /sessions \u5217\u51FA\u5DE5\u4F5C\u533A\u4F1A\u8BDD","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD","/session ID \u7ED1\u5B9A\u5DF2\u6709\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A","/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D","/new \u5F00\u542F\u5168\u65B0\u4F1A\u8BDD","","\u{1F4CA} \u72B6\u6001 / \u538B\u7F29","/status \u8FDE\u63A5\u72B6\u6001","/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C","/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587","/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09","/archived on/off \u4F1A\u8BDD\u5217\u8868\u663E\u793A/\u9690\u85CF\u5F52\u6863","","\u{1F441} \u5173\u6CE8","/watch ID \u5173\u6CE8\u4F1A\u8BDD\uFF08\u5B8C\u6210\u540E\u63A8\u9001\uFF09","/watchlist \u5173\u6CE8\u5217\u8868","/unwatch ID \u53D6\u6D88\u5173\u6CE8","","\u{1F916} \u9884\u8BBE / \u6A21\u578B","/presetlist \u6216 /presets \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","/models \u5217\u51FA\u6A21\u578B","/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","","\u{1F4E6} \u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF09","/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21","","\u{1F3AE} \u4EFB\u52A1\u63A7\u5236","/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","/steer \u6307\u4EE4 \u7ED9 Agent \u8865\u5145\u6307\u4EE4","/repair \u8865\u5168\u98DE\u4E66\u6743\u9650\u4E0E\u5361\u7247\u56DE\u8C03"].map(n=>w(n)).join(` `)}var gve=["**\u{1F4CB} \u5361\u7247\u529F\u80FD**","","1. \u4F1A\u8BDD\u4E0B\u62C9 \u2014 \u5207\u6362\u5F53\u524D\u7ED1\u5B9A\u4F1A\u8BDD","2. \u5DE5\u4F5C\u533A\u4E0B\u62C9 \u2014 \u5207\u6362\u5DE5\u4F5C\u533A","3. \u{1F916} \u9884\u8BBE\u4E0B\u62C9 \u2014 \u5207\u6362 Agent \u9884\u8BBE","4. \u{1F9E0} \u6A21\u578B\u4E0B\u62C9 \u2014 \u5207\u6362\u6A21\u578B","5. \u{1F195} \u65B0\u4F1A\u8BDD \u2014 \u5F00\u542F\u5168\u65B0\u4F1A\u8BDD","6. \u{1F4CB} \u4F1A\u8BDD/\u5173\u6CE8 \u2014 \u67E5\u770B/\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u7BA1\u7406\u5173\u6CE8","7. \u23F9 \u505C\u6B62 \u2014 \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","8. \u{1F4D0} \u538B\u7F29 \u2014 \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587","9. \u8865\u5145\u6307\u4EE4 \u2014 \u7ED9 Agent \u53D1\u9001\u6307\u4EE4","10. \u{1F5C4} \u5F52\u6863\u5207\u6362 \u2014 \u663E\u793A/\u9690\u85CF\u5F52\u6863\u4F1A\u8BDD","11. \u{1F4CA} \u72B6\u6001 \u2014 \u67E5\u770B\u7CFB\u7EDF\u8FDE\u63A5\u72B6\u6001","12. \u{1F4D6} \u5E2E\u52A9 \u2014 \u67E5\u770B\u672C\u5E2E\u52A9"].join(` `),cve=["**\u2328\uFE0F \u6587\u672C\u547D\u4EE4**","","`/m` \u2014 \u6253\u5F00\u83DC\u5355\u5361\u7247","`/new` \u2014 \u5F00\u542F\u5168\u65B0\u4F1A\u8BDD","`/session ID` \u2014 \u7ED1\u5B9A\u5DF2\u6709\u4F1A\u8BDD","`/sessionlist [\u5DE5\u4F5C\u533A]` \u6216 `/sessions [\u5DE5\u4F5C\u533A]` \u2014 \u5217\u51FA\u4F1A\u8BDD","`/sessionlist --limit N` \u6216 `/sessions --limit N` \u2014 \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD","`/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84` \u2014 \u5207\u6362\u5DE5\u4F5C\u533A","`/workspacelist` \u2014 \u5217\u51FA\u5DE5\u4F5C\u533A","`/status` \u2014 \u67E5\u770B\u8FDE\u63A5\u72B6\u6001","`/compact` \u2014 \u538B\u7F29\u4E0A\u4E0B\u6587","`/stop` \u2014 \u505C\u6B62\u5F53\u524D\u4EFB\u52A1","`/steer \u6307\u4EE4` \u2014 \u8865\u5145\u6307\u4EE4","`/watch ID` \u2014 \u5173\u6CE8\u4F1A\u8BDD","`/watchlist` \u2014 \u5173\u6CE8\u5217\u8868","`/unwatch ID` \u2014 \u53D6\u6D88\u5173\u6CE8","`/archived on/off` \u2014 \u5F52\u6863\u663E\u9690","`/presetlist` \u6216 `/presets` \u2014 \u5217\u51FA\u9884\u8BBE","`/preset [\u5E8F\u53F7/ID]` \u2014 \u5207\u6362\u9884\u8BBE","`/preset --default` \u2014 \u8DDF\u968F\u9ED8\u8BA4","`/models` \u2014 \u5217\u51FA\u6A21\u578B","`/reasoninglist` \u6216 `/reasonings` \u2014 \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7","`/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default]` \u2014 \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7","`/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID]` \u2014 \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B","`/batch` \u2014 \u5F00\u542F\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09","`/send` \u2014 \u63D0\u4EA4\u5F53\u524D\u6279\u6B21","`/cancel` \u2014 \u53D6\u6D88\u5F53\u524D\u6279\u6B21","`/repair` \u2014 \u8865\u5168\u98DE\u4E66\u6743\u9650\u4E0E\u5361\u7247\u56DE\u8C03"].join(` `),Ive=["**\u{1F4A1} \u6570\u5B57\u515C\u5E95**","\u56DE\u590D\u6570\u5B57\u5FEB\u901F\u64CD\u4F5C\uFF1A","**1**\u5DE5\u4F5C\u533A\u5217\u8868 \xB7 **2**\u65B0\u4F1A\u8BDD \xB7 **3**\u4F1A\u8BDD/\u5173\u6CE8","**4**\u72B6\u6001 \xB7 **5**\u8865\u5168\u6743\u9650 \xB7 **6**\u5E2E\u52A9"].join(` `);function A5(n=[]){let t=Array.isArray(n)&&n.length>0?` `+n.join(` -`):"",o=[{tag:"div",text:Bt(w(gve))},{tag:"hr"},{tag:"div",text:Bt([w(cve),w("`/version` \u2014 \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09")].join(` +`):"",o=[{tag:"div",text:Bt(w(gve))},{tag:"hr"},{tag:"div",text:Bt([w(cve),w("/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D"),w("`/version` \u2014 \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09")].join(` `)+t)},{tag:"hr"},{tag:"div",text:Bt(w(Ive))},{tag:"hr"},Ql()];return qo(w("\u{1F4D6} \u5E2E\u52A9"),o)}function t5(n){if(typeof n!="string"||!/^[A-Za-z0-9_-]{16,128}$/.test(n))throw new TypeError("A safe card-action probe nonce is required");return qo(w("\u{1F9EA} \u9A8C\u8BC1\u5361\u7247\u6309\u94AE"),[{tag:"div",text:Bt(w("\u6388\u6743\u5DF2\u63D0\u4EA4\u3002\u8BF7\u70B9\u51FB\u4E0B\u65B9\u6309\u94AE\uFF1B\u673A\u5668\u4EBA\u771F\u5B9E\u6536\u5230\u56DE\u8C03\u540E\u624D\u4F1A\u5224\u5B9A\u4FEE\u590D\u6210\u529F\u3002"))},{tag:"column_set",flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:ES(w("\u5B8C\u6210\u9A8C\u8BC1")),type:"primary",width:"fill",behaviors:[{type:"callback",value:{action:"repair_verify",nonce:n}}]}]}]}])}function r5(n,t,o,i,e=new Set){let a=o*vc,A=t.slice(a,a+vc),r=Math.max(1,Math.ceil(i/vc)),s=I=>typeof e?.has=="function"&&e.has(I),g=(I,d)=>({tag:"column_set",flex_mode:"none",horizontal_spacing:"default",columns:[{tag:"column",width:"90px",vertical_align:"center",elements:[I]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[d]}]}),c=[{tag:"div",text:Bt(w(`**\u5DE5\u4F5C\u533A**\uFF1A{workspace} \u5171 **{total}** \u4E2A\u4F1A\u8BDD{paging}`,{workspace:`\`${n}\``,total:i,paging:i>vc?w("\uFF08\u7B2C {page}/{pageCount} \u9875\uFF09",{page:o+1,pageCount:r}):""}))},...A.map((I,d)=>{let B=`${d+1}. ${TC(I.title)}${I.archived===!0?w("\uFF08\u5DF2\u5F52\u6863\uFF09"):""}`,f=s(I.sessionId);return g(hS(f?w("\u2B50 \u53D6\u6D88\u5173\u6CE8"):w("\u2606 \u5173\u6CE8"),f?`unwatch:${I.sessionId}`:`watch:${I.sessionId}`),hS(B,`use:${I.sessionId}`))})];return o>0&&c.push(ws(w("\u25C0 \u4E0A\u4E00\u9875"),`sessions:${o-1}`)),o+1ws(`${e+1}. ${i}${i===t?w("\uFF08\u5F53\u524D\uFF09"):""}`,`workspace:${i}`)),{tag:"hr"},Ql()];return qo(w("\u{1F5C2} \u5DE5\u4F5C\u533A"),o)}function lve(n,t){let o=new Set(n.map(e=>e.sessionId)),i=(Array.isArray(t)?t:[]).filter(e=>e?.sessionId&&!o.has(e.sessionId)).slice(0,30).map(e=>({text:{tag:"plain_text",content:TC(e.title??e.sessionId)},value:e.sessionId}));return i.length===0?null:{tag:"multi_select_static",name:"watch_add",placeholder:{tag:"plain_text",content:w("\u52FE\u9009\u8981\u5173\u6CE8\u7684\u4F1A\u8BDD")},options:i,behaviors:[{type:"callback",value:{action:"watch_add",kind:"multi"}}]}}function dve(n){let t=n.slice(0,30).map(o=>({text:{tag:"plain_text",content:TC(o.title)},value:o.sessionId}));return t.length===0?null:{tag:"multi_select_static",name:"watch_remove",placeholder:{tag:"plain_text",content:w("\u52FE\u9009\u8981\u53D6\u6D88\u5173\u6CE8\u7684\u4F1A\u8BDD")},options:t,behaviors:[{type:"callback",value:{action:"watch_remove",kind:"multi"}}]}}function i5(n,t){let o=Array.isArray(n)?n:[],i=lve(o,t),e=dve(o),a=[];return o.length===0?a.push({tag:"div",text:Bt(w("\u5F53\u524D\u6CA1\u6709\u5173\u6CE8\u7684\u4F1A\u8BDD\u3002\u4EFB\u52A1\u5B8C\u6210\u4F1A\u81EA\u52A8\u63A8\u9001\u7ED3\u679C\u3002"))}):a.push({tag:"div",text:Bt(w("\u5F53\u524D\u5173\u6CE8 **{count}** \u4E2A\u4F1A\u8BDD\uFF1A",{count:o.length}))}),i&&a.push({tag:"hr"},{tag:"div",text:Bt(w("**\u2795 \u6DFB\u52A0\u5173\u6CE8**\uFF08\u591A\u9009\u4E0B\u62C9\u52FE\u9009\uFF09"))},i),e&&a.push({tag:"hr"},{tag:"div",text:Bt(w("**\u2796 \u53D6\u6D88\u5173\u6CE8**\uFF08\u591A\u9009\u4E0B\u62C9\u52FE\u9009\uFF09"))},e),a.push({tag:"hr"},fl(w("\u{1F4CB} \u4F1A\u8BDD\u5217\u8868"),"sessions",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")),qo(w("\u{1F441} \u5173\u6CE8\u5217\u8868"),a)}function o5(n,t,o){let i=o==="completed"?w("\u5DF2\u5B8C\u6210"):o==="stopped"?w("\u5DF2\u505C\u6B62"):o==="aborted"?w("\u5DF2\u4E2D\u6B62"):o==="cancelled"?w("\u5DF2\u53D6\u6D88"):w("\u5DF2\u7ED3\u675F");return qo(w("\u2705 \u4EFB\u52A1\u5B8C\u6210"),[{tag:"div",text:Bt(`**${TC(t)}** \`${n}\``)},{tag:"div",text:Bt(w("**\u72B6\u6001**\uFF1A{reason}",{reason:i}))},{tag:"hr"},fl(w("\u{1F4CB} \u4F1A\u8BDD\u5217\u8868"),"sessions",w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu"),{tag:"div",text:Bt(w("\u7ED1\u5B9A\u8BE5\u4F1A\u8BDD\u540E\u53EF\u7EE7\u7EED\u8FFD\u95EE\uFF0C\u8F93\u5165\u6587\u5B57\u5373\u53EF\u3002"))}])}var n5=["\u7EE7\u7EED","\u52A0\u901F\u8FD0\u884C","\u603B\u7ED3\u5F53\u524D\u8FDB\u5C55","\u66F4\u7B80\u6D01\u4E9B","\u66F4\u8BE6\u7EC6\u4E9B"],NC="__steer_custom__";function s5({hasSession:n}){let t=n?w("\u4ECE\u4E0B\u65B9\u4E0B\u62C9\u9009\u62E9\u8865\u5145\u6307\u4EE4\uFF1B\u6700\u540E\u4E00\u9879\u53EF\u81EA\u5B9A\u4E49\u8F93\u5165\u3002"):w("\u5F53\u524D\u6CA1\u6709\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u7ED1\u5B9A\u4F1A\u8BDD\u518D\u8865\u5145\u6307\u4EE4\u3002"),o=n5.map(e=>({text:{tag:"plain_text",content:w(e)},value:w(e)}));o.push({text:{tag:"plain_text",content:w("\u270F\uFE0F \u66F4\u591A / \u81EA\u5B9A\u4E49\u2026")},value:NC});let i=[{tag:"div",text:Bt(t)},{tag:"hr"},{tag:"select_static",name:"steer_quick",placeholder:{tag:"plain_text",content:w("\u9009\u62E9\u8865\u5145\u6307\u4EE4")},initial_index:0,options:o,behaviors:[{type:"callback",value:{action:"steer",source:"quick"}}]},{tag:"hr"},ws(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")];return qo(w("\u2795 \u8865\u5145\u6307\u4EE4"),i)}function TP(){let n=[{tag:"div",text:Bt(w("\u8F93\u5165\u8865\u5145\u6307\u4EE4\u540E\u70B9\u300C\u63D0\u4EA4\u300D\uFF0C\u53D1\u9001\u7ED9\u5F53\u524D\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))},{tag:"hr"},{tag:"form",name:"steer_form",elements:[{tag:"input",name:"steer_text",placeholder:{tag:"plain_text",content:w("\u8F93\u5165\u4F60\u7684\u8865\u5145\u6307\u4EE4")}},{tag:"button",name:"steer_submit",text:{tag:"plain_text",content:w("\u63D0\u4EA4")},type:"primary",width:"fill",form_action_type:"submit",behaviors:[{type:"callback",value:{action:"steer",source:"form"}}]}]},{tag:"hr"},ws(w("\u{1F519} \u8FD4\u56DE\u83DC\u5355"),"back_to_menu")];return qo(w("\u2795 \u81EA\u5B9A\u4E49\u6307\u4EE4"),n)}import{mkdir as pve,readFile as hve,rename as Eve,writeFile as uve}from"node:fs/promises";import{dirname as Cve}from"node:path";var Bve=Object.freeze({version:1,sessions:{},seenMessageIds:[],watches:{},includeArchivedSessions:!1}),CS=20;function NP(n){return n&&typeof n=="object"&&typeof n.sessionId=="string"&&n.sessionId.length>0&&typeof n.chatId=="string"&&n.chatId.length>0}var uS=class{#e;#A=structuredClone(Bve);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await hve(this.#e,"utf8"));this.#A={version:1,sessions:t.sessions&&typeof t.sessions=="object"?t.sessions:{},seenMessageIds:Array.isArray(t.seenMessageIds)?t.seenMessageIds.slice(-1e3):[],watches:t.watches&&typeof t.watches=="object"?t.watches:{},includeArchivedSessions:typeof t.includeArchivedSessions=="boolean"?t.includeArchivedSessions:!1}}catch(t){if(t?.code!=="ENOENT")throw t;await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}watchEntries(t){let o=this.#A.watches[t];return Array.isArray(o)?o.filter(NP):[]}watchEntry(t,o){return this.watchEntries(t).find(i=>i.sessionId===o)??null}async setWatch(t,o){let i=this.#A.watches[t]??[],e=i.findIndex(a=>a.sessionId===o.sessionId);e===-1?(i.length>=CS&&i.shift(),i.push(o)):i[e]=o,this.#A.watches[t]=i,await this.#r()}async removeWatch(t,o){let i=this.#A.watches[t]??[];this.#A.watches[t]=i.filter(e=>e.sessionId!==o),await this.#r()}async clearWatches(t){delete this.#A.watches[t],await this.#r()}keysWatching(t){return Object.entries(this.#A.watches).filter(([,o])=>Array.isArray(o)&&o.some(i=>NP(i)&&i.sessionId===t)).map(([o])=>o)}watchedSessionIds(){let t=new Set;for(let o of Object.values(this.#A.watches))if(Array.isArray(o))for(let i of o)NP(i)&&t.add(i.sessionId);return[...t]}includesArchivedSessions(){return this.#A.includeArchivedSessions===!0}async setIncludeArchivedSessions(t){this.#A.includeArchivedSessions=t===!0,await this.#r()}async#r(){let t=JSON.stringify(this.#A,null,2)+` -`;this.#t=this.#t.then(async()=>{await pve(Cve(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await uve(o,t,{encoding:"utf8",mode:384}),await Eve(o,this.#e)}),await this.#t}};var Pc=Object.freeze({MENTION:"mention",ALL:"all"});function ho(n){return n===Pc.ALL?Pc.ALL:Pc.MENTION}function BS(n){return n===Pc.MENTION||n===Pc.ALL}var fS=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),Qve=30*6e4,p5=/^\/m(?:enu)?$/i,h5=/^\/repair(?:\s|$)/i,yve=/^\/repair(?:\s+(qr|status|cancel|verify))?\s*$/i,kP=/^\/watch(?:\s+([^\s]+))?$/i,vP=/^\/unwatch(?:\s+([^\s]+))?$/i,E5=/^\/watchlist$/i,mve=/^\/(?:sessionlist|sessions)(?:\s|$)/i,Sve=/^\/workspacelist$/i,g5=/^\d{1,2}$/,wve=10*6e4,Dve=50,Ove=8,bve=8,Mve=10*6e4,c5=400,_ve=10*6e4,Tve=100,Nve=50,Rve=500,kve=5e3,vve=5e3,Pve=15e3,Gve=1e3,u5=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),RP=new Set([...u5,"saving"]),QS=new Set(["succeeded","expired","cancelled","error"]),Fve=new Set(["accounts.feishu.cn","open.feishu.cn","accounts.larksuite.com","open.larksuite.com"]),PP=/^\/archived(?:\s+(on|off))?$/i,Lve=/^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|watchlist|archived(?:\s+(on|off))?)$/i;function Uve(n,{hasImages:t=!1,hasFiles:o=!1}={}){if(t||o||typeof n!="string")return!1;let i=n.trim();return p5.test(i)||h5.test(i)||kP.test(i)||vP.test(i)||E5.test(i)||PP.test(i)}var Hve=["/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"];function RC(n){switch(n?.code){case"workspace-not-absolute":return w("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");case"workspace-not-found":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002");case"workspace-not-directory":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");case"workspace-bot-not-found":return w("\u673A\u5668\u4EBA\u6B63\u5728\u79FB\u9664\u6216\u5DF2\u91CD\u65B0\u63A5\u5165\uFF0C\u65E0\u6CD5\u64CD\u4F5C\u539F\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u3002");default:return w("\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}}function Kve(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11\u98DE\u4E66\u6587\u4EF6\u4E0A\u4F20\u6743\u9650 im:resource\u3002\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u6267\u884C /repair \u547D\u4EE4\uFF0C\u6216\u8005\u5728\u300CIM\u673A\u5668\u4EBA\u300D\u8BBE\u7F6E\u9875\u70B9\u51FB\u201C\u8865\u5168\u6743\u9650\u201D\u6309\u94AE\u5E76\u626B\u7801\u3002\u5B8C\u6210\u98DE\u4E66\u8981\u6C42\u7684\u53D1\u5E03\u5BA1\u6279\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u98DE\u4E66 30 MB \u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u98DE\u4E66\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u98DE\u4E66\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\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",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function yS(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function lA(n){return typeof n=="string"&&n.trim()?n.trim():null}function I5(n){if(n&&typeof n=="object"&&!Array.isArray(n))return n;if(typeof n!="string"||!n.trim())return{};try{let t=JSON.parse(n);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function vC(n){if(n==null)return null;if(Array.isArray(n)){for(let o of n){let i=vC(o);if(i!==null)return i}return null}if(n&&typeof n=="object")return"value"in n?vC(n.value):"option"in n?vC(n.option):null;if(typeof n!="string")return null;let t=n.trim();if(!t)return null;if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return vC(o)}catch{}return t}function Rg(n){if(n==null)return[];if(Array.isArray(n))return n.flatMap(o=>Rg(o));if(n&&typeof n=="object")return"value"in n?Rg(n.value):"option"in n?Rg(n.option):[];if(typeof n!="string")return[];let t=n.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Rg(o)}catch{}return t.split(",").map(o=>o.trim()).filter(Boolean)}function Tn(n){return Number.isSafeInteger(n)&&n>=-1}function PC(n){return Number.isSafeInteger(n)&&n>=0}function SS(n){return Number.isSafeInteger(n?.watchStartedAt)&&n.watchStartedAt>=0?n.watchStartedAt:null}function mS(n){return n&&(SS(n)!==null||!Tn(n.lastSeq))}function xve(n){return(Array.isArray(n?.events)?n.events:[]).map(t=>t?.event??t).filter(t=>t&&typeof t=="object"&&PC(t.seq)).sort((t,o)=>t.seq-o.seq)}function Vp(n){return lA(n?.sender?.sender_id?.open_id)??lA(n?.sender?.sender_id?.user_id)}function Yve(n){return lA(n?.sender?.sender_id?.open_id)}function l5(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))}t?.addEventListener("abort",A,{once:!0})})}function kC(n,{botId:t}={}){let o=n&&typeof n=="object"?n:{},i=o.registration&&typeof o.registration=="object"?o.registration:o,e=lA(i.operation)??lA(o.operation);if(e&&e!=="callback_repair")throw new Error("The active Feishu operation is not a callback repair");let a=lA(i.botId)??lA(o.botId);if(t&&a&&a!==t)throw new Error("The Feishu repair belongs to another bot");let A=lA(i.state),r=i.attemptId??i.attempt,s=typeof r=="string"||Number.isFinite(r)?String(r):null;if(!A||!s)throw new Error("Feishu returned an invalid repair status");let g=lA(i.verificationUrl)??lA(i.qrCodeUrl),c=Number(i.expiresAt),I=Number(i.remainingSeconds),d=Number(i.pollIntervalMs)||Number(i.pollIntervalSeconds)*1e3;return{state:A,attemptId:s,botId:a,verificationUrl:g,expiresAt:Number.isFinite(c)?c:null,remainingSeconds:Number.isFinite(I)?I:null,pollIntervalMs:Number.isFinite(d)&&d>0?d:null,error:i.error&&typeof i.error=="object"?{code:lA(i.error.code),message:lA(i.error.message)}:null}}function d5(n,t){let o=new URL(n);if(o.protocol!=="https:"||!Fve.has(o.hostname))throw new Error("Feishu returned an untrusted repair URL");if(o.searchParams.get("tp")!=="sdk"||o.searchParams.get("clientID")!==t||o.searchParams.has("createOnly"))throw new Error("Feishu returned an invalid existing-app repair URL");if(o.toString().includes("{{client_id}}")||o.toString().includes("%7B%7Bclient_id%7D%7D"))throw new Error("Feishu returned an unresolved client id placeholder");return o.toString()}function jve(n,t){return t.needsPresentation!==!0&&t.questions[t.index]&&Vp(n)===t.actor&&n?.message?.message_type==="text"&&lA(qp(n))}function Jve(n){for(let t of["messagesReceived","messagesReplied","messagesRejected"])n[t]??=0;n.lastMessageAt??=null,n.lastReplyAt??=null,n.lastRejectedAt??=null,n.lastError??=null,n.lastMessageError??=null}var wS=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new ki;#n=new Map;#s=new Map;#d=new Map;#c=new Map;#g=new Set;#I=new Set;#p=new Set;#h=new Map;#u=new Map;#C=new Map;#B=new Map;#f=new Map;#Q=new Map;#S=new Map;#y=new Map;#m=new Map;#D;#E;#R;#_;#O;#w;#T;#M;#P;#N;#F;#k=null;#K=0;#U;#j;#x=new Map;#G=new Map;#L=null;#z=new Map;#q=new Map;#v=new Map;#Z=new Map;#H;constructor({client:t,channel:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,status:r,allowedSenderOpenIds:s=new Set,botId:g,appId:c,botOpenId:I,groupResponseMode:d=Pc.ALL,repair:B,repairPollIntervalMs:f=Gve,repairLinkWaitMs:Q=Pve,cardDataTimeoutMs:y=vve,replyTimeoutMs:m=6e5,logger:T=console,signal:_}){if(!t||!i||!e||!r)throw new TypeError("Feishu bridge dependencies are required");if(B!=null){if(!B||typeof B.start!="function"||typeof B.status!="function"||typeof B.cancel!="function")throw new TypeError("Feishu repair capability requires start/status/cancel");if(!lA(g)||!lA(c))throw new TypeError("Feishu repair capability requires botId and appId")}if(!Number.isFinite(f)||f<=0||!Number.isFinite(Q)||Q<=0||!Number.isFinite(y)||y<=0)throw new TypeError("Feishu timing values must be positive numbers");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#E=r,this.#R=s,this.#T=lA(g),this.#M=lA(c),this.#P=lA(I),this.#N=ho(d),this.#F=B??null,this.#U=f,this.#j=Q,this.#H=y,this.#_=m,this.#O=T,this.#D=new Mi({label:"Feishu",logger:T}),this.#w=_,Jve(this.#E),typeof this.#t?.watchHarnessEvents=="function"&&queueMicrotask(()=>this.#ke())}setGroupResponseMode(t){this.#N=ho(t)}#te(t){if(t?.message?.chat_type==="p2p")return!0;let o=Array.isArray(t?.message?.mentions)?t.message.mentions:[];return this.#P?o.some(i=>i?.id?.open_id===this.#P||i?.open_id===this.#P):o.length>0}accept(t){if(this.#w?.aborted)return Promise.resolve();let o=lA(t?.message?.message_id);if(!o||z6(t))return Promise.resolve();if(!this.#o&&!V6(t,this.#R))return this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString(),this.#O.warn?.("[dsh-feishu] ignored a message from a sender outside the legacy allowlist"),Promise.resolve();let i=this.#te(t);if(t?.message?.chat_type!=="p2p"&&this.#N===Pc.MENTION&&!i||this.#r.hasSeen(o)||this.#c.has(o))return Promise.resolve();let e;try{e=Y6(t)}catch{return this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let a=dS(t,this.#e),A=lA(a.content)??"",r=Nt(a),s=Dt(a),g=t.message.chat_type==="p2p"?"direct":t.message.chat_type==="group"?"group":null,c=Da(this.#o,{conversationType:g,senderIds:Vp(t),text:A,hasImages:r,hasFiles:s,isCommand:HQ(A,{hasImages:r,hasFiles:s})||Uve(A,{hasImages:r,hasFiles:s})||!r&&!s&&g5.test(A)&&this.#x.has(e)});if(!c.allowed)return this.#c.set(o,null),this.#ae(t,o,c);if(t.message.chat_type==="p2p"){let T=lA(t.message.chat_id);T&&Do(this.#r,{chatId:T})}this.#c.set(o,aa(this.#l,g));let I=this.#BA(o),d=t.message.message_type==="text"?lA(qp(t))??"":"",B=t.message.message_type==="text"&&vi(d),f=this.#n.get(e),Q=this.#a.status(e);if(B&&t.message.chat_type!=="p2p")return this.#X(t,o,I,{message:as()});if(t.message.chat_type==="p2p"&&(B||Q.phase==="collecting")){let _=/^\/batch$/iu.test(d)&&Q.phase==="idle"&&(this.#i.has(e)||f||this.#D.hasPending(e))?{handled:!0,kind:"busy",message:Ro()}:this.#a.handle(e,d,{plainText:t.message.message_type==="text"&&!!d&&!Hr(a)});if(_.handled){if(_.kind==="submit"){let R={...t,batchSubmission:{token:_.token},message:{...t.message,message_type:"text",content:JSON.stringify({text:_.prompt}),mentions:[]}};return this.#J(R,o,e,I)}return this.#X(t,o,I,_)}}if(Lve.test(A))return Promise.resolve().then(()=>this.#be(t,e,{alreadyRecorded:!1})).then(()=>this.#re(o,I,"DONE")).catch(_=>this.#$(t,o,I,_)).finally(()=>this.#c.delete(o));let y=xa(A)?ao:Dt(a)?null:ci(A)?Ni:Ii(A)?io:li(A)?Ri:null;if(y&&(i||y===ao)){let T=this.#He(t,o,e,a,y),_;return _=T.then(()=>this.#re(o,I,"DONE")).catch(R=>this.#$(t,o,I,R)).finally(()=>{this.#c.delete(o),this.#I.delete(_)}),this.#I.add(_),_}if(this.#Se(t,e))return Promise.resolve().then(()=>this.#we(t,o)).then(()=>this.#re(o,I,"DONE")).catch(_=>this.#$(t,o,I,_)).finally(()=>this.#c.delete(o));let m=this.#D.claimReply({key:e,actor:Vp(t),messageId:o,text:qp(t)??"",addressed:i,hasPendingQuestion:!!f,questionCompletion:f?.submitting||f?.claimedReplyMessageId?f.queue:null,isQuestionPending:()=>this.#n.has(e),send:T=>this.#b(t.message.chat_id,T,{replyTo:t.message.message_id})});if(m){let T=m.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,!0)),_;return _=T.then(()=>this.#re(o,I,"DONE")).catch(R=>this.#$(t,o,I,R)).finally(()=>{this.#c.delete(o),this.#g.delete(_)}),this.#g.add(_),_}if(f&&Vp(t)!==f.actor)return this.#J(t,o,e,I);if(f?.submitting||f?.claimedReplyMessageId)return this.#J(t,o,e,I);if(f){jve(t,f)&&(f.claimedReplyMessageId=o);let _=(f.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#hA(t,o,e,f,I));f.queue=_;let R=()=>{f.claimedReplyMessageId===o&&(f.claimedReplyMessageId=null),f.queue===_&&(f.queue=null)},x;return x=_.then(()=>(R(),this.#re(o,I,"DONE")),F=>(R(),this.#$(t,o,I,F))).finally(()=>{R(),this.#c.delete(o),this.#g.delete(x)}),this.#g.add(x),x}return this.#J(t,o,e,I)}#X(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,e?.message&&await this.#b(t.message.chat_id,e.message,{replyTo:t.message.message_id}),this.#E.lastError=null)}).then(()=>this.#re(o,i,"DONE")).catch(A=>this.#$(t,o,i,A)).finally(()=>{this.#c.delete(o),this.#I.delete(a)}),this.#I.add(a),a}#ae(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),i.reason==="command-not-allowed"?(this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,await this.#b(t.message.chat_id,w(no),{replyTo:t.message.message_id}),this.#E.messagesReplied+=1,this.#E.lastReplyAt=new Date().toISOString()):(this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString()),this.#E.lastError=null)}).catch(a=>{this.#w?.aborted||(this.#E.lastError=a?.message??String(a),this.#O.warn?.("[dsh-feishu] failed to apply inbound access policy"))}).finally(()=>{this.#c.delete(o),this.#I.delete(e)}),this.#I.add(e),e}#J(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,finalize:r=!0}={}){let g=(this.#i.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#be(t,i,{alreadyRecorded:A})),c=r?g.then(async d=>(await this.#re(o,e,"DONE"),d)).catch(d=>this.#$(t,o,e,d)):g,I;return I=c.finally(()=>{a&&this.#c.delete(o),this.#i.get(i)===I&&this.#i.delete(i)}),this.#i.set(i,I),I}#V(t,{logLabel:o="operation",logLevel:i="warn",userMessage:e,reason:a}={}){this.#E.lastError=t?.message??String(t);let A=tt(this.#E,t,{userMessage:e,reason:a});return this.#O?.[i]?.(`[dsh-feishu] ${o} failed [${A.referenceId}]:`,t?.message??String(t)),A}async#Y(t,o,i={}){let e=this.#V(o,i),a=i.appendMessage?`${Et(e)} +`;this.#t=this.#t.then(async()=>{await pve(Cve(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await uve(o,t,{encoding:"utf8",mode:384}),await Eve(o,this.#e)}),await this.#t}};var Pc=Object.freeze({MENTION:"mention",ALL:"all"});function ho(n){return n===Pc.ALL?Pc.ALL:Pc.MENTION}function BS(n){return n===Pc.MENTION||n===Pc.ALL}var fS=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),Qve=30*6e4,p5=/^\/m(?:enu)?$/i,h5=/^\/repair(?:\s|$)/i,yve=/^\/repair(?:\s+(qr|status|cancel|verify))?\s*$/i,kP=/^\/watch(?:\s+([^\s]+))?$/i,vP=/^\/unwatch(?:\s+([^\s]+))?$/i,E5=/^\/watchlist$/i,mve=/^\/(?:sessionlist|sessions)(?:\s|$)/i,Sve=/^\/(?:workspacelist|workspaces|wsl)$/i,g5=/^\d{1,2}$/,wve=10*6e4,Dve=50,Ove=8,bve=8,Mve=10*6e4,c5=400,_ve=10*6e4,Tve=100,Nve=50,Rve=500,kve=5e3,vve=5e3,Pve=15e3,Gve=1e3,u5=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),RP=new Set([...u5,"saving"]),QS=new Set(["succeeded","expired","cancelled","error"]),Fve=new Set(["accounts.feishu.cn","open.feishu.cn","accounts.larksuite.com","open.larksuite.com"]),PP=/^\/archived(?:\s+(on|off))?$/i,Lve=/^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|workspaces|wsl|watchlist|archived(?:\s+(on|off))?)$/i;function Uve(n,{hasImages:t=!1,hasFiles:o=!1}={}){if(t||o||typeof n!="string")return!1;let i=n.trim();return p5.test(i)||h5.test(i)||kP.test(i)||vP.test(i)||E5.test(i)||PP.test(i)}var Hve=["/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A","/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD","/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84","/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898","/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"];function RC(n){switch(n?.code){case"workspace-not-absolute":return w("\u5DE5\u4F5C\u533A\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");case"workspace-not-found":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u5B58\u5728\u3002");case"workspace-not-directory":return w("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u5FC5\u987B\u6307\u5411\u4E00\u4E2A\u76EE\u5F55\u3002");case"workspace-bot-not-found":return w("\u673A\u5668\u4EBA\u6B63\u5728\u79FB\u9664\u6216\u5DF2\u91CD\u65B0\u63A5\u5165\uFF0C\u65E0\u6CD5\u64CD\u4F5C\u539F\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u3002");default:return w("\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}}function Kve(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u673A\u5668\u4EBA\u7F3A\u5C11\u98DE\u4E66\u6587\u4EF6\u4E0A\u4F20\u6743\u9650 im:resource\u3002\u8BF7\u79C1\u804A\u673A\u5668\u4EBA\u6267\u884C /repair \u547D\u4EE4\uFF0C\u6216\u8005\u5728\u300CIM\u673A\u5668\u4EBA\u300D\u8BBE\u7F6E\u9875\u70B9\u51FB\u201C\u8865\u5168\u6743\u9650\u201D\u6309\u94AE\u5E76\u626B\u7801\u3002\u5B8C\u6210\u98DE\u4E66\u8981\u6C42\u7684\u53D1\u5E03\u5BA1\u6279\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u98DE\u4E66 30 MB \u4E0A\u9650\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u98DE\u4E66\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u98DE\u4E66\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\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",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function yS(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function lA(n){return typeof n=="string"&&n.trim()?n.trim():null}function I5(n){if(n&&typeof n=="object"&&!Array.isArray(n))return n;if(typeof n!="string"||!n.trim())return{};try{let t=JSON.parse(n);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function vC(n){if(n==null)return null;if(Array.isArray(n)){for(let o of n){let i=vC(o);if(i!==null)return i}return null}if(n&&typeof n=="object")return"value"in n?vC(n.value):"option"in n?vC(n.option):null;if(typeof n!="string")return null;let t=n.trim();if(!t)return null;if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return vC(o)}catch{}return t}function Rg(n){if(n==null)return[];if(Array.isArray(n))return n.flatMap(o=>Rg(o));if(n&&typeof n=="object")return"value"in n?Rg(n.value):"option"in n?Rg(n.option):[];if(typeof n!="string")return[];let t=n.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{")||t.startsWith('"'))try{let o=JSON.parse(t);if(o!==n)return Rg(o)}catch{}return t.split(",").map(o=>o.trim()).filter(Boolean)}function Tn(n){return Number.isSafeInteger(n)&&n>=-1}function PC(n){return Number.isSafeInteger(n)&&n>=0}function SS(n){return Number.isSafeInteger(n?.watchStartedAt)&&n.watchStartedAt>=0?n.watchStartedAt:null}function mS(n){return n&&(SS(n)!==null||!Tn(n.lastSeq))}function xve(n){return(Array.isArray(n?.events)?n.events:[]).map(t=>t?.event??t).filter(t=>t&&typeof t=="object"&&PC(t.seq)).sort((t,o)=>t.seq-o.seq)}function Vp(n){return lA(n?.sender?.sender_id?.open_id)??lA(n?.sender?.sender_id?.user_id)}function Yve(n){return lA(n?.sender?.sender_id?.open_id)}function l5(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(a,n);e.unref?.();function a(){t?.removeEventListener("abort",A),o()}function A(){clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))}t?.addEventListener("abort",A,{once:!0})})}function kC(n,{botId:t}={}){let o=n&&typeof n=="object"?n:{},i=o.registration&&typeof o.registration=="object"?o.registration:o,e=lA(i.operation)??lA(o.operation);if(e&&e!=="callback_repair")throw new Error("The active Feishu operation is not a callback repair");let a=lA(i.botId)??lA(o.botId);if(t&&a&&a!==t)throw new Error("The Feishu repair belongs to another bot");let A=lA(i.state),r=i.attemptId??i.attempt,s=typeof r=="string"||Number.isFinite(r)?String(r):null;if(!A||!s)throw new Error("Feishu returned an invalid repair status");let g=lA(i.verificationUrl)??lA(i.qrCodeUrl),c=Number(i.expiresAt),I=Number(i.remainingSeconds),d=Number(i.pollIntervalMs)||Number(i.pollIntervalSeconds)*1e3;return{state:A,attemptId:s,botId:a,verificationUrl:g,expiresAt:Number.isFinite(c)?c:null,remainingSeconds:Number.isFinite(I)?I:null,pollIntervalMs:Number.isFinite(d)&&d>0?d:null,error:i.error&&typeof i.error=="object"?{code:lA(i.error.code),message:lA(i.error.message)}:null}}function d5(n,t){let o=new URL(n);if(o.protocol!=="https:"||!Fve.has(o.hostname))throw new Error("Feishu returned an untrusted repair URL");if(o.searchParams.get("tp")!=="sdk"||o.searchParams.get("clientID")!==t||o.searchParams.has("createOnly"))throw new Error("Feishu returned an invalid existing-app repair URL");if(o.toString().includes("{{client_id}}")||o.toString().includes("%7B%7Bclient_id%7D%7D"))throw new Error("Feishu returned an unresolved client id placeholder");return o.toString()}function jve(n,t){return t.needsPresentation!==!0&&t.questions[t.index]&&Vp(n)===t.actor&&n?.message?.message_type==="text"&&lA(qp(n))}function Jve(n){for(let t of["messagesReceived","messagesReplied","messagesRejected"])n[t]??=0;n.lastMessageAt??=null,n.lastReplyAt??=null,n.lastRejectedAt??=null,n.lastError??=null,n.lastMessageError??=null}var wS=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new ki;#n=new Map;#s=new Map;#d=new Map;#c=new Map;#g=new Set;#I=new Set;#p=new Set;#h=new Map;#u=new Map;#C=new Map;#B=new Map;#f=new Map;#Q=new Map;#S=new Map;#y=new Map;#m=new Map;#D;#E;#R;#_;#O;#w;#T;#M;#P;#N;#F;#k=null;#K=0;#U;#j;#x=new Map;#G=new Map;#L=null;#z=new Map;#q=new Map;#v=new Map;#Z=new Map;#H;constructor({client:t,channel:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,status:r,allowedSenderOpenIds:s=new Set,botId:g,appId:c,botOpenId:I,groupResponseMode:d=Pc.ALL,repair:B,repairPollIntervalMs:f=Gve,repairLinkWaitMs:Q=Pve,cardDataTimeoutMs:y=vve,replyTimeoutMs:m=6e5,logger:T=console,signal:_}){if(!t||!i||!e||!r)throw new TypeError("Feishu bridge dependencies are required");if(B!=null){if(!B||typeof B.start!="function"||typeof B.status!="function"||typeof B.cancel!="function")throw new TypeError("Feishu repair capability requires start/status/cancel");if(!lA(g)||!lA(c))throw new TypeError("Feishu repair capability requires botId and appId")}if(!Number.isFinite(f)||f<=0||!Number.isFinite(Q)||Q<=0||!Number.isFinite(y)||y<=0)throw new TypeError("Feishu timing values must be positive numbers");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#E=r,this.#R=s,this.#T=lA(g),this.#M=lA(c),this.#P=lA(I),this.#N=ho(d),this.#F=B??null,this.#U=f,this.#j=Q,this.#H=y,this.#_=m,this.#O=T,this.#D=new Mi({label:"Feishu",logger:T}),this.#w=_,Jve(this.#E),typeof this.#t?.watchHarnessEvents=="function"&&queueMicrotask(()=>this.#ke())}setGroupResponseMode(t){this.#N=ho(t)}#te(t){if(t?.message?.chat_type==="p2p")return!0;let o=Array.isArray(t?.message?.mentions)?t.message.mentions:[];return this.#P?o.some(i=>i?.id?.open_id===this.#P||i?.open_id===this.#P):o.length>0}accept(t){if(this.#w?.aborted)return Promise.resolve();let o=lA(t?.message?.message_id);if(!o||z6(t))return Promise.resolve();if(!this.#o&&!V6(t,this.#R))return this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString(),this.#O.warn?.("[dsh-feishu] ignored a message from a sender outside the legacy allowlist"),Promise.resolve();let i=this.#te(t);if(t?.message?.chat_type!=="p2p"&&this.#N===Pc.MENTION&&!i||this.#r.hasSeen(o)||this.#c.has(o))return Promise.resolve();let e;try{e=Y6(t)}catch{return this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString(),Promise.resolve()}let a=dS(t,this.#e),A=lA(a.content)??"",r=Nt(a),s=Dt(a),g=t.message.chat_type==="p2p"?"direct":t.message.chat_type==="group"?"group":null,c=Da(this.#o,{conversationType:g,senderIds:Vp(t),text:A,hasImages:r,hasFiles:s,isCommand:HQ(A,{hasImages:r,hasFiles:s})||Uve(A,{hasImages:r,hasFiles:s})||!r&&!s&&g5.test(A)&&this.#x.has(e)});if(!c.allowed)return this.#c.set(o,null),this.#ae(t,o,c);if(t.message.chat_type==="p2p"){let T=lA(t.message.chat_id);T&&Do(this.#r,{chatId:T})}this.#c.set(o,aa(this.#l,g));let I=this.#BA(o),d=t.message.message_type==="text"?lA(qp(t))??"":"",B=t.message.message_type==="text"&&vi(d),f=this.#n.get(e),Q=this.#a.status(e);if(B&&t.message.chat_type!=="p2p")return this.#X(t,o,I,{message:as()});if(t.message.chat_type==="p2p"&&(B||Q.phase==="collecting")){let _=/^\/batch$/iu.test(d)&&Q.phase==="idle"&&(this.#i.has(e)||f||this.#D.hasPending(e))?{handled:!0,kind:"busy",message:Ro()}:this.#a.handle(e,d,{plainText:t.message.message_type==="text"&&!!d&&!Hr(a)});if(_.handled){if(_.kind==="submit"){let R={...t,batchSubmission:{token:_.token},message:{...t.message,message_type:"text",content:JSON.stringify({text:_.prompt}),mentions:[]}};return this.#J(R,o,e,I)}return this.#X(t,o,I,_)}}if(Lve.test(A))return Promise.resolve().then(()=>this.#be(t,e,{alreadyRecorded:!1})).then(()=>this.#re(o,I,"DONE")).catch(_=>this.#$(t,o,I,_)).finally(()=>this.#c.delete(o));let y=xa(A)?ao:Dt(a)?null:ci(A)?Ni:Ii(A)?io:li(A)?Ri:null;if(y&&(i||y===ao)){let T=this.#He(t,o,e,a,y),_;return _=T.then(()=>this.#re(o,I,"DONE")).catch(R=>this.#$(t,o,I,R)).finally(()=>{this.#c.delete(o),this.#I.delete(_)}),this.#I.add(_),_}if(this.#Se(t,e))return Promise.resolve().then(()=>this.#we(t,o)).then(()=>this.#re(o,I,"DONE")).catch(_=>this.#$(t,o,I,_)).finally(()=>this.#c.delete(o));let m=this.#D.claimReply({key:e,actor:Vp(t),messageId:o,text:qp(t)??"",addressed:i,hasPendingQuestion:!!f,questionCompletion:f?.submitting||f?.claimedReplyMessageId?f.queue:null,isQuestionPending:()=>this.#n.has(e),send:T=>this.#b(t.message.chat_id,T,{replyTo:t.message.message_id})});if(m){let T=m.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,!0)),_;return _=T.then(()=>this.#re(o,I,"DONE")).catch(R=>this.#$(t,o,I,R)).finally(()=>{this.#c.delete(o),this.#g.delete(_)}),this.#g.add(_),_}if(f&&Vp(t)!==f.actor)return this.#J(t,o,e,I);if(f?.submitting||f?.claimedReplyMessageId)return this.#J(t,o,e,I);if(f){jve(t,f)&&(f.claimedReplyMessageId=o);let _=(f.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#hA(t,o,e,f,I));f.queue=_;let R=()=>{f.claimedReplyMessageId===o&&(f.claimedReplyMessageId=null),f.queue===_&&(f.queue=null)},x;return x=_.then(()=>(R(),this.#re(o,I,"DONE")),F=>(R(),this.#$(t,o,I,F))).finally(()=>{R(),this.#c.delete(o),this.#g.delete(x)}),this.#g.add(x),x}return this.#J(t,o,e,I)}#X(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,e?.message&&await this.#b(t.message.chat_id,e.message,{replyTo:t.message.message_id}),this.#E.lastError=null)}).then(()=>this.#re(o,i,"DONE")).catch(A=>this.#$(t,o,i,A)).finally(()=>{this.#c.delete(o),this.#I.delete(a)}),this.#I.add(a),a}#ae(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),i.reason==="command-not-allowed"?(this.#E.lastMessageAt=new Date().toISOString(),this.#E.messagesReceived+=1,await this.#b(t.message.chat_id,w(no),{replyTo:t.message.message_id}),this.#E.messagesReplied+=1,this.#E.lastReplyAt=new Date().toISOString()):(this.#E.messagesRejected+=1,this.#E.lastRejectedAt=new Date().toISOString()),this.#E.lastError=null)}).catch(a=>{this.#w?.aborted||(this.#E.lastError=a?.message??String(a),this.#O.warn?.("[dsh-feishu] failed to apply inbound access policy"))}).finally(()=>{this.#c.delete(o),this.#I.delete(e)}),this.#I.add(e),e}#J(t,o,i,e,{releaseMessageId:a=!0,alreadyRecorded:A=!1,finalize:r=!0}={}){let g=(this.#i.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#be(t,i,{alreadyRecorded:A})),c=r?g.then(async d=>(await this.#re(o,e,"DONE"),d)).catch(d=>this.#$(t,o,e,d)):g,I;return I=c.finally(()=>{a&&this.#c.delete(o),this.#i.get(i)===I&&this.#i.delete(i)}),this.#i.set(i,I),I}#V(t,{logLabel:o="operation",logLevel:i="warn",userMessage:e,reason:a}={}){this.#E.lastError=t?.message??String(t);let A=tt(this.#E,t,{userMessage:e,reason:a});return this.#O?.[i]?.(`[dsh-feishu] ${o} failed [${A.referenceId}]:`,t?.message??String(t)),A}async#Y(t,o,i={}){let e=this.#V(o,i),a=i.appendMessage?`${Et(e)} ${i.appendMessage}`:Et(e);return await this.#b(t,a,{replyTo:i.replyTo}).catch(()=>{}),e}async#$(t,o,i,e){if(e?.code==="turn-stopped"){await this.#Ue(o,i),e?.batchInputMessage&&await this.#b(t.message.chat_id,e.batchInputMessage,{replyTo:t.message.message_id}).catch(()=>{});return}if(this.#w?.aborted){await this.#Ue(o,i);return}let a=vo(e)??Mo(e),A=this.#V(e,{logLabel:"message handling",logLevel:"error",userMessage:a,reason:ro(e)?.reason});await this.#re(o,i,"ERROR");let r=e?.batchInputMessage?`${Et(A)} @@ -371,7 +371,7 @@ ID\uFF1A{id}`,{title:r,id:A?.sessionId??i}),w("\u53D1\u9001 /history \u67E5\u770 ${w("\u5185\u5BB9\u8F83\u957F\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u5C06\u5206\u6BB5\u53D1\u9001\u5B8C\u6574\u56DE\u7B54\u3002")}`;return LP(n,FC-t.length)+t}function Xve(n){let t=[],o=n;for(;o.length>FC;){let i=LP(o,FC),e=i.lastIndexOf(` `)+1;e(A&&(a=await this.#o(t,i.replyTo),e.push(a),A=!1),a),g={get messageId(){return a.messageId},rotate:async()=>{if(!A){A=!0;try{await this.#i(a,`${GP(r)} -${w("\u2935\uFE0F \u6700\u7EC8\u7ED3\u679C\u89C1\u4E0B\u65B9")}`),await this.#a(a)}catch(I){console.warn("[dsh-feishu] unable to finalize the superseded stream card:",I.message)}}},setContent:async I=>{let d=String(I??"")||"\u2026",B=await s();await this.#i(B,GP(d)),r=d}};await o.markdown(g);let c=Xve(r);for(let[I,d]of c.entries()){let B=I===0?await s():await this.#o(t,i.replyTo);I>0&&e.push(B),await this.#i(B,d),await this.#a(B)}return{messageId:e[0].messageId,providerMessageIds:e.map(I=>I.messageId)}}catch(r){for(let s of e)await this.#s(s.messageId);throw r}}async sendFile(t,o,{replyTo:i,signal:e}={}){return this.#l(t,o,{replyTo:i,signal:e,messageType:"file",presentation:"feishu-file"})}async sendImage(t,o,{replyTo:i,signal:e}={}){return this.#l(t,o,{replyTo:i,signal:e,messageType:"image",presentation:"feishu-image"})}async#l(t,o,{replyTo:i,signal:e,messageType:a,presentation:A}){if(e?.throwIfAborted(),typeof t!="string"||!t)throw new TypeError("chatId is required");if(!o||typeof o!="object"||typeof o.artifactId!="string"||!o.artifactId||typeof o.deliveryKey!="string"||!o.deliveryKey||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A materialized result file is required");let r;try{r=await B5(Q=>{Q.throwIfAborted();let y=a==="image"?this.#e.im.v1.image.create({data:{image_type:"message",image:o.bytes}}):this.#e.im.v1.file.create({data:{file_type:"stream",file_name:o.fileName,file:o.bytes}});return yn(o,y),y},{signal:e,timeoutMs:this.#t,stage:"upload"})}catch(Q){throw e?.aborted?FP(e):GC("upload",Q)}e?.throwIfAborted();let s=a==="image"?r?.image_key??r?.data?.image_key:r?.file_key??r?.data?.file_key;if(typeof s!="string"||!s)throw GC("upload",void 0,r?.code);let g=Wve(o,t,a),c=JSON.stringify(a==="image"?{image_key:s}:{file_key:s}),I=i?{path:{message_id:i},data:{msg_type:a,content:c,uuid:g}}:{params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:a,content:c,uuid:g}},d=()=>{let Q=i?this.#e.im.v1.message.reply(I):this.#e.im.v1.message.create(I);return yn(o,Q),Q},B;try{B=await B5(async Q=>{Q.throwIfAborted();let y;try{y=await d()}catch(m){if(y5(m)!==230049)throw m;y={code:230049}}return Q.throwIfAborted(),Number(y?.code)===230049&&(y=await d(),Q.throwIfAborted()),y},{signal:e,timeoutMs:this.#r,stage:"message send"})}catch(Q){throw e?.aborted?FP(e):GC("message send",Q,void 0,{uncertain:!0})}if(Number.isFinite(Number(B?.code))&&Number(B.code)!==0)throw GC("message send",void 0,B.code,{uncertain:!0});let f=B?.data?.message_id;if(typeof f!="string"||!f)throw GC("message send",void 0,void 0,{uncertain:!0});return $t({deliveryId:o.deliveryKey,presentation:A,providerMessageIds:[f],artifacts:[{artifactId:o.artifactId,outcome:"sent"}]})}async#o(t,o){let i=GP(this.#A),a=yl("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify($ve(i))}}))?.data?.card_id;if(!a)throw new Error("Feishu card.create returned no card_id");let A=await this.#n(t,a,o);return{cardId:a,messageId:A,content:i,sequence:0}}async#i(t,o){if(o===t.content)return;let i=await this.#e.cardkit.v1.cardElement.content({path:{card_id:t.cardId,element_id:f5},data:{content:o,sequence:++t.sequence,uuid:`content_${t.cardId}_${t.sequence}`}});yl("Feishu cardElement.content",i),t.content=o}async#a(t){let o=await this.#e.cardkit.v1.card.settings({path:{card_id:t.cardId},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:Zve(t.content)||w("\u56DE\u7B54\u5B8C\u6210")}}}),sequence:++t.sequence,uuid:`settings_${t.cardId}_${t.sequence}`}});yl("Feishu card.settings",o)}async#n(t,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:e}});yl("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#s(t){try{let o=await this.#e.im.v1.message.delete({path:{message_id:t}});yl("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(t,o){let e=yl("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(t,o){yl("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}}))}};var S5="/open-apis/application/v7/app_slash_commands",ePe=new Set(["99991640","99991672"]),bS=Object.freeze(["application:app_slash_command:read","application:app_slash_command:write"]),w5="ai-agent_outlined",UP=Object.freeze([{command:"menu",icon:"skill_outlined",default:"\u6253\u5F00\u529F\u80FD\u83DC\u5355",en_us:"Open the feature menu"},{command:"new",icon:"ai-deepthink_outlined",default:"\u5F00\u542F\u5168\u65B0\u4F1A\u8BDD",en_us:"Start a fresh session"},{command:"help",icon:"promptword_outlined",default:"\u67E5\u770B\u5E2E\u52A9",en_us:"Show help"},{command:"status",icon:"ai-functions_outlined",default:"\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001",en_us:"Show bot status"},{command:"compact",icon:"ai-block_outlined",default:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587",en_us:"Compact the current session"},{command:"sessionlist",icon:"chat-ai_outlined",default:"\u5217\u51FA\u4F1A\u8BDD",en_us:"List sessions"},{command:"workspacelist",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"watch",icon:"flag_outlined",default:"\u5173\u6CE8\u4E00\u4E2A\u4F1A\u8BDD",en_us:"Watch a session"},{command:"unwatch",icon:"clear_outlined",default:"\u53D6\u6D88\u5173\u6CE8\u4F1A\u8BDD",en_us:"Unwatch a session"},{command:"watchlist",icon:"flag_outlined",default:"\u67E5\u770B\u5173\u6CE8\u5217\u8868",en_us:"List watched sessions"},{command:"archived",icon:"folder_outlined",default:"\u8BBE\u7F6E\u5F52\u6863\u4F1A\u8BDD\u663E\u9690\uFF08on/off\uFF09",en_us:"Show or hide archived sessions (on/off)"}]);function HP(n,t){let o=n==="lark"?"https://open.larksuite.com":"https://open.feishu.cn";return new URL(t,o)}function m5(n,t){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} returned a non-JSON response`);if(n.code!==0){let o=new Error(`${t} failed: ${n.msg||`code ${n.code}`}`);throw o.code=String(n.code),o.msg=n.msg,o}return n}function KP(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}async function xP(n,t,o){try{return m5(await n.request(t),o)}catch(i){let e=i?.response?.data;if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"code"))return m5(e,o);throw i}}async function APe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}){if(!n||!t)throw new Error("Feishu slash registration requires app credentials");if(!i||typeof i.request!="function")throw new TypeError("Feishu slash registration requires an HTTP instance");let A=await xP(i,{method:"POST",url:HP(o,"/open-apis/auth/v3/tenant_access_token/internal").href,headers:{"content-type":"application/json; charset=utf-8"},data:{app_id:n,app_secret:t},signal:KP(a,e),timeout:e},"Feishu authentication");if(!A.tenant_access_token)throw new Error("Feishu authentication returned no tenant access token");return A.tenant_access_token}async function tPe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e}){let a=await xP(o,{method:"GET",url:HP(t,S5).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},signal:KP(e,i),timeout:i},"Feishu slash command list");return Array.isArray(a.data?.items)?a.data.items:[]}async function rPe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e,command:a,description:A,icon:r=w5}){let s={command:a};return A&&(A.default_value||A.i18n)?s.description=A:typeof A=="string"&&A.trim()&&(s.description={default_value:A.trim()}),r&&(s.description={...s.description??{},icon:{icon_key:r}}),(await xP(o,{method:"POST",url:HP(t,S5).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},data:s,signal:KP(e,i),timeout:i},`Feishu slash command create (/${a})`)).data?.command_id??null}async function D5({appId:n,appSecret:t,domain:o="feishu",httpInstance:i,timeoutMs:e=15e3,signal:a,manifest:A=UP}){let r=await APe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}),s=new Set((await tPe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a})).map(I=>I.command)),g=[],c=[];for(let I of A){let d=String(I.command??"").replace(/^\//,"");if(d&&!s.has(d))try{let B={default_value:I.default??I.en_us??d,i18n:{zh_cn:I.default??d,en_us:I.en_us??I.default??d}},f=await rPe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a,command:d,description:B,icon:I.icon??w5});g.push({command:d,command_id:f})}catch(B){if(B?.code==="40000000"&&/already exists/i.test(B?.msg??"")){s.add(d);continue}if(ePe.has(B?.code)||/(?:lacks permission|access denied)/i.test(B?.msg??"")){c.push({command:d,error:B});break}c.push({command:d,error:B?.message??String(B)})}}return{created:g,existing:[...s].filter(I=>I!=null),failed:c}}var iPe=15e3,oPe="\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002",nPe="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u8D85\u65F6\uFF1A\u672A\u6536\u5230\u6D4B\u8BD5\u5361\u6309\u94AE\u7684 card.action.trigger\uFF0C\u4E0D\u80FD\u786E\u8BA4\u6309\u94AE\u5DF2\u4FEE\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u7684\u5361\u7247\u56DE\u8C03\u914D\u7F6E\uFF0C\u786E\u8BA4\u540E\u518D\u53D1\u9001 /repair\u3002",YP="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A\u65E0\u6CD5\u53D1\u9001\u4E13\u7528\u6D4B\u8BD5\u5361\uFF0C\u4E0D\u80FD\u786E\u8BA4 card.action.trigger \u5DF2\u6062\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u673A\u5668\u4EBA\u6D88\u606F\u6743\u9650\u548C\u8FDE\u63A5\u72B6\u6001\u3002",sPe="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u4E2D\u65AD\uFF1ARuntime \u5DF2\u505C\u6B62\uFF0C\u672A\u5B8C\u6210 card.action.trigger \u5B9E\u6D4B\uFF0C\u4E0D\u80FD\u786E\u8BA4\u4FEE\u590D\u6210\u529F\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u7B49\u5F85\u673A\u5668\u4EBA\u6062\u590D\u8FDE\u63A5\u3002",gPe=new Set(["connected","connecting","reconnecting"]);function Nn(n){return typeof n=="string"&&n.trim()?n.trim():null}function cPe(n){return Nn(n?.operator?.open_id)??Nn(n?.operator?.operator_id?.open_id)}function IPe(n,t){try{let o=n?.getConnectionStatus?.()?.state;return typeof o=="string"&&o?o:t}catch{return t}}function Wp(n,t){let o=new Error(t);return o.code=n,o}function lPe(n,t){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??t});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function dPe({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,cardActionsReceived:0,cardActionProbesVerified:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastCardActionAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n,slashCommandRegistration:"idle",slashCommandsRegistered:0,slashCommandsExisting:0,slashCommandsFailed:0,slashCommandsError:null}}var MS=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g;#I;#p;#h;#u;#C;#B=null;#f=null;#Q=null;#S=null;#y=null;#m=null;#D=new Map;#E;#R=!0;constructor({lark:t,botId:o,appId:i,appSecret:e,domain:a="feishu",botOpenId:A,groupResponseMode:r,ownerOpenId:s,ownerOpenIds:g,harness:c,state:I,contextEnhancement:d,accessPolicy:B,repair:f,replyTimeoutMs:Q=6e5,connectTimeoutMs:y=15e3,requestTimeoutMs:m=iPe,slashCommands:T=!0,wsAgent:_,logger:R=console}){if(!t)throw new Error("FeishuRuntime requires the Feishu SDK");if(!i||!e)throw new Error("FeishuRuntime requires app credentials");let x=Array.isArray(g)?g:[s],F=[...new Set(x.filter(L=>typeof L=="string"&&L))];if(F.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!c)throw new Error("FeishuRuntime requires a Harness client");if(!I)throw new Error("FeishuRuntime requires a state store");if(f!=null&&!Nn(o))throw new TypeError("FeishuRuntime repair capability requires a botId");if(!Number.isFinite(m)||m<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=t,this.#A=Nn(o),this.#t=i,this.#r=e,this.#l=a,this.#o=Nn(A),this.#i=ho(r),this.#a=F,this.#n=c,this.#s=I,this.#d=d,this.#c=B,this.#C=f??null,this.#g=Q,this.#I=y,this.#p=m,this.#R=!!T,this.#h=_,this.#u=R,this.#E=dPe({allowedSenderCount:F.length})}get status(){return structuredClone(this.#E)}setGroupResponseMode(t){this.#i=ho(t),this.#f?.setGroupResponseMode(this.#i)}async start(){for(;;){for(;this.#y;)await this.#y;if(this.#S)return this.#S;let o=this.#Q;if(o){let i=IPe(o,this.#E.feishuLongConnectionState);if(gPe.has(i))return this.status;await this.stop({preserveError:i==="failed"});continue}if(this.#B||this.#f||this.#m){await this.stop({preserveError:this.#E.feishuLongConnectionState==="failed"});continue}break}let t;return t=this.#_().finally(()=>{this.#S===t&&(this.#S=null)}),this.#S=t,t}async#_(){let t=new AbortController;this.#m=t;let{signal:o}=t,i=()=>o.reason??new DOMException("Feishu runtime stopped","AbortError"),e=()=>!o.aborted&&this.#m===t,a=()=>{if(!e())throw i()};this.#E.startedAt=new Date().toISOString(),this.#E.feishuLongConnectionState="connecting",this.#E.lastError=null;try{await this.#n.ensureRunning({signal:o}),a(),this.#E.harnessReachable=!0;let A=this.#l==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,r={appId:this.#t,appSecret:this.#r,domain:A},s=lPe(this.#e.defaultHttpInstance,this.#p);s&&(r.httpInstance=s);let g=new this.#e.Client(r);this.#B=g;let c=new OS({client:g,initialText:w("\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026")}),I=new wS({client:g,channel:c,harness:this.#n,state:this.#s,contextEnhancement:this.#d,accessPolicy:this.#c,status:this.#E,allowedSenderOpenIds:new Set(this.#a),botId:this.#A,appId:this.#t,botOpenId:this.#o,groupResponseMode:this.#i,repair:this.#C,replyTimeoutMs:this.#g,signal:o,logger:this.#u});this.#f=I;let d=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":T=>{e()&&I.accept(T)},"im.message.reaction.created_v1":()=>{},"im.message.reaction.deleted_v1":()=>{},"card.action.trigger":T=>{e()&&(this.#E.cardActionsReceived+=1,this.#E.lastCardActionAt=new Date().toISOString(),this.#O(T)||I.onCardAction(T))}}),B,f,Q=new Promise((T,_)=>{let R=!1,x=()=>{f(i())},F=(q,z)=>{R||(R=!0,clearTimeout(L),o.removeEventListener("abort",x),q(z))},L=setTimeout(()=>{F(_,new Error(`Feishu WebSocket handshake timed out after ${this.#I}ms`))},this.#I);B=()=>{F(T)},f=q=>{F(_,q)},o.addEventListener("abort",x,{once:!0}),o.aborted&&x()});Q.catch(()=>{});let y=new this.#e.WSClient({...r,...this.#h?{agent:this.#h}:{},loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:this.#I,onReady:()=>{e()&&(this.#E.feishuLongConnectionState="connected",this.#E.ready=!0,this.#E.lastError=null,B())},onError:T=>{e()&&(this.#E.feishuLongConnectionState="failed",this.#E.ready=!1,this.#E.lastError=T?.message??String(T),this.#u.error("[dsh-feishu] Feishu long connection failed:",this.#E.lastError),f(T))},onReconnecting:()=>{e()&&(this.#E.feishuLongConnectionState="reconnecting",this.#E.ready=!1)},onReconnected:()=>{e()&&(this.#E.feishuLongConnectionState="connected",this.#E.ready=!0,this.#E.lastError=null)}});this.#Q=y;let m=Promise.resolve().then(()=>y.start({eventDispatcher:d})).catch(T=>{throw f(T),T});return await Promise.all([m,Q]),a(),this.#R&&s&&this.#T(s,e,o),this.status}catch(A){throw o.aborted||(this.#E.ready=!1,this.#E.feishuLongConnectionState="failed",this.#E.lastError=A?.message??String(A),await this.#P({preserveError:!0,abortController:t})),A}}async beginCardActionProbe({expectedOperatorOpenId:t,timeoutMs:o=9e4}={}){if(!this.#E.ready||!this.#B)throw Wp("card_action_probe_unavailable","\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");let i=Nn(t);if(!i||i==="*")throw new TypeError("A precise Feishu operator open_id is required");if(!Number.isFinite(o)||o<=0||o>10*6e4)throw new TypeError("Card-action probe timeout must be between 1 and 600000ms");let e=aPe().replaceAll("-",""),a;try{a=await this.#B.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:i,msg_type:"interactive",content:t5(e)}})}catch{throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5")}if(a?.code&&a.code!==0)throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5");let A=Nn(a?.data?.message_id)??Nn(a?.message_id);if(!A)throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u98DE\u4E66\u672A\u8FD4\u56DE\u6D4B\u8BD5\u5361\u7247\u7684\u6D88\u606F ID");return new Promise((r,s)=>{let g=setTimeout(()=>{let c=this.#D.get(A);!c||c.nonce!==e||(this.#D.delete(A),this.#w(i,w(nPe),"timeout"),s(Wp("card_action_probe_timeout","\u5728\u89C4\u5B9A\u65F6\u95F4\u5185\u672A\u6536\u5230\u98DE\u4E66\u5361\u7247\u6309\u94AE\u56DE\u8C03")))},o);g.unref?.(),this.#D.set(A,{messageId:A,nonce:e,expectedOperatorOpenId:i,timeout:g,resolve:r,reject:s})})}#O(t){let o=Nn(t?.context?.open_message_id);if(!o)return!1;let i=this.#D.get(o);if(!i)return!1;let e=t?.action?.value,a=cPe(t);return e?.action!=="repair_verify"||e?.nonce!==i.nonce||a!==i.expectedOperatorOpenId?!1:(clearTimeout(i.timeout),this.#D.delete(o),this.#E.cardActionProbesVerified+=1,this.#w(a,w(oPe),"success").finally(()=>{i.resolve({verified:!0,messageId:o,operatorOpenId:a})}),!0)}#w(t,o,i){let e=this.#B;return e?Promise.resolve().then(async()=>{let a=await e.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:t,msg_type:"text",content:JSON.stringify({text:o})}});if(a?.code&&a.code!==0)throw new Error("Feishu callback repair notice failed");return!0}).catch(()=>(this.#u.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),!1)):(this.#u.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),Promise.resolve(!1))}async sendConnectionTest(t){if(!this.#E.ready||!this.#B){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof t!="string"||!t.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let r=await this.#B.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(r?.code&&r.code!==0)throw new Error(`Feishu connection test failed: ${r.msg||r.code}`)},i=this.#a.find(e=>e!=="*");return i?(await o("open_id",i,t),{sent:!0}):cc({state:this.#s,text:t,channelLabel:w("\u98DE\u4E66\u673A\u5668\u4EBA"),send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw fr(w("\u98DE\u4E66\u673A\u5668\u4EBA"));await o("chat_id",A,a)}})}async sendProactiveText(t,o,{signal:i}={}){if(!this.#E.ready||!this.#B){let r=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw r.code="bot-not-connected",r}let e=t?.kind==="user"?"open_id":t?.kind==="group"?"chat_id":null,a=t?.kind==="user"?Nn(t?.route?.openId):t?.kind==="group"?Nn(t?.route?.chatId):null;if(!e||!a){let r=new TypeError("Invalid Feishu proactive delivery target");throw r.code="invalid-target",r}i?.throwIfAborted();let A=await this.#B.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:o})}});if(A?.code&&A.code!==0){let r=new Error(`Feishu proactive delivery failed: ${A.msg||A.code}`);throw r.code="target-rejected",r}return{sent:!0}}async#T(t,o,i){this.#E.slashCommandRegistration="registering",this.#E.slashCommandsError=null;try{let e=await D5({appId:this.#t,appSecret:this.#r,domain:this.#l,httpInstance:t,signal:i,manifest:UP});if(!o())return;this.#E.slashCommandRegistration="done",this.#E.slashCommandsRegistered=e.created.length,this.#E.slashCommandsExisting=e.existing.length,this.#E.slashCommandsFailed=e.failed.length,this.#E.slashCommandsError=e.failed.length>0?e.failed.map(a=>`/${a.command}: ${a.error?.message??String(a.error)}`).join("; "):null,e.created.length>0&&this.#u.info?.(`[dsh-feishu] registered ${e.created.length} slash command(s)`),e.failed.length>0&&this.#u.warn?.(`[dsh-feishu] ${e.failed.length} slash command(s) failed to register: ${this.#E.slashCommandsError}`)}catch(e){if(!o())return;this.#E.slashCommandRegistration="failed",this.#E.slashCommandsError=e?.message??String(e),this.#u.warn?.(`[dsh-feishu] slash command registration skipped: ${this.#E.slashCommandsError}`)}}stop(t={}){if(this.#y)return this.#y;let o;return o=this.#M(t).finally(()=>{this.#y===o&&(this.#y=null)}),this.#y=o,o}async#M({preserveError:t=!1}={}){let o=this.#m;this.#m===o&&(this.#m=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));let i=this.#S;return i&&await i.catch(()=>{}),this.#P({preserveError:t,abortController:o})}async#P({preserveError:t=!1,abortController:o}={}){let i=t?this.#E.lastError:null;this.#m===o&&(this.#m=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));for(let A of this.#D.values())clearTimeout(A.timeout),this.#w(A.expectedOperatorOpenId,w(sPe),"abort"),A.reject(Wp("abort","\u98DE\u4E66\u8FD0\u884C\u65F6\u5DF2\u505C\u6B62"));this.#D.clear(),this.#E.ready=!1;let e=this.#Q;this.#Q=null,e?.close({force:!0});let a=this.#f;return this.#f=null,a&&await a.waitForIdle(),this.#B=null,this.#E.feishuLongConnectionState=t?"failed":"idle",this.#E.slashCommandRegistration="idle",this.#E.lastError=i,this.status}};var _S=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as pPe}from"node:crypto";import{mkdir as hPe,readFile as EPe,rename as uPe,unlink as CPe,writeFile as BPe}from"node:fs/promises";import{dirname as fPe}from"node:path";var RS="DSH_FEISHU_APP_SECRET";function Ds(n){return typeof n=="string"&&n.trim()?n.trim():null}function O5(n){let t=Ds(n);return t&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:null}function b5(n){return`bot_${pPe("sha256").update(n).digest("hex").slice(0,24)}`}function QPe(n){let t=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(t.map(Ds).filter(Boolean))]}function TS(n,{legacy:t=!1}={}){if(!n||typeof n!="object")return null;let o=Ds(n.appId),i=QPe(n);if(!o||i.length===0)return null;let e=O5(n.id)??(t?b5(o):null),a=Ds(n.secretRef)??(t?RS:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:Ds(n.botName),botOpenId:Ds(n.botOpenId),activated:n.activated??null,groupResponseMode:ho(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:Ds(n.connectedAt),createdAt:Ds(n.createdAt)??Ds(n.connectedAt)})}function yPe(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>TS(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let t=TS(n,{legacy:!0});return t?{value:Object.freeze({version:2,bots:Object.freeze([t])}),migrated:!0}:null}var NS=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await EPe(this.#e,"utf8")),o=yPe(t);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#o(this.#A)}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let t=this.#A.bots[0];if(!t)return null;let o=structuredClone(t);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(t){let o=this.#A.bots.find(i=>i.id===t);return o?structuredClone(o):null}async save(t){let o={...t};o.id||(o.id=b5(Ds(o.appId)??"invalid")),o.secretRef||(o.secretRef=RS);let i=TS(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(t){let o=TS(t);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#l(i=>{if(i.find(r=>r.secretRef===o.secretRef&&r.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(r=>r.appId===o.appId&&r.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(r=>r.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(t){if(!O5(t))throw new TypeError("Invalid Feishu bot id");return this.#l(o=>{let i=o.findIndex(a=>a.id===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await CPe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o=Object.freeze({version:2,bots:Object.freeze([...t])}),i=this.#t.then(async()=>{await this.#o(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#l(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#o(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#o(t){await hPe(fPe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await BPe(o,`${JSON.stringify(t,null,2)} +${w("\u2935\uFE0F \u6700\u7EC8\u7ED3\u679C\u89C1\u4E0B\u65B9")}`),await this.#a(a)}catch(I){console.warn("[dsh-feishu] unable to finalize the superseded stream card:",I.message)}}},setContent:async I=>{let d=String(I??"")||"\u2026",B=await s();await this.#i(B,GP(d)),r=d}};await o.markdown(g);let c=Xve(r);for(let[I,d]of c.entries()){let B=I===0?await s():await this.#o(t,i.replyTo);I>0&&e.push(B),await this.#i(B,d),await this.#a(B)}return{messageId:e[0].messageId,providerMessageIds:e.map(I=>I.messageId)}}catch(r){for(let s of e)await this.#s(s.messageId);throw r}}async sendFile(t,o,{replyTo:i,signal:e}={}){return this.#l(t,o,{replyTo:i,signal:e,messageType:"file",presentation:"feishu-file"})}async sendImage(t,o,{replyTo:i,signal:e}={}){return this.#l(t,o,{replyTo:i,signal:e,messageType:"image",presentation:"feishu-image"})}async#l(t,o,{replyTo:i,signal:e,messageType:a,presentation:A}){if(e?.throwIfAborted(),typeof t!="string"||!t)throw new TypeError("chatId is required");if(!o||typeof o!="object"||typeof o.artifactId!="string"||!o.artifactId||typeof o.deliveryKey!="string"||!o.deliveryKey||typeof o.fileName!="string"||!o.fileName||!Buffer.isBuffer(o.bytes))throw new TypeError("A materialized result file is required");let r;try{r=await B5(Q=>{Q.throwIfAborted();let y=a==="image"?this.#e.im.v1.image.create({data:{image_type:"message",image:o.bytes}}):this.#e.im.v1.file.create({data:{file_type:"stream",file_name:o.fileName,file:o.bytes}});return yn(o,y),y},{signal:e,timeoutMs:this.#t,stage:"upload"})}catch(Q){throw e?.aborted?FP(e):GC("upload",Q)}e?.throwIfAborted();let s=a==="image"?r?.image_key??r?.data?.image_key:r?.file_key??r?.data?.file_key;if(typeof s!="string"||!s)throw GC("upload",void 0,r?.code);let g=Wve(o,t,a),c=JSON.stringify(a==="image"?{image_key:s}:{file_key:s}),I=i?{path:{message_id:i},data:{msg_type:a,content:c,uuid:g}}:{params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:a,content:c,uuid:g}},d=()=>{let Q=i?this.#e.im.v1.message.reply(I):this.#e.im.v1.message.create(I);return yn(o,Q),Q},B;try{B=await B5(async Q=>{Q.throwIfAborted();let y;try{y=await d()}catch(m){if(y5(m)!==230049)throw m;y={code:230049}}return Q.throwIfAborted(),Number(y?.code)===230049&&(y=await d(),Q.throwIfAborted()),y},{signal:e,timeoutMs:this.#r,stage:"message send"})}catch(Q){throw e?.aborted?FP(e):GC("message send",Q,void 0,{uncertain:!0})}if(Number.isFinite(Number(B?.code))&&Number(B.code)!==0)throw GC("message send",void 0,B.code,{uncertain:!0});let f=B?.data?.message_id;if(typeof f!="string"||!f)throw GC("message send",void 0,void 0,{uncertain:!0});return $t({deliveryId:o.deliveryKey,presentation:A,providerMessageIds:[f],artifacts:[{artifactId:o.artifactId,outcome:"sent"}]})}async#o(t,o){let i=GP(this.#A),a=yl("Feishu card.create",await this.#e.cardkit.v1.card.create({data:{type:"card_json",data:JSON.stringify($ve(i))}}))?.data?.card_id;if(!a)throw new Error("Feishu card.create returned no card_id");let A=await this.#n(t,a,o);return{cardId:a,messageId:A,content:i,sequence:0}}async#i(t,o){if(o===t.content)return;let i=await this.#e.cardkit.v1.cardElement.content({path:{card_id:t.cardId,element_id:f5},data:{content:o,sequence:++t.sequence,uuid:`content_${t.cardId}_${t.sequence}`}});yl("Feishu cardElement.content",i),t.content=o}async#a(t){let o=await this.#e.cardkit.v1.card.settings({path:{card_id:t.cardId},data:{settings:JSON.stringify({config:{streaming_mode:!1,summary:{content:Zve(t.content)||w("\u56DE\u7B54\u5B8C\u6210")}}}),sequence:++t.sequence,uuid:`settings_${t.cardId}_${t.sequence}`}});yl("Feishu card.settings",o)}async#n(t,o,i){let e=JSON.stringify({type:"card",data:{card_id:o}}),a=i?await this.#e.im.v1.message.reply({path:{message_id:i},data:{msg_type:"interactive",content:e}}):await this.#e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:t,msg_type:"interactive",content:e}});yl("Feishu message send",a);let A=a?.data?.message_id;if(!A)throw new Error("Feishu message send returned no message_id");return A}async#s(t){try{let o=await this.#e.im.v1.message.delete({path:{message_id:t}});yl("Feishu message delete",o)}catch(o){console.warn("[bridge] unable to recall a failed streaming card:",o.message)}}async addReaction(t,o){let e=yl("Feishu reaction.create",await this.#e.im.v1.messageReaction.create({path:{message_id:t},data:{reaction_type:{emoji_type:o}}}))?.data?.reaction_id;if(!e)throw new Error("Feishu reaction.create returned no reaction_id");return e}async removeReaction(t,o){yl("Feishu reaction.delete",await this.#e.im.v1.messageReaction.delete({path:{message_id:t,reaction_id:o}}))}};var S5="/open-apis/application/v7/app_slash_commands",ePe=new Set(["99991640","99991672"]),bS=Object.freeze(["application:app_slash_command:read","application:app_slash_command:write"]),w5="ai-agent_outlined",UP=Object.freeze([{command:"menu",icon:"skill_outlined",default:"\u6253\u5F00\u529F\u80FD\u83DC\u5355",en_us:"Open the feature menu"},{command:"new",icon:"ai-deepthink_outlined",default:"\u5F00\u542F\u5168\u65B0\u4F1A\u8BDD",en_us:"Start a fresh session"},{command:"help",icon:"promptword_outlined",default:"\u67E5\u770B\u5E2E\u52A9",en_us:"Show help"},{command:"status",icon:"ai-functions_outlined",default:"\u67E5\u770B\u673A\u5668\u4EBA\u72B6\u6001",en_us:"Show bot status"},{command:"compact",icon:"ai-block_outlined",default:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587",en_us:"Compact the current session"},{command:"sessionlist",icon:"chat-ai_outlined",default:"\u5217\u51FA\u4F1A\u8BDD",en_us:"List sessions"},{command:"workspacelist",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"workspaces",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"wsl",icon:"folder_outlined",default:"\u5217\u51FA\u5DE5\u4F5C\u533A",en_us:"List workspaces"},{command:"ws",icon:"folder_outlined",default:"\u5207\u6362\u5DE5\u4F5C\u533A",en_us:"Switch workspace"},{command:"watch",icon:"flag_outlined",default:"\u5173\u6CE8\u4E00\u4E2A\u4F1A\u8BDD",en_us:"Watch a session"},{command:"unwatch",icon:"clear_outlined",default:"\u53D6\u6D88\u5173\u6CE8\u4F1A\u8BDD",en_us:"Unwatch a session"},{command:"watchlist",icon:"flag_outlined",default:"\u67E5\u770B\u5173\u6CE8\u5217\u8868",en_us:"List watched sessions"},{command:"archived",icon:"folder_outlined",default:"\u8BBE\u7F6E\u5F52\u6863\u4F1A\u8BDD\u663E\u9690\uFF08on/off\uFF09",en_us:"Show or hide archived sessions (on/off)"}]);function HP(n,t){let o=n==="lark"?"https://open.larksuite.com":"https://open.feishu.cn";return new URL(t,o)}function m5(n,t){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} returned a non-JSON response`);if(n.code!==0){let o=new Error(`${t} failed: ${n.msg||`code ${n.code}`}`);throw o.code=String(n.code),o.msg=n.msg,o}return n}function KP(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}async function xP(n,t,o){try{return m5(await n.request(t),o)}catch(i){let e=i?.response?.data;if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"code"))return m5(e,o);throw i}}async function APe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}){if(!n||!t)throw new Error("Feishu slash registration requires app credentials");if(!i||typeof i.request!="function")throw new TypeError("Feishu slash registration requires an HTTP instance");let A=await xP(i,{method:"POST",url:HP(o,"/open-apis/auth/v3/tenant_access_token/internal").href,headers:{"content-type":"application/json; charset=utf-8"},data:{app_id:n,app_secret:t},signal:KP(a,e),timeout:e},"Feishu authentication");if(!A.tenant_access_token)throw new Error("Feishu authentication returned no tenant access token");return A.tenant_access_token}async function tPe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e}){let a=await xP(o,{method:"GET",url:HP(t,S5).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},signal:KP(e,i),timeout:i},"Feishu slash command list");return Array.isArray(a.data?.items)?a.data.items:[]}async function rPe({tenantAccessToken:n,domain:t,httpInstance:o,timeoutMs:i,signal:e,command:a,description:A,icon:r=w5}){let s={command:a};return A&&(A.default_value||A.i18n)?s.description=A:typeof A=="string"&&A.trim()&&(s.description={default_value:A.trim()}),r&&(s.description={...s.description??{},icon:{icon_key:r}}),(await xP(o,{method:"POST",url:HP(t,S5).href,headers:{authorization:`Bearer ${n}`,"content-type":"application/json; charset=utf-8"},data:s,signal:KP(e,i),timeout:i},`Feishu slash command create (/${a})`)).data?.command_id??null}async function D5({appId:n,appSecret:t,domain:o="feishu",httpInstance:i,timeoutMs:e=15e3,signal:a,manifest:A=UP}){let r=await APe({appId:n,appSecret:t,domain:o,httpInstance:i,timeoutMs:e,signal:a}),s=new Set((await tPe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a})).map(I=>I.command)),g=[],c=[];for(let I of A){let d=String(I.command??"").replace(/^\//,"");if(d&&!s.has(d))try{let B={default_value:I.default??I.en_us??d,i18n:{zh_cn:I.default??d,en_us:I.en_us??I.default??d}},f=await rPe({tenantAccessToken:r,domain:o,httpInstance:i,timeoutMs:e,signal:a,command:d,description:B,icon:I.icon??w5});g.push({command:d,command_id:f})}catch(B){if(B?.code==="40000000"&&/already exists/i.test(B?.msg??"")){s.add(d);continue}if(ePe.has(B?.code)||/(?:lacks permission|access denied)/i.test(B?.msg??"")){c.push({command:d,error:B});break}c.push({command:d,error:B?.message??String(B)})}}return{created:g,existing:[...s].filter(I=>I!=null),failed:c}}var iPe=15e3,oPe="\u2705 \u4FEE\u590D\u5B8C\u6210\uFF1A\u5DF2\u5B9E\u6D4B\u6536\u5230 card.action.trigger\uFF0C\u83DC\u5355\u6309\u94AE\u73B0\u5728\u53EF\u7528\u3002",nPe="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u8D85\u65F6\uFF1A\u672A\u6536\u5230\u6D4B\u8BD5\u5361\u6309\u94AE\u7684 card.action.trigger\uFF0C\u4E0D\u80FD\u786E\u8BA4\u6309\u94AE\u5DF2\u4FEE\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u7684\u5361\u7247\u56DE\u8C03\u914D\u7F6E\uFF0C\u786E\u8BA4\u540E\u518D\u53D1\u9001 /repair\u3002",YP="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A\u65E0\u6CD5\u53D1\u9001\u4E13\u7528\u6D4B\u8BD5\u5361\uFF0C\u4E0D\u80FD\u786E\u8BA4 card.action.trigger \u5DF2\u6062\u590D\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u68C0\u67E5\u673A\u5668\u4EBA\u6D88\u606F\u6743\u9650\u548C\u8FDE\u63A5\u72B6\u6001\u3002",sPe="\u26A0\uFE0F \u4FEE\u590D\u9A8C\u8BC1\u4E2D\u65AD\uFF1ARuntime \u5DF2\u505C\u6B62\uFF0C\u672A\u5B8C\u6210 card.action.trigger \u5B9E\u6D4B\uFF0C\u4E0D\u80FD\u786E\u8BA4\u4FEE\u590D\u6210\u529F\u3002\u8BF7\u4E0D\u8981\u91CD\u590D\u6388\u6743\uFF1B\u5148\u7B49\u5F85\u673A\u5668\u4EBA\u6062\u590D\u8FDE\u63A5\u3002",gPe=new Set(["connected","connecting","reconnecting"]);function Nn(n){return typeof n=="string"&&n.trim()?n.trim():null}function cPe(n){return Nn(n?.operator?.open_id)??Nn(n?.operator?.operator_id?.open_id)}function IPe(n,t){try{let o=n?.getConnectionStatus?.()?.state;return typeof o=="string"&&o?o:t}catch{return t}}function Wp(n,t){let o=new Error(t);return o.code=n,o}function lPe(n,t){if(!n||typeof n.request!="function")return;let o=i=>({...i??{},timeout:i?.timeout??t});return{request:i=>n.request(o(i)),get:(i,e)=>n.get(i,o(e)),delete:(i,e)=>n.delete(i,o(e)),head:(i,e)=>n.head(i,o(e)),options:(i,e)=>n.options(i,o(e)),post:(i,e,a)=>n.post(i,e,o(a)),put:(i,e,a)=>n.put(i,e,o(a)),patch:(i,e,a)=>n.patch(i,e,o(a))}}function dPe({allowedSenderCount:n=1}={}){return{startedAt:null,ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1,messagesReceived:0,messagesReplied:0,messagesRejected:0,reactionsAdded:0,reactionsRemoved:0,reactionErrors:0,streamResponses:0,streamUpdates:0,streamFallbacks:0,streamErrors:0,cardActionsReceived:0,cardActionProbesVerified:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastCardActionAt:null,lastError:null,agentPreset:"standard",authorizationMode:"sender-open-id-allowlist",allowedSenderCount:n,slashCommandRegistration:"idle",slashCommandsRegistered:0,slashCommandsExisting:0,slashCommandsFailed:0,slashCommandsError:null}}var MS=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g;#I;#p;#h;#u;#C;#B=null;#f=null;#Q=null;#S=null;#y=null;#m=null;#D=new Map;#E;#R=!0;constructor({lark:t,botId:o,appId:i,appSecret:e,domain:a="feishu",botOpenId:A,groupResponseMode:r,ownerOpenId:s,ownerOpenIds:g,harness:c,state:I,contextEnhancement:d,accessPolicy:B,repair:f,replyTimeoutMs:Q=6e5,connectTimeoutMs:y=15e3,requestTimeoutMs:m=iPe,slashCommands:T=!0,wsAgent:_,logger:R=console}){if(!t)throw new Error("FeishuRuntime requires the Feishu SDK");if(!i||!e)throw new Error("FeishuRuntime requires app credentials");let x=Array.isArray(g)?g:[s],F=[...new Set(x.filter(L=>typeof L=="string"&&L))];if(F.length===0)throw new Error("FeishuRuntime requires at least one owner open_id");if(!c)throw new Error("FeishuRuntime requires a Harness client");if(!I)throw new Error("FeishuRuntime requires a state store");if(f!=null&&!Nn(o))throw new TypeError("FeishuRuntime repair capability requires a botId");if(!Number.isFinite(m)||m<=0)throw new TypeError("FeishuRuntime requestTimeoutMs must be a positive number");this.#e=t,this.#A=Nn(o),this.#t=i,this.#r=e,this.#l=a,this.#o=Nn(A),this.#i=ho(r),this.#a=F,this.#n=c,this.#s=I,this.#d=d,this.#c=B,this.#C=f??null,this.#g=Q,this.#I=y,this.#p=m,this.#R=!!T,this.#h=_,this.#u=R,this.#E=dPe({allowedSenderCount:F.length})}get status(){return structuredClone(this.#E)}setGroupResponseMode(t){this.#i=ho(t),this.#f?.setGroupResponseMode(this.#i)}async start(){for(;;){for(;this.#y;)await this.#y;if(this.#S)return this.#S;let o=this.#Q;if(o){let i=IPe(o,this.#E.feishuLongConnectionState);if(gPe.has(i))return this.status;await this.stop({preserveError:i==="failed"});continue}if(this.#B||this.#f||this.#m){await this.stop({preserveError:this.#E.feishuLongConnectionState==="failed"});continue}break}let t;return t=this.#_().finally(()=>{this.#S===t&&(this.#S=null)}),this.#S=t,t}async#_(){let t=new AbortController;this.#m=t;let{signal:o}=t,i=()=>o.reason??new DOMException("Feishu runtime stopped","AbortError"),e=()=>!o.aborted&&this.#m===t,a=()=>{if(!e())throw i()};this.#E.startedAt=new Date().toISOString(),this.#E.feishuLongConnectionState="connecting",this.#E.lastError=null;try{await this.#n.ensureRunning({signal:o}),a(),this.#E.harnessReachable=!0;let A=this.#l==="lark"?this.#e.Domain.Lark:this.#e.Domain.Feishu,r={appId:this.#t,appSecret:this.#r,domain:A},s=lPe(this.#e.defaultHttpInstance,this.#p);s&&(r.httpInstance=s);let g=new this.#e.Client(r);this.#B=g;let c=new OS({client:g,initialText:w("\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026")}),I=new wS({client:g,channel:c,harness:this.#n,state:this.#s,contextEnhancement:this.#d,accessPolicy:this.#c,status:this.#E,allowedSenderOpenIds:new Set(this.#a),botId:this.#A,appId:this.#t,botOpenId:this.#o,groupResponseMode:this.#i,repair:this.#C,replyTimeoutMs:this.#g,signal:o,logger:this.#u});this.#f=I;let d=new this.#e.EventDispatcher({}).register({"im.message.receive_v1":T=>{e()&&I.accept(T)},"im.message.reaction.created_v1":()=>{},"im.message.reaction.deleted_v1":()=>{},"card.action.trigger":T=>{e()&&(this.#E.cardActionsReceived+=1,this.#E.lastCardActionAt=new Date().toISOString(),this.#O(T)||I.onCardAction(T))}}),B,f,Q=new Promise((T,_)=>{let R=!1,x=()=>{f(i())},F=(q,z)=>{R||(R=!0,clearTimeout(L),o.removeEventListener("abort",x),q(z))},L=setTimeout(()=>{F(_,new Error(`Feishu WebSocket handshake timed out after ${this.#I}ms`))},this.#I);B=()=>{F(T)},f=q=>{F(_,q)},o.addEventListener("abort",x,{once:!0}),o.aborted&&x()});Q.catch(()=>{});let y=new this.#e.WSClient({...r,...this.#h?{agent:this.#h}:{},loggerLevel:this.#e.LoggerLevel.info,handshakeTimeoutMs:this.#I,onReady:()=>{e()&&(this.#E.feishuLongConnectionState="connected",this.#E.ready=!0,this.#E.lastError=null,B())},onError:T=>{e()&&(this.#E.feishuLongConnectionState="failed",this.#E.ready=!1,this.#E.lastError=T?.message??String(T),this.#u.error("[dsh-feishu] Feishu long connection failed:",this.#E.lastError),f(T))},onReconnecting:()=>{e()&&(this.#E.feishuLongConnectionState="reconnecting",this.#E.ready=!1)},onReconnected:()=>{e()&&(this.#E.feishuLongConnectionState="connected",this.#E.ready=!0,this.#E.lastError=null)}});this.#Q=y;let m=Promise.resolve().then(()=>y.start({eventDispatcher:d})).catch(T=>{throw f(T),T});return await Promise.all([m,Q]),a(),this.#R&&s&&this.#T(s,e,o),this.status}catch(A){throw o.aborted||(this.#E.ready=!1,this.#E.feishuLongConnectionState="failed",this.#E.lastError=A?.message??String(A),await this.#P({preserveError:!0,abortController:t})),A}}async beginCardActionProbe({expectedOperatorOpenId:t,timeoutMs:o=9e4}={}){if(!this.#E.ready||!this.#B)throw Wp("card_action_probe_unavailable","\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");let i=Nn(t);if(!i||i==="*")throw new TypeError("A precise Feishu operator open_id is required");if(!Number.isFinite(o)||o<=0||o>10*6e4)throw new TypeError("Card-action probe timeout must be between 1 and 600000ms");let e=aPe().replaceAll("-",""),a;try{a=await this.#B.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:i,msg_type:"interactive",content:t5(e)}})}catch{throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5")}if(a?.code&&a.code!==0)throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u65E0\u6CD5\u53D1\u9001\u98DE\u4E66\u5361\u7247\u56DE\u8C03\u6D4B\u8BD5");let A=Nn(a?.data?.message_id)??Nn(a?.message_id);if(!A)throw this.#w(i,w(YP),"failure"),Wp("card_action_probe_send_failed","\u98DE\u4E66\u672A\u8FD4\u56DE\u6D4B\u8BD5\u5361\u7247\u7684\u6D88\u606F ID");return new Promise((r,s)=>{let g=setTimeout(()=>{let c=this.#D.get(A);!c||c.nonce!==e||(this.#D.delete(A),this.#w(i,w(nPe),"timeout"),s(Wp("card_action_probe_timeout","\u5728\u89C4\u5B9A\u65F6\u95F4\u5185\u672A\u6536\u5230\u98DE\u4E66\u5361\u7247\u6309\u94AE\u56DE\u8C03")))},o);g.unref?.(),this.#D.set(A,{messageId:A,nonce:e,expectedOperatorOpenId:i,timeout:g,resolve:r,reject:s})})}#O(t){let o=Nn(t?.context?.open_message_id);if(!o)return!1;let i=this.#D.get(o);if(!i)return!1;let e=t?.action?.value,a=cPe(t);return e?.action!=="repair_verify"||e?.nonce!==i.nonce||a!==i.expectedOperatorOpenId?!1:(clearTimeout(i.timeout),this.#D.delete(o),this.#E.cardActionProbesVerified+=1,this.#w(a,w(oPe),"success").finally(()=>{i.resolve({verified:!0,messageId:o,operatorOpenId:a})}),!0)}#w(t,o,i){let e=this.#B;return e?Promise.resolve().then(async()=>{let a=await e.im.v1.message.create({params:{receive_id_type:"open_id"},data:{receive_id:t,msg_type:"text",content:JSON.stringify({text:o})}});if(a?.code&&a.code!==0)throw new Error("Feishu callback repair notice failed");return!0}).catch(()=>(this.#u.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),!1)):(this.#u.warn?.(`[dsh-feishu] unable to send the callback repair ${i} notice`),Promise.resolve(!1))}async sendConnectionTest(t){if(!this.#E.ready||!this.#B){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}if(typeof t!="string"||!t.trim())throw new TypeError("Feishu connection test text is required");let o=async(e,a,A)=>{let r=await this.#B.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:A})}});if(r?.code&&r.code!==0)throw new Error(`Feishu connection test failed: ${r.msg||r.code}`)},i=this.#a.find(e=>e!=="*");return i?(await o("open_id",i,t),{sent:!0}):cc({state:this.#s,text:t,channelLabel:w("\u98DE\u4E66\u673A\u5668\u4EBA"),send:async(e,a)=>{let A=typeof e?.chatId=="string"?e.chatId.trim():"";if(!A)throw fr(w("\u98DE\u4E66\u673A\u5668\u4EBA"));await o("chat_id",A,a)}})}async sendProactiveText(t,o,{signal:i}={}){if(!this.#E.ready||!this.#B){let r=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw r.code="bot-not-connected",r}let e=t?.kind==="user"?"open_id":t?.kind==="group"?"chat_id":null,a=t?.kind==="user"?Nn(t?.route?.openId):t?.kind==="group"?Nn(t?.route?.chatId):null;if(!e||!a){let r=new TypeError("Invalid Feishu proactive delivery target");throw r.code="invalid-target",r}i?.throwIfAborted();let A=await this.#B.im.v1.message.create({params:{receive_id_type:e},data:{receive_id:a,msg_type:"text",content:JSON.stringify({text:o})}});if(A?.code&&A.code!==0){let r=new Error(`Feishu proactive delivery failed: ${A.msg||A.code}`);throw r.code="target-rejected",r}return{sent:!0}}async#T(t,o,i){this.#E.slashCommandRegistration="registering",this.#E.slashCommandsError=null;try{let e=await D5({appId:this.#t,appSecret:this.#r,domain:this.#l,httpInstance:t,signal:i,manifest:UP});if(!o())return;this.#E.slashCommandRegistration="done",this.#E.slashCommandsRegistered=e.created.length,this.#E.slashCommandsExisting=e.existing.length,this.#E.slashCommandsFailed=e.failed.length,this.#E.slashCommandsError=e.failed.length>0?e.failed.map(a=>`/${a.command}: ${a.error?.message??String(a.error)}`).join("; "):null,e.created.length>0&&this.#u.info?.(`[dsh-feishu] registered ${e.created.length} slash command(s)`),e.failed.length>0&&this.#u.warn?.(`[dsh-feishu] ${e.failed.length} slash command(s) failed to register: ${this.#E.slashCommandsError}`)}catch(e){if(!o())return;this.#E.slashCommandRegistration="failed",this.#E.slashCommandsError=e?.message??String(e),this.#u.warn?.(`[dsh-feishu] slash command registration skipped: ${this.#E.slashCommandsError}`)}}stop(t={}){if(this.#y)return this.#y;let o;return o=this.#M(t).finally(()=>{this.#y===o&&(this.#y=null)}),this.#y=o,o}async#M({preserveError:t=!1}={}){let o=this.#m;this.#m===o&&(this.#m=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));let i=this.#S;return i&&await i.catch(()=>{}),this.#P({preserveError:t,abortController:o})}async#P({preserveError:t=!1,abortController:o}={}){let i=t?this.#E.lastError:null;this.#m===o&&(this.#m=null),o?.abort(new DOMException("Feishu runtime stopped","AbortError"));for(let A of this.#D.values())clearTimeout(A.timeout),this.#w(A.expectedOperatorOpenId,w(sPe),"abort"),A.reject(Wp("abort","\u98DE\u4E66\u8FD0\u884C\u65F6\u5DF2\u505C\u6B62"));this.#D.clear(),this.#E.ready=!1;let e=this.#Q;this.#Q=null,e?.close({force:!0});let a=this.#f;return this.#f=null,a&&await a.waitForIdle(),this.#B=null,this.#E.feishuLongConnectionState=t?"failed":"idle",this.#E.slashCommandRegistration="idle",this.#E.lastError=i,this.status}};var _S=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"feishu",logPrefix:"dsh-feishu"})}};import{createHash as pPe}from"node:crypto";import{mkdir as hPe,readFile as EPe,rename as uPe,unlink as CPe,writeFile as BPe}from"node:fs/promises";import{dirname as fPe}from"node:path";var RS="DSH_FEISHU_APP_SECRET";function Ds(n){return typeof n=="string"&&n.trim()?n.trim():null}function O5(n){let t=Ds(n);return t&&/^[A-Za-z0-9_-]{1,128}$/.test(t)?t:null}function b5(n){return`bot_${pPe("sha256").update(n).digest("hex").slice(0,24)}`}function QPe(n){let t=Array.isArray(n.ownerOpenIds)?n.ownerOpenIds:[n.ownerOpenId];return[...new Set(t.map(Ds).filter(Boolean))]}function TS(n,{legacy:t=!1}={}){if(!n||typeof n!="object")return null;let o=Ds(n.appId),i=QPe(n);if(!o||i.length===0)return null;let e=O5(n.id)??(t?b5(o):null),a=Ds(n.secretRef)??(t?RS:null);if(!e||!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))return null;let A=n.domain==="lark"?"lark":"feishu";return Object.freeze({id:e,appId:o,secretRef:a,ownerOpenIds:Object.freeze(i),domain:A,botName:Ds(n.botName),botOpenId:Ds(n.botOpenId),activated:n.activated??null,groupResponseMode:ho(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:Ds(n.connectedAt),createdAt:Ds(n.createdAt)??Ds(n.connectedAt)})}function yPe(n){if(!n||typeof n!="object")return null;if(n.version===2&&Array.isArray(n.bots)){let o=n.bots.map(A=>TS(A));if(o.some(A=>A===null))throw new Error("dsh-feishu config contains an invalid bot entry");let i=new Set,e=new Set,a=new Set;for(let A of o){if(i.has(A.id)||e.has(A.secretRef)||a.has(A.appId))throw new Error("dsh-feishu config contains duplicate bot identities");i.add(A.id),e.add(A.secretRef),a.add(A.appId)}return{value:Object.freeze({version:2,bots:Object.freeze(o)}),migrated:!1}}let t=TS(n,{legacy:!0});return t?{value:Object.freeze({version:2,bots:Object.freeze([t])}),migrated:!0}:null}var NS=class{#e;#A=Object.freeze({version:2,bots:Object.freeze([])});#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=JSON.parse(await EPe(this.#e,"utf8")),o=yPe(t);if(!o)throw new Error("dsh-feishu config is incomplete or invalid");this.#A=o.value,o.migrated&&await this.#o(this.#A)}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=Object.freeze({version:2,bots:Object.freeze([])})}return this}get(){let t=this.#A.bots[0];if(!t)return null;let o=structuredClone(t);return o.ownerOpenId=o.ownerOpenIds[0],o}list(){return structuredClone(this.#A.bots)}getBot(t){let o=this.#A.bots.find(i=>i.id===t);return o?structuredClone(o):null}async save(t){let o={...t};o.id||(o.id=b5(Ds(o.appId)??"invalid")),o.secretRef||(o.secretRef=RS);let i=TS(o);if(!i)throw new Error("Refusing to persist incomplete dsh-feishu configuration");return await this.#r([i]),this.get()}async saveBot(t){let o=TS(t);if(!o)throw new Error("Refusing to persist incomplete dsh-feishu bot configuration");return this.#l(i=>{if(i.find(r=>r.secretRef===o.secretRef&&r.id!==o.id))throw new Error("Refusing to share a credential reference between Feishu bots");if(i.find(r=>r.appId===o.appId&&r.id!==o.id))throw new Error("Refusing to persist the same Feishu app twice");let A=i.findIndex(r=>r.id===o.id);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async removeBot(t){if(!O5(t))throw new TypeError("Invalid Feishu bot id");return this.#l(o=>{let i=o.findIndex(a=>a.id===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await CPe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=Object.freeze({version:2,bots:Object.freeze([])})});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o=Object.freeze({version:2,bots:Object.freeze([...t])}),i=this.#t.then(async()=>{await this.#o(o),this.#A=o});this.#t=i.then(()=>{},()=>{}),await i}async#l(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:2,bots:Object.freeze(e)});await this.#o(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#o(t){await hPe(fPe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await BPe(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await uPe(o,this.#e)}};import{randomUUID as k5}from"node:crypto";var jP=new Set(["starting","qr_ready","polling","slow_down","domain_switched","saving"]),mPe=new Set(["polling","slow_down","domain_switched"]),ji=Object.freeze({IDLE:"idle",STARTING:"starting",QR_READY:"qr_ready",POLLING:"polling",SLOW_DOWN:"slow_down",DOMAIN_SWITCHED:"domain_switched",SAVING:"saving",SUCCEEDED:"succeeded",EXPIRED:"expired",CANCELLED:"cancelled",ERROR:"error"});function M5(n){return["access_denied","expired_token","abort"].includes(n?.code)?n.code:"registration_failed"}function JP(n){let t=M5(n);return{code:t,message:{access_denied:"Registration was denied.",abort:"Registration was cancelled.",expired_token:"The registration QR code expired."}[t]??"Unable to register the Feishu app."}}function SPe(n){let t=Number(n);if(!Number.isFinite(t)||t<=0)throw new TypeError("registerApp onQRCodeReady returned an invalid expireIn");return t}function wPe(n){if(n!==void 0){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError("registerApp returned invalid user_info");return{...n}}}var kg=class{#e;#A;#t;#r;#l;#o=0;#i=null;#a;constructor({registerApp:t,onCredentials:o,now:i=Date.now,setTimeout:e=globalThis.setTimeout,clearTimeout:a=globalThis.clearTimeout}={}){if(typeof t!="function")throw new TypeError("RegistrationManager requires a registerApp function");if(typeof o!="function")throw new TypeError("RegistrationManager requires an onCredentials function");if(typeof i!="function"||typeof e!="function"||typeof a!="function")throw new TypeError("RegistrationManager clock dependencies must be functions");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#a=this.#s(null,ji.IDLE)}start(t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("Registration options must be an object");this.#f();let o={id:++this.#o,controller:new AbortController,qrCodeUrl:null,expiresAt:null,pollIntervalSeconds:null,expiryTimer:null};this.#i=o,this.#a=this.#s(o,ji.STARTING);let i={...t,signal:o.controller.signal,onQRCodeReady:a=>this.#c(o,a),onStatusChange:a=>this.#g(o,a)};return Promise.resolve().then(()=>this.#e(i)).then(a=>this.#I(o,a),a=>this.#p(o,a)),this.status()}status(){this.#h();let t={...this.#a};t.error&&(t.error={...t.error});let o=this.#i;return o&&o.expiresAt!==null&&jP.has(t.state)&&(t.remainingSeconds=Math.max(0,Math.ceil((o.expiresAt-this.#t())/1e3))),t}cancel(){let t=this.#i;return t?(this.#C(t,ji.CANCELLED,{error:{code:"abort",message:"Registration was cancelled."}}),t.controller.abort(),this.status()):this.status()}#n(t){return this.#i===t}#s(t,o,i={}){let e={state:o,attempt:t?.id??this.#o,updatedAt:this.#t(),...i};return t?.qrCodeUrl&&jP.has(o)&&(e.qrCodeUrl=t.qrCodeUrl,e.expiresAt=t.expiresAt),t?.pollIntervalSeconds!==null&&jP.has(o)&&(e.pollIntervalSeconds=t.pollIntervalSeconds),e}#d(t,o,i={}){this.#n(t)&&(this.#a=this.#s(t,o,i))}#c(t,o){if(!this.#n(t))return;if(typeof o?.url!="string"||!o.url)throw new TypeError("registerApp onQRCodeReady returned an invalid URL");let i=SPe(o.expireIn);t.qrCodeUrl=o.url,t.expiresAt=this.#t()+i*1e3,this.#B(t),t.expiryTimer=this.#r(()=>this.#u(t),i*1e3),t.expiryTimer?.unref?.(),this.#d(t,ji.QR_READY)}#g(t,o){!this.#n(t)||!mPe.has(o?.status)||(o.status===ji.SLOW_DOWN&&Number.isFinite(Number(o.interval))&&(t.pollIntervalSeconds=Number(o.interval)),this.#d(t,o.status))}async#I(t,o){if(!this.#n(t))return;let i=o?.client_id,e=o?.client_secret;if(typeof i!="string"||!i||typeof e!="string"||!e){this.#C(t,ji.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}let a;try{a=wPe(o.user_info)}catch{this.#C(t,ji.ERROR,{error:{code:"invalid_credentials",message:"Feishu registration returned invalid credentials."}});return}this.#B(t),t.qrCodeUrl=null,t.expiresAt=null,t.pollIntervalSeconds=null,this.#d(t,ji.SAVING);try{await this.#A({client_id:i,client_secret:e,user_info:a})}catch{this.#n(t)&&this.#C(t,ji.ERROR,{error:{code:"credentials_callback_failed",message:"Unable to store the Feishu credentials."}});return}this.#n(t)&&this.#C(t,ji.SUCCEEDED)}#p(t,o){if(!this.#n(t))return;let i=M5(o);if(i==="expired_token"){this.#C(t,ji.EXPIRED,{error:JP(o)});return}if(i==="abort"){this.#C(t,ji.CANCELLED,{error:JP(o)});return}this.#C(t,ji.ERROR,{error:JP(o)})}#h(){let t=this.#i;t&&t.expiresAt!==null&&this.#t()>=t.expiresAt&&this.#u(t)}#u(t){this.#n(t)&&(this.#C(t,ji.EXPIRED,{error:{code:"expired_token",message:"The registration QR code expired."}}),t.controller.abort())}#C(t,o,i={}){this.#n(t)&&(this.#B(t),this.#a=this.#s(t,o,i),this.#i=null)}#B(t){t.expiryTimer!==null&&(this.#l(t.expiryTimer),t.expiryTimer=null)}#f(){let t=this.#i;t&&(this.#B(t),this.#i=null,t.controller.abort())}};var DPe="card.action.trigger",OPe="im:message:readonly",bPe="im:resource",LC="callback_repair";function MPe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function _Pe(n){return n==="lark"?"open.larksuite.com":"open.feishu.cn"}function qP(n,t,o="feishu",i="Feishu app update"){let e;try{e=new URL(n)}catch{throw new Error(`${i} returned an invalid verification URL`)}let a=o==="feishu"||o==="lark",A=e.searchParams.getAll("clientID"),r=e.searchParams.getAll("tp"),s=e.searchParams.getAll("addons"),g=String(t).includes("{{")||String(t).includes("}}")||[...e.searchParams.values()].some(c=>c.includes("{{")||c.includes("}}"));if(!a||e.protocol!=="https:"||e.hostname!==_Pe(o)||e.port!==""||e.username!==""||e.password!==""||r.length!==1||r[0]!=="sdk"||A.length!==1||A[0]!==t||e.searchParams.has("createOnly")||s.length!==1||!s[0]?.trim()||g)throw new Error(`${i} returned an unsafe verification URL`);return e.toString()}function TPe(n,t,o="feishu"){return qP(n,t,o,"Feishu callback repair")}var kS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new kg({registerApp:a=>t({...a,onQRCodeReady:A=>{TPe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-card-action-repair",domain:MPe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[OPe,bPe,...bS]},callbacks:{items:[DPe]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var NPe="im:message.group_msg",PS="group_message_permission";function RPe(n){return n==="lark"?"accounts.larksuite.com":"accounts.feishu.cn"}function kPe(n,t,o="feishu"){return qP(n,t,o,"Feishu group message permission update")}var vS=class{#e;#A;#t;constructor({registerApp:t,onCredentials:o,appId:i,domain:e="feishu"}={}){if(typeof t!="function")throw new TypeError("registerApp is required");if(typeof o!="function")throw new TypeError("onCredentials is required");if(typeof i!="string"||!i.trim())throw new TypeError("appId is required");if(e!=="feishu"&&e!=="lark")throw new TypeError("domain is invalid");this.#A=i.trim(),this.#t=e,this.#e=new kg({registerApp:a=>t({...a,onQRCodeReady:A=>{kPe(A?.url,this.#A,this.#t),a.onQRCodeReady(A)}}),onCredentials:o})}start(){return this.#e.start({source:"deepseek-harness-group-message-permission",domain:RPe(this.#t),appId:this.#A,addons:{preset:!1,scopes:{tenant:[NPe]}}})}status(){return this.#e.status()}cancel(){return this.#e.cancel()}};var _5=Object.freeze(["im:message.p2p_msg:readonly","im:message.group_at_msg:readonly","im:message:readonly","im:message:send_as_bot","im:message.reactions:write_only","im:message:recall","im:resource","cardkit:card:write",...bS]);var zP=new Set(["starting","qr_ready","polling","slow_down","domain_switched"]),GS=new Set([...zP,"saving"]),T5=new Set([LC,PS]),N5="*",vPe=12e4,PPe=6e5;function v5(){return{ready:!1,feishuLongConnectionState:"idle",harnessReachable:!1}}function UC(n){return n?n.status:v5()}function HC(n){return n.ready===!0&&n.feishuLongConnectionState==="connected"&&n.harnessReachable===!0}function P5(n){return n.length>12?`${n.slice(0,8)}\u2022\u2022\u2022\u2022${n.slice(-4)}`:"cli_\u2022\u2022\u2022\u2022"}function GPe(n){return{name:n.botName,appIdMasked:P5(n.appId),activated:n.activated,domain:n.domain}}function FPe({connected:n,error:t,connection:o}){return n?"connected":t||o.feishuLongConnectionState==="failed"?"error":"disconnected"}function LPe(){return`bot_${k5().replaceAll("-","")}`}function UPe(){return`reg_${k5().replaceAll("-","")}`}function R5(n){return`DSH_FEISHU_APP_SECRET_${n.slice(4).toUpperCase()}`}function FS(n){return JSON.stringify({id:n.id,appId:n.appId,secretRef:n.secretRef,ownerOpenIds:n.ownerOpenIds,domain:n.domain,botName:n.botName,botOpenId:n.botOpenId,activated:n.activated,groupResponseMode:ho(n.groupResponseMode),groupMessagePermissionGranted:n.groupMessagePermissionGranted===!0,deletionPending:n.deletionPending===!0,connectedAt:n.connectedAt??null,createdAt:n.createdAt??null})}function LS(n){return typeof n=="string"&&n.trim()?n.trim():null}var KC=class{#e;#A;#t;#r;#l;#o;#i;#a;#n=new Map;#s=new Map;#d=new Map;#c=new Map;#g=new Map;#I=null;#p=Promise.resolve();#h=new Map;#u=1;#C;#B=!1;constructor({registerApp:t,verifyApp:o,credentials:i,configStore:e,createRuntime:a,deleteState:A=async()=>{},createBotId:r=LPe,createRegistrationId:s=UPe,callbackProbeTimeoutMs:g=vPe}){if(typeof t!="function")throw new Error("registerApp is required");if(typeof o!="function")throw new Error("verifyApp is required");if(!i)throw new Error("credentials service is required");if(!e||typeof e.list!="function")throw new Error("multi-bot config store is required");if(typeof a!="function")throw new Error("createRuntime is required");if(typeof A!="function")throw new Error("deleteState must be a function");if(!Number.isFinite(g)||g<=0||g>PPe)throw new TypeError("callbackProbeTimeoutMs must be between 1 and 600000ms");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#C=g}async initialize(){if(this.#B)return this.status();let t=this.#r.list(),o=!1;return await Promise.allSettled(t.map(i=>this.#N(i.id,async()=>{let e=UC(this.#n.get(i.id));if(HC(e)||e.feishuLongConnectionState==="connecting"||e.feishuLongConnectionState==="reconnecting")return;if(o=!0,i.deletionPending){this.#s.set(i.id,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"});return}let a;try{a=await this.#t.resolve(i.secretRef)}catch{this.#s.set(i.id,{code:"missing_credentials",message:"\u65E0\u6CD5\u8BFB\u53D6\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u3002"});return}if(!a?.value){this.#s.set(i.id,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"});return}try{await this.#E(i,a.value),this.#s.delete(i.id)}catch{this.#s.set(i.id,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}}))),o&&this.#k(),this.status()}startRegistration(){this.#M();let t=this.#a();if(typeof t!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t)||this.#d.has(t))throw new Error("Registration id generator returned an invalid or duplicate id");let o={id:t,manager:null,botId:null,createdNew:!1,cancelled:!1};return o.manager=new kg({registerApp:this.#e,onCredentials:i=>this.#P(()=>this.#D(o,i))}),this.#d.set(t,o),this.#I=t,this.#F(),o.manager.start({source:"deepseek-harness",createOnly:!0,appPreset:{name:"{user} \u7684\u5317\u6C47\u661F\u6CB3 AI \u52A9\u624B",desc:"\u8FDE\u63A5\u98DE\u4E66\u4E0E DeepSeek Harness\uFF0C\u5728\u804A\u5929\u4E2D\u4F7F\u7528\u4F01\u4E1A AI \u52A9\u624B\u3002"},addons:{preset:!1,scopes:{tenant:[..._5]},events:{items:{tenant:["im.message.receive_v1"]}},callbacks:{items:["card.action.trigger"]}}}),this.#k(),this.registrationStatus(t)}startCallbackRepair(t,{actorOpenId:o,chatId:i}={}){this.#M();let e=this.#T(t);if(e.deletionPending)throw new Error("Cannot repair a Feishu bot pending deletion");let a=this.#c.get(t),A=a?this.#d.get(a):null;if(A&&GS.has(A.manager.status().state)){if(A.operation!==LC)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(A.id)}this.#c.delete(t);let r=this.#a();if(typeof r!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(r)||this.#d.has(r))throw new Error("Registration id generator returned an invalid or duplicate id");let s={id:r,operation:LC,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(e),targetFingerprint:FS(e),initiator:{actorOpenId:LS(o),chatId:LS(i)}};return s.manager=new kS({registerApp:this.#e,appId:e.appId,domain:e.domain,onCredentials:g=>{s.remoteCommitted=!0;let I=this.#y(s,g).finally(()=>{s.processing===I&&(s.processing=null)});return s.processing=I,I}}),this.#d.set(r,s),this.#c.set(t,r),this.#I=r,this.#F(),s.manager.start(),this.#k(),this.registrationStatus(r)}startGroupMessagePermission(t){this.#M();let o=this.#T(t);if(o.deletionPending)throw new Error("Cannot update permissions for a Feishu bot pending deletion");let i=this.#c.get(t),e=i?this.#d.get(i):null;if(e&&GS.has(e.manager.status().state)){if(e.operation!==PS)throw new Error("Another Feishu app update is already active for this bot");return this.registrationStatus(e.id)}this.#c.delete(t);let a=this.#a();if(typeof a!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(a)||this.#d.has(a))throw new Error("Registration id generator returned an invalid or duplicate id");let A={id:a,operation:PS,manager:null,botId:t,createdNew:!1,cancelled:!1,remoteCommitted:!1,processing:null,publicError:null,stage:"authorizing",target:structuredClone(o),targetFingerprint:FS(o),initiator:{actorOpenId:null,chatId:null}};return A.manager=new vS({registerApp:this.#e,appId:o.appId,domain:o.domain,onCredentials:r=>{A.remoteCommitted=!0;let g=this.#S(A,r).finally(()=>{A.processing===g&&(A.processing=null)});return A.processing=g,g}}),this.#d.set(a,A),this.#c.set(t,a),this.#I=a,this.#F(),A.manager.start(),this.#k(),this.registrationStatus(a)}hasRegistration(t){return this.#d.has(t)}registrationStatus(t){let o=this.#d.get(t);return o?this.#f({registration:o,selectedBotId:o.botId}):null}async cancelRegistration(t=this.#I){let o=this.#d.get(t);if(!o)return this.status();let i=o.manager.status().state;return T5.has(o.operation)&&i==="saving"?this.registrationStatus(t):GS.has(i)?(o.cancelled=!0,o.manager.cancel(),await this.#P(async()=>{o.createdNew&&o.botId&&this.#g.get(o.botId)===o.id&&this.#r.getBot(o.botId)&&await this.#N(o.botId,()=>this.#O(o.botId))}),this.#k(),this.registrationStatus(t)??this.status()):this.registrationStatus(t)}status(t){return this.#f({registration:this.#d.get(this.#I)??null,selectedBotId:t})}async bindCredentials({appId:t,appSecret:o,domain:i="feishu"}={}){this.#M();let e=typeof t=="string"?t.trim():"",a=typeof o=="string"?o.trim():"",A=i==="lark"?"lark":"feishu";if(!e||!a)throw new TypeError("Feishu App ID and App Secret are required");return this.#P(async()=>{this.#M();let r=await this.#A({appId:e,appSecret:a,domain:A});this.#M();let s=this.#r.list().find(f=>f.appId===e),g=s?.id??this.#i();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??R5(g),I=await this.#t.resolve(c).catch(()=>{}),d={...s,id:g,appId:e,secretRef:c,ownerOpenIds:s?.ownerOpenIds?.length?s.ownerOpenIds:[N5],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()};await this.#t.set(c,a);let B;try{B=await this.#r.saveBot(d)}catch(f){throw await this.#w(c,I),f}return await this.#N(g,async()=>{try{await this.#E(B,a),this.#s.delete(g)}catch{this.#s.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u7ED1\u5B9A\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"})}}),this.#k(),this.status(g)})}async reconnectBot(t){return this.#M(),this.#N(t,async()=>{let o=this.#T(t);if(o.deletionPending)return this.#s.set(t,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"}),this.status(t);if(HC(UC(this.#n.get(t))))return this.status(t);let i;try{i=await this.#t.resolve(o.secretRef)}catch{i=null}if(!i?.value)return this.#s.set(t,{code:"missing_credentials",message:"\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u5220\u9664\u540E\u91CD\u65B0\u626B\u7801\u63A5\u5165\u3002"}),this.#k(),this.status(t);try{await this.#E(o,i.value),this.#s.delete(t)}catch{this.#s.set(t,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u98DE\u4E66\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}return this.#k(),this.status(t)})}async sendConnectionTest(t){return this.#M(),this.#N(t,async()=>{let o=this.#T(t),i=this.#n.get(t);if(!HC(UC(i))||typeof i.sendConnectionTest!="function"){let e=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw e.code="test-target-unavailable",e}return i.sendConnectionTest(La(`${o.botName}\uFF08${P5(o.appId)}\uFF09`,"\u98DE\u4E66\u673A\u5668\u4EBA"))})}async sendProactiveText(t,o,i,e={}){return this.#M(),this.#N(t,async()=>{this.#T(t);let a=this.#n.get(t);if(!HC(UC(a))||typeof a.sendProactiveText!="function"){let A=new Error("\u98DE\u4E66\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5");throw A.code="bot-not-connected",A}return a.sendProactiveText(o,i,e)})}async disconnectBot(t){return this.#M(),this.#N(t,async()=>(this.#T(t),await this.#_(t),this.#s.delete(t),this.#k(),this.status(t)))}async updateGroupResponseMode(t,o){if(this.#M(),!BS(o))throw new TypeError("Invalid Feishu group response mode");return this.#P(()=>this.#N(t,async()=>{let i=this.#T(t);if(o==="all"&&i.groupMessagePermissionGranted!==!0){let a=new Error("Authorize im:message.group_msg before enabling all group messages");throw a.code="group_message_permission_required",a}let e=await this.#r.saveBot({...i,groupResponseMode:o});return this.#n.get(t)?.setGroupResponseMode?.(e.groupResponseMode),this.#k(),this.status(t)}))}async deleteBot(t){return this.#M(),this.#P(()=>this.#N(t,async()=>(this.#T(t),await this.#O(t),this.#k(),this.status())))}async reconnect(){let t=this.#r.list()[0];return t?this.reconnectBot(t.id):this.status()}async disconnect(){let t=this.#r.list()[0];return t?this.deleteBot(t.id):this.status()}async close(){if(this.#B)return;this.#B=!0;let t=[];for(let o of this.#d.values()){let i=o.manager.status().state;T5.has(o.operation)&&i==="saving"?(o.manager.cancel(),o.processing&&t.push(o.processing)):GS.has(i)&&(o.cancelled=!0,o.manager.cancel())}await this.#p,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#n.keys()].map(o=>this.#_(o))),await Promise.allSettled(t),await this.#p,await Promise.allSettled([...this.#h.values()]),await Promise.allSettled([...this.#n.keys()].map(o=>this.#_(o)))}#f({registration:t,selectedBotId:o}={}){let i=this.#r.list().map(I=>{let d=UC(this.#n.get(I.id)),B=HC(d),f=this.#s.get(I.id)??null;return{botId:I.id,phase:FPe({connected:B,error:f,connection:d}),connected:B,configured:!0,groupResponseMode:ho(I.groupResponseMode),groupMessagePermissionGranted:I.groupMessagePermissionGranted===!0,bot:GPe(I),connection:d,lastMessageError:Aa(d.lastMessageError),error:f}}),e=t?this.#Q(t):{state:"idle",attempt:0,updatedAt:Date.now()},a=zP.has(e.state),A=e.state==="saving",r=!!t&&(a||A),s=i.find(I=>I.botId===o)??(r?null:i[0]??null),g=i.some(I=>I.connected),c=s?.phase??"unconfigured";return a?c="registering":A?c="connecting":e.state==="error"&&!s&&(c="error"),{schemaVersion:2,revision:this.#u,phase:c,connected:s?.connected??!1,configured:i.length>0,bot:s?.bot??null,connection:s?.connection??v5(),error:s?.error??e.error??null,registration:e,bots:i,totals:{configured:i.length,connected:i.filter(I=>I.connected).length},anyConnected:g}}#Q(t){let o=t.manager.status();return{...o,attempt:t.id,...t.botId?{botId:t.botId}:{},...t.operation?{operation:t.operation}:{},...t.stage?{stage:t.stage}:{},...o.state==="error"&&t.publicError?{error:{...t.publicError}}:{}}}async#S(t,o){let i=o.client_id,e=o.client_secret,a=LS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Group message permission update was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no permission operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");if(!r.ownerOpenIds.includes(N5)&&!r.ownerOpenIds.includes(a))throw this.#m(t,"repair_owner_mismatch","The Feishu permission operator is not an owner of this configured bot.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(g){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the updated app credentials.",g)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The updated Feishu app belongs to a different bot identity.");await this.#P(()=>this.#N(t.botId,async()=>{let g=this.#r.getBot(t.botId);if(!g||g.deletionPending||FS(g)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its permission update was in progress.");let c;try{c=await this.#t.resolve(g.secretRef)}catch(d){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",d)}if(c?.value!==e){t.stage="persisting_secret";try{await this.#t.set(g.secretRef,e)}catch(B){if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the updated Feishu credential.",B)}if((await this.#t.resolve(g.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The updated Feishu credential could not be confirmed after writing.")}t.stage="enabling_all_messages";let I;try{I=await this.#r.saveBot({...g,groupMessagePermissionGranted:!0,groupResponseMode:"all"})}catch(d){throw this.#m(t,"group_message_permission_save_failed","The permission was accepted, but all-message mode could not be saved.",d)}t.stage="restarting";try{await this.#E(I,e)}catch(d){throw this.#s.set(t.botId,{code:"connection_failed",message:"\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u4F46\u673A\u5668\u4EBA\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#k(),this.#m(t,"group_message_permission_connection_failed","The permission was accepted, but the Feishu runtime could not restart.",d)}this.#s.delete(t.botId),t.stage="verified",t.publicError=null,this.#k()}))}async#y(t,o){let i=o.client_id,e=o.client_secret,a=LS(o.user_info?.open_id),A=o.user_info?.tenant_brand,r=t.target;if(t.cancelled)throw this.#m(t,"abort","Callback repair was cancelled before local activation.");if(i!==r.appId)throw this.#m(t,"repair_app_mismatch","Feishu returned credentials for a different app.");if(!a)throw this.#m(t,"repair_owner_missing","Feishu returned no repair operator identity.");if(A!==void 0&&A!==r.domain)throw this.#m(t,"repair_domain_mismatch","Feishu returned credentials for a different account domain.");t.stage="verifying_identity";let s;try{s=await this.#A({appId:i,appSecret:e,domain:r.domain})}catch(c){throw this.#m(t,"repair_credentials_invalid","Feishu could not verify the repaired app credentials.",c)}if(r.botOpenId&&s?.openId!==r.botOpenId)throw this.#m(t,"repair_bot_mismatch","The repaired Feishu app belongs to a different bot identity.");let g=await this.#P(()=>this.#N(t.botId,async()=>{let c=this.#r.getBot(t.botId);if(!c||c.deletionPending||FS(c)!==t.targetFingerprint)throw this.#m(t,"repair_target_changed","The Feishu bot changed while its callback repair was in progress.");let I;try{I=await this.#t.resolve(c.secretRef)}catch(f){throw this.#m(t,"credential_update_failed","Unable to read the current Feishu credential.",f)}if(I?.value!==e){t.stage="persisting_secret";try{await this.#t.set(c.secretRef,e)}catch(Q){if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_update_failed","Unable to store the repaired Feishu credential.",Q)}if((await this.#t.resolve(c.secretRef).catch(()=>null))?.value!==e)throw this.#m(t,"credential_state_unknown","The repaired Feishu credential could not be confirmed after writing.")}let B;t.stage="restarting";try{await this.#E(c,e),B=this.#n.get(t.botId)}catch(f){throw this.#s.set(t.botId,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u56DE\u8C03\u4FEE\u590D\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#k(),this.#m(t,"repair_connection_failed","The repaired Feishu runtime could not be started.",f)}if(!B)throw this.#m(t,"repair_connection_failed","The repaired Feishu runtime is unavailable.");return this.#s.delete(t.botId),this.#k(),B}));if(typeof g.beginCardActionProbe!="function")throw this.#m(t,"card_action_probe_unavailable","The Feishu runtime cannot verify card callbacks.");t.stage="awaiting_callback";try{if((await g.beginCardActionProbe({expectedOperatorOpenId:t.initiator.actorOpenId??a,timeoutMs:this.#C,...t.initiator.chatId?{chatId:t.initiator.chatId}:{}}))?.verified!==!0){let I=new Error("Feishu runtime returned no callback proof");throw I.code="card_action_probe_failed",I}}catch(c){let I=c?.code==="card_action_probe_timeout"?"card_action_probe_timeout":c?.code==="card_action_probe_unavailable"?"card_action_probe_unavailable":c?.code==="card_action_probe_send_failed"?"card_action_probe_send_failed":"card_action_probe_failed";throw this.#m(t,I,I==="card_action_probe_timeout"?"Timed out waiting for the Feishu callback verification button.":"The Feishu card callback probe failed.",c)}t.stage="verified",t.publicError=null,this.#k()}#m(t,o,i,e){t.publicError={code:o,message:i};let a=new Error(i,e?{cause:e}:void 0);return a.code=o,a}async#D(t,o){if(t.cancelled)throw new Error("Registration was cancelled");let i=o.client_id,e=o.client_secret,a=o.user_info?.open_id,A=o.user_info?.tenant_brand==="lark"?"lark":"feishu";if(!a)throw new Error("Feishu registration returned no owner open_id");let r=await this.#A({appId:i,appSecret:e,domain:A});if(t.cancelled)throw new Error("Registration was cancelled");let s=this.#r.list().find(Q=>Q.appId===i),g=s?.id??this.#i();if(typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)||!s&&this.#r.getBot(g))throw new Error("Bot id generator returned an invalid or duplicate id");let c=s?.secretRef??R5(g),I=this.#g.get(g),d=await this.#t.resolve(c).catch(()=>{});await this.#t.set(c,e);let B;try{B=await this.#r.saveBot({...s,id:g,appId:i,secretRef:c,ownerOpenIds:[...new Set([...s?.ownerOpenIds??[],a])],domain:A,botName:r.name,botOpenId:r.openId,activated:r.activated,deletionPending:!1,connectedAt:new Date().toISOString(),createdAt:s?.createdAt??new Date().toISOString()}),t.botId=g,t.createdNew=!s,this.#g.set(g,t.id)}catch(Q){try{await this.#w(c,d)}catch(y){throw new Error("Unable to restore the Feishu credential after a config failure.",{cause:y})}throw Q}if(t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#O(g)):(await this.#r.saveBot(s),await this.#w(c,d),I?this.#g.set(g,I):this.#g.delete(g)),new Error("Registration was cancelled");let f=!1;try{if(await this.#N(g,()=>this.#E(B,e)),t.cancelled)throw t.createdNew?await this.#N(g,()=>this.#O(g)):(await this.#r.saveBot(s),await this.#w(c,d),I?this.#g.set(g,I):this.#g.delete(g),d?.value&&!s.deletionPending?await this.#N(g,()=>this.#E(s,d.value)):await this.#N(g,()=>this.#_(g))),f=!0,new Error("Registration was cancelled");this.#s.delete(g),this.#k()}catch(Q){if(t.cancelled)throw!f&&t.createdNew&&this.#r.getBot(g)?await this.#N(g,()=>this.#O(g)):!f&&s&&(await this.#r.saveBot(s),await this.#w(c,d),I?this.#g.set(g,I):this.#g.delete(g),!this.#B&&d?.value&&!s.deletionPending?await this.#N(g,()=>this.#E(s,d.value)):await this.#N(g,()=>this.#_(g))),this.#k(),Q;if(s&&d?.value)try{throw await this.#r.saveBot(s),await this.#w(c,d),I?this.#g.set(g,I):this.#g.delete(g),s.deletionPending?(await this.#N(g,()=>this.#_(g)),this.#s.set(g,{code:"deletion_pending",message:"\u673A\u5668\u4EBA\u6B63\u5728\u7B49\u5F85\u5B8C\u6210\u672C\u5730\u5220\u9664\uFF0C\u8BF7\u91CD\u8BD5\u79FB\u9664\u3002"})):(await this.#N(g,()=>this.#E(s,d.value)),this.#s.delete(g)),this.#k(),Q}catch(y){throw y===Q?Q:(this.#s.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u8FDE\u63A5\u66F4\u65B0\u5931\u8D25\uFF0C\u4E14\u539F\u8FDE\u63A5\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"}),this.#k(),new Error("Unable to restore the previous Feishu bot connection.",{cause:y}))}throw this.#s.set(g,{code:"connection_failed",message:"\u673A\u5668\u4EBA\u5DF2\u7ECF\u521B\u5EFA\uFF0C\u4F46\u957F\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u8BF7\u70B9\u51FB\u91CD\u8BD5\u3002"}),this.#k(),Q}}async#E(t,o){await this.#_(t.id);let i=await this.#l({botId:t.id,config:t,appSecret:o,repair:this.#R(t.id)});this.#n.set(t.id,i);try{await i.start()}catch(e){throw this.#n.get(t.id)===i&&this.#n.delete(t.id),await i.stop({preserveError:!0}).catch(()=>{}),e}}#R(t){let o=i=>{let e=this.#d.get(i);return e?.operation===LC&&e.botId===t?e:null};return Object.freeze({start:({actorOpenId:i,chatId:e}={})=>this.startCallbackRepair(t,{actorOpenId:i,chatId:e}),status:({attemptId:i}={})=>o(i)?this.registrationStatus(i):null,cancel:async({attemptId:i}={})=>o(i)?this.cancelRegistration(i):this.status(t)})}async#_(t){let o=this.#n.get(t);this.#n.delete(t),o&&await o.stop()}async#O(t){let o=this.#r.getBot(t);if(o){o.deletionPending||(o=await this.#r.saveBot({...o,deletionPending:!0})),await this.#_(t);try{await this.#t.unset(o.secretRef)}catch(i){throw this.#s.set(t,{code:"credential_removal_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u51ED\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu credential.",{cause:i})}try{await this.#o({botId:t,config:o})}catch(i){throw this.#s.set(t,{code:"state_cleanup_failed",message:"\u65E0\u6CD5\u5220\u9664\u673A\u5668\u4EBA\u7684\u672C\u5730\u4F1A\u8BDD\u6570\u636E\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"}),new Error("Unable to remove the Feishu bot session state.",{cause:i})}await this.#r.removeBot(t),this.#s.delete(t),this.#g.delete(t)}}async#w(t,o){o?.value?await this.#t.set(t,o.value):await this.#t.unset(t)}#T(t){let o=this.#r.getBot(t);if(!o)throw new Error("Unknown Feishu bot");return o}#M(){if(this.#B)throw new Error("The Feishu controller is closed")}#P(t){let o=this.#p.then(t,t);return this.#p=o.then(()=>{},()=>{}),o}#N(t,o){let e=(this.#h.get(t)??Promise.resolve()).then(o,o),a=e.then(()=>{},()=>{});return this.#h.set(t,a),a.finally(()=>{this.#h.get(t)===a&&this.#h.delete(t)}),e}#F(){if(!(this.#d.size<=32))for(let[t,o]of this.#d){if(t===this.#I)continue;let i=o.manager.status().state;if(!zP.has(i)&&i!=="saving"&&this.#d.delete(t),this.#d.size<=32)break}}#k(){this.#u+=1}};var xPe=["open.feishu.cn","open.larksuite.com"];function YPe(n,t){if(t==="*")return!0;let o=t.startsWith(".")?t.slice(1):t;return o?n===o||n.endsWith(`.${o}`):!1}function jPe(n){for(let t of["no_proxy","NO_PROXY"]){let o=n?.[t];if(typeof o!="string"||!o.trim())continue;let i=o.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean);if(xPe.some(e=>i.some(a=>YPe(e,a))))return!0}return!1}function JPe(n){if(!jPe(n))for(let t of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"]){let o=n?.[t];if(typeof o=="string"&&o.trim())return o.trim()}}function qPe(n,t=o=>new G5.default(o)){let o=JPe(n);return o?t(o):void 0}function zPe(n){let t=Gc(n.dshHome??process.env.DSH_HOME??Zp(HPe(),".dsh")),o=Gc(n.dataDir??Zp(t,"integrations","dsh-feishu"));return{root:o,config:Gc(n.configPath??Zp(o,"config.json")),legacyState:Gc(n.statePath??Zp(o,"state.json")),bots:Gc(n.botsDir??Zp(o,"bots")),workspaces:Gc(n.workspacesPath??Zp(o,"workspaces.json"))}}async function VP(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-feishu requires ctx.credentials");let i=na(n,t),e=o.lark??OP,a=o.Controller??KC,A=o.ConfigStore??NS,r=o.StateStore??uS,s=o.HarnessClient??_S,g=o.FeishuRuntime??MS,c=o.verifyFeishuApp??H6,I=Be=>c({...Be,httpInstance:e.defaultHttpInstance}),d=o.createConnectionSupervisor??bP,B=typeof n.logger=="function"?n.logger("dsh-feishu"):n.logger??console,f=()=>Ya(n),Q=zPe(t),y=await new A(Q.config).load(),m=Gc(t.workspace??process.cwd()),T=o.WorkspaceStore??oa,_=o.workspaces??await new T(Q.workspaces,{defaultWorkspace:m}).load(),R=typeof y.list=="function",x=()=>R?y.list():[],F=x();R&&await _.reconcile(F.map(Be=>Be.id)),await Promise.all(F.map(Be=>_.ensure(Be.id,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("feishu",Be)})));let L=typeof y.removeBot=="function"?ja(y,{workspaces:_,method:"removeBot",botIdFromRemoved:Be=>Be.id,saveMethod:"saveBot",botIdFromSave:Be=>Be?.id}):y,q=new Map,z=Be=>!Be.id||!Be.secretRef||Be.secretRef===RS?Q.legacyState:Gc(Q.bots,Be.id,"state.json"),H=async Be=>{let ke=Be.id??"__legacy__",Re=q.get(ke);return Re||(Re=await new r(z(Be)).load(),q.set(ke,Re)),Re},G=async Be=>{let ke=x().find(Re=>Re.id===Be);if(!ke)throw new Error("Unknown Feishu bot");return H(ke)},V=Va(n,o.commandExecutor),{controlExecutor:U,sessionMaintenanceExecutor:N,fileIngressExecutor:k}=Wa(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),J=new s({...i,workspace:m,autostart:!1,dshBin:t.dshBin??"dsh",...V?{commandExecutor:V}:{},...U?{controlExecutor:U}:{},...N?{sessionMaintenanceExecutor:N}:{},...k?{fileIngressExecutor:k}:{}}),X=o.proxyEnv??process.env,ie=qPe(X,o.createProxyAgent),we=new a({registerApp:Be=>e.registerApp(Be),verifyApp:I,credentials:n.credentials,configStore:L,createRuntime:async({botId:Be,config:ke,appSecret:Re,repair:We})=>{let ve=await H(ke),aA=Be??ke.id??ke.appId;await _.ensure(aA,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("feishu",ke)});let fe=Ja(J,{botId:aA,workspaces:_,state:ve,agentPresetCatalog:f});return new g({lark:e,botId:aA,repair:We,appId:ke.appId,appSecret:Re,domain:ke.domain,botOpenId:ke.botOpenId,groupResponseMode:ke.groupResponseMode,ownerOpenIds:ke.ownerOpenIds??[ke.ownerOpenId],harness:fe.harness,state:fe.state,contextEnhancement:{botId:aA,getSettings:()=>_.contextEnhancementFor(aA)},accessPolicy:Za(_,aA,{channel:"feishu",config:ke}),replyTimeoutMs:t.replyTimeoutMs??6e5,slashCommands:t.slashCommands!==!1,...ie?{wsAgent:ie}:{},logger:{error:(...Ie)=>B.error?.(`[${Be??ke.id}]`,...Ie),warn:(...Ie)=>B.warn?.(`[${Be??ke.id}]`,...Ie),info:(...Ie)=>B.info?.(`[${Be??ke.id}]`,...Ie),debug:(...Ie)=>B.debug?.(`[${Be??ke.id}]`,...Ie)}})},deleteState:async({botId:Be,config:ke})=>{q.delete(Be);try{await KPe(z(ke))}catch(Re){if(Re?.code!=="ENOENT")throw Re}}}),oe=qa(we,{workspaces:_,stateFor:G,agentPresetCatalog:f}),Se=d({controller:oe,harness:J,logger:B,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:oe,deliveryAdapter:za({channel:"feishu",workspaces:_,coreController:we,stateFor:G}),ready:Se.ready,async close(){await Se.close(),await oe.close(),J.stopManagedProcess(),ie?.destroy?.()}}}import dGe from"qrcode";var $p=qe(tG(),1);var cGe=qe(tG(),1);var IGe=Object.freeze({$locale:"en",IM\u673A\u5668\u4EBA:"IM bots",IM\u673A\u5668\u4EBA\u8BBE\u7F6E:"IM bot settings",\u66F4\u591A\u673A\u5668\u4EBA\u8BBE\u7F6E:"More bot settings",\u673A\u5668\u4EBA\u8BBE\u7F6E:"Bot settings",\u673A\u5668\u4EBA\u8BBE\u7F6E\u9875\u7B7E:"Bot settings tabs",\u6295\u9012\u8BBE\u7F6E:"Delivery settings",\u8BBF\u95EE\u8BBE\u7F6E:"Access settings",\u67E5\u770B\u8BBF\u95EE\u6743\u9650\u8BF4\u660E:"View access permission details",\u5141\u8BB8\u6240\u6709\u7528\u6237:"Allow all users",\u4EC5\u767D\u540D\u5355\u7528\u6237:"Allowlisted users only",\u9ED8\u8BA4\u547D\u4EE4\u6743\u9650:"Default command permission",\u547D\u4EE4\u6743\u9650:"Command permission",\u53EF\u4EE5\u6267\u884C\u547D\u4EE4:"Can run commands",\u4E0D\u53EF\u4EE5\u6267\u884C\u547D\u4EE4:"Cannot run commands",\u767D\u540D\u5355\u7528\u6237:"Allowlisted users",\u67E5\u770B\u767D\u540D\u5355\u8BF4\u660E:"View allowlist details",\u547D\u4EE4\u6743\u9650\u4F8B\u5916:"Command permission exceptions","\u5F53\u524D\u6CA1\u6709\u767D\u540D\u5355\u7528\u6237\uFF0C\u4FDD\u5B58\u540E\u666E\u901A\u7528\u6237\u5C06\u65E0\u6CD5\u4F7F\u7528\u673A\u5668\u4EBA\u3002":"There are currently no allowlisted users. After saving, regular users will not be able to use the bot.",\u65B0\u589E\u7528\u6237:"Add user",\u5C1A\u672A\u6DFB\u52A0\u7528\u6237:"No users added",\u5F53\u524D\u6E20\u9053\u4E0D\u652F\u6301\u7FA4\u804A:"Group chat is not supported by this channel","\u539F\u6240\u6709\u8005\u6216\u626B\u7801\u63A5\u5165\u8005\u59CB\u7EC8\u53EF\u4EE5\u8BBF\u95EE\u5E76\u6267\u884C\u547D\u4EE4\uFF1B\u4EE5\u4E0B\u8BBE\u7F6E\u4EC5\u7EA6\u675F\u5176\u4ED6\u7528\u6237\u3002":"The original owner or QR-code operator can always access the bot and run commands; the settings below apply only to other users.","\u6B64\u533A\u57DF\u65E0\u9700\u914D\u7F6E\uFF0C\u4FDD\u5B58\u79C1\u804A\u8BBE\u7F6E\u65F6\u4F1A\u4FDD\u7559\u73B0\u6709\u7FA4\u804A\u7B56\u7565\u3002":"No setup is needed here. Saving direct-message settings keeps the existing group policy.","\u8BBF\u95EE\u8BBE\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Access settings saved.","\u8BBF\u95EE\u8BBE\u7F6E\u6682\u4E0D\u53EF\u7528\u3002":"Access settings are currently unavailable.","\u8BBF\u95EE\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"Could not save access settings. Try again later.","\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u5DF2\u4FDD\u5B58\u7684\u8BBF\u95EE\u7B56\u7565\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002":"The service did not return the saved access policy. Refresh and try again.","\u8BBF\u95EE\u7B56\u7565\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u8FD4\u56DE\u673A\u5668\u4EBA\u5217\u8868\u5237\u65B0\u540E\u91CD\u8BD5\u3002":"The access policy is not ready. Return to the bot list, refresh, and try again.","\u5F53\u524D\u6E20\u9053\u6682\u4E0D\u652F\u6301\u8BBF\u95EE\u8BBE\u7F6E\u3002":"Access settings are not supported by this channel yet.","\u7528\u6237\u6807\u8BC6\u65E0\u6548\u3002":"The user ID is invalid.","\u7528\u6237\u6807\u8BC6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002":"The user ID must be a string.","\u7528\u6237\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A\u3001\u5305\u542B\u63A7\u5236\u5B57\u7B26\u6216\u8D85\u8FC7 256 \u4E2A\u5B57\u7B26\u3002":"The user ID cannot be empty, contain control characters, or exceed 256 characters.","\u7528\u6237\u6761\u76EE\u5FC5\u987B\u5305\u542B\u7528\u6237\u6807\u8BC6\u548C\u547D\u4EE4\u6743\u9650\u3002":"Each user entry must include a user ID and command permission.","\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002":"Command permission must be a boolean.","\u8BBF\u95EE\u6A21\u5F0F\u53EA\u80FD\u662F open \u6216 allowlist\u3002":"Access mode must be open or allowlist.","\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002":"Open-mode settings must be complete.","\u5F00\u653E\u6A21\u5F0F\u9ED8\u8BA4\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002":"The open-mode default command permission must be a boolean.","\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002":"Open-mode command permission overrides must be an array.","\u5F00\u653E\u6A21\u5F0F\u547D\u4EE4\u6743\u9650\u8986\u76D6\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002":"Open-mode command permission overrides cannot contain duplicate user IDs.","\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002":"Allowlist-mode settings must be complete.","\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u5FC5\u987B\u662F\u6570\u7EC4\u3002":"Allowlist-mode users must be an array.","\u767D\u540D\u5355\u6A21\u5F0F\u7528\u6237\u4E0D\u80FD\u5305\u542B\u91CD\u590D\u7684\u7528\u6237\u6807\u8BC6\u3002":"Allowlist-mode users cannot contain duplicate user IDs.","\u8BBF\u95EE\u573A\u666F\u8BBE\u7F6E\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6A21\u5F0F\u3001\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u548C\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u3002":"Each access context must include its mode, open-mode settings, and allowlist-mode settings.","\u8BF7\u540C\u65F6\u63D0\u4EA4\u5B8C\u6574\u7684\u79C1\u804A\u548C\u7FA4\u804A\u8BBF\u95EE\u8BBE\u7F6E\u3002":"Submit complete direct-message and group access settings together.","\u586B\u5199\u5FAE\u4FE1\u7528\u6237 ID":"Enter a WeChat user ID","\u98DE\u4E66 Open ID":"Feishu Open ID","\u7FA4\u6210\u5458 Open ID":"Group member Open ID","\u9489\u9489\u7528\u6237 ID":"DingTalk user ID","\u586B\u5199 senderStaffId \u6216 senderId":"Enter senderStaffId or senderId","\u7FA4\u6210\u5458\u7528\u6237 ID":"Group member user ID","\u4F01\u4E1A\u5FAE\u4FE1\u7528\u6237 ID":"WeCom user ID","\u586B\u5199 userid":"Enter userid","\u586B\u5199 member_openid":"Enter member_openid","QQ User Open ID":"QQ User Open ID","\u7FA4\u6210\u5458 User ID":"Group member User ID","\u586B\u5199\u6570\u5B57 User ID":"Enter a numeric user ID","WhatsApp \u7535\u8BDD\u53F7\u7801\u6216 JID":"WhatsApp phone number or JID","\u7FA4\u6210\u5458\u7535\u8BDD\u53F7\u7801\u6216 JID":"Group member phone number or JID","8613800000000 \u6216\u5B8C\u6574 JID":"8613800000000 or a full JID","IM \u6E20\u9053":"IM channels","\u8BA9 DeepSeek Harness \u89E6\u624B\u53EF\u53CA":"Connecting DeepSeek Harness",\u5F53\u524D\u7248\u672C:"Current version","DSH-IM \u66F4\u65B0":"DSH-IM update",\u68C0\u67E5\u66F4\u65B0:"Check for updates",\u91CD\u65B0\u68C0\u67E5:"Check again",\u5237\u65B0\u72B6\u6001:"Refresh status",\u624B\u5DE5\u66F4\u65B0:"Manual update",\u624B\u5DE5\u66F4\u65B0\u547D\u4EE4:"Manual update command",\u590D\u5236\u547D\u4EE4:"Copy command","\u590D\u5236\u4E2D\u2026":"Copying\u2026",\u5DF2\u590D\u5236:"Copied","\u547D\u4EE4\u5DF2\u590D\u5236\u3002":"Command copied.","\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u9009\u4E2D\u547D\u4EE4\u540E\u6309 Ctrl+C \u6216 \u2318C \u590D\u5236\u3002":"Copy failed. Select the command and press Ctrl+C or \u2318C to copy it.","\u81EA\u52A8\u66F4\u65B0\u5931\u8D25\u53EF\u4EE5\u4F7F\u7528\u547D\u4EE4\u66F4\u65B0\uFF1A":"If the automatic update fails, update with this command:","\u5C1A\u672A\u786E\u8BA4\u76EE\u6807\u7248\u672C\uFF0C\u6B64\u547D\u4EE4\u5B89\u88C5\u6267\u884C\u65F6 npm \u7684 latest \u7248\u672C\u3002":"No target version has been confirmed. This command installs the npm latest version available when you run it.","\u8BF7\u5728\u5F53\u524D Desktop \u7684\u5185\u7F6E\u7EC8\u7AEF\u6267\u884C\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the current Desktop\u2019s built-in terminal, then restart manually.","\u8BF7\u5728\u8FD0\u884C\u5F53\u524D Harness \u7684\u540C\u4E00\u73AF\u5883\u6267\u884C\uFF0C\u4FDD\u6301 DSH_HOME \u4E00\u81F4\uFF0C\u5B8C\u6210\u540E\u624B\u52A8\u91CD\u542F\u3002":"Run this in the same environment as the current Harness, with the same DSH_HOME, then restart manually.","\u8BF7\u7B49\u5F85\u5F53\u524D\u64CD\u4F5C\u7ED3\u675F\uFF0C\u786E\u8BA4\u6CA1\u6709\u5B89\u88C5\u8FDB\u7A0B\u8FD0\u884C\u540E\u518D\u6267\u884C\u547D\u4EE4\u3002":"Wait for the current operation to finish and confirm no installer is running before using this command.","\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\u8BF7\u6309\u539F\u5B89\u88C5\u65B9\u5F0F\u66F4\u65B0\uFF0C\u4E0D\u63D0\u4F9B\u8986\u76D6\u6E90\u7801\u7684 npm \u547D\u4EE4\u3002":"Update source or linked installations using their original method. No npm command is provided to overwrite the source.","\u65E0\u6CD5\u5B89\u5168\u751F\u6210\u5F53\u524D profile \u7684\u547D\u4EE4\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u624B\u52A8\u786E\u8BA4 profile \u540E\u66F4\u65B0\u3002":"A safe command cannot be generated for this profile. Confirm the profile in your terminal before updating manually.",\u66F4\u65B0\u81F3:"Update to",\u5B89\u88C5\u66F4\u65B0:"Install update","\u6B63\u5728\u66F4\u65B0\u2026":"Updating\u2026",\u5F85\u624B\u52A8\u91CD\u542F:"Restart needed",\u8FD0\u884C\u7248\u672C:"Running version",\u5DF2\u5B89\u88C5\u7248\u672C:"Installed version","\u76EE\u6807 profile":"Target profile",\u76EE\u6807\u7248\u672C:"Target version",\u65E0\u6CD5\u786E\u8BA4:"Unknown",\u53D1\u73B0\u65B0\u7248\u672C:"Update available",\u5DF2\u662F\u6700\u65B0\u7248\u672C:"Up to date",\u5F53\u524D\u7248\u672C\u65E0\u9700\u66F4\u65B0:"No newer version available","\u5DF2\u83B7\u53D6 npm \u6700\u65B0\u7248\u672C":"Latest npm version retrieved","\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5B89\u88C5\u3002":"Check the latest npm version. Nothing is installed automatically.","\u6B63\u5728\u4ECE npm \u68C0\u67E5\u6700\u65B0\u7248\u672C\u2026":"Checking npm for the latest version\u2026","\u6B63\u5728\u5B89\u88C5\uFF0C\u8BF7\u7A0D\u5019\u2026":"Installing, please wait\u2026","\u6B63\u5728\u6821\u9A8C\u5B89\u88C5\u7ED3\u679C\u2026":"Verifying the installation\u2026","\u5DF2\u5B89\u88C5\uFF0C\u5F85\u624B\u52A8\u91CD\u542F":"Installed \u2014 manual restart needed",\u66F4\u65B0\u5DF2\u751F\u6548:"Updated version is active",\u66F4\u65B0\u5931\u8D25:"Update failed",\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25:"Update request failed","\u4EC5\u66F4\u65B0 DSH-IM\u3002\u5B89\u88C5\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u540E\u53F0\uFF1B\u672C\u529F\u80FD\u4E0D\u4F1A\u81EA\u52A8\u91CD\u542F\u6216\u4E3B\u52A8\u5237\u65B0\u9875\u9762\u3002":"Only DSH-IM will be updated. Restart the backend manually after installation. This feature does not automatically restart it or initiate a page refresh.","\u5F53\u524D\u662F\u6E90\u7801\u6216\u94FE\u63A5\u5B89\u88C5\uFF0C\u53EA\u80FD\u68C0\u67E5\u7248\u672C\uFF1B\u8BF7\u624B\u52A8\u66F4\u65B0\u6E90\u7801\uFF0C\u6216\u8FC1\u79FB\u5230 npm \u5B89\u88C5\u3002":"This is a source or linked installation. You can check versions, but must update the source manually or migrate to an npm installation.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D profile\uFF0C\u8BF7\u5728\u5BF9\u5E94\u7684 Harness \u73AF\u5883\u4E2D\u624B\u52A8\u66F4\u65B0\u3002":"The current profile could not be identified. Update manually in the corresponding Harness environment.","\u5F53\u524D\u8FD0\u884C\u73AF\u5883\u4E0D\u652F\u6301\u6309\u94AE\u5B89\u88C5\uFF0C\u8BF7\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u3002":"This runtime cannot install through this button. Update the plugin manually.","\u5F53\u524D npm \u6E90\u914D\u7F6E\u4E0E\u5B98\u65B9\u6E90\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u5148\u68C0\u67E5 registry \u914D\u7F6E\u3002":"The npm registry configuration differs from the official registry. Check your registry settings first.","\u5F53\u524D Host \u7684 Node.js \u7248\u672C\u4E0D\u6EE1\u8DB3\u65B0\u7248\u8981\u6C42\uFF0C\u8BF7\u5148\u66F4\u65B0\u8FD0\u884C\u73AF\u5883\u3002":"The Host Node.js version does not meet the new version\u2019s requirements. Update the runtime first.","\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u8BF7\u5728\u65B9\u4FBF\u65F6\u624B\u52A8\u91CD\u542F\u5F53\u524D Harness \u6216 Desktop\u3002":"The new version is installed. Manually restart this Harness or Desktop when convenient.","\u4E0A\u6B21\u5B89\u88C5\u7ED3\u679C\u65E0\u6CD5\u786E\u8BA4\uFF0C\u8BF7\u5148\u68C0\u67E5\u6B64 profile \u7684\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u3002":"The previous installation result is uncertain. Check this profile\u2019s plugin installation first.","\u65E0\u6CD5\u8BBF\u95EE npm \u6216\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u68C0\u67E5\u3002":"npm is unreachable or the request timed out. Check again later.","npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\uFF0C\u6682\u65F6\u65E0\u6CD5\u66F4\u65B0\u3002":"npm returned invalid release information. Updating is unavailable.","\u7248\u672C\u786E\u8BA4\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u540E\u518D\u5B89\u88C5\u3002":"The version confirmation expired. Check again before installing.","\u63D2\u4EF6\u5B89\u88C5\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u3002":"The plugin installation changed. Check again.","\u6B64 profile \u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u67E5\u770B\u72B6\u6001\u3002":"This profile is already updating. Check its status shortly.","\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"Installation failed. Check the current installation before retrying.","\u5B89\u88C5\u7ED3\u679C\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u63D2\u4EF6\u7248\u672C\u3002":"Installation verification failed. Check the plugin version manually.","\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u66F4\u65B0\u72B6\u6001\uFF0C\u8BF7\u5148\u68C0\u67E5\u5F53\u524D\u5B89\u88C5\u7ED3\u679C\u3002":"Update state could not be saved safely. Check the current installation result before retrying.","\u4E0A\u6B21\u66F4\u65B0\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u72B6\u6001\u540E\u91CD\u8BD5\u3002":"The previous update was interrupted. Check the installation before retrying.","\u66F4\u65B0\u670D\u52A1\u5DF2\u5173\u95ED\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6253\u5F00\u8BBE\u7F6E\u9875\u3002":"The update service has closed. Reopen settings manually.","\u66F4\u65B0\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u7248\u672C\u3002":"The update request is invalid. Check the version again.","\u5F53\u524D\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574\u6216\u4E0E profile \u4E0D\u7B26\uFF0C\u8BF7\u624B\u52A8\u68C0\u67E5\u5B89\u88C5\u914D\u7F6E\u3002":"The plugin installation is incomplete or does not match this profile. Check the installation configuration manually.","\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D npm \u6E90\u914D\u7F6E\uFF0C\u6682\u65F6\u4E0D\u80FD\u5B89\u88C5\u66F4\u65B0\u3002":"The npm registry configuration could not be verified. Installation is unavailable.","\u5B89\u88C5\u8D85\u65F6\uFF0C\u8BF7\u5148\u786E\u8BA4\u5F53\u524D\u5B89\u88C5\u72B6\u6001\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002":"Installation timed out. Check the current installation before retrying.","\u66F4\u65B0\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"The update request failed. Try again.","\u66F4\u65B0\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002":"The update service returned an unrecognized response.","\u5F53\u524D Host \u4E0D\u652F\u6301\u66F4\u65B0\u63A5\u53E3\uFF0C\u8BF7\u5148\u624B\u52A8\u66F4\u65B0\u63D2\u4EF6\u5E76\u91CD\u542F\u3002":"This Host does not support the update API. Update the plugin manually and restart first.","\u5173\u95ED\u7A97\u53E3\u4E0D\u4F1A\u53D6\u6D88\u5B89\u88C5\u3002\u8BF7\u52FF\u540C\u65F6\u5728\u5176\u4ED6\u7A97\u53E3\u7BA1\u7406\u6B64 profile \u7684\u63D2\u4EF6\u3002":"Closing this window does not cancel installation. Do not manage this profile\u2019s plugins in another window at the same time.","\u9875\u9762\u7248\u672C\u4E0E\u8FD0\u884C\u7248\u672C\u4E0D\u540C\uFF0C\u8BF7\u624B\u52A8\u5237\u65B0\u9875\u9762\uFF1B\u82E5\u4ECD\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u624B\u52A8\u91CD\u542F Harness \u6216 Desktop\u3002":"The page and running versions differ. Refresh the page manually; if they still differ, manually restart Harness or Desktop.","\u8BF7\u5728\u673A\u5668\u4EBA\u7A7A\u95F2\u65F6\u5B89\u88C5\uFF1B\u5B89\u88C5\u4F1A\u4FEE\u6539\u5F53\u524D profile \u7684\u4F9D\u8D56\uFF0C\u5B8C\u6210\u540E\u9700\u624B\u52A8\u91CD\u542F\u3002":"Install while bots are idle. This changes the current profile\u2019s dependencies and requires a manual restart afterward.","AI Office":"AI Office","\uFF08\u5B9E\u9A8C\u529F\u80FD\uFF09":"(Experimental)","AI Office \u8BBE\u7F6E":"AI Office settings","AI Office \u8BBE\u7F6E\u9875\u7F3A\u5C11 RPC \u8FDE\u63A5":"AI Office settings are missing an RPC connection","\u6B63\u5728\u8BFB\u53D6 AI Office Connector\u2026":"Loading AI Office Connector\u2026","\u672C\u673A\u4E3B\u52A8\u8FDE\u63A5\u516C\u7F51 Office\uFF1BHarness \u4E0D\u5F00\u653E\u7AEF\u53E3\u3002\u534F\u8BAE Hook \u56FA\u5B9A\u4E3A ":"This machine connects outward to the public Office; Harness exposes no port. Protocol hooks: ",\u5C1A\u672A\u914D\u7F6E:"Not configured","\u5DF2\u8FDE\u63A5 Office":"Connected to Office",\u5DF2\u914D\u7F6E:"Configured",\u7B49\u5F85\u91CD\u8FDE:"Waiting to reconnect",\u51ED\u636E\u7F3A\u5931:"Credential missing",\u6700\u8FD1\u5FC3\u8DF3:"Last heartbeat",\u6700\u8FD1\u4E8B\u4EF6:"Last event",\u91CD\u8FDE\u6B21\u6570:"Reconnects","\u8FD0\u884C Job":"Running Jobs","\u5B8C\u6210 Job":"Completed Jobs",\u5C1A\u65E0:"None yet",\u8BBE\u5907\u8FDE\u63A5:"Device connection","Token \u53EA\u5199\u5165\u672C\u673A\u51ED\u636E\u5B58\u50A8":"Token is written only to the local credential store","\u7C98\u8D34 Office \u4E00\u6B21\u6027\u51ED\u636E":"Paste the one-time Office credential","\u5DF2\u5B89\u5168\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u6301\u4E0D\u53D8":"Stored securely; leave blank to keep it",\u6700\u5927\u5E76\u53D1:"Max concurrency","Heartbeat \u79D2\u6570":"Heartbeat seconds","Workspace \u6620\u5C04":"Workspace mappings","\u6BCF\u884C alias=/\u672C\u673A/\u7EDD\u5BF9\u8DEF\u5F84\uFF1BOffice \u53EA\u80FD\u770B\u5230 alias\u3002":"One alias=/local/absolute/path per line; Office sees only aliases.","Instruction Preset \u6620\u5C04":"Instruction preset mappings","\u6BCF\u884C alias=\u6307\u4EE4\uFF1B\u65B0\u589E preset \u4E0D\u9700\u8981\u6539 Office \u4EE3\u7801\u3002":"One alias=instruction per line; new presets require no Office code change.",\u4FDD\u5B58\u5E76\u8FDE\u63A5:"Save and connect",\u6D4B\u8BD5\u8FDE\u63A5:"Test connection","\u6D4B\u8BD5\u4E2D\u2026":"Testing\u2026",\u91CD\u65B0\u8FDE\u63A5:"Reconnect",\u79FB\u9664\u8FDE\u63A5:"Remove connection","\u8FDE\u63A5\u6D4B\u8BD5\u901A\u8FC7\u3002":"Connection test passed.","\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002":"Configuration saved.","\u534F\u8BAE Hook \u9884\u89C8":"Protocol hook preview","\u7531 Base URL \u81EA\u52A8\u6D3E\u751F\uFF0C\u4E0D\u5355\u72EC\u586B\u5199":"Derived from Base URL; no separate input","Base URL \u65E0\u6548":"Invalid Base URL","Office Hook \u5C1A\u672A\u90E8\u7F72\u65F6\uFF0C\u914D\u7F6E\u4F1A\u5B89\u5168\u4FDD\u5B58\u5E76\u81EA\u52A8\u91CD\u8BD5\uFF1B\u51FA\u73B0 HTTP 404 \u4EE3\u8868\u534F\u8BAE\u7AEF\u70B9\u5F85\u4E0A\u7EBF\uFF0C\u4E0D\u4EE3\u8868 Harness \u6545\u969C\u3002":"Configuration is saved and retried while Office hooks are unavailable; HTTP 404 means the protocol endpoint is pending, not a Harness failure.","Workspace \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each workspace mapping must use alias=value","Instruction Preset \u6620\u5C04\u6BCF\u884C\u5FC5\u987B\u4F7F\u7528 alias=value":"Each instruction preset mapping must use alias=value","action-items=\u8F6C\u6362\u4E3A\u8D1F\u8D23\u4EBA\u3001\u622A\u6B62\u548C\u9A8C\u6536\u660E\u786E\u7684\u5DE5\u5355":"action-items=Turn this into accountable tasks with deadlines and acceptance criteria","AI Office \u62D2\u7EDD\u4E86 Device Token\u3002":"AI Office rejected the Device Token.","AI Office Connector Hook \u5C1A\u672A\u5C31\u7EEA\u3002":"AI Office Connector hooks are not available yet.","AI Office Connector \u534F\u8BAE\u7248\u672C\u4E0D\u517C\u5BB9\u3002":"The AI Office Connector protocol is incompatible.","\u672C\u673A\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE AI Office\u3002":"AI Office cannot currently be reached from this machine.","AI Office \u8FDE\u63A5\u5DF2\u4E2D\u65AD\u3002":"The AI Office connection was interrupted.","\u5E2E\u52A9\u4E0E\u53CD\u9988 \xB7 \u524D\u5F80 GitHub":"Help & feedback \xB7 Open GitHub","\u8BF7\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u9875\u9762\u4F1A\u5728\u5F53\u524D\u7AEF\u53E3\u91CD\u65B0\u6253\u5F00\uFF0C\u673A\u5668\u4EBA\u914D\u7F6E\u4E0D\u4F1A\u6539\u53D8\u3002":"The page will reopen on the current port. Your bot configuration will not change.","\u4F7F\u7528 localhost \u91CD\u65B0\u6253\u5F00":"Reopen with localhost","\u5F53\u524D\u5730\u5740\u4E0E\u6D4F\u89C8\u5668\u7684\u672C\u673A\u8BF7\u6C42\u6821\u9A8C\u4E0D\u517C\u5BB9\u3002\u8BF7\u4F7F\u7528\u4E0A\u65B9\u6309\u94AE\u6539\u7528 localhost \u91CD\u65B0\u6253\u5F00\u3002":"This address is incompatible with the browser\u2019s local-request checks. Use the button above to reopen with localhost.",\u5FAE\u4FE1:"WeChat",\u98DE\u4E66:"Feishu",\u9489\u9489:"DingTalk",\u4F01\u4E1A\u5FAE\u4FE1:"WeCom",\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeChat bot",\u98DE\u4E66\u673A\u5668\u4EBA:"Feishu bot",\u9489\u9489\u673A\u5668\u4EBA:"DingTalk bot",\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA:"WeCom bot",QQ\u673A\u5668\u4EBA:"QQ bot",WhatsApp\u673A\u5668\u4EBA:"WhatsApp bot",WhatsApp\u8D26\u53F7:"WhatsApp account",\u5FAE\u4FE1\u8BBE\u7F6E:"WeChat settings",\u98DE\u4E66\u673A\u5668\u4EBA\u8BBE\u7F6E:"Feishu bot settings",\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F:"Group response mode","\u4EC5\u5728 @\u673A\u5668\u4EBA\u65F6\u54CD\u5E94\uFF08\u63A8\u8350\uFF09":"Only respond when @mentioned (recommended)",\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F:"Respond to all group messages","\u54CD\u5E94\u6240\u6709\u7FA4\u6D88\u606F\uFF08\u9700\u98DE\u4E66\u654F\u611F\u6743\u9650\uFF09":"Respond to all group messages (requires a sensitive Feishu scope)",\u91CD\u65B0\u6388\u6743:"Reauthorize",\u53BB\u6388\u6743:"Authorize",\u91CD\u65B0\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Reauthorize group-message permission",\u6388\u6743\u7FA4\u6D88\u606F\u6743\u9650:"Authorize group-message permission","\u6B63\u5728\u51C6\u5907\u6388\u6743\u2026":"Preparing authorization\u2026","\u6B63\u5728\u51C6\u5907\u2026":"Preparing\u2026","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u7FA4\u6D88\u606F\u6743\u9650\u5DF2\u5F00\u901A\uFF0C\u518D\u6B21\u5207\u6362\u65E0\u9700\u6388\u6743\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. The group-message permission is already granted, so switching again needs no authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002\u9009\u62E9\u5168\u90E8\u6D88\u606F\u540E\u4F1A\u6253\u5F00\u98DE\u4E66\u5B98\u65B9\u6388\u6743\u6D41\u7A0B\u3002":"Direct messages always work; group chats require an explicit @mention of this bot. Selecting all messages opens the official Feishu authorization flow.","\u5DF2\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"The \u201CRead all messages in associated group chat\u201D scope (im:message.group_msg) is granted; the bot processes every visible group message.","\u5C1A\u672A\u786E\u8BA4\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF0C\u8BF7\u5B8C\u6210\u98DE\u4E66\u6388\u6743\u3002":"The \u201CRead all messages in associated group chat\u201D scope has not been confirmed. Complete Feishu authorization.","\u79C1\u804A\u59CB\u7EC8\u54CD\u5E94\uFF1B\u7FA4\u804A\u4EC5\u5904\u7406\u660E\u786E @\u5F53\u524D\u673A\u5668\u4EBA\u7684\u6D88\u606F\u3002":"Direct messages always work; group chats require an explicit @mention of this bot.","\u9700\u5728\u98DE\u4E66\u4E3A\u8BE5\u673A\u5668\u4EBA\u5F00\u901A\u201C\u83B7\u53D6\u7FA4\u7EC4\u4E2D\u6240\u6709\u6D88\u606F\u201D\u6743\u9650\uFF08im:message.group_msg\uFF09\uFF1B\u5F00\u901A\u540E\uFF0C\u673A\u5668\u4EBA\u4F1A\u5904\u7406\u7FA4\u804A\u4E2D\u7684\u6240\u6709\u53EF\u89C1\u6D88\u606F\u3002":"Grant this bot the \u201CRead all messages in associated group chat\u201D Feishu scope (im:message.group_msg); once granted, it will process every visible group message.","\u7FA4\u804A\u54CD\u5E94\u65B9\u5F0F\u4FEE\u6539\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not update the group response mode. Try again.","\u7FA4\u6D88\u606F\u6743\u9650\u6388\u6743\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not authorize group-message permission. Try again.",\u9489\u9489\u8BBE\u7F6E:"DingTalk settings",\u4F01\u4E1A\u5FAE\u4FE1\u8BBE\u7F6E:"WeCom settings",\u626B\u7801\u63A5\u5165\u673A\u5668\u4EBA:"Scan QR code",\u6B63\u5728\u63A5\u5165:"Connecting",\u624B\u52A8\u63A5\u5165:"Manual setup",\u6536\u8D77\u51ED\u636E:"Hide credentials",\u6536\u8D77\u63A5\u5165:"Hide setup",\u63A5\u5165\u673A\u5668\u4EBA:"Connect bot",\u5F00\u59CB\u63A5\u5165:"Start setup",\u5728\u7EBF:"online",\u8FD0\u884C\u6B63\u5E38:"Connected",\u6B63\u5728\u8FDE\u63A5:"Connecting","\u6B63\u5728\u8FDE\u63A5\u2026":"Connecting\u2026",\u8FDE\u63A5\u672A\u5C31\u7EEA:"Not connected",\u8FDE\u63A5\u4E2D:"Connecting",\u8FDE\u63A5\u4E2D\u65AD:"Disconnected",\u9700\u8981\u5904\u7406:"Needs attention",\u72B6\u6001\u672A\u77E5:"Unknown status",\u79BB\u7EBF:"Offline",\u5DF2\u65AD\u5F00:"Disconnected",\u6D88\u606F\u901A\u9053:"Message channel",\u67E5\u770B\u6D88\u606F\u901A\u9053\u8BF4\u660E:"View message channel details",\u6700\u8FD1\u68C0\u67E5:"Last checked",\u6700\u8FD1\u4E00\u6761\u6D88\u606F\u5904\u7406\u5931\u8D25:"Latest message failed",\u9519\u8BEF\u7801:"Code",\u53C2\u8003\u53F7:"Reference",\u5F53\u524D\u5DE5\u4F5C\u533A:"Current workspace",\u9009\u62E9\u76EE\u5F55:"Choose folder",\u9009\u62E9\u673A\u5668\u4EBA\u5DE5\u4F5C\u533A\u76EE\u5F55:"Select bot workspace folder",\u5F53\u524D\u76EE\u5F55:"Current folder",\u4E3B\u76EE\u5F55:"Home",\u76F4\u63A5\u8F93\u5165\u8DEF\u5F84:"Enter a path directly","\u652F\u6301 Windows \u76D8\u7B26\u3001UNC \u4E0E POSIX \u7EDD\u5BF9\u8DEF\u5F84\u3002":"Supports Windows drives, UNC paths, and POSIX absolute paths.","\u8F93\u5165 Host \u4E0A\u7684\u5B8C\u6574\u7EDD\u5BF9\u8DEF\u5F84":"Enter a full absolute path on the Host",\u524D\u5F80:"Go","\u8BFB\u53D6\u4E2D\u2026":"Loading\u2026","\u6B63\u5728\u51C6\u5907\u76EE\u5F55\u9009\u62E9\u5668\u2026":"Preparing folder picker\u2026","\u6B63\u5728\u8BFB\u53D6\u76EE\u5F55\u2026":"Loading folders\u2026","\u8FD9\u4E2A\u76EE\u5F55\u4E2D\u6CA1\u6709\u5B50\u6587\u4EF6\u5939\u3002":"This folder has no subfolders.","\u6B64\u76EE\u5F55\u7684\u5B50\u6587\u4EF6\u5939\u8FC7\u591A\uFF0C\u4EC5\u663E\u793A\u524D\u4E00\u90E8\u5206\u3002":"This folder has too many subfolders; only the first group is shown.","\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not load the folder. Try again.",\u91CD\u8BD5:"Retry",\u663E\u793A\u9690\u85CF\u6587\u4EF6\u5939:"Show hidden folders","\u5207\u6362\u540E\u4F1A\u6E05\u9664\u8FD9\u4E2A\u673A\u5668\u4EBA\u7684\u65E7\u4F1A\u8BDD\u6620\u5C04\u3002":"Switching clears this bot\u2019s previous session mappings.","\u5207\u6362\u4E2D\u2026":"Switching\u2026",\u9009\u62E9\u6B64\u76EE\u5F55:"Select this folder",\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84:"Absolute workspace path","/\u7EDD\u5BF9\u8DEF\u5F84/\u5230/\u5DE5\u4F5C\u533A":"/absolute/path/to/workspace",\u4FEE\u6539:"Change",\u4FDD\u5B58:"Save",\u4E0A\u4E0B\u6587\u589E\u5F3A:"Context enhancement",\u672A\u5F00\u542F:"Not enabled",\u4EC5\u7FA4\u804A:"Groups only",\u4EC5\u79C1\u804A:"Direct only",\u7FA4\u804A\u548C\u79C1\u804A:"Groups and direct",\u5173\u95ED\u5F39\u7A97:"Close dialog",\u67E5\u770B\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BF4\u660E:"View context enhancement details",\u4E0A\u4E0B\u6587\u589E\u5F3A\u8303\u56F4:"Context enhancement scope",\u542F\u7528\u8303\u56F4:"Enable in",\u542F\u7528:"Enabled","\uFF08\u5F53\u524D\u6E20\u9053\u4E0D\u652F\u6301\u7FA4\u804A\uFF09":"(This channel does not support group chats)",\u6765\u6E90\u5B57\u6BB5:"Source fields",\u67E5\u770B\u6765\u6E90\u5B57\u6BB5\u8BF4\u660E:"View source field details",\u67E5\u770B\u7FA4\u804A\u6765\u6E90\u5B57\u6BB5\u8BF4\u660E:"View group source field details",\u67E5\u770B\u79C1\u804A\u6765\u6E90\u5B57\u6BB5\u8BF4\u660E:"View direct source field details",\u6E20\u9053:"Channel",\u4F1A\u8BDD\u7C7B\u578B:"Conversation type",\u53D1\u9001\u8005\u6807\u8BC6:"Sender ID",\u53D1\u9001\u8005\u6635\u79F0:"Sender name",\u67E5\u770B\u53D1\u9001\u8005\u6635\u79F0\u5B57\u6BB5\u8BF4\u660E:"View sender name field details",\u67E5\u770B\u7FA4\u804A\u53D1\u9001\u8005\u6635\u79F0\u5B57\u6BB5\u8BF4\u660E:"View group sender name field details",\u67E5\u770B\u79C1\u804A\u53D1\u9001\u8005\u6635\u79F0\u5B57\u6BB5\u8BF4\u660E:"View direct sender name field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u5F53\u524D\u6D88\u606F\u6CA1\u6709\u53D1\u9001\u8005\u6635\u79F0\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 senderName\u3002":"This field is not available on every channel. If the current message has no sender name, omits senderName even when the field is selected.",\u4F1A\u8BDD\u6807\u9898:"Conversation title",\u67E5\u770B\u7FA4\u804A\u4F1A\u8BDD\u6807\u9898\u5B57\u6BB5\u8BF4\u660E:"View group conversation title field details",\u67E5\u770B\u79C1\u804A\u4F1A\u8BDD\u6807\u9898\u5B57\u6BB5\u8BF4\u660E:"View direct conversation title field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u9489\u9489\u7FA4\u804A\u4F1A\u5E26\u4E0A\u7FA4\u540D\u3002\u5F53\u524D\u6D88\u606F\u6CA1\u6709\u4F1A\u8BDD\u6807\u9898\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 conversationTitle\u3002":"This field is not available on every channel. DingTalk group chats include the group name. If the current message has no conversation title, omits conversationTitle even when the field is selected.",\u4F1A\u8BDD\u6807\u8BC6:"Chat ID",\u67E5\u770B\u7FA4\u804A\u4F1A\u8BDD\u6807\u8BC6\u5B57\u6BB5\u8BF4\u660E:"View group chat ID field details",\u67E5\u770B\u79C1\u804A\u4F1A\u8BDD\u6807\u8BC6\u5B57\u6BB5\u8BF4\u660E:"View direct chat ID field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u4F1A\u8BDD\u6807\u8BC6\u7528\u4E8E\u533A\u5206\u4E0D\u540C\u7684\u7FA4\u7EC4\u6216\u79C1\u804A\uFF0C\u98DE\u4E66\u7FA4\u804A\u4F1A\u5E26\u4E0A\u7FA4 ID\u3002\u5F53\u524D\u6D88\u606F\u6CA1\u6709\u4F1A\u8BDD\u6807\u8BC6\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 chatId\u3002":"This field is not available on every channel. The chat ID distinguishes different groups or direct chats, and Feishu group chats include the group ID. If the current message has no chat ID, omits chatId even when the field is selected.",\u8BDD\u9898\u6807\u8BC6:"Topic ID",\u67E5\u770B\u7FA4\u804A\u8BDD\u9898\u6807\u8BC6\u5B57\u6BB5\u8BF4\u660E:"View group topic ID field details",\u67E5\u770B\u79C1\u804A\u8BDD\u9898\u6807\u8BC6\u5B57\u6BB5\u8BF4\u660E:"View direct topic ID field details","\u8BE5\u5B57\u6BB5\u4E0D\u662F\u6BCF\u4E2A\u6E20\u9053\u90FD\u80FD\u63D0\u4F9B\u3002\u98DE\u4E66\u8BDD\u9898\u7FA4\u7684\u6D88\u606F\u4F1A\u5E26\u4E0A\u8BDD\u9898 ID\uFF0C\u7528\u4E8E\u533A\u5206\u540C\u4E00\u7FA4\u7EC4\u5185\u7684\u4E0D\u540C\u8BDD\u9898\uFF1B\u5F53\u524D\u6D88\u606F\u4E0D\u5728\u8BDD\u9898\u4E2D\u65F6\uFF0C\u5373\u4F7F\u5DF2\u9009\u62E9\u8BE5\u5B57\u6BB5\uFF0C \u4E2D\u4E5F\u4F1A\u7701\u7565 threadId\u3002":"This field is not available on every channel. Messages in a Feishu topic chat carry the topic ID, which distinguishes different topics inside the same group. If the current message is not inside a topic, omits threadId even when the field is selected.",\u673A\u5668\u4EBA\u6807\u8BC6:"Bot ID",\u589E\u5F3A\u63D0\u793A\u8BCD:"Guidance",\u67E5\u770B\u589E\u5F3A\u63D0\u793A\u8BCD\u4F7F\u7528\u8BF4\u660E:"View guidance instructions",\u67E5\u770B\u7FA4\u804A\u589E\u5F3A\u63D0\u793A\u8BCD\u4F7F\u7528\u8BF4\u660E:"View group guidance instructions",\u67E5\u770B\u79C1\u804A\u589E\u5F3A\u63D0\u793A\u8BCD\u4F7F\u7528\u8BF4\u660E:"View direct guidance instructions",\u4F7F\u7528\u8BF4\u660E:"How to use","\u7528\u4E8E\u544A\u8BC9\u6A21\u578B\u5982\u4F55\u4F7F\u7528 \u4E2D\u5DF2\u9009\u62E9\u7684\u6765\u6E90\u5B57\u6BB5\u3002\u53EA\u586B\u5199\u6B63\u6587\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u6DFB\u52A0 \u6210\u5BF9\u6807\u7B7E\u3002":"Tell the model how to use the selected fields in . Enter only the body; the plugin adds paired tags.",\u751F\u6548\u89C4\u5219:"Behavior",\u9690\u79C1\u63D0\u793A:"Privacy",\u4F7F\u7528\u793A\u4F8B:"Example","\u4EC5\u4F9D\u636E\u5F53\u524D\u6D88\u606F\u7684 \u4E2D\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\u7406\u89E3\u6765\u6E90\uFF1B\u6CA1\u6709\u63D0\u4F9B\u7684\u5B57\u6BB5\u4E0D\u8981\u731C\u6D4B\u6216\u8865\u5168\u3002\nconversationType\u662F\u7FA4\u804A\u65F6\u56DE\u590D\u4E25\u8083\u4E00\u70B9\uFF0CconversationType\u662F\u79C1\u804A\u65F6\u56DE\u590D\u4E00\u5B9A\u8981\u5E7D\u9ED8\u641E\u7B11\uFF0C\u50CF\u5468\u661F\u9A70\u7684\u7535\u5F71\u4E00\u6837\u641E\u7B11":`Understand the source only from fields actually present in for the current message; do not guess or fill in missing fields. When conversationType is group, reply more seriously. When conversationType is direct, make the reply humorous and funny.`,"\u4EC5\u4F9D\u636E\u5F53\u524D\u6D88\u606F\u7684 \u4E2D\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\u7406\u89E3\u6765\u6E90\uFF1B\u6CA1\u6709\u63D0\u4F9B\u7684\u5B57\u6BB5\u4E0D\u8981\u731C\u6D4B\u6216\u8865\u5168\u3002\n\u5F53\u524D\u6D88\u606F\u6765\u81EA\u7FA4\u804A\uFF0C\u8BF7\u4F7F\u7528\u4E25\u8083\u3001\u514B\u5236\u3001\u7B80\u6D01\u7684\u8868\u8FBE\u65B9\u5F0F\u3002":`Understand the source only from fields actually present in for the current message; do not guess or fill in missing fields. This message is from a group chat. Use a serious, restrained, and concise style.`,"\u4EC5\u4F9D\u636E\u5F53\u524D\u6D88\u606F\u7684 \u4E2D\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\u7406\u89E3\u6765\u6E90\uFF1B\u6CA1\u6709\u63D0\u4F9B\u7684\u5B57\u6BB5\u4E0D\u8981\u731C\u6D4B\u6216\u8865\u5168\u3002\n\u5F53\u524D\u6D88\u606F\u6765\u81EA\u79C1\u804A\uFF0C\u53EF\u4EE5\u4F7F\u7528\u66F4\u8F7B\u677E\u3001\u5E7D\u9ED8\u3001\u8BE6\u7EC6\u7684\u8868\u8FBE\u65B9\u5F0F\u3002":`Understand the source only from fields actually present in for the current message; do not guess or fill in missing fields. @@ -395,7 +395,7 @@ ${s}`,r=[s]):(A=g,r.push(s))}return a.push({markdown:A,plain:a.length===0?A:r.jo ${c}`;d.length>i?(A.length>0&&a.push({markdown:A,plain:A}),A=c):A=d;return}r();let I=c;for(;I.length>i;){let d=IG(I,i),B=I.slice(0,d);a.push({markdown:B,plain:B}),I=I.slice(d)}A=I},g=c=>{let I=c;for(;I.length>i;){r();let d=IG(I,i),B=I.slice(0,d);a.push({markdown:B,plain:B}),I=I.slice(d)}s(I)};for(let c=0;cc.length>0||I.length>0)}function $Ge(){let n=Date.now()%1e8,t=Math.floor(Math.random()*65536);return(n^t)%65536}function eFe(n){return n instanceof UGe&&n.httpStatus>=400&&n.httpStatus<500&&KGe.has(Number(n.bizCode))}function hZ(n,t,o,i){return typeof n?.send=="function"?n.send({target:t,msgType:0,content:o,extra:{msg_seq:i}}):n.sendText(t,o)}async function CZ(n,t,o,{logger:i}={}){let e=XGe(o),a=[],A=$Ge(),r=t?.msgId?xGe[t.scope]:null,s=r!==null&&e.length>r,g=s?r-1:e.length,c=t?.msgId?{scope:t.scope,targetId:t.targetId}:t,I=!1,d=async()=>{if(!(I||!t?.msgId)){I=!0;try{a.push(await hZ(n,t,YGe(),A+e.length&65535))}catch(B){i?.warn?.("[dsh-im:qq] unable to send partial reply notice:",B)}}};for(let[B,f]of e.entries()){let Q=A+B&65535,y=s&&B>=g?c:t;if(typeof n?.send=="function")try{a.push(await n.send({target:y,msgType:2,markdown:{content:f.markdown},extra:{msg_seq:Q}}));continue}catch(m){if(!eFe(m)){if(i?.warn?.("[dsh-im:qq] markdown delivery outcome is uncertain; refusing a duplicate-prone retry:",m),a.length===0)throw m;await d();break}i?.warn?.("[dsh-im:qq] markdown delivery failed; retrying as plain text:",m)}if(f.plain.length!==0)try{a.push(await hZ(n,y,f.plain,Q))}catch(m){if(a.length===0)throw m;await d();break}}return a}function $S(){return w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")}var ew=12e4,AFe=Object.freeze([".myqcloud.com",".qpic.cn",".qq.com",".qq.com.cn",".tencentcos.com",".ugcimg.cn"]),tFe=/\.(?:gif|jpe?g|png|webp)$/i;function rFe(){return[w("QQ \u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` +`);f.length<=i?s(f):(r(),a.push(...ZGe(B,i))),c=d;continue}g(e[c]),c+=1}return r(),a.filter(({markdown:c,plain:I})=>c.length>0||I.length>0)}function $Ge(){let n=Date.now()%1e8,t=Math.floor(Math.random()*65536);return(n^t)%65536}function eFe(n){return n instanceof UGe&&n.httpStatus>=400&&n.httpStatus<500&&KGe.has(Number(n.bizCode))}function hZ(n,t,o,i){return typeof n?.send=="function"?n.send({target:t,msgType:0,content:o,extra:{msg_seq:i}}):n.sendText(t,o)}async function CZ(n,t,o,{logger:i}={}){let e=XGe(o),a=[],A=$Ge(),r=t?.msgId?xGe[t.scope]:null,s=r!==null&&e.length>r,g=s?r-1:e.length,c=t?.msgId?{scope:t.scope,targetId:t.targetId}:t,I=!1,d=async()=>{if(!(I||!t?.msgId)){I=!0;try{a.push(await hZ(n,t,YGe(),A+e.length&65535))}catch(B){i?.warn?.("[dsh-im:qq] unable to send partial reply notice:",B)}}};for(let[B,f]of e.entries()){let Q=A+B&65535,y=s&&B>=g?c:t;if(typeof n?.send=="function")try{a.push(await n.send({target:y,msgType:2,markdown:{content:f.markdown},extra:{msg_seq:Q}}));continue}catch(m){if(!eFe(m)){if(i?.warn?.("[dsh-im:qq] markdown delivery outcome is uncertain; refusing a duplicate-prone retry:",m),a.length===0)throw m;await d();break}i?.warn?.("[dsh-im:qq] markdown delivery failed; retrying as plain text:",m)}if(f.plain.length!==0)try{a.push(await hZ(n,y,f.plain,Q))}catch(m){if(a.length===0)throw m;await d();break}}return a}function $S(){return w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")}var ew=12e4,AFe=Object.freeze([".myqcloud.com",".qpic.cn",".qq.com",".qq.com.cn",".tencentcos.com",".ugcimg.cn"]),tFe=/\.(?:gif|jpe?g|png|webp)$/i;function rFe(){return[w("QQ \u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `)}function aFe(n){return`${n.kind}:${n.kind==="group"?n.groupOpenid:n.senderId}`}function iFe(n,t){return n?.kind==="group"||t==="*"||n?.senderId===t}function JC(n){return typeof n?.content=="string"?n.content.trim():""}function pG(n){let t=Ma(n?.content_type??n?.contentType);return t?t.split(";",1)[0].trim().toLowerCase():null}function hG(n){return pG(n)?.startsWith("image/")===!0||tFe.test(Ma(n?.filename)??"")}function eh(n){return Array.isArray(n?.attachments)&&n.attachments.some(hG)}function Dl(n){return Array.isArray(n?.attachments)&&n.attachments.some(t=>!hG(t))}function BZ(n){let t=pG(n);return t?.startsWith("image/")?"image":t?.startsWith("audio/")?"audio":t?.startsWith("video/")?"video":"file"}function QZ(n){let t=Ma(n?.refMsgIdx);if(!t)return null;let o=Array.isArray(n?.msgElements)?n.msgElements[0]:null,i=Array.isArray(o?.attachments)?o.attachments:[],e=i.map(r=>{let s=Ma(r?.filename);return{kind:BZ(r),...s?{name:s}:{}}}),A=i.filter(r=>BZ(r)==="audio").map(r=>Ma(r?.asr_refer_text)).filter(Boolean).join(` `)||Ma(o?.content);return{messageId:t,...A?{content:A}:{},...e.length>0?{attachments:e}:{},...!A&&e.length===0?{unavailableReason:"not-delivered"}:{}}}async function oFe(n,{fetchImpl:t,signal:o}){let i=n.startsWith("//")?`https:${n}`:n,e=await t(new URL(i),{method:"GET",signal:o,redirect:"follow"});if(!e?.ok)throw await e?.body?.cancel?.().catch?.(()=>{}),new Error(`QQ file download failed with HTTP ${e?.status??"unknown"}`);return Buffer.from(await e.arrayBuffer())}function fZ(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[],i=[];for(let a of n?.attachments??[]){let A=Ma(a?.url),r=Ma(a?.filename)??void 0,s=pG(a),g=Number(a?.size);if(hG(a)){o.push({...r?{name:r}:{},...s?.startsWith("image/")?{mediaType:s}:{},...Number.isFinite(g)&&g>=0?{size:g}:{},load:({signal:c,maxBytes:I})=>{if(!A)throw new Error("QQ image attachment has no download URL");return bo(A,{fetchImpl:t,signal:c,maxBytes:I,allowedHosts:AFe})}});continue}i.push({name:r??(i.length===0?"file":`file-${i.length+1}`),...s?.includes("/")?{mediaType:s}:{},...Number.isFinite(g)&&g>=0?{size:g}:{},load:({signal:c}={})=>{if(!A)throw new Error("QQ file attachment has no download URL");return oFe(A,{fetchImpl:t,signal:c})}})}let e=QZ(n);return{content:JC(n),images:o,files:i,...e?{replyTo:e}:{}}}function Ma(n){return typeof n=="string"&&n.trim()?n.trim():null}function nFe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");if(t?.name==="UploadDailyLimitExceededError")return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u4ECA\u65E5\u6587\u4EF6\u4E0A\u4F20\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5F53\u524D QQ \u673A\u5668\u4EBA\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D QQ \u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0CQQ \u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB QQ \u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46 QQ \u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7 QQ \u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function sFe(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):n}function yZ(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;if(n?.name==="UploadDailyLimitExceededError"){let e=new Error("QQ daily file upload limit exceeded",{cause:n});return e.name=n.name,e.code="artifact-rate-limited",e}let o=Number(n?.httpStatus),i=new Error("QQ file delivery failed",{cause:n});return o===401||o===403?i.code="artifact-permission-required":o===413?i.code="artifact-too-large":o===429?i.code="artifact-rate-limited":[400,404,405,406,410,415,422].includes(o)?i.code="artifact-provider-rejected":i.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",i}function EG(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function mZ(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,EG(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}async function gFe(n,t,o,{signal:i,timeoutMs:e=ew}={}){if(i?.throwIfAborted(),typeof n?.sendImage!="function"){let a=new Error("QQ image delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendImage(t,{buffer:o.bytes},{onProgress:()=>i?.throwIfAborted()});return yn(o,r),await mZ(r,A)}catch(a){throw i?.aborted?EG(i):yZ(a,{dispatched:!0})}}async function cFe(n,t,o,{signal:i,timeoutMs:e=ew}={}){if(i?.throwIfAborted(),typeof n?.sendFile!="function"){let a=new Error("QQ file delivery is unavailable");throw a.code="artifact-provider-unavailable",a}try{let a=AbortSignal.timeout(e),A=i?AbortSignal.any([i,a]):a,r=n.sendFile(t,{buffer:o.bytes},{fileName:o.fileName,onProgress:()=>i?.throwIfAborted()});return yn(o,r),await mZ(r,A)}catch(a){throw i?.aborted?EG(i):yZ(a,{dispatched:!0})}}function IFe(n,t){return t.questions[t.index]&&Ma(n?.senderId)===t.actor&&(n.kind!=="group"||n.rawEventType==="GROUP_AT_MESSAGE_CREATE")&&!eh(n)&&!Dl(n)&&Ma(JC(n))}function uG(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var Aw=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g=new Map;#I=new Map;#p=new Map;#h=new Map;#u=new Set;#C=new Set;#B;#f=new ki;constructor({bot:t,ownerUserOpenid:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,status:r=uG(),logger:s=console,replyTimeoutMs:g=6e5,signal:c,fetchImpl:I=fetch,fileUploadTimeoutMs:d=ew}){if(!t||typeof t.sendText!="function")throw new TypeError("QQ bot client is required");if(!o)throw new TypeError("QQ scanner identity is required");if(!i||!e)throw new TypeError("Harness client and state store are required");if(typeof I!="function")throw new TypeError("fetchImpl must be a function");if(!Number.isInteger(d)||d<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#d=I,this.#c=Math.min(d,ew),this.#B=new Mi({label:"qq",logger:s})}get status(){return structuredClone(this.#i)}accept(t){if(this.#s?.aborted)return Promise.resolve();let o=Ma(t?.messageId),i=Ma(t?.senderId);if(!o||!i||t?.senderIsBot===!0||!["c2c","group"].includes(t?.kind)||this.#r.hasSeen(o)||this.#h.has(o))return Promise.resolve();let e=aFe(t),a=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",A=JC(t);if(a){let d=this.#o?Da(this.#o,{conversationType:t.kind==="c2c"?"direct":"group",senderIds:i,text:A,hasImages:eh(t),hasFiles:Dl(t)}):iFe(t,this.#A)?{allowed:!0,reason:"legacy-owner"}:{allowed:!1,reason:"sender-not-allowed"};if(!d.allowed)return this.#h.set(o,null),this.#m(t,o,d)}this.#h.set(o,aa(this.#l,t.kind==="c2c"?"direct":"group")),t.kind==="c2c"&&(this.#A==="*"||i===this.#A)&&t.replyTarget?.scope==="c2c"&&Ma(t.replyTarget.targetId)===i&&Do(this.#r,t.replyTarget);let r=this.#I.get(e),s=vi(A),g=this.#f.status(e);if(s&&a&&t.kind==="group")return this.#y(t,o,{message:as()});if(t.kind==="c2c"&&(s||g.phase==="collecting")){let B=/^\/batch$/iu.test(A)&&g.phase==="idle"&&(this.#g.has(e)||r||this.#B.hasPending(e))?{handled:!0,kind:"busy",message:Ro()}:this.#f.handle(e,A,{plainText:!!A&&!eh(t)&&!Dl(t)&&!QZ(t)});if(B.handled)return B.kind==="submit"?this.#Q({...t,content:B.prompt,attachments:[]},o,e,{batchSubmission:B}):this.#y(t,o,B)}let c=xa(A)?ao:Dl(t)?null:ci(A)?Ni:Ii(A)?io:li(A)?Ri:null;if(c&&a){let d;return d=this.#S(t,o,e,A,c).catch(B=>{if(B?.code==="turn-stopped"||this.#s?.aborted)return;this.#i.lastError=B?.message??String(B);let f=tt(this.#i,B);return this.#a.error?.(`[dsh-im:qq] failed to process a command [${f.referenceId}]:`,B),this.#e.sendText(t.replyTarget,Et(f)).catch(()=>{})}).finally(()=>{this.#h.delete(o),this.#C.delete(d)}),this.#C.add(d),d}let I=this.#B.claimReply({key:e,actor:i,messageId:o,text:eh(t)||Dl(t)?"":JC(t),addressed:t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE",hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#I.has(e),send:d=>this.#e.sendText(t.replyTarget,d)});if(I){let d;return d=I.process(async()=>this.#r.hasSeen(o)?!1:(await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#h.delete(o),this.#u.delete(d)}),this.#u.add(d),d}if(r&&i!==r.actor)return this.#Q(t,o,e);if(r?.submitting||r?.claimedReplyMessageId)return this.#Q(t,o,e);if(r){IFe(t,r)&&(r.claimedReplyMessageId=o);let B=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#R(t,o,e,r)).catch(f=>this.#F(t,o,f)).finally(()=>{this.#h.delete(o),r.claimedReplyMessageId===o&&(r.claimedReplyMessageId=null),r.queue===B&&(r.queue=null)});return r.queue=B,B}return this.#Q(t,o,e)}#Q(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let s=t.kind!=="group"||t.rawEventType==="GROUP_AT_MESSAGE_CREATE"?Fd(fZ(t,{fetchImpl:this.#d}),{signal:this.#s}):void 0,c=(this.#g.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#E(t,i,{alreadyRecorded:a,preparedMessage:s,batchSubmission:A})).finally(()=>{e&&this.#h.delete(o),this.#g.get(i)===c&&this.#g.delete(i)});return this.#g.set(i,c),c}async waitForIdle(){await Promise.allSettled([...this.#g.values(),...[...this.#I.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#u,...this.#C])}async#S(t,o,i,e,a){if(this.#s?.throwIfAborted(),this.#r.hasSeen(o))return;await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString();let A=await a(e,this.#t,this.#r,i,{signal:this.#s,isDirect:t.kind==="c2c",hasImages:eh(t),hasFiles:Dl(t),pendingInteraction:this.#I.has(i)||this.#B.hasPending(i),control:{owner:this,key:i}});A?.stopped&&await Promise.allSettled([this.#N(i),this.#B.closeRoute(i)]);for(let r of A?.messages??[A?.message])r&&await this.#e.sendText(t.replyTarget,r);this.#i.lastError=null}#y(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),i.message&&await this.#e.sendText(t.replyTarget,i.message),this.#i.lastError=null)}).catch(async a=>{if(this.#s?.aborted)return;this.#i.lastError=a?.message??String(a);let A=tt(this.#i,a);this.#a.error?.(`[dsh-im:qq] failed to process a batch input message [${A.referenceId}]:`,a),await this.#e.sendText(t.replyTarget,Et(A)).catch(()=>{})}).finally(()=>{this.#h.delete(o),this.#C.delete(e)}),this.#C.add(e),e}#m(t,o,i){let e;return e=Promise.resolve().then(async()=>{this.#r.hasSeen(o)||(await this.#r.markSeen(o),i.reason==="command-not-allowed"?(this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString(),await this.#e.sendText(t.replyTarget,w(no)),this.#i.messagesReplied+=1,this.#i.lastReplyAt=new Date().toISOString()):(this.#i.messagesRejected+=1,this.#i.lastRejectedAt=new Date().toISOString()),this.#i.lastError=null)}).catch(a=>{this.#s?.aborted||(this.#i.lastError=a?.message??String(a),this.#a.error?.("[dsh-im:qq] failed to apply inbound access policy:",a))}).finally(()=>{this.#h.delete(o),this.#C.delete(e)}),this.#C.add(e),e}async#D(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await Po({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"qq-text-and-files":"qq-files",alwaysMerge:!0,channelKey:"qq",signal:this.#s,sendImage:A=>gFe(this.#e,t,A,{signal:this.#s,timeoutMs:this.#c}),sendFile:A=>cFe(this.#e,t,A,{signal:this.#s,timeoutMs:this.#c}),onFailure:(A,r)=>tt(this.#i,r,{userMessage:nFe(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#e.sendText(t,Et(s)),logger:this.#a});return this.#i.artifactsSent=(this.#i.artifactsSent??0)+a.artifactsSent,this.#i.artifactSendErrors=(this.#i.artifactSendErrors??0)+a.artifactSendErrors,{receipt:a.receipt,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#E(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){if(this.#s?.aborted)return;let A=Ma(t?.messageId),r=Ma(t?.senderId);if(!A||!r||t.senderIsBot===!0||!["c2c","group"].includes(t.kind))return;if(!i){if(this.#r.hasSeen(A))return;this.#i.messagesReceived+=1,this.#i.lastMessageAt=new Date().toISOString()}let s=i,g=async()=>{s||(await this.#r.markSeen(A),s=!0)};if(t.kind==="group"&&t.rawEventType!=="GROUP_AT_MESSAGE_CREATE")return;let c=t.replyTarget,I=e??fZ(t,{fetchImpl:this.#d}),d=I.content,B=Nt(I),f=Dt(I),Q=Hr(I),y=null,m=a===null;try{if(!d&&!B&&!f&&!Q){await this.#e.sendText(c,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u548C\u6587\u4EF6\u6D88\u606F\u3002")),await g();return}let T=d.toLowerCase();if(!B&&!f&&T==="/help"){await this.#e.sendText(c,rFe()),await g();return}if(!B&&!f&&T==="/status"){await this.#t.ensureRunning({signal:this.#s}),await this.#e.sendText(c,w("QQ \u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await g();return}if(!B&&!f&&T==="/new"){await this.#r.clearSession(o),await this.#e.sendText(c,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await g();return}let _=B||f?null:await _o(d,this.#t,o);if(_){for(let X of _.messages??[_.message])await this.#e.sendText(c,X);await g();return}let R=B||f?null:await Ti(d,this.#t,this.#r,o,{signal:this.#s});if(R){await this.#e.sendText(c,R.message),await g();return}let x=B||Q?await Go(I,{signal:this.#s}):void 0,F=this.#h.get(A),L=!1;if(F){let X=x??d;x=No(X,F,()=>({channel:"qq",senderId:r,senderName:t.kind==="group"?t.senderName:void 0,chatId:t.kind==="group"?t.groupOpenid:t.senderId})),L=x!==X}let q=[],z,H=[];try{await g(),{answer:z,artifacts:H=[]}=await _i({harness:this.#t,state:this.#r,key:o,text:d,content:x,contextEnhanced:L,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#n,signal:this.#s,control:{owner:this,key:o},progressMode:"all",onUpdate:X=>{if(X.error){let ie=(Ma(X.toolName)??w("\u5DE5\u5177")).replace(/[\r\n]+/gu," ").slice(0,80);q.push(w("\u5DE5\u5177\u8C03\u7528\u300C{name}\u300D\u672A\u6210\u529F\uFF0C\u8BF7\u68C0\u67E5\u5DE5\u5177\u914D\u7F6E\u6216\u7A0D\u540E\u91CD\u8BD5\u3002",{name:ie}))}},onInteraction:X=>this.#_(X,{key:o,actor:r,target:c,requiresMention:t.kind==="group"}),onInteractionResolved:X=>this.#O(X),files:I.files}}),a&&(this.#f.complete(o,a.token),m=!0)}finally{await Promise.allSettled([this.#N(o),this.#B.closeRoute(o)])}this.#s?.throwIfAborted();let G=sFe(z,H),V=q.length>0?`${G} @@ -410,9 +410,9 @@ ${_}`:F),await g()}catch(F){this.#a.error?.("[dsh-im:qq] failed to send the safe `,{encoding:"utf8",mode:384}),await PFe(A,this.#e),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}};var KFe="https://slack.com/api/",ZC="files.slack.com",xFe="slack.com",TZ="/files-pri/",YFe=Object.freeze([ZC]),jFe="/upload/",JFe=12e4;function bs(n){return typeof n=="string"&&n.trim()?n.trim():null}function NZ(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function VC(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function qFe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function RZ(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),Number.isInteger(t?.status)&&(n.status=t.status),n}function bl(n){let t="artifact-provider-failed",o="Slack file upload preparation failed";n?.code==="slack-file_upload_size_restricted"?(t="artifact-too-large",o="Slack rejected the result file because it is too large"):n?.code==="slack-missing-scope"?(t="artifact-permission-required",o="Slack file delivery requires the files:write scope"):n?.code?.startsWith?.("slack-")&&(t="artifact-provider-rejected",o="Slack rejected file upload preparation");let i=new Error(o,{cause:n});return i.code=t,RZ(i,n)}function zFe(n){let t=new Error("Slack file completion result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",RZ(t,n)}function VFe(n){return Number.isInteger(n)&&n>=300&&n<400}async function DG(n){try{await n?.body?.cancel?.()}catch{}}function WFe(n){let t=new URL(n);if(t.protocol!=="https:")throw new Error("Image download URL must use HTTPS");if(t.username||t.password||t.port&&t.port!=="443")throw new Error("Image download URL is not hosted by the messaging platform");if(t.hostname===xFe&&t.pathname.startsWith(TZ)&&(t.hostname=ZC),t.hostname!==ZC||!t.pathname.startsWith(TZ))throw new Error("Image download URL is not hosted by the messaging platform");return t.hash="",t}function ZFe(n){let t=new URL(n);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443"||t.hostname!==ZC||!t.pathname.startsWith(jFe))throw new Error("Slack returned an unsafe file upload URL");return t.hash="",t}function XFe(n,t){let o=n?.headers?.get?.("location");if(!o)return null;try{return new URL(o,t)}catch{return null}}function $Fe(n){let t=n?.headers?.get?.("x-oauth-scopes");return t==null?null:new Set(t.split(",").map(o=>o.trim()).filter(Boolean))}function eLe(n){return n?.protocol==="https:"&&!n.username&&!n.password&&(!n.port||n.port==="443")&&n.hostname.endsWith(".slack.com")&&n.hostname!==ZC&&n.pathname==="/"&&n.searchParams.has("redir")}function ALe(n,t){return new Promise((o,i)=>{if(t?.aborted){i(t.reason??new DOMException("Aborted","AbortError"));return}let e=setTimeout(o,n);e?.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(e),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}function Wo(n,t){let o=bs(n);if(!o||!/^[A-Z][A-Z0-9]{4,30}$/i.test(o))throw new TypeError(`Invalid Slack ${t}`);return o}function vn(n,t){let o=bs(n);if(!o)throw new TypeError(`Slack ${t} is required`);return o}function WC(n,{trim:t=!0}={}){let o=typeof n=="string"?n:"",i=t?o.trim():o;if(!i)throw new TypeError("Slack message text is required");return i.replace(/<@([A-Z0-9]+)>/gi,"@$1").replace(/]*)?>/gi,"@$1")}function tLe(n,t,o){let i=bs(t?.error)??"unknown_error",e=new Error(`Slack ${n} failed: ${i.replaceAll("_"," ")}`);return e.providerCode=i,["invalid_auth","not_authed","token_revoked","account_inactive"].includes(i)?e.code=o==="app"?"slack-invalid-app-token":"slack-invalid-bot-token":i==="missing_scope"?e.code="slack-missing-scope":i==="method_not_supported_for_channel_type"||i==="channel_type_not_supported"||i==="deprecated_endpoint"?e.code="slack-stream-unavailable":e.code=`slack-${i}`,e}function kZ(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())}function vZ(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())}var XC=class{#e;#A;#t;#r;#l=null;#o;constructor({botToken:t,appToken:o,fetchImpl:i=fetch,baseUrl:e=KFe,fileUploadTimeoutMs:a=JFe}){if(t!==void 0&&!kZ(t))throw new TypeError("Slack Bot Token is invalid");if(o!==void 0&&!vZ(o))throw new TypeError("Slack App Token is invalid");if(!t&&!o)throw new TypeError("SlackApi requires a token");if(typeof i!="function")throw new TypeError("SlackApi requires fetch");this.#e=t?.trim(),this.#A=o?.trim(),this.#t=i,this.#r=new URL(e),this.#o=qFe(a,"fileUploadTimeoutMs")}authTest(t={}){return this.#a("auth.test",{...t,tokenKind:"bot"})}openConnection(t={}){return this.#a("apps.connections.open",{...t,tokenKind:"app",body:void 0})}async fileInfo({fileId:t,signal:o}={}){let i=await this.#a("files.info",{tokenKind:"bot",signal:o,body:{file:Wo(t,"file id")}});if(!i?.file||typeof i.file!="object"||Array.isArray(i.file))throw new Error("Slack files.info returned no file object");return i.file}async getMessage({channelId:t,messageTs:o,signal:i}={}){let e=vn(o,"message timestamp"),a=await this.#a("conversations.history",{tokenKind:"bot",signal:i,body:{channel:Wo(t,"channel id"),oldest:e,latest:e,inclusive:!0,limit:1}});return Array.isArray(a?.messages)?a.messages.find(A=>String(A?.ts??"")===e)??null:null}postMessage({channelId:t,text:o,threadTs:i,signal:e}){return this.#a("chat.postMessage",{tokenKind:"bot",signal:e,body:{channel:Wo(t,"channel id"),text:WC(o),...i?{thread_ts:bs(i)}:{},mrkdwn:!0,link_names:!1,unfurl_links:!1,unfurl_media:!1}})}updateMessage({channelId:t,ts:o,text:i,signal:e}){return this.#a("chat.update",{tokenKind:"bot",signal:e,body:{channel:Wo(t,"channel id"),ts:vn(o,"message timestamp"),text:WC(i),parse:"none",link_names:!1}})}addReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#a("reactions.add",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:Wo(t,"channel id"),timestamp:vn(o,"message timestamp"),name:vn(i,"reaction name")}})}removeReaction({channelId:t,messageTs:o,emojiName:i,signal:e,timeoutMs:a}){return this.#a("reactions.remove",{tokenKind:"bot",signal:e,timeoutMs:a,retry:!1,body:{channel:Wo(t,"channel id"),timestamp:vn(o,"message timestamp"),name:vn(i,"reaction name")}})}startStream({channelId:t,threadTs:o,recipientTeamId:i,recipientUserId:e,markdownText:a,signal:A}){return this.#a("chat.startStream",{tokenKind:"bot",signal:A,body:{channel:Wo(t,"channel id"),thread_ts:vn(o,"thread timestamp"),...i?{recipient_team_id:Wo(i,"team id")}:{},...e?{recipient_user_id:Wo(e,"user id")}:{},...bs(a)?{markdown_text:WC(a)}:{}}})}appendStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#a("chat.appendStream",{tokenKind:"bot",signal:e,body:{channel:Wo(t,"channel id"),ts:vn(o,"stream timestamp"),markdown_text:WC(i,{trim:!1})}})}stopStream({channelId:t,ts:o,markdownText:i,signal:e}){return this.#a("chat.stopStream",{tokenKind:"bot",signal:e,body:{channel:Wo(t,"channel id"),ts:vn(o,"stream timestamp"),...bs(i)?{markdown_text:WC(i,{trim:!1})}:{}}})}async uploadFile({channelId:t,threadTs:o,file:i,signal:e}){if(!i||typeof i!="object"||typeof i.fileName!="string"||!i.fileName||!Buffer.isBuffer(i.bytes))throw new TypeError("A Slack file is required");if(e?.aborted)throw VC(e);let a=NZ(e,this.#o),A;try{A=await this.#a("files.getUploadURLExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#o,body:{filename:i.fileName,length:i.bytes.byteLength}})}catch(I){throw e?.aborted?VC(e):bl(I)}let r,s;try{r=vn(A?.file_id,"file id"),s=ZFe(A?.upload_url)}catch(I){throw bl(I)}let g;try{g=await this.#t(s,{method:"POST",headers:{"content-type":i.mediaType??"application/octet-stream"},body:i.bytes,signal:a,redirect:"error"})}catch(I){throw e?.aborted?VC(e):bl(I)}if(!Number.isInteger(g?.status))throw bl(new Error("Slack file upload returned an invalid response"));if(g.status!==200){await DG(g);let I=new Error(`Slack file upload failed with HTTP ${g.status}`);throw I.status=g.status,g.status===413?I.code="artifact-too-large":g.status===429?I.code="artifact-rate-limited":I.code="artifact-provider-rejected",I}await DG(g);let c;try{c={files:[{id:r,title:i.fileName}],channel_id:Wo(t,"channel id"),...o?{thread_ts:vn(o,"thread timestamp")}:{}}}catch(I){throw bl(I)}if(a.aborted)throw e?.aborted?VC(e):bl(a.reason);try{let I=await this.#a("files.completeUploadExternal",{tokenKind:"bot",signal:a,timeoutMs:this.#o,retry:!1,body:c});if(!Array.isArray(I?.files)||!I.files.some(d=>bs(d?.id)===r))throw new Error("Slack file completion did not confirm the uploaded file");return I}catch(I){throw e?.aborted?VC(e):I?.code==="slack-missing-scope"?bl(I):zFe(I)}}async downloadFile({url:t,signal:o,maxBytes:i}){return this.#i({url:t,signal:o,maxBytes:i,stream:!1})}async downloadFileStream({url:t,signal:o}){return this.#i({url:t,signal:o,stream:!0})}async#i({url:t,signal:o,maxBytes:i,stream:e}){if(!this.#e)throw new TypeError("Slack bot token is required for file download");let a=WFe(t),r={fetchImpl:async(s,g)=>{let c=await this.#t(s,g);if(!VFe(c?.status))return c;let I=XFe(c,s);if(this.#l&&!this.#l.has("files:read")||eLe(I))throw await DG(c),new ft("slack-file-access-required","Slack redirected a private file request to the workspace because file access was not granted",w("Slack \u672A\u6388\u6743\u673A\u5668\u4EBA\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u8BF7\u4E3A\u5E94\u7528\u6DFB\u52A0 files:read \u540E\u91CD\u65B0\u5B89\u88C5\uFF0C\u518D\u91CD\u65B0\u53D1\u9001\u56FE\u7247\u3002"));return c},headers:{authorization:`Bearer ${this.#e}`},signal:o,allowedHosts:YFe};return e?Vd(a,r):bo(a,{...r,maxBytes:i})}async#a(t,{tokenKind:o,body:i,signal:e,timeoutMs:a=15e3,retry:A=!0}){let r=o==="app"?this.#A:this.#e;if(!r)throw new TypeError(`Slack ${o} token is required for ${t}`);let s=t==="files.getUploadURLExternal"||t==="files.info",g;try{g=await this.#t(new URL(t,this.#r),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":i===void 0||s?"application/x-www-form-urlencoded;charset=utf-8":"application/json;charset=utf-8","user-agent":"DeepSeek-Harness-dsh-im (https://github.com/xmanrui/dsh-im, 0.2.2)"},...i===void 0?{}:{body:s?new URLSearchParams(i).toString():JSON.stringify(i)},signal:NZ(e,a),redirect:"error"})}catch(I){throw I?.name==="AbortError"||I?.name==="TimeoutError"?I:new Error(`Slack ${t} transport failed`)}if(o==="bot"){let I=$Fe(g);I&&(this.#l=I)}let c;try{c=await g.json()}catch{throw new Error(`Slack ${t} returned invalid JSON`)}if(g.status===429&&A){let I=Number(g.headers.get("retry-after"))||1;return await ALe(Math.min(1e4,Math.max(100,I*1e3)),e),this.#a(t,{tokenKind:o,body:i,signal:e,timeoutMs:a,retry:!1})}if(!g.ok||c?.ok!==!0){let I=tLe(t,c,o);throw I.status=g.status,I}return c}};async function PZ({botToken:n,appToken:t},o={}){if(!kZ(n)){let r=new TypeError(w("Slack Bot Token \u5FC5\u987B\u4EE5 xoxb- \u5F00\u5934\u3002"));throw r.code="slack-invalid-bot-token",r}if(!vZ(t)){let r=new TypeError(w("Slack App Token \u5FC5\u987B\u4EE5 xapp- \u5F00\u5934\u3002"));throw r.code="slack-invalid-app-token",r}let i=new XC({botToken:n,appToken:t,...o}),[e,a]=await Promise.all([i.authTest(),i.openConnection()]);if(!e?.team_id||!e?.user_id||!e?.bot_id)throw new Error(w("Slack Bot Token \u6CA1\u6709\u8FD4\u56DE\u5B8C\u6574\u7684\u673A\u5668\u4EBA\u8EAB\u4EFD\u3002"));let A;try{A=new URL(a?.url)}catch{A=null}if(!A||A.protocol!=="wss:"){let r=new Error(w("Slack App Token \u65E0\u6CD5\u521B\u5EFA Socket Mode \u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u542F\u7528 Socket Mode \u548C connections:write\u3002"));throw r.code="slack-socket-mode",r}return{platformId:`${e.team_id}:${e.user_id}`,name:bs(e.user)??"DeepSeek Harness",username:bs(e.user),teamId:String(e.team_id),teamName:bs(e.team)}}var OG=Object.freeze({key:"slack",label:"Slack",connectionLabel:" Socket Mode \u957F\u8FDE\u63A5",reactions:Object.freeze({processing:"eyes",success:"white_check_mark",error:"x"})}),sw=class extends Is{constructor(t){super({descriptor:OG,...t})}};function vg(n){return typeof n=="string"&&n.trim()?n.trim():null}function gw(n,t){return Object.freeze({code:n,message:t})}var $C=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new Map;#n=new Map;#s=0;#d=!1;constructor({credentials:t,configStore:o,inspectCredentials:i=PZ,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.resolve!="function"||typeof t.set!="function"||typeof t.unset!="function")throw new TypeError("Slack requires the DSH credential provider");if(!o||typeof o.list!="function"||typeof o.save!="function"||typeof o.remove!="function")throw new TypeError("Slack requires a config store");if(typeof i!="function"||typeof e!="function")throw new TypeError("Slack controller dependencies are incomplete");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A}async initialize(){if(this.#d)return this.status();for(let t of this.#A.list())await this.#h(t.botId,async()=>{if(this.#d||this.#i.get(t.botId)?.status?.ready)return;let o=await this.#I(t);if(!o){this.#a.set(t.botId,gw("missing-token",w("Slack\u673A\u5668\u4EBA\u51ED\u636E\u7F3A\u5931\uFF0C\u8BF7\u79FB\u9664\u540E\u91CD\u65B0\u63A5\u5165\u3002")));return}try{await this.#c(t,o),this.#a.delete(t.botId)}catch(i){this.#a.set(t.botId,gw("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002"))),this.#o.warn?.(`[dsh-im:slack] bot ${t.botId} failed to initialize:`,i)}finally{this.#u()}});return this.status()}async bindCredentials({botToken:t,appToken:o}={}){if(this.#d)throw new Error("Slack controller is closed");let i=vg(t),e=vg(o);if(!i||!e)throw new TypeError("Slack Bot Token and App Token are required");let a=await this.#t({botToken:i,appToken:e}),A=vg(a?.platformId),r=vg(a?.name);if(!A||!r)throw new Error("Slack returned an invalid bot identity");let s=SG(A);return await this.#h(s.botId,async()=>{if(this.#d)throw new Error("Slack controller is closed");let g=this.#A.getByPlatformId(A),c=await this.#e.resolve(s.botTokenRef).catch(()=>{}),I=await this.#e.resolve(s.appTokenRef).catch(()=>{}),d={...s,platformId:A,name:r,username:vg(a.username),teamId:vg(a.teamId),teamName:vg(a.teamName),createdAt:g?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};try{await this.#e.set(s.botTokenRef,i),await this.#e.set(s.appTokenRef,e),await this.#A.save(d)}catch(B){throw await Promise.all([this.#p(s.botTokenRef,c),this.#p(s.appTokenRef,I)]),B}try{await this.#c(d,{botToken:i,appToken:e}),this.#a.delete(s.botId)}catch(B){this.#a.set(s.botId,gw("connection-failed",w("Slack\u673A\u5668\u4EBA\u5DF2\u63A5\u5165\uFF0CSocket Mode \u8FDE\u63A5\u6682\u672A\u5C31\u7EEA\u3002"))),this.#o.warn?.(`[dsh-im:slack] bot ${s.botId} credential connection failed:`,B)}this.#u()}),this.status()}async reconnectBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#I(o);if(!i)throw new Error("Slack bot credentials are missing");try{await this.#c(o,i),this.#a.delete(t)}catch(e){throw this.#a.set(t,gw("connection-failed",w("Slack Socket Mode \u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u4E24\u4E2A Token\u3002"))),e}finally{this.#u()}}),this.status()}async sendConnectionTest(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function"){let e=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw e.code="test-target-unavailable",e}return await i.sendConnectionTest(La(`${o.name}\uFF08${wG(o.platformId)}\uFF09`,w("Slack\u673A\u5668\u4EBA"))),{sent:!0}})}async sendProactiveText(t,o,i,e={}){if(!this.#A.get(t))throw new Error("Unknown Slack bot");return this.#h(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("Slack\u673A\u5668\u4EBA\u5C1A\u672A\u8FDE\u63A5"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#A.get(t);if(!o)throw new Error("Unknown Slack bot");return await this.#h(t,async()=>{let i=await this.#e.resolve(o.botTokenRef).catch(()=>{}),e=await this.#e.resolve(o.appTokenRef).catch(()=>{});await this.#g(t);try{await this.#e.unset(o.botTokenRef),await this.#e.unset(o.appTokenRef),await this.#A.remove(t)}catch(a){throw await Promise.all([this.#p(o.botTokenRef,i),this.#p(o.appTokenRef,e)]),i?.value&&e?.value&&await this.#c(o,{botToken:i.value,appToken:e.value}).catch(()=>{}),new Error("Unable to remove the Slack bot safely.",{cause:a})}await this.#l({botId:t,config:o}).catch(a=>{this.#o.warn?.(`[dsh-im:slack] bot ${t} state cleanup failed:`,a)}),this.#a.delete(t),this.#u()}),this.status()}status(){let t=this.#A.list().map(i=>{let e=this.#i.get(i.botId)?.status??null,a=e?.ready===!0&&e.connectionState==="connected"&&e.harnessReachable===!0,A=a?"connected":e?.connectionState==="connecting"?"connecting":this.#a.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,teamName:i.teamName,idMasked:wG(i.platformId)},health:{status:a?"healthy":A==="error"?"error":"offline",summary:a?w(`Slack${OG.connectionLabel}\u8FD0\u884C\u6B63\u5E38`):A==="error"?w("Slack\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("Slack\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:e?.lastCheckedAt??null,lastConnectedAt:e?.lastConnectedAt??null},stats:{messagesReceived:e?.messagesReceived??0,messagesReplied:e?.messagesReplied??0},lastMessageError:Aa(e?.lastMessageError),error:structuredClone(this.#a.get(i.botId)??null)}}),o=t.filter(i=>i.connected).length;return{schemaVersion:1,revision:this.#s,state:t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o}}}async close(){this.#d||(this.#d=!0,await Promise.allSettled([...this.#n.values()]),await Promise.allSettled([...this.#i.keys()].map(t=>this.#g(t))))}async#c(t,{botToken:o,appToken:i}){if(this.#d)throw new Error("Slack controller is closed");if(await this.#g(t.botId),this.#d)throw new Error("Slack controller is closed");let e=await this.#r({botId:t.botId,config:t,botToken:o,appToken:i});if(!e||typeof e.start!="function"||typeof e.stop!="function")throw new TypeError("createRuntime returned an invalid Slack runtime");this.#i.set(t.botId,e);try{await e.start()}catch(a){throw await e.stop().catch(()=>{}),this.#i.delete(t.botId),a}}async#g(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-im:slack] bot ${t} failed to stop cleanly:`,i)})}async#I(t){let[o,i]=await Promise.all([this.#e.resolve(t.botTokenRef).catch(()=>{}),this.#e.resolve(t.appTokenRef).catch(()=>{})]),e=vg(o?.value),a=vg(i?.value);return e&&a?{botToken:e,appToken:a}:null}async#p(t,o){o?.value?await this.#e.set(t,o.value).catch(()=>{}):await this.#e.unset(t).catch(()=>{})}#h(t,o){let a=(this.#n.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#n.get(t)===a&&this.#n.delete(t)});return this.#n.set(t,a),a}#u(){this.#s+=1}};var cw=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"slack",logPrefix:"dsh-slack"})}};var GZ=Object.freeze([1e3,3e3,5e3,1e4,3e4]),MG=38e3,FZ=11e3,UZ=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function bG(n,t,o){if(typeof n.addEventListener=="function")n.addEventListener(t,o);else if(typeof n.on=="function")n.on(t,o);else throw new TypeError("Slack WebSocket does not support events")}function rLe(n){let t=n?.data??n;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("utf8"):t instanceof ArrayBuffer?Buffer.from(t).toString("utf8"):ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):null}function aLe(n){let t=new URL(n);if(t.protocol!=="wss:")throw new Error("Slack returned an insecure Socket Mode URL");return t.href}function HZ(n){return typeof n=="string"?n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"):""}function iLe(n,t){return HZ(n).replace(new RegExp(`<@${t}>`,"gi"),"").trim()}function _G(n){return typeof n?.url_private_download=="string"&&n.url_private_download?n.url_private_download:n?.url_private}function oLe(n){if(!n||typeof n!="object")return null;let t=typeof n.mimetype=="string"?n.mimetype.toLowerCase():"",o=t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file",i=typeof n.name=="string"&&n.name?n.name:typeof n.title=="string"&&n.title?n.title:void 0;return{kind:o,...i?{name:i}:{}}}function nLe(n,t){if(!n||String(n.ts??"")!==t)return null;let o=typeof n.user=="string"&&n.user?n.user:typeof n.bot_id=="string"&&n.bot_id?n.bot_id:void 0,i=typeof n.username=="string"&&n.username?n.username:void 0;return{messageId:t,...o?{authorId:o}:{},...i?{authorName:i}:{},content:HZ(n.text??""),attachments:Array.isArray(n.files)?n.files.map(oLe).filter(Boolean):[]}}function sLe(n,t){let o=typeof n?.thread_ts=="string"?n.thread_ts:"";if(!(!o||o===String(n?.ts??"")))return{messageId:o,load:async({signal:i}={})=>{try{let e=await t({channelId:String(n.channel),messageTs:o,signal:i});return nLe(e,o)}catch(e){if(e?.code==="slack-missing-scope")return{messageId:o,unavailableReason:"permission-denied"};throw e}}}}function gLe(n,t){let o=typeof n?.mimetype=="string"?n.mimetype.toLowerCase():"",i=_G(n);return!UZ.has(o)||typeof i!="string"||!i?null:{name:typeof n.name=="string"?n.name:void 0,mediaType:o,size:Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0,load:e=>t(i,e)}}function cLe(n,t,o){let i=typeof n?.mimetype=="string"&&n.mimetype?n.mimetype.toLowerCase():void 0,e=_G(n);if(UZ.has(i))return null;let a=n?.file_access==="check_file_info"&&typeof n?.id=="string"&&n.id;return(typeof e!="string"||!e)&&!a?null:{name:typeof n?.name=="string"&&n.name?n.name:typeof n?.title=="string"&&n.title?n.title:a?n.id:"slack-file",...i?{mediaType:i}:{},size:Number.isSafeInteger(n?.size)&&n.size>=0?n.size:void 0,load:async({signal:A}={})=>{if(!a)return t(e,{signal:A});let r=await o(n.id,{signal:A}),s=_G(r);if(typeof s!="string"||!s)throw new Error("Slack files.info returned no downloadable URL");let g=await t(s,{signal:A}),c=typeof r?.name=="string"&&r.name?r.name:typeof r?.title=="string"&&r.title?r.title:n.id,I=typeof r?.mimetype=="string"&&r.mimetype?r.mimetype.toLowerCase():void 0;return Buffer.isBuffer(g)||g instanceof Uint8Array?{data:g,name:c,...I?{mediaType:I}:{}}:{...g,name:c,...I?{mediaType:I}:{}}}}}function ILe(n,t,{loadFile:o=async()=>{throw new Error("Slack file downloader is unavailable")},loadFileStream:i=o,loadFileInfo:e=async()=>{throw new Error("Slack file metadata loader is unavailable")},loadReply:a=async()=>{throw new Error("Slack reply loader is unavailable")}}={}){let A=n?.event;if(!A||!n?.event_id||!A.channel||!A.user||!A.ts)return null;let r=A.type==="message"&&A.channel_type==="im",s=A.type==="app_mention";if(!r&&!s||A.subtype&&A.subtype!=="file_share"||A.bot_id||A.app_id)return null;let g=String(A.thread_ts??A.ts),c=sLe(A,a);return{messageId:String(n.event_id),senderId:String(A.user),senderIsBot:String(A.user)===String(t),kind:r?"direct":"group",conversationId:r?String(A.channel):`${A.channel}:${g}`,contextSource:()=>({chatId:String(A.channel),threadId:A.thread_ts?String(A.thread_ts):void 0}),content:iLe(A.text??"",t),plainText:!Array.isArray(A.files)||A.files.length===0,images:Array.isArray(A.files)?A.files.map(I=>gLe(I,o)).filter(Boolean):[],files:Array.isArray(A.files)?A.files.map(I=>cLe(I,i,e)).filter(Boolean):[],...c?{replyTo:c}:{},addressed:r||s,reactionTarget:{channelId:String(A.channel),messageTs:String(A.ts)},replyTarget:{channelId:String(A.channel),threadTs:g,recipientUserId:String(A.user),recipientTeamId:String(A.user_team??n.team_id??"")},connectionTestTarget:{channelId:String(A.channel)}}}function lLe(n){if(typeof n!="string")return!1;let t="__DSH_IM_TOOL_NAME__",o=w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:t}),i=o.indexOf(t);if(i<0)return!1;let e=o.slice(0,i),a=o.slice(i+t.length),A=n.trim();return A.startsWith(e)&&A.endsWith(a)&&A.length>e.length+a.length}async function LZ(n,t,o,i,e){if(i)for(let a=0;a{let y=ls(Q,MG)[0]??"";if(!y||!y.startsWith(A))return;let m=y.slice(A.length);m&&(await LZ(n,t,a,m,o),A=y)},f=()=>{I||c||s!==null||g||!r||(s=setTimeout(()=>{s=null;let Q=r;r="",g=B(Q).catch(y=>{c=!0,i.warn?.("[dsh-im:slack] streaming append failed:",y)}).finally(()=>{g=null,f()})},350),s?.unref?.())};return{messageId:a,get providerMessageIds(){return[...d]},update(Q){I||c||typeof Q!="string"||!Q.trim()||lLe(Q)||(r=Q,f())},async finish(Q){if(I)throw new Error("Slack message stream is already closed");I=!0,s!==null&&clearTimeout(s),s=null,r="",await g?.catch(()=>{});let y=ls(Q,MG),m=y[0]??w("\u5904\u7406\u5B8C\u6210\u3002");!c&&m.startsWith(A)?(await LZ(n,t,a,m.slice(A.length),o),await n.stopStream({channelId:t.channelId,ts:a,signal:o})):(await n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{}),await n.updateMessage({channelId:t.channelId,ts:a,text:m,signal:o}));for(let T of y.slice(1)){let _=await n.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:T,signal:o});typeof _?.ts=="string"&&_.ts&&d.push(_.ts)}},cancel(){I=!0,r="",s!==null&&clearTimeout(s),s=null,n.stopStream({channelId:t.channelId,ts:a,signal:o}).catch(()=>{})}}}var TG=class{#e;#A;#t;constructor({api:t,signal:o,logger:i}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=ls(o,MG),e=[];for(let a of i){let A=await this.#e.postMessage({channelId:t.channelId,threadTs:t.threadTs,text:a,signal:this.#A});typeof A?.ts=="string"&&A.ts&&e.push(A.ts)}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.addReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.removeReaction({channelId:t.channelId,messageTs:t.messageTs,emojiName:o,signal:i??this.#A})}openStream(t){return dLe({api:this.#e,target:t,signal:this.#A,logger:this.#t})}sendFile(t,o){return this.#e.uploadFile({channelId:t.channelId,threadTs:t.threadTs,file:o,signal:this.#A})}};function pLe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...so()}}var eB=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g=pLe();#I=null;#p=null;#h=null;#u=null;#C=null;#B=null;#f=0;#Q=0;#S=!0;#y=null;constructor({config:t,botToken:o,appToken:i,harness:e,state:a,contextEnhancement:A,accessPolicy:r,logger:s=console,replyTimeoutMs:g=6e5,connectTimeoutMs:c=2e4,createApi:I=B=>new XC(B),createWebSocket:d=B=>new WebSocket(B)}){if(!t||!o||!i||!e||!a)throw new TypeError("SlackRuntime requires config, both tokens, Harness, and state");if(typeof d!="function")throw new TypeError("SlackRuntime requires WebSocket");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#d=I,this.#c=d}get status(){return structuredClone(this.#g)}async sendConnectionTest(t){if(!this.#g.ready||!this.#p){let o=new Error("Slack bot is not connected");throw o.code="test-target-unavailable",o}return this.#p.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#g.ready||!this.#p){let A=new Error("Slack bot is not connected");throw A.code="bot-not-connected",A}let e=typeof t?.route?.channelId=="string"?t.route.channelId.trim():"",a=typeof t?.route?.threadTs=="string"?t.route.threadTs.trim():"";if(!e||t?.kind!=="conversation"&&t?.kind!=="thread"||t.kind==="thread"&&!a||t.kind==="conversation"&&a){let A=new TypeError("Invalid Slack proactive delivery target");throw A.code="invalid-target",A}return this.#p.sendProactiveText({channelId:e,...a?{threadTs:a}:{}},o,i)}async start(){return this.#g.ready&&this.#u?this.status:this.#y?this.#y:(this.#y=this.#m().finally(()=>{this.#y=null}),this.#y)}async#m(){await this.stop(),this.#S=!1,this.#f=0,this.#g.startedAt=new Date().toISOString(),this.#g.connectionState="connecting",this.#g.lastError=null,await this.#r.ensureRunning(),this.#g.harnessReachable=!0;let t=new AbortController;this.#h=t;let o=this.#d({botToken:this.#A,appToken:this.#t});this.#I=o;try{let i=await o.authTest({signal:t.signal});if(`${i?.team_id}:${i?.user_id}`!==this.#e.platformId)throw new Error("Slack Bot Token identity does not match the saved bot");let e=new TG({api:o,signal:t.signal,logger:this.#a});this.#p=new sw({bot:e,harness:this.#r,state:this.#l,contextEnhancement:this.#o,accessPolicy:this.#i,status:this.#g,logger:this.#a,replyTimeoutMs:this.#n,signal:t.signal});let a;try{await Promise.race([this.#D(),new Promise((A,r)=>{a=setTimeout(()=>r(new Error("Slack Socket Mode did not become ready in time")),this.#s),a?.unref?.()})])}finally{clearTimeout(a)}return this.status}catch(i){throw this.#g.ready=!1,this.#g.connectionState="failed",this.#g.lastError=i?.message??String(i),await this.stop(),i}}async#D(){if(this.#S)throw new Error("Slack runtime is stopped");let t=await this.#I.openConnection({signal:this.#h?.signal});return this.#E(t?.url)}#E(t){if(this.#S)return Promise.reject(new Error("Slack runtime is stopped"));let o=++this.#Q,i=this.#c(aLe(t));this.#u=i;let e=!1;return new Promise((a,A)=>{let r=s=>{if(e||o!==this.#Q)return;e=!0,this.#C=s?.connection_info?.app_id??null,this.#f=0;let g=Date.now();this.#g.ready=!0,this.#g.connectionState="connected",this.#g.lastCheckedAt=g,this.#g.lastConnectedAt=g,this.#g.lastError=null,a()};bG(i,"message",s=>{if(o!==this.#Q||this.#S)return;let g=rLe(s);if(!g)return;let c;try{c=JSON.parse(g)}catch{this.#a.warn?.("[dsh-im:slack] ignored malformed Socket Mode JSON");return}if(c.type==="hello"){r(c);return}if(c.envelope_id&&i.readyState===1&&(i.send(JSON.stringify({envelope_id:c.envelope_id})),this.#g.lastCheckedAt=Date.now()),c.type==="disconnect"){i.close(4e3,"Slack requested reconnect");return}if(c.type!=="events_api"||c.payload?.type!=="event_callback"||this.#C&&c.payload.api_app_id&&c.payload.api_app_id!==this.#C)return;let I=ILe(c.payload,this.#e.platformId.split(":")[1],{loadFile:(B,f)=>this.#I.downloadFile({url:B,...f}),loadFileStream:(B,f)=>this.#I.downloadFileStream({url:B,...f}),loadFileInfo:(B,f)=>this.#I.fileInfo({fileId:B,...f}),loadReply:B=>this.#I.getMessage(B)}),d=this.#p;I&&d&&d.accept(I).catch(B=>{o!==this.#Q||this.#S||this.#a.error?.(`[dsh-im:slack] bot ${this.#e.botId} message handling failed:`,B)})}),bG(i,"close",(s={})=>{if(o!==this.#Q)return;if(this.#u===i&&(this.#u=null),this.#S){e||A(new DOMException("Stopped","AbortError"));return}let g=Number(s.code)||0,c=new Error(`Slack Socket Mode closed (${g||"unknown"})`);this.#g.ready=!1,this.#g.connectionState="connecting",this.#g.lastError=c.message,e||(e=!0,A(c)),this.#R()}),bG(i,"error",()=>{o!==this.#Q||this.#S||(this.#g.lastError="Slack Socket Mode WebSocket error")})})}#R(){if(this.#S||this.#B!==null)return;let t=GZ[Math.min(this.#f,GZ.length-1)];this.#f+=1,this.#B=setTimeout(()=>{this.#B=null,this.#D().catch(o=>{this.#S||(this.#a.warn?.("[dsh-im:slack] Socket Mode reconnect failed:",o),this.#R())})},t),this.#B?.unref?.()}async stop(){this.#S=!0,this.#Q+=1,this.#h?.abort(),this.#h=null,this.#B!==null&&clearTimeout(this.#B),this.#B=null;let t=this.#u,o=this.#p;this.#u=null,this.#p=null,this.#I=null,this.#C=null;try{t&&t.readyState<2&&t.close(1e3,"Plugin stopped")}catch(i){this.#a.warn?.(`[dsh-im:slack] bot ${this.#e.botId} failed to close Socket Mode:`,i)}return await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(i=>setTimeout(i,2e3))]),this.#g.ready=!1,this.#g.connectionState="idle",this.status}};var Iw=class extends ds{};async function NG(n,t={},o={}){if(!n?.credentials)throw new TypeError("dsh-im slack requires ctx.credentials");let i=na(n,t),e=o.ConfigStore??nw,a=o.StateStore??Iw,A=o.HarnessClient??cw,r=o.Controller??$C,s=o.Runtime??eB,g=o.createConnectionSupervisor??Wd,c=typeof n.logger=="function"?n.logger("dsh-im:slack"):n.logger??console,I=()=>Ya(n),d=fT(t,"slack"),B=await new e(d.config).load(),f=KZ(t.workspace??process.cwd()),Q=o.WorkspaceStore??oa,y=o.workspaces??await new Q(d.workspaces,{defaultWorkspace:f}).load(),m=B.list();await y.reconcile(m.map(N=>N.botId)),await Promise.all(m.map(N=>y.ensure(N.botId,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("slack",N)})));let T=typeof B.remove=="function"?ja(B,{workspaces:y}):B,_=new Map,R=N=>KZ(d.bots,N,"state.json"),x=async N=>{let k=_.get(N);return k||(k=await new a(R(N)).load(),_.set(N,k)),k},F=Va(n,o.commandExecutor),{controlExecutor:L,sessionMaintenanceExecutor:q,fileIngressExecutor:z}=Wa(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),H=new A({...i,workspace:f,autostart:!1,dshBin:t.dshBin??"dsh",...F?{commandExecutor:F}:{},...L?{controlExecutor:L}:{},...q?{sessionMaintenanceExecutor:q}:{},...z?{fileIngressExecutor:z}:{}}),G=new r({credentials:n.credentials,configStore:T,logger:c,...o.inspectCredentials?{inspectCredentials:o.inspectCredentials}:{},createRuntime:async({botId:N,config:k,botToken:J,appToken:X})=>{let ie=await x(N);await y.ensure(N,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("slack",k)});let we=Ja(H,{botId:N,workspaces:y,state:ie,agentPresetCatalog:I});return new s({config:k,botToken:J,appToken:X,harness:we.harness,state:we.state,contextEnhancement:{botId:N,getSettings:()=>y.contextEnhancementFor(N)},accessPolicy:Za(y,N,{channel:"slack",config:k}),replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,logger:{error:(...oe)=>c.error?.(`[${N}]`,...oe),warn:(...oe)=>c.warn?.(`[${N}]`,...oe),info:(...oe)=>c.info?.(`[${N}]`,...oe),debug:(...oe)=>c.debug?.(`[${N}]`,...oe)}})},deleteState:async({botId:N})=>{let k=_.get(N);if(_.delete(N),k&&typeof k.remove=="function")await k.remove();else try{await hLe(R(N))}catch(J){if(J?.code!=="ENOENT")throw J}}}),V=qa(G,{workspaces:y,stateFor:x,agentPresetCatalog:I}),U=g({channel:"slack",controller:V,harness:H,logger:c,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:V,deliveryAdapter:za({channel:"slack",workspaces:y,coreController:G,stateFor:x}),ready:U.ready,async close(){await U.close(),await V.close(),H.stopManagedProcess()}}}var YZ="/slack",_a=Object.freeze({status:"connection.status",bindCredentials:"bot.bind-credentials",reconnectBot:"bot.reconnect",deleteBot:"bot.delete",setWorkspace:Fi,setAgentPreset:Li,setContextEnhancement:Gi,setAccessPolicy:$a}),jZ=Object.freeze(Object.values(_a)),ELe=new Set(["token","botToken","appToken","botTokenRef","appTokenRef","tokenRef","platformId","secret","secretRef"]);function kG(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function lw(n,t){return kG(n)&&Object.keys(n).every(o=>t.includes(o))}function xZ(n){return typeof n=="string"&&/^slack_[a-f0-9]{24}$/.test(n)}function uLe(n){return typeof n=="string"&&/^xoxb-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function CLe(n){return typeof n=="string"&&/^xapp-[A-Za-z0-9-]{16,}$/.test(n.trim())&&n.length<=4096}function BLe(n,t){return kG(t)?n===_a.status?lw(t,[])?null:"connection.status does not accept fields.":n===_a.bindCredentials?lw(t,["botToken","appToken"])&&uLe(t.botToken)&&CLe(t.appToken)?null:"bot.bind-credentials requires xoxb Bot Token and xapp App Token.":n===_a.reconnectBot?lw(t,["botId","sendTest"])&&xZ(t.botId)&&(t.sendTest===void 0||typeof t.sendTest=="boolean")?null:"bot.reconnect requires a botId.":n===_a.deleteBot?lw(t,["botId","confirm"])&&xZ(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===_a.setWorkspace?Ai(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===_a.setAgentPreset?ri(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===_a.setContextEnhancement?Xa(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===_a.setAccessPolicy?ei(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u8BBF\u95EE\u8BBE\u7F6E\u3002":"Unknown Slack endpoint.":"Payload must be an object."}function RG(n){if(Array.isArray(n))return n.map(RG);if(!kG(n))return n;let t={};for(let[o,i]of Object.entries(n))ELe.has(o)||(t[o]=RG(i));return t}function fLe(n){let t=ti(n);return t||(n?.code==="slack-invalid-bot-token"?{code:"invalid-bot-token",message:"Slack Bot Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xoxb- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-invalid-app-token"?{code:"invalid-app-token",message:"Slack App Token \u65E0\u6548\uFF0C\u8BF7\u786E\u8BA4\u4F7F\u7528\u4EE5 xapp- \u5F00\u5934\u7684\u4EE4\u724C\u3002"}:n?.code==="slack-missing-scope"?{code:"missing-scope",message:"Slack \u5E94\u7528\u6743\u9650\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165 Manifest \u5E76\u5B89\u88C5\u5230\u5DE5\u4F5C\u533A\u3002"}:n?.code==="slack-socket-mode"?{code:"socket-mode-unavailable",message:n.message}:{code:"slack-operation-failed",message:"Slack \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}function JZ(n){for(let t of["status","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[t]!="function")throw new TypeError(`A complete Slack controller is required (${t})`);return async(t,o,i)=>{if(i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!jZ.includes(t))return{ok:!1,error:{code:"bad-request",message:"Unknown Slack endpoint."}};let e=BLe(t,o);if(e)return{ok:!1,error:{code:"bad-request",message:e}};try{let a;if(t===_a.status)a=await n.status();else if(t===_a.bindCredentials)a=await n.bindCredentials(o);else if(t===_a.reconnectBot){if(a=await n.reconnectBot(o.botId),i?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(o.sendTest===!0){let A=null;try{if(a?.bots?.find(r=>r?.botId===o.botId)?.connected!==!0){let r=new Error("Bot is not connected");throw r.code="test-target-unavailable",r}if(typeof n.sendConnectionTest!="function"){let r=new Error("Connection test is unavailable");throw r.code="test-target-unavailable",r}await n.sendConnectionTest(o.botId)}catch(r){A=r}a={...a,testMessage:gr(A)}}}else if(t===_a.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");a=await n.updateWorkspace(o.botId,o.workspace)}else if(t===_a.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");a=await n.updateContextEnhancement(o.botId,o.config)}else if(t===_a.setAccessPolicy){if(typeof n.updateAccessPolicy!="function")throw new Error("Access policy update is unavailable");a=await n.updateAccessPolicy(o.botId,o.policy)}else if(t===_a.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");a=await n.updateAgentPreset(o.botId,o.agentPreset)}else a=await n.deleteBot(o.botId);return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:RG(a)}}catch(a){return i?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!1,error:fLe(a)}}}}function dw(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(YZ,JZ(t),{authority:yr(o)})}async function qZ(n,t={}){if(t?.controller)return dw(n,t.controller,t.rpcAuthority);let o=await NG(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=dw(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Slack bot connections"),e}var zZ=Object.freeze({botPrefix:"telegram",tokenRefPrefix:"DSH_TELEGRAM_BOT_TOKEN"}),vG=Object.freeze({compatible:"compatible",privateAllowlist:"private-allowlist"}),QLe=/^[1-9]\d{0,15}$/;function VZ(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n))throw new TypeError("allowedUsers must be an array of numeric Telegram User IDs");let t=n.map(o=>{let i=typeof o=="number"&&Number.isSafeInteger(o)?String(o):typeof o=="string"?o.trim():"";if(!QLe.test(i))throw new TypeError("allowedUsers contains an invalid Telegram User ID");return i});return Object.freeze([...new Set(t)])}function hw(n={}){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Telegram access policy must be an object");let t=n.accessMode??vG.compatible;if(!Object.values(vG).includes(t))throw new TypeError("Telegram accessMode must be compatible or private-allowlist");return Object.freeze({accessMode:t,allowedUsers:VZ(n.allowedUsers)})}function yLe(n){let t=Object.hasOwn(n,"accessMode"),o=Object.hasOwn(n,"allowedUsers");if(!t&&!o)return{};try{let i=hw(n);return{...t?{accessMode:i.accessMode}:{},...o||t?{allowedUsers:i.allowedUsers}:{}}}catch{return null}}function WZ(n){return nu(n,zZ)}function ZZ(n){return Ay(n,w("Telegram\u673A\u5668\u4EBA"))}var pw=class extends qd{constructor(t){super(t,{channel:"Telegram",...zZ,normalizeBotExtension:yLe})}async save(t){let o=t?.platformId?this.getByPlatformId(String(t.platformId)):null;return super.save({...o,...t})}};var Ew=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"telegram",logPrefix:"dsh-telegram"})}};var mLe="https://api.telegram.org/",XZ=Object.freeze(["api.telegram.org"]),SLe=12e4;function Pg(n){return typeof n=="string"&&n.trim()?n.trim():null}function $Z(n,t){let o=AbortSignal.timeout(t);return n?AbortSignal.any([n,o]):o}function PG(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function wLe(n,t){if(!Number.isInteger(n)||n<1)throw new TypeError(`${t} must be a positive integer`);return n}function A9(n,t){return t?.providerCode!==void 0&&(n.providerCode=t.providerCode),t?.retry_after!==void 0&&(n.retry_after=t.retry_after,n.retryAfter=t.retry_after),Number.isInteger(t?.status)&&(n.status=t.status),n}function GG(n){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("A Telegram rich message is required");let t=["markdown","html","blocks"].filter(i=>n[i]!==void 0);if(t.length!==1)throw new TypeError("A Telegram rich message requires exactly one format");let o=t[0];if((o==="markdown"||o==="html")&&(typeof n[o]!="string"||!n[o].trim()))throw new TypeError("Telegram rich message text is invalid");if(o==="blocks"&&!Array.isArray(n.blocks))throw new TypeError("Telegram rich message blocks are invalid");return n}function DLe(n,t="document"){let o=Number(n?.providerCode),i=Number(n?.status),e=Pg(n?.message)??"",a="artifact-provider-rejected",A=`Telegram rejected the ${t}.`;o===401||o===403||i===401||i===403?(a="artifact-permission-required",A=`Telegram denied permission to send the ${t}.`):o===413||i===413||/(?:file|request|entity).{0,20}(?:too (?:big|large)|size limit)|too (?:big|large)/i.test(e)?(a="artifact-too-large",A=`The ${t} exceeds Telegram's size limit.`):o===429||i===429?(a="artifact-rate-limited",A=`Telegram rate-limited ${t} delivery.`):(o>=500||i>=500)&&(a="artifact-delivery-uncertain",A=`Telegram ${t} delivery result is uncertain.`);let r=new Error(A,{cause:n});return r.code=a,A9(r,n)}function e9(n,t="document"){let o=new Error(`Telegram ${t} delivery result is uncertain`,{cause:n});return o.code="artifact-delivery-uncertain",A9(o,n)}function OLe(n){return typeof n=="string"&&/^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(n.trim())}var bLe=/^[a-z0-9_]{1,32}$/;function MLe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.command=="string"&&bLe.test(n.command)&&typeof n.description=="string"&&n.description.length>=1&&n.description.length<=256}var FG=Object.freeze({type:"commands"}),AB=class{#e;#A;#t;#r;#l;constructor({token:t,fetchImpl:o=fetch,FormDataImpl:i=globalThis.FormData,baseUrl:e=mLe,fileUploadTimeoutMs:a=SLe}){if(!OLe(t))throw new TypeError("Telegram Bot Token is invalid");if(typeof o!="function")throw new TypeError("TelegramApi requires fetch");if(typeof i!="function")throw new TypeError("TelegramApi requires FormData");this.#e=t.trim(),this.#A=o,this.#t=i,this.#r=new URL(e),this.#l=wLe(a,"fileUploadTimeoutMs")}async getMe(t={}){return this.#a("getMe",{},t)}async getWebhookInfo(t={}){return this.#a("getWebhookInfo",{},t)}async getUpdates({offset:t,timeout:o=25,signal:i}={}){let e={timeout:o,limit:100,allowed_updates:["message"],...Number.isSafeInteger(t)?{offset:t}:{}};return this.#a("getUpdates",e,{signal:i,timeoutMs:Math.max(1e4,(o+10)*1e3)})}async getFile({fileId:t,signal:o}={}){let i=Pg(t);if(!i||!/^[A-Za-z0-9_-]{1,512}$/.test(i))throw new TypeError("Telegram file id is invalid");return this.#a("getFile",{file_id:i},{signal:o})}async downloadFile({fileId:t,signal:o,maxBytes:i}={}){let e=await this.#o(t,o);return bo(e,{fetchImpl:this.#A,signal:o,maxBytes:i,allowedHosts:XZ})}async downloadFileStream({fileId:t,signal:o}={}){let i=await this.#o(t,o);return Vd(i,{fetchImpl:this.#A,signal:o,allowedHosts:XZ})}async#o(t,o){let i=await this.getFile({fileId:t,signal:o}),e=Pg(i?.file_path);if(!e||e.startsWith("/")||e.includes("\\")||e.includes("?")||e.includes("#"))throw new Error("Telegram returned an invalid file path");let a;try{a=e.split("/").map(r=>decodeURIComponent(r))}catch{throw new Error("Telegram returned an invalid file path")}if(a.some(r=>!r||r==="."||r===".."))throw new Error("Telegram returned an invalid file path");let A=new URL(this.#r);return A.pathname=`/file/bot${this.#e}/${e}`,A}async sendMessage({chatId:t,text:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#a("sendMessage",{chat_id:t,text:o,link_preview_options:{is_disabled:!0},...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async setMessageReaction({chatId:t,messageId:o,emoji:i,signal:e,timeoutMs:a}){let A=Pg(i);return this.#a("setMessageReaction",{chat_id:t,message_id:o,reaction:A?[{type:"emoji",emoji:A}]:[]},{signal:e,timeoutMs:a})}async sendRichMessage({chatId:t,richMessage:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#a("sendRichMessage",{chat_id:t,rich_message:GG(o),...i?{reply_parameters:{message_id:i,allow_sending_without_reply:!0}}:{},...e?{message_thread_id:e}:{}},{signal:a})}async sendRichMessageDraft({chatId:t,draftId:o,richMessage:i,messageThreadId:e,signal:a}){if(!Number.isSafeInteger(o)||o===0)throw new TypeError("Telegram rich message draft id must be a non-zero integer");return this.#a("sendRichMessageDraft",{chat_id:t,draft_id:o,rich_message:GG(i),...e?{message_thread_id:e}:{}},{signal:a})}async sendDocument({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendDocument","document","document",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async sendPhoto({chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a}){return this.#i("sendPhoto","photo","photo",{chatId:t,file:o,replyToMessageId:i,messageThreadId:e,signal:a})}async#i(t,o,i,{chatId:e,file:a,replyToMessageId:A,messageThreadId:r,signal:s}){if(!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError(`A Telegram ${i} is required`);let g=new this.#t;if(g.append("chat_id",String(e)),g.append(o,new Blob([a.bytes],{type:a.mediaType??"application/octet-stream"}),a.fileName),A&&g.append("reply_parameters",JSON.stringify({message_id:A,allow_sending_without_reply:!0})),r&&g.append("message_thread_id",String(r)),s?.aborted)throw PG(s);let c=$Z(s,this.#l);try{return await this.#a(t,g,{signal:c,timeoutMs:this.#l,multipart:!0})}catch(I){throw s?.aborted?PG(s):I?.deliveryOutcome==="unknown"?e9(I?.cause??I,i):I?.code?.startsWith?.("telegram-")?DLe(I,i):e9(I,i)}}async editMessageText({chatId:t,messageId:o,text:i,richMessage:e,signal:a}){if(i===void 0==(e===void 0))throw new TypeError("Telegram message edit requires exactly one of text or richMessage");return this.#a("editMessageText",{chat_id:t,message_id:o,...i===void 0?{rich_message:GG(e)}:{text:i,link_preview_options:{is_disabled:!0}}},{signal:a})}async sendChatAction({chatId:t,messageThreadId:o,signal:i}){return this.#a("sendChatAction",{chat_id:t,action:"typing",...o?{message_thread_id:o}:{}},{signal:i})}async setMyCommands({commands:t,scope:o,languageCode:i,signal:e}={}){if(!Array.isArray(t)||t.length===0||t.some(a=>!MLe(a)))throw new TypeError("Telegram bot commands are invalid");return this.#a("setMyCommands",{commands:t,...o?{scope:o}:{},...Pg(i)?{language_code:Pg(i)}:{}},{signal:e})}async setChatMenuButton({menuButton:t=FG,signal:o}={}){if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("Telegram menu button is invalid");return this.#a("setChatMenuButton",{menu_button:t},{signal:o})}async#a(t,o,{signal:i,timeoutMs:e=15e3,multipart:a=!1}={}){if(i?.aborted)throw PG(i);let A=new URL(this.#r);A.pathname=`${A.pathname.replace(/\/$/,"")}/bot${this.#e}/${t}`;let r;try{r=await this.#A(A,{method:"POST",...a?{}:{headers:{"content-type":"application/json"}},body:a?o:JSON.stringify(o),signal:$Z(i,e),redirect:"error"})}catch(g){let c=new Error(`Telegram ${t} transport failed`,{cause:g});throw c.code=g?.name==="TimeoutError"?"telegram-timeout":g?.name==="AbortError"?"telegram-aborted-after-dispatch":"telegram-transport-error",c.deliveryOutcome="unknown",c}let s;try{s=await r.json()}catch{let g=new Error(`Telegram ${t} returned invalid JSON`);throw g.status=r?.status,g.code="telegram-response-invalid",g.deliveryOutcome="unknown",g}if(!r.ok||s?.ok!==!0){let g=Pg(s?.description),c=new Error(g??`Telegram ${t} failed`);c.code=Number.isInteger(s?.error_code)?`telegram-${s.error_code}`:"telegram-api-error",c.status=r.status,Number.isInteger(s?.error_code)&&(c.providerCode=s.error_code);let I=Number(s?.parameters?.retry_after);throw Number.isFinite(I)&&I>=0&&(c.retry_after=I,c.retryAfter=I),c}return s.result}};async function t9(n,t={}){let i=await new AB({token:n,...t}).getMe();if(!i?.id||i?.is_bot!==!0)throw new Error("Telegram token does not belong to a bot");return{platformId:String(i.id),name:Pg([i.first_name,i.last_name].filter(Boolean).join(" "))??w("Telegram\u673A\u5668\u4EBA"),username:Pg(i.username)}}var LG=Object.freeze({key:"telegram",label:"Telegram",connectionLabel:" Bot API \u957F\u8F6E\u8BE2",reactions:Object.freeze({processing:"\u{1F440}",success:"\u{1F44D}",error:"\u{1F44E}"})}),uw=class extends Is{constructor(t){super({descriptor:LG,...t})}};var tB=class extends zd{#e;constructor(t){super({...t,descriptor:LG,inspectToken:t.inspectToken??t9,deriveIdentity:WZ,maskPlatformId:ZZ}),this.#e=t.configStore}status(){let t=super.status();return{...t,bots:t.bots.map(o=>{let i=this.#e.get(o.botId),e=hw(i??{});return{...o,accessPolicy:e}})}}async setAccessPolicy(t,o){let i=hw(o);return this.updateBotConfig(t,e=>({...e,...i}))}};import{randomInt as GLe}from"node:crypto";import{EnvHttpProxyAgent as _Le,FormData as TLe,fetch as NLe}from"undici";var RLe=4;function r9(){let n=new _Le({connections:RLe}),t=!1;return{fetchImpl:(o,i={})=>NLe(o,{...i,dispatcher:n}),FormDataImpl:TLe,async destroy(){t||(t=!0,await n.destroy())}}}function HG(n){if(typeof n!="string"||!n.trim())throw new TypeError("Telegram message text must be a non-empty string");return n}function KG(n){return n==="&"?5:n==="<"||n===">"?4:1}function UG(n){return Array.from(n).reduce((t,o)=>t+KG(o),0)}function kLe(n,t,o,i){let e=t+Math.floor(i*.5);for(let a=o-1;a>=e;a-=1)if(n[a]===` `||n[a]===" ")return a+1;return o}function xG(n,t,o=()=>1){if(typeof n!="string")throw new TypeError("Telegram message text must be a string");if(!n)return[];let i=Array.from(n),e=[],a=0;for(;at)break;r+=s,A+=1}if(A===a)throw new Error("Telegram message character exceeds the chunk limit");A",">")}function a9(n,t){return xG(n,t,KG).map(o=>({source:o,markdown:rB(o)}))}function PLe(n,t,o,i){let e=n.slice(t.length,n.length-o.length),a=UG(t)+Math.max(UG(o),UG("```"))+1,A=i-a;if(A<1)throw new Error("Telegram Rich Markdown code fence exceeds the limit");let r=xG(e,A,KG);return r.map((s,g)=>{let c=g===r.length-1,I=s.endsWith(` `)?"":` -`,d=c?o:"```",B=`${g===0?t:""}${s}${c?o:""}`,f=rB(`${t}${s}${I}${d}`);if(Array.from(f).length>i)throw new Error("Telegram Rich Markdown code block exceeds the limit");return{source:B,markdown:f}})}function YG(n){let t=HG(n);return i9(t),rB(t)}function jG(n,t=3e4){if(!Number.isInteger(t)||t<128||t>32768)throw new TypeError("Telegram Rich Markdown limit is invalid");let o=HG(n),i=i9(o),e=rB(o);if(Array.from(e).length<=t)return[{source:o,markdown:e}];let a=[],A=0;for(let r=0;rA&&a.push(...a9(o.slice(A,s.index),t));let c=g.index+g[0].length,I=o.slice(s.index,c),d=rB(I);Array.from(d).length<=t?a.push({source:I,markdown:d}):a.push(...PLe(I,s[0],g[0],t)),A=c}return A4096)throw new TypeError("Telegram regular message limit is invalid");return xG(HG(n),t,o=>o.length)}var FLe=Object.freeze([{command:"new",description:"\u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"},{command:"compact",description:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"},{command:"workspace",description:"\u5207\u6362\u5DE5\u4F5C\u533A"},{command:"workspacelist",description:"\u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"},{command:"sessionlist",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"sessions",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"session",description:"\u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"},{command:"models",description:"\u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"},{command:"model",description:"\u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"},{command:"presetlist",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"presets",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"preset",description:"\u67E5\u770B\u6216\u8BBE\u7F6E\u65B0\u4F1A\u8BDD Agent Preset"},{command:"stop",description:"\u505C\u6B62\u5F53\u524D\u4EFB\u52A1"},{command:"steer",description:"\u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"},{command:"batch",description:"\u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF09"},{command:"send",description:"\u63D0\u4EA4\u5F53\u524D\u6279\u6B21"},{command:"cancel",description:"\u53D6\u6D88\u5F53\u524D\u6279\u6B21"},{command:"status",description:"\u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"},{command:"version",description:"\u67E5\u770B\u63D2\u4EF6\u7248\u672C"},{command:"help",description:"\u663E\u793A\u5E2E\u52A9"}]);function LLe(){return FLe.map(n=>({...n,description:w(n.description)}))}function ULe(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function HLe(n,t){return t?[[n?.text,n?.entities],[n?.caption,n?.caption_entities]].some(([o,i])=>typeof o=="string"&&Array.isArray(i)&&i.some(e=>e?.type!=="mention"||!Number.isInteger(e.offset)||!Number.isInteger(e.length)?!1:o.slice(e.offset,e.offset+e.length).toLowerCase()===`@${t.toLowerCase()}`)):!1}function KLe(n,t){return!t||typeof n!="string"?n:n.replace(new RegExp(`@${ULe(t)}\\b`,"ig"),"").trim()}var xLe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),YLe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]);function VG(n){let t=n?.mime_type??n?.mimetype,o=typeof t=="string"?t.toLowerCase():"";if(xLe.has(o))return o;let i=typeof n?.file_name=="string"?n.file_name.toLowerCase():"";for(let[e,a]of YLe)if(i.endsWith(e))return a;return null}function WG(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function Bw(n){return WG(n?.file_size)??(Number(n?.width)||0)*(Number(n?.height)||0)}function jLe(n,t){let o,i,e;if(Array.isArray(n?.photo)&&n.photo.length>0)o=n.photo.reduce((a,A)=>Bw(A)>Bw(a)?A:a),i="image/jpeg",e=`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`;else if(n?.document){let a=VG(n.document);if(!a)return null;o=n.document,i=a,e=typeof o.file_name=="string"?o.file_name:void 0}return!o||typeof o.file_id!="string"?null:{name:e,mediaType:i,size:WG(o.file_size),load:a=>t(o.file_id,a)}}function JLe(n,t){let o=n?.document;if(!o||VG(o)||typeof o.file_id!="string"||!o.file_id)return null;let i=typeof o.mime_type=="string"&&o.mime_type?o.mime_type.toLowerCase():void 0;return{name:typeof o.file_name=="string"&&o.file_name?o.file_name:String(o.file_unique_id??o.file_id),...i?{mediaType:i}:{},size:WG(o.file_size),load:({signal:e}={})=>t(o.file_id,{signal:e})}}function Cw(n,t,o){if(!t||typeof t!="object")return null;let i=typeof t.file_name=="string"&&t.file_name?t.file_name:typeof o=="string"&&o?o:void 0;return{kind:n,...i?{name:i}:{}}}function qLe(n){let t=[];if(Array.isArray(n?.photo)&&n.photo.length>0){let o=n.photo.reduce((i,e)=>Bw(e)>Bw(i)?e:i);t.push(Cw("image",o,`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`))}else n?.document&&t.push(Cw(VG(n.document)?"image":"file",n.document));for(let[o,i]of[["audio","audio"],["voice","audio"],["video","video"],["video_note","video"],["animation","video"]])n?.[o]&&t.push(Cw(i,n[o]));return n?.sticker&&t.push(Cw(n.sticker.is_video===!0?"video":"image",n.sticker,n.sticker.file_unique_id??n.sticker.file_id)),t.filter(Boolean)}function zLe(n,{quote:t,loadReplyContent:o}={}){if((!n||typeof n!="object")&&(!t||typeof t!="object"))return;let i=n?.from?.id===void 0?void 0:String(n.from.id),e=[n?.from?.first_name,n?.from?.last_name].filter(c=>typeof c=="string"&&c.trim()).map(c=>c.trim()).join(" ")||(typeof n?.from?.username=="string"&&n.from.username?n.from.username:void 0),a=typeof n?.text=="string"?n.text:typeof n?.caption=="string"?n.caption:typeof t?.text=="string"?t.text:"",A=qLe(n),r=Number.isSafeInteger(n?.message_id)?String(n.message_id):void 0,s=Number.isSafeInteger(n?.date)&&n.date>=0?n.date*1e3:void 0,g=!a.trim()&&A.length===0&&typeof o=="function"?({signal:c}={})=>o({...r?{messageId:r}:{},...s===void 0?{}:{createdAt:s}},{signal:c}):null;return{...r?{messageId:r}:{},...i?{authorId:i}:{},...e?{authorName:e}:{},...a.trim()?{content:a}:{},...A.length>0?{attachments:A}:{},...g?{load:g}:{},...!a.trim()&&A.length===0&&!g?{unavailableReason:"not-delivered"}:{}}}function VLe(n,{botId:t,username:o,loadFile:i=async()=>{throw new Error("Telegram file downloader is unavailable")},loadFileStream:e=i,loadReplyContent:a}){let A=n?.message,r=A?.chat?.id,s=A?.from?.id,g=A?.message_id;if(!Number.isSafeInteger(n?.update_id)||r===void 0||s===void 0||!Number.isSafeInteger(g)||!["private","group","supergroup"].includes(A.chat?.type))return null;let c=A.chat.type==="private",I=c||String(A.reply_to_message?.from?.id??"")===String(t)||HLe(A,o),d=Number.isSafeInteger(A.message_thread_id)?A.message_thread_id:void 0,B=jLe(A,i),f=JLe(A,e),Q=d===void 0?String(r):`${r}:${d}`,y=`${c?"direct":"group"}:${Q}`,m=zLe(A.reply_to_message??A.external_reply,{quote:A.quote,...typeof a=="function"?{loadReplyContent:(T,_)=>a({conversationKey:y,...T},_)}:{}});return{messageId:String(n.update_id),senderId:String(s),contextSource:()=>({senderName:[A.from?.first_name,A.from?.last_name].filter(T=>typeof T=="string"&&T.trim()).map(T=>T.trim()).join(" ")||A.from?.username,conversationTitle:c?void 0:A.chat?.title,chatId:String(r),threadId:d===void 0?void 0:String(d)}),senderIsBot:A.from?.is_bot===!0,kind:c?"direct":"group",conversationId:Q,content:KLe(A.text??A.caption??"",o),plainText:typeof A.text=="string",images:B?[B]:[],files:f?[f]:[],...m?{replyTo:m}:{},addressed:I,reactionTarget:{chatId:r,messageId:g},replyTarget:{chatId:r,chatType:A.chat.type,replyToMessageId:g,messageThreadId:d},connectionTestTarget:{chatId:r,messageThreadId:d}}}function qG(n){return Number.isSafeInteger(n?.message_id)?String(n.message_id):null}function aB(n){let t=Number(n?.providerCode),o=Number(n?.status),i=n?.deliveryOutcome==="unknown"||t>=500||o>=500||["telegram-timeout","telegram-aborted-after-dispatch","telegram-transport-error","telegram-response-invalid"].includes(n?.code);return{outcome:i?"unknown":"failed",reason:typeof n?.code=="string"&&n.code?n.code:i?"telegram-delivery-uncertain":"telegram-provider-rejected"}}function Ji(n,t,o="sent",i){return{presentation:n,providerMessageIds:[...new Set(t)],deliveryOutcome:o,...i?{reason:i}:{}}}var fw=class{#e;#A;#t;#r;#l;#o=!1;#i=null;constructor({update:t,finish:o,fail:i,providerMessageIds:e=[],presentation:a,logger:A}){this.#e=t,this.#A=o,this.#t=i,this.#l=e,this.presentation=a,this.#r=A}get providerMessageIds(){return[...this.#l]}async update(t){if(this.#o)return;let o=os(t),i=`${o.format}:${o.text}`;if(i!==this.#i){this.#i=i;try{return await this.#e(o)}catch(e){this.#r.warn?.("[dsh-im:telegram] rich stream update failed:",e);return}}}async finish(t){if(this.#o)throw new Error("Message stream is already closed");this.#o=!0;let o=await this.#A(os(t));return this.#l.push(...o?.providerMessageIds??[]),o}async fail(t){if(this.#o)return;this.#o=!0;let o=await this.#t(os(t,"plain"));return this.#l.push(...o?.providerMessageIds??[]),o}cancel(){this.#o=!0}},zG=class{#e;#A;#t;constructor({api:t,signal:o,logger:i=console}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=JG(o),e=[];for(let[a,A]of i.entries()){let r=await this.#e.sendMessage({chatId:t.chatId,text:A,replyToMessageId:a===0?t.replyToMessageId:void 0,messageThreadId:t.messageThreadId,signal:this.#A});Number.isSafeInteger(r?.message_id)&&e.push(String(r.message_id))}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,emoji:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,signal:i??this.#A})}sendTyping(t){return this.#e.sendChatAction({chatId:t.chatId,messageThreadId:t.messageThreadId,signal:this.#A})}sendFile(t,o){return this.#e.sendDocument({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}sendImage(t,o){return this.#e.sendPhoto({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}async#r(t,o,{placeholderMessageId:i}={}){let e=JG(o),a=i===void 0?[]:[String(i)],A=0;if(i!==void 0)try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e[0],signal:this.#A}),A=1}catch(r){let s=aB(r);if(s.outcome==="unknown")return Ji("text-fallback",a,"unknown",s.reason);let g=await this.#r(t,o),c=g.deliveryOutcome==="sent"?"\u56DE\u590D\u5DF2\u53D1\u9001\u3002":g.deliveryOutcome==="unknown"?"\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002":"\u6D88\u606F\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:c,signal:this.#A})}catch(I){this.#t.warn?.("[dsh-im:telegram] unable to replace the processing placeholder:",I)}return Ji("text-fallback",[...a,...g.providerMessageIds],g.deliveryOutcome,g.reason)}for(let r=A;rI.source).join(""),c=await this.#r({...t,replyToMessageId:a===0?t.replyToMessageId:void 0},g);return Ji(c.presentation,[...e,...c.providerMessageIds],c.deliveryOutcome,c.reason)}return Ji("telegram-rich-final",e)}async#o(t,o,i){if(i.format==="plain")return this.#r(t,i.text,{placeholderMessageId:o});let e;try{e=jG(i.text)}catch{return this.#r(t,i.text,{placeholderMessageId:o})}let a=[String(o)];try{await this.#e.editMessageText({chatId:t.chatId,messageId:o,richMessage:{markdown:e[0].markdown},signal:this.#A})}catch(A){let r=aB(A);return r.outcome==="unknown"?Ji("telegram-rich-final",a,"unknown",r.reason):this.#r(t,i.text,{placeholderMessageId:o})}for(let[A,r]of e.slice(1).entries())try{let s=await this.#e.sendRichMessage({chatId:t.chatId,richMessage:{markdown:r.markdown},messageThreadId:t.messageThreadId,signal:this.#A}),g=qG(s);g&&a.push(g)}catch(s){let g=aB(s);if(g.outcome==="unknown")return Ji("telegram-rich-final",a,"unknown",g.reason);let c=e.slice(A+1).map(d=>d.source).join(""),I=await this.#r({...t,replyToMessageId:void 0},c);return Ji(I.presentation,[...a,...I.providerMessageIds],I.deliveryOutcome,I.reason)}return Ji("telegram-rich-final",a)}sendDelivery(t,o){return this.#l(t,os(o))}async openDeliveryStream(t){if(t.chatType==="private"){let e=GLe(1,2147483647),a=async r=>{let s={markdown:YG(r.text)};return await this.#e.sendRichMessageDraft({chatId:t.chatId,draftId:e,richMessage:s,messageThreadId:t.messageThreadId,signal:this.#A}),Ji("telegram-rich-draft",[])},A=new fw({update:a,finish:r=>this.#l(t,r),fail:r=>this.#r(t,r.text),presentation:"telegram-rich-draft",logger:this.#t});return await A.update(os("\u6B63\u5728\u5904\u7406\u2026","plain")),A}let i=(await this.#e.sendMessage({chatId:t.chatId,text:"\u6B63\u5728\u5904\u7406\u2026",replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A}))?.message_id;if(!Number.isSafeInteger(i))throw new Error("Telegram did not return a placeholder message id");return new fw({update:async e=>e.format==="plain"?(await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e.text,signal:this.#A}),Ji("text-fallback",[String(i)])):(await this.#e.editMessageText({chatId:t.chatId,messageId:i,richMessage:{markdown:YG(e.text)},signal:this.#A}),Ji("telegram-rich-draft",[String(i)])),finish:e=>this.#o(t,i,e),fail:e=>this.#r(t,e.text,{placeholderMessageId:i}),providerMessageIds:[String(i)],presentation:"telegram-regular",logger:this.#t})}async openStream(t){return oy({limit:4e3,create:async i=>(await this.#e.sendMessage({chatId:t.chatId,text:i,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})).message_id,edit:(i,e)=>this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e,signal:this.#A}),sendRemainder:i=>this.#e.sendMessage({chatId:t.chatId,text:i,messageThreadId:t.messageThreadId,signal:this.#A}),messageIdForResult:i=>i?.message_id}).start()}};function WLe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...so()}}var iB=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d=WLe();#c=null;#g=null;#I=null;#p=null;#h=null;#u=null;constructor({config:t,token:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,logger:r=console,replyTimeoutMs:s=6e5,createApi:g=I=>new AB(I),createHttpTransport:c=r9}){if(!t||!o||!i||!e)throw new TypeError("TelegramRuntime requires config, token, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c}get status(){return structuredClone(this.#d)}async sendConnectionTest(t){if(!this.#d.ready||!this.#I){let o=new Error("Telegram bot is not connected");throw o.code="test-target-unavailable",o}return this.#I.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#d.ready||!this.#I){let r=new Error("Telegram bot is not connected");throw r.code="bot-not-connected",r}let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"",a=Number(e),A=t?.route?.messageThreadId;if(!/^-?\d+$/.test(e)||!Number.isSafeInteger(a)||t?.kind!=="chat"&&t?.kind!=="topic"||t.kind==="topic"&&(!Number.isSafeInteger(A)||A<=0)||t.kind==="chat"&&A!==void 0){let r=new TypeError("Invalid Telegram proactive delivery target");throw r.code="invalid-target",r}return this.#I.sendProactiveText({chatId:a,...t.kind==="topic"?{messageThreadId:A}:{}},o,i)}async start(){return this.#d.ready&&this.#h?this.status:this.#u?this.#u:(this.#u=this.#C().finally(()=>{this.#u=null}),this.#u)}async#C(){await this.stop(),this.#d.startedAt=new Date().toISOString(),this.#d.connectionState="connecting",this.#d.lastError=null,await this.#t.ensureRunning(),this.#d.harnessReachable=!0;let t=new AbortController;this.#p=t;try{let o=this.#s();this.#c=o;let i=this.#n({token:this.#A,fetchImpl:o.fetchImpl,FormDataImpl:o.FormDataImpl});this.#g=i;let e=await i.getMe({signal:t.signal});if(String(e?.id??"")!==this.#e.platformId||e?.is_bot!==!0)throw new Error("Telegram token identity does not match the saved bot");let a=await i.getWebhookInfo({signal:t.signal});if(typeof a?.url=="string"&&a.url){let g=new Error(w("\u8BE5 Telegram \u673A\u5668\u4EBA\u5DF2\u914D\u7F6E Webhook\uFF0C\u8BF7\u5148\u5728\u539F\u670D\u52A1\u4E2D\u79FB\u9664 Webhook \u540E\u91CD\u8BD5\u3002"));throw g.code="webhook-configured",g}try{await i.setMyCommands({commands:LLe(),signal:t.signal}),await i.setChatMenuButton({menuButton:FG,signal:t.signal})}catch(g){this.#i.warn?.(`[dsh-im:telegram] bot ${this.#e.botId} command menu setup failed:`,g)}let A=new zG({api:i,signal:t.signal,logger:this.#i});this.#I=new uw({bot:A,harness:this.#t,state:this.#r,contextEnhancement:this.#l,accessPolicy:this.#o,status:this.#d,logger:this.#i,replyTimeoutMs:this.#a,signal:t.signal});let r=this.#r.cursor();if(r===null){let g=await i.getUpdates({offset:-1,timeout:0,signal:t.signal});r=g.length>0?g.at(-1).update_id+1:0,await this.#r.setCursor(r)}let s=Date.now();return this.#d.ready=!0,this.#d.connectionState="connected",this.#d.lastCheckedAt=s,this.#d.lastConnectedAt=s,this.#h=this.#f(r,t.signal),this.#h.catch(g=>{t.signal.aborted||(this.#d.ready=!1,this.#d.connectionState="failed",this.#d.lastError=g?.message??String(g),this.#i.error?.(`[dsh-im:telegram] bot ${this.#e.botId} polling stopped:`,g))}),this.status}catch(o){throw this.#d.ready=!1,this.#d.connectionState="failed",this.#d.lastError=o?.message??String(o),await this.stop(),o}}async#B(t,{signal:o}={}){let i=typeof t?.conversationKey=="string"?t.conversationKey.trim():"",e=Number(t?.createdAt);if(!i||!Number.isFinite(e))return{unavailableReason:"not-delivered"};let a=this.#r.sessionFor(i),A=typeof a=="string"&&a?this.#t.workspaceSession?.(a):null,r=await Ud({session:A,quotedAt:e,signal:o});return r?{content:r}:{unavailableReason:"not-delivered"}}async#f(t,o){let i=t;for(;!o.aborted;){let e=await this.#g.getUpdates({offset:i,timeout:25,signal:o});if(this.#d.lastCheckedAt=Date.now(),o.aborted)return;let a=e.map(A=>{let r=A?.message?.chat?.type;return{update:A,contextSnapshot:aa(this.#l,r==="private"?"direct":r==="group"||r==="supergroup"?"group":null)}});for(let{update:A,contextSnapshot:r}of a){if(o.aborted)return;let s=VLe(A,{botId:this.#e.platformId,username:this.#e.username,loadFile:(g,c)=>this.#g.downloadFile({fileId:g,...c}),loadFileStream:(g,c)=>this.#g.downloadFileStream({fileId:g,...c}),loadReplyContent:(g,c)=>this.#B(g,c)});s&&this.#I.accept(s,{contextSnapshot:r}).catch(g=>{o.aborted||this.#i.error?.(`[dsh-im:telegram] bot ${this.#e.botId} message handling failed:`,g)}),i=A.update_id+1,await this.#r.setCursor(i)}}}async stop(){let t=this.#h,o=this.#I,i=this.#c;this.#p?.abort(),this.#p=null,this.#h=null,this.#c=null,this.#g=null,this.#I=null,await Promise.race([t?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]);try{await i?.destroy()}catch{this.#i.warn?.("[dsh-im:telegram] Telegram HTTP transport cleanup failed")}return this.#d.ready=!1,this.#d.connectionState="idle",this.status}};var Qw=class extends ds{};function ZG(n,t={},o={}){return gy(n,t,o,{channel:"telegram",ConfigStore:pw,StateStore:Qw,HarnessClient:Ew,Controller:tB,Runtime:iB})}var o9="/telegram",n9=Nr,ZLe=Object.freeze(Object.values(n9));function s9(n){return Iy(n,{channel:"Telegram"})}function yw(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(o9,s9(t),{authority:yr(o)})}async function g9(n,t={}){if(t?.controller)return yw(n,t.controller,t.rpcAuthority);let o=await ZG(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=yw(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Telegram bot connections"),e}import{unlink as Y2e}from"node:fs/promises";import{homedir as j2e}from"node:os";import{join as cB,resolve as Nl}from"node:path";import{createHash as XLe}from"node:crypto";import{mkdir as $Le,readFile as e2e,rename as A2e,unlink as t2e,writeFile as r2e}from"node:fs/promises";import{dirname as a2e}from"node:path";var XG=Object.freeze({version:1,bots:Object.freeze([])});function Ml(n){return typeof n=="string"&&n.trim()?n.trim():null}function c9(n){let t=Ml(n);return t&&/^wecom_[a-f0-9]{24}$/.test(t)?t:null}function i2e(n){let t=Ml(n);return t&&/^DSH_WECOM_BOT_SECRET_[A-F0-9]{24}$/.test(t)?t:null}function Sw(n){let t=Ml(n);if(!t)throw new TypeError("Enterprise WeChat bot ID is required");let o=XLe("sha256").update(t).digest("hex").slice(0,24);return{botId:`wecom_${o}`,secretRef:`DSH_WECOM_BOT_SECRET_${o.toUpperCase()}`}}function $G(n){let t=Ml(n)??"";return t?t.length<=10?`${t.slice(0,3)}\u2022\u2022\u2022`:`${t.slice(0,6)}\u2022\u2022\u2022\u2022${t.slice(-4)}`:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA")}function I9(n){if(!n||typeof n!="object")return null;let t=c9(n.botId),o=Ml(n.remoteBotId),i=i2e(n.secretRef);if(!t||!o||!i)return null;let e=Sw(o);return e.botId!==t||e.secretRef!==i?null:Object.freeze({botId:t,remoteBotId:o,secretRef:i,createdAt:Ml(n.createdAt)??new Date().toISOString(),connectedAt:Ml(n.connectedAt)})}function o2e(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let t=n.bots.map(I9);if(t.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.remoteBotId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.remoteBotId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(t)})}var mw=class{#e;#A=XG;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=o2e(JSON.parse(await e2e(this.#e,"utf8")));if(!t)throw new Error("dsh-im Enterprise WeChat config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=XG}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByRemoteBotId(t){let o=this.#A.bots.find(i=>i.remoteBotId===t);return o?structuredClone(o):null}async save(t){let o=I9(t);if(!o)throw new Error("Refusing to persist incomplete Enterprise WeChat bot data");return this.#r(i=>{let e=i.find(r=>r.remoteBotId===o.remoteBotId&&r.botId!==o.botId),a=i.find(r=>r.secretRef===o.secretRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate Enterprise WeChat bot identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!c9(t))throw new TypeError("Invalid Enterprise WeChat bot ID");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await t2e(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=XG});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#l(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#l(t){await $Le(a2e(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await r2e(o,`${JSON.stringify(t,null,2)} +`,d=c?o:"```",B=`${g===0?t:""}${s}${c?o:""}`,f=rB(`${t}${s}${I}${d}`);if(Array.from(f).length>i)throw new Error("Telegram Rich Markdown code block exceeds the limit");return{source:B,markdown:f}})}function YG(n){let t=HG(n);return i9(t),rB(t)}function jG(n,t=3e4){if(!Number.isInteger(t)||t<128||t>32768)throw new TypeError("Telegram Rich Markdown limit is invalid");let o=HG(n),i=i9(o),e=rB(o);if(Array.from(e).length<=t)return[{source:o,markdown:e}];let a=[],A=0;for(let r=0;rA&&a.push(...a9(o.slice(A,s.index),t));let c=g.index+g[0].length,I=o.slice(s.index,c),d=rB(I);Array.from(d).length<=t?a.push({source:I,markdown:d}):a.push(...PLe(I,s[0],g[0],t)),A=c}return A4096)throw new TypeError("Telegram regular message limit is invalid");return xG(HG(n),t,o=>o.length)}var FLe=Object.freeze([{command:"new",description:"\u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"},{command:"compact",description:"\u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"},{command:"workspace",description:"\u5207\u6362\u5DE5\u4F5C\u533A"},{command:"ws",description:"\u5207\u6362\u5DE5\u4F5C\u533A"},{command:"workspacelist",description:"\u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"},{command:"workspaces",description:"\u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"},{command:"wsl",description:"\u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"},{command:"sessionlist",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"sessions",description:"\u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"},{command:"session",description:"\u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"},{command:"models",description:"\u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"},{command:"model",description:"\u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"},{command:"presetlist",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"presets",description:"\u5217\u51FA\u53EF\u7528 Agent Preset"},{command:"preset",description:"\u67E5\u770B\u6216\u8BBE\u7F6E\u65B0\u4F1A\u8BDD Agent Preset"},{command:"stop",description:"\u505C\u6B62\u5F53\u524D\u4EFB\u52A1"},{command:"steer",description:"\u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"},{command:"batch",description:"\u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF09"},{command:"send",description:"\u63D0\u4EA4\u5F53\u524D\u6279\u6B21"},{command:"cancel",description:"\u53D6\u6D88\u5F53\u524D\u6279\u6B21"},{command:"status",description:"\u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"},{command:"version",description:"\u67E5\u770B\u63D2\u4EF6\u7248\u672C"},{command:"help",description:"\u663E\u793A\u5E2E\u52A9"}]);function LLe(){return FLe.map(n=>({...n,description:w(n.description)}))}function ULe(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function HLe(n,t){return t?[[n?.text,n?.entities],[n?.caption,n?.caption_entities]].some(([o,i])=>typeof o=="string"&&Array.isArray(i)&&i.some(e=>e?.type!=="mention"||!Number.isInteger(e.offset)||!Number.isInteger(e.length)?!1:o.slice(e.offset,e.offset+e.length).toLowerCase()===`@${t.toLowerCase()}`)):!1}function KLe(n,t){return!t||typeof n!="string"?n:n.replace(new RegExp(`@${ULe(t)}\\b`,"ig"),"").trim()}var xLe=new Set(["image/jpeg","image/png","image/webp","image/gif"]),YLe=new Map([[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".gif","image/gif"]]);function VG(n){let t=n?.mime_type??n?.mimetype,o=typeof t=="string"?t.toLowerCase():"";if(xLe.has(o))return o;let i=typeof n?.file_name=="string"?n.file_name.toLowerCase():"";for(let[e,a]of YLe)if(i.endsWith(e))return a;return null}function WG(n){return Number.isSafeInteger(n)&&n>=0?n:void 0}function Bw(n){return WG(n?.file_size)??(Number(n?.width)||0)*(Number(n?.height)||0)}function jLe(n,t){let o,i,e;if(Array.isArray(n?.photo)&&n.photo.length>0)o=n.photo.reduce((a,A)=>Bw(A)>Bw(a)?A:a),i="image/jpeg",e=`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`;else if(n?.document){let a=VG(n.document);if(!a)return null;o=n.document,i=a,e=typeof o.file_name=="string"?o.file_name:void 0}return!o||typeof o.file_id!="string"?null:{name:e,mediaType:i,size:WG(o.file_size),load:a=>t(o.file_id,a)}}function JLe(n,t){let o=n?.document;if(!o||VG(o)||typeof o.file_id!="string"||!o.file_id)return null;let i=typeof o.mime_type=="string"&&o.mime_type?o.mime_type.toLowerCase():void 0;return{name:typeof o.file_name=="string"&&o.file_name?o.file_name:String(o.file_unique_id??o.file_id),...i?{mediaType:i}:{},size:WG(o.file_size),load:({signal:e}={})=>t(o.file_id,{signal:e})}}function Cw(n,t,o){if(!t||typeof t!="object")return null;let i=typeof t.file_name=="string"&&t.file_name?t.file_name:typeof o=="string"&&o?o:void 0;return{kind:n,...i?{name:i}:{}}}function qLe(n){let t=[];if(Array.isArray(n?.photo)&&n.photo.length>0){let o=n.photo.reduce((i,e)=>Bw(e)>Bw(i)?e:i);t.push(Cw("image",o,`${o.file_unique_id??o.file_id??"telegram-photo"}.jpg`))}else n?.document&&t.push(Cw(VG(n.document)?"image":"file",n.document));for(let[o,i]of[["audio","audio"],["voice","audio"],["video","video"],["video_note","video"],["animation","video"]])n?.[o]&&t.push(Cw(i,n[o]));return n?.sticker&&t.push(Cw(n.sticker.is_video===!0?"video":"image",n.sticker,n.sticker.file_unique_id??n.sticker.file_id)),t.filter(Boolean)}function zLe(n,{quote:t,loadReplyContent:o}={}){if((!n||typeof n!="object")&&(!t||typeof t!="object"))return;let i=n?.from?.id===void 0?void 0:String(n.from.id),e=[n?.from?.first_name,n?.from?.last_name].filter(c=>typeof c=="string"&&c.trim()).map(c=>c.trim()).join(" ")||(typeof n?.from?.username=="string"&&n.from.username?n.from.username:void 0),a=typeof n?.text=="string"?n.text:typeof n?.caption=="string"?n.caption:typeof t?.text=="string"?t.text:"",A=qLe(n),r=Number.isSafeInteger(n?.message_id)?String(n.message_id):void 0,s=Number.isSafeInteger(n?.date)&&n.date>=0?n.date*1e3:void 0,g=!a.trim()&&A.length===0&&typeof o=="function"?({signal:c}={})=>o({...r?{messageId:r}:{},...s===void 0?{}:{createdAt:s}},{signal:c}):null;return{...r?{messageId:r}:{},...i?{authorId:i}:{},...e?{authorName:e}:{},...a.trim()?{content:a}:{},...A.length>0?{attachments:A}:{},...g?{load:g}:{},...!a.trim()&&A.length===0&&!g?{unavailableReason:"not-delivered"}:{}}}function VLe(n,{botId:t,username:o,loadFile:i=async()=>{throw new Error("Telegram file downloader is unavailable")},loadFileStream:e=i,loadReplyContent:a}){let A=n?.message,r=A?.chat?.id,s=A?.from?.id,g=A?.message_id;if(!Number.isSafeInteger(n?.update_id)||r===void 0||s===void 0||!Number.isSafeInteger(g)||!["private","group","supergroup"].includes(A.chat?.type))return null;let c=A.chat.type==="private",I=c||String(A.reply_to_message?.from?.id??"")===String(t)||HLe(A,o),d=Number.isSafeInteger(A.message_thread_id)?A.message_thread_id:void 0,B=jLe(A,i),f=JLe(A,e),Q=d===void 0?String(r):`${r}:${d}`,y=`${c?"direct":"group"}:${Q}`,m=zLe(A.reply_to_message??A.external_reply,{quote:A.quote,...typeof a=="function"?{loadReplyContent:(T,_)=>a({conversationKey:y,...T},_)}:{}});return{messageId:String(n.update_id),senderId:String(s),contextSource:()=>({senderName:[A.from?.first_name,A.from?.last_name].filter(T=>typeof T=="string"&&T.trim()).map(T=>T.trim()).join(" ")||A.from?.username,conversationTitle:c?void 0:A.chat?.title,chatId:String(r),threadId:d===void 0?void 0:String(d)}),senderIsBot:A.from?.is_bot===!0,kind:c?"direct":"group",conversationId:Q,content:KLe(A.text??A.caption??"",o),plainText:typeof A.text=="string",images:B?[B]:[],files:f?[f]:[],...m?{replyTo:m}:{},addressed:I,reactionTarget:{chatId:r,messageId:g},replyTarget:{chatId:r,chatType:A.chat.type,replyToMessageId:g,messageThreadId:d},connectionTestTarget:{chatId:r,messageThreadId:d}}}function qG(n){return Number.isSafeInteger(n?.message_id)?String(n.message_id):null}function aB(n){let t=Number(n?.providerCode),o=Number(n?.status),i=n?.deliveryOutcome==="unknown"||t>=500||o>=500||["telegram-timeout","telegram-aborted-after-dispatch","telegram-transport-error","telegram-response-invalid"].includes(n?.code);return{outcome:i?"unknown":"failed",reason:typeof n?.code=="string"&&n.code?n.code:i?"telegram-delivery-uncertain":"telegram-provider-rejected"}}function Ji(n,t,o="sent",i){return{presentation:n,providerMessageIds:[...new Set(t)],deliveryOutcome:o,...i?{reason:i}:{}}}var fw=class{#e;#A;#t;#r;#l;#o=!1;#i=null;constructor({update:t,finish:o,fail:i,providerMessageIds:e=[],presentation:a,logger:A}){this.#e=t,this.#A=o,this.#t=i,this.#l=e,this.presentation=a,this.#r=A}get providerMessageIds(){return[...this.#l]}async update(t){if(this.#o)return;let o=os(t),i=`${o.format}:${o.text}`;if(i!==this.#i){this.#i=i;try{return await this.#e(o)}catch(e){this.#r.warn?.("[dsh-im:telegram] rich stream update failed:",e);return}}}async finish(t){if(this.#o)throw new Error("Message stream is already closed");this.#o=!0;let o=await this.#A(os(t));return this.#l.push(...o?.providerMessageIds??[]),o}async fail(t){if(this.#o)return;this.#o=!0;let o=await this.#t(os(t,"plain"));return this.#l.push(...o?.providerMessageIds??[]),o}cancel(){this.#o=!0}},zG=class{#e;#A;#t;constructor({api:t,signal:o,logger:i=console}){this.#e=t,this.#A=o,this.#t=i}async sendText(t,o){let i=JG(o),e=[];for(let[a,A]of i.entries()){let r=await this.#e.sendMessage({chatId:t.chatId,text:A,replyToMessageId:a===0?t.replyToMessageId:void 0,messageThreadId:t.messageThreadId,signal:this.#A});Number.isSafeInteger(r?.message_id)&&e.push(String(r.message_id))}return{providerMessageIds:e}}async addReaction(t,o,{signal:i}={}){let e=String(o??"").trim();return await this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,emoji:e,signal:i??this.#A}),e}removeReaction(t,o,{signal:i}={}){return this.#e.setMessageReaction({chatId:t.chatId,messageId:t.messageId,signal:i??this.#A})}sendTyping(t){return this.#e.sendChatAction({chatId:t.chatId,messageThreadId:t.messageThreadId,signal:this.#A})}sendFile(t,o){return this.#e.sendDocument({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}sendImage(t,o){return this.#e.sendPhoto({chatId:t.chatId,file:o,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})}async#r(t,o,{placeholderMessageId:i}={}){let e=JG(o),a=i===void 0?[]:[String(i)],A=0;if(i!==void 0)try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e[0],signal:this.#A}),A=1}catch(r){let s=aB(r);if(s.outcome==="unknown")return Ji("text-fallback",a,"unknown",s.reason);let g=await this.#r(t,o),c=g.deliveryOutcome==="sent"?"\u56DE\u590D\u5DF2\u53D1\u9001\u3002":g.deliveryOutcome==="unknown"?"\u56DE\u590D\u53D1\u9001\u7ED3\u679C\u672A\u80FD\u786E\u8BA4\u3002":"\u6D88\u606F\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";try{await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:c,signal:this.#A})}catch(I){this.#t.warn?.("[dsh-im:telegram] unable to replace the processing placeholder:",I)}return Ji("text-fallback",[...a,...g.providerMessageIds],g.deliveryOutcome,g.reason)}for(let r=A;rI.source).join(""),c=await this.#r({...t,replyToMessageId:a===0?t.replyToMessageId:void 0},g);return Ji(c.presentation,[...e,...c.providerMessageIds],c.deliveryOutcome,c.reason)}return Ji("telegram-rich-final",e)}async#o(t,o,i){if(i.format==="plain")return this.#r(t,i.text,{placeholderMessageId:o});let e;try{e=jG(i.text)}catch{return this.#r(t,i.text,{placeholderMessageId:o})}let a=[String(o)];try{await this.#e.editMessageText({chatId:t.chatId,messageId:o,richMessage:{markdown:e[0].markdown},signal:this.#A})}catch(A){let r=aB(A);return r.outcome==="unknown"?Ji("telegram-rich-final",a,"unknown",r.reason):this.#r(t,i.text,{placeholderMessageId:o})}for(let[A,r]of e.slice(1).entries())try{let s=await this.#e.sendRichMessage({chatId:t.chatId,richMessage:{markdown:r.markdown},messageThreadId:t.messageThreadId,signal:this.#A}),g=qG(s);g&&a.push(g)}catch(s){let g=aB(s);if(g.outcome==="unknown")return Ji("telegram-rich-final",a,"unknown",g.reason);let c=e.slice(A+1).map(d=>d.source).join(""),I=await this.#r({...t,replyToMessageId:void 0},c);return Ji(I.presentation,[...a,...I.providerMessageIds],I.deliveryOutcome,I.reason)}return Ji("telegram-rich-final",a)}sendDelivery(t,o){return this.#l(t,os(o))}async openDeliveryStream(t){if(t.chatType==="private"){let e=GLe(1,2147483647),a=async r=>{let s={markdown:YG(r.text)};return await this.#e.sendRichMessageDraft({chatId:t.chatId,draftId:e,richMessage:s,messageThreadId:t.messageThreadId,signal:this.#A}),Ji("telegram-rich-draft",[])},A=new fw({update:a,finish:r=>this.#l(t,r),fail:r=>this.#r(t,r.text),presentation:"telegram-rich-draft",logger:this.#t});return await A.update(os("\u6B63\u5728\u5904\u7406\u2026","plain")),A}let i=(await this.#e.sendMessage({chatId:t.chatId,text:"\u6B63\u5728\u5904\u7406\u2026",replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A}))?.message_id;if(!Number.isSafeInteger(i))throw new Error("Telegram did not return a placeholder message id");return new fw({update:async e=>e.format==="plain"?(await this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e.text,signal:this.#A}),Ji("text-fallback",[String(i)])):(await this.#e.editMessageText({chatId:t.chatId,messageId:i,richMessage:{markdown:YG(e.text)},signal:this.#A}),Ji("telegram-rich-draft",[String(i)])),finish:e=>this.#o(t,i,e),fail:e=>this.#r(t,e.text,{placeholderMessageId:i}),providerMessageIds:[String(i)],presentation:"telegram-regular",logger:this.#t})}async openStream(t){return oy({limit:4e3,create:async i=>(await this.#e.sendMessage({chatId:t.chatId,text:i,replyToMessageId:t.replyToMessageId,messageThreadId:t.messageThreadId,signal:this.#A})).message_id,edit:(i,e)=>this.#e.editMessageText({chatId:t.chatId,messageId:i,text:e,signal:this.#A}),sendRemainder:i=>this.#e.sendMessage({chatId:t.chatId,text:i,messageThreadId:t.messageThreadId,signal:this.#A}),messageIdForResult:i=>i?.message_id}).start()}};function WLe(){return{startedAt:null,ready:!1,connectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...so()}}var iB=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d=WLe();#c=null;#g=null;#I=null;#p=null;#h=null;#u=null;constructor({config:t,token:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,logger:r=console,replyTimeoutMs:s=6e5,createApi:g=I=>new AB(I),createHttpTransport:c=r9}){if(!t||!o||!i||!e)throw new TypeError("TelegramRuntime requires config, token, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c}get status(){return structuredClone(this.#d)}async sendConnectionTest(t){if(!this.#d.ready||!this.#I){let o=new Error("Telegram bot is not connected");throw o.code="test-target-unavailable",o}return this.#I.sendConnectionTest(t)}async sendProactiveText(t,o,i={}){if(!this.#d.ready||!this.#I){let r=new Error("Telegram bot is not connected");throw r.code="bot-not-connected",r}let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"",a=Number(e),A=t?.route?.messageThreadId;if(!/^-?\d+$/.test(e)||!Number.isSafeInteger(a)||t?.kind!=="chat"&&t?.kind!=="topic"||t.kind==="topic"&&(!Number.isSafeInteger(A)||A<=0)||t.kind==="chat"&&A!==void 0){let r=new TypeError("Invalid Telegram proactive delivery target");throw r.code="invalid-target",r}return this.#I.sendProactiveText({chatId:a,...t.kind==="topic"?{messageThreadId:A}:{}},o,i)}async start(){return this.#d.ready&&this.#h?this.status:this.#u?this.#u:(this.#u=this.#C().finally(()=>{this.#u=null}),this.#u)}async#C(){await this.stop(),this.#d.startedAt=new Date().toISOString(),this.#d.connectionState="connecting",this.#d.lastError=null,await this.#t.ensureRunning(),this.#d.harnessReachable=!0;let t=new AbortController;this.#p=t;try{let o=this.#s();this.#c=o;let i=this.#n({token:this.#A,fetchImpl:o.fetchImpl,FormDataImpl:o.FormDataImpl});this.#g=i;let e=await i.getMe({signal:t.signal});if(String(e?.id??"")!==this.#e.platformId||e?.is_bot!==!0)throw new Error("Telegram token identity does not match the saved bot");let a=await i.getWebhookInfo({signal:t.signal});if(typeof a?.url=="string"&&a.url){let g=new Error(w("\u8BE5 Telegram \u673A\u5668\u4EBA\u5DF2\u914D\u7F6E Webhook\uFF0C\u8BF7\u5148\u5728\u539F\u670D\u52A1\u4E2D\u79FB\u9664 Webhook \u540E\u91CD\u8BD5\u3002"));throw g.code="webhook-configured",g}try{await i.setMyCommands({commands:LLe(),signal:t.signal}),await i.setChatMenuButton({menuButton:FG,signal:t.signal})}catch(g){this.#i.warn?.(`[dsh-im:telegram] bot ${this.#e.botId} command menu setup failed:`,g)}let A=new zG({api:i,signal:t.signal,logger:this.#i});this.#I=new uw({bot:A,harness:this.#t,state:this.#r,contextEnhancement:this.#l,accessPolicy:this.#o,status:this.#d,logger:this.#i,replyTimeoutMs:this.#a,signal:t.signal});let r=this.#r.cursor();if(r===null){let g=await i.getUpdates({offset:-1,timeout:0,signal:t.signal});r=g.length>0?g.at(-1).update_id+1:0,await this.#r.setCursor(r)}let s=Date.now();return this.#d.ready=!0,this.#d.connectionState="connected",this.#d.lastCheckedAt=s,this.#d.lastConnectedAt=s,this.#h=this.#f(r,t.signal),this.#h.catch(g=>{t.signal.aborted||(this.#d.ready=!1,this.#d.connectionState="failed",this.#d.lastError=g?.message??String(g),this.#i.error?.(`[dsh-im:telegram] bot ${this.#e.botId} polling stopped:`,g))}),this.status}catch(o){throw this.#d.ready=!1,this.#d.connectionState="failed",this.#d.lastError=o?.message??String(o),await this.stop(),o}}async#B(t,{signal:o}={}){let i=typeof t?.conversationKey=="string"?t.conversationKey.trim():"",e=Number(t?.createdAt);if(!i||!Number.isFinite(e))return{unavailableReason:"not-delivered"};let a=this.#r.sessionFor(i),A=typeof a=="string"&&a?this.#t.workspaceSession?.(a):null,r=await Ud({session:A,quotedAt:e,signal:o});return r?{content:r}:{unavailableReason:"not-delivered"}}async#f(t,o){let i=t;for(;!o.aborted;){let e=await this.#g.getUpdates({offset:i,timeout:25,signal:o});if(this.#d.lastCheckedAt=Date.now(),o.aborted)return;let a=e.map(A=>{let r=A?.message?.chat?.type;return{update:A,contextSnapshot:aa(this.#l,r==="private"?"direct":r==="group"||r==="supergroup"?"group":null)}});for(let{update:A,contextSnapshot:r}of a){if(o.aborted)return;let s=VLe(A,{botId:this.#e.platformId,username:this.#e.username,loadFile:(g,c)=>this.#g.downloadFile({fileId:g,...c}),loadFileStream:(g,c)=>this.#g.downloadFileStream({fileId:g,...c}),loadReplyContent:(g,c)=>this.#B(g,c)});s&&this.#I.accept(s,{contextSnapshot:r}).catch(g=>{o.aborted||this.#i.error?.(`[dsh-im:telegram] bot ${this.#e.botId} message handling failed:`,g)}),i=A.update_id+1,await this.#r.setCursor(i)}}}async stop(){let t=this.#h,o=this.#I,i=this.#c;this.#p?.abort(),this.#p=null,this.#h=null,this.#c=null,this.#g=null,this.#I=null,await Promise.race([t?.catch(()=>{})??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]),await Promise.race([o?.waitForIdle()??Promise.resolve(),new Promise(e=>setTimeout(e,2e3))]);try{await i?.destroy()}catch{this.#i.warn?.("[dsh-im:telegram] Telegram HTTP transport cleanup failed")}return this.#d.ready=!1,this.#d.connectionState="idle",this.status}};var Qw=class extends ds{};function ZG(n,t={},o={}){return gy(n,t,o,{channel:"telegram",ConfigStore:pw,StateStore:Qw,HarnessClient:Ew,Controller:tB,Runtime:iB})}var o9="/telegram",n9=Nr,ZLe=Object.freeze(Object.values(n9));function s9(n){return Iy(n,{channel:"Telegram"})}function yw(n,t,o){if(!n?.connection?.rpc||typeof n.connection.rpc.handle!="function")throw new TypeError("DSH Host Connection RPC is required");return n.connection.rpc.handle(o9,s9(t),{authority:yr(o)})}async function g9(n,t={}){if(t?.controller)return yw(n,t.controller,t.rpcAuthority);let o=await ZG(n,t,t.internals??{}),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=yw(n,o.controller,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Telegram bot connections"),e}import{unlink as Y2e}from"node:fs/promises";import{homedir as j2e}from"node:os";import{join as cB,resolve as Nl}from"node:path";import{createHash as XLe}from"node:crypto";import{mkdir as $Le,readFile as e2e,rename as A2e,unlink as t2e,writeFile as r2e}from"node:fs/promises";import{dirname as a2e}from"node:path";var XG=Object.freeze({version:1,bots:Object.freeze([])});function Ml(n){return typeof n=="string"&&n.trim()?n.trim():null}function c9(n){let t=Ml(n);return t&&/^wecom_[a-f0-9]{24}$/.test(t)?t:null}function i2e(n){let t=Ml(n);return t&&/^DSH_WECOM_BOT_SECRET_[A-F0-9]{24}$/.test(t)?t:null}function Sw(n){let t=Ml(n);if(!t)throw new TypeError("Enterprise WeChat bot ID is required");let o=XLe("sha256").update(t).digest("hex").slice(0,24);return{botId:`wecom_${o}`,secretRef:`DSH_WECOM_BOT_SECRET_${o.toUpperCase()}`}}function $G(n){let t=Ml(n)??"";return t?t.length<=10?`${t.slice(0,3)}\u2022\u2022\u2022`:`${t.slice(0,6)}\u2022\u2022\u2022\u2022${t.slice(-4)}`:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA")}function I9(n){if(!n||typeof n!="object")return null;let t=c9(n.botId),o=Ml(n.remoteBotId),i=i2e(n.secretRef);if(!t||!o||!i)return null;let e=Sw(o);return e.botId!==t||e.secretRef!==i?null:Object.freeze({botId:t,remoteBotId:o,secretRef:i,createdAt:Ml(n.createdAt)??new Date().toISOString(),connectedAt:Ml(n.connectedAt)})}function o2e(n){if(!n||n.version!==1||!Array.isArray(n.bots))return null;let t=n.bots.map(I9);if(t.some(a=>a===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.remoteBotId)||e.has(a.secretRef))return null;o.add(a.botId),i.add(a.remoteBotId),e.add(a.secretRef)}return Object.freeze({version:1,bots:Object.freeze(t)})}var mw=class{#e;#A=XG;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=o2e(JSON.parse(await e2e(this.#e,"utf8")));if(!t)throw new Error("dsh-im Enterprise WeChat config contains invalid bot data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=XG}return this}list(){return structuredClone(this.#A.bots)}get(t){let o=this.#A.bots.find(i=>i.botId===t);return o?structuredClone(o):null}getByRemoteBotId(t){let o=this.#A.bots.find(i=>i.remoteBotId===t);return o?structuredClone(o):null}async save(t){let o=I9(t);if(!o)throw new Error("Refusing to persist incomplete Enterprise WeChat bot data");return this.#r(i=>{let e=i.find(r=>r.remoteBotId===o.remoteBotId&&r.botId!==o.botId),a=i.find(r=>r.secretRef===o.secretRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate Enterprise WeChat bot identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!c9(t))throw new TypeError("Invalid Enterprise WeChat bot ID");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await t2e(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=XG});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.bots];o=t(e);let a=Object.freeze({version:1,bots:Object.freeze(e)});await this.#l(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#l(t){await $Le(a2e(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await r2e(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await A2e(o,this.#e)}};var ww=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"wecom",logPrefix:"dsh-wecom"})}};var n2e="https://work.weixin.qq.com/ai/qc/generate",s2e="https://work.weixin.qq.com/ai/qc/query_result";function l9(){return process.platform==="win32"?2:process.platform==="linux"?3:1}function rh(n){return typeof n=="string"&&n.trim()?n.trim():null}function g2e(n){let t=rh(n);if(!t)return null;try{let o=new URL(t);return o.protocol==="https:"&&o.hostname==="work.weixin.qq.com"&&(!o.port||o.port==="443")?o.href:null}catch{return null}}function c2e(n,t){return n?AbortSignal.any([n,AbortSignal.timeout(t)]):AbortSignal.timeout(t)}async function d9(n,t,o){let i=await n(t,{method:"GET",redirect:"error",signal:c2e(o,1e4),headers:{accept:"application/json"}});if(!i.ok)throw new Error(`Enterprise WeChat QR service returned HTTP ${i.status}`);return i.json()}var Dw=class{#e;#A;#t;#r;constructor({fetch:t=globalThis.fetch,clock:o=()=>Date.now(),source:i="deepseek-harness",platform:e=l9()}={}){if(typeof t!="function")throw new TypeError("A fetch implementation is required");this.#e=t,this.#A=o,this.#t=i,this.#r=[1,2,3].includes(e)?e:l9()}async start({signal:t}={}){let o=new URL(n2e);o.searchParams.set("source",this.#t),o.searchParams.set("plat",String(this.#r));let i=await d9(this.#e,o,t),e=rh(i?.data?.scode),a=g2e(i?.data?.auth_url);if(!e||!a)throw new Error("Enterprise WeChat QR service returned invalid data");return{scode:e,verificationUrl:a,expiresAt:this.#A()+3e5,pollIntervalMs:3e3}}async poll({scode:t,signal:o}={}){let i=rh(t);if(!i)throw new TypeError("Enterprise WeChat QR poll code is required");let e=new URL(s2e);e.searchParams.set("scode",i);let a=await d9(this.#e,e,o),A=rh(a?.data?.status)?.toLowerCase();if(A==="success"){let r=rh(a?.data?.bot_info?.botid),s=rh(a?.data?.bot_info?.secret);if(!r||!s)throw new Error("Enterprise WeChat QR result omitted bot credentials");return{status:"success",remoteBotId:r,secret:s}}return["expired","timeout"].includes(A)?{status:"expired"}:["fail","failed","error"].includes(A)?{status:"failed"}:{status:"waiting"}}};import{mkdir as I2e,readFile as l2e,rename as d2e,unlink as p2e,writeFile as h2e}from"node:fs/promises";import{dirname as E2e}from"node:path";var Ow=Object.freeze({version:1,sessions:{},seenMessageIds:[]});function u2e(n){if(!n||typeof n!="object")return structuredClone(Ow);let t={};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&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[]}}var bw=class{#e;#A=structuredClone(Ow);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=u2e(JSON.parse(await l2e(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(Ow),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}snapshot(){return structuredClone(this.#A)}async remove(){try{await p2e(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(Ow)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await I2e(E2e(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await h2e(i,t,{encoding:"utf8",mode:384}),await d2e(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as C2e}from"node:crypto";var p9=new Set(["pending","connecting"]),oB=new Set(["connected","failed","cancelled","expired"]);function _l(n){return typeof n=="string"&&n.trim()?n.trim():null}function qi(n,t){return Object.freeze({code:n,message:t})}function Tl(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 nB=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new Map;#n=new Map;#s=null;#d=new Map;#c=0;#g=!1;constructor({qrAuth:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.start!="function"||typeof t.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A}async initialize(){if(this.#g)return this.status();for(let t of this.#t.list())await this.#Q(t.botId,async()=>{let o=this.#i.get(t.botId)?.status;if(this.#g||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#B(t.secretRef);if(!i){this.#a.set(t.botId,qi("missing-secret",w("\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.#u(t,i),this.#a.delete(t.botId)}catch{this.#a.set(t.botId,qi("connection-failed",w("\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 ${t.botId} failed to initialize`)}finally{this.#y()}});return this.status()}async startProvisioning(){if(this.#g)throw new Error("Enterprise WeChat controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t={id:C2e(),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(t.id,t),this.#s=t.id,this.#y();try{let o=await this.#e.start({signal:t.controller.signal});if(t.scode=_l(o.scode),t.verificationUrl=_l(o.verificationUrl),t.expiresAt=Number(o.expiresAt),t.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!t.scode||!t.verificationUrl||!Number.isFinite(t.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#y(),Tl(t)}catch(o){throw t.state=t.controller.signal.aborted?"cancelled":"failed",t.error=t.controller.signal.aborted?qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):qi("qr-start-failed",w("\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#S(t),o}}async registrationStatus(t){let o=this.#n.get(t);if(!o||oB.has(o.state))return Tl(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),Tl(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=qi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),o.controller.abort(),this.#S(o),Tl(o);if(!o.polling){let i=this.#I(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),Tl(o)}async bindCredentials({botId:t,secret:o}={}){if(this.#g)throw new Error("Enterprise WeChat controller is closed");let i=_l(t),e=_l(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#s&&await this.cancelProvisioning(this.#s),this.#g)throw new Error("Enterprise WeChat controller is closed");let a=Sw(i);return await this.#Q(a.botId,async()=>{if(this.#g)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),r=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#g)throw new Error("Enterprise WeChat controller is closed");let s={botId:a.botId,remoteBotId:i,secretRef:a.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#f(a.secretRef,r),g}try{await this.#u(s,e),this.#a.delete(a.botId)}catch{this.#a.set(a.botId,qi("connection-failed",w("\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 ${a.botId} credential connection failed`)}this.#y()}),this.status()}async cancelProvisioning(t){let o=this.#n.get(t);return o?(oB.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),oB.has(o.state)||(o.state="cancelled"),o.error??=qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#S(o)),Tl(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(t,async()=>{let i=await this.#B(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#u(o,i),this.#a.delete(t)}catch(e){throw this.#a.set(t,qi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#y()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return this.#Q(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw fr(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(La(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{botId}\uFF09",{botId:$G(o.remoteBotId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Enterprise WeChat bot");return this.#Q(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(t,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#C(t);try{await this.#A.unset(o.secretRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#u(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#l({botId:t,config:o}).catch(e=>{this.#o.warn?.(`[dsh-im:wecom] bot ${t} state cleanup failed:`,e)}),this.#a.delete(t),this.#y()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.wecomConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.wecomConnectionState==="connecting"?"connecting":this.#a.has(e.botId)||a?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),appIdMasked:$G(e.remoteBotId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Aa(a?.lastMessageError),error:structuredClone(this.#a.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#n.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&p9.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&p9.has(i.state)?{provisioning:Tl(i)}:{}}}async close(){this.#g||(this.#g=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#d.values()]),await Promise.allSettled([...this.#i.keys()].map(t=>this.#C(t))))}async#I(t){try{let o=await this.#e.poll({scode:t.scode,signal:t.controller.signal});if(t.controller.signal.aborted||oB.has(t.state)||o.status==="waiting")return;if(o.status==="expired"){t.state="expired",t.error=qi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),this.#S(t);return}if(o.status!=="success"){t.state="failed",t.error=qi("qr-connect-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#S(t);return}t.state="connecting",t.verificationUrl=null,t.expiresAt=null,t.scode=null,this.#y();let i=this.#p(t,o);t.transition=i,await i}catch{if(t.controller.signal.aborted)return;t.state="failed",t.error=qi("qr-connect-failed",w("\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.#S(t)}}async#p(t,o){try{let i=_l(o.remoteBotId),e=_l(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");t.botId=await this.#h(t,{remoteBotId:i,secret:e}),t.state="connected",t.error=null}catch{t.controller.signal.aborted?(t.state="cancelled",t.error=qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=qi("activation-failed",w("\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.#S(t)}}async#h(t,{remoteBotId:o,secret:i}){let e=Sw(o),a=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),r={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:a?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#Q(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(r)}catch(s){throw await this.#f(e.secretRef,A),s}try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#u(r,i),this.#a.delete(e.botId)}catch(s){if(t.controller.signal.aborted)throw await this.#C(e.botId),a?await this.#t.save(a).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#l({botId:e.botId,config:r}).catch(c=>{this.#o.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#f(e.secretRef,A),s;this.#a.set(e.botId,qi("connection-failed",w("\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.#y(),e.botId})}async#u(t,o){if(this.#g)throw new Error("Enterprise WeChat controller is closed");if(await this.#C(t.botId),this.#g)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:t.botId,config:t,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(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#i.delete(t.botId),e}}async#C(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-im:wecom] bot ${t} failed to stop cleanly:`,i)})}async#B(t){let o=await this.#A.resolve(t).catch(()=>{});return _l(o?.value)}async#f(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#Q(t,o){let a=(this.#d.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#d.get(t)===a&&this.#d.delete(t)});return this.#d.set(t,a),a}#S(t){t.scode=null,t.verificationUrl=null,t.expiresAt=null,this.#s===t.id&&(this.#s=null),this.#y();let o=[...this.#n.values()].filter(i=>oB.has(i.state));for(;o.length>16;)this.#n.delete(o.shift().id)}#y(){this.#c+=1}};import{WSAuthFailureError as F2e,WSClient as L2e,WSReconnectExhaustedError as U2e}from"@wecom/aibot-node-sdk";import{generateReqId as B2e}from"@wecom/aibot-node-sdk";var rF=12e4;function f2e(){return[w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` +`,o=this.#t.then(async()=>{await I2e(E2e(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await h2e(i,t,{encoding:"utf8",mode:384}),await d2e(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as C2e}from"node:crypto";var p9=new Set(["pending","connecting"]),oB=new Set(["connected","failed","cancelled","expired"]);function _l(n){return typeof n=="string"&&n.trim()?n.trim():null}function qi(n,t){return Object.freeze({code:n,message:t})}function Tl(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 nB=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new Map;#n=new Map;#s=null;#d=new Map;#c=0;#g=!1;constructor({qrAuth:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.start!="function"||typeof t.poll!="function")throw new TypeError("Enterprise WeChat QR auth is required");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WecomController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WecomController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A}async initialize(){if(this.#g)return this.status();for(let t of this.#t.list())await this.#Q(t.botId,async()=>{let o=this.#i.get(t.botId)?.status;if(this.#g||o?.ready||o?.wecomConnectionState==="connecting")return;let i=await this.#B(t.secretRef);if(!i){this.#a.set(t.botId,qi("missing-secret",w("\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.#u(t,i),this.#a.delete(t.botId)}catch{this.#a.set(t.botId,qi("connection-failed",w("\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 ${t.botId} failed to initialize`)}finally{this.#y()}});return this.status()}async startProvisioning(){if(this.#g)throw new Error("Enterprise WeChat controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t={id:C2e(),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(t.id,t),this.#s=t.id,this.#y();try{let o=await this.#e.start({signal:t.controller.signal});if(t.scode=_l(o.scode),t.verificationUrl=_l(o.verificationUrl),t.expiresAt=Number(o.expiresAt),t.pollIntervalMs=Math.min(1e4,Math.max(500,Number(o.pollIntervalMs)||3e3)),!t.scode||!t.verificationUrl||!Number.isFinite(t.expiresAt))throw new Error("Enterprise WeChat QR auth returned incomplete data");return this.#y(),Tl(t)}catch(o){throw t.state=t.controller.signal.aborted?"cancelled":"failed",t.error=t.controller.signal.aborted?qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")):qi("qr-start-failed",w("\u65E0\u6CD5\u751F\u6210\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")),this.#S(t),o}}async registrationStatus(t){let o=this.#n.get(t);if(!o||oB.has(o.state))return Tl(o);if(o.state==="connecting")return await o.transition?.catch(()=>{}),Tl(o);if(Date.now()>=o.expiresAt)return o.state="expired",o.error=qi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),o.controller.abort(),this.#S(o),Tl(o);if(!o.polling){let i=this.#I(o).finally(()=>{o.polling===i&&(o.polling=null)});o.polling=i}return await o.polling.catch(()=>{}),Tl(o)}async bindCredentials({botId:t,secret:o}={}){if(this.#g)throw new Error("Enterprise WeChat controller is closed");let i=_l(t),e=_l(o);if(!i||!e)throw new TypeError("Enterprise WeChat Bot ID and Secret are required");if(this.#s&&await this.cancelProvisioning(this.#s),this.#g)throw new Error("Enterprise WeChat controller is closed");let a=Sw(i);return await this.#Q(a.botId,async()=>{if(this.#g)throw new Error("Enterprise WeChat controller is closed");let A=this.#t.getByRemoteBotId(i),r=await this.#A.resolve(a.secretRef).catch(()=>{});if(this.#g)throw new Error("Enterprise WeChat controller is closed");let s={botId:a.botId,remoteBotId:i,secretRef:a.secretRef,createdAt:A?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};await this.#A.set(a.secretRef,e);try{await this.#t.save(s)}catch(g){throw await this.#f(a.secretRef,r),g}try{await this.#u(s,e),this.#a.delete(a.botId)}catch{this.#a.set(a.botId,qi("connection-failed",w("\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 ${a.botId} credential connection failed`)}this.#y()}),this.status()}async cancelProvisioning(t){let o=this.#n.get(t);return o?(oB.has(o.state)||(o.controller.abort(),await Promise.allSettled([o.polling,o.transition].filter(Boolean)),oB.has(o.state)||(o.state="cancelled"),o.error??=qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002")),this.#S(o)),Tl(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(t,async()=>{let i=await this.#B(o.secretRef);if(!i)throw new Error("Enterprise WeChat bot secret is missing");try{await this.#u(o,i),this.#a.delete(t)}catch(e){throw this.#a.set(t,qi("connection-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#y()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return this.#Q(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw fr(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(La(w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{botId}\uFF09",{botId:$G(o.remoteBotId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Enterprise WeChat bot");return this.#Q(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Enterprise WeChat bot");return await this.#Q(t,async()=>{let i=await this.#A.resolve(o.secretRef).catch(()=>{});await this.#C(t);try{await this.#A.unset(o.secretRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.secretRef,i.value).catch(()=>{}),await this.#u(o,i.value).catch(()=>{})),new Error("Unable to remove the Enterprise WeChat bot safely.",{cause:e})}await this.#l({botId:t,config:o}).catch(e=>{this.#o.warn?.(`[dsh-im:wecom] bot ${t} state cleanup failed:`,e)}),this.#a.delete(t),this.#y()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.wecomConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.wecomConnectionState==="connecting"?"connecting":this.#a.has(e.botId)||a?.wecomConnectionState==="failed"?"error":"offline";return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),appIdMasked:$G(e.remoteBotId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u4F01\u4E1A\u5FAE\u4FE1 WebSocket \u957F\u8FDE\u63A5\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u4F01\u4E1A\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null,lastConnectedAt:a?.lastConnectedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Aa(a?.lastMessageError),error:structuredClone(this.#a.get(e.botId)??null)}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#n.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&p9.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&p9.has(i.state)?{provisioning:Tl(i)}:{}}}async close(){this.#g||(this.#g=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#d.values()]),await Promise.allSettled([...this.#i.keys()].map(t=>this.#C(t))))}async#I(t){try{let o=await this.#e.poll({scode:t.scode,signal:t.controller.signal});if(t.controller.signal.aborted||oB.has(t.state)||o.status==="waiting")return;if(o.status==="expired"){t.state="expired",t.error=qi("expired",w("\u4F01\u4E1A\u5FAE\u4FE1\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")),this.#S(t);return}if(o.status!=="success"){t.state="failed",t.error=qi("qr-connect-failed",w("\u4F01\u4E1A\u5FAE\u4FE1\u626B\u7801\u6CA1\u6709\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002")),this.#S(t);return}t.state="connecting",t.verificationUrl=null,t.expiresAt=null,t.scode=null,this.#y();let i=this.#p(t,o);t.transition=i,await i}catch{if(t.controller.signal.aborted)return;t.state="failed",t.error=qi("qr-connect-failed",w("\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.#S(t)}}async#p(t,o){try{let i=_l(o.remoteBotId),e=_l(o.secret);if(!i||!e)throw new Error("Enterprise WeChat authorization returned incomplete credentials");t.botId=await this.#h(t,{remoteBotId:i,secret:e}),t.state="connected",t.error=null}catch{t.controller.signal.aborted?(t.state="cancelled",t.error=qi("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=qi("activation-failed",w("\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.#S(t)}}async#h(t,{remoteBotId:o,secret:i}){let e=Sw(o),a=this.#t.getByRemoteBotId(o),A=await this.#A.resolve(e.secretRef).catch(()=>{}),r={botId:e.botId,remoteBotId:o,secretRef:e.secretRef,createdAt:a?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()};return this.#Q(e.botId,async()=>{await this.#A.set(e.secretRef,i);try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#t.save(r)}catch(s){throw await this.#f(e.secretRef,A),s}try{if(t.controller.signal.aborted)throw new DOMException("Cancelled","AbortError");await this.#u(r,i),this.#a.delete(e.botId)}catch(s){if(t.controller.signal.aborted)throw await this.#C(e.botId),a?await this.#t.save(a).catch(()=>{}):await this.#t.remove(e.botId).catch(()=>null)&&await this.#l({botId:e.botId,config:r}).catch(c=>{this.#o.warn?.("[dsh-im:wecom] cancelled bot state cleanup failed:",c)}),await this.#f(e.secretRef,A),s;this.#a.set(e.botId,qi("connection-failed",w("\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.#y(),e.botId})}async#u(t,o){if(this.#g)throw new Error("Enterprise WeChat controller is closed");if(await this.#C(t.botId),this.#g)throw new Error("Enterprise WeChat controller is closed");let i=await this.#r({botId:t.botId,config:t,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(t.botId,i);try{await i.start()}catch(e){throw await i.stop().catch(()=>{}),this.#i.delete(t.botId),e}}async#C(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-im:wecom] bot ${t} failed to stop cleanly:`,i)})}async#B(t){let o=await this.#A.resolve(t).catch(()=>{});return _l(o?.value)}async#f(t,o){o?.value?await this.#A.set(t,o.value).catch(()=>{}):await this.#A.unset(t).catch(()=>{})}#Q(t,o){let a=(this.#d.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#d.get(t)===a&&this.#d.delete(t)});return this.#d.set(t,a),a}#S(t){t.scode=null,t.verificationUrl=null,t.expiresAt=null,this.#s===t.id&&(this.#s=null),this.#y();let o=[...this.#n.values()].filter(i=>oB.has(i.state));for(;o.length>16;)this.#n.delete(o.shift().id)}#y(){this.#c+=1}};import{WSAuthFailureError as F2e,WSClient as L2e,WSReconnectExhaustedError as U2e}from"@wecom/aibot-node-sdk";import{generateReqId as B2e}from"@wecom/aibot-node-sdk";var rF=12e4;function f2e(){return[w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u6216\u6587\u4EF6\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `)}var Q2e=18e3,h9=5*1024*1024,C9=4;function da(n){return typeof n=="string"&&n.trim()?n.trim():null}function Pn(n){return n?.body&&typeof n.body=="object"?n.body:{}}function E9(n){let t=Pn(n);return t.chattype==="group"?`group:${t.chatid}`:`direct:${t.from?.userid}`}function B9(n){let t="";return n.msgtype==="text"?t=typeof n.text?.content=="string"?n.text.content.trim():"":n.msgtype==="voice"?t=typeof n.voice?.content=="string"?n.voice.content.trim():"":n.msgtype==="mixed"&&Array.isArray(n.mixed?.msg_item)&&(t=n.mixed.msg_item.filter(o=>o?.msgtype==="text"&&typeof o.text?.content=="string").map(o=>o.text.content).join(` `).trim()),t}function oF(n){let t=Pn(n),o=B9(t);return t.chattype==="group"?o.replace(/^\s*@\S+(?:\s+|$)/u,"").trim():o}function y2e(n){let t=Pn(n);return t.msgtype==="image"?[t.image]:t.msgtype!=="mixed"||!Array.isArray(t.mixed?.msg_item)?[]:t.mixed.msg_item.filter(o=>o?.msgtype==="image").map(o=>o.image)}function m2e(n){let t=Pn(n);return t.msgtype==="file"&&t.file&&typeof t.file=="object"?[t.file]:[]}function S2e(n){if(n?.msgtype==="image")return[{kind:"image"}];if(n?.msgtype==="voice")return[{kind:"audio"}];if(n?.msgtype==="file"){let t=da(n.file?.filename??n.file?.file_name??n.file?.name);return[{kind:"file",...t?{name:t}:{}}]}return n?.msgtype!=="mixed"||!Array.isArray(n.mixed?.msg_item)?[]:n.mixed.msg_item.filter(t=>t?.msgtype==="image").map(()=>({kind:"image"}))}function w2e(n){let t=n?.quote;if(!t||typeof t!="object")return null;let o=B9(t),i=S2e(t),e=["text","image","mixed","voice","file"].includes(t.msgtype);return{...o?{content:o}:{},...i.length>0?{attachments:i}:{},...!o&&i.length===0?{unavailableReason:e?"not-delivered":"unsupported"}:{}}}function D2e(n,t){let o=da(t?.url);if(!o)return null;let i=da(t?.aeskey)??void 0;return{async load({signal:e,maxBytes:a}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat image download is unavailable");let A=await n.downloadFile(o,i);e?.throwIfAborted();let r=A?.buffer;if(!Buffer.isBuffer(r)&&!(r instanceof Uint8Array))throw new Error("Enterprise WeChat image download returned no data");let s=Buffer.from(r);if(Number.isFinite(a)&&s.length>a)throw new ft("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));return{data:s,name:A?.filename}}}}function O2e(n,t){let o=da(t?.url);if(!o)return null;let i=da(t?.aeskey)??void 0;return{name:da(t?.filename??t?.file_name??t?.name)??"file",async load({signal:e}={}){if(e?.throwIfAborted(),typeof n?.downloadFile!="function")throw new Error("Enterprise WeChat file download is unavailable");let a=await n.downloadFile(o,i);e?.throwIfAborted();let A=a?.buffer??a?.data;if(!Buffer.isBuffer(A)&&!(A instanceof Uint8Array))throw new Error("Enterprise WeChat file download returned no data");return{data:Buffer.from(A),...da(a?.filename)?{name:a.filename.trim()}:{}}}}}function eF(n,t){let o=Pn(n),i=w2e(o);return{content:oF(n),images:y2e(n).map(e=>D2e(t,e)).filter(Boolean),files:m2e(n).map(e=>O2e(t,e)).filter(Boolean),...i?{replyTo:i}:{}}}function b2e(n,t){return!Array.isArray(n?.files)||n.files.length===0?n:{...n,files:n.files.map(o=>{let i=o.load({signal:t});return i.catch(()=>{}),{...o,async load({signal:e}={}){e?.throwIfAborted();let a=await i;return e?.throwIfAborted(),a}}})}}function M2e(n,t){return Nt(n)?{...n,images:n.images.map(o=>{let i=o.load({signal:t,maxBytes:h9});return i.catch(()=>{}),{...o,async load({signal:e,maxBytes:a=h9}={}){e?.throwIfAborted();let A=await i;e?.throwIfAborted();let r=A?.data??A?.buffer??A;if((Buffer.isBuffer(r)||r instanceof Uint8Array?r.length:0)>a)throw new ft("image-too-large",`Enterprise WeChat image exceeds ${a} bytes`,w("\u56FE\u7247\u8D85\u8FC7 5 MB\uFF0C\u8BF7\u538B\u7F29\u540E\u91CD\u8BD5\u3002"));return A}}})}:n}function _2e(n){return{...n,images:n.images.map(t=>({...t,async load(){throw new ft("image-queue-full",`Enterprise WeChat already has ${C9} prefetched images`,w("\u5F53\u524D\u5F85\u5904\u7406\u56FE\u7247\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u53D1\u9001\u3002"))}}))}}function aF(n){return Pn(n).msgtype==="text"?oF(n):""}function T2e(n){return Pn(n).msgtype==="text"&&!!da(oF(n))}function Mw(n,t=Q2e){let o=String(n??"").trim();if(!o)return[];let i=[],e="",a=0;for(let A of o){let r=Buffer.byteLength(A);e&&a+r>t?(i.push(e),e=A,a=r):(e+=A,a+=r)}return e&&i.push(e),i}function N2e(n){return n?.type==="tool"?w("\u6B63\u5728\u4F7F\u7528{name}\u2026",{name:n.name}):n?.text}function sB(n,t="",{finish:o=!1}={}){let i=String(n??"").replace(/<\/?think>/gi,"").trim(),e=String(t??"").trim();if(!i)return e;let a=o||e?`${i}`:`${i}`;return e?`${a} ${e}`:a}function R2e(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u7F3A\u5C11\u7D20\u6750\u4E0A\u4F20\u6216\u6587\u4EF6\u6D88\u606F\u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6743\u9650\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-empty":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u4E3A\u7A7A\uFF0C\u4F01\u4E1A\u5FAE\u4FE1\u4E0D\u5141\u8BB8\u53D1\u9001\u7A7A\u6587\u4EF6\u3002",{name:o});case"artifact-changed":case"artifact-invalid":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u4F01\u4E1A\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u4F01\u4E1A\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6216\u6587\u4EF6\u6D88\u606F\u3002",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u4F01\u4E1A\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function iF(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}function u9(n,t){return t?(t.throwIfAborted(),new Promise((o,i)=>{let e=!1,a=(r,s)=>{e||(e=!0,t.removeEventListener("abort",A),r(s))},A=()=>a(i,iF(t));t.addEventListener("abort",A,{once:!0}),Promise.resolve(n).then(r=>a(o,r),r=>a(i,r)),t.aborted&&A()})):n}function AF(n,{dispatched:t=!1}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.httpStatus??n?.status??n?.response?.status),i=Number(n?.providerCode??n?.errcode??n?.body?.errcode),e=new Error("Enterprise WeChat file delivery failed",{cause:n});return o===401||o===403||i===48002?e.code="artifact-permission-required":o===413?e.code="artifact-too-large":o===429||i===45009?e.code="artifact-rate-limited":Number.isFinite(i)&&i!==0?e.code="artifact-provider-rejected":e.code=t?"artifact-delivery-uncertain":"artifact-provider-failed",Number.isFinite(o)&&(e.status=o),Number.isFinite(i)&&(e.providerCode=i),e}async function f9(n,t,o,i,{signal:e,timeoutMs:a=rF}={}){if(e?.throwIfAborted(),typeof n?.uploadMedia!="function"||typeof n?.sendMediaMessage!="function"){let d=new Error(`Enterprise WeChat ${i} delivery is unavailable`);throw d.code="artifact-provider-unavailable",d}let A=AbortSignal.timeout(a),r=e?AbortSignal.any([e,A]):A,s;try{let d=n.uploadMedia(o.bytes,{type:i,filename:o.fileName});yn(o,d),s=await u9(d,r)}catch(d){throw e?.aborted?iF(e):AF(d)}e?.throwIfAborted();let g=da(s?.media_id);if(!g){let d=new Error(`Enterprise WeChat ${i} upload returned no media id`);throw d.code="artifact-provider-rejected",d}let c;try{let d=n.sendMediaMessage(t,i,g);yn(o,d),c=await u9(d,r)}catch(d){throw e?.aborted?iF(e):AF(d,{dispatched:!0})}e?.throwIfAborted();let I=Number(c?.body?.errcode??c?.errcode);if(Number.isFinite(I)&&I!==0)throw AF({providerCode:I});return c}function k2e(n,t,o,i){return f9(n,t,o,"image",i)}function v2e(n,t,o,i){return f9(n,t,o,"file",i)}function P2e(n,t){return typeof n=="string"&&n.trim()?n:t.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):w("\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u4F46\u6CA1\u6709\u751F\u6210\u53EF\u663E\u793A\u7684\u6587\u672C\u3002")}function tF(n){return da(n?.body?.msgid)??da(n?.body?.message_id)}function G2e(n,t){return t.questions[t.index]&&da(Pn(n).from?.userid)===t.actor&&da(aF(n))}function nF(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,artifactsSent:0,artifactSendErrors:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var _w=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c=new Map;#g=new Map;#I=new Map;#p=new Map;#h=new Set;#u=new Set;#C;#B=new ki;#f=0;constructor({client:t,harness:o,state:i,contextEnhancement:e,accessPolicy:a,status:A=nF(),logger:r=console,replyTimeoutMs:s=6e5,generateStreamId:g=B2e,fileUploadTimeoutMs:c=rF,signal:I}){if(!t||typeof t.replyStream!="function"||typeof t.sendMessage!="function")throw new TypeError("Enterprise WeChat client is required");if(!o||!i)throw new TypeError("Harness client and state store are required");if(!Number.isInteger(c)||c<1)throw new TypeError("fileUploadTimeoutMs must be a positive integer");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#d=Math.min(c,rF),this.#s=I,this.#C=new Mi({label:"wecom",logger:r})}get status(){return structuredClone(this.#o)}accept(t){if(this.#s?.aborted)return Promise.resolve();let o=Pn(t),i=da(o.msgid),e=da(o.from?.userid),a=o.chattype==="group"?da(o.chatid):e;if(!i||!e||!a||!["single","group"].includes(o.chattype)||this.#t.hasSeen(i)||this.#p.has(i))return Promise.resolve();let A=E9(t),r=this.#g.get(A),s=eF(t,this.#e),g=da(s.content)??"",c=o.chattype==="single"?"direct":"group",I=Da(this.#l,{conversationType:c,senderIds:e,text:g,hasImages:Nt(s),hasFiles:Dt(s)});if(!I.allowed)return this.#p.set(i,null),this.#y(t,i,a,I);this.#p.set(i,aa(this.#r,c)),o.chattype==="single"&&Do(this.#t,{chatId:a});let d=vi(g),B=this.#B.status(A);if(d&&o.chattype==="group")return this.#S(t,i,a,{message:as()});if(o.chattype==="single"&&(d||B.phase==="collecting")){let m=/^\/batch$/iu.test(g)&&B.phase==="idle"&&(this.#c.has(A)||r||this.#C.hasPending(A))?{handled:!0,kind:"busy",message:Ro()}:this.#B.handle(A,g,{plainText:T2e(t)&&!Hr(s)});if(m.handled)return m.kind==="submit"?this.#Q({...t,body:{...o,msgtype:"text",text:{content:m.prompt}}},i,A,{batchSubmission:m}):this.#S(t,i,a,m)}let f=xa(g)?ao:Dt(s)?null:ci(g)?Ni:Ii(g)?io:li(g)?Ri:null;if(f){let y;return y=this.#m(t,i,a,A,s,f).catch(m=>{if(m?.code==="turn-stopped"||this.#s?.aborted)return;this.#o.lastError=m?.message??String(m);let T=tt(this.#o,m);return this.#i.error?.(`[dsh-im:wecom] failed to process a command [${T.referenceId}]`),this.#E(t,a,Et(T)).catch(()=>{})}).finally(()=>{this.#p.delete(i),this.#u.delete(y)}),this.#u.add(y),y}let Q=this.#C.claimReply({key:A,actor:e,messageId:i,text:aF(t),addressed:!0,hasPendingQuestion:!!r,questionCompletion:r?.submitting||r?.claimedReplyMessageId?r.queue:null,isQuestionPending:()=>this.#g.has(A),send:y=>this.#E(t,a,y)});if(Q){let y;return y=Q.process(async()=>this.#t.hasSeen(i)?!1:(await this.#t.markSeen(i),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#p.delete(i),this.#h.delete(y)}),this.#h.add(y),y}if(r&&r.actor!==e)return this.#Q(t,i,A);if(r?.submitting||r?.claimedReplyMessageId)return this.#Q(t,i,A);if(r){G2e(t,r)&&(r.claimedReplyMessageId=i);let m=(r.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#O(t,i,e,a,A,r)).finally(()=>{this.#p.delete(i),r.claimedReplyMessageId===i&&(r.claimedReplyMessageId=null),r.queue===m&&(r.queue=null)});return r.queue=m,m}return this.#Q(t,i,A)}#Q(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=eF(t,this.#e),s=r.images.length,g=0,c=r;s>0&&(this.#f+s<=C9?(g=s,this.#f+=g,c=M2e(r,this.#s)):c=_2e(r)),c=b2e(c,this.#s);let d=(this.#c.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#_(t,{alreadyRecorded:a,preparedMessage:c,batchSubmission:A})).finally(()=>{this.#f-=g,e&&this.#p.delete(o),this.#c.get(i)===d&&this.#c.delete(i)});return this.#c.set(i,d),d}#S(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),e.message&&await this.#E(t,i,e.message),this.#o.lastError=null)}).catch(async A=>{if(this.#s?.aborted)return;this.#o.lastError=A?.message??String(A);let r=tt(this.#o,A);this.#i.error?.(`[dsh-im:wecom] failed to process a batch input message [${r.referenceId}]`),await this.#E(t,i,Et(r)).catch(()=>{})}).finally(()=>{this.#p.delete(o),this.#u.delete(a)}),this.#u.add(a),a}#y(t,o,i,e){let a;return a=Promise.resolve().then(async()=>{this.#t.hasSeen(o)||(await this.#t.markSeen(o),e.reason==="command-not-allowed"?(this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),await this.#E(t,i,w(no)),this.#o.messagesReplied+=1,this.#o.lastReplyAt=new Date().toISOString()):(this.#o.messagesRejected+=1,this.#o.lastRejectedAt=new Date().toISOString()),this.#o.lastError=null)}).catch(A=>{this.#s?.aborted||(this.#o.lastError=A?.message??String(A),this.#i.error?.("[dsh-im:wecom] failed to apply inbound access policy",A))}).finally(()=>{this.#p.delete(o),this.#u.delete(a)}),this.#u.add(a),a}async waitForIdle(){await Promise.allSettled([...this.#c.values(),...[...this.#g.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#h,...this.#u])}async#m(t,o,i,e,a,A){if(this.#s?.throwIfAborted(),this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString();let r=await A(a.content,this.#A,this.#t,e,{signal:this.#s,isDirect:Pn(t).chattype==="single",hasImages:Nt(a),hasFiles:Dt(a),pendingInteraction:this.#g.has(e)||this.#C.hasPending(e),control:{owner:this,key:e}});r?.stopped&&await Promise.allSettled([this.#k(e),this.#C.closeRoute(e)]);for(let s of r?.messages??[r?.message])s&&await this.#E(t,i,s);this.#o.lastError=null}async#D(t,o){let i=[];for(let e of Mw(o)){this.#s?.throwIfAborted();let a=await this.#e.sendMessage(t,{msgtype:"markdown",markdown:{content:e}}),A=tF(a);A&&i.push(A)}return i}async#E(t,o,i){this.#s?.throwIfAborted();let e=Mw(i);if(e.length!==0)try{await this.#e.replyStream(t,this.#n("stream"),e[0],!0);for(let a of e.slice(1))await this.#e.sendMessage(o,{msgtype:"markdown",markdown:{content:a}})}catch{await this.#D(o,i)}}async#R(t,o,i=[],e=null){if(i.length===0)return{receipt:e,failureNoticeVisible:!1,artifactSendErrors:0};let a=await Po({artifacts:i,baseReceipt:e,deliveryId:o,aggregatePresentation:e?"wecom-text-and-files":"wecom-files",alwaysMerge:!0,channelKey:"wecom",signal:this.#s,sendImage:A=>k2e(this.#e,t,A,{signal:this.#s,timeoutMs:this.#d}),sendFile:A=>v2e(this.#e,t,A,{signal:this.#s,timeoutMs:this.#d}),onFailure:(A,r)=>tt(this.#o,r,{userMessage:R2e(A?.fileName,r),reason:r?.code}),sendFailureNotice:(A,r,s)=>this.#D(t,Et(s)),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,failureNoticeVisible:a.failureNoticeVisible,artifactSendErrors:a.artifactSendErrors}}async#_(t,{alreadyRecorded:o=!1,preparedMessage:i,batchSubmission:e=null}={}){if(this.#s?.aborted)return;let a=Pn(t),A=typeof a.msgid=="string"?a.msgid:"",r=typeof a.from?.userid=="string"?a.from.userid:"",s=a.chattype==="group"?a.chatid:r;if(!A||!r||!s||!["single","group"].includes(a.chattype))return;if(!o){if(this.#t.hasSeen(A))return;this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString()}let g=i??eF(t,this.#e),c=g.content,I=Nt(g),d=Dt(g),B=Hr(g),f=E9(t),Q=null,y=!1,m=w("\u6B63\u5728\u601D\u8003\u4E2D\u2026"),T="",_=e===null,R=!1;try{if(!c&&!I&&!d&&!B){await this.#E(t,s,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8F6C\u5199\u6D88\u606F\u3002")),await this.#t.markSeen(A);return}let x=c.toLowerCase();if(!I&&!d&&x==="/help"){await this.#E(t,s,f2e()),await this.#t.markSeen(A);return}if(!I&&!d&&x==="/status"){await this.#A.ensureRunning({signal:this.#s}),await this.#E(t,s,w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002")),await this.#t.markSeen(A);return}if(!I&&!d&&x==="/new"){await this.#t.clearSession(f),await this.#E(t,s,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002")),await this.#t.markSeen(A);return}let F=I||d?null:await _o(c,this.#A,f);if(F){for(let oe of F.messages??[F.message])await this.#E(t,s,oe);await this.#t.markSeen(A);return}let L=I||d?null:await Ti(c,this.#A,this.#t,f,{signal:this.#s});if(L){await this.#E(t,s,L.message),await this.#t.markSeen(A);return}Q=this.#n("stream");try{await this.#e.replyStream(t,Q,sB(m),!1),y=!0}catch(oe){this.#i.warn?.("[dsh-im:wecom] unable to start a stream; using an active reply:",oe)}let q=I||B?await Go(g,{signal:this.#s}):void 0,z=this.#p.get(A),H=!1;if(z){let oe=q??c;q=No(oe,z,()=>({channel:"wecom",senderId:r,chatId:s})),H=q!==oe}await this.#t.markSeen(A),R=!0;let{answer:G,artifacts:V=[]}=await _i({harness:this.#A,state:this.#t,key:f,text:c,content:q,contextEnhanced:H,createOptions:{signal:this.#s},existsOptions:{signal:this.#s},askOptions:{timeoutMs:this.#a,signal:this.#s,control:{owner:this,key:f},onUpdate:y&&typeof this.#e.replyStreamNonBlocking=="function"?async oe=>{oe?.type==="text"?T=oe.text:m=N2e(oe)||m;let Se=Mw(sB(m,T))[0];Se&&await this.#e.replyStreamNonBlocking(t,Q,Se,!1)}:void 0,onInteraction:oe=>this.#w(oe,{key:f,actor:r,chatId:s,requiresMention:a.chattype==="group"}),onInteractionResolved:oe=>this.#T(oe),files:g.files}});e&&(this.#B.complete(f,e.token),_=!0),this.#s?.throwIfAborted();let U=P2e(G,V),N=Mw(sB(m,U,{finish:!0})),k=!1,J=null,X=null;try{if(y&&N.length>0)try{let oe=[],Se=await this.#e.replyStream(t,Q,N[0],!0),Be=tF(Se);Be&&oe.push(Be);for(let ke of N.slice(1)){let Re=await this.#e.sendMessage(s,{msgtype:"markdown",markdown:{content:ke}}),We=tF(Re);We&&oe.push(We)}k=!0,J=$t({deliveryId:A,presentation:"wecom-text",providerMessageIds:oe})}catch(oe){this.#i.warn?.("[dsh-im:wecom] stream finalization failed; using an active reply:",oe)}if(!k){let oe=await this.#D(s,U);J=$t({deliveryId:A,presentation:"wecom-text",providerMessageIds:oe})}}catch(oe){X=Ua(oe),this.#i.warn?.("[dsh-im:wecom] final text delivery failed; continuing with result files:",oe)}let ie=await this.#R(s,A,V,J),we=ie.receipt?.artifacts?.some(({outcome:oe})=>oe==="sent"||oe==="unknown");if(X&&!we&&!ie.failureNoticeVisible)throw X;return X&&ie.artifactSendErrors===0&&tt(this.#o,X),R||await this.#t.markSeen(A),this.#o.messagesReplied+=1,this.#o.lastReplyAt=new Date().toISOString(),this.#o.lastError=null,!X&&ie.artifactSendErrors===0&&Oo(this.#o),ie.receipt}catch(x){let F=null;if(!_&&e&&(x?.code==="turn-stopped"?this.#B.complete(f,e.token):F=this.#B.fail(f,e.token).message??null,_=!0),x?.code==="turn-stopped"){y&&Q&&await this.#e.replyStream(t,Q,sB(m,w("\u5DF2\u505C\u6B62\u3002"),{finish:!0}),!0).catch(()=>{}),R||await this.#t.markSeen(A);return}if(this.#s?.aborted)return;this.#o.lastError=x?.message??String(x);let L=vo(x)??Mo(x),q=tt(this.#o,x,{userMessage:L,reason:ro(x)?.reason});this.#i.error?.(`[dsh-im:wecom] failed to process an inbound message [${q.referenceId}]`);let z=Et(q),H=F?`${z} @@ -420,7 +420,7 @@ ${e}`:a}function R2e(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace ${F}`:z;try{y&&Q?await this.#e.replyStream(t,Q,sB(m,H,{finish:!0}),!0):await this.#E(t,s,H),R||await this.#t.markSeen(A)}catch{this.#i.error?.("[dsh-im:wecom] failed to send the safe error reply")}}finally{await Promise.allSettled([this.#k(f),this.#C.closeRoute(f)])}}async#O(t,o,i,e,a,A){if(this.#s?.aborted)return;let r=this.#g.get(a),s=A.claimedReplyMessageId===o;if(!r||r!==A||r.submitting)return s&&(!r||r!==A)?this.#P(t,o,e):this.#Q(t,o,a,{releaseMessageId:!1});if(this.#t.hasSeen(o))return;await this.#t.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString();let g=da(aF(t));if(!g){await this.#E(t,e,w("\u8BF7\u7528\u6587\u5B57\u56DE\u7B54\u5F53\u524D\u95EE\u9898\u3002")).catch(()=>{});return}let c=this.#g.get(a);if(!c||c!==A||c.submitting){if(s&&(!c||c!==A)){await this.#E(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#Q(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}if(c.actor!==i)return this.#Q(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0});if(c.chatId=e,c.needsPresentation){try{await this.#M(c)}catch{this.#o.lastError=w("\u4F01\u4E1A\u5FAE\u4FE1\u4EA4\u4E92\u95EE\u9898\u53D1\u9001\u5931\u8D25\u3002"),this.#i.error?.("[dsh-im:wecom] failed to retry an interaction question"),c.interaction.reconnect?.();return}let d=this.#g.get(a);if(!d||d!==A||d.submitting){if(s&&(!d||d!==A)){await this.#E(t,e,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{});return}return this.#Q(t,o,a,{releaseMessageId:!1,alreadyRecorded:!0})}}let I=c.questions[c.index];if(I){if(c.answers.push(bi(I,g)),c.index+=1,c.index{});return}if(this.#g.get(a)!==c)return;c.submitting=!1,c.answers.pop(),c.index-=1,this.#o.lastError=w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\u3002"),this.#i.error?.("[dsh-im:wecom] failed to answer a Harness interaction"),await this.#E(t,e,w("\u56DE\u7B54\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u5F53\u524D\u95EE\u9898\u7684\u7B54\u6848\u3002")).catch(()=>{})}}}async#w(t,{key:o,actor:i,chatId:e,requiresMention:a}){if(t?.kind==="approval")return this.#C.handleRequested(t,{key:o,actor:i,requiresMention:a,send:c=>this.#D(e,c)});if(t?.kind!=="question")return;let A=t?.payload?.questions,r=typeof t?.interactionId=="string"?t.interactionId:t?.rpcId;if(typeof t?.rpcId!="string"||typeof r!="string"||typeof t.sessionId!="string"||!Array.isArray(A)||A.length===0||A.some(c=>!Di(c))){this.#i.warn?.("[dsh-im:wecom] ignored an invalid Harness question interaction");return}if(t.recovered===!0){await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat safely cancelled an interaction left by an earlier client.",details:{}}}),await this.#D(e,w("\u68C0\u6D4B\u5230\u8FD9\u4E2A Session \u4E2D\u9057\u7559\u7684\u5F85\u56DE\u7B54\u95EE\u9898\uFF0C\u5DF2\u5B89\u5168\u53D6\u6D88\u5E76\u7EE7\u7EED\u5904\u7406\u4F60\u521A\u624D\u7684\u6D88\u606F\u3002")).catch(()=>{});return}let s=this.#g.get(o);if(s?.interactionId===r){s.interaction=t,s.needsPresentation&&await this.#M(s);return}if(this.#I.has(r))return;if(s){this.#i.warn?.("[dsh-im:wecom] cancelled a second pending Harness question"),await t.respond({ok:!1,error:{code:"cancelled",message:"Enterprise WeChat is already handling another user interaction.",details:{}}});return}let g={kind:"question",interactionId:r,sessionId:t.sessionId,interaction:t,actor:i,requiresMention:a,questions:A,answers:[],index:0,chatId:e,queue:null,claimedReplyMessageId:null,submitting:!1,needsPresentation:!0,presentationPromise:null};this.#g.set(o,g),this.#I.set(g.interactionId,o),await this.#M(g)}async#T(t){if(t?.kind==="approval"){await this.#C.handleResolved(t);return}let o=t?.interactionId;if(t?.kind!=="question"||typeof o!="string")return;let i=this.#I.get(o);i&&this.#F(i,o)}#M(t){if(!t.needsPresentation)return Promise.resolve();if(t.presentationPromise)return t.presentationPromise;let o=t.questions[t.index];if(!o)return Promise.resolve();let i=this.#D(t.chatId,Oi(o,t.index,t.questions.length,{requiresMention:t.requiresMention})).then(()=>{t.needsPresentation=!1}).finally(()=>{t.presentationPromise===i&&(t.presentationPromise=null)});return t.presentationPromise=i,i}async#P(t,o,i){this.#t.hasSeen(o)||(await this.#t.markSeen(o),this.#o.messagesReceived+=1,this.#o.lastMessageAt=new Date().toISOString(),await this.#E(t,i,w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002")).catch(()=>{}))}#N(t,o){let i=this.#g.get(t);return!i||o!==void 0&&i.interactionId!==o?null:(this.#g.delete(t),this.#I.delete(i.interactionId),i)}#F(t,o){return this.#N(t,o)!==null}async#k(t){let o=this.#N(t);if(!(!o||o.kind!=="question"))try{await o.interaction.respond({ok:!1,error:{code:"cancelled",message:"The Enterprise WeChat interaction ended before the user answered.",details:{}}},{signal:AbortSignal.timeout(5e3)})}catch(i){i?.code!=="interaction-not-pending"&&this.#i.warn?.("[dsh-im:wecom] failed to cancel a pending Harness interaction")}}};function H2e(){let n=new Error("Enterprise WeChat WebSocket authentication timed out");return n.code="connect-timeout",n}function K2e(){return{startedAt:null,ready:!1,wecomConnectionState:"idle",harnessReachable:!1,lastCheckedAt:null,lastConnectedAt:null,lastError:null,...nF()}}var gB=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c=K2e();#g=null;#I=null;#p=null;#h=null;#u=null;constructor({config:t,secret:o,harness:i,state:e,contextEnhancement:a,accessPolicy:A,logger:r=console,replyTimeoutMs:s=6e5,connectTimeoutMs:g=2e4,maxReconnectAttempts:c=10,createClient:I=d=>new L2e(d)}){if(!t||!o||!i||!e)throw new TypeError("WecomRuntime requires config, secret, Harness, and state");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#d=I}get status(){return structuredClone(this.#c)}async start(){if(this.#c.ready&&this.#g)return this.status;if(this.#p)return this.#p;this.#u?.abort(new DOMException("Enterprise WeChat runtime replaced","AbortError"));let t=new AbortController;return this.#h=t,this.#u=t,this.#p=this.#C(t.signal).finally(()=>{this.#h===t&&(this.#h=null),this.#p=null}),this.#p}async#C(t){await this.#B(),t.throwIfAborted(),this.#c.startedAt=new Date().toISOString(),this.#c.wecomConnectionState="connecting",this.#c.lastError=null,await this.#t.ensureRunning(),this.#c.harnessReachable=!0;let o={debug(){},info(){},warn(){},error(){}},i=this.#d({botId:this.#e.remoteBotId,secret:this.#A,logger:o,maxReconnectAttempts:this.#s});if(!i||typeof i.connect!="function"||typeof i.disconnect!="function")throw new TypeError("Enterprise WeChat client factory returned an invalid client");this.#g=i,this.#I=new _w({client:i,harness:this.#t,state:this.#r,contextEnhancement:this.#l,accessPolicy:this.#o,status:this.#c,logger:this.#i,replyTimeoutMs:this.#a,signal:t});let e,a,A=!1,r=new Promise((f,Q)=>{e=f,a=Q}),s=()=>{if(this.#g!==i||t.aborted)return;A=!0;let f=Date.now();this.#c.ready=!0,this.#c.wecomConnectionState="connected",this.#c.lastCheckedAt=f,this.#c.lastConnectedAt=f,this.#c.lastError=null,e()},g=()=>{this.#g===i&&(this.#c.ready=!1,this.#c.wecomConnectionState="connecting",this.#c.lastCheckedAt=Date.now())},c=()=>{this.#g===i&&(this.#c.ready=!1,this.#c.wecomConnectionState="connecting",this.#c.lastCheckedAt=Date.now())},I=f=>{if(this.#g!==i)return;let Q=f instanceof F2e||f instanceof U2e;!A&&Q&&a(f),Q&&(this.#c.ready=!1,this.#c.wecomConnectionState="failed"),this.#c.lastError=Q?f.name:"connection-error",this.#i.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} connection error`)},d=f=>this.#I?.accept(f);i.on("authenticated",s),i.on("disconnected",g),i.on("reconnecting",c),i.on("error",I),i.on("message",d);let B;try{return i.connect(),await Promise.race([r,new Promise((f,Q)=>{t.addEventListener("abort",()=>Q(t.reason),{once:!0})}),new Promise((f,Q)=>{B=setTimeout(()=>Q(H2e()),this.#n)})]),this.status}catch(f){throw t.aborted?(await this.#B(),f):(this.#c.ready=!1,this.#c.wecomConnectionState="failed",this.#c.lastError=f?.message??String(f),await this.#B(),f)}finally{clearTimeout(B)}}async stop(){let t=this.#p;return this.#h?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#u?.abort(new DOMException("Enterprise WeChat runtime stopped","AbortError")),this.#u=null,await this.#B(),await t?.catch(()=>{}),this.status}async sendConnectionTest(t){return cc({state:this.#r,text:t,channelLabel:w("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"),send:async({chatId:o},i)=>{if(!this.#c.ready||!this.#g)throw new Error("Enterprise WeChat runtime is not connected");await this.#g.sendMessage(o,{msgtype:"markdown",markdown:{content:i}})}})}async sendProactiveText(t,o,{signal:i}={}){let e=typeof t?.route?.chatId=="string"?t.route.chatId.trim():"";if(t?.kind!=="user"&&t?.kind!=="group"||!e){let a=new TypeError("Invalid Enterprise WeChat proactive delivery target");throw a.code="invalid-target",a}if(!this.#c.ready||!this.#g){let a=new Error("Enterprise WeChat runtime is not connected");throw a.code="bot-not-connected",a}return i?.throwIfAborted(),await this.#g.sendMessage(e,{msgtype:"markdown",markdown:{content:o}}),{sent:!0}}async#B(){let t=this.#g,o=this.#I;this.#g=null,this.#I=null;try{t?.disconnect(),t?.removeAllListeners?.()}catch{this.#i.warn?.(`[dsh-im:wecom] bot ${this.#e.botId} failed to stop cleanly`)}await o?.waitForIdle(),this.#c.ready=!1,this.#c.wecomConnectionState="idle"}};var Q9=Object.freeze([250,1e3,3e3,5e3,1e4,3e4]);function x2e(n){if(!Array.isArray(n)||n.length===0)return[...Q9];let t=n.filter(o=>Number.isFinite(o)&&o>=0);return t.length>0?t:[...Q9]}var Tw=class{#e;#A;#t;#r;#l;#o;#i;#a=null;#n=null;#s=0;#d=!1;#c=!1;#g;#I;constructor({controller:t,harness:o,logger:i=console,retryDelaysMs:e,healthyIntervalMs:a=15e3,setTimeoutImpl:A=setTimeout,clearTimeoutImpl:r=clearTimeout}){if(!t||typeof t.initialize!="function"||typeof t.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=t,this.#A=o,this.#t=i,this.#r=x2e(e),this.#l=Number.isFinite(a)&&a>=0?a:15e3,this.#o=A,this.#i=r,this.#g=new Promise(s=>{this.#I=s})}get ready(){return this.#g}start(){return this.#c||this.#d?this:(this.#c=!0,this.#p(0),this)}async close(){this.#d||(this.#d=!0,this.#a!==null&&this.#i(this.#a),this.#a=null,await this.#n?.catch(()=>{}),this.#I?.(null),this.#I=null)}#p(t){this.#d||(this.#a=this.#o(()=>{this.#a=null,this.#h()},t),this.#a?.unref?.())}async#h(){if(this.#d||this.#n)return;let t=this.#u();this.#n=t;try{await t}finally{this.#n===t&&(this.#n=null)}}async#u(){try{if(await this.#A.ensureRunning(),this.#d)return;let t=await this.#e.initialize();if(this.#d)return;this.#I?.(t),this.#I=null;let{configured:o,connected:i}=t.totals;if(iYa(n),B=J2e(t),f=await new e(B.config).load(),Q=Nl(t.workspace??process.cwd()),y=o.WorkspaceStore??oa,m=o.workspaces??await new y(B.workspaces,{defaultWorkspace:Q}).load(),T=f.list();await m.reconcile(T.map(J=>J.botId)),await Promise.all(T.map(J=>m.ensure(J.botId,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("wecom",J)})));let _=typeof f.remove=="function"?ja(f,{workspaces:m}):f,R=o.qrAuth??new g({source:t.qrSource??"deepseek-harness",platform:t.qrPlatform}),x=new Map,F=J=>Nl(B.bots,J,"state.json"),L=async J=>{let X=x.get(J);return X||(X=await new a(F(J)).load(),x.set(J,X)),X},q=Va(n,o.commandExecutor),{controlExecutor:z,sessionMaintenanceExecutor:H,fileIngressExecutor:G}=Wa(n,{controlExecutor:o.controlExecutor,sessionMaintenanceExecutor:o.sessionMaintenanceExecutor,fileIngressExecutor:o.fileIngressExecutor}),V=new A({...i,workspace:Q,autostart:!1,dshBin:t.dshBin??"dsh",...q?{commandExecutor:q}:{},...z?{controlExecutor:z}:{},...H?{sessionMaintenanceExecutor:H}:{},...G?{fileIngressExecutor:G}:{}}),U=new r({qrAuth:R,credentials:n.credentials,configStore:_,logger:I,createRuntime:async({botId:J,config:X,secret:ie})=>{let we=await L(J);await m.ensure(J,{defaultAgentPreset:t.agentPreset,initialAccessPolicy:cr("wecom",X)});let oe=Ja(V,{botId:J,workspaces:m,state:we,agentPresetCatalog:d});return new s({config:X,secret:ie,harness:oe.harness,state:oe.state,contextEnhancement:{botId:J,getSettings:()=>m.contextEnhancementFor(J)},accessPolicy:Za(m,J,{channel:"wecom",config:X}),replyTimeoutMs:t.replyTimeoutMs??6e5,connectTimeoutMs:t.connectTimeoutMs??2e4,maxReconnectAttempts:t.maxReconnectAttempts??10,logger:{error:(...Se)=>I.error?.(`[${J}]`,...Se),warn:(...Se)=>I.warn?.(`[${J}]`,...Se),info:(...Se)=>I.info?.(`[${J}]`,...Se),debug:(...Se)=>I.debug?.(`[${J}]`,...Se)}})},deleteState:async({botId:J})=>{let X=x.get(J);if(x.delete(J),X&&typeof X.remove=="function")await X.remove();else try{await Y2e(F(J))}catch(ie){if(ie?.code!=="ENOENT")throw ie}}}),N=qa(U,{workspaces:m,stateFor:L,agentPresetCatalog:d}),k=c({controller:N,harness:V,logger:I,retryDelaysMs:t.retryDelaysMs,healthyIntervalMs:t.healthyIntervalMs}).start();return{controller:N,deliveryAdapter:za({channel:"wecom",workspaces:m,coreController:U,stateFor:L}),ready:k.ready,async close(){await k.close(),await N.close(),V.stopManagedProcess()}}}import q2e from"qrcode";var m9="/wecom",pr=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:Fi,setAgentPreset:Li,setContextEnhancement:Gi,setAccessPolicy:$a}),S9=Object.freeze(Object.values(pr)),z2e=new Set(["secret","secretRef","scode","remoteBotId","verificationUrl","bot_info","botid"]);function lF(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ah(n,t){return lF(n)&&Object.keys(n).every(o=>t.includes(o))}function cF(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)}function y9(n,t){return typeof n=="string"&&n.trim().length>0&&n.length<=t}function V2e(n,t){return lF(t)?n===pr.status?ah(t,[])?null:"connection.status does not accept fields.":n===pr.beginProvisioning?ah(t,["locale"])&&(t.locale===void 0||t.locale==="zh-CN")?null:"provision.begin received unsupported fields.":[pr.pollProvisioning,pr.cancelProvisioning].includes(n)?ah(t,["attemptId"])&&cF(t.attemptId)?null:`${n} requires an attemptId.`:n===pr.bindCredentials?ah(t,["botId","secret"])&&y9(t.botId,512)&&y9(t.secret,1024)?null:"bot.bind-credentials requires Bot ID and Secret.":n===pr.reconnectBot?ah(t,["botId","sendTest"])&&cF(t.botId)&&(t.sendTest===void 0||t.sendTest===!0)?null:"bot.reconnect requires a botId and optional sendTest=true.":n===pr.deleteBot?ah(t,["botId","confirm"])&&cF(t.botId)&&t.confirm===!0?null:"bot.delete requires a botId and confirm=true.":n===pr.setWorkspace?Ai(t)?null:"\u8BF7\u8F93\u5165\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84\u3002":n===pr.setAgentPreset?ri(t)?null:"\u8BF7\u9009\u62E9 Agent Preset\u3002":n===pr.setContextEnhancement?Xa(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u4E0A\u4E0B\u6587\u589E\u5F3A\u8BBE\u7F6E\u3002":n===pr.setAccessPolicy?ei(t)?null:"\u8BF7\u63D0\u4EA4\u6709\u6548\u7684\u8BBF\u95EE\u8BBE\u7F6E\u3002":"Unknown Enterprise WeChat endpoint.":"Payload must be an object."}function ih(n){if(Array.isArray(n))return n.map(ih);if(!lF(n))return n;let t={};for(let[o,i]of Object.entries(n))z2e.has(o)||(t[o]=ih(i));return t}async function W2e(n){return q2e.toDataURL(n,{type:"image/png",errorCorrectionLevel:"M",margin:2,width:320})}async function IF(n,t){return!n||typeof n.verificationUrl!="string"?ih(n):ih({...n,qrCodeDataUrl:await t(n.verificationUrl)})}async function Uc(n,t){let o=structuredClone(n);return o?.provisioning&&(o.provisioning=await IF(o.provisioning,t)),ih(o)}function w9(n,{encodeQr:t=W2e}={}){for(let e of["status","startProvisioning","registrationStatus","cancelProvisioning","bindCredentials","reconnectBot","deleteBot"])if(typeof n?.[e]!="function")throw new TypeError(`A complete Enterprise WeChat controller is required (${e})`);let o=new Map,i=e=>{let a=o.get(e);return a||(o.size>=16&&o.delete(o.keys().next().value),a=Promise.resolve().then(()=>t(e)),o.set(e,a)),a};return async(e,a,A)=>{if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};if(!S9.includes(e))return{ok:!1,error:{code:"bad-request",message:"Unknown Enterprise WeChat endpoint."}};let r=V2e(e,a);if(r)return{ok:!1,error:{code:"bad-request",message:r}};try{let s;if(e===pr.status)s=await Uc(await n.status(),i);else if(e===pr.beginProvisioning)s=await IF(await n.startProvisioning(),i);else if(e===pr.pollProvisioning){let g=await n.registrationStatus(a.attemptId);if(!g)return{ok:!1,error:{code:"bad-request",message:"The provisioning attempt no longer exists."}};s=await IF(g,i)}else if(e===pr.cancelProvisioning)s=ih(await n.cancelProvisioning(a.attemptId));else if(e===pr.bindCredentials)s=await Uc(await n.bindCredentials(a),i);else if(e===pr.reconnectBot){let g=await n.reconnectBot(a.botId);if(A?.aborted)return{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}};let c;if(a.sendTest===!0)if(!g?.bots?.some(d=>d?.botId===a.botId&&d?.connected===!0)||typeof n.sendConnectionTest!="function")c=gr(fr("\u4F01\u4E1A\u5FAE\u4FE1\u673A\u5668\u4EBA"));else try{await n.sendConnectionTest(a.botId),c=gr()}catch(d){c=gr(d)}s=await Uc({...g,...c?{testMessage:c}:{}},i)}else if(e===pr.setWorkspace){if(typeof n.updateWorkspace!="function")throw new Error("Workspace update is unavailable");s=await Uc(await n.updateWorkspace(a.botId,a.workspace),i)}else if(e===pr.setContextEnhancement){if(typeof n.updateContextEnhancement!="function")throw new Error("Context enhancement update is unavailable");s=await n.updateContextEnhancement(a.botId,a.config,g=>Uc(g,i))}else if(e===pr.setAccessPolicy){if(typeof n.updateAccessPolicy!="function")throw new Error("Access policy update is unavailable");s=await n.updateAccessPolicy(a.botId,a.policy,g=>Uc(g,i))}else if(e===pr.setAgentPreset){if(typeof n.updateAgentPreset!="function")throw new Error("Agent preset update is unavailable");s=await Uc(await n.updateAgentPreset(a.botId,a.agentPreset),i)}else s=await Uc(await n.deleteBot(a.botId),i);return A?.aborted?{ok:!1,error:{code:"cancelled",message:"The request was cancelled."}}:{ok:!0,value:s}}catch(s){let g=ti(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 Nw(n,t,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(m9,w9(t,o),{authority:yr(i)})}async function D9(n,t={}){if(t?.controller)return Nw(n,t.controller,t.rpcOptions,t.rpcAuthority);let o=await gF(n,t,t.internals),i=t.deliveryService&&o.deliveryAdapter?t.deliveryService.registerAdapter(o.deliveryAdapter):void 0,e=Nw(n,o.controller,t.rpcOptions,t.rpcAuthority);return n.effect(()=>async()=>{await i?.(),await o.close()},"dsh-im: close Enterprise WeChat bot connections"),e}import{unlink as pHe}from"node:fs/promises";import{homedir as hHe}from"node:os";import{join as fB,resolve as vl}from"node:path";import{createHash as yUe}from"node:crypto";import{mkdir as mUe,readFile as SUe,rename as wUe,unlink as DUe,writeFile as OUe}from"node:fs/promises";import{dirname as bUe}from"node:path";import{createCipheriv as Z2e,createDecipheriv as X2e,createHash as O9,randomBytes as pF,randomUUID as b9}from"node:crypto";var Rw="https://ilinkai.weixin.qq.com/",$2e="2.4.6",eUe="3",T9="https://novac2c.cdn.weixin.qq.com/c2c",Rl=1800,hF="novac2c.cdn.weixin.qq.com",AUe="bot",tUe=2<<16|1024|6,rUe=15e3,M9=35e3,aUe=3,iUe=22n,oUe=Date.UTC(2020,0,1),nUe=1440*60*1e3,sUe=new Set(["wait","scaned","confirmed","expired","scaned_but_redirect","need_verifycode","verify_code_blocked","binded_redirect"]),NA=class extends Error{constructor(t,o,i={}){super(o,i),this.name="WeixinApiError",this.code=t,this.status=i.status,this.providerCode=i.providerCode}};function lt(n){return typeof n=="string"&&n.trim()?n.trim():null}function N9(n){let t=n==null?null:String(n).trim();return t&&/^-?[A-Za-z0-9_.:-]{1,160}$/.test(t)?t:void 0}function R9(n,t){return Number.isInteger(t?.status)&&(n.status=t.status),t?.providerCode!==void 0&&(n.providerCode=t.providerCode),n}function IB(n,{fallback:t="artifact-provider-rejected"}={}){if(n?.code?.startsWith?.("artifact-"))return n;let o=Number(n?.status),i=N9(n?.providerCode),e=i??"",a=t,A="Weixin could not prepare the file for delivery.";o===401||o===403||i==="401"||i==="403"||/(?:permission|forbidden|unauthor|access.?denied)/i.test(e)?(a="artifact-permission-required",A="Weixin denied permission to send the file."):o===413||i==="413"||/(?:too.?large|size.?limit)/i.test(e)?(a="artifact-too-large",A="The file exceeds Weixin's size limit."):o===429||i==="429"||/(?:rate.?limit|too.?many)/i.test(e)?(a="artifact-rate-limited",A="Weixin rate-limited file delivery."):t==="artifact-provider-rejected"&&(A="Weixin rejected the file message.");let r=new Error(A,{cause:n});return r.code=a,R9(r,n)}function gUe(n){let t=new Error("Weixin file delivery result is uncertain",{cause:n});return t.code="artifact-delivery-uncertain",R9(t,n)}function dF(n){if(!n||typeof n!="object")return null;for(let t of["ret","errcode"])if(n[t]!==void 0&&n[t]!==0&&n[t]!=="0")return N9(n[t])??"rejected";return null}function cUe(n,t){if(t?.aborted)throw oh(t);let o=Number(n?.status);return n?.code==="network-error"||n?.code==="timeout"||n?.code==="invalid-response"||o>=500&&o<600?gUe(n):IB(n)}function IUe(n){let t=lt(n);return!t||t.length%4!==0||!/^[A-Za-z0-9+/]+={0,2}$/.test(t)?null:Buffer.from(t,"base64")}function k9(n){let t=lt(n?.aeskey);if(t){if(!/^[0-9a-fA-F]{32}$/.test(t))throw new NA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002");return Buffer.from(t,"hex")}let o=IUe(n?.media?.aes_key);if(o?.length===16)return o;if(o?.length===32&&/^[0-9a-fA-F]{32}$/.test(o.toString("ascii")))return Buffer.from(o.toString("ascii"),"hex");throw new NA("invalid-image-key","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u5BC6\u94A5\u65E0\u6548\u3002")}function v9(n,t){let o=Buffer.from(n),i=Buffer.from(t);if(i.length!==16||o.length===0||o.length%16!==0)throw new NA("invalid-image-ciphertext","\u5FAE\u4FE1\u56FE\u7247\u7684\u52A0\u5BC6\u6570\u636E\u65E0\u6548\u3002");try{let e=X2e("aes-128-ecb",i,null);return Buffer.concat([e.update(o),e.final()])}catch(e){throw new NA("image-decryption-failed","\u5FAE\u4FE1\u56FE\u7247\u89E3\u5BC6\u5931\u8D25\u3002",{cause:e})}}function P9(n){let t=lt(n?.encrypt_query_param);if(t)return`${T9}/download?encrypted_query_param=${encodeURIComponent(t)}`;let o=lt(n?.full_url);if(!o)throw new NA("missing-image-url","\u5FAE\u4FE1\u56FE\u7247\u6CA1\u6709\u53EF\u7528\u7684\u4E0B\u8F7D\u5730\u5740\u3002");let i;try{i=new URL(o)}catch{throw new NA("invalid-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u65E0\u6548\u3002")}if(i.protocol!=="https:"||i.hostname!==hF||i.port&&i.port!=="443"||!i.pathname.startsWith("/c2c/"))throw new NA("untrusted-image-url","\u5FAE\u4FE1\u56FE\u7247\u7684\u4E0B\u8F7D\u5730\u5740\u4E0D\u53D7\u4FE1\u4EFB\u3002");return i.username="",i.password="",i.hash="",i.toString()}function EF(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.image_item;!e||typeof e!="object"||o.push({name:o.length===0?"image":`image-${o.length+1}`,load:async({signal:a,maxBytes:A})=>{let r=k9(e),s=P9(e.media),g=await bo(s,{fetchImpl:t,signal:a,maxBytes:A+16,allowedHosts:[hF]});return v9(g,r)}})}return o}async function lUe(n,{fetchImpl:t,signal:o}){let i=await t(new URL(n),{method:"GET",signal:o,redirect:"manual"});if(!i?.ok)throw await i?.body?.cancel?.().catch?.(()=>{}),new NA("file-download-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${i?.status??"unknown"}\uFF09\u3002`,{status:i?.status});return Buffer.from(await i.arrayBuffer())}function uF(n,{fetchImpl:t=fetch}={}){if(typeof t!="function")throw new TypeError("fetchImpl must be a function");let o=[];for(let i of n?.item_list??[]){let e=i?.file_item;if(!e||typeof e!="object")continue;let a=Number(e.len);o.push({name:lt(e.file_name)??(o.length===0?"file":`file-${o.length+1}`),...Number.isFinite(a)&&a>=0?{size:a}:{},load:async({signal:A}={})=>{A?.throwIfAborted();let r=k9(e),s=P9(e.media),g=await lUe(s,{fetchImpl:t,signal:A});return A?.throwIfAborted(),v9(g,r)}})}return o}function CF(n){let t=n.toLowerCase().replace(/\.$/,"");return t==="weixin.qq.com"||t.endsWith(".weixin.qq.com")||t==="wechat.com"||t.endsWith(".wechat.com")}function nh(n){let t;try{t=new URL(n)}catch{throw new NA("invalid-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740\u3002")}if(t.protocol!=="https:"||!CF(t.hostname)||t.port!==""&&t.port!=="443")throw new NA("untrusted-base-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740\u3002");return t.username="",t.password="",t.search="",t.hash="",t.pathname.endsWith("/")||(t.pathname+="/"),t.toString()}function dUe(n){let t=lt(n);if(!t)throw new NA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u626B\u7801\u5730\u5740\u3002");let o;try{o=new URL(t)}catch{throw new NA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740\u3002")}if(o.protocol!=="https:"||!CF(o.hostname))throw new NA("untrusted-qr","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740\u3002");return o.toString()}function G9(){return{"iLink-App-Id":AUe,"iLink-App-ClientVersion":String(tUe)}}function pUe(n){let t={...G9(),"content-type":"application/json",AuthorizationType:"ilink_bot_token","X-WECHAT-UIN":Buffer.from(String(pF(4).readUInt32BE(0)),"utf8").toString("base64")};return lt(n)&&(t.Authorization=`Bearer ${n.trim()}`),t}function Hc(){return{channel_version:$2e,bot_agent:"DeepSeekHarness/1.1.0"}}function hUe(n){return Math.ceil((n+1)/16)*16}function _9(n){let t;try{t=new URL(n)}catch{throw new NA("invalid-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002")}if(t.protocol!=="https:"||t.hostname!==hF||t.port&&t.port!=="443"||t.pathname!=="/c2c/upload"||t.username||t.password)throw new NA("untrusted-upload-url","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");return t.hash="",t}function EUe(n,t){let o=lt(n?.upload_full_url);if(o)return _9(o);let i=lt(n?.upload_param);if(!i)throw new NA("missing-upload-url","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6587\u4EF6\u4E0A\u4F20\u5730\u5740\u3002");let e=new URL(`${T9}/upload`);return e.searchParams.set("encrypted_query_param",i),e.searchParams.set("filekey",t),_9(e)}function uUe(n,t){let o=Z2e("aes-128-ecb",t,null);return Buffer.concat([o.update(n),o.final()])}async function CUe(n,t,o,{signal:i}={}){let e;for(let a=1;a<=aUe;a+=1){i?.throwIfAborted();try{let A=await n(t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:o,signal:i?AbortSignal.any([i,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4),redirect:"error"});if(A.status>=400&&A.status<500)throw new NA("upload-rejected",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u88AB\u62D2\u7EDD\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});if(A.status!==200)throw new NA("upload-failed",`\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF08HTTP ${A.status}\uFF09\u3002`,{status:A.status});let r=lt(A.headers.get("x-encrypted-param"));if(await A.body?.cancel?.().catch(()=>{}),!r)throw new NA("invalid-upload-response","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11\u4E0B\u8F7D\u53C2\u6570\u3002");return r}catch(A){if(i?.aborted)throw oh(i);if(A instanceof NA&&(A.code==="upload-rejected"||A.status<500))throw A;e=A}}throw e instanceof NA?e:new NA("upload-failed","\u5FAE\u4FE1\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\u3002",{cause:e})}function oh(n){return n?.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError")}async function Ms(n,{method:t,baseUrl:o,endpoint:i,body:e,token:a,timeoutMs:A=rUe,signal:r,authenticated:s=!0}){let g=nh(o),c=new URL(i,g);if(!CF(c.hostname))throw new NA("untrusted-endpoint","\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u670D\u52A1\u5730\u5740\u3002");let I=new AbortController,d=!1,B=()=>I.abort(r?.reason);if(r?.aborted)throw oh(r);r?.addEventListener("abort",B,{once:!0});let f=A>0?setTimeout(()=>{d=!0,I.abort()},A):null;try{let Q=await n(c,{method:t,headers:s?pUe(a):G9(),...e===void 0?{}:{body:JSON.stringify(e)},signal:I.signal});if(!Q.ok)throw new NA("http-error",`\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${Q.status}\uFF09\u3002`,{status:Q.status});try{return await Q.json()}catch(y){throw new NA("invalid-response","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\u3002",{cause:y})}}catch(Q){throw r?.aborted?oh(r):d?new NA("timeout","\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6\u3002",{cause:Q}):Q instanceof NA?Q:new NA("network-error","\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1\u3002",{cause:Q})}finally{f&&clearTimeout(f),r?.removeEventListener("abort",B)}}function BUe(n){if(!n||typeof n!="object"||!sUe.has(n.status))throw new NA("invalid-login-status","\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001\u3002");return n}function F9({fetchImpl:n=fetch}={}){if(typeof n!="function")throw new TypeError("fetchImpl must be a function");async function t({baseUrl:o,token:i,toUserId:e,file:a,contextToken:A,runId:r,signal:s},{mediaType:g,createItem:c}){let I=lt(e);if(!I||!a||typeof a!="object"||typeof a.fileName!="string"||!a.fileName||!Buffer.isBuffer(a.bytes))throw new TypeError("toUserId and a file are required");s?.throwIfAborted();let d=pF(16).toString("hex"),B=pF(16),f=O9("md5").update(a.bytes).digest("hex"),Q;try{Q=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getuploadurl",token:i,signal:s,body:{filekey:d,media_type:g,to_user_id:I,rawsize:a.bytes.byteLength,rawfilemd5:f,filesize:hUe(a.bytes.byteLength),no_need_thumb:!0,aeskey:B.toString("hex"),base_info:Hc()}})}catch(H){if(s?.aborted)throw oh(s);let G=Number(H?.status),V=H?.code==="http-error"&&G>=400&&G<500?"artifact-provider-rejected":"artifact-provider-failed";throw IB(H,{fallback:V})}let y=dF(Q);if(y)throw IB(new NA("upload-url-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u4E0A\u4F20\u8BF7\u6C42\u3002",{providerCode:y}));let m=EUe(Q,d),T=uUe(a.bytes,B),_;try{_=await CUe(n,m,T,{signal:s})}catch(H){if(s?.aborted)throw oh(s);let G=Number(H?.status),V=H?.code==="upload-rejected"||G>=400&&G<500?"artifact-provider-rejected":"artifact-provider-failed";throw IB(H,{fallback:V})}s?.throwIfAborted();let R=lt(a.deliveryKey)??lt(a.artifactId)??b9(),x=g===3?R:`${R}\0${g}`,F=`dsh-weixin-${O9("sha256").update(x).digest("hex").slice(0,32)}`,L={encrypt_query_param:_,aes_key:Buffer.from(B.toString("hex")).toString("base64"),encrypt_type:1},q;try{q=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:I,client_id:F,message_type:2,message_state:2,item_list:[c({file:a,media:L,ciphertextSize:T.byteLength})],...lt(A)?{context_token:A.trim()}:{},...lt(r)?{run_id:r.trim()}:{}},base_info:Hc()}})}catch(H){throw cUe(H,s)}let z=dF(q);if(z)throw IB(new NA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6587\u4EF6\u6D88\u606F\u3002",{providerCode:z}));return{messageId:F}}return Object.freeze({inboundImages(o){return EF(o,{fetchImpl:n})},inboundFiles(o){return uF(o,{fetchImpl:n})},async beginLogin({localTokens:o=[],botType:i=eUe,signal:e}={}){let a=[...new Set(o.map(lt).filter(Boolean))].slice(-10),A=await Ms(n,{method:"POST",baseUrl:Rw,endpoint:`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(i)}`,body:{local_token_list:a},timeoutMs:1e4,signal:e}),r=lt(A?.qrcode);if(!r)throw new NA("invalid-qr","\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u4E8C\u7EF4\u7801\u4EE4\u724C\u3002");return{qrcode:r,qrcodeUrl:dUe(A.qrcode_img_content)}},async pollLogin({qrcode:o,baseUrl:i=Rw,verifyCode:e,signal:a}){let A=lt(o);if(!A)throw new TypeError("qrcode is required");let r=`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(A)}`;lt(e)&&(r+=`&verify_code=${encodeURIComponent(e.trim())}`);let s=await Ms(n,{method:"GET",baseUrl:i,endpoint:r,timeoutMs:M9,signal:a,authenticated:!1});return BUe(s)},async getUpdates({baseUrl:o,token:i,getUpdatesBuf:e="",timeoutMs:a,signal:A}){try{return await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getupdates",body:{get_updates_buf:e,base_info:Hc()},token:i,timeoutMs:a??M9,signal:A})}catch(r){if(r instanceof NA&&r.code==="timeout")return{ret:0,msgs:[],get_updates_buf:e};throw r}},async getConfig({baseUrl:o,token:i,toUserId:e,contextToken:a,signal:A}){let r=lt(e);if(!r)throw new TypeError("toUserId is required");let s=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/getconfig",token:i,signal:A,timeoutMs:1e4,body:{ilink_user_id:r,...lt(a)?{context_token:a.trim()}:{},base_info:Hc()}});if(s?.ret!==void 0&&s.ret!==0)throw new NA("config-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u673A\u5668\u4EBA\u914D\u7F6E\u8BF7\u6C42\u3002");return{typingTicket:lt(s?.typing_ticket)}},async sendTyping({baseUrl:o,token:i,toUserId:e,typingTicket:a,status:A,signal:r}){let s=lt(e),g=lt(a);if(!s||!g)throw new TypeError("toUserId and typingTicket are required");if(A!==1&&A!==2)throw new TypeError("typing status must be 1 or 2");let c=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendtyping",token:i,signal:r,timeoutMs:1e4,body:{ilink_user_id:s,typing_ticket:g,status:A,base_info:Hc()}});if(c?.ret!==void 0&&c.ret!==0)throw new NA("typing-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u8F93\u5165\u72B6\u6001\u8BF7\u6C42\u3002");return!0},async sendText({baseUrl:o,token:i,toUserId:e,text:a,contextToken:A,runId:r,signal:s}){let g=lt(e),c=lt(a);if(!g||!c)throw new TypeError("toUserId and text are required");let I=`dsh-weixin-${b9()}`,d=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/sendmessage",token:i,signal:s,body:{msg:{from_user_id:"",to_user_id:g,client_id:I,message_type:2,message_state:2,item_list:[{type:1,text_item:{text:c}}],...lt(A)?{context_token:A.trim()}:{},...lt(r)?{run_id:r.trim()}:{}},base_info:Hc()}}),B=dF(d);if(B)throw new NA("send-rejected","\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u56DE\u590D\u6D88\u606F\u3002",{providerCode:B});return{...d&&typeof d=="object"?d:{},providerMessageIds:[I]}},async sendFile(o){return t(o,{mediaType:3,createItem:({file:i,media:e})=>({type:4,file_item:{media:e,file_name:i.fileName,len:String(i.bytes.byteLength)}})})},async sendImage(o){return t(o,{mediaType:1,createItem:({media:i,ciphertextSize:e})=>({type:2,image_item:{media:i,mid_size:e}})})},async notifyStart({baseUrl:o,token:i,signal:e}){let a=await Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystart",token:i,signal:e,timeoutMs:1e4,body:{base_info:Hc()}});if(a?.ret!==void 0&&a.ret!==0)throw new NA("start-rejected","\u5FAE\u4FE1\u8D26\u53F7\u8FDE\u63A5\u542F\u52A8\u5931\u8D25\u3002");return a},async notifyStop({baseUrl:o,token:i,signal:e}){return Ms(n,{method:"POST",baseUrl:o,endpoint:"ilink/bot/msg/notifystop",token:i,signal:e,timeoutMs:1e4,body:{base_info:Hc()}})}})}function kl(n){for(let t of n?.item_list??[]){if(t?.type===1&&typeof t.text_item?.text=="string"){let o=t.text_item.text.trim();if(o)return o}if(t?.type===3&&typeof t.voice_item?.text=="string"){let o=t.voice_item.text.trim();if(o)return o}}return null}function fUe(n){if(n?.type===2||n?.image_item&&typeof n.image_item=="object")return{kind:"image"};if(n?.type===3||n?.voice_item&&typeof n.voice_item=="object")return{kind:"audio"};if(n?.type===4||n?.file_item&&typeof n.file_item=="object"){let t=lt(n?.file_item?.file_name);return{kind:"file",...t?{name:t}:{}}}return n?.type===5||n?.video_item&&typeof n.video_item=="object"?{kind:"video"}:null}function QUe(n){let t=lt(n?.text_item?.text);return t||lt(n?.voice_item?.text)}function BF(n,{resolveContent:t,loadContent:o}={}){let i=(n?.item_list??[]).find(B=>B?.ref_msg&&typeof B.ref_msg=="object");if(!i)return null;let e=i.ref_msg,a=e.message_item&&typeof e.message_item=="object"?e.message_item:null,r=QUe(a)??lt(e.title),s=fUe(a),g=a?.msg_id===void 0||a?.msg_id===null?null:lt(String(a.msg_id)),c={messageId:g,createTimeMs:a?.create_time_ms??e.create_time_ms,updateTimeMs:a?.update_time_ms??e.update_time_ms};!r&&!s&&typeof t=="function"&&(r=lt(t(c)));let I=!r&&!s&&typeof o=="function"?B=>o(c,B):null,d=a&&[1,2,3,4,5,8].includes(a.type);return{...g?{messageId:g}:{},...r?{content:r}:{},...s?{attachments:[s]}:{},...I?{load:I}:{},...!r&&!s&&!I?{unavailableReason:a&&!d?"unsupported":"not-delivered"}:{}}}function kw(n,{now:t=Date.now()}={}){let o=n==null?"":String(n).trim();if(!/^\d{16,20}$/u.test(o))return null;try{let i=Number(BigInt(o)>>iUe);return!Number.isSafeInteger(i)||it+nUe?null:i}catch{return null}}function fF(n){return n?.message_id!==void 0&&n.message_id!==null?String(n.message_id):lt(n?.client_id)}function L9(n,t=Rl){if(n.length<=t)return[n];let o=[],i=n;for(;i.length>t;){let e=i.lastIndexOf(` `,t);ea===null))return null;let o=new Set,i=new Set,e=new Set;for(let a of t){if(o.has(a.botId)||i.has(a.accountId)||e.has(a.tokenRef))return null;o.add(a.botId),i.add(a.accountId),e.add(a.tokenRef)}return Object.freeze({version:1,accounts:Object.freeze(t)})}var vw=class{#e;#A=QF;#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{let t=_Ue(JSON.parse(await SUe(this.#e,"utf8")));if(!t)throw new Error("dsh-weixin config contains invalid account data");this.#A=t}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=QF}return this}list(){return structuredClone(this.#A.accounts)}get(t){let o=this.#A.accounts.find(i=>i.botId===t);return o?structuredClone(o):null}getByAccountId(t){let o=this.#A.accounts.find(i=>i.accountId===t);return o?structuredClone(o):null}async save(t){let o=H9(t);if(!o)throw new Error("Refusing to persist incomplete dsh-weixin account data");return this.#r(i=>{let e=i.find(r=>r.accountId===o.accountId&&r.botId!==o.botId),a=i.find(r=>r.tokenRef===o.tokenRef&&r.botId!==o.botId);if(e||a)throw new Error("Duplicate Weixin account identity");let A=i.findIndex(r=>r.botId===o.botId);return A===-1?i.push(o):i[A]=o,structuredClone(o)})}async remove(t){if(!U9(t))throw new TypeError("Invalid Weixin bot id");return this.#r(o=>{let i=o.findIndex(a=>a.botId===t);if(i===-1)return null;let[e]=o.splice(i,1);return structuredClone(e)})}async clear(){let t=this.#t.then(async()=>{try{await DUe(this.#e)}catch(o){if(o?.code!=="ENOENT")throw o}this.#A=QF});this.#t=t.then(()=>{},()=>{}),await t}async#r(t){let o,i=this.#t.then(async()=>{let e=[...this.#A.accounts];o=t(e);let a=Object.freeze({version:1,accounts:Object.freeze(e)});await this.#l(a),this.#A=a});return this.#t=i.then(()=>{},()=>{}),await i,o}async#l(t){await mUe(bUe(this.#e),{recursive:!0,mode:448});let o=`${this.#e}.tmp`;await OUe(o,`${JSON.stringify(t,null,2)} `,{encoding:"utf8",mode:384}),await wUe(o,this.#e)}};var Pw=class extends Qr{constructor(t){super({...t,rpcIdPrefix:"weixin",logPrefix:"dsh-weixin"})}};import{mkdir as TUe,readFile as NUe,rename as RUe,unlink as kUe,writeFile as vUe}from"node:fs/promises";import{dirname as PUe}from"node:path";var Gw=Object.freeze({version:1,sessions:{},seenMessageIds:[],getUpdatesBuf:"",recentOutboundMessages:[]}),GUe=200,FUe=720*60*60*1e3,LUe=8e3,K9=15e3;function lB(n){return typeof n=="string"&&n.trim()?n.trim():null}function Fw(n){let t=typeof n=="string"&&n.trim()?Number(n):n;return Number.isFinite(t)&&t>=0?Math.trunc(t):null}function UUe(n){return Array.isArray(n)?[...new Set(n.map(t=>t==null?null:lB(String(t))).filter(Boolean))]:[]}function HUe(n){let t=lB(n);return t?[...t].slice(0,LUe).join(""):null}function x9(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=lB(n.toUserId),o=HUe(n.text),i=Fw(n.sentAt),e=Fw(n.completedAt)??i;return!t||!o||i===null||e===null?null:{toUserId:t,text:o,sentAt:i,completedAt:Math.max(i,e),providerMessageIds:UUe(n.providerMessageIds)}}function SF(n,t=Date.now()){if(!Array.isArray(n))return[];let o=t-FUe;return n.map(x9).filter(i=>i&&i.completedAt>=o).slice(-GUe)}function KUe(n){if(!n||typeof n!="object")return structuredClone(Gw);let t={};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&&(t[o]=i);return{version:1,sessions:t,seenMessageIds:Array.isArray(n.seenMessageIds)?n.seenMessageIds.filter(o=>typeof o=="string").slice(-1e3):[],getUpdatesBuf:typeof n.getUpdatesBuf=="string"?n.getUpdatesBuf:"",recentOutboundMessages:SF(n.recentOutboundMessages)}}var Lw=class{#e;#A=structuredClone(Gw);#t=Promise.resolve();constructor(t){this.#e=t}async load(){try{this.#A=KUe(JSON.parse(await NUe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(Gw),await this.#r()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){this.#A.sessions[t]=o,await this.#r()}async clearSession(t){delete this.#A.sessions[t],await this.#r()}async clearSessions(){this.#A.sessions={},await this.#r()}hasSeen(t){return this.#A.seenMessageIds.includes(t)}async markSeen(t){this.hasSeen(t)||(this.#A.seenMessageIds.push(t),this.#A.seenMessageIds.length>1e3&&this.#A.seenMessageIds.splice(0,this.#A.seenMessageIds.length-1e3),await this.#r())}getUpdatesBuf(){return this.#A.getUpdatesBuf}async setGetUpdatesBuf(t){typeof t!="string"||t===this.#A.getUpdatesBuf||(this.#A.getUpdatesBuf=t,await this.#r())}async rememberOutboundMessage({toUserId:t,text:o,sentAt:i=Date.now(),completedAt:e=Date.now(),providerMessageIds:a=[]}={}){let A=x9({toUserId:t,text:o,sentAt:i,completedAt:e,providerMessageIds:a});if(!A)throw new TypeError("Invalid Weixin outbound message");this.#A.recentOutboundMessages=SF([...this.#A.recentOutboundMessages,A]),await this.#r()}recentOutboundTextFor({toUserId:t,messageId:o,createTimeMs:i,updateTimeMs:e,now:a=Date.now()}={}){let A=lB(t);if(!A)return null;let r=SF(this.#A.recentOutboundMessages,a).filter(I=>I.toUserId===A),s=o==null?null:lB(String(o));if(s){let I=r.filter(d=>d.providerMessageIds.includes(s));if(I.length===1)return I[0].text;if(I.length>1)return null}let g=[Fw(i),Fw(e),kw(s,{now:a})].filter(I=>I!==null);if(g.length===0)return null;let c=r.filter(I=>g.some(d=>d>=I.sentAt-K9&&d<=I.completedAt+K9));return c.length===1?c[0].text:null}snapshot(){return structuredClone(this.#A)}async remove(){try{await kUe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(Gw)}async#r(){let t=`${JSON.stringify(this.#A,null,2)} -`,o=this.#t.then(async()=>{await TUe(PUe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await vUe(i,t,{encoding:"utf8",mode:384}),await RUe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as xUe}from"node:crypto";var Y9=new Set(["starting","pending","scanned","needs_verification","connecting"]),Uw=new Set(["connected","expired","failed","cancelled"]),j9=5*6e4,z9=Object.freeze({"credential-read-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u8BFB\u53D6\u73B0\u6709\u767B\u5F55\u51ED\u636E\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u5B58\u50A8\u3002","credential-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u65E0\u6CD5\u5199\u5165 DSH \u51ED\u636E\u5B58\u50A8\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u662F\u5426\u53EF\u5199\u3002","account-config-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u8D26\u53F7\u914D\u7F6E\u65E0\u6CD5\u5199\u5165\u672C\u673A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u76EE\u5F55\u6743\u9650\u3002","runtime-prepare-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u521D\u59CB\u5316\u8D26\u53F7\u72B6\u6001\u6216\u5DE5\u4F5C\u533A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u548C\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002","harness-connect-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u63D2\u4EF6\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A Harness\u3002\u8BF7\u68C0\u67E5 dsh web \u5730\u5740\u548C\u7AEF\u53E3\u3002","harness-timeout":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\u3002\u8BF7\u786E\u8BA4 dsh web \u672A\u963B\u585E\u3002","harness-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u9700\u8981\u8EAB\u4EFD\u8BA4\u8BC1\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u3001\u7F51\u5173\u6216\u81EA\u5B9A\u4E49\u9274\u6743\u914D\u7F6E\u3002","harness-proxy-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u672C\u673A Harness \u8BF7\u6C42\u88AB\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\u3002\u8BF7\u8BA9\u56DE\u73AF\u5730\u5740\u7ED5\u8FC7\u4EE3\u7406\uFF0C\u5E76\u68C0\u67E5 NO_PROXY \u914D\u7F6E\u3002","harness-loopback-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5F02\u5E38\u62D2\u7EDD\u4E86\u56DE\u73AF\u5730\u5740\u7684\u5065\u5EB7\u68C0\u67E5\u3002\u8BF7\u68C0\u67E5 HTTP \u4EE3\u7406\u3001Harness \u6E90\u7801\u7248\u672C\u548C\u6784\u5EFA\u4EA7\u7269\u3002","harness-host-untrusted":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u7684 Host \u4FE1\u4EFB\u68C0\u67E5\u62D2\u7EDD\u4E86\u975E\u56DE\u73AF\u5730\u5740\u8BF7\u6C42\u3002\u8BF7\u68C0\u67E5 harnessBaseUrl \u4E0E trustedHosts \u914D\u7F6E\u3002","harness-request-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u5065\u5EB7\u68C0\u67E5\u6536\u5230\u4E86\u975E Harness \u6807\u51C6\u7684 403 \u62D2\u7EDD\u54CD\u5E94\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u6216\u7F51\u5173\u914D\u7F6E\u3002","harness-api-not-found":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u627E\u4E0D\u5230 Harness \u5065\u5EB7\u68C0\u67E5\u63A5\u53E3\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-http-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8FD4\u56DE\u670D\u52A1\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-response-invalid":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-rpc-rejected":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u5065\u5EB7\u68C0\u67E5\u8BF7\u6C42\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-check-unknown-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","connection-start-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6D88\u606F\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u540E\u91CD\u8BD5\u3002"});function sh(n){return typeof n=="string"&&n.trim()?n.trim():null}function YUe(){return new DOMException("Provisioning was cancelled","AbortError")}function J9(n,t){let o=sh(n);return o?nh(o.includes("://")?o:`https://${o}`):nh(t)}function dB(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 Ei(n,t){return Object.freeze({code:n,message:t})}function pB(n,t){let o=new Error(`Weixin activation failed during ${n}`,{cause:t});return o.name="WeixinActivationStageError",o.code=n,o}function jUe(n){if(n instanceof NA)return Ei(n.code,n.message);let t=z9[n?.code];return t?Ei(n.code,w(t)):Ei("activation-unknown-failed",w("\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6FC0\u6D3B\u8FC7\u7A0B\u4E2D\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002"))}function q9(n,t){return n instanceof NA||z9[n?.code]?n:pB(t,n)}var hB=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new Map;#n=new Map;#s=null;#d=new Map;#c=0;#g=!1;constructor({api:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.beginLogin!="function"||typeof t.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A}async initialize(){if(this.#g)return this.status();for(let t of this.#t.list())this.#i.get(t.botId)?.status?.ready!==!0&&await this.#Q(t.botId,async()=>{let i=this.#t.get(t.botId);if(!(!i||this.#g))try{let e=await this.#C(i.tokenRef);if(!e){this.#a.set(i.botId,Ei("missing-token",w("\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.#a.delete(i.botId)}catch(e){this.#a.set(i.botId,Ei("connection-failed",w("\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.#y()}});return this.status()}async startProvisioning(){if(this.#g)throw new Error("dsh-weixin controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t={id:xUe(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+j9,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:Rw,error:null,botId:null,task:null};this.#n.set(t.id,t),this.#s=t.id,this.#y();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#C(e.tokenRef)))).filter(Boolean),i=await this.#e.beginLogin({localTokens:o,signal:t.controller.signal});return this.#f(t),t.qrcode=i.qrcode,t.verificationUrl=i.qrcodeUrl,t.state="pending",t.expiresAt=Date.now()+j9,this.#y(),t.task=this.#I(t),dB(t)}catch(o){throw t.controller.signal.aborted?(t.state="cancelled",t.error=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Ei(o instanceof NA?o.code:"qr-start-failed",o instanceof NA?o.message:w("\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),this.#s===t.id&&(this.#s=null),this.#y(),o}}registrationStatus(t){return dB(this.#n.get(t))}async submitVerification(t,o){let i=this.#n.get(t);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=sh(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.#y(),dB(i)}async cancelProvisioning(t){let o=this.#n.get(t);return o?(Uw.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),Uw.has(o.state)||(o.state="cancelled"),o.error??=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))),this.#s===o.id&&(this.#s=null),this.#y(),dB(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(t,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#a.delete(t)}catch(e){throw this.#a.set(t,Ei("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#y()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return this.#Q(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw fr(w("\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(La(w("\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{name}\uFF09",{name:mF(o.accountId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Weixin account");return this.#Q(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#u(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the Weixin account safely.",{cause:e})}try{await this.#l({botId:t,config:o})}catch(e){this.#o.warn?.(`[dsh-weixin] account ${t} state cleanup failed:`,e)}this.#a.delete(t),this.#y()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.weixinConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.weixinConnectionState==="connecting"?"connecting":this.#a.has(e.botId)||a?.weixinConnectionState==="failed"?"error":"offline",s=this.#a.get(e.botId)??(r==="error"?Ei("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")):null);return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u5FAE\u4FE1\u673A\u5668\u4EBA"),accountIdMasked:mF(e.accountId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Aa(a?.lastMessageError),error:s?structuredClone(s):null}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#n.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&Y9.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&Y9.has(i.state)?{provisioning:dB(i)}:{}}}async close(){this.#g||(this.#g=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#i.keys()].map(t=>this.#u(t))))}async#I(t){try{for(;!t.controller.signal.aborted&&Date.now(){t.verifyResolve=i,t.controller.signal.aborted&&i()}),t.verifyResolve=null,this.#f(t));let o=await this.#e.pollLogin({qrcode:t.qrcode,baseUrl:t.currentBaseUrl,verifyCode:t.pendingVerifyCode,signal:t.controller.signal});if(this.#f(t),o.status==="wait")t.state="pending";else if(o.status==="scaned")t.pendingVerifyCode=null,t.state="scanned";else if(o.status==="need_verifycode")t.pendingVerifyCode=null,t.state="needs_verification";else if(o.status==="verify_code_blocked"){t.state="failed",t.error=Ei("verification-blocked",w("\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"));break}else if(o.status==="expired"){t.state="expired",t.error=Ei("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"));break}else if(o.status==="scaned_but_redirect")t.currentBaseUrl=J9(o.redirect_host,t.currentBaseUrl),t.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?(t.state="connected",t.botId=i.botId,t.alreadyConnected=!0):(t.state="failed",t.error=Ei("already-bound",w("\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=sh(o.bot_token),e=sh(o.ilink_bot_id),a=sh(o.ilink_user_id);if(!i||!e||!a)throw new NA("incomplete-login",w("\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002"));t.state="connecting",this.#y();let A=J9(o.baseurl,t.currentBaseUrl);t.botId=await this.#p(t,{token:i,accountId:e,ownerUserId:a,baseUrl:A}),t.state="connected",t.error=null;break}this.#y()}!t.controller.signal.aborted&&Date.now()>=t.expiresAt&&!Uw.has(t.state)&&(t.state="expired",t.error=Ei("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")))}catch(o){t.controller.signal.aborted||o?.name==="AbortError"?(t.state="cancelled",t.error=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=jUe(o),this.#o.error?.("[dsh-weixin] provisioning failed:",o))}finally{t.pendingVerifyCode=null,t.verifyResolve?.(),t.verifyResolve=null,this.#s===t.id&&(this.#s=null),this.#y(),this.#S()}}async#p(t,{token:o,accountId:i,ownerUserId:e,baseUrl:a}){let A=yF(i),r=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:a,createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g;try{g=await this.#A.resolve(A.tokenRef)}catch(c){throw pB("credential-read-failed",c)}return this.#Q(A.botId,async()=>{try{try{await this.#A.set(A.tokenRef,o)}catch(c){throw pB("credential-save-failed",c)}this.#f(t);try{await this.#t.save(s)}catch(c){throw pB("account-config-save-failed",c)}return this.#f(t),await this.#h(s,o),this.#f(t),this.#a.delete(A.botId),this.#y(),A.botId}catch(c){throw await this.#u(A.botId),r?await this.#t.save(r).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.remove(A.botId).catch(()=>null)&&await this.#l({botId:A.botId,config:s}).catch(d=>{this.#o.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",d)}),await this.#B(A.tokenRef,g),r&&g?.value&&await this.#h(r,g.value).catch(()=>{}),c}})}async#h(t,o){await this.#u(t.botId);let i;try{i=await this.#r({botId:t.botId,config:t,token:o})}catch(e){throw q9(e,"runtime-prepare-failed")}if(!i||typeof i.start!="function"||typeof i.stop!="function")throw pB("runtime-prepare-failed",new TypeError("createRuntime returned an invalid Weixin runtime"));try{await i.start(),this.#i.set(t.botId,i)}catch(e){throw await i.stop().catch(()=>{}),q9(e,"connection-start-failed")}}async#u(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-weixin] account ${t} failed to stop cleanly:`,i)})}async#C(t){let o=await this.#A.resolve(t).catch(()=>{});return sh(o?.value)}async#B(t,o){try{o?.value?await this.#A.set(t,o.value):await this.#A.unset(t)}catch(i){this.#o.error?.(`[dsh-weixin] failed to restore credential ${t}:`,i)}}#f(t){if(t.controller.signal.aborted||this.#s!==t.id)throw YUe()}#Q(t,o){let a=(this.#d.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#d.get(t)===a&&this.#d.delete(t)});return this.#d.set(t,a),a}#S(){for(let[t,o]of this.#n)t!==this.#s&&Uw.has(o.state)&&this.#n.size>16&&this.#n.delete(t)}#y(){this.#c+=1}};var Hw=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),JUe=5e3,wF=6e4,Z9=Symbol("weixin-send-diagnostic"),qUe=100,zUe=3,VUe=5e3,WUe=15e3,ZUe=()=>[w("\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` +`,o=this.#t.then(async()=>{await TUe(PUe(this.#e),{recursive:!0,mode:448});let i=`${this.#e}.tmp`;await vUe(i,t,{encoding:"utf8",mode:384}),await RUe(i,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};import{randomUUID as xUe}from"node:crypto";var Y9=new Set(["starting","pending","scanned","needs_verification","connecting"]),Uw=new Set(["connected","expired","failed","cancelled"]),j9=5*6e4,z9=Object.freeze({"credential-read-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u8BFB\u53D6\u73B0\u6709\u767B\u5F55\u51ED\u636E\u3002\u8BF7\u68C0\u67E5 DSH \u51ED\u636E\u5B58\u50A8\u3002","credential-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u65E0\u6CD5\u5199\u5165 DSH \u51ED\u636E\u5B58\u50A8\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u5B58\u50A8\u662F\u5426\u53EF\u5199\u3002","account-config-save-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u8D26\u53F7\u914D\u7F6E\u65E0\u6CD5\u5199\u5165\u672C\u673A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u76EE\u5F55\u6743\u9650\u3002","runtime-prepare-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u65E0\u6CD5\u521D\u59CB\u5316\u8D26\u53F7\u72B6\u6001\u6216\u5DE5\u4F5C\u533A\u3002\u8BF7\u68C0\u67E5 DSH_HOME \u548C\u5DE5\u4F5C\u533A\u76EE\u5F55\u3002","harness-connect-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u63D2\u4EF6\u65E0\u6CD5\u8FDE\u63A5\u672C\u673A Harness\u3002\u8BF7\u68C0\u67E5 dsh web \u5730\u5740\u548C\u7AEF\u53E3\u3002","harness-timeout":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\u3002\u8BF7\u786E\u8BA4 dsh web \u672A\u963B\u585E\u3002","harness-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u9700\u8981\u8EAB\u4EFD\u8BA4\u8BC1\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u3001\u7F51\u5173\u6216\u81EA\u5B9A\u4E49\u9274\u6743\u914D\u7F6E\u3002","harness-proxy-auth-required":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u672C\u673A Harness \u8BF7\u6C42\u88AB\u4EE3\u7406\u8981\u6C42\u8BA4\u8BC1\u3002\u8BF7\u8BA9\u56DE\u73AF\u5730\u5740\u7ED5\u8FC7\u4EE3\u7406\uFF0C\u5E76\u68C0\u67E5 NO_PROXY \u914D\u7F6E\u3002","harness-loopback-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5F02\u5E38\u62D2\u7EDD\u4E86\u56DE\u73AF\u5730\u5740\u7684\u5065\u5EB7\u68C0\u67E5\u3002\u8BF7\u68C0\u67E5 HTTP \u4EE3\u7406\u3001Harness \u6E90\u7801\u7248\u672C\u548C\u6784\u5EFA\u4EA7\u7269\u3002","harness-host-untrusted":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u7684 Host \u4FE1\u4EFB\u68C0\u67E5\u62D2\u7EDD\u4E86\u975E\u56DE\u73AF\u5730\u5740\u8BF7\u6C42\u3002\u8BF7\u68C0\u67E5 harnessBaseUrl \u4E0E trustedHosts \u914D\u7F6E\u3002","harness-request-forbidden":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u5065\u5EB7\u68C0\u67E5\u6536\u5230\u4E86\u975E Harness \u6807\u51C6\u7684 403 \u62D2\u7EDD\u54CD\u5E94\u3002\u8BF7\u68C0\u67E5\u4EE3\u7406\u6216\u7F51\u5173\u914D\u7F6E\u3002","harness-api-not-found":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u627E\u4E0D\u5230 Harness \u5065\u5EB7\u68C0\u67E5\u63A5\u53E3\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-http-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u8FD4\u56DE\u670D\u52A1\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-response-invalid":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u54CD\u5E94\u3002\u8BF7\u786E\u8BA4 Harness \u4E0E\u63D2\u4EF6\u7248\u672C\u517C\u5BB9\u3002","harness-rpc-rejected":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u62D2\u7EDD\u4E86\u5065\u5EB7\u68C0\u67E5\u8BF7\u6C42\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","harness-check-unknown-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46 Harness \u5065\u5EB7\u68C0\u67E5\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002","connection-start-failed":"\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6D88\u606F\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u540E\u91CD\u8BD5\u3002"});function sh(n){return typeof n=="string"&&n.trim()?n.trim():null}function YUe(){return new DOMException("Provisioning was cancelled","AbortError")}function J9(n,t){let o=sh(n);return o?nh(o.includes("://")?o:`https://${o}`):nh(t)}function dB(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 Ei(n,t){return Object.freeze({code:n,message:t})}function pB(n,t){let o=new Error(`Weixin activation failed during ${n}`,{cause:t});return o.name="WeixinActivationStageError",o.code=n,o}function jUe(n){if(n instanceof NA)return Ei(n.code,n.message);let t=z9[n?.code];return t?Ei(n.code,w(t)):Ei("activation-unknown-failed",w("\u5FAE\u4FE1\u5DF2\u6388\u6743\uFF0C\u4F46\u6FC0\u6D3B\u8FC7\u7A0B\u4E2D\u53D1\u751F\u672A\u77E5\u9519\u8BEF\u3002\u8BF7\u67E5\u770B dsh web \u65E5\u5FD7\u3002"))}function q9(n,t){return n instanceof NA||z9[n?.code]?n:pB(t,n)}var hB=class{#e;#A;#t;#r;#l;#o;#i=new Map;#a=new Map;#n=new Map;#s=null;#d=new Map;#c=0;#g=!1;constructor({api:t,credentials:o,configStore:i,createRuntime:e,deleteState:a=async()=>{},logger:A=console}){if(!t||typeof t.beginLogin!="function"||typeof t.pollLogin!="function")throw new TypeError("WeixinController requires a Weixin API client");if(!o||typeof o.resolve!="function"||typeof o.set!="function"||typeof o.unset!="function")throw new TypeError("WeixinController requires the DSH credential provider");if(!i||typeof i.list!="function"||typeof i.save!="function"||typeof i.remove!="function")throw new TypeError("WeixinController requires a config store");if(typeof e!="function")throw new TypeError("createRuntime is required");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A}async initialize(){if(this.#g)return this.status();for(let t of this.#t.list())this.#i.get(t.botId)?.status?.ready!==!0&&await this.#Q(t.botId,async()=>{let i=this.#t.get(t.botId);if(!(!i||this.#g))try{let e=await this.#C(i.tokenRef);if(!e){this.#a.set(i.botId,Ei("missing-token",w("\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.#a.delete(i.botId)}catch(e){this.#a.set(i.botId,Ei("connection-failed",w("\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.#y()}});return this.status()}async startProvisioning(){if(this.#g)throw new Error("dsh-weixin controller is closed");this.#s&&await this.cancelProvisioning(this.#s);let t={id:xUe(),state:"starting",createdAt:Date.now(),expiresAt:Date.now()+j9,controller:new AbortController,pendingVerifyCode:null,verifyResolve:null,currentBaseUrl:Rw,error:null,botId:null,task:null};this.#n.set(t.id,t),this.#s=t.id,this.#y();try{let o=(await Promise.all(this.#t.list().slice(-10).map(async e=>this.#C(e.tokenRef)))).filter(Boolean),i=await this.#e.beginLogin({localTokens:o,signal:t.controller.signal});return this.#f(t),t.qrcode=i.qrcode,t.verificationUrl=i.qrcodeUrl,t.state="pending",t.expiresAt=Date.now()+j9,this.#y(),t.task=this.#I(t),dB(t)}catch(o){throw t.controller.signal.aborted?(t.state="cancelled",t.error=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=Ei(o instanceof NA?o.code:"qr-start-failed",o instanceof NA?o.message:w("\u65E0\u6CD5\u751F\u6210\u5FAE\u4FE1\u4E8C\u7EF4\u7801\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),this.#s===t.id&&(this.#s=null),this.#y(),o}}registrationStatus(t){return dB(this.#n.get(t))}async submitVerification(t,o){let i=this.#n.get(t);if(!i||i.state!=="needs_verification")throw new Error("The provisioning attempt is not waiting for a verification code");let e=sh(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.#y(),dB(i)}async cancelProvisioning(t){let o=this.#n.get(t);return o?(Uw.has(o.state)||(o.controller.abort(),o.verifyResolve?.(),o.verifyResolve=null,await o.task?.catch(()=>{}),Uw.has(o.state)||(o.state="cancelled"),o.error??=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))),this.#s===o.id&&(this.#s=null),this.#y(),dB(o)):null}async reconnectBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(t,async()=>{let i=await this.#C(o.tokenRef);if(!i)throw new Error("The Weixin token is missing");try{await this.#h(o,i),this.#a.delete(t)}catch(e){throw this.#a.set(t,Ei("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u4ECD\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))),e}finally{this.#y()}}),this.status()}async sendConnectionTest(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return this.#Q(t,async()=>{let i=this.#i.get(t);if(!i?.status?.ready||typeof i.sendConnectionTest!="function")throw fr(w("\u5FAE\u4FE1\u673A\u5668\u4EBA"));return i.sendConnectionTest(La(w("\u5FAE\u4FE1\u673A\u5668\u4EBA\uFF08{name}\uFF09",{name:mF(o.accountId)})))})}async sendProactiveText(t,o,i,e={}){if(!this.#t.get(t))throw new Error("Unknown Weixin account");return this.#Q(t,async()=>{let A=this.#i.get(t);if(!A?.status?.ready||typeof A.sendProactiveText!="function"){let r=new Error(w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"));throw r.code="bot-not-connected",r}return A.sendProactiveText(o,i,e)})}async deleteBot(t){let o=this.#t.get(t);if(!o)throw new Error("Unknown Weixin account");return await this.#Q(t,async()=>{let i=await this.#A.resolve(o.tokenRef).catch(()=>{});await this.#u(t);try{await this.#A.unset(o.tokenRef),await this.#t.remove(t)}catch(e){throw i?.value&&(await this.#A.set(o.tokenRef,i.value).catch(()=>{}),await this.#h(o,i.value).catch(()=>{})),new Error("Unable to remove the Weixin account safely.",{cause:e})}try{await this.#l({botId:t,config:o})}catch(e){this.#o.warn?.(`[dsh-weixin] account ${t} state cleanup failed:`,e)}this.#a.delete(t),this.#y()}),this.status()}status(){let t=this.#t.list().map(e=>{let a=this.#i.get(e.botId)?.status??null,A=a?.ready===!0&&a.weixinConnectionState==="connected"&&a.harnessReachable===!0,r=A?"connected":a?.weixinConnectionState==="connecting"?"connecting":this.#a.has(e.botId)||a?.weixinConnectionState==="failed"?"error":"offline",s=this.#a.get(e.botId)??(r==="error"?Ei("connection-failed",w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002")):null);return{botId:e.botId,state:r,connected:A,configured:!0,bot:{name:w("\u5FAE\u4FE1\u673A\u5668\u4EBA"),accountIdMasked:mF(e.accountId)},health:{status:A?"healthy":r==="error"?"error":"offline",summary:A?w("\u5FAE\u4FE1\u6D88\u606F\u957F\u8F6E\u8BE2\u8FD0\u884C\u6B63\u5E38"):r==="error"?w("\u5FAE\u4FE1\u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u63D2\u4EF6\u4F1A\u81EA\u52A8\u91CD\u8BD5"):w("\u5FAE\u4FE1\u8FDE\u63A5\u5F53\u524D\u79BB\u7EBF"),lastCheckedAt:a?.lastCheckedAt??null},stats:{messagesReceived:a?.messagesReceived??0,messagesReplied:a?.messagesReplied??0},lastMessageError:Aa(a?.lastMessageError),error:s?structuredClone(s):null}}),o=t.filter(e=>e.connected).length,i=this.#s?this.#n.get(this.#s):null;return{schemaVersion:1,revision:this.#c,state:i&&Y9.has(i.state)?"provisioning":t.length===0?"disconnected":o===t.length?"connected":o>0?"degraded":"offline",bots:t,totals:{configured:t.length,connected:o},...i&&Y9.has(i.state)?{provisioning:dB(i)}:{}}}async close(){this.#g||(this.#g=!0,this.#s&&await this.cancelProvisioning(this.#s),await Promise.allSettled([...this.#i.keys()].map(t=>this.#u(t))))}async#I(t){try{for(;!t.controller.signal.aborted&&Date.now(){t.verifyResolve=i,t.controller.signal.aborted&&i()}),t.verifyResolve=null,this.#f(t));let o=await this.#e.pollLogin({qrcode:t.qrcode,baseUrl:t.currentBaseUrl,verifyCode:t.pendingVerifyCode,signal:t.controller.signal});if(this.#f(t),o.status==="wait")t.state="pending";else if(o.status==="scaned")t.pendingVerifyCode=null,t.state="scanned";else if(o.status==="need_verifycode")t.pendingVerifyCode=null,t.state="needs_verification";else if(o.status==="verify_code_blocked"){t.state="failed",t.error=Ei("verification-blocked",w("\u914D\u5BF9\u7801\u591A\u6B21\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u4E8C\u7EF4\u7801\u3002"));break}else if(o.status==="expired"){t.state="expired",t.error=Ei("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002"));break}else if(o.status==="scaned_but_redirect")t.currentBaseUrl=J9(o.redirect_host,t.currentBaseUrl),t.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?(t.state="connected",t.botId=i.botId,t.alreadyConnected=!0):(t.state="failed",t.error=Ei("already-bound",w("\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=sh(o.bot_token),e=sh(o.ilink_bot_id),a=sh(o.ilink_user_id);if(!i||!e||!a)throw new NA("incomplete-login",w("\u5FAE\u4FE1\u6388\u6743\u6210\u529F\uFF0C\u4F46\u8FD4\u56DE\u7684\u8D26\u53F7\u51ED\u636E\u4E0D\u5B8C\u6574\u3002"));t.state="connecting",this.#y();let A=J9(o.baseurl,t.currentBaseUrl);t.botId=await this.#p(t,{token:i,accountId:e,ownerUserId:a,baseUrl:A}),t.state="connected",t.error=null;break}this.#y()}!t.controller.signal.aborted&&Date.now()>=t.expiresAt&&!Uw.has(t.state)&&(t.state="expired",t.error=Ei("expired",w("\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u3002")))}catch(o){t.controller.signal.aborted||o?.name==="AbortError"?(t.state="cancelled",t.error=Ei("cancelled",w("\u626B\u7801\u7ED1\u5B9A\u5DF2\u53D6\u6D88\u3002"))):(t.state="failed",t.error=jUe(o),this.#o.error?.("[dsh-weixin] provisioning failed:",o))}finally{t.pendingVerifyCode=null,t.verifyResolve?.(),t.verifyResolve=null,this.#s===t.id&&(this.#s=null),this.#y(),this.#S()}}async#p(t,{token:o,accountId:i,ownerUserId:e,baseUrl:a}){let A=yF(i),r=this.#t.getByAccountId(i),s={botId:A.botId,accountId:i,tokenRef:A.tokenRef,ownerUserId:e,baseUrl:a,createdAt:r?.createdAt??new Date().toISOString(),connectedAt:new Date().toISOString()},g;try{g=await this.#A.resolve(A.tokenRef)}catch(c){throw pB("credential-read-failed",c)}return this.#Q(A.botId,async()=>{try{try{await this.#A.set(A.tokenRef,o)}catch(c){throw pB("credential-save-failed",c)}this.#f(t);try{await this.#t.save(s)}catch(c){throw pB("account-config-save-failed",c)}return this.#f(t),await this.#h(s,o),this.#f(t),this.#a.delete(A.botId),this.#y(),A.botId}catch(c){throw await this.#u(A.botId),r?await this.#t.save(r).catch(()=>{}):this.#t.get(A.botId)&&await this.#t.remove(A.botId).catch(()=>null)&&await this.#l({botId:A.botId,config:s}).catch(d=>{this.#o.warn?.("[dsh-weixin] failed to clean up cancelled bot state:",d)}),await this.#B(A.tokenRef,g),r&&g?.value&&await this.#h(r,g.value).catch(()=>{}),c}})}async#h(t,o){await this.#u(t.botId);let i;try{i=await this.#r({botId:t.botId,config:t,token:o})}catch(e){throw q9(e,"runtime-prepare-failed")}if(!i||typeof i.start!="function"||typeof i.stop!="function")throw pB("runtime-prepare-failed",new TypeError("createRuntime returned an invalid Weixin runtime"));try{await i.start(),this.#i.set(t.botId,i)}catch(e){throw await i.stop().catch(()=>{}),q9(e,"connection-start-failed")}}async#u(t){let o=this.#i.get(t);this.#i.delete(t),await o?.stop().catch(i=>{this.#o.warn?.(`[dsh-weixin] account ${t} failed to stop cleanly:`,i)})}async#C(t){let o=await this.#A.resolve(t).catch(()=>{});return sh(o?.value)}async#B(t,o){try{o?.value?await this.#A.set(t,o.value):await this.#A.unset(t)}catch(i){this.#o.error?.(`[dsh-weixin] failed to restore credential ${t}:`,i)}}#f(t){if(t.controller.signal.aborted||this.#s!==t.id)throw YUe()}#Q(t,o){let a=(this.#d.get(t)??Promise.resolve()).catch(()=>{}).then(o).finally(()=>{this.#d.get(t)===a&&this.#d.delete(t)});return this.#d.set(t,a),a}#S(){for(let[t,o]of this.#n)t!==this.#s&&Uw.has(o.state)&&this.#n.size>16&&this.#n.delete(t)}#y(){this.#c+=1}};var Hw=()=>w("\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002"),JUe=5e3,wF=6e4,Z9=Symbol("weixin-send-diagnostic"),qUe=100,zUe=3,VUe=5e3,WUe=15e3,ZUe=()=>[w("\u5FAE\u4FE1\u5DF2\u8FDE\u63A5 DeepSeek Harness\u3002"),"",w("\u76F4\u63A5\u53D1\u9001\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\u6216\u5E26\u6587\u5B57\u8BC6\u522B\u7ED3\u679C\u7684\u8BED\u97F3\u5373\u53EF\u7EE7\u7EED\u5F53\u524D\u4F1A\u8BDD\u3002"),w("/new \u5F00\u542F\u4E00\u4E2A\u5168\u65B0\u4F1A\u8BDD"),w("/compact \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u7684\u8F83\u65E9\u4E0A\u4E0B\u6587"),w("/history [\u6570\u91CF] \u67E5\u770B\u6700\u8FD1\u5386\u53F2\u6D88\u606F\uFF08\u9ED8\u8BA4 3 \u6761\uFF0C\u6700\u591A 5 \u6761\uFF09"),w("/workspace \u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84 \u5207\u6362\u5DE5\u4F5C\u533A"),w("/workspacelist \u5217\u51FA\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84"),w("/ws\u3001/wsl\u3001/workspaces \u5DE5\u4F5C\u533A\u547D\u4EE4\u522B\u540D"),w("/sessionlist \u6216 /sessions [\u5DE5\u4F5C\u533A\u5E8F\u53F7\u6216\u7EDD\u5BF9\u8DEF\u5F84] \u5217\u51FA\u4F1A\u8BDD ID \u548C\u6807\u9898"),w("/sessionlist --limit N \u4EC5\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u524D N \u4E2A\u4F1A\u8BDD"),w("/session Session ID \u6216\u5F53\u524D\u5DE5\u4F5C\u533A\u5E8F\u53F7 \u5C06\u5F53\u524D\u804A\u5929\u7ED1\u5B9A\u5230\u6307\u5B9A\u4F1A\u8BDD"),w("/models \u6309\u5E8F\u53F7\u5217\u51FA\u6240\u6709\u53EF\u7528\u6A21\u578B"),w("/reasoninglist \u6216 /reasonings \u6309\u5E8F\u53F7\u5217\u51FA\u5F53\u524D\u6A21\u578B\u53EF\u7528\u63A8\u7406\u7B49\u7EA7"),w("/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u63A8\u7406\u7B49\u7EA7"),w("/model [\u5E8F\u53F7\u6216\u5B8C\u6574\u6A21\u578BID] [\u63A8\u7406\u7B49\u7EA7ID] \u67E5\u770B\u6216\u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),w("\u793A\u4F8B\uFF1A\u5148\u53D1 /models\uFF0C\u518D\u53D1 /model 2 [\u63A8\u7406\u7B49\u7EA7ID]"),w("/presetlist \u6216 /presets \u6309\u5E8F\u53F7\u5217\u51FA\u53EF\u7528 Agent Preset"),w("/preset [\u5E8F\u53F7\u6216\u5B8C\u6574ID] \u67E5\u770B\u6216\u8BBE\u7F6E\u5F53\u524D\u673A\u5668\u4EBA Agent Preset"),w("\u7EAF\u6570\u5B57 ID\uFF1A/preset id:"),w("/preset --default \u8DDF\u968F Host \u9ED8\u8BA4"),w("/stop \u505C\u6B62\u5F53\u524D\u4EFB\u52A1"),w("/steer \u8865\u5145\u6307\u4EE4 \u7EA0\u504F\u5F53\u524D\u4EFB\u52A1"),w("/batch \u5F00\u59CB\u6279\u91CF\u8F93\u5165\uFF08\u4EC5\u79C1\u804A\uFF0C\u6700\u591A 10 \u6761\u6587\u5B57\uFF09"),w("/send \u63D0\u4EA4\u5F53\u524D\u6279\u6B21"),w("/cancel \u53D6\u6D88\u5F53\u524D\u6279\u6B21"),w("/status \u68C0\u67E5\u8FDE\u63A5\u72B6\u6001"),w("/version \u67E5\u770B\u63D2\u4EF6\u7248\u672C"),w("/help \u663E\u793A\u672C\u5E2E\u52A9")].join(` `);function V9(n){return`p2p:${n}`}function Ar(n){return typeof n=="string"&&n.trim()?n.trim():null}function CB(n){let t=n==null?"":String(n).trim();return/^-?[A-Za-z0-9_.:-]{1,160}$/u.test(t)?t:"-"}function XUe(n){try{return CB(new URL(n).hostname.toLowerCase())}catch{return"-"}}function $Ue({baseUrl:n,text:t,chunk:o,chunkIndex:i,chunkCount:e,maxMessageChars:a,contextToken:A,runId:r,error:s}){let g=Number(s?.status??s?.httpStatus),c=Number.isInteger(g)?String(g):s?.code==="send-rejected"?"2xx":"-";return["endpoint=sendmessage",`host=${XUe(n)}`,`chunk=${i+1}/${e}`,`chunkChars=${o.length}`,`chunkUtf8Bytes=${Buffer.byteLength(o,"utf8")}`,`totalChars=${t.length}`,`totalUtf8Bytes=${Buffer.byteLength(t,"utf8")}`,`limitChars=${a}`,`contextToken=${A?"yes":"no"}`,`runId=${r?"yes":"no"}`,`http=${c}`,`provider=${CB(s?.providerCode)}`,`cause=${CB(s?.code??s?.name)}`].join(" ")}function eHe(n,t){let o=$Ue({...t,error:n}),i=new Error(`Weixin text delivery failed (${o})`,{cause:n}),e=CB(n?.code);i.code=e==="-"?"weixin-send-failed":e;let a=Number(n?.status??n?.httpStatus);Number.isInteger(a)&&(i.status=a);let A=CB(n?.providerCode);return A!=="-"&&(i.providerCode=A),i[Z9]=o,i}function W9(n){let t=n;for(let o=0;t&&o<5;o+=1){let i=t[Z9];if(typeof i=="string"&&i)return{reason:"weixin-send-failed",userMessage:[w("\u56DE\u590D\u5DF2\u7ECF\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u53D1\u9001\u5931\u8D25\uFF0C\u53EF\u80FD\u53EA\u6536\u5230\u90E8\u5206\u5185\u5BB9\u3002\u8BF7\u5C06\u4E0B\u9762\u7684\u8BCA\u65AD\u4FE1\u606F\u5B8C\u6574\u53CD\u9988\u7ED9\u7BA1\u7406\u5458\u3002"),w("\u5FAE\u4FE1\u53D1\u9001\u8BCA\u65AD\uFF1A{diagnostic}",{diagnostic:i})].join(` `)};t=t.cause}}function AHe(n,t,o,{loadReplyContent:i}={}){let e=Ar(n?.from_user_id),a=BF(n,{resolveContent:A=>o?.recentOutboundTextFor?.({toUserId:e,...A}),...typeof i=="function"?{loadContent:(A,r)=>i({toUserId:e,...A},r)}:{}});return{content:kl(n)??"",images:typeof t?.inboundImages=="function"?t.inboundImages(n):EF(n),files:typeof t?.inboundFiles=="function"?t.inboundFiles(n):uF(n),...a?{replyTo:a}:{}}}function EB(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.image_item&&typeof t.image_item=="object")}function uB(n){return Array.isArray(n?.item_list)&&n.item_list.some(t=>t?.file_item&&typeof t.file_item=="object")}function tHe(n){return Array.isArray(n?.item_list)&&n.item_list.length>0&&n.item_list.every(t=>t?.type===1&&typeof t.text_item?.text=="string")&&!!Ar(kl(n))}function rHe(n,t){return t.questions[t.index]&&Ar(n?.from_user_id)===t.actor&&!EB(n)&&!uB(n)&&Ar(kl(n))}function aHe(n,t){let o=String(n??w("\u7ED3\u679C\u6587\u4EF6")).replace(/[\r\n]+/g," ").trim()||w("\u7ED3\u679C\u6587\u4EF6");switch(t?.code){case"artifact-delivery-uncertain":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\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",{name:o});case"artifact-permission-required":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u673A\u5668\u4EBA\u5F53\u524D\u6CA1\u6709\u6587\u4EF6\u6D88\u606F\u53D1\u9001\u6743\u9650\uFF0C\u8BF7\u68C0\u67E5\u673A\u5668\u4EBA\u6587\u4EF6\u6D88\u606F\u80FD\u529B\u3002",{name:o});case"artifact-too-large":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u8D85\u8FC7\u5F53\u524D\u5FAE\u4FE1\u4F1A\u8BDD\u53EF\u53D1\u9001\u7684\u6587\u4EF6\u5927\u5C0F\uFF0C\u672A\u53D1\u9001\u3002",{name:o});case"artifact-rate-limited":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u6682\u65F6\u88AB\u5FAE\u4FE1\u9650\u6D41\uFF0C\u672A\u80FD\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o});case"artifact-provider-rejected":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u5FAE\u4FE1\u62D2\u7EDD\u4E86\u8BE5\u6587\u4EF6\u6D88\u606F\u3002",{name:o});case"artifact-invalid":case"artifact-changed":case"artifact-unavailable":return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\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",{name:o});default:return w("\u7ED3\u679C\u6587\u4EF6\u300C{name}\u300D\u5DF2\u751F\u6210\uFF0C\u4F46\u6682\u65F6\u672A\u80FD\u901A\u8FC7\u5FAE\u4FE1\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",{name:o})}}function DF(){return{messagesReceived:0,messagesReplied:0,messagesRejected:0,lastMessageAt:null,lastReplyAt:null,lastRejectedAt:null,lastError:null,lastMessageError:null}}var Kw=class{#e;#A;#t;#r;#l;#o;#i;#a;#n;#s;#d;#c;#g;#I;#p=new Map;#h=new Map;#u=new Map;#C=new Map;#B=new Set;#f=new Set;#Q;#S=new ki;#y=null;#m=null;#D=null;#E=0;#R=Promise.resolve();#_=!1;#O=0;#w=!1;constructor({api:t,baseUrl:o,token:i,ownerUserId:e,harness:a,state:A,contextEnhancement:r,accessPolicy:s,status:g=DF(),logger:c=console,replyTimeoutMs:I=6e5,maxMessageChars:d=Rl,typingKeepaliveMs:B=JUe,signal:f}){if(!t||typeof t.sendText!="function")throw new TypeError("Weixin API is required");if(!o||!i||!e)throw new TypeError("Weixin account credentials are required");if(!a||!A)throw new TypeError("Harness client and state store are required");if(!Number.isFinite(B)||B<=0)throw new TypeError("typingKeepaliveMs must be a positive number");this.#e=t,this.#A=o,this.#t=i,this.#r=e,this.#l=a,this.#o=A,this.#i=r,this.#a=s,this.#n=g,this.#s=c,this.#d=I,this.#c=d,this.#g=B,this.#I=f,this.#Q=new Mi({label:"weixin",logger:c})}get status(){return structuredClone(this.#n)}accept(t){if(this.#I?.aborted||t?.message_type===2)return Promise.resolve();let o=fF(t),i=Ar(t?.from_user_id);if(!o||!i||this.#o.hasSeen(o)||this.#C.has(o))return Promise.resolve();let e=Ar(kl(t))??"",a=this.#a?Da(this.#a,{conversationType:"direct",senderIds:i,text:e,hasImages:EB(t),hasFiles:uB(t)}):i===this.#r?{allowed:!0,reason:"legacy-owner"}:{allowed:!1,reason:"sender-not-allowed"};if(!a.allowed)return this.#C.set(o,null),this.#F(o,i,t,a);this.#C.set(o,aa(this.#i,"direct")),i===this.#r&&Do(this.#o,{toUserId:i});let A=V9(i),r=Ar(t?.context_token)??void 0,s=Ar(t?.run_id)??void 0,g=this.#h.get(A),c=vi(e),I=this.#S.status(A);if(c||I.phase==="collecting"){let Q=/^\/batch$/iu.test(e)&&I.phase==="idle"&&(this.#p.has(A)||g||this.#Q.hasPending(A))?{handled:!0,kind:"busy",message:Ro()}:this.#S.handle(A,e,{plainText:tHe(t)&&!BF(t)});if(Q.handled)return Q.kind==="submit"?this.#T({...t,item_list:[{type:1,text_item:{text:Q.prompt}}]},o,A,{batchSubmission:Q}):this.#N(t,o,A,i,r,s,Q)}let d=xa(e)?ao:uB(t)?null:ci(e)?Ni:Ii(e)?io:li(e)?Ri:null;if(d){let f;return f=this.#k(t,o,A,i,r,s,e,d).catch(Q=>{if(Q?.code==="turn-stopped"||this.#I?.aborted)return;this.#n.lastError=Q?.message??String(Q);let y=tt(this.#n,Q);return this.#s.error?.(`[dsh-weixin] failed to process a command [${y.referenceId}]:`,Q),this.#te(A,i,Et(y),r,s).catch(()=>{})}).finally(()=>{this.#C.delete(o),this.#f.delete(f)}),this.#f.add(f),f}let B=this.#Q.claimReply({key:A,actor:i,messageId:o,text:EB(t)||uB(t)?"":kl(t),addressed:!0,hasPendingQuestion:!!g,questionCompletion:g?.submitting||g?.claimedReplyMessageId?g.queue:null,isQuestionPending:()=>this.#h.has(A),send:f=>this.#H(i,f,r,s)});if(B){let f;return f=B.process(async()=>this.#o.hasSeen(o)?!1:(await this.#o.markSeen(o),this.#n.messagesReceived+=1,this.#n.lastMessageAt=new Date().toISOString(),!0)).finally(()=>{this.#C.delete(o),this.#B.delete(f)}),this.#B.add(f),f}if(g?.submitting||g?.claimedReplyMessageId)return this.#T(t,o,A);if(g){rHe(t,g)&&(g.claimedReplyMessageId=o);let Q=(g.queue??Promise.resolve()).catch(()=>{}).then(()=>this.#U(t,o,A,g)).catch(y=>this.#Z(t,o,y)).finally(()=>{this.#C.delete(o),g.claimedReplyMessageId===o&&(g.claimedReplyMessageId=null),g.queue===Q&&(g.queue=null)});return g.queue=Q,Q}return this.#T(t,o,A)}#T(t,o,i,{releaseMessageId:e=!0,alreadyRecorded:a=!1,batchSubmission:A=null}={}){let r=Fd(this.#M(t),{signal:this.#I}),g=(this.#p.get(i)??Promise.resolve()).catch(()=>{}).then(()=>this.#K(t,i,{alreadyRecorded:a,preparedMessage:r,batchSubmission:A})).finally(()=>{e&&this.#C.delete(o),this.#p.get(i)===g&&this.#p.delete(i)});return this.#p.set(i,g),g}#M(t){return AHe(t,this.#e,this.#o,{loadReplyContent:(o,i)=>this.#P(o,i)})}async#P(t,{signal:o}={}){let i=this.#o.recentOutboundTextFor?.(t);if(i)return{content:i};let e=[kw(t?.messageId),Number(t?.createTimeMs),Number(t?.updateTimeMs)].find(Number.isSafeInteger);if(e===void 0)return{unavailableReason:"not-delivered"};let a=Ar(t?.toUserId),A=a?this.#o.sessionFor(V9(a)):null,r=typeof A=="string"&&A?this.#l.workspaceSession?.(A):null;if(typeof r?.readHistory!="function")return{unavailableReason:"not-delivered"};let s=await Ud({session:r,quotedAt:e,signal:o,pageSize:qUe,maxPages:zUe,timeoutMs:VUe,toleranceMs:WUe});if(!s)return{unavailableReason:"not-delivered"};let g=Ar(t?.messageId);try{await this.#o.rememberOutboundMessage?.({toUserId:a,text:s,sentAt:e,completedAt:e,providerMessageIds:g?[g]:[]})}catch(c){this.#s.warn?.("[dsh-weixin] failed to remember a recovered quote:",c)}return{content:s}}#N(t,o,i,e,a,A,r){let s;return s=Promise.resolve().then(async()=>{this.#o.hasSeen(o)||(await this.#o.markSeen(o),this.#n.messagesReceived+=1,this.#n.lastMessageAt=new Date().toISOString(),r.message&&await this.#te(i,e,r.message,a,A),this.#n.lastError=null)}).catch(async g=>{if(this.#I?.aborted)return;this.#n.lastError=g?.message??String(g);let c=tt(this.#n,g);this.#s.error?.(`[dsh-weixin] failed to process a batch input message [${c.referenceId}]:`,g),await this.#te(i,e,Et(c),a,A).catch(()=>{})}).finally(()=>{this.#C.delete(o),this.#f.delete(s)}),this.#f.add(s),s}#F(t,o,i,e){let a=Ar(i?.context_token)??void 0,A=Ar(i?.run_id)??void 0,r;return r=Promise.resolve().then(async()=>{this.#o.hasSeen(t)||(await this.#o.markSeen(t),e.reason==="command-not-allowed"?(this.#n.messagesReceived+=1,this.#n.lastMessageAt=new Date().toISOString(),await this.#H(o,w(no),a,A),this.#n.messagesReplied+=1,this.#n.lastReplyAt=new Date().toISOString()):(this.#n.messagesRejected+=1,this.#n.lastRejectedAt=new Date().toISOString()),this.#n.lastError=null)}).catch(s=>{this.#I?.aborted||(this.#n.lastError=s?.message??String(s),this.#s.error?.("[dsh-weixin] failed to apply inbound access policy:",s))}).finally(()=>{this.#C.delete(t),this.#f.delete(r)}),this.#f.add(r),r}async waitForIdle(){await Promise.allSettled([...this.#p.values(),...[...this.#h.values()].flatMap(t=>t.queue?[t.queue]:[]),...this.#B,...this.#f,this.#R])}async close(){this.#_=!0,await this.#J({signal:AbortSignal.timeout(5e3)})}async#k(t,o,i,e,a,A,r,s){if(this.#I?.throwIfAborted(),this.#o.hasSeen(o))return;await this.#o.markSeen(o),this.#n.messagesReceived+=1,this.#n.lastMessageAt=new Date().toISOString();let g=await s(r,this.#l,this.#o,i,{signal:this.#I,isDirect:!0,hasImages:EB(t),hasFiles:uB(t),pendingInteraction:this.#h.has(i)||this.#Q.hasPending(i),control:{owner:this,key:i}});g?.stopped&&await Promise.allSettled([this.#v(i),this.#Q.closeRoute(i)]);for(let c of g?.messages??[g?.message])c&&(g?.stopped?await this.#H(e,c,a,A):await this.#te(i,e,c,a,A));this.#n.lastError=null}async#K(t,o,{alreadyRecorded:i=!1,preparedMessage:e,batchSubmission:a=null}={}){this.#I?.throwIfAborted();let A=fF(t),r=Ar(t?.from_user_id);if(!A||!r)return;if(!i){if(this.#o.hasSeen(A))return;this.#n.messagesReceived+=1,this.#n.lastMessageAt=new Date().toISOString()}let s=typeof t.context_token=="string"?t.context_token:void 0,g=typeof t.run_id=="string"?t.run_id:void 0,c=a===null,I=!1;try{let d=e??this.#M(t),B=d.content,f=Nt(d),Q=Dt(d),y=Hr(d);if(!B&&!f&&!Q&&!y){await this.#H(r,w("\u76EE\u524D\u652F\u6301\u6587\u5B57\u3001\u56FE\u7247\u3001\u6587\u4EF6\uFF0C\u4EE5\u53CA\u5FAE\u4FE1\u5DF2\u8F6C\u6210\u6587\u5B57\u7684\u8BED\u97F3\u6D88\u606F\u3002"),s,g),await this.#o.markSeen(A);return}let m=B.trim().toLowerCase();if(!f&&!Q&&m==="/help"){await this.#H(r,ZUe(),s,g),await this.#o.markSeen(A);return}if(!f&&!Q&&m==="/status"){await this.#l.ensureRunning({signal:this.#I}),await this.#H(r,w("\u5FAE\u4FE1\u4E0E DeepSeek Harness \u8FDE\u63A5\u6B63\u5E38\u3002"),s,g),await this.#o.markSeen(A);return}if(!f&&!Q&&m==="/new"){await this.#o.clearSession(o),await this.#H(r,w("\u5DF2\u5F00\u542F\u65B0\u4F1A\u8BDD\u3002\u8BF7\u53D1\u9001\u4F60\u7684\u95EE\u9898\u3002"),s,g),await this.#o.markSeen(A);return}let T=f||Q?null:await _o(B,this.#l,o);if(T){for(let H of T.messages??[T.message])await this.#H(r,H,s,g);await this.#o.markSeen(A);return}let _=f||Q?null:await Ti(B,this.#l,this.#o,o,{signal:this.#I});if(_){await this.#H(r,_.message,s,g),await this.#o.markSeen(A);return}let R,x=[];await this.#ae(r,s);try{let H=f||y?await Go(d,{signal:this.#I}):void 0,G=this.#C.get(A),V=!1;if(G){let U=H??B;H=No(U,G,()=>({channel:"weixin",senderId:r,chatId:r})),V=H!==U}await this.#o.markSeen(A),I=!0,{answer:R,artifacts:x=[]}=await _i({harness:this.#l,state:this.#o,key:o,text:B,content:H,contextEnhanced:V,createOptions:{signal:this.#I},existsOptions:{signal:this.#I},askOptions:{timeoutMs:this.#d,signal:this.#I,control:{owner:this,key:o},onUpdate:()=>this.#$(o,r,s),onInteraction:U=>this.#j(U,{key:o,actor:r,contextToken:s,runId:g}),onInteractionResolved:async U=>{await this.#x(U),await this.#$(o,r,s)},files:d.files}}),a&&(this.#S.complete(o,a.token),c=!0)}finally{await Promise.allSettled([this.#J(),this.#v(o),this.#Q.closeRoute(o)])}let F=typeof R=="string"&&R.trim()?R:x.length>0?w("\u7ED3\u679C\u6587\u4EF6\u5DF2\u751F\u6210\u3002"):R,L=null,q=null;try{q=$t({deliveryId:A,presentation:"weixin-text",providerMessageIds:await this.#H(r,F,s,g)})}catch(H){L=Ua(H)}let z=await this.#ee(r,A,x,s,g,q);if(L&&!z.userVisible)throw L;return L&&z.artifactSendErrors===0&&tt(this.#n,L,W9(L)),I||await this.#o.markSeen(A),this.#n.messagesReplied+=1,this.#n.lastReplyAt=new Date().toISOString(),this.#n.lastError=null,!L&&z.artifactSendErrors===0&&Oo(this.#n),z.receipt}catch(d){let B=null;if(!c&&a&&(d?.code==="turn-stopped"?this.#S.complete(o,a.token):B=this.#S.fail(o,a.token).message??null,c=!0),d?.code==="turn-stopped"){I||await this.#o.markSeen(A);return}if(this.#I?.aborted)return;this.#n.lastError=d?.message??String(d);let f=vo(d)??Mo(d),Q=ro(d),y=W9(d),m=tt(this.#n,d,{userMessage:f??y?.userMessage,reason:Q?.reason??y?.reason});this.#s.error?.(`[dsh-weixin] failed to process an inbound message [${m.referenceId}]:`,d);try{await this.#H(r,B?`${Et(m)} diff --git a/src/channels/dingtalk/dingtalk-bridge.mjs b/src/channels/dingtalk/dingtalk-bridge.mjs index f287849..3e0ba35 100644 --- a/src/channels/dingtalk/dingtalk-bridge.mjs +++ b/src/channels/dingtalk/dingtalk-bridge.mjs @@ -81,6 +81,7 @@ const HELP_TEXT_LINES = [ '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)', '/workspace 工作区序号或绝对路径 切换工作区', '/workspacelist 列出工作区绝对路径', + '/ws、/wsl、/workspaces 工作区命令别名', '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题', '/sessionlist --limit N 仅列出当前工作区前 N 个会话', '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话', diff --git a/src/channels/feishu/bridge.mjs b/src/channels/feishu/bridge.mjs index f3255cc..3c0cddd 100644 --- a/src/channels/feishu/bridge.mjs +++ b/src/channels/feishu/bridge.mjs @@ -107,7 +107,7 @@ const WATCH_COMMAND = /^\/watch(?:\s+([^\s]+))?$/i; const UNWATCH_COMMAND = /^\/unwatch(?:\s+([^\s]+))?$/i; const WATCHLIST_COMMAND = /^\/watchlist$/i; const SESSION_LIST_PREFIX = /^\/(?:sessionlist|sessions)(?:\s|$)/i; -const WORKSPACE_LIST_COMMAND = /^\/workspacelist$/i; +const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)$/i; const NUMBER_REPLY = /^\d{1,2}$/; /** A displayed menu stays number-tappable for this long. */ const MENU_TTL_MS = 10 * 60_000; @@ -146,7 +146,7 @@ const REPAIR_URL_HOSTS = new Set([ const ARCHIVED_COMMAND = /^\/archived(?:\s+(on|off))?$/i; /** Matches fast card commands that should not be queued behind a running task. */ -const CARD_COMMAND = /^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|watchlist|archived(?:\s+(on|off))?)$/i; +const CARD_COMMAND = /^\/(?:m(?:enu)?|new|help|status|compact|(?:sessionlist|sessions)(?:\s|$)|workspacelist|workspaces|wsl|watchlist|archived(?:\s+(on|off))?)$/i; function isFeishuLocalCommand(text, { hasImages = false, hasFiles = false } = {}) { if (hasImages || hasFiles || typeof text !== 'string') return false; diff --git a/src/channels/feishu/feishu-cards.mjs b/src/channels/feishu/feishu-cards.mjs index 43af8ed..d5fee57 100644 --- a/src/channels/feishu/feishu-cards.mjs +++ b/src/channels/feishu/feishu-cards.mjs @@ -492,6 +492,7 @@ export function menuHelpText() { '/session ID 绑定已有会话', '/workspacelist 列出工作区', '/workspace 工作区序号或绝对路径 切换工作区', + '/ws、/wsl、/workspaces 工作区命令别名', '/new 开启全新会话', '', '📊 状态 / 压缩', @@ -595,6 +596,7 @@ export function helpCard(extraTextLines = []) { { tag: 'hr' }, { tag: 'div', text: markdown([ t(HELP_TEXT_COMMANDS), + t('/ws、/wsl、/workspaces 工作区命令别名'), t('`/version` — 查看插件版本'), t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'), ].join('\n') + extraText) }, diff --git a/src/channels/feishu/slash-command-registry.mjs b/src/channels/feishu/slash-command-registry.mjs index 65ad19f..0587e7c 100644 --- a/src/channels/feishu/slash-command-registry.mjs +++ b/src/channels/feishu/slash-command-registry.mjs @@ -43,6 +43,9 @@ export const SLASH_COMMAND_MANIFEST = Object.freeze([ { command: 'compact', icon: 'ai-block_outlined', default: '压缩当前会话上下文', en_us: 'Compact the current session' }, { command: 'sessionlist', icon: 'chat-ai_outlined', default: '列出会话', en_us: 'List sessions' }, { command: 'workspacelist', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' }, + { command: 'workspaces', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' }, + { command: 'wsl', icon: 'folder_outlined', default: '列出工作区', en_us: 'List workspaces' }, + { command: 'ws', icon: 'folder_outlined', default: '切换工作区', en_us: 'Switch workspace' }, { command: 'watch', icon: 'flag_outlined', default: '关注一个会话', en_us: 'Watch a session' }, { command: 'unwatch', icon: 'clear_outlined', default: '取消关注会话', en_us: 'Unwatch a session' }, { command: 'watchlist', icon: 'flag_outlined', default: '查看关注列表', en_us: 'List watched sessions' }, diff --git a/src/channels/qq/qq-bridge.mjs b/src/channels/qq/qq-bridge.mjs index a68bf56..a62af64 100644 --- a/src/channels/qq/qq-bridge.mjs +++ b/src/channels/qq/qq-bridge.mjs @@ -90,6 +90,7 @@ function helpText() { t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'), t('/workspace 工作区序号或绝对路径 切换工作区'), t('/workspacelist 列出工作区绝对路径'), + t('/ws、/wsl、/workspaces 工作区命令别名'), t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'), t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'), t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'), diff --git a/src/channels/shared/i18n-en/shared-a.mjs b/src/channels/shared/i18n-en/shared-a.mjs index 68f050c..79b3f9e 100644 --- a/src/channels/shared/i18n-en/shared-a.mjs +++ b/src/channels/shared/i18n-en/shared-a.mjs @@ -123,6 +123,7 @@ export default { '/workspace 工作区序号或绝对路径 切换工作区': '/workspace Switch workspace', '/workspacelist 列出工作区绝对路径': '/workspacelist List absolute workspace paths', + '/ws、/wsl、/workspaces 工作区命令别名': '/ws, /wsl, /workspaces Workspace command aliases', '/sessionlist [工作区序号或绝对路径] 列出会话 ID 和标题': '/sessionlist [workspace index or absolute path] List session IDs and titles', '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题': diff --git a/src/channels/shared/text-harness-bridge.mjs b/src/channels/shared/text-harness-bridge.mjs index ea1f483..b746484 100644 --- a/src/channels/shared/text-harness-bridge.mjs +++ b/src/channels/shared/text-harness-bridge.mjs @@ -596,6 +596,7 @@ export class TextHarnessBridge { t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'), t('/workspace 工作区序号或绝对路径 切换工作区'), t('/workspacelist 列出工作区绝对路径'), + t('/ws、/wsl、/workspaces 工作区命令别名'), t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'), t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'), t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'), diff --git a/src/channels/shared/workspace-command.mjs b/src/channels/shared/workspace-command.mjs index d6ce461..28b41f5 100644 --- a/src/channels/shared/workspace-command.mjs +++ b/src/channels/shared/workspace-command.mjs @@ -4,8 +4,8 @@ import { isAbsolute, resolve } from 'node:path'; import { t } from './i18n.mjs'; import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs'; -const WORKSPACE_COMMAND = /^\/workspace(?:\s+([\s\S]+))?$/i; -const WORKSPACE_LIST_COMMAND = /^\/workspacelist(?:\s+([\s\S]+))?$/i; +const WORKSPACE_COMMAND = /^\/(?:workspace|ws)(?:\s+([\s\S]+))?$/i; +const WORKSPACE_LIST_COMMAND = /^\/(?:workspacelist|workspaces|wsl)(?:\s+([\s\S]+))?$/i; const SESSION_LIST_COMMAND = /^\/(?:sessionlist|sessions)(?:\s+([\s\S]+))?$/i; const SESSION_BIND_PREFIX = /^\/session(?=$|\s)/i; const SESSION_BIND_COMMAND = /^\/session[ \t]+([^\s]+)$/i; diff --git a/src/channels/telegram/telegram-runtime.mjs b/src/channels/telegram/telegram-runtime.mjs index c3b34f8..2a093d6 100644 --- a/src/channels/telegram/telegram-runtime.mjs +++ b/src/channels/telegram/telegram-runtime.mjs @@ -21,7 +21,10 @@ export const TELEGRAM_COMMAND_MENU = Object.freeze([ { command: 'new', description: '开启一个全新会话' }, { command: 'compact', description: '压缩当前会话的较早上下文' }, { command: 'workspace', description: '切换工作区' }, + { command: 'ws', description: '切换工作区' }, { command: 'workspacelist', description: '列出工作区绝对路径' }, + { command: 'workspaces', description: '列出工作区绝对路径' }, + { command: 'wsl', description: '列出工作区绝对路径' }, { command: 'sessionlist', description: '列出会话 ID 和标题' }, { command: 'sessions', description: '列出会话 ID 和标题' }, { command: 'session', description: '将当前聊天绑定到指定会话' }, diff --git a/src/channels/wecom/wecom-bridge.mjs b/src/channels/wecom/wecom-bridge.mjs index 5d66cf4..eea13cd 100644 --- a/src/channels/wecom/wecom-bridge.mjs +++ b/src/channels/wecom/wecom-bridge.mjs @@ -73,6 +73,7 @@ function helpText() { t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'), t('/workspace 工作区序号或绝对路径 切换工作区'), t('/workspacelist 列出工作区绝对路径'), + t('/ws、/wsl、/workspaces 工作区命令别名'), t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'), t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'), t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'), diff --git a/src/channels/weixin/weixin-bridge.mjs b/src/channels/weixin/weixin-bridge.mjs index a7632e3..cc459e6 100644 --- a/src/channels/weixin/weixin-bridge.mjs +++ b/src/channels/weixin/weixin-bridge.mjs @@ -87,6 +87,7 @@ const HELP_TEXT = () => [ t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'), t('/workspace 工作区序号或绝对路径 切换工作区'), t('/workspacelist 列出工作区绝对路径'), + t('/ws、/wsl、/workspaces 工作区命令别名'), t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'), t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'), t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'), diff --git a/test/channels/feishu/bridge.test.mjs b/test/channels/feishu/bridge.test.mjs index ffd50ba..6fe4ce8 100644 --- a/test/channels/feishu/bridge.test.mjs +++ b/test/channels/feishu/bridge.test.mjs @@ -4602,7 +4602,7 @@ test('compact card action contains session lookup failures', async () => { }); test('Feishu list and status command failures share one safe classified format', async () => { - for (const command of ['/sessionlist', '/workspacelist', '/status']) { + for (const command of ['/sessionlist', '/workspacelist', '/workspaces', '/wsl', '/status']) { const fixture = stateFixture(); const sent = []; const status = bridgeStatus(); @@ -4619,7 +4619,7 @@ test('Feishu list and status command failures share one safe classified format', ensureRunning: async () => true, }; if (command === '/sessionlist') harness.listWorkspaceSessions = async () => { throw providerFailure(); }; - if (command === '/workspacelist') harness.listWorkspaces = async () => { throw providerFailure(); }; + if (['/workspacelist', '/workspaces', '/wsl'].includes(command)) harness.listWorkspaces = async () => { throw providerFailure(); }; if (command === '/status') harness.ensureRunning = async () => { throw providerFailure(); }; const bridge = new FeishuHarnessBridge({ client: textClient(async ({ text }) => sent.push(text)), diff --git a/test/channels/feishu/feishu-cards.test.mjs b/test/channels/feishu/feishu-cards.test.mjs index d0a3216..5cf56e0 100644 --- a/test/channels/feishu/feishu-cards.test.mjs +++ b/test/channels/feishu/feishu-cards.test.mjs @@ -70,6 +70,7 @@ test('menu and card help advertise Agent Preset, reasoning, and batch commands', assert.match(help, /\/presets/); assert.match(help, /\/sessions/); assert.match(help, /\/workspace 工作区序号或绝对路径/); + assert.match(help, /\/ws、\/wsl、\/workspaces/); assert.match(help, /\/preset \[序号或完整ID\]/); assert.match(help, /\/preset id:/); assert.match(help, /\/preset --default/); @@ -85,6 +86,7 @@ test('menu and card help advertise Agent Preset, reasoning, and batch commands', assert.match(card, /\/presets/); assert.match(card, /\/sessions/); assert.match(card, /\/workspace 工作区序号或绝对路径/); + assert.match(card, /\/ws、\/wsl、\/workspaces/); assert.match(card, /\/reasoninglist/); assert.match(card, /\/reasonings/); assert.match(card, /\/reasoning \[序号、等级ID或 --default\]/); @@ -220,7 +222,9 @@ test('reachable Feishu cards contain no Chinese literals in English mode', () => const englishMenuHelp = menuHelpText(); const englishCardHelp = helpCard(['Additional help']); assert.match(englishMenuHelp, /\/workspace /); + assert.match(englishMenuHelp, /\/ws, \/wsl, \/workspaces/); assert.match(englishCardHelp, /\/workspace /); + assert.match(englishCardHelp, /\/ws, \/wsl, \/workspaces/); rendered.push( menuCard({ workspaces: ['/work'], diff --git a/test/workspace.test.mjs b/test/workspace.test.mjs index 6aa47b5..485f9da 100644 --- a/test/workspace.test.mjs +++ b/test/workspace.test.mjs @@ -962,6 +962,9 @@ test('/workspace command supports fresh list numbers, preserves paths, and retur assert.match((await runWorkspaceCommand('/workspace 2', harness)).message, /workspacelist/); assert.deepEqual(switched, [alternateWorkspace, alternateWorkspace, defaultWorkspace]); + assert.match((await runWorkspaceCommand(`/WS ${alternateWorkspace}`, harness)).message, new RegExp(alternateWorkspace)); + assert.equal(await runWorkspaceCommand('/wsnope /tmp', harness), null); + const invalidHarness = { async switchWorkspace() { const error = new Error('工作区路径不存在。'); @@ -1018,8 +1021,14 @@ test('/workspacelist returns existing absolute paths with the current workspace assert.equal(result.messages.join(''), result.message); assert.equal(listCalls, 1); + for (const alias of ['/wsl', '/WORKSPACES']) { + assert.equal((await runWorkspaceCommand(` ${alias} `, harness)).message, result.message); + } + assert.match((await runWorkspaceCommand('/wsl extra', harness)).message, /用法/); + assert.equal(await runWorkspaceCommand('/workspacesnope', harness), null); + assert.match((await runWorkspaceCommand('/workspacelist extra', harness)).message, /用法/); - assert.equal(listCalls, 1); + assert.equal(listCalls, 3); assert.match((await runWorkspaceCommand('/workspacelist', {})).message, /暂不支持/); assert.match((await runWorkspaceCommand('/workspacelist', { async listWorkspaces() { throw new Error('private host detail'); },