feat: Reader Skill 支持版本自检与自助更新

微信机器人回复剥离引用编号、列表改用空行分隔,失败通知补失败时刻
 问问微信关键词检索在索引落后时按单会话直读原始记录兜底
 关闭窗口支持记住选择并在设置中修改
 退群监控刷新列表
This commit is contained in:
Wxw-Gu committed 2026-10-14 10:31:01 +08:00
1 parent fd7d5016a8
commit eaa25cd29e
33 files changed
+1401 -154

No files matched your search

+37 -1
View File
@@ -148,12 +148,48 @@ export function resolveInboundRoute(text: string): InboundRoute {
/** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */
export const QUERY_AGENT_UNAVAILABLE_TEXT = '当前 AI 查询服务暂时不可用,请稍后再试。'
/**
* 桌面 UI 的 inline citation(`[E6]`)在微信里**没有落点** ——
* 点不开、也没有证据卡可以对照,留在正文里纯属噪音。下发前一律剥离。
*
* 只吃行内空格(`[ \t]`)而不是 `\s`:引用可能独占一行,用 `\s*` 会把上一行的换行
* 一起吞掉,把两行粘成一行。
*/
const INLINE_CITATION_PATTERN = /[ \t]*\[E\d+\]/g
function stripInlineCitations(text: string): string {
return text.replace(INLINE_CITATION_PATTERN, '').replace(/[ \t]+$/gm, '')
}
/**
* 微信气泡的换行规则:**单个 `\n` 会被压成空格,只有空行(`\n\n`)才真的换行**。
*
* 所以列表项之间必须用**空行**分隔:单换行等于白发,多条 bullet 会被挤成一整段。
*
* 顺带把 Markdown 列表标记(`-` / `*` / `+`)统一成 `• `:下游
* `markdownToPlainText()` 虽然也做这一步,但它只保证 `• `、不保证前面有空行,
* 在这里先接住才能拿到正确行距。
*/
export function formatWechatReplyText(content: string): string {
return content
.replace(/\r\n?/g, '\n')
.replace(/^[ \t]*[-*+][ \t]+/gm, '• ')
.replace(/[ \t]*•[ \t]*/g, '\n\n• ')
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
/**
* 把 Query Agent 结果映射成**微信文字回复**。
* 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。
*/
export function queryAgentReplyText(result: AskWechatQueryResult): string {
if (result.status === 'answered') return result.answer
if (result.status === 'answered') {
const text = stripInlineCitations(result.answer).trim()
// 极端情况(整段只有引用编号)宁可原样下发,也不能发一条空消息出去。
return text || result.answer.trim()
}
if (result.status === 'provider_unavailable' || result.status === 'error') return result.message
// Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。
return QUERY_AGENT_UNAVAILABLE_TEXT
+3 -11
View File
@@ -17,6 +17,7 @@ import { QueryAgentService } from './query-agent-service'
import { AskWechatService } from './ask-wechat-service'
import {
QUERY_AGENT_UNAVAILABLE_TEXT,
formatWechatReplyText,
queryAgentReplyText,
resolveInboundRoute,
type GroupMemberChatIntent,
@@ -700,7 +701,7 @@ export class AgentHubService {
{ requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text },
conversationKey
)
await this.sendToConversation(conversation, this.formatAIReply(queryAgentReplyText(result)))
await this.sendToConversation(conversation, formatWechatReplyText(queryAgentReplyText(result)))
this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`)
} catch (error) {
this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`)
@@ -834,7 +835,7 @@ export class AgentHubService {
}
await this.sendToConversation(
conversation,
this.formatAIReply(
formatWechatReplyText(
`${displayName}在“${group.m_nsNickName}”的发言总结(共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}`
)
)
@@ -850,15 +851,6 @@ export class AgentHubService {
return `[${label}]`
}
private formatAIReply(content: string): string {
return content
.replace(/\r\n?/g, '\n')
.replace(/[ \t]*•[ \t]*/g, '\n• ')
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
private async generateAndSendReport(
conversation: AgentHubTarget,
intent: GroupReportIntent
+131 -12
View File
@@ -64,8 +64,11 @@ const kinds: QueryMessageType[] = ['text', 'image', 'voice', 'video', 'file', 'l
*
* 一次完整 pass 的耗时以分钟计,远超任何交互预算。所以这个预算只用来兜住「已经很接近追平」
* 的情况:追不上就按当前覆盖如实回答并让后台继续追,而不是把查询卡在索引上。
*
* 2 秒连"索引已经快跑完"都等不到,就会出现**索引正在追、查询却拿旧覆盖下结论**的矛盾表现。
* 15 秒仍远小于一次完整 pass,不会把查询卡住,但足以覆盖"追平在即"的绝大多数情况。
*/
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 2000
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 15000
/**
* 两次由查询触发的追赶之间的最小间隔,避免每个 Query 都重跑一遍索引。
@@ -120,17 +123,26 @@ function formatLocalMinute(ms: number): string {
function buildIndexCoverage(
indexLatestAt: number | null,
sourceLatestAt: number | null,
covered: boolean
covered: boolean,
directReadApplied = false
): QueryIndexCoverage | undefined {
if (indexLatestAt === null) return undefined
const indexLabel = formatLocalMinute(indexLatestAt)
return {
// 注意:直读补齐**不**把 covered 改成 true。
//
// 直读只扫了 `indexLatestAt` 之后那一段(权威源、全量),更早的部分仍然依赖索引;
// 而 `indexLatestAt` 是**全局**水位,不代表"这个会话在更早区间被索引得多完整"。
// 所以这里保持诚实:覆盖结论不变,只在 summary 里说明"这之后已用直读补齐"。
// 一旦把 covered 改成 true,prompt 就会允许模型在 0 结果时下"没有",那是错误的否定。
covered,
indexLatestAtLabel: indexLabel,
...(sourceLatestAt !== null ? { sourceLatestAtLabel: formatLocalMinute(sourceLatestAt) } : {}),
summary: covered
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
summary: directReadApplied
? `关键词索引只更新到 ${indexLabel};这之后的聊天已改用直读原始记录补齐,本会话该区间的结果来自直读。`
: covered
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
}
}
@@ -544,6 +556,7 @@ export class LocalQueryApiService {
let found: Awaited<ReturnType<LocalQueryApiService['probe']>>
let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
let freshnessMs = 0
let directFallback: { evidence: Map<string, QueryEvidenceItem>; scanned: number } | undefined
try {
found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
probeMs.push(...found.probeMs)
@@ -562,13 +575,38 @@ export class LocalQueryApiService {
enrichmentMs += reProbe.enrichmentMs
found = reProbe
}
// 直读兜底必须在这个 `beginInteractiveQuery` 窗口内跑。
//
// 这个窗口的作用就是让后台索引让路;一旦 `endInteractiveQuery()` 放开,
// 正在追赶的索引会立刻进来抢 WCDB,把直读拖成几十秒。
const soleId = conversationIds && conversationIds.length === 1 ? conversationIds[0] : undefined
const soleContact = soleId ? contactByMd5.get(soleId) : undefined
if (!indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) && soleContact) {
// 索引不可信、而范围又恰好是一个会话 → 用 WCDB 直读把索引落后的那一段补上。
// 微信机器人问"某个群最近聊了 X"时,这正是"索引没追完就拿不到东西"的解药。
directFallback = await this.directReadKeywordFallback({
conversationId: soleContact.md5,
contact: soleContact,
probes,
fromMs: found.indexLatestAt,
range,
limit
})
}
} finally {
this.knowledge.endInteractiveQuery()
}
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
const covered = indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)
const indexCoverage = buildIndexCoverage(found.indexLatestAt, found.sourceLatestAt, covered)
const evidence = new Map(found.evidence)
if (directFallback) for (const [key, item] of directFallback.evidence) evidence.set(key, item)
const indexCoverage = buildIndexCoverage(
found.indexLatestAt,
found.sourceLatestAt,
covered,
directFallback !== undefined
)
// 图片文字索引是**独立覆盖维度**:文字索引再完整也不代表图片里的文字搜得到。
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
const timings: QuerySearchTimings = {
@@ -586,8 +624,8 @@ export class LocalQueryApiService {
resolvedTimeRange: range,
coverage: { state: this.searchCoverage(found, requestedEnd) },
probeCount: probes.length,
evidenceCount: found.evidence.size,
evidence: Array.from(found.evidence.values()).slice(0, limit),
evidenceCount: evidence.size,
evidence: Array.from(evidence.values()).slice(0, limit),
scope: corpus.scope,
indexLatestAt: found.indexLatestAt,
sourceLatestAt: found.sourceLatestAt,
@@ -598,6 +636,80 @@ export class LocalQueryApiService {
}
}
/**
* 索引不可信时的**直读兜底** —— 只在"范围恰好是一个会话"时启用。
*
* `search_messages` 是四个 Query Tool 里唯一依赖派生索引的:索引在追赶期间它给不出新消息,
* 而 WCDB 才是权威源、永远最新。跨会话直读不可行(要遍历上千个会话,实测大会话全量读一次
* 15s 以上),但**单个会话**成本可控 —— 所以只在这一种形状下降级,其余情况仍如实标 partial。
*
* 只扫索引**没覆盖**的那一段(`fromMs` 之后):已经进索引的部分仍以索引结果为准,不重复劳动。
* 匹配口径与索引保持一致:正文 + 语音转写 + 图片 OCR 派生文本。
*/
private async directReadKeywordFallback(input: {
conversationId: string
contact: FormattedContact
probes: string[]
/** 索引水位(epoch **毫秒**);null 表示索引还没建立过,那就从头扫。 */
fromMs: number | null
range: ResolvedTimeRange
limit: number
}): Promise<{ evidence: Map<string, QueryEvidenceItem>; scanned: number }> {
// freshness 是**毫秒**口径,而 WCDB 读消息的时间窗是**秒**口径。
// 显式换算,不让两种单位在同一个表达式里静默错位(这个坑历史上踩过)。
const coveredSeconds = input.fromMs === null ? undefined : Math.floor(input.fromMs / 1000)
const startTime =
coveredSeconds === undefined
? input.range.startTime
: input.range.startTime === undefined
? coveredSeconds
: Math.max(input.range.startTime, coveredSeconds)
const raw = await listMessagesAsync(input.conversationId, startTime, input.range.endTime)
const needles = input.probes
.map((value) => value.trim().toLowerCase())
.filter(Boolean)
const evidence = new Map<string, QueryEvidenceItem>()
for (const message of raw) {
if (evidence.size >= input.limit) break
const kind = kindOf(message)
const ocr =
kind === 'image' ? this.imageOcrEntry?.(input.conversationId, sourceMessageId(message)) : undefined
const haystack = [
message.content,
message.voiceTranscript,
ocr && ocr.state === 'indexed' ? ocr.text : ''
]
.filter(Boolean)
.join('\n')
.toLowerCase()
if (!haystack || !needles.some((needle) => haystack.includes(needle))) continue
const item = toQueryMessage(
input.conversationId,
message,
input.contact,
ocr,
this.voiceSnapshot(message)
)
// key 必须与索引路径一致(`会话:归一化消息 id`):两条路径可能命中同一条消息,
// 合并时要能去重。`message.id` 可能带 `local:` 装饰,所以走归一化。
const normalizedId = normalizeMessageIdentity(input.conversationId, message.id)?.messageId
if (!normalizedId) continue
evidence.set(`${input.conversationId}:${normalizedId}`, {
messageRef: item.messageRef,
timestamp: item.timestamp,
sender: item.sender,
sourceKind: item.sourceKind,
text: toEvidenceDisplayText(item.text ?? ''),
...(item.derivedSource ? { derivedSource: item.derivedSource } : {}),
...(item.imageOcrText ? { imageOcrText: item.imageOcrText } : {}),
conversationName: contactView(input.contact).displayName,
conversationType: input.contact.type
})
}
return { evidence, scanned: raw.length }
}
/** 逐 probe 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */
private async probe(
probes: string[],
@@ -721,12 +833,19 @@ export class LocalQueryApiService {
if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' }
const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS)
if (!request.triggered) {
// 已经在跑 → 复用;刚触发过 → 节流。两种都不阻塞本次查询,后台继续追。
return { resynced: false, catchUp: request.inProgress ? 'reused' : 'skipped' }
// 只有在"刚刚触发过、节流窗口内"时才不等 —— 那种情况再等也没意义。
if (!request.triggered && !request.inProgress) {
return { resynced: false, catchUp: 'skipped' }
}
// 本次触发、以及**正在跑(复用)**两种都要等。
//
// 复用场景若直接返回旧快照,就会出现**索引明明在追、查询却拿旧覆盖下结论**的表现。
// 等待后统一 `resynced: true`:即使没等到追平,索引也可能前进了一段,值得按新覆盖重查一次。
const completed = await this.knowledge.waitForIndexingComplete(QUERY_FRESHNESS_WAIT_BUDGET_MS)
return { resynced: true, catchUp: completed ? 'completed' : 'pending' }
return {
resynced: true,
catchUp: completed ? 'completed' : request.triggered ? 'pending' : 'reused'
}
}
/**
+2
View File
@@ -299,6 +299,8 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使
- indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。
- 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。
- 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。
- 结论句说"暂时无法确认"时**不能只停在那里**:必须同时给出可执行的下一步 —— 明确告诉用户「指定某个群或联系人、再加上时间再问一次」,这类精确查询读的是原始聊天记录,**不受索引进度影响**。索引在后台追赶可以如实说明,但那是背景,不是结论的终点。
- 结论句若说"已改用直读原始记录补齐",表示这段**已经查过原始记录了**:直接按检索结果回答即可,**不要**再让用户换问法,也不要再说"暂时无法确认"。
图片文字索引:search_messages 的 imageOcrCoverage 是**独立于文字索引**的覆盖维度,只针对“图片里的文字”(截图、报价图、公告截图、海报)。规则:
- 文字消息索引完整**不代表**图片里的文字搜得到。不要把这两个维度混着说。
- 问题涉及图片里的文字、而 imageOcrCoverage.state 不是 complete 时:即使图片证据为 0,也**绝不能**回答“没有”或“没找到”。必须如实引用 imageOcrCoverage.summary,说明图片文字索引尚未完成、当前无法确认全部历史图片。
+25 -4
View File
@@ -613,7 +613,10 @@ export class ScheduledReportService {
payload?.severity || notification.severity,
payload?.title || notification.title,
payload?.message || notification.message,
payload?.suggestedAction
payload?.suggestedAction,
// 用**失败发生时刻**而不是发送时刻:pending 通知会跨天补发,
// 同一批里几条文案完全相同的失败,只有这个时间能区分开。
notification.createdAt
)
})
if (result.success) {
@@ -679,17 +682,20 @@ export class ScheduledReportService {
severity: ScheduledReportNotificationSeverity,
title: string,
message: string,
suggestedAction?: string
suggestedAction?: string,
occurredAt?: string
): string {
const icon = severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : '✅'
const stamp = formatNotificationTimestamp(occurredAt)
return [
`${icon} ${ruleName}`,
`${icon} ${ruleName}${stamp ? ` · ${stamp}` : ''}`,
title,
message,
suggestedAction ? `建议:${suggestedAction}` : ''
]
.filter(Boolean)
.join('\n')
// 必须用**空行**分隔:微信会把单个换行压成空格,否则整条通知会连成一行长句。
.join('\n\n')
}
// ---------------------------------------------------------------------------
@@ -996,6 +1002,21 @@ export class ScheduledReportService {
}
}
/**
* 微信通知里的时间戳(「10月13日 16:28」)。
*
* 必须精确到分钟而不是只到「几月几日」:pending 通知会跨天补发,同一批里
* 几条文案完全相同的失败(同规则、同原因),只到日仍然分不清谁是谁。
* 时间非法时返回空串,调用方据此去掉整段前缀。
*/
const formatNotificationTimestamp = (iso?: string): string => {
if (!iso) return ''
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return ''
const pad = (value: number): string => String(value).padStart(2, '0')
return `${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
const asArray = <T>(value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : [])
const executionStatuses = new Set<ScheduledReportExecution['status']>([
+20 -1
View File
@@ -20,6 +20,8 @@ function redirectLegacyWeChatFilesToXwechat(candidate: string): string {
return candidate
}
export type CloseAction = 'ask' | 'tray' | 'quit'
export interface AppSettings {
dbRoot: string
apiEnabled: boolean
@@ -47,6 +49,17 @@ export interface AppSettings {
* 不在用户界面暴露实验性名称)。
*/
queryAgentEnabled: boolean
/**
* 关闭主窗口时的行为。
*
* - `ask`:每次弹窗询问(默认,保持既有行为)
* - `tray`:直接最小化到系统托盘,应用继续在后台跑
* - `quit`:直接退出整个进程
*
* 只有用户在关闭弹窗里勾了"记住我的选择"才会离开 `ask`;
* 设置页随时可以改回来。
*/
closeAction: CloseAction
}
function getDefaultDbRoot(): string {
@@ -131,7 +144,8 @@ const DEFAULT_SETTINGS: AppSettings = {
ttsModel: 's2.1-pro-free',
windowsWechatPort: '',
reportImagePostfixText: '今日日报',
queryAgentEnabled: true
queryAgentEnabled: true,
closeAction: 'ask'
}
const SETTINGS_FILE = path.join(
@@ -176,6 +190,11 @@ export function loadSettings(): AppSettings {
if (cache.dbRoot) {
cache.dbRoot = redirectLegacyWeChatFilesToXwechat(cache.dbRoot)
}
// 关闭行为可能来自旧版本或手改过的 settings.json —— 非法值一律收敛回 `ask`。
// 放任非法值会造成最难排查的一种表现:点关闭窗口什么也不发生。
if (cache.closeAction !== 'ask' && cache.closeAction !== 'tray' && cache.closeAction !== 'quit') {
cache.closeAction = 'ask'
}
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
+138 -18
View File
@@ -1,5 +1,6 @@
import { createHash } from 'crypto'
import { app, shell } from 'electron'
import { existsSync, promises as fs } from 'fs'
import { existsSync, readFileSync, promises as fs, statSync } from 'fs'
import { dirname, join } from 'path'
import { isPackagedRuntime } from '../runtime-mode'
@@ -8,7 +9,8 @@ const SKILL_RELATIVE_PATHS = [
join('skill', 'wechatexplorer-reader', 'SKILL.md')
]
const GITHUB_URL = 'https://github.com/Wxw-Gu/TraceMemo/tree/main/docs/skill/tracememo-reader'
const SKILL_VERSION = 'v1.2'
export const READER_SKILL_NAME = 'tracememo-reader'
type SkillResourceSource = 'development' | 'bundled'
@@ -27,7 +29,9 @@ interface SkillCandidate {
export interface SkillResourceStatus {
available: boolean
name?: string
version?: string
contentHash?: string
filePath?: string
directoryPath?: string
source: SkillResourceSource
@@ -35,6 +39,27 @@ export interface SkillResourceStatus {
error?: string
}
export interface SkillDocument {
name: string
version?: string
contentHash: string
modifiedAt: string
markdown: string
filePath: string
}
export interface SkillFrontmatter {
name?: string
version?: string
}
interface SkillDocumentCacheEntry {
filePath: string
mtimeMs: number
size: number
document: SkillDocument
}
function currentEnvironment(): SkillPathEnvironment {
return {
appPath: app.getAppPath(),
@@ -54,6 +79,81 @@ function uniqueCandidates(candidates: SkillCandidate[]): SkillCandidate[] {
})
}
/**
* 版本号只认 SKILL.md frontmatter 的 `version`,不再维护源码常量:
* 常量与文档分离必然漂移,曾经出现过文档改了两轮而版本号纹丝不动的情况。
*/
export function parseSkillFrontmatter(content: string): SkillFrontmatter {
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content)
if (!match) return {}
const block = match[1]
if (!block) return {}
const frontmatter: SkillFrontmatter = {}
for (const rawLine of block.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line || line.startsWith('#')) continue
const separator = line.indexOf(':')
if (separator <= 0) continue
const key = line.slice(0, separator).trim().toLowerCase()
const value = line
.slice(separator + 1)
.trim()
.replace(/^["']/, '')
.replace(/["']$/, '')
if (!value) continue
if (key === 'name') frontmatter.name = value
else if (key === 'version') frontmatter.version = value
}
return frontmatter
}
function hashSkillContent(content: string): string {
return createHash('sha256').update(content, 'utf8').digest('hex')
}
let cachedDocument: SkillDocumentCacheEntry | null = null
/**
* 同步读取 Skill 文档。`/health` 属于高频接口,因此按 mtime + size 缓存,
* 文件被替换(版本升级)后缓存自动失效。
*/
export function readSkillDocument(filePath: string): SkillDocument | null {
try {
const stats = statSync(filePath)
if (
cachedDocument &&
cachedDocument.filePath === filePath &&
cachedDocument.mtimeMs === stats.mtimeMs &&
cachedDocument.size === stats.size
) {
return cachedDocument.document
}
const markdown = readFileSync(filePath, 'utf-8')
const frontmatter = parseSkillFrontmatter(markdown)
const document: SkillDocument = {
name: frontmatter.name || READER_SKILL_NAME,
contentHash: hashSkillContent(markdown),
modifiedAt: stats.mtime.toISOString(),
markdown,
filePath
}
if (frontmatter.version) document.version = frontmatter.version
cachedDocument = {
filePath,
mtimeMs: stats.mtimeMs,
size: stats.size,
document
}
return document
} catch {
cachedDocument = null
return null
}
}
export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCandidate[] {
const runtime = environment || currentEnvironment()
const developmentPaths = SKILL_RELATIVE_PATHS.flatMap((relativePath) => [
@@ -82,26 +182,40 @@ export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCan
export function resolveSkillResourceStatus(
environment?: SkillPathEnvironment
): SkillResourceStatus {
const candidates = getSkillCandidates(environment)
const resolved = candidates.find((candidate) => existsSync(candidate.path))
const filePath = resolved?.path || candidates[0].path
const source = resolved?.source || candidates[0].source
const directoryPath = dirname(filePath)
if (!resolved) {
return {
available: false,
source,
githubUrl: GITHUB_URL,
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
let candidates: SkillCandidate[] = []
let source: SkillResourceSource = environment?.packaged ? 'bundled' : 'development'
try {
candidates = getSkillCandidates(environment)
const resolved = candidates.find((candidate) => existsSync(candidate.path))
if (resolved) {
const filePath = resolved.path
const status: SkillResourceStatus = {
available: true,
filePath,
directoryPath: dirname(filePath),
source: resolved.source,
githubUrl: GITHUB_URL
}
const document = readSkillDocument(filePath)
if (document) {
status.name = document.name
status.contentHash = document.contentHash
if (document.version) status.version = document.version
}
return status
}
const fallback = candidates[0]
if (fallback) source = fallback.source
} catch {
// 环境探测失败(例如非 Electron 进程)时退化成“不可用”:
// /health 是外部 Agent 的自检入口,不能因为 Skill 读不到就整条挂掉。
}
return {
available: true,
version: SKILL_VERSION,
filePath,
directoryPath,
available: false,
source,
githubUrl: GITHUB_URL
githubUrl: GITHUB_URL,
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
}
}
@@ -112,6 +226,12 @@ function getStatus(): SkillResourceStatus {
export const skillResourceService = {
getStatus,
getDocument(): SkillDocument | null {
const status = this.getStatus()
if (!status.available || !status.filePath) return null
return readSkillDocument(status.filePath)
},
async read(): Promise<{ success: boolean; content?: string; error?: string }> {
const status = this.getStatus()
if (!status.available || !status.filePath) return { success: false, error: status.error }