mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-10 23:23:29 +08:00
feat(weixin): native official runner and OSS install docs
Default Weixin to official native runner, add /weixin/native/reply host endpoint, and harden gateway stop to clean stale port listeners. Document open-source installation flow for gateway + Personal WeChat. Made-with: Cursor
This commit is contained in:
parent
31e3962c74
commit
88b1fdc9d3
12 changed files with 823 additions and 42 deletions
|
|
@ -37,9 +37,15 @@ if (Test-Path $pidFile) {
|
|||
$ok = Kill-ProcId -procId $procId
|
||||
if ($ok) {
|
||||
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
|
||||
exit 0
|
||||
# Keep going to also clean up any orphan listeners on $Port.
|
||||
} else {
|
||||
# Stale pid file is common after crashes; fall back to stop-by-port.
|
||||
if ($Force) {
|
||||
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
|
||||
} else {
|
||||
Warn "PID file kill failed; falling back to stop-by-port. Re-run with -Force to also clear pid file."
|
||||
}
|
||||
}
|
||||
if (-not $Force) { exit 1 }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,11 +15,27 @@ function Resolve-RepoRoot {
|
|||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$stateDir = Join-Path $sidecarRoot "state"
|
||||
$pluginRoot = Join-Path $env:USERPROFILE ".openclaw\\extensions\\openclaw-weixin"
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $sidecarRoot | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $sidecarRoot "logs") | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path $stateDir | Out-Null
|
||||
|
||||
function Ensure-OfficialPluginRuntimeDeps {
|
||||
if (-not (Test-Path (Join-Path $pluginRoot "package.json"))) {
|
||||
throw "official plugin root not found at $pluginRoot"
|
||||
}
|
||||
Push-Location $pluginRoot
|
||||
try {
|
||||
npm.cmd install openclaw@latest --no-save
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "npm install official plugin runtime deps failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
if ($UseOpenclawCli) {
|
||||
$openclawCmd = Get-Command openclaw -ErrorAction SilentlyContinue
|
||||
if (-not $openclawCmd) {
|
||||
|
|
@ -29,6 +45,7 @@ if ($UseOpenclawCli) {
|
|||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "openclaw-weixin-cli install failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
Ensure-OfficialPluginRuntimeDeps
|
||||
Push-Location $sidecarRoot
|
||||
try {
|
||||
if (-not (Test-Path (Join-Path $sidecarRoot "package.json"))) {
|
||||
|
|
@ -37,17 +54,18 @@ if ($UseOpenclawCli) {
|
|||
throw "npm init failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
npm.cmd install --save-exact tsx@4.21.0 typescript@6.0.3
|
||||
npm.cmd install openclaw@latest --save tsx@4.21.0 typescript@6.0.3
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "npm install bridge runtime deps failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
$bridgeSrc = Join-Path $oclawRoot "runtime\\operations\\weixin_bridge"
|
||||
Copy-Item -Path (Join-Path $bridgeSrc "runner.ts") -Destination (Join-Path $sidecarRoot "runner.ts") -Force
|
||||
Copy-Item -Path (Join-Path $bridgeSrc "official_runner.ts") -Destination (Join-Path $sidecarRoot "official_runner.ts") -Force
|
||||
Copy-Item -Path (Join-Path $bridgeSrc "login.ts") -Destination (Join-Path $sidecarRoot "login.ts") -Force
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Write-Host "[ok] installed official openclaw-weixin plugin + local bridge runtime"
|
||||
Write-Host "[ok] installed official openclaw-weixin plugin + native/fallback sidecar runtime"
|
||||
exit 0
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,12 +16,18 @@ $sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
|||
$stateDir = Join-Path $sidecarRoot "state"
|
||||
$logDir = Join-Path $sidecarRoot "logs"
|
||||
$pidFile = Join-Path $sidecarRoot "pid.txt"
|
||||
$bridgeSrc = Join-Path $oclawRoot "runtime\\operations\\weixin_bridge"
|
||||
$pluginRoot = Join-Path $env:USERPROFILE ".openclaw\\extensions\\openclaw-weixin"
|
||||
$runnerMode = [string]($env:AIA_WEIXIN_RUNNER_MODE)
|
||||
if (-not $runnerMode) { $runnerMode = "official" }
|
||||
$runnerMode = $runnerMode.Trim().ToLowerInvariant()
|
||||
|
||||
function Get-SidecarProcesses {
|
||||
$escapedSidecarRoot = $sidecarRoot.Replace("\", "\\")
|
||||
$patterns = @(
|
||||
"*$ChannelId*",
|
||||
"*runner.ts*",
|
||||
"*official_runner.ts*",
|
||||
"*$escapedSidecarRoot*"
|
||||
)
|
||||
Get-CimInstance Win32_Process | Where-Object {
|
||||
|
|
@ -46,38 +52,21 @@ function Stop-SidecarProcesses {
|
|||
return $procs.Count
|
||||
}
|
||||
|
||||
function Set-OfficialWeixinBaseUrl([string]$BaseUrl) {
|
||||
$weixinRoot = Join-Path $env:USERPROFILE ".openclaw\\openclaw-weixin"
|
||||
$accountsListPath = Join-Path $weixinRoot "accounts.json"
|
||||
if (-not (Test-Path $accountsListPath)) {
|
||||
Write-Host "[warn] official mode: accounts.json not found, skip baseUrl rewrite"
|
||||
function Ensure-OfficialPluginRuntimeDeps {
|
||||
if (-not (Test-Path (Join-Path $pluginRoot "package.json"))) {
|
||||
throw "official plugin root not found at $pluginRoot"
|
||||
}
|
||||
if (Test-Path (Join-Path $pluginRoot "node_modules\\openclaw\\package.json")) {
|
||||
return
|
||||
}
|
||||
$ids = @()
|
||||
Push-Location $pluginRoot
|
||||
try {
|
||||
$parsed = Get-Content -Path $accountsListPath -Raw | ConvertFrom-Json
|
||||
if ($parsed -is [System.Array]) {
|
||||
$ids = @($parsed)
|
||||
}
|
||||
} catch {
|
||||
Write-Host "[warn] official mode: failed to parse accounts.json"
|
||||
return
|
||||
}
|
||||
foreach ($aid in $ids) {
|
||||
$idText = [string]$aid
|
||||
if (-not $idText) { continue }
|
||||
$accPath = Join-Path (Join-Path $weixinRoot "accounts") "$idText.json"
|
||||
if (-not (Test-Path $accPath)) { continue }
|
||||
try {
|
||||
$obj = Get-Content -Path $accPath -Raw | ConvertFrom-Json
|
||||
$obj.baseUrl = $BaseUrl
|
||||
$json = $obj | ConvertTo-Json -Depth 8
|
||||
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
||||
[System.IO.File]::WriteAllText($accPath, $json + "`n", $utf8NoBom)
|
||||
Write-Host "[ok] official mode: set baseUrl for $idText -> $BaseUrl"
|
||||
} catch {
|
||||
Write-Host "[warn] official mode: failed to rewrite $accPath"
|
||||
npm.cmd install openclaw@latest --no-save
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "npm install official plugin runtime deps failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -90,17 +79,36 @@ New-Item -ItemType Directory -Force -Path $stateDir | Out-Null
|
|||
$cleaned = Stop-SidecarProcesses
|
||||
Remove-Item -Force $pidFile -ErrorAction SilentlyContinue
|
||||
|
||||
if (Test-Path $bridgeSrc) {
|
||||
foreach ($name in @("runner.ts", "official_runner.ts", "login.ts")) {
|
||||
$srcPath = Join-Path $bridgeSrc $name
|
||||
if (Test-Path $srcPath) {
|
||||
Copy-Item -Path $srcPath -Destination (Join-Path $sidecarRoot $name) -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$logPath = Join-Path $logDir "weixin_sidecar.log"
|
||||
$errPath = Join-Path $logDir "weixin_sidecar.err.log"
|
||||
if (Test-Path (Join-Path $sidecarRoot "runner.ts")) {
|
||||
if ((Test-Path (Join-Path $sidecarRoot "runner.ts")) -or (Test-Path (Join-Path $sidecarRoot "official_runner.ts"))) {
|
||||
$runnerFile = "official_runner.ts"
|
||||
if ($runnerMode -eq "legacy") {
|
||||
$runnerFile = "runner.ts"
|
||||
}
|
||||
if ($runnerMode -eq "official") {
|
||||
Ensure-OfficialPluginRuntimeDeps
|
||||
}
|
||||
if (-not (Test-Path (Join-Path $sidecarRoot $runnerFile))) {
|
||||
throw "selected runner file missing: $runnerFile"
|
||||
}
|
||||
$cmd = "cmd.exe"
|
||||
$args = @(
|
||||
"/c",
|
||||
"cd /d $sidecarRoot && set OCLAW_STATE_DIR=$stateDir&& set AIA_GATEWAY_BASE_URL=$GatewayBaseUrl&& npm.cmd exec -- tsx runner.ts"
|
||||
"cd /d $sidecarRoot && set OCLAW_STATE_DIR=$stateDir&& set AIA_GATEWAY_BASE_URL=$GatewayBaseUrl&& set NODE_PATH=$sidecarRoot\node_modules&& npm.cmd exec -- tsx $runnerFile"
|
||||
)
|
||||
$p = Start-Process -FilePath $cmd -ArgumentList $args -WorkingDirectory $sidecarRoot -PassThru -WindowStyle Hidden -RedirectStandardOutput $logPath -RedirectStandardError $errPath
|
||||
Set-Content -Path $pidFile -Value $p.Id
|
||||
Write-Host "[ok] started weixin sidecar pid=$($p.Id) cleaned=$cleaned out=$logPath err=$errPath"
|
||||
Write-Host "[ok] started weixin sidecar pid=$($p.Id) mode=$runnerMode cleaned=$cleaned out=$logPath err=$errPath"
|
||||
exit 0
|
||||
}
|
||||
|
||||
|
|
@ -113,9 +121,8 @@ $systemNodeDir = "C:\\Program Files\\nodejs"
|
|||
if (Test-Path (Join-Path $systemNodeDir "node.exe")) {
|
||||
$env:PATH = "$systemNodeDir;$env:PATH"
|
||||
}
|
||||
Set-OfficialWeixinBaseUrl -BaseUrl $GatewayBaseUrl
|
||||
$args = @("/c", "openclaw gateway --allow-unconfigured")
|
||||
$p = Start-Process -FilePath "cmd.exe" -ArgumentList $args -WorkingDirectory $oclawRoot -PassThru -WindowStyle Hidden -RedirectStandardOutput $logPath -RedirectStandardError $errPath
|
||||
Set-Content -Path $pidFile -Value $p.Id
|
||||
Write-Host "[ok] started openclaw gateway bridge pid=$($p.Id) cleaned=$cleaned out=$logPath err=$errPath"
|
||||
Write-Host "[ok] started openclaw gateway pid=$($p.Id) cleaned=$cleaned out=$logPath err=$errPath"
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ function Get-SidecarProcesses {
|
|||
$patterns = @(
|
||||
"*$ChannelId*",
|
||||
"*runner.ts*",
|
||||
"*official_runner.ts*",
|
||||
"*$escapedSidecarRoot*"
|
||||
)
|
||||
Get-CimInstance Win32_Process | Where-Object {
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ function Get-SidecarProcesses {
|
|||
$patterns = @(
|
||||
"*$ChannelId*",
|
||||
"*runner.ts*",
|
||||
"*official_runner.ts*",
|
||||
"*$escapedSidecarRoot*"
|
||||
)
|
||||
Get-CimInstance Win32_Process | Where-Object {
|
||||
|
|
|
|||
430
runtime/operations/weixin_bridge/official_runner.ts
Normal file
430
runtime/operations/weixin_bridge/official_runner.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
type TokenMap = Record<string, string>;
|
||||
|
||||
const LOCAL_BASE_URL = (process.env.AIA_GATEWAY_BASE_URL || "http://127.0.0.1:8787").trim();
|
||||
const STATE_DIR = (process.env.OCLAW_STATE_DIR || path.resolve(process.cwd(), "state")).trim();
|
||||
const STATE_FILE = path.join(STATE_DIR, "official_bridge_state.json");
|
||||
const POLL_TIMEOUT_MS = 35_000;
|
||||
const DEFAULT_CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c";
|
||||
|
||||
type OfficialModules = {
|
||||
getUpdates: (params: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
get_updates_buf?: string;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<Json>;
|
||||
setContextToken: (accountId: string, userId: string, token: string) => void;
|
||||
getContextToken: (accountId: string, userId: string) => string | undefined;
|
||||
restoreContextTokens: (accountId: string) => void;
|
||||
weixinMessageToMsgContext: (msg: Json, accountId: string, opts?: Json) => Json;
|
||||
downloadMediaFromItem: (
|
||||
item: Json,
|
||||
deps: {
|
||||
cdnBaseUrl: string;
|
||||
saveMedia: (
|
||||
buffer: Buffer,
|
||||
contentType?: string,
|
||||
subdir?: string,
|
||||
maxBytes?: number,
|
||||
originalFilename?: string,
|
||||
) => Promise<{ path: string }>;
|
||||
log: (msg: string) => void;
|
||||
errLog: (msg: string) => void;
|
||||
label: string;
|
||||
},
|
||||
) => Promise<Json>;
|
||||
sendMessageWeixin: (params: {
|
||||
to: string;
|
||||
text: string;
|
||||
opts: { baseUrl: string; token?: string; contextToken?: string };
|
||||
}) => Promise<{ messageId: string }>;
|
||||
sendWeixinMediaFile: (params: {
|
||||
filePath: string;
|
||||
to: string;
|
||||
text: string;
|
||||
opts: { baseUrl: string; token?: string; contextToken?: string };
|
||||
cdnBaseUrl: string;
|
||||
}) => Promise<{ messageId: string }>;
|
||||
};
|
||||
|
||||
let officialModulesPromise: Promise<OfficialModules> | null = null;
|
||||
|
||||
class HttpStatusError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "HttpStatusError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function log(msg: string): void {
|
||||
process.stdout.write(`${new Date().toISOString()} [official-weixin] ${msg}\n`);
|
||||
}
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
function readJsonFile<T>(p: string): T | null {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(p, "utf8")) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeJsonFile(p: string, obj: unknown): void {
|
||||
fs.writeFileSync(p, JSON.stringify(obj, null, 2) + "\n", "utf8");
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function homeOpenclawPath(...parts: string[]): string {
|
||||
return path.join(os.homedir(), ".openclaw", ...parts);
|
||||
}
|
||||
|
||||
function resolvePluginRoot(): string {
|
||||
const configured = String(process.env.OCLAW_WEIXIN_PLUGIN_ROOT || "").trim();
|
||||
return configured || homeOpenclawPath("extensions", "openclaw-weixin");
|
||||
}
|
||||
|
||||
async function loadOfficialModules(): Promise<OfficialModules> {
|
||||
if (officialModulesPromise) {
|
||||
return officialModulesPromise;
|
||||
}
|
||||
officialModulesPromise = (async () => {
|
||||
const pluginRoot = resolvePluginRoot();
|
||||
const srcRoot = path.join(pluginRoot, "src");
|
||||
const importTs = async (relativePath: string): Promise<any> => {
|
||||
const fullPath = path.join(srcRoot, relativePath);
|
||||
return import(pathToFileURL(fullPath).href);
|
||||
};
|
||||
const [apiMod, inboundMod, mediaMod, sendMod, sendMediaMod] = await Promise.all([
|
||||
importTs(path.join("api", "api.ts")),
|
||||
importTs(path.join("messaging", "inbound.ts")),
|
||||
importTs(path.join("media", "media-download.ts")),
|
||||
importTs(path.join("messaging", "send.ts")),
|
||||
importTs(path.join("messaging", "send-media.ts")),
|
||||
]);
|
||||
return {
|
||||
getUpdates: apiMod.getUpdates,
|
||||
setContextToken: inboundMod.setContextToken,
|
||||
getContextToken: inboundMod.getContextToken,
|
||||
restoreContextTokens: inboundMod.restoreContextTokens,
|
||||
weixinMessageToMsgContext: inboundMod.weixinMessageToMsgContext,
|
||||
downloadMediaFromItem: mediaMod.downloadMediaFromItem,
|
||||
sendMessageWeixin: sendMod.sendMessageWeixin,
|
||||
sendWeixinMediaFile: sendMediaMod.sendWeixinMediaFile,
|
||||
} satisfies OfficialModules;
|
||||
})();
|
||||
return officialModulesPromise;
|
||||
}
|
||||
|
||||
function resolveAccount(): { accountId: string; token: string; cloudBaseUrl: string } {
|
||||
const ids = readJsonFile<string[]>(homeOpenclawPath("openclaw-weixin", "accounts.json")) || [];
|
||||
const accountId = String(ids[0] || "").trim();
|
||||
if (!accountId) {
|
||||
throw new Error("no weixin account id found; run login first");
|
||||
}
|
||||
const account = readJsonFile<Json>(homeOpenclawPath("openclaw-weixin", "accounts", `${accountId}.json`)) || {};
|
||||
const token = String(account.token || "").trim();
|
||||
if (!token) {
|
||||
throw new Error(`missing token for account ${accountId}; run login again`);
|
||||
}
|
||||
const envCloud = String(process.env.OCLAW_WEIXIN_CLOUD_BASE_URL || "").trim();
|
||||
const cfgCloud = String(account.baseUrl || "").trim();
|
||||
const cloudBaseUrl = (envCloud || cfgCloud || "https://ilinkai.weixin.qq.com").trim();
|
||||
return { accountId, token, cloudBaseUrl };
|
||||
}
|
||||
|
||||
function resolveHeaders(token: string): Record<string, string> {
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
AuthorizationType: "ilink_bot_token",
|
||||
Authorization: `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function postNativeReply(token: string, body: Json): Promise<Json> {
|
||||
const url = `${LOCAL_BASE_URL.replace(/\/+$/, "")}/weixin/native/reply`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: resolveHeaders(token),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) {
|
||||
throw new HttpStatusError(res.status, `native reply ${res.status}: ${text.slice(0, 300)}`);
|
||||
}
|
||||
return text ? (JSON.parse(text) as Json) : {};
|
||||
}
|
||||
|
||||
async function safeSendNativeFailureNotice(modules: OfficialModules, params: {
|
||||
to: string;
|
||||
cloudBaseUrl: string;
|
||||
token: string;
|
||||
contextToken?: string;
|
||||
err: unknown;
|
||||
}): Promise<void> {
|
||||
const msg = `[weixin] native reply failed: ${String(params.err)}`.slice(0, 3500);
|
||||
try {
|
||||
await modules.sendMessageWeixin({
|
||||
to: params.to,
|
||||
text: msg,
|
||||
opts: {
|
||||
baseUrl: params.cloudBaseUrl,
|
||||
token: params.token,
|
||||
contextToken: params.contextToken,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
|
||||
function inferExtension(contentType: string, originalFilename: string): string {
|
||||
const explicit = path.extname(originalFilename || "").trim();
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
const low = (contentType || "").toLowerCase();
|
||||
if (low.includes("jpeg")) return ".jpg";
|
||||
if (low.includes("png")) return ".png";
|
||||
if (low.includes("gif")) return ".gif";
|
||||
if (low.includes("webp")) return ".webp";
|
||||
if (low.includes("mp4")) return ".mp4";
|
||||
if (low.includes("wav")) return ".wav";
|
||||
if (low.includes("pdf")) return ".pdf";
|
||||
if (low.includes("text/plain")) return ".txt";
|
||||
return ".bin";
|
||||
}
|
||||
|
||||
async function saveMediaBuffer(
|
||||
buffer: Buffer,
|
||||
contentType?: string,
|
||||
subdir?: string,
|
||||
maxBytes?: number,
|
||||
originalFilename?: string,
|
||||
): Promise<{ path: string }> {
|
||||
if (typeof maxBytes === "number" && maxBytes > 0 && buffer.length > maxBytes) {
|
||||
throw new Error(`media exceeds max bytes: ${buffer.length} > ${maxBytes}`);
|
||||
}
|
||||
const dir = path.join(STATE_DIR, "media", subdir || "inbound");
|
||||
ensureDir(dir);
|
||||
const filePath = path.join(
|
||||
dir,
|
||||
`${Date.now()}-${Math.random().toString(16).slice(2, 10)}${inferExtension(contentType || "", originalFilename || "")}`,
|
||||
);
|
||||
await fs.promises.writeFile(filePath, buffer);
|
||||
return { path: filePath };
|
||||
}
|
||||
|
||||
function pickDownloadableMedia(msg: Json): Json | null {
|
||||
const items = Array.isArray(msg.item_list) ? (msg.item_list as Json[]) : [];
|
||||
const hasDownloadableMedia = (item: Json, kind: string): boolean => {
|
||||
const media = item[kind] && typeof item[kind] === "object" ? (item[kind] as Json).media : null;
|
||||
if (!media || typeof media !== "object") return false;
|
||||
return Boolean((media as Json).encrypt_query_param || (media as Json).full_url);
|
||||
};
|
||||
const direct =
|
||||
items.find((item) => Number(item.type || 0) === 3 && hasDownloadableMedia(item, "image_item")) ||
|
||||
items.find((item) => Number(item.type || 0) === 4 && hasDownloadableMedia(item, "video_item")) ||
|
||||
items.find((item) => Number(item.type || 0) === 5 && hasDownloadableMedia(item, "file_item")) ||
|
||||
items.find((item) => Number(item.type || 0) === 2 && hasDownloadableMedia(item, "voice_item"));
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (Number(item.type || 0) !== 1) continue;
|
||||
const refMsg = item.ref_msg;
|
||||
if (!refMsg || typeof refMsg !== "object") continue;
|
||||
const messageItem = (refMsg as Json).message_item;
|
||||
if (!messageItem || typeof messageItem !== "object") continue;
|
||||
const ref = messageItem as Json;
|
||||
if (
|
||||
(Number(ref.type || 0) === 3 && hasDownloadableMedia(ref, "image_item")) ||
|
||||
(Number(ref.type || 0) === 4 && hasDownloadableMedia(ref, "video_item")) ||
|
||||
(Number(ref.type || 0) === 5 && hasDownloadableMedia(ref, "file_item")) ||
|
||||
(Number(ref.type || 0) === 2 && hasDownloadableMedia(ref, "voice_item"))
|
||||
) {
|
||||
return ref;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildAttachmentsFromMedia(mediaOpts: Json): Json[] {
|
||||
const out: Json[] = [];
|
||||
const pushIf = (key: string, mimeKey: string, kind: string): void => {
|
||||
const filePath = String(mediaOpts[key] || "").trim();
|
||||
if (!filePath) return;
|
||||
out.push({
|
||||
kind,
|
||||
local_path: filePath,
|
||||
media_type: String(mediaOpts[mimeKey] || "").trim(),
|
||||
});
|
||||
};
|
||||
pushIf("decryptedPicPath", "", "image");
|
||||
pushIf("decryptedVideoPath", "", "video");
|
||||
pushIf("decryptedFilePath", "fileMediaType", "file");
|
||||
pushIf("decryptedVoicePath", "voiceMediaType", "voice");
|
||||
return out;
|
||||
}
|
||||
|
||||
async function handleInboundMessage(
|
||||
modules: OfficialModules,
|
||||
params: {
|
||||
token: string;
|
||||
accountId: string;
|
||||
cloudBaseUrl: string;
|
||||
full: Json;
|
||||
userContextTokens: TokenMap;
|
||||
localCursor: string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const fromUser = String(params.full.from_user_id || "").trim();
|
||||
const toUser = String(params.full.to_user_id || "").trim();
|
||||
if (!fromUser) return params.localCursor;
|
||||
if (toUser && toUser === fromUser) return params.localCursor;
|
||||
if (Number(params.full.message_type || 1) !== 1) return params.localCursor;
|
||||
|
||||
const contextToken = String(params.full.context_token || "").trim();
|
||||
if (contextToken) {
|
||||
params.userContextTokens[fromUser] = contextToken;
|
||||
modules.setContextToken(params.accountId, fromUser, contextToken);
|
||||
}
|
||||
|
||||
const mediaItem = pickDownloadableMedia(params.full);
|
||||
const mediaOpts = mediaItem
|
||||
? await modules.downloadMediaFromItem(mediaItem, {
|
||||
cdnBaseUrl: DEFAULT_CDN_BASE_URL,
|
||||
saveMedia: saveMediaBuffer,
|
||||
log: (msg: string) => log(`media ${msg}`),
|
||||
errLog: (msg: string) => log(`media-error ${msg}`),
|
||||
label: "inbound",
|
||||
})
|
||||
: {};
|
||||
const ctx = modules.weixinMessageToMsgContext(params.full, params.accountId, mediaOpts);
|
||||
let replies: Json[] = [];
|
||||
try {
|
||||
const native = await postNativeReply(params.token, {
|
||||
channel: "wechat",
|
||||
account_id: params.accountId,
|
||||
ctx,
|
||||
attachments: buildAttachmentsFromMedia(mediaOpts),
|
||||
metadata: {
|
||||
source: "weixin_official_native",
|
||||
raw: {
|
||||
msg: params.full,
|
||||
},
|
||||
},
|
||||
});
|
||||
replies = Array.isArray(native.replies) ? (native.replies as Json[]) : [];
|
||||
} catch (err) {
|
||||
log(`native reply failed; no fallback enabled err=${String(err)}`);
|
||||
await safeSendNativeFailureNotice(modules, {
|
||||
to: fromUser,
|
||||
cloudBaseUrl: params.cloudBaseUrl,
|
||||
token: params.token,
|
||||
contextToken: contextToken || undefined,
|
||||
err,
|
||||
});
|
||||
return params.localCursor;
|
||||
}
|
||||
for (const reply of replies) {
|
||||
const text = String(reply.text || "").trim();
|
||||
const mediaPath = String(reply.media_path || reply.mediaPath || "").trim();
|
||||
const mediaUrl = String(reply.media_url || reply.mediaUrl || "").trim();
|
||||
const deliverTo = String(reply.chat_id || reply.to || fromUser).trim() || fromUser;
|
||||
const replyContextToken = String(
|
||||
reply.context_token || modules.getContextToken(params.accountId, deliverTo) || contextToken || "",
|
||||
).trim();
|
||||
if (mediaPath || mediaUrl) {
|
||||
const filePath = mediaPath || mediaUrl;
|
||||
await modules.sendWeixinMediaFile({
|
||||
filePath,
|
||||
to: deliverTo,
|
||||
text,
|
||||
opts: {
|
||||
baseUrl: params.cloudBaseUrl,
|
||||
token: params.token,
|
||||
contextToken: replyContextToken || undefined,
|
||||
},
|
||||
cdnBaseUrl: DEFAULT_CDN_BASE_URL,
|
||||
});
|
||||
log(`reply media sent to=${deliverTo} textLen=${text.length}`);
|
||||
continue;
|
||||
}
|
||||
if (!text) continue;
|
||||
await modules.sendMessageWeixin({
|
||||
to: deliverTo,
|
||||
text,
|
||||
opts: {
|
||||
baseUrl: params.cloudBaseUrl,
|
||||
token: params.token,
|
||||
contextToken: replyContextToken || undefined,
|
||||
},
|
||||
});
|
||||
log(`reply text sent to=${deliverTo} textLen=${text.length}`);
|
||||
}
|
||||
return params.localCursor;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
ensureDir(STATE_DIR);
|
||||
const state = (readJsonFile<Json>(STATE_FILE) || {}) as Json;
|
||||
let cloudCursor = String(state.cloud_cursor || "").trim();
|
||||
const userContextTokens: TokenMap =
|
||||
state.user_context_tokens && typeof state.user_context_tokens === "object"
|
||||
? (state.user_context_tokens as TokenMap)
|
||||
: {};
|
||||
const { accountId, token, cloudBaseUrl } = resolveAccount();
|
||||
const modules = await loadOfficialModules();
|
||||
modules.restoreContextTokens(accountId);
|
||||
log(`official runner started account=${accountId} cloud=${cloudBaseUrl} local=${LOCAL_BASE_URL}`);
|
||||
while (true) {
|
||||
try {
|
||||
const out = await modules.getUpdates({
|
||||
baseUrl: cloudBaseUrl,
|
||||
token,
|
||||
get_updates_buf: cloudCursor,
|
||||
timeoutMs: POLL_TIMEOUT_MS + 5000,
|
||||
});
|
||||
const msgs = Array.isArray(out.msgs) ? (out.msgs as Json[]) : [];
|
||||
const nextCloudCursor = String(out.get_updates_buf || cloudCursor || "").trim();
|
||||
if (nextCloudCursor) {
|
||||
cloudCursor = nextCloudCursor;
|
||||
}
|
||||
for (const full of msgs) {
|
||||
await handleInboundMessage(modules, {
|
||||
token,
|
||||
accountId,
|
||||
cloudBaseUrl,
|
||||
full,
|
||||
userContextTokens,
|
||||
localCursor: "0",
|
||||
});
|
||||
}
|
||||
writeJsonFile(STATE_FILE, {
|
||||
cloud_cursor: cloudCursor,
|
||||
user_context_tokens: userContextTokens,
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
} catch (err) {
|
||||
log(`loop error: ${String(err)}`);
|
||||
await sleep(1500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main();
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
// Legacy fallback bridge. The default startup path now uses `official_runner.ts`,
|
||||
// which drives the official openclaw-weixin modules directly.
|
||||
import fs from "node:fs";
|
||||
import crypto from "node:crypto";
|
||||
import os from "node:os";
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue