shennian 0.2.120 → 0.2.121
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 +10 -10
- 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
|
@@ -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": 39493,
|
|
395
|
+
"afterBytes": 21665
|
|
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",
|
|
@@ -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 v from"node:os";import t from"node:path";import{spawnSync as C}from"node:child_process";import H from"chalk";import{getDefaultWeChatHelperRuntimeRoot as V,readWeChatChannelHelperRuntimePackageManifest as y,resolveWeChatChannelHelperAsset as b,SHENNIAN_HELPER_RUNTIME_DIR_ENV as U,WECHAT_CHANNEL_HELPER_DIR_ENV as T}from"../channels/wechat-channel/helper-assets.js";import{downloadOfficialHelperRuntimePackage as L}from"./helper-runtime-official-download.js";import{compareVersions as N,getCurrentVersion as j}from"../upgrade/engine.js";import{SerialWeChatAutomationLane as W}from"../channels/wechat-channel/automation-lane.js";const u="helper-runtime-package.json";function ge(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=R({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 R(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:c("unsupported_platform")};const o=e.env??process.env,a=e.homedir,n=b({platform:r,env:o,homedir:a,includeInstalledDesktop:!1}),i=V({platform:r,env:o,homedir:a});if(!n.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:G(n.reasonCode),reasonCode:n.reasonCode,message:n.message,runtimeRoot:i,repairSuggestion:c(n.reasonCode),checkedSources:S({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:S({platform:r,env:o,homedir:a})};const l=O({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:S({platform:r,env:o,homedir:a})}}function M(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:c("unsupported_platform")};const o=e.env??process.env,a=J(e.io),n=e.homedir??a.homedir(),i=R({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:Z(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)]:S({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 h=y({platform:r,manifestPath:l.packageManifestPath});if(!h.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:h.reasonCode,message:h.message,repairSuggestion:c(h.reasonCode),checkedSources:s};const g=O({platform:r,packageManifest:h.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,h.manifest.minCliVersion),checkedSources:s};const d=Y({platform:r,env:o,homedir:n,packageKind:l.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:c("helper_runtime_target_unavailable"),checkedSources:s};ee({platform:r,sourceDir:l.sourceDir,targetDir:d,io:a}),te({sourceManifestPath:l.packageManifestPath,targetManifestPath:l.packageManifestPathInTarget(d),io:a});const f=b({platform:r,baseDir:l.manifestDirInTarget(d),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};ie(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:d,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 ${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:c(p.reasonCode),checkedSources:s}}async function P(e={}){const r=new W({lockPath:K(e),owner:"helper-runtime-install",defaultWaitMs:0});try{return await r.run("helper-runtime-install",()=>B(e))}catch(o){if(F(o)){const a=k(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 K(e){const r=e.env?.SHENNIAN_HOME?.trim()||process.env.SHENNIAN_HOME?.trim(),o=r?t.resolve(r):t.join(e.homedir??v.homedir(),".shennian");return t.join(o,"runtime","wechat-automation.lock")}function F(e){return e instanceof Error?e.message.includes("wechat_automation_busy"):String(e).includes("wechat_automation_busy")}async function B(e={}){if(e.preferOfficialDownload&&!e.source&&e.officialDownload!==!1)return await I(e);const r=M(e);return r.ok||e.source||e.officialDownload===!1||!z(r.reasonCode)?r.ok?{...r,source:r.source??"local"}:r:await I(e,r)}async function I(e,r){const o=k(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 L({...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=M({...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 z(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 O(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}:N(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 G(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 J(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??v.homedir,stopMacHelperProcesses:e?.stopMacHelperProcesses??ne,stopWindowsHelperProcesses:e?.stopWindowsHelperProcesses??oe}}function q(e){const r=t.resolve(e.candidate);return!e.io.existsSync(r)||re(r,e.io)?null:e.platform==="darwin"?X(r,e.io):Q(r,e.io)}function X(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:$(r,[t.join(o,"Contents","Resources","helper-runtime-package.json"),t.join(e,u)]),packageManifestPathInTarget:n=>t.join(n,"Contents","Resources",u),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,u),manifestDirInTarget:n=>n}:null}function Q(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:$(r,[t.join(o,"resources",u),t.join(e,u)]),packageManifestPathInTarget:n=>t.join(n,"resources",u),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,u),manifestDirInTarget:n=>n}:null}function Y(e){const r=V(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 Z(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 ee(e){const r=t.resolve(e.sourceDir),o=t.resolve(e.targetDir);if(r===o)return;const a=A(r,e.io),n=A(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.platform==="darwin"&&e.io.stopMacHelperProcesses(o),e.platform==="win32"&&e.io.stopWindowsHelperProcesses(),e.io.rmSync(o,{recursive:!0,force:!0}),e.io.renameSync(i,o)}function re(e,r){try{return r.lstatSync(e).isSymbolicLink()}catch{return!1}}function A(e,r){try{return r.realpathSync(e)}catch{return null}}function ne(e){if(process.platform!=="darwin")return;const r=t.join(t.resolve(e),"Contents","MacOS","Shennian Helper"),o=C("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{}x(a,1e3);for(const n of a)if(E(n))try{process.kill(n,"SIGKILL")}catch{}x(a,500)}function x(e,r){const o=Date.now()+r;for(;Date.now()<o&&e.some(E);)ae(50)}function ae(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function E(e){try{return process.kill(e,0),!0}catch{return!1}}function oe(){if(process.platform!=="win32")return;const e=C("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 te(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 $(e,r){return r.find(o=>e.existsSync(o))??r[0]}function ie(e,r,o){if(e==="darwin")try{const a=m.statSync(r);(a.mode&73)===0&&o.chmodSync(r,a.mode|493)}catch{}}function S(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[T]),a(e.env[U]),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(H.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(H.red(`\u2717 ${e.reasonCode}`)),console.error(e.message)}export{R as getHelperRuntimeStatus,M as installHelperRuntime,P as installHelperRuntimeWithOfficialDownload,ge 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};
|