shennian 0.2.120 → 0.2.122
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/publish-build-manifest.json +12 -12
- package/dist/src/channels/wechat-channel/helper-assets.d.ts +1 -1
- package/dist/src/channels/wechat-channel/helper-assets.js +1 -1
- package/dist/src/channels/wechat-channel/helper-client.js +3 -3
- package/dist/src/channels/wechat-channel/runner.d.ts +1 -0
- package/dist/src/channels/wechat-channel/runner.js +1 -1
- package/dist/src/commands/helper-runtime-official-download.js +1 -1
- package/dist/src/commands/runtime.d.ts +7 -0
- package/dist/src/commands/runtime.js +1 -1
- package/dist/src/config/index.js +1 -1
- package/dist/src/session/handlers/wechat-helper-runtime.js +1 -1
- package/package.json +1 -1
|
@@ -221,8 +221,8 @@
|
|
|
221
221
|
},
|
|
222
222
|
{
|
|
223
223
|
"file": "src/channels/wechat-channel/helper-client.js",
|
|
224
|
-
"beforeBytes":
|
|
225
|
-
"afterBytes":
|
|
224
|
+
"beforeBytes": 41881,
|
|
225
|
+
"afterBytes": 18901
|
|
226
226
|
},
|
|
227
227
|
{
|
|
228
228
|
"file": "src/channels/wechat-channel/helper-protocol.js",
|
|
@@ -286,8 +286,8 @@
|
|
|
286
286
|
},
|
|
287
287
|
{
|
|
288
288
|
"file": "src/channels/wechat-channel/runner.js",
|
|
289
|
-
"beforeBytes":
|
|
290
|
-
"afterBytes":
|
|
289
|
+
"beforeBytes": 16219,
|
|
290
|
+
"afterBytes": 7723
|
|
291
291
|
},
|
|
292
292
|
{
|
|
293
293
|
"file": "src/channels/wechat-channel/runtime.js",
|
|
@@ -371,8 +371,8 @@
|
|
|
371
371
|
},
|
|
372
372
|
{
|
|
373
373
|
"file": "src/commands/helper-runtime-official-download.js",
|
|
374
|
-
"beforeBytes":
|
|
375
|
-
"afterBytes":
|
|
374
|
+
"beforeBytes": 12611,
|
|
375
|
+
"afterBytes": 6719
|
|
376
376
|
},
|
|
377
377
|
{
|
|
378
378
|
"file": "src/commands/manager.js",
|
|
@@ -391,8 +391,8 @@
|
|
|
391
391
|
},
|
|
392
392
|
{
|
|
393
393
|
"file": "src/commands/runtime.js",
|
|
394
|
-
"beforeBytes":
|
|
395
|
-
"afterBytes":
|
|
394
|
+
"beforeBytes": 39879,
|
|
395
|
+
"afterBytes": 21821
|
|
396
396
|
},
|
|
397
397
|
{
|
|
398
398
|
"file": "src/commands/tools.js",
|
|
@@ -451,8 +451,8 @@
|
|
|
451
451
|
},
|
|
452
452
|
{
|
|
453
453
|
"file": "src/config/index.js",
|
|
454
|
-
"beforeBytes":
|
|
455
|
-
"afterBytes":
|
|
454
|
+
"beforeBytes": 1702,
|
|
455
|
+
"afterBytes": 1036
|
|
456
456
|
},
|
|
457
457
|
{
|
|
458
458
|
"file": "src/daemon-log.js",
|
|
@@ -626,8 +626,8 @@
|
|
|
626
626
|
},
|
|
627
627
|
{
|
|
628
628
|
"file": "src/session/handlers/wechat-helper-runtime.js",
|
|
629
|
-
"beforeBytes":
|
|
630
|
-
"afterBytes":
|
|
629
|
+
"beforeBytes": 7107,
|
|
630
|
+
"afterBytes": 3846
|
|
631
631
|
},
|
|
632
632
|
{
|
|
633
633
|
"file": "src/session/manager.js",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const WECHAT_CHANNEL_HELPER_VERSION = "0.1.
|
|
1
|
+
export declare const WECHAT_CHANNEL_HELPER_VERSION = "0.1.12";
|
|
2
2
|
export declare const WECHAT_CHANNEL_HELPER_DIR_ENV = "SHENNIAN_WECHAT_CHANNEL_HELPER_DIR";
|
|
3
3
|
export declare const SHENNIAN_HELPER_RUNTIME_DIR_ENV = "SHENNIAN_HELPER_RUNTIME_DIR";
|
|
4
4
|
export declare const WECHAT_CHANNEL_HELPER_RUNTIME_REQUIRED_REASON = "helper_runtime_required";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:fs";import s from"node:path";import E from"node:crypto";const V="0.1.
|
|
1
|
+
import c from"node:fs";import s from"node:path";import E from"node:crypto";const V="0.1.12",S="SHENNIAN_WECHAT_CHANNEL_HELPER_DIR",g="SHENNIAN_HELPER_RUNTIME_DIR",C="helper_runtime_required",u=["en","v"].join("");function $(n={}){const r=n.platform??process.platform;if(r!=="darwin"&&r!=="win32")return{ok:!1,reasonCode:"unsupported_platform",message:"WeChat channel helper is only available on macOS and Windows"};const e=n.baseDir?[s.resolve(n.baseDir)]:A({platform:r,env:n[u]??R(),homedir:n.homedir,includeInstalledDesktop:n.includeInstalledDesktop});let a=null;for(const t of e){const i=_({platform:r,baseDir:t,verifyIntegrity:n.verifyIntegrity});if(i.ok||(n.baseDir||c.existsSync(t))&&(a??=i,n.baseDir))return i}return a??{ok:!1,reasonCode:C,message:x(r,e)}}function _(n){const{platform:r,baseDir:e}=n,a=s.join(e,"manifest.json"),t=F(a);if(!t)return{ok:!1,reasonCode:"manifest_missing",message:`WeChat channel helper manifest is missing: ${a}`};const i=t.platforms[r],o=i?s.join(e,i.executable):"";if(!i||!o||!c.existsSync(o))return{ok:!1,reasonCode:"helper_missing",message:`WeChat channel helper executable is missing: ${o||e}`};if(N({platform:r,baseDir:e,verifyIntegrity:n.verifyIntegrity})&&i.sha256&&E.createHash("sha256").update(c.readFileSync(o)).digest("hex")!==i.sha256)return{ok:!1,reasonCode:"integrity_mismatch",message:`WeChat channel helper integrity mismatch: ${o}`};const f=H(r,o);return f.ok?{ok:!0,helperPath:o,helperDir:e,version:t.helperVersion,manifest:t,warning:i.signed&&i.notarized?void 0:"helper_not_signed_or_notarized"}:{ok:!1,reasonCode:"helper_not_executable",message:f.message}}function H(n,r){if(n!=="darwin")return{ok:!0};try{const e=c.statSync(r);return(e.mode&73)!==0?{ok:!0}:(c.chmodSync(r,e.mode|73),{ok:!0})}catch(e){return{ok:!1,message:`WeChat channel helper is not executable and could not be repaired: ${r}: ${e instanceof Error?e.message:String(e)}`}}}function A(n){const{platform:r,env:e}=n,a=r==="win32"?"windows":"macos",t=[],i=l=>{if(!l)return;const p=s.resolve(l);t.includes(p)||t.push(p)},o=e[S]?.trim();o&&i(j(o,a));const f=e[g]?.trim();if(f)for(const l of P(f,a))i(l);if(b({platform:r,platformDir:a,env:e,homedir:n.homedir,push:i}),n.includeInstalledDesktop===!1)return t;if(r==="darwin"){const l=n.homedir||e.HOME;l&&i(s.join(l,"Applications","Shennian.app","Contents","Resources","wechat-channel",a)),i(s.join("/Applications","Shennian.app","Contents","Resources","wechat-channel",a))}else if(r==="win32"){const l=n.homedir||e.USERPROFILE,p=e.LOCALAPPDATA||(l?s.join(l,"AppData","Local"):""),m=e.ProgramFiles||e.PROGRAMFILES,h=e["ProgramFiles(x86)"]||e["PROGRAMFILES(X86)"];for(const d of[p?s.join(p,"Programs","Shennian"):"",p?s.join(p,"Programs","shennian"):"",m?s.join(m,"Shennian"):"",h?s.join(h,"Shennian"):""])d&&i(s.join(d,"resources","wechat-channel",a))}return t}function b(n){const{platform:r,platformDir:e,env:a,push:t}=n;if(r==="darwin"){const i=n.homedir||a.HOME,o=k({platform:r,env:a,homedir:n.homedir});o&&(t(s.join(o,"Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join(o,"wechat-channel",e))),i&&t(s.join(i,"Applications","Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join("/Applications","Shennian Helper.app","Contents","Resources","wechat-channel",e)),t(s.join("/Library","Application Support","Shennian","Helper","wechat-channel",e))}else if(r==="win32"){const i=n.homedir||a.USERPROFILE,o=a.LOCALAPPDATA||(i?s.join(i,"AppData","Local"):""),f=a.ProgramFiles||a.PROGRAMFILES,l=a["ProgramFiles(x86)"]||a["PROGRAMFILES(X86)"];o&&(t(s.join(o,"Programs","Shennian Helper","resources","wechat-channel",e)),t(s.join(o,"Shennian","Helper","wechat-channel",e))),f&&t(s.join(f,"Shennian Helper","resources","wechat-channel",e)),l&&t(s.join(l,"Shennian Helper","resources","wechat-channel",e))}}function j(n,r){return c.existsSync(s.join(n,"manifest.json"))?n:s.join(n,r)}function P(n,r){if(c.existsSync(s.join(n,"manifest.json")))return[n];const e=s.join(n,"Shennian Helper.app","Contents","Resources","wechat-channel",r),a=s.join(n,"wechat-channel",r),t=s.join(n,r);return[e,a,t]}function k(n){const r=n[u],e=r[g]?.trim();if(e)return s.resolve(e);const a=n.homedir||(n.platform==="win32"?r.USERPROFILE:r.HOME);if(n.platform==="darwin")return a?s.join(a,"Library","Application Support","Shennian","Helper"):null;if(n.platform==="win32"){const t=r.LOCALAPPDATA||(a?s.join(a,"AppData","Local"):"");return t?s.join(t,"Shennian","Helper"):null}return null}function q(n={}){return k({platform:n.platform??process.platform,env:n.env??R(),homedir:n.homedir})}function D(n){const r=s.resolve(n);return O([s.join(r,"helper-runtime-package.json"),s.join(s.dirname(r),"..","helper-runtime-package.json")])}function U(n){const r=n.platform??process.platform;if(r!=="darwin"&&r!=="win32")return{ok:!1,reasonCode:"unsupported_platform",message:"WeChat channel helper runtime package is only available on macOS and Windows"};const e=n.manifestPath?[s.resolve(n.manifestPath)]:n.helperDir?D(n.helperDir):[],a=e.find(t=>c.existsSync(t));if(!a)return{ok:!1,reasonCode:"helper_runtime_package_manifest_missing",message:`Helper runtime package manifest is missing. Checked: ${e.join(", ")||"(none)"}`,manifestPath:e[0]};try{const t=JSON.parse(w(a)),i=I(t,r);return i.ok?{ok:!0,manifestPath:a,manifest:t}:{ok:!1,reasonCode:"helper_runtime_package_manifest_invalid",message:`${i.message}: ${a}`,manifestPath:a}}catch(t){return{ok:!1,reasonCode:"helper_runtime_package_manifest_invalid",message:`Helper runtime package manifest is invalid JSON: ${t instanceof Error?t.message:String(t)}`,manifestPath:a}}}function I(n,r){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,message:"manifest must be an object"};const e=n;return e.schemaVersion!==1?{ok:!1,message:"schemaVersion must be 1"}:e.packageKind!=="shennian-helper-runtime"?{ok:!1,message:"packageKind must be shennian-helper-runtime"}:e.platform!==r?{ok:!1,message:`platform must be ${r}`}:e.helperVersion?!Number.isInteger(e.protocolVersion)||Number(e.protocolVersion)<=0?{ok:!1,message:"protocolVersion must be a positive integer"}:L(e.minCliVersion)?!e.sha256||typeof e.sha256.runtimeManifest!="string"?{ok:!1,message:"sha256.runtimeManifest is required"}:y(e.sha256.runtimeManifest)?e.sha256.entrypoint!==null&&typeof e.sha256.entrypoint!="string"?{ok:!1,message:"sha256.entrypoint must be a string or null"}:typeof e.sha256.entrypoint=="string"&&!y(e.sha256.entrypoint)?{ok:!1,message:"sha256.entrypoint must be a sha256 digest or null"}:!e.installTarget?.kind||!e.installTarget.defaultPath?{ok:!1,message:"installTarget.kind and installTarget.defaultPath are required"}:!e.payload?.kind||!e.payload.runtimeManifest||!e.payload.entrypoint?{ok:!1,message:"payload.kind, payload.runtimeManifest, and payload.entrypoint are required"}:r==="darwin"&&e.installTarget.kind!=="app-bundle"?{ok:!1,message:"darwin installTarget.kind must be app-bundle"}:r==="darwin"&&e.payload.kind!=="macos-helper-app"?{ok:!1,message:"darwin payload.kind must be macos-helper-app"}:r==="win32"&&e.installTarget.kind!=="directory"?{ok:!1,message:"win32 installTarget.kind must be directory"}:r==="win32"&&e.payload.kind!=="windows-helper-runtime"?{ok:!1,message:"win32 payload.kind must be windows-helper-runtime"}:!e.signature||typeof e.signature.requiredForRelease!="boolean"||typeof e.signature.signed!="boolean"||typeof e.signature.notarized!="boolean"?{ok:!1,message:"signature.requiredForRelease, signature.signed, and signature.notarized are required"}:{ok:!0}:{ok:!1,message:"sha256.runtimeManifest must be a sha256 digest"}:{ok:!1,message:"minCliVersion must be a semver string"}:{ok:!1,message:"helperVersion is required"}}function L(n){return typeof n=="string"&&/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(n)}function y(n){return/^[a-f0-9]{64}$/i.test(n)}function N(n){return n.verifyIntegrity===!0?!0:n.verifyIntegrity===!1?!1:!v(n.platform,n.baseDir)}function v(n,r){const e=r.replace(/[\\/]+/g,"/");return n==="darwin"?/\/Shennian\.app\/Contents\/Resources\/wechat-channel\/macos$/i.test(e):n==="win32"?/\/resources\/wechat-channel\/windows$/i.test(e):!1}function x(n,r){const e=n==="win32"?"Windows":"macOS",a=r.length>0?` Checked helper directories: ${r.join(", ")}`:"";return`WeChat RPA requires Shennian Helper runtime on ${e}; open Shennian Desktop or use the \u4F7F\u7528\u5FAE\u4FE1 page to install Helper, then retry.${a}`}function R(){return globalThis.process?.[u]??{}}function F(n){try{const r=JSON.parse(w(n));return r.schemaVersion!==1||typeof r.helperVersion!="string"||!r.platforms?null:r}catch{return null}}function w(n){return c.readFileSync(n,"utf8").replace(/^\uFEFF/,"")}function O(n){const r=new Set,e=[];for(const a of n){const t=s.resolve(a);r.has(t)||(r.add(t),e.push(t))}return e}export{g as SHENNIAN_HELPER_RUNTIME_DIR_ENV,S as WECHAT_CHANNEL_HELPER_DIR_ENV,C as WECHAT_CHANNEL_HELPER_RUNTIME_REQUIRED_REASON,V as WECHAT_CHANNEL_HELPER_VERSION,q as getDefaultWeChatHelperRuntimeRoot,D as helperRuntimePackageManifestCandidates,U as readWeChatChannelHelperRuntimePackageManifest,$ as resolveWeChatChannelHelperAsset,I as validateWeChatChannelHelperRuntimePackageManifest};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)}catch(
|
|
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(
|
|
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};
|
|
@@ -5,6 +5,7 @@ import type { WeChatChannelHelperTransport } from './observer.js';
|
|
|
5
5
|
import { type WeChatChannelObserveApi } from './observer.js';
|
|
6
6
|
import { WeChatChannelScheduler, type WeChatChannelSchedulerTickOptions, type WeChatChannelSchedulerTickResult } from './scheduler.js';
|
|
7
7
|
import { type WeChatAutomationLane } from './automation-lane.js';
|
|
8
|
+
export declare const WECHAT_CHANNEL_UNCHANGED_FINGERPRINT_MAX_SKIP_MS: number;
|
|
8
9
|
export type WeChatChannelProductRunnerOptions = {
|
|
9
10
|
runtime: WeChatChannelRuntime;
|
|
10
11
|
workDir: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"node:path";import h from"node:fs";import{createWeChatChannelApiClient as m}from"./client.js";import{WeChatChannelHelperClient as f}from"./helper-client.js";import{resolveWeChatChannelHelperAsset as k,WECHAT_CHANNEL_HELPER_VERSION as W}from"./helper-assets.js";import{requiredWindowsWeChatChannelHelperCapabilitiesForProfile as c}from"./helper-protocol.js";import{captureWeChatWindow as S,detectWeChatMessageInputPointByServerVision as I,focusKnownWeChatWindow as g,observeWeChatChannelBindingViaHelper as P,openConversationBySearch as A,recognizeWeChatScreenshot as
|
|
1
|
+
import u from"node:path";import h from"node:fs";import{createWeChatChannelApiClient as m}from"./client.js";import{WeChatChannelHelperClient as f}from"./helper-client.js";import{resolveWeChatChannelHelperAsset as k,WECHAT_CHANNEL_HELPER_VERSION as W}from"./helper-assets.js";import{requiredWindowsWeChatChannelHelperCapabilitiesForProfile as c}from"./helper-protocol.js";import{captureWeChatWindow as S,detectWeChatMessageInputPointByServerVision as I,focusKnownWeChatWindow as g,observeWeChatChannelBindingViaHelper as P,openConversationBySearch as A,recognizeWeChatScreenshot as D,selectWeChatWindowForBinding as w}from"./observer.js";import{WeChatChannelScheduler as O}from"./scheduler.js";import{loadWeChatChannelLedger as F}from"./ledger.js";import{buildWeChatConversationFingerprint as M,matchWeChatConversationFingerprints as _}from"./fingerprint.js";import{WeChatChannelOutboundSender as T}from"./outbound-sender.js";import{SerialWeChatAutomationLane as x}from"./automation-lane.js";import{decideWeChatChannelActivityGate as L,nextWeChatChannelActivityRetryAt as H,normalizeWeChatChannelActivitySnapshot as E}from"./human-coordination.js";const N=120*1e3;class R{options;scheduler;helper;helperStarted=!1;lane;constructor(e){this.options=e;const n=e.api??m();this.helper=e.helper??U(e),this.lane=e.lane??new x,this.scheduler=new O({runtime:e.runtime,workDir:e.workDir,api:n,ledgerPath:e.ledgerPath,outboundLedgerPath:e.outboundLedgerPath,onInboundMessages:e.onInboundMessages,activityGate:{canObserve:async(a,i)=>{if(e.runtime.foregroundPolicy==="work")return{ok:!0};const o=await this.helper.request("activity.snapshot",{});if(!o.ok)return{ok:!1,reasonCode:"user_activity_unknown",nextAttemptAt:new Date(i.getTime()+5e3)};const t=L({snapshot:E(o.result),stage:"observe"});return t.ok?{ok:!0}:{ok:!1,reasonCode:t.reasonCode,nextAttemptAt:H(i,t.waitMs)}}},shouldSkipObserve:(a,i)=>this.shouldSkipObserveForUnchangedFingerprint(a,i.foregroundMode),outboundSender:new T({helper:this.helper,platform:e.runtime.policy.platform,activityGatePolicy:e.runtime.foregroundPolicy==="work"?{mouseMovedThresholdMs:0,mouseClickThresholdMs:0,scrollWheelThresholdMs:0,keyDownThresholdMs:0}:void 0,takeoverCheck:e.runtime.foregroundPolicy!=="work",openConversation:async a=>{const i={bindingId:`outbound:${a}`,sessionId:"outbound",conversationDisplayName:a,enabled:!0,allowReply:!0,downloadMedia:!0},o=await w({runtime:e.runtime,binding:i,helper:this.helper,api:n,workDir:e.workDir}),t=await g(this.helper,o),s=await A({helper:this.helper,window:t,settleToBottom:!1,binding:i,runtime:e.runtime,api:n,workDir:e.workDir});if(!s.opened)return{...s,windowId:t.windowId,inputPoint:null};const l=await I({runtime:e.runtime,binding:i,helper:this.helper,api:n,workDir:e.workDir,window:t});return{...s,windowId:t.windowId,inputPoint:l}}}),observeBinding:(a,i)=>P({runtime:e.runtime,binding:a,helper:this.helper,api:n,workDir:e.workDir,localLedgerTailAnchors:q(e.ledgerPath??B(e.workDir,e.runtime.runtimeId),e.runtime.runtimeId,a.bindingId),localOutboundEchoAnchors:i?.localOutboundEchoAnchors,foregroundMode:i?.foregroundMode,onObservationEvidence:({ocr:o})=>{$({statePath:b(e.workDir,e.runtime.runtimeId),runtimeId:e.runtime.runtimeId,binding:a,ocr:o})}})})}async start(){return this.lane.run("wechat.runner.start",async()=>{await this.ensureHelperStarted(),await this.scheduler.start()})}async tick(e){return this.lane.run("wechat.runner.tick",async()=>(await this.ensureHelperStarted(),this.scheduler.tick(e)))}async stop(){return this.lane.run("wechat.runner.stop",async()=>{await this.scheduler.stop(),this.helperStarted&&this.helper.stop&&await this.helper.stop(),this.helperStarted=!1})}async ensureHelperStarted(){this.helperStarted||(this.helper.start&&await this.helper.start(),this.helperStarted=!0)}async shouldSkipObserveForUnchangedFingerprint(e,n="required"){if(this.options.runtime.policy.platform!=="darwin"&&this.options.runtime.policy.platform!=="win32")return{skip:!1};const a=b(this.options.workDir,this.options.runtime.runtimeId),i=p(a,this.options.runtime.runtimeId).bindings[e.bindingId];if(!i?.fingerprint)return{skip:!1};if(j(i))return{skip:!1};try{const o=this.options.api??m(),t=await w({runtime:this.options.runtime,binding:e,helper:this.helper,api:o,workDir:this.options.workDir},{foregroundMode:n}),s=n==="background"?t:await g(this.helper,t),l=await S(this.helper,s.windowId,void 0,s.bounds),y=await D(this.helper,l),d=v({binding:e,ocr:y,prior:i});return!d?.fingerprint||d.fingerprint!==i.fingerprint?{skip:!1}:{skip:!0,reasonCode:"conversation_fingerprint_unchanged",fingerprint:d.fingerprint}}catch{return{skip:!1}}}}function oe(r){return new R(r)}function q(r,e,n,a=3){return(F(r,e).bindings[n]?.recent??[]).slice(-a).map(t=>({stableMessageKey:t.stableMessageKey,senderRole:t.senderRole,kind:t.kind,anchorText:t.anchorText??t.normalizedText??t.textExcerpt??null,anchorMetadata:t.anchorMetadata??null}))}function U(r){if(r.helperClientOptions)return new f({...r.helperClientOptions,requiredCapabilities:r.helperClientOptions.requiredCapabilities??C(r.runtime),guardUnsafeWindowsCommands:r.helperClientOptions.guardUnsafeWindowsCommands??r.runtime.policy.platform==="win32",skipUserActivityGuard:r.helperClientOptions.skipUserActivityGuard??r.runtime.foregroundPolicy==="work",cleanupWindowsOverlays:r.helperClientOptions.cleanupWindowsOverlays??r.runtime.policy.platform==="win32",requestLogger:r.helperClientOptions.requestLogger??r.helperRequestLogger});const e=k();if(!e.ok)throw new Error(`${e.reasonCode}: ${e.message}`);return new f({helperPath:e.helperPath,expectedHelperVersion:e.version||W,requiredCapabilities:C(r.runtime),guardUnsafeWindowsCommands:r.runtime.policy.platform==="win32",skipUserActivityGuard:r.runtime.foregroundPolicy==="work",cleanupWindowsOverlays:r.runtime.policy.platform==="win32",requestLogger:r.helperRequestLogger})}function C(r){if(r.policy.platform==="win32")return r.bindings.some(e=>e.enabled!==!1&&e.allowReply!==!1)?c("send"):r.bindings.some(e=>e.enabled!==!1&&e.downloadMedia!==!1)?c("download"):c("observe")}function B(r,e){return u.join(r,"wechat-channel",`${e}.ledger.json`)}function b(r,e){return u.join(r,"wechat-channel",`${z(e)}.conversation-fingerprints.json`)}function p(r,e){try{const n=JSON.parse(h.readFileSync(r,"utf8"));if(n?.version===1&&n.runtimeId===e&&n.bindings&&typeof n.bindings=="object")return n}catch{}return{version:1,runtimeId:e,bindings:{}}}function G(r,e){h.mkdirSync(u.dirname(r),{recursive:!0}),h.writeFileSync(r,JSON.stringify(e,null,2))}function $(r){const e=v({binding:r.binding,ocr:r.ocr,prior:p(r.statePath,r.runtimeId).bindings[r.binding.bindingId]});if(!e?.fingerprint)return;const n=p(r.statePath,r.runtimeId);n.bindings[r.binding.bindingId]={bindingId:r.binding.bindingId,fingerprint:e.fingerprint,title:e.item.title??null,preview:e.item.preview??null,timeText:e.item.timeText??null,unreadText:e.item.unreadText??null,observedAt:new Date().toISOString()},G(r.statePath,n)}function j(r){const e=Date.parse(r.observedAt||"");return Number.isFinite(e)?Date.now()-e>=N:!0}function v(r){const e=r.ocr.visibleConversationFingerprints??[],n=_({visibleItems:e,targets:[{bindingId:r.binding.bindingId,conversationDisplayName:r.binding.conversationDisplayName,lastConversationFingerprint:r.prior?.fingerprint,lastPreview:r.prior?.preview??void 0}]})[0];if(!n)return null;const a=M(n.item);return a?{item:n.item,fingerprint:a,reason:n.reason}:null}function z(r){return String(r||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}export{N as WECHAT_CHANNEL_UNCHANGED_FINGERPRINT_MAX_SKIP_MS,R as WeChatChannelProductRunner,q as buildLocalLedgerTailAnchors,oe as createWeChatChannelProductRunner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import U from"node:crypto";import{once as _}from"node:events";import o from"node:fs";import z from"node:os";import h from"node:path";import{spawnSync as y}from"node:child_process";const R="https://videoindustry.oss-cn-hangzhou.aliyuncs.com/shennian/helper-runtime",g="stable",$=
|
|
1
|
+
import U from"node:crypto";import{once as _}from"node:events";import o from"node:fs";import z from"node:os";import h from"node:path";import{spawnSync as y}from"node:child_process";const R="https://videoindustry.oss-cn-hangzhou.aliyuncs.com/shennian/helper-runtime",g="stable",$=5*6e4,I=350*1024*1024;async function X(e){const r=e.env??process.env,n=S(e.channel??r.SHENNIAN_HELPER_RUNTIME_CHANNEL)??g,t=e.manifestUrl??P({env:r,channel:n}),a=e.arch??process.arch,s=A(r.SHENNIAN_HELPER_RUNTIME_DOWNLOAD_TIMEOUT_MS)??e.timeoutMs??$,c=A(r.SHENNIAN_HELPER_RUNTIME_MAX_BYTES)??e.maxBytes??I,m=e.fetchImpl??globalThis.fetch?.bind(globalThis);if(!m)return{ok:!1,reasonCode:"helper_runtime_manifest_unavailable",message:"This Node.js runtime does not provide fetch for official Helper runtime download.",manifestUrl:t};const l=await L({manifestUrl:t,fetchImpl:m,timeoutMs:s});if(!l.ok)return l;const i=x({manifest:l.manifest,platform:e.platform,arch:a});if(!i)return{ok:!1,reasonCode:"helper_runtime_artifact_unavailable",message:`No official Helper runtime artifact is available for ${e.platform}/${a} on channel ${l.manifest.channel}.`,manifestUrl:t};const f=o.mkdtempSync(h.join(e.workRoot??z.tmpdir(),"shennian-helper-runtime-")),d=h.join(f,"helper-runtime.zip"),p=h.join(f,"source");try{await(e.downloadFile??C)({url:i.url,outputPath:d,fetchImpl:m,timeoutMs:s,maxBytes:c})}catch(u){return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_download_failed",message:`Official Helper runtime download failed: ${u instanceof Error?u.message:String(u)}`,manifestUrl:t,artifactUrl:i.url}}const H=o.statSync(d).size,T=O(d);if(H!==i.sizeBytes||T!==i.sha256)return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_artifact_integrity_mismatch",message:"Official Helper runtime artifact failed size or sha256 verification.",manifestUrl:t,artifactUrl:i.url};try{o.mkdirSync(p,{recursive:!0}),await(e.extractZip??M)({zipPath:d,outputDir:p,platform:e.platform}),v(p)}catch(u){return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_artifact_invalid",message:`Official Helper runtime artifact could not be extracted safely: ${u instanceof Error?u.message:String(u)}`,manifestUrl:t,artifactUrl:i.url}}return{ok:!0,sourceDir:p,tempDir:f,cleanup:()=>o.rmSync(f,{recursive:!0,force:!0}),channel:l.manifest.channel,manifestUrl:t,artifactUrl:i.url,artifactSha256:i.sha256,artifactSizeBytes:i.sizeBytes,platform:i.platform,arch:i.arch,helperVersion:i.helperVersion,protocolVersion:i.protocolVersion,minCliVersion:i.minCliVersion}}function P(e={}){const r=e.env??process.env,n=r.SHENNIAN_HELPER_RUNTIME_MANIFEST_URL?.trim();if(n)return n;const t=S(e.channel??r.SHENNIAN_HELPER_RUNTIME_CHANNEL)??g;return`${(r.SHENNIAN_HELPER_RUNTIME_BASE_URL?.trim()||R).replace(/\/+$/g,"")}/${encodeURIComponent(t)}/manifest.json`}function x(e){return N(e.manifest)?e.manifest.artifacts.filter(n=>n.platform===e.platform).find(n=>D(n.arch,e.arch))??null:null}async function L(e){try{const r=new AbortController,n=setTimeout(()=>r.abort(),e.timeoutMs);try{const t=await e.fetchImpl(e.manifestUrl,{signal:r.signal});if(!t.ok)throw new Error(`HTTP ${t.status}`);const a=JSON.parse(await t.text());if(!N(a))throw new Error("manifest schema is invalid");return{ok:!0,manifest:a}}finally{clearTimeout(n)}}catch(r){return{ok:!1,reasonCode:"helper_runtime_manifest_unavailable",message:`Official Helper runtime manifest is unavailable: ${r instanceof Error?r.message:String(r)}`,manifestUrl:e.manifestUrl}}}async function C(e){const r=new AbortController,n=setTimeout(()=>r.abort(),e.timeoutMs);let t=null;try{const a=await e.fetchImpl(e.url,{signal:r.signal});if(!a.ok)throw new Error(`HTTP ${a.status}`);if(!a.body)throw new Error("response body is empty");t=o.createWriteStream(e.outputPath,{flags:"wx"});const s=a.body.getReader();let c=0;for(;;){const{done:m,value:l}=await s.read();if(m)break;const i=Buffer.from(l);if(c+=i.byteLength,c>e.maxBytes)throw new Error(`download exceeded ${e.maxBytes} bytes`);t.write(i)||await _(t,"drain")}t.end(),await _(t,"finish")}finally{clearTimeout(n),t&&!t.closed&&t.destroy()}}async function M(e){if(k(e.zipPath),process.platform==="win32"){E("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`Expand-Archive -LiteralPath ${b(e.zipPath)} -DestinationPath ${b(e.outputDir)} -Force`]);return}if(e.platform==="darwin"&&w("ditto")){E("ditto",["-x","-k",e.zipPath,e.outputDir]);return}E("unzip",["-q",e.zipPath,"-d",e.outputDir])}function k(e){const r=w("unzip")?"unzip":w("tar")?"tar":null;if(!r)return;const n=r==="unzip"?y(r,["-Z","-1",e],{encoding:"utf8"}):y(r,["-tf",e],{encoding:"utf8"});if(n.status!==0)throw new Error(`unable to inspect zip entries with ${r}`);for(const t of n.stdout.split(/\r?\n/u).filter(Boolean)){const a=t.replace(/\\/g,"/");if(a.startsWith("/")||a.includes("../")||a===".."||/^[A-Za-z]:\//u.test(a))throw new Error(`unsafe zip entry: ${t}`)}}function v(e){const r=o.realpathSync(e),n=[e];for(;n.length>0;){const t=n.pop();if(t)for(const a of o.readdirSync(t,{withFileTypes:!0})){const s=h.join(t,a.name),c=o.realpathSync(s);if(c!==r&&!c.startsWith(`${r}${h.sep}`))throw new Error(`extracted path escapes target directory: ${s}`);a.isDirectory()&&n.push(s)}}}function N(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return r.schemaVersion!==1||r.kind!=="shennian-helper-runtime-index"||!r.channel||typeof r.channel!="string"||!r.generatedAt||typeof r.generatedAt!="string"||!Array.isArray(r.artifacts)?!1:r.artifacts.every(B)}function B(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return(r.platform==="darwin"||r.platform==="win32")&&typeof r.arch=="string"&&typeof r.helperVersion=="string"&&Number.isInteger(r.protocolVersion)&&typeof r.minCliVersion=="string"&&typeof r.url=="string"&&typeof r.sizeBytes=="number"&&Number.isInteger(r.sizeBytes)&&r.sizeBytes>0&&typeof r.sha256=="string"&&/^[a-f0-9]{64}$/iu.test(r.sha256)}function D(e,r){const n=e.toLowerCase(),t=r.toLowerCase();return n===t||n==="universal"||n==="all"||n===`win-${t}`||n===`darwin-${t}`}function S(e){const r=e?.trim();return!r||!/^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(r)?null:r}function A(e){if(!e)return null;const r=Number(e);return Number.isInteger(r)&&r>0?r:null}function O(e){return U.createHash("sha256").update(o.readFileSync(e)).digest("hex")}function w(e){return y(e,["--version"],{stdio:"ignore"}).status===0}function E(e,r){const n=y(e,r,{stdio:"ignore"});if(n.status!==0)throw new Error(`${e} exited ${n.status}`)}function b(e){return`'${e.replace(/'/g,"''")}'`}export{X as downloadOfficialHelperRuntimePackage,P as getOfficialHelperRuntimeManifestUrl,x as selectOfficialHelperRuntimeArtifact};
|
|
@@ -33,6 +33,9 @@ export type HelperRuntimeInstallResult = {
|
|
|
33
33
|
artifactSha256: string;
|
|
34
34
|
artifactSizeBytes: number;
|
|
35
35
|
arch: string;
|
|
36
|
+
helperVersion: string;
|
|
37
|
+
protocolVersion: number;
|
|
38
|
+
minCliVersion: string;
|
|
36
39
|
};
|
|
37
40
|
message: string;
|
|
38
41
|
} | {
|
|
@@ -78,13 +81,16 @@ export type HelperRuntimeStatusResult = {
|
|
|
78
81
|
};
|
|
79
82
|
type RuntimeIo = {
|
|
80
83
|
existsSync?: typeof fs.existsSync;
|
|
84
|
+
lstatSync?: typeof fs.lstatSync;
|
|
81
85
|
readFileSync?: typeof fs.readFileSync;
|
|
86
|
+
realpathSync?: typeof fs.realpathSync;
|
|
82
87
|
mkdirSync?: typeof fs.mkdirSync;
|
|
83
88
|
rmSync?: typeof fs.rmSync;
|
|
84
89
|
cpSync?: typeof fs.cpSync;
|
|
85
90
|
renameSync?: typeof fs.renameSync;
|
|
86
91
|
chmodSync?: typeof fs.chmodSync;
|
|
87
92
|
homedir?: () => string;
|
|
93
|
+
stopMacHelperProcesses?: (targetDir: string) => void;
|
|
88
94
|
stopWindowsHelperProcesses?: () => void;
|
|
89
95
|
};
|
|
90
96
|
export declare function registerRuntimeCommand(program: Command): void;
|
|
@@ -107,6 +113,7 @@ export declare function installHelperRuntimeWithOfficialDownload(input?: {
|
|
|
107
113
|
env?: NodeJS.ProcessEnv;
|
|
108
114
|
homedir?: string;
|
|
109
115
|
force?: boolean;
|
|
116
|
+
preferOfficialDownload?: boolean;
|
|
110
117
|
io?: RuntimeIo;
|
|
111
118
|
officialDownload?: false | Partial<HelperRuntimeOfficialDownloadOptions>;
|
|
112
119
|
}): Promise<HelperRuntimeInstallResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import f from"node:fs";import y from"node:os";import t from"node:path";import{spawnSync as A}from"node:child_process";import v from"chalk";import{getDefaultWeChatHelperRuntimeRoot as D,readWeChatChannelHelperRuntimePackageManifest as w,resolveWeChatChannelHelperAsset as C,SHENNIAN_HELPER_RUNTIME_DIR_ENV as E,WECHAT_CHANNEL_HELPER_DIR_ENV as O}from"../channels/wechat-channel/helper-assets.js";import{downloadOfficialHelperRuntimePackage as $}from"./helper-runtime-official-download.js";import{compareVersions as x,getCurrentVersion as H}from"../upgrade/engine.js";import{SerialWeChatAutomationLane as U}from"../channels/wechat-channel/automation-lane.js";const u="helper-runtime-package.json";function ce(e){const r=e.command("runtime").description("Install, repair, and inspect Shennian local runtimes");r.command("status").description("Print local Shennian runtime status").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(o=>{const n=V({platform:o.platform});P(n,!!o.json),n.ok||(process.exitCode=1)}),r.command("install").description("Install a Shennian runtime component").argument("<component>","Runtime component, currently only: helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,n)=>{const a=o==="helper"?await b({source:n.source,platform:n.platform,officialDownload:n.officialDownload===!1?!1:{channel:n.channel,manifestUrl:n.manifestUrl}}):M(o);P(a,!!n.json),a.ok||(process.exitCode=1)}),r.command("repair").description("Repair a Shennian runtime component").argument("[component]","Runtime component, currently only: helper","helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,n)=>{const a=o==="helper"?await b({source:n.source,platform:n.platform,force:!0,officialDownload:n.officialDownload===!1?!1:{channel:n.channel,manifestUrl:n.manifestUrl}}):M(o);P(a,!!n.json),a.ok||(process.exitCode=1)})}function V(e={}){const r=k(e.platform);if(!r)return{ok:!1,installed:!1,repairable:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairSuggestion:l("unsupported_platform")};const o=e.env??process.env,n=e.homedir,a=C({platform:r,env:o,homedir:n,includeInstalledDesktop:!1}),i=D({platform:r,env:o,homedir:n});if(!a.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:K(a.reasonCode),reasonCode:a.reasonCode,message:a.message,runtimeRoot:i,repairSuggestion:l(a.reasonCode),checkedSources:_({platform:r,env:o,homedir:n})};const s=w({platform:r,helperDir:a.helperDir});if(!s.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:s.reasonCode,message:s.message,helperDir:a.helperDir,helperPath:a.helperPath,helperVersion:a.version,runtimeVersion:a.version,protocolVersion:a.manifest.protocolVersion,runtimeRoot:i,repairSuggestion:l(s.reasonCode),checkedSources:_({platform:r,env:o,homedir:n})};const c=R({platform:r,packageManifest:s.manifest,currentCliVersion:H(),helperVersion:a.version,protocolVersion:a.manifest.protocolVersion});return c.ok?{ok:!0,platform:r,targetPlatform:r,installed:!0,repairable:!1,message:`Shennian Helper runtime is installed: ${a.helperDir}`,helperDir:a.helperDir,helperPath:a.helperPath,helperVersion:a.version,runtimeVersion:a.version,protocolVersion:a.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i}:{ok:!1,platform:r,targetPlatform:r,installed:!0,repairable:c.repairable,reasonCode:c.reasonCode,message:c.message,helperDir:a.helperDir,helperPath:a.helperPath,helperVersion:a.version,runtimeVersion:a.version,protocolVersion:a.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i,repairSuggestion:l(c.reasonCode,s.manifest.minCliVersion),checkedSources:_({platform:r,env:o,homedir:n})}}function j(e={}){const r=k(e.platform);if(!r)return{ok:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairable:!1,repairSuggestion:l("unsupported_platform")};const o=e.env??process.env,n=F(e.io),a=e.homedir??n.homedir(),i=V({platform:r,env:o,homedir:a});if(i.ok&&!e.force&&i.helperDir&&i.helperPath&&i.helperVersion&&i.protocolVersion)return{ok:!0,action:"already_installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:q(r,i.helperDir),helperDir:i.helperDir,helperPath:i.helperPath,helperVersion:i.helperVersion,runtimeVersion:i.helperVersion,protocolVersion:i.protocolVersion,minCliVersion:i.minCliVersion,sha256:i.sha256,packageManifestPath:i.packageManifestPath,packageKind:i.packageKind,installTarget:i.installTarget,signature:i.signature,message:`Shennian Helper runtime is already installed: ${i.helperDir}`};const s=e.source?[t.resolve(e.source)]:_({platform:r,env:o,homedir:a}),c=s.map(S=>z({candidate:S,platform:r,io:n})).find(S=>S!=null);if(!c)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:"helper_runtime_source_missing",message:"No installable Shennian Helper runtime package was found. Open Shennian Desktop, pass --source, or download the official helper package.",repairSuggestion:l("helper_runtime_source_missing"),checkedSources:s};const h=w({platform:r,manifestPath:c.packageManifestPath});if(!h.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:h.reasonCode,message:h.message,repairSuggestion:l(h.reasonCode),checkedSources:s};const g=R({platform:r,packageManifest:h.manifest,currentCliVersion:H()});if(!g.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:g.repairable,reasonCode:g.reasonCode,message:g.message,repairSuggestion:l(g.reasonCode,h.manifest.minCliVersion),checkedSources:s};const d=J({platform:r,env:o,homedir:a,packageKind:c.packageKind});if(!d)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!1,reasonCode:"helper_runtime_target_unavailable",message:"Unable to determine Helper runtime install target for this platform.",repairSuggestion:l("helper_runtime_target_unavailable"),checkedSources:s};X({platform:r,sourceDir:c.sourceDir,targetDir:d,io:n}),Y({sourceManifestPath:c.packageManifestPath,targetManifestPath:c.packageManifestPathInTarget(d),io:n});const m=C({platform:r,baseDir:c.manifestDirInTarget(d),verifyIntegrity:!0});if(!m.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:m.reasonCode,message:`Installed Helper runtime could not be verified: ${m.message}`,repairSuggestion:l(m.reasonCode),checkedSources:s};Z(r,m.helperPath,n);const p=w({platform:r,helperDir:m.helperDir});return p.ok?{ok:!0,action:"installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:d,helperDir:m.helperDir,helperPath:m.helperPath,helperVersion:m.version,runtimeVersion:m.version,protocolVersion:m.manifest.protocolVersion,minCliVersion:p.manifest.minCliVersion,sha256:p.manifest.sha256,packageManifestPath:p.manifestPath,packageKind:p.manifest.packageKind,installTarget:p.manifest.installTarget,signature:p.manifest.signature,message:`Installed Shennian Helper runtime to ${d}`}:{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:p.reasonCode,message:`Installed Helper runtime package manifest could not be verified: ${p.message}`,repairSuggestion:l(p.reasonCode),checkedSources:s}}async function b(e={}){const r=new U({lockPath:T(e),owner:"helper-runtime-install",defaultWaitMs:0});try{return await r.run("helper-runtime-install",()=>N(e))}catch(o){if(L(o)){const n=k(e.platform)??void 0;return{ok:!1,platform:n,targetPlatform:n,installed:!1,repairable:!0,reasonCode:"wechat_automation_busy",message:o instanceof Error?o.message:String(o),repairSuggestion:"Wait for the current WeChat automation run to finish, then retry Helper install or repair."}}throw o}}function T(e){const r=e.env?.SHENNIAN_HOME?.trim()||process.env.SHENNIAN_HOME?.trim(),o=r?t.resolve(r):t.join(e.homedir??y.homedir(),".shennian");return t.join(o,"runtime","wechat-automation.lock")}function L(e){return e instanceof Error?e.message.includes("wechat_automation_busy"):String(e).includes("wechat_automation_busy")}async function N(e={}){const r=j(e);if(r.ok||e.source||e.officialDownload===!1||!W(r.reasonCode))return r.ok?{...r,source:r.source??"local"}:r;const o=k(e.platform);if(!o)return r;const n=await $({...e.officialDownload,platform:o,env:e.env??process.env});if(!n.ok)return{ok:!1,platform:o,targetPlatform:o,installed:!1,repairable:!0,reasonCode:n.reasonCode,message:n.message,repairSuggestion:l(n.reasonCode),checkedSources:r.checkedSources,officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}};try{const a=j({...e,source:n.sourceDir,platform:o});return a.ok?{...a,source:"official-download",officialDownload:{channel:n.channel,manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl,artifactSha256:n.artifactSha256,artifactSizeBytes:n.artifactSizeBytes,arch:n.arch}}:{...a,reasonCode:a.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":a.reasonCode,message:a.reasonCode==="helper_runtime_source_missing"?"Official Helper runtime artifact did not contain an installable runtime package.":a.message,repairSuggestion:l(a.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":a.reasonCode),officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}}}finally{n.cleanup()}}function W(e){return e==="helper_runtime_source_missing"||e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid"}function k(e){const r=e??process.platform;return r==="darwin"||r==="win32"?r:null}function R(e){return e.packageManifest.platform!==e.platform?{ok:!1,reasonCode:"helper_runtime_platform_mismatch",message:`Helper runtime package platform ${e.packageManifest.platform} does not match ${e.platform}.`,repairable:!0}:e.helperVersion&&e.packageManifest.helperVersion!==e.helperVersion?{ok:!1,reasonCode:"helper_runtime_version_mismatch",message:`Helper runtime package version ${e.packageManifest.helperVersion} does not match installed helper ${e.helperVersion}.`,repairable:!0}:e.protocolVersion&&e.packageManifest.protocolVersion!==e.protocolVersion?{ok:!1,reasonCode:"helper_runtime_protocol_mismatch",message:`Helper runtime package protocol ${e.packageManifest.protocolVersion} does not match installed helper protocol ${e.protocolVersion}.`,repairable:!0}:x(e.currentCliVersion,e.packageManifest.minCliVersion)!=="none"?{ok:!1,reasonCode:"helper_runtime_cli_too_old",message:`Shennian CLI ${e.currentCliVersion} is older than required ${e.packageManifest.minCliVersion}.`,repairable:!1}:{ok:!0}}function K(e){return e!=="unsupported_platform"&&e!=="helper_runtime_cli_too_old"}function l(e,r){if(e==="unsupported_platform")return"Use Shennian Helper runtime on macOS or Windows.";if(e==="unsupported_runtime_component")return"Use `shennian runtime install helper` or `shennian runtime repair helper`.";if(e==="helper_runtime_cli_too_old")return`Upgrade Shennian CLI${r?` to ${r} or newer`:""}, then retry.`;if(e==="helper_runtime_target_unavailable")return"Set the current user home/LOCALAPPDATA correctly, then retry.";if(e==="helper_runtime_required")return"Open Shennian Desktop or use the \u4F7F\u7528\u5FAE\u4FE1 page to install Helper.";if(e==="helper_runtime_source_missing")return"Open Shennian Desktop, retry from the \u4F7F\u7528\u5FAE\u4FE1 page, or pass `--source <path>`.";if(e==="helper_runtime_manifest_unavailable")return"Check network access to Shennian official downloads, then retry from the \u4F7F\u7528\u5FAE\u4FE1 page.";if(e==="helper_runtime_artifact_unavailable")return"Upgrade Shennian CLI or wait for this platform Helper runtime to be published.";if(e==="helper_runtime_download_failed")return"Check network access to Shennian official downloads, then retry.";if(e==="helper_runtime_artifact_integrity_mismatch")return"Retry the official Helper runtime download; the downloaded package did not match the published hash.";if(e==="helper_runtime_artifact_invalid")return"Retry after Shennian republishes a valid Helper runtime package for this platform.";if(e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid")return"Reinstall or repair the official Shennian Helper runtime package.";if(e==="helper_runtime_platform_mismatch")return"Install the Helper runtime package for this platform.";if(e==="helper_runtime_version_mismatch"||e==="helper_runtime_protocol_mismatch")return"Run `shennian runtime repair helper` with the matching official Helper runtime package.";if(e==="manifest_missing"||e==="helper_missing"||e==="integrity_mismatch"||e==="helper_not_executable")return"Run `shennian runtime repair helper` or reinstall Shennian Desktop."}function M(e){return{ok:!1,repairable:!1,reasonCode:"unsupported_runtime_component",message:`Unsupported runtime component: ${e}. Supported component: helper.`,repairSuggestion:l("unsupported_runtime_component")}}function F(e){return{existsSync:e?.existsSync??f.existsSync,readFileSync:e?.readFileSync??f.readFileSync,mkdirSync:e?.mkdirSync??f.mkdirSync,rmSync:e?.rmSync??f.rmSync,cpSync:e?.cpSync??f.cpSync,renameSync:e?.renameSync??f.renameSync,chmodSync:e?.chmodSync??f.chmodSync,homedir:e?.homedir??y.homedir,stopWindowsHelperProcesses:e?.stopWindowsHelperProcesses??Q}}function z(e){const r=t.resolve(e.candidate);return e.io.existsSync(r)?e.platform==="darwin"?B(r,e.io):G(r,e.io):null}function B(e,r){const o=e.endsWith(".app")?e:t.join(e,"Shennian Helper.app");if(r.existsSync(t.join(o,"Contents","Resources","wechat-channel","macos","manifest.json")))return{sourceDir:o,packageKind:"macos-app",packageManifestPath:I(r,[t.join(o,"Contents","Resources","helper-runtime-package.json"),t.join(e,u)]),packageManifestPathInTarget:a=>t.join(a,"Contents","Resources",u),manifestDirInTarget:a=>t.join(a,"Contents","Resources","wechat-channel","macos")};const n=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","macos");return r.existsSync(t.join(n,"manifest.json"))?{sourceDir:n,packageKind:"asset-dir",packageManifestPath:t.join(n,"helper-runtime-package.json"),packageManifestPathInTarget:a=>t.join(a,u),manifestDirInTarget:a=>a}:null}function G(e,r){const o=t.basename(e).toLowerCase()==="shennian helper"?e:t.join(e,"Shennian Helper");if(r.existsSync(t.join(o,"resources","wechat-channel","windows","manifest.json")))return{sourceDir:o,packageKind:"windows-runtime",packageManifestPath:I(r,[t.join(o,"resources",u),t.join(e,u)]),packageManifestPathInTarget:a=>t.join(a,"resources",u),manifestDirInTarget:a=>t.join(a,"resources","wechat-channel","windows")};const n=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","windows");return r.existsSync(t.join(n,"manifest.json"))?{sourceDir:n,packageKind:"asset-dir",packageManifestPath:t.join(n,"helper-runtime-package.json"),packageManifestPathInTarget:a=>t.join(a,u),manifestDirInTarget:a=>a}:null}function J(e){const r=D(e);if(!r)return null;if(e.platform==="darwin")return e.packageKind==="macos-app"?t.join(r,"Shennian Helper.app"):t.join(r,"wechat-channel","macos");if(e.packageKind==="windows-runtime"){const o=e.env.LOCALAPPDATA||(e.homedir?t.join(e.homedir,"AppData","Local"):"");return o?t.join(o,"Programs","Shennian Helper"):null}return t.join(r,"wechat-channel","windows")}function q(e,r){const o=t.resolve(r);if(e==="darwin"){const a=`${t.sep}Contents${t.sep}Resources${t.sep}wechat-channel${t.sep}macos`;return o.endsWith(a)?o.slice(0,-a.length):o}const n=`${t.sep}resources${t.sep}wechat-channel${t.sep}windows`;return o.endsWith(n)?o.slice(0,-n.length):o}function X(e){const r=t.resolve(e.sourceDir),o=t.resolve(e.targetDir);if(r===o)return;const n=`${o}.tmp-${process.pid}-${Date.now()}`;e.io.rmSync(n,{recursive:!0,force:!0}),e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,n,{recursive:!0}),e.platform==="win32"&&e.io.stopWindowsHelperProcesses(),e.io.rmSync(o,{recursive:!0,force:!0}),e.io.renameSync(n,o)}function Q(){if(process.platform!=="win32")return;const e=A("taskkill",["/IM","shennian-wechat-channel-helper.exe","/T","/F"],{stdio:"ignore",windowsHide:!0});if(e.status!==0&&e.status!==128)throw new Error(`taskkill shennian-wechat-channel-helper.exe exited ${e.status}`)}function Y(e){const r=t.resolve(e.sourceManifestPath),o=t.resolve(e.targetManifestPath);!e.io.existsSync(r)||r===o||(e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,o))}function I(e,r){return r.find(o=>e.existsSync(o))??r[0]}function Z(e,r,o){if(e==="darwin")try{const n=f.statSync(r);(n.mode&73)===0&&o.chmodSync(r,n.mode|493)}catch{}}function _(e){const r=e.homedir||(e.platform==="win32"?e.env.USERPROFILE:e.env.HOME),o=[],n=a=>{if(!a)return;const i=t.resolve(a);o.includes(i)||o.push(i)};if(n(e.env.SHENNIAN_HELPER_PACKAGE_DIR),n(e.env[O]),n(e.env[E]),e.platform==="darwin")r&&(n(t.join(r,"Applications","Shennian.app","Contents","Resources")),n(t.join(r,"Applications","Shennian Helper.app"))),n(t.join("/Applications","Shennian.app","Contents","Resources")),n(t.join("/Applications","Shennian Helper.app"));else{const a=e.env.LOCALAPPDATA||(r?t.join(r,"AppData","Local"):""),i=e.env.ProgramFiles||e.env.PROGRAMFILES,s=e.env["ProgramFiles(x86)"]||e.env["PROGRAMFILES(X86)"];a&&(n(t.join(a,"Programs","Shennian","resources")),n(t.join(a,"Programs","Shennian Helper"))),i&&(n(t.join(i,"Shennian","resources")),n(t.join(i,"Shennian Helper"))),s&&(n(t.join(s,"Shennian","resources")),n(t.join(s,"Shennian Helper")))}return n(t.resolve(process.cwd(),"packages/helper-runtime/dist",e.platform==="darwin"?"macos":"windows")),n(t.resolve(process.cwd(),"packages/helper-runtime/wechat-channel",e.platform==="darwin"?"macos":"windows")),o}function P(e,r){if(r){console.log(JSON.stringify(e,null,2));return}if(e.ok){console.log(v.green(`\u2713 ${e.message}`)),"helperVersion"in e&&console.log(`version=${e.helperVersion} protocol=${e.protocolVersion}`),"helperPath"in e&&console.log(e.helperPath);return}console.error(v.red(`\u2717 ${e.reasonCode}`)),console.error(e.message)}export{V as getHelperRuntimeStatus,j as installHelperRuntime,b as installHelperRuntimeWithOfficialDownload,ce as registerRuntimeCommand};
|
|
1
|
+
import m from"node:fs";import C from"node:os";import t from"node:path";import{spawnSync as H}from"node:child_process";import V from"chalk";import{getDefaultWeChatHelperRuntimeRoot as b,readWeChatChannelHelperRuntimePackageManifest as y,resolveWeChatChannelHelperAsset as R,SHENNIAN_HELPER_RUNTIME_DIR_ENV as L,WECHAT_CHANNEL_HELPER_DIR_ENV as N}from"../channels/wechat-channel/helper-assets.js";import{downloadOfficialHelperRuntimePackage as W}from"./helper-runtime-official-download.js";import{compareVersions as K,getCurrentVersion as j}from"../upgrade/engine.js";import{SerialWeChatAutomationLane as F}from"../channels/wechat-channel/automation-lane.js";const h="helper-runtime-package.json";function ke(e){const r=e.command("runtime").description("Install, repair, and inspect Shennian local runtimes");r.command("status").description("Print local Shennian runtime status").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(o=>{const a=M({platform:o.platform});_(a,!!o.json),a.ok||(process.exitCode=1)}),r.command("install").description("Install a Shennian runtime component").argument("<component>","Runtime component, currently only: helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)}),r.command("upgrade").description("Upgrade a Shennian runtime component").argument("<component>","Runtime component, currently only: helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not use Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,force:!0,preferOfficialDownload:!a.source,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)}),r.command("repair").description("Repair a Shennian runtime component").argument("[component]","Runtime component, currently only: helper","helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,force:!0,preferOfficialDownload:!a.source,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)})}function M(e={}){const r=S(e.platform);if(!r)return{ok:!1,installed:!1,repairable:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairSuggestion:c("unsupported_platform")};const o=e.env??process.env,a=e.homedir,n=R({platform:r,env:o,homedir:a,includeInstalledDesktop:!1}),i=b({platform:r,env:o,homedir:a});if(!n.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:q(n.reasonCode),reasonCode:n.reasonCode,message:n.message,runtimeRoot:i,repairSuggestion:c(n.reasonCode),checkedSources:k({platform:r,env:o,homedir:a})};const s=y({platform:r,helperDir:n.helperDir});if(!s.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:s.reasonCode,message:s.message,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,runtimeRoot:i,repairSuggestion:c(s.reasonCode),checkedSources:k({platform:r,env:o,homedir:a})};const l=A({platform:r,packageManifest:s.manifest,currentCliVersion:j(),helperVersion:n.version,protocolVersion:n.manifest.protocolVersion});return l.ok?{ok:!0,platform:r,targetPlatform:r,installed:!0,repairable:!1,message:`Shennian Helper runtime is installed: ${n.helperDir}`,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i}:{ok:!1,platform:r,targetPlatform:r,installed:!0,repairable:l.repairable,reasonCode:l.reasonCode,message:l.message,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i,repairSuggestion:c(l.reasonCode,s.manifest.minCliVersion),checkedSources:k({platform:r,env:o,homedir:a})}}function I(e={}){const r=S(e.platform);if(!r)return{ok:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairable:!1,repairSuggestion:c("unsupported_platform")};const o=e.env??process.env,a=X(e.io),n=e.homedir??a.homedir(),i=M({platform:r,env:o,homedir:n});if(i.ok&&!e.force&&i.helperDir&&i.helperPath&&i.helperVersion&&i.protocolVersion)return{ok:!0,action:"already_installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:re(r,i.helperDir),helperDir:i.helperDir,helperPath:i.helperPath,helperVersion:i.helperVersion,runtimeVersion:i.helperVersion,protocolVersion:i.protocolVersion,minCliVersion:i.minCliVersion,sha256:i.sha256,packageManifestPath:i.packageManifestPath,packageKind:i.packageKind,installTarget:i.installTarget,signature:i.signature,message:`Shennian Helper runtime is already installed: ${i.helperDir}`};const s=e.source?[t.resolve(e.source)]:k({platform:r,env:o,homedir:n}),l=s.map(w=>Q({candidate:w,platform:r,io:a})).find(w=>w!=null);if(!l)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:"helper_runtime_source_missing",message:"No installable Shennian Helper runtime package was found. Open Shennian Desktop, pass --source, or download the official helper package.",repairSuggestion:c("helper_runtime_source_missing"),checkedSources:s};const d=y({platform:r,manifestPath:l.packageManifestPath});if(!d.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:d.reasonCode,message:d.message,repairSuggestion:c(d.reasonCode),checkedSources:s};const g=A({platform:r,packageManifest:d.manifest,currentCliVersion:j()});if(!g.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:g.repairable,reasonCode:g.reasonCode,message:g.message,repairSuggestion:c(g.reasonCode,d.manifest.minCliVersion),checkedSources:s};const u=ee({platform:r,env:o,homedir:n,packageKind:l.packageKind});if(!u)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!1,reasonCode:"helper_runtime_target_unavailable",message:"Unable to determine Helper runtime install target for this platform.",repairSuggestion:c("helper_runtime_target_unavailable"),checkedSources:s};const v=a.existsSync(u);v&&x({platform:r,targetDir:u,io:a}),ne({platform:r,sourceDir:l.sourceDir,targetDir:u,io:a}),v&&x({platform:r,targetDir:u,io:a}),se({sourceManifestPath:l.packageManifestPath,targetManifestPath:l.packageManifestPathInTarget(u),io:a});const f=R({platform:r,baseDir:l.manifestDirInTarget(u),verifyIntegrity:!0});if(!f.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:f.reasonCode,message:`Installed Helper runtime could not be verified: ${f.message}`,repairSuggestion:c(f.reasonCode),checkedSources:s};le(r,f.helperPath,a);const p=y({platform:r,helperDir:f.helperDir});return p.ok?{ok:!0,action:"installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:u,helperDir:f.helperDir,helperPath:f.helperPath,helperVersion:f.version,runtimeVersion:f.version,protocolVersion:f.manifest.protocolVersion,minCliVersion:p.manifest.minCliVersion,sha256:p.manifest.sha256,packageManifestPath:p.manifestPath,packageKind:p.manifest.packageKind,installTarget:p.manifest.installTarget,signature:p.manifest.signature,message:`Installed Shennian Helper runtime to ${u}`}:{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:p.reasonCode,message:`Installed Helper runtime package manifest could not be verified: ${p.message}`,repairSuggestion:c(p.reasonCode),checkedSources:s}}async function P(e={}){const r=new F({lockPath:B(e),owner:"helper-runtime-install",defaultWaitMs:0});try{return await r.run("helper-runtime-install",()=>G(e))}catch(o){if(z(o)){const a=S(e.platform)??void 0;return{ok:!1,platform:a,targetPlatform:a,installed:!1,repairable:!0,reasonCode:"wechat_automation_busy",message:o instanceof Error?o.message:String(o),repairSuggestion:"Wait for the current WeChat automation run to finish, then retry Helper install or repair."}}throw o}}function B(e){const r=e.env?.SHENNIAN_HOME?.trim()||process.env.SHENNIAN_HOME?.trim(),o=r?t.resolve(r):t.join(e.homedir??C.homedir(),".shennian");return t.join(o,"runtime","wechat-automation.lock")}function z(e){return e instanceof Error?e.message.includes("wechat_automation_busy"):String(e).includes("wechat_automation_busy")}async function G(e={}){if(e.preferOfficialDownload&&!e.source&&e.officialDownload!==!1)return await O(e);const r=I(e);return r.ok||e.source||e.officialDownload===!1||!J(r.reasonCode)?r.ok?{...r,source:r.source??"local"}:r:await O(e,r)}async function O(e,r){const o=S(e.platform);if(!o)return r??{ok:!1,repairable:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairSuggestion:c("unsupported_platform")};const a=e.officialDownload===!1||e.officialDownload==null?{}:e.officialDownload,n=await W({...a,platform:o,env:e.env??process.env});if(!n.ok)return{ok:!1,platform:o,targetPlatform:o,installed:!1,repairable:!0,reasonCode:n.reasonCode,message:n.message,repairSuggestion:c(n.reasonCode),checkedSources:r?.checkedSources,officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}};try{const i=I({...e,source:n.sourceDir,platform:o,force:e.force??e.preferOfficialDownload??!1});return i.ok?{...i,source:"official-download",officialDownload:{channel:n.channel,manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl,artifactSha256:n.artifactSha256,artifactSizeBytes:n.artifactSizeBytes,arch:n.arch,helperVersion:n.helperVersion,protocolVersion:n.protocolVersion,minCliVersion:n.minCliVersion}}:{...i,reasonCode:i.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":i.reasonCode,message:i.reasonCode==="helper_runtime_source_missing"?"Official Helper runtime artifact did not contain an installable runtime package.":i.message,repairSuggestion:c(i.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":i.reasonCode),officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}}}finally{n.cleanup()}}function J(e){return e==="helper_runtime_source_missing"||e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid"}function S(e){const r=e??process.platform;return r==="darwin"||r==="win32"?r:null}function A(e){return e.packageManifest.platform!==e.platform?{ok:!1,reasonCode:"helper_runtime_platform_mismatch",message:`Helper runtime package platform ${e.packageManifest.platform} does not match ${e.platform}.`,repairable:!0}:e.helperVersion&&e.packageManifest.helperVersion!==e.helperVersion?{ok:!1,reasonCode:"helper_runtime_version_mismatch",message:`Helper runtime package version ${e.packageManifest.helperVersion} does not match installed helper ${e.helperVersion}.`,repairable:!0}:e.protocolVersion&&e.packageManifest.protocolVersion!==e.protocolVersion?{ok:!1,reasonCode:"helper_runtime_protocol_mismatch",message:`Helper runtime package protocol ${e.packageManifest.protocolVersion} does not match installed helper protocol ${e.protocolVersion}.`,repairable:!0}:K(e.currentCliVersion,e.packageManifest.minCliVersion)!=="none"?{ok:!1,reasonCode:"helper_runtime_cli_too_old",message:`Shennian CLI ${e.currentCliVersion} is older than required ${e.packageManifest.minCliVersion}.`,repairable:!1}:{ok:!0}}function q(e){return e!=="unsupported_platform"&&e!=="helper_runtime_cli_too_old"}function c(e,r){if(e==="unsupported_platform")return"Use Shennian Helper runtime on macOS or Windows.";if(e==="unsupported_runtime_component")return"Use `shennian runtime install helper` or `shennian runtime repair helper`.";if(e==="helper_runtime_cli_too_old")return`Upgrade Shennian CLI${r?` to ${r} or newer`:""}, then retry.`;if(e==="helper_runtime_target_unavailable")return"Set the current user home/LOCALAPPDATA correctly, then retry.";if(e==="helper_runtime_required")return"Open Shennian Desktop or use the \u4F7F\u7528\u5FAE\u4FE1 page to install Helper.";if(e==="helper_runtime_source_missing")return"Open Shennian Desktop, retry from the \u4F7F\u7528\u5FAE\u4FE1 page, or pass `--source <path>`.";if(e==="helper_runtime_manifest_unavailable")return"Check network access to Shennian official downloads, then retry from the \u4F7F\u7528\u5FAE\u4FE1 page.";if(e==="helper_runtime_artifact_unavailable")return"Upgrade Shennian CLI or wait for this platform Helper runtime to be published.";if(e==="helper_runtime_download_failed")return"Check network access to Shennian official downloads, then retry.";if(e==="helper_runtime_artifact_integrity_mismatch")return"Retry the official Helper runtime download; the downloaded package did not match the published hash.";if(e==="helper_runtime_artifact_invalid")return"Retry after Shennian republishes a valid Helper runtime package for this platform.";if(e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid")return"Reinstall or repair the official Shennian Helper runtime package.";if(e==="helper_runtime_platform_mismatch")return"Install the Helper runtime package for this platform.";if(e==="helper_runtime_version_mismatch"||e==="helper_runtime_protocol_mismatch")return"Run `shennian runtime repair helper` with the matching official Helper runtime package.";if(e==="manifest_missing"||e==="helper_missing"||e==="integrity_mismatch"||e==="helper_not_executable")return"Run `shennian runtime repair helper` or reinstall Shennian Desktop."}function D(e){return{ok:!1,repairable:!1,reasonCode:"unsupported_runtime_component",message:`Unsupported runtime component: ${e}. Supported component: helper.`,repairSuggestion:c("unsupported_runtime_component")}}function X(e){return{existsSync:e?.existsSync??m.existsSync,lstatSync:e?.lstatSync??m.lstatSync,readFileSync:e?.readFileSync??m.readFileSync,realpathSync:e?.realpathSync??m.realpathSync,mkdirSync:e?.mkdirSync??m.mkdirSync,rmSync:e?.rmSync??m.rmSync,cpSync:e?.cpSync??m.cpSync,renameSync:e?.renameSync??m.renameSync,chmodSync:e?.chmodSync??m.chmodSync,homedir:e?.homedir??C.homedir,stopMacHelperProcesses:e?.stopMacHelperProcesses??oe,stopWindowsHelperProcesses:e?.stopWindowsHelperProcesses??ie}}function Q(e){const r=t.resolve(e.candidate);return!e.io.existsSync(r)||ae(r,e.io)?null:e.platform==="darwin"?Y(r,e.io):Z(r,e.io)}function Y(e,r){const o=e.endsWith(".app")?e:t.join(e,"Shennian Helper.app");if(r.existsSync(t.join(o,"Contents","Resources","wechat-channel","macos","manifest.json")))return{sourceDir:o,packageKind:"macos-app",packageManifestPath:T(r,[t.join(o,"Contents","Resources","helper-runtime-package.json"),t.join(e,h)]),packageManifestPathInTarget:n=>t.join(n,"Contents","Resources",h),manifestDirInTarget:n=>t.join(n,"Contents","Resources","wechat-channel","macos")};const a=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","macos");return r.existsSync(t.join(a,"manifest.json"))?{sourceDir:a,packageKind:"asset-dir",packageManifestPath:t.join(a,"helper-runtime-package.json"),packageManifestPathInTarget:n=>t.join(n,h),manifestDirInTarget:n=>n}:null}function Z(e,r){const o=t.basename(e).toLowerCase()==="shennian helper"?e:t.join(e,"Shennian Helper");if(r.existsSync(t.join(o,"resources","wechat-channel","windows","manifest.json")))return{sourceDir:o,packageKind:"windows-runtime",packageManifestPath:T(r,[t.join(o,"resources",h),t.join(e,h)]),packageManifestPathInTarget:n=>t.join(n,"resources",h),manifestDirInTarget:n=>t.join(n,"resources","wechat-channel","windows")};const a=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","windows");return r.existsSync(t.join(a,"manifest.json"))?{sourceDir:a,packageKind:"asset-dir",packageManifestPath:t.join(a,"helper-runtime-package.json"),packageManifestPathInTarget:n=>t.join(n,h),manifestDirInTarget:n=>n}:null}function ee(e){const r=b(e);if(!r)return null;if(e.platform==="darwin")return e.packageKind==="macos-app"?t.join(r,"Shennian Helper.app"):t.join(r,"wechat-channel","macos");if(e.packageKind==="windows-runtime"){const o=e.env.LOCALAPPDATA||(e.homedir?t.join(e.homedir,"AppData","Local"):"");return o?t.join(o,"Programs","Shennian Helper"):null}return t.join(r,"wechat-channel","windows")}function re(e,r){const o=t.resolve(r);if(e==="darwin"){const n=`${t.sep}Contents${t.sep}Resources${t.sep}wechat-channel${t.sep}macos`;return o.endsWith(n)?o.slice(0,-n.length):o}const a=`${t.sep}resources${t.sep}wechat-channel${t.sep}windows`;return o.endsWith(a)?o.slice(0,-a.length):o}function ne(e){const r=t.resolve(e.sourceDir),o=t.resolve(e.targetDir);if(r===o)return;const a=E(r,e.io),n=E(o,e.io);if(a&&n&&a===n)return;const i=`${o}.tmp-${process.pid}-${Date.now()}`;e.io.rmSync(i,{recursive:!0,force:!0}),e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,i,{recursive:!0}),e.io.rmSync(o,{recursive:!0,force:!0}),e.io.renameSync(i,o)}function x(e){e.io.existsSync(e.targetDir)&&(e.platform==="darwin"&&e.io.stopMacHelperProcesses(e.targetDir),e.platform==="win32"&&e.io.stopWindowsHelperProcesses())}function ae(e,r){try{return r.lstatSync(e).isSymbolicLink()}catch{return!1}}function E(e,r){try{return r.realpathSync(e)}catch{return null}}function oe(e){if(process.platform!=="darwin")return;const r=t.join(t.resolve(e),"Contents","MacOS","Shennian Helper"),o=H("ps",["-axo","pid=,command="],{encoding:"utf8"});if(o.status!==0)return;const a=o.stdout.split(/\r?\n/u).map(n=>{const i=/^\s*(\d+)\s+(.+)$/u.exec(n);if(!i)return null;const s=Number(i[1]),l=i[2];return Number.isInteger(s)&&l.includes(r)?s:null}).filter(n=>!!(n&&n!==process.pid));for(const n of a)try{process.kill(n,"SIGTERM")}catch{}$(a,1e3);for(const n of a)if(U(n))try{process.kill(n,"SIGKILL")}catch{}$(a,500)}function $(e,r){const o=Date.now()+r;for(;Date.now()<o&&e.some(U);)te(50)}function te(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function U(e){try{return process.kill(e,0),!0}catch{return!1}}function ie(){if(process.platform!=="win32")return;const e=H("taskkill",["/IM","shennian-wechat-channel-helper.exe","/T","/F"],{stdio:"ignore",windowsHide:!0});if(e.status!==0&&e.status!==128)throw new Error(`taskkill shennian-wechat-channel-helper.exe exited ${e.status}`)}function se(e){const r=t.resolve(e.sourceManifestPath),o=t.resolve(e.targetManifestPath);!e.io.existsSync(r)||r===o||(e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,o))}function T(e,r){return r.find(o=>e.existsSync(o))??r[0]}function le(e,r,o){if(e==="darwin")try{const a=m.statSync(r);(a.mode&73)===0&&o.chmodSync(r,a.mode|493)}catch{}}function k(e){const r=e.homedir||(e.platform==="win32"?e.env.USERPROFILE:e.env.HOME),o=[],a=n=>{if(!n)return;const i=t.resolve(n);o.includes(i)||o.push(i)};if(a(e.env.SHENNIAN_HELPER_PACKAGE_DIR),a(e.env[N]),a(e.env[L]),e.platform==="darwin")r&&(a(t.join(r,"Applications","Shennian.app","Contents","Resources")),a(t.join(r,"Applications","Shennian Helper.app"))),a(t.join("/Applications","Shennian.app","Contents","Resources")),a(t.join("/Applications","Shennian Helper.app"));else{const n=e.env.LOCALAPPDATA||(r?t.join(r,"AppData","Local"):""),i=e.env.ProgramFiles||e.env.PROGRAMFILES,s=e.env["ProgramFiles(x86)"]||e.env["PROGRAMFILES(X86)"];n&&(a(t.join(n,"Programs","Shennian","resources")),a(t.join(n,"Programs","Shennian Helper"))),i&&(a(t.join(i,"Shennian","resources")),a(t.join(i,"Shennian Helper"))),s&&(a(t.join(s,"Shennian","resources")),a(t.join(s,"Shennian Helper")))}return a(t.resolve(process.cwd(),"packages/helper-runtime/dist",e.platform==="darwin"?"macos":"windows")),a(t.resolve(process.cwd(),"packages/helper-runtime/wechat-channel",e.platform==="darwin"?"macos":"windows")),o}function _(e,r){if(r){console.log(JSON.stringify(e,null,2));return}if(e.ok){console.log(V.green(`\u2713 ${e.message}`)),"helperVersion"in e&&console.log(`version=${e.helperVersion} protocol=${e.protocolVersion}`),"helperPath"in e&&console.log(e.helperPath);return}console.error(V.red(`\u2717 ${e.reasonCode}`)),console.error(e.message)}export{M as getHelperRuntimeStatus,I as installHelperRuntime,P as installHelperRuntimeWithOfficialDownload,ke as registerRuntimeCommand};
|
package/dist/src/config/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import r from"node:fs";import
|
|
1
|
+
import r from"node:fs";import e from"node:path";import s from"node:os";function t(){const n=process.env.SHENNIAN_HOME?.trim();return n?e.resolve(n):u()?e.join(s.tmpdir(),"shennian-vitest-runtime",String(process.pid)):e.join(s.homedir(),".shennian")}function c(...n){return e.join(t(),...n)}function o(){return c("config.json")}const h=o();function S(){try{const n=o();if(!r.existsSync(n))return{};const i=JSON.parse(f(r.readFileSync(n,"utf-8")));return i.serverUrl?.includes("shennian.ai")&&(i.serverUrl="https://shennian.net"),i}catch{return{}}}function l(n){r.mkdirSync(t(),{recursive:!0}),r.writeFileSync(o(),JSON.stringify(n,null,2))}function v(){r.mkdirSync(t(),{recursive:!0}),r.mkdirSync(c("sessions"),{recursive:!0})}function u(){return(process.env.VITEST==="true"||!!process.env.VITEST_WORKER_ID)&&!process.env.SHENNIAN_HOME?.trim()}function f(n){return n.charCodeAt(0)===65279?n.slice(1):n}export{h as configPath,v as ensureDir,o as getConfigPath,t as getShennianDir,S as loadConfig,c as resolveShennianPath,l as saveConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadConfig as d}from"../../config/index.js";import{getHelperRuntimeStatus as p,installHelperRuntimeWithOfficialDownload as h}from"../../commands/runtime.js";import{createWeChatChannelApiClient as w}from"../../channels/wechat-channel/client.js";import{WECHAT_CHANNEL_HELPER_VERSION as g}from"../../channels/wechat-channel/helper-assets.js";import{WeChatChannelHelperClient as y}from"../../channels/wechat-channel/helper-client.js";import{requiredWeChatChannelHelperCapabilitiesForProfile as R}from"../../channels/wechat-channel/helper-protocol.js";import{createWeChatChannelRuntime as V}from"../../channels/wechat-channel/runtime.js";import{getCurrentVersion as b}from"../../upgrade/engine.js";async function I(e,o){const
|
|
1
|
+
import{loadConfig as d}from"../../config/index.js";import{getHelperRuntimeStatus as p,installHelperRuntimeWithOfficialDownload as h}from"../../commands/runtime.js";import{createWeChatChannelApiClient as w}from"../../channels/wechat-channel/client.js";import{WECHAT_CHANNEL_HELPER_VERSION as g}from"../../channels/wechat-channel/helper-assets.js";import{WeChatChannelHelperClient as y}from"../../channels/wechat-channel/helper-client.js";import{requiredWeChatChannelHelperCapabilitiesForProfile as R}from"../../channels/wechat-channel/helper-protocol.js";import{createWeChatChannelRuntime as V}from"../../channels/wechat-channel/runtime.js";import{getCurrentVersion as b}from"../../upgrade/engine.js";async function I(e,o){const r=o.params??{},t=k(r.action);if(!t){e.client.sendRes({type:"res",id:o.id,ok:!1,error:'action must be "status", "install", "upgrade", or "repair"'});return}const n=typeof r.platform=="string"?r.platform:void 0,i=typeof r.source=="string"&&r.source.trim()?r.source:void 0,a=typeof r.channel=="string"&&r.channel.trim()?r.channel:void 0,c=typeof r.manifestUrl=="string"&&r.manifestUrl.trim()?r.manifestUrl:void 0,u=await C({action:t,platform:n,source:i,channel:a,manifestUrl:c});e.client.sendRes({type:"res",id:o.id,ok:!0,payload:u})}async function C(e){if(e.action==="status"){const i=p({platform:e.platform}),a=e.probePermissions===!1?void 0:await f(i),c=await m(i,a);return{action:e.action,status:i,permissions:a,projection:c}}const o=await h({source:e.source,platform:e.platform,force:e.action==="upgrade"||e.action==="repair",preferOfficialDownload:(e.action==="upgrade"||e.action==="repair")&&!e.source,officialDownload:{channel:e.channel,manifestUrl:e.manifestUrl}}),r=p({platform:e.platform}),t=e.probePermissions===!1?void 0:await f(r),n=await m(r,t);return{action:e.action,install:o,status:r,permissions:t,projection:n}}function k(e){return e==="status"||e==="install"||e==="upgrade"||e==="repair"?e:null}async function f(e){const o=new Date().toISOString();if(!e.ok||!e.helperPath)return{checkedAt:o,helperReady:!1,helperVersion:e.helperVersion??null,protocolVersion:e.protocolVersion??null,platform:e.platform};const r=new y({helperPath:e.helperPath,expectedHelperVersion:e.helperVersion||g,requiredCapabilities:R("send")});try{await r.start();const t=await r.request("permissions.check",{},`helper-runtime-status-${Date.now()}`),n=t.ok&&t.result&&typeof t.result=="object"?t.result:{};return{checkedAt:o,helperReady:t.ok,helperVersion:e.helperVersion??H(n.helperVersion),protocolVersion:e.protocolVersion??A(n.protocolVersion),platform:e.platform,screenRecording:l(n.screenRecording),accessibility:l(n.accessibility),inputMonitoring:l(n.inputMonitoring),automation:l(n.automation),wechatRunning:s(n.wechatRunning),wechatAppDetected:s(n.wechatAppDetected??n.wechatRunning),wechatWindowAvailable:s(n.wechatWindowAvailable)}}catch{return{checkedAt:o,helperReady:!1,helperVersion:e.helperVersion??null,protocolVersion:e.protocolVersion??null,platform:e.platform}}finally{await r.stop().catch(()=>{})}}async function m(e,o){if(!o||e.platform!=="darwin"&&e.platform!=="win32")return;const r=d(),t=r.machineId?.trim(),n=r.machineToken?.trim();if(!t||!n)return{ok:!1,error:"machine_not_paired"};try{const i=V({runtimeId:`wechat-machine:${t}`,machineId:t,platform:e.platform,bindings:[]});return await w({serverUrl:r.serverUrl,machineToken:n}).upsertRuntime(i,void 0,{helperVersion:e.helperVersion??void 0,clientRuntimeVersion:b(),preflight:o}),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}function l(e){return typeof e=="boolean"?e:"unknown"}function s(e){return typeof e=="boolean"?e:void 0}function H(e){return(typeof e=="string"?e.trim():"")||null}function A(e){const o=Number(e);return Number.isFinite(o)?o:null}export{I as handleWeChatHelperRuntime,C as runHelperRuntimeAction};
|