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(session-ref): 引用载荷不再重复投递已内联的被引消息,并保护锚点不被削头

Zhang Yunjin9995cc3f32b4
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 55cbab1ae2..ca68e90498 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -2088,7 +2088,10 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {
);
await flush();
- expect(h.resolveSessionReferences).toHaveBeenCalledWith([{ sessionId: 'foreign-session' }]);
+ expect(h.resolveSessionReferences).toHaveBeenCalledWith(
+ [{ sessionId: 'foreign-session' }],
+ { inlineMessageKeys: new Set() },
+ );
expect(h.sendToAgent).toHaveBeenCalledWith(
'target-session',
{ type: 'user', content: text },
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
index cc83e1c915..2185c3cd0c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
@@ -221,6 +221,71 @@ describe('sessionReferenceResolver', () => {
]);
});
+ it('omits an anchor the composer already delivered verbatim in the message text', async () => {
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: [{
+ id: 'anchor-id',
+ clientId: 'anchor',
+ sessionId: 's-1',
+ role: 'assistant',
+ content: '报告全文',
+ createdAt: 100,
+ }],
+ })
+ .mockResolvedValueOnce(historyPage([
+ { id: 'older-id', sessionId: 's-1', role: 'user', content: '更早的一条', createdAt: 99 },
+ ]))
+ .mockResolvedValueOnce(historyPage([]));
+
+ const [context] = await resolveSessionReferences(
+ [{ sessionId: 's-1', deviceId: 'dev-1', messageClientId: 'anchor' }],
+ { inlineMessageKeys: new Set(['s-1\u0000anchor']) },
+ );
+
+ // The quoted body already reached the model inside the user message, so the
+ // payload must not deliver it a second time (and must not trim it).
+ expect(context.messages.map((message) => message.content)).toEqual(['更早的一条']);
+ expect(context.messageClientId).toBe('anchor');
+ expect(context.range).toBe('around-anchor');
+ });
+
+ it('keeps the anchor whole when the serialized payload has to shrink', async () => {
+ // The anchor is the longest message and carries quotes, so the escaped
+ // JSON costs far more than the raw text: the final payload fit has to shed
+ // content, and it must not shed the anchor the user pointed at.
+ const anchorBody = '结'.repeat(2_000) + '"'.repeat(8_000);
+ const neighborBody = '邻'.repeat(2_900);
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: [{
+ id: 'anchor-id',
+ clientId: 'anchor',
+ sessionId: 's-1',
+ role: 'assistant',
+ content: anchorBody,
+ createdAt: 100,
+ }],
+ })
+ .mockResolvedValueOnce(historyPage([]))
+ .mockResolvedValueOnce(historyPage([
+ { id: 'after-id', sessionId: 's-1', role: 'user', content: neighborBody, createdAt: 101 },
+ ]));
+
+ const [context] = await resolveSessionReferences(
+ [{ sessionId: 's-1', deviceId: 'dev-1', messageClientId: 'anchor' }],
+ );
+
+ expect(context.messages[0]?.content).toBe(anchorBody);
+ expect(context.messages[1]?.content.startsWith('…')).toBe(true);
+ expect(estimateReferenceTokens(serializeSessionReferencePayload([context])))
+ .toBeLessThanOrEqual(MAX_REFERENCE_TOKENS - 128);
+ });
+
it('keeps the anchor when a long following message exhausts the token budget', async () => {
remoteInvoke
.mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index e3cfa94d6e..b46057a402 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -88,6 +88,7 @@ import {
import { CONTINUE_AFTER_ERROR_PROMPT, syntheticTriggerKind } from '../../shared/interruptedTurn.js';
import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';
import { attachSessionReferenceMetadata } from '../../shared/sessionReferenceMetadata.js';
+import { collectInlineMessageReferenceKeys } from '@cindy/maker-shared/agent-input-projection';
import {
appendRecoveryCheckpointPrompt,
buildRecoveryCheckpoint,
@@ -486,6 +487,7 @@ export interface AgentInputCoordinatorDeps {
/** 在 vendor dispatch 前读取用户选中的本地/在线会话引用。 */
resolveSessionReferences?: (
refs: AgentInputQueuedMessage['sessionRefs'],
+ options?: { inlineMessageKeys?: ReadonlySet<string> },
) => Promise<AgentInputSessionReferenceContext[]>;
/**
* Refresh ephemeral structured-reference state at the actual dispatch
@@ -4589,7 +4591,10 @@ export class AgentInputCoordinator {
throw new Error('Remote session reference snapshot is missing; edit and resend the message.');
}
try {
- return await (this.deps.resolveSessionReferences?.(item.sessionRefs) ?? []);
+ return await (this.deps.resolveSessionReferences?.(item.sessionRefs, {
+ // 引用的消息正文已经在用户消息里逐字送达,引用载荷不再重复投递。
+ inlineMessageKeys: collectInlineMessageReferenceKeys(item.agentReferences),
+ }) ?? []);
} catch (error) {
// Session links are still useful as ordinary Agent-facing text when the
// referenced session belongs to another account, was deleted, or is
diff --git a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
index dad510051f..cf6cdfd8da 100644
--- a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
@@ -12,6 +12,7 @@ import { messages, sessions } from '../localDb/schema.js';
import { readLatestSessionTerminal } from '../localDb/sessionTerminal.js';
import { messageToCamel } from '../localDb/mapper.js';
import { isSyntheticTriggerText } from '../../shared/interruptedTurn.js';
+import { agentInputMessageReferenceKey } from '@cindy/maker-shared/agent-input-projection';
import {
serializeSessionReferencePayload,
type AgentInputSessionRef,
@@ -109,28 +110,42 @@ function fitMessagesToTokenBudget(
raw: AgentInputSessionReferenceMessage[],
tokenBudget: number,
anchorIndex?: number,
-): { messages: AgentInputSessionReferenceMessage[]; usedTokens: number; truncated: boolean } {
+ options?: { excludeAnchor?: boolean },
+): {
+ messages: AgentInputSessionReferenceMessage[];
+ usedTokens: number;
+ truncated: boolean;
+ /** Position of the anchor inside `messages`; -1 when it is not part of the quote. */
+ anchorPosition: number;
+} {
if (anchorIndex !== undefined && raw[anchorIndex]) {
const anchor = raw[anchorIndex];
const anchorTokens = estimateReferenceTokens(anchor.content);
- if (anchorTokens >= tokenBudget) {
+ // The anchor can already be delivered verbatim inside the user message. In
+ // that case the quote only carries the surrounding context, and the anchor
+ // body must not be paid for twice.
+ const excludeAnchor = options?.excludeAnchor === true;
+ if (!excludeAnchor && anchorTokens >= tokenBudget) {
const content = sliceTailToTokenBudget(anchor.content, tokenBudget);
return {
messages: content ? [{ ...anchor, content }] : [],
usedTokens: tokenBudget,
truncated: true,
+ anchorPosition: content ? 0 : -1,
};
}
- let remaining = tokenBudget - anchorTokens;
- const kept = new Map<number, AgentInputSessionReferenceMessage>([[anchorIndex, anchor]]);
+ let remaining = excludeAnchor ? tokenBudget : tokenBudget - anchorTokens;
+ const kept = new Map<number, AgentInputSessionReferenceMessage>();
+ if (!excludeAnchor) kept.set(anchorIndex, anchor);
let budgetExhausted = false;
let partialTruncation = false;
for (let distance = 1; kept.size < raw.length && !budgetExhausted; distance += 1) {
if (remaining === 0) break;
- const candidates = [anchorIndex - distance, anchorIndex + distance];
+ const candidates: number[] = [anchorIndex - distance, anchorIndex + distance];
let found = false;
for (const index of candidates) {
+ if (index === anchorIndex) continue;
const message = raw[index];
if (!message) continue;
found = true;
@@ -149,10 +164,15 @@ function fitMessagesToTokenBudget(
}
if (!found) break;
}
+ const messages = [...kept.entries()].sort(([a], [b]) => a - b).map(([, message]) => message);
+ // The anchor was left out on purpose (it is already in the user message),
+ // so it does not count as a budget loss.
+ const available = raw.length - (excludeAnchor ? 1 : 0);
return {
- messages: [...kept.entries()].sort(([a], [b]) => a - b).map(([, message]) => message),
+ messages,
usedTokens: tokenBudget - remaining,
- truncated: partialTruncation || kept.size < raw.length,
+ truncated: partialTruncation || kept.size < available,
+ anchorPosition: excludeAnchor ? -1 : messages.indexOf(anchor),
};
}
@@ -176,12 +196,13 @@ function fitMessagesToTokenBudget(
truncated = true;
break;
}
- return { messages: kept, usedTokens: tokenBudget - remaining, truncated };
+ return { messages: kept, usedTokens: tokenBudget - remaining, truncated, anchorPosition: -1 };
}
/** Enforce the budget on the exact JSON that will be injected, including escaping and metadata. */
function fitSerializedPayloadBudget(
input: readonly AgentInputSessionReferenceContext[],
+ anchorPositions: readonly number[] = [],
): AgentInputSessionReferenceContext[] {
const contexts = input.map((context) => ({
...context,
@@ -189,16 +210,33 @@ function fitSerializedPayloadBudget(
}));
let tokens = estimateReferenceTokens(serializeSessionReferencePayload(contexts));
while (tokens > FINAL_REFERENCE_PAYLOAD_TOKENS) {
+ // The anchor is the message the user pointed at: it must not lose its head
+ // while other quoted content can still be shed.
let targetContext: AgentInputSessionReferenceContext | undefined;
let targetMessage: AgentInputSessionReferenceMessage | undefined;
- for (const context of contexts) {
- for (const message of context.messages) {
+ for (let contextIndex = 0; contextIndex < contexts.length; contextIndex += 1) {
+ const context = contexts[contextIndex];
+ const anchorPosition = anchorPositions[contextIndex] ?? -1;
+ for (let messageIndex = 0; messageIndex < context.messages.length; messageIndex += 1) {
+ if (messageIndex === anchorPosition) continue;
+ const message = context.messages[messageIndex];
if (!targetMessage || message.content.length > targetMessage.content.length) {
targetContext = context;
targetMessage = message;
}
}
}
+ if (!targetMessage) {
+ // Only anchors are left; the payload cap still has to hold.
+ for (const context of contexts) {
+ for (const message of context.messages) {
+ if (!targetMessage || message.content.length > targetMessage.content.length) {
+ targetContext = context;
+ targetMessage = message;
+ }
+ }
+ }
+ }
if (targetMessage && targetMessage.content.length > 1) {
const excess = tokens - FINAL_REFERENCE_PAYLOAD_TOKENS;
const drop = Math.min(targetMessage.content.length - 1, Math.max(1, excess));
@@ -354,7 +392,8 @@ async function resolveLocal(
ref: AgentInputSessionRef,
messageLimit: number,
tokenBudget: number,
-): Promise<{ context: AgentInputSessionReferenceContext; usedTokens: number }> {
+ options?: { excludeAnchor?: boolean },
+): Promise<{ context: AgentInputSessionReferenceContext; usedTokens: number; anchorPosition: number }> {
const db = getDbClient().drizzle;
const [session] = await db
.select({
@@ -393,7 +432,12 @@ async function resolveLocal(
if (ref.messageClientId && anchorIndex === -1) {
throw new SessionReferenceError('SESSION_REFERENCE_NOT_FOUND', `找不到消息锚点 ${ref.messageClientId}`);
}
- const fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ const excludeAnchor = options?.excludeAnchor === true && anchorIndex !== undefined;
+ let fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex, { excludeAnchor });
+ if (excludeAnchor && fitted.messages.length === 0) {
+ // An empty quote carries nothing: keep the anchor instead.
+ fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ }
return {
context: {
sessionId: ref.sessionId,
@@ -407,6 +451,7 @@ async function resolveLocal(
...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
+ anchorPosition: fitted.anchorPosition,
};
}
@@ -596,7 +641,8 @@ async function resolveRemote(
ref: AgentInputSessionRef,
messageLimit: number,
tokenBudget: number,
-): Promise<{ context: AgentInputSessionReferenceContext; usedTokens: number }> {
+ options?: { excludeAnchor?: boolean },
+): Promise<{ context: AgentInputSessionReferenceContext; usedTokens: number; anchorPosition: number }> {
if (!ref.deviceId) {
throw new SessionReferenceError('SESSION_REFERENCE_NOT_FOUND', `任务 ${ref.sessionId} 没有在线来源设备`);
}
@@ -697,7 +743,12 @@ async function resolveRemote(
if (mapped.length === 0) {
throw new SessionReferenceError('SESSION_REFERENCE_NOT_FOUND', `任务 ${ref.sessionId} 没有可引用的可见消息`);
}
- const fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ const excludeAnchor = options?.excludeAnchor === true && anchorIndex !== undefined;
+ let fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex, { excludeAnchor });
+ if (excludeAnchor && fitted.messages.length === 0) {
+ // An empty quote carries nothing: keep the anchor instead.
+ fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ }
return {
context: {
sessionId: ref.sessionId,
@@ -714,12 +765,14 @@ async function resolveRemote(
...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
+ anchorPosition: fitted.anchorPosition,
};
}
/** 解析全部引用;超出数量或共享预算时明确报错/标记,不静默丢引用。 */
export async function resolveSessionReferences(
refs: readonly AgentInputSessionRef[] | undefined,
+ options?: { inlineMessageKeys?: ReadonlySet<string> },
): Promise<AgentInputSessionReferenceContext[]> {
if (!refs || refs.length === 0) return [];
if (refs.length > MAX_SESSION_REFERENCES) {
@@ -729,6 +782,7 @@ export async function resolveSessionReferences(
);
}
const contexts: AgentInputSessionReferenceContext[] = [];
+ const anchorPositions: number[] = [];
let remainingMessages = MAX_REFERENCE_MESSAGES;
let remainingTokens = MAX_REFERENCE_TOKENS;
for (let index = 0; index < refs.length; index++) {
@@ -752,12 +806,24 @@ export async function resolveSessionReferences(
const remoteDeviceId = ref.deviceId && ref.deviceId !== getSelfDeviceId()
? ref.deviceId
: undefined;
+ // The anchor is already delivered verbatim inside the user message when the
+ // composer inlined it; the quote then carries the surrounding context only.
+ const inlineAnchor = ref.messageClientId !== undefined
+ && options?.inlineMessageKeys?.has(
+ agentInputMessageReferenceKey(ref.sessionId, ref.messageClientId),
+ ) === true;
const resolved = remoteDeviceId
- ? await resolveRemote({ ...ref, deviceId: remoteDeviceId }, messageLimit, tokenBudget)
- : await resolveLocal(ref, messageLimit, tokenBudget);
+ ? await resolveRemote(
+ { ...ref, deviceId: remoteDeviceId },
+ messageLimit,
+ tokenBudget,
+ { excludeAnchor: inlineAnchor },
+ )
+ : await resolveLocal(ref, messageLimit, tokenBudget, { excludeAnchor: inlineAnchor });
contexts.push(resolved.context);
+ anchorPositions.push(resolved.anchorPosition);
remainingMessages -= resolved.context.messageCount;
remainingTokens -= resolved.usedTokens;
}
- return fitSerializedPayloadBudget(contexts);
+ return fitSerializedPayloadBudget(contexts, anchorPositions);
}
diff --git a/apps/mobile/src/__tests__/sessionReferences.test.ts b/apps/mobile/src/__tests__/sessionReferences.test.ts
index a70fdace7f..444b6ab063 100644
--- a/apps/mobile/src/__tests__/sessionReferences.test.ts
+++ b/apps/mobile/src/__tests__/sessionReferences.test.ts
@@ -535,6 +535,65 @@ describe('resolveMobileSessionReferences', () => {
]);
});
+ it('omits an anchor the composer already delivered verbatim in the message text', async () => {
+ const invoke = asInvoke(async (_deviceId, channel, args) => {
+ if (channel === 'local-db:sessions:get') return { id: args[0] };
+ if (channel === 'local-db:messages:around-client-id') {
+ return [message('s1', '5', 'anchor', '报告全文', 'assistant', 5_000)];
+ }
+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {
+ const request = args[0] as { order: string };
+ return request.order === 'desc'
+ ? { items: [message('s1', '4', 'c4', '更早的一条', 'user', 4_000)], hasMore: false }
+ : { items: [], hasMore: false };
+ }
+ throw new Error(`unexpected channel ${channel}`);
+ });
+
+ const [context] = await resolveMobileSessionReferences(
+ [{ sessionId: 's1', messageClientId: 'anchor', deviceId: 'dev-b' }],
+ invoke,
+ { inlineMessageKeys: new Set(['s1\u0000anchor']) },
+ );
+
+ // The quoted body already reached the model inside the user message, so the
+ // payload must not deliver it a second time (and must not trim it).
+ expect(context.messages.map((item) => item.content)).toEqual(['更早的一条']);
+ expect(context.messageClientId).toBe('anchor');
+ expect(context.range).toBe('around-anchor');
+ });
+
+ it('keeps the anchor whole when the serialized payload has to shrink', async () => {
+ // The anchor is the longest message and carries quotes, so the escaped
+ // JSON costs far more than the raw text: the final payload fit has to shed
+ // content, and it must not shed the anchor the user pointed at.
+ const anchorBody = '结'.repeat(2_000) + '"'.repeat(8_000);
+ const neighborBody = '邻'.repeat(2_900);
+ const invoke = asInvoke(async (_deviceId, channel, args) => {
+ if (channel === 'local-db:sessions:get') return { id: args[0] };
+ if (channel === 'local-db:messages:around-client-id') {
+ return [message('s1', '5', 'anchor', anchorBody, 'assistant', 5_000)];
+ }
+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {
+ const request = args[0] as { order: string };
+ return request.order === 'desc'
+ ? { items: [], hasMore: false }
+ : { items: [message('s1', '6', 'c6', neighborBody, 'user', 6_000)], hasMore: false };
+ }
+ throw new Error(`unexpected channel ${channel}`);
+ });
+
+ const [context] = await resolveMobileSessionReferences(
+ [{ sessionId: 's1', messageClientId: 'anchor', deviceId: 'dev-b' }],
+ invoke,
+ );
+
+ expect(context.messages[0]?.content).toBe(anchorBody);
+ expect(context.messages[1]?.content.startsWith('…')).toBe(true);
+ expect(estimateMobileReferenceTokens(serializeMobileSessionReferencePayload([context])))
+ .toBeLessThanOrEqual(8_000 - 128);
+ });
+
it('marks an anchored neighbor as truncated when it is partially kept', async () => {
const invoke = asInvoke(async (_deviceId, channel, args) => {
if (channel === 'local-db:sessions:get') return { id: args[0] };
diff --git a/apps/mobile/src/session/sessionReferences.ts b/apps/mobile/src/session/sessionReferences.ts
index fa059efd44..4ed6516bff 100644
--- a/apps/mobile/src/session/sessionReferences.ts
+++ b/apps/mobile/src/session/sessionReferences.ts
@@ -10,6 +10,11 @@ import {
trimSessionLinkMatch,
} from '@/session/sessionLinks';
import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';
+import {
+ agentInputMessageReferenceKey,
+ collectInlineMessageReferenceKeys,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
export const MAX_MOBILE_SESSION_REFERENCES = 8;
export const MAX_MOBILE_REFERENCE_MESSAGES = 20;
@@ -73,6 +78,8 @@ interface MobileQueuedReferenceCarrier {
sessionRefs?: MobileSessionReference[];
trustedSessionReferenceContexts?: MobileSessionReferenceContext[];
sessionReferencesRequireTrustedSnapshot?: boolean;
+ /** Composer references already delivered verbatim in the message text. */
+ agentReferences?: readonly AgentInputReference[];
}
export type MobileSessionReferenceErrorCode =
@@ -271,28 +278,42 @@ function fitMessagesToTokenBudget(
raw: MobileSessionReferenceMessage[],
tokenBudget: number,
anchorIndex?: number,
-): { messages: MobileSessionReferenceMessage[]; usedTokens: number; truncated: boolean } {
+ options?: { excludeAnchor?: boolean },
+): {
+ messages: MobileSessionReferenceMessage[];
+ usedTokens: number;
+ truncated: boolean;
+ /** Position of the anchor inside `messages`; -1 when it is not part of the quote. */
+ anchorPosition: number;
+} {
if (anchorIndex !== undefined && raw[anchorIndex]) {
const anchor = raw[anchorIndex];
const anchorTokens = estimateMobileReferenceTokens(anchor.content);
- if (anchorTokens >= tokenBudget) {
+ // The anchor can already be delivered verbatim inside the user message. In
+ // that case the quote only carries the surrounding context, and the anchor
+ // body must not be paid for twice.
+ const excludeAnchor = options?.excludeAnchor === true;
+ if (!excludeAnchor && anchorTokens >= tokenBudget) {
const content = sliceTailToTokenBudget(anchor.content, tokenBudget);
return {
messages: content ? [{ ...anchor, content }] : [],
usedTokens: tokenBudget,
truncated: true,
+ anchorPosition: content ? 0 : -1,
};
}
- let remaining = tokenBudget - anchorTokens;
- const kept = new Map<number, MobileSessionReferenceMessage>([[anchorIndex, anchor]]);
+ let remaining = excludeAnchor ? tokenBudget : tokenBudget - anchorTokens;
+ const kept = new Map<number, MobileSessionReferenceMessage>();
+ if (!excludeAnchor) kept.set(anchorIndex, anchor);
let budgetExhausted = false;
let partialTruncation = false;
for (let distance = 1; kept.size < raw.length && !budgetExhausted; distance += 1) {
if (remaining === 0) break;
- const candidates = [anchorIndex - distance, anchorIndex + distance];
+ const candidates: number[] = [anchorIndex - distance, anchorIndex + distance];
let found = false;
for (const index of candidates) {
+ if (index === anchorIndex) continue;
const message = raw[index];
if (!message) continue;
found = true;
@@ -311,10 +332,15 @@ function fitMessagesToTokenBudget(
}
if (!found) break;
}
+ const messages = [...kept.entries()].sort(([left], [right]) => left - right).map(([, message]) => message);
+ // The anchor was left out on purpose (it is already in the user message),
+ // so it does not count as a budget loss.
+ const available = raw.length - (excludeAnchor ? 1 : 0);
return {
- messages: [...kept.entries()].sort(([left], [right]) => left - right).map(([, message]) => message),
+ messages,
usedTokens: tokenBudget - remaining,
- truncated: partialTruncation || kept.size < raw.length,
+ truncated: partialTruncation || kept.size < available,
+ anchorPosition: excludeAnchor ? -1 : messages.indexOf(anchor),
};
}
@@ -338,11 +364,12 @@ function fitMessagesToTokenBudget(
truncated = true;
break;
}
- return { messages: kept, usedTokens: tokenBudget - remaining, truncated };
+ return { messages: kept, usedTokens: tokenBudget - remaining, truncated, anchorPosition: -1 };
}
function fitSerializedPayloadBudget(
input: readonly MobileSessionReferenceContext[],
+ anchorPositions: readonly number[] = [],
): MobileSessionReferenceContext[] {
const contexts = input.map((context) => ({
...context,
@@ -350,16 +377,33 @@ function fitSerializedPayloadBudget(
}));
let tokens = estimateMobileReferenceTokens(serializeMobileSessionReferencePayload(contexts));
while (tokens > FINAL_REFERENCE_PAYLOAD_TOKENS) {
+ // The anchor is the message the user pointed at: it must not lose its head
+ // while other quoted content can still be shed.
let targetContext: MobileSessionReferenceContext | undefined;
let targetMessage: MobileSessionReferenceMessage | undefined;
- for (const context of contexts) {
- for (const message of context.messages) {
+ for (let contextIndex = 0; contextIndex < contexts.length; contextIndex += 1) {
+ const context = contexts[contextIndex];
+ const anchorPosition = anchorPositions[contextIndex] ?? -1;
+ for (let messageIndex = 0; messageIndex < context.messages.length; messageIndex += 1) {
+ if (messageIndex === anchorPosition) continue;
+ const message = context.messages[messageIndex];
if (!targetMessage || message.content.length > targetMessage.content.length) {
targetContext = context;
targetMessage = message;
}
}
}
+ if (!targetMessage) {
+ // Only anchors are left; the payload cap still has to hold.
+ for (const context of contexts) {
+ for (const message of context.messages) {
+ if (!targetMessage || message.content.length > targetMessage.content.length) {
+ targetContext = context;
+ targetMessage = message;
+ }
+ }
+ }
+ }
if (targetMessage && targetMessage.content.length > 1) {
const excess = tokens - FINAL_REFERENCE_PAYLOAD_TOKENS;
const drop = Math.min(targetMessage.content.length - 1, Math.max(1, excess));
@@ -601,7 +645,8 @@ async function resolveRemoteReference(
ref: MobileSessionReference,
messageLimit: number,
tokenBudget: number,
-): Promise<{ context: MobileSessionReferenceContext; usedTokens: number }> {
+ options?: { excludeAnchor?: boolean },
+): Promise<{ context: MobileSessionReferenceContext; usedTokens: number; anchorPosition: number }> {
if (!ref.deviceId) {
throw new MobileSessionReferenceError(
'SESSION_REFERENCE_NOT_FOUND',
@@ -706,7 +751,12 @@ async function resolveRemoteReference(
`Session ${ref.sessionId} has no visible messages to reference`,
);
}
- const fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ const excludeAnchor = options?.excludeAnchor === true && anchorIndex !== undefined;
+ let fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex, { excludeAnchor });
+ if (excludeAnchor && fitted.messages.length === 0) {
+ // An empty quote carries nothing: keep the anchor instead.
+ fitted = fitMessagesToTokenBudget(mapped, tokenBudget, anchorIndex);
+ }
return {
context: {
sessionId: ref.sessionId,
@@ -723,6 +773,7 @@ async function resolveRemoteReference(
...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
+ anchorPosition: fitted.anchorPosition,
};
}
@@ -730,6 +781,7 @@ async function resolveRemoteReference(
export async function resolveMobileSessionReferences(
refs: readonly MobileSessionReference[] | undefined,
invoke: RemoteInvoke,
+ options?: { inlineMessageKeys?: ReadonlySet<string> },
): Promise<MobileSessionReferenceContext[]> {
if (!refs || refs.length === 0) return [];
if (refs.length > MAX_MOBILE_SESSION_REFERENCES) {
@@ -740,6 +792,7 @@ export async function resolveMobileSessionReferences(
}
const contexts: MobileSessionReferenceContext[] = [];
+ const anchorPositions: number[] = [];
let remainingMessages = MAX_MOBILE_REFERENCE_MESSAGES;
let remainingTokens = MAX_MOBILE_REFERENCE_TOKENS;
for (let index = 0; index < refs.length; index += 1) {
@@ -764,12 +817,25 @@ export async function resolveMobileSessionReferences(
const referencesLeft = refs.length - index;
const messageLimit = Math.max(1, Math.floor(remainingMessages / referencesLeft));
const tokenBudget = Math.max(1, Math.floor(remainingTokens / referencesLeft));
- const resolved = await resolveRemoteReference(invoke, ref, messageLimit, tokenBudget);
+ // The anchor is already delivered verbatim inside the user message when the
+ // composer inlined it; the quote then carries the surrounding context only.
+ const inlineAnchor = ref.messageClientId !== undefined
+ && options?.inlineMessageKeys?.has(
+ agentInputMessageReferenceKey(ref.sessionId, ref.messageClientId),
+ ) === true;
+ const resolved = await resolveRemoteReference(
+ invoke,
+ ref,
+ messageLimit,
+ tokenBudget,
+ { excludeAnchor: inlineAnchor },
+ );
contexts.push(resolved.context);
+ anchorPositions.push(resolved.anchorPosition);
remainingMessages -= resolved.context.messageCount;
remainingTokens -= resolved.usedTokens;
}
- return fitSerializedPayloadBudget(contexts);
+ return fitSerializedPayloadBudget(contexts, anchorPositions);
}
/**
@@ -876,7 +942,10 @@ export async function prepareMobileQueuedSessionReferences<T extends MobileQueue
return prepared;
}
try {
- const contexts = await resolveMobileSessionReferences(refs, invoke);
+ const contexts = await resolveMobileSessionReferences(refs, invoke, {
+ // 引用的消息正文已经在用户消息里逐字送达,引用载荷不再重复投递。
+ inlineMessageKeys: collectInlineMessageReferenceKeys(item.agentReferences),
+ });
return {
...prepared,
sessionRefs: refs,
@@ -917,7 +986,10 @@ export async function prepareMobileQueuedSessionReferencesForSteer<T extends Mob
return prepared;
}
try {
- const contexts = await resolveMobileSessionReferences(refs, invoke);
+ const contexts = await resolveMobileSessionReferences(refs, invoke, {
+ // 引用的消息正文已经在用户消息里逐字送达,引用载荷不再重复投递。
+ inlineMessageKeys: collectInlineMessageReferenceKeys(item.agentReferences),
+ });
return {
...prepared,
sessionRefs: refs,
diff --git a/packages/maker-shared/src/agentInputProjection.ts b/packages/maker-shared/src/agentInputProjection.ts
index 4f8a2b5cbc..11bbc27d5b 100644
--- a/packages/maker-shared/src/agentInputProjection.ts
+++ b/packages/maker-shared/src/agentInputProjection.ts
@@ -136,6 +136,33 @@ export function boundAgentReferenceText(
return { text: text.slice(0, cap), truncated: true };
}
+/** Stable identity of one quoted message across the composer and the session-reference resolver. */
+export function agentInputMessageReferenceKey(sessionId: string, messageClientId: string): string {
+ return `${sessionId}\u0000${messageClientId}`;
+}
+
+/**
+ * Messages whose body already reaches the model verbatim inside the user
+ * message. The quoted-history payload must not deliver those bodies a second
+ * time: a duplicate copy spends the shared quote budget and can arrive
+ * trimmed, so the model would see the same message twice — once complete,
+ * once mutilated.
+ */
+export function collectInlineMessageReferenceKeys(
+ references: readonly AgentInputReference[] | undefined,
+): Set<string> {
+ const keys = new Set<string>();
+ for (const reference of references ?? []) {
+ if (reference.kind !== 'message') continue;
+ // No inline body, or a body that was cut at the reference cap: the quote
+ // still has to carry the message.
+ if (!reference.text?.trim()) continue;
+ if (reference.truncated === true) continue;
+ keys.add(agentInputMessageReferenceKey(reference.sessionId, reference.messageClientId));
+ }
+ return keys;
+}
+
function nonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.length > 0;
}