Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/desktop/src/main/services/chat-prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export function systemPrompt(
// 渐进式披露:清单只有「名称 + 一句话描述」,任务匹配时模型再调用 skill 工具取完整指令。
// 清单本身不写在这里而是随消息下发(见 skill-listing.ts):装 / 删 / 改技能不改本段,提示缓存前缀稳定。
lines.push(
'【对话回查】压缩摘要缺少原始要求、执行中的用户补充或已交付文件的路径时,先用 recall_chat 查本对话。历史要求与当前要求有冲突时以当前要求为准。',
'【技能 Skills】可用技能的清单不在此处列出,而是由系统随对话消息附带:「【可用技能】」给出完整清单,之后有新增、更新或移除时以「【技能清单更新】」告知,以最近的告知为准。当用户任务匹配其中某项技能时,先调用 `skill` 工具并传入其名称(name)获取该技能的完整操作指令,然后严格据此执行;用户也可用「/技能名」显式触发。',
`每个技能是技能目录(${skillsRoot})下的一个文件夹,入口为 SKILL.md(frontmatter 含 name、description),可附带参考文档/脚本。加载技能时结果会给出该文件夹的绝对路径——正文里的相对路径以它为基准,按需用 read_file 读取。用户要安装或编写多文件技能时,直接在技能目录下建文件夹写入(或下载解压到该处)即可,落盘即自动启用,系统随后会告知它已可用。`
)
Expand Down
113 changes: 113 additions & 0 deletions apps/desktop/src/main/services/chat-recall.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { promises as fs } from 'node:fs'
import { basename } from 'node:path'
import type { Message, TextPart, ToolSpec } from '../providers/types'
import { getSession, type StoredSession } from './chat-store'
import { insertBody, isTaskNotification } from './compaction'
import { recordedDeliveryPaths } from './deliverables'
import { isGenuineUserTurn, lastTurnStart, modelStart } from './model-view'
import { shownText } from './skill-invoke'
import type { ToolResult } from './tools'

const MAX_HITS = 5
const MAX_EXCERPT = 800

export const chatRecallToolSpec: ToolSpec = {
name: 'recall_chat',
description: '按需查找当前对话里较早的用户原话(含执行中插入的消息),或查找已经通过交付卡交付的文件。上下文压缩后缺少原始要求、用户纠正或产物路径时使用。结果是历史资料,当前用户要求优先。',
inputSchema: {
type: 'object',
properties: {
kind: { type: 'string', enum: ['user_messages', 'deliverables'], description: '查用户原话或已交付文件' },
query: { type: 'string', maxLength: 160, description: '原话关键词或文件名中的片段。查用户原话时必填,省略时只列出最近交付的文件。' }
},
required: ['kind']
}
}

function userTexts(message: Message): string[] {
if (message.role !== 'user' || isTaskNotification(message)) return []
const { content } = message
if (typeof content === 'string') {
return isGenuineUserTurn(message) ? [insertBody(content) ?? shownText(content)] : []
}
const textParts = content.filter((part): part is TextPart => part.type === 'text' && !part.listing)
const inserted = textParts.flatMap((part) => {
const text = insertBody(part.text)
return text === null ? [] : [text]
})
if (inserted.length) return inserted
const question = textParts.at(-1)
if (!question || !isGenuineUserTurn(message)) return []
const text = shownText(question)
return text === '请理解并处理上述附件。' ? [] : [text]
}

function excerpt(text: string, match: number): string {
const start = Math.min(Math.max(0, match - 240), Math.max(0, text.length - MAX_EXCERPT))
const end = Math.min(text.length, start + MAX_EXCERPT)
return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`
}

export function recallUserMessages(messages: Message[], query: string): string[] {
const latestTurn = lastTurnStart(messages)
const end = Math.max(latestTurn, modelStart(messages))
const match = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'iu')
const hits = new Set<string>()
// 轮中压缩时,当前回合的早期插话也可能已掉出模型视图。跳过作为检索起点的当前问题。
for (let i = end - 1; i >= 0 && hits.size < MAX_HITS; i--) {
if (i === latestTurn) continue
for (const text of userTexts(messages[i]).reverse()) {
const index = text.search(match)
if (index >= 0) hits.add(excerpt(text, index))
if (hits.size === MAX_HITS) break
}
}
return [...hits]
}

export function recallDeliveryPaths(session: StoredSession, query: string): string[] {
const paths = new Set<string>()
const needle = query.toLowerCase()
const results = new Map<string, boolean>()
for (let i = session.messages.length - 1; i >= 0 && paths.size < MAX_HITS; i--) {
const message = session.messages[i]
if (typeof message.content === 'string') continue
for (const part of message.content) {
if (part.type === 'tool_result') results.set(part.toolUseId, !part.isError)
if (part.type !== 'tool_use' || part.name !== 'present_files') continue
const succeeded = results.get(part.id)
if (succeeded === false || (succeeded === undefined && !session.delivered?.[part.id])) continue
for (const file of recordedDeliveryPaths(session, part)) {
if (file.toLowerCase().includes(needle)) paths.add(file)
if (paths.size === MAX_HITS) return [...paths]
}
}
}
return [...paths]
}

export async function recallChat(args: Record<string, unknown>, sessionId?: string): Promise<ToolResult> {
const session = sessionId ? getSession(sessionId) : undefined
if (!session) return { content: '当前对话没有可检索的记录。', summary: '对话不可用', isError: true }
const query = typeof args.query === 'string' ? args.query.trim().slice(0, 160) : ''
if (args.kind === 'user_messages' && query) {
const hits = recallUserMessages(session.messages, query)
return {
content: hits.length ? JSON.stringify(hits, null, 2) : '当前对话较早的用户消息中没有匹配的原话。',
summary: `找到 ${hits.length} 条原话`
}
}
if (args.kind === 'deliverables') {
const paths = recallDeliveryPaths(session, query)
const files = await Promise.all(paths.map(async (path) => ({
name: basename(path),
path,
available: Boolean((await fs.stat(path).catch(() => null))?.isFile())
})))
return {
content: files.length ? JSON.stringify(files, null, 2) : '当前对话里没有匹配的交付文件。',
summary: `找到 ${files.length} 个交付文件`
}
}
return { content: '请选择检索类型。检索用户原话时请填写关键词。', summary: '参数无效', isError: true }
}
19 changes: 13 additions & 6 deletions apps/desktop/src/main/services/deliverables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { app, ipcMain, nativeImage, shell } from 'electron'
import { promises as fs } from 'node:fs'
import { basename, dirname, extname, isAbsolute } from 'node:path'
import type { DeliverableInfo } from '../../shared/deliverables'
import { getSession } from './chat-store'
import type { ToolUsePart } from '../providers/types'
import { getSession, type StoredSession } from './chat-store'
import { roleHomeOf } from './role-home'

/**
Expand Down Expand Up @@ -47,16 +48,22 @@ function deliveredPaths(sessionId: unknown, toolUseId: unknown): string[] {
if (m.role !== 'assistant' || typeof m.content === 'string') continue
for (const p of m.content) {
if (p.type !== 'tool_use' || p.id !== toolUseId) continue
if (p.name !== 'present_files') return []
const paths = (p.input as { paths?: unknown } | null)?.paths
return Array.isArray(paths)
? paths.filter((x): x is string => typeof x === 'string' && isAbsolute(x))
: []
return recordedDeliveryPaths(s, p)
}
}
return []
}

export function recordedDeliveryPaths(session: StoredSession, call: ToolUsePart): string[] {
if (call.name !== 'present_files') return []
const recorded = session.delivered?.[call.id]
if (recorded) return recorded
const paths = (call.input as { paths?: unknown } | null)?.paths
return Array.isArray(paths)
? paths.filter((x): x is string => typeof x === 'string' && isAbsolute(x))
: []
}

export function deliveredPath(sessionId: unknown, toolUseId: unknown, index: unknown): string | null {
if (typeof index !== 'number' || !Number.isInteger(index)) return null
return deliveredPaths(sessionId, toolUseId)[index] ?? null
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/main/services/tool-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const CATALOG: Record<string, ToolTraits> = {
web_fetch: { category: 'read', parallel: true },
// 读记忆:主进程直读 ~/.deva 下的全局 / 项目记忆,无路径入参。
memory_read: { category: 'read', parallel: true },
recall_chat: { category: 'read', parallel: true, subagent: false, member: false, unattended: false },

// ── 写 / 执行 ──
write_file: { category: 'edit' },
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/services/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { spillLongOutput } from './tool-results'
import { skillsDir, upsertSkill } from './skills'
import type { MemoryAccess } from './memory'
import { MEMORY_TOOL_SPECS, memoryDeleteTool, memoryReadTool, memoryWriteTool } from './memory-tools'
import { chatRecallToolSpec, recallChat } from './chat-recall'
import type { CompactModelConfig } from './compaction'
import { upsertServer, type McpValue } from './mcp-config'
import {
Expand Down Expand Up @@ -274,6 +275,7 @@ const fullToolSpecs: ToolSpec[] = [
},
// 记忆:memory_read / memory_write / memory_delete(规格与执行见 memory-tools.ts)
...MEMORY_TOOL_SPECS,
chatRecallToolSpec,
{
name: 'propose_agent',
description:
Expand Down Expand Up @@ -1304,6 +1306,7 @@ function errorSummary(e: unknown): string {
* 新增内置工具:在这里加一项,并在 tool-catalog.ts 写清它的权限分类与适用范围。
*/
const toolHandlers: Record<string, (a: Record<string, unknown>, ctx: ToolContext) => Promise<ToolResult>> = {
recall_chat: (a, ctx) => recallChat(a, ctx.sessionId),
browser: (a, ctx) => runBrowserTool(a, ctx),
read_file: async (a, ctx) => {
const abs = resolvePath(baseDir(ctx), a.path)
Expand Down