shennian 0.2.133 → 0.2.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/publish-build-manifest.json +20 -15
- package/dist/src/channels/wechat-channel/helper-assets.js +1 -1
- package/dist/src/channels/wechat-channel/observer.js +1 -1
- package/dist/src/channels/wechat-rpa/product-channel.js +9 -9
- package/dist/src/channels/wechat-rpa.js +3 -5
- package/dist/src/commands/daemon-start-wait.d.ts +8 -0
- package/dist/src/commands/daemon-start-wait.js +1 -0
- package/dist/src/commands/daemon.js +9 -9
- package/dist/src/commands/pair.js +8 -8
- package/dist/src/session/handlers/wechat-helper-runtime.d.ts +2 -0
- package/dist/src/session/handlers/wechat-helper-runtime.js +1 -1
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"jsMinified": true,
|
|
4
4
|
"minifier": "esbuild",
|
|
5
|
-
"fileCount":
|
|
5
|
+
"fileCount": 137,
|
|
6
6
|
"files": [
|
|
7
7
|
{
|
|
8
8
|
"file": "bin/shennian.js",
|
|
@@ -216,8 +216,8 @@
|
|
|
216
216
|
},
|
|
217
217
|
{
|
|
218
218
|
"file": "src/channels/wechat-channel/helper-assets.js",
|
|
219
|
-
"beforeBytes":
|
|
220
|
-
"afterBytes":
|
|
219
|
+
"beforeBytes": 17157,
|
|
220
|
+
"afterBytes": 9152
|
|
221
221
|
},
|
|
222
222
|
{
|
|
223
223
|
"file": "src/channels/wechat-channel/helper-client.js",
|
|
@@ -261,8 +261,8 @@
|
|
|
261
261
|
},
|
|
262
262
|
{
|
|
263
263
|
"file": "src/channels/wechat-channel/observer.js",
|
|
264
|
-
"beforeBytes":
|
|
265
|
-
"afterBytes":
|
|
264
|
+
"beforeBytes": 112878,
|
|
265
|
+
"afterBytes": 50794
|
|
266
266
|
},
|
|
267
267
|
{
|
|
268
268
|
"file": "src/channels/wechat-channel/outbound-ledger.js",
|
|
@@ -321,8 +321,8 @@
|
|
|
321
321
|
},
|
|
322
322
|
{
|
|
323
323
|
"file": "src/channels/wechat-rpa/product-channel.js",
|
|
324
|
-
"beforeBytes":
|
|
325
|
-
"afterBytes":
|
|
324
|
+
"beforeBytes": 20920,
|
|
325
|
+
"afterBytes": 10980
|
|
326
326
|
},
|
|
327
327
|
{
|
|
328
328
|
"file": "src/channels/wechat-rpa-session-sync.js",
|
|
@@ -331,8 +331,8 @@
|
|
|
331
331
|
},
|
|
332
332
|
{
|
|
333
333
|
"file": "src/channels/wechat-rpa.js",
|
|
334
|
-
"beforeBytes":
|
|
335
|
-
"afterBytes":
|
|
334
|
+
"beforeBytes": 58039,
|
|
335
|
+
"afterBytes": 29680
|
|
336
336
|
},
|
|
337
337
|
{
|
|
338
338
|
"file": "src/channels/wecom.js",
|
|
@@ -349,6 +349,11 @@
|
|
|
349
349
|
"beforeBytes": 3288,
|
|
350
350
|
"afterBytes": 1780
|
|
351
351
|
},
|
|
352
|
+
{
|
|
353
|
+
"file": "src/commands/daemon-start-wait.js",
|
|
354
|
+
"beforeBytes": 1013,
|
|
355
|
+
"afterBytes": 422
|
|
356
|
+
},
|
|
352
357
|
{
|
|
353
358
|
"file": "src/commands/daemon-windows.js",
|
|
354
359
|
"beforeBytes": 3570,
|
|
@@ -356,8 +361,8 @@
|
|
|
356
361
|
},
|
|
357
362
|
{
|
|
358
363
|
"file": "src/commands/daemon.js",
|
|
359
|
-
"beforeBytes":
|
|
360
|
-
"afterBytes":
|
|
364
|
+
"beforeBytes": 37422,
|
|
365
|
+
"afterBytes": 18015
|
|
361
366
|
},
|
|
362
367
|
{
|
|
363
368
|
"file": "src/commands/external-attachments.js",
|
|
@@ -386,8 +391,8 @@
|
|
|
386
391
|
},
|
|
387
392
|
{
|
|
388
393
|
"file": "src/commands/pair.js",
|
|
389
|
-
"beforeBytes":
|
|
390
|
-
"afterBytes":
|
|
394
|
+
"beforeBytes": 11420,
|
|
395
|
+
"afterBytes": 6596
|
|
391
396
|
},
|
|
392
397
|
{
|
|
393
398
|
"file": "src/commands/runtime.js",
|
|
@@ -626,8 +631,8 @@
|
|
|
626
631
|
},
|
|
627
632
|
{
|
|
628
633
|
"file": "src/session/handlers/wechat-helper-runtime.js",
|
|
629
|
-
"beforeBytes":
|
|
630
|
-
"afterBytes":
|
|
634
|
+
"beforeBytes": 7243,
|
|
635
|
+
"afterBytes": 3930
|
|
631
636
|
},
|
|
632
637
|
{
|
|
633
638
|
"file": "src/session/manager.js",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:fs";import s from"node:path";import
|
|
1
|
+
import c from"node:fs";import s from"node:path";import w from"node:crypto";const V="0.1.12",E="SHENNIAN_WECHAT_CHANNEL_HELPER_DIR",d="SHENNIAN_HELPER_RUNTIME_DIR",S="helper_runtime_required",C=["en","v"].join("");function $(n={}){const r=n.platform??process.platform;if(r!=="darwin"&&r!=="win32")return{ok:!1,reasonCode:"unsupported_platform",message:"WeChat channel helper is only available on macOS and Windows"};const e=n.baseDir?[s.resolve(n.baseDir)]:A({platform:r,env:n.env??y(),homedir:n.homedir,includeInstalledDesktop:n.includeInstalledDesktop});let a=null;for(const t of e){const i=_({platform:r,baseDir:t,verifyIntegrity:n.verifyIntegrity});if(i.ok||(n.baseDir||c.existsSync(t))&&(a??=i,n.baseDir))return i}return a??{ok:!1,reasonCode:S,message:x(r,e)}}function _(n){const{platform:r,baseDir:e}=n,a=s.join(e,"manifest.json"),t=F(a);if(!t)return{ok:!1,reasonCode:"manifest_missing",message:`WeChat channel helper manifest is missing: ${a}`};const i=t.platforms[r],o=i?s.join(e,i.executable):"";if(!i||!o||!c.existsSync(o))return{ok:!1,reasonCode:"helper_missing",message:`WeChat channel helper executable is missing: ${o||e}`};if(L({platform:r,baseDir:e,verifyIntegrity:n.verifyIntegrity})&&i.sha256&&w.createHash("sha256").update(c.readFileSync(o)).digest("hex")!==i.sha256)return{ok:!1,reasonCode:"integrity_mismatch",message:`WeChat channel helper integrity mismatch: ${o}`};const f=H(r,o);return f.ok?{ok:!0,helperPath:o,helperDir:e,version:t.helperVersion,manifest:t,warning:i.signed&&i.notarized?void 0:"helper_not_signed_or_notarized"}:{ok:!1,reasonCode:"helper_not_executable",message:f.message}}function H(n,r){if(n!=="darwin")return{ok:!0};try{const e=c.statSync(r);return(e.mode&73)!==0?{ok:!0}:(c.chmodSync(r,e.mode|73),{ok:!0})}catch(e){return{ok:!1,message:`WeChat channel helper is not executable and could not be repaired: ${r}: ${e instanceof Error?e.message:String(e)}`}}}function A(n){const{platform:r,env:e}=n,a=r==="win32"?"windows":"macos",t=[],i=l=>{if(!l)return;const p=s.resolve(l);t.includes(p)||t.push(p)},o=e[E]?.trim();o&&i(j(o,a));const f=e[d]?.trim();if(f)for(const l of P(f,a))i(l);if(b({platform:r,platformDir:a,env:e,homedir:n.homedir,push:i}),n.includeInstalledDesktop===!1)return t;if(r==="darwin"){const l=n.homedir||e.HOME;l&&i(s.join(l,"Applications","Shennian.app","Contents","Resources","wechat-channel",a)),i(s.join("/Applications","Shennian.app","Contents","Resources","wechat-channel",a))}else if(r==="win32"){const l=n.homedir||e.USERPROFILE,p=e.LOCALAPPDATA||(l?s.join(l,"AppData","Local"):""),u=e.ProgramFiles||e.PROGRAMFILES,m=e["ProgramFiles(x86)"]||e["PROGRAMFILES(X86)"];for(const h of[p?s.join(p,"Programs","Shennian"):"",p?s.join(p,"Programs","shennian"):"",u?s.join(u,"Shennian"):"",m?s.join(m,"Shennian"):""])h&&i(s.join(h,"resources","wechat-channel",a))}return t}function b(n){const{platform:r,platformDir:e,env:a,push:t}=n;if(r==="darwin"){const i=n.homedir||a.HOME,o=g({platform:r,env:a,homedir:n.homedir});o&&(t(s.join(o,"Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join(o,"wechat-channel",e))),i&&t(s.join(i,"Applications","Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join("/Applications","Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join("/Library","Application Support","Shennian","Helper","wechat-channel",e))}else if(r==="win32"){const i=n.homedir||a.USERPROFILE,o=a.LOCALAPPDATA||(i?s.join(i,"AppData","Local"):""),f=a.ProgramFiles||a.PROGRAMFILES,l=a["ProgramFiles(x86)"]||a["PROGRAMFILES(X86)"];o&&(t(s.join(o,"Programs","Shennian Helper","resources","wechat-channel",e)),t(s.join(o,"Shennian","Helper","wechat-channel",e))),f&&t(s.join(f,"Shennian Helper","resources","wechat-channel",e)),l&&t(s.join(l,"Shennian Helper","resources","wechat-channel",e))}}function j(n,r){return c.existsSync(s.join(n,"manifest.json"))?n:s.join(n,r)}function P(n,r){if(c.existsSync(s.join(n,"manifest.json")))return[n];const e=s.join(n,"Shennian Helper.app","Contents","Resources","wechat-channel",r),a=s.join(n,"wechat-channel",r),t=s.join(n,r);return[e,a,t]}function g(n){const r=n.env,e=r[d]?.trim();if(e)return s.resolve(e);const a=n.homedir||(n.platform==="win32"?r.USERPROFILE:r.HOME);if(n.platform==="darwin")return a?s.join(a,"Library","Application Support","Shennian","Helper"):null;if(n.platform==="win32"){const t=r.LOCALAPPDATA||(a?s.join(a,"AppData","Local"):"");return t?s.join(t,"Shennian","Helper"):null}return null}function q(n={}){return g({platform:n.platform??process.platform,env:n.env??y(),homedir:n.homedir})}function D(n){const r=s.resolve(n);return O([s.join(r,"helper-runtime-package.json"),s.join(s.dirname(r),"..","helper-runtime-package.json")])}function U(n){const r=n.platform??process.platform;if(r!=="darwin"&&r!=="win32")return{ok:!1,reasonCode:"unsupported_platform",message:"WeChat channel helper runtime package is only available on macOS and Windows"};const e=n.manifestPath?[s.resolve(n.manifestPath)]:n.helperDir?D(n.helperDir):[],a=e.find(t=>c.existsSync(t));if(!a)return{ok:!1,reasonCode:"helper_runtime_package_manifest_missing",message:`Helper runtime package manifest is missing. Checked: ${e.join(", ")||"(none)"}`,manifestPath:e[0]};try{const t=JSON.parse(R(a)),i=v(t,r);return i.ok?{ok:!0,manifestPath:a,manifest:t}:{ok:!1,reasonCode:"helper_runtime_package_manifest_invalid",message:`${i.message}: ${a}`,manifestPath:a}}catch(t){return{ok:!1,reasonCode:"helper_runtime_package_manifest_invalid",message:`Helper runtime package manifest is invalid JSON: ${t instanceof Error?t.message:String(t)}`,manifestPath:a}}}function v(n,r){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,message:"manifest must be an object"};const e=n;return e.schemaVersion!==1?{ok:!1,message:"schemaVersion must be 1"}:e.packageKind!=="shennian-helper-runtime"?{ok:!1,message:"packageKind must be shennian-helper-runtime"}:e.platform!==r?{ok:!1,message:`platform must be ${r}`}:e.helperVersion?!Number.isInteger(e.protocolVersion)||Number(e.protocolVersion)<=0?{ok:!1,message:"protocolVersion must be a positive integer"}:I(e.minCliVersion)?!e.sha256||typeof e.sha256.runtimeManifest!="string"?{ok:!1,message:"sha256.runtimeManifest is required"}:k(e.sha256.runtimeManifest)?e.sha256.entrypoint!==null&&typeof e.sha256.entrypoint!="string"?{ok:!1,message:"sha256.entrypoint must be a string or null"}:typeof e.sha256.entrypoint=="string"&&!k(e.sha256.entrypoint)?{ok:!1,message:"sha256.entrypoint must be a sha256 digest or null"}:!e.installTarget?.kind||!e.installTarget.defaultPath?{ok:!1,message:"installTarget.kind and installTarget.defaultPath are required"}:!e.payload?.kind||!e.payload.runtimeManifest||!e.payload.entrypoint?{ok:!1,message:"payload.kind, payload.runtimeManifest, and payload.entrypoint are required"}:r==="darwin"&&e.installTarget.kind!=="app-bundle"?{ok:!1,message:"darwin installTarget.kind must be app-bundle"}:r==="darwin"&&e.payload.kind!=="macos-helper-app"?{ok:!1,message:"darwin payload.kind must be macos-helper-app"}:r==="win32"&&e.installTarget.kind!=="directory"?{ok:!1,message:"win32 installTarget.kind must be directory"}:r==="win32"&&e.payload.kind!=="windows-helper-runtime"?{ok:!1,message:"win32 payload.kind must be windows-helper-runtime"}:!e.signature||typeof e.signature.requiredForRelease!="boolean"||typeof e.signature.signed!="boolean"||typeof e.signature.notarized!="boolean"?{ok:!1,message:"signature.requiredForRelease, signature.signed, and signature.notarized are required"}:{ok:!0}:{ok:!1,message:"sha256.runtimeManifest must be a sha256 digest"}:{ok:!1,message:"minCliVersion must be a semver string"}:{ok:!1,message:"helperVersion is required"}}function I(n){return typeof n=="string"&&/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(n)}function k(n){return/^[a-f0-9]{64}$/i.test(n)}function L(n){return n.verifyIntegrity===!0?!0:n.verifyIntegrity===!1?!1:!N(n.platform,n.baseDir)}function N(n,r){const e=r.replace(/[\\/]+/g,"/");return n==="darwin"?/\/Shennian\.app\/Contents\/Resources\/wechat-channel\/macos$/i.test(e):n==="win32"?/\/resources\/wechat-channel\/windows$/i.test(e):!1}function x(n,r){const e=n==="win32"?"Windows":"macOS",a=r.length>0?` Checked helper directories: ${r.join(", ")}`:"";return`WeChat RPA requires Shennian Helper runtime on ${e}; open Shennian Desktop or use the \u4F7F\u7528\u5FAE\u4FE1 page to install Helper, then retry.${a}`}function y(){return globalThis.process?.[C]??{}}function F(n){try{const r=JSON.parse(R(n));return r.schemaVersion!==1||typeof r.helperVersion!="string"||!r.platforms?null:r}catch{return null}}function R(n){return c.readFileSync(n,"utf8").replace(/^\uFEFF/,"")}function O(n){const r=new Set,e=[];for(const a of n){const t=s.resolve(a);r.has(t)||(r.add(t),e.push(t))}return e}export{d as SHENNIAN_HELPER_RUNTIME_DIR_ENV,E as WECHAT_CHANNEL_HELPER_DIR_ENV,S as WECHAT_CHANNEL_HELPER_RUNTIME_REQUIRED_REASON,V as WECHAT_CHANNEL_HELPER_VERSION,q as getDefaultWeChatHelperRuntimeRoot,D as helperRuntimePackageManifestCandidates,U as readWeChatChannelHelperRuntimePackageManifest,$ as resolveWeChatChannelHelperAsset,v as validateWeChatChannelHelperRuntimePackageManifest};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import R from"node:fs";import Z from"node:path";import{WeChatChannelApiError as Le}from"./client.js";import{defaultWeChatChannelAttachmentDir as De,resolveVisibleWeChatChannelMedia as Ke}from"./media-resolver.js";import{updateWeChatChannelBindingLedger as Oe}from"./ledger.js";import{defaultWeChatChannelVectorStorePath as $e,loadWeChatChannelVectorStore as ze,saveWeChatChannelVectorStore as Ve,upsertWeChatChannelVectorReferences as qe}from"./vector-store.js";import{normalizeWeChatChannelAttachmentAvailability as Q,normalizeWeChatChannelMessageKind as je}from"./core/schema.js";import{waitForWeChatChannelPacing as ee,weChatChannelPacingDelayMs as Ge}from"./pacing.js";import{matchWeChatConversationFingerprints as He}from"./fingerprint.js";import{normalizeWeChatAnchorText as v,weChatTextSimilarity as te}from"./anchor.js";import{decideWeChatChannelActivityGate as Ue,normalizeWeChatChannelActivitySnapshot as Ye}from"./human-coordination.js";const Xe=3,Je=5,Ze="wechat_login_required",Qe=5500;class N extends Error{reasonCode;stage;action;constructor(t){super(`user_active:${t.reasonCode}:${t.stage}:${t.action}`),this.name="WeChatChannelUserActivityAbort",this.reasonCode=t.reasonCode,this.stage=t.stage,this.action=t.action}}async function An(e){return await ft(e.helper,e.activityGuard,e.traceId).withLease("observe","observe-binding",async n=>et({...e,helper:n}))}async function et(e){const t=e.foregroundMode??"required";let n=await tt(e,{foregroundMode:t});if(t!=="background"&&(n=await Ie(e.helper,n,e.traceId)),t==="background"){const{capture:a,ocr:s}=await k({helper:e.helper,window:n,traceId:e.traceId}),c=W({capture:a,ocr:s,window:n});if(c)throw new Error(c);if(!O(s,a,e.binding.conversationDisplayName))throw new Error("conversation_not_visible_background");if(X({capture:a,ocr:s,binding:e.binding}))throw new Error("wechat_window_obstructed_background");return e.onObservationEvidence?.({window:n,capture:a,ocr:s}),le(e)?ue({...e,window:n,capture:a,ocr:s}):q({...e,window:n,capture:a,ocr:s})}const r=await H({helper:e.helper,window:n,binding:e.binding,runtime:e.runtime,api:e.api,workDir:e.workDir,traceId:e.traceId});if(!r.opened){const a=await ce({...e,fallback:n,requireTargetConversation:!1,force:!0});if(a.windowId!==n.windowId){n=await Ie(e.helper,a,e.traceId);const s=await H({helper:e.helper,window:n,binding:e.binding,runtime:e.runtime,api:e.api,workDir:e.workDir,traceId:e.traceId});if(!s.opened)throw new Error(s.reason||r.reason||"conversation_not_opened")}else throw new Error(r.reason||"conversation_not_opened")}let{capture:i,ocr:o}=await k({helper:e.helper,window:n,traceId:e.traceId});if(X({capture:i,ocr:o,binding:e.binding})){n=await Ut(e.helper,e.traceId);const a=await H({helper:e.helper,window:n,binding:e.binding,runtime:e.runtime,api:e.api,workDir:e.workDir,traceId:e.traceId});if(!a.opened)throw new Error(a.reason||"wechat_window_obstructed");if({capture:i,ocr:o}=await k({helper:e.helper,window:n,traceId:e.traceId}),X({capture:i,ocr:o,binding:e.binding}))throw new Error("wechat_window_obstructed")}return e.onObservationEvidence?.({window:n,capture:i,ocr:o}),le(e)?ue({...e,window:n,capture:i,ocr:o}):q({...e,window:n,capture:i,ocr:o})}async function tt(e,t={}){const n=t.foregroundMode??e.foregroundMode??"required",r=await jt(e.helper,e.traceId,{foreground:n});return n==="background"?r:ce({...e,fallback:r,requireTargetConversation:!1,force:t.forceVision})}const x=new Map;function nt(){return process.env.SHENNIAN_WECHAT_VISION_LAYOUT_REUSE!=="0"}function ne(e){if(!nt()||!e.classification||e.classification.windowKind!=="chat_main")return;const t=e.window.windowId;if(!t)return;const n=se(e.window),r=A(e.classification.layout?.messageInputRect,e.screenshot,e.window,"message-input"),i=A(e.classification.layout?.searchInputRect,e.screenshot,e.window,"search-input");if(!r&&!i)return;const o={windowId:t,boundsKey:n,messageInputPoint:r,searchInputPoint:i,updatedAt:new Date().toISOString()},a=`${e.runtime.runtimeId}:${e.binding.bindingId}:${t}`,s=`${e.runtime.runtimeId}:window:${t}:${n}`;x.set(a,o),x.set(s,o),F(e,a,o),F(e,s,o)}async function Ln(e){const t=await re(e,"messageInputPoint");if(!t.messageInputPoint)throw new Error("wechat_message_input_not_found:vision_rect_missing");return t.messageInputPoint}async function rt(e){const t=await re(e,"searchInputPoint");if(!t.searchInputPoint)throw new Error("wechat_search_input_not_found:vision_rect_missing");return t.searchInputPoint}async function re(e,t){const n=t==="searchInputPoint"?"wechat_search_input":"wechat_message_input";if(!e.api.classifyWindow)throw new Error(`${n}_detector_unavailable`);const r=e.window.windowId,i=se(e.window),o=`${e.runtime.runtimeId}:${e.binding.bindingId}:${r||"unknown"}`,a=`${e.runtime.runtimeId}:window:${r||"unknown"}:${i}`,s=x.get(o)??x.get(a)??oe(e,o)??oe(e,a);if(s&&s.windowId===r&&s.boundsKey===i&&(!t||s[t]))return x.set(o,s),x.set(a,s),s;const c=e.screenshot??await T(e.helper,r,e.traceId,e.window.bounds),l=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:c.mimeType,dataBase64:c.dataBase64,width:c.width,height:c.height,windowId:r},traceId:e.traceId});if(l.windowKind!=="chat_main")throw new Error(`${n}_not_found:${l.windowKind||"unknown_window"}`);const w=A(l.layout?.messageInputRect,c,e.window,"message-input"),u=A(l.layout?.searchInputRect,c,e.window,"search-input"),d={windowId:r||"",boundsKey:i,messageInputPoint:w,searchInputPoint:u,updatedAt:new Date().toISOString()};return x.set(o,d),x.set(a,d),F(e,o,d),F(e,a,d),d}function ie(e){const t=e.workDir;return t?Z.join(t,"wechat-channel",e.runtime.runtimeId,"vision-layout-point-cache.json"):null}function oe(e,t){const n=ie(e);if(!n)return null;try{const r=JSON.parse(R.readFileSync(n,"utf8"));return it(r[t])}catch{return null}}function F(e,t,n){const r=ie(e);if(r)try{let i={};try{i=JSON.parse(R.readFileSync(r,"utf8"))}catch{i={}}i[t]=n,R.mkdirSync(Z.dirname(r),{recursive:!0}),R.writeFileSync(r,`${JSON.stringify(i,null,2)}
|
|
2
2
|
`,"utf8")}catch{}}function it(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.windowId=="string"?t.windowId:"",r=typeof t.boundsKey=="string"?t.boundsKey:"";if(!r)return null;const i=ae(t.messageInputPoint??t.point),o=ae(t.searchInputPoint);return{windowId:n,boundsKey:r,messageInputPoint:i,searchInputPoint:o,...typeof t.updatedAt=="string"?{updatedAt:t.updatedAt}:{}}}function ae(e){if(!e||typeof e!="object")return null;const t=e,n=Number(t.x),r=Number(t.y);return!Number.isFinite(n)||!Number.isFinite(r)?null:{x:Math.round(n),y:Math.round(r),coordinateSpace:"screen"}}function se(e){const t=e.bounds;return[Math.round(Number(t?.x??0)),Math.round(Number(t?.y??0)),Math.round(Number(t?.width??0)),Math.round(Number(t?.height??0))].join(",")}function A(e,t,n,r="message-input"){const i=Number(e?.x),o=Number(e?.y),a=Number(e?.width),s=Number(e?.height);if(![i,o,a,s].every(Number.isFinite)||a<=0||s<=0)return null;const c=e?.coordinateSpace==="screen"?{x:i,y:o,width:a,height:s,coordinateSpace:"screen"}:{x:i/999*t.width,y:o/999*t.height,width:a/999*t.width,height:s/999*t.height,coordinateSpace:"screenshotPixel"},l=ot(c,t,n,r);return l?{x:Math.round(l.x),y:Math.round(l.y),coordinateSpace:"screen"}:null}function ot(e,t,n,r="message-input"){const i=r==="message-input"?.28:.55,o=at({x:e.x+e.width*.54,y:e.y+e.height*i,coordinateSpace:e.coordinateSpace},t,n);return o?{x:o.x,y:o.y,coordinateSpace:"screen"}:null}function at(e,t,n){if(![e.x,e.y].every(Number.isFinite))return null;if(e.coordinateSpace==="screen"||!n.bounds)return{x:e.x,y:e.y};const r=t.width&&n.bounds.width?t.width/n.bounds.width:1,i=t.height&&n.bounds.height?t.height/n.bounds.height:r,o=Math.max(0,(t.width-n.bounds.width*r)/2),a=Math.max(0,(t.height-n.bounds.height*i)/2);return{x:n.bounds.x+(e.x-o)/r,y:n.bounds.y+(e.y-a)/i}}async function ce(e){if(!e.api.classifyWindow)throw new Error("wechat_window_classifier_unavailable");const t=await e.helper.request("windows.list",{},e.traceId);m(t,"windows.list");const n=(t.result?.windows??[]).filter(B).filter(a=>a.visible!==!1&&a.minimized!==!0&&!!a.windowId),r=dt(n.length?n:[e.fallback],e.fallback);if(!r.length)throw new Error("wechat_window_not_found");const i=[];for(const a of r)try{const s=await T(e.helper,a.windowId,e.traceId,a.bounds),c=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:s.mimeType,dataBase64:s.dataBase64,width:s.width,height:s.height,windowId:a.windowId},traceId:e.traceId});i.push({window:a,classification:c,screenshot:s,score:lt(c,e.requireTargetConversation===!0)})}catch(s){if(st(s))throw s;i.push({window:a,classification:null,errorSummary:s instanceof Error?s.message:String(s||"window classification failed"),score:-1})}const o=i.filter(a=>a.score>0).sort((a,s)=>s.score-a.score)[0];if(!o){const a=ut(i,e.fallback);if(a)return console.warn(`[wechat-channel] window classifier fallback to local Windows WeChat shell windowId=${a.window.windowId}`),a.window;const s=i.map(c=>({windowId:c.window.windowId,appName:c.window.appName,title:c.window.title,score:c.score,errorSummary:c.errorSummary,classification:c.classification?{windowKind:c.classification.windowKind,reasonCode:c.classification.reasonCode,confidence:c.classification.confidence,conversationTitle:c.classification.conversationTitle,isTargetConversation:c.classification.isTargetConversation}:null}));throw new Error(`wechat_chat_main_window_not_found: ${JSON.stringify(s)}`)}return o.screenshot&&ne({helper:e.helper,runtime:e.runtime,binding:e.binding,workDir:e.workDir,traceId:e.traceId,window:o.window,classification:o.classification,screenshot:o.screenshot}),o.window}async function Dn(e,t,n){if(e.runtime.policy.platform!=="win32")return;const r=t.filter(i=>{if(i.window.windowId===n.window.windowId||!i.window.windowId)return!1;const o=i.classification?.windowKind;return o==="chat_main"||o==="login"});if(r.length!==0)for(const i of r)try{await e.helper.request("windows.closeWindow",{windowId:i.window.windowId},e.traceId)}catch{}}function st(e){const t=ct(e);return t==="insufficient_credits"||t==="entitlement_required"||t==="manual_review_required"||t==="wechat_channel_network_failed"||t==="wechat_channel_invalid_response"}function ct(e){if(e instanceof Le||e&&typeof e=="object"&&typeof e.reasonCode=="string")return e.reasonCode.trim().toLowerCase();const t=e instanceof Error?e.message:String(e||"");return/classify-window (?:network )?failed:\s*([a-z][a-z0-9_]*)/i.exec(t)?.[1]?.trim().toLowerCase()||""}function dt(e,t){const n=[],r=i=>{i?.windowId&&(n.some(o=>o.windowId===i.windowId)||n.push(i))};r(e.find(i=>i.windowId===t.windowId));for(const i of e)r(i);return n}function lt(e,t){if(!e||e.windowKind!=="chat_main")return 0;const n=Number(e.confidence??0);return t&&e.isTargetConversation!==!0?0:100+(e.isTargetConversation?50:0)+Math.round(Math.max(0,Math.min(1,n))*100)}function ut(e,t){const n=e.filter(i=>i.score<=0).filter(i=>i.classification?.reasonCode==="server_window_classified").filter(i=>wt(i.window));return n.length===1?n[0]:n.find(i=>i.window.windowId===t.windowId)??null}function wt(e){if(!B(e)||e.visible===!1||e.minimized===!0||!j(e.title))return!1;const t=String(e.className??"");if(!/^Qt\d+QWindowIcon$/i.test(t))return!1;const n=e.bounds;return n?Number(n.width)>=700&&Number(n.height)>=500:!1}function ft(e,t,n){if(!t)return{helper:e,withLease:async(s,c,l)=>await l(e)};let r=null;const i=s=>{t.onEvent?.({...s,at:new Date().toISOString()})},o=async(s,c,l={})=>{if(r){const u=await e.request("automation.lease.status",{},n),d=u.result??{},h=u.ok&&d.interrupted?de(d.interruptReason):u.ok?void 0:u.errorCode||"user_activity_unknown";if(i({phase:"lease-status",stage:s,action:c,ok:u.ok===!0&&!d.interrupted,...h?{reasonCode:h}:{}}),!u.ok)throw new N({reasonCode:u.errorCode||"user_activity_unknown",stage:s,action:c});if(d.active===!1||d.leaseId!==r||!d.interrupted)return;throw new N({reasonCode:de(d.interruptReason),stage:s,action:c})}const w=Date.now()+mt(t.preflightIdleSettleTimeoutMs);for(;;){const u=await e.request("activity.snapshot",{},n);if(!u.ok)throw i({phase:"snapshot",stage:s,action:c,ok:!1,reasonCode:u.errorCode||"user_activity_unknown"}),new N({reasonCode:u.errorCode||"user_activity_unknown",stage:s,action:c});const d=Ue({snapshot:Ye(u.result),stage:s,policy:t.policy});if(i({phase:"snapshot",stage:s,action:c,ok:d.ok,...d.ok?{}:{reasonCode:d.reasonCode,waitMs:d.waitMs}}),d.ok)return;const h=new N({reasonCode:d.reasonCode,stage:s,action:c});if(!l.settle)throw h;const J=w-Date.now();if(J<=0)throw h;await Y(Math.max(50,Math.min(d.waitMs,J)))}},a={request:async(s,c,l)=>{const w=ht(s);w&&await o(w.stage,`${s}:before`);const u=await e.request(s,c,l);return w&&u.ok&&await o(w.stage,`${s}:after`),u}};return{helper:a,async withLease(s,c,l){if(await Ot(e,n),await o(s,`${c}:preflight`,{settle:!0}),t.useAutomationLease===!1)return await l(a);const w=await e.request("automation.lease.acquire",{owner:"wechat-channel",purpose:`observe:${c}`,ttlMs:12e4},n);if(r=typeof w.result?.leaseId=="string"?w.result.leaseId:null,i({phase:"lease-acquire",stage:s,action:c,ok:w.ok===!0,...w.ok?{}:{reasonCode:w.errorCode||"user_activity_unknown"}}),!w.ok)throw r=null,new N({reasonCode:w.errorCode||"user_activity_unknown",stage:s,action:c});try{const u=await l(a);return await o(s,`${c}:complete`),u}finally{const u=r;if(r=null,u){const d=await e.request("automation.lease.release",{leaseId:u},n).catch(h=>({ok:!1,errorCode:"automation_lease_release_failed",errorSummary:h instanceof Error?h.message:String(h)}));i({phase:"lease-release",stage:s,action:c,ok:d.ok===!0,...d.ok?{}:{reasonCode:d.errorCode||"automation_lease_release_failed"}})}}}}}function ht(e){return e==="windows.ensureReady"||e==="windows.focus"||e==="wechat.searchConversation"?{stage:"open_conversation"}:e==="keyboard.shortcut"||e==="mouse.click"||e==="mouse.rightClick"||e==="mouse.scroll"||e==="clipboard.snapshot"||e==="clipboard.readAttachment"||e==="menu.pickItem"?{stage:"dangerous_action"}:null}function de(e){return e==="recent_mouse_activity"||e==="recent_mouse_click"||e==="recent_scroll_activity"||e==="recent_keyboard_activity"||e==="frontmost_app_changed"?e:"user_activity_unknown"}function mt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:Qe}function le(e){return e.observePipeline==="edge-structure"?!0:e.observePipeline==="server-observe"?!1:!!e.api.structureWindow}async function q(e){const t=await Se(e),n=await e.api.observe(e.runtime,e.binding,{screenshots:[{captureIndex:0,mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height}],edgeOcrBlocks:e.ocr.blocks??[],visibleConversationFingerprints:e.ocr.visibleConversationFingerprints??[],localLedgerTailAnchors:e.localLedgerTailAnchors??[],traceId:e.traceId}),r=await me({helper:e.helper,runtime:e.runtime,binding:e.binding,messages:n.observedMessages??[],workDir:e.workDir,attachmentsDir:e.attachmentsDir,window:e.window,screenshot:t,windowId:e.window.windowId,traceId:e.traceId,mediaAnchorText:e.mediaAnchorText});return Pe(r,We({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}))}async function ue(e){if(!e.api.structureWindow)throw new Error("wechat_structure_window_unavailable");const t=await Se(e);let n;try{n=await e.api.structureWindow(e.runtime,e.binding,{screenshots:[{captureIndex:0,mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height}],edgeOcrBlocks:e.ocr.blocks??[],visibleConversationFingerprints:e.ocr.visibleConversationFingerprints??[],localLedgerTailAnchors:e.localLedgerTailAnchors??[],traceId:e.traceId})}catch(c){if(bt(c))return q(e);throw c}const r=kt(n.structuredMessages??n.observedMessages??[]),i=await gt({...e,messages:r,screenshot:t}),o=await me({helper:e.helper,runtime:e.runtime,binding:e.binding,messages:i.messages,workDir:e.workDir,attachmentsDir:e.attachmentsDir,window:e.window,screenshot:t,windowId:e.window.windowId,traceId:e.traceId,mediaAnchorText:e.mediaAnchorText}),a=Pe(o,We({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}));return e.localLedger?Oe({ledger:e.localLedger,bindingId:e.binding.bindingId,observedMessages:a,baselineOnly:e.baselineOnly,vectorReferences:i.vectorReferences}).newMessages:a}function bt(e){return e instanceof Error&&/\bedge_runtime_disabled\b/.test(e.message)}async function gt(e){const t=yt(e.messages);if(!t.length)return{messages:e.messages,vectorReferences:[]};const n=e.api.embedVisual?await vt({...e,seedBlocks:t}):t.filter(a=>f(a.vectorBase64)||f(a.signature));if(!n.length)return{messages:e.messages,vectorReferences:[]};const r=e.vectorStorePath??$e(e.workDir||process.cwd(),e.runtime.runtimeId),i=ze(r,e.runtime.runtimeId),o=qe({store:i,bindingId:e.binding.bindingId,blocks:n});return o.length?(Ve(r,i),{messages:It(e.messages,o),vectorReferences:o}):{messages:e.messages,vectorReferences:[]}}function yt(e){const t=[];for(const n of e)for(const[r,i]of(n.visualBlocks??[]).entries()){const o=f(i.blockId)||`${n.stableMessageKey}:visual-${r}`,a=f(i.blockKind)||n.kind||"visual";t.push({...i,stableMessageKey:n.stableMessageKey,blockId:o,blockKind:a,...i.bbox!==void 0?{bbox:i.bbox}:n.bbox!==void 0?{bbox:n.bbox}:{}})}return t}async function xt(e){if(!e.api.embedVisual)return[];const t=await e.api.embedVisual(e.runtime,e.binding,{screenshots:[{captureIndex:0,mimeType:e.screenshot.mimeType,dataBase64:e.screenshot.dataBase64,width:e.screenshot.width,height:e.screenshot.height}],visualBlocks:e.seedBlocks,traceId:e.traceId});return Ct(t.visualBlocks??t.embeddedBlocks??[],e.seedBlocks)}async function vt(e){try{return await xt(e)}catch(t){if(pt(t))throw t;return[]}}function pt(e){return!e||typeof e!="object"?!1:e.reasonCode==="insufficient_credits"?!0:e instanceof Error&&/\binsufficient_credits\b/.test(e.message)}function Ct(e,t){return e.map((n,r)=>{const i=t[r];return{...n,stableMessageKey:f(n.stableMessageKey)||f(i?.stableMessageKey),blockId:f(n.blockId)||f(i?.blockId),blockKind:f(n.blockKind)||f(i?.blockKind)||"visual",...n.bbox!==void 0?{bbox:n.bbox}:i?.bbox!==void 0?{bbox:i.bbox}:{}}}).filter(n=>f(n.stableMessageKey)&&f(n.blockId))}function It(e,t){const n=new Map;for(const r of t){const i=n.get(r.stableMessageKey)??[];i.push(r),n.set(r.stableMessageKey,i)}return e.map(r=>{const i=n.get(r.stableMessageKey);return i?.length?{...r,visualBlocks:_t(r,i)}:r})}function _t(e,t){const r=(e.visualBlocks??[]).map((o,a)=>{const s=f(o.blockId)||`${e.stableMessageKey}:visual-${a}`,c=t.find(l=>l.blockId===s);return c?we(c,o):fe(o)}),i=new Set(r.map(o=>o.blockId));for(const o of t)i.has(o.blockId)||r.push(we(o));return r}function we(e,t){return{...t?fe(t):{},stableMessageKey:e.stableMessageKey,blockId:e.blockId,blockKind:e.blockKind,vectorStoreKey:e.vectorStoreKey,model:e.model,...e.modelVersion!==void 0?{modelVersion:e.modelVersion}:{},dims:e.dims,...e.signature?{signature:e.signature}:{},...e.bbox!==void 0?{bbox:e.bbox}:{}}}function fe(e){const{vectorBase64:t,...n}=e;return n}function kt(e){return e.map((t,n)=>St(t,n)).filter(t=>t!=null)}function St(e,t){if(!b(e))return null;const n=je(e.kind),r=Tt(e.senderRole),i=g(e.normalizedText),o=g(e.anchorText)??i??g(e.textExcerpt),a=f(e.stableMessageKey)||Mt({message:e,index:t,senderRole:r,kind:n,anchorText:o});return{stableMessageKey:a,senderRole:r,...g(e.senderName)!==null?{senderName:g(e.senderName)}:{},kind:n,...i!==null?{normalizedText:i}:{},...o!==null?{anchorText:o}:{},...I(e,"anchorMetadata")?{anchorMetadata:e.anchorMetadata}:{},...I(e,"neighborContext")?{neighborContext:e.neighborContext}:{},...g(e.textExcerpt)!==null?{textExcerpt:g(e.textExcerpt)}:{},...I(e,"bbox")?{bbox:e.bbox}:{},...I(e,"mediaMetadata")?{mediaMetadata:Nt(e.mediaMetadata)}:{},...typeof e.isBaseline=="boolean"?{isBaseline:e.isBaseline}:{},...g(e.deliveryStatus)!==null?{deliveryStatus:g(e.deliveryStatus)??void 0}:{},...g(e.observedAt)!==null?{observedAt:g(e.observedAt)??void 0}:{},...Array.isArray(e.visualBlocks)?{visualBlocks:e.visualBlocks}:{},...o?{}:{anchorText:a}}}function Mt(e){const t=b(e.message.bbox)?JSON.stringify(e.message.bbox):"";return`structured-window:${[e.index,e.senderRole,e.kind,e.anchorText||f(e.message.textExcerpt)||"",t].join(":").slice(0,180)}`}function Nt(e){if(!b(e))return e;const t={...e};return I(t,"availability")&&(t.availability=Q(t.availability)),b(t.attachment)&&(t.attachment=he(t.attachment)),Array.isArray(t.attachments)&&(t.attachments=t.attachments.map(n=>b(n)?he(n):n)),t}function he(e){const t={...e};return I(t,"availability")&&(t.availability=Q(t.availability)),t}function Tt(e){return e==="self"||e==="contact"||e==="system"||e==="unknown"?e:"unknown"}async function me(e){if(e.binding.downloadMedia===!1)return e.messages;const t=e.messages.map((o,a)=>At(o,e.screenshot,e.window,Ft(e.messages,a))).filter((o,a)=>Bt(e.messages,a,e.mediaAnchorText)).filter(o=>o!=null);if(!t.length)return e.messages;const n=e.attachmentsDir??De(e.workDir||process.cwd(),e.runtime.runtimeId,e.binding.bindingId),r=await Ke({helper:e.helper,candidates:t,attachmentsDir:n,screenshot:e.screenshot,windowId:e.windowId,window:e.window,traceId:e.traceId,platform:e.runtime.policy.platform,stabilityCheck:async()=>{const o=await M({helper:e.helper,window:e.window,binding:e.binding,traceId:e.traceId});return o.ok?{ok:!0}:{ok:!1,reasonCode:o.reason}}});if(!r.length)return e.messages;const i=new Map(r.map(o=>[o.messageKey,o]));return e.messages.map(o=>{const a=i.get(o.stableMessageKey);return a?{...o,mediaMetadata:Lt(o.mediaMetadata,a.attachment,a.reasonCode,a.attemptReasonCodes,a.resolveTrace)}:o})}function Bt(e,t,n){const r=ge(n);if(!r)return!0;const i=Et(r),o=e.map((a,s)=>ge(Rt(a)).includes(r)?s:-1).filter(a=>a>=0);if(!o.length)return t===Wt(e,i);for(const a of o)if(t>=a&&t<=a+8||t===a-1&&!e.slice(a+1,Math.min(e.length,a+9)).some(be))return!0;return!1}function Et(e){return e.includes("video")||e.includes("vide0")?"video":e.includes("image")||e.includes("photo")||e.includes("ph0t0")||e.includes("picture")?"image":e.includes("file")||e.includes("document")?"file":null}function Wt(e,t=null){for(let n=e.length-1;n>=0;n-=1)if(be(e[n]))return Pt(e[n],t)?n:-1;return-1}function be(e){if(!e)return!1;const t=String(e.kind||"").toLowerCase(),n=b(e.mediaMetadata)?e.mediaMetadata:{},r=b(n.attachment)?n.attachment:{};return ye(t,n,r)}function Pt(e,t){if(!e||!t)return!0;const n=String(e.kind||"").toLowerCase(),r=b(e.mediaMetadata)?e.mediaMetadata:{},i=b(r.attachment)?r.attachment:{},o=String(i.type||"").toLowerCase(),a=String(i.mimeType||"").toLowerCase(),s=String(i.name||i.localPath||e.anchorText||e.textExcerpt||"").toLowerCase();return t==="video"?n.includes("video")||o==="video"||a.startsWith("video/")||/\.(mp4|mov|m4v|avi|mkv|webm)$/i.test(s):t==="image"?/image|photo|picture/.test(n)||o==="image"||a.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(s):/file|document/.test(n)||o==="file"||!/image|photo|picture|video/.test(n)&&o!=="image"&&o!=="video"&&!a.startsWith("image/")&&!a.startsWith("video/")}function Rt(e){if(!e)return"";const t=e;return[e.normalizedText,e.anchorText,e.textExcerpt,t.text].map(n=>String(n||"")).join(`
|
|
3
3
|
`)}function ge(e){return String(e||"").normalize("NFKC").replace(/[o]/giu,"0").replace(/[^\p{L}\p{N}]/gu,"").toLowerCase()}function Ft(e,t){return[e[t-1],e[t],e[t+1]].map(r=>r&&(r.normalizedText||r.anchorText||r.textExcerpt)||"").map(r=>String(r||"").trim()).filter(Boolean).join(`
|
|
4
|
-
`)||null}function At(e,t,n,r){const i=String(e.kind||"").toLowerCase(),o=b(e.mediaMetadata)?e.mediaMetadata:{},a=b(o.attachment)?o.attachment:{},s=f(a.availability)||f(o.availability),c=f(a.localPath)||f(o.localPath);if(s==="edge-local"&&c||!ye(i,o,a))return null;const l=L(e.bbox)??L(o.bbox)??L(o.downloadActionBbox),w=L(o.downloadActionBbox),u=xe(l,t,n),d=Kt(l,t,n),h=xe(w,t,n);return{messageKey:e.stableMessageKey,kind:f(a.type)||f(a.kind)||f(o.messageType)||i,fileName:f(a.name)||f(a.fileName)||f(o.fileName)||null,mimeType:f(a.mimeType)||f(o.mimeType)||null,size:_(a.size)??_(o.size),mediaStatus:Dt(o,a),observedAt:e.observedAt??null,contextText:r??e.normalizedText??e.anchorText??e.textExcerpt??null,...u?{bbox:u}:{},...d?{screenshotBbox:d}:{},...h?{downloadActionBbox:h}:{}}}function Lt(e,t,n,r,i){const o=b(e)?{...e}:{};return{...o,availability:b(t)?t.availability:o.availability,mediaStatus:b(t)&&t.availability==="edge-local"?"downloaded":o.mediaStatus,attachment:t,edgeResolveReasonCode:n,...r?.length?{edgeResolveAttempts:r}:{},...i?{edgeResolveTrace:i}:{}}}function Dt(e,t){const n=f(e.mediaStatus);if(n==="not_downloaded")return"not_downloaded";if(n==="loading"||n==="downloading"||n==="in_progress")return"loading";if(n==="downloaded"||n==="available")return"available";const r=f(t.availability)||f(e.availability);return r==="pending-download"?"not_downloaded":r==="metadata-only"?"metadata_only":n||null}function ye(e,t,n){const r=`${e} ${f(t.messageType)} ${f(n.type)} ${f(n.kind)}`.toLowerCase();return/image|photo|video|file|document/.test(r)}function L(e){if(!b(e))return null;const t=_(e.x),n=_(e.y),r=_(e.width),i=_(e.height);return t==null||n==null||r==null||i==null?null:{x:t,y:n,width:r,height:i,...typeof e.coordinateSpace=="string"?{coordinateSpace:e.coordinateSpace}:{}}}function xe(e,t,n){if(!e)return null;if(e.coordinateSpace==="screen")return e;const r=$(e,t,n);if(!r)return e;const i=n.bounds;if(!i?.width||!i?.height)return{...e,x:r.x-e.width/2,y:r.y-e.height/2,coordinateSpace:"screen"};const o=i.width/t.width,a=i.height/t.height,s=r.x,c=r.y;return{x:s-e.width*o/2,y:c-e.height*a/2,width:e.width*o,height:e.height*a,coordinateSpace:"screen"}}function Kt(e,t,n){if(!e)return null;if(e.coordinateSpace!=="screen")return{...e,coordinateSpace:"screenshotPixel"};const r=n.bounds;if(!r?.width||!r?.height)return null;const i=t.width/r.width,o=t.height/r.height;return{x:(e.x-r.x)*i,y:(e.y-r.y)*o,width:e.width*i,height:e.height*o,coordinateSpace:"screenshotPixel"}}function b(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function f(e){return typeof e=="string"?e.trim():""}function g(e){return f(e)||null}function _(e){const t=Number(e);return Number.isFinite(t)?t:null}async function Kn(e,t){await pe(e,t)}async function Ot(e,t){await ve(e,t)}async function ve(e,t){const n=await e.request("permissions.check",{},t);m(n,"permissions.check");const r=n.result??{};if(Vt(r.platform)){const i=await $t(e,r,t);if(i==="screen-recording")throw new Error("permission_screen_recording_missing");if(i==="accessibility")throw new Error("permission_accessibility_missing");if(i==="input-monitoring")throw new Error("permission_input_monitoring_missing");if(r.automation===!1)throw new Error("permission_automation_missing")}return r}async function pe(e,t,n={}){const r=await ve(e,t),i=String(r.platform??"").toLowerCase();if(r.wechatRunning===!1)throw new Error("wechat_not_running");if(Ht(r))throw new Error("windows_visible_desktop_unavailable");if(r.dpiMappingAvailable===!1||r.displayTopologySupported===!1)throw new Error("dpi_mapping_failed");if(r.wechatMainWindowResponsive===!1)throw new Error("wechat_window_unresponsive");if(r.wechatWindowAvailable===!1&&i!=="win32"&&n.allowUnavailableWindow!==!0)throw new Error("wechat_window_unavailable");return r}async function $t(e,t,n){const r=zt(t);if(!r||process.platform!=="darwin")return r;const i=qt(r);try{await e.request(i,{},n)}catch{}return r}function zt(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function Vt(e){const t=String(e||"").toLowerCase();return t?t.includes("darwin")||t.includes("mac"):!0}function qt(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}async function jt(e,t,n={}){const i=(n.foreground??"required")!=="background",o=await pe(e,t,{allowUnavailableWindow:i});if(String(o.platform??"").toLowerCase()==="win32"){const c=await e.request("windows.ensureReady",{activate:i,allowRecovery:!1,allowLaunch:!1},t);m(c,"windows.ensureReady");const l=c.result;if(!l?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return await Gt(e,l,t)}const a=await e.request("windows.ensureReady",{restore:i,focus:i},t);m(a,"windows.ensureReady");const s=a.result;if(!s?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return s}async function Gt(e,t,n){if(j(t.title))return t;try{const r=await e.request("windows.list",{},n);m(r,"windows.list");const o=(r.result?.windows??[]).find(a=>a.windowId&&a.visible!==!1&&a.minimized!==!0&&B(a)&&j(a.title));if(!o)return t;if(t.windowId&&t.windowId!==o.windowId)try{await e.request("windows.closeWindow",{windowId:t.windowId},n)}catch{}return o}catch{return t}}function j(e){const t=String(e??"").normalize("NFKC").trim().toLowerCase();return t==="\u5FAE\u4FE1"||t==="wechat"||t==="weixin"}function Ht(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function Ce(e){const t=e.filter(B),n=t.filter(i=>i.visible!==!1&&i.minimized!==!0);return(n.length?n:t)[0]??null}async function On(e,t){let n=await e.request("windows.list",{},t);m(n,"windows.list");let r=n.result?.windows??[],i=Ce(r);if(!i)throw new Error("wechat_window_not_found");const o=await e.request("windows.focus",{windowId:i.windowId},t);return m(o,"windows.focus"),await _e(e,i,t)}async function Ie(e,t,n){if(!t.windowId)throw new Error("wechat_window_not_found");const r=await e.request("windows.focus",{windowId:t.windowId},n);return m(r,"windows.focus"),t}async function Ut(e,t){const n=await e.request("windows.list",{},t);m(n,"windows.list");const r=n.result?.windows??[],i=Ce(r);if(!i)throw new Error("wechat_window_not_found");const o=await e.request("windows.focus",{windowId:i.windowId},t);return m(o,"windows.focus"),await _e(e,i,t)}async function _e(e,t,n){let r;try{r=await e.request("windows.list",{},n)}catch{return t}if(!r.ok)return t;const i=(r.result?.windows??[]).filter(B);return i.find(o=>o.windowId===t.windowId)??i[0]??t}async function G(e){const{capture:t,ocr:n}=e.observation??await k(e),r=W({capture:t,ocr:n,window:e.window});if(r)return{opened:!1,reason:r};const i=He({visibleItems:sn(n,t,e.allowOcrTitleRows!==!1),targets:[{bindingId:e.binding.bindingId,conversationDisplayName:e.binding.conversationDisplayName}]})[0];if(!i)return{opened:!1,reason:"conversation_not_visible"};const o=In(i.item.bbox,t,e.window);if(!o)return{opened:!1,reason:"conversation_bbox_missing"};const a=await e.helper.request("mouse.click",{x:o.x,y:o.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(a,"mouse.click"),{opened:!0,reason:i.reason}}async function H(e){let t={opened:!1,reason:"conversation_not_opened"};for(let r=0;r<Xe;r+=1){if(t=await Yt(e),t.opened||t.reason!=="conversation_title_not_confirmed")return t;await S(e,"open-retry",`retry:${r}`)}const n=await ke(e);return n.opened?{opened:!0,reason:`${n.reason}:final-visible-recovery`}:t}async function Yt(e){const t=await k(e),n=W({capture:t.capture,ocr:t.ocr,window:e.window});if(n)return{opened:!1,reason:n};let r=!1;if(O(t.ocr,t.capture,e.binding.conversationDisplayName))return e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId,observation:t}),{opened:!0,reason:"current-conversation-title-confirmed"};if(!r){const u=await G({...e,observation:t});if(u.opened){if(await S(e,"open-click-settle","visible-initial"),(await M(e)).ok)return{opened:!0,reason:u.reason};const h=await ke(e);if(h.opened)return h}}const i=await tn(e,t.capture);if(!i.ok)return{opened:!1,reason:i.reason};const o=await e.helper.request("wechat.searchConversation",{conversationName:e.binding.conversationDisplayName,windowId:e.window.windowId,waitMs:e.searchDelayMs??D(e,"search-input-settle","search-input"),searchPoint:i.point},e.traceId);m(o,"wechat.searchConversation");const a=await Xt(e);if(a.opened){await S(e,"open-click-settle","search-result-click");const u=await M(e);return u.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:a.reason}):{opened:!1,reason:u.reason}}let s=a.observation;const c=y(e.binding.conversationDisplayName)&&a.reason==="search_result_not_visible";if(!y(e.binding.conversationDisplayName)){await rn(e.helper,e.traceId),await S(e,"open-click-settle","search-return");const u=await M(e);if(u.ok)return e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:u.reason};const d=await e.helper.request("wechat.searchConversation",{conversationName:e.binding.conversationDisplayName,windowId:e.window.windowId,waitMs:e.searchDelayMs??D(e,"search-input-settle","search-input-retry-after-return"),searchPoint:i.point},e.traceId);m(d,"wechat.searchConversation"),s=void 0}const l=await G({...e,...s?{observation:s}:{},allowOcrTitleRows:!c});if(!l.opened)return l;await S(e,"open-click-settle","visible-final");const w=await M(e);return w.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:l.reason}):{opened:!1,reason:w.reason}}async function ke(e){const t=await G(e);if(!t.opened)return t;await S(e,"open-click-settle","visible-retry");const n=await M(e);return n.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:`${t.reason}:retry-visible-title-confirmed`}):{opened:!1,reason:n.reason}}async function Xt(e){let t;const n=e.searchDelayMs===0?0:D(e,"search-result-probe","search-result-probe"),r=y(e.binding.conversationDisplayName)?Je:1;for(let i=0;i<r;i+=1){i>0&&n>0&&await Y(n);const o=await Jt(e);t=o;const{capture:a,ocr:s}=o,c=W({capture:a,ocr:s,window:e.window});if(c)return{opened:!1,reason:c,observation:o};const l=ln(s,a,e.binding.conversationDisplayName);if(!l){if(un(s)||wn(s,e.binding.conversationDisplayName))break;continue}const w=$(l.bbox,a,Zt(a,e.window));if(!w)return{opened:!1,reason:"search_result_bbox_missing",observation:o};const u=await e.helper.request("mouse.click",{x:w.x,y:w.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(u,"mouse.click"),{opened:!0,reason:l.reason,observation:o}}return{opened:!1,reason:"search_result_not_visible",observation:t}}async function Jt(e){if(e.window.bounds&&y(e.binding.conversationDisplayName)){const t=await e.helper.request("screen.capture",{bounds:e.window.bounds},e.traceId);if(t.ok&&t.result?.dataBase64&&t.result.width&&t.result.height){const n={...t.result,windowId:e.window.windowId,bounds:t.result.bounds??e.window.bounds},r=await Me(e.helper,n,e.traceId);return{capture:n,ocr:r}}t.errorCode&&t.errorCode!=="helper_unknown_command"&&t.errorCode!=="helper_command_unsupported"&&m(t,"screen.capture")}return k(e)}function Zt(e,t){return e.bounds?{...t,bounds:e.bounds}:t}async function k(e){let{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds);return await Qt({helper:e.helper,window:e.window,capture:t,ocr:n,traceId:e.traceId})&&(await ee("preview-dismiss-settle",`${e.traceId||""}:${e.window.windowId}:preview-dismiss`),{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds)),{capture:t,ocr:n}}async function Qt(e){const t=en(e.ocr,e.capture,e.window);if(!t)return!1;for(const n of[async()=>e.helper.request("keyboard.shortcut",{key:"escape",modifiers:[]},e.traceId),async()=>e.helper.request("mouse.click",{x:t.x,y:t.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId)])if((await n()).ok)return!0;return!1}function en(e,t,n){const r=e.blocks??[],i=r.find(c=>{const l=String(c.text||""),w=c.bbox;if(!w)return!1;const u=Number(w.x),d=Number(w.y);return Number.isFinite(u)&&Number.isFinite(d)&&d>t.height*.06&&d<t.height*.22&&u>t.width*.3&&/查看原视频|查看原图|原视频|原图|视频|图片|图像/.test(l)});if(!i)return null;const o=i.bbox,a=Number(o?.y);if(!Number.isFinite(a))return null;const s=r.filter(c=>{const l=String(c.text||"").trim(),w=c.bbox;if(!w||l!=="\xD7")return!1;const u=Number(w.x),d=Number(w.y);return Number.isFinite(u)&&Number.isFinite(d)&&u>t.width*.55&&u<t.width*.9&&Math.abs(d-a)<t.height*.08}).sort((c,l)=>Number(l.bbox?.x??0)-Number(c.bbox?.x??0))[0];return $(s?.bbox,t,n)}async function tn(e,t){if(!e.runtime||!e.api?.classifyWindow)return{ok:!1,reason:"wechat_search_input_detector_unavailable"};try{return{ok:!0,point:await rt({runtime:e.runtime,binding:e.binding,helper:e.helper,api:e.api,workDir:e.workDir,traceId:e.traceId,window:e.window,...t.dataBase64?{screenshot:t}:{}})}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:"wechat_search_input_not_found"}}}async function T(e,t,n,r){const i=await e.request("windows.capture",{windowId:t,scope:"full-window",...r?{bounds:r}:{}},n);m(i,"windows.capture");const o=i.result;if(!o?.dataBase64||!o.mimeType||!o.width||!o.height)throw new Error("helper_invalid_response: windows.capture missing screenshot data");return o}async function Se(e){return e.capture.dataBase64?e.capture:T(e.helper,e.window.windowId,e.traceId,e.window.bounds)}async function U(e,t,n,r){const i=await e.request("windows.captureAndOcr",{windowId:t,scope:"full-window",...r?{bounds:r}:{}},n);if(i.ok&&i.result?.capture&&i.result?.ocr)return{capture:i.result.capture,ocr:i.result.ocr};!i.ok&&i.errorCode&&i.errorCode!=="helper_unknown_command"&&i.errorCode!=="helper_command_unsupported"&&m(i,"windows.captureAndOcr");const o=await T(e,t,n,r),a=await Me(e,o,n);return{capture:o,ocr:a}}async function Me(e,t,n){const r=await e.request("ocr.recognize",{mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height},n);return m(r,"ocr.recognize"),r.result??{}}function m(e,t){if(!e.ok)throw new Error(`${e.errorCode||"helper_command_failed"}: ${e.errorSummary||t}`)}function B(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"||t==="\u5FAE\u4FE1"}function Y(e){return new Promise(t=>setTimeout(t,e))}function D(e,t,n){return e.searchDelayMs===0?0:Ge(t,nn(e,n))}async function S(e,t,n){const r=D(e,t,n);r>0&&await Y(r)}function nn(e,t){return`${e.traceId||""}:${e.binding.conversationDisplayName}:${t}`}async function rn(e,t){const n=await e.request("keyboard.shortcut",{key:"return",modifiers:[]},t);m(n,"keyboard.shortcut")}async function E(e){if(!e.window.bounds)return;const t=e.observation,n=_n(t?.ocr,t?.capture,e.window);if(n){const r=await e.helper.request("mouse.click",{x:n.x,y:n.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);m(r,"mouse.click"),await ee("jump-latest-settle",`${e.traceId||""}:${e.window.windowId}:jump-latest`)}}async function M(e){const{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds),r=W({capture:t,ocr:n,window:e.window});return r?{ok:!1,reason:r}:O(n,t,e.binding.conversationDisplayName)?{ok:!0,reason:"target-conversation-title-confirmed"}:!on(n)&&await an({...e,capture:t})?{ok:!0,reason:"target-conversation-title-confirmed-by-vision"}:{ok:!1,reason:"conversation_title_not_confirmed"}}function on(e){return(e.blocks??[]).length>0?!0:String(e.text??"").trim().length>0}async function an(e){if(!e.runtime||!e.api?.classifyWindow)return!1;try{const t=e.capture.dataBase64?e.capture:await T(e.helper,e.window.windowId,e.traceId,e.window.bounds),n=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height,windowId:e.window.windowId},traceId:e.traceId});return n.windowKind!=="chat_main"||!(n.isTargetConversation===!0||z(n.conversationTitle,e.binding.conversationDisplayName))?!1:(ne({helper:e.helper,runtime:e.runtime,binding:e.binding,workDir:e.workDir,traceId:e.traceId,window:e.window,classification:n,screenshot:t}),!0)}catch{return!1}}function W(e){const n=(e.ocr.blocks??[]).map(r=>hn(r.text)).filter(Boolean).join("");return/(扫码登录|仅传输文件|重新登录|为了安全|安全验证|登录微信|微信登录|该账号已登录|帐号已登录|账号已登录|当前账号已登录|当前帐号已登录|已登录|进入微信|進入微信)/u.test(n)?Ze:null}function sn(e,t,n=!0){const r=n?cn(e.blocks??[],t):[];return r.length?r:e.visibleConversationFingerprints??[]}function cn(e,t){const n=e.map(i=>Ne(i)).filter(i=>!!i).filter(i=>i.text.length>=2).filter(i=>i.x>t.width*.08&&i.x<t.width*.38).filter(i=>i.y>t.height*.06&&i.y<t.height*.96).filter(i=>!Te(i.text)),r=new Set;return n.filter(i=>!dn(i,n,t)).sort((i,o)=>i.y-o.y||i.x-o.x).map(i=>{const o=i.text.trim();return{title:o,bbox:{x:Math.max(0,i.x-24),y:Math.max(0,i.y-Math.max(24,i.height)),width:Math.max(120,t.width*.3),height:Math.max(48,i.height+40),coordinateSpace:"screenshotPixel"},fingerprint:o.toLowerCase()}}).filter(i=>{const o=P(i.title);return!o||r.has(o)?!1:(r.add(o),!0)})}function Ne(e){const t=e.bbox,n=String(e.text||"").normalize("NFKC").trim(),r=Number(t?.x),i=Number(t?.y),o=Number(t?.width),a=Number(t?.height);return!n||![r,i,o,a].every(Number.isFinite)?null:{text:n,x:r,y:i,width:o,height:a}}function dn(e,t,n){const r=Math.max(36,Math.min(64,n.height*.058));return t.some(i=>i!==e&&i.y<e.y&&e.y-i.y<=r&&Math.abs(i.x-e.x)<=16&&i.height>=e.height*.85)}function Te(e){const t=p(e);return/^(搜索|微信|通讯录|收藏|设置|search)$/iu.test(t)||K(t)||fn(t)||/^包含[::]?/u.test(t)||/搜索网络结果/u.test(t)}function ln(e,t,n){const r=(e.blocks??[]).map(s=>Ne(s)).filter(s=>!!s),i=r.filter(s=>K(p(s.text))).sort((s,c)=>s.y-c.y||s.x-c.x),o=["\u7FA4\u804A","GroupChats","\u8054\u7CFB\u4EBA","Contacts"];for(const s of o){const c=i.findIndex(d=>p(d.text)===s);if(c<0)continue;const l=i[c],w=i[c+1]?.y??Number.POSITIVE_INFINITY,u=r.filter(d=>d.y>l.y&&d.y<w).filter(d=>d.x<t.width*.7).filter(d=>d.text.length>=2).filter(d=>!K(p(d.text))).filter(d=>!Ee(d,r)).filter(d=>z(d.text,n)).sort((d,h)=>d.y-h.y||d.x-h.x)[0];if(u)return{bbox:Be(u,t),reason:"search-result-title"}}const a=r.filter(s=>s.y>t.height*.12&&s.y<t.height*.82).filter(s=>s.x>t.width*.08&&s.x<t.width*.45).filter(s=>s.text.length>=2).filter(s=>!Te(s.text)).filter(s=>!Ee(s,r)).filter(s=>z(s.text,n)).sort((s,c)=>s.y-c.y||s.x-c.x)[0];return y(n)?null:a?{bbox:Be(a,t),reason:"search-result-title"}:null}function Be(e,t){return{x:Math.max(0,e.x-24),y:Math.max(0,e.y-12),width:Math.max(e.width+t.width*.18,160),height:Math.max(e.height+28,44),coordinateSpace:"screenshotPixel"}}function K(e){return/^(群聊|联系人|聊天记录|公众号|小程序|GroupChats|Contacts|ChatHistory|OfficialAccounts|MiniPrograms)$/u.test(e)}function un(e){return(e.blocks??[]).some(t=>K(p(t.text)))}function wn(e,t){return(e.visibleConversationFingerprints??[]).some(n=>z(n.title,t))}function p(e){return String(e||"").normalize("NFKC").replace(/[^\p{L}\p{N}_-]/gu,"").trim()}function Ee(e,t){return/^包含[::]?/u.test(e.text.trim())?!0:t.some(n=>n!==e&&Math.abs(n.y-e.y)<=Math.max(18,e.height)&&n.x<e.x&&/^包含[::]?/u.test(n.text.trim()))}function fn(e){const t=String(e||"").trim();return!!(/^(星期[一二三四五六日天]|周[一二三四五六日天])\s*\d{1,2}:\d{2}$/u.test(t)||/^\d{1,2}:\d{2}(?::\d{2})?$/u.test(t)||/^\d{4}[-/.年]\d{1,2}(?:[-/.月]\d{1,2}日?)?$/u.test(t)||/^\d{1,2}[-/.月]\d{1,2}日?$/u.test(t))}function hn(e){return String(e||"").normalize("NFKC").replace(/\s+/g,"").trim()}function O(e,t,n){const r=y(n)?P(n):V(n);return r?(e.blocks??[]).some(i=>{const o=y(n)?P(i.text):V(i.text);if(!o||!Re(o,r))return!1;const a=i.bbox;if(!a)return!1;const s=Number(a.x),c=Number(a.y);if(!Number.isFinite(s)||!Number.isFinite(c))return!1;const l=s>t.width*.32&&s<t.width*.78&&c<t.height*.16,w=s<t.width*.18&&c<t.height*.12;return l||w}):!1}function X(e){if(O(e.ocr,e.capture,e.binding.conversationDisplayName))return!1;const t=(e.ocr.blocks??[]).map(s=>String(s.text||"").normalize("NFKC").replace(/\s+/g," ").trim()).filter(Boolean),n=t.join(`
|
|
4
|
+
`)||null}function At(e,t,n,r){const i=String(e.kind||"").toLowerCase(),o=b(e.mediaMetadata)?e.mediaMetadata:{},a=b(o.attachment)?o.attachment:{},s=f(a.availability)||f(o.availability),c=f(a.localPath)||f(o.localPath);if(s==="edge-local"&&c||!ye(i,o,a))return null;const l=L(e.bbox)??L(o.bbox)??L(o.downloadActionBbox),w=L(o.downloadActionBbox),u=xe(l,t,n),d=Kt(l,t,n),h=xe(w,t,n);return{messageKey:e.stableMessageKey,kind:f(a.type)||f(a.kind)||f(o.messageType)||i,fileName:f(a.name)||f(a.fileName)||f(o.fileName)||null,mimeType:f(a.mimeType)||f(o.mimeType)||null,size:_(a.size)??_(o.size),mediaStatus:Dt(o,a),observedAt:e.observedAt??null,contextText:r??e.normalizedText??e.anchorText??e.textExcerpt??null,...u?{bbox:u}:{},...d?{screenshotBbox:d}:{},...h?{downloadActionBbox:h}:{}}}function Lt(e,t,n,r,i){const o=b(e)?{...e}:{};return{...o,availability:b(t)?t.availability:o.availability,mediaStatus:b(t)&&t.availability==="edge-local"?"downloaded":o.mediaStatus,attachment:t,edgeResolveReasonCode:n,...r?.length?{edgeResolveAttempts:r}:{},...i?{edgeResolveTrace:i}:{}}}function Dt(e,t){const n=f(e.mediaStatus);if(n==="not_downloaded")return"not_downloaded";if(n==="loading"||n==="downloading"||n==="in_progress")return"loading";if(n==="downloaded"||n==="available")return"available";const r=f(t.availability)||f(e.availability);return r==="pending-download"?"not_downloaded":r==="metadata-only"?"metadata_only":n||null}function ye(e,t,n){const r=`${e} ${f(t.messageType)} ${f(n.type)} ${f(n.kind)}`.toLowerCase();return/image|photo|video|file|document/.test(r)}function L(e){if(!b(e))return null;const t=_(e.x),n=_(e.y),r=_(e.width),i=_(e.height);return t==null||n==null||r==null||i==null?null:{x:t,y:n,width:r,height:i,...typeof e.coordinateSpace=="string"?{coordinateSpace:e.coordinateSpace}:{}}}function xe(e,t,n){if(!e)return null;if(e.coordinateSpace==="screen")return e;const r=$(e,t,n);if(!r)return e;const i=n.bounds;if(!i?.width||!i?.height)return{...e,x:r.x-e.width/2,y:r.y-e.height/2,coordinateSpace:"screen"};const o=i.width/t.width,a=i.height/t.height,s=r.x,c=r.y;return{x:s-e.width*o/2,y:c-e.height*a/2,width:e.width*o,height:e.height*a,coordinateSpace:"screen"}}function Kt(e,t,n){if(!e)return null;if(e.coordinateSpace!=="screen")return{...e,coordinateSpace:"screenshotPixel"};const r=n.bounds;if(!r?.width||!r?.height)return null;const i=t.width/r.width,o=t.height/r.height;return{x:(e.x-r.x)*i,y:(e.y-r.y)*o,width:e.width*i,height:e.height*o,coordinateSpace:"screenshotPixel"}}function b(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function f(e){return typeof e=="string"?e.trim():""}function g(e){return f(e)||null}function _(e){const t=Number(e);return Number.isFinite(t)?t:null}async function Kn(e,t){await pe(e,t)}async function Ot(e,t){await ve(e,t)}async function ve(e,t){const n=await e.request("permissions.check",{},t);m(n,"permissions.check");const r=n.result??{};if(Vt(r.platform)){const i=await $t(e,r,t);if(i==="screen-recording")throw new Error("permission_screen_recording_missing");if(i==="accessibility")throw new Error("permission_accessibility_missing");if(i==="input-monitoring")throw new Error("permission_input_monitoring_missing");if(r.automation===!1)throw new Error("permission_automation_missing")}return r}async function pe(e,t,n={}){const r=await ve(e,t),i=String(r.platform??"").toLowerCase();if(r.wechatRunning===!1)throw new Error("wechat_not_running");if(Ht(r))throw new Error("windows_visible_desktop_unavailable");if(r.dpiMappingAvailable===!1||r.displayTopologySupported===!1)throw new Error("dpi_mapping_failed");if(r.wechatMainWindowResponsive===!1)throw new Error("wechat_window_unresponsive");if(r.wechatWindowAvailable===!1&&i!=="win32"&&n.allowUnavailableWindow!==!0)throw new Error("wechat_window_unavailable");return r}async function $t(e,t,n){const r=zt(t);if(!r||process.platform!=="darwin")return r;const i=qt(r);try{await e.request(i,{},n)}catch{}return r}function zt(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function Vt(e){const t=String(e||"").toLowerCase();return t?t.includes("darwin")||t.includes("mac"):!0}function qt(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}async function jt(e,t,n={}){const i=(n.foreground??"required")!=="background",o=await pe(e,t,{allowUnavailableWindow:i});if(String(o.platform??"").toLowerCase()==="win32"){const c=await e.request("windows.ensureReady",{activate:i,allowRecovery:!1,allowLaunch:!1},t);m(c,"windows.ensureReady");const l=c.result;if(!l?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return await Gt(e,l,t)}const a=await e.request("windows.ensureReady",{restore:i,focus:i},t);m(a,"windows.ensureReady");const s=a.result;if(!s?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return s}async function Gt(e,t,n){if(j(t.title))return t;try{const r=await e.request("windows.list",{},n);m(r,"windows.list");const o=(r.result?.windows??[]).find(a=>a.windowId&&a.visible!==!1&&a.minimized!==!0&&B(a)&&j(a.title));if(!o)return t;if(t.windowId&&t.windowId!==o.windowId)try{await e.request("windows.closeWindow",{windowId:t.windowId},n)}catch{}return o}catch{return t}}function j(e){const t=String(e??"").normalize("NFKC").trim().toLowerCase();return t==="\u5FAE\u4FE1"||t==="wechat"||t==="weixin"}function Ht(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function Ce(e){const t=e.filter(B),n=t.filter(i=>i.visible!==!1&&i.minimized!==!0);return(n.length?n:t)[0]??null}async function On(e,t){let n=await e.request("windows.list",{},t);m(n,"windows.list");let r=n.result?.windows??[],i=Ce(r);if(!i)throw new Error("wechat_window_not_found");const o=await e.request("windows.focus",{windowId:i.windowId},t);return m(o,"windows.focus"),await _e(e,i,t)}async function Ie(e,t,n){if(!t.windowId)throw new Error("wechat_window_not_found");const r=await e.request("windows.focus",{windowId:t.windowId},n);return m(r,"windows.focus"),t}async function Ut(e,t){const n=await e.request("windows.list",{},t);m(n,"windows.list");const r=n.result?.windows??[],i=Ce(r);if(!i)throw new Error("wechat_window_not_found");const o=await e.request("windows.focus",{windowId:i.windowId},t);return m(o,"windows.focus"),await _e(e,i,t)}async function _e(e,t,n){let r;try{r=await e.request("windows.list",{},n)}catch{return t}if(!r.ok)return t;const i=(r.result?.windows??[]).filter(B);return i.find(o=>o.windowId===t.windowId)??i[0]??t}async function G(e){const{capture:t,ocr:n}=e.observation??await k(e),r=W({capture:t,ocr:n,window:e.window});if(r)return{opened:!1,reason:r};const i=He({visibleItems:sn(n,t,e.allowOcrTitleRows!==!1),targets:[{bindingId:e.binding.bindingId,conversationDisplayName:e.binding.conversationDisplayName}]})[0];if(!i)return{opened:!1,reason:"conversation_not_visible"};const o=In(i.item.bbox,t,e.window);if(!o)return{opened:!1,reason:"conversation_bbox_missing"};const a=await e.helper.request("mouse.click",{x:o.x,y:o.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(a,"mouse.click"),{opened:!0,reason:i.reason}}async function H(e){let t={opened:!1,reason:"conversation_not_opened"};for(let r=0;r<Xe;r+=1){if(t=await Yt(e),t.opened||t.reason!=="conversation_title_not_confirmed")return t;await S(e,"open-retry",`retry:${r}`)}const n=await ke(e);return n.opened?{opened:!0,reason:`${n.reason}:final-visible-recovery`}:t}async function Yt(e){const t=await k(e),n=W({capture:t.capture,ocr:t.ocr,window:e.window});if(n)return{opened:!1,reason:n};let r=!1;if(O(t.ocr,t.capture,e.binding.conversationDisplayName))return e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId,observation:t}),{opened:!0,reason:"current-conversation-title-confirmed"};if(!r){const u=await G({...e,observation:t});if(u.opened){if(await S(e,"open-click-settle","visible-initial"),(await M(e)).ok)return{opened:!0,reason:u.reason};const h=await ke(e);if(h.opened)return h}}const i=await tn(e,t.capture);if(!i.ok)return{opened:!1,reason:i.reason};const o=await e.helper.request("wechat.searchConversation",{conversationName:e.binding.conversationDisplayName,windowId:e.window.windowId,waitMs:e.searchDelayMs??D(e,"search-input-settle","search-input"),searchPoint:i.point},e.traceId);m(o,"wechat.searchConversation");const a=await Xt(e);if(a.opened){await S(e,"open-click-settle","search-result-click");const u=await M(e);return u.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:a.reason}):{opened:!1,reason:u.reason}}let s=a.observation;const c=y(e.binding.conversationDisplayName)&&a.reason==="search_result_not_visible";if(!y(e.binding.conversationDisplayName)){await rn(e.helper,e.traceId),await S(e,"open-click-settle","search-return");const u=await M(e);if(u.ok)return e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:u.reason};const d=await e.helper.request("wechat.searchConversation",{conversationName:e.binding.conversationDisplayName,windowId:e.window.windowId,waitMs:e.searchDelayMs??D(e,"search-input-settle","search-input-retry-after-return"),searchPoint:i.point},e.traceId);m(d,"wechat.searchConversation"),s=void 0}const l=await G({...e,...s?{observation:s}:{},allowOcrTitleRows:!c});if(!l.opened)return l;await S(e,"open-click-settle","visible-final");const w=await M(e);return w.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:l.reason}):{opened:!1,reason:w.reason}}async function ke(e){const t=await G(e);if(!t.opened)return t;await S(e,"open-click-settle","visible-retry");const n=await M(e);return n.ok?(e.settleToBottom===!0&&await E({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:`${t.reason}:retry-visible-title-confirmed`}):{opened:!1,reason:n.reason}}async function Xt(e){let t;const n=e.searchDelayMs===0?0:D(e,"search-result-probe","search-result-probe"),r=y(e.binding.conversationDisplayName)?Je:1;for(let i=0;i<r;i+=1){i>0&&n>0&&await Y(n);const o=await Jt(e);t=o;const{capture:a,ocr:s}=o,c=W({capture:a,ocr:s,window:e.window});if(c)return{opened:!1,reason:c,observation:o};const l=ln(s,a,e.binding.conversationDisplayName);if(!l){if(un(s)||wn(s,e.binding.conversationDisplayName))break;continue}const w=$(l.bbox,a,Zt(a,e.window));if(!w)return{opened:!1,reason:"search_result_bbox_missing",observation:o};const u=await e.helper.request("mouse.click",{x:w.x,y:w.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(u,"mouse.click"),{opened:!0,reason:l.reason,observation:o}}return{opened:!1,reason:"search_result_not_visible",observation:t}}async function Jt(e){if(e.window.bounds&&y(e.binding.conversationDisplayName)){const t=await e.helper.request("screen.capture",{bounds:e.window.bounds},e.traceId);if(t.ok&&t.result?.dataBase64&&t.result.width&&t.result.height){const n={...t.result,windowId:e.window.windowId,bounds:t.result.bounds??e.window.bounds},r=await Me(e.helper,n,e.traceId);return{capture:n,ocr:r}}t.errorCode&&t.errorCode!=="helper_unknown_command"&&t.errorCode!=="helper_command_unsupported"&&m(t,"screen.capture")}return k(e)}function Zt(e,t){return e.bounds?{...t,bounds:e.bounds}:t}async function k(e){let{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds);return await Qt({helper:e.helper,window:e.window,capture:t,ocr:n,traceId:e.traceId})&&(await ee("preview-dismiss-settle",`${e.traceId||""}:${e.window.windowId}:preview-dismiss`),{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds)),{capture:t,ocr:n}}async function Qt(e){const t=en(e.ocr,e.capture,e.window);if(!t)return!1;for(const n of[async()=>e.helper.request("keyboard.shortcut",{key:"escape",modifiers:[]},e.traceId),async()=>e.helper.request("mouse.click",{x:t.x,y:t.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId)])if((await n()).ok)return!0;return!1}function en(e,t,n){const r=e.blocks??[],i=r.find(c=>{const l=String(c.text||""),w=c.bbox;if(!w)return!1;const u=Number(w.x),d=Number(w.y);return Number.isFinite(u)&&Number.isFinite(d)&&d>t.height*.06&&d<t.height*.22&&u>t.width*.3&&/查看原视频|查看原图|原视频|原图|视频|图片|图像/.test(l)});if(!i)return null;const o=i.bbox,a=Number(o?.y);if(!Number.isFinite(a))return null;const s=r.filter(c=>{const l=String(c.text||"").trim(),w=c.bbox;if(!w||l!=="\xD7")return!1;const u=Number(w.x),d=Number(w.y);return Number.isFinite(u)&&Number.isFinite(d)&&u>t.width*.55&&u<t.width*.9&&Math.abs(d-a)<t.height*.08}).sort((c,l)=>Number(l.bbox?.x??0)-Number(c.bbox?.x??0))[0];return $(s?.bbox,t,n)}async function tn(e,t){if(!e.runtime||!e.api?.classifyWindow)return{ok:!1,reason:"wechat_search_input_detector_unavailable"};try{return{ok:!0,point:await rt({runtime:e.runtime,binding:e.binding,helper:e.helper,api:e.api,workDir:e.workDir,traceId:e.traceId,window:e.window,...t.dataBase64?{screenshot:t}:{}})}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:"wechat_search_input_not_found"}}}async function T(e,t,n,r){const i=await e.request("windows.capture",{windowId:t,scope:"full-window",...r?{bounds:r}:{}},n);m(i,"windows.capture");const o=i.result;if(!o?.dataBase64||!o.mimeType||!o.width||!o.height)throw new Error("helper_invalid_response: windows.capture missing screenshot data");return o}async function Se(e){return e.capture.dataBase64?e.capture:T(e.helper,e.window.windowId,e.traceId,e.window.bounds)}async function U(e,t,n,r){const i=await e.request("windows.captureAndOcr",{windowId:t,scope:"full-window",...r?{bounds:r}:{}},n);if(i.ok&&i.result?.capture&&i.result?.ocr)return{capture:i.result.capture,ocr:i.result.ocr};!i.ok&&i.errorCode&&i.errorCode!=="helper_unknown_command"&&i.errorCode!=="helper_command_unsupported"&&m(i,"windows.captureAndOcr");const o=await T(e,t,n,r),a=await Me(e,o,n);return{capture:o,ocr:a}}async function Me(e,t,n){const r=await e.request("ocr.recognize",{mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height},n);return m(r,"ocr.recognize"),r.result??{}}function m(e,t){if(!e.ok)throw new Error(`${e.errorCode||"helper_command_failed"}: ${e.errorSummary||t}`)}function B(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"||t==="\u5FAE\u4FE1"}function Y(e){return new Promise(t=>setTimeout(t,e))}function D(e,t,n){return e.searchDelayMs===0?0:Ge(t,nn(e,n))}async function S(e,t,n){const r=D(e,t,n);r>0&&await Y(r)}function nn(e,t){return`${e.traceId||""}:${e.binding.conversationDisplayName}:${t}`}async function rn(e,t){const n=await e.request("keyboard.shortcut",{key:"return",modifiers:[]},t);m(n,"keyboard.shortcut")}async function E(e){if(!e.window.bounds)return;const t=e.observation,n=_n(t?.ocr,t?.capture,e.window);if(n){const r=await e.helper.request("mouse.click",{x:n.x,y:n.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);m(r,"mouse.click"),await ee("jump-latest-settle",`${e.traceId||""}:${e.window.windowId}:jump-latest`)}}async function M(e){const{capture:t,ocr:n}=await U(e.helper,e.window.windowId,e.traceId,e.window.bounds),r=W({capture:t,ocr:n,window:e.window});return r?{ok:!1,reason:r}:O(n,t,e.binding.conversationDisplayName)?{ok:!0,reason:"target-conversation-title-confirmed"}:!on(n)&&await an({...e,capture:t})?{ok:!0,reason:"target-conversation-title-confirmed-by-vision"}:{ok:!1,reason:"conversation_title_not_confirmed"}}function on(e){return(e.blocks??[]).length>0?!0:String(e.text??"").trim().length>0}async function an(e){if(!e.runtime||!e.api?.classifyWindow)return!1;try{const t=e.capture.dataBase64?e.capture:await T(e.helper,e.window.windowId,e.traceId,e.window.bounds),n=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:t.mimeType,dataBase64:t.dataBase64,width:t.width,height:t.height,windowId:e.window.windowId},traceId:e.traceId});return n.windowKind!=="chat_main"||!(n.isTargetConversation===!0||z(n.conversationTitle,e.binding.conversationDisplayName))?!1:(ne({helper:e.helper,runtime:e.runtime,binding:e.binding,workDir:e.workDir,traceId:e.traceId,window:e.window,classification:n,screenshot:t}),!0)}catch{return!1}}function W(e){const t=(e.ocr.blocks??[]).map(r=>hn(r.text)).filter(Boolean);if(t.length===0)return null;const n=t.join("");return/(扫码登录|仅传输文件|重新登录|为了安全|安全验证|登录微信|微信登录|该账号已登录|帐号已登录|账号已登录|当前账号已登录|当前帐号已登录|进入微信|進入微信)/u.test(n)?Ze:null}function sn(e,t,n=!0){const r=n?cn(e.blocks??[],t):[];return r.length?r:e.visibleConversationFingerprints??[]}function cn(e,t){const n=e.map(i=>Ne(i)).filter(i=>!!i).filter(i=>i.text.length>=2).filter(i=>i.x>t.width*.08&&i.x<t.width*.38).filter(i=>i.y>t.height*.06&&i.y<t.height*.96).filter(i=>!Te(i.text)),r=new Set;return n.filter(i=>!dn(i,n,t)).sort((i,o)=>i.y-o.y||i.x-o.x).map(i=>{const o=i.text.trim();return{title:o,bbox:{x:Math.max(0,i.x-24),y:Math.max(0,i.y-Math.max(24,i.height)),width:Math.max(120,t.width*.3),height:Math.max(48,i.height+40),coordinateSpace:"screenshotPixel"},fingerprint:o.toLowerCase()}}).filter(i=>{const o=P(i.title);return!o||r.has(o)?!1:(r.add(o),!0)})}function Ne(e){const t=e.bbox,n=String(e.text||"").normalize("NFKC").trim(),r=Number(t?.x),i=Number(t?.y),o=Number(t?.width),a=Number(t?.height);return!n||![r,i,o,a].every(Number.isFinite)?null:{text:n,x:r,y:i,width:o,height:a}}function dn(e,t,n){const r=Math.max(36,Math.min(64,n.height*.058));return t.some(i=>i!==e&&i.y<e.y&&e.y-i.y<=r&&Math.abs(i.x-e.x)<=16&&i.height>=e.height*.85)}function Te(e){const t=p(e);return/^(搜索|微信|通讯录|收藏|设置|search)$/iu.test(t)||K(t)||fn(t)||/^包含[::]?/u.test(t)||/搜索网络结果/u.test(t)}function ln(e,t,n){const r=(e.blocks??[]).map(s=>Ne(s)).filter(s=>!!s),i=r.filter(s=>K(p(s.text))).sort((s,c)=>s.y-c.y||s.x-c.x),o=["\u7FA4\u804A","GroupChats","\u8054\u7CFB\u4EBA","Contacts"];for(const s of o){const c=i.findIndex(d=>p(d.text)===s);if(c<0)continue;const l=i[c],w=i[c+1]?.y??Number.POSITIVE_INFINITY,u=r.filter(d=>d.y>l.y&&d.y<w).filter(d=>d.x<t.width*.7).filter(d=>d.text.length>=2).filter(d=>!K(p(d.text))).filter(d=>!Ee(d,r)).filter(d=>z(d.text,n)).sort((d,h)=>d.y-h.y||d.x-h.x)[0];if(u)return{bbox:Be(u,t),reason:"search-result-title"}}const a=r.filter(s=>s.y>t.height*.12&&s.y<t.height*.82).filter(s=>s.x>t.width*.08&&s.x<t.width*.45).filter(s=>s.text.length>=2).filter(s=>!Te(s.text)).filter(s=>!Ee(s,r)).filter(s=>z(s.text,n)).sort((s,c)=>s.y-c.y||s.x-c.x)[0];return y(n)?null:a?{bbox:Be(a,t),reason:"search-result-title"}:null}function Be(e,t){return{x:Math.max(0,e.x-24),y:Math.max(0,e.y-12),width:Math.max(e.width+t.width*.18,160),height:Math.max(e.height+28,44),coordinateSpace:"screenshotPixel"}}function K(e){return/^(群聊|联系人|聊天记录|公众号|小程序|GroupChats|Contacts|ChatHistory|OfficialAccounts|MiniPrograms)$/u.test(e)}function un(e){return(e.blocks??[]).some(t=>K(p(t.text)))}function wn(e,t){return(e.visibleConversationFingerprints??[]).some(n=>z(n.title,t))}function p(e){return String(e||"").normalize("NFKC").replace(/[^\p{L}\p{N}_-]/gu,"").trim()}function Ee(e,t){return/^包含[::]?/u.test(e.text.trim())?!0:t.some(n=>n!==e&&Math.abs(n.y-e.y)<=Math.max(18,e.height)&&n.x<e.x&&/^包含[::]?/u.test(n.text.trim()))}function fn(e){const t=String(e||"").trim();return!!(/^(星期[一二三四五六日天]|周[一二三四五六日天])\s*\d{1,2}:\d{2}$/u.test(t)||/^\d{1,2}:\d{2}(?::\d{2})?$/u.test(t)||/^\d{4}[-/.年]\d{1,2}(?:[-/.月]\d{1,2}日?)?$/u.test(t)||/^\d{1,2}[-/.月]\d{1,2}日?$/u.test(t))}function hn(e){return String(e||"").normalize("NFKC").replace(/\s+/g,"").trim()}function O(e,t,n){const r=y(n)?P(n):V(n);return r?(e.blocks??[]).some(i=>{const o=y(n)?P(i.text):V(i.text);if(!o||!Re(o,r))return!1;const a=i.bbox;if(!a)return!1;const s=Number(a.x),c=Number(a.y);if(!Number.isFinite(s)||!Number.isFinite(c))return!1;const l=s>t.width*.32&&s<t.width*.78&&c<t.height*.16,w=s<t.width*.18&&c<t.height*.12;return l||w}):!1}function X(e){if(O(e.ocr,e.capture,e.binding.conversationDisplayName))return!1;const t=(e.ocr.blocks??[]).map(s=>String(s.text||"").normalize("NFKC").replace(/\s+/g," ").trim()).filter(Boolean),n=t.join(`
|
|
5
5
|
`),i=[{pattern:/UTF-?8/iu,source:n},{pattern:/Unix\s*\(LF\)/iu,source:n},{pattern:/纯文本/u,source:n},{pattern:/\d+\s*个字符/u,source:n},{pattern:/\bH1\b/u,source:n},{pattern:/^查看$/u,source:t}].reduce((s,c)=>{const l=Array.isArray(c.source)?c.source.some(w=>c.pattern.test(w)):c.pattern.test(c.source);return s+(l?1:0)},0);if(i>=2)return!0;const o=(e.ocr.blocks??[]).filter(s=>Number(s.bbox?.y)<e.capture.height*.14).map(s=>String(s.text||"")).join(`
|
|
6
6
|
`);return/\.(txt|md|rtf|docx?|pdf)\b/i.test(o)&&i>=1||/\.(png|jpe?g|gif|webp|bmp|heic|mp4|mov|m4v|avi|mkv|webm)\b/i.test(o)&&mn(e.capture,e.ocr)?!0:((e.ocr.visibleConversationFingerprints??[]).some(s=>{const c=y(e.binding.conversationDisplayName)?P(s.title):V(s.title),l=y(e.binding.conversationDisplayName)?P(e.binding.conversationDisplayName):V(e.binding.conversationDisplayName);return!!(c&&l&&Re(c,l))}),!1)}function mn(e,t){const n=(t.blocks??[]).map(o=>String(o.text||"").normalize("NFKC").trim()).filter(Boolean),r=n.join(`
|
|
7
7
|
`);if(/\b\d+\s*x\s*\d+\b/i.test(r)&&/\b\d+(\.\d+)?\s*(B|KB|MB|GB)\b/i.test(r)||/\b100%\b/.test(r)&&n.length<=20)return!0;const i=n.filter(o=>!/^(□|×|\+|…|\.\.\.|100%|\d+|发送)$/u.test(o));return e.width>600&&e.height>500&&i.length<=6}function We(e){const t=e.anchors.map(o=>({...o,normalized:v(o.expectedEchoAnchor)})).filter(o=>o.normalized);if(!t.length)return[];const n=[],r=new Set,i=bn(e.ocr,e.screenshot).sort((o,a)=>v(a.text).length-v(o.text).length);for(const o of i){const a=v(o.text);if(!a)continue;const s=t.find(l=>gn(l.normalized,a));if(!s)continue;const c=`local-outbound-echo:${e.binding.bindingId}:${s.idempotencyKey||s.replyId||s.normalized}`;r.has(c)||(r.add(c),n.push({stableMessageKey:c,senderRole:"self",kind:"text",normalizedText:a,anchorText:a,textExcerpt:o.text.trim(),bbox:o.bbox??null,observedAt:new Date().toISOString(),deliveryStatus:"suppressed"}))}return n}function bn(e,t){const n=(e.blocks??[]).filter(i=>Cn(i,t)&&v(i.text)).sort((i,o)=>C(i.bbox,"y")-C(o.bbox,"y")),r=n.map(i=>({text:String(i.text||"").trim(),bbox:i.bbox}));for(let i=0;i<n.length;i+=1){const o=[n[i]];for(let a=i+1;a<n.length&&o.length<5;a+=1){const s=n[a];if(!yn(o[o.length-1],s,t))break;o.push(s),r.push({text:xn(o.map(c=>String(c.text||"").trim())),bbox:pn(o.map(c=>c.bbox))})}}return r}function gn(e,t){if(!e||!t)return!1;if(te(e,t)>=.88)return!0;const n=e.replace(/\s+/g,""),r=t.replace(/\s+/g,"");return r.length>=8&&n.includes(r)}function yn(e,t,n){const r=C(e.bbox,"x"),i=C(e.bbox,"y"),o=C(e.bbox,"height"),a=C(t.bbox,"x"),s=C(t.bbox,"y");if(![r,i,o,a,s].every(Number.isFinite)||r<n.width*.5||a<n.width*.5)return!1;const c=s-(i+o);return c>=-8&&c<=Math.max(64,n.height*.04)&&Math.abs(a-r)<=120}function xn(e){return e.reduce((t,n)=>t?n?`${t}${vn(t,n)?" ":""}${n}`:t:n,"")}function vn(e,t){return/[A-Za-z0-9]$/u.test(e)&&/^[A-Za-z0-9]/u.test(t)}function pn(e){const t=e.filter(c=>!!c);if(!t.length)return;const n=t.map(c=>Number(c.x)).filter(Number.isFinite),r=t.map(c=>Number(c.y)).filter(Number.isFinite),i=t.map(c=>Number(c.x)+Number(c.width)).filter(Number.isFinite),o=t.map(c=>Number(c.y)+Number(c.height)).filter(Number.isFinite);if(!n.length||!r.length||!i.length||!o.length)return t[0];const a=Math.min(...n),s=Math.min(...r);return{x:a,y:s,width:Math.max(...i)-a,height:Math.max(...o)-s,coordinateSpace:t.find(c=>c.coordinateSpace)?.coordinateSpace}}function C(e,t){const n=Number(e?.[t]);return Number.isFinite(n)?n:Number.NaN}function Pe(e,t){if(!t.length)return e;const n=[...e];for(const r of t){const i=v(r.anchorText||r.normalizedText||r.textExcerpt);n.some(a=>{if(a.senderRole!=="self")return!1;const s=v(a.anchorText||a.normalizedText||a.textExcerpt);return s&&i&&te(s,i)>=.9})||n.push(r)}return n}function Cn(e,t){const n=e.bbox;if(!n)return!1;const r=Number(n.x),i=Number(n.y);return!Number.isFinite(r)||!Number.isFinite(i)?!1:r>t.width*.34&&r<t.width*.96&&i>t.height*.12&&i<t.height*.86}function In(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),a=Number(r.width),s=Number(r.height);if(![i,o,a,s].every(Number.isFinite))return null;const c=typeof r.coordinateSpace=="string"?r.coordinateSpace:void 0,l=t.width&&n.bounds?.width?t.width/n.bounds.width:1,w=t.height&&n.bounds?.height?t.height/n.bounds.height:l,u={x:i+Math.min(a*.35,110*l),y:o+Math.min(s-8*w,Math.max(18*w,s/2))};if(c==="screen"||!n.bounds)return u;const d=Math.max(0,(t.width-n.bounds.width*l)/2),h=Math.max(0,(t.height-n.bounds.height*w)/2);return{x:n.bounds.x+(u.x-d)/l,y:n.bounds.y+(u.y-h)/w}}function $(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),a=Number(r.width),s=Number(r.height);if(![i,o,a,s].every(Number.isFinite))return null;const c=typeof r.coordinateSpace=="string"?r.coordinateSpace:void 0,l={x:i+a/2,y:o+s/2};if(c==="screen"||!n.bounds)return l;const w=t.width&&n.bounds.width?t.width/n.bounds.width:1,u=t.height&&n.bounds.height?t.height/n.bounds.height:w,d=Math.max(0,(t.width-n.bounds.width*w)/2),h=Math.max(0,(t.height-n.bounds.height*u)/2);return{x:n.bounds.x+(l.x-d)/w,y:n.bounds.y+(l.y-h)/u}}function _n(e,t,n){if(!e?.blocks?.length||!t)return null;const r=e.blocks.find(i=>{const o=String(i.text||"").trim(),a=i.bbox;if(!a||!o)return!1;const s=Number(a.x),c=Number(a.y);return!Number.isFinite(s)||!Number.isFinite(c)||!/跳转到最新消息|回到最新消息|jump\s+to\s+latest/i.test(o)?!1:s>t.width*.55&&c>t.height*.45&&c<t.height*.92});return $(r?.bbox,t,n)}function Re(e,t){return y(t)?Ae(e,t):e===t||e.includes(t)||t.includes(e)}function z(e,t){if(y(t))return Ae(e,t);const n=Fe(p(e)),r=Fe(p(t));return!n||!r?!1:n===r?!0:n.replace(/\d+$/u,"")===r}function Fe(e){return e.toLowerCase().replace(/[l1]/g,"i")}function V(e){return String(e||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").replace(/[l1]/gi,"i").toLowerCase().trim()}function P(e){return String(e||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").trim()}function y(e){const t=String(e||"").trim();return/^[A-Z0-9_-]{1,6}$/.test(t)&&/[A-Z]/.test(t)}function Ae(e,t){const n=String(e||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").trim(),r=String(t||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").trim();return!!(n&&r&&(n===r||n.replace(/\d+$/u,"")===r))}export{N as WeChatChannelUserActivityAbort,U as captureAndRecognizeWeChatWindow,T as captureWeChatWindow,Ln as detectWeChatMessageInputPointByServerVision,rt as detectWeChatSearchInputPointByServerVision,Ot as ensureHelperPermissionPreflight,Kn as ensureHelperPreflight,jt as ensureWeChatWindowReady,Ut as focusExistingWeChatWindow,Ie as focusKnownWeChatWindow,On as focusWeChatWindow,An as observeWeChatChannelBindingViaHelper,H as openConversationBySearch,G as openConversationInVisibleList,Me as recognizeWeChatScreenshot,tt as selectWeChatWindowForBinding};
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import C from"node:crypto";import p from"node:fs";import y from"node:path";import{loadConfig as W}from"../../config/index.js";import{createWeChatChannelProductRunner as $}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as O}from"../wechat-channel/client.js";import{createWeChatAutomationLane as k}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as b,saveWeChatChannelOutboundLedger as S}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as P}from"../wechat-channel/ledger.js";const j="wechat-channel";function fe(e){const t=D({runtimeId:e.config.id,machineId:ee(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:E(e.secret.forceForeground),bindings:q(e.config,e.secret)}),n=x(e.config.workDir,t.runtimeId),o=f(e.config.workDir,t.runtimeId),r=F(e.config.workDir,t.runtimeId),a=[];p.mkdirSync(y.dirname(r),{recursive:!0}),p.writeFileSync(r,"");const
|
|
1
|
+
import C from"node:crypto";import p from"node:fs";import y from"node:path";import{loadConfig as W}from"../../config/index.js";import{createWeChatChannelProductRunner as $}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as O}from"../wechat-channel/client.js";import{createWeChatAutomationLane as k}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as b,saveWeChatChannelOutboundLedger as S}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as P}from"../wechat-channel/ledger.js";const j="wechat-channel";function fe(e){const t=D({runtimeId:e.config.id,machineId:ee(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:E(e.secret.forceForeground),bindings:q(e.config,e.secret)}),n=x(e.config.workDir,t.runtimeId),o=f(e.config.workDir,t.runtimeId),r=F(e.config.workDir,t.runtimeId),a=[];p.mkdirSync(y.dirname(r),{recursive:!0}),p.writeFileSync(r,"");const s=e.createRunner??$,l=z(),u=s({runtime:t,workDir:e.config.workDir,api:l,ledgerPath:n,outboundLedgerPath:o,lane:k(),helperRequestLogger:B(r),onInboundMessages:(h,c)=>{const m=t.bindings.find(N=>N.bindingId===h.bindingId)??h,g=v(e.config,m,c);if(!g)return;const M=e.onMessage?.({...g,managerSessionId:e.config.managerSessionId})??g;a.push(M)}});return{runtime:t,runner:u,emitted:a,ledgerPath:n,outboundLedgerPath:o,helperTracePath:r}}function z(){let e=null;const t=()=>(e??=O(),e);return{observe:(...n)=>t().observe(...n),structureWindow:(...n)=>t().structureWindow(...n),embedVisual:(...n)=>t().embedVisual(...n),classifyWindow:(...n)=>t().classifyWindow(...n),upsertRuntime:async(...n)=>(await Promise.resolve().then(()=>t().upsertRuntime(...n)).catch(()=>null),{ok:!0}),ingest:async(...n)=>(await Promise.resolve().then(()=>t().ingest(...n)).catch(()=>null),{ok:!0}),reportRunStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportRunStatus(...n)).catch(()=>null),{ok:!0}),reportOutboundStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportOutboundStatus(...n)).catch(()=>null),{ok:!0})}}function E(e){return e===!1?"polite":"work"}function he(e){const t=e.config.id,n=R(e.config,e.conversationName),o=P(x(e.config.workDir,t),t),r=f(e.config.workDir,t),a=b(r,t),s=e.reply.attachment?[X(e.reply.attachment)]:[],l=K({ledger:a,replyId:e.reply.messageId||e.reply.idempotencyKey||d("wechat-channel-reply",`${Date.now()}:${e.reply.text}`),idempotencyKey:e.reply.idempotencyKey||d("wechat-channel-send",`${e.config.id}
|
|
2
2
|
${e.reply.conversationId}
|
|
3
3
|
${e.reply.text}
|
|
4
|
-
${
|
|
5
|
-
`)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:o.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:
|
|
4
|
+
${s.join(`
|
|
5
|
+
`)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:o.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:s});return S(r,a),l}function ge(e){return b(f(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).length}function pe(e){return b(f(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).slice(0,100).map(n=>({replyId:n.replyId,idempotencyKey:n.idempotencyKey,status:n.sendStatus,conversationName:n.conversationName,reasonCode:n.deferReason||n.failureCode||null,nextAttemptAt:n.nextAttemptAt??null,queuedAt:n.queuedAt??n.createdAt,lastAttemptAt:n.lastAttemptAt??null,attemptCount:n.attemptCount??0,commitStage:n.commitStage??null}))}function ye(e){const t=ne(e.limit,20,1,100),n=P(e.product.ledgerPath,e.product.runtime.runtimeId),o=[];for(const r of e.product.runtime.bindings){const a=(n.bindings[r.bindingId]?.recent??[]).filter(s=>s.senderRole!=="self");for(const s of a.slice(-t)){const l=A(e.config,r,s);l&&o.push(l)}}return o}function be(e){const t=f(e.config.workDir,e.config.id),n=b(t,e.config.id),o=String(e.idempotencyKey??"").trim(),r=String(e.replyId??"").trim();if(!o&&!r)return{cancelled:!1};const a=n.records.find(l=>o&&l.idempotencyKey===o||r&&l.replyId===r);if(!a)return{cancelled:!1};const s=a.sendStatus;return T(a,e.reason||"user_cancelled"),a.sendStatus!==s?(S(t,n),{cancelled:!0,status:a.sendStatus,record:a}):{cancelled:!1,status:a.sendStatus,record:a}}function we(e){return e===j}function L(e){return d("wechat-conversation",i(e))}function _(e,t){return d("wechat-channel-binding",`${e}
|
|
6
6
|
${i(t)}`)}function x(e,t){return y.join(e,"wechat-channel",`${I(t)}.ledger.json`)}function f(e,t){return y.join(e,"wechat-channel",`${I(t)}.outbound-ledger.json`)}function F(e,t){return y.join(e,"wechat-channel",`${I(t)}.helper-trace.jsonl`)}function I(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}function B(e){return t=>{p.appendFileSync(e,`${JSON.stringify(H(t))}
|
|
7
|
-
`)}}function H(e){const t={phase:e.phase,at:e.at,id:e.id,command:e.command};return e.traceId&&(t.traceId=e.traceId),e.timeoutMs!=null&&(t.timeoutMs=e.timeoutMs),e.durationMs!=null&&(t.durationMs=e.durationMs),e.params!==void 0&&(t.params=w(e.params)),e.ok!==void 0&&(t.ok=e.ok),e.errorCode&&(t.errorCode=e.errorCode),e.errorSummary&&(t.errorSummary=e.errorSummary),e.latencyMs!=null&&(t.latencyMs=e.latencyMs),e.result!==void 0&&(t.result=w(e.result)),t}function w(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return e.length>240||/(base64|bytes|data|image|screenshot|png|jpeg|jpg|buffer)/i.test(t)&&e.length>48?{type:"string",length:e.length,sha256:C.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const a=e.slice(0,10).map(
|
|
7
|
+
`)}}function H(e){const t={phase:e.phase,at:e.at,id:e.id,command:e.command};return e.traceId&&(t.traceId=e.traceId),e.timeoutMs!=null&&(t.timeoutMs=e.timeoutMs),e.durationMs!=null&&(t.durationMs=e.durationMs),e.params!==void 0&&(t.params=w(e.params)),e.ok!==void 0&&(t.ok=e.ok),e.errorCode&&(t.errorCode=e.errorCode),e.errorSummary&&(t.errorSummary=e.errorSummary),e.latencyMs!=null&&(t.latencyMs=e.latencyMs),e.result!==void 0&&(t.result=w(e.result)),t}function w(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return e.length>240||/(base64|bytes|data|image|screenshot|png|jpeg|jpg|buffer)/i.test(t)&&e.length>48?{type:"string",length:e.length,sha256:C.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const a=e.slice(0,10).map(s=>w(s,t,n+1));return e.length>a.length?{type:"array",length:e.length,items:a}:a}if(typeof e!="object")return String(e);if(n>=5)return{type:"object",truncated:!0};const o=e,r={};for(const[a,s]of Object.entries(o))r[a]=w(s,a,n+1);return r}function q(e,t){return Y(t).map(n=>({bindingId:R(e,n),sessionId:e.sessionId||e.managerSessionId,conversationDisplayName:n,enabled:!0,allowReply:t.canReply!==!1,downloadMedia:t.downloadAttachments!==!1,selfTriggerMarker:i(t.selfTriggerMarker||"")||null}))}function R(e,t){return e.managedBy==="session-sync"||e.id.startsWith("wechat-binding:")?e.id:_(e.id,t)}function A(e,t,n){if(n.senderRole==="self")return null;const o=i(n.normalizedText||n.anchorText||n.textExcerpt||""),r=V(n);if(!o&&r.length===0)return null;const a=i(n.senderName||"");return{type:"external.message",channelId:e.id,channelType:"wechat-rpa",conversationId:L(t.conversationDisplayName),conversationName:t.conversationDisplayName,messageId:d("wechat-message",`${t.bindingId}
|
|
8
8
|
${n.stableMessageKey}`),sender:{id:d("wechat-sender",`${t.bindingId}
|
|
9
|
-
${a||n.senderRole}`),name:a||null},text:o,attachments:r,receivedAt:te(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function v(e,t,n){const o=n.map(
|
|
9
|
+
${a||n.senderRole}`),name:a||null},text:o,attachments:r,receivedAt:te(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function v(e,t,n){const o=n.map(c=>A(e,t,c)).filter(c=>c!=null);if(o.length<=1)return o[0]??null;const r=o[0],a=n.map(c=>i(c.stableMessageKey||"")).filter(Boolean),l=new Set(o.map(c=>i(c.sender.name||""))).size===1?r.sender.name??null:null,u=new Set(o.map(c=>c.sender.id)).size===1?r.sender.id:d("wechat-sender-batch",`${t.bindingId}
|
|
10
10
|
${a.join(`
|
|
11
|
-
`)}`),h=o.map(
|
|
11
|
+
`)}`),h=o.map(c=>{const m=i(c.text);return m?l!==null?m:`${i(c.sender.name||"")||"\u5BF9\u65B9"}: ${m}`:""}).filter(Boolean).join(`
|
|
12
12
|
`);return{...r,messageId:d("wechat-message-batch",`${t.bindingId}
|
|
13
13
|
${a.join(`
|
|
14
|
-
`)}`),sender:{id:u,name:l},text:h,attachments:G(o.flatMap(
|
|
15
|
-
`)}}function V(e){const t=e.mediaMetadata;return U(t).map(o=>{const r=o,a=typeof r.localPath=="string"?i(r.localPath):"",
|
|
16
|
-
`);t.has(r)||(t.add(r),n.push(o))}return n}function J(e){let t=0;for(const n of e){const o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t?new Date(t).toISOString():new Date().toISOString()}function Z(e,t){return e==="edge-local"||e==="server-url"||e==="pending-download"||e==="metadata-only"||e==="unavailable-large"?e:t.localPath?"edge-local":t.url?"server-url":"metadata-only"}function Q(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function X(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!p.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function Y(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function ee(){return process.env.SHENNIAN_MACHINE_ID?.trim()||W().machineId||"local"}function te(e){if(!e)return new Date().toISOString();const t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function i(e){return e.replace(/\s+/g," ").trim()}function ne(e,t,n,o){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(o,Math.floor(r))):t}function d(e,t){return`${e}:${C.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{j as WECHAT_RPA_PRODUCT_SOURCE,be as cancelWeChatRpaProductOutboundReply,ge as countPendingWeChatRpaProductOutbound,fe as createWeChatRpaProductSourceConnection,he as enqueueWeChatRpaProductOutboundReply,we as isWeChatRpaProductSource,pe as listPendingWeChatRpaProductOutbound,ye as listWeChatRpaProductRecentMessages,
|
|
14
|
+
`)}`),sender:{id:u,name:l},text:h,attachments:G(o.flatMap(c=>c.attachments)),receivedAt:J(o.map(c=>c.receivedAt)),rawRef:a.join(`
|
|
15
|
+
`)}}function V(e){const t=e.mediaMetadata;return U(t).map(o=>{const r=o,a=typeof r.localPath=="string"?i(r.localPath):"",s=typeof r.thumbnailPath=="string"?i(r.thumbnailPath):"",l=typeof r.url=="string"?i(r.url):"",u=Number(r.size??r.sizeBytes??0);return{type:i(String(r.type||r.kind||e.kind||"file"))||"file",...r.name||r.fileName?{name:i(String(r.name||r.fileName))}:{},...l?{url:l}:{},...typeof r.mimeType=="string"?{mimeType:i(r.mimeType)}:{},...typeof r.extension=="string"?{extension:i(r.extension)}:{},...Number.isFinite(u)&&u>0?{size:u}:{},...a?{localPath:a}:{},...s?{thumbnailPath:s}:{},...typeof r.hash=="string"||typeof r.sha256=="string"?{hash:i(String(r.hash||r.sha256))}:{},availability:Z(r.availability,{localPath:a,url:l}),...typeof r.providerError=="string"?{providerError:i(r.providerError)}:{},...typeof r.sourceAction=="string"?{sourceAction:i(r.sourceAction)}:{},...Q(r.materializationKind)?{materializationKind:r.materializationKind}:{},...typeof r.isOriginal=="boolean"?{isOriginal:r.isOriginal}:{},...typeof r.mimeKindMatches=="boolean"?{mimeKindMatches:r.mimeKindMatches}:{}}})}function U(e){if(!e||typeof e!="object")return[];const t=e;return Array.isArray(t.attachments)?t.attachments:t.attachment&&typeof t.attachment=="object"?[t.attachment]:t.localPath||t.url||t.name||t.fileName||t.availability?[t]:[]}function G(e){const t=new Set,n=[];for(const o of e){const r=[o.localPath||"",o.url||"",o.thumbnailPath||"",o.hash||"",o.name||"",o.mimeType||"",o.type||""].join(`
|
|
16
|
+
`);t.has(r)||(t.add(r),n.push(o))}return n}function J(e){let t=0;for(const n of e){const o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t?new Date(t).toISOString():new Date().toISOString()}function Z(e,t){return e==="edge-local"||e==="server-url"||e==="pending-download"||e==="metadata-only"||e==="unavailable-large"?e:t.localPath?"edge-local":t.url?"server-url":"metadata-only"}function Q(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function X(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!p.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function Y(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function ee(){return process.env.SHENNIAN_MACHINE_ID?.trim()||W().machineId||"local"}function te(e){if(!e)return new Date().toISOString();const t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function i(e){return e.replace(/\s+/g," ").trim()}function ne(e,t,n,o){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(o,Math.floor(r))):t}function d(e,t){return`${e}:${C.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{j as WECHAT_RPA_PRODUCT_SOURCE,be as cancelWeChatRpaProductOutboundReply,ge as countPendingWeChatRpaProductOutbound,fe as createWeChatRpaProductSourceConnection,he as enqueueWeChatRpaProductOutboundReply,we as isWeChatRpaProductSource,pe as listPendingWeChatRpaProductOutbound,ye as listWeChatRpaProductRecentMessages,A as observedMessageToExternalEvent,v as observedMessagesToExternalEvent,I as safeWeChatChannelRuntimePathSegment,_ as weChatChannelBindingId,L as weChatChannelConversationId,F as weChatChannelHelperTracePath,x as weChatChannelLedgerPath,f as weChatChannelOutboundLedgerPath};
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import I from"node:crypto";import m from"node:fs";import f from"node:path";import{fileURLToPath as ee,pathToFileURL as te}from"node:url";import{ChannelSecretRegistry as re}from"./secret-registry.js";import{resolveShennianPath as ne}from"../config/index.js";import{probeMacWeChat as q,observedMessageFromProbe as ae}from"./wechat-rpa/macos.js";import{runMacWeChatRpaFlow as F}from"./wechat-rpa/macos-flow.js";import{normalizeWeChatRpaMessage as se,WeChatRpaDeduper as K,weChatRpaConversationId as x}from"./wechat-rpa/normalizer.js";import{cancelWeChatRpaProductOutboundReply as ie,countPendingWeChatRpaProductOutbound as oe,createWeChatRpaProductSourceConnection as ue,enqueueWeChatRpaProductOutboundReply as de,isWeChatRpaProductSource as y,listWeChatRpaProductRecentMessages as ce,listPendingWeChatRpaProductOutbound as le,weChatChannelConversationId as N}from"./wechat-rpa/product-channel.js";import{createWeChatChannelApiClient as H}from"./wechat-channel/client.js";const pe=5e3,A=5,fe=8,S=Number(process.env.SHENNIAN_WECHAT_RPA_OUTBOUND_ATTACHMENT_MAX_BYTES||20*1024*1024),W=Number(process.env.SHENNIAN_WECHAT_RPA_INTERRUPTION_COOLDOWN_THRESHOLD||3),E=Number(process.env.SHENNIAN_WECHAT_RPA_INTERRUPTION_COOLDOWN_MS||300*1e3),he=10;function me(t){return P(t,A,1,50)>=fe?"scroll-read":"read-latest"}class it{onMessage;options;type="wechat-rpa";secrets=new re;connections=new Map;constructor(e,r={}){this.onMessage=e,this.options=r}async connect(e){if(!e.enabled)return;const r=this.readSecret(e),n=this.ensureConnection(e);if(n.stopped=!1,n.config=e,M(n,e),O(n,e),this.seedConfiguredConversations(n,r),y(r.source)){const a=await this.stopProductWhenControlPlaneDisabled(n,r);if(a||await this.ensureProductConnection(n,r),n.timer)return;n.timer=setInterval(()=>{this.enqueueOperation(n,()=>this.pollProductOnce(n,this.readSecret(n.config))).catch(i=>{console.error(`[wechat-rpa] autonomous poll failed id=${e.id}: ${i instanceof Error?i.message:String(i)}`)})},n.product?.runtime.policy.pollIntervalMs??j(r.pollIntervalMs)),n.timer.unref(),!r.deferInitialPoll&&!a&&this.enqueueOperation(n,()=>this.pollProductOnce(n,this.readSecret(n.config))).catch(i=>{console.error(`[wechat-rpa] initial poll failed id=${e.id}: ${i instanceof Error?i.message:String(i)}`)});return}n.timer||(n.timer=setInterval(()=>{this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config))).catch(()=>{})},j(r.pollIntervalMs)),n.timer.unref(),r.deferInitialPoll||this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config))).catch(()=>{}))}async disconnect(e){const r=this.connections.get(e.id);if(!r)return;r.stopped=!0,r.timer&&clearInterval(r.timer),r.timer=null;const n=r.product;await this.enqueueOperation(r,async()=>{n&&await n.runner.stop()}).catch(()=>{}),this.connections.delete(e.id)}async syncNow(e){if(!e.enabled)throw new Error("WeChat RPA channel is disabled");const r=this.readSecret(e),n=this.ensureConnection(e);return n.stopped=!1,n.config=e,M(n,e),O(n,e),this.seedConfiguredConversations(n,r),y(r.source)?this.enqueueOperation(n,async()=>{const a=this.readSecret(n.config);if(await this.stopProductWhenControlPlaneDisabled(n,a))return[];const i=await this.pollProductOnce(n,a,{forceObserve:!0}),s=n.product;if(!s)return i;const u=ce({config:n.config,product:s,limit:a.recentLimit});return Xe(u,i)}):this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config)))}async cancelOutbound(e,r){const n=this.readSecret(e);return y(n.source)?ie({config:e,idempotencyKey:r.idempotencyKey,replyId:r.replyId,reason:r.reason}):{cancelled:!1,status:"unsupported_source"}}async send(e,r){const n=this.readSecret(e);if(n.canReply===!1)throw new Error("WeChat RPA channel does not allow replies");const a=this.ensureConnection(e);if(a.config=e,M(a,e),O(a,e),this.seedConfiguredConversations(a,n),y(n.source)){const d=this.resolveConversationName(e,n,r.conversationId);if(!d)throw new Error(`Unknown WeChat RPA conversation: ${r.conversationId}`);const h=r.text.trim();if(!h&&!r.attachment)throw new Error("Reply text or attachment is required");if(await this.stopProductWhenControlPlaneDisabled(a,n))throw new Error("WeChat RPA channel is disabled");return de({config:a.config,secret:n,reply:{...r,text:h},conversationName:d}),a.runtimeState="retrying",w(a,{status:"sent",runId:a.lastRunId??null,summary:`queued ${d}`}),this.enqueueOperation(a,()=>this.pollProductOnce(a,this.readSecret(a.config))).catch(v=>{a.lastError=v instanceof Error?v.message:String(v)}),{status:"queued"}}if(!Ee(n.source))throw new Error("WeChat RPA reply requires source=macos-flow, windows-visual-flow, or wechat-rpa-lab");const i=this.resolveConversationName(e,n,r.conversationId);if(!i)throw new Error(`Unknown WeChat RPA conversation: ${r.conversationId}`);const s=Te(e,r);if(a.completedPendingReplyKeys.has(s))return{status:"sent"};const u=a.manualReviewReplies.get(s);if(u)return{status:"manual-review",reason:u.reason};const o=r.attachment?await Be(e.workDir,r.attachment):void 0,c=r.text.trim();if(!c&&!o)throw new Error("Reply text or attachment is required");if(Z(a,n)){const d="WeChat RPA is cooling down after repeated user activity";return a.runtimeState="cooldown",T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:c,attachmentPath:o,reason:d}),{status:"queued",reason:d}}let l;try{a.runtimeState="syncing",l=await this.enqueueOperation(a,()=>(a.lastRunAt=new Date().toISOString(),V(e,n,i,c,o,s)))}catch(d){throw a.lastError=d instanceof Error?d.message:String(d),w(a,{status:b(a.lastError),runId:a.lastRunId??null,summary:a.lastError}),d}$(a,l);const p=Y(l,{text:c,attachmentPath:o});if(p.status==="queued"){const d=p.reason;return T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:p.text,attachmentPath:p.attachmentPath,reason:d,skipText:p.skipText}),a.lastError=d,{status:"queued",reason:d}}if(l.interrupted){const d=l.error||"WeChat RPA send was interrupted by user activity";return _(a,l,d),T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:p.text,attachmentPath:o,reason:d,skipText:p.skipText}),{status:"queued",reason:d}}if(!l.ok){const d=l.error||"WeChat RPA send validator failed; manual review required before retry";return Q(a,s,d),{status:"manual-review",reason:d}}return w(a,{status:"sent",runId:a.lastRunId??null,summary:l.rpaTraceSummary||`sent ${i}`}),C(a),a.lastError=null,{status:"sent"}}async health(e){const r=this.readSecret(e);if((r.source??"macos-probe")==="fixture-jsonl")return r.fixturePath&&m.existsSync(r.fixturePath)?{ok:!0}:{ok:!1,message:"WeChat RPA fixture file is missing"};if(r.source==="macos-flow"){if(process.platform!=="darwin")return{ok:!1,message:"WeChat RPA macOS flow requires macOS"};if(!g(r).length)return{ok:!1,message:"WeChat RPA macOS flow requires at least one group"}}if(y(r.source))return Se(r,process.platform);if(r.source==="wechat-rpa-lab"){if(process.platform!=="darwin")return{ok:!1,message:"WeChat RPA Lab source requires macOS for live runs"};if(!g(r).length)return{ok:!1,message:"WeChat RPA Lab source requires at least one group"};try{J(e.workDir)}catch(a){return{ok:!1,message:a instanceof Error?a.message:String(a)}}return{ok:!0,message:"WeChat RPA Lab source configured"}}if(r.source==="windows-visual-flow")return ve(r,process.platform);const n=await q();return n.ok?{ok:!0,message:n.wechatRunning?"WeChat detected":"WeChat is not running"}:{ok:!1,message:n.message}}async defaultConversation(e){const r=this.readSecret(e),n=g(r)[0];if(!n)throw new Error("WeChat RPA channel has no configured groups");return y(r.source)?{conversationId:N(n),conversationName:n}:{conversationId:x(n),conversationName:n}}runtimeStatus(e){const r=this.connections.get(e.id);return r?{wechatRpaRuntimeState:r.runtimeState,wechatRpaLastRunAt:r.lastRunAt??null,wechatRpaLastMessageAt:r.lastMessageAt??null,wechatRpaLastInterruptedAt:r.lastInterruptedAt??null,wechatRpaLastError:r.lastError??null,wechatRpaLastRunId:r.lastRunId??null,wechatRpaLastTracePath:r.lastTracePath??r.product?.helperTracePath??null,wechatRpaLastTraceSummary:r.lastTraceSummary??null,wechatRpaPendingReplyCount:r.pendingReplies.size+oe({config:e}),wechatRpaPendingReplies:Me(r,e),wechatRpaRecentTaskSummaries:r.recentTaskSummaries}:{}}ensureConnection(e){let r=this.connections.get(e.id);return r||(r={config:e,timer:null,deduper:new K,stopped:!1,conversations:new Map,pendingReplies:new Map,manualReviewReplies:new Map,completedPendingReplyKeys:new Set,pendingStatePath:void 0,messageStatePath:void 0,operation:Promise.resolve(),recentTaskSummaries:[],runtimeState:"idle_waiting",consecutiveInterruptions:0},this.connections.set(e.id,r)),r}enqueueOperation(e,r){const n=this.options.automationLane?()=>this.options.automationLane?.run(`wechat-rpa:${e.config.id}`,r):r,a=e.operation.then(n,n);return e.operation=a.then(()=>{},()=>{}),a}readSecret(e){const r=this.secrets.get(e.secretRef);if(!r||r.type!=="wechat-rpa")throw new Error("WeChat RPA channel is not configured on this daemon");return r}async pollOnce(e,r){if(e.stopped)return[];const n=[];e.lastRunAt=new Date().toISOString();try{if(Z(e,r))return e.runtimeState="cooldown",[];if(await this.drainPendingReplies(e,r))return[];let i=!1;e.runtimeState="syncing";const s=await this.readObservedMessages(e.config,r,u=>{$(e,u),u.interrupted&&(i=!0,_(e,u,u.error||"WeChat RPA poll was interrupted by user activity"))});e.lastError=null;for(const u of s){const o=se(u,{selfNicknames:U(r)});if(!o||!e.deduper.accept(o.messageId))continue;De(e),e.conversations.set(o.conversationId,o.conversationName),e.lastMessageAt=o.receivedAt;const c={type:"external.message",managerSessionId:e.config.managerSessionId,channelId:e.config.id,channelType:"wechat-rpa",conversationId:o.conversationId,conversationName:o.conversationName,messageId:o.messageId,sender:o.sender,text:o.text,attachments:o.attachments,receivedAt:o.receivedAt,isMentioned:o.isMentioned,replyTarget:"",rawRef:o.rawRef};n.push(this.onMessage?.(c)??c),w(e,{status:"received",runId:e.lastRunId??null,summary:`received ${o.conversationName}${o.sender.name?` from ${o.sender.name}`:""}: ${L(o.text||o.attachments[0]?.name||"attachment")}`})}return i||C(e),n}catch(a){throw e.lastError=a instanceof Error?a.message:String(a),w(e,{status:b(e.lastError),runId:e.lastRunId??null,summary:e.lastError}),a}}async pollProductOnce(e,r,n){if(e.stopped)return[];if(!y(r.source))return[];if(await this.stopProductWhenControlPlaneDisabled(e,r))return[];const a=await this.ensureProductConnection(e,r);await B(a).catch(()=>null);const i=a.emitted.length;e.lastRunAt=new Date().toISOString(),e.runtimeState="syncing";try{await a.runner.tick(n);const s=a.emitted.slice(i);e.lastError=null;for(const u of s)e.conversations.set(u.conversationId,u.conversationName||""),e.lastMessageAt=u.receivedAt,w(e,{status:"received",runId:e.lastRunId??null,summary:`received ${u.conversationName||u.conversationId}${u.sender.name?` from ${u.sender.name}`:""}: ${L(u.text||u.attachments[0]?.name||"attachment")}`});return C(e),s}catch(s){throw e.lastError=s instanceof Error?s.message:String(s),e.runtimeState=b(e.lastError)==="blocked"?"interrupted":"idle_waiting",w(e,{status:b(e.lastError),runId:e.lastRunId??null,summary:e.lastError}),s}}async ensureProductConnection(e,r){const n=ge(e.config,r);return e.product&&e.productConfigKey===n||(e.product&&await e.product.runner.stop().catch(()=>{}),e.product=ue({config:e.config,secret:r,createRunner:this.options.createProductRunner,onMessage:this.onMessage}),await B(e.product).catch(()=>{}),e.productConfigKey=n,e.lastTracePath=e.product.helperTracePath),e.product}async stopProductWhenControlPlaneDisabled(e,r){if(!y(r.source))return!1;let n=null;try{n=await we(e.config,r)}catch(a){return e.productDisabled?(e.lastRunAt=new Date().toISOString(),e.runtimeState="idle_waiting",e.lastError=a instanceof Error?a.message:String(a),!0):!1}if(n?.enabled!==!1)return e.productDisabled=!1,!1;if(e.productDisabled=!0,e.lastRunAt=new Date().toISOString(),e.runtimeState="idle_waiting",e.lastError=null,e.product){const a=e.product;e.product=void 0,e.productConfigKey=void 0,await a.runner.stop().catch(()=>{})}return!0}async drainPendingReplies(e,r){if(!e.pendingReplies.size)return!1;for(const n of Array.from(e.pendingReplies.values())){e.runtimeState="retrying",n.attempts+=1,n.lastAttemptAt=new Date().toISOString(),R(e);const a=await V(e.config,r,n.conversationName,n.skipText?"":n.text,n.attachmentPath,n.key);$(e,a);const i=Y(a,{text:n.skipText?"":n.text,attachmentPath:n.attachmentPath});if(i.status==="queued")return n.text=i.text,n.attachmentPath=i.attachmentPath,n.skipText=i.skipText,n.lastInterruptedReason=i.reason,e.lastError=i.reason,R(e),!0;if(a.interrupted){const s=a.error||"WeChat RPA pending send was interrupted by user activity";return n.text=i.text,n.attachmentPath=i.attachmentPath,n.skipText=i.skipText,n.lastInterruptedReason=s,_(e,a,s),R(e),!0}if(!a.ok){const s=a.error||"WeChat RPA pending send validator failed; manual review required before retry";return e.pendingReplies.delete(n.key),Q(e,n.key,s),R(e),!0}e.pendingReplies.delete(n.key),e.completedPendingReplyKeys.add(n.key),R(e),e.lastError=null,w(e,{status:"sent",runId:e.lastRunId??null,summary:a.rpaTraceSummary||`sent ${n.conversationName}`}),C(e)}return!1}async readObservedMessages(e,r,n){if(r.source==="fixture-jsonl")return He(r.fixturePath);if(r.source==="macos-flow")return Ne(e,r,n);if(r.source==="wechat-rpa-lab")return Pe(e,r,n);if(r.source==="windows-visual-flow")return We(e,r,n);const a=await q(),i=ae(a);return i?[i]:[]}seedConfiguredConversations(e,r){for(const n of g(r))e.conversations.set(x(n),n),e.conversations.set(N(n),n)}resolveConversationName(e,r,n){const i=this.connections.get(e.id)?.conversations.get(n);return i||(g(r).find(s=>x(s)===n||N(s)===n)??null)}}function ge(t,e){return JSON.stringify({id:t.id,workDir:t.workDir,managerSessionId:t.managerSessionId,pollIntervalMs:e.pollIntervalMs,forceForeground:k(e),downloadAttachments:e.downloadAttachments!==!1,canReply:e.canReply!==!1,selfTriggerMarker:e.selfTriggerMarker||"",groups:g(e)})}async function we(t,e,r){const n=r??H(),a=await n.getRuntimePolicy();if(a.feature?.enabled===!1)return{enabled:!1,reasonCode:a.feature.reasonCode||"feature_disabled"};if(a.runtime?.current?.status==="disabled")return{enabled:!1,reasonCode:"runtime_disabled"};const i=t.sessionId||t.managerSessionId;if(!i)return{enabled:!1,reasonCode:"session_missing"};let s;try{s=(await n.getBinding({sessionId:i})).binding}catch(o){const c=ye(o);if(c==="binding_not_found"||c==="session_not_found"||c==="machine_not_found")return{enabled:!1,reasonCode:c};throw o}if(!s||s.enabled===!1)return{enabled:!1,reasonCode:"no_enabled_binding"};const u=g(e);return u.length?u.includes(s.conversationName)?{enabled:!0}:{enabled:!1,reasonCode:"binding_conversation_changed"}:{enabled:!1,reasonCode:"no_configured_conversation"}}async function B(t){const r=(await H().getRuntimePolicy()).runtime?.current;return t.runtime.foregroundPolicy="work",{enabled:r?.status!=="disabled"}}function ye(t){if(t&&typeof t=="object"){const e=t.reasonCode;if(typeof e=="string")return e}return""}function j(t){return Number.isFinite(t)?Math.min(6e4,Math.max(1e3,Number(t))):pe}function g(t){return Array.isArray(t.groups)?t.groups.map(e=>String(e?.name||"").trim()).filter(Boolean):[]}function U(t){return String(t.selfNickname||"").split(/[,\n,、]/).map(e=>e.trim()).filter(Boolean)}function Re(t,e){return e.length?e.some(r=>{const n=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`@\\s*${n}(?=$|\\s|[\uFF0C\u3002\uFF01\uFF1F,.!?:\uFF1A\uFF1B;\u3001)])`).test(t)}):!1}function ve(t,e=process.platform){return e!=="win32"?{ok:!1,message:"WeChat RPA Windows visual flow requires Windows"}:{ok:!1,message:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}}function Se(t,e=process.platform){return e!=="darwin"&&e!=="win32"?{ok:!1,message:"WeChat channel product source requires macOS or Windows"}:(Array.isArray(t.groups)?t.groups.map(n=>String(n?.name||"").trim()).filter(Boolean):[]).length?{ok:!0,message:"WeChat channel product source configured"}:{ok:!1,message:"WeChat channel product source requires at least one group"}}async function Pe(t,e,r){const n=await z(t.workDir),a=[];for(const i of g(e)){const s=await Ie(n,t,e,i);if(r?.(s),!(!s.ok||s.interrupted))for(const u of s.newMessages??[]){const o=G(i,u,e);o&&a.push(o)}}return a}async function Ie(t,e,r,n){const a=me(r.recentLimit),i={kind:a,requestId:`wechat-rpa:${n}:read:${Date.now()}`,targetGroup:n,policy:r.forceForeground?"work":"polite",limit:P(r.recentLimit,A,1,50),attachmentsDir:D(e,r)},s=await t.runWechatRpaReadLatest(i),u=Array.isArray(s.data?.structuredMessages)?s.data.structuredMessages:[],o=s.validation?.deterministic?.latestMessages??[],c=u.length?u.map((l,p)=>Ae(l,s.runId||"lab-read",p)):o.map((l,p)=>({id:`${s.runId||"lab-read"}:${p}`,text:l,confidence:.8}));return{ok:!!s.ok,groupName:n,interrupted:s.status==="interrupted",reason:s.status,rpaRunId:s.runId,rpaTraceSummary:`${a} ${s.status||(s.ok?"success":"failed")} ${n}`,recentMessages:c,newMessages:c,screenshotPath:s.tracePath,error:X(s)}}function Ae(t,e,r){return{id:`${e}:${t.index??r}`,text:String(t.text||t.card?.title||"").trim(),confidence:typeof t.confidence=="number"?t.confidence:.75,senderName:typeof t.senderName=="string"?t.senderName:null,attachments:Ce(t)}}function Ce(t){const e=String(t.kind||"");if(!["image","file","video-file","video-card","link-card","official-account-card","mini-program-card"].includes(e))return[];const r=typeof t.localPath=="string"?t.localPath:void 0;return[{type:e==="video-file"||e==="video-card"?"video":e==="link-card"||e==="official-account-card"||e==="mini-program-card"?"file":e,localPath:r,availability:r?"edge-local":"metadata-only"}]}async function be(t,e,r,n,a,i){const s=await z(t.workDir),u=ke({groupName:r,text:n,attachmentPath:a,dedupeKey:i,requestId:i,policy:"work"}),o=[];for(const h of u){const v=await s.runWechatRpaTask(h);if(o.push(v),!v.ok)break}const c=o.find(h=>h.kind==="send-text"),l=o.find(h=>h.kind==="send-image"||h.kind==="send-video"||h.kind==="send-file"),p=u.length>0&&o.length===u.length&&o.every(h=>h.ok),d=o.some(h=>h.status==="interrupted");return{ok:p,groupName:r,interrupted:d,reason:o.at(-1)?.status,rpaRunId:o.at(-1)?.runId,rpaTraceSummary:`send ${p?"success":o.at(-1)?.status||"failed"} ${r} (${o.length}/${u.length})`,sentReply:!!n,sentReplyObserved:n?!!c?.ok:!1,sentAttachment:!!a,sentAttachmentObserved:a?!!l?.ok:!1,postSendScreenshotPath:o.at(-1)?.tracePath,error:p?void 0:X(o.at(-1))}}function ke(t){const e=[],r=String(t.text||"").trim(),n=t.policy||"work";if(r&&e.push({kind:"send-text",requestId:t.requestId?`${t.requestId}:text`:void 0,targetGroup:t.groupName,policy:n,text:r,...t.dedupeKey?{dedupeKey:`${t.dedupeKey}:text`}:{}}),t.attachmentPath){const a=xe(t.attachmentPath);e.push({kind:a,requestId:t.requestId?`${t.requestId}:attachment`:void 0,targetGroup:t.groupName,policy:n,filePath:t.attachmentPath,...t.dedupeKey?{dedupeKey:`${t.dedupeKey}:attachment`}:{}})}return e}function xe(t){const e=f.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp",".heic"].includes(e)?"send-image":[".mp4",".mov",".avi",".mkv"].includes(e)?"send-video":"send-file"}async function z(t){const e=J(t);return await import(te(e).href)}function J(t){const e=f.dirname(ee(import.meta.url)),n=[process.env.SHENNIAN_WECHAT_RPA_LAB_INDEX,f.resolve(e,"../../../../scripts/wechat-rpa-lab/index.mjs"),t?f.join(t,"scripts/wechat-rpa-lab/index.mjs"):"",f.resolve(process.cwd(),"scripts/wechat-rpa-lab/index.mjs")].filter(Boolean).find(a=>m.existsSync(a));if(!n)throw new Error("WeChat RPA Lab API is missing; set SHENNIAN_WECHAT_RPA_LAB_INDEX or run from the repository root");return f.resolve(n)}function X(t){return t?typeof t.error=="string"?t.error:t.error?.message||(t.ok?void 0:`WeChat RPA Lab task ${t.kind||"<unknown>"} ${t.status||"failed"}`):"WeChat RPA Lab did not return a result"}async function Ne(t,e,r){const n=[];for(const a of g(e)){const i=await F({groupName:a,scriptPath:e.flowScriptPath,workDir:t.workDir,forceForeground:k(e),noRestore:e.noRestore!==!1,idleSeconds:P(e.idleSeconds,15,0,3600),recentLimit:P(e.recentLimit,A,0,50),downloadAttachmentsDir:D(t,e)});if(r?.(i),!i.interrupted)for(const s of i.newMessages??[]){const u=G(a,s,e);u&&n.push(u)}}return n}async function We(t,e,r){const n=g(e)[0]||"<unbound>";return r?.({ok:!1,groupName:n,interrupted:!0,reason:"windows-visual-flow-archived",newMessages:[],recentMessages:[],error:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}),[]}function G(t,e,r){const n=String(e.text||"").trim(),a=Array.isArray(e.attachments)?e.attachments:[];if(!n&&a.length===0)return null;const i=typeof e.senderName=="string"?e.senderName.trim():"",s=String(e.observedAt||e.timestampIso||"").trim()||new Date().toISOString();return{conversationName:t,senderName:i||null,text:n,attachments:Je(a),observedAt:s,isMentioned:e.isMentioned===!0||Re(n,U(r)),rawId:String(e.id||`${t}:${i}:${n}:${s}`)}}async function V(t,e,r,n,a,i){return e.source==="windows-visual-flow"?{ok:!1,groupName:r,interrupted:!0,reason:"windows-visual-flow-archived",newMessages:[],recentMessages:[],error:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}:e.source==="wechat-rpa-lab"?be(t,e,r,n,a,i):F({groupName:r,replyText:n||void 0,attachmentPath:a,scriptPath:e.flowScriptPath,workDir:t.workDir,forceForeground:k(e),noRestore:e.noRestore!==!1,idleSeconds:P(e.idleSeconds,15,0,3600),recentLimit:P(e.recentLimit,A,0,50),downloadAttachmentsDir:D(t,e)})}function Ee(t){return t==="macos-flow"||t==="wechat-rpa-lab"}function Y(t,e){return e.text&&e.attachmentPath&&t.sentReplyObserved&&!t.sentAttachmentObserved?{status:t.interrupted?"continue":"queued",text:"",attachmentPath:e.attachmentPath,skipText:!0,reason:t.error||"WeChat RPA sent the text but did not confirm the attachment; queued attachment-only retry"}:{status:"continue",text:e.text,attachmentPath:e.attachmentPath,reason:t.error||""}}function Te(t,e){return e.idempotencyKey?e.idempotencyKey:I.createHash("sha256").update(`${t.id}
|
|
1
|
+
import I from"node:crypto";import m from"node:fs";import h from"node:path";import{fileURLToPath as ee,pathToFileURL as te}from"node:url";import{ChannelSecretRegistry as re}from"./secret-registry.js";import{resolveShennianPath as ne}from"../config/index.js";import{probeMacWeChat as q,observedMessageFromProbe as ae}from"./wechat-rpa/macos.js";import{runMacWeChatRpaFlow as F}from"./wechat-rpa/macos-flow.js";import{normalizeWeChatRpaMessage as se,WeChatRpaDeduper as K,weChatRpaConversationId as x}from"./wechat-rpa/normalizer.js";import{cancelWeChatRpaProductOutboundReply as ie,countPendingWeChatRpaProductOutbound as oe,createWeChatRpaProductSourceConnection as ue,enqueueWeChatRpaProductOutboundReply as de,isWeChatRpaProductSource as y,listPendingWeChatRpaProductOutbound as ce,weChatChannelConversationId as N}from"./wechat-rpa/product-channel.js";import{createWeChatChannelApiClient as H}from"./wechat-channel/client.js";const le=5e3,A=5,pe=8,S=Number(process.env.SHENNIAN_WECHAT_RPA_OUTBOUND_ATTACHMENT_MAX_BYTES||20*1024*1024),W=Number(process.env.SHENNIAN_WECHAT_RPA_INTERRUPTION_COOLDOWN_THRESHOLD||3),E=Number(process.env.SHENNIAN_WECHAT_RPA_INTERRUPTION_COOLDOWN_MS||300*1e3),he=10;function fe(t){return P(t,A,1,50)>=pe?"scroll-read":"read-latest"}class at{onMessage;options;type="wechat-rpa";secrets=new re;connections=new Map;constructor(e,r={}){this.onMessage=e,this.options=r}async connect(e){if(!e.enabled)return;const r=this.readSecret(e),n=this.ensureConnection(e);if(n.stopped=!1,n.config=e,O(n,e),M(n,e),this.seedConfiguredConversations(n,r),y(r.source)){const a=await this.stopProductWhenControlPlaneDisabled(n,r);if(a||await this.ensureProductConnection(n,r),n.timer)return;n.timer=setInterval(()=>{this.enqueueOperation(n,()=>this.pollProductOnce(n,this.readSecret(n.config))).catch(i=>{console.error(`[wechat-rpa] autonomous poll failed id=${e.id}: ${i instanceof Error?i.message:String(i)}`)})},n.product?.runtime.policy.pollIntervalMs??j(r.pollIntervalMs)),n.timer.unref(),!r.deferInitialPoll&&!a&&this.enqueueOperation(n,()=>this.pollProductOnce(n,this.readSecret(n.config))).catch(i=>{console.error(`[wechat-rpa] initial poll failed id=${e.id}: ${i instanceof Error?i.message:String(i)}`)});return}n.timer||(n.timer=setInterval(()=>{this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config))).catch(()=>{})},j(r.pollIntervalMs)),n.timer.unref(),r.deferInitialPoll||this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config))).catch(()=>{}))}async disconnect(e){const r=this.connections.get(e.id);if(!r)return;r.stopped=!0,r.timer&&clearInterval(r.timer),r.timer=null;const n=r.product;await this.enqueueOperation(r,async()=>{n&&await n.runner.stop()}).catch(()=>{}),this.connections.delete(e.id)}async syncNow(e){if(!e.enabled)throw new Error("WeChat RPA channel is disabled");const r=this.readSecret(e),n=this.ensureConnection(e);return n.stopped=!1,n.config=e,O(n,e),M(n,e),this.seedConfiguredConversations(n,r),y(r.source)?this.enqueueOperation(n,async()=>{const a=this.readSecret(n.config);return await this.stopProductWhenControlPlaneDisabled(n,a)?[]:this.pollProductOnce(n,a,{forceObserve:!0})}):this.enqueueOperation(n,()=>this.pollOnce(n,this.readSecret(n.config)))}async cancelOutbound(e,r){const n=this.readSecret(e);return y(n.source)?ie({config:e,idempotencyKey:r.idempotencyKey,replyId:r.replyId,reason:r.reason}):{cancelled:!1,status:"unsupported_source"}}async send(e,r){const n=this.readSecret(e);if(n.canReply===!1)throw new Error("WeChat RPA channel does not allow replies");const a=this.ensureConnection(e);if(a.config=e,O(a,e),M(a,e),this.seedConfiguredConversations(a,n),y(n.source)){const d=this.resolveConversationName(e,n,r.conversationId);if(!d)throw new Error(`Unknown WeChat RPA conversation: ${r.conversationId}`);const f=r.text.trim();if(!f&&!r.attachment)throw new Error("Reply text or attachment is required");if(await this.stopProductWhenControlPlaneDisabled(a,n))throw new Error("WeChat RPA channel is disabled");return de({config:a.config,secret:n,reply:{...r,text:f},conversationName:d}),a.runtimeState="retrying",w(a,{status:"sent",runId:a.lastRunId??null,summary:`queued ${d}`}),this.enqueueOperation(a,()=>this.pollProductOnce(a,this.readSecret(a.config))).catch(v=>{a.lastError=v instanceof Error?v.message:String(v)}),{status:"queued"}}if(!We(n.source))throw new Error("WeChat RPA reply requires source=macos-flow, windows-visual-flow, or wechat-rpa-lab");const i=this.resolveConversationName(e,n,r.conversationId);if(!i)throw new Error(`Unknown WeChat RPA conversation: ${r.conversationId}`);const s=Ee(e,r);if(a.completedPendingReplyKeys.has(s))return{status:"sent"};const u=a.manualReviewReplies.get(s);if(u)return{status:"manual-review",reason:u.reason};const o=r.attachment?await He(e.workDir,r.attachment):void 0,c=r.text.trim();if(!c&&!o)throw new Error("Reply text or attachment is required");if(Z(a,n)){const d="WeChat RPA is cooling down after repeated user activity";return a.runtimeState="cooldown",T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:c,attachmentPath:o,reason:d}),{status:"queued",reason:d}}let l;try{a.runtimeState="syncing",l=await this.enqueueOperation(a,()=>(a.lastRunAt=new Date().toISOString(),V(e,n,i,c,o,s)))}catch(d){throw a.lastError=d instanceof Error?d.message:String(d),w(a,{status:b(a.lastError),runId:a.lastRunId??null,summary:a.lastError}),d}$(a,l);const p=Y(l,{text:c,attachmentPath:o});if(p.status==="queued"){const d=p.reason;return T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:p.text,attachmentPath:p.attachmentPath,reason:d,skipText:p.skipText}),a.lastError=d,{status:"queued",reason:d}}if(l.interrupted){const d=l.error||"WeChat RPA send was interrupted by user activity";return _(a,l,d),T(a,{key:s,conversationId:r.conversationId,conversationName:i,text:p.text,attachmentPath:o,reason:d,skipText:p.skipText}),{status:"queued",reason:d}}if(!l.ok){const d=l.error||"WeChat RPA send validator failed; manual review required before retry";return Q(a,s,d),{status:"manual-review",reason:d}}return w(a,{status:"sent",runId:a.lastRunId??null,summary:l.rpaTraceSummary||`sent ${i}`}),C(a),a.lastError=null,{status:"sent"}}async health(e){const r=this.readSecret(e);if((r.source??"macos-probe")==="fixture-jsonl")return r.fixturePath&&m.existsSync(r.fixturePath)?{ok:!0}:{ok:!1,message:"WeChat RPA fixture file is missing"};if(r.source==="macos-flow"){if(process.platform!=="darwin")return{ok:!1,message:"WeChat RPA macOS flow requires macOS"};if(!g(r).length)return{ok:!1,message:"WeChat RPA macOS flow requires at least one group"}}if(y(r.source))return ve(r,process.platform);if(r.source==="wechat-rpa-lab"){if(process.platform!=="darwin")return{ok:!1,message:"WeChat RPA Lab source requires macOS for live runs"};if(!g(r).length)return{ok:!1,message:"WeChat RPA Lab source requires at least one group"};try{J(e.workDir)}catch(a){return{ok:!1,message:a instanceof Error?a.message:String(a)}}return{ok:!0,message:"WeChat RPA Lab source configured"}}if(r.source==="windows-visual-flow")return Re(r,process.platform);const n=await q();return n.ok?{ok:!0,message:n.wechatRunning?"WeChat detected":"WeChat is not running"}:{ok:!1,message:n.message}}async defaultConversation(e){const r=this.readSecret(e),n=g(r)[0];if(!n)throw new Error("WeChat RPA channel has no configured groups");return y(r.source)?{conversationId:N(n),conversationName:n}:{conversationId:x(n),conversationName:n}}runtimeStatus(e){const r=this.connections.get(e.id);return r?{wechatRpaRuntimeState:r.runtimeState,wechatRpaLastRunAt:r.lastRunAt??null,wechatRpaLastMessageAt:r.lastMessageAt??null,wechatRpaLastInterruptedAt:r.lastInterruptedAt??null,wechatRpaLastError:r.lastError??null,wechatRpaLastRunId:r.lastRunId??null,wechatRpaLastTracePath:r.lastTracePath??r.product?.helperTracePath??null,wechatRpaLastTraceSummary:r.lastTraceSummary??null,wechatRpaPendingReplyCount:r.pendingReplies.size+oe({config:e}),wechatRpaPendingReplies:Te(r,e),wechatRpaRecentTaskSummaries:r.recentTaskSummaries}:{}}ensureConnection(e){let r=this.connections.get(e.id);return r||(r={config:e,timer:null,deduper:new K,stopped:!1,conversations:new Map,pendingReplies:new Map,manualReviewReplies:new Map,completedPendingReplyKeys:new Set,pendingStatePath:void 0,messageStatePath:void 0,operation:Promise.resolve(),recentTaskSummaries:[],runtimeState:"idle_waiting",consecutiveInterruptions:0},this.connections.set(e.id,r)),r}enqueueOperation(e,r){const n=this.options.automationLane?()=>this.options.automationLane?.run(`wechat-rpa:${e.config.id}`,r):r,a=e.operation.then(n,n);return e.operation=a.then(()=>{},()=>{}),a}readSecret(e){const r=this.secrets.get(e.secretRef);if(!r||r.type!=="wechat-rpa")throw new Error("WeChat RPA channel is not configured on this daemon");return r}async pollOnce(e,r){if(e.stopped)return[];const n=[];e.lastRunAt=new Date().toISOString();try{if(Z(e,r))return e.runtimeState="cooldown",[];if(await this.drainPendingReplies(e,r))return[];let i=!1;e.runtimeState="syncing";const s=await this.readObservedMessages(e.config,r,u=>{$(e,u),u.interrupted&&(i=!0,_(e,u,u.error||"WeChat RPA poll was interrupted by user activity"))});e.lastError=null;for(const u of s){const o=se(u,{selfNicknames:U(r)});if(!o||!e.deduper.accept(o.messageId))continue;De(e),e.conversations.set(o.conversationId,o.conversationName),e.lastMessageAt=o.receivedAt;const c={type:"external.message",managerSessionId:e.config.managerSessionId,channelId:e.config.id,channelType:"wechat-rpa",conversationId:o.conversationId,conversationName:o.conversationName,messageId:o.messageId,sender:o.sender,text:o.text,attachments:o.attachments,receivedAt:o.receivedAt,isMentioned:o.isMentioned,replyTarget:"",rawRef:o.rawRef};n.push(this.onMessage?.(c)??c),w(e,{status:"received",runId:e.lastRunId??null,summary:`received ${o.conversationName}${o.sender.name?` from ${o.sender.name}`:""}: ${D(o.text||o.attachments[0]?.name||"attachment")}`})}return i||C(e),n}catch(a){throw e.lastError=a instanceof Error?a.message:String(a),w(e,{status:b(e.lastError),runId:e.lastRunId??null,summary:e.lastError}),a}}async pollProductOnce(e,r,n){if(e.stopped)return[];if(!y(r.source))return[];if(await this.stopProductWhenControlPlaneDisabled(e,r))return[];const a=await this.ensureProductConnection(e,r);await B(a).catch(()=>null);const i=a.emitted.length;e.lastRunAt=new Date().toISOString(),e.runtimeState="syncing";try{await a.runner.tick(n);const s=a.emitted.slice(i);e.lastError=null;for(const u of s)e.conversations.set(u.conversationId,u.conversationName||""),e.lastMessageAt=u.receivedAt,w(e,{status:"received",runId:e.lastRunId??null,summary:`received ${u.conversationName||u.conversationId}${u.sender.name?` from ${u.sender.name}`:""}: ${D(u.text||u.attachments[0]?.name||"attachment")}`});return C(e),s}catch(s){throw e.lastError=s instanceof Error?s.message:String(s),e.runtimeState=b(e.lastError)==="blocked"?"interrupted":"idle_waiting",w(e,{status:b(e.lastError),runId:e.lastRunId??null,summary:e.lastError}),s}}async ensureProductConnection(e,r){const n=me(e.config,r);return e.product&&e.productConfigKey===n||(e.product&&await e.product.runner.stop().catch(()=>{}),e.product=ue({config:e.config,secret:r,createRunner:this.options.createProductRunner,onMessage:this.onMessage}),await B(e.product).catch(()=>{}),e.productConfigKey=n,e.lastTracePath=e.product.helperTracePath),e.product}async stopProductWhenControlPlaneDisabled(e,r){if(!y(r.source))return!1;let n=null;try{n=await ge(e.config,r)}catch(a){return e.productDisabled?(e.lastRunAt=new Date().toISOString(),e.runtimeState="idle_waiting",e.lastError=a instanceof Error?a.message:String(a),!0):!1}if(n?.enabled!==!1)return e.productDisabled=!1,!1;if(e.productDisabled=!0,e.lastRunAt=new Date().toISOString(),e.runtimeState="idle_waiting",e.lastError=null,e.product){const a=e.product;e.product=void 0,e.productConfigKey=void 0,await a.runner.stop().catch(()=>{})}return!0}async drainPendingReplies(e,r){if(!e.pendingReplies.size)return!1;for(const n of Array.from(e.pendingReplies.values())){e.runtimeState="retrying",n.attempts+=1,n.lastAttemptAt=new Date().toISOString(),R(e);const a=await V(e.config,r,n.conversationName,n.skipText?"":n.text,n.attachmentPath,n.key);$(e,a);const i=Y(a,{text:n.skipText?"":n.text,attachmentPath:n.attachmentPath});if(i.status==="queued")return n.text=i.text,n.attachmentPath=i.attachmentPath,n.skipText=i.skipText,n.lastInterruptedReason=i.reason,e.lastError=i.reason,R(e),!0;if(a.interrupted){const s=a.error||"WeChat RPA pending send was interrupted by user activity";return n.text=i.text,n.attachmentPath=i.attachmentPath,n.skipText=i.skipText,n.lastInterruptedReason=s,_(e,a,s),R(e),!0}if(!a.ok){const s=a.error||"WeChat RPA pending send validator failed; manual review required before retry";return e.pendingReplies.delete(n.key),Q(e,n.key,s),R(e),!0}e.pendingReplies.delete(n.key),e.completedPendingReplyKeys.add(n.key),R(e),e.lastError=null,w(e,{status:"sent",runId:e.lastRunId??null,summary:a.rpaTraceSummary||`sent ${n.conversationName}`}),C(e)}return!1}async readObservedMessages(e,r,n){if(r.source==="fixture-jsonl")return Ke(r.fixturePath);if(r.source==="macos-flow")return xe(e,r,n);if(r.source==="wechat-rpa-lab")return Se(e,r,n);if(r.source==="windows-visual-flow")return Ne(e,r,n);const a=await q(),i=ae(a);return i?[i]:[]}seedConfiguredConversations(e,r){for(const n of g(r))e.conversations.set(x(n),n),e.conversations.set(N(n),n)}resolveConversationName(e,r,n){const i=this.connections.get(e.id)?.conversations.get(n);return i||(g(r).find(s=>x(s)===n||N(s)===n)??null)}}function me(t,e){return JSON.stringify({id:t.id,workDir:t.workDir,managerSessionId:t.managerSessionId,pollIntervalMs:e.pollIntervalMs,forceForeground:k(e),downloadAttachments:e.downloadAttachments!==!1,canReply:e.canReply!==!1,selfTriggerMarker:e.selfTriggerMarker||"",groups:g(e)})}async function ge(t,e,r){const n=r??H(),a=await n.getRuntimePolicy();if(a.feature?.enabled===!1)return{enabled:!1,reasonCode:a.feature.reasonCode||"feature_disabled"};if(a.runtime?.current?.status==="disabled")return{enabled:!1,reasonCode:"runtime_disabled"};const i=t.sessionId||t.managerSessionId;if(!i)return{enabled:!1,reasonCode:"session_missing"};let s;try{s=(await n.getBinding({sessionId:i})).binding}catch(o){const c=we(o);if(c==="binding_not_found"||c==="session_not_found"||c==="machine_not_found")return{enabled:!1,reasonCode:c};throw o}if(!s||s.enabled===!1)return{enabled:!1,reasonCode:"no_enabled_binding"};const u=g(e);return u.length?u.includes(s.conversationName)?{enabled:!0}:{enabled:!1,reasonCode:"binding_conversation_changed"}:{enabled:!1,reasonCode:"no_configured_conversation"}}async function B(t){const r=(await H().getRuntimePolicy()).runtime?.current;return t.runtime.foregroundPolicy="work",{enabled:r?.status!=="disabled"}}function we(t){if(t&&typeof t=="object"){const e=t.reasonCode;if(typeof e=="string")return e}return""}function j(t){return Number.isFinite(t)?Math.min(6e4,Math.max(1e3,Number(t))):le}function g(t){return Array.isArray(t.groups)?t.groups.map(e=>String(e?.name||"").trim()).filter(Boolean):[]}function U(t){return String(t.selfNickname||"").split(/[,\n,、]/).map(e=>e.trim()).filter(Boolean)}function ye(t,e){return e.length?e.some(r=>{const n=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`@\\s*${n}(?=$|\\s|[\uFF0C\u3002\uFF01\uFF1F,.!?:\uFF1A\uFF1B;\u3001)])`).test(t)}):!1}function Re(t,e=process.platform){return e!=="win32"?{ok:!1,message:"WeChat RPA Windows visual flow requires Windows"}:{ok:!1,message:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}}function ve(t,e=process.platform){return e!=="darwin"&&e!=="win32"?{ok:!1,message:"WeChat channel product source requires macOS or Windows"}:(Array.isArray(t.groups)?t.groups.map(n=>String(n?.name||"").trim()).filter(Boolean):[]).length?{ok:!0,message:"WeChat channel product source configured"}:{ok:!1,message:"WeChat channel product source requires at least one group"}}async function Se(t,e,r){const n=await z(t.workDir),a=[];for(const i of g(e)){const s=await Pe(n,t,e,i);if(r?.(s),!(!s.ok||s.interrupted))for(const u of s.newMessages??[]){const o=G(i,u,e);o&&a.push(o)}}return a}async function Pe(t,e,r,n){const a=fe(r.recentLimit),i={kind:a,requestId:`wechat-rpa:${n}:read:${Date.now()}`,targetGroup:n,policy:r.forceForeground?"work":"polite",limit:P(r.recentLimit,A,1,50),attachmentsDir:L(e,r)},s=await t.runWechatRpaReadLatest(i),u=Array.isArray(s.data?.structuredMessages)?s.data.structuredMessages:[],o=s.validation?.deterministic?.latestMessages??[],c=u.length?u.map((l,p)=>Ie(l,s.runId||"lab-read",p)):o.map((l,p)=>({id:`${s.runId||"lab-read"}:${p}`,text:l,confidence:.8}));return{ok:!!s.ok,groupName:n,interrupted:s.status==="interrupted",reason:s.status,rpaRunId:s.runId,rpaTraceSummary:`${a} ${s.status||(s.ok?"success":"failed")} ${n}`,recentMessages:c,newMessages:c,screenshotPath:s.tracePath,error:X(s)}}function Ie(t,e,r){return{id:`${e}:${t.index??r}`,text:String(t.text||t.card?.title||"").trim(),confidence:typeof t.confidence=="number"?t.confidence:.75,senderName:typeof t.senderName=="string"?t.senderName:null,attachments:Ae(t)}}function Ae(t){const e=String(t.kind||"");if(!["image","file","video-file","video-card","link-card","official-account-card","mini-program-card"].includes(e))return[];const r=typeof t.localPath=="string"?t.localPath:void 0;return[{type:e==="video-file"||e==="video-card"?"video":e==="link-card"||e==="official-account-card"||e==="mini-program-card"?"file":e,localPath:r,availability:r?"edge-local":"metadata-only"}]}async function Ce(t,e,r,n,a,i){const s=await z(t.workDir),u=be({groupName:r,text:n,attachmentPath:a,dedupeKey:i,requestId:i,policy:"work"}),o=[];for(const f of u){const v=await s.runWechatRpaTask(f);if(o.push(v),!v.ok)break}const c=o.find(f=>f.kind==="send-text"),l=o.find(f=>f.kind==="send-image"||f.kind==="send-video"||f.kind==="send-file"),p=u.length>0&&o.length===u.length&&o.every(f=>f.ok),d=o.some(f=>f.status==="interrupted");return{ok:p,groupName:r,interrupted:d,reason:o.at(-1)?.status,rpaRunId:o.at(-1)?.runId,rpaTraceSummary:`send ${p?"success":o.at(-1)?.status||"failed"} ${r} (${o.length}/${u.length})`,sentReply:!!n,sentReplyObserved:n?!!c?.ok:!1,sentAttachment:!!a,sentAttachmentObserved:a?!!l?.ok:!1,postSendScreenshotPath:o.at(-1)?.tracePath,error:p?void 0:X(o.at(-1))}}function be(t){const e=[],r=String(t.text||"").trim(),n=t.policy||"work";if(r&&e.push({kind:"send-text",requestId:t.requestId?`${t.requestId}:text`:void 0,targetGroup:t.groupName,policy:n,text:r,...t.dedupeKey?{dedupeKey:`${t.dedupeKey}:text`}:{}}),t.attachmentPath){const a=ke(t.attachmentPath);e.push({kind:a,requestId:t.requestId?`${t.requestId}:attachment`:void 0,targetGroup:t.groupName,policy:n,filePath:t.attachmentPath,...t.dedupeKey?{dedupeKey:`${t.dedupeKey}:attachment`}:{}})}return e}function ke(t){const e=h.extname(t).toLowerCase();return[".png",".jpg",".jpeg",".gif",".webp",".heic"].includes(e)?"send-image":[".mp4",".mov",".avi",".mkv"].includes(e)?"send-video":"send-file"}async function z(t){const e=J(t);return await import(te(e).href)}function J(t){const e=h.dirname(ee(import.meta.url)),n=[process.env.SHENNIAN_WECHAT_RPA_LAB_INDEX,h.resolve(e,"../../../../scripts/wechat-rpa-lab/index.mjs"),t?h.join(t,"scripts/wechat-rpa-lab/index.mjs"):"",h.resolve(process.cwd(),"scripts/wechat-rpa-lab/index.mjs")].filter(Boolean).find(a=>m.existsSync(a));if(!n)throw new Error("WeChat RPA Lab API is missing; set SHENNIAN_WECHAT_RPA_LAB_INDEX or run from the repository root");return h.resolve(n)}function X(t){return t?typeof t.error=="string"?t.error:t.error?.message||(t.ok?void 0:`WeChat RPA Lab task ${t.kind||"<unknown>"} ${t.status||"failed"}`):"WeChat RPA Lab did not return a result"}async function xe(t,e,r){const n=[];for(const a of g(e)){const i=await F({groupName:a,scriptPath:e.flowScriptPath,workDir:t.workDir,forceForeground:k(e),noRestore:e.noRestore!==!1,idleSeconds:P(e.idleSeconds,15,0,3600),recentLimit:P(e.recentLimit,A,0,50),downloadAttachmentsDir:L(t,e)});if(r?.(i),!i.interrupted)for(const s of i.newMessages??[]){const u=G(a,s,e);u&&n.push(u)}}return n}async function Ne(t,e,r){const n=g(e)[0]||"<unbound>";return r?.({ok:!1,groupName:n,interrupted:!0,reason:"windows-visual-flow-archived",newMessages:[],recentMessages:[],error:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}),[]}function G(t,e,r){const n=String(e.text||"").trim(),a=Array.isArray(e.attachments)?e.attachments:[];if(!n&&a.length===0)return null;const i=typeof e.senderName=="string"?e.senderName.trim():"",s=String(e.observedAt||e.timestampIso||"").trim()||new Date().toISOString();return{conversationName:t,senderName:i||null,text:n,attachments:ze(a),observedAt:s,isMentioned:e.isMentioned===!0||ye(n,U(r)),rawId:String(e.id||`${t}:${i}:${n}:${s}`)}}async function V(t,e,r,n,a,i){return e.source==="windows-visual-flow"?{ok:!1,groupName:r,interrupted:!0,reason:"windows-visual-flow-archived",newMessages:[],recentMessages:[],error:"WeChat RPA Windows visual flow is archived; redesign Windows support before enabling it"}:e.source==="wechat-rpa-lab"?Ce(t,e,r,n,a,i):F({groupName:r,replyText:n||void 0,attachmentPath:a,scriptPath:e.flowScriptPath,workDir:t.workDir,forceForeground:k(e),noRestore:e.noRestore!==!1,idleSeconds:P(e.idleSeconds,15,0,3600),recentLimit:P(e.recentLimit,A,0,50),downloadAttachmentsDir:L(t,e)})}function We(t){return t==="macos-flow"||t==="wechat-rpa-lab"}function Y(t,e){return e.text&&e.attachmentPath&&t.sentReplyObserved&&!t.sentAttachmentObserved?{status:t.interrupted?"continue":"queued",text:"",attachmentPath:e.attachmentPath,skipText:!0,reason:t.error||"WeChat RPA sent the text but did not confirm the attachment; queued attachment-only retry"}:{status:"continue",text:e.text,attachmentPath:e.attachmentPath,reason:t.error||""}}function Ee(t,e){return e.idempotencyKey?e.idempotencyKey:I.createHash("sha256").update(`${t.id}
|
|
2
2
|
${e.conversationId}
|
|
3
3
|
${e.text}
|
|
4
4
|
${e.attachment?.name||""}
|
|
5
|
-
${e.attachment?.size||0}`).digest("hex").slice(0,24)}function
|
|
6
|
-
`).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>!!e)}async function
|
|
7
|
-
${n.conversationId}
|
|
8
|
-
${n.messageId}`;e.has(a)||(e.add(a),r.push(n))}return r}export{it as WeChatRpaChannelAdapter,Je as annotateWeChatRpaInboundAttachments,Be as materializeWeChatRpaOutboundAttachment,ke as planWeChatRpaLabSendTasks,D as resolveWeChatRpaInboundAttachmentDir,me as selectWeChatRpaLabReadKind,xe as weChatRpaLabTaskKindForAttachment,Se as weChatRpaProductSourceHealth,ve as windowsVisualFlowHealth};
|
|
5
|
+
${e.attachment?.size||0}`).digest("hex").slice(0,24)}function Te(t,e){return[...Array.from(t.pendingReplies.values()).map(n=>({replyId:n.key,idempotencyKey:n.key,status:"queued",conversationName:n.conversationName,reasonCode:n.lastInterruptedReason??null,nextAttemptAt:null,queuedAt:n.queuedAt,lastAttemptAt:n.lastAttemptAt??null,attemptCount:n.attempts,commitStage:null})),...ce({config:e})].slice(0,100)}function T(t,e){const r=t.pendingReplies.get(e.key);t.pendingReplies.set(e.key,{key:e.key,conversationId:e.conversationId,conversationName:e.conversationName,text:e.text,attachmentPath:e.attachmentPath,skipText:e.skipText,queuedAt:r?.queuedAt??new Date().toISOString(),attempts:r?.attempts??0,lastAttemptAt:r?.lastAttemptAt,lastInterruptedReason:e.reason}),R(t)}function Q(t,e,r){t.manualReviewReplies.set(e,{key:e,reason:r,createdAt:t.manualReviewReplies.get(e)?.createdAt??new Date().toISOString()}),t.lastError=r,w(t,{status:"failed",runId:t.lastRunId??null,summary:`manual review required: ${r}`}),R(t)}function O(t,e){const r=$e(e);if(t.pendingStatePath===r)return;t.pendingStatePath=r;const n=Oe(r);for(const a of n.pending??[])Me(a)&&(t.pendingReplies.has(a.key)||t.pendingReplies.set(a.key,a));for(const a of n.manualReview??[])_e(a)&&(t.manualReviewReplies.has(a.key)||t.manualReviewReplies.set(a.key,a));for(const a of n.completedKeys??[])typeof a=="string"&&a&&t.completedPendingReplyKeys.add(a)}function R(t){if(!t.pendingStatePath)return;const e=Array.from(t.completedPendingReplyKeys).slice(-500),r=Array.from(t.pendingReplies.values()).slice(0,500),n=Array.from(t.manualReviewReplies.values()).slice(-500);try{m.mkdirSync(h.dirname(t.pendingStatePath),{recursive:!0}),m.writeFileSync(t.pendingStatePath,JSON.stringify({version:1,pending:r,manualReview:n,completedKeys:e},null,2))}catch{}}function Oe(t){try{const e=JSON.parse(m.readFileSync(t,"utf8"));return e&&e.version===1?e:{version:1,pending:[],completedKeys:[]}}catch{return{version:1,pending:[],completedKeys:[]}}}function Me(t){if(!t||typeof t!="object")return!1;const e=t;return typeof e.key=="string"&&typeof e.conversationId=="string"&&typeof e.conversationName=="string"&&typeof e.text=="string"&&typeof e.queuedAt=="string"&&typeof e.attempts=="number"&&Number.isFinite(e.attempts)&&(e.attachmentPath===void 0||typeof e.attachmentPath=="string")&&(e.skipText===void 0||typeof e.skipText=="boolean")}function _e(t){if(!t||typeof t!="object")return!1;const e=t;return typeof e.key=="string"&&typeof e.reason=="string"&&typeof e.createdAt=="string"}function $e(t){const e=I.createHash("sha256").update(t.id).digest("hex").slice(0,16);return h.join(t.workDir,".shennian","wechat-rpa-pending-replies",`${e}.json`)}function M(t,e){const r=qe(e);if(t.messageStatePath===r)return;t.messageStatePath=r;const n=Le(r);t.deduper=new K((n.messageIds??[]).filter(a=>typeof a=="string"&&a.length>0))}function De(t){if(t.messageStatePath)try{m.mkdirSync(h.dirname(t.messageStatePath),{recursive:!0}),m.writeFileSync(t.messageStatePath,JSON.stringify({version:1,messageIds:t.deduper.snapshot()},null,2))}catch{}}function Le(t){try{const e=JSON.parse(m.readFileSync(t,"utf8"));return e&&e.version===1?e:{version:1,messageIds:[]}}catch{return{version:1,messageIds:[]}}}function qe(t){const e=I.createHash("sha256").update(t.id).digest("hex").slice(0,16);return h.join(t.workDir,".shennian","wechat-rpa-seen-messages",`${e}.json`)}function _(t,e,r){t.lastInterruptedAt=new Date().toISOString(),t.lastError=null,t.consecutiveInterruptions+=1,t.runtimeState="interrupted",Fe(t)&&(t.interruptionCooldownUntil=Date.now()+E,t.runtimeState="cooldown"),w(t,{status:"interrupted",runId:e.rpaRunId||t.lastRunId||null,summary:r})}function C(t){t.consecutiveInterruptions=0,t.interruptionCooldownUntil=void 0,t.runtimeState="idle_waiting"}function $(t,e){const r=e.postSendScreenshotPath||e.screenshotPath;e.rpaRunId&&(t.lastRunId=e.rpaRunId),r&&(t.lastTracePath=r),t.lastTraceSummary=e.rpaTraceSummary||[e.groupName?`group=${e.groupName}`:"",e.ok===!1?"failed":e.interrupted?"interrupted":"ok",e.reason?`reason=${e.reason}`:""].filter(Boolean).join(" ")}function w(t,e){const r=e.runId||t.lastRunId||`local:${Date.now().toString(36)}`;t.lastRunId=r,t.recentTaskSummaries.unshift({at:new Date().toISOString(),status:e.status,runId:r,summary:D(e.summary)}),t.recentTaskSummaries=t.recentTaskSummaries.slice(0,he)}function b(t){const e=String(t||"").toLowerCase();return/permission|accessibility|screen recording|automation|window|foreground|target group|refusing|requires|安全|权限|窗口|目标群/.test(e)?"blocked":"failed"}function D(t){return String(t||"").replace(/\s+/g," ").trim().slice(0,180)}function Z(t,e){if(k(e))return!1;const r=t.interruptionCooldownUntil;return r?Date.now()<r?!0:(t.interruptionCooldownUntil=void 0,t.consecutiveInterruptions=0,!1):!1}function k(t){return t.forceForeground!==!1}function Fe(t){return!Number.isFinite(W)||W<=0||!Number.isFinite(E)||E<=0?!1:t.consecutiveInterruptions>=W}function Ke(t){return!t||!m.existsSync(t)?[]:m.readFileSync(t,"utf-8").split(`
|
|
6
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(e=>!!e)}async function He(t,e){if(e.localPath){if(!m.existsSync(e.localPath))throw new Error(`WeChat RPA local attachment does not exist: ${e.localPath}`);return e.localPath}if(e.url)return Be(t,e);throw new Error("WeChat RPA attachment requires localPath or url; dataBase64 is not accepted over Manager IPC")}async function Be(t,e){if(!e.url||!/^https?:\/\//i.test(e.url))throw new Error("WeChat RPA attachment url must be http(s)");if(Number.isFinite(e.size)&&e.size>S)throw new Error(`WeChat RPA cross-machine attachment is too large: ${e.size} bytes. Max: ${S} bytes.`);const r=await fetch(e.url);if(!r.ok)throw new Error(`WeChat RPA attachment url download failed: ${r.status}`);const n=Number(r.headers.get("content-length")||e.size||0);if(n>S)throw new Error(`WeChat RPA cross-machine attachment is too large: ${n} bytes. Max: ${S} bytes.`);const a=Buffer.from(await r.arrayBuffer());return je(t,e,a)}function je(t,e,r){if(!r.byteLength)throw new Error("WeChat RPA attachment is empty");if(r.byteLength>S)throw new Error(`WeChat RPA cross-machine attachment is too large: ${r.byteLength} bytes. Max: ${S} bytes.`);const n=h.join(t,".uploads","wechat-rpa","outbound");m.mkdirSync(n,{recursive:!0});const a=Ue(e.name||"attachment"),i=I.createHash("sha256").update(r).digest("hex").slice(0,12),s=h.extname(a),u=s?a.slice(0,-s.length):a,o=h.join(n,`${u}-${i}${s}`);return m.existsSync(o)||m.writeFileSync(o,r),o}function Ue(t){return h.basename(t||"attachment").normalize("NFKC").replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").replace(/\s+/g," ").replace(/^[ ._]+|[ ._]+$/g,"")||"attachment"}function L(t,e){if(e.downloadAttachments===!1)return;const r=e.downloadAttachmentsDir?.trim();if(r)return h.resolve(r);const n=I.createHash("sha256").update(t.id).digest("hex").slice(0,16);return ne("wechat-rpa","attachments","inbound",n)}function ze(t){if(!Array.isArray(t))return[];const e=process.env.SHENNIAN_MACHINE_ID?.trim();return t.map(r=>r?.localPath?{...r,availability:r.availability||"edge-local",...r.machineId||!e?{}:{machineId:e}}:r)}function P(t,e,r,n){const a=Number(t);return Number.isFinite(a)?Math.min(n,Math.max(r,a)):e}export{at as WeChatRpaChannelAdapter,ze as annotateWeChatRpaInboundAttachments,He as materializeWeChatRpaOutboundAttachment,be as planWeChatRpaLabSendTasks,L as resolveWeChatRpaInboundAttachmentDir,fe as selectWeChatRpaLabReadKind,ke as weChatRpaLabTaskKindForAttachment,ve as weChatRpaProductSourceHealth,Re as windowsVisualFlowHealth};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { DaemonStatus } from './daemon.js';
|
|
2
|
+
export declare function isDaemonReadyStatus(status: Pick<DaemonStatus, 'running' | 'stale'>): boolean;
|
|
3
|
+
export declare function waitForDaemonReadyStatus(readStatus: () => DaemonStatus, opts?: {
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
intervalMs?: number;
|
|
6
|
+
now?: () => number;
|
|
7
|
+
sleep?: (ms: number) => void;
|
|
8
|
+
}): DaemonStatus;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const T=2e4,c=500;function M(n){return n.running===!0&&n.stale!==!0}function s(n){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n)}function u(n,t={}){const r=Math.max(0,t.timeoutMs??2e4),i=Math.max(1,t.intervalMs??500),e=t.now??Date.now,A=t.sleep??s,o=e()+r;let a=n();for(;!M(a)&&e()<o;){const _=Math.max(1,o-e());A(Math.min(i,_)),a=n()}return a}export{M as isDaemonReadyStatus,u as waitForDaemonReadyStatus};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import s from"chalk";import o from"node:fs";import d from"node:path";import a from"node:os";import{execSync as c,spawn as
|
|
2
|
-
`)}function
|
|
1
|
+
import s from"chalk";import o from"node:fs";import d from"node:path";import a from"node:os";import{execSync as c,spawn as ce}from"node:child_process";import{randomUUID as ae}from"node:crypto";import{fileURLToPath as ue}from"node:url";import{getShennianDir as de,loadConfig as j,resolveShennianPath as h,saveConfig as le}from"../config/index.js";import{buildAugmentedPath as pe}from"../env-path.js";import{buildWindowsLauncherCommand as me,buildWindowsScheduledTaskXml as fe,buildWindowsStartupVbs as Se,escapeXml as N,isWindowsCmdScript as he,quoteCmdArg as W,quoteSystemdArg as ge}from"./daemon-windows.js";import{waitForDaemonReadyStatus as b}from"./daemon-start-wait.js";import{findRunningWindowsDaemonProcessIds as ye,isShennianRunServiceCommand as we}from"./daemon-process.js";import{buildWindowsLauncherCommand as fn,buildWindowsScheduledTaskXml as Sn,buildWindowsStartupVbs as hn}from"./daemon-windows.js";import{isShennianRunServiceCommand as yn}from"./daemon-process.js";const ve=d.dirname(ue(import.meta.url)),y=de(),p=h("daemon.pid"),u=h("daemon.log"),L=h("remote-access.disabled"),I=h("daemon-launcher.json"),F=d.resolve(ve,"../../bin/shennian.js"),B=process.execPath,V=new Set(["PATH","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","USERNAME","USERDOMAIN","COMPUTERNAME","USER","LOGNAME","SHELL","TMPDIR","LANG","LC_ALL","LC_CTYPE","SSH_AUTH_SOCK","XDG_CONFIG_HOME","XDG_DATA_HOME","TEMP","TMP","APPDATA","LOCALAPPDATA","SHENNIAN_DESKTOP_SERVER_URL","SHENNIAN_WECHAT_CHANNEL_HELPER_DIR","SHENNIAN_HOME","SHENNIAN_NATIVE_FUSION_DISABLED","SHENNIAN_WECHAT_DELIVERABILITY_TRACE"]);function Ee(e){return V.has(e)}function l(){const e=a.platform();return e==="darwin"||e==="linux"||e==="win32"?e:"linux"}function R(e){const n=e.replace(/\\/g,"/").toLowerCase(),t=a.tmpdir().replace(/\\/g,"/").toLowerCase();return n.includes("/_npx/")||n.includes("/npm-cache/_npx/")||n.includes("/pnpm/dlx/")||n.startsWith(t.endsWith("/")?t:`${t}/`)}function ke(e){return o.existsSync(e.scriptPath)&&!R(e.scriptPath)?{command:e.nodeExec,args:[e.scriptPath,"run-service"],mode:"direct"}:e.shennianCommandPath&&!R(e.shennianCommandPath)?{command:e.shennianCommandPath,args:["run-service"],mode:"global-shim"}:e.npxPath?{command:e.npxPath,args:["--yes","shennian","run-service"],mode:"npx"}:{command:e.nodeExec,args:[e.scriptPath,"run-service"],mode:"direct"}}function Pe(e){const n=e.trim();if(!n)return null;if(n.startsWith("{"))try{const r=JSON.parse(n),i=Number(r.pid);return!Number.isInteger(i)||i<=0?null:{pid:i,...typeof r.instanceId=="string"?{instanceId:r.instanceId}:{},...typeof r.version=="string"?{version:r.version}:{},...r.launcher==="desktop-managed"||r.launcher==="global-cli"||r.launcher==="unknown"?{launcher:r.launcher}:{},...typeof r.startedAt=="string"?{startedAt:r.startedAt}:{},...r.adopted===!0?{adopted:!0}:{}}}catch{return null}const t=parseInt(n,10);return isNaN(t)?null:{pid:t}}function O(){try{return Pe(o.readFileSync(p,"utf-8"))}catch{return null}}function Ae(){return O()?.pid??null}function w(e){try{return process.kill(e,0),!0}catch{return!1}}function Ie(e,n=3e3){const t=Date.now();for(;Date.now()-t<n;){if(!w(e))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!w(e)}function De(){return o.existsSync(L)}function Ne(){try{o.unlinkSync(L)}catch{}}function J(){return"global-cli"}function be(){return`${process.pid}-${Date.now()}-${ae()}`}function Le(e,n,t={}){o.mkdirSync(y,{recursive:!0}),o.writeFileSync(p,JSON.stringify({pid:e,instanceId:n,...t.version?{version:t.version}:{},launcher:t.launcher??J(),...t.adopted?{adopted:!0}:{},startedAt:new Date().toISOString()},null,2))}function dn(e,n){const t=O();if(!(t?.pid!==e||t.instanceId!==n))try{o.unlinkSync(p)}catch{}}function G(e,n=J(),t){o.mkdirSync(y,{recursive:!0}),o.writeFileSync(I,JSON.stringify({pid:e,launcher:n,...t?{instanceId:t}:{},updatedAt:new Date().toISOString()},null,2))}function T(e){if(e)try{if(JSON.parse(o.readFileSync(I,"utf-8")).instanceId!==e)return}catch{return}try{o.unlinkSync(I)}catch{}}function Re(e){e&&G(e)}function Oe(e,n){if(!e||!n)return"unknown";try{const t=JSON.parse(o.readFileSync(I,"utf-8"));if(t.pid!==e)return"unknown";if(t.launcher==="desktop-managed"||t.launcher==="global-cli")return t.launcher}catch{}return x(e)}function x(e){if(l()==="win32")return"unknown";try{const n=c(`ps -p ${e} -o command=`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e3,windowsHide:!0}).replace(/\\/g,"/");if(n.includes("/node_modules/shennian/")||n.includes("/bin/shennian")||n.includes(" shennian run-service")||n.includes(" shennian.js run-service"))return"global-cli"}catch{}return"unknown"}function K(e=process.pid){if(l()==="win32")return ye(e);try{return c("ps -axo pid=,command=",{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e3,windowsHide:!0}).split(/\r?\n/).map(t=>{const r=t.trim().match(/^(\d+)\s+(.+)$/);if(!r)return null;const i=Number(r[1]),S=r[2];return!Number.isInteger(i)||i===e?null:we(S)?i:null}).filter(t=>typeof t=="number")}catch{return[]}}function f(e={}){let n=O(),t=n?.pid??null,r=t!==null&&w(t),i=t!==null&&!r,S=n?.adopted===!0;const v=j();if(i&&e.cleanupStale){try{o.unlinkSync(p)}catch{}n=null,t=null,r=!1,i=!1}if(!r){const g=K()[0];if(g&&(t=g,r=!0,i=!1,S=!0,e.cleanupStale)){const M=be();Le(g,M,{launcher:x(g),adopted:!0}),G(g,x(g)),n={pid:g,instanceId:M,adopted:!0}}}return{running:r,pid:t,stale:i,remoteAccessDisabled:De(),launcher:Oe(t,r),platform:l(),shennianDir:y,pidFile:p,logFile:u,...n?.instanceId?{instanceId:n.instanceId}:{},...S?{adopted:!0}:{},...v.machineId?{machineId:v.machineId}:{},paired:!!(v.machineToken&&v.machineId),...v.serverUrl?{serverUrl:v.serverUrl}:{}}}function E(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function X(e){const n=e?.trim();if(!n)return;const t=j();t.serverUrl=n,le(t)}function q(e){return e?.trim()||process.env.SHENNIAN_DESKTOP_SERVER_URL?.trim()||void 0}const $="com.shennian.agent",m=d.join(a.homedir(),"Library/LaunchAgents",`${$}.plist`),Te=d.join(a.homedir(),"AppData","Roaming","Microsoft","Windows","Start Menu","Programs","Startup"),H=h("autostart.cmd"),_=h("autostart.vbs"),U=h("autostart.xml"),xe=d.join(Te,"ShennianAgent.vbs");function Y(e){const n=l()==="win32"?`where ${e}`:`command -v ${e}`;try{return c(n,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",windowsHide:!0}).split(/\r?\n/).map(i=>i.trim()).find(Boolean)??null}catch{return null}}function $e(){const e=l()==="win32"?"npx.cmd":"npx",n=d.join(d.dirname(B),e);return o.existsSync(n)?n:Y("npx")}function k(){return ke({nodeExec:B,scriptPath:F,shennianCommandPath:Y("shennian"),npxPath:$e()})}function z(){try{c(`schtasks /delete /tn "${P}" /f`,{stdio:"pipe",windowsHide:!0})}catch{}}function Q(){try{o.unlinkSync(xe)}catch{}}function He(){const e=process.env.USERDOMAIN?.trim(),n=process.env.COMPUTERNAME?.trim(),t=process.env.USERNAME?.trim()||a.userInfo().username;return e&&e.toUpperCase()!=="WORKGROUP"?`${e}\\${t}`:n?`${n}\\${t}`:t}function _e(e){if(l()==="win32"&&he(e.command)){const n=[e.command,...e.args].map(W).join(" ");return{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",`"${n}"`],windowsVerbatimArguments:!0}}return{command:e.command,args:e.args}}function Ue(e,n,t=process.env){return{detached:!0,stdio:["ignore",n,n],env:t,windowsHide:!0,...e.windowsVerbatimArguments?{windowsVerbatimArguments:!0}:{}}}function Ce(){const e=k();o.writeFileSync(H,me(e,u)),o.writeFileSync(_,Se(H)),Q(),z();const n=fe({userId:He(),command:d.join(process.env.SystemRoot||"C:\\Windows","System32","wscript.exe"),arguments:[W(_)]});o.writeFileSync(U,n,"utf8");try{return c(`schtasks /create /tn "${P}" /xml "${U}" /f`,{stdio:"pipe",windowsHide:!0}),c(`schtasks /run /tn "${P}"`,{stdio:"pipe",windowsHide:!0}),!0}catch{return!1}}function Z(){const e={};for(const n of V)process.env[n]&&(e[n]=process.env[n]);if(e.HOME??=a.homedir(),e.PATH=pe({pathValue:e.PATH,env:e}),e.USER??=a.userInfo().username,l()==="win32"){const n=process.env.TEMP||process.env.TMP||a.tmpdir(),t=a.homedir();e.USERPROFILE??=t;const r=d.win32.parse(t);e.HOMEDRIVE??=r.root.replace(/[\\/]$/,"")||process.env.HOMEDRIVE||"",e.HOMEPATH??=t.slice((e.HOMEDRIVE||"").length)||process.env.HOMEPATH||"",e.USERNAME??=process.env.USERNAME||a.userInfo().username,e.COMPUTERNAME??=process.env.COMPUTERNAME||"",e.TMPDIR??=n,e.TEMP??=n,e.TMP??=n}else e.TMPDIR??="/tmp";return e}function Me(){const e=Z(),n=k(),t=Object.entries(e).map(([i,S])=>` <key>${N(i)}</key>
|
|
3
3
|
<string>${N(S)}</string>`).join(`
|
|
4
|
-
`),r=[
|
|
4
|
+
`),r=[n.command,...n.args].map(i=>` <string>${N(i)}</string>`).join(`
|
|
5
5
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
6
6
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
7
7
|
<plist version="1.0">
|
|
8
8
|
<dict>
|
|
9
9
|
<key>Label</key>
|
|
10
|
-
<string>${
|
|
10
|
+
<string>${$}</string>
|
|
11
11
|
<key>ProgramArguments</key>
|
|
12
12
|
<array>
|
|
13
13
|
${r}
|
|
@@ -27,8 +27,8 @@ ${t}
|
|
|
27
27
|
<key>StandardErrorPath</key>
|
|
28
28
|
<string>${u}</string>
|
|
29
29
|
</dict>
|
|
30
|
-
</plist>`}const D=d.join(a.homedir(),".config/systemd/user/shennian.service");function
|
|
31
|
-
`),r=[
|
|
30
|
+
</plist>`}const D=d.join(a.homedir(),".config/systemd/user/shennian.service");function je(){const e=Z(),n=k(),t=Object.entries(e).map(([i,S])=>`Environment=${i}=${S}`).join(`
|
|
31
|
+
`),r=[n.command,...n.args].map(ge).join(" ");return`[Unit]
|
|
32
32
|
Description=Shennian Agent Daemon
|
|
33
33
|
After=network.target
|
|
34
34
|
|
|
@@ -41,6 +41,6 @@ StandardOutput=append:${u}
|
|
|
41
41
|
StandardError=append:${u}
|
|
42
42
|
|
|
43
43
|
[Install]
|
|
44
|
-
WantedBy=default.target`}const P="ShennianAgent";function
|
|
45
|
-
`).slice(-
|
|
46
|
-
`))}}async function
|
|
44
|
+
WantedBy=default.target`}const P="ShennianAgent";function We(e){c(e,{stdio:"pipe",windowsHide:!0})}function Fe(){const e=process.getuid?.();if(typeof e=="number")return e;const n=a.userInfo();return typeof n.uid=="number"?n.uid:n.username}function ee(e=Fe()){return`gui/${e}/${$}`}function Be(e=We){try{return e(`launchctl unload "${m}" 2>/dev/null; launchctl load -w "${m}"`),e(`launchctl kickstart -k "${ee()}"`),!0}catch{try{return e(`launchctl load -w "${m}"`),e(`launchctl kickstart -k "${ee()}"`),!0}catch{return!1}}}function Ve(){o.mkdirSync(y,{recursive:!0});const e={};for(const[n,t]of Object.entries(process.env))t!==void 0&&Ee(n)&&(e[n]=t);o.writeFileSync(h("env.json"),JSON.stringify(e,null,2))}function ne(e={}){o.mkdirSync(y,{recursive:!0});const n=f({cleanupStale:!0});if(n.pid!==null&&n.running&&!n.adopted){e.quiet||console.log(s.green(`\u2713 Background service already running (PID ${n.pid})`));return}te(n);const t=o.openSync(u,"a"),r=_e(k()),i=ce(r.command,r.args,Ue(r,t));i.unref(),o.closeSync(t),Re(i.pid),e.quiet||(console.log(s.green(`\u2713 Background service started (PID ${i.pid})`)),console.log(s.gray(` Logs: ${u}`)))}function te(e=f({cleanupStale:!0})){if(!(e.pid===null||!e.running||!e.adopted))try{process.kill(e.pid,"SIGTERM"),Ie(e.pid);try{o.unlinkSync(p)}catch{}}catch{}}function re(){o.mkdirSync(y,{recursive:!0});const e=l();switch(k().mode==="direct"&&R(F)&&console.warn(s.yellow("\u26A0 Warning: Current CLI path is temporary (npx). Auto-start may not work after reboot.\n Run `npm install -g shennian@latest` for reliable auto-start.")),e){case"darwin":{const t=d.dirname(m);return o.mkdirSync(t,{recursive:!0}),o.writeFileSync(m,Me()),Be()}case"linux":{const t=d.dirname(D);o.mkdirSync(t,{recursive:!0}),o.writeFileSync(D,je());try{c("systemctl --user daemon-reload && systemctl --user enable shennian",{stdio:"pipe",windowsHide:!0})}catch{return!1}try{c(`loginctl enable-linger ${a.userInfo().username}`,{stdio:"pipe",windowsHide:!0})}catch{}try{return c("systemctl --user restart shennian",{stdio:"pipe",windowsHide:!0}),!0}catch{return!1}}case"win32":return Ce()}}function Je(){const n=f({cleanupStale:!0}).pid;if(n===null)return{};if(!w(n)){try{o.unlinkSync(p)}catch{}return{stalePid:n}}try{return process.kill(n,"SIGTERM"),{stoppedPid:n}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}async function Ge(e=5e3){const n=Je();if(!n.stoppedPid)return n;if(!await A(n.stoppedPid,e))try{process.kill(n.stoppedPid,"SIGKILL"),await A(n.stoppedPid,2e3)}catch(r){return{...n,error:r instanceof Error?r.message:String(r)}}try{o.unlinkSync(p)}catch{}T();for(const r of K())if(r!==n.stoppedPid)try{process.kill(r,"SIGTERM"),await A(r,2e3)}catch{}return n}function Ke(e={}){X(q(e.api)),Ne(),te(),re()||ne({quiet:e.json}),e.json?E(b(()=>f({cleanupStale:!0}))):console.log(s.green("\u2713 Background service started"))}async function Xe(e={}){switch(o.mkdirSync(y,{recursive:!0}),o.writeFileSync(L,new Date().toISOString()),l()){case"darwin":{if(o.existsSync(m))try{c(`launchctl unload -w "${m}"`,{stdio:"pipe",windowsHide:!0})}catch{}break}case"linux":{try{c("systemctl --user disable --now shennian",{stdio:"pipe",windowsHide:!0})}catch{}break}case"win32":{try{c(`schtasks /change /tn "${P}" /disable`,{stdio:"pipe",windowsHide:!0})}catch{}try{c(`schtasks /end /tn "${P}"`,{stdio:"pipe",windowsHide:!0})}catch{}break}}const t=await Ge(),r=f({cleanupStale:!0});if(e.json){E(t.error?{...r,error:t.error}:r);return}t.error?console.error(s.red(`\u2717 Failed to stop: ${t.error}`)):console.log(s.green("\u2713 Background service stopped"))}function oe(e){Ve(),Ke(e)}async function C(e={}){await Xe(e)}async function A(e,n=5e3){const t=Date.now();for(;Date.now()-t<n;){if(!w(e))return!0;await new Promise(r=>setTimeout(r,100))}return!w(e)}async function qe(e={}){X(q(e.api));const n=Ae();if(n!==null&&w(n))try{process.kill(n,"SIGTERM"),await A(n)||(process.kill(n,"SIGKILL"),await A(n,2e3));try{o.unlinkSync(p)}catch{}T(),e.json||console.log(s.green(`\u2713 Background service stopped (PID ${n})`))}catch(t){const r=t instanceof Error?t.message:String(t);e.json?E({...f(),error:r}):console.error(s.red(`\u2717 Failed to stop: ${r}`));return}else if(n!==null){try{o.unlinkSync(p)}catch{}T(),e.json||console.log(s.yellow(`\u26A0 Service process no longer exists, cleaned up stale PID ${n}`))}else e.json||console.log(s.gray("\u25CF Background service not running, starting it now"));if(l()==="linux"&&re()){e.json&&E(b(()=>f({cleanupStale:!0})));return}ne({quiet:e.json}),e.json&&E(b(()=>f({cleanupStale:!0})))}function ie(e={}){const n=f({cleanupStale:!0});if(e.json){E(n);return}if(n.pid===null){console.log(s.gray("\u25CF Background service not running"));return}n.running?(console.log(s.green(`\u25CF Background service running (PID ${n.pid})`)),console.log(s.gray(` Logs: ${u}`))):console.log(s.yellow(`\u25CF Background service stopped (PID ${n.pid} is stale)`))}function se(e){if(!o.existsSync(u)){console.log(s.gray("No logs yet"));return}try{const n=c(a.platform()==="win32"?`powershell Get-Content -Tail ${e.lines} "${u}"`:`tail -n ${e.lines} "${u}"`,{encoding:"utf-8",windowsHide:!0});process.stdout.write(n)}catch{const n=o.readFileSync(u,"utf-8").split(`
|
|
45
|
+
`).slice(-e.lines);console.log(n.join(`
|
|
46
|
+
`))}}async function Ye(){switch(await C(),l()){case"darwin":{if(o.existsSync(m)){try{c(`launchctl unload -w "${m}"`,{stdio:"pipe",windowsHide:!0})}catch{}o.unlinkSync(m),console.log(s.green("\u2713 Auto-start uninstalled (launchd)"))}break}case"linux":{try{c("systemctl --user disable --now shennian",{stdio:"pipe",windowsHide:!0})}catch{}if(o.existsSync(D)){o.unlinkSync(D);try{c("systemctl --user daemon-reload",{stdio:"pipe",windowsHide:!0})}catch{}}console.log(s.green("\u2713 Auto-start uninstalled (systemd)"));break}case"win32":{z();try{o.unlinkSync(H)}catch{}try{o.unlinkSync(_)}catch{}try{o.unlinkSync(U)}catch{}Q(),console.log(s.green("\u2713 Auto-start uninstalled (Task Scheduler)"));break}}}function ln(e){e.command("start").description("Start the background service").option("--json","Print machine-readable status JSON").option("--api <url>","Server URL override").action(r=>oe(r)),e.command("stop").description("Stop the background service").option("--json","Print machine-readable status JSON").action(r=>C(r)),e.command("status").description("Show background service status").option("--json","Print machine-readable status JSON").action(r=>ie(r)),e.command("logs").description("Show recent logs").option("-n, --lines <n>","Number of lines","50").action(r=>se({lines:parseInt(r.lines,10)}));const n=e.command("daemon",{hidden:!0}).description("Deprecated: use top-level start/stop/status/logs"),t=(r,i)=>{i||console.error(s.yellow(`\u26A0 Deprecated command. Use \`shennian ${r}\` instead.`))};n.command("start").description("Start the background service").option("--json","Print machine-readable status JSON").option("--api <url>","Server URL override").action(r=>{t("start",r.json),oe(r)}),n.command("stop").description("Stop the background service").option("--json","Print machine-readable status JSON").action(async r=>{t("stop",r.json),await C(r)}),n.command("restart").description("Restart the background service").option("--json","Print machine-readable status JSON").option("--api <url>","Server URL override").action(r=>{t("stop && shennian start",r.json),qe(r)}),n.command("status").description("Show background service status").option("--json","Print machine-readable status JSON").action(r=>{t("status",r.json),ie(r)}),n.command("logs").description("Show recent logs").option("-n, --lines <n>","Number of lines","50").action(r=>{t("logs"),se({lines:parseInt(r.lines,10)})}),n.command("uninstall").description("Uninstall auto-start service").action(Ye)}export{Ue as buildDaemonSpawnOptions,fn as buildWindowsLauncherCommand,Sn as buildWindowsScheduledTaskXml,hn as buildWindowsStartupVbs,Z as captureEnvForService,T as clearDaemonLauncher,dn as clearDaemonPidIfOwner,Ne as clearRemoteAccessDisabled,be as createDaemonInstanceId,K as findRunningDaemonProcessIds,J as getCurrentProcessDaemonLauncher,f as getDaemonStatus,ee as getLaunchdServiceTarget,re as installService,R as isEphemeralCliPath,De as isRemoteAccessDisabled,Ee as isSafeSnapshotEnvKey,yn as isShennianRunServiceCommand,Re as recordStartedDaemon,ln as registerDaemonCommand,Be as reloadLaunchdAgent,ke as resolveServiceLaunchSpec,Ve as saveEnvSnapshot,ne as startDaemonProcess,G as writeDaemonLauncher,Le as writeDaemonPid};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
`)}function w(o,e){s({type:"error",code:o,message:e}),process.exit(1)}function
|
|
3
|
-
\u2717 Pairing code expired. Please re-run: shennian pair`)),process.exit(1))),!
|
|
1
|
+
import i from"chalk";import y from"node:os";import U from"node:readline";import{loadConfig as d,saveConfig as S}from"../config/index.js";import{detectAgents as T}from"../agents/detect.js";import{clearRemoteAccessDisabled as v,getDaemonStatus as O,startDaemonProcess as P,installService as R,saveEnvSnapshot as N}from"./daemon.js";import{waitForDaemonReadyStatus as $}from"./daemon-start-wait.js";import{detectAndChooseServer as I}from"../region.js";import{buildPairQrPayload as j,PAIR_QR_RENDER_OPTIONS as D}from"./pair-qr.js";const _=3e3,E=600*1e3;function s(o){process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
+
`)}function w(o,e){s({type:"error",code:o,message:e}),process.exit(1)}function C(o){const e="\u2500".repeat(o.length+4);console.log(i.cyan(`\u250C${e}\u2510`)),console.log(i.cyan("\u2502 ")+i.bold.yellow(o)+i.cyan(" \u2502")),console.log(i.cyan(`\u2514${e}\u2518`))}async function L(o){const e=(await import("qrcode-terminal")).default;return new Promise(n=>{e.generate(o,D,r=>{console.log(r),n()})})}async function b(o,e,n={}){const r=Date.now()+E;for(n.json&&s({type:"pair.waiting"});Date.now()<r;){await new Promise(m=>setTimeout(m,_));let a;try{a=await fetch(`${o}/api/machines/pair/status?token=${encodeURIComponent(e)}`)}catch{continue}if(a.status===410&&(n.json?w("PAIR_EXPIRED","Pairing code expired"):(console.error(i.red(`
|
|
3
|
+
\u2717 Pairing code expired. Please re-run: shennian pair`)),process.exit(1))),!a.ok)continue;const t=await a.json();if(t.status==="claimed"&&t.machineToken&&t.machineId)return n.json&&s({type:"pair.claimed"}),{machineToken:t.machineToken,machineId:t.machineId,machineName:t.machineName??""}}return null}function M(o){const e=U.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{e.question(o,r=>{e.close(),n(r.trim().toLowerCase()==="y")})})}async function A(o){const{serverUrl:e,machineName:n,force:r,json:a}=o,t=d();if(t.machineToken&&t.machineId&&!r){a?s({type:"done",status:"already-paired",machineId:t.machineId}):(console.log(i.green(`\u2713 Already paired (machine ID: ${t.machineId})`)),console.log(i.gray(' Run "shennian pair" to re-pair to another account')));return}const c=T().map(g=>g.type),l=y.platform(),u=l==="win32"?"windows":l==="darwin"?"macos":"linux";a||(console.log(i.bold(`
|
|
4
4
|
Shennian CLI \u2014 Pairing
|
|
5
|
-
`)),console.log(
|
|
6
|
-
\u2717 Timed out. Pairing code expired, please try again.`)),process.exit(1)),
|
|
7
|
-
\u2713 Paired successfully! Machine "${f.machineName}" is now linked.`))}async function
|
|
8
|
-
Starting background service...`)),
|
|
9
|
-
Starting background service...`)),
|
|
5
|
+
`)),console.log(i.gray(` Machine: ${n} | OS: ${u} | Agents: ${c.join(", ")||"none"}`)),console.log());let h;try{h=await fetch(`${e}/api/machines/pair/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,os:u,agentList:c})})}catch{const g=`Network error: cannot connect to ${e}`;a&&w("NETWORK_ERROR",g),console.error(i.red(`\u2717 ${g}`)),process.exit(1)}if(!h.ok){const k=`Failed to create machine: ${(await h.json().catch(()=>({}))).error??h.statusText}`;a&&w("PAIR_CREATE_FAILED",k),console.error(i.red(`\u2717 ${k}`)),process.exit(1)}const p=await h.json(),x=j(p.pairToken);a?s({type:"pair.created",code:p.pairToken,machineId:p.machineId,expiresAt:new Date(Date.now()+E).toISOString()}):(console.log(i.white("Scan QR code or enter the pairing code in the Shennian app:")),console.log(),await L(x),C(p.pairToken),console.log(),console.log(i.gray("Waiting for pairing... (Ctrl+C to cancel)")));const f=await b(e,p.pairToken,{json:a});f||(a&&w("PAIR_TIMEOUT","Timed out waiting for pairing"),console.error(i.red(`
|
|
6
|
+
\u2717 Timed out. Pairing code expired, please try again.`)),process.exit(1)),S({...t,machineToken:f.machineToken,machineId:f.machineId,serverUrl:e}),a&&s({type:"pair.saved",machineId:f.machineId}),a||console.log(i.green(`
|
|
7
|
+
\u2713 Paired successfully! Machine "${f.machineName}" is now linked.`))}async function B(o){const e=d(),r=T().map(l=>l.type),a=y.platform(),t=a==="win32"?"windows":a==="darwin"?"macos":"linux",m=await fetch(`${o.serverUrl}/api/machines/desktop/register`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.authToken}`},body:JSON.stringify({machineId:e.machineId,name:o.machineName,os:t,agentList:r})});if(!m.ok){const u=(await m.json().catch(()=>({}))).error??m.statusText;throw new Error(`Failed to register desktop machine: ${u}`)}const c=await m.json();if(!c.machine?.id||!c.machineToken)throw new Error("Failed to register desktop machine: missing machine token");return e.machineId=c.machine.id,e.machineToken=c.machineToken,e.serverUrl=o.serverUrl,S(e),{machineId:c.machine.id,machineName:c.machine.name}}async function F(o){const e=o?.trim();if(e)return e;const n=process.env.SHENNIAN_DESKTOP_SERVER_URL?.trim();if(n)return n;const r=d().serverUrl?.trim();return r||I()}async function G(o,e){const n=d();if(!n.machineToken||!n.machineId){const a=o??await I();await A({serverUrl:a,machineName:e,force:!1})}else console.log(i.green(`\u2713 Already paired (machine ID: ${n.machineId})`));N(),v(),console.log(i.gray(`
|
|
8
|
+
Starting background service...`)),R()||P()}function Y(o){o.command("desktop-register",{hidden:!0}).description("Register this desktop-managed machine to the authenticated account").option("--api <url>","Server URL").option("--name <name>","Machine name",y.hostname()).action(async e=>{try{const n=process.env.SHENNIAN_DESKTOP_AUTH_TOKEN;if(!n)throw new Error("Missing desktop auth token");const r=await F(e.api),a=await B({serverUrl:r,authToken:n,machineName:e.name});console.log(JSON.stringify({ok:!0,...a}))}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}),o.command("pair").description("Pair this machine to a Shennian account (re-pair if already paired)").option("--api <url>","Server URL override").option("--server <url>","Server URL override").option("--name <name>","Machine name",y.hostname()).option("--json","Emit machine-readable JSONL events").option("--force","Force re-pair even when a machine token exists").action(async e=>{const n=d();if(n.machineToken&&n.machineId&&!e.force){if(e.json){s({type:"done",status:"already-paired",machineId:n.machineId});return}if(console.log(i.yellow(`Currently paired (machine ID: ${n.machineId})`)),!await M("Re-pairing will unlink the current account. Continue? (y/N) ")){console.log(i.gray("Cancelled"));return}}const r=e.server??e.api??await I(),a=!!(e.force||n.machineToken&&n.machineId);await A({serverUrl:r,machineName:e.name,force:a,json:!!e.json}),N(),v(),e.json?s({type:"daemon.starting"}):console.log(i.gray(`
|
|
9
|
+
Starting background service...`)),R()||P({quiet:!!e.json}),e.json&&($(()=>O({cleanupStale:!0})),s({type:"done",status:"paired",machineId:d().machineId}))})}export{B as registerDesktopMachine,Y as registerPairCommand,A as runPairFlow,G as runSmartStart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadConfig as
|
|
1
|
+
import{loadConfig as h}from"../../config/index.js";import{getHelperRuntimeStatus as f,installHelperRuntimeWithOfficialDownload as u}from"../../commands/runtime.js";import{createWeChatChannelApiClient as w}from"../../channels/wechat-channel/client.js";import{WECHAT_CHANNEL_HELPER_VERSION as g}from"../../channels/wechat-channel/helper-assets.js";import{WeChatChannelHelperClient as y}from"../../channels/wechat-channel/helper-client.js";import{requiredWeChatChannelHelperCapabilitiesForProfile as R}from"../../channels/wechat-channel/helper-protocol.js";import{createWeChatChannelRuntime as V}from"../../channels/wechat-channel/runtime.js";import{getCurrentVersion as b}from"../../upgrade/engine.js";async function I(e,o){const r=o.params??{},t=k(r.action);if(!t){e.client.sendRes({type:"res",id:o.id,ok:!1,error:'action must be "status", "install", "upgrade", or "repair"'});return}const n=typeof r.platform=="string"?r.platform:void 0,i=typeof r.source=="string"&&r.source.trim()?r.source:void 0,a=typeof r.channel=="string"&&r.channel.trim()?r.channel:void 0,c=typeof r.manifestUrl=="string"&&r.manifestUrl.trim()?r.manifestUrl:void 0,d=await C({action:t,platform:n,source:i,channel:a,manifestUrl:c});e.client.sendRes({type:"res",id:o.id,ok:!0,payload:d})}async function C(e){if(e.action==="status"){const i=f({platform:e.platform,env:e.env,homedir:e.homedir}),a=e.probePermissions===!1?void 0:await m(i),c=await p(i,a);return{action:e.action,status:i,permissions:a,projection:c}}const o=await u({source:e.source,platform:e.platform,env:e.env,homedir:e.homedir,force:e.action==="upgrade"||e.action==="repair",preferOfficialDownload:(e.action==="upgrade"||e.action==="repair")&&!e.source,officialDownload:{channel:e.channel,manifestUrl:e.manifestUrl}}),r=f({platform:e.platform,env:e.env,homedir:e.homedir}),t=e.probePermissions===!1?void 0:await m(r),n=await p(r,t);return{action:e.action,install:o,status:r,permissions:t,projection:n}}function k(e){return e==="status"||e==="install"||e==="upgrade"||e==="repair"?e:null}async function m(e){const o=new Date().toISOString();if(!e.ok||!e.helperPath)return{checkedAt:o,helperReady:!1,helperVersion:e.helperVersion??null,protocolVersion:e.protocolVersion??null,platform:e.platform};const r=new y({helperPath:e.helperPath,expectedHelperVersion:e.helperVersion||g,requiredCapabilities:R("send")});try{await r.start();const t=await r.request("permissions.check",{},`helper-runtime-status-${Date.now()}`),n=t.ok&&t.result&&typeof t.result=="object"?t.result:{};return{checkedAt:o,helperReady:t.ok,helperVersion:e.helperVersion??H(n.helperVersion),protocolVersion:e.protocolVersion??A(n.protocolVersion),platform:e.platform,screenRecording:l(n.screenRecording),accessibility:l(n.accessibility),inputMonitoring:l(n.inputMonitoring),automation:l(n.automation),wechatRunning:s(n.wechatRunning),wechatAppDetected:s(n.wechatAppDetected??n.wechatRunning),wechatWindowAvailable:s(n.wechatWindowAvailable)}}catch{return{checkedAt:o,helperReady:!1,helperVersion:e.helperVersion??null,protocolVersion:e.protocolVersion??null,platform:e.platform}}finally{await r.stop().catch(()=>{})}}async function p(e,o){if(!o||e.platform!=="darwin"&&e.platform!=="win32")return;const r=h(),t=r.machineId?.trim(),n=r.machineToken?.trim();if(!t||!n)return{ok:!1,error:"machine_not_paired"};try{const i=V({runtimeId:`wechat-machine:${t}`,machineId:t,platform:e.platform,bindings:[]});return await w({serverUrl:r.serverUrl,machineToken:n}).upsertRuntime(i,void 0,{helperVersion:e.helperVersion??void 0,clientRuntimeVersion:b(),preflight:o}),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}function l(e){return typeof e=="boolean"?e:"unknown"}function s(e){return typeof e=="boolean"?e:void 0}function H(e){return(typeof e=="string"?e.trim():"")||null}function A(e){const o=Number(e);return Number.isFinite(o)?o:null}export{I as handleWeChatHelperRuntime,C as runHelperRuntimeAction};
|