v1.3 工具调用及界面优化
This commit is contained in:
@@ -591,6 +591,21 @@ function focusComposerAtEnd(): void {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 零产出整轮作废时回填用户原文(ChatView 经 ref 调用):
|
||||
* 输入框为空 ⇒ 直接填入;已非空 ⇒ 原文拼在现有内容前面(两边都不丢)。
|
||||
* 回填后聚焦并把光标放到末尾,用户可直接编辑或回车重发。
|
||||
*/
|
||||
function restoreDraft(text: string): void {
|
||||
if (!text) return
|
||||
// 空判定用 trim:纯空白不算「已有内容」(否则会拼出 text\n );
|
||||
// 已有内容原样保留(不做 trim),只在其前面拼原文
|
||||
inputValue.value = inputValue.value.trim() ? `${text}\n${inputValue.value}` : text
|
||||
focusComposerAtEnd()
|
||||
}
|
||||
|
||||
defineExpose({ restoreDraft })
|
||||
|
||||
// 引导区点击 → 底部任务行同一组 handler(不允许第二套写 store 的路径),再按 §7.2 安排焦点
|
||||
function handleGuideTaskClick(kind: TaskKind): void {
|
||||
handleTaskClick(kind)
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
### 切入点描述
|
||||
|
||||
**ASD 语法**用于简洁描述"庄/闲/和"序列模式,等价于正则表达式。
|
||||
**ASD 语法**用于简洁描述"庄/闲/和"或"红/蓝"序列模式,等价于正则表达式。
|
||||
|
||||
原子:
|
||||
- a = 庄 = 红
|
||||
@@ -40,8 +40,8 @@
|
||||
|
||||
切入点决定「什么时候打」,下注决定「打哪边」。
|
||||
取值五个(全部小写):
|
||||
- a = 押庄(红方)
|
||||
- s = 押闲(蓝方)
|
||||
- a = 押庄(红)
|
||||
- s = 押闲(蓝)
|
||||
- d = 押和
|
||||
- x = 本手不下注
|
||||
- z = 局停(暂停下注,洗牌后再重新匹配切入点)
|
||||
@@ -199,6 +199,8 @@
|
||||
|
||||
### 硬约束
|
||||
|
||||
- 除珠盘路可用`庄/闲`说法外,其它路单必须用`红/蓝`。
|
||||
- 切入点对于`恰好几个`这样的表述,一律用小写字母。
|
||||
- 切入点**相邻不得同色**(不分大小写):`aa`、`dD`、`s2S3s` 全部非法,解析器直接拒绝。
|
||||
- **`d`/`D` 仅珠盘可用**;大眼路/小路/小强路下非珠盘不含「和」。
|
||||
- 运行时切入点匹配逻辑:从第 1 行逐条尝试,命中即采用并停止匹配;一行都不命中则不下注 ⇒ **难匹配的在前、易匹配的在后**。
|
||||
|
||||
+10
-10
@@ -17,7 +17,7 @@ export const WORKFLOW_PROMPT = `# 流程说明
|
||||
|
||||
## 工作流程
|
||||
1. 结合对话历史还原用户消息中的指代。
|
||||
2. 结合用户指令与 [任务选项] 识别用户意图,明确任务类型、所需策略技能、所需策略实例。当 [任务选项] 与用户正文指令冲突时,以用户正文为准。
|
||||
2. 结合用户指令与 [任务选项] 识别用户意图,明确任务类型(解释/改写/生成)、所需策略技能、所需策略实例。当 [任务选项] 与用户正文指令冲突时,以用户正文为准。
|
||||
3. 意图不明确 → 澄清,不进入后续步骤。
|
||||
4. 若用户提到了具体实例:
|
||||
a. 按规则加载该实例;
|
||||
@@ -29,14 +29,14 @@ export const WORKFLOW_PROMPT = `# 流程说明
|
||||
## 加载规则
|
||||
|
||||
### 技能(按 skill_name 认)—— 以下两条同时成立才算已加载:
|
||||
1. 对话历史里有 load_skill 的工具调用,且其 skill_name 与所需技能的英文名一致(拼写、大小写都一致);
|
||||
2. 该调用对应的工具结果是技能正文,不是以「⚠️工具调用未完成:」开头的纠错说明,也不为空。
|
||||
两条全成立 → 直接用,不再调用;任一条不成立 → 务必调用 load_skill。
|
||||
1. 当前可见对话历史里有 load_skill 的工具调用,且其 skill_name 与所需技能的英文名相同;
|
||||
2. 该调用对应的工具结果是技能正文,且包含"### 实例 JSON 结构"字段。
|
||||
两条全成立 → 直接用,不得重复调用;任一条不成立 → 务必调用 load_skill 工具加载该技能。
|
||||
|
||||
### 实例(按 分组 + 实例 认)—— 以下两条同时成立才算已加载:
|
||||
1. 对话历史里有 get_policy 的工具调用,且其 category 与目标分组一致;
|
||||
2. 该调用的结果里包含目标实例(按 id 查须出现该 id;按名查须出现该名称)——空数组、"没有「X」的「Y」策略"这类否定说明都不算。
|
||||
两条全成立 → 不再调用;任一条不成立 → 务必调用 get_policy。
|
||||
1. 当前可见对话历史里有 get_policy 的工具调用,且其 category 与目标分组一致;
|
||||
2. 该调用的结果里是目标实例(按 id 查须出现该 id;按名查须出现该名称),且包含"description"、"data"等字段。
|
||||
两条全成立 → 不得重复调用;任一条不成立 → 务必调用 get_policy 工具获取该实例。
|
||||
结果命中多条 ⇒ 全部可依据,按 description 自行判断哪条是目标;判断不了就向用户澄清,不要自己选定。
|
||||
|
||||
## 解释任务流程
|
||||
@@ -49,9 +49,9 @@ export const WORKFLOW_PROMPT = `# 流程说明
|
||||
a. 策略分组与类型已确定(打法策略/注码策略,及具体类名);
|
||||
b. 已用 load_skill 工具取到该类技能的正文;
|
||||
c. 技能要求的匹配条件、跳转路径、下注决策等都已讲全,没有未决项;
|
||||
d. 用户没有尚未处理的生成/改写要求。
|
||||
4. 只要 4 个判断条件全部满足,即使是重复上次回复,都必须在**同一次响应**中既输出完整逻辑、又调用 logic_complete 工具。**不得单独调用 logic_complete 工具**。
|
||||
5. 若逻辑不完整,向用户追加询问,直至逻辑完整。
|
||||
d. 用的生成/改写要求均已处理。
|
||||
4. 只要 4 个判断条件全部满足,则先输出完整逻辑,再在**同一次响应**中调用 logic_complete 工具。
|
||||
5. 若逻辑不完整,向用户追加询问,直至逻辑完整;否则每次回复后均应调用 logic_complete 工具。
|
||||
6. 若用户追加/变更了需求,按 1-6 步重新生成逻辑。
|
||||
|
||||
## [任务选项] 键值说明
|
||||
|
||||
+365
-81
@@ -64,6 +64,14 @@
|
||||
* (`fetchSkillBody` 统一取数,IPC 只在缓存未命中时发生)。native 不会在
|
||||
* 页面开启期间改结构 ⇒ 无需失效机制;提示词前缀缓存看的是最终文本 ——
|
||||
* 取几次得到的都是同一份字符串,不影响命中。
|
||||
*
|
||||
* ── 不重复取数 / 历史只留一份(改造后)──────────────────────────────────
|
||||
* - 已加载判定:技能按 skill_name(`inContext`),实例按 `分组 + id`
|
||||
* (`loadedPolicies`),两者都从账本恢复、校验段判重。
|
||||
* 命中 ⇒ 回纠错(「已加载,不得重复获取」),计入 `MAX_TOOL_CORRECTIONS`。
|
||||
* - 历史压缩:`compactPolicyHistory` 让同一策略实例在历史里只留**最新一份**,
|
||||
* loop 入口、每轮回填后、出口各跑一次。技能不压 —— 重复 load 在校验段就被拦下。
|
||||
* - 纠错消息跨 loop 清除:`stripToolCorrections`(loop 入口与出口各一次)。
|
||||
*/
|
||||
|
||||
import * as acorn from 'acorn'
|
||||
@@ -96,12 +104,14 @@ const LOOP_INTERNAL_ERROR_TEXT = '服务端异常,请重发'
|
||||
const MAX_TOOL_CORRECTIONS = 2
|
||||
|
||||
/**
|
||||
* 纠错回灌文案的统一前缀。两个用途:
|
||||
* 纠错回灌文案的统一前缀。三个用途:
|
||||
* 1. 历史扫描(`collectLoadedSkillsFromHistory`)据此把「失败回灌」与「成功正文」
|
||||
* 区分开 —— 失败回灌不是技能正文,不能当正文缓存 / 注入;
|
||||
* 2. 模型看到它就知道这条工具结果是「调用没成功,要纠正」。
|
||||
* 2. 模型看到它就知道这条工具结果是「调用没成功,要纠正」;
|
||||
* 3. ChatView 截断账本时据此把失败回灌排除在「必留技能正文」之外
|
||||
* (见 `utils/common.ts` 的 `TruncateMessagesOptions`)。
|
||||
*/
|
||||
const TOOL_CORRECTION_PREFIX = '⚠️工具调用未完成:'
|
||||
export const TOOL_CORRECTION_PREFIX = '⚠️工具调用未完成:'
|
||||
|
||||
/**
|
||||
* `get_policy` 的 `category` 合法值(sealed 分组,与工具 schema 的 enum 同源,
|
||||
@@ -191,8 +201,9 @@ export interface AgentLoopParams {
|
||||
onToolEvent?: (event: AgentLoopEvent) => void
|
||||
/**
|
||||
* logic_complete 声明兑现时的回调:置会话级「保存按钮可见」状态。
|
||||
* ⚠️ 触发时机是**执行段兑现时**(不是收尾)—— 兑现前提是本轮 content 非空
|
||||
* 且声明的技能正文在本轮上下文里;兑现即摘 tool_call、中止 loop、不再发请求。
|
||||
* ⚠️ 触发时机是 **loop 收尾时**(不在执行段当轮触发)—— 判据是本 loop 调过
|
||||
* logic_complete 且整个 loop 的 accumulated 非空;技能正文闸(正文在上下文里)
|
||||
* 仍在执行段判,不满足则中止兑现、不触发本回调。
|
||||
* ⚠️ 幂等由调用方保证(store 里保存流程状态已非 idle ⇒ 不重改)。
|
||||
* 调用方在 ChatView 里提供:`() => chatStore.markLogicComplete()`。
|
||||
* 改造-05/D5:纯信号,无参数 —— 保存落点由 handleSaveStrategy 执行时按当前选择判定。
|
||||
@@ -235,7 +246,7 @@ export interface AgentLoopResult {
|
||||
ledger: OpenAIMessage[]
|
||||
/**
|
||||
* 本次 loop 的完成声明所依据的技能名(logic_complete 的 skill_name)。
|
||||
* 仅当完成声明在执行段被兑现(本轮 content 非空、正文在上下文里、
|
||||
* 仅当完成声明在执行段被兑现(accumulated 非空、正文在上下文里、
|
||||
* 摘除 tool_call 并中止)时非空;出错 / 撞上限一律 null。
|
||||
* 调用方(ChatView)把它写进会话(`logicSkillName`,瞬态不落盘)——
|
||||
* 保存流程取它对应的正文,保存按钮显隐也用它。
|
||||
@@ -284,11 +295,13 @@ function buildLoadSkillTool(): ToolDefinition {
|
||||
* **本工具不保存任何东西** —— 落盘只发生在用户点击按钮之后。
|
||||
*
|
||||
* ── 中止语义已恢复 ────────────────────────────────────────────────────
|
||||
* 判据只有一条:**本轮 result.content 非空**(不看 accumulated —— 它含前几轮
|
||||
* 的寒暄/开场白,用它判「之前说过逻辑」不可靠)。
|
||||
* - content 非空 ⇒ 合规:摘掉该 tool_call、不填 tool 消息、`stopReason='model'`、
|
||||
* 跳出循环、不再发请求;`onLogicComplete` 在执行段兑现时触发。
|
||||
* - content 为空 ⇒ 不合规:回纠错文案「不许单独调 logic_complete」、继续 loop
|
||||
* content 闸判据:**accumulated 非空**(本 loop 内各轮 result.content 累加,
|
||||
* loop 局部、不含跨 loop 寒暄 —— 它是 runAgentLoop 的局部变量,每次进入重置,
|
||||
* 只含本次 loop 的 assistant content,可靠)。
|
||||
* - accumulated 非空 ⇒ 逻辑已输出(本次 loop 任意一轮都算,不限当轮):
|
||||
* 摘掉该 tool_call、不填 tool 消息、`stopReason='model'`、跳出循环、
|
||||
* 不再发请求;`onLogicComplete` 统一在 loop 收尾触发。
|
||||
* - accumulated 为空 ⇒ 不合规:回纠错文案「不许单独调 logic_complete」、继续 loop
|
||||
* (走既有纠错计次)。
|
||||
* ⚠️ 已知取舍(有意为之,别当 bug 修):用户说「对」之后模型只发工具的场合,
|
||||
* 会被退回、下一轮把逻辑再输出一遍 ⇒ 用户看到一次重复。用一次重复换零丢失。
|
||||
@@ -316,14 +329,12 @@ function buildLogicCompleteTool(): ToolDefinition {
|
||||
function: {
|
||||
name: 'logic_complete',
|
||||
description:
|
||||
'声明「本条策略逻辑已完整,可以交付」。必须带 skill_name:本次完整逻辑所依据的策略技能英文名。' +
|
||||
'调用方式:**本工具不得单独调用** —— 必须在同一条回复里既输出完整逻辑,又调用本工具;' +
|
||||
// '只调用本工具、或把它放在另一条回复里,都会被退回重来。\n' +
|
||||
'声明「本条策略逻辑已完整」。' +
|
||||
'调用方式:必须带 skill_name:本次完整逻辑所依据的策略技能英文名。' +
|
||||
'调用时机:\n' +
|
||||
'- 只要输出的策略逻辑已满足「生成/改写任务流程」的 4 个完整判断条件;\n' +
|
||||
'- 用户提了变更需求,你已按需求给出新的完整逻辑。\n' +
|
||||
// '完整性由你按上述 4 个条件判断,不由用户的话判断。\n' +
|
||||
'下列情况不要调用:还在追问信息 / 逻辑还有空缺 / 用户在提问而不是在定方案 / 本次任务是「解释」。',
|
||||
'- 只要生成/改写任务的策略逻辑已满足「生成/改写任务流程」的 4 个完整判断条件;\n' +
|
||||
'- 完整逻辑已输出,或用户提了变更需求,你已按需求给出新的完整逻辑;\n' +
|
||||
'下列情况不要调用:尚未加载所需技能 / 还在追问信息 / 逻辑还有空缺 / 本次任务是「解释」。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -534,6 +545,191 @@ export function collectLoadedSkillsFromHistory(history: OpenAIMessage[]): { skil
|
||||
return { skills: loaded }
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `get_policy` 的工具结果:成功时是 `StrategyInstance[]` 的 JSON 文本。
|
||||
* 空结果 / 纠错文案 / 坏 JSON ⇒ null(不当已加载记录)。
|
||||
*/
|
||||
function parsePolicyResult(content: string): unknown[] | null {
|
||||
if (!content.trim() || content.startsWith(TOOL_CORRECTION_PREFIX)) return null
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(content)
|
||||
return Array.isArray(parsed) ? parsed : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实例的唯一键:`分组 + id`。
|
||||
* ⚠️ id 只在分组内唯一(同一 id 可同时存在于「常规注码」与「常规打法」)——
|
||||
* 与 `ChatSession.selectedStrategyKind` 的配对口径一致。
|
||||
*/
|
||||
function policyInstanceKey(category: string, item: unknown): string | null {
|
||||
if (typeof item !== 'object' || item === null) return null
|
||||
const id = (item as Record<string, unknown>).id
|
||||
if (typeof id !== 'number' || !Number.isFinite(id)) return null
|
||||
return `${category}\u0000${id}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 从历史账本里恢复「已成功取过的策略实例」:`分组 + id` 的集合。
|
||||
*
|
||||
* 只读 `get_policy` 的调用参数(category)与工具结果里的 `id`,不碰 `data` 内部。
|
||||
* 结果不是合法 JSON 数组(未命中文案 / 纠错回灌 / 坏数据)⇒ 跳过。
|
||||
*/
|
||||
function collectLoadedPoliciesFromHistory(history: OpenAIMessage[]): Set<string> {
|
||||
const callCategory = new Map<string, string>()
|
||||
for (const message of history) {
|
||||
if (message.role !== 'assistant' || !message.tool_calls) continue
|
||||
for (const call of message.tool_calls) {
|
||||
if (call.function.name !== 'get_policy') continue
|
||||
let args: Record<string, unknown>
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(call.function.arguments)
|
||||
if (typeof parsed !== 'object' || parsed === null) continue
|
||||
args = parsed as Record<string, unknown>
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const category = extractNonEmptyString(args, 'category')
|
||||
if (!category) continue
|
||||
callCategory.set(call.id, category)
|
||||
}
|
||||
}
|
||||
|
||||
const loaded = new Set<string>()
|
||||
for (const message of history) {
|
||||
if (message.role !== 'tool' || !message.tool_call_id) continue
|
||||
const category = callCategory.get(message.tool_call_id)
|
||||
if (!category) continue
|
||||
const results = parsePolicyResult(message.content)
|
||||
if (!results) continue
|
||||
for (const item of results) {
|
||||
const key = policyInstanceKey(category, item)
|
||||
if (key) loaded.add(key)
|
||||
}
|
||||
}
|
||||
return loaded
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除纠错回灌消息(`TOOL_CORRECTION_PREFIX` 开头)及其工具调用对。
|
||||
*
|
||||
* 纠错消息只在**本次 loop 内**对模型有意义(让它同轮纠正)。跨 loop 再带上它
|
||||
* 没有价值,反而会把「技能加载失败」「参数不合法」这些过期失败写进下一轮提示词。
|
||||
* ⇒ loop 出口 / 入口各清一次(见 runAgentLoop)。
|
||||
*
|
||||
* ⚠️ 只删「整条 tool 消息以该前缀开头」的 —— 技能正文 / 实例 json 不会长这样。
|
||||
*/
|
||||
function stripToolCorrections(messages: OpenAIMessage[]): OpenAIMessage[] {
|
||||
const correctionIds = new Set<string>()
|
||||
for (const m of messages) {
|
||||
if (m.role !== 'tool' || !m.tool_call_id) continue
|
||||
if (m.content.startsWith(TOOL_CORRECTION_PREFIX)) correctionIds.add(m.tool_call_id)
|
||||
}
|
||||
return removeToolCallIds(messages, correctionIds)
|
||||
}
|
||||
|
||||
/**
|
||||
* 历史压缩:同一策略实例只留**最新一份**,其余副本就地裁掉。
|
||||
*
|
||||
* 为什么要压:`get_policy` 的 name 是子串匹配,模型换一种问法再查会真的取到
|
||||
* 「部分命中」的结果 —— 同一实例可能在账本里出现多次。冗余既费 token,
|
||||
* 也会让 `collectLoadedPoliciesFromHistory` 的口径与模型看到的历史不一致。
|
||||
*
|
||||
* 为什么**不管技能**:重复 `load_skill` 在执行前就被校验段拦下
|
||||
* (`inContext` / `plannedSkillNames`,回纠错并计次),账本里不会产生第二份
|
||||
* 成功正文;失败回灌由 `stripToolCorrections` 清。再压一遍是死代码。
|
||||
*
|
||||
* 规则(只针对 get_policy):
|
||||
* - 以每条成功 get_policy 结果里的 id 为准(键 = category + id),
|
||||
* 只保留该实例**最后一次出现**的那条 tool 结果;更早的结果里**只删重复实例**,
|
||||
* 保留该结果里的其它实例 —— 否则那些实例会从历史消失。
|
||||
* - 裁空 ⇒ 删该 tool 消息与对应调用。
|
||||
* - 失败结果(纠错前缀 / 未命中文案 / 坏 JSON / 空串)不参与「成功副本」判定。
|
||||
* - 技能不在这里:重复 load_skill 由执行前校验段拦下,账本里不会有第二份;
|
||||
* 截断时另有豁免(`ChatView.vue` 的 `LOOP_HISTORY_TRUNCATE_OPTIONS`),
|
||||
* 旧正文不会被整轮丢掉。
|
||||
*
|
||||
* 配对清理复用 `removeToolCallIds`(不留孤儿 tool_calls)。
|
||||
* 纯函数:不改入参数组;无可删 / 可改时可返回原数组引用。
|
||||
*/
|
||||
function compactPolicyHistory(messages: OpenAIMessage[]): OpenAIMessage[] {
|
||||
const callCategory = new Map<string, string>()
|
||||
|
||||
for (const m of messages) {
|
||||
if (m.role !== 'assistant' || !m.tool_calls) continue
|
||||
for (const call of m.tool_calls) {
|
||||
if (call.function.name !== 'get_policy') continue
|
||||
let args: Record<string, unknown>
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(call.function.arguments)
|
||||
if (typeof parsed !== 'object' || parsed === null) continue
|
||||
args = parsed as Record<string, unknown>
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const category = extractNonEmptyString(args, 'category')
|
||||
if (category) callCategory.set(call.id, category)
|
||||
}
|
||||
}
|
||||
|
||||
// 第一遍:记录每个实例最后一次出现的 tool 消息下标。
|
||||
const lastPolicyIndex = new Map<string, number>()
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const m = messages[i]
|
||||
if (m.role !== 'tool' || !m.tool_call_id) continue
|
||||
const category = callCategory.get(m.tool_call_id)
|
||||
if (!category) continue
|
||||
const results = parsePolicyResult(m.content)
|
||||
if (!results) continue
|
||||
for (const item of results) {
|
||||
const key = policyInstanceKey(category, item)
|
||||
if (key) lastPolicyIndex.set(key, i)
|
||||
}
|
||||
}
|
||||
|
||||
// 第二遍:算要删的调用 + 要重写的 tool 结果(只裁掉被更新的实例)。
|
||||
const removed = new Set<string>()
|
||||
const rewritten = new Map<number, string>()
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const m = messages[i]
|
||||
if (m.role !== 'tool' || !m.tool_call_id) continue
|
||||
const category = callCategory.get(m.tool_call_id)
|
||||
if (!category) continue
|
||||
const results = parsePolicyResult(m.content)
|
||||
if (!results) continue
|
||||
const kept: unknown[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of results) {
|
||||
const key = policyInstanceKey(category, item)
|
||||
if (!key) {
|
||||
kept.push(item)
|
||||
continue
|
||||
}
|
||||
// 只在「最后一次出现」的那条留下;同一条里重复出现也只留一份。
|
||||
if (lastPolicyIndex.get(key) !== i || seen.has(key)) continue
|
||||
seen.add(key)
|
||||
kept.push(item)
|
||||
}
|
||||
if (kept.length === 0) {
|
||||
removed.add(m.tool_call_id)
|
||||
} else if (kept.length !== results.length) {
|
||||
rewritten.set(i, JSON.stringify(kept, null, 2))
|
||||
}
|
||||
}
|
||||
|
||||
if (removed.size === 0 && rewritten.size === 0) return messages
|
||||
|
||||
const normalized = rewritten.size === 0
|
||||
? messages
|
||||
: messages.map((m, i) => {
|
||||
const content = rewritten.get(i)
|
||||
return content === undefined ? m : { ...m, content }
|
||||
})
|
||||
return removeToolCallIds(normalized, removed)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按技能主体切 history:只保留「最后一次成功 load_skill(skillName)」那一轮及之后的消息。
|
||||
*
|
||||
@@ -641,33 +837,35 @@ export function sliceHistoryForSkill(history: OpenAIMessage[], skillName: string
|
||||
*
|
||||
* ⚠️ 剥空后不写 `tool_calls: []` —— 部分网关会把空数组当 400 处理(与「中止语义」节既有约定一致)。
|
||||
*/
|
||||
function stripLogicCompleteTrace(messages: OpenAIMessage[]): OpenAIMessage[] {
|
||||
const logicCompleteIds = new Set<string>()
|
||||
for (const m of messages) {
|
||||
if (m.role === 'assistant' && Array.isArray(m.tool_calls)) {
|
||||
for (const call of m.tool_calls) {
|
||||
if (call.function?.name === 'logic_complete') {
|
||||
logicCompleteIds.add(call.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (logicCompleteIds.size === 0) return messages
|
||||
|
||||
/**
|
||||
* 从消息序列里删掉指定的工具调用对:对应的 tool 消息 + assistant 消息里该调用项。
|
||||
*
|
||||
* 配对清理规则(多条清理共用,行为必须一致):
|
||||
* - `role === 'tool'` 且 `tool_call_id ∈ removed` ⇒ 整条丢弃;
|
||||
* - `role === 'assistant'` 且带 `tool_calls` ⇒ 剥掉命中项;
|
||||
* · 剥完为空 且 content 为空/纯空白 ⇒ 整条丢弃;
|
||||
* · 剥完为空 但有 content ⇒ 不写 tool_calls 键(不能留 []);
|
||||
* · 部分剥 ⇒ 写入剩余条目;
|
||||
* - 其余消息原样保留。
|
||||
*
|
||||
* ⚠️ 不留 `tool_calls: []` —— 部分网关会把空数组当 400。
|
||||
*/
|
||||
function removeToolCallIds(messages: OpenAIMessage[], removed: Set<string>): OpenAIMessage[] {
|
||||
if (removed.size === 0) return messages
|
||||
const out: OpenAIMessage[] = []
|
||||
for (const m of messages) {
|
||||
if (m.role === 'tool' && m.tool_call_id && logicCompleteIds.has(m.tool_call_id)) {
|
||||
if (m.role === 'tool' && m.tool_call_id && removed.has(m.tool_call_id)) {
|
||||
continue
|
||||
}
|
||||
if (m.role === 'assistant' && Array.isArray(m.tool_calls)) {
|
||||
const remaining = m.tool_calls.filter((c) => !logicCompleteIds.has(c.id))
|
||||
const remaining = m.tool_calls.filter((c) => !removed.has(c.id))
|
||||
const hasContent = Boolean(m.content && m.content.trim())
|
||||
if (remaining.length === 0 && !hasContent) {
|
||||
continue
|
||||
}
|
||||
if (remaining.length === 0) {
|
||||
// 剥空但 content 非空:必须把 tool_calls 键整个去掉 ——
|
||||
// 不能留 [](部分网关当 400),也不能留原数组(logic_complete 痕迹还在)。
|
||||
// 不能留 [](部分网关当 400),也不能留原数组(被删的调用痕迹还在)。
|
||||
const { tool_calls: _stripped, ...rest } = m
|
||||
out.push({ ...rest, content: m.content ?? '' })
|
||||
continue
|
||||
@@ -682,6 +880,20 @@ function stripLogicCompleteTrace(messages: OpenAIMessage[]): OpenAIMessage[] {
|
||||
return out
|
||||
}
|
||||
|
||||
function stripLogicCompleteTrace(messages: OpenAIMessage[]): OpenAIMessage[] {
|
||||
const logicCompleteIds = new Set<string>()
|
||||
for (const m of messages) {
|
||||
if (m.role === 'assistant' && Array.isArray(m.tool_calls)) {
|
||||
for (const call of m.tool_calls) {
|
||||
if (call.function?.name === 'logic_complete') {
|
||||
logicCompleteIds.add(call.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return removeToolCallIds(messages, logicCompleteIds)
|
||||
}
|
||||
|
||||
/** 把错误译成 loop 的失败说明(保留已累计的文字)。 */
|
||||
function describeLoopError(error: unknown): string {
|
||||
if (error instanceof ChatTransportError) {
|
||||
@@ -1094,7 +1306,13 @@ type ValidatedCall =
|
||||
* 已产出的文字要保留给 UI。
|
||||
*/
|
||||
export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopResult> {
|
||||
const { config, systemPrompt, history, userMessage, strategiesByCategory, signal, onDelta, onToolEvent, onLogicComplete, onSkillBound } = params
|
||||
const { config, systemPrompt, userMessage, strategiesByCategory, signal, onDelta, onToolEvent, onLogicComplete, onSkillBound } = params
|
||||
|
||||
// 入参 history 先清洗(顺序固定):
|
||||
// ① stripToolCorrections —— 跨 loop 不保留任何纠错回灌(本次 loop 产生的另行在出口清);
|
||||
// ② compactPolicyHistory —— 同一策略实例只留一份(技能重复在校验段拦下,不压)。
|
||||
// 下面组 messages / ledger / inContext / loadedPolicies 全用清洗后的 history。
|
||||
const history = compactPolicyHistory(stripToolCorrections(params.history))
|
||||
|
||||
// Step 0 —— 降级判定:清单取不到(或取到空白)⇒ 不挂任何工具,模型只靠 system 提示作答
|
||||
// ⚠️ 每轮现取、不缓存(口径见文件头)。取不到 ⇒ null ⇒ 降级,**不抛** ——
|
||||
@@ -1117,11 +1335,12 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// Step 1/2 —— 拼 system 消息 + 组装 messages
|
||||
const systemMessage = buildSystemMessage(systemPrompt, glossaryText, skillList, degraded)
|
||||
const userMsg: OpenAIMessage = { role: 'user', content: userMessage }
|
||||
const messages: OpenAIMessage[] = systemMessage ? [systemMessage, ...history, userMsg] : [...history, userMsg]
|
||||
let messages: OpenAIMessage[] = systemMessage ? [systemMessage, ...history, userMsg] : [...history, userMsg]
|
||||
// 账本 = 本次调用用过的完整序列(**不含 system**),与 messages 平行的另一份:
|
||||
// messages 带 system、是发给网关的;账本由调用方存内存、下次当 history 传回。
|
||||
// ⚠️ messages 数组本身不动(它带 system),账本是独立的一份。
|
||||
const ledger: OpenAIMessage[] = [...history, userMsg]
|
||||
// ⚠️ 两者都会在每轮回填后经 compactPolicyHistory 压缩(见循环内),故用 let。
|
||||
let ledger: OpenAIMessage[] = [...history, userMsg]
|
||||
|
||||
let accumulated = ''
|
||||
// 循环自然耗尽 = 撞上限;下面各成功/中断路径会覆盖它
|
||||
@@ -1140,16 +1359,22 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// IPC 只在缓存未命中时发生。它**不**参与「是否已注入」的判定。
|
||||
const recovered = collectLoadedSkillsFromHistory(history)
|
||||
const inContext = new Map(recovered.skills)
|
||||
// get_policy 的「已加载实例」(category + id 键):从清洗后的账本恢复。
|
||||
// 校验段据此判重复获取(见下);执行段每取到一批新实例就登记。
|
||||
const loadedPolicies = collectLoadedPoliciesFromHistory(history)
|
||||
|
||||
// 纠错回灌计次(未知工具名 / 坏参数 / 技能加载失败):模型在 loop 内自我纠正的轮数。
|
||||
// 纠错回灌计次(未知工具名 / 坏参数 / 技能加载失败 / 重复取数):模型在 loop 内自我纠正的轮数。
|
||||
// ⚠️ 与 MAX_AGENT_ROUNDS 分开计 —— 纠错作废的是「当前这次请求」,
|
||||
// 但要单独封顶,否则坏上游能把每一轮都烧成纠错。
|
||||
let correctionRounds = 0
|
||||
|
||||
// logic_complete 的兑现标志:**本轮 content 非空**时在执行段兑现并中止 ——
|
||||
// 摘 tool_call、不填 tool 消息、onLogicComplete 在执行段触发(不是收尾)、
|
||||
// 跳出轮次循环、不再发请求。content 为空 ⇒ 纠错回灌、继续 loop(见校验段闸门 A)。
|
||||
// logic_complete 的兑现标志:执行段兑现(accumulated 非空 + 正文在上下文)时置位并中止 ——
|
||||
// 摘 tool_call、不填 tool 消息、跳出轮次循环、不再发请求。
|
||||
// onLogicComplete 不在这里触发,统一在 loop 收尾触发(见 Step 4/5)。
|
||||
let logicCompleteRequested = false
|
||||
// logic_complete 是否在本 loop 被调过(只记有无,不管次数、不管当轮 content 空不空)。
|
||||
// 收尾时据此 + accumulated 非空 ⇒ 触发 onLogicComplete。
|
||||
let logicCompleteCalled = false
|
||||
// 本次 loop 内被兑现的完成声明所依据的技能名(logic_complete 的 skill_name)。
|
||||
// 只在兑现路径被赋值 —— 兑现即中止,不存在「重复调用以最后一次为准」;
|
||||
// 收尾时随返回值带出(stopReason === 'model' 时)。
|
||||
@@ -1164,7 +1389,7 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
content: accumulated,
|
||||
stopReason: 'error',
|
||||
error,
|
||||
ledger: stripLogicCompleteTrace(ledger),
|
||||
ledger: stripLogicCompleteTrace(compactPolicyHistory(stripToolCorrections(ledger))),
|
||||
logicSkillName: null,
|
||||
})
|
||||
|
||||
@@ -1247,6 +1472,10 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// 名字错了到执行段由 bridge 抛错 ⇒ 同样走纠错回灌。
|
||||
const validatedCalls: ValidatedCall[] = []
|
||||
const corrections: Array<{ call: ToolCall; reason: string }> = []
|
||||
// 本轮已接受的新取数:inContext / loadedPolicies 只在执行段更新,
|
||||
// 同一轮里第二条同名 / 同实例调用要靠这两个集合判重复。
|
||||
const plannedSkillNames = new Set<string>()
|
||||
const plannedPolicyKeys = new Set<string>()
|
||||
for (const call of result.toolCalls) {
|
||||
// 1. 工具名白名单(模型工具面就这三个;空名已被上方的静默重试拦掉)
|
||||
if (call.function.name !== 'load_skill' && call.function.name !== 'logic_complete' && call.function.name !== 'get_policy') {
|
||||
@@ -1282,18 +1511,34 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
})
|
||||
continue
|
||||
}
|
||||
validatedCalls.push({ kind: 'load', call, skillName })
|
||||
} else if (call.function.name === 'logic_complete') {
|
||||
// 闸门 A:不得单独调用 —— 本轮回复必须有 content(逻辑就写在这条回复里)。
|
||||
// ⚠️ 只看 result.content,不看 accumulated:accumulated 含前几轮的寒暄/开场白,
|
||||
// 用它判「之前说过逻辑」不可靠(用户明确否掉这条思路)。
|
||||
// ⚠️ content 闸门优先于 skill_name 校验:单独调用时先纠正「不许单独调」,
|
||||
// 比报缺参更有指导性。
|
||||
if (!result.content.trim()) {
|
||||
logLoopIssue('logic_complete 单独调用(本轮无 content)', { arguments: call.function.arguments.slice(0, 200) })
|
||||
// 已加载 ⇒ 不得重复获取(模型会无视提示词里的「不得重复调用」再取一遍)。
|
||||
// 判据与执行段同口径:正文已在本次请求上下文里(inContext 从账本恢复 +
|
||||
// 本 loop 已取);plannedSkillNames 管同一轮的重复调用。
|
||||
if (inContext.has(skillName) || plannedSkillNames.has(skillName)) {
|
||||
logLoopIssue('load_skill 重复加载', { skillName, arguments: call.function.arguments.slice(0, 200) })
|
||||
corrections.push({
|
||||
call,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}logic_complete 不能单独调用。请在**这一次回复**里既完整输出本条策略逻辑(规则、路径、下注、走向),又调用本工具;单独调用本工具会被退回。`,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}技能「${skillName}」已加载,不得重复获取。请直接使用可见对话历史里已取到的技能正文。`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
plannedSkillNames.add(skillName)
|
||||
validatedCalls.push({ kind: 'load', call, skillName })
|
||||
} else if (call.function.name === 'logic_complete') {
|
||||
// 本 loop 调过即记下(不管次数、不管 content 空不空)—— 收尾触发 onLogicComplete 用。
|
||||
logicCompleteCalled = true
|
||||
// 闸门 A:不得单独调用 —— 逻辑必须在本次 loop 里输出过(accumulated 非空)。
|
||||
// ⚠️ 判据用 accumulated(本 loop 内各轮 result.content 累加,loop 局部、
|
||||
// 不含跨 loop 寒暄):它是 runAgentLoop 的局部变量,每次进入重置,
|
||||
// 只含本次 loop 的 assistant content,可靠。本轮 result.content 为空
|
||||
// 但前几轮已输出过逻辑 ⇒ 同样放行(逻辑在任意一轮输出即可,不限当轮)。
|
||||
// ⚠️ content 闸门优先于 skill_name 校验:单独调用时先纠正「不许单独调」,
|
||||
// 比报缺参更有指导性。
|
||||
if (!accumulated.trim()) {
|
||||
logLoopIssue('logic_complete 单独调用(本 loop 无逻辑输出)', { arguments: call.function.arguments.slice(0, 200) })
|
||||
corrections.push({
|
||||
call,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}logic_complete 不能单独调用。请先完整输出本条策略逻辑(规则、路径、下注、走向),再调用本工具;单独调用本工具会被退回。`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -1347,6 +1592,28 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
})
|
||||
continue
|
||||
}
|
||||
// 已加载 ⇒ 不得重复获取(方案 A):本次命中的实例**全部**已在历史 / 本轮
|
||||
// 取过 ⇒ 回纠错;只要有一条是新实例 ⇒ 放行、回填全量结果
|
||||
// (旧副本由 compactPolicyHistory 裁掉,历史里仍只留一份)。
|
||||
const bucket = (strategiesByCategory ?? {})[category] ?? []
|
||||
const results = getPolicy(bucket, name, id)
|
||||
if (results.length > 0) {
|
||||
const keys = results.map((item) => policyInstanceKey(category, item))
|
||||
const allLoaded = keys.every(
|
||||
(key) => key !== null && (loadedPolicies.has(key) || plannedPolicyKeys.has(key)),
|
||||
)
|
||||
if (allLoaded) {
|
||||
logLoopIssue('get_policy 重复获取', { category, id, name })
|
||||
corrections.push({
|
||||
call,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}实例已加载,不得重复获取。请直接使用可见对话历史里已取到的实例 json。`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
for (const key of keys) {
|
||||
if (key) plannedPolicyKeys.add(key)
|
||||
}
|
||||
}
|
||||
validatedCalls.push({ kind: 'query', call, category, id, name })
|
||||
}
|
||||
}
|
||||
@@ -1367,33 +1634,33 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// 拿不到规则却让模型硬答 = 静默错误(术语表硬答策略的实证,02 §13),但阻断更糟
|
||||
// —— 用户被迫重发。纠错计次封顶兜底。
|
||||
const toolResults = new Map<string, string>()
|
||||
// 中止标志:logic_complete 兑现(本轮 content 非空 + 正文在上下文)⇒ 置位。
|
||||
// 中止标志:logic_complete 兑现(accumulated 非空 + 正文在上下文)⇒ 置位。
|
||||
// 执行循环跳出后据此结束本轮轮次 —— 回填剩余结果、break 外层轮次循环、不再发请求。
|
||||
let aborted = false
|
||||
for (const item of validatedCalls) {
|
||||
if (item.kind === 'load') {
|
||||
onToolEvent?.({ name: 'load_skill', kind: 'load', skillName: item.skillName, status: 'loading' })
|
||||
|
||||
// 去重:同名技能已有成功记录(账本恢复 + 本 loop 内)⇒ 本地回填,不再调 native。
|
||||
let text = inContext.get(item.skillName)
|
||||
if (text === undefined) {
|
||||
try {
|
||||
// ⚠️ bridge 认不出技能名时在这里抛错(dev 是 browser 桩,生产是 native)——
|
||||
// 错误原因进日志,纠错文案只给模型看。
|
||||
text = await fetchSkillBody(item.skillName)
|
||||
} catch (error: unknown) {
|
||||
const reason = error instanceof Error && error.message ? error.message : '未知原因'
|
||||
logLoopIssue('load_skill 失败', { skillName: item.skillName, reason })
|
||||
// failed 事件不带错误文案(tool-event 只在 dev 渲染,且不外泄原因)
|
||||
onToolEvent?.({ name: 'load_skill', kind: 'load', skillName: item.skillName, status: 'failed' })
|
||||
corrections.push({
|
||||
call: item.call,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}加载技能「${item.skillName}」失败:${reason}。请检查技能的英文名,原样照抄技能清单「英文名」一栏后重新调用 load_skill。`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
inContext.set(item.skillName, text)
|
||||
// 校验段已拦掉重复加载(inContext / plannedSkillNames)⇒ 这里必然是新技能,直接取正文。
|
||||
// ⚠️ 取数仍经 fetchSkillBody(命中 skillBodyCache 时不走 IPC);
|
||||
// inContext 只管「正文是否已在本次请求上下文里」——校验段判重用它。
|
||||
let text: string
|
||||
try {
|
||||
// ⚠️ bridge 认不出技能名时在这里抛错(dev 是 browser 桩,生产是 native)——
|
||||
// 错误原因进日志,纠错文案只给模型看。
|
||||
text = await fetchSkillBody(item.skillName)
|
||||
} catch (error: unknown) {
|
||||
const reason = error instanceof Error && error.message ? error.message : '未知原因'
|
||||
logLoopIssue('load_skill 失败', { skillName: item.skillName, reason })
|
||||
// failed 事件不带错误文案(tool-event 只在 dev 渲染,且不外泄原因)
|
||||
onToolEvent?.({ name: 'load_skill', kind: 'load', skillName: item.skillName, status: 'failed' })
|
||||
corrections.push({
|
||||
call: item.call,
|
||||
reason: `${TOOL_CORRECTION_PREFIX}加载技能「${item.skillName}」失败:${reason}。请检查技能的英文名,原样照抄技能清单「英文名」一栏后重新调用 load_skill。`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
inContext.set(item.skillName, text)
|
||||
|
||||
// R2:模型加载了与已提交技能**不同**的技能 ⇒ 回调(调用方收回保存按钮)。
|
||||
// 判据用 committedInLoop(本 loop 已兑现的声明)兜 params.logicSkillName
|
||||
@@ -1410,8 +1677,8 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
}
|
||||
|
||||
// ── logic_complete ────────────────────────────────────────────────────
|
||||
// 完成声明(带 skill_name):校验段闸门 A 已保证本轮 content 非空(逻辑就写在
|
||||
// 这条回复里)。兑现 ⇒ 直接中止:摘 tool_call、不填 tool 消息、不再发请求。
|
||||
// 完成声明(带 skill_name):校验段闸门 A 已保证 accumulated 非空(逻辑已在
|
||||
// 本次 loop 输出过)。兑现 ⇒ 直接中止:摘 tool_call、不填 tool 消息、不再发请求。
|
||||
// 幂等:调用方(ChatView)的 store 里保存流程状态已非 idle ⇒ 不重改。
|
||||
// ⚠️ 本工具不保存任何东西 —— 落盘由用户点保存按钮触发(见 ChatView.handleSaveStrategy)。
|
||||
if (item.kind === 'complete') {
|
||||
@@ -1427,7 +1694,7 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// ⇒ 并且要求模型先按「逻辑完整」的 4 个判断条件重新核实逻辑完整性 ——
|
||||
// 名字错往往伴随它压根没读过该类技能正文,逻辑本身多半也不完整。
|
||||
// ⇒ 不满足就把原因作为工具结果回给模型,引导它核实后先调 load_skill 再重调。
|
||||
// ⚠️ 此时 content 非空 —— 本轮逻辑已输出,但技能正文没进上下文,仍不应交付:
|
||||
// ⚠️ 此时 accumulated 非空 —— 逻辑已输出,但技能正文没进上下文,仍不应交付:
|
||||
// 不兑现、不中止(与纠错路径一致),回填后继续下一轮。
|
||||
// ⚠️ 文案只描述「缺什么、补什么」,**绝不出现保存 / 按钮** ——
|
||||
// 模型读到就会重新产生「要提示用户按按钮」的意识(话权已收归 app)。
|
||||
@@ -1463,9 +1730,9 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// 合规:兑现 + 中止。摘掉该 tool_call(悬空 tool_call 会让下一轮请求 400)、
|
||||
// 不为它填 tool 消息 —— 本轮回复里已带完整逻辑,账本收进这条 assistant 即可。
|
||||
// ⚠️ logicCompleteRequested 现在的语义是「本轮已兑现并中止」的标志。
|
||||
// ⚠️ onLogicComplete 不在这里触发 —— 统一在 loop 收尾触发(见 Step 4/5)。
|
||||
logicCompleteRequested = true
|
||||
committedInLoop = effectiveSkillName
|
||||
onLogicComplete?.()
|
||||
const idx = result.toolCalls.indexOf(item.call)
|
||||
if (idx >= 0) result.toolCalls.splice(idx, 1)
|
||||
stopReason = 'model'
|
||||
@@ -1480,6 +1747,11 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
onToolEvent?.({ name: 'get_policy', kind: 'query', status: 'loading' })
|
||||
const bucket = (strategiesByCategory ?? {})[item.category] ?? []
|
||||
const results = getPolicy(bucket, item.name, item.id)
|
||||
// 登记已加载实例:下一轮的重复获取判定用它(plannedPolicyKeys 只在本轮有效)
|
||||
for (const result of results) {
|
||||
const key = policyInstanceKey(item.category, result)
|
||||
if (key) loadedPolicies.add(key)
|
||||
}
|
||||
const resultText = results.length
|
||||
? JSON.stringify(results, null, 2)
|
||||
: `没有「${item.name ?? `id=${item.id}`}」的「${item.category}」策略`
|
||||
@@ -1495,7 +1767,7 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
// 账本同步 push 同样两条(顺序一致)—— tool 消息靠它跨轮存活。
|
||||
// ⚠️ 校验 / 执行失败的调用也回填(纠错文案),与成功结果同组 ——
|
||||
// assistant 里列了却没回 tool 消息 = 孤儿 tool_calls ⇒ 网关 400。
|
||||
// ⚠️ logic_complete 在本轮 content 非空时被摘除并中止:它已不在 result.toolCalls 里,
|
||||
// ⚠️ logic_complete 在 accumulated 非空时被摘除并中止:它已不在 result.toolCalls 里,
|
||||
// 下面的循环天然不会为它回填 tool 消息(中止路径也走这里 —— 本轮 assistant
|
||||
// 带着完整逻辑,必须收进账本,下一轮对话与保存流程都靠它)。
|
||||
// 同轮其余调用(load_skill / get_policy)照常回填,不留孤儿。
|
||||
@@ -1522,6 +1794,12 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
ledger.push(toolMessage)
|
||||
}
|
||||
|
||||
// 历史压缩:同一技能 / 同一实例只留最新一份。
|
||||
// 本轮刚回填的结果算最新 ⇒ 旧副本被它取代(例:部分命中时新结果已含旧实例,
|
||||
// 早期那条 get_policy 结果里的同一实例被裁掉)。messages 与 ledger 并行处理。
|
||||
messages = compactPolicyHistory(messages)
|
||||
ledger = compactPolicyHistory(ledger)
|
||||
|
||||
// 工具结果已回填,进入下一轮,让模型接着说
|
||||
|
||||
// 中止路径:完成声明已兑现(摘 tool_call、不填它的 tool 消息、按钮已出),
|
||||
@@ -1542,15 +1820,21 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
|
||||
ledger.push({ role: 'assistant', content: lastRoundContent })
|
||||
}
|
||||
|
||||
// 完成声明的兑现(含 onLogicComplete 触发)已在执行段完成 —— 兑现即中止,
|
||||
// 走不到这里的「正常收尾」;这里不再有第二次触发。
|
||||
// 出错 / max-rounds 收场 ⇒ 没有兑现,不出按钮、不带技能名。
|
||||
// onLogicComplete 统一在 loop 收尾触发(不在执行段当轮触发):
|
||||
// 本 loop 调过 logic_complete 且整个 loop 的 accumulated 非空 ⇒ 触发。
|
||||
// 幂等由调用方保证(ChatView store 保存流程状态已非 idle ⇒ 不重改)。
|
||||
// ⚠️ max-rounds 收场也会走到这里 —— 模型撞轮上限前调过 logic_complete 且
|
||||
// accumulated 非空时触发是合理的(逻辑确实输出过)。
|
||||
// 出错路径(stopReason === 'error')都在循环内提前 return,走不到这里。
|
||||
if (logicCompleteCalled && accumulated.trim()) {
|
||||
onLogicComplete?.()
|
||||
}
|
||||
|
||||
return {
|
||||
content: accumulated,
|
||||
stopReason,
|
||||
...(stopReason === 'max-rounds' ? { error: `已达到最大轮数(${MAX_AGENT_ROUNDS})` } : {}),
|
||||
ledger: stripLogicCompleteTrace(ledger),
|
||||
ledger: stripLogicCompleteTrace(compactPolicyHistory(stripToolCorrections(ledger))),
|
||||
// 兑现即中止(stopReason === 'model' 且 committedInLoop 已赋值)才带出技能名;
|
||||
// committedInLoop 只在兑现路径被赋值,非中止路径恒为 null
|
||||
logicSkillName: stopReason === 'model' ? committedInLoop : null,
|
||||
|
||||
+39
-5
@@ -59,6 +59,16 @@ function sortSessionsByUpdatedAt(sessions: ChatSession[]): ChatSession[] {
|
||||
return [...sessions].sort((first, second) => second.updatedAt - first.updatedAt)
|
||||
}
|
||||
|
||||
/**
|
||||
* 重算会话标题(第一条 user 消息;没有则「新对话」)。
|
||||
* 删除消息 / 把消息插回会话都可能改变第一条 user ⇒ 标题要跟着重算,
|
||||
* removeMessages 与 insertMessageAt 共用这一份,不写两套。
|
||||
*/
|
||||
function refreshSessionTitle(session: ChatSession): void {
|
||||
const firstUserMessage = session.messages.find((item) => item.role === 'user')
|
||||
session.title = firstUserMessage ? buildSessionTitle(firstUserMessage.content) : '新对话'
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「生成中」形态的消息落定为 stopped(正文原样保留)。
|
||||
* 两处共用同一变换,保证口径一致:
|
||||
@@ -431,12 +441,36 @@ export const useChatStore = defineStore('chat', {
|
||||
// 这是有意接受的取舍 —— 重新问一次即可,不值得为它引入节流。
|
||||
this.persistPending = true
|
||||
},
|
||||
removeMessage(messageId: string) {
|
||||
const targetSession = this.sessions.find((session) => session.messages.some((message) => message.id === messageId))
|
||||
/**
|
||||
* 批量删除消息(跨会话按 id 定位,同 removeMessage 的定位方式)。
|
||||
* 零产出整轮作废用:一轮失败要同时删 user + assistant 两条,
|
||||
* 一次 filter、一次重算标题、一次落盘 —— 不为每条消息各写一遍 localStorage。
|
||||
*/
|
||||
removeMessages(messageIds: string[]) {
|
||||
const ids = new Set(messageIds)
|
||||
const targetSession = this.sessions.find((session) => session.messages.some((message) => ids.has(message.id)))
|
||||
if (!targetSession) return
|
||||
targetSession.messages = targetSession.messages.filter((message) => message.id !== messageId)
|
||||
const firstUserMessage = targetSession.messages.find((item) => item.role === 'user')
|
||||
targetSession.title = firstUserMessage ? buildSessionTitle(firstUserMessage.content) : '新对话'
|
||||
targetSession.messages = targetSession.messages.filter((message) => !ids.has(message.id))
|
||||
refreshSessionTitle(targetSession)
|
||||
targetSession.updatedAt = Date.now()
|
||||
this.persistSessions()
|
||||
},
|
||||
removeMessage(messageId: string) {
|
||||
// 口径只留一份:单条删除委托批量版
|
||||
this.removeMessages([messageId])
|
||||
},
|
||||
/**
|
||||
* 把消息按下标插回指定会话(按 sessionId 定位,不是 activeSession ——
|
||||
* 重新生成零产出失败时要把原回复放回**原会话**,用户此刻可能已切走)。
|
||||
* 幂等:同 id 已在会话里 ⇒ 直接 return(迟到的结算不得插出重复消息)。
|
||||
*/
|
||||
insertMessageAt(sessionId: string, index: number, message: ChatMessage) {
|
||||
const targetSession = this.sessions.find((session) => session.id === sessionId)
|
||||
if (!targetSession) return
|
||||
if (targetSession.messages.some((item) => item.id === message.id)) return
|
||||
const clampedIndex = Math.max(0, Math.min(index, targetSession.messages.length))
|
||||
targetSession.messages.splice(clampedIndex, 0, message)
|
||||
refreshSessionTitle(targetSession)
|
||||
targetSession.updatedAt = Date.now()
|
||||
this.persistSessions()
|
||||
},
|
||||
|
||||
+143
-16
@@ -51,6 +51,87 @@ export function estimateTokenCount(text: string): number {
|
||||
return chinese + Math.ceil(english / 4) + Math.ceil(special * 0.25)
|
||||
}
|
||||
|
||||
/** `truncateMessagesByTokenCount` 能识别的消息形状(`OpenAIMessage` 的子集)。 */
|
||||
export interface TruncatableToolCall {
|
||||
id: string
|
||||
function?: { name?: string }
|
||||
}
|
||||
|
||||
export interface TruncatableMessage {
|
||||
role: string
|
||||
content: string
|
||||
tool_calls?: TruncatableToolCall[]
|
||||
tool_call_id?: string
|
||||
}
|
||||
|
||||
export interface TruncateMessagesOptions {
|
||||
/**
|
||||
* 这些工具调用的成功结果**整对保留**(`assistant(tool_calls)` + 紧随的 tool 消息),
|
||||
* 不随旧轮被截断。用于技能正文这类「结论性事实」——丢了模型就会重新取一遍。
|
||||
* 传入的名称由调用方决定(本文件不认识具体工具协议)。
|
||||
*/
|
||||
pinnedToolNames?: readonly string[]
|
||||
/** 额外的成功判定;默认「非空即成功」。 */
|
||||
isPinnedToolResult?: (content: string) => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 找出「必留工具调用块」的消息下标:
|
||||
* - 发起 pinned 调用的 assistant 消息本身;
|
||||
* - 它紧随其后的**整段** tool 消息(同一 assistant 可能一次调多个工具,
|
||||
* 按单个 call 拆会留下孤儿 `tool_calls`);
|
||||
* - 它之前最近的 user 消息(截断结果必须以 user 开头,否则网关 400)。
|
||||
*
|
||||
* 只认「有对应 tool 结果且判为成功」的调用。
|
||||
*/
|
||||
function collectPinnedToolIndexes<T extends TruncatableMessage>(
|
||||
messages: T[],
|
||||
options: TruncateMessagesOptions,
|
||||
): Set<number> {
|
||||
const mandatory = new Set<number>()
|
||||
const names = options.pinnedToolNames
|
||||
if (!names || names.length === 0) return mandatory
|
||||
|
||||
const pinnedNames = new Set(names)
|
||||
const isSuccess = options.isPinnedToolResult ?? (() => true)
|
||||
|
||||
// call id → 发起它的 assistant 下标
|
||||
const callOwner = new Map<string, number>()
|
||||
for (let i = 0; i < messages.length; i += 1) {
|
||||
const message = messages[i]
|
||||
if (message.role !== 'assistant' || !message.tool_calls) continue
|
||||
for (const call of message.tool_calls) {
|
||||
const name = call.function?.name
|
||||
if (name && pinnedNames.has(name)) callOwner.set(call.id, i)
|
||||
}
|
||||
}
|
||||
if (callOwner.size === 0) return mandatory
|
||||
|
||||
const successfulOwners = new Set<number>()
|
||||
for (const message of messages) {
|
||||
if (message.role !== 'tool' || !message.tool_call_id) continue
|
||||
const owner = callOwner.get(message.tool_call_id)
|
||||
if (owner === undefined) continue
|
||||
if (!message.content.trim()) continue
|
||||
if (!isSuccess(message.content)) continue
|
||||
successfulOwners.add(owner)
|
||||
}
|
||||
|
||||
for (const owner of successfulOwners) {
|
||||
mandatory.add(owner)
|
||||
for (let i = owner + 1; i < messages.length && messages[i].role === 'tool'; i += 1) {
|
||||
mandatory.add(i)
|
||||
}
|
||||
for (let i = owner - 1; i >= 0; i -= 1) {
|
||||
if (messages[i].role === 'user') {
|
||||
mandatory.add(i)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return mandatory
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 token 截断,**整轮保留**:一轮 = 一条 user + 其后所有消息(assistant/tool),
|
||||
* 按 `role === 'user'` 切组,从最新轮向前累加,总 token 超过上限时停止。
|
||||
@@ -59,39 +140,85 @@ export function estimateTokenCount(text: string): number {
|
||||
* 头部防御:开头若不是 user(异常形态)⇒ 丢到第一条 user 为止 ——
|
||||
* tool / assistant(tool_calls) 开头的序列网关直接 400。
|
||||
* 最新一轮即使自身超上限也保留(否则空历史,请求无法发出)。
|
||||
*
|
||||
* ── 必留块(`options.pinnedToolNames`)──────────────────────────────────
|
||||
* 命中的成功工具对不随旧轮丢弃(如技能正文)。它们**计入** token 预算:
|
||||
* 预算 = 上限 - 必留块 token,剩余的才留给近期轮次。必留块自带触发它的 user,
|
||||
* 因此截断结果仍以 user 开头。必留块本身超上限时照常保留(同「最新一轮」策略)。
|
||||
*/
|
||||
export function truncateMessagesByTokenCount<T extends { content: string; role: string }>(
|
||||
export function truncateMessagesByTokenCount<T extends TruncatableMessage>(
|
||||
messages: T[],
|
||||
maxTokens: number,
|
||||
options: TruncateMessagesOptions = {},
|
||||
): T[] {
|
||||
const limit = Math.max(Number(maxTokens), 0)
|
||||
if (!limit || !messages.length) return []
|
||||
|
||||
const groups: T[][] = []
|
||||
let current: T[] = []
|
||||
for (const message of messages) {
|
||||
if (message.role === 'user' && current.length) {
|
||||
const mandatory = collectPinnedToolIndexes(messages, options)
|
||||
|
||||
// 按 user 切组,记下标(后面要按「必留 / 非必留」分别计 token)。
|
||||
const groups: number[][] = []
|
||||
let current: number[] = []
|
||||
for (let i = 0; i < messages.length; i += 1) {
|
||||
if (messages[i].role === 'user' && current.length) {
|
||||
groups.push(current)
|
||||
current = []
|
||||
}
|
||||
current.push(message)
|
||||
current.push(i)
|
||||
}
|
||||
if (current.length) groups.push(current)
|
||||
|
||||
const keptGroups: T[][] = []
|
||||
let total = 0
|
||||
let pinnedTokens = 0
|
||||
for (const index of mandatory) pinnedTokens += estimateTokenCount(messages[index].content)
|
||||
const budget = limit - pinnedTokens
|
||||
|
||||
const kept = new Set(mandatory)
|
||||
let extra = 0
|
||||
let keptGroupCount = 0
|
||||
for (let index = groups.length - 1; index >= 0; index -= 1) {
|
||||
const groupTokens = groups[index].reduce(
|
||||
(sum, message) => sum + estimateTokenCount(message.content),
|
||||
const group = groups[index]
|
||||
const groupExtra = group.reduce(
|
||||
(sum, messageIndex) =>
|
||||
sum + (mandatory.has(messageIndex) ? 0 : estimateTokenCount(messages[messageIndex].content)),
|
||||
0,
|
||||
)
|
||||
if (keptGroups.length && total + groupTokens > limit) break
|
||||
keptGroups.unshift(groups[index])
|
||||
total += groupTokens
|
||||
if (keptGroupCount > 0 && extra + groupExtra > budget) break
|
||||
for (const messageIndex of group) kept.add(messageIndex)
|
||||
extra += groupExtra
|
||||
keptGroupCount += 1
|
||||
}
|
||||
|
||||
const kept = keptGroups.flat()
|
||||
const out: T[] = []
|
||||
for (let i = 0; i < messages.length; i += 1) {
|
||||
if (kept.has(i)) out.push(messages[i])
|
||||
}
|
||||
// 头部防御:必留块已带上触发它的 user,正常不会切掉正文。
|
||||
let start = 0
|
||||
while (start < kept.length && kept[start].role !== 'user') start += 1
|
||||
return kept.slice(start)
|
||||
while (start < out.length && out[start].role !== 'user') start += 1
|
||||
return out.slice(start)
|
||||
}
|
||||
|
||||
/**
|
||||
* 发给模型的 history 严格交替:部分网关(Perplexity / Minimax / Dashscope 等)
|
||||
* 对连续 user 直接 400。只动 user,assistant / tool 原样保留。
|
||||
* 规则:① 相邻 user 合并为一条(content 用 '\n' 拼接,信息不丢);
|
||||
* ② 尾部未获回复的 user 整条丢掉(已被下一条提问取代,且没有 assistant 配对)。
|
||||
* 返回新数组;不就地改入参。
|
||||
*/
|
||||
export function normalizeHistoryForRequest<T extends { role: string; content: string }>(messages: T[]): T[] {
|
||||
// ① 相邻 user 合并:老数据 / 异常收场可能留下连排 user,网关不收
|
||||
const merged: T[] = []
|
||||
for (const message of messages) {
|
||||
const prev = merged[merged.length - 1]
|
||||
if (message.role === 'user' && prev?.role === 'user') {
|
||||
merged[merged.length - 1] = { ...prev, content: `${prev.content}\n${message.content}` }
|
||||
} else {
|
||||
merged.push(message)
|
||||
}
|
||||
}
|
||||
// ② 尾部未获回复的 user 丢掉:当前这条提问由 runAgentLoop 的 userMessage 单独传,
|
||||
// history 里尾部挂着的 user 只会是「上一条没得到回复的旧提问」
|
||||
let end = merged.length
|
||||
while (end > 0 && merged[end - 1].role === 'user') end -= 1
|
||||
return merged.slice(0, end)
|
||||
}
|
||||
|
||||
+257
-55
@@ -7,6 +7,7 @@
|
||||
<div class="chat-layout__main">
|
||||
<div class="chat-layout__content">
|
||||
<ChatPanel
|
||||
ref="chatPanelRef"
|
||||
:messages="chatMessages"
|
||||
:tool-event="toolEvent"
|
||||
@send="handleSendMessage"
|
||||
@@ -30,27 +31,57 @@ import SidebarSessions from '../components/SidebarSessions.vue'
|
||||
import type { ChatMessage, MessageActionPayload, OpenAIMessage, SendMessagePayload } from '../types'
|
||||
import { useChatStore } from '../stores/chat'
|
||||
import { useConfigStore } from '../stores/config'
|
||||
import { runAgentLoop, runSaveStrategyFlow, buildSystemMessage, sliceHistoryForSkill, collectLoadedSkillsFromHistory } from '../services/agent-loop'
|
||||
import { runAgentLoop, runSaveStrategyFlow, buildSystemMessage, sliceHistoryForSkill, collectLoadedSkillsFromHistory, TOOL_CORRECTION_PREFIX } from '../services/agent-loop'
|
||||
import type { AgentLoopEvent } from '../services/agent-loop'
|
||||
import { requestChatCompletion } from '../services/chat'
|
||||
import { getGlossaryText, ensureGlossaryLoaded, refreshGlossary } from '../services/glossary'
|
||||
import { getAiBridge } from '../bridge'
|
||||
import { generateId, truncateMessagesByTokenCount, validateHttpUrl } from '../utils/common'
|
||||
import { generateId, normalizeHistoryForRequest, truncateMessagesByTokenCount, validateHttpUrl } from '../utils/common'
|
||||
import { parseStrategyClasses } from '../utils/strategy-classes'
|
||||
|
||||
const chatStore = useChatStore()
|
||||
const configStore = useConfigStore()
|
||||
const router = useRouter()
|
||||
const abortControllerRef = ref<AbortController | null>(null)
|
||||
// ChatPanel 实例引用:零产出整轮作废时经 restoreDraft 把用户原文回填输入框
|
||||
const chatPanelRef = ref<InstanceType<typeof ChatPanel> | null>(null)
|
||||
|
||||
// 请求代次:requestAssistantReply 每次开跑时自增。
|
||||
// 迟到收场(用户已停止旧请求并发出新请求后,旧 invocation 才 settle)不得写新请求的
|
||||
// 状态(会话账本 / abortControllerRef / requesting 标志)—— 所有收场写入前先比对代次。
|
||||
let requestGeneration = 0
|
||||
|
||||
/**
|
||||
* 在途回合记录:一轮请求从发出到收场的完整身份。
|
||||
* 结算(settlePendingTurn)一律用请求开始时捕获的**对象引用**,不重读 ref ——
|
||||
* 迟到的旧请求不得结算到新请求的记录上。
|
||||
*/
|
||||
interface PendingTurn {
|
||||
generation: number
|
||||
sessionId?: string
|
||||
assistantMessageId: string
|
||||
/** 仅首次发送:零产出 ⇒ 整轮作废、正文回填输入框 */
|
||||
rollback?: { userMessageId: string; content: string; taskOptionLine: string | null }
|
||||
/** 仅重新生成:零产出 ⇒ 原回复按原下标放回 */
|
||||
regenerateOf?: { message: ChatMessage; index: number }
|
||||
settled?: boolean
|
||||
}
|
||||
|
||||
// 当前在途回合(null = 没有);handleStopGenerate 的防御性结算要能看到它
|
||||
const pendingTurnRef = ref<PendingTurn | null>(null)
|
||||
|
||||
// 当前正在进行的工具轮(null = 没有);传给 ChatPanel 展示,工具轮不得静默
|
||||
const toolEvent = ref<AgentLoopEvent | null>(null)
|
||||
|
||||
/**
|
||||
* 账本截断的必留规则:成功的 `load_skill` 调用对整对保留。
|
||||
* 技能正文是「结论性事实」—— 被截掉后模型会重新取一遍;失败回灌不是正文,不保留。
|
||||
*/
|
||||
const LOOP_HISTORY_TRUNCATE_OPTIONS = {
|
||||
pinnedToolNames: ['load_skill'],
|
||||
isPinnedToolResult: (content: string) => !content.startsWith(TOOL_CORRECTION_PREFIX),
|
||||
}
|
||||
|
||||
// 任务选择已内联进输入面板(ChatPanel),这里只剩「新建会话」一条流;
|
||||
// 任务档(解释/改写/生成)由用户在面板里选,不再在新建时钉死。
|
||||
function handleCreateSession(): void {
|
||||
@@ -160,23 +191,91 @@ function createAssistantPlaceholder(assistantMessageId: string): void {
|
||||
})
|
||||
}
|
||||
|
||||
type SettleOutcome = 'kept' | 'rolled-back' | 'restored' | 'removed' | 'noop'
|
||||
interface SettleResult { outcome: SettleOutcome; draft?: string }
|
||||
|
||||
/**
|
||||
* 统一结算在途回合(幂等:已 settled ⇒ 'noop')。
|
||||
*
|
||||
* 产品口径:一轮对话**模型零产出**(内容 trim 后为空,不分 stopReason)⇒ 整轮作废;
|
||||
* **有半截内容**再失败 ⇒ 保留半截气泡('kept',调用方负责写状态),不删不恢复不回填。
|
||||
*
|
||||
* 零产出时严格按此顺序:
|
||||
* 1. 先删占位消息(无论代次是否过期,占位都该消失);
|
||||
* 2. 代次过期 ⇒ 只删不恢复('removed')—— 迟到的旧请求不得动新请求的会话与输入框;
|
||||
* 3. 重新生成 ⇒ 原回复按原下标放回('restored',会话状态回到点「重新生成」之前);
|
||||
* 4. 首次发送且用户仍在该会话 ⇒ 删 user 消息、按签名清 lastTaskOption、原文回填('rolled-back');
|
||||
* 5. 其余(重发;或首发但用户已切走会话)⇒ 只删占位('removed')。
|
||||
*/
|
||||
function settlePendingTurn(turn: PendingTurn | null, hasContent: boolean): SettleResult {
|
||||
if (!turn) return { outcome: 'noop' }
|
||||
if (turn.settled) return { outcome: 'noop' }
|
||||
|
||||
// 有半截内容 ⇒ 保留给用户看,状态由调用方写('kept')
|
||||
if (hasContent) {
|
||||
turn.settled = true
|
||||
return { outcome: 'kept' }
|
||||
}
|
||||
|
||||
// 零产出:占位消息一律删掉(空 assistant 留在会话里只会污染下一轮文本历史)
|
||||
chatStore.removeMessages([turn.assistantMessageId])
|
||||
turn.settled = true
|
||||
|
||||
// 代次过期 ⇒ 迟到收场:不插入、不回填、不动其他会话
|
||||
if (turn.generation !== requestGeneration) {
|
||||
return { outcome: 'removed' }
|
||||
}
|
||||
|
||||
// 重新生成零产出 ⇒ 原回复按原下标放回(字段原样,含 status)
|
||||
if (turn.regenerateOf) {
|
||||
chatStore.insertMessageAt(turn.sessionId ?? '', turn.regenerateOf.index, turn.regenerateOf.message)
|
||||
return { outcome: 'restored' }
|
||||
}
|
||||
|
||||
// 首次发送零产出且用户仍在本会话 ⇒ 整轮作废:删 user 消息 + 原文回填输入框。
|
||||
// 拼接签名只在「它正是本轮拼进的那行」时清零 ⇒ 重发同签名会重新拼上 [任务选项] 行。
|
||||
if (turn.rollback && chatStore.activeSessionId === turn.sessionId) {
|
||||
chatStore.removeMessages([turn.rollback.userMessageId])
|
||||
if (turn.rollback.taskOptionLine && chatStore.activeSession?.lastTaskOption === turn.rollback.taskOptionLine) {
|
||||
chatStore.clearLastTaskOption()
|
||||
}
|
||||
return { outcome: 'rolled-back', draft: turn.rollback.content }
|
||||
}
|
||||
|
||||
// 重发(用户消息是历史原件,不动);或首发但用户已切走会话(不碰新会话的输入框)
|
||||
return { outcome: 'removed' }
|
||||
}
|
||||
|
||||
/** 把结算产生的草稿回填输入框(仅 rolled-back 有草稿)。 */
|
||||
function applySettleDraft(result: SettleResult): void {
|
||||
if (result.outcome === 'rolled-back' && result.draft) {
|
||||
chatPanelRef.value?.restoreDraft(result.draft)
|
||||
}
|
||||
}
|
||||
|
||||
async function requestAssistantReply(
|
||||
payload: SendMessagePayload,
|
||||
excludedMessageIds: string[] = [],
|
||||
options: { useLedger?: boolean } = {},
|
||||
): Promise<void> {
|
||||
options: {
|
||||
useLedger?: boolean
|
||||
/** 仅首次发送:零产出 ⇒ 整轮作废、正文回填输入框 */
|
||||
rollback?: PendingTurn['rollback']
|
||||
/** 仅重新生成:零产出 ⇒ 原回复按原下标放回 */
|
||||
regenerateOf?: PendingTurn['regenerateOf']
|
||||
} = {},
|
||||
): Promise<boolean> {
|
||||
if (!validateRequestConfig()) {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if (chatStore.isRequesting) {
|
||||
ElMessage.warning('当前已有请求进行中,请稍后再试')
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if (configStore.availableModels.length === 0) {
|
||||
ElMessage.warning('AI 暂停服务,请稍后重试')
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
// history 三选一(顺序重要):
|
||||
@@ -188,10 +287,17 @@ async function requestAssistantReply(
|
||||
if (!options.useLedger) {
|
||||
history = buildHistoryMessages(excludedMessageIds)
|
||||
} else if (chatStore.activeSession?.loopMessages?.length) {
|
||||
history = truncateMessagesByTokenCount(chatStore.activeSession.loopMessages, configStore.effectiveConfig.contextMaxTokens)
|
||||
history = truncateMessagesByTokenCount(
|
||||
chatStore.activeSession.loopMessages,
|
||||
configStore.effectiveConfig.contextMaxTokens,
|
||||
LOOP_HISTORY_TRUNCATE_OPTIONS,
|
||||
)
|
||||
} else {
|
||||
history = buildHistoryMessages(excludedMessageIds)
|
||||
}
|
||||
// 严格交替归一:部分网关(Perplexity / Minimax / Dashscope 等)对连续 user 直接 400。
|
||||
// 文本历史与账本两条路径都要过(老数据里可能有尾部无答 user / 连排 user)。
|
||||
history = normalizeHistoryForRequest(history)
|
||||
const assistantMessageId = generateId('message')
|
||||
createAssistantPlaceholder(assistantMessageId)
|
||||
|
||||
@@ -201,6 +307,16 @@ async function requestAssistantReply(
|
||||
// 被新请求换成别的会话,收场时一律用这里捕获的值,不再重读 store。
|
||||
const myGeneration = ++requestGeneration
|
||||
const mySessionId = chatStore.activeSession?.id
|
||||
// 在途回合记录:结算一律用这个对象引用(不重读 pendingTurnRef)——
|
||||
// 迟到的旧请求不得结算到新请求的记录上。
|
||||
const myTurn: PendingTurn = {
|
||||
generation: myGeneration,
|
||||
sessionId: mySessionId,
|
||||
assistantMessageId,
|
||||
rollback: options.rollback,
|
||||
regenerateOf: options.regenerateOf,
|
||||
}
|
||||
pendingTurnRef.value = myTurn
|
||||
let accumulated = ''
|
||||
|
||||
try {
|
||||
@@ -247,14 +363,12 @@ async function requestAssistantReply(
|
||||
|
||||
const failed = result.stopReason === 'error'
|
||||
|
||||
// 失败轮的处理(改造-08):
|
||||
// - 无产出文字 ⇒ 删掉占位消息(与「请求已停止」同款)—— 一条空气回合留在
|
||||
// 会话里只会污染下一轮的文本历史(曾被作为空 assistant 发回给模型)。
|
||||
// - 有产出文字 ⇒ 保留给用户看,但标 status 'error' ⇒ buildHistoryMessages
|
||||
// 会把它排除(半截上下文不能进历史),气泡里文字仍在。
|
||||
if (failed && !result.content.trim()) {
|
||||
chatStore.removeMessage(assistantMessageId)
|
||||
} else {
|
||||
// 结算(零产出整轮作废 / 半截保留的统一入口):
|
||||
// - 'kept'(有产出文字)⇒ 写消息:失败标 status 'error' ⇒ buildHistoryMessages
|
||||
// 会把它排除(半截上下文不能进历史),气泡里文字仍在;
|
||||
// - 非 'kept'(零产出)⇒ 占位已删,可能整轮回滚 / 原回复已放回,这里不再写消息。
|
||||
const settle = settlePendingTurn(myTurn, Boolean(result.content.trim()))
|
||||
if (settle.outcome === 'kept') {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
content: result.content,
|
||||
isLoading: false,
|
||||
@@ -263,12 +377,13 @@ async function requestAssistantReply(
|
||||
})
|
||||
}
|
||||
|
||||
// 账本跨轮存活:正常收场(model / max-rounds)⇒ 存本次的账本,
|
||||
// 下轮当 history 传回 ⇒ 模型看得见上轮取过的技能正文。
|
||||
// 出错(error)⇒ 清空 —— 半截上下文不能留,下轮退回文本历史重建。
|
||||
// 账本跨轮存活:正常收场且消息保留 ⇒ 存本次的账本,下轮当 history 传回
|
||||
// ⇒ 模型看得见上轮取过的技能正文。
|
||||
// 出错(error)或零产出作废 ⇒ 清空 —— 半截 / 作废的上下文不能留,
|
||||
// 下轮退回文本历史重建。
|
||||
// 代次过期(迟到收场)⇒ 整个跳过:不能把旧请求的账本写进新请求的会话。
|
||||
if (myGeneration === requestGeneration && mySessionId) {
|
||||
chatStore.setSessionLoopMessages(mySessionId, failed ? undefined : result.ledger)
|
||||
chatStore.setSessionLoopMessages(mySessionId, settle.outcome === 'kept' && !failed ? result.ledger : undefined)
|
||||
}
|
||||
|
||||
// 提交声明兜底写入:以返回值为准(仅当完成声明被兑现时非空)
|
||||
@@ -281,6 +396,12 @@ async function requestAssistantReply(
|
||||
} else if (result.stopReason === 'max-rounds' && result.error) {
|
||||
ElMessage.warning(result.error)
|
||||
}
|
||||
// 回填草稿无条件调一次('kept' 时是 no-op):不能只挂在上面两个 else if 里 ——
|
||||
// stopReason 'model' 且零产出、或 max-rounds 未带 error 时同样可能整轮作废,
|
||||
// 草稿不回填用户原文就丢了。模态框分支已先 await ⇒ 焦点仍落在输入框。
|
||||
applySettleDraft(settle)
|
||||
// 本轮是否拿到一条正常完成的回复(调用方据此决定要不要弹「已重新生成/发送」)
|
||||
return settle.outcome === 'kept' && !failed
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : '请求失败,请稍后重试'
|
||||
|
||||
@@ -292,29 +413,42 @@ async function requestAssistantReply(
|
||||
}
|
||||
|
||||
if (message === '请求已停止') {
|
||||
const currentMessage = chatStore.sessions.flatMap((session) => session.messages).find((item) => item.id === assistantMessageId)
|
||||
if (!currentMessage?.content.trim()) {
|
||||
chatStore.removeMessage(assistantMessageId)
|
||||
} else {
|
||||
// 用户主动停止:有半截 ⇒ 保留并标 stopped;零产出 ⇒ 结算
|
||||
//(首发整轮作废 + 原文回填 / 重新生成放回原回复 / 重发只删占位)。
|
||||
const hasContent = Boolean(accumulated.trim())
|
||||
const settle = settlePendingTurn(myTurn, hasContent)
|
||||
if (settle.outcome === 'kept') {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
isLoading: false,
|
||||
error: false,
|
||||
status: 'stopped',
|
||||
})
|
||||
}
|
||||
return
|
||||
// 这里没有模态框,直接回填(零产出首发 ⇒ 原文回输入框并聚焦)
|
||||
applySettleDraft(settle)
|
||||
return false
|
||||
}
|
||||
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
content: message,
|
||||
isLoading: false,
|
||||
error: true,
|
||||
status: 'error',
|
||||
})
|
||||
// 兜底分支:不再把错误文案写进 content ——
|
||||
// 有半截内容 ⇒ 保留半截气泡并标 error(半截上下文不能进历史,但文字给用户看);
|
||||
// 零产出 ⇒ 结算(首发整轮回滚 / 重新生成放回原回复 / 重发只删占位)。
|
||||
const hasContent = Boolean(accumulated.trim())
|
||||
const settle = settlePendingTurn(myTurn, hasContent)
|
||||
if (settle.outcome === 'kept') {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
content: accumulated,
|
||||
isLoading: false,
|
||||
error: true,
|
||||
status: 'error',
|
||||
})
|
||||
}
|
||||
|
||||
await ElMessageBox.alert(message, '错误提示', {
|
||||
type: 'error',
|
||||
})
|
||||
// 模态框关闭后再回填草稿:焦点才能落在输入框(模态框会抢焦点)
|
||||
applySettleDraft(settle)
|
||||
return false
|
||||
} finally {
|
||||
// 代次过期(迟到收场)⇒ 全局状态一律不碰:abortControllerRef / requesting / 工具轮
|
||||
// 可能已被新请求占用,清掉等于把新请求的 controller 弄丢(之后停不掉)。
|
||||
@@ -325,15 +459,15 @@ async function requestAssistantReply(
|
||||
}
|
||||
// 安全网(E):任何收场路径都不得把占位消息留在「生成中」。
|
||||
// 正常路径(成功分支 / catch 两个分支)已结算,这里只兜极端情况
|
||||
//(catch 自身先抛错);口径与「请求已停止」分支一致。
|
||||
// 按 assistantMessageId 定位,id 唯一 ⇒ 代次过期时在新会话里找不到该消息,天然 no-op。
|
||||
const unsettled = chatStore.activeSession?.messages.find(
|
||||
(item) => item.id === assistantMessageId && item.isLoading,
|
||||
)
|
||||
//(catch 自身先抛错)。跨会话按 assistantMessageId 定位(代次过期时
|
||||
// 消息可能在别的会话),id 唯一 ⇒ 天然不误伤。找到就结算:
|
||||
// 零产出 ⇒ 整轮作废 / 原回复放回;有内容 ⇒ 落定 stopped。不弹提示。
|
||||
const unsettled = chatStore.sessions
|
||||
.flatMap((session) => session.messages)
|
||||
.find((item) => item.id === assistantMessageId && item.isLoading)
|
||||
if (unsettled) {
|
||||
if (!unsettled.content.trim()) {
|
||||
chatStore.removeMessage(assistantMessageId)
|
||||
} else {
|
||||
const settle = settlePendingTurn(myTurn, Boolean(unsettled.content.trim()))
|
||||
if (settle.outcome === 'kept') {
|
||||
chatStore.updateMessage(assistantMessageId, {
|
||||
isLoading: false,
|
||||
error: false,
|
||||
@@ -347,6 +481,10 @@ async function requestAssistantReply(
|
||||
// 代次过期 ⇒ 上面的安全网没动过任何状态,无需落盘。
|
||||
if (myGeneration === requestGeneration) {
|
||||
chatStore.flushPersist()
|
||||
// 代次匹配才清在途回合记录:迟到的旧请求不得清掉新请求的记录
|
||||
if (pendingTurnRef.value === myTurn) {
|
||||
pendingTurnRef.value = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -379,6 +517,13 @@ async function handleSendMessage(payload: SendMessagePayload): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 模型列表为空 ⇒ 请求必然失败 ⇒ 在 append 用户消息**之前**拦下,
|
||||
// 避免留下一条悬空的用户消息(零产出回滚只管请求发出之后的失败)。
|
||||
if (configStore.availableModels.length === 0) {
|
||||
ElMessage.warning('AI 暂停服务,请稍后重试')
|
||||
return
|
||||
}
|
||||
|
||||
const userMessageId = generateId('message')
|
||||
// 发送前先判定拼接(D2):拼了 ⇒ 行记进 message.taskOption(界面不渲染)+ 会话记录
|
||||
const resolved = resolveTaskOption(payload.content)
|
||||
@@ -395,7 +540,20 @@ async function handleSendMessage(payload: SendMessagePayload): Promise<void> {
|
||||
// 当前实例不再拼进 user 消息 —— 实例内容由模型按 [任务选项] 自己调 get_policy 取
|
||||
// (无注入 —— 改造-04;saveTarget 快照链路已删 —— 改造-05)
|
||||
// ⚠️ 账本收到的 user 消息是拼接后真身(resolved.text),与文本历史同口径
|
||||
await requestAssistantReply({ content: resolved.text }, [userMessageId], { useLedger: true })
|
||||
await requestAssistantReply(
|
||||
{ content: resolved.text },
|
||||
[userMessageId],
|
||||
{
|
||||
useLedger: true,
|
||||
// 首次发送:零产出 ⇒ 整轮作废。content 是用户原文(不含 taskOption 行),
|
||||
// 回填输入框的必须是用户能编辑重发的原文。
|
||||
rollback: {
|
||||
userMessageId,
|
||||
content: payload.content,
|
||||
taskOptionLine: resolved.appended && resolved.line ? resolved.line : null,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function handleStopGenerate(): void {
|
||||
@@ -407,20 +565,42 @@ function handleStopGenerate(): void {
|
||||
chatStore.setRequesting(false)
|
||||
|
||||
// 防御性结算(C):挂起路径(promise 永不 settle,如 bridge / fetch 卡死)进不了
|
||||
// requestAssistantReply 的 catch,abort 事件落不到消息上 ⇒ 这里立即把 in-flight
|
||||
// 的 assistant 消息落定,口径与 catch 的「请求已停止」分支一致(空内容删、有内容 stopped)。
|
||||
const inFlight = chatStore.activeSession?.messages.find((item) => item.role === 'assistant' && item.isLoading)
|
||||
if (inFlight) {
|
||||
if (!inFlight.content.trim()) {
|
||||
chatStore.removeMessage(inFlight.id)
|
||||
} else {
|
||||
chatStore.updateMessage(inFlight.id, {
|
||||
// requestAssistantReply 的 catch,abort 事件落不到消息上 ⇒ 这里立即用在途回合记录收场:
|
||||
// 零产出 ⇒ 整轮作废(删占位;首发还回填原文)/ 重新生成放回原回复;有半截 ⇒ 保留标 stopped。
|
||||
// 之后 promise 若迟到 settle,因 settled 已置 true 自然 no-op。
|
||||
const turn = pendingTurnRef.value
|
||||
if (turn) {
|
||||
// 跨会话按 id 找该回合的助手消息(用户可能已切走会话)
|
||||
const inFlightMessage = chatStore.sessions
|
||||
.flatMap((session) => session.messages)
|
||||
.find((item) => item.id === turn.assistantMessageId)
|
||||
const settle = settlePendingTurn(turn, Boolean(inFlightMessage?.content.trim()))
|
||||
if (settle.outcome === 'kept') {
|
||||
chatStore.updateMessage(turn.assistantMessageId, {
|
||||
isLoading: false,
|
||||
error: false,
|
||||
status: 'stopped',
|
||||
})
|
||||
}
|
||||
chatStore.flushPersist()
|
||||
// 这里没有模态框,直接回填(零产出首发 ⇒ 原文回输入框并聚焦)
|
||||
applySettleDraft(settle)
|
||||
} else {
|
||||
// 无在途回合记录(理论不可达:isRequesting 时必有记录)⇒ 退回旧的就地落定,
|
||||
// 避免占位卡「生成中」
|
||||
const inFlight = chatStore.activeSession?.messages.find((item) => item.role === 'assistant' && item.isLoading)
|
||||
if (inFlight) {
|
||||
if (!inFlight.content.trim()) {
|
||||
chatStore.removeMessage(inFlight.id)
|
||||
} else {
|
||||
chatStore.updateMessage(inFlight.id, {
|
||||
isLoading: false,
|
||||
error: false,
|
||||
status: 'stopped',
|
||||
})
|
||||
}
|
||||
chatStore.flushPersist()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,13 +664,17 @@ async function handleResendMessage({ messageId }: MessageActionPayload): Promise
|
||||
}
|
||||
}
|
||||
|
||||
await requestAssistantReply(
|
||||
const completed = await requestAssistantReply(
|
||||
{
|
||||
content: resolved.text,
|
||||
},
|
||||
[targetMessage.id],
|
||||
)
|
||||
ElMessage.success('已重新发送该消息')
|
||||
// 只有本轮真正拿到正常回复才弹成功提示;零产出回滚 / 失败时
|
||||
// 错误提示已由 alert / toast 覆盖,再弹「已重新发送」自相矛盾
|
||||
if (completed) {
|
||||
ElMessage.success('已重新发送该消息')
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRegenerateMessage({ messageId }: MessageActionPayload): Promise<void> {
|
||||
@@ -518,6 +702,11 @@ async function handleRegenerateMessage({ messageId }: MessageActionPayload): Pro
|
||||
return
|
||||
}
|
||||
|
||||
// 快照要在 removeMessage 之前:零产出失败时要把原回复**按原下标、字段原样**放回
|
||||
//(含 status / error —— 会话状态要回到点「重新生成」之前)。
|
||||
const original = { ...assistantMessage }
|
||||
const originalIndex = assistantIndex
|
||||
|
||||
chatStore.removeMessage(messageId)
|
||||
// 重新生成按**当前**签名重新判定是否拼(与重发同口径,票里已定)
|
||||
const resolved = resolveTaskOption(relatedUserMessage.content)
|
||||
@@ -530,13 +719,22 @@ async function handleRegenerateMessage({ messageId }: MessageActionPayload): Pro
|
||||
chatStore.clearLastTaskOption()
|
||||
}
|
||||
}
|
||||
await requestAssistantReply(
|
||||
const completed = await requestAssistantReply(
|
||||
{
|
||||
content: resolved.text,
|
||||
},
|
||||
[relatedUserMessage.id],
|
||||
{
|
||||
// 重新生成:零产出 ⇒ 原回复按原下标放回。不需要 rollback ——
|
||||
// 用户消息是历史原件,不动。
|
||||
regenerateOf: { message: original, index: originalIndex },
|
||||
},
|
||||
)
|
||||
ElMessage.success('已重新生成回复')
|
||||
// 只有本轮真正拿到正常回复才弹成功提示;零产出放回原回复 / 失败时
|
||||
// 错误提示已由 alert / toast 覆盖,再弹「已重新生成」自相矛盾
|
||||
if (completed) {
|
||||
ElMessage.success('已重新生成回复')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -565,7 +763,11 @@ async function handleSaveStrategy(): Promise<void> {
|
||||
// 技能正文:解析优先级见下方注释(声明技能 → 账本 → 无则静默退出)
|
||||
await ensureGlossaryLoaded()
|
||||
const history = chatStore.activeSession?.loopMessages?.length
|
||||
? truncateMessagesByTokenCount(chatStore.activeSession.loopMessages, config.contextMaxTokens)
|
||||
? truncateMessagesByTokenCount(
|
||||
chatStore.activeSession.loopMessages,
|
||||
config.contextMaxTokens,
|
||||
LOOP_HISTORY_TRUNCATE_OPTIONS,
|
||||
)
|
||||
: buildHistoryMessages()
|
||||
|
||||
// 技能正文解析:技能名来自模型在 logic_complete 里的声明(skill_name),
|
||||
@@ -629,8 +831,8 @@ async function handleSaveStrategy(): Promise<void> {
|
||||
content:
|
||||
'请把当前已讨论清楚的完整策略逻辑,转写为一段文字输出。' +
|
||||
'如果有多条完整的策略逻辑,只提取最新的一条进行转写,其它的一律不要提及、不要合并。' +
|
||||
'转写原则:不省略、不改写、不输出代码或 json —— 用自然语言把每一条规则(切入点、下注、走向、硬约束)说全。' +
|
||||
'你的输出会被交给保存流程,用于生成策略交付物。',
|
||||
'转写原则:不省略、不改写、不输出代码或 json —— 优先使用领域术语,结合自然语言把每一条规则(切入点、下注、走向、硬约束)说全。' +
|
||||
'你的输出会被用于生成策略交付物。',
|
||||
},
|
||||
]
|
||||
const logicResult = await requestChatCompletion({
|
||||
|
||||
Reference in New Issue
Block a user