shennian 0.2.123 → 0.2.124

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.
@@ -221,8 +221,8 @@
221
221
  },
222
222
  {
223
223
  "file": "src/channels/wechat-channel/helper-client.js",
224
- "beforeBytes": 41881,
225
- "afterBytes": 18901
224
+ "beforeBytes": 42215,
225
+ "afterBytes": 19023
226
226
  },
227
227
  {
228
228
  "file": "src/channels/wechat-channel/helper-protocol.js",
@@ -261,8 +261,8 @@
261
261
  },
262
262
  {
263
263
  "file": "src/channels/wechat-channel/observer.js",
264
- "beforeBytes": 107167,
265
- "afterBytes": 48683
264
+ "beforeBytes": 107493,
265
+ "afterBytes": 48811
266
266
  },
267
267
  {
268
268
  "file": "src/channels/wechat-channel/outbound-ledger.js",
@@ -281,8 +281,8 @@
281
281
  },
282
282
  {
283
283
  "file": "src/channels/wechat-channel/preflight.js",
284
- "beforeBytes": 4888,
285
- "afterBytes": 3736
284
+ "beforeBytes": 4949,
285
+ "afterBytes": 3761
286
286
  },
287
287
  {
288
288
  "file": "src/channels/wechat-channel/runner.js",
@@ -321,8 +321,8 @@
321
321
  },
322
322
  {
323
323
  "file": "src/channels/wechat-rpa/product-channel.js",
324
- "beforeBytes": 18089,
325
- "afterBytes": 9740
324
+ "beforeBytes": 18332,
325
+ "afterBytes": 9837
326
326
  },
