mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 拓展中心加入机器人
This commit is contained in:
1 parent
116989a091
commit
f16067d6d0
31 files changed
+3510
-566
No files matched your search
@@ -19,7 +19,8 @@ import {
|
||||
type ExtensionSendImageRequest,
|
||||
type ExtensionSendTextRequest,
|
||||
type ExtensionSendTextResult,
|
||||
type ExtensionSendVideoRequest
|
||||
type ExtensionSendVideoRequest,
|
||||
type ExtensionSendVoiceRequest
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
|
||||
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
|
||||
@@ -49,12 +50,7 @@ const STDERR_WINDOW_BYTES = 64 * 1024
|
||||
const STDERR_WINDOW_ENTRIES = 20
|
||||
const STDERR_MAX_CHUNK_CHARS = 400
|
||||
|
||||
/**
|
||||
* stderr 里常见的凭据写法。
|
||||
*
|
||||
* 扩展的 stderr 是任意文本,可能包含用户配置的 Cookie / Token;
|
||||
* 落日志前统一抹掉值,只保留键名。
|
||||
*/
|
||||
/** stderr 里的凭据形态;落日志前只保留键名。 */
|
||||
const SECRET_ASSIGNMENT =
|
||||
/\b(cookie|token|authorization|password|passwd|secret|api[_-]?key)\b(\s*[:=]\s*)(?!Bearer\b)([^\s,;"']{4,})/gi
|
||||
const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi
|
||||
@@ -79,10 +75,7 @@ export interface ExtensionHostChild {
|
||||
on(event: 'error', listener: (error: Error) => void): void
|
||||
once?(event: 'exit', listener: () => void): void
|
||||
readonly pid?: number
|
||||
/**
|
||||
* 子进程的 stderr。必须被消费:管道写满会让子进程在 `write` 上阻塞,
|
||||
* 表现为「扩展还活着但不再响应」。
|
||||
*/
|
||||
/** stderr 必须持续消费,否则管道写满会让子进程阻塞在 write。 */
|
||||
readonly stderr?: NodeJS.ReadableStream | null
|
||||
}
|
||||
|
||||
@@ -119,6 +112,10 @@ export interface ExtensionHostDependencies {
|
||||
extensionId: string,
|
||||
request: ExtensionSendVideoRequest
|
||||
) => Promise<ExtensionSendTextResult>
|
||||
sendVoice?: (
|
||||
extensionId: string,
|
||||
request: ExtensionSendVoiceRequest
|
||||
) => Promise<ExtensionSendTextResult>
|
||||
aiChat?: (
|
||||
extensionId: string,
|
||||
messages: Array<{ role: string; content: string }>
|
||||
@@ -155,15 +152,7 @@ interface ActivationWaiter {
|
||||
child: ExtensionHostChild
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个扩展的后台进程。
|
||||
*
|
||||
* **隔离边界**:每个扩展一个独立 Node 子进程,`require` 只发生在那里面;
|
||||
* 主进程从不 `require` 扩展代码。子进程拿不到 Electron API、数据库句柄、
|
||||
* 授权凭据或原生发送通道 —— 它只能通过本类转发的白名单 RPC 申请能力。
|
||||
*
|
||||
* ⚠️ 独立进程不等于强沙箱:后台仍是任意 Node 代码,安装时按「受信任本地开发者扩展」处理。
|
||||
*/
|
||||
/** 单个扩展的后台进程:独立 Node 子进程,主进程从不 require 扩展代码。 */
|
||||
export class ExtensionHost {
|
||||
private readonly dependencies: ExtensionHostDependencies
|
||||
private readonly storage: ExtensionStorage
|
||||
@@ -216,16 +205,11 @@ export class ExtensionHost {
|
||||
return Array.from(this.actions.values()).map((action) => ({ ...action }))
|
||||
}
|
||||
|
||||
/**
|
||||
* 把页面请求转给同扩展的后台处理器。
|
||||
*
|
||||
* 这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。
|
||||
* 响应大小与超时都在这里收口,避免页面被一个坏 handler 拖死。
|
||||
*/
|
||||
/** 把页面请求转给同扩展的后台处理器;这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。 */
|
||||
async requestPage(
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
timeoutMs = 10_000
|
||||
timeoutMs = 90_000
|
||||
): Promise<unknown> {
|
||||
const child = this.child
|
||||
if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
|
||||
@@ -310,13 +294,7 @@ export class ExtensionHost {
|
||||
return this.activation
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止后台进程。
|
||||
*
|
||||
* 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。
|
||||
* 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用
|
||||
* 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。
|
||||
*/
|
||||
/** 停止后台:等真实 exit 才算完成,只发信号会在进程占用文件时替换失败。 */
|
||||
async stop(): Promise<void> {
|
||||
this.stopping = true
|
||||
if (this.restartTimer) {
|
||||
@@ -353,15 +331,7 @@ export class ExtensionHost {
|
||||
this.setState('inactive')
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束扩展进程及其派生进程。
|
||||
*
|
||||
* POSIX 依赖 `fork` 时的 `detached` 建立独立进程组,`kill(-pid)` 一次覆盖整组;
|
||||
* 组不存在时退化为只杀直接子进程,并记一条降级日志。
|
||||
*
|
||||
* Windows 用 `taskkill /T /F`,且必须**在父进程仍存活时**执行:
|
||||
* 父进程先退出后,进程树的父子关系消失,`/T` 再也找不到孙进程。
|
||||
*/
|
||||
/** 结束进程树;Windows 的 taskkill /T 必须在父进程存活时执行,否则找不到孙进程。 */
|
||||
private killTree(child: ExtensionHostChild): void {
|
||||
const pid = child.pid
|
||||
if (!pid) {
|
||||
@@ -392,12 +362,7 @@ export class ExtensionHost {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 投递消息事件。
|
||||
*
|
||||
* 令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志,
|
||||
* 也不能让主进程的监听回调被拖垮。
|
||||
*/
|
||||
/** 投递消息事件;令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志, 也不能让主进程的监听回调被拖垮。 */
|
||||
deliverEvent(envelope: ExtensionEventEnvelope): boolean {
|
||||
if (this.state.state !== 'active' || !this.child) return false
|
||||
this.refillTokens()
|
||||
@@ -554,13 +519,7 @@ export class ExtensionHost {
|
||||
this.consumeStderr(child)
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费子进程 stderr。
|
||||
*
|
||||
* 两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞),
|
||||
* 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。
|
||||
* 凭据形态的字段在落日志前抹掉值。
|
||||
*/
|
||||
/** 消费子进程 stderr;两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞), 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。 */
|
||||
private consumeStderr(child: ExtensionHostChild): void {
|
||||
const stream = child.stderr
|
||||
if (!stream || typeof stream.on !== 'function') return
|
||||
@@ -832,6 +791,14 @@ export class ExtensionHost {
|
||||
params as unknown as ExtensionSendVideoRequest
|
||||
)
|
||||
}
|
||||
case 'wechat.send.voice': {
|
||||
this.requirePermission('wechat.send.voice')
|
||||
if (!this.dependencies.sendVoice) throw new ExtensionError('SEND_NOT_SUPPORTED')
|
||||
return this.dependencies.sendVoice(
|
||||
extensionId,
|
||||
params as unknown as ExtensionSendVoiceRequest
|
||||
)
|
||||
}
|
||||
case 'ai.chat': {
|
||||
this.requirePermission('ai.chat')
|
||||
if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
@@ -907,14 +874,7 @@ export class ExtensionHost {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束 `pid` 对应的进程树。
|
||||
*
|
||||
* 返回值表示实际使用的手段:
|
||||
* - `group`:POSIX 进程组,覆盖扩展派生的全部子进程;
|
||||
* - `taskkill`:Windows 进程树,必须在父进程仍存活时调用;
|
||||
* - `fallback`:只能结束进程本身,调用方应记录降级。
|
||||
*/
|
||||
/** 结束 `pid` 对应的进程树;`taskkill`:Windows 进程树,必须在父进程仍存活时调用。 */
|
||||
export function killProcessTree(
|
||||
pid: number | undefined,
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
ExtensionActionInfo,
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
ExtensionTtsCapabilitySnapshot,
|
||||
InstalledExtension
|
||||
} from '../../shared/extensions/types'
|
||||
import type {
|
||||
@@ -40,7 +41,8 @@ import type {
|
||||
ExtensionSendImageRequest,
|
||||
ExtensionSendTextRequest,
|
||||
ExtensionSendTextResult,
|
||||
ExtensionSendVideoRequest
|
||||
ExtensionSendVideoRequest,
|
||||
ExtensionSendVoiceRequest
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
|
||||
@@ -84,6 +86,13 @@ export interface ExtensionManagerDependencies {
|
||||
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
|
||||
/** 当前 AI 是否已配置;不暴露 key、endpoint 或任何凭据。 */
|
||||
aiStatus?: () => { configured: boolean; modelName: string }
|
||||
/** 当前文字转语音配置与选定音色摘要;不暴露 key。 */
|
||||
ttsStatus?: () => Promise<ExtensionTtsCapabilitySnapshot> | ExtensionTtsCapabilitySnapshot
|
||||
synthesizeVoice?: (request: {
|
||||
text: string
|
||||
voiceId?: string
|
||||
}) => Promise<{ filePath: string }>
|
||||
cleanupVoice?: (filePath: string) => void
|
||||
getAccountId: () => string
|
||||
getSelfUsernames: () => string[]
|
||||
isDatabaseReady: () => boolean
|
||||
@@ -112,16 +121,7 @@ const PAGE_METHODS: ExtensionPageMethod[] = [
|
||||
'extension.info'
|
||||
]
|
||||
|
||||
/**
|
||||
* 扩展系统的编排层。
|
||||
*
|
||||
* 职责边界:
|
||||
* - **只做编排**:清单读取、安装、启停、进程托管、事件分发、能力转发;
|
||||
* - 不实现消息监听(复用 `MessageListenerService`)、不实现发送(复用
|
||||
* `WechatActionGateway`)、不实现自动化规则存储(复用 `AutomationRuleStore`)。
|
||||
*
|
||||
* 所有扩展代码都在 `ExtensionHost` 的子进程里运行;本类不 `require` 任何扩展文件。
|
||||
*/
|
||||
/** 扩展系统的编排层:只管编排,不实现消息监听、发送与规则存储。 */
|
||||
export class ExtensionManager {
|
||||
private readonly dependencies: ExtensionManagerDependencies
|
||||
private readonly paths: ExtensionPaths
|
||||
@@ -187,6 +187,9 @@ export class ExtensionManager {
|
||||
checkEntitlement: dependencies.checkEntitlement,
|
||||
executeAction: dependencies.executeAction,
|
||||
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId),
|
||||
synthesizeVoice: dependencies.synthesizeVoice,
|
||||
cleanupVoice: dependencies.cleanupVoice,
|
||||
getFromId: () => dependencies.getAccountId(),
|
||||
now: this.now
|
||||
})
|
||||
this.eventBus = new ExtensionEventBus({
|
||||
@@ -275,12 +278,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验状态记录与磁盘上的 manifest 是否描述同一个版本。
|
||||
*
|
||||
* 升级会在「换代码」与「写状态」之间留下一个窗口;进程在该窗口被杀时,
|
||||
* 磁盘上是新代码、状态里是旧版本。这种扩展不能带着旧授权直接跑。
|
||||
*/
|
||||
/** 校验状态记录与磁盘上的 manifest 是否描述同一个版本;这种扩展不能带着旧授权直接跑。 */
|
||||
private checkInstallConsistency(
|
||||
record: ExtensionRegistryRecord,
|
||||
manifest: ExtensionManifest
|
||||
@@ -343,14 +341,7 @@ export class ExtensionManager {
|
||||
return this.templates.list()
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装官方模板。
|
||||
*
|
||||
* 三条硬约束:
|
||||
* 1. 只接受模板索引里的 id,ZIP 路径由目录服务解析并校验哈希;
|
||||
* 2. 同 id 已被非模板来源占用时拒绝接管;
|
||||
* 3. 安装只落代码,不启用——启用仍需用户确认权限。
|
||||
*/
|
||||
/** 安装官方模板;同 id 被非模板来源占用时拒绝接管。 */
|
||||
async installTemplate(templateId: string): Promise<ExtensionInstallResult> {
|
||||
const templates = this.templates
|
||||
if (!templates) {
|
||||
@@ -393,22 +384,12 @@ export class ExtensionManager {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 该扩展当前是否被暂停(配置待确认 / 版本不一致)。
|
||||
*
|
||||
* 这是唯一的判断入口:事件投递、动作调用、发送出口都走它,
|
||||
* 避免出现「某处放行、某处拦截」的不一致状态。
|
||||
*/
|
||||
/** 该扩展是否被暂停(配置待确认 / 版本不一致);事件、动作、发送都看它。 */
|
||||
private isSuspended(extensionId: string): boolean {
|
||||
return this.storageHolds.has(extensionId) || this.inconsistencies.has(extensionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行期检测到配置回退:立刻收住这个扩展。
|
||||
*
|
||||
* 顺序很重要:先停后台(切断正在跑的回复循环),再改状态、记日志。
|
||||
* 已经交给 Native Host 的发送请求无法撤回,属于已知边界。
|
||||
*/
|
||||
/** 运行期检测到配置回退:立刻收住这个扩展。 */
|
||||
private handleStorageHealthChange(
|
||||
extensionId: string,
|
||||
health: { state: string; message?: string }
|
||||
@@ -442,12 +423,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 链接外部开发项目。
|
||||
*
|
||||
* 只读用户显式选择的目录:校验 manifest、入口文件、路径边界与 ID 冲突,
|
||||
* 然后登记为 `development` 来源。**不复制代码**,也不写回源码目录。
|
||||
*/
|
||||
/** 链接外部开发项目:只读用户选的目录,不复制代码,也不写回源码目录。 */
|
||||
async linkDevelopmentProject(directory: string): Promise<ExtensionInstallResult> {
|
||||
const raw = String(directory || '').trim()
|
||||
if (!raw) {
|
||||
@@ -553,12 +529,7 @@ export class ExtensionManager {
|
||||
return { success: true, ...(extension ? { extension } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新加载开发项目。
|
||||
*
|
||||
* 停后台 → 清 manifest 缓存 → 重新解析 → 权限取交集 → 原本启用则重启。
|
||||
* 页面侧由界面刷新 iframe 完成,两者互不依赖。
|
||||
*/
|
||||
/** 重新加载开发项目。 */
|
||||
async reloadDevelopment(extensionId: string): Promise<ExtensionOperationResult> {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
|
||||
@@ -627,12 +598,7 @@ export class ExtensionManager {
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除开发链接。
|
||||
*
|
||||
* 绝不删除外部源码目录。若安装副本还在,把来源退回安装副本;
|
||||
* 否则移除 Registry 记录。用户数据按 `keepData` 决定。
|
||||
*/
|
||||
/** 移除开发链接:有安装副本就退回它,否则删记录;外部目录永不删除。 */
|
||||
async unlinkDevelopment(
|
||||
extensionId: string,
|
||||
options: { keepData: boolean }
|
||||
@@ -681,11 +647,7 @@ export class ExtensionManager {
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 把开发项目转成正式安装副本。
|
||||
*
|
||||
* 只复制代码;用户配置本来就在 `extensions-data`,不受影响。
|
||||
*/
|
||||
/** 把开发项目转成正式安装副本。 */
|
||||
async convertDevelopmentToInstalled(extensionId: string): Promise<ExtensionOperationResult> {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
|
||||
@@ -728,12 +690,7 @@ export class ExtensionManager {
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 从官方模板生成一个独立项目(不安装、不启用)。
|
||||
*
|
||||
* ZIP 来自官方模板目录并已校验哈希;生成过程在暂存目录完成,
|
||||
* 目标目录非空时不会写入任何文件。
|
||||
*/
|
||||
/** 从官方模板生成一个独立项目(不安装、不启用)。 */
|
||||
async createProjectFromTemplate(
|
||||
templateId: string,
|
||||
targetDirectory: string,
|
||||
@@ -789,12 +746,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把已安装副本导出成外部项目,并把来源切换为 development。
|
||||
*
|
||||
* 导出的必须是**用户改过的安装副本**,不能重新解压官方 ZIP——
|
||||
* 那样会把二开内容换回原版。原安装副本保留,作为显式恢复来源。
|
||||
*/
|
||||
/** 把已安装副本导出成外部项目,并把来源切换为 development。 */
|
||||
async exportInstalledAsProject(
|
||||
extensionId: string,
|
||||
targetDirectory: string
|
||||
@@ -895,12 +847,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授予扩展已声明的权限。
|
||||
*
|
||||
* 只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。
|
||||
* 权限在子进程启动时快照,因此已启用的扩展需要重启后台才会生效。
|
||||
*/
|
||||
/** 授予扩展已声明的权限;只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。 */
|
||||
async grantPermissions(
|
||||
extensionId: string,
|
||||
permissions: ExtensionPermission[]
|
||||
@@ -1040,11 +987,7 @@ export class ExtensionManager {
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。
|
||||
*
|
||||
* 用于「上次升级中断」后的修复。授权按新 manifest 取交集,不会扩大能力。
|
||||
*/
|
||||
/** 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。 */
|
||||
adoptInstalledCode(extensionId: string): ExtensionOperationResult {
|
||||
const record = this.registry.get(extensionId)
|
||||
const manifest = this.readManifest(extensionId)
|
||||
@@ -1137,12 +1080,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展页面可调用的能力。
|
||||
*
|
||||
* 页面**没有**发送 / 查询 / AI 权限:那些能力只从后台进程按权限申请。
|
||||
* 页面与后台共享同一个 `storage` 命名空间,所以配置页保存的内容后台能直接读到。
|
||||
*/
|
||||
/** 扩展页面可调用的能力。 */
|
||||
async pageRequest(
|
||||
extensionId: string,
|
||||
method: string,
|
||||
@@ -1214,7 +1152,7 @@ export class ExtensionManager {
|
||||
result: await host.requestPage(
|
||||
inner,
|
||||
(rawParams as Record<string, unknown> | undefined) ?? {},
|
||||
10_000
|
||||
90_000
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1273,12 +1211,7 @@ export class ExtensionManager {
|
||||
return this.actions.list()
|
||||
}
|
||||
|
||||
/**
|
||||
* 供自动化编辑器使用的动作列表。
|
||||
*
|
||||
* `registered` 只是「后台注册过」,是否可用要逐条判断:停用、代码缺失、
|
||||
* 权限未授予、Storage 暂停、Schema 非法,任一成立都不可执行。
|
||||
*/
|
||||
/** 供自动化编辑器使用的动作列表。 */
|
||||
listActions(): ExtensionActionInfo[] {
|
||||
return this.actions.list().map((action) => {
|
||||
const record = this.registry.get(action.extensionId)
|
||||
@@ -1322,13 +1255,7 @@ export class ExtensionManager {
|
||||
await Promise.all(ids.map((id) => this.stopHost(id)))
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装 / 升级的编排。
|
||||
*
|
||||
* 顺序是「停旧进程 → 换代码 → 写状态 → 起新进程」,任何一步失败都要让
|
||||
* 磁盘与 Registry 回到同一个版本。仅靠多次 rename 不构成跨进程事务,
|
||||
* 所以失败时显式回滚,并把错误原样返回给界面,不吞成成功。
|
||||
*/
|
||||
/** 安装 / 升级的编排。 */
|
||||
private async install(
|
||||
run: (
|
||||
beforeReplace: (
|
||||
@@ -1404,12 +1331,7 @@ export class ExtensionManager {
|
||||
return { success: true, ...(installed ? { extension: installed } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板来源的「本地改动」检查。
|
||||
*
|
||||
* 只保护 `template` 来源:用户自己装的 ZIP / 目录本来就会被覆盖,
|
||||
* 开发模式根本没有安装副本可覆盖。
|
||||
*/
|
||||
/** 模板来源的「本地改动」检查。 */
|
||||
private assertTemplateCodeUntouched(record: ExtensionRegistryRecord): void {
|
||||
const root = this.paths.installDir(record.id)
|
||||
if (!fs.existsSync(path.join(root, 'manifest.json'))) return
|
||||
@@ -1471,6 +1393,7 @@ export class ExtensionManager {
|
||||
sendText: (id, request) => this.sendText(id, request),
|
||||
sendImage: (id, request) => this.sendImage(id, request),
|
||||
sendVideo: (id, request) => this.sendVideo(id, request),
|
||||
sendVoice: (id, request) => this.sendVoice(id, request),
|
||||
aiChat: (_id, messages) => this.dependencies.aiChat(messages),
|
||||
capabilities: (id) => this.buildCapabilitySnapshot(id)
|
||||
})
|
||||
@@ -1544,14 +1467,14 @@ export class ExtensionManager {
|
||||
if (!conversationId || conversationId.length > 128) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '会话 id 不合法')
|
||||
}
|
||||
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 200))
|
||||
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 500))
|
||||
const startTime = Number.isFinite(Number(request?.startTime))
|
||||
? Number(request.startTime)
|
||||
: Date.now() - 24 * 60 * 60 * 1000
|
||||
const endTime = Number.isFinite(Number(request?.endTime)) ? Number(request.endTime) : Date.now()
|
||||
if (endTime <= startTime) throw new ExtensionError('INVALID_REQUEST', '时间范围不合法')
|
||||
if (endTime - startTime > 7 * 24 * 60 * 60 * 1000) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 7 天')
|
||||
if (endTime - startTime > 35 * 24 * 60 * 60 * 1000) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 35 天')
|
||||
}
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
@@ -1626,15 +1549,54 @@ export class ExtensionManager {
|
||||
)
|
||||
}
|
||||
|
||||
private async sendVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionSendVoiceRequest
|
||||
): Promise<ExtensionSendTextResult> {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝')
|
||||
}
|
||||
const manifest = this.manifests.get(extensionId)
|
||||
return this.sendGateway.sendVoice(
|
||||
{
|
||||
extensionId,
|
||||
permissions: record.grantedPermissions,
|
||||
conversationScope: manifest?.subscriptions?.conversationIds ?? []
|
||||
},
|
||||
request
|
||||
)
|
||||
}
|
||||
|
||||
private async buildCapabilitySnapshot(extensionId: string): Promise<ExtensionCapabilitySnapshot> {
|
||||
const record = this.registry.get(extensionId)
|
||||
const granted = record?.grantedPermissions ?? []
|
||||
const capability = await this.dependencies.getCapability().catch(() => null)
|
||||
let licensed = false
|
||||
if (hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text')) {
|
||||
if (
|
||||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text') ||
|
||||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.voice') ||
|
||||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.image') ||
|
||||
hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.video')
|
||||
) {
|
||||
const entitlement = await this.dependencies.checkEntitlement().catch(() => null)
|
||||
licensed = entitlement?.ok === true
|
||||
}
|
||||
let tts: ExtensionTtsCapabilitySnapshot | undefined
|
||||
if (this.dependencies.ttsStatus) {
|
||||
try {
|
||||
tts = await this.dependencies.ttsStatus()
|
||||
} catch {
|
||||
tts = {
|
||||
configured: false,
|
||||
model: 's2.1-pro-free',
|
||||
selectedVoiceId: '',
|
||||
selectedVoice: null
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
extensionId,
|
||||
enabled: record?.enabled === true,
|
||||
@@ -1647,6 +1609,7 @@ export class ExtensionManager {
|
||||
canSendText: Boolean(capability?.capabilities?.text),
|
||||
canSendImage: Boolean(capability?.capabilities?.image),
|
||||
canSendVideo: Boolean(capability?.capabilities?.video),
|
||||
canSendVoice: Boolean(capability?.capabilities?.voice),
|
||||
licensed,
|
||||
message: capability?.message || '暂时无法获知微信发送能力'
|
||||
},
|
||||
@@ -1659,7 +1622,8 @@ export class ExtensionManager {
|
||||
} catch {
|
||||
return { configured: false, modelName: '' }
|
||||
}
|
||||
})()
|
||||
})(),
|
||||
...(tts ? { tts } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1720,12 +1684,7 @@ export class ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 没有 Host 时的运行状态。
|
||||
*
|
||||
* 只有页面入口的扩展本来就不会有后台进程,必须与「启用但启动失败」区分开:
|
||||
* 前者是 `inactive` 加说明,后者是 `error` 加原因。
|
||||
*/
|
||||
/** 没有 Host 时的运行状态。 */
|
||||
private deriveIdleRuntime(
|
||||
record: ExtensionRegistryRecord,
|
||||
manifest: ExtensionManifest | null
|
||||
|
||||
@@ -25,12 +25,7 @@ const MIME_TYPES: Record<string, string> = {
|
||||
'.wasm': 'application/wasm'
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在
|
||||
* 扩展目录内;响应带严格 CSP(无外链、无内联脚本、无网络)。
|
||||
*
|
||||
* `registerSchemesAsPrivileged` 必须在 app ready 前调用。
|
||||
*/
|
||||
/** 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在。 */
|
||||
export function registerExtensionScheme(): void {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -48,10 +43,7 @@ export function registerExtensionScheme(): void {
|
||||
|
||||
export interface ExtensionProtocolDependencies {
|
||||
paths: ExtensionPaths
|
||||
/**
|
||||
* 解析扩展代码根目录。开发模式下是外部源码目录,
|
||||
* 必须与后台进程、Manifest 读取使用同一个解析器,否则页面会读到旧副本。
|
||||
*/
|
||||
/** 解析代码根目录:开发模式指向外部源码,必须与后台/Manifest 用同一解析器。 */
|
||||
resolveRoot: (extensionId: string) => string | null
|
||||
}
|
||||
|
||||
@@ -86,7 +78,8 @@ export function installExtensionProtocolHandler(dependencies: ExtensionProtocolD
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"img-src 'self' data: https:",
|
||||
"media-src 'self' data: https:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'none'",
|
||||
"object-src 'none'",
|
||||
|
||||
@@ -11,7 +11,8 @@ import type {
|
||||
ExtensionSendImageRequest,
|
||||
ExtensionSendTextRequest,
|
||||
ExtensionSendTextResult,
|
||||
ExtensionSendVideoRequest
|
||||
ExtensionSendVideoRequest,
|
||||
ExtensionSendVoiceRequest
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
|
||||
@@ -19,6 +20,7 @@ import type { ExtensionEntitlementResult } from './extension-entitlement'
|
||||
import { isPathInside } from './extension-paths'
|
||||
|
||||
const MAX_TEXT_LENGTH = 2_000
|
||||
const MAX_VOICE_TEXT_LENGTH = 1_000
|
||||
const MAX_RECIPIENT_LENGTH = 128
|
||||
const MAX_MEDIA_BYTES = 100 * 1024 * 1024
|
||||
const SEND_INTERVAL_MS = 2_000
|
||||
@@ -27,6 +29,7 @@ const SEND_WINDOW_LIMIT = 10
|
||||
/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */
|
||||
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'])
|
||||
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v'])
|
||||
const VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.silk', '.amr', '.m4a', '.ogg'])
|
||||
|
||||
export interface ExtensionSendContext {
|
||||
extensionId: string
|
||||
@@ -41,20 +44,28 @@ export interface ExtensionSendGatewayDependencies {
|
||||
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
/** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */
|
||||
getExtensionDataRoot?: (extensionId: string) => string
|
||||
/** 使用宿主已配置的文字转语音服务生成临时音频文件。 */
|
||||
synthesizeVoice?: (request: {
|
||||
text: string
|
||||
voiceId?: string
|
||||
}) => Promise<{ filePath: string }>
|
||||
cleanupVoice?: (filePath: string) => void
|
||||
getFromId?: () => string | Promise<string>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。
|
||||
*
|
||||
* origin、purpose、triggerType、幂等键全部由宿主填写,扩展只描述
|
||||
* 「发给谁、发什么」。
|
||||
*/
|
||||
/** 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。 */
|
||||
export class ExtensionSendGateway {
|
||||
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
private readonly checkEntitlement: () => Promise<ExtensionEntitlementResult>
|
||||
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
private readonly getExtensionDataRoot: (extensionId: string) => string
|
||||
private readonly synthesizeVoice?: (request: {
|
||||
text: string
|
||||
voiceId?: string
|
||||
}) => Promise<{ filePath: string }>
|
||||
private readonly cleanupVoice?: (filePath: string) => void
|
||||
private readonly getFromId?: () => string | Promise<string>
|
||||
private readonly now: () => number
|
||||
private readonly sendHistory = new Map<string, number[]>()
|
||||
|
||||
@@ -63,6 +74,9 @@ export class ExtensionSendGateway {
|
||||
this.checkEntitlement = dependencies.checkEntitlement
|
||||
this.executeAction = dependencies.executeAction
|
||||
this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '')
|
||||
this.synthesizeVoice = dependencies.synthesizeVoice
|
||||
this.cleanupVoice = dependencies.cleanupVoice
|
||||
this.getFromId = dependencies.getFromId
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
@@ -124,12 +138,7 @@ export class ExtensionSendGateway {
|
||||
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送图片。
|
||||
*
|
||||
* 文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件,
|
||||
* 否则扩展就能借 TraceMemo 把本机任意文件发出去。
|
||||
*/
|
||||
/** 发送图片;文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件, 否则扩展就能借 TraceMemo 把本机任意文件发出去。 */
|
||||
async sendImage(
|
||||
context: ExtensionSendContext,
|
||||
request: ExtensionSendImageRequest
|
||||
@@ -188,12 +197,7 @@ export class ExtensionSendGateway {
|
||||
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送视频。
|
||||
*
|
||||
* 与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。
|
||||
* 文件边界与图片相同(扩展数据目录 / 临时目录、普通文件、≤ 100MB)。
|
||||
*/
|
||||
/** 发送视频;与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。 */
|
||||
async sendVideo(
|
||||
context: ExtensionSendContext,
|
||||
request: ExtensionSendVideoRequest
|
||||
@@ -252,6 +256,110 @@ export class ExtensionSendGateway {
|
||||
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
|
||||
}
|
||||
|
||||
/** 发送语音气泡。 */
|
||||
async sendVoice(
|
||||
context: ExtensionSendContext,
|
||||
request: ExtensionSendVoiceRequest
|
||||
): Promise<ExtensionSendTextResult> {
|
||||
if (!hasExtensionPermission(context.permissions, 'wechat.send.voice')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.voice 权限')
|
||||
}
|
||||
const to = String(request?.to || '').trim()
|
||||
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
|
||||
}
|
||||
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
|
||||
}
|
||||
const rawPath = String(request?.path || '').trim()
|
||||
const rawText = String(request?.text || '').trim()
|
||||
if (!rawPath && !rawText) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '发送语音需要提供 text 或音频文件 path')
|
||||
}
|
||||
if (rawText.length > MAX_VOICE_TEXT_LENGTH) {
|
||||
throw new ExtensionError(
|
||||
'INVALID_REQUEST',
|
||||
`语音合成文字不能超过 ${MAX_VOICE_TEXT_LENGTH} 字`
|
||||
)
|
||||
}
|
||||
|
||||
let directMediaPath = ''
|
||||
if (rawPath) {
|
||||
directMediaPath = assertSendableMediaPath(
|
||||
rawPath,
|
||||
this.getExtensionDataRoot(context.extensionId),
|
||||
VOICE_EXTENSIONS
|
||||
)
|
||||
} else if (!this.synthesizeVoice) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前宿主未配置文字转语音合成能力')
|
||||
}
|
||||
|
||||
this.assertRateLimit(context.extensionId)
|
||||
|
||||
const capability = await this.getCapability().catch(() => null)
|
||||
if (!capability || !capability.supported) {
|
||||
throw new ExtensionError(
|
||||
'SEND_NOT_SUPPORTED',
|
||||
capability?.message || '当前环境不支持微信发送'
|
||||
)
|
||||
}
|
||||
if (!capability.ready || !capability.capabilities?.voice) {
|
||||
throw new ExtensionError(
|
||||
'CAPABILITY_UNAVAILABLE',
|
||||
capability.message || '当前微信发送能力不支持语音'
|
||||
)
|
||||
}
|
||||
|
||||
const entitlement = await this.checkEntitlement()
|
||||
if (!entitlement.ok) {
|
||||
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
|
||||
}
|
||||
|
||||
let synthesizedFile = ''
|
||||
try {
|
||||
let mediaPath = directMediaPath
|
||||
if (!mediaPath && this.synthesizeVoice) {
|
||||
const voiceId = String(request?.voiceId || '').trim() || undefined
|
||||
const synthesized = await this.synthesizeVoice({ text: rawText, voiceId })
|
||||
synthesizedFile = String(synthesized?.filePath || '').trim()
|
||||
mediaPath = assertSendableMediaPath(
|
||||
synthesizedFile,
|
||||
this.getExtensionDataRoot(context.extensionId),
|
||||
VOICE_EXTENSIONS
|
||||
)
|
||||
}
|
||||
|
||||
const fromId = this.getFromId ? String((await this.getFromId()) || '').trim() : ''
|
||||
const result = await this.executeAction({
|
||||
...(request.dedupeKey
|
||||
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
|
||||
: {}),
|
||||
origin: 'extension',
|
||||
purpose: 'extension_send',
|
||||
triggerType: 'automation',
|
||||
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
|
||||
content: { type: 'voice', path: mediaPath },
|
||||
metadata: {
|
||||
extensionId: context.extensionId,
|
||||
...(fromId ? { fromId } : {})
|
||||
}
|
||||
})
|
||||
|
||||
if (result.status === 'sent') {
|
||||
return { actionId: result.actionId, status: 'sent' }
|
||||
}
|
||||
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信语音发送失败')
|
||||
} finally {
|
||||
if (synthesizedFile && this.cleanupVoice) {
|
||||
try {
|
||||
this.cleanupVoice(synthesizedFile)
|
||||
} catch {
|
||||
// 临时语音清理失败不影响主流程结果。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */
|
||||
private assertRateLimit(extensionId: string): void {
|
||||
const now = this.now()
|
||||
@@ -270,12 +378,7 @@ export class ExtensionSendGateway {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件。
|
||||
*
|
||||
* 用 realpath 复核,符号链接跳到目录外同样会被拒绝;这一层不能省,
|
||||
* 否则 `wechat.send.image` 就等价于「读取并外发任意本机文件」。
|
||||
*/
|
||||
/** 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件;用 realpath 复核,符号链接跳到目录外同样会被拒绝。 */
|
||||
function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set<string>): string {
|
||||
const raw = String(value ?? '').trim()
|
||||
if (!raw || raw.length > 4_096) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveMd5
|
||||
} from '../services/chat-service'
|
||||
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
|
||||
import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service'
|
||||
import { wechatActionGateway } from '../services/wechat-action-gateway'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import type {
|
||||
@@ -22,12 +23,7 @@ import { getExtensionPaths } from './extension-paths'
|
||||
|
||||
let manager: ExtensionManager | null = null
|
||||
|
||||
/**
|
||||
* 官方模板资源根目录。
|
||||
*
|
||||
* 打包后是 `<resources>/extension-templates`;开发态读构建产物目录。
|
||||
* 两者都不指向 `examples/extensions`——源码树不是运行时依赖。
|
||||
*/
|
||||
/** 官方模板资源根目录;两者都不指向 `examples/extensions`——源码树不是运行时依赖。 */
|
||||
function resolveTemplateRoot(): string {
|
||||
const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR
|
||||
if (override && override.trim()) return path.resolve(override.trim())
|
||||
@@ -40,14 +36,10 @@ export interface ExtensionSystemOptions {
|
||||
onChange: (extensionId: string, reason: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展系统的主进程接线。
|
||||
*
|
||||
* 这里只做依赖注入:所有能力都来自既有服务,扩展系统自己不实现第二套
|
||||
* 消息监听、发送通道或 AI Provider。
|
||||
*/
|
||||
/** 扩展系统的主进程接线。 */
|
||||
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
|
||||
if (manager) return
|
||||
const ttsService = new TextToSpeechSettingsService()
|
||||
manager = new ExtensionManager({
|
||||
paths: getExtensionPaths(),
|
||||
appVersion: options.appVersion,
|
||||
@@ -73,6 +65,50 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
|
||||
const config = new AIProviderService().getRuntimeConfig()
|
||||
return { configured: config.configured, modelName: config.modelName }
|
||||
},
|
||||
ttsStatus: async () => {
|
||||
const status = await ttsService.getVoiceStatus()
|
||||
return {
|
||||
configured: status.configured,
|
||||
model: status.model,
|
||||
selectedVoiceId: status.selectedVoiceId,
|
||||
selectedVoice: status.selectedVoice
|
||||
? {
|
||||
id: status.selectedVoice.id,
|
||||
name: status.selectedVoice.name,
|
||||
description: status.selectedVoice.description,
|
||||
tags: status.selectedVoice.tags,
|
||||
languages: status.selectedVoice.languages,
|
||||
...(status.selectedVoice.authorName
|
||||
? { authorName: status.selectedVoice.authorName }
|
||||
: {}),
|
||||
...(status.selectedVoice.previewUrl
|
||||
? { previewUrl: status.selectedVoice.previewUrl }
|
||||
: {}),
|
||||
...(status.selectedVoice.coverImage
|
||||
? { coverImage: status.selectedVoice.coverImage }
|
||||
: {})
|
||||
}
|
||||
: null
|
||||
}
|
||||
},
|
||||
synthesizeVoice: async ({ text, voiceId }) => {
|
||||
const current = ttsService.get()
|
||||
const referenceId = String(voiceId || current.settings.selectedVoiceId || '').trim()
|
||||
if (!referenceId) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '请先在文字转语音设置中选择音色')
|
||||
}
|
||||
const synthesized = await ttsService.synthesize({ text, referenceId })
|
||||
if (!synthesized.success || !synthesized.filePath) {
|
||||
throw new ExtensionError(
|
||||
'CAPABILITY_UNAVAILABLE',
|
||||
synthesized.error || '文字转语音生成失败'
|
||||
)
|
||||
}
|
||||
return { filePath: synthesized.filePath }
|
||||
},
|
||||
cleanupVoice: (filePath) => {
|
||||
ttsService.removeGeneratedAudio(filePath)
|
||||
},
|
||||
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
|
||||
getSelfUsernames: () => {
|
||||
try {
|
||||
@@ -114,29 +150,63 @@ export async function disposeExtensionSystem(): Promise<void> {
|
||||
if (current) await current.dispose()
|
||||
}
|
||||
|
||||
function normalizeQueriedMessageType(rawType: string | undefined): {
|
||||
type: string
|
||||
isTextLike: boolean
|
||||
} {
|
||||
const value = String(rawType ?? '').trim()
|
||||
if (value === 'text' || value === '普通文本' || value === '1') {
|
||||
return { type: 'text', isTextLike: true }
|
||||
}
|
||||
if (value === '引用消息') {
|
||||
return { type: 'text', isTextLike: true }
|
||||
}
|
||||
if (value === '图片' || value === 'image') return { type: 'image', isTextLike: false }
|
||||
if (value === '语音' || value === 'voice') return { type: 'voice', isTextLike: false }
|
||||
if (value === '视频' || value === 'video') return { type: 'video', isTextLike: false }
|
||||
if (value === '表情包' || value === 'sticker') return { type: 'sticker', isTextLike: false }
|
||||
if (value === '系统消息' || value === 'system') return { type: 'system', isTextLike: false }
|
||||
return { type: value || 'other', isTextLike: false }
|
||||
}
|
||||
|
||||
async function queryConversationMessages(
|
||||
request: ExtensionMessagesQueryRequest
|
||||
): Promise<ExtensionQueriedMessage[]> {
|
||||
const contact = resolveMd5(request.conversationId)
|
||||
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
|
||||
const messages = await listMessagesAsync(
|
||||
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
|
||||
const rawMessages = await listMessagesAsync(
|
||||
contact.md5,
|
||||
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
|
||||
Math.floor((request.endTime ?? Date.now()) / 1000),
|
||||
{ limit: request.limit ?? 50 },
|
||||
undefined,
|
||||
'',
|
||||
'unknown'
|
||||
)
|
||||
return messages.map((message) => ({
|
||||
messageId: message.serverId || String(message.localId ?? message.id),
|
||||
conversationId: request.conversationId,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.name ? { senderName: message.name } : {}),
|
||||
isSelf: message.isSender === true,
|
||||
type: message.type,
|
||||
...(message.type === 'text' ? { text: message.content } : {}),
|
||||
timestamp: Math.round((message.createTime ?? 0) * 1000)
|
||||
}))
|
||||
const sorted = [...rawMessages]
|
||||
.sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0))
|
||||
.slice(-limit)
|
||||
return sorted.map((message) => {
|
||||
const normalizedType = normalizeQueriedMessageType(message.type)
|
||||
const quoteText =
|
||||
message.contentData &&
|
||||
typeof message.contentData === 'object' &&
|
||||
message.contentData.type === 'quote' &&
|
||||
typeof message.contentData.content === 'string'
|
||||
? message.contentData.content
|
||||
: ''
|
||||
const resolvedText = String(message.content || quoteText || '').trim()
|
||||
return {
|
||||
messageId: message.serverId || String(message.localId ?? message.id),
|
||||
conversationId: request.conversationId,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.name ? { senderName: message.name } : {}),
|
||||
isSelf: message.isSender === true,
|
||||
type: normalizedType.type,
|
||||
...(normalizedType.isTextLike && resolvedText ? { text: resolvedText } : {}),
|
||||
timestamp: Math.round((message.createTime ?? 0) * 1000)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function chatWithConfiguredProvider(
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
/**
|
||||
* 扩展后台进程入口。
|
||||
*
|
||||
* 这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、
|
||||
* 把请求转成白名单 RPC。任何 `require` 都只发生在这里,主进程永远不会加载
|
||||
* 第三方扩展代码。
|
||||
*
|
||||
* 与主进程的协议见 `src/shared/extensions/rpc.ts`。
|
||||
*/
|
||||
/** 扩展后台进程入口;这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、 把请求转成白名单 RPC。 */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
@@ -108,12 +100,7 @@ const tm = {
|
||||
return [...permissions]
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 页面 → 同扩展后台的通用请求处理器注册。
|
||||
*
|
||||
* 不需要额外权限:注册本身不产生任何能力,handler 内部若调用
|
||||
* `tm.wechat.send` 等能力,仍然各自走权限检查。
|
||||
*/
|
||||
/** 页面 → 同扩展后台的通用请求处理器注册。 */
|
||||
page: {
|
||||
onRequest(method: string, handler: (params: Record<string, unknown>) => unknown): void {
|
||||
const name = String(method || '').trim()
|
||||
@@ -123,12 +110,7 @@ const tm = {
|
||||
pageHandlers.set(name, handler)
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 扩展私有凭据。
|
||||
*
|
||||
* 真正加密发生在主进程(`safeStorage`);子进程只在需要时拿到明文。
|
||||
* 每个扩展一个命名空间,A 扩展拿不到 B 的密钥。
|
||||
*/
|
||||
/** 扩展私有凭据。 */
|
||||
secrets: {
|
||||
async get(key: string): Promise<string | null> {
|
||||
requirePermission('secrets')
|
||||
@@ -166,27 +148,45 @@ const tm = {
|
||||
limit?: number
|
||||
}): Promise<{ messages: unknown[] }> {
|
||||
requirePermission('messages.query')
|
||||
const result = (await callHost('messages.query', { ...request })) as { messages: unknown[] }
|
||||
const result = (await callHost('messages.query', { ...request }, 25_000)) as {
|
||||
messages: unknown[]
|
||||
}
|
||||
return result
|
||||
}
|
||||
},
|
||||
wechat: {
|
||||
/**
|
||||
* 发送文本、图片或视频。
|
||||
*
|
||||
* 兼容旧调用:不传 `type` 视为 `text`。视频走独立的 video 通道,
|
||||
* 原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
|
||||
*/
|
||||
/** 发送文本、图片、视频或语音。 */
|
||||
async send(request: {
|
||||
type?: 'text' | 'image' | 'video'
|
||||
type?: 'text' | 'image' | 'video' | 'voice'
|
||||
to: string
|
||||
text?: string
|
||||
path?: string
|
||||
voiceId?: string
|
||||
at?: Record<string, string>
|
||||
dedupeKey?: string
|
||||
}) {
|
||||
const type =
|
||||
request && (request.type === 'image' || request.type === 'video') ? request.type : 'text'
|
||||
request &&
|
||||
(request.type === 'image' || request.type === 'video' || request.type === 'voice')
|
||||
? request.type
|
||||
: 'text'
|
||||
if (type === 'voice') {
|
||||
requirePermission('wechat.send.voice')
|
||||
return (await callHost(
|
||||
'wechat.send.voice',
|
||||
{
|
||||
to: request.to,
|
||||
...(request.path ? { path: request.path } : {}),
|
||||
...(request.text ? { text: request.text } : {}),
|
||||
...(request.voiceId ? { voiceId: request.voiceId } : {}),
|
||||
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
|
||||
},
|
||||
150_000
|
||||
)) as {
|
||||
actionId: string
|
||||
status: 'sent'
|
||||
}
|
||||
}
|
||||
if (type === 'image' || type === 'video') {
|
||||
requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image')
|
||||
return (await callHost(
|
||||
@@ -383,11 +383,7 @@ async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 UI 共用同一套校验规则。
|
||||
*
|
||||
* 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。
|
||||
*/
|
||||
/** 与 UI 共用同一套校验规则。 */
|
||||
function validateActionInput(
|
||||
schema: Record<string, unknown> | undefined,
|
||||
input: Record<string, unknown>
|
||||
@@ -414,7 +410,7 @@ async function handlePageRequest(message: ExtensionHostPageRequest): Promise<voi
|
||||
try {
|
||||
const raw = await withTimeout(
|
||||
Promise.resolve(handler(message.params ?? {})),
|
||||
Math.max(1_000, Math.min(message.timeoutMs - 500, 30_000))
|
||||
Math.max(1_000, Math.min(message.timeoutMs - 500, 90_000))
|
||||
)
|
||||
// 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。
|
||||
const serialized = JSON.stringify(raw ?? null)
|
||||
|
||||
@@ -74,11 +74,7 @@ export function buildPersonalWechatRuntimePath(): string {
|
||||
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the environment used by TraceMemo's local voice encoding helpers.
|
||||
* Keep this in one place so environment checks cannot accidentally inspect a
|
||||
* different ffmpeg than the sender process.
|
||||
*/
|
||||
/** Build the environment used by TraceMemo's local voice encoding helpers.。 */
|
||||
export function buildPersonalWechatRuntimeEnvironment(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
@@ -217,13 +213,15 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
|
||||
)
|
||||
const pcm = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout || '')
|
||||
if (!pcm.length) throw new Error('语音转换失败:没有得到 PCM 音频数据')
|
||||
const pcmDurationMs = Math.round((pcm.length / 2 / 24_000) * 1000)
|
||||
const encoded = await new SilkAudioEncoder().encode(pcm, 24_000)
|
||||
if (!encoded.data.length) throw new Error('语音转换失败:没有得到 SILK 数据')
|
||||
const durationMs = encoded.durationMs >= 1000 ? encoded.durationMs : pcmDurationMs
|
||||
const convertedPath = join(tmpdir(), `tracememo-voice-${randomBytes(8).toString('hex')}.silk`)
|
||||
writeFileSync(convertedPath, encoded.data)
|
||||
return {
|
||||
filePath: convertedPath,
|
||||
...(encoded.durationMs > 0 ? { durationMs: encoded.durationMs } : {}),
|
||||
...(durationMs > 0 ? { durationMs } : {}),
|
||||
temporary: true
|
||||
}
|
||||
}
|
||||
@@ -297,12 +295,7 @@ function prepareMacWechatImageFile(
|
||||
senderWxid: string,
|
||||
wechatFilesRoot = WECHAT_FILES_ROOT
|
||||
): { filePath: string; md5: string } {
|
||||
/* Stage the image in WeChat's temporary image directory using the
|
||||
* filename/hash layout required by the macOS native send path:
|
||||
* - stage inside the active account's ImageTemp tree selected by
|
||||
* findWechatImagePath(), not an arbitrary readable sandbox directory;
|
||||
* - append a per-send salt before calculating MD5, so the staged image and
|
||||
* the MD5 passed to the CDN task describe the same unique byte stream. */
|
||||
/** Stage the image in WeChat's temporary image directory using the。 */
|
||||
const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid)
|
||||
if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录')
|
||||
mkdirSync(temporaryRoot, { recursive: true })
|
||||
@@ -346,12 +339,7 @@ function stageMacWechatImageForMessageSourceSend(
|
||||
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
|
||||
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
|
||||
|
||||
/**
|
||||
* macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`
|
||||
* 只能读取 `~/Library/Containers/com.tencent.xinWeChat/Data/...` 容器内路径,
|
||||
* 直接传 `~/Library/Application Support/TraceMemo/...` 会触发 `VIDEO_PREPARATION_FAILED:0`。
|
||||
* 因此发送前需将容器外视频暂存到微信容器的 `Documents` 目录。
|
||||
*/
|
||||
/** macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`。 */
|
||||
export function stageMacWechatVideoForSend(
|
||||
filePath: string,
|
||||
wechatFilesRoot = WECHAT_FILES_ROOT
|
||||
@@ -587,14 +575,7 @@ function isDefinitiveImageSourcePreparationFailure(message: string): boolean {
|
||||
return message.trim() === 'IMAGE_PREPARATION_FAILED:0'
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。
|
||||
*
|
||||
* 只有在设置里打开「调试模式」时才输出,所以正常使用不会刷屏。
|
||||
*
|
||||
* **隐私约束**:只允许输出类型、字节数、HTTP 状态码、hook 的 `ret` 这类结构性字段。
|
||||
* 文件名、完整路径、wxid、群名、消息正文不进日志。
|
||||
*/
|
||||
/** 发送链路诊断日志(排查「hook 报成功、群里却没有消息」时用)。 */
|
||||
function logSendDiagnostic(
|
||||
stage: string,
|
||||
detail: Record<string, string | number | boolean | null>
|
||||
@@ -607,16 +588,7 @@ function logSendDiagnostic(
|
||||
console.log(`[SendDiag] ${stage} ${JSON.stringify(detail)}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。
|
||||
*
|
||||
* 为什么留这个开关:`finally` 里的删除发生在 **hook 返回之后**,这隐含假设
|
||||
* 「hook 返回时发送已经完成」。如果 hook 其实是「先回 200、后台再读文件」,
|
||||
* 文件就可能在它读到之前已经被删掉 —— 现象正好是「hook 报成功、微信里没有消息」。
|
||||
*
|
||||
* 置为非 0 时可分辨两类失败:保留期间图片到了 ⇒ 删除时机问题(修法与 hook 约定文件生命周期);
|
||||
* 仍然没到 ⇒ 与文件生命周期无关。
|
||||
*/
|
||||
/** 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。 */
|
||||
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
|
||||
|
||||
/** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */
|
||||
@@ -784,10 +756,7 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。
|
||||
* 绑定状态由 host 侧保证;未绑定/未就绪时返回与旧契约一致的结果结构。
|
||||
*/
|
||||
/** macOS native runtime 的文字发送:HTTP POST /sendText 到 tm-wechat-host。 */
|
||||
private async sendMacText(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'text' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
@@ -856,12 +825,7 @@ export class PersonalWechatSendService {
|
||||
return { success: true, status: resultStatus }
|
||||
}
|
||||
|
||||
/*
|
||||
* Resolve the bound account's own wxid from the local WeChat data root.
|
||||
* The media proto embeds the sender, and the mac runtime does not learn it
|
||||
* from inbound traffic, so it is read from
|
||||
* the on-disk account identity instead.
|
||||
*/
|
||||
/** Resolve the bound account's own wxid from the local WeChat data root.。 */
|
||||
private async resolveMacSenderWxid(): Promise<string> {
|
||||
const identity = readLocalAccountIdentity(this.wechatFilesRoot)
|
||||
return identity?.wxid ?? ''
|
||||
@@ -881,11 +845,7 @@ export class PersonalWechatSendService {
|
||||
if (response === null || !response.ok) return null
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null
|
||||
if (!payload) return null
|
||||
/*
|
||||
* 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`,
|
||||
* `/SendMsg` 兼容层可能返回 `{status:true}` 或 Windows 风格的 `{ret:0}`。
|
||||
* 这里统一收敛,避免「实际已发送、界面报失败」。
|
||||
*/
|
||||
/** 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`。 */
|
||||
const explicitFailure = payload.ok === false || payload.status === false
|
||||
const ok =
|
||||
!explicitFailure &&
|
||||
@@ -897,13 +857,7 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。
|
||||
*
|
||||
* 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行,
|
||||
* 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。
|
||||
* 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。
|
||||
*/
|
||||
/** macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。 */
|
||||
private async sendMacVideo(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
@@ -1057,8 +1011,7 @@ export class PersonalWechatSendService {
|
||||
if (!sender) return fail('无法识别当前微信账号 wxid')
|
||||
}
|
||||
|
||||
/* Reuse the Windows SILK preparation: it already normalizes any input to
|
||||
* SILK and reports the duration. */
|
||||
/** Reuse the Windows SILK preparation: it already normalizes any input to。 */
|
||||
let temporaryVoicePath: string | undefined
|
||||
try {
|
||||
const prepared = await prepareWindowsVoiceFile(filePath)
|
||||
|
||||
@@ -22,6 +22,20 @@ const FISH_AUDIO_PUBLIC_ASSET_URL = 'https://public-platform.r2.fish.audio/'
|
||||
const DEFAULT_PAGE_SIZE = 24
|
||||
const MAX_PAGE_SIZE = 100
|
||||
const GENERATED_AUDIO_MAX_AGE_MS = 24 * 60 * 60 * 1000
|
||||
const VOICE_META_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
const voiceMetaCache = new Map<string, { voice: TextToSpeechVoice; cachedAt: number }>()
|
||||
|
||||
function cacheVoiceMeta(voice: TextToSpeechVoice): void {
|
||||
if (!voice?.id) return
|
||||
voiceMetaCache.set(voice.id, { voice, cachedAt: Date.now() })
|
||||
}
|
||||
|
||||
function getCachedVoiceMeta(id: string): TextToSpeechVoice | null {
|
||||
const entry = voiceMetaCache.get(id)
|
||||
if (!entry) return null
|
||||
if (Date.now() - entry.cachedAt > VOICE_META_CACHE_TTL_MS) return null
|
||||
return entry.voice
|
||||
}
|
||||
|
||||
interface FishAudioModelEntity {
|
||||
_id: string
|
||||
@@ -128,6 +142,7 @@ export class TextToSpeechSettingsService {
|
||||
let items = payload.items
|
||||
.filter((model) => model.type === 'tts' && model.state === 'trained')
|
||||
.map(toVoice)
|
||||
for (const item of items) cacheVoiceMeta(item)
|
||||
|
||||
const selectedVoiceId = normalizeSelectedVoiceId(loadSettings().ttsSelectedVoiceId)
|
||||
if (
|
||||
@@ -138,7 +153,10 @@ export class TextToSpeechSettingsService {
|
||||
) {
|
||||
if (!items.some((item) => item.id === selectedVoiceId)) {
|
||||
const selected = await this.getVoice(selectedVoiceId, resolved.key)
|
||||
if (selected) items = [selected, ...items]
|
||||
if (selected) {
|
||||
cacheVoiceMeta(selected)
|
||||
items = [selected, ...items]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,6 +247,37 @@ export class TextToSpeechSettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
async getVoiceStatus(): Promise<{
|
||||
configured: boolean
|
||||
model: TextToSpeechModel
|
||||
selectedVoiceId: string
|
||||
selectedVoice: TextToSpeechVoice | null
|
||||
}> {
|
||||
const resolved = this.resolveKey()
|
||||
const settings = loadSettings()
|
||||
const selectedVoiceId = normalizeSelectedVoiceId(settings.ttsSelectedVoiceId)
|
||||
const model = normalizeModel(settings.ttsModel)
|
||||
const configured = Boolean(resolved.key && selectedVoiceId)
|
||||
if (!selectedVoiceId) {
|
||||
return { configured: false, model, selectedVoiceId: '', selectedVoice: null }
|
||||
}
|
||||
const cached = getCachedVoiceMeta(selectedVoiceId)
|
||||
if (cached) {
|
||||
return { configured, model, selectedVoiceId, selectedVoice: cached }
|
||||
}
|
||||
if (!resolved.key) {
|
||||
return { configured: false, model, selectedVoiceId, selectedVoice: null }
|
||||
}
|
||||
const fetched = await this.getVoice(selectedVoiceId, resolved.key)
|
||||
if (fetched) cacheVoiceMeta(fetched)
|
||||
return {
|
||||
configured,
|
||||
model,
|
||||
selectedVoiceId,
|
||||
selectedVoice: fetched
|
||||
}
|
||||
}
|
||||
|
||||
private resolveKey(): {
|
||||
success: boolean
|
||||
key?: string
|
||||
@@ -299,7 +348,7 @@ function toVoice(model: FishAudioModelEntity): TextToSpeechVoice {
|
||||
languages: Array.isArray(model.languages) ? model.languages : [],
|
||||
source: 'fish-audio',
|
||||
coverImage: resolvePublicAssetUrl(model.cover_image || model.author?.avatar),
|
||||
previewUrl: sample?.audio || undefined,
|
||||
previewUrl: resolvePublicAssetUrl(sample?.audio),
|
||||
previewText: sample?.text || model.default_text || undefined,
|
||||
authorName: model.author?.nickname || undefined,
|
||||
taskCount: model.task_count,
|
||||
|
||||
Reference in new issue
Block a user