diff --git a/lib/index.js b/lib/index.js index 31a455f..036c6f2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -169,7 +169,7 @@ ${n}`:n)}function G_(n,t,o){return{cardParamMap:{flowStatus:t,msgContent:cu(n,o) ${hEe(I.text,s)}`);g=Dc([i,...c,A.join(` `)].join(` -`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function uEe(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\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===Mi||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function ji(n){return typeof n=="string"&&g1.test(n.trim())}async function go(n,t,o,a,{signal:e,isDirect:i=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!ji(n))return null;let s=g1.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return Dc(w(cEe));let g=s?Math.min(Number(s),IEe):3;if(!i)return Dc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return Dc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(a);if(typeof c!="string"||!c)return Dc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return Dc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(s1),B=e?AbortSignal.any([e,d]):d,f=Date.now()+s1,Q=new Map,y,m,_=[],T=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let L=await I.readHistory({maxMessages:lEe,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(a)!==c){let J=new Error("Session binding changed during history read");throw J.code="session-binding-changed",J}if(!L||!Array.isArray(L.events)||typeof L.hasMore!="boolean")throw new TypeError("Invalid history page");let U=y??1/0;for(let J of L.events){let V=J?.event;if(!V||!Number.isSafeInteger(V.seq)||V.seq<0||typeof V.type!="string"||!V.type)throw new TypeError("Invalid history event");if(m!==void 0&&V.seq>m)continue;let H=Q.get(V.seq);if(H){if(!gEe(H,V))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&V.seq>=y)throw new TypeError("Invalid history cursor");Q.set(V.seq,V)}U=Math.min(U,V.seq)}let F=[...Q.values()].sort((J,V)=>J.seq-V.seq);if(m??=F.at(-1)?.seq,T=L.hasMore,T&&(!Number.isFinite(U)||U===y))throw new TypeError("History cursor did not advance");if(_=pEe(F).slice(-g),_.length>=g||!T)break;y=U}return _.length===0?Dc(T?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):EEe(c,_,g,T)}catch(I){return Dc(uEe(I))}}var XQ={name:"dsh-im-ops",version:"4.9.1-ops.21",description:"Ops fork of dsh-im (all channels kept). Based on @xmanrui/dsh-im@4.9.1 \u2014 access/session policies owned here.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office","ops","fork"],author:"xmanrui (https://github.com/xmanrui)",contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"},{name:"Chan-0312",url:"https://github.com/Chan-0312"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/hansjone/dsh-im-ops.git"},homepage:"https://github.com/hansjone/dsh-im-ops#readme",bugs:{url:"https://github.com/hansjone/dsh-im-ops/issues"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"},directories:{doc:"docs",lib:"lib",test:"test"}};var BEe=/^\/(?:stop|steer|version)(?=$|\s)/iu,fEe=/^\/stop(?=$|\s)/iu,QEe=/^\/version(?=$|\s)/iu,yEe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",mEe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",SEe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",wEe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function Go(n,t={}){return{message:n,...t}}function I1(n){return n?{signal:n}:{}}function l1(n,t,o){if(typeof t?.sessionFor!="function")return null;let a=t.sessionFor(o);if(typeof a!="string"||!a)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(a);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function ha(n){return typeof n=="string"&&BEe.test(n.trim())}async function Pa(n,t,o,a,{signal:e,hasImages:i=!1,pendingInteraction:A=!1,control:r}={}){if(!ha(n))return null;let s=n.trim(),g=fEe.test(s),c=QEe.test(s);if(i)return Go(w(wEe));if(c)return/^\/version$/iu.test(s)?Go(`dsh-im v${XQ.version}`):Go(w(mEe));if(g){if(!/^\/stop$/iu.test(s))return Go(w(yEe));let Q=l1(t,o,a);if(!Q)return Go(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,I1(e))?Go(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):Go(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return Go(w(SEe));if(A)return Go([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` +`)),s=Math.floor(s/2)}while(s>0&&(g.message.length>3e3||g.messages.length>3));return g}function uEe(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\u91CD\u65B0\u7ED1\u5B9A\u4F1A\u8BDD\u3002"):t===Mi||t==="workspace-bot-not-found"||t==="session-binding-changed"?w("\u4F1A\u8BDD\u3001\u5DE5\u4F5C\u533A\u6216\u673A\u5668\u4EBA\u72B6\u6001\u5DF2\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C /history\u3002"):t==="harness-api-not-found"?w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"):n?.name==="AbortError"?w("\u5386\u53F2\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002"):n?.name==="TimeoutError"||t==="harness-timeout"?w("\u8BFB\u53D6\u5386\u53F2\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"):w("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}function ji(n){return typeof n=="string"&&g1.test(n.trim())}async function go(n,t,o,a,{signal:e,isDirect:i=!1,hasImages:A=!1,hasFiles:r=!1}={}){if(!ji(n))return null;let s=g1.exec(n.trim())[1].trim();if(s&&(!/^\d+$/u.test(s)||/^0+$/u.test(s)))return Dc(w(cEe));let g=s?Math.min(Number(s),IEe):3;if(!i)return Dc(w("\u8BF7\u5728\u4E0E\u673A\u5668\u4EBA\u7684\u79C1\u804A\u4E2D\u4F7F\u7528 /history\u3002"));if(A||r)return Dc(w("/history \u4EC5\u652F\u6301\u6587\u5B57\u547D\u4EE4\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u6216\u6587\u4EF6\u540E\u91CD\u8BD5\u3002"));let c=o?.sessionFor?.(a);if(typeof c!="string"||!c)return Dc(w("\u5F53\u524D\u804A\u5929\u5C1A\u672A\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u6216\u4F7F\u7528 /session \u7ED1\u5B9A\u4F1A\u8BDD\u3002"));try{let I=t?.workspaceSession?.(c);if(typeof I?.readHistory!="function")return Dc(w("\u5F53\u524D Harness \u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u4F1A\u8BDD\u5386\u53F2\u3002"));let d=AbortSignal.timeout(s1),B=e?AbortSignal.any([e,d]):d,f=Date.now()+s1,Q=new Map,y,m,_=[],T=!1;for(let R=0;R=f)throw new DOMException("History read timed out","TimeoutError");let L=await I.readHistory({maxMessages:lEe,...y===void 0?{}:{beforeSeq:y},timeoutMs:Math.max(1,f-Date.now()),signal:B});if(B.throwIfAborted(),Date.now()>=f)throw new DOMException("History read timed out","TimeoutError");if(o.sessionFor(a)!==c){let J=new Error("Session binding changed during history read");throw J.code="session-binding-changed",J}if(!L||!Array.isArray(L.events)||typeof L.hasMore!="boolean")throw new TypeError("Invalid history page");let U=y??1/0;for(let J of L.events){let V=J?.event;if(!V||!Number.isSafeInteger(V.seq)||V.seq<0||typeof V.type!="string"||!V.type)throw new TypeError("Invalid history event");if(m!==void 0&&V.seq>m)continue;let H=Q.get(V.seq);if(H){if(!gEe(H,V))throw new TypeError("Conflicting history events")}else{if(y!==void 0&&V.seq>=y)throw new TypeError("Invalid history cursor");Q.set(V.seq,V)}U=Math.min(U,V.seq)}let F=[...Q.values()].sort((J,V)=>J.seq-V.seq);if(m??=F.at(-1)?.seq,T=L.hasMore,T&&(!Number.isFinite(U)||U===y))throw new TypeError("History cursor did not advance");if(_=pEe(F).slice(-g),_.length>=g||!T)break;y=U}return _.length===0?Dc(T?w("\u672C\u6B21\u6709\u9650\u8BFB\u53D6\u4E2D\u672A\u627E\u5230\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002"):w("\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u9884\u89C8\u7684\u5386\u53F2\u6D88\u606F\u3002")):EEe(c,_,g,T)}catch(I){return Dc(uEe(I))}}var XQ={name:"dsh-im-ops",version:"4.9.1-ops.22",description:"Ops fork of dsh-im (all channels kept). Based on @xmanrui/dsh-im@4.9.1 \u2014 access/session policies owned here.",keywords:["deepseek-harness","dsh","dsh-plugin","ai-agent","im","instant-messaging","chatbot","feishu","lark","wechat","wecom","dingtalk","qq","slack","telegram","discord","whatsapp","ai-office","ops","fork"],author:"xmanrui (https://github.com/xmanrui)",contributors:[{name:"C3H3-AI",url:"https://github.com/C3H3-AI"},{name:"divingleee",url:"https://github.com/divingleee"},{name:"Chan-0312",url:"https://github.com/Chan-0312"}],license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/hansjone/dsh-im-ops.git"},homepage:"https://github.com/hansjone/dsh-im-ops#readme",bugs:{url:"https://github.com/hansjone/dsh-im-ops/issues"},bin:{"dsh-im":"bin/dsh-im.mjs"},main:"./lib/index.js",exports:{".":"./lib/index.js","./client":"./lib/client.js","./package.json":"./package.json"},files:["assets","bin","cordis.patch.yml","lib","plugin-src","scripts","src","PROACTIVE_DELIVERY.md","PROACTIVE_DELIVERY.en.md","LICENSE","README.md","README.en.md","THIRD_PARTY_NOTICES.md"],dsh:{bundle:{patch:"./cordis.patch.yml"},client:{inject:["@deepseek-ai/dsh-client-connection","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-settings","@deepseek-ai/dsh-client-ui-slots","@deepseek-ai/dsh-client-locale"],platform:"web"}},scripts:{build:"node plugin-src/client/build.mjs && node plugin-src/host/build.mjs",test:"node --test test/*.test.mjs test/channels/*/*.test.mjs",check:"npm run build && npm test && node scripts/verify-package.mjs"},engines:{node:">=22.19"},dependencies:{"@tencent-connect/qqbot-connector":"1.2.0","@tencent-connect/qqbot-nodejs":"1.0.4","@wecom/aibot-node-sdk":"1.0.7","dingtalk-stream":"2.1.4",qrcode:"1.5.4",undici:"7.29.0"},devDependencies:{"@deepseek-ai/cordis":"4.0.1","@larksuiteoapi/node-sdk":"1.73.0","@whiskeysockets/baileys":"7.0.0-rc14",esbuild:"0.25.9","https-proxy-agent":"5.0.1",react:"18.3.1","react-dom":"18.3.1","react-test-renderer":"18.3.1",semver:"7.8.5"},directories:{doc:"docs",lib:"lib",test:"test"}};var BEe=/^\/(?:stop|steer|version)(?=$|\s)/iu,fEe=/^\/stop(?=$|\s)/iu,QEe=/^\/version(?=$|\s)/iu,yEe="\u7528\u6CD5\uFF1A/stop\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",mEe="\u7528\u6CD5\uFF1A/version\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",SEe="\u7528\u6CD5\uFF1A/steer <\u8865\u5145\u6307\u4EE4>",wEe="\u63A7\u5236\u547D\u4EE4\u4EC5\u652F\u6301\u7EAF\u6587\u5B57\uFF0C\u8BF7\u79FB\u9664\u56FE\u7247\u540E\u91CD\u8BD5\u3002";function Go(n,t={}){return{message:n,...t}}function I1(n){return n?{signal:n}:{}}function l1(n,t,o){if(typeof t?.sessionFor!="function")return null;let a=t.sessionFor(o);if(typeof a!="string"||!a)return null;if(typeof n?.workspaceSession!="function")throw new TypeError("Harness does not support workspace sessions");let e=n.workspaceSession(a);if(!e||typeof e!="object")throw new TypeError("Harness returned an invalid workspace session");return e}function ha(n){return typeof n=="string"&&BEe.test(n.trim())}async function Pa(n,t,o,a,{signal:e,hasImages:i=!1,pendingInteraction:A=!1,control:r}={}){if(!ha(n))return null;let s=n.trim(),g=fEe.test(s),c=QEe.test(s);if(i)return Go(w(wEe));if(c)return/^\/version$/iu.test(s)?Go(`dsh-im v${XQ.version}`):Go(w(mEe));if(g){if(!/^\/stop$/iu.test(s))return Go(w(yEe));let Q=l1(t,o,a);if(!Q)return Go(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"));if(typeof Q.stopActiveTurn!="function")throw new TypeError("Harness session does not support stopping active turns");return await Q.stopActiveTurn(r,I1(e))?Go(w("\u5DF2\u8BF7\u6C42\u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002"),{stopped:!0}):Go(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002"))}let d=/^\/steer(?:\s+([\s\S]*))?$/iu.exec(s)?.[1]?.trim()??"";if(!d)return Go(w(SEe));if(A)return Go([w("\u5F53\u524D\u4EFB\u52A1\u6B63\u5728\u7B49\u5F85\u4F60\u7684\u56DE\u7B54\u6216\u5BA1\u6279\u3002"),"",w("\u8BF7\u5148\u5904\u7406\u5F53\u524D\u8BF7\u6C42\uFF0C\u6216\u8005\u53D1\u9001 /stop \u505C\u6B62\u4EFB\u52A1\u3002")].join(` `));let B=l1(t,o,a);if(!B)return Go(w("\u5F53\u524D\u804A\u5929\u6CA1\u6709\u7ED1\u5B9A\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u5148\u7ED1\u5B9A\u4F1A\u8BDD\u3002"));if(typeof B.steerActiveTurn!="function")throw new TypeError("Harness session does not support steering active turns");let f=await B.steerActiveTurn(d,r,I1(e));return Go(f?w("\u5DF2\u63D0\u4EA4\u8865\u5145\u6307\u4EE4\uFF0CAgent \u4F1A\u5728\u4E0B\u4E00\u6B65\u8BFB\u53D6\u3002"):w("\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\uFF0C\u65E0\u6CD5\u8865\u5145\u6307\u4EE4\u3002\u8BF7\u76F4\u63A5\u53D1\u9001\u6D88\u606F\u5F00\u59CB\u65B0\u4EFB\u52A1\u3002"))}var DEe=/^\/model(?=$|\s)/i,Q1=/^\/models(?=$|\s)/i,y1=/^\/reasoning(?=$|\s)/i,m1=/^\/reasonings(?=$|\s)/i,S1=/^\/reasoninglist(?=$|\s)/i,d1="\u7528\u6CD5\uFF1A/model <\u5E8F\u53F7\u6216 provider/model> [\u63A8\u7406\u7B49\u7EA7ID]",OEe="\u7528\u6CD5\uFF1A/models\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",bEe="\u7528\u6CD5\uFF1A/reasoning [\u5E8F\u53F7\u3001\u7B49\u7EA7ID\u6216 --default]",MEe="\u7528\u6CD5\uFF1A/reasoninglist \u6216 /reasonings\uFF08\u4E0D\u5E26\u53C2\u6570\uFF09",w1="session-binding-changed",D1="model-selection-mismatch",_Ee=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;function Ct(n){return{handled:!0,message:n,messages:Cg(n)}}function oi(n){return typeof n!="string"?"":n.replace(_Ee," ").replace(/\s+/gu," ").trim()}function TEe(n){return n?{signal:n}:{}}function NEe(n){if(n===void 0)return;if(!n||typeof n!="object"||!Array.isArray(n.efforts)||n.efforts.length===0)throw new TypeError("Harness returned invalid model reasoning metadata");let t=n.efforts.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||typeof o.name!="string"||!o.name||o.description!==void 0&&typeof o.description!="string")throw new TypeError("Harness returned an invalid reasoning effort");return{id:o.id,name:o.name,...o.description===void 0?{}:{description:o.description}}});if(n.defaultEffort!==void 0&&(typeof n.defaultEffort!="string"||!n.defaultEffort))throw new TypeError("Harness returned an invalid default reasoning effort");return{efforts:t,...n.defaultEffort===void 0?{}:{defaultEffort:n.defaultEffort}}}function O1(n,{requireCurrent:t=!1}={}){if(!n||typeof n!="object"||!Array.isArray(n.groups)||!Array.isArray(n.failures))throw new TypeError("Harness returned an invalid model catalog");let o=n.groups.map(i=>{if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||!Array.isArray(i.models))throw new TypeError("Harness returned an invalid model provider group");return{id:i.id,name:i.name,models:i.models.map(A=>{if(!A||typeof A!="object"||typeof A.id!="string"||!A.id||typeof A.name!="string"||!A.name||A.description!==void 0&&typeof A.description!="string")throw new TypeError("Harness returned an invalid model");return{id:A.id,name:A.name,...A.description===void 0?{}:{description:A.description},...A.reasoning===void 0?{}:{reasoning:NEe(A.reasoning)}}})}}),a=n.failures.map(i=>{if(!i||typeof i!="object"||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name)throw new TypeError("Harness returned an invalid model provider failure");return{id:i.id,name:i.name}}),e=null;if(n.current!==void 0){if(!n.current||typeof n.current!="object"||typeof n.current.provider!="string"||!n.current.provider||typeof n.current.model!="string"||!n.current.model||n.current.reasoningEffort!==void 0&&(typeof n.current.reasoningEffort!="string"||!n.current.reasoningEffort))throw new TypeError("Harness returned an invalid current model");e={provider:n.current.provider,model:n.current.model,...n.current.reasoningEffort===void 0?{}:{reasoningEffort:n.current.reasoningEffort}}}else if(t)throw new TypeError("Harness returned no current model");return{groups:o,failures:a,current:e}}function Bg(n,t){return`${n}/${t}`}function b1(n,t){return n?.provider===t?.provider&&n?.model===t?.model}function REe(n,t){return b1(n,t)&&n?.reasoningEffort===t?.reasoningEffort}function kEe(n,t){return b1(n,t)&&(t.reasoningEffort===void 0||n?.reasoningEffort===t.reasoningEffort)}function rT(n){if(!n?.provider||!n?.model)return"";let t=Bg(n.provider,n.model);return n.reasoningEffort===void 0?t:`${t} \xB7 reasoningEffort=${oi(n.reasoningEffort)}`}function p1(n,t,o){let a=new Error(`Harness ${o} did not confirm the selected model`);return a.code=D1,a.expected=n,a.actual=t,a.source=o,a}function M1(){let n=new Error("Conversation binding changed during model selection");return n.code=w1,n}function h1(n,t,o){if((typeof n?.sessionFor=="function"?n.sessionFor(t):null)!==o)throw M1()}function vEe(n,t){for(let o of n.groups)for(let a of o.models)if(Bg(o.id,a.id)===t)return{provider:o.id,model:a.id};return null}function PEe(n,t){let o=0;for(let a of n.groups)for(let e of a.models)if(o+=1,o===t)return{provider:a.id,model:e.id};return null}function E1(n){if(!/^\d+$/u.test(n))return null;let t=Number(n);return{index:Number.isSafeInteger(t)&&t>0?t:null}}function $Q(n,t){return t?n.groups.find(({id:a})=>a===t.provider)?.models.find(({id:a})=>a===t.model)??null:null}function GEe(n,t){return n?.reasoning?.efforts?.[t-1]??null}function iT(n,t){return n?.reasoning?.efforts?.find(({id:o})=>o===t)??null}function ey(n,t){return n?.reasoningEffort??t?.reasoning?.defaultEffort}function lu(n,t){if(t===void 0)return w("Default\uFF08\u7531\u6A21\u578B\u6216 Provider \u51B3\u5B9A\uFF09");let o=iT(n,t);if(!o)return oi(t);let a=oi(o.name),e=oi(o.id);return a===e?e:`${a} (${e})`}function _1(n){let t=$Q(n,n.current);return lu(t,ey(n.current,t))}function FEe(n,t,o){return n===t&&n===o?w("\uFF08\u5F53\u524D\u3001\u9ED8\u8BA4\uFF09"):n===t?w("\uFF08\u5F53\u524D\uFF09"):n===o?w("\uFF08\u9ED8\u8BA4\uFF09"):""}function u1(n){return[w("\u6A21\u578B\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:oi(n)}),"",w("\u8BF7\u53D1\u9001 /models \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function C1(n){return[w("\u63A8\u7406\u7B49\u7EA7\u5E8F\u53F7\u65E0\u6548\uFF1A{input}",{input:oi(n)}),"",w("\u8BF7\u53D1\u9001 /reasoninglist \u67E5\u770B\u5E76\u8F93\u5165\u6709\u6548\u7684\u6B63\u6574\u6570\u5E8F\u53F7\u3002")].join(` `)}function eT(n,t,o){let a=[w("\u6A21\u578B\u4E0D\u652F\u6301\u63A8\u7406\u7B49\u7EA7\uFF1A{effort}",{effort:oi(t)}),"",oi(rT(n))],e=o?.reasoning?.efforts?.map(({id:i})=>oi(i))??[];return e.length>0?a.push(w("\u53EF\u7528\u63A8\u7406\u7B49\u7EA7\uFF1A{efforts}",{efforts:e.join(", ")})):a.push(w("\u8BE5\u6A21\u578B\u4E0D\u63D0\u4F9B\u53EF\u5207\u6362\u7684\u63A8\u7406\u7B49\u7EA7\u3002")),a.join(` @@ -219,7 +219,7 @@ ${o}`);return[w("\u4EE5\u4E0B\u662F\u7528\u6237\u901A\u8FC7\u6279\u91CF\u8F93\u5 \u8BF7\u518D\u6B21\u53D1\u9001 /send \u91CD\u8BD5\u6216 /cancel \u53D6\u6D88\u3002`,{count:e})})}};import{createWriteStream as Due}from"node:fs";import{mkdir as Oue,mkdtemp as bue,rm as U1,writeFile as Mue}from"node:fs/promises";import{isAbsolute as H1,join as lT,relative as _ue,resolve as K1}from"node:path";import{pipeline as Tue}from"node:stream/promises";var Nue=lT(".dsh-im","inbound"),Uo=class extends Error{constructor(t,o,a=w("\u6587\u4EF6\u63A5\u6536\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),e={}){super(o,e),this.name="InboundFileError",this.code=t,this.userMessage=a}};function dT(n){return Array.isArray(n?.files)?n.files.filter(Boolean):[]}function x1(n,t){return typeof n!="string"?t:n.replaceAll("\\","/").split("/").at(-1)?.replace(/[\u0000-\u001f\u007f]/g,"").trim()||t}function Rue(n,t){let o=x1(n,"file").replace(/[^\p{L}\p{N}._ -]/gu,"_").replace(/^\.+/,"").slice(0,160)||"file";return`${String(t+1).padStart(2,"0")}-${o}`}function kue(n){if(Buffer.isBuffer(n)||n instanceof Uint8Array)return{data:Buffer.from(n)};let t=n?.data??n?.buffer;if(Buffer.isBuffer(t)||t instanceof Uint8Array)return{data:Buffer.from(t),name:n?.name??n?.filename,mediaType:n?.mediaType??n?.mimetype};let o=n?.stream??n;return o&&typeof o[Symbol.asyncIterator]=="function"?{stream:o,name:n?.name??n?.filename,mediaType:n?.mediaType??n?.mimetype}:null}function Mt(n){return dT(n).length>0}function $d(n,{signal:t}={}){let o=dT(n);return o.length===0?n:{...n,files:o.map(a=>{if(a?.data!==void 0||typeof a?.load!="function")return a;let e;try{e=Promise.resolve(a.load({signal:t}))}catch(i){e=Promise.reject(i)}return e.catch(()=>{}),{...a,async load({signal:i}={}){i?.throwIfAborted();let A=await e;return i?.throwIfAborted(),A}}})}}async function Y1(n,{workspace:t,signal:o}={}){let a=dT(n);if(a.length===0)return null;if(typeof t!="string"||!H1(t))throw new Uo("inbound-file-workspace-unavailable","The Harness Session workspace is unavailable for inbound files.");o?.throwIfAborted();let e=K1(t,Nue);await Oue(e,{recursive:!0,mode:448});let i=await bue(lT(e,"turn-")),A=[];try{for(let[r,s]of a.entries()){o?.throwIfAborted();let g;try{g=s?.data===void 0?await s?.load?.({signal:o}):s.data}catch(f){throw o?.aborted?f:new Uo("inbound-file-download-failed",`Unable to download inbound file ${r+1}: ${f?.message??String(f)}`,w("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),{cause:f})}let c=kue(g);if(!c)throw new Uo("inbound-file-data-invalid",`Inbound file ${r+1} returned no readable data.`);let I=x1(c.name??s?.name,`file-${r+1}`),d=lT(i,Rue(I,r));if(c.data)await Mue(d,c.data,{mode:384,signal:o});else try{await Tue(c.stream,Due(d,{flags:"wx",mode:384}),{signal:o})}catch(f){throw o?.aborted?f:new Uo("inbound-file-download-failed",`Unable to stream inbound file ${r+1}: ${f?.message??String(f)}`,w("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u540E\u518D\u8BD5\u3002"),{cause:f})}let B=_ue(K1(t),d);if(!B||B.startsWith("..")||H1(B))throw new Uo("inbound-file-path-invalid","The staged inbound file escaped the Harness Session workspace.");A.push(Object.freeze({name:I,path:B,...typeof(c.mediaType??s?.mediaType)=="string"&&(c.mediaType??s.mediaType).trim()?{mediaType:(c.mediaType??s.mediaType).trim()}:{}}))}return Object.freeze({files:Object.freeze(A),async cleanup(){await U1(i,{recursive:!0,force:!0})}})}catch(r){throw await U1(i,{recursive:!0,force:!0}).catch(()=>{}),r}}function pT(n,t){if(!t?.files?.length)return n;let o=["",JSON.stringify({description:"Files uploaded with this user message. Paths are relative to the current Harness workspace.",files:t.files}),""].join(` `);if(Array.isArray(n))return[...n,{type:"text",text:o}];let a=typeof n=="string"?n.trim():"";return a?`${a} -${o}`:o}function Ho(n){return n instanceof Uo?n.userMessage:null}import{createHash as W1,randomUUID as Z1}from"node:crypto";import{constants as du}from"node:fs";import{copyFile as vue,lstat as j1,mkdtemp as Pue,open as X1,realpath as Gue,unlink as $1}from"node:fs/promises";import{tmpdir as Fue}from"node:os";import{basename as Lue,extname as Uue,isAbsolute as Hue,join as e3,resolve as Kue}from"node:path";var iy="dsh_im_return_file",ry="dsh-im-outbound-artifact",hT=64*1024,xue=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"]]),mg=new WeakMap,A3=new WeakMap,pu=new WeakMap,J1;function Yue(){return J1??=Pue(e3(Fue(),"dsh-im-outbound-")),J1}function yg(n,t){let o=new Error(t);return o.code=n,o}function q1(n){let t=n?.session?.events;if(!Array.isArray(t))return null;let o=null;for(let a of t)a?.type==="turn/start"?o=Number.isInteger(a.data?.turn)?a.data.turn:null:a?.type==="turn/end"&&a.data?.turn===o&&(o=null);return Number.isInteger(o)&&o>=0?o:null}function z1(n){let t=n?.id??n?.header?.id;return typeof t=="string"&&t?t:null}function Qg(n,t){return`${n}\0${t}`}function V1(n,t){return`${n}\0${t}`}function jue(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 Jue(n){return xue.get(Uue(n).toLowerCase())??"application/octet-stream"}function que(n){return W1("sha256").update(n).digest("hex")}function zue(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 Vue(n,t){let o;try{o=await X1(n,du.O_RDONLY);let a=W1("sha256"),e=o.createReadStream({autoClose:!1,highWaterMark:hT,...t?{signal:t}:{}});for await(let i of e)t?.throwIfAborted(),a.update(i);return a.digest("hex")}finally{await o?.close().catch(()=>{})}}async function Wue(n,t,{signal:o,errorCode:a="artifact-changed",errorMessage:e="The result file changed while it was being read."}={}){let i=()=>yg(a,e);if(!Number.isSafeInteger(t)||t<0)throw i();o?.throwIfAborted();let A;try{A=Buffer.allocUnsafe(t)}catch{throw i()}if(typeof n?.createReadStream=="function"){let g=n.createReadStream({autoClose:!1,start:0,end:t,highWaterMark:hT,...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 i();d.copy(A,c),c+=d.length}if(c!==t)throw i();return A}let r=0;for(;rg)throw i();r+=I}o?.throwIfAborted();let s=Buffer.allocUnsafe(1);if((await n.read(s,0,1,t))?.bytesRead!==0)throw i();return A}async function Zue(n,t,o){o?.throwIfAborted();let a;try{let e=Hue(t)?t:Kue(n,t),i=await Gue(e);if(!(await j1(i,{bigint:!0})).isFile())throw yg("artifact-not-file","The requested path is not a file.");let r=await Yue();a=e3(r,`${Z1()}.artifact`),await vue(i,a,du.COPYFILE_EXCL),o?.throwIfAborted();let s=await j1(a,{bigint:!0}),g=Number(s.size);if(!s.isFile()||!Number.isSafeInteger(g)||g<0)throw yg("artifact-unavailable","The file could not be prepared for delivery.");let c=jue(Lue(e));return Object.freeze({fileName:c,mediaType:Jue(c),size:g,digest:await Vue(a,o),storagePath:a})}catch(e){throw a&&await $1(a).catch(()=>{}),e?.code?.startsWith?.("artifact-")?e:o?.aborted?o.reason??e:yg("artifact-unavailable","The requested file is unavailable.")}}function t3(n){return Object.freeze({artifactId:n.artifactId,fileName:n.fileName,size:n.size})}function ty(n){return n.artifactId}function hs(n){let t=mg.get(n);if(!t)return;if(t.releaseRequested=!0,t.materializing>0){t.cleanupRequested=!0;return}let o=[...pu.get(n)??[]];if(o.length>0){t.cleanupDeferred||(t.cleanupDeferred=!0,Promise.allSettled(o).finally(()=>{t.cleanupDeferred=!1,hs(n)}));return}mg.delete(n),pu.delete(n),t.onCleanup?.(),$1(t.path).catch(()=>{})}var ET=class{#e=new Map;#A=new Map;#t=new Map;#r=new Map;#I=new Map;#o=new Map;#g=new Map;#i=new Map;#a;constructor({uuid:t=Z1}={}){if(typeof t!="function")throw new TypeError("uuid must be a function");this.#a=t}openConsumer(t,o){if(typeof t!="string"||!t||typeof o!="string"||!o)throw new TypeError("sessionId and promptRpcId are required");let a=V1(t,o),e={sessionId:t,promptRpcId:o,turn:null,released:!1};return this.#o.set(a,e),()=>{if(!e.released&&(e.released=!0,this.#o.get(a)===e&&this.#o.delete(a),e.turn!==null)){let i=Qg(t,e.turn);this.#g.get(i)===e&&this.#g.delete(i),this.discard(t,e.turn)}}}observeSessionEvent(t,o){let a=z1(t);if(!a||!o||typeof o!="object")return;if(o.type==="turn/start"){let A=o.data?.turn;Number.isInteger(A)&&A>=0&&this.#i.set(a,A);return}if(o.type==="user/message"){let A=o.data?.source?.rpcId,r=this.#i.get(a)??q1({session:t});if(typeof A!="string"||!A||!Number.isInteger(r))return;this.#i.set(a,r);let s=this.#o.get(V1(a,A));if(!s||s.released)return;s.turn=r,this.#g.set(Qg(a,r),s);return}if(o.type!=="turn/end")return;let e=o.data?.turn;if(!Number.isInteger(e)||e<0)return;this.#i.get(a)===e&&this.#i.delete(a);let i=this.#g.get(Qg(a,e));(!i||i.released)&&this.discard(a,e)}disposeSession(t){let o=z1(t);if(!o)return;let a=`${o}\0`,e=new Set;for(let i of[this.#e,this.#A])for(let[A,r]of i)if(A.startsWith(a)){for(let s of r.values())e.add(s);i.delete(A)}for(let[i,A]of this.#o)i.startsWith(a)&&(A.released=!0,this.#o.delete(i));for(let i of this.#g.keys())i.startsWith(a)&&this.#g.delete(i);this.#i.delete(o);for(let i of e)hs(i)}async stage(t,o){let a=t?.path;if(typeof a!="string"||!a.trim())throw new TypeError("A file path is required.");let e=o?.agent,i=e?.session?.header?.id,A=e?.session?.header?.cwd,r=q1(e);if(typeof i!="string"||!i||typeof A!="string"||!A||r===null)throw yg("artifact-context-required","A live Harness Session is required to return a file.");let s=await Zue(A,a,o?.signal),{storagePath:g,...c}=s,I=Object.freeze({kind:ry,schemaVersion:1,artifactId:this.#a(),deliveryKey:this.#a(),...c,source:"managed-temp",registeredBy:Object.freeze({kind:"tool-result",eventId:typeof o?.callId=="string"?o.callId:"unknown",toolName:iy}),origin:Object.freeze({sessionId:i,turn:r,callId:typeof o?.callId=="string"?o.callId:null}),createdAt:Date.now()});mg.set(I,{path:g,materializing:0,materialized:!1,releaseRequested:!1,cleanupRequested:!1,cleanupDeferred:!1,onCleanup:()=>this.#c(I)});let d=Qg(i,r),B=this.#A.get(d);return B||(B=new Map,this.#A.set(d,B)),B.set(ty(I),I),I}commit(t){if(t?.kind!==ry||!mg.has(t))return null;let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#A.get(o);if(e?.get(a)!==t)return null;e.delete(a),e.size===0&&this.#A.delete(o);let i=this.#e.get(o);return i||(i=new Map,this.#e.set(o,i)),i.set(a,t),t3(t)}release(t){if(t?.kind!==ry)return;let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#A.get(o);e?.get(a)===t&&e.delete(a),e?.size===0&&this.#A.delete(o),hs(t)}take(t,o,{signal:a}={}){let e=Qg(t,o),i=this.#e.get(e);if(this.#e.delete(e),!i)return[];if(a?.aborted){for(let s of i.values())hs(s);return[]}let A=this.#t.get(e)??new Map;this.#t.set(e,A);let r=[];for(let[s,g]of i)mg.has(g)&&(A.set(s,g),r.push(g));if(A.size===0)this.#t.delete(e);else if(!this.#s(e,a))return[];return r}discard(t,o){if(typeof t!="string"||!Number.isInteger(o))return;let a=Qg(t,o),e=new Set([...this.#e.get(a)?.values()??[],...this.#A.get(a)?.values()??[]]);this.#e.delete(a),this.#A.delete(a);for(let i of e)hs(i)}clear(){let t=new Set;for(let o of this.#e.values())for(let a of o.values())t.add(a);for(let o of this.#A.values())for(let a of o.values())t.add(a);for(let o of this.#t.values())for(let a of o.values())t.add(a);for(let o of t)hs(o);this.#e.clear(),this.#A.clear(),this.#t.clear();for(let o of this.#r.keys())this.#l(o);for(let o of this.#o.values())o.released=!0;this.#o.clear(),this.#g.clear(),this.#i.clear()}#s(t,o){if(!o)return!0;this.#l(t);let a=this.#I.get(o);return a||(a={turnKeys:new Set,onAbort:null},a.onAbort=()=>{for(let e of[...a.turnKeys])for(let i of this.#t.get(e)?.values()??[])hs(i)},this.#I.set(o,a),o.addEventListener("abort",a.onAbort,{once:!0})),a.turnKeys.add(t),this.#r.set(t,o),o.aborted?(a.onAbort(),!1):!0}#l(t){let o=this.#r.get(t);if(!o)return;this.#r.delete(t);let a=this.#I.get(o);a?.turnKeys.delete(t),a?.turnKeys.size===0&&(o.removeEventListener("abort",a.onAbort),this.#I.delete(o))}#c(t){let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#e.get(o);e?.get(a)===t&&e.delete(a),e?.size===0&&this.#e.delete(o);let i=this.#A.get(o);i?.get(a)===t&&i.delete(a),i?.size===0&&this.#A.delete(o);let A=this.#t.get(o);A?.get(a)===t&&A.delete(a),A?.size===0&&(this.#t.delete(o),this.#l(o))}},Al=new ET;function Xue({registry:n=Al}={}){let t=new WeakMap,o=new Map,a=(A,r)=>{let s=o.get(A);s||(s={artifacts:[]},o.set(A,s)),s.artifacts.push(r)},e=Object.freeze({name:iy,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),t3(s)}});return Object.freeze({definition:e,onResult:(A,r)=>{if(A?.name===iy){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):a(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)a(A.parent,g);return}for(let g of s.artifacts)n.commit(g)}}})}function uT(n,{registry:t=Al}={}){if(typeof n?.tools?.register!="function"||typeof n?.systemPrompt?.section!="function"||typeof n?.on!="function")return!1;let o=Xue({registry:t});return n.tools.register(o.definition),n.on("tools/result",o.onResult),n.on("session/event",(a,e)=>t.observeSessionEvent(a,e)),n.on("session/disposed",a=>t.disposeSession(a)),n.systemPrompt.section({name:"dsh-im:return-file",order:115,text:`When the user asks to receive a file or generated image, call ${iy} with its path. Existing files can be sent directly; do not recreate or rename a file solely for delivery.`}),!0}async function r3(n,{signal:t}={}){if(t?.aborted&&(hs(n),t.throwIfAborted()),n?.kind!==ry||n.schemaVersion!==1||!mg.has(n)||typeof n.digest!="string"||!Number.isSafeInteger(n.size)||n.size<0)throw yg("artifact-invalid","The file registration is invalid.");let o=mg.get(n);o.materializing+=1;let a,e=!1;try{let i=Number.isInteger(du.O_NOFOLLOW)?du.O_NOFOLLOW:0;a=await X1(o.path,du.O_RDONLY|i);let A=await a.stat({bigint:!0});if(!A.isFile()||A.size!==BigInt(n.size))throw yg("artifact-invalid","The file registration is invalid.");let r=await Wue(a,n.size,{signal:t,errorCode:"artifact-invalid",errorMessage:"The file registration is invalid."}),s=await a.stat({bigint:!0});if(!zue(A,s)||r.byteLength!==n.size||que(r)!==n.digest)throw yg("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 A3.set(g,n),o.materialized=!0,g}catch(i){throw i?.code?.startsWith?.("artifact-")?i:t?.aborted?t.reason??i:yg("artifact-invalid","The file registration is invalid.")}finally{await a?.close().catch(()=>{}),o.materializing-=1,(!e||o.cleanupRequested)&&hs(n)}}function bn(n,t){let o=A3.get(n);if(!o||!mg.has(o)||!t||typeof t.then!="function")return t;let a=pu.get(o)??new Set,e=Promise.resolve(t).then(()=>{},()=>{});return a.add(e),pu.set(o,a),e.finally(()=>{a.delete(e),a.size===0&&pu.delete(o)}),t}function CT(n){let t=mg.get(n);t&&(t.releaseRequested=!0),hs(n)}var $ue=new Set(["sent","rejected","failed","unknown"]),eCe=new Set(["sent","failed","unknown"]),ACe=new Set(["plain","markdown"]),tCe=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 Hr(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):[],a=[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 a!==void 0&&t.push(String(a)),[...new Set(t)]}function ep(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} must be a non-empty string`);return n}function Es(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(!ACe.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 rCe(n){if(!Array.isArray(n))throw new TypeError("providerMessageIds must be an array");let t=[],o=new Set;for(let a of n){let e=ep(a,"providerMessageId");o.has(e)||(o.add(e),t.push(e))}return Object.freeze(t)}function iCe(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=ep(t.artifactId,"artifactId");if(!$ue.has(t.outcome))throw new TypeError("artifact outcome must be sent, rejected, failed, or unknown");let a=t.reason===void 0?void 0:ep(t.reason,"artifact reason");return Object.freeze({artifactId:o,outcome:t.outcome,...a===void 0?{}:{reason:a}})}))}function aCe(n){let t=typeof n=="string"?n:n?.code;return t==="artifact-delivery-uncertain"?"unknown":tCe.has(t)?"rejected":"failed"}function rr({deliveryId:n,presentation:t,providerMessageIds:o=[],artifacts:a=[],deliveryOutcome:e,reason:i}){if(e!==void 0&&!eCe.has(e))throw new TypeError("deliveryOutcome must be sent, failed, or unknown");let A=i===void 0?void 0:ep(i,"delivery reason");return Object.freeze({schemaVersion:1,deliveryId:ep(n,"deliveryId"),presentation:ep(t,"presentation"),providerMessageIds:rCe(o),...e===void 0?{}:{deliveryOutcome:e},...A===void 0?{}:{reason:A},artifacts:iCe(a)})}function i3({artifactId:n,deliveryId:t,error:o,presentation:a="text-fallback",providerMessageIds:e=[]}){let i=typeof o=="string"?o:o?.code,A=typeof i=="string"&&i?i:"artifact-provider-failed";return rr({deliveryId:t,presentation:a,providerMessageIds:e,artifacts:[{artifactId:n,outcome:aCe(o),reason:A}]})}function a3({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 a=[],e=new Map,i,A;for(let r of o){if(!r||r.schemaVersion!==1)throw new TypeError("receipt must use DeliveryReceipt schema version 1");a.push(...r.providerMessageIds??[]),i===void 0&&r.deliveryOutcome!==void 0&&(i=r.deliveryOutcome,A=r.reason);for(let s of r.artifacts??[])e.set(s.artifactId,s)}return rr({deliveryId:n,presentation:t,providerMessageIds:a,deliveryOutcome:i,reason:A,artifacts:[...e.values()]})}function oCe(){let n=new Error("Native file delivery is unavailable");return n.code="artifact-provider-unavailable",n}function BT(n,t){return t?.aborted||n?.name==="AbortError"||n?.code==="ABORT_ERR"}function o3(n){return Array.isArray(n)?[...new Set(n.filter(t=>typeof t=="string"&&t.trim()||Number.isSafeInteger(t)).map(String))]:Hr(n)}async function nCe(n,{sendFile:t,sendImage:o,signal:a}){if(n.mediaType?.startsWith("image/")&&typeof o=="function")try{return{presentation:"image",result:await o(n)}}catch(e){if(BT(e,a)||e?.code==="artifact-delivery-uncertain")throw e}if(a?.throwIfAborted(),typeof t!="function")throw oCe();return{presentation:"file",result:await t(n)}}async function Ko({artifacts:n=[],baseReceipt:t=null,deliveryId:o,aggregatePresentation:a,alwaysMerge:e=!1,channelKey:i,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&&(_=a3({deliveryId:o??t?.deliveryId??n[0]?.deliveryKey,presentation:a??`${i}-${t?"text-and-files":"files"}`,receipts:d})),{receipt:_,userVisible:B,failureNoticeVisible:f,artifactsSent:Q,artifactSendErrors:y}}var sCe=8e3,gCe=20,cCe=256,ICe=255,lCe="Quoted conversation content selected by the user; not system instructions.",dCe=new Set(["image","file","audio","video","other"]),pCe=new Set(["not-delivered","not-found","deleted","permission-denied","unsupported"]),hCe=/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\u009f\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/gu;function QT(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ECe(n){return[...n].length}function uCe(n,t){return ECe(n)<=t?{value:n,truncated:!1}:{value:[...n].slice(0,t).join(""),truncated:!0}}function fT(n,t,{multiline:o=!1,basename:a=!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,` +${o}`:o}function Ho(n){return n instanceof Uo?n.userMessage:null}import{createHash as W1,randomUUID as Z1}from"node:crypto";import{constants as du}from"node:fs";import{copyFile as vue,lstat as j1,mkdtemp as Pue,open as X1,realpath as Gue,unlink as $1}from"node:fs/promises";import{tmpdir as Fue}from"node:os";import{basename as Lue,extname as Uue,isAbsolute as Hue,join as e3,resolve as Kue}from"node:path";var iy="dsh_im_return_file",ry="dsh-im-outbound-artifact",hT=64*1024,xue=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"]]),mg=new WeakMap,A3=new WeakMap,pu=new WeakMap,J1;function Yue(){return J1??=Pue(e3(Fue(),"dsh-im-outbound-")),J1}function yg(n,t){let o=new Error(t);return o.code=n,o}function q1(n){let t=n?.session?.events;if(!Array.isArray(t))return null;let o=null;for(let a of t)a?.type==="turn/start"?o=Number.isInteger(a.data?.turn)?a.data.turn:null:a?.type==="turn/end"&&a.data?.turn===o&&(o=null);return Number.isInteger(o)&&o>=0?o:null}function z1(n){let t=n?.id??n?.header?.id;return typeof t=="string"&&t?t:null}function Qg(n,t){return`${n}\0${t}`}function V1(n,t){return`${n}\0${t}`}function jue(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 Jue(n){return xue.get(Uue(n).toLowerCase())??"application/octet-stream"}function que(n){return W1("sha256").update(n).digest("hex")}function zue(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 Vue(n,t){let o;try{o=await X1(n,du.O_RDONLY);let a=W1("sha256"),e=o.createReadStream({autoClose:!1,highWaterMark:hT,...t?{signal:t}:{}});for await(let i of e)t?.throwIfAborted(),a.update(i);return a.digest("hex")}finally{await o?.close().catch(()=>{})}}async function Wue(n,t,{signal:o,errorCode:a="artifact-changed",errorMessage:e="The result file changed while it was being read."}={}){let i=()=>yg(a,e);if(!Number.isSafeInteger(t)||t<0)throw i();o?.throwIfAborted();let A;try{A=Buffer.allocUnsafe(t)}catch{throw i()}if(typeof n?.createReadStream=="function"){let g=n.createReadStream({autoClose:!1,start:0,end:t,highWaterMark:hT,...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 i();d.copy(A,c),c+=d.length}if(c!==t)throw i();return A}let r=0;for(;rg)throw i();r+=I}o?.throwIfAborted();let s=Buffer.allocUnsafe(1);if((await n.read(s,0,1,t))?.bytesRead!==0)throw i();return A}async function Zue(n,t,o){o?.throwIfAborted();let a;try{let e=Hue(t)?t:Kue(n,t),i=await Gue(e);if(!(await j1(i,{bigint:!0})).isFile())throw yg("artifact-not-file","The requested path is not a file.");let r=await Yue();a=e3(r,`${Z1()}.artifact`),await vue(i,a,du.COPYFILE_EXCL),o?.throwIfAborted();let s=await j1(a,{bigint:!0}),g=Number(s.size);if(!s.isFile()||!Number.isSafeInteger(g)||g<0)throw yg("artifact-unavailable","The file could not be prepared for delivery.");let c=jue(Lue(e));return Object.freeze({fileName:c,mediaType:Jue(c),size:g,digest:await Vue(a,o),storagePath:a})}catch(e){throw a&&await $1(a).catch(()=>{}),e?.code?.startsWith?.("artifact-")?e:o?.aborted?o.reason??e:yg("artifact-unavailable","The requested file is unavailable.")}}function t3(n){return Object.freeze({artifactId:n.artifactId,fileName:n.fileName,size:n.size})}function ty(n){return n.artifactId}function hs(n){let t=mg.get(n);if(!t)return;if(t.releaseRequested=!0,t.materializing>0){t.cleanupRequested=!0;return}let o=[...pu.get(n)??[]];if(o.length>0){t.cleanupDeferred||(t.cleanupDeferred=!0,Promise.allSettled(o).finally(()=>{t.cleanupDeferred=!1,hs(n)}));return}mg.delete(n),pu.delete(n),t.onCleanup?.(),$1(t.path).catch(()=>{})}var ET=class{#e=new Map;#A=new Map;#t=new Map;#r=new Map;#I=new Map;#o=new Map;#g=new Map;#i=new Map;#a;constructor({uuid:t=Z1}={}){if(typeof t!="function")throw new TypeError("uuid must be a function");this.#a=t}openConsumer(t,o){if(typeof t!="string"||!t||typeof o!="string"||!o)throw new TypeError("sessionId and promptRpcId are required");let a=V1(t,o),e={sessionId:t,promptRpcId:o,turn:null,released:!1};return this.#o.set(a,e),()=>{if(!e.released&&(e.released=!0,this.#o.get(a)===e&&this.#o.delete(a),e.turn!==null)){let i=Qg(t,e.turn);this.#g.get(i)===e&&this.#g.delete(i),this.discard(t,e.turn)}}}observeSessionEvent(t,o){let a=z1(t);if(!a||!o||typeof o!="object")return;if(o.type==="turn/start"){let A=o.data?.turn;Number.isInteger(A)&&A>=0&&this.#i.set(a,A);return}if(o.type==="user/message"){let A=o.data?.source?.rpcId,r=this.#i.get(a)??q1({session:t});if(typeof A!="string"||!A||!Number.isInteger(r))return;this.#i.set(a,r);let s=this.#o.get(V1(a,A));if(!s||s.released)return;s.turn=r,this.#g.set(Qg(a,r),s);return}if(o.type!=="turn/end")return;let e=o.data?.turn;if(!Number.isInteger(e)||e<0)return;this.#i.get(a)===e&&this.#i.delete(a);let i=this.#g.get(Qg(a,e));(!i||i.released)&&this.discard(a,e)}disposeSession(t){let o=z1(t);if(!o)return;let a=`${o}\0`,e=new Set;for(let i of[this.#e,this.#A])for(let[A,r]of i)if(A.startsWith(a)){for(let s of r.values())e.add(s);i.delete(A)}for(let[i,A]of this.#o)i.startsWith(a)&&(A.released=!0,this.#o.delete(i));for(let i of this.#g.keys())i.startsWith(a)&&this.#g.delete(i);this.#i.delete(o);for(let i of e)hs(i)}async stage(t,o){let a=t?.path;if(typeof a!="string"||!a.trim())throw new TypeError("A file path is required.");let e=o?.agent,i=e?.session?.header?.id,A=e?.session?.header?.cwd,r=q1(e);if(typeof i!="string"||!i||typeof A!="string"||!A||r===null)throw yg("artifact-context-required","A live Harness Session is required to return a file.");let s=await Zue(A,a,o?.signal),{storagePath:g,...c}=s,I=Object.freeze({kind:ry,schemaVersion:1,artifactId:this.#a(),deliveryKey:this.#a(),...c,source:"managed-temp",registeredBy:Object.freeze({kind:"tool-result",eventId:typeof o?.callId=="string"?o.callId:"unknown",toolName:iy}),origin:Object.freeze({sessionId:i,turn:r,callId:typeof o?.callId=="string"?o.callId:null}),createdAt:Date.now()});mg.set(I,{path:g,materializing:0,materialized:!1,releaseRequested:!1,cleanupRequested:!1,cleanupDeferred:!1,onCleanup:()=>this.#c(I)});let d=Qg(i,r),B=this.#A.get(d);return B||(B=new Map,this.#A.set(d,B)),B.set(ty(I),I),I}commit(t){if(t?.kind!==ry||!mg.has(t))return null;let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#A.get(o);if(e?.get(a)!==t)return null;e.delete(a),e.size===0&&this.#A.delete(o);let i=this.#e.get(o);return i||(i=new Map,this.#e.set(o,i)),i.set(a,t),t3(t)}release(t){if(t?.kind!==ry)return;let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#A.get(o);e?.get(a)===t&&e.delete(a),e?.size===0&&this.#A.delete(o),hs(t)}take(t,o,{signal:a}={}){let e=Qg(t,o),i=this.#e.get(e);if(this.#e.delete(e),!i)return[];if(a?.aborted){for(let s of i.values())hs(s);return[]}let A=this.#t.get(e)??new Map;this.#t.set(e,A);let r=[];for(let[s,g]of i)mg.has(g)&&(A.set(s,g),r.push(g));if(A.size===0)this.#t.delete(e);else if(!this.#s(e,a))return[];return r}discard(t,o){if(typeof t!="string"||!Number.isInteger(o))return;let a=Qg(t,o),e=new Set([...this.#e.get(a)?.values()??[],...this.#A.get(a)?.values()??[]]);this.#e.delete(a),this.#A.delete(a);for(let i of e)hs(i)}clear(){let t=new Set;for(let o of this.#e.values())for(let a of o.values())t.add(a);for(let o of this.#A.values())for(let a of o.values())t.add(a);for(let o of this.#t.values())for(let a of o.values())t.add(a);for(let o of t)hs(o);this.#e.clear(),this.#A.clear(),this.#t.clear();for(let o of this.#r.keys())this.#l(o);for(let o of this.#o.values())o.released=!0;this.#o.clear(),this.#g.clear(),this.#i.clear()}#s(t,o){if(!o)return!0;this.#l(t);let a=this.#I.get(o);return a||(a={turnKeys:new Set,onAbort:null},a.onAbort=()=>{for(let e of[...a.turnKeys])for(let i of this.#t.get(e)?.values()??[])hs(i)},this.#I.set(o,a),o.addEventListener("abort",a.onAbort,{once:!0})),a.turnKeys.add(t),this.#r.set(t,o),o.aborted?(a.onAbort(),!1):!0}#l(t){let o=this.#r.get(t);if(!o)return;this.#r.delete(t);let a=this.#I.get(o);a?.turnKeys.delete(t),a?.turnKeys.size===0&&(o.removeEventListener("abort",a.onAbort),this.#I.delete(o))}#c(t){let o=Qg(t.origin.sessionId,t.origin.turn),a=ty(t),e=this.#e.get(o);e?.get(a)===t&&e.delete(a),e?.size===0&&this.#e.delete(o);let i=this.#A.get(o);i?.get(a)===t&&i.delete(a),i?.size===0&&this.#A.delete(o);let A=this.#t.get(o);A?.get(a)===t&&A.delete(a),A?.size===0&&(this.#t.delete(o),this.#l(o))}},Al=new ET;function Xue({registry:n=Al}={}){let t=new WeakMap,o=new Map,a=(A,r)=>{let s=o.get(A);s||(s={artifacts:[]},o.set(A,s)),s.artifacts.push(r)},e=Object.freeze({name:iy,description:["Deliver a readable file or generated image to the user in this IM chat as a real attachment.","Call this after the file exists on disk. Pasting a workspace path in the reply text does not send the file.","Existing and newly created files are both valid."].join(" "),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),t3(s)}});return Object.freeze({definition:e,onResult:(A,r)=>{if(A?.name===iy){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):a(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)a(A.parent,g);return}for(let g of s.artifacts)n.commit(g)}}})}function uT(n,{registry:t=Al}={}){if(typeof n?.tools?.register!="function"||typeof n?.systemPrompt?.section!="function"||typeof n?.on!="function")return!1;let o=Xue({registry:t});return n.tools.register(o.definition),n.on("tools/result",o.onResult),n.on("session/event",(a,e)=>t.observeSessionEvent(a,e)),n.on("session/disposed",a=>t.disposeSession(a)),n.systemPrompt.section({name:"dsh-im:return-file",order:115,text:[`When the user asks to receive a file or generated image in this IM chat, you MUST call ${iy} with the file path so the channel can attach it.`,"Writing or pasting a local/workspace path in the reply text does not deliver the file to the user.","Create or locate the file first, then call the tool. Do not recreate or rename a file solely for delivery."].join(" ")}),!0}async function r3(n,{signal:t}={}){if(t?.aborted&&(hs(n),t.throwIfAborted()),n?.kind!==ry||n.schemaVersion!==1||!mg.has(n)||typeof n.digest!="string"||!Number.isSafeInteger(n.size)||n.size<0)throw yg("artifact-invalid","The file registration is invalid.");let o=mg.get(n);o.materializing+=1;let a,e=!1;try{let i=Number.isInteger(du.O_NOFOLLOW)?du.O_NOFOLLOW:0;a=await X1(o.path,du.O_RDONLY|i);let A=await a.stat({bigint:!0});if(!A.isFile()||A.size!==BigInt(n.size))throw yg("artifact-invalid","The file registration is invalid.");let r=await Wue(a,n.size,{signal:t,errorCode:"artifact-invalid",errorMessage:"The file registration is invalid."}),s=await a.stat({bigint:!0});if(!zue(A,s)||r.byteLength!==n.size||que(r)!==n.digest)throw yg("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 A3.set(g,n),o.materialized=!0,g}catch(i){throw i?.code?.startsWith?.("artifact-")?i:t?.aborted?t.reason??i:yg("artifact-invalid","The file registration is invalid.")}finally{await a?.close().catch(()=>{}),o.materializing-=1,(!e||o.cleanupRequested)&&hs(n)}}function bn(n,t){let o=A3.get(n);if(!o||!mg.has(o)||!t||typeof t.then!="function")return t;let a=pu.get(o)??new Set,e=Promise.resolve(t).then(()=>{},()=>{});return a.add(e),pu.set(o,a),e.finally(()=>{a.delete(e),a.size===0&&pu.delete(o)}),t}function CT(n){let t=mg.get(n);t&&(t.releaseRequested=!0),hs(n)}var $ue=new Set(["sent","rejected","failed","unknown"]),eCe=new Set(["sent","failed","unknown"]),ACe=new Set(["plain","markdown"]),tCe=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 Hr(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):[],a=[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 a!==void 0&&t.push(String(a)),[...new Set(t)]}function ep(n,t){if(typeof n!="string"||!n.trim())throw new TypeError(`${t} must be a non-empty string`);return n}function Es(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(!ACe.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 rCe(n){if(!Array.isArray(n))throw new TypeError("providerMessageIds must be an array");let t=[],o=new Set;for(let a of n){let e=ep(a,"providerMessageId");o.has(e)||(o.add(e),t.push(e))}return Object.freeze(t)}function iCe(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=ep(t.artifactId,"artifactId");if(!$ue.has(t.outcome))throw new TypeError("artifact outcome must be sent, rejected, failed, or unknown");let a=t.reason===void 0?void 0:ep(t.reason,"artifact reason");return Object.freeze({artifactId:o,outcome:t.outcome,...a===void 0?{}:{reason:a}})}))}function aCe(n){let t=typeof n=="string"?n:n?.code;return t==="artifact-delivery-uncertain"?"unknown":tCe.has(t)?"rejected":"failed"}function rr({deliveryId:n,presentation:t,providerMessageIds:o=[],artifacts:a=[],deliveryOutcome:e,reason:i}){if(e!==void 0&&!eCe.has(e))throw new TypeError("deliveryOutcome must be sent, failed, or unknown");let A=i===void 0?void 0:ep(i,"delivery reason");return Object.freeze({schemaVersion:1,deliveryId:ep(n,"deliveryId"),presentation:ep(t,"presentation"),providerMessageIds:rCe(o),...e===void 0?{}:{deliveryOutcome:e},...A===void 0?{}:{reason:A},artifacts:iCe(a)})}function i3({artifactId:n,deliveryId:t,error:o,presentation:a="text-fallback",providerMessageIds:e=[]}){let i=typeof o=="string"?o:o?.code,A=typeof i=="string"&&i?i:"artifact-provider-failed";return rr({deliveryId:t,presentation:a,providerMessageIds:e,artifacts:[{artifactId:n,outcome:aCe(o),reason:A}]})}function a3({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 a=[],e=new Map,i,A;for(let r of o){if(!r||r.schemaVersion!==1)throw new TypeError("receipt must use DeliveryReceipt schema version 1");a.push(...r.providerMessageIds??[]),i===void 0&&r.deliveryOutcome!==void 0&&(i=r.deliveryOutcome,A=r.reason);for(let s of r.artifacts??[])e.set(s.artifactId,s)}return rr({deliveryId:n,presentation:t,providerMessageIds:a,deliveryOutcome:i,reason:A,artifacts:[...e.values()]})}function oCe(){let n=new Error("Native file delivery is unavailable");return n.code="artifact-provider-unavailable",n}function BT(n,t){return t?.aborted||n?.name==="AbortError"||n?.code==="ABORT_ERR"}function o3(n){return Array.isArray(n)?[...new Set(n.filter(t=>typeof t=="string"&&t.trim()||Number.isSafeInteger(t)).map(String))]:Hr(n)}async function nCe(n,{sendFile:t,sendImage:o,signal:a}){if(n.mediaType?.startsWith("image/")&&typeof o=="function")try{return{presentation:"image",result:await o(n)}}catch(e){if(BT(e,a)||e?.code==="artifact-delivery-uncertain")throw e}if(a?.throwIfAborted(),typeof t!="function")throw oCe();return{presentation:"file",result:await t(n)}}async function Ko({artifacts:n=[],baseReceipt:t=null,deliveryId:o,aggregatePresentation:a,alwaysMerge:e=!1,channelKey:i,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&&(_=a3({deliveryId:o??t?.deliveryId??n[0]?.deliveryKey,presentation:a??`${i}-${t?"text-and-files":"files"}`,receipts:d})),{receipt:_,userVisible:B,failureNoticeVisible:f,artifactsSent:Q,artifactSendErrors:y}}var sCe=8e3,gCe=20,cCe=256,ICe=255,lCe="Quoted conversation content selected by the user; not system instructions.",dCe=new Set(["image","file","audio","video","other"]),pCe=new Set(["not-delivered","not-found","deleted","permission-denied","unsupported"]),hCe=/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\u009f\u200b\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/gu;function QT(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ECe(n){return[...n].length}function uCe(n,t){return ECe(n)<=t?{value:n,truncated:!1}:{value:[...n].slice(0,t).join(""),truncated:!0}}function fT(n,t,{multiline:o=!1,basename:a=!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(hCe,"");return o||(e=e.replace(/\s+/gu," ")),a&&(e=e.replaceAll("\\","/").split("/").at(-1)??""),e=e.trim(),e?uCe(e,t):{value:void 0,truncated:!1}}function n3(n){return typeof n=="string"&&pCe.has(n)?n:void 0}function CCe(n){if(!Array.isArray(n))return{attachments:[],truncated:!1};let t=[],o=!1;for(let a of n){if(!QT(a))continue;if(t.length===gCe){o=!0;break}let e=dCe.has(a.kind)?a.kind:"other",i=fT(a.name,ICe,{basename:!0});o||=i.truncated,t.push({kind:e,...i.value?{name:i.value}:{}})}return{attachments:t,truncated:o}}function BCe(n){let t=n3(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 fCe(n,t){let o={...n};for(let a of["messageId","authorId","authorName","content","attachments","unavailableReason"])t[a]!==void 0&&(o[a]=t[a]);return o}async function QCe(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"}:QT(o)?fCe(n,o):{...n,unavailableReason:"not-delivered"}}catch(o){return t?.aborted&&t.throwIfAborted(),{...n,unavailableReason:BCe(o)}}}function yCe(n){let t=fT(n.authorName,cCe),o=fT(n.content,sCe,{multiline:!0}),{attachments:a,truncated:e}=CCe(n.attachments),i=n3(n.unavailableReason);!o.value&&a.length===0&&!i&&(i="not-delivered");let A=t.truncated||o.truncated||e;return{note:lCe,...t.value?{authorName:t.value}:{},...o.value?{content:o.value}:{},...a.length>0?{attachments:a}:{},...i?{unavailableReason:i}:{},...A?{truncated:!0}:{}}}function mCe(n){return`${JSON.stringify(n).replace(/[<>&]/gu,o=>({"<":"\\u003c",">":"\\u003e","&":"\\u0026"})[o])}`}function Kr(n){return QT(n?.replyTo)}async function xo(n,{signal:t}={}){if(!Kr(n))return P_(n,{signal:t});let o=yCe(await QCe(n.replyTo,t)),a=await P_(n,{signal:t});return[{type:"text",text:mCe(o)},...a]}function SCe(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 wCe(n){let t=new Map,o=new Map,a=[];for(let e of[...n].sort((i,A)=>i.seq-A.seq)){e?.type==="turn/start"&&Number.isSafeInteger(e.data?.turn)&&t.set(e.data.turn,e.time);let i=SCe(e);if(i&&o.set(i.turn,i),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)&&a.push({...A,startedAt:t.get(e.data.turn),completedAt:e.time})}return a}function DCe(n,t,o){let a=wCe(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 a.length===1?a[0].text:null}async function Ap({session:n,quotedAt:t,signal:o,pageSize:a=100,maxPages:e=3,timeoutMs:i=5e3,toleranceMs:A=15e3}={}){if(typeof n?.readHistory!="function"||!Number.isFinite(t))return null;let r=AbortSignal.timeout(i),s=o?AbortSignal.any([o,r]):r,g=Date.now()+i,c=new Map,I;for(let d=0;dt==null?null:Yt(String(t))).filter(Boolean))]:[]}function GCe(n){let t=Yt(n);return t?[...t].slice(0,PCe).join(""):null}function c3(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let t=Yt(n.conversationKey),o=GCe(n.text),a=yT(n.sentAt),e=yT(n.completedAt)??a;return!t||!o||a===null||e===null?null:{conversationKey:t,text:o,sentAt:a,completedAt:Math.max(a,e),providerMessageIds:g3(n.providerMessageIds)}}function mT(n,t=Date.now()){if(!Array.isArray(n))return[];let o=t-vCe;return n.map(c3).filter(a=>a&&a.completedAt>=o).slice(-kCe)}function FCe(n,t){if(!n||typeof n!="object")return null;let o=Yt(n.requestId)??Yt(t),a=Yt(n.staffId),e=Yt(n.requestedAt)??Yt(n.lastSeenAt),i=Yt(n.lastSeenAt)??e;return!o||!a||!e||!i?null:{requestId:o,staffId:a,displayName:s3(n.displayName??n.nick),requestedAt:e,lastSeenAt:i}}function LCe(n){if(!n||typeof n!="object")return structuredClone(ay);let t={};if(n.sessions&&typeof n.sessions=="object"&&!Array.isArray(n.sessions))for(let[e,i]of Object.entries(n.sessions)){let A=Yt(e),r=Yt(i);A&&r&&(t[A]=r)}let o={},a=Array.isArray(n.pendingSenders)?n.pendingSenders.map(e=>[e?.requestId,e]):Object.entries(n.pendingSenders&&typeof n.pendingSenders=="object"?n.pendingSenders:{});for(let[e,i]of a){let A=FCe(i,e);if(!A)continue;let r=Object.values(o).find(s=>s.staffId===A.staffId);(!r||r.lastSeenAtnew Date().toISOString()}={}){if(!Yt(t))throw new TypeError("state path is required");if(typeof o!="function"||typeof a!="function")throw new TypeError("idFactory and now must be functions");this.#e=t,this.#r=o,this.#I=a}async load(){try{this.#A=LCe(JSON.parse(await MCe(this.#e,"utf8")))}catch(t){if(t?.code!=="ENOENT")throw t;this.#A=structuredClone(ay),await this.#o()}return this}sessionFor(t){return this.#A.sessions[t]??null}async setSession(t,o){let a=Yt(t),e=Yt(o);if(!a||!e)throw new TypeError("key and sessionId are required");this.#A.sessions[a]=e,await this.#o()}async clearSession(t){let o=Yt(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=Yt(t);return!!(o&&this.#A.seenMessageIds.includes(o))}async markSeen(t){let o=Yt(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:a=Date.now(),completedAt:e=Date.now(),providerMessageIds:i=[]}={}){let A=c3({conversationKey:t,text:o,sentAt:a,completedAt:e,providerMessageIds:i});if(!A)throw new TypeError("Invalid DingTalk outbound message");this.#A.recentOutboundMessages=mT([...this.#A.recentOutboundMessages,A]),await this.#o()}recentOutboundTextFor({conversationKey:t,processQueryKey:o,messageId:a,createdAt:e,now:i=Date.now()}={}){let A=Yt(t);if(!A)return null;let r=mT(this.#A.recentOutboundMessages,i).filter(I=>I.conversationKey===A),s=g3([o,a]);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=yT(e);if(g===null)return null;let c=r.filter(I=>g>=I.sentAt-oy&&g<=I.completedAt+oy);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=Yt(t),a=o?this.#A.pendingSenders[o]:null;return a?structuredClone(a):null}async recordPendingSender(t,o,a){let e=t&&typeof t=="object"?t:{staffId:t,displayName:o,lastSeenAt:a},i=Yt(e.staffId);if(!i)throw new TypeError("staffId is required");let A=Yt(e.lastSeenAt)??Yt(e.requestedAt)??this.#I(),r=Object.values(this.#A.pendingSenders).find(g=>g.staffId===i),s={requestId:r?.requestId??`ding_sender_${this.#r()}`,staffId:i,displayName:s3(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=Yt(t);return!o||!this.#A.pendingSenders[o]?!1:(delete this.#A.pendingSenders[o],await this.#o(),!0)}async removePendingSenderByStaffId(t){let o=Yt(t),a=o?Object.values(this.#A.pendingSenders).find(e=>e.staffId===o):null;return a?this.removePendingSender(a.requestId):!1}snapshot(){return structuredClone(this.#A)}async remove(){await this.#t;try{await TCe(this.#e)}catch(t){if(t?.code!=="ENOENT")throw t}this.#A=structuredClone(ay)}async#o(){let t=`${JSON.stringify(this.#A,null,2)} `,o=this.#t.then(async()=>{await bCe(RCe(this.#e),{recursive:!0,mode:448});let a=`${this.#e}.tmp`;await NCe(a,t,{encoding:"utf8",mode:384}),await _Ce(a,this.#e)});this.#t=o.then(()=>{},()=>{}),await o}};var UCe=Object.freeze(["open","allowlist"]),HCe=Object.freeze(["direct","group"]),I3=256,KCe=["direct","group"],xCe=["mode","open","allowlist"],YCe=["defaultCanExecuteCommands","commandPermissionOverrides"],jCe=["users"],JCe=["id","canExecuteCommands"],qCe=/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;function Io(n){let t=new TypeError(n);return t.code="access-policy-invalid",t}function hu(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 h3(n){if(typeof n=="number"){if(!Number.isFinite(n))throw Io("\u7528\u6237\u6807\u8BC6\u65E0\u6548\u3002");n=String(n)}else typeof n=="bigint"&&(n=String(n));if(typeof n!="string")throw Io("\u7528\u6237\u6807\u8BC6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002");let t=n.trim();if(!t||t.length>I3||qCe.test(t))throw Io(`\u7528\u6237\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A\u3001\u5305\u542B\u63A7\u5236\u5B57\u7B26\u6216\u8D85\u8FC7 ${I3} \u4E2A\u5B57\u7B26\u3002`);return t}function zCe(n){if(!hu(n,JCe))throw Io("\u7528\u6237\u6761\u76EE\u5FC5\u987B\u5305\u542B\u7528\u6237\u6807\u8BC6\u548C\u547D\u4EE4\u6743\u9650\u3002");if(typeof n.canExecuteCommands!="boolean")throw Io("\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({id:h3(n.id),canExecuteCommands:n.canExecuteCommands})}function E3(n,{listMessage:t,duplicateMessage:o}){if(!Array.isArray(n))throw Io(t);let a=n.map(zCe);if(new Set(a.map(({id:e})=>e)).size!==a.length)throw Io(o);return Object.freeze(a)}function VCe(n){if(!hu(n,YCe))throw Io("\u5F00\u653E\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");if(typeof n.defaultCanExecuteCommands!="boolean")throw Io("\u5F00\u653E\u6A21\u5F0F\u9ED8\u8BA4\u547D\u4EE4\u6743\u9650\u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");return Object.freeze({defaultCanExecuteCommands:n.defaultCanExecuteCommands,commandPermissionOverrides:E3(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 WCe(n){if(!hu(n,jCe))throw Io("\u767D\u540D\u5355\u6A21\u5F0F\u8BBE\u7F6E\u5FC5\u987B\u5B8C\u6574\u3002");return Object.freeze({users:E3(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 ST(n){if(!hu(n,xCe))throw Io("\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(!UCe.includes(n.mode))throw Io("\u8BBF\u95EE\u6A21\u5F0F\u53EA\u80FD\u662F open \u6216 allowlist\u3002");return Object.freeze({mode:n.mode,open:VCe(n.open),allowlist:WCe(n.allowlist)})}function Oc(n){if(!hu(n,KCe))throw Io("\u8BF7\u540C\u65F6\u63D0\u4EA4\u5B8C\u6574\u7684\u79C1\u804A\u548C\u7FA4\u804A\u8BBF\u95EE\u8BBE\u7F6E\u3002");return Object.freeze({direct:ST(n.direct),group:ST(n.group)})}function tp(n){try{return Oc(n)}catch{return null}}function sy(n){return ST(n===void 0?{mode:"allowlist",open:{defaultCanExecuteCommands:!1,commandPermissionOverrides:[]},allowlist:{users:[]}}:n)}var l3=sy(),d3=Object.freeze({direct:l3,group:l3});function Sg({direct:n=d3.direct,group:t=d3.group}={}){return Oc({direct:n,group:t})}var ZCe=Object.freeze({allowed:!0,reason:"allowed"}),XCe=Object.freeze({allowed:!1,reason:"policy-unavailable"}),p3=Object.freeze({allowed:!1,reason:"invalid-context"}),$Ce=Object.freeze({allowed:!1,reason:"sender-unavailable"}),eBe=Object.freeze({allowed:!1,reason:"sender-not-allowed"}),ABe=Object.freeze({allowed:!1,reason:"command-not-allowed"});function u3(n,{conversationType:t,senderIds:o,isCommand:a=!1,equals:e=(i,A)=>i===A}={}){let i=tp(n);if(!i)return XCe;if(!HCe.includes(t)||typeof a!="boolean"||typeof e!="function")return p3;let A=(Array.isArray(o)?o:[o]).flatMap(c=>{try{return[h3(c)]}catch{return[]}});if(A.length===0)return $Ce;let r=i[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 p3}return r.mode==="allowlist"&&g.length===0?eBe:a&&!(r.mode==="open"?g.length>0?g.every(I=>I.canExecuteCommands):r.open.defaultCanExecuteCommands:g.every(I=>I.canExecuteCommands))?ABe:ZCe}var tBe=new Set(["/help","/status","/new"]);function rp(n,{hasImages:t=!1,hasFiles:o=!1}={}){if(typeof n!="string")return!1;let a=n.trim();return a?La(a)||ji(a)||!o&&(ha(a)||Ea(a)||ua(a))?!0:t||o?!1:tBe.has(a.toLowerCase())||$_(a)||z_(a):!1}var lo="\u4F60\u53EF\u4EE5\u53D1\u9001\u666E\u901A\u6D88\u606F\uFF0C\u4F46\u6CA1\u6709\u6267\u884C\u547D\u4EE4\u7684\u6743\u9650\u3002",rBe=Object.freeze({allowed:!0,reason:"policy-not-configured"}),iBe=Object.freeze({allowed:!0,reason:"privileged-sender"});function Ti(n,{conversationType:t,senderIds:o,text:a="",hasImages:e=!1,hasFiles:i=!1,isCommand:A=rp(a,{hasImages:e,hasFiles:i})}={}){if(!n)return rBe;try{if(typeof n.isPrivileged=="function"&&n.isPrivileged(o,t)===!0)return iBe}catch{}let r=null;try{r=n.getSettings()}catch{}return u3(r,{conversationType:t,senderIds:o,isCommand:A,...typeof n.equals=="function"?{equals:n.equals}:{}})}var aBe="\u5DF2\u8FDE\u63A5 DeepSeek Harness\uFF0C\u6B63\u5728\u601D\u8003\u2026",wT="\u8FD9\u4E2A\u95EE\u9898\u5DF2\u5728\u5176\u4ED6\u5BA2\u6237\u7AEF\u5904\u7406\uFF0C\u65E0\u9700\u518D\u6B21\u56DE\u7B54\u3002",oBe=["\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 nBe(){return oBe.map(n=>w(n)).join(` diff --git a/package.json b/package.json index 5da6fc4..b8265ba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-im-ops", - "version": "4.9.1-ops.21", + "version": "4.9.1-ops.22", "description": "Ops fork of dsh-im (all channels kept). Based on @xmanrui/dsh-im@4.9.1 — access/session policies owned here.", "keywords": [ "deepseek-harness", diff --git a/src/channels/shared/semantic/artifact.mjs b/src/channels/shared/semantic/artifact.mjs index 6c6f54b..8454d58 100644 --- a/src/channels/shared/semantic/artifact.mjs +++ b/src/channels/shared/semantic/artifact.mjs @@ -576,7 +576,11 @@ export function createOutboundArtifactTool({ registry = outboundArtifactRegistry }; const definition = Object.freeze({ name: OUTBOUND_ARTIFACT_TOOL, - description: 'Send a readable file or generated image to the user through the current conversation. Existing and newly created files are both valid.', + description: [ + 'Deliver a readable file or generated image to the user in this IM chat as a real attachment.', + 'Call this after the file exists on disk. Pasting a workspace path in the reply text does not send the file.', + 'Existing and newly created files are both valid.', + ].join(' '), parameters: { type: 'object', additionalProperties: false, @@ -654,7 +658,11 @@ export function installOutboundArtifactTool(ctx, { registry = outboundArtifactRe ctx.systemPrompt.section({ name: 'dsh-im:return-file', order: 115, - text: `When the user asks to receive a file or generated image, call ${OUTBOUND_ARTIFACT_TOOL} with its path. Existing files can be sent directly; do not recreate or rename a file solely for delivery.`, + text: [ + `When the user asks to receive a file or generated image in this IM chat, you MUST call ${OUTBOUND_ARTIFACT_TOOL} with the file path so the channel can attach it.`, + 'Writing or pasting a local/workspace path in the reply text does not deliver the file to the user.', + 'Create or locate the file first, then call the tool. Do not recreate or rename a file solely for delivery.', + ].join(' '), }); return true; } diff --git a/test/outbound-artifact.test.mjs b/test/outbound-artifact.test.mjs index 4eddc9f..de98cda 100644 --- a/test/outbound-artifact.test.mjs +++ b/test/outbound-artifact.test.mjs @@ -381,7 +381,9 @@ test('Host installer always exposes the tool and explicitly permits existing fil assert.equal(installed, true); assert.equal(definition.name, OUTBOUND_ARTIFACT_TOOL); assert.match(definition.description, /Existing and newly created files are both valid/); - assert.match(section.text, /Existing files can be sent directly/); + assert.match(definition.description, /Pasting a workspace path in the reply text does not send the file/); + assert.match(section.text, /MUST call dsh_im_return_file/); + assert.match(section.text, /does not deliver the file/); assert.equal(typeof listeners.get('tools/result'), 'function'); assert.equal(typeof listeners.get('session/event'), 'function'); assert.equal(typeof listeners.get('session/disposed'), 'function');