Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(companions): discover and search attributed cross-channel history

Chrisc3110df49b3b
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.ts
index bf7b5bfe54..ef4ba310ba 100644
--- a/apps/desktop/src/main/hook-control/ipc.ts
+++ b/apps/desktop/src/main/hook-control/ipc.ts
@@ -1274,6 +1274,12 @@ export function registerHookControlIpc(): void {
log.info('hook-control ipc registered');
}
+/** Read the current owner's already-loaded assignment without starting a transport. */
+export function readXCompanionAssignment(): { botId: string; enabled: boolean } | null {
+ const config = store?.get();
+ return config?.xCompanionBotId ? { botId: config.xCompanionBotId, enabled: config.xEnabled } : null;
+}
+
/** Called after the current account DB is ready; app:ready-for-bot may retry it. */
export function startHookControlAccount(): void {
if (!hookControlAvailable()) return;
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
index c82a936976..c076812910 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
@@ -82,6 +82,7 @@ vi.mock('../../../security/trustedAppRenderer', () => ({ assertTrustedAppRendere
import {
addBotImConnection,
+ buildBotImConnectionListPayload,
configureBotImConnectionRuntime,
setWechatCompanionBinding,
getBotFeishuTransport,
@@ -544,6 +545,17 @@ describe('bot im connection runtime', () => {
expect(h.sent).toEqual([{ channel: 'wechatBot:channel-settings-changed', payload: readWechatChannelSettings() }]);
});
+ // Owner recall must discover only the selected teammate's persisted connections,
+ // including disconnected ones, without changing the settings page's all-bot view.
+ it('projects only the requested teammate connections after transports stop', async () => {
+ const a = await addBotImConnection({ botId: 'bot-mia', channel: 'telegram', token: '1:ABCDEFGHIJKLMNOPQRSTUVWXYZ', ownerUserId: '4242' });
+ await addBotImConnection({ botId: 'bot-other', channel: 'telegram', token: '2:ABCDEFGHIJKLMNOPQRSTUVWXYZ', ownerUserId: '4242' });
+ await stopBotImConnections();
+ expect(buildBotImConnectionListPayload('bot-mia').connections.map(r => r.id)).toEqual([a.connection.id]);
+ expect(buildBotImConnectionListPayload('absent').connections).toEqual([]);
+ expect(buildBotImConnectionListPayload().connections).toHaveLength(2);
+ });
+
it('starts recorded connections on login, keeps records across stop, and drops them with the teammate', async () => {
const a = await addBotImConnection({ botId: 'bot-mia', channel: 'telegram', token: '1:ABCDEFGHIJKLMNOPQRSTUVWXYZ', ownerUserId: '4242' });
await stopBotImConnections();
diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
index fe9c5b19e9..1d10a09420 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
@@ -208,8 +208,9 @@ function toView(record: BotImConnectionRecord): BotImConnectionView {
return { ...record, status: statusOf(transport), identity: identityOf(transport) };
}
-export function buildBotImConnectionListPayload(): BotImConnectionListPayload {
- return { connections: listBotImConnections().map(toView) };
+export function buildBotImConnectionListPayload(botId?: string): BotImConnectionListPayload {
+ const records = botId === undefined ? listBotImConnections() : listBotImConnectionsForBot(botId);
+ return { connections: records.map(toView) };
}
function broadcastChanged(): void {
diff --git a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
index 0e46fa2611..1f03f38817 100644
--- a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
@@ -44,13 +44,13 @@ describe.each(modes)('%s remote history visibility', (mode) => {
db.exec(`
CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT DEFAULT '', working_dir TEXT,
agent_kind TEXT DEFAULT 'codex', workspace_kind TEXT DEFAULT 'project', model TEXT DEFAULT '',
- status TEXT DEFAULT 'active', source TEXT DEFAULT 'desktop', orca_role TEXT,
+ status TEXT DEFAULT 'active', source TEXT DEFAULT 'desktop', orca_role TEXT, orca_remote_lead TEXT,
parent_session_id TEXT, created_at INTEGER, updated_at INTEGER, user_send_at INTEGER, hidden_at INTEGER);
CREATE TABLE messages (id TEXT PRIMARY KEY, client_id TEXT, session_id TEXT, role TEXT,
content TEXT, tool_use_id TEXT, agent_meta TEXT, agent_kind TEXT, created_at INTEGER, rewind_at INTEGER);
CREATE VIRTUAL TABLE messages_fts USING fts5(message_id UNINDEXED, content);
CREATE TABLE bot_profiles (id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT);
- CREATE TABLE bot_session_links (session_id TEXT PRIMARY KEY, bot_id TEXT);
+ CREATE TABLE bot_session_links (session_id TEXT PRIMARY KEY, bot_id TEXT, role TEXT DEFAULT 'canonical', route_key TEXT);
CREATE TABLE embedding_jobs (source_id TEXT);
CREATE TABLE chat_messages_vec_v1 (distance REAL);
INSERT INTO bot_profiles VALUES ('visible', NULL, 'active'), ('zero', 0, 'active'),
@@ -71,7 +71,7 @@ describe.each(modes)('%s remote history visibility', (mode) => {
'INSERT INTO sessions (id, source, created_at, updated_at) VALUES (?, ?, ?, ?)',
).run(id, id === 'ordinary' ? 'desktop' : 'bot', i + 1, i + 1);
if (id !== 'orphan' && id !== 'ordinary')
- db.prepare('INSERT INTO bot_session_links VALUES (?, ?)').run(id, bot);
+ db.prepare('INSERT INTO bot_session_links (session_id, bot_id) VALUES (?, ?)').run(id, bot);
db.prepare(
"INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, 'user', ?, ?)",
).run(id, id, id, JSON.stringify('needle'), i + 1);
@@ -159,6 +159,48 @@ describe.each(modes)('%s remote history visibility', (mode) => {
return projectRemoteSessionResult(channel, result);
};
+ // Regression: old-created, recently active chats were lost by workdir/creation
+ // filters; known ownership must include archived channels/topics without claiming
+ // unrelated legacy Telegram records. Unit: real readers + MCP/remote handler + SQLite.
+ it('finds old active teammate conversations and keeps legacy source separate', async () => {
+ db.exec(`
+ UPDATE sessions SET created_at=1, updated_at=1000, status='archived' WHERE id='visible';
+ UPDATE bot_session_links SET role='channel', route_key='im:telegram:123:g:456:t:789' WHERE session_id='visible';
+ UPDATE sessions SET source='telegram', created_at=1, updated_at=1000 WHERE id='ordinary';
+ `);
+ const created = await invokeHistory('list_sessions', { teammate_id: 'visible', from: '1970-01-01T00:00:00.900Z' });
+ expect(created).toMatchObject({ ok: true, sessions: [] });
+ const active = await invokeHistory('list_sessions', {
+ teammate_id: 'visible', time_field: 'activity', from: '1970-01-01T00:00:00.900Z', limit: 1,
+ });
+ expect(active).toMatchObject({ ok: true, sessions: [{ id: 'visible', status: 'archived',
+ companion: { id: 'visible', role: 'channel', channel: 'telegram' } }] });
+ const own = await invokeHistory('search_chat_history', { query: 'needle', teammate_id: 'visible' });
+ expect(own).toMatchObject({ ok: true, hits: [{ sessionId: 'visible', context: [{ content: 'needle' }] }] });
+ expect((own as any).hits).toHaveLength(1);
+ const legacy = await invokeHistory('search_chat_history', { query: 'needle', source: 'telegram' });
+ expect(legacy).toMatchObject({ ok: true, sessions: { ordinary: { source: 'telegram', companion: null } } });
+ expect((legacy as any).hits.map((hit: any) => hit.sessionId)).toEqual(['ordinary']);
+ });
+
+ // Activity cursor must use the same clock as ordering, including userSendAt and ties.
+ it('paginates activity ties and preserves the existing scope intersection', async () => {
+ db.exec(`
+ UPDATE sessions SET created_at=1, updated_at=2, user_send_at=1000 WHERE id IN ('visible', 'zero');
+ UPDATE bot_session_links SET bot_id='visible', role='thread' WHERE session_id='zero';
+ `);
+ const args = { teammate_id: 'visible', time_field: 'activity', limit: 1 };
+ const first = await invokeHistory('list_sessions', args) as any;
+ const second = await invokeHistory('list_sessions', { ...args, cursor: first.nextCursor }) as any;
+ expect([first.sessions[0].id, second.sessions[0].id]).toEqual(['zero', 'visible']);
+ expect(second.hasMore).toBe(false);
+ expect(first.sessions[0]).toMatchObject({ lastActivityAt: '1970-01-01T00:00:01.000Z', companion: { role: 'thread' } });
+ const restricted = await listSessionsForHistory({ ...listArgs, teammateId: 'visible', sessionIds: ['ordinary'] });
+ expect(restricted.items).toEqual([]);
+ const search = await searchChatHistoryHybrid({ ...searchArgs, teammateId: 'visible', sessionIds: ['ordinary'] });
+ expect(search.hits).toEqual([]);
+ });
+
it('paginates the visible list without hidden rows consuming slots or cursors', async () => {
const first = await listSessionsForHistory(listArgs);
const second = await listSessionsForHistory({ ...listArgs, cursor: first.nextCursor });
diff --git a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
index cd71a34ce1..e189074833 100644
--- a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
@@ -35,6 +35,7 @@ function createLocalDb(): Database.Database {
permission_mode TEXT NOT NULL DEFAULT 'ask',
status TEXT NOT NULL DEFAULT 'active',
orca_role TEXT,
+ orca_remote_lead TEXT,
user_send_at INTEGER,
agent_kind TEXT NOT NULL DEFAULT 'cc',
parent_session_id TEXT,
@@ -73,6 +74,7 @@ function createLocalDb(): Database.Database {
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
+ CREATE TABLE bot_session_links (session_id TEXT PRIMARY KEY, bot_id TEXT, role TEXT, route_key TEXT);
CREATE TABLE messages (
id TEXT PRIMARY KEY,
client_id TEXT NOT NULL,
diff --git a/apps/desktop/src/main/localDb/chatHistoryReader.ts b/apps/desktop/src/main/localDb/chatHistoryReader.ts
index bb998db26f..4569255388 100644
--- a/apps/desktop/src/main/localDb/chatHistoryReader.ts
+++ b/apps/desktop/src/main/localDb/chatHistoryReader.ts
@@ -15,6 +15,8 @@
import { and, asc, desc, eq, gt, gte, lt, inArray, isNotNull, isNull, ne, or, sql } from 'drizzle-orm';
+import type { HistoryCompanion } from '@cindy/mcps';
+import { historyCompanionJson, parseHistoryCompanion, teammateHistoryFilter } from './historyCompanion';
import { getDbClient } from './client/current';
import { sessions, messages } from './schema';
import { messageToCamel } from './mapper';
@@ -170,6 +172,9 @@ export async function listWorkdirsForHistory(
// ── list_sessions ───────────────────────────────────────────────────────────
export interface ListSessionsParams {
+ teammateId?: string;
+ source?: string;
+ timeField?: 'created' | 'activity';
/** Set only by the authorized remote history handler, never by tool input. */
remoteVisibleOnly?: boolean;
sessionIds?: string[] | null;
@@ -184,6 +189,8 @@ export interface ListSessionsParams {
}
export interface SessionSummary {
+ lastActivityAt: number;
+ companion: HistoryCompanion | null;
id: string;
title: string;
workingDir: string | null;
@@ -211,7 +218,11 @@ export async function listSessionsForHistory(
const db = getDbClient().drizzle;
const orderFn = params.order === 'asc' ? asc : desc;
+ const lastActivityAt = sql<number>`MAX(${sessions.createdAt}, ${sessions.updatedAt}, COALESCE(${sessions.userSendAt}, 0))`;
+ const time = params.timeField === 'activity' ? lastActivityAt : sql<number>`${sessions.createdAt}`;
const conds = [];
+ if (params.teammateId) conds.push(teammateHistoryFilter(sql`${sessions.id}`, params.teammateId));
+ if (params.source) conds.push(sql`${sessions.source} = ${params.source}`);
if (params.remoteVisibleOnly) conds.push(sql.raw(remoteVisibleSessionSql('sessions')));
if (scopedSessionIds !== null) conds.push(inArray(sessions.id, scopedSessionIds));
if (!params.includeDeleted) conds.push(ne(sessions.status, 'deleted'));
@@ -220,21 +231,21 @@ export async function listSessionsForHistory(
if (candidates.length === 0) return { items: [], nextCursor: null, hasMore: false };
conds.push(inArray(sessions.workingDir, candidates));
}
- if (params.fromMs !== null) conds.push(gte(sessions.createdAt, params.fromMs));
- if (params.toMs !== null) conds.push(lt(sessions.createdAt, params.toMs));
+ if (params.fromMs !== null) conds.push(gte(time, params.fromMs));
+ if (params.toMs !== null) conds.push(lt(time, params.toMs));
if (params.agentKind !== null) conds.push(eq(sessions.agentKind, params.agentKind));
if (params.cursor) {
const { createdAt: c, id } = params.cursor;
if (params.order === 'desc') {
conds.push(
- or(lt(sessions.createdAt, c), and(eq(sessions.createdAt, c), lt(sessions.id, id))),
+ or(lt(time, c), and(eq(time, c), lt(sessions.id, id))),
);
} else {
conds.push(
or(
- sql`${sessions.createdAt} > ${c}`,
- and(eq(sessions.createdAt, c), sql`${sessions.id} > ${id}`),
+ sql`${time} > ${c}`,
+ and(eq(time, c), sql`${sessions.id} > ${id}`),
),
);
}
@@ -249,6 +260,8 @@ export async function listSessionsForHistory(
// 但 limit 上限 1000 下完全可接受, 且语义清晰。
const sessionRows = await db
.select({
+ lastActivityAt,
+ companionJson: historyCompanionJson(sql`${sessions.id}`),
id: sessions.id,
title: sessions.title,
workingDir: sessions.workingDir,
@@ -266,7 +279,7 @@ export async function listSessionsForHistory(
})
.from(sessions)
.where(and(...conds))
- .orderBy(orderFn(sessions.createdAt), orderFn(sessions.id))
+ .orderBy(orderFn(time), orderFn(sessions.id))
.limit(fetchLimit);
const hasMore = sessionRows.length > params.limit;
@@ -288,6 +301,8 @@ export async function listSessionsForHistory(
}
const items: SessionSummary[] = sliced.map((r) => ({
+ lastActivityAt: r.lastActivityAt,
+ companion: parseHistoryCompanion(r.companionJson),
id: r.id,
title: r.title,
workingDir: r.workingDir,
@@ -306,7 +321,7 @@ export async function listSessionsForHistory(
}));
const last = items[items.length - 1];
const nextCursor: HistoryCursor | null = hasMore && last
- ? { createdAt: last.createdAt, id: last.id }
+ ? { createdAt: params.timeField === 'activity' ? last.lastActivityAt : last.createdAt, id: last.id }
: null;
return { items, nextCursor, hasMore };
}
diff --git a/apps/desktop/src/main/localDb/chatHistorySearch.ts b/apps/desktop/src/main/localDb/chatHistorySearch.ts
index 71b1da9ae1..331cfc4f81 100644
--- a/apps/desktop/src/main/localDb/chatHistorySearch.ts
+++ b/apps/desktop/src/main/localDb/chatHistorySearch.ts
@@ -26,7 +26,7 @@
* - 上下文窗口 / content 解析复用 mapper.ts 的 messageToCamel(走 drizzle 驼峰行)。
*/
-import { and, asc, desc, eq, gt, inArray, isNull, lt, or } from 'drizzle-orm';
+import { and, asc, desc, eq, gt, inArray, isNull, lt, or, sql } from 'drizzle-orm';
import type {
SearchChatHistoryArgs,
@@ -37,6 +37,7 @@ import type {
HistoryRole,
} from '@cindy/mcps';
+import { historyCompanionJson, parseHistoryCompanion } from './historyCompanion';
import { getDbClient } from './client/current';
import { messages as messagesTable, sessions as sessionsTable } from './schema';
import { messageToCamel } from './mapper';
@@ -454,6 +455,14 @@ function buildFilterClause(
const conds: string[] = ['m.rewind_at IS NULL'];
if (args.remoteVisibleOnly) conds.push(remoteVisibleSessionSql('s'));
const params: unknown[] = [];
+ if (args.teammateId) {
+ conds.push('EXISTS (SELECT 1 FROM bot_session_links hcf WHERE hcf.session_id = s.id AND hcf.bot_id = ?)');
+ params.push(args.teammateId);
+ }
+ if (args.source) {
+ conds.push('s.source = ?');
+ params.push(args.source);
+ }
if (args.sessionIds && args.sessionIds.length > 0) {
conds.push(`m.session_id IN (${args.sessionIds.map(() => '?').join(',')})`);
params.push(...args.sessionIds);
@@ -605,12 +614,14 @@ async function fetchSessionsMeta(
workingDir: sessionsTable.workingDir,
agentKind: sessionsTable.agentKind,
title: sessionsTable.title,
+ source: sessionsTable.source,
+ companionJson: historyCompanionJson(sql`${sessionsTable.id}`),
})
.from(sessionsTable)
.where(inArray(sessionsTable.id, uniq));
const out: Record<string, SearchChatHistorySessionMeta> = {};
for (const r of rows) {
- out[r.id] = { workingDir: r.workingDir, agentKind: r.agentKind, title: r.title };
+ out[r.id] = { workingDir: r.workingDir, agentKind: r.agentKind, title: r.title, source: r.source, companion: parseHistoryCompanion(r.companionJson) };
}
return out;
}
diff --git a/apps/desktop/src/main/localDb/historyCompanion.ts b/apps/desktop/src/main/localDb/historyCompanion.ts
new file mode 100644
index 0000000000..7e0e54c1b2
--- /dev/null
+++ b/apps/desktop/src/main/localDb/historyCompanion.ts
@@ -0,0 +1,21 @@
+import { sql, type SQL } from 'drizzle-orm';
+import type { HistoryCompanion } from '@cindy/mcps';
+
+/** Attribution is a persisted link, never a directory, channel, name or current connection guess. */
+export function historyCompanionJson(sessionId: SQL): SQL<string | null> {
+ return sql<string | null>`(SELECT json_object('id', hcl.bot_id, 'role', hcl.role, 'routeKey', hcl.route_key)
+ FROM bot_session_links hcl WHERE hcl.session_id = ${sessionId} LIMIT 1)`;
+}
+
+export function parseHistoryCompanion(value: string | null | undefined): HistoryCompanion | null {
+ if (!value) return null;
+ const row = JSON.parse(value) as { id: string; role: string; routeKey: string | null };
+ const channel = row.routeKey?.match(/^im:([^:]+):/)?.[1];
+ return { id: row.id, role: row.role, ...(channel ? { channel } : {}) };
+}
+
+/** A query filter only: callers' existing authorization/remote visibility still applies. */
+export function teammateHistoryFilter(sessionId: SQL, teammateId: string): SQL {
+ return sql`EXISTS (SELECT 1 FROM bot_session_links hcf
+ WHERE hcf.session_id = ${sessionId} AND hcf.bot_id = ${teammateId})`;
+}
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index c4bf8f78e5..7999002657 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -5801,6 +5801,27 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { release(); }
});
+ // Cross-channel recall needs live connection discovery, but a group self-read must
+ // not reveal the owner's other connections. Existing model tests did not cover it.
+ it('exposes conversation discovery only with owner access', async () => {
+ await seedPair(); seedGroupLane();
+ const readConversationConnections = vi.fn(async () => [{ channel: 'telegram', connectionId: 'fixture', status: 'offline' }]);
+ const service = createBotCapabilityService({ ...capabilityDeps, readConversationConnections });
+ const owner = await service.inspect({ callerSessionId: 'session-1' });
+ expect(owner).toMatchObject({ ok: true, state: { conversations: {
+ scope: 'local', teammateId: 'bot-a', connectionsAvailable: true,
+ connections: [{ channel: 'telegram', status: 'offline' }],
+ } } });
+ expect(readConversationConnections).toHaveBeenCalledWith('bot-a');
+ readConversationConnections.mockClear();
+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'tools', isCurrent: () => true, validate: async () => {} });
+ try {
+ const guest = await service.inspect({ callerSessionId: 'group-lane' });
+ expect(guest.ok && guest.state.conversations).toBeUndefined();
+ expect(readConversationConnections).not.toHaveBeenCalled();
+ } finally { release(); }
+ });
+
it.each([
{ label: 'null override', config: { modelChainOverride: null } },
{ label: 'legacy default marker', config: { modelOverride: null, model: 'stale-profile-model' } },
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index b1293a3bc0..8cfa70e925 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -894,6 +894,20 @@ function createDesktopBotCapabilityService() {
return createBotCapabilityService({
getMaker, getPluginRegistry, isBotToolsetAvailable,
listMcpServers: listBotRuntimeMcpServers,
+ readConversationConnections: async (botId) => {
+ const [{ buildBotImConnectionListPayload }, { readWechatChannelSettings }, { readXCompanionAssignment }] = await Promise.all([
+ import('../im/shared/botImConnectionRuntime.js'),
+ import('../im/wechat/channelSettings.js'),
+ import('../hook-control/ipc.js'),
+ ]);
+ const connections: NonNullable<import('@cindy/mcps').BotControlState['conversations']>['connections'] =
+ buildBotImConnectionListPayload(botId).connections
+ .map(record => ({ channel: record.service ?? record.channel, connectionId: record.id, status: record.status.kind }));
+ if (readWechatChannelSettings().companionBotId === botId) connections.push({ channel: 'wechat', status: 'assigned' });
+ const x = readXCompanionAssignment();
+ if (x?.botId === botId) connections.push({ channel: 'x', status: x.enabled ? 'assigned' : 'disabled' });
+ return connections;
+ },
resolveBotAgentKind: async (sessionId, chain) => _resolveBotCapabilityAgentKind?.(sessionId, chain) ?? null,
});
}
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index e6abcb8d41..043d5f268b 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -21,6 +21,7 @@ type Kind = 'skill' | 'mcp' | 'toolset';
type Input = { callerSessionId: string; kind: Kind };
type Entry = { id: string; name: string; description: string; available: boolean; joined: boolean };
export interface BotCapabilityServiceDeps {
+ readConversationConnections?(botId: string): Promise<NonNullable<BotControlState['conversations']>['connections']>;
getMaker: () => Pick<Maker, 'listAgentSkills'>;
resolveBotAgentKind: (sessionId: string, modelChain?: BotModelRoute[]) => Promise<AgentKind | null>;
getPluginRegistry: () => Pick<PluginRegistry, 'getPlugins' | 'getEnableState'>;
@@ -276,8 +277,16 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {
// A self-read may report inherited selection without exposing owner route IDs.
const candidates = explicit === null && !ctx.canReadOwnerModels
? [] : await readEffectiveBotModelChain(ctx.config);
+ const conversations: BotControlState['conversations'] = ctx.canReadOwnerModels ? {
+ scope: 'local',
+ teammateId: ctx.botId,
+ connections: await deps.readConversationConnections?.(ctx.botId) ?? [],
+ connectionsAvailable: Boolean(deps.readConversationConnections),
+ guidance: 'Recall a topic with search_chat_history(query, teammate_id=teammateId), without a workdir or creation-date filter. list_sessions(teammate_id=teammateId, time_field=activity) includes old active, archived and topic/channel chats. Read matching originals with get_chat_history. If no match, existing account-history permission permits a bounded topic search without teammate_id for unlinked legacy records; report companion=null as unverified ownership, never infer it from a current connection, name or directory. device=all queries online authorized computers; unavailable/older devices and capped results are incomplete coverage.',
+ } : undefined;
await ctx.refresh();
const state: BotControlState = {
+ ...(conversations ? { conversations } : {}),
profile: { id: ctx.botId, name: ctx.displayName, description: ctx.description,
identitySource: ctx.identitySource, version: ctx.version },
session: { id: input.callerSessionId, workingDir: ctx.workingDir, remoteHostId: ctx.remoteHostId },
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 43bb327b6d..19897a62bc 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -525,6 +525,13 @@ Claude Code 终态 error 事件可带 `usageResetAt`(unix ms)。服务端无
## Agent 跨设备历史发现与搜索
+历史查询的可选 `teammate_id`、`source` 由源端在召回、排名、分页前过滤,仍与原调用方权限
+及远程可见范围取交集。`list_sessions` 的 `time_field=activity` 同时控制时间窗、排序和游标,
+活动时间取创建、更新、用户发送时间的最大值;省略时保持创建时间语义。新增输出
+`lastActivityAt`、`companion`(持久伙伴关联及可证明的渠道),搜索元数据补充 `source`。
+跨设备转发不丢筛选字段;旧端若拒绝新参数,保留失败设备组与 `partial`,不能重试成无归属
+筛选的查询,也不能把失败当作无聊天。没有这些参数的旧调用保持兼容。
+
`cindy_helper` 的 `list_history_devices` 使用现有同账号设备目录;`list_sessions` 和
`search_chat_history` 新增 `device` 参数,默认 `local` 保留原行为,`all` 查询本机和在线且
允许访问的电脑,也可指定目录返回的设备 ID。跨设备响应按设备分组;`limit`、排序、
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index 1c3e020a13..aabed94d5b 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -56,6 +56,8 @@
| 项目 | 列出、登记、改名、移除;工作目录列表 | 有 | 无 |
| 伙伴 | 发现伙伴、伙伴间消息 | 有 | 有 |
| 伙伴 | 资料、能力、待办、后台任务 | 有 | 无 |
+| 伙伴 | 按已证实归属搜索跨渠道聊天、按最近活动列出旧任务 | 有 | 有(历史查询,两端需支持筛选参数) |
+| 伙伴 | 查看自己的本机 IM 连接分配与状态 | 有 | 无 |
| 伙伴 | 「一眼」投影(等你 / 在做;用户界面已改为近况,2026-10-21) | 有 | 无 |
| 伙伴 | 跟进任务:读取与继续(自动跟进所有任务的伙伴) | 有 | 有(2026-10-17) |
| 伙伴 | 查看与更换主力电脑 | 有 | 有(2026-10-17) |
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index fc7269e77e..a57df1ebf3 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -28,6 +28,20 @@ Pi、Claude Code、Codex 是执行引擎,它们的原生工具说明不定义
正在使用对应 CLI。面向用户的配置指引应落到 Cindy 的实际入口;不能把 `/login`、
`/model` 等原生终端命令推荐为伙伴聊天中的操作。用户明确询问独立 CLI 用法时可正常说明。
+### 按话题找回跨渠道聊天
+
+主人询问过去的话题时,不要求先点名渠道,也不默认限制当前工作目录或任务创建日期。
+`get_teammate_state` 在主人可读范围返回本机连接分配、状态和历史检索说明;连接分配不是
+历史归属证据,也不代表实时在线。访客自查不增加主人连接信息。
+按 `search_chat_history(query, teammate_id)` 搜索已保存的 `bot_session_links`,包含主任务、
+历史、话题及渠道专线;按 `list_sessions(teammate_id, time_field=activity)` 查最近活跃的旧任务,
+不因任务已归档而漏掉。命中后用 `get_chat_history` 阅读原文,并区分任务 `source` 与关联的渠道。
+
+未关联的旧 IM 记录不自动认领:在已有账号历史权限内,可去掉伙伴筛选按具体话题有限检索,
+结果 `companion=null` 明确表示没有可证明的伙伴归属。不能按目录、名字、当前连接,或将某渠道
+全部聊天归给一位伙伴。`device=all` 沿既有同账号在线设备授权查询,失败设备、旧版本和召回上限
+仍明确列出;只查本机不能声称覆盖全部设备。不增加后台扫库、全量上下文注入或私有记忆补丁。
+
## 2. 所有权与挂靠关系
```text
@@ -58,7 +72,8 @@ Chris:「私聊话题和群聊话题,要真的能把独立事件隔离到独
- **数据**:主人在私聊里对某条消息(主人自己的或伙伴的)点「创建话题」,宿主为「这条消息 × 这位伙伴」另开一条隐藏
Session,`bot_session_links.role = 'thread'`,`route_key = 'dm-thread:<根消息所在 Session>:<根消息 clientId>'`;
根消息必须是这位伙伴当前主任务里可见的 user / assistant 消息。同一条消息只有一个话题,再次打开复用它。
- 话题 Session 不进任务列表、历史与会话搜索,消息只在话题里,不写进主时间线。
+ 话题 Session 不进普通任务列表与界面会话搜索,消息只在话题里,不写进主时间线;
+ 主人授权的 Agent 历史检索可以按伙伴归属读取话题记录,沿用既有权限边界。
- **身份与能力**:话题是主人自己的对话,与主任务同一 Profile、Home 工作目录、模型链与权限档(随 Profile 与权限档更新),
带主任务的私有能力(记忆、自有与基座 Skill、定时任务、建伙伴、工作台、插件授权卡、伙伴绑定的 IM 工具);
伙伴间私信仍只属于主任务(对方的回复会回到主任务)。
diff --git a/packages/lizi-mcps/src/__tests__/historyDevices.test.ts b/packages/lizi-mcps/src/__tests__/historyDevices.test.ts
index d343687782..d9f001a7b8 100644
--- a/packages/lizi-mcps/src/__tests__/historyDevices.test.ts
+++ b/packages/lizi-mcps/src/__tests__/historyDevices.test.ts
@@ -151,6 +151,23 @@ describe("history device discovery and queries", () => {
expect.objectContaining({ device: "local", cursor: "remote-cursor" }),
);
});
+ // Optional filters survive forwarding; an old schema failure must never retry unscoped.
+ it("forwards teammate filters and reports an old schema rejection without dropping them", async () => {
+ const s = setup();
+ s.remoteQuery.mockResolvedValueOnce({ ok: false, errorCode: "INVALID_ARGS", message: "Unrecognized key: teammate_id" } as any);
+ const result = await s.call("list_sessions", {
+ device: "all", teammate_id: "bot-a", source: "bot", time_field: "activity",
+ });
+ expect(s.history.listSessions).toHaveBeenCalledWith(expect.objectContaining({ teammateId: "bot-a", source: "bot", timeField: "activity" }));
+ expect(s.remoteQuery).toHaveBeenCalledExactlyOnceWith("mac", "list_sessions", expect.objectContaining({
+ device: "local", teammate_id: "bot-a", source: "bot", time_field: "activity",
+ }));
+ expect(result).toMatchObject({ partial: true, groups: expect.arrayContaining([
+ expect.objectContaining({ deviceId: "mac", ok: false, errorCode: "INVALID_ARGS" }),
+ ]) });
+ await s.call("search_chat_history", { device: "mac", query: "topic", teammate_id: "bot-a", source: "bot" });
+ expect(s.remoteQuery).toHaveBeenLastCalledWith("mac", "search_chat_history", expect.objectContaining({ teammate_id: "bot-a", source: "bot" }));
+ });
it("qualifies search hits, metadata and context and supports reading the returned identity", async () => {
const s = setup();
s.remoteQuery.mockResolvedValueOnce({
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 7324e33485..fbccc2a267 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -149,7 +149,7 @@ export const HELPER_CATEGORY_DESCRIPTIONS: Record<(typeof CATEGORY_ENUM)[number]
cindy: `${BRAND_NAME} 能力说明与当前任务信息;get_capabilities({key:"self-management"}) 是管理自己的任务、定时任务、项目、伙伴的工具索引。本机。`,
auth: '供应商授权登录(Grok 设备码)。本机。',
control: '管理任务与项目:归档/取消归档支持本机与跨电脑(deviceId::sessionId);改名、移动、标签、排队消息、插话、停止、运行设置、项目列表与增删改仅本机。',
- history: '查询任务、工作目录、聊天记录、任务摘要与输入队列。任务列表、搜索、读取聊天记录、任务摘要(get_task_digest)可跨电脑(device 参数 / deviceId::sessionId);其余本机。',
+ history: '按话题查找跨渠道聊天,支持伙伴归属(teammate_id)、最近活动时间与真实来源;不要默认限制当前工作目录或创建日期。查询任务、工作目录、聊天记录、任务摘要与输入队列。任务列表、搜索、读取聊天记录、任务摘要(get_task_digest)可跨电脑(device 参数 / deviceId::sessionId);其余本机。',
feedback: `向 ${BRAND_NAME} 官方提交反馈。`,
handoff: '给已有任务发消息,或新建任务。发给已有任务可跨电脑(deviceId::sessionId);新建只在本机。',
skills: 'Skill 的搜索、发布与学习。本机与 SkillHub。',
diff --git a/packages/lizi-mcps/src/xdt-helper/_history_types.ts b/packages/lizi-mcps/src/xdt-helper/_history_types.ts
index f568d0de9d..1882feff09 100644
--- a/packages/lizi-mcps/src/xdt-helper/_history_types.ts
+++ b/packages/lizi-mcps/src/xdt-helper/_history_types.ts
@@ -56,6 +56,12 @@ export interface HistoryWorkdir {
agentKinds: string[];
}
+export interface HistoryCompanion {
+ id: string;
+ role: string;
+ channel?: string;
+}
+
export interface HistorySession {
id: string;
title: string;
@@ -79,6 +85,8 @@ export interface HistorySession {
updatedAt: number;
userSendAt: number | null;
messageCount: number;
+ lastActivityAt?: number;
+ companion?: HistoryCompanion | null;
}
export interface HistoryMessage {
@@ -106,6 +114,10 @@ export interface ListWorkdirsArgs {
}
export interface ListSessionsArgs {
+ /** Optional filters, intersected with the host-authorized scope. */
+ teammateId?: string;
+ source?: string;
+ timeField?: 'created' | 'activity';
/** Host-owned ownership scope. null = account history; [] = deny all. */
sessionIds: string[] | null;
workdir: string | null;
@@ -141,6 +153,8 @@ export interface GetMessagesArgs {
// 上下文窗口拼装; 向量不可用 / 未开 embedding 时静默退化为纯 FTS。
export interface SearchChatHistoryArgs {
+ teammateId?: string;
+ source?: string;
/** 自然语言查询(必填)。 */
query: string;
sessionIds: string[] | null;
@@ -192,6 +206,8 @@ export interface SearchChatHistoryHit {
}
export interface SearchChatHistorySessionMeta {
+ source?: string;
+ companion?: HistoryCompanion | null;
workingDir: string | null;
agentKind: string;
title: string;
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
index 7b2a3cd243..4e5836afa7 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
@@ -55,6 +55,13 @@ export interface AppDefaultModelRoute {
}
export interface BotControlState {
+ conversations?: {
+ scope: 'local';
+ teammateId: string;
+ connections: { channel: string; connectionId?: string; status: string }[];
+ connectionsAvailable: boolean;
+ guidance: string;
+ };
profile: { id: string; name: string; description: string; identitySource: string; version: number };
session: { id: string; workingDir: string | null; remoteHostId: string | null };
model: { source: "override" | "default"; candidates: { harness: string; providerId?: string | null; model: string }[] };
@@ -139,7 +146,7 @@ export function registerBotCapabilityTools(
if (deps.callbacks.inspect) registry.register({
name: "get_teammate_state",
category: "bots",
- description: TEAMMATE_CONTROL_GUIDANCE,
+ description: TEAMMATE_CONTROL_GUIDANCE + '\n主人私聊中还返回本机消息平台连接与跨渠道历史检索指引。按话题接续时使用 profile.id 作为 history 工具的 teammate_id,不需要主人先点名渠道;连接不证明旧记录归属。',
inputShape: {},
handler: async () => {
const callerSessionId = deps.getSessionContext().sessionId;
diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
index cede591802..95c7335e0d 100644
--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
@@ -201,7 +201,8 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [
detail: [
`【是什么】${BRAND_NAME} 的对话历史保存在各电脑的本地 SQLite。cindy_helper 的 history 类提供只读查询入口,让 agent 按宿主授予的范围读取历史,协助用户组织 memory / 知识库。`,
'【六个工具】(1)list_workdirs: 列出本机出现过的工作目录 + session 数 / 首末活动时间; (2)list_sessions: 按 workdir / 时间段 / agent_kind 过滤 session 元数据,并附当前 queuedCount; (3)list_session_queue: 按 session_id 查看尚未消费消息的位置、来源、入队时间、正文摘要与投递状态; (4)get_chat_history: 按 session_ids / workdir / 时间段 / role "按元数据精确捞"原始消息(content / agentMeta JSON 解析后透传); (5)search_chat_history: 跨 session "按内容语义找"——自然语言 query, FTS5 全文(全量、永远可用)+ 向量语义(开启"聊天记录语义索引"后生效)RRF 融合, 返回命中 + 上下文窗口; (6)list_history_devices: 发现本机与在线已授权电脑。',
- '【典型用法】"帮我总结这周和 agent 的讨论, 写成 memory 条目" → list_sessions({from: 周一 ISO}) 拿 sessionId 列表 → get_chat_history({session_ids: [...]}) 拿对话 → LLM 提炼成 memory。"我之前聊过 X / 上次怎么解决那个 bug"(只记得内容、不知道在哪) → search_chat_history({query}) 直接语义召回。"我在 xxx 项目里都聊过啥" → list_sessions({workdir}) → get_chat_history。',
+ '【典型用法】"帮我总结这周和 agent 的讨论, 写成 memory 条目" → list_sessions({from: 周一 ISO, time_field: "activity"}) 拿 sessionId 列表 → get_chat_history({session_ids: [...]}) 拿对话 → LLM 提炼成 memory。"我之前聊过 X / 上次怎么解决那个 bug"(只记得内容、不知道在哪) → search_chat_history({query}) 直接语义召回。"我在 xxx 项目里都聊过啥" → list_sessions({workdir}) → get_chat_history。',
+ '【伙伴跨渠道】get_teammate_state 返回本机连接;list_sessions / search_chat_history 使用 teammate_id=profile.id 匹配已保存的归属,含归档、旧历史和话题。按话题搜索不默认限制 workdir 或创建时间。旧 IM 未关联记录仍可在原有账号权限内按内容查询,结果 companion=null 不代表属于当前伙伴;当前连接、目录或名字都不能补造归属。source 是原始任务来源,伙伴渠道看 companion.channel 和消息来源。',
'【跨设备】list_history_devices 发现设备;list_sessions / search_chat_history 传 device="all" 查询本机与在线已授权电脑,或 device=<设备 ID> 指定电脑。结果按设备分组,每组独立翻页,partial 表示有设备未查到。远程任务 ID 带 deviceId:: 前缀,可直接传给 get_chat_history;不读取离线缓存,旧端不支持会明确报告。默认 device="local" 保持原本机查询。',
'【向量是增益不是依赖】search_chat_history 在用户没开 embedding / sqlite-vec 不可用时静默退化为纯 FTS, 搜索照常工作; 响应里 vector_used 标明向量是否生效。',
'【分页】任务列表与聊天读取可用 hasMore + nextCursor 持续翻页;跨设备时每台电脑独立翻页。搜索受候选池上限约束,pool_capped=true 时应缩小查询范围,不能声称已经穷尽全部匹配。',
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index c5126ec0b9..3b43b65819 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -220,6 +220,7 @@ export type {
HistoryPage,
HistoryWorkdir,
HistorySession,
+ HistoryCompanion,
HistoryMessage,
ListWorkdirsArgs,
ListSessionsArgs,
diff --git a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
index e7cbc5b808..7250a6de47 100644
--- a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
+++ b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
@@ -27,12 +27,13 @@ const DESCRIPTION = [
'时间戳 / messageCount 等), 按多种过滤条件组合查。**不返回 messages 内容** —',
'要拉具体聊天内容请用 get_chat_history。',
'',
+ '按话题回忆先用 search_chat_history,不要默认限制当前 workdir 或创建日期。teammate_id 只匹配已证实的伙伴关联;旧 IM 未关联记录需在已有权限内另查,不自动认领。',
'【何时调用】用户问"我某天聊了哪些 session / 这个项目下我都开过哪些会话 /',
'我用 codex 的所有 session 列一下"等场景。',
'',
'【过滤参数】所有参数可任意组合, 不传 = 不过滤:',
' - workdir: 精确匹配 sessions.workingDir',
- ' - from / to: ISO 8601 时间窗 (from 含, to 不含), 过滤 sessions.createdAt',
+ ' - from / to: ISO 8601 时间窗 (from 含, to 不含), 按 time_field 过滤(默认创建时间,activity 为最近活动)',
' - agent_kind: cc(Claude Code) | codex',
' - include_deleted: 默认 false (排除 status=deleted)',
'',
@@ -60,6 +61,9 @@ export function registerListSessionsTool(
description: DESCRIPTION,
inputShape: {
...historyDeviceShape,
+ teammate_id: z.string().min(1).max(256).optional().describe('按已保存的伙伴归属筛选,使用 get_teammate_state 的 profile.id;包含历史、话题和渠道专线,不按工作目录猜归属。'),
+ source: z.string().min(1).max(64).optional().describe('精确匹配任务的原始 source,如 telegram(旧独立机器人)或 bot(伙伴);不是伙伴归属证明。'),
+ time_field: z.enum(['created', 'activity']).optional().describe('from/to 与排序使用的时间:created(默认,创建时间);activity(最近活动,含旧建但近期聊天的任务)。'),
workdir: z
.string()
.optional()
@@ -67,11 +71,11 @@ export function registerListSessionsTool(
from: z
.string()
.optional()
- .describe('ISO 8601 时间字符串(含), 过滤 sessions.createdAt >= from。例: "2026-05-01T00:00:00Z"'),
+ .describe('ISO 8601 时间字符串(含), 过滤所选 time_field >= from。例: "2026-05-01T00:00:00Z"'),
to: z
.string()
.optional()
- .describe('ISO 8601 时间字符串(不含), 过滤 sessions.createdAt < to。'),
+ .describe('ISO 8601 时间字符串(不含), 过滤所选 time_field < to。'),
agent_kind: z
.enum(['cc', 'codex'])
.optional()
@@ -85,11 +89,11 @@ export function registerListSessionsTool(
order: z
.enum(['asc', 'desc'])
.default('desc')
- .describe('按 sessions.createdAt 排序, desc = 最新在前(默认)。'),
+ .describe('按 time_field 排序,desc = 最新在前(默认)。'),
},
handler: async (args) => {
if (args.device !== 'local') return queryHistoryDevices(registry, deps, 'list_sessions', args);
- const { workdir, from, to, agent_kind, include_deleted, limit, cursor, order } = args;
+ const { workdir, from, to, agent_kind, include_deleted, limit, cursor, order, teammate_id, source, time_field } = args;
const scope = await resolveHistoryScope(deps.history, deps.getSessionContext, null);
if (!scope.ok) return errorPayload(scope.errorCode, scope.message);
const fromMs = parseIsoMs(from);
@@ -104,6 +108,9 @@ export function registerListSessionsTool(
const result = await deps.history.listSessions({
sessionIds: scope.sessionIds,
+ ...(teammate_id ? { teammateId: teammate_id } : {}),
+ ...(source ? { source } : {}),
+ ...(time_field ? { timeField: time_field } : {}),
workdir: workdir ?? null,
fromMs,
toMs,
@@ -155,6 +162,8 @@ export function registerListSessionsTool(
createdAt: new Date(s.createdAt).toISOString(),
updatedAt: new Date(s.updatedAt).toISOString(),
messageCount: s.messageCount,
+ ...(s.lastActivityAt !== undefined ? { lastActivityAt: new Date(s.lastActivityAt).toISOString() } : {}),
+ ...(s.companion !== undefined ? { companion: s.companion } : {}),
};
if (queuedCounts !== null) out.queuedCount = queuedCounts[s.id] ?? 0;
if (s.orcaRole !== null) out.orcaRole = s.orcaRole;
@@ -165,7 +174,7 @@ export function registerListSessionsTool(
}),
nextCursor: page.nextCursor ? encodeCursor(page.nextCursor) : null,
hasMore: page.hasMore,
- query: { workdir, from, to, agent_kind, include_deleted, limit, order },
+ query: { workdir, from, to, agent_kind, include_deleted, limit, order, teammate_id, source, time_field },
...(cursor && !cursorObj ? { warning: 'INVALID_CURSOR_FALLBACK_TO_FIRST_PAGE' } : {}),
});
},
diff --git a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts b/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
index 1d14718be3..12deb58224 100644
--- a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
+++ b/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
@@ -88,6 +88,8 @@ export function registerSearchChatHistoryTool(
description: DESCRIPTION,
inputShape: {
...historyDeviceShape,
+ teammate_id: z.string().min(1).max(256).optional().describe('限定已保存归属的伙伴聊天(含历史、话题、渠道专线),使用 get_teammate_state 的 profile.id。不限制当前 workdir;未关联的旧 IM 记录不自动认领。'),
+ source: z.string().min(1).max(64).optional().describe('精确匹配任务原始 source,如 telegram(旧独立机器人)或 bot(伙伴)。不指定则跨来源搜索。'),
query: z.string().min(1).max(256).describe('自然语言查询(必填, 最长 256)。例: "上次怎么修的语音输入授权问题"。'),
session_ids: stringArrayParam(z.array(z.string().min(1)).max(50))
.optional()
@@ -164,6 +166,8 @@ export function registerSearchChatHistoryTool(
const res = await deps.history.searchChatHistory({
query: query.trim(),
sessionIds: scope.sessionIds,
+ ...(args.teammate_id ? { teammateId: args.teammate_id } : {}),
+ ...(args.source ? { source: args.source } : {}),
workdir: workdir ?? null,
fromMs,
toMs,
@@ -222,6 +226,8 @@ export function registerSearchChatHistoryTool(
hasMore: result.hasMore,
query: {
query: query.trim(),
+ teammate_id: args.teammate_id,
+ source: args.source,
session_ids,
workdir,
from,