修改特殊注码和打注一体的data格式

This commit is contained in:
2026-11-14 16:21:34 +08:00
parent 46cbe888ac
commit eade886d0e
19 changed files with 657 additions and 156 deletions
+296 -74
View File
@@ -31,14 +31,14 @@
* 模型工具面没有保存工具。用户点「保存」按钮后,app 走
* `runSaveStrategyFlow`(导出,ChatView.handleSaveStrategy 调用):
* ① 要逻辑:主会话模型 + 全套上下文 + 指令「输出完整逻辑」⇒ 一段逻辑文本
* ② 交付物:`produceStrategyDeliverable`(温度 0、无工具)按 logic_complete
* 声明的技能(skill_name)取到的正文把逻辑转成 JSON → 提取 + 形状校验 → 只改顶层
* ② 交付物(温度 0、无工具)→ 审查(同一份配置、温度 0)→ 只改顶层
* `id`(新建 0 / 改写 = 选中实例的 id)与 `name`(留空,命名交给 native)
* → 调 `applyStrategy` 交 native。native 判 `校验失败` / `解析失败` 时把
* 上一次的 json + 错误原文回灌交付物生成请求重做(上限 2 次重试);
* `用户取消` / `操作失败` 直接显示状态、不重试。
* + 剥 `data.code` 注释 → 调 `applyStrategy` 交 native。native 判
* `校验失败` / `解析失败` 时把上一次的 json + 错误原文回灌交付物生成请求
* 重做(上限 2 次重试);`用户取消` / `操作失败` 直接显示状态、不重试。
* app 全程**不认识 skill 名、不解析 JSON 字段**(只读/只改顶层
* `id` / `kind` / `name`,`data` 内部一律不碰)。
* `id` / `kind` / `name`;`data` 内部唯一的例外是提交前用
* `stripJsComments` 剥掉 `data.code` 的注释 —— 只清文本,不改结构)。
*
* ── 实测事实(one-api / agnes-2.5-flash,勿「简化」掉)────────────────────
* - `tool_choice: 'required'` 会**每个请求**都强制调工具,且实测会逼模型
@@ -86,8 +86,9 @@ import type { ChatCompletionResult } from './chat'
import { AGENT_CONDUCT } from '../constants/agent-conduct'
import { WORKFLOW_PROMPT } from '../constants/workflow'
import { buildPolicySkillsPrompt } from '../constants/policy-skills'
import { buildDeliverableSystemMessage } from '../constants/strategy-save'
import { buildDeliverableSystemMessage, buildReviewSystemMessage } from '../constants/strategy-save'
import { getPolicy } from './policy-lookup'
import { stripJsComments } from '../utils/strategy-instances'
/** 硬上限:一个 loop 最多几轮。 */
export const MAX_AGENT_ROUNDS = 8
@@ -245,9 +246,9 @@ export interface AgentLoopResult {
*/
ledger: OpenAIMessage[]
/**
* 本次 loop 的完成声明所依据的技能名(logic_complete 的 skill_name)。
* 仅当完成声明在执行段被兑现(accumulated 非空、正文在上下文里、
* 摘除 tool_call 并中止)时非空;出错 / 撞上限一律 null。
* 本次 loop 声明的技能名(logic_complete 的 skill_name,且正文确实在上下文里)。
* 与 onLogicComplete 同一个判据(本 loop 调过 logic_complete 且 accumulated 非空)
* 决定是否非空 —— 回调触发就带出声明名,否则 null;出错路径提前 return,恒为 null。
* 调用方(ChatView)把它写进会话(`logicSkillName`,瞬态不落盘)——
* 保存流程取它对应的正文,保存按钮显隐也用它。
*/
@@ -329,7 +330,7 @@ function buildLogicCompleteTool(): ToolDefinition {
function: {
name: 'logic_complete',
description:
'声明「本条策略逻辑已完整」。' +
'声明「本条生成/改写策略逻辑已完整」。每次输出完整逻辑都必须调用。' +
'调用方式:必须带 skill_name:本次完整逻辑所依据的策略技能英文名。' +
'调用时机:\n' +
'- 只要生成/改写任务的策略逻辑已满足「生成/改写任务流程」的 4 个完整判断条件;\n' +
@@ -545,6 +546,62 @@ export function collectLoadedSkillsFromHistory(history: OpenAIMessage[]): { skil
return { skills: loaded }
}
/**
* 扫出「每个技能最后一次成功 load_skill」的锚点,供恢复会话时重建工具对:
* - callId:原调用 id,重建时原样复用;
* - anchorUserSeq:该 pair 之前(按数组顺序)的 **user 条数**;
* - text:正文(调用方顺手塞进内存缓存,省一次 native 往返)。
* 同 name 后出现的覆盖先出现的(与 `sliceHistoryForSkill` 的锚点口径一致)。
*/
export function collectLoadedSkillAnchors(
history: OpenAIMessage[],
): Array<{ name: string; callId: string; anchorUserSeq: number; text: string }> {
// 先把 assistant.tool_calls 里 load_skill 的参数解析出来,按 call id 索引
//(成功判定口径与 collectLoadedSkillsFromHistory 一致)
const loadCallArgs = new Map<string, { skillName: 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 !== 'load_skill') 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 skillName = extractNonEmptyString(args, 'skill_name')
if (!skillName) continue
loadCallArgs.set(call.id, { skillName })
}
}
// 按顺序遍历:userCount 累计该消息**之前**出现过的 user 条数(遇到 user 先自增,
// 因此遍历到 tool 消息时 userCount 正是「该 pair 之前的 user 条数」)。
// 命中成功 load 时写 Map(同名后者覆盖前者)。
const anchors = new Map<string, { name: string; callId: string; anchorUserSeq: number; text: string }>()
let userCount = 0
for (const message of history) {
if (message.role === 'user') {
userCount += 1
continue
}
if (message.role !== 'tool' || !message.tool_call_id) continue
const record = loadCallArgs.get(message.tool_call_id)
if (!record) continue
// 纠错回灌(load_skill 失败等)带 TOOL_CORRECTION_PREFIX —— 不是正文,不算成功
if (message.content.startsWith(TOOL_CORRECTION_PREFIX)) continue
if (!message.content.trim()) continue
anchors.set(record.skillName, {
name: record.skillName,
callId: message.tool_call_id,
anchorUserSeq: userCount,
text: message.content,
})
}
return Array.from(anchors.values())
}
/**
* 解析 `get_policy` 的工具结果:成功时是 `StrategyInstance[]` 的 JSON 文本。
* 空结果 / 纠错文案 / 坏 JSON ⇒ null(不当已加载记录)。
@@ -970,9 +1027,6 @@ function validateDeliverableShape(text: string): { ok: true } | { ok: false; rea
return { ok: true }
}
/** 代码类策略的 skill 名集合。 */
const CODE_SKILLS = new Set(['specialBet', 'specialChip', 'betWithChip'])
/** 禁用的标识符/语法(全部在 acorn AST 里可检测)。 */
const FORBIDDEN_IDENTIFIERS = new Set([
'eval', 'Function', 'require', 'import', 'console', 'fetch', 'XMLHttpRequest',
@@ -1101,6 +1155,102 @@ function validateCodeStrategy(code: string): string | null {
return walk(ast)
}
/** 是否普通对象(非 null / 非数组)。JSON 形状检查用。 */
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* 取交付物里的代码字段:`data.code` 是字符串 ⇒ 返回它,否则 null。
*
* **判据是结构,不是技能名** —— app 不认识任何 skill 名;表格式策略的 data 是
* rows/options,没有 code,自然返回 null。审查、AST 校验、注释剥离三处同口径。
*/
function extractCodeField(jsonText: string): string | null {
let parsed: unknown
try {
parsed = JSON.parse(jsonText)
} catch {
return null
}
if (!isPlainObject(parsed)) return null
const data = parsed.data
if (!isPlainObject(data)) return null
return typeof data.code === 'string' ? data.code : null
}
/**
* 只采纳审查结果里的 `data.code`,其余字段(kind / description / name / id)一律
* 用原交付物的 —— 审查器可能顺手改名、改描述,那些不是它该碰的。
*
* 任何一条不满足 ⇒ null(调用方沿用原始生成,**审查永不阻断保存**):
* ① 两份都是合法 JSON 对象;② 双方 data 都是对象;③ 审查的 data.code 是非空字符串;
* ④ 该 code 通过 `validateCodeStrategy`。
*/
function tryReplaceCode(originalJsonText: string, reviewJsonText: string): string | null {
let original: unknown
let review: unknown
try {
original = JSON.parse(originalJsonText)
review = JSON.parse(reviewJsonText)
} catch {
return null
}
if (!isPlainObject(original) || !isPlainObject(review)) return null
const originalData = original.data
const reviewData = review.data
if (!isPlainObject(originalData) || !isPlainObject(reviewData)) return null
const code = reviewData.code
if (typeof code !== 'string' || !code.trim()) return null
if (validateCodeStrategy(code)) return null
originalData.code = code
return JSON.stringify(original)
}
/**
* 审查一份交付物,返回可能被修正的 JSON 文本。
*
* - `data.code` 不是字符串 ⇒ 原样返回(表格式策略不该为审查花 token)
* - 请求失败 / 空回复 / 回复里没有 JSON 块 / 审查结果不合法 ⇒ 原样返回
* - 用户中断 ⇒ 上抛(与生成请求同口径)
*
* ⚠️ **永远返回一份可提交的 JSON 文本**,所以调用点不需要任何兜底判断。
* ⚠️ 审查的存在不向用户吐露(行为准则:不得透露工作流程)。
*/
async function reviewStrategyDeliverable(
config: AppConfig,
skillText: string,
logic: string,
jsonText: string,
signal?: AbortSignal,
): Promise<string> {
if (extractCodeField(jsonText) === null) return jsonText
const subConfig: AppConfig = { ...config, temperature: 0, stream: false }
const messages: OpenAIMessage[] = [
{ role: 'system', content: buildReviewSystemMessage(skillText) },
{
role: 'user',
content: `用户已确认的完整策略逻辑:\n${logic}\n\n据此生成的 JSON 交付物:\n${jsonText}`,
},
]
let reply: string
try {
const result = await requestChatCompletion({ config: subConfig, messages, signal })
reply = result.content
} catch (error: unknown) {
if (isAbort(error)) throw error
logLoopIssue('审查交付物失败,沿用原始生成', error)
return jsonText
}
if (!reply.trim()) return jsonText
const reviewedJson = extractJsonDeliverable(reply)
if (!reviewedJson) return jsonText
return tryReplaceCode(jsonText, reviewedJson) ?? jsonText
}
/**
* 「交付物生成请求」= 一次专门的 AI 请求(**不是 loop 的一轮**,也不是 agent)。
*
@@ -1118,7 +1268,6 @@ async function produceStrategyDeliverable(
skillText: string,
logic: string,
previous?: { jsonText: string; error: string },
skillName?: string,
signal?: AbortSignal,
): Promise<DeliverableResult> {
const subConfig: AppConfig = { ...config, temperature: 0, stream: false }
@@ -1168,21 +1317,13 @@ async function produceStrategyDeliverable(
const shape = validateDeliverableShape(jsonText)
if (!shape.ok) return shape
// 代码类策略的 AST 静态校验
if (CODE_SKILLS.has(skillName ?? '')) {
try {
const parsed = JSON.parse(jsonText)
if (parsed && typeof parsed === 'object' && 'data' in parsed) {
const data = parsed.data as Record<string, unknown>
if (typeof data.code === 'string') {
const err = validateCodeStrategy(data.code)
if (err) {
return { ok: false, reason: `代码策略静态校验失败:${err}` }
}
}
}
} catch {
// JSON.parse 失败由 validateDeliverableShape 捕获,这里忽略
// 代码类交付物(data.code 是字符串)走 AST 静态校验;表格式策略没有 code ⇒ 跳过。
// ⚠️ 判据是结构不是技能名,见 extractCodeField。
const code = extractCodeField(jsonText)
if (code !== null) {
const err = validateCodeStrategy(code)
if (err) {
return { ok: false, reason: `代码策略静态校验失败:${err}` }
}
}
@@ -1193,12 +1334,59 @@ async function produceStrategyDeliverable(
const MAX_SAVE_ATTEMPTS = 3
/**
* 提交前只改交付物**顶层**:`id`(新建 0 / 改写 = 选中实例的 id)与 `name`
* (留空字符串 —— 名字由用户在 native 的命名对话框里给,app 不填)。
* ⚠️ 只动顶层这两个键,`data` 内部一律不碰(app 不解析)。
* description 的 UTF-8 字节上限。
*
* native 用 buf[1024] 存这个字段、按字节截断且不拒绝。1000 是留给 prompt 侧
* 的写作余量(见 `constants/strategy-save.ts` 的生成指令),这里只做兜底。
*/
const DESCRIPTION_MAX_BYTES = 1000
/**
* 把 description 截到不超过上限字节,**且不切断多字节字符**。
*
* 与 native 的字节截断互补:native 切在字节上,可能把汉字切成半个(存成非法
* UTF-8);这里按码点累加,结果永远是合法 UTF-8 且 ≤ 上限。
*
* - 未超长 ⇒ 原样返回,不做任何改动;
* - 超长 ⇒ 返回截断结果,并打一条内部日志(只进 console,不进界面)。
*
* @param text 原始 description
* @returns 长度合规的 description
*/
function clampDescription(text: string): string {
const encoder = new TextEncoder()
const total = encoder.encode(text).length
if (total <= DESCRIPTION_MAX_BYTES) return text
let out = ''
let bytes = 0
// for...of 按码点遍历(代理对作为整体),不会切出半个字符
for (const ch of text) {
const size = encoder.encode(ch).length
if (bytes + size > DESCRIPTION_MAX_BYTES) break
out += ch
bytes += size
}
logLoopIssue('description 超出 UTF-8 字节上限,已截断', `${total} → ${bytes} 字节(上限 ${DESCRIPTION_MAX_BYTES})`)
return out
}
/**
* 提交前整理交付物:顶层 `id` / `name`、代码类交付物的 `data.code` 注释剥离、
* `description` 的字节裁剪(都是文本清理,不改结构、不改语义)。
*
* - `id`:新建 0 / 改写 = 选中实例的 id
* - `name`:留空字符串 —— 名字由用户在 native 的命名对话框里给,app 不填
* - `data.code`:是字符串 ⇒ `stripJsComments` 去注释(其它字段一律不碰)
* - `description`:是字符串 ⇒ `clampDescription` 截到 ≤ DESCRIPTION_MAX_BYTES
* (native 只截断不拒绝;这里按字符边界截,防切出半个汉字)
*
* ⚠️ 判据是「字段是字符串」,**不认 skill 名** —— 特殊打法 / 特殊注码 /
* 打注一体三类代码技能自动命中 code 那条。
* ⚠️ 这也是回灌重做用的那一份:模型看到的上一次 JSON 已无注释,不会照抄回来。
* 不是 JSON 对象 ⇒ null(调用方按失败收场)。
*/
function withTopLevelFields(jsonText: string, id: number): string | null {
function prepareSubmission(jsonText: string, id: number): string | null {
let parsed: unknown
try {
parsed = JSON.parse(jsonText)
@@ -1206,11 +1394,26 @@ function withTopLevelFields(jsonText: string, id: number): string | null {
return null
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
return JSON.stringify({ ...(parsed as Record<string, unknown>), id, name: '' })
const record = parsed as Record<string, unknown>
// description 按 UTF-8 字节上限裁剪(native 只截断不拒绝;这里按字符边界截,
// 防 native 的字节截断切出半个汉字)
if (typeof record.description === 'string') {
record.description = clampDescription(record.description)
}
const data = record.data
if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
const dataRecord = data as Record<string, unknown>
if (typeof dataRecord.code === 'string') {
dataRecord.code = stripJsComments(dataRecord.code)
}
}
return JSON.stringify({ ...record, id, name: '' })
}
/**
* 保存策略的完整流程:**产出 → 填顶层 → 提交 → 失败分流**。
* 保存策略的完整流程:**产出 → 审查 → 填顶层 → 提交 → 失败分流**。
*
* 导出供 ChatView.handleSaveStrategy 调用:`logic` 来自「要逻辑」子请求
* (loop 外、主会话上下文 + 指令「输出完整逻辑」)。
@@ -1218,6 +1421,7 @@ function withTopLevelFields(jsonText: string, id: number): string | null {
* ```
* for attempt in 1..3:
* 交付物 = 交付物生成请求(技能正文, 策略逻辑, [上一次的 json + native 错误原文])
* 交付物 = 审查请求(技能正文, 策略逻辑, 交付物) ← 注释掉这一行即关闭审查
* 交付物顶层 id = 选中实例的 id(未选中 ⇒ 0);name = ''
* result = applyStrategy(json 文本)
* ├─ ok: true ⇒ 「已保存:<name>(ID <id>)」
@@ -1227,6 +1431,11 @@ function withTopLevelFields(jsonText: string, id: number): string | null {
* 3 次都不过 ⇒ 失败收场(附 native 原始错误)
* ```
*
* 每次尝试 = **生成 + 审查**(都属生成阶段)→ 整理 → applyStrategy(保存阶段)。
* 审查只对 `data.code` 是字符串的交付物生效,任何失败都沿用原始生成 ——
* **审查永不阻断保存**;要关闭审查,注释掉循环体里调用
* `reviewStrategyDeliverable` 的那一行即可,其余流程不变。
*
* 返回 `ok`(是否保存成功)、**结果文本**(原样返回给调用方)与 `name`
* (native 确认后的实例名,仅成功时带;失败分支一律不带);
* 不抛(用户中断由交付物生成请求上抛)。
@@ -1236,21 +1445,27 @@ export async function runSaveStrategyFlow(
skillText: string,
logic: string,
instanceId: number,
skillName?: string,
signal?: AbortSignal,
onPhase?: (phase: 'generating' | 'saving') => void,
): Promise<{ ok: boolean; toolResult: string; name?: string }> {
/** 上一次被 native 拒绝的 json + 错误原文(回灌重做的输入)。 */
let previous: { jsonText: string; error: string } | undefined
for (let attempt = 1; attempt <= MAX_SAVE_ATTEMPTS; attempt++) {
const deliverable = await produceStrategyDeliverable(config, skillText, logic, previous, skillName, signal)
// 交付物生成 + 审查都算生成阶段
onPhase?.('generating')
const deliverable = await produceStrategyDeliverable(config, skillText, logic, previous, signal)
if (!deliverable.ok) {
return { ok: false, toolResult: `保存策略失败:${deliverable.reason}。请把失败原因告知用户。` }
}
// 提交前只改顶层 id / name(见 withTopLevelFields);app 不解析其余字段。
const submitted = withTopLevelFields(deliverable.jsonText, instanceId)
let deliverableJson = deliverable.jsonText
// 审查:注释掉本行即关闭审查,其余流程不变(非代码类/失败/无需修正都原样返回)
deliverableJson = await reviewStrategyDeliverable(config, skillText, logic, deliverableJson, signal)
// 提交前整理:顶层 id / name + 代码类交付物剥离 data.code 注释(见 prepareSubmission)。
const submitted = prepareSubmission(deliverableJson, instanceId)
if (!submitted) {
return {
ok: false,
@@ -1258,6 +1473,8 @@ export async function runSaveStrategyFlow(
}
}
// applyStrategy 才转「保存阶段」(含 native 命名对话框)
onPhase?.('saving')
// 调 native:传**提取并填好 id 的 JSON 文本**。弹框与落盘都在 native 内部。
let result: ApplyResult
try {
@@ -1368,17 +1585,15 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
// 但要单独封顶,否则坏上游能把每一轮都烧成纠错。
let correctionRounds = 0
// 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' 时)。
let committedInLoop: string | null = null
// 本 loop 声明过的技能名(logic_complete 的 skill_name),且正文确实在上下文里。
// 两处写入:① 校验段收到声明就记 —— 即便本次因「单独调用」被退回也记:
// 「先调工具、后补逻辑」是模型的常见顺序,退回只是要求它补文字,不是作废声明;
// ② 兑现段用 effectiveSkillName 覆盖 —— R1 单正文容错时声明名可能是错的。
// 收尾统一由 fired 决定它是否随返回值带出 —— 与 onLogicComplete 同一个布尔量。
let declaredSkillName: string | null = null
// 工具面固定:除降级外一律挂这三个(不分任务),`tool_choice` 恒为 'auto' ——
// 注入已取消(改造-04),模型按 `# 流程说明` 的加载规则自决调不调工具。
@@ -1527,21 +1742,6 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
} 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
}
const skillName = extractSkillName(parsedArgs)
if (!skillName) {
logLoopIssue('logic_complete 未指定技能名', { arguments: call.function.arguments.slice(0, 200) })
@@ -1551,6 +1751,27 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
})
continue
}
else if (inContext.has(skillName)){
// 声明即记候选名:即便本次因「单独调用」被退回,技能声明本身仍然有效 ——
// 模型补完逻辑文字后不会重调它(实测),收尾要靠这里记下的名字带出。
// ⚠️ 必须 inContext.has(...):模型会编造技能名(实测),编错的名字不能记,
// 否则保存流程会按错名字取正文,把打法逻辑当注码交付。
declaredSkillName = skillName
}
// 闸门 A:不得单独调用 —— 逻辑必须在本次 loop 里输出过(accumulated 非空)。
// ⚠️ 判据用 accumulated(本 loop 内各轮 result.content 累加,loop 局部、
// 不含跨 loop 寒暄):它是 runAgentLoop 的局部变量,每次进入重置,
// 只含本次 loop 的 assistant content,可靠。本轮 result.content 为空
// 但前几轮已输出过逻辑 ⇒ 同样放行(逻辑在任意一轮输出即可,不限当轮)。
if (!accumulated.trim()) {
logLoopIssue('logic_complete 单独调用(本 loop 无逻辑输出)', { arguments: call.function.arguments.slice(0, 200) })
corrections.push({
call,
reason: `${TOOL_CORRECTION_PREFIX}logic_complete 不能单独调用。请先完整输出本条策略逻辑(规则、路径、下注、走向),再调用本工具;单独调用本工具会被退回。`,
})
continue
}
validatedCalls.push({ kind: 'complete', call, skillName })
} else if (call.function.name === 'get_policy') {
const args = parsedArgs as Record<string, unknown>
@@ -1663,9 +1884,9 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
inContext.set(item.skillName, text)
// R2:模型加载了与已提交技能**不同**的技能 ⇒ 回调(调用方收回保存按钮)。
// 判据用 committedInLoop(本 loop 已兑现的声明)兜 params.logicSkillName
// 判据用 declaredSkillName(本 loop 已声明的技能名)兜 params.logicSkillName
// (会话级、与 savePhase 同生命周期)。同名重复加载不回调;没有已提交逻辑时不触发。
const committed = committedInLoop ?? (params.logicSkillName?.trim() || null)
const committed = declaredSkillName ?? (params.logicSkillName?.trim() || null)
if (committed && item.skillName !== committed) {
onSkillBound?.({ skillName: item.skillName, switched: true })
}
@@ -1724,15 +1945,14 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
'若技能名写错了,改为原样照抄技能清单「英文名」一栏;若还没有取到该技能的正文,先调用 load_skill 获取;' +
'然后按本工具描述和参数的要求重新调用 logic_complete。',
)
declaredSkillName = null
continue
}
}
// 合规:兑现 + 中止。摘掉该 tool_call(悬空 tool_call 会让下一轮请求 400)、
// 不为它填 tool 消息 —— 本轮回复里已带完整逻辑,账本收进这条 assistant 即可。
// ⚠️ logicCompleteRequested 现在的语义是「本轮已兑现并中止」的标志。
// ⚠️ onLogicComplete 不在这里触发 —— 统一在 loop 收尾触发(见 Step 4/5)。
logicCompleteRequested = true
committedInLoop = effectiveSkillName
declaredSkillName = effectiveSkillName
const idx = result.toolCalls.indexOf(item.call)
if (idx >= 0) result.toolCalls.splice(idx, 1)
stopReason = 'model'
@@ -1826,17 +2046,19 @@ export async function runAgentLoop(params: AgentLoopParams): Promise<AgentLoopRe
// ⚠️ max-rounds 收场也会走到这里 —— 模型撞轮上限前调过 logic_complete 且
// accumulated 非空时触发是合理的(逻辑确实输出过)。
// 出错路径(stopReason === 'error')都在循环内提前 return,走不到这里。
if (logicCompleteCalled && accumulated.trim()) {
onLogicComplete?.()
}
// fired 同时决定 logicSkillName 是否带出 —— 回调与返回值同源,永远同步:
// 被退回后补出逻辑文字的场景(调过但没兑现)也照常带出声明名。
const fired = Boolean(logicCompleteCalled && declaredSkillName && accumulated.trim())
if (fired) onLogicComplete?.()
return {
content: accumulated,
stopReason,
...(stopReason === 'max-rounds' ? { error: `已达到最大轮数(${MAX_AGENT_ROUNDS})` } : {}),
ledger: stripLogicCompleteTrace(compactPolicyHistory(stripToolCorrections(ledger))),
// 兑现即中止(stopReason === 'model' 且 committedInLoop 已赋值)才带出技能名;
// committedInLoop 只在兑现路径被赋值,非中止路径恒为 null
logicSkillName: stopReason === 'model' ? committedInLoop : null,
// 与 onLogicComplete 同一个 fired 决定:触发回调就带出声明名,不触发就 null。
// ⚠️ 不再用 stopReason === 'model' 当闸 —— 它与触发条件不同源(max-rounds
// 收场同样会触发回调),双闸并存会出现「占位出了、名字没带」的缺口。
logicSkillName: fired ? declaredSkillName : null,
}
}