import crypto from 'node:crypto';
import { buildUserContent } from '../multimodal.js';
import { isModelHistoryMessage } from '../runtime/systemEvents.js';
import type { Message, ToolCall, ToolResult, Provider } from '../types.js';
// ---------------- 辅助函数 ----------------
/**
* 易变上下文只存在于 provider 请求副本中,不会进入会话历史。
*/
export const SYSTEM_REMINDER_OPEN = '';
export const SYSTEM_REMINDER_CLOSE = '';
/**
* Attach transient context to the current turn's user message in a model-only
* clone. Later tool-loop requests reuse the same decorated message, making each
* serialized request a strict prefix extension of the previous one.
*/
export function buildModelMessages(
history: Message[],
transientContext?: string,
currentUserMessageId?: string,
): Message[] {
history = history.filter(isModelHistoryMessage);
const transient = transientContext?.trim();
if (!transient) return history;
let index = currentUserMessageId
? history.findIndex((message) => message.role === 'user' && message.id === currentUserMessageId)
: -1;
if (index < 0) {
for (let cursor = history.length - 1; cursor >= 0; cursor--) {
if (history[cursor]?.role === 'user') {
index = cursor;
break;
}
}
}
if (index < 0) return history;
const target = history[index];
if (target.role !== 'user') return history;
const reminder = `${SYSTEM_REMINDER_OPEN}\n${transient}\n${SYSTEM_REMINDER_CLOSE}`;
const content =
typeof target.content === 'string'
? `${target.content}\n\n${reminder}`
: [...target.content, { type: 'text' as const, text: reminder }];
const next = [...history];
next[index] = { ...target, content };
return next;
}
// 关键节点图像核验的合成消息标记:既是给模型的提示前缀,也是 evictPriorVisionShots 识别旧图消息的锚。
export const VISION_SHOT_MARKER = '【实况图像】';
/**
* 历史标记。这套机制最初只有 WebBrowser 用得上,文案写死了「浏览器」;
* 现在 Bash 的 ATTACH_IMAGE sentinel 也能产图(屏幕截图 / 生成的产物),文案必须中性。
* 但**持久化会话里仍存着旧前缀的消息**,淘汰逻辑必须继续认它 ——
* 否则老会话里的旧截图永远不会被降级,图片一路累积撑爆上下文。
*/
const LEGACY_VISION_SHOT_MARKERS = ['【浏览器实况截图】'] as const;
const VISION_SHOT_PROMPT = `${VISION_SHOT_MARKER}上面是刚才工具执行后附带的真实图像(浏览器页面 / 屏幕截图 / 生成的产物)。请仔细看图核对:是否真的到达/呈现了你预期的状态?若与预期不符(空白/报错/弹窗遮挡/验证拦截/内容不对),不要假设成功,如实说明并调整下一步。`;
/** 一条 user 消息的文本是否是「实况图像」合成消息(含历史前缀)。 */
function isVisionShotText(text: string): boolean {
return text.startsWith(VISION_SHOT_MARKER) || LEGACY_VISION_SHOT_MARKERS.some((marker) => text.startsWith(marker));
}
/**
* 把本轮工具附带的实况截图(ToolResult.visionImages)组装成一条带图 user 消息喂给模型自我核验。
* - 仅在模型明确支持识图时注入(provider.supportsVision === true);否则丢弃(不假装核验、也不给非视觉端点发图触发 400)。
* - 注入前先把历史里旧的截图消息降级为纯文字占位(evictPriorVisionShots),保证上下文里最多一张实况图,
* 避免图片累积撑爆上下文(呼应浏览器 ADR「高频帧只存内存、只持久化最终结果」)。
* - **失败的工具结果同样回填**:出错现场那张图往往比成功时更有信息量(权限弹窗、
* 验证拦截、意外的前台窗口)。此前这里要求 `ok === true`,逼得想附图的工具只能
* 把失败伪装成成功——见 types.ts 里 ToolResult 那段注释。
*/
export async function injectVisionFollowups(
history: Message[],
settled: { result: ToolResult }[],
provider: Provider,
): Promise {
if (provider.supportsVision === false) return null;
const images = settled.flatMap((s) => s.result.visionImages ?? []);
if (images.length === 0) return null;
evictPriorVisionShots(history);
// 工具可以给自己这批图配一句说明(visionNote)。内核只负责把它拼在通用提示之后,
// 不解读内容——「这是一组 1Hz 连续帧」这类语义只有产图的工具知道。
const notes = settled
.flatMap((s) => (s.result.visionNote ? [s.result.visionNote] : []))
.filter((note, index, all) => all.indexOf(note) === index);
const text = notes.length > 0 ? `${VISION_SHOT_PROMPT}\n\n${notes.join('\n\n')}` : VISION_SHOT_PROMPT;
const content = await buildUserContent({ text, images });
const msg: Message = {
role: 'user',
inputOrigin: 'tool-observation',
content,
timestamp: Date.now(),
id: crypto.randomUUID(),
};
history.push(msg);
return msg;
}
/** 把历史里旧的实况图像 user 消息降级为纯文字占位、剔除其图片,释放上下文(只保留最近一张真图)。 */
export function evictPriorVisionShots(history: Message[]): void {
for (const msg of history) {
if (msg.role !== 'user' || !Array.isArray(msg.content)) continue;
const textPart = msg.content.find((p) => p.type === 'text');
if (textPart?.type === 'text' && isVisionShotText(textPart.text)) {
msg.content = `${VISION_SHOT_MARKER}(此前的实况图像已从上下文移除以节省空间。)`;
}
}
}
/**
* 用户按ESC手动中断
*/
export function pushManualInterruptMarker(history: Message[]): void {
history.push({
role: 'user',
content: '(用户按下了 ESC/Ctrl+C 中断了任务。等待用户新指令。)',
timestamp: Date.now(),
id: crypto.randomUUID(),
});
}
/**
* 回答已发布但实质成果没经顾问复核(advisor.enforcement='followup'):补一条系统提示,
* 让模型自己去调 Advisor。回答不撤回,Advisor 调用由模型发出,宿主不替它伪造。
*/
export function pushAdvisorFollowUpMarker(history: Message[]): void {
history.push({
role: 'user',
content: '(系统提示:你刚才给出的回答包含实质结论或成果,但还没有经过顾问复核。现在调用 Advisor 复核:意见指出问题就更正并说明;没有异议则用一句话说明已复核,不要重复整篇回答。)',
timestamp: Date.now(),
id: crypto.randomUUID(),
});
}
/**
* 有新的用户输入在队列中,当前安全停靠
*/
export function pushQueuedInputMarker(history: Message[]): void {
history.push({
role: 'user',
content: [
'(系统提示:用户在工作过程中发送了新的消息。',
'你现在看到的是上一轮工作在被打断前已完成的部分。',
'请阅读用户的新消息,判断:',
'1. 如果是不相关的新任务:简要确认已收到,转向新任务,可在新任务完成后询问是否回到之前工作',
'2. 如果是补充信息或前置依赖:把新信息纳入考虑,判断是否需要调整已做的工作,然后继续',
'3. 如果是改变方向或取消:评估已完成的部分,说明你对变更的理解,按新方向推进)',
].join('\n'),
timestamp: Date.now(),
id: crypto.randomUUID(),
});
}
/** 把一条 tool_call_delta 合并到累积数组上 */
export function mergeToolCallDelta(
acc: ToolCall[],
ev: {
index: number;
id?: string;
name?: string;
argumentsDelta?: string;
},
): void {
if (!Number.isSafeInteger(ev.index) || ev.index < 0 || ev.index > 1023)
throw new Error('模型流提供了无效的工具调用索引');
if ([ev.id, ev.name, ev.argumentsDelta].some(value => value !== undefined && typeof value !== 'string'))
throw new Error('模型流提供了无效的工具调用字段');
let slot = acc[ev.index];
if (!slot) {
slot = {
id: '',
type: 'function',
function: { name: '', arguments: '' },
};
acc[ev.index] = slot;
}
if (ev.id) {
if (slot.id && slot.id !== ev.id) throw new Error('模型流的同一个工具调用存在冲突的身份');
slot.id = ev.id;
}
if (ev.name) slot.function.name += ev.name;
if (ev.argumentsDelta) slot.function.arguments += ev.argumentsDelta;
}