327
327
  {
328
328
  "file": "src/channels/wechat-rpa-session-sync.js",
@@ -1,3 +1,3 @@
1
- import{spawn as g}from"node:child_process";import{randomUUID as O}from"node:crypto";import w from"node:fs";import N from"node:net";import G from"node:os";import d from"node:path";import{createInterface as E}from"node:readline";import{decideWeChatChannelActivityGate as C,normalizeWeChatChannelActivitySnapshot as _}from"./human-coordination.js";import{createWeChatChannelHelperHello as T,extractWeChatChannelHelperWarmupSnapshot as L,timeoutForWeChatChannelHelperCommand as U,validateWeChatChannelHelperReady as R}from"./helper-protocol.js";const I=["en","v"].join(""),m=1500,V=1500,b=8e3,J="SHENNIAN_WECHAT_DANGEROUS_GUARD_THROTTLE_MS";class P extends Error{helperPid;constructor(t,r){super(t),this.helperPid=r,this.name="HelperVersionMismatchError"}}function z(){const e=process.env[J];if(e===void 0||e==="")return b;const t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?b:t}class Ee{options;child=null;socket=null;lines=null;readyState=null;warmupState=null;stderrTail="";startPromise=null;requestQueueTail=Promise.resolve();lastGuardPassAtMs=0;pending=new Map;constructor(t){this.options=t}async start(){return this.hasTransport()&&this.readyState?this.readyState:this.startPromise?this.startPromise:(this.hasTransport()&&await this.stop(),this.startPromise=this.startFresh().catch(async t=>{throw await this.stop().catch(()=>{}),t}).finally(()=>{this.startPromise=null}),this.startPromise)}async startFresh(){const t=Z(this.options.helperPath,this.options.args??[]);return t.transport==="macos-socket"?this.startDarwinAppSocketFresh(t):this.startStdioFresh(t)}async startStdioFresh(t){const r=g(t.command,t.args,{cwd:this.options.cwd,stdio:["pipe","pipe","pipe"],windowsHide:!0});this.child=r,this.stderrTail="",this.lines=E({input:r.stdout}),this.lines.on("line",s=>this.handleLine(s)),r.stderr.on("data",s=>{this.captureStderr(s)}),r.stdin.on("error",s=>{this.rejectAllPending(s instanceof Error?s:new Error(String(s)))}),r.once("error",s=>{this.child===r&&(this.child=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(s instanceof Error?s:new Error(String(s)))}),r.once("exit",(s,n)=>{this.child===r&&(this.child=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(new Error(this.formatHelperExitMessage(s,n)))});const i=new Promise((s,n)=>{const a=setTimeout(()=>n(new Error("WeChat channel helper handshake timed out")),1e4),c=u=>{clearTimeout(a),this.lines?.off("line",l),r.off("exit",o),n(new Error(`WeChat channel helper failed to start: ${u.message}`))},o=(u,h)=>{clearTimeout(a),r.off("error",c),this.lines?.off("line",l),n(new Error(this.formatHelperExitMessage(u,h)))},l=u=>{let h;try{h=JSON.parse(u)}catch{clearTimeout(a),r.off("error",c),this.lines?.off("line",l),n(new Error("WeChat channel helper sent invalid handshake JSON"));return}if(!$(h))return;clearTimeout(a),r.off("error",c),r.off("exit",o),this.lines?.off("line",l);const p=R(h,this.options.expectedHelperVersion,this.options.requiredCapabilities);p.ok?(this.readyState=h,this.captureWarmupSnapshot(h),s(h)):n(new Error(`${p.errorCode}: ${p.errorSummary}`))};r.once("error",c),r.once("exit",o),this.lines?.on("line",l)});try{r.stdin.write(`${JSON.stringify(T(this.options.expectedHelperVersion,this.options.requiredCapabilities))}
2
- `)}catch(s){throw await this.stop().catch(()=>{}),s}return i}async startDarwinAppSocketFresh(t,r=!0){const i=await this.connectDarwinHelperSocket(t);this.socket=i,this.stderrTail="",this.lines=E({input:i}),this.lines.on("line",n=>this.handleLine(n)),i.on("error",n=>{this.socket===i&&(this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(n instanceof Error?n:new Error(String(n)))}),i.once("close",()=>{this.socket===i&&(this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(new Error("WeChat channel helper socket closed"))});const s=new Promise((n,a)=>{const c=setTimeout(()=>a(new Error("WeChat channel helper socket handshake timed out")),1e4),o=h=>{clearTimeout(c),this.lines?.off("line",u),i.off("close",l),a(new Error(`WeChat channel helper socket failed: ${h.message}`))},l=()=>{clearTimeout(c),i.off("error",o),this.lines?.off("line",u),a(new Error("WeChat channel helper socket closed before handshake"))},u=h=>{let p;try{p=JSON.parse(h)}catch{clearTimeout(c),i.off("error",o),i.off("close",l),this.lines?.off("line",u),a(new Error("WeChat channel helper sent invalid socket handshake JSON"));return}if(!$(p))return;clearTimeout(c),i.off("error",o),i.off("close",l),this.lines?.off("line",u);const y=R(p,this.options.expectedHelperVersion,this.options.requiredCapabilities);if(y.ok)this.readyState=p,this.captureWarmupSnapshot(p),n(p);else{const k=`${y.errorCode}: ${y.errorSummary}`;a(y.errorCode==="helper_version_mismatch"?new P(k,Number.isInteger(p.pid)?p.pid:null):new Error(k))}};i.once("error",o),i.once("close",l),this.lines?.on("line",u)});try{this.writeFrame(T(this.options.expectedHelperVersion,this.options.requiredCapabilities))}catch(n){throw await this.stop().catch(()=>{}),n}try{return await s}catch(n){if(r&&n instanceof P)return await this.stop().catch(()=>{}),await ie(n.helperPid),w.rmSync(t.runtimeFile,{force:!0}),this.startDarwinAppSocketFresh(t,!1);throw n}}async request(t,r,i){const s=this.requestQueueTail.catch(()=>{}).then(()=>this.sendRequest(t,r,i));return this.requestQueueTail=s.then(()=>{},()=>{}),s}async sendRequest(t,r,i){await this.guardUnsafeWindowsCommand(t,i);try{return await this.sendRawRequest(t,r,i)}finally{await this.cleanupWindowsOverlaysAfterCommand(t,i).catch(()=>{})}}async sendRawRequest(t,r,i){if((!this.hasTransport()||!this.readyState)&&await this.start(),!this.hasTransport())throw new Error("WeChat channel helper is not started");const s=O(),n=U(t),a=Date.now();this.emitRequestTrace({phase:"request",at:new Date(a).toISOString(),id:s,command:t,traceId:i,params:r,timeoutMs:n});const c=new Promise((o,l)=>{const u=setTimeout(()=>{this.pending.get(s)&&(this.pending.delete(s),this.stopAfterCommandTimeout(t).finally(()=>{l(new Error(`helper_command_timeout: ${t}`))}))},n);this.pending.set(s,{resolve:o,reject:l,timer:u})});try{this.writeFrame({id:s,command:t,params:r,traceId:i})}catch(o){const l=this.pending.get(s);throw l&&clearTimeout(l.timer),this.pending.delete(s),this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-a,errorSummary:o instanceof Error?o.message:String(o)}),o}try{const o=await c;return this.emitRequestTrace({phase:"response",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-a,ok:o.ok,errorCode:o.errorCode,errorSummary:o.errorSummary,latencyMs:o.latencyMs,result:o.result}),this.captureWarmupSnapshot(o),this.captureWarmupSnapshot(o.result),o}catch(o){throw this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-a,errorSummary:o instanceof Error?o.message:String(o)}),o}}async guardUnsafeWindowsCommand(t,r){if(!this.options.guardUnsafeWindowsCommands||!ue(t))return;const i=z(),s=q(t)?Math.max(V,i):i;if(s>0&&this.lastGuardPassAtMs>0&&Date.now()-this.lastGuardPassAtMs<s){if(!q(t)){if(!this.options.skipUserActivityGuard&&F(t)){const o=await this.sendRawRequest("activity.snapshot",{},r);if(!o.ok)throw new Error(`${o.errorCode??"user_activity_unknown"}: ${o.errorSummary??t}`);const l=C({snapshot:_(o.result),stage:"dangerous_action"});if(!l.ok)throw new Error(`user_active:${l.reasonCode}`)}await this.cleanupWindowsOverlays("before",t,r)}return}let n=await this.sendRawRequest("permissions.check",{},r);if(!n.ok)throw new Error(`${n.errorCode??"permissions_check_failed"}: ${n.errorSummary??t}`);let a=n.result??{};if(a.wechatRunning!==!1&&B(a)&&await this.tryRecoverFromStuckShell(r)){if(n=await this.sendRawRequest("permissions.check",{},r),!n.ok)throw new Error(`${n.errorCode??"permissions_check_failed"}: ${n.errorSummary??t}`);a=n.result??{}}const c=await this.requestFirstMissingMacPermissionPrompt(a,r);if(c==="screen-recording")throw new Error("permission_screen_recording_missing");if(c==="accessibility")throw new Error("permission_accessibility_missing");if(c==="input-monitoring")throw new Error("permission_input_monitoring_missing");if(a.automation===!1)throw new Error("permission_automation_missing");if(a.wechatRunning===!1)throw new Error("wechat_not_running");if(K(a))throw new Error("wechat_login_required");if(Q(a))throw new Error("windows_visible_desktop_unavailable");if(a.dpiMappingAvailable===!1||a.displayTopologySupported===!1)throw new Error("dpi_mapping_failed");if(a.wechatWindowAvailable===!1)throw new Error("wechat_window_unavailable");if(a.wechatMainWindowResponsive===!1)throw new Error("wechat_window_unresponsive");if(!this.options.skipUserActivityGuard&&F(t)){const o=await this.sendRawRequest("activity.snapshot",{},r);if(!o.ok)throw new Error(`${o.errorCode??"user_activity_unknown"}: ${o.errorSummary??t}`);const l=C({snapshot:_(o.result),stage:"dangerous_action"});if(!l.ok)throw new Error(`user_active:${l.reasonCode}`)}await this.cleanupWindowsOverlays("before",t,r),this.lastGuardPassAtMs=Date.now()}async tryRecoverFromStuckShell(t){try{const r=await this.sendRawRequest("wechat.healthProbe",{},t);if(!r.ok||r.result?.stuckShell!==!0)return!1;const i=await this.sendRawRequest("windows.recoverWeChat",{allowRestart:!0,onlyIfUnresponsive:!1,waitAfterStartMs:4e3},t);return i.ok===!0&&i.result?.started===!0}catch{return!1}}async requestFirstMissingMacPermissionPrompt(t,r){const i=ae(t);if(!i||process.platform!=="darwin")return i;const s=ce(i);try{await this.sendRawRequest(s,{},r)}catch{}return i}async cleanupWindowsOverlaysAfterCommand(t,r){!this.options.guardUnsafeWindowsCommands||!he(t)||await this.cleanupWindowsOverlays("after",t,r)}async cleanupWindowsOverlays(t,r,i){if(this.options.cleanupWindowsOverlays===!1)return;if(!this.readyState?.capabilities.includes("overlayCleanup"))throw new Error("helper_capability_missing: overlayCleanup");const s=await this.sendRawRequest("windows.cleanupOverlays",{stage:t,command:r,includeGeneratedMediaPreviews:!0,includeToolingTerminals:!1,waitMs:t==="after"?220:120},i);if(!s.ok)throw new Error(`${s.errorCode??"overlay_cleanup_failed"}: ${s.errorSummary??r}`)}async healthCheck(t){return this.request("health.check",{},t)}getReadyState(){return this.readyState?{...this.readyState,capabilities:[...this.readyState.capabilities]}:null}getWarmupState(){return this.warmupState?{warmState:this.warmupState.warmState,metrics:this.warmupState.metrics?{...this.warmupState.metrics}:void 0}:null}async stop(){const t=this.child,r=this.socket;this.child=null,this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null,this.rejectAllPending(new Error("WeChat channel helper stopped")),r&&!r.destroyed&&r.destroy(),t&&await re(t)}hasTransport(){return!!this.child||!!this.socket}writeFrame(t){const r=`${JSON.stringify(t)}
3
- `;if(this.socket){this.socket.write(r);return}if(this.child){this.child.stdin.write(r);return}throw new Error("WeChat channel helper is not started")}handleLine(t){let r;try{r=JSON.parse(t)}catch{return}if(!le(r))return;const i=this.pending.get(r.id);i&&(clearTimeout(i.timer),this.pending.delete(r.id),i.resolve(r))}captureWarmupSnapshot(t){const r=L(t);r&&(this.warmupState=r)}captureStderr(t){const r=Buffer.isBuffer(t)?t.toString("utf8"):String(t??"");r&&(this.stderrTail=(this.stderrTail+r).slice(-2e3))}formatHelperExitMessage(t,r){const i=[t===null?null:`code=${t}`,r?`signal=${r}`:null,this.stderrTail.trim()?`stderr=${this.stderrTail.trim()}`:null].filter(Boolean);return i.length?`WeChat channel helper process exited (${i.join(", ")})`:"WeChat channel helper process exited"}rejectAllPending(t){for(const[r,i]of this.pending)clearTimeout(i.timer),i.reject(t),this.pending.delete(r)}emitRequestTrace(t){try{this.options.requestLogger?.(t)}catch{}}async stopAfterCommandTimeout(t){const r=this.child?.pid;if(await this.stop().catch(()=>{}),process.platform==="win32"){const i=typeof r=="number"&&r>0?[r]:[];await j(i).catch(()=>{})}this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:`timeout-cleanup:${t}`,command:t,errorSummary:"helper process stopped after command timeout"})}async connectDarwinHelperSocket(t){try{return await A(t.runtimeFile)}catch{w.rmSync(t.runtimeFile,{force:!0})}await D(t,{},this.options.openHelperAppForTest);const r=await x(t.runtimeFile,this.options.macosRuntimeInitialReadyTimeoutMs??5e3);if(r.ok)return r.socket;w.rmSync(t.runtimeFile,{force:!0}),await D(t,{forceNewInstance:!0},this.options.openHelperAppForTest);const i=await x(t.runtimeFile,this.options.macosRuntimeRelaunchReadyTimeoutMs??1e4);if(i.ok)return i.socket;throw new Error(`WeChat channel Helper.app socket did not become ready: ${i.error.message}`)}}async function j(e=[]){if(process.platform!=="win32")return;const t=e.filter(r=>Number.isInteger(r)&&r>0);if(t.length!==0)for(const r of t)await M(["taskkill","/PID",String(r),"/T","/F"],[0,128])}function B(e){return e.wechatWindowAvailable===!1&&(e.captureCandidateCount??0)===0&&(e.restoreCandidateCount??0)===0&&(e.hiddenRestoreCandidateCount??0)===0}function K(e){return e.wechatWindowAvailable!==!1?!1:![...e.captureCandidates??[],...e.restoreCandidates??[],...e.hiddenRestoreCandidates??[]].some(X)}function Q(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function Y(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"}function X(e){return!(!Y(e)||e.visible===!1||e.minimized===!0)}function Z(e,t,r=process.platform){if(r==="darwin"){const i=ee(e);if(i&&t.length===0){const s=te();return{transport:"macos-socket",command:"/usr/bin/open",args:["-g",i,"--args","--socket-runtime",s],appPath:i,runtimeDir:s,runtimeFile:d.join(s,"runtime.json")}}}return{transport:"legacy-stdio",command:e,args:t}}function ee(e){const t=d.resolve(e),r=`${d.sep}Contents${d.sep}MacOS${d.sep}`,i=t.lastIndexOf(r);if(i<0)return null;const s=t.slice(0,i);return s.endsWith(".app")?s:null}function te(){const e=se().SHENNIAN_HELPER_RUNTIME_DIR?.trim();return e?d.resolve(e):d.join(G.homedir(),"Library","Application Support","Shennian","Helper")}async function re(e){if(W(e))return;if(process.platform==="win32"&&e.pid){e.kill("SIGTERM"),await M(["taskkill","/PID",String(e.pid),"/T","/F"],[0,128]).catch(()=>{}),await S(e,m);return}e.kill("SIGTERM"),!await S(e,m)&&e.pid&&f(e.pid)&&(e.kill("SIGKILL"),await S(e,m))}async function ie(e){if(process.platform!=="darwin"||!e||e===process.pid||!f(e))return;try{process.kill(e,"SIGTERM")}catch{return}if(!await v(e,m)&&f(e)){try{process.kill(e,"SIGKILL")}catch{return}await v(e,m)}}async function v(e,t){const r=Date.now()+t;for(;Date.now()<r;){if(!f(e))return!0;await H(Math.min(50,r-Date.now()))}return!f(e)}function W(e){return e.exitCode!==null||e.signalCode!==null}function S(e,t){return W(e)?Promise.resolve(!0):new Promise(r=>{const i=setTimeout(()=>{e.off("exit",s),r(!1)},t),s=()=>{clearTimeout(i),r(!0)};e.once("exit",s)})}function M(e,t){return new Promise((r,i)=>{const[s,...n]=e,a=g(s,n,{stdio:"ignore",windowsHide:!0});a.once("error",i),a.once("exit",c=>{c!==null&&t.includes(c)?r():i(new Error(`${s} exited ${c}`))})})}function se(){return globalThis.process?.[I]??{}}function ne(e){let t;try{t=JSON.parse(w.readFileSync(e,"utf8"))}catch(s){throw new Error(`runtime_file_unreadable: ${s instanceof Error?s.message:String(s)}`)}if(!t||typeof t!="object")throw new Error("runtime_file_invalid");const r=t.socketPath;if(typeof r!="string"||!r.trim())throw new Error("runtime_socket_missing");const i=t.pid;return{socketPath:r,...typeof i=="number"&&Number.isInteger(i)&&i>0?{pid:i}:{}}}async function A(e){const{socketPath:t,pid:r}=ne(e);if(r&&!f(r))throw new Error(`runtime_process_stale: ${r}`);return new Promise((i,s)=>{const n=N.createConnection(t),a=setTimeout(()=>{n.destroy(),s(new Error(`runtime_socket_connect_timeout: ${t}`))},1e3);n.once("connect",()=>{clearTimeout(a),n.off("error",c),i(n)});const c=o=>{clearTimeout(a),n.destroy(),s(o)};n.once("error",c)})}async function x(e,t){const r=Date.now()+t;let i=null;for(;Date.now()<r;)try{return{ok:!0,socket:await A(e)}}catch(s){i=s instanceof Error?s:new Error(String(s));const n=r-Date.now();n>0&&await H(Math.min(150,n))}return{ok:!1,error:i??new Error("runtime file missing")}}async function D(e,t={},r=oe){w.mkdirSync(e.runtimeDir,{recursive:!0,mode:448});const i=t.forceNewInstance?["-n",...e.args]:e.args;try{await r(e.command,i)}catch(s){if(!(s instanceof Error?s.message:String(s)).includes("-1712"))throw s;await r(e.command,["-n",...e.args])}}function f(e){try{return process.kill(e,0),!0}catch{return!1}}async function oe(e,t){await new Promise((r,i)=>{const s=g(e,t,{stdio:["ignore","ignore","pipe"],windowsHide:!0});let n="";s.stderr.on("data",a=>{n=(n+String(a)).slice(-2e3)}),s.once("error",i),s.once("exit",(a,c)=>{a===0?r():i(new Error(`open Helper.app failed (${c?`signal=${c}`:`code=${a}`}${n.trim()?`, stderr=${n.trim()}`:""})`))})})}function H(e){return new Promise(t=>setTimeout(t,e))}function ae(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function ce(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}function $(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="ready"&&typeof t.helperVersion=="string"&&typeof t.protocolVersion=="number"&&Array.isArray(t.capabilities)&&typeof t.pid=="number"}function le(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.ok=="boolean"&&typeof t.latencyMs=="number"}function ue(e){return e==="windows.focus"||e==="windows.capture"||e==="screen.capture"||e==="ocr.recognize"||e==="image.cropHash"||e==="wechat.searchConversation"||e==="wechat.focusMessageInput"||e==="wechat.pasteAndSubmit"||e==="keyboard.primeTextPaste"||e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.")||e==="menu.pickItem"||e==="savePanel.saveToPath"}function q(e){return e==="windows.capture"||e==="screen.capture"||e==="ocr.recognize"||e==="image.cropHash"}function he(e){return e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.")||e==="menu.pickItem"||e==="savePanel.saveToPath"}function F(e){return e==="windows.focus"||e==="wechat.searchConversation"||e==="wechat.focusMessageInput"||e==="wechat.pasteAndSubmit"||e==="keyboard.primeTextPaste"||e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.set")||e==="clipboard.restore"||e==="menu.pickItem"||e==="savePanel.saveToPath"}export{Ee as WeChatChannelHelperClient,Z as helperLaunchSpec,j as stopWindowsWeChatChannelHelperProcesses};
1
+ import{spawn as g}from"node:child_process";import{randomUUID as O}from"node:crypto";import w from"node:fs";import N from"node:net";import G from"node:os";import d from"node:path";import{createInterface as E}from"node:readline";import{decideWeChatChannelActivityGate as C,normalizeWeChatChannelActivitySnapshot as _}from"./human-coordination.js";import{createWeChatChannelHelperHello as T,extractWeChatChannelHelperWarmupSnapshot as L,timeoutForWeChatChannelHelperCommand as U,validateWeChatChannelHelperReady as R}from"./helper-protocol.js";const I=["en","v"].join(""),m=1500,V=1500,P=8e3,J="SHENNIAN_WECHAT_DANGEROUS_GUARD_THROTTLE_MS";class b extends Error{helperPid;constructor(t,r){super(t),this.helperPid=r,this.name="HelperVersionMismatchError"}}function z(){const e=process.env[J];if(e===void 0||e==="")return P;const t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?P:t}class Ce{options;child=null;socket=null;lines=null;readyState=null;warmupState=null;stderrTail="";startPromise=null;requestQueueTail=Promise.resolve();lastGuardPassAtMs=0;pending=new Map;constructor(t){this.options=t}async start(){return this.hasTransport()&&this.readyState?this.readyState:this.startPromise?this.startPromise:(this.hasTransport()&&await this.stop(),this.startPromise=this.startFresh().catch(async t=>{throw await this.stop().catch(()=>{}),t}).finally(()=>{this.startPromise=null}),this.startPromise)}async startFresh(){const t=Z(this.options.helperPath,this.options.args??[]);return t.transport==="macos-socket"?this.startDarwinAppSocketFresh(t):this.startStdioFresh(t)}async startStdioFresh(t){const r=g(t.command,t.args,{cwd:this.options.cwd,stdio:["pipe","pipe","pipe"],windowsHide:!0});this.child=r,this.stderrTail="",this.lines=E({input:r.stdout}),this.lines.on("line",s=>this.handleLine(s)),r.stderr.on("data",s=>{this.captureStderr(s)}),r.stdin.on("error",s=>{this.rejectAllPending(s instanceof Error?s:new Error(String(s)))}),r.once("error",s=>{this.child===r&&(this.child=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(s instanceof Error?s:new Error(String(s)))}),r.once("exit",(s,n)=>{this.child===r&&(this.child=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(new Error(this.formatHelperExitMessage(s,n)))});const i=new Promise((s,n)=>{const o=setTimeout(()=>n(new Error("WeChat channel helper handshake timed out")),1e4),c=u=>{clearTimeout(o),this.lines?.off("line",l),r.off("exit",a),n(new Error(`WeChat channel helper failed to start: ${u.message}`))},a=(u,h)=>{clearTimeout(o),r.off("error",c),this.lines?.off("line",l),n(new Error(this.formatHelperExitMessage(u,h)))},l=u=>{let h;try{h=JSON.parse(u)}catch{clearTimeout(o),r.off("error",c),this.lines?.off("line",l),n(new Error("WeChat channel helper sent invalid handshake JSON"));return}if(!$(h))return;clearTimeout(o),r.off("error",c),r.off("exit",a),this.lines?.off("line",l);const p=R(h,this.options.expectedHelperVersion,this.options.requiredCapabilities);p.ok?(this.readyState=h,this.captureWarmupSnapshot(h),s(h)):n(new Error(`${p.errorCode}: ${p.errorSummary}`))};r.once("error",c),r.once("exit",a),this.lines?.on("line",l)});try{r.stdin.write(`${JSON.stringify(T(this.options.expectedHelperVersion,this.options.requiredCapabilities))}
2
+ `)}catch(s){throw await this.stop().catch(()=>{}),s}return i}async startDarwinAppSocketFresh(t,r=!0){const i=await this.connectDarwinHelperSocket(t);this.socket=i,this.stderrTail="",this.lines=E({input:i}),this.lines.on("line",n=>this.handleLine(n)),i.on("error",n=>{this.socket===i&&(this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(n instanceof Error?n:new Error(String(n)))}),i.once("close",()=>{this.socket===i&&(this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null),this.rejectAllPending(new Error("WeChat channel helper socket closed"))});const s=new Promise((n,o)=>{const c=setTimeout(()=>o(new Error("WeChat channel helper socket handshake timed out")),1e4),a=h=>{clearTimeout(c),this.lines?.off("line",u),i.off("close",l),o(new Error(`WeChat channel helper socket failed: ${h.message}`))},l=()=>{clearTimeout(c),i.off("error",a),this.lines?.off("line",u),o(new Error("WeChat channel helper socket closed before handshake"))},u=h=>{let p;try{p=JSON.parse(h)}catch{clearTimeout(c),i.off("error",a),i.off("close",l),this.lines?.off("line",u),o(new Error("WeChat channel helper sent invalid socket handshake JSON"));return}if(!$(p))return;clearTimeout(c),i.off("error",a),i.off("close",l),this.lines?.off("line",u);const y=R(p,this.options.expectedHelperVersion,this.options.requiredCapabilities);if(y.ok)this.readyState=p,this.captureWarmupSnapshot(p),n(p);else{const k=`${y.errorCode}: ${y.errorSummary}`;o(y.errorCode==="helper_version_mismatch"?new b(k,Number.isInteger(p.pid)?p.pid:null):new Error(k))}};i.once("error",a),i.once("close",l),this.lines?.on("line",u)});try{this.writeFrame(T(this.options.expectedHelperVersion,this.options.requiredCapabilities))}catch(n){throw await this.stop().catch(()=>{}),n}try{return await s}catch(n){if(r&&n instanceof b)return await this.stop().catch(()=>{}),await ie(n.helperPid),w.rmSync(t.runtimeFile,{force:!0}),this.startDarwinAppSocketFresh(t,!1);throw n}}async request(t,r,i){const s=this.requestQueueTail.catch(()=>{}).then(()=>this.sendRequest(t,r,i));return this.requestQueueTail=s.then(()=>{},()=>{}),s}async sendRequest(t,r,i){await this.guardUnsafeWindowsCommand(t,i);try{return await this.sendRawRequest(t,r,i)}finally{await this.cleanupWindowsOverlaysAfterCommand(t,i).catch(()=>{})}}async sendRawRequest(t,r,i){if((!this.hasTransport()||!this.readyState)&&await this.start(),!this.hasTransport())throw new Error("WeChat channel helper is not started");const s=O(),n=U(t),o=Date.now();this.emitRequestTrace({phase:"request",at:new Date(o).toISOString(),id:s,command:t,traceId:i,params:r,timeoutMs:n});const c=new Promise((a,l)=>{const u=setTimeout(()=>{this.pending.get(s)&&(this.pending.delete(s),this.stopAfterCommandTimeout(t).finally(()=>{l(new Error(`helper_command_timeout: ${t}`))}))},n);this.pending.set(s,{resolve:a,reject:l,timer:u})});try{this.writeFrame({id:s,command:t,params:r,traceId:i})}catch(a){const l=this.pending.get(s);throw l&&clearTimeout(l.timer),this.pending.delete(s),this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-o,errorSummary:a instanceof Error?a.message:String(a)}),a}try{const a=await c;return this.emitRequestTrace({phase:"response",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-o,ok:a.ok,errorCode:a.errorCode,errorSummary:a.errorSummary,latencyMs:a.latencyMs,result:a.result}),this.captureWarmupSnapshot(a),this.captureWarmupSnapshot(a.result),a}catch(a){throw this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:s,command:t,traceId:i,durationMs:Date.now()-o,errorSummary:a instanceof Error?a.message:String(a)}),a}}async guardUnsafeWindowsCommand(t,r){if(!this.options.guardUnsafeWindowsCommands||!he(t))return;const i=z(),s=q(t)?Math.max(V,i):i;if(s>0&&this.lastGuardPassAtMs>0&&Date.now()-this.lastGuardPassAtMs<s){if(!q(t)){if(!this.options.skipUserActivityGuard&&F(t)){const c=await this.sendRawRequest("activity.snapshot",{},r);if(!c.ok)throw new Error(`${c.errorCode??"user_activity_unknown"}: ${c.errorSummary??t}`);const a=C({snapshot:_(c.result),stage:"dangerous_action"});if(!a.ok)throw new Error(`user_active:${a.reasonCode}`)}await this.cleanupWindowsOverlays("before",t,r)}return}let n=await this.sendRawRequest("permissions.check",{},r);if(!n.ok)throw new Error(`${n.errorCode??"permissions_check_failed"}: ${n.errorSummary??t}`);let o=n.result??{};if(o.wechatRunning!==!1&&B(o)&&await this.tryRecoverFromStuckShell(r)){if(n=await this.sendRawRequest("permissions.check",{},r),!n.ok)throw new Error(`${n.errorCode??"permissions_check_failed"}: ${n.errorSummary??t}`);o=n.result??{}}if(ce(o.platform)){const c=await this.requestFirstMissingMacPermissionPrompt(o,r);if(c==="screen-recording")throw new Error("permission_screen_recording_missing");if(c==="accessibility")throw new Error("permission_accessibility_missing");if(c==="input-monitoring")throw new Error("permission_input_monitoring_missing");if(o.automation===!1)throw new Error("permission_automation_missing")}if(o.wechatRunning===!1)throw new Error("wechat_not_running");if(K(o))throw new Error("wechat_login_required");if(Q(o))throw new Error("windows_visible_desktop_unavailable");if(o.dpiMappingAvailable===!1||o.displayTopologySupported===!1)throw new Error("dpi_mapping_failed");if(o.wechatWindowAvailable===!1)throw new Error("wechat_window_unavailable");if(o.wechatMainWindowResponsive===!1)throw new Error("wechat_window_unresponsive");if(!this.options.skipUserActivityGuard&&F(t)){const c=await this.sendRawRequest("activity.snapshot",{},r);if(!c.ok)throw new Error(`${c.errorCode??"user_activity_unknown"}: ${c.errorSummary??t}`);const a=C({snapshot:_(c.result),stage:"dangerous_action"});if(!a.ok)throw new Error(`user_active:${a.reasonCode}`)}await this.cleanupWindowsOverlays("before",t,r),this.lastGuardPassAtMs=Date.now()}async tryRecoverFromStuckShell(t){try{const r=await this.sendRawRequest("wechat.healthProbe",{},t);if(!r.ok||r.result?.stuckShell!==!0)return!1;const i=await this.sendRawRequest("windows.recoverWeChat",{allowRestart:!0,onlyIfUnresponsive:!1,waitAfterStartMs:4e3},t);return i.ok===!0&&i.result?.started===!0}catch{return!1}}async requestFirstMissingMacPermissionPrompt(t,r){const i=ae(t);if(!i||process.platform!=="darwin")return i;const s=le(i);try{await this.sendRawRequest(s,{},r)}catch{}return i}async cleanupWindowsOverlaysAfterCommand(t,r){!this.options.guardUnsafeWindowsCommands||!pe(t)||await this.cleanupWindowsOverlays("after",t,r)}async cleanupWindowsOverlays(t,r,i){if(this.options.cleanupWindowsOverlays===!1)return;if(!this.readyState?.capabilities.includes("overlayCleanup"))throw new Error("helper_capability_missing: overlayCleanup");const s=await this.sendRawRequest("windows.cleanupOverlays",{stage:t,command:r,includeGeneratedMediaPreviews:!0,includeToolingTerminals:!1,waitMs:t==="after"?220:120},i);if(!s.ok)throw new Error(`${s.errorCode??"overlay_cleanup_failed"}: ${s.errorSummary??r}`)}async healthCheck(t){return this.request("health.check",{},t)}getReadyState(){return this.readyState?{...this.readyState,capabilities:[...this.readyState.capabilities]}:null}getWarmupState(){return this.warmupState?{warmState:this.warmupState.warmState,metrics:this.warmupState.metrics?{...this.warmupState.metrics}:void 0}:null}async stop(){const t=this.child,r=this.socket;this.child=null,this.socket=null,this.readyState=null,this.lines?.close(),this.lines=null,this.rejectAllPending(new Error("WeChat channel helper stopped")),r&&!r.destroyed&&r.destroy(),t&&await re(t)}hasTransport(){return!!this.child||!!this.socket}writeFrame(t){const r=`${JSON.stringify(t)}
3
+ `;if(this.socket){this.socket.write(r);return}if(this.child){this.child.stdin.write(r);return}throw new Error("WeChat channel helper is not started")}handleLine(t){let r;try{r=JSON.parse(t)}catch{return}if(!ue(r))return;const i=this.pending.get(r.id);i&&(clearTimeout(i.timer),this.pending.delete(r.id),i.resolve(r))}captureWarmupSnapshot(t){const r=L(t);r&&(this.warmupState=r)}captureStderr(t){const r=Buffer.isBuffer(t)?t.toString("utf8"):String(t??"");r&&(this.stderrTail=(this.stderrTail+r).slice(-2e3))}formatHelperExitMessage(t,r){const i=[t===null?null:`code=${t}`,r?`signal=${r}`:null,this.stderrTail.trim()?`stderr=${this.stderrTail.trim()}`:null].filter(Boolean);return i.length?`WeChat channel helper process exited (${i.join(", ")})`:"WeChat channel helper process exited"}rejectAllPending(t){for(const[r,i]of this.pending)clearTimeout(i.timer),i.reject(t),this.pending.delete(r)}emitRequestTrace(t){try{this.options.requestLogger?.(t)}catch{}}async stopAfterCommandTimeout(t){const r=this.child?.pid;if(await this.stop().catch(()=>{}),process.platform==="win32"){const i=typeof r=="number"&&r>0?[r]:[];await j(i).catch(()=>{})}this.emitRequestTrace({phase:"error",at:new Date().toISOString(),id:`timeout-cleanup:${t}`,command:t,errorSummary:"helper process stopped after command timeout"})}async connectDarwinHelperSocket(t){try{return await A(t.runtimeFile)}catch{w.rmSync(t.runtimeFile,{force:!0})}await D(t,{},this.options.openHelperAppForTest);const r=await x(t.runtimeFile,this.options.macosRuntimeInitialReadyTimeoutMs??5e3);if(r.ok)return r.socket;w.rmSync(t.runtimeFile,{force:!0}),await D(t,{forceNewInstance:!0},this.options.openHelperAppForTest);const i=await x(t.runtimeFile,this.options.macosRuntimeRelaunchReadyTimeoutMs??1e4);if(i.ok)return i.socket;throw new Error(`WeChat channel Helper.app socket did not become ready: ${i.error.message}`)}}async function j(e=[]){if(process.platform!=="win32")return;const t=e.filter(r=>Number.isInteger(r)&&r>0);if(t.length!==0)for(const r of t)await M(["taskkill","/PID",String(r),"/T","/F"],[0,128])}function B(e){return e.wechatWindowAvailable===!1&&(e.captureCandidateCount??0)===0&&(e.restoreCandidateCount??0)===0&&(e.hiddenRestoreCandidateCount??0)===0}function K(e){return e.wechatWindowAvailable!==!1?!1:![...e.captureCandidates??[],...e.restoreCandidates??[],...e.hiddenRestoreCandidates??[]].some(X)}function Q(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function Y(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"}function X(e){return!(!Y(e)||e.visible===!1||e.minimized===!0)}function Z(e,t,r=process.platform){if(r==="darwin"){const i=ee(e);if(i&&t.length===0){const s=te();return{transport:"macos-socket",command:"/usr/bin/open",args:["-g",i,"--args","--socket-runtime",s],appPath:i,runtimeDir:s,runtimeFile:d.join(s,"runtime.json")}}}return{transport:"legacy-stdio",command:e,args:t}}function ee(e){const t=d.resolve(e),r=`${d.sep}Contents${d.sep}MacOS${d.sep}`,i=t.lastIndexOf(r);if(i<0)return null;const s=t.slice(0,i);return s.endsWith(".app")?s:null}function te(){const e=se().SHENNIAN_HELPER_RUNTIME_DIR?.trim();return e?d.resolve(e):d.join(G.homedir(),"Library","Application Support","Shennian","Helper")}async function re(e){if(W(e))return;if(process.platform==="win32"&&e.pid){e.kill("SIGTERM"),await M(["taskkill","/PID",String(e.pid),"/T","/F"],[0,128]).catch(()=>{}),await S(e,m);return}e.kill("SIGTERM"),!await S(e,m)&&e.pid&&f(e.pid)&&(e.kill("SIGKILL"),await S(e,m))}async function ie(e){if(process.platform!=="darwin"||!e||e===process.pid||!f(e))return;try{process.kill(e,"SIGTERM")}catch{return}if(!await v(e,m)&&f(e)){try{process.kill(e,"SIGKILL")}catch{return}await v(e,m)}}async function v(e,t){const r=Date.now()+t;for(;Date.now()<r;){if(!f(e))return!0;await H(Math.min(50,r-Date.now()))}return!f(e)}function W(e){return e.exitCode!==null||e.signalCode!==null}function S(e,t){return W(e)?Promise.resolve(!0):new Promise(r=>{const i=setTimeout(()=>{e.off("exit",s),r(!1)},t),s=()=>{clearTimeout(i),r(!0)};e.once("exit",s)})}function M(e,t){return new Promise((r,i)=>{const[s,...n]=e,o=g(s,n,{stdio:"ignore",windowsHide:!0});o.once("error",i),o.once("exit",c=>{c!==null&&t.includes(c)?r():i(new Error(`${s} exited ${c}`))})})}function se(){return globalThis.process?.[I]??{}}function ne(e){let t;try{t=JSON.parse(w.readFileSync(e,"utf8"))}catch(s){throw new Error(`runtime_file_unreadable: ${s instanceof Error?s.message:String(s)}`)}if(!t||typeof t!="object")throw new Error("runtime_file_invalid");const r=t.socketPath;if(typeof r!="string"||!r.trim())throw new Error("runtime_socket_missing");const i=t.pid;return{socketPath:r,...typeof i=="number"&&Number.isInteger(i)&&i>0?{pid:i}:{}}}async function A(e){const{socketPath:t,pid:r}=ne(e);if(r&&!f(r))throw new Error(`runtime_process_stale: ${r}`);return new Promise((i,s)=>{const n=N.createConnection(t),o=setTimeout(()=>{n.destroy(),s(new Error(`runtime_socket_connect_timeout: ${t}`))},1e3);n.once("connect",()=>{clearTimeout(o),n.off("error",c),i(n)});const c=a=>{clearTimeout(o),n.destroy(),s(a)};n.once("error",c)})}async function x(e,t){const r=Date.now()+t;let i=null;for(;Date.now()<r;)try{return{ok:!0,socket:await A(e)}}catch(s){i=s instanceof Error?s:new Error(String(s));const n=r-Date.now();n>0&&await H(Math.min(150,n))}return{ok:!1,error:i??new Error("runtime file missing")}}async function D(e,t={},r=oe){w.mkdirSync(e.runtimeDir,{recursive:!0,mode:448});const i=t.forceNewInstance?["-n",...e.args]:e.args;try{await r(e.command,i)}catch(s){if(!(s instanceof Error?s.message:String(s)).includes("-1712"))throw s;await r(e.command,["-n",...e.args])}}function f(e){try{return process.kill(e,0),!0}catch{return!1}}async function oe(e,t){await new Promise((r,i)=>{const s=g(e,t,{stdio:["ignore","ignore","pipe"],windowsHide:!0});let n="";s.stderr.on("data",o=>{n=(n+String(o)).slice(-2e3)}),s.once("error",i),s.once("exit",(o,c)=>{o===0?r():i(new Error(`open Helper.app failed (${c?`signal=${c}`:`code=${o}`}${n.trim()?`, stderr=${n.trim()}`:""})`))})})}function H(e){return new Promise(t=>setTimeout(t,e))}function ae(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function ce(e){const t=String(e||"").toLowerCase();return t?t.includes("darwin")||t.includes("mac"):!0}function le(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}function $(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="ready"&&typeof t.helperVersion=="string"&&typeof t.protocolVersion=="number"&&Array.isArray(t.capabilities)&&typeof t.pid=="number"}function ue(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.ok=="boolean"&&typeof t.latencyMs=="number"}function he(e){return e==="windows.focus"||e==="windows.capture"||e==="screen.capture"||e==="ocr.recognize"||e==="image.cropHash"||e==="wechat.searchConversation"||e==="wechat.focusMessageInput"||e==="wechat.pasteAndSubmit"||e==="keyboard.primeTextPaste"||e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.")||e==="menu.pickItem"||e==="savePanel.saveToPath"}function q(e){return e==="windows.capture"||e==="screen.capture"||e==="ocr.recognize"||e==="image.cropHash"}function pe(e){return e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.")||e==="menu.pickItem"||e==="savePanel.saveToPath"}function F(e){return e==="windows.focus"||e==="wechat.searchConversation"||e==="wechat.focusMessageInput"||e==="wechat.pasteAndSubmit"||e==="keyboard.primeTextPaste"||e.startsWith("mouse.")||e.startsWith("keyboard.")||e.startsWith("clipboard.set")||e==="clipboard.restore"||e==="menu.pickItem"||e==="savePanel.saveToPath"}export{Ce as WeChatChannelHelperClient,Z as helperLaunchSpec,j as stopWindowsWeChatChannelHelperProcesses};
@@ -1,7 +1,7 @@
1
- import P from"node:fs";import J from"node:path";import{WeChatChannelApiError as Ae}from"./client.js";import{defaultWeChatChannelAttachmentDir as Fe,resolveVisibleWeChatChannelMedia as De}from"./media-resolver.js";import{updateWeChatChannelBindingLedger as Le}from"./ledger.js";import{defaultWeChatChannelVectorStorePath as Oe,loadWeChatChannelVectorStore as Ke,saveWeChatChannelVectorStore as $e,upsertWeChatChannelVectorReferences as Ve}from"./vector-store.js";import{normalizeWeChatChannelAttachmentAvailability as Z,normalizeWeChatChannelMessageKind as ze}from"./core/schema.js";import{waitForWeChatChannelPacing as Q,weChatChannelPacingDelayMs as qe}from"./pacing.js";import{matchWeChatConversationFingerprints as je}from"./fingerprint.js";import{normalizeWeChatAnchorText as v,weChatTextSimilarity as ee}from"./anchor.js";import{decideWeChatChannelActivityGate as Ge,normalizeWeChatChannelActivitySnapshot as He}from"./human-coordination.js";const Ue=3,Ye=5,Xe="wechat_login_required",Je=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 Tn(e){return await lt(e.helper,e.activityGuard,e.traceId).withLease("observe","observe-binding",async n=>Ze({...e,helper:n}))}async function Ze(e){const t=e.foregroundMode??"required";let n=await Qe(e,{foregroundMode:t});if(t!=="background"&&(n=await pe(e.helper,n,e.traceId)),t==="background"){const{capture:s,ocr:a}=await k({helper:e.helper,window:n,traceId:e.traceId}),c=E({capture:s,ocr:a,window:n});if(c)throw new Error(c);if(!O(a,s,e.binding.conversationDisplayName))throw new Error("conversation_not_visible_background");if(U({capture:s,ocr:a,binding:e.binding}))throw new Error("wechat_window_obstructed_background");return e.onObservationEvidence?.({window:n,capture:s,ocr:a}),ce(e)?de({...e,window:n,capture:s,ocr:a}):V({...e,window:n,capture:s,ocr:a})}const r=await q({helper:e.helper,window:n,binding:e.binding,runtime:e.runtime,api:e.api,workDir:e.workDir,traceId:e.traceId});if(!r.opened){const s=await ae({...e,fallback:n,requireTargetConversation:!1,force:!0});if(s.windowId!==n.windowId){n=await pe(e.helper,s,e.traceId);const a=await q({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||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(U({capture:i,ocr:o,binding:e.binding})){n=await zt(e.helper,e.traceId);const s=await q({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||"wechat_window_obstructed");if({capture:i,ocr:o}=await k({helper:e.helper,window:n,traceId:e.traceId}),U({capture:i,ocr:o,binding:e.binding}))throw new Error("wechat_window_obstructed")}return e.onObservationEvidence?.({window:n,capture:i,ocr:o}),ce(e)?de({...e,window:n,capture:i,ocr:o}):V({...e,window:n,capture:i,ocr:o})}async function Qe(e,t={}){const n=t.foregroundMode??e.foregroundMode??"required",r=await $t(e.helper,e.traceId,{foreground:n});return n==="background"?r:ae({...e,fallback:r,requireTargetConversation:!1,force:t.forceVision})}const x=new Map;function et(){return process.env.SHENNIAN_WECHAT_VISION_LAYOUT_REUSE!=="0"}function tt(e){if(!et()||!e.classification||e.classification.windowKind!=="chat_main")return;const t=e.window.windowId;if(!t)return;const n=oe(e.window),r=R(e.classification.layout?.messageInputRect,e.screenshot,e.window,"message-input"),i=R(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()},s=`${e.runtime.runtimeId}:${e.binding.bindingId}:${t}`,a=`${e.runtime.runtimeId}:window:${t}:${n}`;x.set(s,o),x.set(a,o),W(e,s,o),W(e,a,o)}async function En(e){const t=await te(e,"messageInputPoint");if(!t.messageInputPoint)throw new Error("wechat_message_input_not_found:vision_rect_missing");return t.messageInputPoint}async function nt(e){const t=await te(e,"searchInputPoint");if(!t.searchInputPoint)throw new Error("wechat_search_input_not_found:vision_rect_missing");return t.searchInputPoint}async function te(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=oe(e.window),o=`${e.runtime.runtimeId}:${e.binding.bindingId}:${r||"unknown"}`,s=`${e.runtime.runtimeId}:window:${r||"unknown"}:${i}`,a=x.get(o)??x.get(s)??re(e,o)??re(e,s);if(a&&a.windowId===r&&a.boundsKey===i&&(!t||a[t]))return x.set(o,a),x.set(s,a),a;const c=e.screenshot??await F(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=R(l.layout?.messageInputRect,c,e.window,"message-input"),u=R(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(s,d),W(e,o,d),W(e,s,d),d}function ne(e){const t=e.workDir;return t?J.join(t,"wechat-channel",e.runtime.runtimeId,"vision-layout-point-cache.json"):null}function re(e,t){const n=ne(e);if(!n)return null;try{const r=JSON.parse(P.readFileSync(n,"utf8"));return rt(r[t])}catch{return null}}function W(e,t,n){const r=ne(e);if(r)try{let i={};try{i=JSON.parse(P.readFileSync(r,"utf8"))}catch{i={}}i[t]=n,P.mkdirSync(J.dirname(r),{recursive:!0}),P.writeFileSync(r,`${JSON.stringify(i,null,2)}
2
- `,"utf8")}catch{}}function rt(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=ie(t.messageInputPoint??t.point),o=ie(t.searchInputPoint);return{windowId:n,boundsKey:r,messageInputPoint:i,searchInputPoint:o,...typeof t.updatedAt=="string"?{updatedAt:t.updatedAt}:{}}}function ie(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 oe(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 R(e,t,n,r="message-input"){const i=Number(e?.x),o=Number(e?.y),s=Number(e?.width),a=Number(e?.height);if(![i,o,s,a].every(Number.isFinite)||s<=0||a<=0)return null;const c=e?.coordinateSpace==="screen"?{x:i,y:o,width:s,height:a,coordinateSpace:"screen"}:{x:i/999*t.width,y:o/999*t.height,width:s/999*t.width,height:a/999*t.height,coordinateSpace:"screenshotPixel"},l=it(c,t,n,r);return l?{x:Math.round(l.x),y:Math.round(l.y),coordinateSpace:"screen"}:null}function it(e,t,n,r="message-input"){const i=r==="message-input"?.28:.55,o=ot({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 ot(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),s=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-s)/i}}async function ae(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(G).filter(s=>s.visible!==!1&&s.minimized!==!0&&!!s.windowId),r=ct(n.length?n:[e.fallback],e.fallback);if(!r.length)throw new Error("wechat_window_not_found");const i=[];for(const s of r)try{const a=await F(e.helper,s.windowId,e.traceId,s.bounds),c=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:a.mimeType,dataBase64:a.dataBase64,width:a.width,height:a.height,windowId:s.windowId},traceId:e.traceId});i.push({window:s,classification:c,screenshot:a,score:dt(c,e.requireTargetConversation===!0)})}catch(a){if(at(a))throw a;i.push({window:s,classification:null,errorSummary:a instanceof Error?a.message:String(a||"window classification failed"),score:-1})}const o=i.filter(s=>s.score>0).sort((s,a)=>a.score-s.score)[0];if(!o){const s=i.map(a=>({windowId:a.window.windowId,appName:a.window.appName,title:a.window.title,score:a.score,errorSummary:a.errorSummary,classification:a.classification?{windowKind:a.classification.windowKind,reasonCode:a.classification.reasonCode,confidence:a.classification.confidence,conversationTitle:a.classification.conversationTitle,isTargetConversation:a.classification.isTargetConversation}:null}));throw new Error(`wechat_chat_main_window_not_found: ${JSON.stringify(s)}`)}return o.screenshot&&tt({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 Bn(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 at(e){const t=st(e);return t==="insufficient_credits"||t==="entitlement_required"||t==="manual_review_required"||t==="wechat_channel_network_failed"||t==="wechat_channel_invalid_response"}function st(e){if(e instanceof Ae||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 ct(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 dt(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 lt(e,t,n){if(!t)return{helper:e,withLease:async(a,c,l)=>await l(e)};let r=null;const i=a=>{t.onEvent?.({...a,at:new Date().toISOString()})},o=async(a,c,l={})=>{if(r){const u=await e.request("automation.lease.status",{},n),d=u.result??{},f=u.ok&&d.interrupted?se(d.interruptReason):u.ok?void 0:u.errorCode||"user_activity_unknown";if(i({phase:"lease-status",stage:a,action:c,ok:u.ok===!0&&!d.interrupted,...f?{reasonCode:f}:{}}),!u.ok)throw new N({reasonCode:u.errorCode||"user_activity_unknown",stage:a,action:c});if(d.active===!1||d.leaseId!==r||!d.interrupted)return;throw new N({reasonCode:se(d.interruptReason),stage:a,action:c})}const w=Date.now()+wt(t.preflightIdleSettleTimeoutMs);for(;;){const u=await e.request("activity.snapshot",{},n);if(!u.ok)throw i({phase:"snapshot",stage:a,action:c,ok:!1,reasonCode:u.errorCode||"user_activity_unknown"}),new N({reasonCode:u.errorCode||"user_activity_unknown",stage:a,action:c});const d=Ge({snapshot:He(u.result),stage:a,policy:t.policy});if(i({phase:"snapshot",stage:a,action:c,ok:d.ok,...d.ok?{}:{reasonCode:d.reasonCode,waitMs:d.waitMs}}),d.ok)return;const f=new N({reasonCode:d.reasonCode,stage:a,action:c});if(!l.settle)throw f;const X=w-Date.now();if(X<=0)throw f;await H(Math.max(50,Math.min(d.waitMs,X)))}},s={request:async(a,c,l)=>{const w=ut(a);w&&await o(w.stage,`${a}:before`);const u=await e.request(a,c,l);return w&&u.ok&&await o(w.stage,`${a}:after`),u}};return{helper:s,async withLease(a,c,l){if(await Dt(e,n),await o(a,`${c}:preflight`,{settle:!0}),t.useAutomationLease===!1)return await l(s);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:a,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:a,action:c});try{const u=await l(s);return await o(a,`${c}:complete`),u}finally{const u=r;if(r=null,u){const d=await e.request("automation.lease.release",{leaseId:u},n).catch(f=>({ok:!1,errorCode:"automation_lease_release_failed",errorSummary:f instanceof Error?f.message:String(f)}));i({phase:"lease-release",stage:a,action:c,ok:d.ok===!0,...d.ok?{}:{reasonCode:d.errorCode||"automation_lease_release_failed"}})}}}}}function ut(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 se(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 wt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:Je}function ce(e){return e.observePipeline==="edge-structure"?!0:e.observePipeline==="server-observe"?!1:!!e.api.structureWindow}async function V(e){const t=await _e(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 he({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 Be(r,Ee({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}))}async function de(e){if(!e.api.structureWindow)throw new Error("wechat_structure_window_unavailable");const t=await _e(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(ht(c))return V(e);throw c}const r=Ct(n.structuredMessages??n.observedMessages??[]),i=await ft({...e,messages:r,screenshot:t}),o=await he({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}),s=Be(o,Ee({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}));return e.localLedger?Le({ledger:e.localLedger,bindingId:e.binding.bindingId,observedMessages:s,baselineOnly:e.baselineOnly,vectorReferences:i.vectorReferences}).newMessages:s}function ht(e){return e instanceof Error&&/\bedge_runtime_disabled\b/.test(e.message)}async function ft(e){const t=mt(e.messages);if(!t.length)return{messages:e.messages,vectorReferences:[]};const n=e.api.embedVisual?await gt({...e,seedBlocks:t}):t.filter(s=>h(s.vectorBase64)||h(s.signature));if(!n.length)return{messages:e.messages,vectorReferences:[]};const r=e.vectorStorePath??Oe(e.workDir||process.cwd(),e.runtime.runtimeId),i=Ke(r,e.runtime.runtimeId),o=Ve({store:i,bindingId:e.binding.bindingId,blocks:n});return o.length?($e(r,i),{messages:vt(e.messages,o),vectorReferences:o}):{messages:e.messages,vectorReferences:[]}}function mt(e){const t=[];for(const n of e)for(const[r,i]of(n.visualBlocks??[]).entries()){const o=h(i.blockId)||`${n.stableMessageKey}:visual-${r}`,s=h(i.blockKind)||n.kind||"visual";t.push({...i,stableMessageKey:n.stableMessageKey,blockId:o,blockKind:s,...i.bbox!==void 0?{bbox:i.bbox}:n.bbox!==void 0?{bbox:n.bbox}:{}})}return t}async function bt(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 xt(t.visualBlocks??t.embeddedBlocks??[],e.seedBlocks)}async function gt(e){try{return await bt(e)}catch(t){if(yt(t))throw t;return[]}}function yt(e){return!e||typeof e!="object"?!1:e.reasonCode==="insufficient_credits"?!0:e instanceof Error&&/\binsufficient_credits\b/.test(e.message)}function xt(e,t){return e.map((n,r)=>{const i=t[r];return{...n,stableMessageKey:h(n.stableMessageKey)||h(i?.stableMessageKey),blockId:h(n.blockId)||h(i?.blockId),blockKind:h(n.blockKind)||h(i?.blockKind)||"visual",...n.bbox!==void 0?{bbox:n.bbox}:i?.bbox!==void 0?{bbox:i.bbox}:{}}}).filter(n=>h(n.stableMessageKey)&&h(n.blockId))}function vt(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:pt(r,i)}:r})}function pt(e,t){const r=(e.visualBlocks??[]).map((o,s)=>{const a=h(o.blockId)||`${e.stableMessageKey}:visual-${s}`,c=t.find(l=>l.blockId===a);return c?le(c,o):ue(o)}),i=new Set(r.map(o=>o.blockId));for(const o of t)i.has(o.blockId)||r.push(le(o));return r}function le(e,t){return{...t?ue(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 ue(e){const{vectorBase64:t,...n}=e;return n}function Ct(e){return e.map((t,n)=>It(t,n)).filter(t=>t!=null)}function It(e,t){if(!b(e))return null;const n=ze(e.kind),r=St(e.senderRole),i=g(e.normalizedText),o=g(e.anchorText)??i??g(e.textExcerpt),s=h(e.stableMessageKey)||_t({message:e,index:t,senderRole:r,kind:n,anchorText:o});return{stableMessageKey:s,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:kt(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:s}}}function _t(e){const t=b(e.message.bbox)?JSON.stringify(e.message.bbox):"";return`structured-window:${[e.index,e.senderRole,e.kind,e.anchorText||h(e.message.textExcerpt)||"",t].join(":").slice(0,180)}`}function kt(e){if(!b(e))return e;const t={...e};return I(t,"availability")&&(t.availability=Z(t.availability)),b(t.attachment)&&(t.attachment=we(t.attachment)),Array.isArray(t.attachments)&&(t.attachments=t.attachments.map(n=>b(n)?we(n):n)),t}function we(e){const t={...e};return I(t,"availability")&&(t.availability=Z(t.availability)),t}function St(e){return e==="self"||e==="contact"||e==="system"||e==="unknown"?e:"unknown"}async function he(e){if(e.binding.downloadMedia===!1)return e.messages;const t=e.messages.map((o,s)=>Wt(o,e.screenshot,e.window,Pt(e.messages,s))).filter((o,s)=>Mt(e.messages,s,e.mediaAnchorText)).filter(o=>o!=null);if(!t.length)return e.messages;const n=e.attachmentsDir??Fe(e.workDir||process.cwd(),e.runtime.runtimeId,e.binding.bindingId),r=await De({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 s=i.get(o.stableMessageKey);return s?{...o,mediaMetadata:Rt(o.mediaMetadata,s.attachment,s.reasonCode,s.attemptReasonCodes,s.resolveTrace)}:o})}function Mt(e,t,n){const r=me(n);if(!r)return!0;const i=Nt(r),o=e.map((s,a)=>me(Bt(s)).includes(r)?a:-1).filter(s=>s>=0);if(!o.length)return t===Tt(e,i);for(const s of o)if(t>=s&&t<=s+8||t===s-1&&!e.slice(s+1,Math.min(e.length,s+9)).some(fe))return!0;return!1}function Nt(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 Tt(e,t=null){for(let n=e.length-1;n>=0;n-=1)if(fe(e[n]))return Et(e[n],t)?n:-1;return-1}function fe(e){if(!e)return!1;const t=String(e.kind||"").toLowerCase(),n=b(e.mediaMetadata)?e.mediaMetadata:{},r=b(n.attachment)?n.attachment:{};return be(t,n,r)}function Et(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(),s=String(i.mimeType||"").toLowerCase(),a=String(i.name||i.localPath||e.anchorText||e.textExcerpt||"").toLowerCase();return t==="video"?n.includes("video")||o==="video"||s.startsWith("video/")||/\.(mp4|mov|m4v|avi|mkv|webm)$/i.test(a):t==="image"?/image|photo|picture/.test(n)||o==="image"||s.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(a):/file|document/.test(n)||o==="file"||!/image|photo|picture|video/.test(n)&&o!=="image"&&o!=="video"&&!s.startsWith("image/")&&!s.startsWith("video/")}function Bt(e){if(!e)return"";const t=e;return[e.normalizedText,e.anchorText,e.textExcerpt,t.text].map(n=>String(n||"")).join(`
1
+ import P from"node:fs";import J from"node:path";import{WeChatChannelApiError as Ae}from"./client.js";import{defaultWeChatChannelAttachmentDir as Fe,resolveVisibleWeChatChannelMedia as Le}from"./media-resolver.js";import{updateWeChatChannelBindingLedger as De}from"./ledger.js";import{defaultWeChatChannelVectorStorePath as Oe,loadWeChatChannelVectorStore as Ke,saveWeChatChannelVectorStore as $e,upsertWeChatChannelVectorReferences as ze}from"./vector-store.js";import{normalizeWeChatChannelAttachmentAvailability as Z,normalizeWeChatChannelMessageKind as Ve}from"./core/schema.js";import{waitForWeChatChannelPacing as Q,weChatChannelPacingDelayMs as qe}from"./pacing.js";import{matchWeChatConversationFingerprints as je}from"./fingerprint.js";import{normalizeWeChatAnchorText as v,weChatTextSimilarity as ee}from"./anchor.js";import{decideWeChatChannelActivityGate as He,normalizeWeChatChannelActivitySnapshot as Ge}from"./human-coordination.js";const Ue=3,Ye=5,Xe="wechat_login_required",Je=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 En(e){return await lt(e.helper,e.activityGuard,e.traceId).withLease("observe","observe-binding",async n=>Ze({...e,helper:n}))}async function Ze(e){const t=e.foregroundMode??"required";let n=await Qe(e,{foregroundMode:t});if(t!=="background"&&(n=await pe(e.helper,n,e.traceId)),t==="background"){const{capture:s,ocr:a}=await k({helper:e.helper,window:n,traceId:e.traceId}),c=E({capture:s,ocr:a,window:n});if(c)throw new Error(c);if(!O(a,s,e.binding.conversationDisplayName))throw new Error("conversation_not_visible_background");if(U({capture:s,ocr:a,binding:e.binding}))throw new Error("wechat_window_obstructed_background");return e.onObservationEvidence?.({window:n,capture:s,ocr:a}),ce(e)?de({...e,window:n,capture:s,ocr:a}):z({...e,window:n,capture:s,ocr:a})}const r=await q({helper:e.helper,window:n,binding:e.binding,runtime:e.runtime,api:e.api,workDir:e.workDir,traceId:e.traceId});if(!r.opened){const s=await ae({...e,fallback:n,requireTargetConversation:!1,force:!0});if(s.windowId!==n.windowId){n=await pe(e.helper,s,e.traceId);const a=await q({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||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(U({capture:i,ocr:o,binding:e.binding})){n=await qt(e.helper,e.traceId);const s=await q({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||"wechat_window_obstructed");if({capture:i,ocr:o}=await k({helper:e.helper,window:n,traceId:e.traceId}),U({capture:i,ocr:o,binding:e.binding}))throw new Error("wechat_window_obstructed")}return e.onObservationEvidence?.({window:n,capture:i,ocr:o}),ce(e)?de({...e,window:n,capture:i,ocr:o}):z({...e,window:n,capture:i,ocr:o})}async function Qe(e,t={}){const n=t.foregroundMode??e.foregroundMode??"required",r=await zt(e.helper,e.traceId,{foreground:n});return n==="background"?r:ae({...e,fallback:r,requireTargetConversation:!1,force:t.forceVision})}const x=new Map;function et(){return process.env.SHENNIAN_WECHAT_VISION_LAYOUT_REUSE!=="0"}function tt(e){if(!et()||!e.classification||e.classification.windowKind!=="chat_main")return;const t=e.window.windowId;if(!t)return;const n=oe(e.window),r=R(e.classification.layout?.messageInputRect,e.screenshot,e.window,"message-input"),i=R(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()},s=`${e.runtime.runtimeId}:${e.binding.bindingId}:${t}`,a=`${e.runtime.runtimeId}:window:${t}:${n}`;x.set(s,o),x.set(a,o),W(e,s,o),W(e,a,o)}async function Bn(e){const t=await te(e,"messageInputPoint");if(!t.messageInputPoint)throw new Error("wechat_message_input_not_found:vision_rect_missing");return t.messageInputPoint}async function nt(e){const t=await te(e,"searchInputPoint");if(!t.searchInputPoint)throw new Error("wechat_search_input_not_found:vision_rect_missing");return t.searchInputPoint}async function te(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=oe(e.window),o=`${e.runtime.runtimeId}:${e.binding.bindingId}:${r||"unknown"}`,s=`${e.runtime.runtimeId}:window:${r||"unknown"}:${i}`,a=x.get(o)??x.get(s)??re(e,o)??re(e,s);if(a&&a.windowId===r&&a.boundsKey===i&&(!t||a[t]))return x.set(o,a),x.set(s,a),a;const c=e.screenshot??await F(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=R(l.layout?.messageInputRect,c,e.window,"message-input"),u=R(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(s,d),W(e,o,d),W(e,s,d),d}function ne(e){const t=e.workDir;return t?J.join(t,"wechat-channel",e.runtime.runtimeId,"vision-layout-point-cache.json"):null}function re(e,t){const n=ne(e);if(!n)return null;try{const r=JSON.parse(P.readFileSync(n,"utf8"));return rt(r[t])}catch{return null}}function W(e,t,n){const r=ne(e);if(r)try{let i={};try{i=JSON.parse(P.readFileSync(r,"utf8"))}catch{i={}}i[t]=n,P.mkdirSync(J.dirname(r),{recursive:!0}),P.writeFileSync(r,`${JSON.stringify(i,null,2)}
2
+ `,"utf8")}catch{}}function rt(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=ie(t.messageInputPoint??t.point),o=ie(t.searchInputPoint);return{windowId:n,boundsKey:r,messageInputPoint:i,searchInputPoint:o,...typeof t.updatedAt=="string"?{updatedAt:t.updatedAt}:{}}}function ie(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 oe(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 R(e,t,n,r="message-input"){const i=Number(e?.x),o=Number(e?.y),s=Number(e?.width),a=Number(e?.height);if(![i,o,s,a].every(Number.isFinite)||s<=0||a<=0)return null;const c=e?.coordinateSpace==="screen"?{x:i,y:o,width:s,height:a,coordinateSpace:"screen"}:{x:i/999*t.width,y:o/999*t.height,width:s/999*t.width,height:a/999*t.height,coordinateSpace:"screenshotPixel"},l=it(c,t,n,r);return l?{x:Math.round(l.x),y:Math.round(l.y),coordinateSpace:"screen"}:null}function it(e,t,n,r="message-input"){const i=r==="message-input"?.28:.55,o=ot({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 ot(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),s=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-s)/i}}async function ae(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(H).filter(s=>s.visible!==!1&&s.minimized!==!0&&!!s.windowId),r=ct(n.length?n:[e.fallback],e.fallback);if(!r.length)throw new Error("wechat_window_not_found");const i=[];for(const s of r)try{const a=await F(e.helper,s.windowId,e.traceId,s.bounds),c=await e.api.classifyWindow(e.runtime,e.binding,{screenshot:{mimeType:a.mimeType,dataBase64:a.dataBase64,width:a.width,height:a.height,windowId:s.windowId},traceId:e.traceId});i.push({window:s,classification:c,screenshot:a,score:dt(c,e.requireTargetConversation===!0)})}catch(a){if(at(a))throw a;i.push({window:s,classification:null,errorSummary:a instanceof Error?a.message:String(a||"window classification failed"),score:-1})}const o=i.filter(s=>s.score>0).sort((s,a)=>a.score-s.score)[0];if(!o){const s=i.map(a=>({windowId:a.window.windowId,appName:a.window.appName,title:a.window.title,score:a.score,errorSummary:a.errorSummary,classification:a.classification?{windowKind:a.classification.windowKind,reasonCode:a.classification.reasonCode,confidence:a.classification.confidence,conversationTitle:a.classification.conversationTitle,isTargetConversation:a.classification.isTargetConversation}:null}));throw new Error(`wechat_chat_main_window_not_found: ${JSON.stringify(s)}`)}return o.screenshot&&tt({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 Pn(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 at(e){const t=st(e);return t==="insufficient_credits"||t==="entitlement_required"||t==="manual_review_required"||t==="wechat_channel_network_failed"||t==="wechat_channel_invalid_response"}function st(e){if(e instanceof Ae||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 ct(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 dt(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 lt(e,t,n){if(!t)return{helper:e,withLease:async(a,c,l)=>await l(e)};let r=null;const i=a=>{t.onEvent?.({...a,at:new Date().toISOString()})},o=async(a,c,l={})=>{if(r){const u=await e.request("automation.lease.status",{},n),d=u.result??{},f=u.ok&&d.interrupted?se(d.interruptReason):u.ok?void 0:u.errorCode||"user_activity_unknown";if(i({phase:"lease-status",stage:a,action:c,ok:u.ok===!0&&!d.interrupted,...f?{reasonCode:f}:{}}),!u.ok)throw new N({reasonCode:u.errorCode||"user_activity_unknown",stage:a,action:c});if(d.active===!1||d.leaseId!==r||!d.interrupted)return;throw new N({reasonCode:se(d.interruptReason),stage:a,action:c})}const w=Date.now()+wt(t.preflightIdleSettleTimeoutMs);for(;;){const u=await e.request("activity.snapshot",{},n);if(!u.ok)throw i({phase:"snapshot",stage:a,action:c,ok:!1,reasonCode:u.errorCode||"user_activity_unknown"}),new N({reasonCode:u.errorCode||"user_activity_unknown",stage:a,action:c});const d=He({snapshot:Ge(u.result),stage:a,policy:t.policy});if(i({phase:"snapshot",stage:a,action:c,ok:d.ok,...d.ok?{}:{reasonCode:d.reasonCode,waitMs:d.waitMs}}),d.ok)return;const f=new N({reasonCode:d.reasonCode,stage:a,action:c});if(!l.settle)throw f;const X=w-Date.now();if(X<=0)throw f;await G(Math.max(50,Math.min(d.waitMs,X)))}},s={request:async(a,c,l)=>{const w=ut(a);w&&await o(w.stage,`${a}:before`);const u=await e.request(a,c,l);return w&&u.ok&&await o(w.stage,`${a}:after`),u}};return{helper:s,async withLease(a,c,l){if(await Lt(e,n),await o(a,`${c}:preflight`,{settle:!0}),t.useAutomationLease===!1)return await l(s);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:a,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:a,action:c});try{const u=await l(s);return await o(a,`${c}:complete`),u}finally{const u=r;if(r=null,u){const d=await e.request("automation.lease.release",{leaseId:u},n).catch(f=>({ok:!1,errorCode:"automation_lease_release_failed",errorSummary:f instanceof Error?f.message:String(f)}));i({phase:"lease-release",stage:a,action:c,ok:d.ok===!0,...d.ok?{}:{reasonCode:d.errorCode||"automation_lease_release_failed"}})}}}}}function ut(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 se(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 wt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:Je}function ce(e){return e.observePipeline==="edge-structure"?!0:e.observePipeline==="server-observe"?!1:!!e.api.structureWindow}async function z(e){const t=await _e(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 he({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 Be(r,Ee({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}))}async function de(e){if(!e.api.structureWindow)throw new Error("wechat_structure_window_unavailable");const t=await _e(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(ht(c))return z(e);throw c}const r=Ct(n.structuredMessages??n.observedMessages??[]),i=await ft({...e,messages:r,screenshot:t}),o=await he({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}),s=Be(o,Ee({ocr:e.ocr,screenshot:t,binding:e.binding,anchors:e.localOutboundEchoAnchors??[]}));return e.localLedger?De({ledger:e.localLedger,bindingId:e.binding.bindingId,observedMessages:s,baselineOnly:e.baselineOnly,vectorReferences:i.vectorReferences}).newMessages:s}function ht(e){return e instanceof Error&&/\bedge_runtime_disabled\b/.test(e.message)}async function ft(e){const t=mt(e.messages);if(!t.length)return{messages:e.messages,vectorReferences:[]};const n=e.api.embedVisual?await gt({...e,seedBlocks:t}):t.filter(s=>h(s.vectorBase64)||h(s.signature));if(!n.length)return{messages:e.messages,vectorReferences:[]};const r=e.vectorStorePath??Oe(e.workDir||process.cwd(),e.runtime.runtimeId),i=Ke(r,e.runtime.runtimeId),o=ze({store:i,bindingId:e.binding.bindingId,blocks:n});return o.length?($e(r,i),{messages:vt(e.messages,o),vectorReferences:o}):{messages:e.messages,vectorReferences:[]}}function mt(e){const t=[];for(const n of e)for(const[r,i]of(n.visualBlocks??[]).entries()){const o=h(i.blockId)||`${n.stableMessageKey}:visual-${r}`,s=h(i.blockKind)||n.kind||"visual";t.push({...i,stableMessageKey:n.stableMessageKey,blockId:o,blockKind:s,...i.bbox!==void 0?{bbox:i.bbox}:n.bbox!==void 0?{bbox:n.bbox}:{}})}return t}async function bt(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 xt(t.visualBlocks??t.embeddedBlocks??[],e.seedBlocks)}async function gt(e){try{return await bt(e)}catch(t){if(yt(t))throw t;return[]}}function yt(e){return!e||typeof e!="object"?!1:e.reasonCode==="insufficient_credits"?!0:e instanceof Error&&/\binsufficient_credits\b/.test(e.message)}function xt(e,t){return e.map((n,r)=>{const i=t[r];return{...n,stableMessageKey:h(n.stableMessageKey)||h(i?.stableMessageKey),blockId:h(n.blockId)||h(i?.blockId),blockKind:h(n.blockKind)||h(i?.blockKind)||"visual",...n.bbox!==void 0?{bbox:n.bbox}:i?.bbox!==void 0?{bbox:i.bbox}:{}}}).filter(n=>h(n.stableMessageKey)&&h(n.blockId))}function vt(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:pt(r,i)}:r})}function pt(e,t){const r=(e.visualBlocks??[]).map((o,s)=>{const a=h(o.blockId)||`${e.stableMessageKey}:visual-${s}`,c=t.find(l=>l.blockId===a);return c?le(c,o):ue(o)}),i=new Set(r.map(o=>o.blockId));for(const o of t)i.has(o.blockId)||r.push(le(o));return r}function le(e,t){return{...t?ue(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 ue(e){const{vectorBase64:t,...n}=e;return n}function Ct(e){return e.map((t,n)=>It(t,n)).filter(t=>t!=null)}function It(e,t){if(!b(e))return null;const n=Ve(e.kind),r=St(e.senderRole),i=g(e.normalizedText),o=g(e.anchorText)??i??g(e.textExcerpt),s=h(e.stableMessageKey)||_t({message:e,index:t,senderRole:r,kind:n,anchorText:o});return{stableMessageKey:s,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:kt(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:s}}}function _t(e){const t=b(e.message.bbox)?JSON.stringify(e.message.bbox):"";return`structured-window:${[e.index,e.senderRole,e.kind,e.anchorText||h(e.message.textExcerpt)||"",t].join(":").slice(0,180)}`}function kt(e){if(!b(e))return e;const t={...e};return I(t,"availability")&&(t.availability=Z(t.availability)),b(t.attachment)&&(t.attachment=we(t.attachment)),Array.isArray(t.attachments)&&(t.attachments=t.attachments.map(n=>b(n)?we(n):n)),t}function we(e){const t={...e};return I(t,"availability")&&(t.availability=Z(t.availability)),t}function St(e){return e==="self"||e==="contact"||e==="system"||e==="unknown"?e:"unknown"}async function he(e){if(e.binding.downloadMedia===!1)return e.messages;const t=e.messages.map((o,s)=>Wt(o,e.screenshot,e.window,Pt(e.messages,s))).filter((o,s)=>Mt(e.messages,s,e.mediaAnchorText)).filter(o=>o!=null);if(!t.length)return e.messages;const n=e.attachmentsDir??Fe(e.workDir||process.cwd(),e.runtime.runtimeId,e.binding.bindingId),r=await Le({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 s=i.get(o.stableMessageKey);return s?{...o,mediaMetadata:Rt(o.mediaMetadata,s.attachment,s.reasonCode,s.attemptReasonCodes,s.resolveTrace)}:o})}function Mt(e,t,n){const r=me(n);if(!r)return!0;const i=Nt(r),o=e.map((s,a)=>me(Bt(s)).includes(r)?a:-1).filter(s=>s>=0);if(!o.length)return t===Tt(e,i);for(const s of o)if(t>=s&&t<=s+8||t===s-1&&!e.slice(s+1,Math.min(e.length,s+9)).some(fe))return!0;return!1}function Nt(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 Tt(e,t=null){for(let n=e.length-1;n>=0;n-=1)if(fe(e[n]))return Et(e[n],t)?n:-1;return-1}function fe(e){if(!e)return!1;const t=String(e.kind||"").toLowerCase(),n=b(e.mediaMetadata)?e.mediaMetadata:{},r=b(n.attachment)?n.attachment:{};return be(t,n,r)}function Et(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(),s=String(i.mimeType||"").toLowerCase(),a=String(i.name||i.localPath||e.anchorText||e.textExcerpt||"").toLowerCase();return t==="video"?n.includes("video")||o==="video"||s.startsWith("video/")||/\.(mp4|mov|m4v|avi|mkv|webm)$/i.test(a):t==="image"?/image|photo|picture/.test(n)||o==="image"||s.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(a):/file|document/.test(n)||o==="file"||!/image|photo|picture|video/.test(n)&&o!=="image"&&o!=="video"&&!s.startsWith("image/")&&!s.startsWith("video/")}function Bt(e){if(!e)return"";const t=e;return[e.normalizedText,e.anchorText,e.textExcerpt,t.text].map(n=>String(n||"")).join(`
3
3
  `)}function me(e){return String(e||"").normalize("NFKC").replace(/[o]/giu,"0").replace(/[^\p{L}\p{N}]/gu,"").toLowerCase()}function Pt(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 Wt(e,t,n,r){const i=String(e.kind||"").toLowerCase(),o=b(e.mediaMetadata)?e.mediaMetadata:{},s=b(o.attachment)?o.attachment:{},a=h(s.availability)||h(o.availability),c=h(s.localPath)||h(o.localPath);if(a==="edge-local"&&c||!be(i,o,s))return null;const l=A(e.bbox)??A(o.bbox)??A(o.downloadActionBbox),w=A(o.downloadActionBbox),u=ge(l,t,n),d=Ft(l,t,n),f=ge(w,t,n);return{messageKey:e.stableMessageKey,kind:h(s.type)||h(s.kind)||h(o.messageType)||i,fileName:h(s.name)||h(s.fileName)||h(o.fileName)||null,mimeType:h(s.mimeType)||h(o.mimeType)||null,size:_(s.size)??_(o.size),mediaStatus:At(o,s),observedAt:e.observedAt??null,contextText:r??e.normalizedText??e.anchorText??e.textExcerpt??null,...u?{bbox:u}:{},...d?{screenshotBbox:d}:{},...f?{downloadActionBbox:f}:{}}}function Rt(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 At(e,t){const n=h(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=h(t.availability)||h(e.availability);return r==="pending-download"?"not_downloaded":r==="metadata-only"?"metadata_only":n||null}function be(e,t,n){const r=`${e} ${h(t.messageType)} ${h(n.type)} ${h(n.kind)}`.toLowerCase();return/image|photo|video|file|document/.test(r)}function A(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 ge(e,t,n){if(!e)return null;if(e.coordinateSpace==="screen")return e;const r=K(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,s=i.height/t.height,a=r.x,c=r.y;return{x:a-e.width*o/2,y:c-e.height*s/2,width:e.width*o,height:e.height*s,coordinateSpace:"screen"}}function Ft(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 h(e){return typeof e=="string"?e.trim():""}function g(e){return h(e)||null}function _(e){const t=Number(e);return Number.isFinite(t)?t:null}async function Pn(e,t){await xe(e,t)}async function Dt(e,t){await ye(e,t)}async function ye(e,t){const n=await e.request("permissions.check",{},t);m(n,"permissions.check");const r=n.result??{},i=await Lt(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 xe(e,t,n={}){const r=await ye(e,t),i=String(r.platform??"").toLowerCase();if(r.wechatRunning===!1)throw new Error("wechat_not_running");if(Vt(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 Lt(e,t,n){const r=Ot(t);if(!r||process.platform!=="darwin")return r;const i=Kt(r);try{await e.request(i,{},n)}catch{}return r}function Ot(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function Kt(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}async function $t(e,t,n={}){const i=(n.foreground??"required")!=="background",o=await xe(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 l}const s=await e.request("windows.ensureReady",{restore:i,focus:i},t);m(s,"windows.ensureReady");const a=s.result;if(!a?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return a}function Vt(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function ve(e){const t=e.filter(G),n=t.filter(i=>i.visible!==!1&&i.minimized!==!0);return(n.length?n:t)[0]??null}async function Wn(e,t){let n=await e.request("windows.list",{},t);m(n,"windows.list");let r=n.result?.windows??[],i=ve(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 Ce(e,i,t)}async function pe(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 zt(e,t){const n=await e.request("windows.list",{},t);m(n,"windows.list");const r=n.result?.windows??[],i=ve(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 Ce(e,i,t)}async function Ce(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(G);return i.find(o=>o.windowId===t.windowId)??i[0]??t}async function z(e){const{capture:t,ocr:n}=e.observation??await k(e),r=E({capture:t,ocr:n,window:e.window});if(r)return{opened:!1,reason:r};const i=je({visibleItems:Qt(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=bn(i.item.bbox,t,e.window);if(!o)return{opened:!1,reason:"conversation_bbox_missing"};const s=await e.helper.request("mouse.click",{x:o.x,y:o.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(s,"mouse.click"),{opened:!0,reason:i.reason}}async function q(e){let t={opened:!1,reason:"conversation_not_opened"};for(let r=0;r<Ue;r+=1){if(t=await qt(e),t.opened||t.reason!=="conversation_title_not_confirmed")return t;await S(e,"open-retry",`retry:${r}`)}const n=await Ie(e);return n.opened?{opened:!0,reason:`${n.reason}:final-visible-recovery`}:t}async function qt(e){const t=await k(e),n=E({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 T({helper:e.helper,window:e.window,traceId:e.traceId,observation:t}),{opened:!0,reason:"current-conversation-title-confirmed"};if(!r){const u=await z({...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 f=await Ie(e);if(f.opened)return f}}const i=await Xt(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 s=await jt(e);if(s.opened){await S(e,"open-click-settle","search-result-click");const u=await M(e);return u.ok?(e.settleToBottom===!0&&await T({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:s.reason}):{opened:!1,reason:u.reason}}let a=s.observation;const c=y(e.binding.conversationDisplayName)&&s.reason==="search_result_not_visible";if(!y(e.binding.conversationDisplayName)){await Zt(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 T({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"),a=void 0}const l=await z({...e,...a?{observation:a}:{},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 T({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:l.reason}):{opened:!1,reason:w.reason}}async function Ie(e){const t=await z(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 T({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 jt(e){let t;const n=e.searchDelayMs===0?0:D(e,"search-result-probe","search-result-probe"),r=y(e.binding.conversationDisplayName)?Ye:1;for(let i=0;i<r;i+=1){i>0&&n>0&&await H(n);const o=await Gt(e);t=o;const{capture:s,ocr:a}=o,c=E({capture:s,ocr:a,window:e.window});if(c)return{opened:!1,reason:c,observation:o};const l=nn(a,s,e.binding.conversationDisplayName);if(!l){if(rn(a)||on(a,e.binding.conversationDisplayName))break;continue}const w=K(l.bbox,s,Ht(s,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 Gt(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 ke(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 Ht(e,t){return e.bounds?{...t,bounds:e.bounds}:t}async function k(e){let{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds);return await Ut({helper:e.helper,window:e.window,capture:t,ocr:n,traceId:e.traceId})&&(await Q("preview-dismiss-settle",`${e.traceId||""}:${e.window.windowId}:preview-dismiss`),{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds)),{capture:t,ocr:n}}async function Ut(e){const t=Yt(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 Yt(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,s=Number(o?.y);if(!Number.isFinite(s))return null;const a=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-s)<t.height*.08}).sort((c,l)=>Number(l.bbox?.x??0)-Number(c.bbox?.x??0))[0];return K(a?.bbox,t,n)}async function Xt(e,t){if(!e.runtime||!e.api?.classifyWindow)return{ok:!1,reason:"wechat_search_input_detector_unavailable"};try{return{ok:!0,point:await nt({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 F(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 _e(e){return e.capture.dataBase64?e.capture:F(e.helper,e.window.windowId,e.traceId,e.window.bounds)}async function j(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 F(e,t,n,r),s=await ke(e,o,n);return{capture:o,ocr:s}}async function ke(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 G(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"||t==="\u5FAE\u4FE1"}function H(e){return new Promise(t=>setTimeout(t,e))}function D(e,t,n){return e.searchDelayMs===0?0:qe(t,Jt(e,n))}async function S(e,t,n){const r=D(e,t,n);r>0&&await H(r)}function Jt(e,t){return`${e.traceId||""}:${e.binding.conversationDisplayName}:${t}`}async function Zt(e,t){const n=await e.request("keyboard.shortcut",{key:"return",modifiers:[]},t);m(n,"keyboard.shortcut")}async function T(e){if(!e.window.bounds)return;const t=e.observation,n=gn(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 Q("jump-latest-settle",`${e.traceId||""}:${e.window.windowId}:jump-latest`)}}async function M(e){const{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds),r=E({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"}:{ok:!1,reason:"conversation_title_not_confirmed"}}function E(e){const n=(e.ocr.blocks??[]).map(r=>sn(r.text)).filter(Boolean).join("");return/(扫码登录|仅传输文件|重新登录|为了安全|安全验证|登录微信|微信登录|该账号已登录|帐号已登录|账号已登录|当前账号已登录|当前帐号已登录|已登录|进入微信|進入微信)/u.test(n)?Xe:null}function Qt(e,t,n=!0){const r=n?en(e.blocks??[],t):[];return r.length?r:e.visibleConversationFingerprints??[]}function en(e,t){const n=e.map(i=>Se(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=>!Me(i.text)),r=new Set;return n.filter(i=>!tn(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=B(i.title);return!o||r.has(o)?!1:(r.add(o),!0)})}function Se(e){const t=e.bbox,n=String(e.text||"").normalize("NFKC").trim(),r=Number(t?.x),i=Number(t?.y),o=Number(t?.width),s=Number(t?.height);return!n||![r,i,o,s].every(Number.isFinite)?null:{text:n,x:r,y:i,width:o,height:s}}function tn(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 Me(e){const t=p(e);return/^(搜索|微信|通讯录|收藏|设置|search)$/iu.test(t)||L(t)||an(t)||/^包含[::]?/u.test(t)||/搜索网络结果/u.test(t)}function nn(e,t,n){const r=(e.blocks??[]).map(a=>Se(a)).filter(a=>!!a),i=r.filter(a=>L(p(a.text))).sort((a,c)=>a.y-c.y||a.x-c.x),o=["\u7FA4\u804A","GroupChats","\u8054\u7CFB\u4EBA","Contacts"];for(const a of o){const c=i.findIndex(d=>p(d.text)===a);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=>!L(p(d.text))).filter(d=>!Te(d,r)).filter(d=>Y(d.text,n)).sort((d,f)=>d.y-f.y||d.x-f.x)[0];if(u)return{bbox:Ne(u,t),reason:"search-result-title"}}const s=r.filter(a=>a.y>t.height*.12&&a.y<t.height*.82).filter(a=>a.x>t.width*.08&&a.x<t.width*.45).filter(a=>a.text.length>=2).filter(a=>!Me(a.text)).filter(a=>!Te(a,r)).filter(a=>Y(a.text,n)).sort((a,c)=>a.y-c.y||a.x-c.x)[0];return y(n)?null:s?{bbox:Ne(s,t),reason:"search-result-title"}:null}function Ne(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 L(e){return/^(群聊|联系人|聊天记录|公众号|小程序|GroupChats|Contacts|ChatHistory|OfficialAccounts|MiniPrograms)$/u.test(e)}function rn(e){return(e.blocks??[]).some(t=>L(p(t.text)))}function on(e,t){return(e.visibleConversationFingerprints??[]).some(n=>Y(n.title,t))}function p(e){return String(e||"").normalize("NFKC").replace(/[^\p{L}\p{N}_-]/gu,"").trim()}function Te(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 an(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 sn(e){return String(e||"").normalize("NFKC").replace(/\s+/g,"").trim()}function O(e,t,n){const r=y(n)?B(n):$(n);return r?(e.blocks??[]).some(i=>{const o=y(n)?B(i.text):$(i.text);if(!o||!Pe(o,r))return!1;const s=i.bbox;if(!s)return!1;const a=Number(s.x),c=Number(s.y);if(!Number.isFinite(a)||!Number.isFinite(c))return!1;const l=a>t.width*.32&&a<t.width*.78&&c<t.height*.16,w=a<t.width*.18&&c<t.height*.12;return l||w}):!1}function U(e){if(O(e.ocr,e.capture,e.binding.conversationDisplayName))return!1;const t=(e.ocr.blocks??[]).map(a=>String(a.text||"").normalize("NFKC").replace(/\s+/g," ").trim()).filter(Boolean),n=t.join(`
4
+ `)||null}function Wt(e,t,n,r){const i=String(e.kind||"").toLowerCase(),o=b(e.mediaMetadata)?e.mediaMetadata:{},s=b(o.attachment)?o.attachment:{},a=h(s.availability)||h(o.availability),c=h(s.localPath)||h(o.localPath);if(a==="edge-local"&&c||!be(i,o,s))return null;const l=A(e.bbox)??A(o.bbox)??A(o.downloadActionBbox),w=A(o.downloadActionBbox),u=ge(l,t,n),d=Ft(l,t,n),f=ge(w,t,n);return{messageKey:e.stableMessageKey,kind:h(s.type)||h(s.kind)||h(o.messageType)||i,fileName:h(s.name)||h(s.fileName)||h(o.fileName)||null,mimeType:h(s.mimeType)||h(o.mimeType)||null,size:_(s.size)??_(o.size),mediaStatus:At(o,s),observedAt:e.observedAt??null,contextText:r??e.normalizedText??e.anchorText??e.textExcerpt??null,...u?{bbox:u}:{},...d?{screenshotBbox:d}:{},...f?{downloadActionBbox:f}:{}}}function Rt(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 At(e,t){const n=h(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=h(t.availability)||h(e.availability);return r==="pending-download"?"not_downloaded":r==="metadata-only"?"metadata_only":n||null}function be(e,t,n){const r=`${e} ${h(t.messageType)} ${h(n.type)} ${h(n.kind)}`.toLowerCase();return/image|photo|video|file|document/.test(r)}function A(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 ge(e,t,n){if(!e)return null;if(e.coordinateSpace==="screen")return e;const r=K(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,s=i.height/t.height,a=r.x,c=r.y;return{x:a-e.width*o/2,y:c-e.height*s/2,width:e.width*o,height:e.height*s,coordinateSpace:"screen"}}function Ft(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 h(e){return typeof e=="string"?e.trim():""}function g(e){return h(e)||null}function _(e){const t=Number(e);return Number.isFinite(t)?t:null}async function Wn(e,t){await xe(e,t)}async function Lt(e,t){await ye(e,t)}async function ye(e,t){const n=await e.request("permissions.check",{},t);m(n,"permissions.check");const r=n.result??{};if(Kt(r.platform)){const i=await Dt(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 xe(e,t,n={}){const r=await ye(e,t),i=String(r.platform??"").toLowerCase();if(r.wechatRunning===!1)throw new Error("wechat_not_running");if(Vt(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 Dt(e,t,n){const r=Ot(t);if(!r||process.platform!=="darwin")return r;const i=$t(r);try{await e.request(i,{},n)}catch{}return r}function Ot(e){return e.screenRecording===!1?"screen-recording":e.accessibility===!1?"accessibility":e.inputMonitoring===!1?"input-monitoring":null}function Kt(e){const t=String(e||"").toLowerCase();return t?t.includes("darwin")||t.includes("mac"):!0}function $t(e){return e==="screen-recording"?"permissions.requestScreenRecording":e==="accessibility"?"permissions.requestAccessibility":"permissions.requestInputMonitoring"}async function zt(e,t,n={}){const i=(n.foreground??"required")!=="background",o=await xe(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 l}const s=await e.request("windows.ensureReady",{restore:i,focus:i},t);m(s,"windows.ensureReady");const a=s.result;if(!a?.windowId)throw new Error("helper_invalid_response: windows.ensureReady missing WeChat window data");return a}function Vt(e){return e.windowsVisibleDesktopAvailable===!1||e.rdpVisibleDesktopAvailable===!1||e.desktopSessionVisible===!1||e.screenLocked===!0||e.rdpDisconnected===!0}function ve(e){const t=e.filter(H),n=t.filter(i=>i.visible!==!1&&i.minimized!==!0);return(n.length?n:t)[0]??null}async function Rn(e,t){let n=await e.request("windows.list",{},t);m(n,"windows.list");let r=n.result?.windows??[],i=ve(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 Ce(e,i,t)}async function pe(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 qt(e,t){const n=await e.request("windows.list",{},t);m(n,"windows.list");const r=n.result?.windows??[],i=ve(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 Ce(e,i,t)}async function Ce(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(H);return i.find(o=>o.windowId===t.windowId)??i[0]??t}async function V(e){const{capture:t,ocr:n}=e.observation??await k(e),r=E({capture:t,ocr:n,window:e.window});if(r)return{opened:!1,reason:r};const i=je({visibleItems:en(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=gn(i.item.bbox,t,e.window);if(!o)return{opened:!1,reason:"conversation_bbox_missing"};const s=await e.helper.request("mouse.click",{x:o.x,y:o.y,coordinateSpace:"screen",windowId:e.window.windowId},e.traceId);return m(s,"mouse.click"),{opened:!0,reason:i.reason}}async function q(e){let t={opened:!1,reason:"conversation_not_opened"};for(let r=0;r<Ue;r+=1){if(t=await jt(e),t.opened||t.reason!=="conversation_title_not_confirmed")return t;await S(e,"open-retry",`retry:${r}`)}const n=await Ie(e);return n.opened?{opened:!0,reason:`${n.reason}:final-visible-recovery`}:t}async function jt(e){const t=await k(e),n=E({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 T({helper:e.helper,window:e.window,traceId:e.traceId,observation:t}),{opened:!0,reason:"current-conversation-title-confirmed"};if(!r){const u=await V({...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 f=await Ie(e);if(f.opened)return f}}const i=await Jt(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??L(e,"search-input-settle","search-input"),searchPoint:i.point},e.traceId);m(o,"wechat.searchConversation");const s=await Ht(e);if(s.opened){await S(e,"open-click-settle","search-result-click");const u=await M(e);return u.ok?(e.settleToBottom===!0&&await T({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:s.reason}):{opened:!1,reason:u.reason}}let a=s.observation;const c=y(e.binding.conversationDisplayName)&&s.reason==="search_result_not_visible";if(!y(e.binding.conversationDisplayName)){await Qt(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 T({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??L(e,"search-input-settle","search-input-retry-after-return"),searchPoint:i.point},e.traceId);m(d,"wechat.searchConversation"),a=void 0}const l=await V({...e,...a?{observation:a}:{},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 T({helper:e.helper,window:e.window,traceId:e.traceId}),{opened:!0,reason:l.reason}):{opened:!1,reason:w.reason}}async function Ie(e){const t=await V(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 T({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 Ht(e){let t;const n=e.searchDelayMs===0?0:L(e,"search-result-probe","search-result-probe"),r=y(e.binding.conversationDisplayName)?Ye:1;for(let i=0;i<r;i+=1){i>0&&n>0&&await G(n);const o=await Gt(e);t=o;const{capture:s,ocr:a}=o,c=E({capture:s,ocr:a,window:e.window});if(c)return{opened:!1,reason:c,observation:o};const l=rn(a,s,e.binding.conversationDisplayName);if(!l){if(on(a)||an(a,e.binding.conversationDisplayName))break;continue}const w=K(l.bbox,s,Ut(s,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 Gt(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 ke(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 Ut(e,t){return e.bounds?{...t,bounds:e.bounds}:t}async function k(e){let{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds);return await Yt({helper:e.helper,window:e.window,capture:t,ocr:n,traceId:e.traceId})&&(await Q("preview-dismiss-settle",`${e.traceId||""}:${e.window.windowId}:preview-dismiss`),{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds)),{capture:t,ocr:n}}async function Yt(e){const t=Xt(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 Xt(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,s=Number(o?.y);if(!Number.isFinite(s))return null;const a=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-s)<t.height*.08}).sort((c,l)=>Number(l.bbox?.x??0)-Number(c.bbox?.x??0))[0];return K(a?.bbox,t,n)}async function Jt(e,t){if(!e.runtime||!e.api?.classifyWindow)return{ok:!1,reason:"wechat_search_input_detector_unavailable"};try{return{ok:!0,point:await nt({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 F(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 _e(e){return e.capture.dataBase64?e.capture:F(e.helper,e.window.windowId,e.traceId,e.window.bounds)}async function j(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 F(e,t,n,r),s=await ke(e,o,n);return{capture:o,ocr:s}}async function ke(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 H(e){const t=String(e.appName||"").toLowerCase();return t==="wechat"||t==="weixin"||t==="\u5FAE\u4FE1"}function G(e){return new Promise(t=>setTimeout(t,e))}function L(e,t,n){return e.searchDelayMs===0?0:qe(t,Zt(e,n))}async function S(e,t,n){const r=L(e,t,n);r>0&&await G(r)}function Zt(e,t){return`${e.traceId||""}:${e.binding.conversationDisplayName}:${t}`}async function Qt(e,t){const n=await e.request("keyboard.shortcut",{key:"return",modifiers:[]},t);m(n,"keyboard.shortcut")}async function T(e){if(!e.window.bounds)return;const t=e.observation,n=yn(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 Q("jump-latest-settle",`${e.traceId||""}:${e.window.windowId}:jump-latest`)}}async function M(e){const{capture:t,ocr:n}=await j(e.helper,e.window.windowId,e.traceId,e.window.bounds),r=E({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"}:{ok:!1,reason:"conversation_title_not_confirmed"}}function E(e){const n=(e.ocr.blocks??[]).map(r=>cn(r.text)).filter(Boolean).join("");return/(扫码登录|仅传输文件|重新登录|为了安全|安全验证|登录微信|微信登录|该账号已登录|帐号已登录|账号已登录|当前账号已登录|当前帐号已登录|已登录|进入微信|進入微信)/u.test(n)?Xe:null}function en(e,t,n=!0){const r=n?tn(e.blocks??[],t):[];return r.length?r:e.visibleConversationFingerprints??[]}function tn(e,t){const n=e.map(i=>Se(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=>!Me(i.text)),r=new Set;return n.filter(i=>!nn(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=B(i.title);return!o||r.has(o)?!1:(r.add(o),!0)})}function Se(e){const t=e.bbox,n=String(e.text||"").normalize("NFKC").trim(),r=Number(t?.x),i=Number(t?.y),o=Number(t?.width),s=Number(t?.height);return!n||![r,i,o,s].every(Number.isFinite)?null:{text:n,x:r,y:i,width:o,height:s}}function nn(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 Me(e){const t=p(e);return/^(搜索|微信|通讯录|收藏|设置|search)$/iu.test(t)||D(t)||sn(t)||/^包含[::]?/u.test(t)||/搜索网络结果/u.test(t)}function rn(e,t,n){const r=(e.blocks??[]).map(a=>Se(a)).filter(a=>!!a),i=r.filter(a=>D(p(a.text))).sort((a,c)=>a.y-c.y||a.x-c.x),o=["\u7FA4\u804A","GroupChats","\u8054\u7CFB\u4EBA","Contacts"];for(const a of o){const c=i.findIndex(d=>p(d.text)===a);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=>!D(p(d.text))).filter(d=>!Te(d,r)).filter(d=>Y(d.text,n)).sort((d,f)=>d.y-f.y||d.x-f.x)[0];if(u)return{bbox:Ne(u,t),reason:"search-result-title"}}const s=r.filter(a=>a.y>t.height*.12&&a.y<t.height*.82).filter(a=>a.x>t.width*.08&&a.x<t.width*.45).filter(a=>a.text.length>=2).filter(a=>!Me(a.text)).filter(a=>!Te(a,r)).filter(a=>Y(a.text,n)).sort((a,c)=>a.y-c.y||a.x-c.x)[0];return y(n)?null:s?{bbox:Ne(s,t),reason:"search-result-title"}:null}function Ne(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 D(e){return/^(群聊|联系人|聊天记录|公众号|小程序|GroupChats|Contacts|ChatHistory|OfficialAccounts|MiniPrograms)$/u.test(e)}function on(e){return(e.blocks??[]).some(t=>D(p(t.text)))}function an(e,t){return(e.visibleConversationFingerprints??[]).some(n=>Y(n.title,t))}function p(e){return String(e||"").normalize("NFKC").replace(/[^\p{L}\p{N}_-]/gu,"").trim()}function Te(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 sn(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 cn(e){return String(e||"").normalize("NFKC").replace(/\s+/g,"").trim()}function O(e,t,n){const r=y(n)?B(n):$(n);return r?(e.blocks??[]).some(i=>{const o=y(n)?B(i.text):$(i.text);if(!o||!Pe(o,r))return!1;const s=i.bbox;if(!s)return!1;const a=Number(s.x),c=Number(s.y);if(!Number.isFinite(a)||!Number.isFinite(c))return!1;const l=a>t.width*.32&&a<t.width*.78&&c<t.height*.16,w=a<t.width*.18&&c<t.height*.12;return l||w}):!1}function U(e){if(O(e.ocr,e.capture,e.binding.conversationDisplayName))return!1;const t=(e.ocr.blocks??[]).map(a=>String(a.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((a,c)=>{const l=Array.isArray(c.source)?c.source.some(w=>c.pattern.test(w)):c.pattern.test(c.source);return a+(l?1:0)},0);if(i>=2)return!0;const o=(e.ocr.blocks??[]).filter(a=>Number(a.bbox?.y)<e.capture.height*.14).map(a=>String(a.text||"")).join(`
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)&&cn(e.capture,e.ocr)?!0:((e.ocr.visibleConversationFingerprints??[]).some(a=>{const c=y(e.binding.conversationDisplayName)?B(a.title):$(a.title),l=y(e.binding.conversationDisplayName)?B(e.binding.conversationDisplayName):$(e.binding.conversationDisplayName);return!!(c&&l&&Pe(c,l))}),!1)}function cn(e,t){const n=(t.blocks??[]).map(o=>String(o.text||"").normalize("NFKC").trim()).filter(Boolean),r=n.join(`
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 Ee(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=dn(e.ocr,e.screenshot).sort((o,s)=>v(s.text).length-v(o.text).length);for(const o of i){const s=v(o.text);if(!s)continue;const a=t.find(l=>ln(l.normalized,s));if(!a)continue;const c=`local-outbound-echo:${e.binding.bindingId}:${a.idempotencyKey||a.replyId||a.normalized}`;r.has(c)||(r.add(c),n.push({stableMessageKey:c,senderRole:"self",kind:"text",normalizedText:s,anchorText:s,textExcerpt:o.text.trim(),bbox:o.bbox??null,observedAt:new Date().toISOString(),deliveryStatus:"suppressed"}))}return n}function dn(e,t){const n=(e.blocks??[]).filter(i=>mn(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 s=i+1;s<n.length&&o.length<5;s+=1){const a=n[s];if(!un(o[o.length-1],a,t))break;o.push(a),r.push({text:wn(o.map(c=>String(c.text||"").trim())),bbox:fn(o.map(c=>c.bbox))})}}return r}function ln(e,t){if(!e||!t)return!1;if(ee(e,t)>=.88)return!0;const n=e.replace(/\s+/g,""),r=t.replace(/\s+/g,"");return r.length>=8&&n.includes(r)}function un(e,t,n){const r=C(e.bbox,"x"),i=C(e.bbox,"y"),o=C(e.bbox,"height"),s=C(t.bbox,"x"),a=C(t.bbox,"y");if(![r,i,o,s,a].every(Number.isFinite)||r<n.width*.5||s<n.width*.5)return!1;const c=a-(i+o);return c>=-8&&c<=Math.max(64,n.height*.04)&&Math.abs(s-r)<=120}function wn(e){return e.reduce((t,n)=>t?n?`${t}${hn(t,n)?" ":""}${n}`:t:n,"")}function hn(e,t){return/[A-Za-z0-9]$/u.test(e)&&/^[A-Za-z0-9]/u.test(t)}function fn(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 s=Math.min(...n),a=Math.min(...r);return{x:s,y:a,width:Math.max(...i)-s,height:Math.max(...o)-a,coordinateSpace:t.find(c=>c.coordinateSpace)?.coordinateSpace}}function C(e,t){const n=Number(e?.[t]);return Number.isFinite(n)?n:Number.NaN}function Be(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(s=>{if(s.senderRole!=="self")return!1;const a=v(s.anchorText||s.normalizedText||s.textExcerpt);return a&&i&&ee(a,i)>=.9})||n.push(r)}return n}function mn(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 bn(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),s=Number(r.width),a=Number(r.height);if(![i,o,s,a].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(s*.35,110*l),y:o+Math.min(a-8*w,Math.max(18*w,a/2))};if(c==="screen"||!n.bounds)return u;const d=Math.max(0,(t.width-n.bounds.width*l)/2),f=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-f)/w}}function K(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),s=Number(r.width),a=Number(r.height);if(![i,o,s,a].every(Number.isFinite))return null;const c=typeof r.coordinateSpace=="string"?r.coordinateSpace:void 0,l={x:i+s/2,y:o+a/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),f=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-f)/u}}function gn(e,t,n){if(!e?.blocks?.length||!t)return null;const r=e.blocks.find(i=>{const o=String(i.text||"").trim(),s=i.bbox;if(!s||!o)return!1;const a=Number(s.x),c=Number(s.y);return!Number.isFinite(a)||!Number.isFinite(c)||!/跳转到最新消息|回到最新消息|jump\s+to\s+latest/i.test(o)?!1:a>t.width*.55&&c>t.height*.45&&c<t.height*.92});return K(r?.bbox,t,n)}function Pe(e,t){return y(t)?Re(e,t):e===t||e.includes(t)||t.includes(e)}function Y(e,t){if(y(t))return Re(e,t);const n=We(p(e)),r=We(p(t));return!n||!r?!1:n===r?!0:n.replace(/\d+$/u,"")===r}function We(e){return e.toLowerCase().replace(/[l1]/g,"i")}function $(e){return String(e||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").replace(/[l1]/gi,"i").toLowerCase().trim()}function B(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 Re(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,j as captureAndRecognizeWeChatWindow,F as captureWeChatWindow,En as detectWeChatMessageInputPointByServerVision,nt as detectWeChatSearchInputPointByServerVision,Dt as ensureHelperPermissionPreflight,Pn as ensureHelperPreflight,$t as ensureWeChatWindowReady,zt as focusExistingWeChatWindow,pe as focusKnownWeChatWindow,Wn as focusWeChatWindow,Tn as observeWeChatChannelBindingViaHelper,q as openConversationBySearch,z as openConversationInVisibleList,ke as recognizeWeChatScreenshot,Qe as selectWeChatWindowForBinding};
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)&&dn(e.capture,e.ocr)?!0:((e.ocr.visibleConversationFingerprints??[]).some(a=>{const c=y(e.binding.conversationDisplayName)?B(a.title):$(a.title),l=y(e.binding.conversationDisplayName)?B(e.binding.conversationDisplayName):$(e.binding.conversationDisplayName);return!!(c&&l&&Pe(c,l))}),!1)}function dn(e,t){const n=(t.blocks??[]).map(o=>String(o.text||"").normalize("NFKC").trim()).filter(Boolean),r=n.join(`
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 Ee(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=ln(e.ocr,e.screenshot).sort((o,s)=>v(s.text).length-v(o.text).length);for(const o of i){const s=v(o.text);if(!s)continue;const a=t.find(l=>un(l.normalized,s));if(!a)continue;const c=`local-outbound-echo:${e.binding.bindingId}:${a.idempotencyKey||a.replyId||a.normalized}`;r.has(c)||(r.add(c),n.push({stableMessageKey:c,senderRole:"self",kind:"text",normalizedText:s,anchorText:s,textExcerpt:o.text.trim(),bbox:o.bbox??null,observedAt:new Date().toISOString(),deliveryStatus:"suppressed"}))}return n}function ln(e,t){const n=(e.blocks??[]).filter(i=>bn(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 s=i+1;s<n.length&&o.length<5;s+=1){const a=n[s];if(!wn(o[o.length-1],a,t))break;o.push(a),r.push({text:hn(o.map(c=>String(c.text||"").trim())),bbox:mn(o.map(c=>c.bbox))})}}return r}function un(e,t){if(!e||!t)return!1;if(ee(e,t)>=.88)return!0;const n=e.replace(/\s+/g,""),r=t.replace(/\s+/g,"");return r.length>=8&&n.includes(r)}function wn(e,t,n){const r=C(e.bbox,"x"),i=C(e.bbox,"y"),o=C(e.bbox,"height"),s=C(t.bbox,"x"),a=C(t.bbox,"y");if(![r,i,o,s,a].every(Number.isFinite)||r<n.width*.5||s<n.width*.5)return!1;const c=a-(i+o);return c>=-8&&c<=Math.max(64,n.height*.04)&&Math.abs(s-r)<=120}function hn(e){return e.reduce((t,n)=>t?n?`${t}${fn(t,n)?" ":""}${n}`:t:n,"")}function fn(e,t){return/[A-Za-z0-9]$/u.test(e)&&/^[A-Za-z0-9]/u.test(t)}function mn(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 s=Math.min(...n),a=Math.min(...r);return{x:s,y:a,width:Math.max(...i)-s,height:Math.max(...o)-a,coordinateSpace:t.find(c=>c.coordinateSpace)?.coordinateSpace}}function C(e,t){const n=Number(e?.[t]);return Number.isFinite(n)?n:Number.NaN}function Be(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(s=>{if(s.senderRole!=="self")return!1;const a=v(s.anchorText||s.normalizedText||s.textExcerpt);return a&&i&&ee(a,i)>=.9})||n.push(r)}return n}function bn(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 gn(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),s=Number(r.width),a=Number(r.height);if(![i,o,s,a].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(s*.35,110*l),y:o+Math.min(a-8*w,Math.max(18*w,a/2))};if(c==="screen"||!n.bounds)return u;const d=Math.max(0,(t.width-n.bounds.width*l)/2),f=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-f)/w}}function K(e,t,n){if(!e||typeof e!="object")return null;const r=e,i=Number(r.x),o=Number(r.y),s=Number(r.width),a=Number(r.height);if(![i,o,s,a].every(Number.isFinite))return null;const c=typeof r.coordinateSpace=="string"?r.coordinateSpace:void 0,l={x:i+s/2,y:o+a/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),f=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-f)/u}}function yn(e,t,n){if(!e?.blocks?.length||!t)return null;const r=e.blocks.find(i=>{const o=String(i.text||"").trim(),s=i.bbox;if(!s||!o)return!1;const a=Number(s.x),c=Number(s.y);return!Number.isFinite(a)||!Number.isFinite(c)||!/跳转到最新消息|回到最新消息|jump\s+to\s+latest/i.test(o)?!1:a>t.width*.55&&c>t.height*.45&&c<t.height*.92});return K(r?.bbox,t,n)}function Pe(e,t){return y(t)?Re(e,t):e===t||e.includes(t)||t.includes(e)}function Y(e,t){if(y(t))return Re(e,t);const n=We(p(e)),r=We(p(t));return!n||!r?!1:n===r?!0:n.replace(/\d+$/u,"")===r}function We(e){return e.toLowerCase().replace(/[l1]/g,"i")}function $(e){return String(e||"").normalize("NFKC").replace(/[((]\d+[))]/g,"").replace(/\s+/g,"").replace(/[l1]/gi,"i").toLowerCase().trim()}function B(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 Re(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,j as captureAndRecognizeWeChatWindow,F as captureWeChatWindow,Bn as detectWeChatMessageInputPointByServerVision,nt as detectWeChatSearchInputPointByServerVision,Lt as ensureHelperPermissionPreflight,Wn as ensureHelperPreflight,zt as ensureWeChatWindowReady,qt as focusExistingWeChatWindow,pe as focusKnownWeChatWindow,Rn as focusWeChatWindow,En as observeWeChatChannelBindingViaHelper,q as openConversationBySearch,V as openConversationInVisibleList,ke as recognizeWeChatScreenshot,Qe as selectWeChatWindowForBinding};
@@ -1 +1 @@
1
- import{requiredWeChatChannelHelperCapabilitiesForProfile as o,requiredWindowsWeChatChannelHelperCapabilitiesForProfile as t,validateWeChatChannelHelperReady as d}from"./helper-protocol.js";function p(e){const a=[],n=e.platform==="darwin"||e.platform==="win32";if(a.push(i(n,"platform_unsupported","\u5FAE\u4FE1 Channel \u5F53\u524D\u652F\u6301 macOS \u548C Windows \u684C\u9762\u5FAE\u4FE1\u3002")),a.push(i(e.accountTier==="enterprise","enterprise_required","\u5F53\u524D\u9636\u6BB5\u5FAE\u4FE1 Channel \u4EC5\u4F01\u4E1A\u7248\u8D26\u53F7\u53EF\u7528\u3002")),a.push(i(!!e.privacyConsentAccepted,"privacy_consent_required","\u542F\u7528\u524D\u9700\u8981\u786E\u8BA4\u5FAE\u4FE1 Channel \u6570\u636E\u4E0E\u9690\u79C1\u6388\u6743\u3002")),a.push(i(!!e.serverDecisionAvailable,"server_decision_unavailable","\u670D\u52A1\u7AEF\u5224\u65AD\u80FD\u529B\u4E0D\u53EF\u7528\uFF0C\u6682\u4E0D\u80FD\u542F\u7528\u3002")),e.currentMachineId&&e.runtime.machineId&&a.push(i(e.currentMachineId===e.runtime.machineId,"same_machine_required","\u7B2C\u4E00\u7248\u53EA\u652F\u6301\u540C\u673A\u5FAE\u4FE1\u4E0E\u540C\u673A\u795E\u5FF5\u8FD0\u884C\u65F6\u7ED1\u5B9A\u3002")),e.localAgentMachineId&&e.runtime.machineId&&a.push(i(e.localAgentMachineId===e.runtime.machineId,"same_machine_required","\u7ED1\u5B9A\u7684 Agent \u5FC5\u987B\u4E0E\u5FAE\u4FE1\u8FD0\u884C\u65F6\u5728\u540C\u4E00\u53F0\u673A\u5668\u3002")),a.push(i(e.localAgentAvailable!==!1,"local_agent_unavailable","\u672C\u673A Agent \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u63A5\u7BA1\u5FAE\u4FE1\u56DE\u590D\u3002")),!e.helperReady)a.push(i(!1,"helper_not_ready","\u5E73\u53F0 helper \u672A\u5C31\u7EEA\u3002"));else{const l=d(e.helperReady,e.expectedHelperVersion,e.requiredHelperCapabilities??c(e.platform,e.binding));l.ok?a.push(i(!0,"ok",e.platform==="win32"?"Windows helper \u7248\u672C\u4E0E\u80FD\u529B\u68C0\u67E5\u901A\u8FC7\u3002":"macOS helper \u7248\u672C\u4E0E\u80FD\u529B\u68C0\u67E5\u901A\u8FC7\u3002")):a.push(i(!1,l.errorCode,l.errorSummary))}const r=e.permissions;r&&(a.push(i(r.screenRecording!==!1,"permission_screen_recording_missing","\u7F3A\u5C11\u5C4F\u5E55\u5F55\u5236\u6743\u9650\u3002")),a.push(i(r.automation!==!1,"permission_automation_missing","\u7F3A\u5C11\u81EA\u52A8\u5316\u63A7\u5236\u6743\u9650\u3002")),a.push(i(r.wechatRunning!==!1,"wechat_not_running","\u5FAE\u4FE1\u672A\u8FD0\u884C\u3002")),a.push(i(r.wechatWindowAvailable!==!1,"wechat_window_unavailable","\u5FAE\u4FE1\u7A97\u53E3\u4E0D\u53EF\u7528\u3002")),a.push(i(r.wechatMainWindowResponsive!==!1,"wechat_window_unresponsive","\u5FAE\u4FE1\u7A97\u53E3\u65E0\u54CD\u5E94\uFF0C\u9700\u6062\u590D\u540E\u518D\u7EE7\u7EED\u3002")),a.push(i(r.windowsVisibleDesktopAvailable!==!1&&r.rdpVisibleDesktopAvailable!==!1&&r.desktopSessionVisible!==!1&&r.screenLocked!==!0&&r.rdpDisconnected!==!0,"windows_visible_desktop_unavailable","Windows \u53EF\u89C1\u684C\u9762\u4E0D\u53EF\u7528\uFF0C\u8BF7\u89E3\u9501\u6216\u4FDD\u6301 RDP \u53EF\u89C1\u684C\u9762\u4F1A\u8BDD\u540E\u518D\u542F\u7528\u3002")),a.push(i(r.dpiMappingAvailable!==!1&&r.displayTopologySupported!==!1,"dpi_mapping_failed","Windows DPI / \u591A\u5C4F\u5750\u6807\u6620\u5C04\u4E0D\u53EF\u7528\uFF0C\u8BF7\u628A\u5FAE\u4FE1\u5B8C\u6574\u653E\u5728\u4E00\u4E2A\u53EF\u89C1\u663E\u793A\u5668\u4E0A\u540E\u518D\u542F\u7528\u3002")));const s=a.filter(l=>!l.ok&&l.severity==="blocking");return{ok:s.length===0,canEnable:s.length===0,status:s.length===0?"ready":"blocked",checks:a}}function i(e,a,n){return{ok:e,code:e?"ok":a,severity:"blocking",message:n}}function c(e,a){const n=e==="win32"?t:o;return!a||a.allowReply!==!1?n("send"):a.downloadMedia!==!1?n("download"):n("observe")}export{p as evaluateWeChatChannelPreflight};
1
+ import{requiredWeChatChannelHelperCapabilitiesForProfile as o,requiredWindowsWeChatChannelHelperCapabilitiesForProfile as d,validateWeChatChannelHelperReady as t}from"./helper-protocol.js";function p(e){const a=[],l=e.platform==="darwin"||e.platform==="win32";if(a.push(i(l,"platform_unsupported","\u5FAE\u4FE1 Channel \u5F53\u524D\u652F\u6301 macOS \u548C Windows \u684C\u9762\u5FAE\u4FE1\u3002")),a.push(i(e.accountTier==="enterprise","enterprise_required","\u5F53\u524D\u9636\u6BB5\u5FAE\u4FE1 Channel \u4EC5\u4F01\u4E1A\u7248\u8D26\u53F7\u53EF\u7528\u3002")),a.push(i(!!e.privacyConsentAccepted,"privacy_consent_required","\u542F\u7528\u524D\u9700\u8981\u786E\u8BA4\u5FAE\u4FE1 Channel \u6570\u636E\u4E0E\u9690\u79C1\u6388\u6743\u3002")),a.push(i(!!e.serverDecisionAvailable,"server_decision_unavailable","\u670D\u52A1\u7AEF\u5224\u65AD\u80FD\u529B\u4E0D\u53EF\u7528\uFF0C\u6682\u4E0D\u80FD\u542F\u7528\u3002")),e.currentMachineId&&e.runtime.machineId&&a.push(i(e.currentMachineId===e.runtime.machineId,"same_machine_required","\u7B2C\u4E00\u7248\u53EA\u652F\u6301\u540C\u673A\u5FAE\u4FE1\u4E0E\u540C\u673A\u795E\u5FF5\u8FD0\u884C\u65F6\u7ED1\u5B9A\u3002")),e.localAgentMachineId&&e.runtime.machineId&&a.push(i(e.localAgentMachineId===e.runtime.machineId,"same_machine_required","\u7ED1\u5B9A\u7684 Agent \u5FC5\u987B\u4E0E\u5FAE\u4FE1\u8FD0\u884C\u65F6\u5728\u540C\u4E00\u53F0\u673A\u5668\u3002")),a.push(i(e.localAgentAvailable!==!1,"local_agent_unavailable","\u672C\u673A Agent \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u63A5\u7BA1\u5FAE\u4FE1\u56DE\u590D\u3002")),!e.helperReady)a.push(i(!1,"helper_not_ready","\u5E73\u53F0 helper \u672A\u5C31\u7EEA\u3002"));else{const n=t(e.helperReady,e.expectedHelperVersion,e.requiredHelperCapabilities??c(e.platform,e.binding));n.ok?a.push(i(!0,"ok",e.platform==="win32"?"Windows helper \u7248\u672C\u4E0E\u80FD\u529B\u68C0\u67E5\u901A\u8FC7\u3002":"macOS helper \u7248\u672C\u4E0E\u80FD\u529B\u68C0\u67E5\u901A\u8FC7\u3002")):a.push(i(!1,n.errorCode,n.errorSummary))}const r=e.permissions;r&&(e.platform==="darwin"&&(a.push(i(r.screenRecording!==!1,"permission_screen_recording_missing","\u7F3A\u5C11\u5C4F\u5E55\u5F55\u5236\u6743\u9650\u3002")),a.push(i(r.automation!==!1,"permission_automation_missing","\u7F3A\u5C11\u81EA\u52A8\u5316\u63A7\u5236\u6743\u9650\u3002"))),a.push(i(r.wechatRunning!==!1,"wechat_not_running","\u5FAE\u4FE1\u672A\u8FD0\u884C\u3002")),a.push(i(r.wechatWindowAvailable!==!1,"wechat_window_unavailable","\u5FAE\u4FE1\u7A97\u53E3\u4E0D\u53EF\u7528\u3002")),a.push(i(r.wechatMainWindowResponsive!==!1,"wechat_window_unresponsive","\u5FAE\u4FE1\u7A97\u53E3\u65E0\u54CD\u5E94\uFF0C\u9700\u6062\u590D\u540E\u518D\u7EE7\u7EED\u3002")),a.push(i(r.windowsVisibleDesktopAvailable!==!1&&r.rdpVisibleDesktopAvailable!==!1&&r.desktopSessionVisible!==!1&&r.screenLocked!==!0&&r.rdpDisconnected!==!0,"windows_visible_desktop_unavailable","Windows \u53EF\u89C1\u684C\u9762\u4E0D\u53EF\u7528\uFF0C\u8BF7\u89E3\u9501\u6216\u4FDD\u6301 RDP \u53EF\u89C1\u684C\u9762\u4F1A\u8BDD\u540E\u518D\u542F\u7528\u3002")),a.push(i(r.dpiMappingAvailable!==!1&&r.displayTopologySupported!==!1,"dpi_mapping_failed","Windows DPI / \u591A\u5C4F\u5750\u6807\u6620\u5C04\u4E0D\u53EF\u7528\uFF0C\u8BF7\u628A\u5FAE\u4FE1\u5B8C\u6574\u653E\u5728\u4E00\u4E2A\u53EF\u89C1\u663E\u793A\u5668\u4E0A\u540E\u518D\u542F\u7528\u3002")));const s=a.filter(n=>!n.ok&&n.severity==="blocking");return{ok:s.length===0,canEnable:s.length===0,status:s.length===0?"ready":"blocked",checks:a}}function i(e,a,l){return{ok:e,code:e?"ok":a,severity:"blocking",message:l}}function c(e,a){const l=e==="win32"?d:o;return!a||a.allowReply!==!1?l("send"):a.downloadMedia!==!1?l("download"):l("observe")}export{p as evaluateWeChatChannelPreflight};
@@ -1,9 +1,9 @@
1
- import w from"node:crypto";import m from"node:fs";import f from"node:path";import{loadConfig as W}from"../../config/index.js";import{createWeChatChannelProductRunner as O}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as k}from"../wechat-channel/client.js";import{createWeChatAutomationLane as $}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as h,saveWeChatChannelOutboundLedger as I}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as S}from"../wechat-channel/ledger.js";const z="wechat-channel";function le(e){const t=D({runtimeId:e.config.id,machineId:Z(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:j(e.secret.forceForeground),bindings:q(e.config,e.secret)}),n=x(e.config.workDir,t.runtimeId),a=u(e.config.workDir,t.runtimeId),r=_(e.config.workDir,t.runtimeId),o=[];m.mkdirSync(f.dirname(r),{recursive:!0}),m.writeFileSync(r,"");const s=e.createRunner??O,c=L(),d=s({runtime:t,workDir:e.config.workDir,api:c,ledgerPath:n,outboundLedgerPath:a,lane:$(),helperRequestLogger:F(r),onInboundMessages:(C,R)=>{const M=t.bindings.find(p=>p.bindingId===C.bindingId)??C;for(const p of R){const y=A(e.config,M,p);if(!y)continue;const N=e.onMessage?.({...y,managerSessionId:e.config.managerSessionId})??y;o.push(N)}}});return{runtime:t,runner:d,emitted:o,ledgerPath:n,outboundLedgerPath:a,helperTracePath:r}}function L(){let e=null;const t=()=>(e??=k(),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 j(e){return e===!1?"polite":"work"}function de(e){const t=e.config.id,n=P(e.config.id,e.conversationName),a=S(x(e.config.workDir,t),t),r=u(e.config.workDir,t),o=h(r,t),s=e.reply.attachment?[G(e.reply.attachment)]:[],c=K({ledger:o,replyId:e.reply.messageId||e.reply.idempotencyKey||l("wechat-channel-reply",`${Date.now()}:${e.reply.text}`),idempotencyKey:e.reply.idempotencyKey||l("wechat-channel-send",`${e.config.id}
1
+ import w from"node:crypto";import m from"node:fs";import f from"node:path";import{loadConfig as N}from"../../config/index.js";import{createWeChatChannelProductRunner as O}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as k}from"../wechat-channel/client.js";import{createWeChatAutomationLane as $}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as h,saveWeChatChannelOutboundLedger as I}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as S}from"../wechat-channel/ledger.js";const z="wechat-channel";function de(e){const t=D({runtimeId:e.config.id,machineId:Q(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:j(e.secret.forceForeground),bindings:B(e.config,e.secret)}),n=P(e.config.workDir,t.runtimeId),a=u(e.config.workDir,t.runtimeId),r=F(e.config.workDir,t.runtimeId),o=[];m.mkdirSync(f.dirname(r),{recursive:!0}),m.writeFileSync(r,"");const s=e.createRunner??O,c=L(),d=s({runtime:t,workDir:e.config.workDir,api:c,ledgerPath:n,outboundLedgerPath:a,lane:$(),helperRequestLogger:H(r),onInboundMessages:(C,A)=>{const M=t.bindings.find(p=>p.bindingId===C.bindingId)??C;for(const p of A){const y=x(e.config,M,p);if(!y)continue;const W=e.onMessage?.({...y,managerSessionId:e.config.managerSessionId})??y;o.push(W)}}});return{runtime:t,runner:d,emitted:o,ledgerPath:n,outboundLedgerPath:a,helperTracePath:r}}function L(){let e=null;const t=()=>(e??=k(),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 j(e){return e===!1?"polite":"work"}function ue(e){const t=e.config.id,n=R(e.config,e.conversationName),a=S(P(e.config.workDir,t),t),r=u(e.config.workDir,t),o=h(r,t),s=e.reply.attachment?[J(e.reply.attachment)]:[],c=K({ledger:o,replyId:e.reply.messageId||e.reply.idempotencyKey||l("wechat-channel-reply",`${Date.now()}:${e.reply.text}`),idempotencyKey:e.reply.idempotencyKey||l("wechat-channel-send",`${e.config.id}
2
2
  ${e.reply.conversationId}
3
3
  ${e.reply.text}
4
4
  ${s.join(`
5
- `)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:a.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:s});return I(r,o),c}function ue(e){return h(u(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).length}function me(e){return h(u(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 fe(e){const t=X(e.limit,20,1,100),n=S(e.product.ledgerPath,e.product.runtime.runtimeId),a=[];for(const r of e.product.runtime.bindings){const o=n.bindings[r.bindingId]?.recent??[];for(const s of o.slice(-t)){const c=A(e.config,r,s);c&&a.push(c)}}return a}function he(e){const t=u(e.config.workDir,e.config.id),n=h(t,e.config.id),a=String(e.idempotencyKey??"").trim(),r=String(e.replyId??"").trim();if(!a&&!r)return{cancelled:!1};const o=n.records.find(c=>a&&c.idempotencyKey===a||r&&c.replyId===r);if(!o)return{cancelled:!1};const s=o.sendStatus;return T(o,e.reason||"user_cancelled"),o.sendStatus!==s?(I(t,n),{cancelled:!0,status:o.sendStatus,record:o}):{cancelled:!1,status:o.sendStatus,record:o}}function ge(e){return e===z}function E(e){return l("wechat-conversation",i(e))}function P(e,t){return l("wechat-channel-binding",`${e}
6
- ${i(t)}`)}function x(e,t){return f.join(e,"wechat-channel",`${b(t)}.ledger.json`)}function u(e,t){return f.join(e,"wechat-channel",`${b(t)}.outbound-ledger.json`)}function _(e,t){return f.join(e,"wechat-channel",`${b(t)}.helper-trace.jsonl`)}function b(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}function F(e){return t=>{m.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=g(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=g(e.result)),t}function g(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:w.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const o=e.slice(0,10).map(s=>g(s,t,n+1));return e.length>o.length?{type:"array",length:e.length,items:o}:o}if(typeof e!="object")return String(e);if(n>=5)return{type:"object",truncated:!0};const a=e,r={};for(const[o,s]of Object.entries(a))r[o]=g(s,o,n+1);return r}function q(e,t){return J(t).map(n=>({bindingId:P(e.id,n),sessionId:e.sessionId||e.managerSessionId,conversationDisplayName:n,enabled:!0,allowReply:t.canReply!==!1,downloadMedia:t.downloadAttachments!==!1,selfTriggerMarker:i(t.selfTriggerMarker||"")||null}))}function A(e,t,n){const a=i(n.normalizedText||n.anchorText||n.textExcerpt||""),r=B(n);if(!a&&r.length===0)return null;const o=i(n.senderName||"");return{type:"external.message",channelId:e.id,channelType:"wechat-rpa",conversationId:E(t.conversationDisplayName),conversationName:t.conversationDisplayName,messageId:l("wechat-message",`${t.bindingId}
5
+ `)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:a.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:s});return I(r,o),c}function me(e){return h(u(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).length}function fe(e){return h(u(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 he(e){const t=Y(e.limit,20,1,100),n=S(e.product.ledgerPath,e.product.runtime.runtimeId),a=[];for(const r of e.product.runtime.bindings){const o=n.bindings[r.bindingId]?.recent??[];for(const s of o.slice(-t)){const c=x(e.config,r,s);c&&a.push(c)}}return a}function ge(e){const t=u(e.config.workDir,e.config.id),n=h(t,e.config.id),a=String(e.idempotencyKey??"").trim(),r=String(e.replyId??"").trim();if(!a&&!r)return{cancelled:!1};const o=n.records.find(c=>a&&c.idempotencyKey===a||r&&c.replyId===r);if(!o)return{cancelled:!1};const s=o.sendStatus;return T(o,e.reason||"user_cancelled"),o.sendStatus!==s?(I(t,n),{cancelled:!0,status:o.sendStatus,record:o}):{cancelled:!1,status:o.sendStatus,record:o}}function pe(e){return e===z}function E(e){return l("wechat-conversation",i(e))}function _(e,t){return l("wechat-channel-binding",`${e}
6
+ ${i(t)}`)}function P(e,t){return f.join(e,"wechat-channel",`${b(t)}.ledger.json`)}function u(e,t){return f.join(e,"wechat-channel",`${b(t)}.outbound-ledger.json`)}function F(e,t){return f.join(e,"wechat-channel",`${b(t)}.helper-trace.jsonl`)}function b(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}function H(e){return t=>{m.appendFileSync(e,`${JSON.stringify(q(t))}
7
+ `)}}function q(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=g(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=g(e.result)),t}function g(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:w.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const o=e.slice(0,10).map(s=>g(s,t,n+1));return e.length>o.length?{type:"array",length:e.length,items:o}:o}if(typeof e!="object")return String(e);if(n>=5)return{type:"object",truncated:!0};const a=e,r={};for(const[o,s]of Object.entries(a))r[o]=g(s,o,n+1);return r}function B(e,t){return Z(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 x(e,t,n){const a=i(n.normalizedText||n.anchorText||n.textExcerpt||""),r=V(n);if(!a&&r.length===0)return null;const o=i(n.senderName||"");return{type:"external.message",channelId:e.id,channelType:"wechat-rpa",conversationId:E(t.conversationDisplayName),conversationName:t.conversationDisplayName,messageId:l("wechat-message",`${t.bindingId}
8
8
  ${n.stableMessageKey}`),sender:{id:l("wechat-sender",`${t.bindingId}
9
- ${o||n.senderRole}`),name:o||null},text:a,attachments:r,receivedAt:Q(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function B(e){const t=e.mediaMetadata;return V(t).map(a=>{const r=a,o=typeof r.localPath=="string"?i(r.localPath):"",s=typeof r.thumbnailPath=="string"?i(r.thumbnailPath):"",c=typeof r.url=="string"?i(r.url):"",d=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))}:{},...c?{url:c}:{},...typeof r.mimeType=="string"?{mimeType:i(r.mimeType)}:{},...typeof r.extension=="string"?{extension:i(r.extension)}:{},...Number.isFinite(d)&&d>0?{size:d}:{},...o?{localPath:o}:{},...s?{thumbnailPath:s}:{},...typeof r.hash=="string"||typeof r.sha256=="string"?{hash:i(String(r.hash||r.sha256))}:{},availability:v(r.availability,{localPath:o,url:c}),...typeof r.providerError=="string"?{providerError:i(r.providerError)}:{},...typeof r.sourceAction=="string"?{sourceAction:i(r.sourceAction)}:{},...U(r.materializationKind)?{materializationKind:r.materializationKind}:{},...typeof r.isOriginal=="boolean"?{isOriginal:r.isOriginal}:{},...typeof r.mimeKindMatches=="boolean"?{mimeKindMatches:r.mimeKindMatches}:{}}})}function V(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 v(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 U(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function G(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!m.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function J(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function Z(){return process.env.SHENNIAN_MACHINE_ID?.trim()||W().machineId||"local"}function Q(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 X(e,t,n,a){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(a,Math.floor(r))):t}function l(e,t){return`${e}:${w.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{z as WECHAT_RPA_PRODUCT_SOURCE,he as cancelWeChatRpaProductOutboundReply,ue as countPendingWeChatRpaProductOutbound,le as createWeChatRpaProductSourceConnection,de as enqueueWeChatRpaProductOutboundReply,ge as isWeChatRpaProductSource,me as listPendingWeChatRpaProductOutbound,fe as listWeChatRpaProductRecentMessages,A as observedMessageToExternalEvent,b as safeWeChatChannelRuntimePathSegment,P as weChatChannelBindingId,E as weChatChannelConversationId,_ as weChatChannelHelperTracePath,x as weChatChannelLedgerPath,u as weChatChannelOutboundLedgerPath};
9
+ ${o||n.senderRole}`),name:o||null},text:a,attachments:r,receivedAt:X(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function V(e){const t=e.mediaMetadata;return v(t).map(a=>{const r=a,o=typeof r.localPath=="string"?i(r.localPath):"",s=typeof r.thumbnailPath=="string"?i(r.thumbnailPath):"",c=typeof r.url=="string"?i(r.url):"",d=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))}:{},...c?{url:c}:{},...typeof r.mimeType=="string"?{mimeType:i(r.mimeType)}:{},...typeof r.extension=="string"?{extension:i(r.extension)}:{},...Number.isFinite(d)&&d>0?{size:d}:{},...o?{localPath:o}:{},...s?{thumbnailPath:s}:{},...typeof r.hash=="string"||typeof r.sha256=="string"?{hash:i(String(r.hash||r.sha256))}:{},availability:U(r.availability,{localPath:o,url:c}),...typeof r.providerError=="string"?{providerError:i(r.providerError)}:{},...typeof r.sourceAction=="string"?{sourceAction:i(r.sourceAction)}:{},...G(r.materializationKind)?{materializationKind:r.materializationKind}:{},...typeof r.isOriginal=="boolean"?{isOriginal:r.isOriginal}:{},...typeof r.mimeKindMatches=="boolean"?{mimeKindMatches:r.mimeKindMatches}:{}}})}function v(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 U(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 G(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function J(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!m.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function Z(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function Q(){return process.env.SHENNIAN_MACHINE_ID?.trim()||N().machineId||"local"}function X(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 Y(e,t,n,a){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(a,Math.floor(r))):t}function l(e,t){return`${e}:${w.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{z as WECHAT_RPA_PRODUCT_SOURCE,ge as cancelWeChatRpaProductOutboundReply,me as countPendingWeChatRpaProductOutbound,de as createWeChatRpaProductSourceConnection,ue as enqueueWeChatRpaProductOutboundReply,pe as isWeChatRpaProductSource,fe as listPendingWeChatRpaProductOutbound,he as listWeChatRpaProductRecentMessages,x as observedMessageToExternalEvent,b as safeWeChatChannelRuntimePathSegment,_ as weChatChannelBindingId,E as weChatChannelConversationId,F as weChatChannelHelperTracePath,P as weChatChannelLedgerPath,u as weChatChannelOutboundLedgerPath};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shennian",
3
- "version": "0.2.123",
3
+ "version": "0.2.124",
4
4
  "description": "Shennian — AI Agent Control Plane CLI",
5
5
  "type": "module",
6
6
  "bin": {