Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): redact sensitive values in chat history reader and error surfaces (issue #3098)
Battleplusfa0d3b6ab957
diff --git a/apps/desktop/src/main/localDb/chatHistoryReader.ts b/apps/desktop/src/main/localDb/chatHistoryReader.tsindex de5ea9a5d7..561afc6b38 100644--- a/apps/desktop/src/main/localDb/chatHistoryReader.ts+++ b/apps/desktop/src/main/localDb/chatHistoryReader.ts@@ -304,6 +304,10 @@ export async function listSessionsForHistory(// ── get_chat_history ────────────────────────────────────────────────────────+/**+ * history reader 接受的 role 全集。'error' 为技术性 role: terminal error 诊断行+ * (role: 'error', content 已脱敏) 只有调用方显式列出时才会被返回, 不进默认集。+ */export type HistoryRole =| 'user'| 'assistant'@@ -311,7 +315,8 @@ export type HistoryRole =| 'tool_result'| 'ask_user'| 'plan_review'- | 'thinking';+ | 'thinking'+ | 'error';export interface GetMessagesParams {sessionIds: string[] | null;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.tsindex e0031dbbc8..d1ecdb5f9b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts@@ -363,4 +363,99 @@ describe('local-db:history:messages', () => {expect(readTerminal).toHaveBeenCalledWith('session-1', null);expect(page.terminal).toBeNull();});++ it('accepts the error role on the wire and forwards it to the reader', async () => {+ const getMessages = vi.fn(async () => ({+ items: [{+ id: 'm-error',+ sessionId: 'session-1',+ sessionWorkingDir: null,+ sessionAgentKind: 'cc',+ sessionTitle: 'Session',+ role: 'error',+ content: { message: 'worker terminated without output' },+ toolUseId: null,+ agentMeta: null,+ createdAt: 500,+ rewindAt: null,+ }],+ nextCursor: null,+ hasMore: false,+ }));+ register({+ sessionExists: vi.fn(async () => true),+ getMessages,+ });++ const handler = handlers.get(DL_HISTORY_MESSAGES_CHANNEL);+ const page = await handler?.({}, { ...request, roles: ['error'] }) as {+ items: Array<{ role: string }>;+ };++ expect(getMessages).toHaveBeenCalledWith(expect.objectContaining({ roles: ['error'] }));+ expect(page.items.map((row) => row.role)).toEqual(['error']);+ });++ it('redacts sensitive text in error rows before they cross device-link', async () => {+ const getMessages = vi.fn(async () => ({+ items: [{+ id: 'm-error-secret',+ sessionId: 'session-1',+ sessionWorkingDir: null,+ sessionAgentKind: 'cc',+ sessionTitle: 'Session',+ role: 'error',+ // 写入侧只脱敏过 message / sdkError, reason / toolLoop 是入库原样内容。+ content: {+ message: 'worker terminated without output; last token sk-abc123secret leaked',+ reason: 'Bearer sk-abc123secret expired',+ sdkError: 'Authorization: Bearer sk-abc123secret',+ toolLoop: 'api_key=sk-abc123secret',+ },+ toolUseId: null,+ agentMeta: null,+ createdAt: 500,+ rewindAt: null,+ }],+ nextCursor: null,+ hasMore: false,+ }));+ register({+ sessionExists: vi.fn(async () => true),+ getMessages,+ });++ // device-link 默认 roles=null 走全 role 集, error 行会随默认集出网, 必须脱敏。+ const handler = handlers.get(DL_HISTORY_MESSAGES_CHANNEL);+ const page = await handler?.({}, { ...request, roles: ['error'] }) as {+ items: Array<{ role: string; content: Record<string, string> }>;+ };++ const redacted = page.items[0].content;+ expect(page.items[0].role).toBe('error');+ // 原始凭据绝不出网+ expect(JSON.stringify(redacted)).not.toContain('sk-abc123secret');+ // 各字段脱敏形态符合 redactSensitiveText 约定: 凭据值被 mask,+ // 但 Bearer 前缀 / 上下文文字(如 " expired")会保留。+ expect(redacted.message).toContain('[REDACTED_KEY]');+ expect(redacted.message).not.toContain('sk-abc123secret');+ expect(redacted.reason).toContain('Bearer [REDACTED]');+ expect(redacted.reason).not.toContain('sk-abc123secret');+ expect(redacted.sdkError).toBe('Authorization: [REDACTED]');+ expect(redacted.toolLoop).toBe('api_key=[REDACTED_KEY]');+ });++ it('still rejects roles outside the allowlist', async () => {+ const getMessages = vi.fn();+ register({+ sessionExists: vi.fn(async () => true),+ getMessages,+ });++ const handler = handlers.get(DL_HISTORY_MESSAGES_CHANNEL);+ await expect(handler?.({}, { ...request, roles: ['nope'] })).rejects.toThrow(+ '[INVALID_PARAMS]',+ );+ expect(getMessages).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/localDb/ipc/history.ts b/apps/desktop/src/main/localDb/ipc/history.tsindex e22a700159..c9d06c3693 100644--- a/apps/desktop/src/main/localDb/ipc/history.ts+++ b/apps/desktop/src/main/localDb/ipc/history.ts@@ -20,6 +20,7 @@ import { getDbClient } from '../client/current';import { sessions } from '../schema';import { readLatestSessionTerminal, type SessionTerminalHint } from '../sessionTerminal';import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate';+import { redactSensitiveTextDeep } from '@cindy/maker-shared/error-redaction';const VALID_AGENT_KINDS: readonly HistoryAgentKind[] = ['cc', 'codex', 'pi'];const VALID_ORDERS: readonly HistoryOrder[] = ['asc', 'desc'];@@ -31,6 +32,7 @@ const VALID_ROLES: readonly HistoryRole[] = ['ask_user','plan_review','thinking',+ 'error',];/** Wire payload accepted by the remote history channel. */@@ -266,6 +268,24 @@ function capReferenceHistoryPage(};}+/**+ * 跨设备出口前的最后一道理脱敏兜底: device-link 默认 roles=null 走全 role 集,+ * 错误诊断行 (role='error') 会随默认集出网。写入侧只有 content.message /+ * sdkError 过过 redactSensitiveText, reason / toolLoop 等其余字段是入库原样内容,+ * 不过脱敏。所以出口这里必须自己把 error 行的敏感字符串叶子统一脱敏, 否则凭据 /+ * 内部 id 会随错误行流出受控端。其余 role 逐字节透传, 行为不变。+ */+function redactErrorRowsInPage(+ page: Awaited<ReturnType<typeof getMessagesForHistory>>,+): Awaited<ReturnType<typeof getMessagesForHistory>> {+ return {+ ...page,+ items: page.items.map((m) =>+ m.role === 'error' ? { ...m, content: redactSensitiveTextDeep(m.content) } : m,+ ),+ };+}+const defaultSessionExists = async (sessionId: string): Promise<boolean> => {const rows = await getDbClient().drizzle.select({ id: sessions.id })@@ -313,7 +333,11 @@ export function registerRemoteHistoryIpc(deps: RemoteHistoryIpcDeps = defaultDeprequest.roles === null ||request.roles.some((role) => role !== 'user' && role !== 'assistant');return {- ...capReferenceHistoryPage(page, request.contentCharLimit, preserveStructuredRoles),+ ...capReferenceHistoryPage(+ redactErrorRowsInPage(page),+ request.contentCharLimit,+ preserveStructuredRoles,+ ),terminal: terminal ?? null,};});diff --git a/packages/lizi-mcps/src/__tests__/getChatHistoryTool.test.ts b/packages/lizi-mcps/src/__tests__/getChatHistoryTool.test.tsindex 6eafe00f59..6433379cbf 100644--- a/packages/lizi-mcps/src/__tests__/getChatHistoryTool.test.ts+++ b/packages/lizi-mcps/src/__tests__/getChatHistoryTool.test.ts@@ -79,6 +79,116 @@ describe('get_chat_history cursor pagination', () => {});});+describe('get_chat_history error role', () => {+ it('returns error rows when the caller lists the role explicitly', async () => {+ const getMessages = vi.fn(async () => ({+ ok: true as const,+ page: {+ items: [{+ id: 'm-error',+ sessionId: 'session-1',+ sessionWorkingDir: null,+ sessionAgentKind: 'cc',+ sessionTitle: 'Session',+ role: 'error',+ content: { message: 'worker 派发成功后无输出就终止', sdkError: '[redacted]' },+ toolUseId: null,+ agentMeta: null,+ createdAt: 1_700_000_000_000,+ rewindAt: null,+ }],+ nextCursor: null,+ hasMore: false,+ },+ }));+ const history = {+ listWorkdirs: vi.fn(),+ listSessions: vi.fn(),+ getMessages,+ searchChatHistory: vi.fn(),+ } satisfies XdtHelperHistoryDeps;+ const registry = new XdtHelperToolRegistry();+ registerGetChatHistoryTool(registry, { history });++ const result = await registry.call('get_chat_history', {+ session_ids: ['session-1'],+ roles: ['error'],+ });++ expect(result.isError).toBeFalsy();+ expect(getMessages).toHaveBeenCalledWith(expect.objectContaining({+ roles: ['error'],+ rolesDefaulted: false,+ }));+ const payload = parseText(result) as {+ messages: Array<{ role: string }>;+ query: { roles: string[]; roles_defaulted: boolean };+ };+ expect(payload.query.roles).toEqual(['error']);+ expect(payload.query.roles_defaulted).toBe(false);+ expect(payload.messages.map((m) => m.role)).toEqual(['error']);+ });++ it('keeps error rows out of the unchanged default role set', async () => {+ const items = [+ {+ id: 'm-user',+ sessionId: 'session-1',+ sessionWorkingDir: null,+ sessionAgentKind: 'cc',+ sessionTitle: 'Session',+ role: 'user',+ content: 'hello',+ toolUseId: null,+ agentMeta: null,+ createdAt: 1_700_000_000_000,+ rewindAt: null,+ },+ {+ id: 'm-error',+ sessionId: 'session-1',+ sessionWorkingDir: null,+ sessionAgentKind: 'cc',+ sessionTitle: 'Session',+ role: 'error',+ content: { message: 'worker 派发成功后无输出就终止' },+ toolUseId: null,+ agentMeta: null,+ createdAt: 1_700_000_000_001,+ rewindAt: null,+ },+ ];+ const getMessages = vi.fn(async (args: { roles: readonly string[] | null }) => ({+ ok: true as const,+ page: {+ items: items.filter((m) => args.roles?.includes(m.role)),+ nextCursor: null,+ hasMore: false,+ },+ }));+ const history = {+ listWorkdirs: vi.fn(),+ listSessions: vi.fn(),+ getMessages,+ searchChatHistory: vi.fn(),+ } satisfies XdtHelperHistoryDeps;+ const registry = new XdtHelperToolRegistry();+ registerGetChatHistoryTool(registry, { history });++ const payload = parseText(+ await registry.call('get_chat_history', { session_ids: ['session-1'] }),+ ) as { messages: Array<{ role: string }>; query: { roles: string[] } };++ expect(getMessages).toHaveBeenCalledWith(expect.objectContaining({+ roles: ['user', 'assistant', 'ask_user', 'plan_review'],+ rolesDefaulted: true,+ }));+ expect(payload.query.roles).toEqual(['user', 'assistant', 'ask_user', 'plan_review']);+ expect(payload.query.roles).not.toContain('error');+ expect(payload.messages.map((m) => m.role)).toEqual(['user']);+ });+});+describe('get_chat_history role defaults', () => {it('marks omitted roles so remote adapters can keep their bounded default', async () => {const getMessages = vi.fn(async () => ({diff --git a/packages/lizi-mcps/src/xdt-helper/_history_types.ts b/packages/lizi-mcps/src/xdt-helper/_history_types.tsindex 5c5ee1acc6..bcf1d338b5 100644--- a/packages/lizi-mcps/src/xdt-helper/_history_types.ts+++ b/packages/lizi-mcps/src/xdt-helper/_history_types.ts@@ -25,6 +25,12 @@ export type HistoryReadErrorCode =| 'REMOTE_TIMEOUT'| 'REMOTE_PAYLOAD_TOO_LARGE';+/**+ * history 读取侧可读的 message role 全集。+ * 'error' 是技术性 role: 由 terminal error 诊断行落库(messagePersistBroadcaster+ * 写入 role: 'error', content 内 message / sdkError 已过 redactSensitiveText 脱敏),+ * 与 tool_use / tool_result / thinking 一样仅在调用方显式列出时才返回。+ */export type HistoryRole =| 'user'| 'assistant'@@ -32,7 +38,8 @@ export type HistoryRole =| 'tool_result'| 'ask_user'| 'plan_review'- | 'thinking';+ | 'thinking'+ | 'error';export interface HistoryCursor {/** unix ms */diff --git a/packages/lizi-mcps/src/xdt-helper/get_chat_history.ts b/packages/lizi-mcps/src/xdt-helper/get_chat_history.tsindex 71305326e8..a8294129d4 100644--- a/packages/lizi-mcps/src/xdt-helper/get_chat_history.ts+++ b/packages/lizi-mcps/src/xdt-helper/get_chat_history.ts@@ -13,6 +13,7 @@*/import { BRAND_NAME } from '@cindy/maker-shared/branding';+import { redactSensitiveTextDeep } from '@cindy/maker-shared/error-redaction';import { z } from 'zod';import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';@@ -29,6 +30,7 @@ const ROLE_VALUES = ['ask_user','plan_review','thinking',+ 'error',] as const satisfies readonly HistoryRole[];/**@@ -66,9 +68,16 @@ const DESCRIPTION = ['传 include_full_history=true 解锁。响应里的 query.auto_window_days 会标明窗口是否生效。','','【默认只返问答类 role】不传 roles = 只返 user / assistant / ask_user / plan_review,',- '排除 tool_use / tool_result / thinking 这些开发者 debug 用的技术性 role(体积大且',+ '排除 tool_use / tool_result / thinking / error 这些开发者 debug 用的技术性 role(体积大且','对"回顾对话"无价值)。需要工具调用 / 思考链等技术 role 时, 在 roles 里显式列出',- '(例如要全量就传 roles=["user","assistant","tool_use","tool_result","ask_user","plan_review","thinking"])。',+ '(例如要全量就传 roles=["user","assistant","tool_use","tool_result","ask_user","plan_review","thinking","error"])。',+ '',+ '【error 是技术性 role, 需显式列出】role="error" 是终端错误诊断行(worker 派发成功后',+ '无输出就终止等技术性终止会落一行), 默认集不含它——只有显式传 roles=["error"] 才返回。',+ 'error 行 content 里 message / sdkError 已由 redactSensitiveText 脱敏(凭据值呈现为 [REDACTED]',+ '或 [REDACTED_KEY], Bearer 形态保留前缀如 "Bearer [REDACTED]"); 其余字段是写入侧原样内容,',+ '未过脱敏, 不要把 error 行当可信干净的日志外发。用于判断"这轮是不是技术性失败",',+ '不应当作对话正文渲染给用户。','','【返回原始数据】content 是 JSON.parse 后的原始结构 (按 role 形态不同, 调用方自己解析),','不做任何 markdown / 文本拼装。',@@ -125,7 +134,9 @@ export function registerGetChatHistoryTool(.optional().describe('只返这些 role 的消息。不传 = 默认只返问答类(user/assistant/ask_user/plan_review),' +- '排除 tool_use/tool_result/thinking 等技术性 role。需要技术 role 时, 在数组里显式列出。',+ '排除 tool_use/tool_result/thinking/error 等技术性 role。需要技术 role 时, 在数组里显式列出。' ++ 'role="error" 是终端错误诊断行(默认不返), 显式传 roles=["error"] 才返回;' ++ '其 content.message / sdkError 已脱敏, 其余字段为写入侧原样内容。',),include_rewound: z.boolean()@@ -256,11 +267,14 @@ export function registerGetChatHistoryTool(title: m.sessionTitle,};}+ // error 行的 content 只有 message / sdkError 在写入侧过过脱敏,reason 等其余+ // 字段是原样入库的。出口必须自己兜住,否则未知结构的原始字段会直接出网。+ // 其余 role 逐字节透传,保持既有行为不变。const out: Record<string, unknown> = {id: m.id,sessionId: m.sessionId,role: m.role,- content: m.content,+ content: m.role === 'error' ? redactSensitiveTextDeep(m.content) : m.content,createdAt: new Date(m.createdAt).toISOString(),};if (m.toolUseId !== null) out.toolUseId = m.toolUseId;diff --git a/packages/maker-shared/src/errorRedaction.ts b/packages/maker-shared/src/errorRedaction.tsindex 8efac54c9e..0ff22b3533 100644--- a/packages/maker-shared/src/errorRedaction.ts+++ b/packages/maker-shared/src/errorRedaction.ts@@ -38,6 +38,34 @@ export function redactSensitiveText(input: string): string {return output;}+/**+ * Recursively apply `redactSensitiveText` to every string leaf of an unknown+ * structure, preserving keys and shape.+ *+ * Why this exists: error rows are persisted as `{ message, reason?, sdkError?,+ * toolLoop?, providerId? }` but only `message` / `sdkError` pass through+ * `redactSensitiveText` on the write path — `reason` is stored verbatim. Any+ * exit that hands error rows to another process or device must therefore+ * redact on the way out, otherwise raw operator-visible strings can leave the+ * controlled device.+ *+ * Non-string leaves (number / boolean / null / undefined) are returned as-is;+ * the intent is masking, not coercion. Input is expected to come from+ * JSON.parse, so reference cycles are not handled.+ */+export function redactSensitiveTextDeep(input: unknown): unknown {+ if (typeof input === 'string') return redactSensitiveText(input);+ if (Array.isArray(input)) return input.map((item) => redactSensitiveTextDeep(item));+ if (input && typeof input === 'object') {+ const output: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(input as Record<string, unknown>)) {+ output[key] = redactSensitiveTextDeep(value);+ }+ return output;+ }+ return input;+}+export interface NonSecretErrorSignals {errorStatus?: 401 | 429 | 529;usageLimit: boolean;