import { DELIVERY_CORRECTION_REMINDER, expectsFormalDelivery } from './loop/deliveryIntent.js'; import { buildModelMessages, evictPriorVisionShots, injectVisionFollowups, mergeToolCallDelta, pushManualInterruptMarker, pushAdvisorFollowUpMarker, pushQueuedInputMarker, } from './loop/messages.js'; import type { RunQueryOptions } from './loop/options.js'; import { prepareModelRequest } from './loop/requestPreparation.js'; import { createTurnProjection } from './loop/turnProjection.js'; import { executeToolBatch } from './loop/toolBatch.js'; import { createToolExecutor, type WorkerOutcome } from './loop/toolExecutor.js'; import { advisorSemanticsFor } from './loop/toolSemantics.js'; export { expectsFormalDelivery } from './loop/deliveryIntent.js'; export { buildModelMessages, SYSTEM_REMINDER_CLOSE, SYSTEM_REMINDER_OPEN, VISION_SHOT_MARKER, } from './loop/messages.js'; export type { RunQueryOptions } from './loop/options.js'; export { friendlyToolDescription } from './loop/toolPresentation.js'; export { advisorSemanticsFor } from './loop/toolSemantics.js'; /** * Agent turn orchestrator. Owns conversation state and continuation decisions. * Request preparation and tool execution/scheduling live in ./loop/; the * final answer is published here, verbatim, once every delivery gate passes. * Host options and LoopEvent remain the public compatibility boundary. * See ./loop/README.md for phase ownership and invariants. */ import crypto from 'node:crypto'; import { isPriorTaskNotice } from './runtime/systemEvents.js'; import { contentToPlainText } from './multimodal.js'; import { resolve } from 'node:path'; import { AdvisorNudge } from './advisor/advisorNudge.js'; import { advisorBackgroundParts } from './advisor/reviewContext.js'; import { previousUserRequest } from './memory/recallQuery.js'; import { configService } from './config/configService.js'; import { buildContextBudgetPlan, modelInputLimit } from './context/budgetPlan.js'; import { assembleContextBundle, contextFragment, resizeContextBundle } from './context/contextBundle.js'; import { expireOldEntries, getToolResultPolicy, incrementTurn, microCompact, reclaimOldToolResults, resetCacheEdits, } from './context/microCompactLite.js'; import { createConversationOptimizer } from './context/optimizeConversation.js'; import { isPromptTooLongError, reactiveCompactIfApplicable } from './context/reactiveCompact.js'; import { countMessagesTokens, estimateToolsTokens } from './context/tokenCounter.js'; import { archiveToolResult } from './context/toolResultArchive.js'; import { checkMemoryPublication, validateFinalClaims } from './harness/claimValidation.js'; import { explicitSave, explicitForget } from './tools/memory/policy.js'; import { EvidenceLedger } from './harness/evidenceLedger.js'; import { classifyGenerationError, completeGenerationTerminal, createGenerationReceipt } from './harness/generationReceipt.js'; import { StallGuard } from './harness/stallGuard.js'; import { chat as defaultChat } from './llm/client.js'; import { buildUserContent } from './multimodal.js'; import { delegationRuntimeGuidance } from './prompts/delegation.js'; import { capabilitiesForTools, enabledPolicyIds } from './prompts/policyRegistry.js'; import { loadProjectPromptInstructions } from './prompts/projectInstructions.js'; import { needsDiagramPreparation, requestKeepsTextDiagrams, visualPresentation } from './prompts/visualPresentation.js'; import { LiveDiagramGate } from './loop/liveDiagramGate.js'; import { planFinalPublication } from './loop/finalPublication.js'; import { createAgentRuntimeContext } from './runtime/agentRuntimeContext.js'; import { answerPreparationNotice } from './runtime/answerPreparation.js'; import { deliveryBindingNote, evaluateDeliveryGate, pendingRequiredSummary, resolveDeliveryId, } from './runtime/deliveryGate.js'; import { invocationInstructions, invocationToolAllowed } from './runtime/invocationPolicy.js'; import { createLifecycleTrace } from './runtime/lifecycleTrace.js'; import { resolveOutputContract } from './runtime/outputContract.js'; import { filterToolsForProvider } from './team/toolPolicy.js'; import { agentCoordinationContext, takeAgentNotifications } from './tools/agent/agentTaskService.js'; import { takeBackgroundNotifications } from './tools/tasks/backgroundTaskService.js'; import { needsInteractiveQuestion } from './tools/ask/routing.js'; import { capabilityForToolName } from './tools/capabilities.js'; import { classifyComputerAutomationIntent } from './tools/computeruse/computerIntent.js'; import { recordComputerUseExposure } from './tools/computeruse/telemetryLog.js'; import { createEffectiveToolSet } from './tools/effectiveToolSet.js'; import { ALL_TOOLS, executeCatalogTool, getToolGateDetails } from './tools/index.js'; import { planReadBudgets } from './tools/shared/readBudget.js'; import { hydrateSessionWorktree } from './tools/worktree/sessionWorktree.js'; import type { GenerationReceipt, LoopEvent, Message, Tool, ToolCall, ToolCallContext, TurnResourceUsage, } from './types.js'; import { stripThinkBlocks } from './utils/stripThink.js'; /** 主工具循环的默认轮数上限。 */ export const DEFAULT_MAX_TURNS = 200; /** Live streaming starts once real answer text exists. A leading inline * block (MiniMax and similar), even a tag still arriving in pieces, * is not the answer and must not be shown as if it were. */ /** 显式选项优先;否则读配置 `advisor.enforcement`(只在需要补问时才读一次盘,读失败当作关闭)。 */ async function advisorFollowUpEnabled(options: RunQueryOptions): Promise { if (options.advisorFollowUp !== undefined) return options.advisorFollowUp; try { return (await configService.advisor())?.enforcement === 'followup'; } catch { return false; } } function answerTextStarted(text: string): boolean { const lead = text.trimStart(); if (lead.length < ''.length && ''.startsWith(lead.toLowerCase())) return false; return stripThinkBlocks(text).length > 0; } /** * 执行一次"用户输入 → 模型回答完成"的完整流程。 * * yield 出来的 LoopEvent 会被 UI 用来更新界面。 */ export async function* runQuery(userInput: string, options: RunQueryOptions): AsyncGenerator { const { provider, history, signal, sessionState } = options; // Tool screenshots are transient evidence for the tool continuation that produced them. // Never carry a prior turn's base64 image into a new user request. evictPriorVisionShots(history); const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS; const inferredDesktop = options.browserRun?.supervised === true || options.browserRun?.viewer === 'desktop'; const baseRuntimeContext = options.runtimeContext ?? createAgentRuntimeContext({ surface: inferredDesktop ? 'desktop' : 'headless', ...(inferredDesktop ? { host: 'desktop' as const } : {}), profile: 'main', conversationMode: options.messageProvenance?.mode, cwd: process.cwd(), workspaceId: options.memoryContext?.workspaceId, sessionId: options.memoryContext?.sessionId, owner: options.memoryContext?.access !== 'denied' ? 'local-owner' : 'untrusted', memoryAccess: options.memoryContext?.access ?? 'denied', interactiveAsk: false, browser: options.browserRun, computer: options.computerRun, computerIntervention: options.computerIntervention, toolGate: options.toolGate, }); const computerIntent = baseRuntimeContext.computerIntent ?? classifyComputerAutomationIntent(userInput, sessionState?.computerAutomation); const runtimeContext = createAgentRuntimeContext({ ...baseRuntimeContext, computerIntent, }); if (runtimeContext.computer) { void recordComputerUseExposure(computerIntent.needed, computerIntent.source); } if (!computerIntent.needed && sessionState) delete sessionState.computerAutomation; // DI fallback:测试可传 stub,生产走真实模块单例 const chatFn = options.chat ?? defaultChat; const trace = createLifecycleTrace('loop'); const hostCatalog = [...(options.availableTools ?? ALL_TOOLS)]; const executeToolFn: NonNullable = options.executeTool ?? ((name, args, signal, ctx) => executeCatalogTool(hostCatalog, name, args, signal, ctx)); const explicitFileDeliveryRequested = expectsFormalDelivery(options.backgroundContinuation?.request ?? userInput); const backgroundNotificationIds = options.backgroundContinuation?.taskIds ?? (options.deferBackgroundNotifications ? [] : undefined); const currentUserMessageId = options.userMessageId ?? crypto.randomUUID(); let currentTransientBundle = options.transientBundle; let advisorContextBundle = currentTransientBundle; let recallInvalidated = false; const stillSelected = (f: import('./context/contextBundle.js').ContextFragment) => !recallInvalidated || !['memory', 'persona', 'episode'].includes(f.kind); const invalidateRecall = () => { recallInvalidated = true; if (advisorContextBundle) advisorContextBundle = assembleContextBundle( advisorContextBundle.fragments.filter(stillSelected), advisorContextBundle.diagnostics.budgetTokens, ); }; let modelEnvironmentCwd = runtimeContext.cwd; const observedRuleScopes = new Map(); const pendingRuleScopes = new Set(); const transientFor = (tools: readonly Tool[]): string => { const opaque = [options.transientContext?.trim(), invocationInstructions(options.invocationPolicy)] .filter(Boolean) .join('\n\n'); const bundle = currentTransientBundle; if (!bundle) return opaque; const basePlan = buildContextBudgetPlan({ provider, history, tools, transientContext: opaque, }); const availableForBundle = Math.max( 0, basePlan.inputLimit - basePlan.historyTokens - basePlan.toolTokens - basePlan.transientTokens, ); const selected = availableForBundle >= bundle.diagnostics.usedTokens ? bundle : resizeContextBundle(bundle, availableForBundle); advisorContextBundle = selected; return [selected.text, opaque].filter(Boolean).join('\n\n'); }; let resultPresented = false; let presentedResultUnverified = false; let deliveryCorrectionAttempted = false; let emptyResponseRecoveryAttempted = false; let emptyResponseRecoveryReason = ''; let askCorrectionAttempted = false; let diagramCorrectionAttempted = false; // The retired draft rides along with the next request only, as private // revision material: never shown to the user, never stored in history. let diagramCorrectionDraft = ''; // Part of that draft already streamed live (the text before the box): the // model continues from there instead of rewriting what the user has read. let diagramContinuation = false; const output = resolveOutputContract(runtimeContext.surface, runtimeContext.output); const subagents = await configService.subagents(); await hydrateSessionWorktree({ sessionState, workspaceId: runtimeContext.workspaceId, sessionId: runtimeContext.sessionId, cwd: runtimeContext.cwd, }); const toolCallContext: ToolCallContext = { steering: options.steering, output, availableToolNames: () => currentEffectiveToolSet.names, executionServices: { ...options.executionServices, executeTool: executeToolFn, chat: chatFn, invocationPolicy: options.invocationPolicy, }, history, sessionState, // Older plugin consumers retain the combined view; the built-in advisor // keeps project constraints and current background on opposite sides of history. advisorBackground: () => Object.values(toolCallContext.advisorBackgroundParts!()).filter(Boolean).join('\n\n'), advisorBackgroundParts: () => advisorBackgroundParts(advisorContextBundle, { cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd, availableTools: [...currentEffectiveToolSet.names], invocation: invocationInstructions(options.invocationPolicy), }), // Statistics only; consultations have no per-turn quota. advisorCalls: { used: 0 }, advisorInvocation: 'agent', // Agent 等派生工具起嵌套子查询所需的运行态:与主循环同一 provider、 // 同一审批闸门(子 agent 不绕过宿主策略)。agentCalls 限同一回合内的子任务派生总数,防失控 fan-out。 provider, toolGate: runtimeContext.toolGate ?? options.toolGate, agentCalls: { used: 0, max: subagents.enabled ? subagents.maxCallsPerTurn : 0 }, subagentConfig: subagents, browserRun: runtimeContext.browser ?? options.browserRun, computerRun: runtimeContext.computer ?? options.computerRun, computerIntervention: runtimeContext.computerIntervention ?? options.computerIntervention, currentUserInput: userInput, userInputs: [{ id: currentUserMessageId, text: userInput }], backgroundRequest: options.backgroundContinuation?.request, userMessageId: currentUserMessageId, agentHandoff: options.agentHandoff, messageProvenance: options.messageProvenance, memoryAccess: runtimeContext.memoryAccess, owner: runtimeContext.owner, conversationMode: runtimeContext.conversationMode ?? 'private', surface: runtimeContext.surface, workspaceId: runtimeContext.workspaceId, sessionId: runtimeContext.sessionId, cwd: runtimeContext.cwd, promptCache: options.promptCache, }; // 实际下发给模型的工具集:allowedTools 未传时给全量; // 传入数组时严格按数组过滤,[] 表示本轮不下发任何工具。 // 同时约束模型可见工具和本循环实际执行的工具。 const hostTools = filterToolsForProvider(hostCatalog, provider); const availableTools = hostTools.filter( (tool) => invocationToolAllowed(tool.name, options.invocationPolicy) && (tool.name !== 'Agent' || subagents.enabled) && (tool.name !== 'ComputerUse' || (runtimeContext.computer !== undefined && runtimeContext.computerIntent?.needed === true)), ); const effectiveToolSet = createEffectiveToolSet({ availableTools, runtime: runtimeContext, allowedNames: options.allowedTools, requiredNames: options.requiredTools, }); const activeTools = effectiveToolSet.tools; let formalDeliveryRequired = explicitFileDeliveryRequested && runtimeContext.profile === 'main' && options.invocationPolicy?.delivery !== 'caller' && effectiveToolSet.names.has('PresentResult'); // Stable delivery target: saying "continue the review" inherits the open // goal only when that binding is unambiguous. Host-supplied ids win; several // open targets are reported back to the model instead of picking the most // recently updated one. Records without their own deliveryId stay scoped to // their original request. const deliveryBinding = runtimeContext.profile === 'main' ? await resolveDeliveryId( userInput, toolCallContext, currentUserMessageId, options.backgroundContinuation?.deliveryId ?? options.deliveryId, ) : { deliveryId: currentUserMessageId, source: 'new' as const }; const deliveryId = deliveryBinding.deliveryId; toolCallContext.deliveryId = deliveryId; const canSteer = () => Boolean(options.takePendingMessages) && options.canConsumePendingMessages?.() !== false; const takePendingMessages = async (): Promise => { if (!canSteer()) return []; const messages = options.takePendingMessages?.() ?? []; if (options.steering && messages.length) { const users = messages.filter(m => m.role === 'user'); const additions = users.map(m => contentToPlainText(m.content)); if (additions.length) { for (const message of users) { message.id ??= crypto.randomUUID(); const text = contentToPlainText(message.content); toolCallContext.userInputs!.push({ id: message.id, text }); toolCallContext.currentUserInput = text; toolCallContext.userMessageId = message.id; } if (additions.some(expectsFormalDelivery) && runtimeContext.profile === 'main' && options.invocationPolicy?.delivery !== 'caller' && effectiveToolSet.names.has('PresentResult')) { formalDeliveryRequired = true; resultPresented = false; deliveryCorrectionAttempted = false; } } } // Prepare human supplements through the same image parser as initial input. // Preserve the original message even when preparation fails; report the // failure explicitly, never consume an input and then throw it away. if (options.steering) for (const message of [...messages]) { if (message.role !== 'user' || typeof message.content !== 'string') continue; const warnings: string[] = []; try { const content = await buildUserContent({ text: message.content, parseInlineImages: options.parseInlineImages, detail: options.imageDetail, maxLongSidePixel: options.imageMaxLongSidePixel, onInlineImageSkipped: (source, reason) => warnings.push(`${source}:${reason}`), }); const visual = Array.isArray(content) && content.some(p => p.type === 'image_url' || p.type === 'video_url'); if (visual && provider.supportsVision === false) warnings.push('当前模型不支持视觉,补充图片未发送;请切换模型。'); else { message.content = content; visionRequiredThisTurn ||= visual; } } catch (error) { warnings.push(`补充图片处理失败:${(error as Error).message}`); } if (warnings.length) messages.push({ role: 'system', content: `[输入处理提示] ${warnings.join('\n')}`, _ephemeral: true, _uiProgress: true }); } return messages; }; let currentEffectiveToolSet = effectiveToolSet; // The host only reminds; whether to consult the advisor is the model's call // (see advisor/advisorNudge.ts). Nothing here blocks a tool or holds an answer. const advisorNudge = new AdvisorNudge({ currentRequest: userInput, previousRequest: previousUserRequest(history), advisorAvailable: effectiveToolSet.names.has('Advisor') && options.advisorReminders !== false, }); let coordinationText = ''; let delegationCorrectionAttempted = false; // 组装每轮请求的易变上下文。三个构建点(首轮 / autoCompact 后 / snip 后)共用, // 避免 Advisor 相关提醒在复制粘贴中三处漂移。提醒均为 transient:只进当轮请求副本, // 不进会话历史(与 DELIVERY_CORRECTION_REMINDER 同构,见 buildModelMessages)。 const projection = createTurnProjection(); const buildRequestTransientContext = () => { const advisorAvailable = currentEffectiveToolSet.names.has('Advisor') && options.advisorReminders !== false; const base = transientFor(currentEffectiveToolSet.tools); const capacity = delegationRuntimeGuidance({ available: runtimeContext.profile === 'main' && currentEffectiveToolSet.names.has('Agent'), maxConcurrent: subagents.maxConcurrent, callsUsed: toolCallContext.agentCalls?.used ?? 0, maxCalls: toolCallContext.agentCalls?.max ?? 0, }); const parts = [ deliveryBindingNote(deliveryBinding), diagramCorrectionDraft ? `${visualPresentation(output)}\n${ diagramContinuation ? `你这版回答已向用户显示到字符框图之前(已保存为上一条消息,不能修改或撤回),框图及其后内容用户尚未看到。请紧接着已显示的内容继续写:先用 ${output.diagrams.join('/')} 重画那张框图,再按下方草稿写完其余部分,保留结论、数字、限定条件和链接;不要重复已显示的内容。` : `你上一版回答(下方内部草稿,用户尚未看到)用字符画了框图,而当前载体可渲染 ${output.diagrams.join('/')}。请在这版草稿的基础上修订:只把字符框图改成这些格式,保留其余结论、数字、限定条件和链接。` }技能目录里有图形技能时可先加载。\n\n${diagramCorrectionDraft}\n` : '', delegationCorrectionAttempted ? '本轮必要子任务尚未验收或接管完成。先读取结果、等待运行任务或完成接力,使用 AgentResolve 记录判断;若确实无法完成,明确报告缺口,不声称全部完成。' : '', askCorrectionAttempted ? '当前交互宿主支持 AskUserQuestion。若仍需用户选择或补充,请调用该工具一次只问一个问题,等待答案后继续;不要仅在正文列问后停止。若没有待决事项则正常回答,不必提问。' : '', emptyResponseRecoveryAttempted ? `上一次模型响应没有可交付正文(${emptyResponseRecoveryReason})。请基于已有历史和工具结果继续完成任务:信息充分则给出实质结论,不充分则继续必要操作或明确缺口。不要重复已经完成的调查或有副作用的操作;不要把未完成的任务说成完成。已有顾问意见继续有效,无需仅因恢复而再次咨询。` : '', deliveryCorrectionAttempted && !resultPresented ? DELIVERY_CORRECTION_REMINDER : '', advisorAvailable ? advisorNudge.reminder() : '', ]; return projection.plan(currentEffectiveToolSet.signature + '\n' + base, base, capacity, coordinationText, parts.filter(Boolean).join('\n\n')); }; let plannedView: ReturnType; let lastRequestTransientContext = [options.transientBundle?.text, options.transientContext] .filter(Boolean) .join('\n\n'); const evidenceLedger = new EvidenceLedger(); const stallGuard = new StallGuard(); const harnessDiagnostics = ( stopReason: import('./types.js').HarnessDiagnostics['stopReason'], ): import('./types.js').HarnessDiagnostics => ({ promptVersion: 'minimal-agent:prompt:v2', basePromptHash: crypto .createHash('sha256') .update(history[0]?.role === 'system' ? history[0].content : '') .digest('hex'), enabledPolicyIds: enabledPolicyIds({ profile: runtimeContext.profile, surface: runtimeContext.surface, cwd: runtimeContext.cwd, capabilities: capabilitiesForTools(currentEffectiveToolSet.tools), toolNames: currentEffectiveToolSet.names, }), enabledCapabilities: [ ...new Set( currentEffectiveToolSet.tools .map((tool) => capabilityForToolName(tool.name)) .filter((capability): capability is NonNullable => Boolean(capability)), ), ], effectiveToolSetSignature: currentEffectiveToolSet.signature, tokenBudget: buildContextBudgetPlan({ provider, history, tools: currentEffectiveToolSet.tools, transientContext: lastRequestTransientContext, }), stopReason, evidence: evidenceLedger.snapshot(), }); let userContent: Message['content']; // 行内图片是从用户文本里**猜**出来的(拖拽进终端的路径就走这条路),猜错很正常: // 路径可能还没生成、已删除、或纯粹是在讨论一个文件名。这类失败只降级成文本 + 一条 // warning,绝不能像下面 catch 那样打死整个回合——否则「随口提一个 .png 路径」=回合当场死。 const skippedInlineImages: { source: string; reason: string }[] = []; try { userContent = await buildUserContent({ text: userInput, images: options.imageInputs, parseInlineImages: options.parseInlineImages, detail: options.imageDetail, maxLongSidePixel: options.imageMaxLongSidePixel, onInlineImageSkipped: (source, reason) => skippedInlineImages.push({ source, reason }), }); } catch (e) { // 走到这里只剩「显式传入的图」读失败(-p --image / 工具实况截图)——调用方明确要了这张图。 yield { type: 'error', error: `图片输入处理失败:${(e as Error).message}`, code: 'llm_error', }; return; } for (const skipped of skippedInlineImages) { yield { type: 'warning', message: `未作为图片附加:${skipped.source}(${skipped.reason}),已按普通文本处理。`, }; } let visionRequiredThisTurn = Array.isArray(userContent) && userContent.some((part) => part.type === 'image_url' || part.type === 'video_url'); if (visionRequiredThisTurn && provider.supportsVision === false) { yield { type: 'error', error: '当前模型已配置为不支持视觉输入,图片未发送。请切换到支持图片的模型。', code: 'llm_error', }; return; } // 1. 用户消息入栈(v2:填 timestamp,让 MessageList 的 turn 边界横线 // 能拿到首条 user 的真实时间,否则 fallback Date.now() 会丢失"提交时刻"语义) const userMessage: Extract = { role: 'user', content: userContent, ...(options.userAttachments?.length ? { attachments: options.userAttachments } : {}), ...(options.userBrowserReferences?.length ? { browserReferences: options.userBrowserReferences } : {}), timestamp: Date.now(), id: currentUserMessageId, ...(options.messageProvenance ? { provenance: options.messageProvenance } : {}), }; const alreadyCommitted = history.some((message) => message.role === 'user' && message.id === userMessage.id); if (!alreadyCommitted) { history.push(userMessage); // 立即通知 UI:用户消息已入栈,触发 bump 让 马上把它 commit 进 scrollback, // 不必等整轮 assistant 落定(保证用户输入第一时间置顶,符合 T-A-O-R 展示顺序)。 yield { type: 'user_message_committed', message: userMessage, deliveryId }; } // 反应式压缩自救:本 runQuery 内最多触发 MAX_REACTIVE_PER_QUERY 次(防本轮死循环); // 跨 runQuery 的连续失败由 reactiveCompact.ts 的 circuit breaker(consecutiveFailures)兜底。 let reactiveCount = 0; const MAX_REACTIVE_PER_QUERY = 3; // 上一轮 LLM 返回的真实 prompt token 数(done.promptTokens;provider 开 include_usage 才有)。 // 作为 autoCompact 的权威判据,校正本地估算的系统性低估;压缩后清空(历史已变,旧值失真)。 let lastPromptTokens: number | undefined; // ── 回合级资源账本 ──────────────────────────────────────────────── // ⚠️ 与 lastPromptTokens 生命周期**故意不同**:那个是「当前 history 有多大」的快照, // 压缩后必须清零;这个是「本回合总共花了多少」的累计,压缩不影响已经花掉的钱。 // ⚠️ 它只记账,**不参与任何控制流** —— loop 绝不因预算中断进行中的工具循环。 const turnUsage = { inputTokens: 0, outputTokens: 0, totalCalls: 0, reportedCalls: 0 }; const usageByScope: NonNullable = {}; const measuredChat = (scope: import('./types.js').TurnUsageScope): typeof chatFn => async function* (args) { const scoped = usageByScope[scope] ??= { inputTokens: 0, outputTokens: 0, totalCalls: 0, reportedCalls: 0 }; scoped.totalCalls++; turnUsage.totalCalls++; let reportedIn: number | undefined; let reportedOut: number | undefined; const valid = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0; try { // The host audience applies to every request, including compaction and recovery. for await (const event of chatFn({ ...args, conversationMode: runtimeContext.conversationMode ?? 'private', cacheRole: runtimeContext.profile === 'main' ? 'main' : 'fork', })) { if (event.type === 'done' || event.type === 'usage') { if (valid(event.promptTokens)) reportedIn = event.promptTokens; if (valid(event.outputTokens)) reportedOut = event.outputTokens; } yield event; } } finally { for (const ledger of [turnUsage, scoped]) { ledger.inputTokens += reportedIn ?? 0; ledger.outputTokens += reportedOut ?? 0; if (reportedIn !== undefined && reportedOut !== undefined) ledger.reportedCalls++; } } }; const usageSnapshot = (): TurnResourceUsage => ({ ...turnUsage, byScope: structuredClone(usageByScope), trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls, }); // 本次 runQuery 的稳定身份:回合事件与会话消息用它把「半截回答」和具体请求对上。 const turnId = crypto.randomUUID(); const sessionId = options.memoryContext?.sessionId; // 归档退化只报一次:每条超长结果都报会把上下文刷满,反而盖掉别的信号。 let archiveDegradedWarned = false; // 提示词缓存观测位(纯展示,不参与任何控制流)。与 lastPromptTokens 同生命周期: // 压缩后一并清空,避免把压缩前的命中数据挂到压缩后的新历史上误导排障。 let lastCachedPromptTokens: number | undefined; let lastCacheMissTokens: number | undefined; let lastCacheWriteTokens: number | undefined; let lastPromptCacheUsage: import('./types.js').PromptCacheUsage = { reported: false }; const replaceHistory = (messages: Message[]) => { projection.reset(); history.splice(0, history.length, ...messages); if (sessionState?.microCompact) resetCacheEdits(sessionState.microCompact); lastPromptTokens = undefined; lastCachedPromptTokens = undefined; lastCacheMissTokens = undefined; lastCacheWriteTokens = undefined; lastPromptCacheUsage = { reported: false }; }; const optimizationEvents: LoopEvent[] = []; toolCallContext.optimizeConversation = createConversationOptimizer({ history, provider, // This additional model call must contribute to the turn's resource ledger, // without replacing the main model's context/cache usage measurements. chat: measuredChat('manual_optimize'), protectedImageUserIds: () => new Set(toolCallContext.userInputs?.map(message => message.id)), promptCache: options.promptCache, replaceHistory, hasQueuedInput: options.hasQueuedInput, onCompacted: (event) => optimizationEvents.push(event), }); const interruption = (): Extract => { if (options.hasQueuedInput?.()) { pushQueuedInputMarker(history); return { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; } pushManualInterruptMarker(history); return { type: 'interrupted', reason: 'manual', usage: usageSnapshot() }; }; let turn = 0; let workStarted = false; while (turn < maxTurns) { turn++; /** 这一次模型调用的本地请求 ID;终态回执用它把消息与具体请求对上。 */ let requestId = crypto.randomUUID(); /** true = 流在没有显式终止事件的情况下 EOF(client 的兜底 done)。 */ let streamEndedWithoutTerminal = true; /** * 本回合的文本终态回执。`requestId` 指向产生这段文本的那次模型调用, * 诊断字段已脱敏;它只说明「文本完整吗、为什么没完整」,不参与交付判定。 */ const generationReceipt = ( status: GenerationReceipt['status'], shownChars: number, extra: Partial< Pick > = {}, ): GenerationReceipt => createGenerationReceipt({ status, turnId, requestId, sessionId, shownChars, ...extra }); const nextEnvironmentCwd = sessionState?.activeWorktree?.path ?? runtimeContext.cwd; if (nextEnvironmentCwd !== modelEnvironmentCwd) { invalidateRecall(); observedRuleScopes.clear(); pendingRuleScopes.clear(); } modelEnvironmentCwd = nextEnvironmentCwd; try { const rules = (await loadProjectPromptInstructions(modelEnvironmentCwd)) ?? ''; observedRuleScopes.set(resolve(modelEnvironmentCwd), rules); for (const scope of new Set([...observedRuleScopes.keys(), ...pendingRuleScopes])) { if (scope !== resolve(modelEnvironmentCwd)) observedRuleScopes.set(scope, (await loadProjectPromptInstructions(scope)) ?? ''); } pendingRuleScopes.clear(); const mergedRules = (await loadProjectPromptInstructions(modelEnvironmentCwd, [...observedRuleScopes.keys()])) ?? ''; currentTransientBundle = assembleContextBundle( [ ...(options.transientBundle?.fragments ?? []).filter( (f) => stillSelected(f) && f.id !== 'project.instructions' && f.id !== 'runtime.execution-environment', ), contextFragment({ id: 'runtime.execution-environment', kind: 'runtime', authority: 'host', priority: 100, required: true, atomic: true, content: `当前有效执行目录:${modelEnvironmentCwd}。此宿主快照替换旧执行目录;项目规则以本次快照为准,旧历史中的版本不再生效。${rules ? '' : '当前目录及父目录没有适用的项目规则文件,旧规则不得恢复。'}工具权限仍以本次有效工具集和宿主闸门为准。`, }), ...(mergedRules ? [ contextFragment({ id: 'project.instructions', kind: 'project', authority: 'constraint', priority: 90, required: true, atomic: true, content: mergedRules, }), ] : []), ], options.transientBundle?.diagnostics.budgetTokens, ); } catch (error) { yield { type: 'error', error: `无法加载完整项目规则,停止本轮:${(error as Error).message}` }; yield { type: 'turn_done', completionStatus: 'delivery_incomplete', usage: usageSnapshot() }; return; } const handoff = options.agentHandoff?.current(); if (handoff && handoff.kind !== 'help') { yield { type: 'turn_done', completionStatus: handoff.kind === 'result' ? 'completed' : 'delivery_incomplete', warning: handoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined, usage: usageSnapshot(), }; return; } const pendingInput = await takePendingMessages(); // Commit drained input before any asynchronous notification IO can fail. history.push(...pendingInput); for (const message of pendingInput) if (message.role === 'user') yield { type: 'user_message_committed', message, deliveryId, ...(options.steering && runtimeContext.profile === 'main' ? { inputSource: 'supplement' as const } : {}) }; history.push(...(await takeAgentNotifications(toolCallContext, options.agentNoticeDelivery)), ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds)); if (runtimeContext.profile === 'main') coordinationText = (await agentCoordinationContext(toolCallContext)).text; incrementTurn(sessionState?.microCompact); expireOldEntries(sessionState?.microCompact); // Path C 批量回收旧工具结果:可重放的观察类工具结果(Read/Grep/Bash…) // 超过阈值时只保留热尾部。必须在 buildContextBudgetPlan 之前跑——预算估算和 // autoCompact 判据直接看到瘦身后的历史,避免无谓的全量压缩。 // cacheEdits 模式(Anthropic 格式 + provider.cacheEdits):不改 history,删除目标 // 记入状态、由请求层组装 cache_edits 发送--服务端 KV 原地删除,前缀缓存完整保留。 // 本地估算的虚高部分(服务端已删内容)由 autoCompactIfNeeded 的 serverDeletedTokens // 校正,判据不会因此过早触发压缩。 const cacheEditsMode = provider.apiFormat === 'anthropic' && provider.cacheEdits === true; reclaimOldToolResults(history, sessionState?.microCompact, cacheEditsMode ? 'cacheEdits' : 'inline'); if (signal?.aborted) { pushManualInterruptMarker(history); const receipt = generationReceipt('interrupted', 0, { source: 'user_cancel' }); const marker = history[history.length - 1]; if (marker) { marker.generation = receipt; receipt.messageId = marker.id; } yield { type: 'generation_outcome', outcome: receipt }; if (!workStarted) { yield { type: 'error', error: '用户中断了任务', code: 'aborted', usage: usageSnapshot() }; } else { yield { type: 'interrupted', reason: 'manual', usage: usageSnapshot() }; } return; } if (options.hasQueuedInput?.()) { if (canSteer()) { turn--; continue; } pushQueuedInputMarker(history); const receipt = generationReceipt('interrupted', 0, { source: 'queued_input' }); const marker = history[history.length - 1]; if (marker) { marker.generation = receipt; receipt.messageId = marker.id; } yield { type: 'generation_outcome', outcome: receipt }; if (!workStarted) { yield { type: 'error', error: '收到新输入,取消当前任务', code: 'aborted', usage: usageSnapshot() }; } else { yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; } return; } const prepared = yield* prepareModelRequest({ history, provider, activeTools, effectiveToolSet, runtimeContext, sessionState, signal, lastPromptTokens, cacheEditsMode, options, chatFn: measuredChat('auto_compact'), protectedImageUserIds: new Set(toolCallContext.userInputs?.map(message => message.id)), usageSnapshot, replaceHistory, buildRequestTransientContext: (tools) => { currentEffectiveToolSet = tools; advisorNudge.setAvailable(tools.names.has('Advisor') && options.advisorReminders !== false); plannedView = buildRequestTransientContext(); lastRequestTransientContext = plannedView.budgetText; return lastRequestTransientContext; }, }); if (prepared.kind === 'interrupted') { yield interruption(); return; } if (prepared.kind === 'overflow') { yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('error') }; return; } currentEffectiveToolSet = prepared.currentEffectiveToolSet; // 3. 调 LLM 并组装 assistant 消息 trace('model_start'); let assistantText = ''; // Candidate text is private until the delivery gates allow publication. // Keep the compatibility event as a phase notice, never as a text retraction. function* preparationNotice( reason: Extract['reason'] | 'interrupted', receipt?: GenerationReceipt, ): Generator { const message: Message = { role: 'system', content: answerPreparationNotice(reason), id: crypto.randomUUID(), timestamp: Date.now(), _ephemeral: true, _uiProgress: true, ...(receipt ? { generation: receipt } : {}), }; if (receipt) receipt.messageId = message.id; history.push(message); yield { type: 'injected_message', message }; if (receipt) yield { type: 'generation_outcome', outcome: receipt }; } function* retireDraft( reason: Extract['reason'] | 'interrupted', receipt?: GenerationReceipt, ): Generator { yield* preparationNotice(reason, receipt); if (reason !== 'interrupted') yield { type: 'assistant_draft_discarded', reason, textLength: 0 }; } /** 按 index 累积 tool_calls(OpenAI 协议下 tool_calls 是分片返回的) */ const toolCallsByIndex: ToolCall[] = []; /** * 思维链累积器。三个 provider 字段名各管一份;最后哪个非空就挂哪个, * 多个非空就都挂上(不会冲突,下一轮请求时整个 message 透传给 API)。 */ let reasoningContent = ''; let reasoningString = ''; const reasoningDetails: unknown[] = []; /** Visible text is never retracted: whatever already streamed live is * committed before the turn moves on (interruption, error, new messages). */ function* commitLiveAnswer( presentation: 'final' | 'progress', receipt?: GenerationReceipt, ): Generator { const message: Extract = { role: 'assistant', // Only what the user actually saw: a box held back by the diagram gate // must not slip into history through an interruption. content: assistantText.slice(0, shownLength), ...(reasoningContent ? { reasoning_content: reasoningContent } : {}), ...(reasoningString ? { reasoning: reasoningString } : {}), ...(reasoningDetails.length > 0 ? { reasoning_details: reasoningDetails } : {}), timestamp: Date.now(), id: crypto.randomUUID(), presentation, ...(options.messageProvenance ? { provenance: options.messageProvenance } : {}), ...(receipt ? { generation: receipt } : {}), }; if (receipt) receipt.messageId = message.id; history.push(message); yield { type: 'assistant_message', message }; if (receipt) yield { type: 'generation_outcome', outcome: receipt }; } /** * R2:本轮 LLM 流的终止原因(来自 client 的 done.stopReason)。 * 'length' = 被 provider 因 max_tokens 截断 —— 收尾时据此给 warning, * 避免「半截答案」被静默当成正常 end_turn。 */ let lastFinishReason: 'stop' | 'tool_calls' | 'length' | 'unknown' | 'aborted' = 'unknown'; // Decided before the model writes anything: can a check still hold this // answer back? If not, it is irrevocable by construction and streams live // (visible text is never retracted). If one can — a required formal delivery // or an unresolved delegation — the candidate stays private until it passes // and is then published verbatim. Streaming everything and retracting on a // later check showed users drafts that vanished; buffering everything made // every answer appear as one block. The advisor is deliberately not a holder // any more: it is a reminder, so an answer never waits for it. // Correction count and delivery permission are different questions: once the // one corrective request has been spent, an open gate still holds the answer // back and publishes it as progress, never as a final answer. const checkMemoryReceipt = runtimeContext.profile === 'main' && !options.responseFormat && (toolCallContext.userInputs ?? []).some(m => explicitSave(m.text) || explicitForget(m.text)); const liveEligible = !checkMemoryReceipt && !options.responseFormat && runtimeContext.profile === 'main' && output.finalDelivery === 'stream' && !(formalDeliveryRequired && !resultPresented); // Unreadable delegation state also holds it back: "cannot read" is never // "nothing is pending". The final gate re-reads the ledger before publishing. // Responsibility belongs to the delivery target, not to whether the Agent // tool happens to be visible in this turn's tool set. const delegationMayHold = liveEligible && (await evaluateDeliveryGate(toolCallContext, deliveryId).then( (gate) => gate.kind !== 'ready', () => true, )); const liveFinal = liveEligible && !delegationMayHold; let liveStarted = false; let shownLength = 0; // Live answers on a diagram-rendering surface hold back a fence that could // be a text drawing until it closes, so a box can be corrected without // retracting anything (see loop/liveDiagramGate.ts). const diagramGate = liveFinal && output.diagrams.length > 0 && !diagramCorrectionAttempted && !requestKeepsTextDiagrams(userInput) ? new LiveDiagramGate() : undefined; function* releaseLive(final = false): Generator { const end = diagramGate ? diagramGate.releasable(assistantText, final) : assistantText.length; if (!liveStarted) { if (!answerTextStarted(assistantText.slice(0, end))) return; liveStarted = true; yield { type: 'stage_change', stage: 'streaming' }; } if (end > shownLength) { yield { type: 'text', delta: assistantText.slice(shownLength, end) }; shownLength = end; } } // 进入 LLM 流前:等首 token / reasoning,本质是 thinking yield { type: 'stage_change', stage: 'thinking' }; workStarted = true; try { // Private cache_edits pins protocol-level message indices across turns. const modelMessages = cacheEditsMode ? buildModelMessages(history, plannedView!.budgetText, userMessage.id) : projection.render(history, userMessage.id!, plannedView!); for await (const ev of measuredChat('main')({ provider, messages: modelMessages, tools: currentEffectiveToolSet.tools, signal, promptCache: options.promptCache, visionPolicy: visionRequiredThisTurn ? 'required' : 'optional-history', protectedImageUserIds: new Set(toolCallContext.userInputs?.map(message => message.id)), // cacheEdits 回收状态(同一会话级对象跨轮复用;compact 后由 resetCacheEdits 清空) ...(cacheEditsMode && sessionState?.microCompact ? { cacheEdits: sessionState.microCompact.cacheEdits } : {}), ...(options.responseFormat ? { responseFormat: options.responseFormat } : {}), })) { if (ev.type === 'text_delta') { assistantText += ev.delta; if (liveFinal) yield* releaseLive(); } else if (ev.type === 'tool_call_delta') { mergeToolCallDelta(toolCallsByIndex, ev); } else if (ev.type === 'reasoning_delta') { if (ev.field === 'reasoning_content' && ev.delta) { reasoningContent += ev.delta; yield { type: 'reasoning', delta: ev.delta }; } else if (ev.field === 'reasoning' && ev.delta) { reasoningString += ev.delta; yield { type: 'reasoning', delta: ev.delta }; } else if (ev.field === 'reasoning_details' && ev.items) { // reasoning_details 是结构化数组,没有 delta 字符串,跳过 yield reasoningDetails.push(...ev.items); } } else if (ev.type === 'usage') { if (typeof ev.promptTokens === 'number') lastPromptTokens = ev.promptTokens; } else if (ev.type === 'done') { // R2:记下流的终止原因。'length'(max_tokens 截断)会在本轮收尾时触发 warning。 lastFinishReason = ev.stopReason; // 没有显式终止事件的 EOF:文本不能算正常完成,工具调用也不能执行。 streamEndedWithoutTerminal = ev.endedWithoutTerminal === true; // 真实 prompt token(provider 开 include_usage 才有)→ 喂给下一轮 autoCompact 做权威判据 if (typeof ev.promptTokens === 'number') lastPromptTokens = ev.promptTokens; // 缓存命中观测:只在 provider 真实报告时才记录(undefined ≠ 0,见 types.ts 注释) if (typeof ev.cachedPromptTokens === 'number') lastCachedPromptTokens = ev.cachedPromptTokens; if (typeof ev.cacheMissTokens === 'number') lastCacheMissTokens = ev.cacheMissTokens; if (typeof ev.cacheWriteTokens === 'number') lastCacheWriteTokens = ev.cacheWriteTokens; if (ev.promptCacheUsage) lastPromptCacheUsage = ev.promptCacheUsage; } } } catch (e) { trace('model_error'); if ((e as Error).name === 'AbortError') { const receipt = generationReceipt('interrupted', liveStarted ? shownLength : 0, { source: options.hasQueuedInput?.() ? 'queued_input' : 'user_cancel', ...(lastFinishReason === 'aborted' ? { stopReason: 'aborted' as const } : {}), }); if (liveStarted) { yield* commitLiveAnswer('final', receipt); yield { type: 'warning', message: '回答未完整生成,已保留已显示的内容;未撤回或重新生成。' }; } else yield* retireDraft('interrupted', receipt); yield interruption(); return; } // prompt_too_long 反应式自救:压缩历史 → 同 turn 重发 LLM // LLM 看到压缩后的 9 段摘要 + 近期 verbatim 消息,能接着干活, // 不会丢失中途的工具调用上下文。已实时显示过文字时不重发(会重复输出)。 if (!liveStarted && isPromptTooLongError(e) && reactiveCount < MAX_REACTIVE_PER_QUERY) { reactiveCount++; yield { type: 'compact_start' }; yield { type: 'stage_change', stage: 'compacting' }; let result; try { result = await reactiveCompactIfApplicable( history, provider, e, sessionState?.reactive, signal, { chat: measuredChat('reactive_compact'), protectedImageUserIds: new Set(toolCallContext.userInputs?.map(message => message.id)) }, options.promptCache, ); } catch (error) { const recoveryFailure = classifyGenerationError(error, { aborted: signal?.aborted === true, }); const receipt = generationReceipt('error', 0, recoveryFailure); yield* retireDraft('interrupted', receipt); if (signal?.aborted || (error as Error).name === 'AbortError') { yield interruption(); return; } yield { type: 'error', code: 'llm_error', error: `上下文恢复失败:${(error as Error).message}`, usage: usageSnapshot() }; return; } // 仅当确实压下去了(after < before)才重试;否则(没压动 / 未恢复)退回错误路径,杜绝死循环。 const shrank = (result.after ?? 0) < (result.before ?? 0); if (result.recovered && shrank) { replaceHistory(result.messages); yield { type: 'compact_done', before: result.before ?? 0, after: result.after ?? 0, trigger: 'provider-overflow', mode: result.mode, degraded: result.degraded, ...(result.fallbackReason ? { fallbackReason: result.fallbackReason } : {}), ...(result.messagesRemoved !== undefined ? { messagesRemoved: result.messagesRemoved } : {}), ...(result.tokensFreed !== undefined ? { tokensFreed: result.tokensFreed } : {}), }; // 压缩完回到 LLM 调用 yield { type: 'stage_change', stage: 'thinking' }; turn--; // 不消耗 turn 配额,本轮重新走 continue; } // reactive 没压动或未恢复 → 退回正常错误路径 } // code='llm_error':终结性错误,stop_reason='error' const failure = classifyGenerationError(e, { aborted: signal?.aborted === true }); const receipt = generationReceipt('error', liveStarted ? shownLength : 0, { ...failure, ...(lastFinishReason !== 'unknown' ? { stopReason: lastFinishReason } : {}), }); if (liveStarted) { yield* commitLiveAnswer('final', receipt); yield { type: 'warning', message: '回答未完整生成,已保留已显示的内容;未撤回或重新生成。' }; } else yield* retireDraft('interrupted', receipt); yield { type: 'error', error: `LLM 调用失败:${(e as Error).message}`, code: 'llm_error', usage: usageSnapshot(), }; return; } trace('model_end'); // A tool round (e.g. loading a graphics skill) is part of the revision; // the draft is dropped only once the revised answer itself has arrived. if (toolCallsByIndex.length === 0) { diagramCorrectionDraft = ''; diagramContinuation = false; } if (lastFinishReason === 'aborted' || signal?.aborted || options.hasQueuedInput?.()) { const queued = options.hasQueuedInput?.() && !signal?.aborted; const receipt = generationReceipt('interrupted', liveStarted ? shownLength : 0, { source: queued ? 'queued_input' : 'user_cancel', ...(lastFinishReason !== 'unknown' ? { stopReason: lastFinishReason } : {}), }); if (liveStarted) { yield* commitLiveAnswer(queued ? 'progress' : 'final', receipt); if (lastFinishReason !== 'stop') yield { type: 'warning', message: '回答未完整生成,已保留已显示的内容;未撤回或重新生成。' }; } else yield* retireDraft('interrupted', receipt); if (queued) { // The preceding generation cannot publish a final answer or start its // old calls. Preserve any live text, then consume steering in this run; // delivery identity and background task ownership remain unchanged. if (canSteer()) continue; pushQueuedInputMarker(history); yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; } else { pushManualInterruptMarker(history); yield { type: 'interrupted', reason: 'manual', usage: usageSnapshot() }; } return; } // S2 防御:OpenAI 协议保证 tool_call 的 index 连续;万一某 provider 跳号产生稀疏数组, // 这里压实掉空洞,避免后续遍历 / 回填遇到 undefined(assistantMsg.tool_calls 与执行都用它)。 { const dense = toolCallsByIndex.filter((tc): tc is ToolCall => tc != null); if (dense.length !== toolCallsByIndex.length) { toolCallsByIndex.length = 0; toolCallsByIndex.push(...dense); } } // 流没有终止事件就 EOF:JSON 参数可能只是"看起来能解析"的半截。 // 执行写类工具或被截断的副作用操作无法回滚,所以宁可失败也不猜。 // finish_reason=length 同理:模型是被 token 上限掐断的,此刻的工具调用 // 参数可能已被截断,只是恰好还能解析成 JSON。 const invalidCallIdentity = toolCallsByIndex.some(call => !call.id.trim() || !call.function.name.trim()) || new Set(toolCallsByIndex.map(call => call.id)).size !== toolCallsByIndex.length; if (toolCallsByIndex.length > 0 && (invalidCallIdentity || !completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal))) { const truncated = lastFinishReason === 'length'; const invalidMessage = '响应流缺少有效且唯一的工具调用身份,未执行任何本批工具。'; const receipt = generationReceipt(truncated ? 'incomplete' : 'error', liveStarted ? shownLength : 0, { source: streamEndedWithoutTerminal ? 'transport_error' : 'provider_error', stopReason: lastFinishReason, errorDetail: invalidCallIdentity ? invalidMessage : truncated ? '回答因长度上限被截断,已跳过执行以避免不完整的工具参数产生副作用。' : '响应流在发出工具调用后未正常结束,已跳过执行以免重放半截参数。', }); if (liveStarted) yield* commitLiveAnswer('final', receipt); else yield* retireDraft('interrupted', receipt); yield { type: 'warning', message: invalidCallIdentity ? invalidMessage : truncated ? '回答因长度上限被截断,已跳过本轮工具调用;已显示的内容保留。' : '响应流未正常结束,已跳过本轮工具调用;已显示的内容保留。', }; yield { type: 'error', code: 'llm_error', usage: usageSnapshot(), error: invalidCallIdentity ? invalidMessage : truncated ? 'LLM 回答在工具调用完成前因长度上限截断,已跳过执行以避免不完整参数产生副作用。' : 'LLM 响应流在工具调用完成前中断,已跳过执行以避免半截参数产生副作用。', }; return; } if (liveFinal) { // Narration before a tool round, or no turn left to revise: show it all. if (diagramGate?.hit !== undefined && (toolCallsByIndex.length > 0 || turn >= maxTurns)) diagramGate.release(); yield* releaseLive(true); } const assistantMsg: Message = { role: 'assistant', content: assistantText.length > 0 ? assistantText : null, ...(toolCallsByIndex.length > 0 ? { tool_calls: toolCallsByIndex } : {}), ...(reasoningContent ? { reasoning_content: reasoningContent } : {}), ...(reasoningString ? { reasoning: reasoningString } : {}), ...(reasoningDetails.length > 0 ? { reasoning_details: reasoningDetails } : {}), timestamp: Date.now(), id: crypto.randomUUID(), ...(options.messageProvenance ? { provenance: options.messageProvenance } : {}), }; // 4. 没有工具调用 → 整轮交互结束 finalResponse: if (toolCallsByIndex.length === 0) { if (diagramGate?.hit !== undefined) { diagramCorrectionAttempted = true; diagramCorrectionDraft = assistantText; if (liveStarted) { // The text before the box stays exactly as shown, as its own message. diagramContinuation = true; yield* commitLiveAnswer('progress'); yield* preparationNotice('diagram_preparation'); } else yield* retireDraft('diagram_preparation'); continue; } // A boxed ASCII diagram on a surface that renders real diagrams: retire the // private draft once and let the model revise it, with the draft passed // back as internal material (asking it to "keep the rest" without showing // the rest made it answer from scratch). The kernel names no skill and // never writes a tool call the model did not make — it used to inject // Skill("dynamic-ui") into history under the model's name. Content checks // like this one and the ask correction apply only to private drafts; an // answer that already streamed live is never retracted. if ( !liveStarted && !diagramCorrectionAttempted && !options.responseFormat && runtimeContext.profile === 'main' && output.diagrams.length > 0 && turn < maxTurns && needsDiagramPreparation(assistantText, userInput) ) { diagramCorrectionAttempted = true; diagramCorrectionDraft = assistantText; yield* retireDraft('diagram_preparation'); continue; } if ( !liveStarted && !askCorrectionAttempted && runtimeContext.interactiveAsk && currentEffectiveToolSet.names.has('AskUserQuestion') && needsInteractiveQuestion(stripThinkBlocks(assistantText)) && turn < maxTurns ) { askCorrectionAttempted = true; yield* retireDraft('interactive_question'); continue; } const emptyResponse = stripThinkBlocks(assistantText).length === 0; // The same gate that decides publication. One corrective request may be // spent on an open/unknown gate, but spending it never grants delivery. const deliveryGate = runtimeContext.profile === 'main' ? await evaluateDeliveryGate(toolCallContext, deliveryId) : ({ kind: 'ready' as const, version: 'disabled' }); const pendingDelegations = deliveryGate.kind === 'pending' ? deliveryGate.tasks : []; const gateUnknown = deliveryGate.kind === 'unknown' ? deliveryGate.reason : ''; if ( !liveStarted && (pendingDelegations.length > 0 || Boolean(gateUnknown)) && !delegationCorrectionAttempted && turn < maxTurns ) { delegationCorrectionAttempted = true; coordinationText = gateUnknown ? `[交付状态未知] ${gateUnknown}。先恢复子任务账本的可读性(检查 Session 运行目录权限与记录完整性),不能声称全部完成。` : (await agentCoordinationContext(toolCallContext)).text; yield* retireDraft('formal_delivery'); continue; } // Do not drain any mailbox when we cannot make another request. const pendingNotices = turn < maxTurns ? [...(await takeAgentNotifications(toolCallContext, options.agentNoticeDelivery)), ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds)] : []; const pendingHuman = turn < maxTurns ? await takePendingMessages() : []; const pendingMessages = [...pendingHuman, ...pendingNotices]; const needsAnotherRequest = pendingHuman.length > 0 || pendingNotices.some(message => !isPriorTaskNotice(message)); if (pendingMessages.length && !needsAnotherRequest) { history.push(...pendingNotices); for (const message of pendingNotices) yield { type: 'injected_message', message }; } else if (pendingMessages.length) { // Commit synchronously before yielding: drained input cannot disappear // if a host stops consuming events. Old visible text precedes new input. const progressEvents = liveStarted ? [...commitLiveAnswer('progress')] : []; history.push(...pendingMessages); yield* progressEvents; for (const message of pendingHuman) if (message.role === 'user') yield { type: 'user_message_committed', message, deliveryId, ...(options.steering && runtimeContext.profile === 'main' ? { inputSource: 'supplement' as const } : {}) }; for (const message of pendingNotices) yield { type: 'injected_message', message }; continue; } // Notification collection above awaits IO: input may have arrived after // the mailbox was drained. Never publish an old final across that gap. if (options.hasQueuedInput?.()) { if (liveStarted) yield* commitLiveAnswer('progress'); if (canSteer()) continue; yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; return; } // A model occasionally writes a path/link in prose and stops without formally // presenting it. Give it one model-only corrective pass; the reminder is // transient and therefore never pollutes persisted conversation history. if ( !liveStarted && !emptyResponse && formalDeliveryRequired && !resultPresented && !deliveryCorrectionAttempted && turn < maxTurns ) { deliveryCorrectionAttempted = true; yield* retireDraft('formal_delivery'); continue; } let advisorFollowUp = false; if (!emptyResponse) { // A reminder, never a gate: the answer is already on its way to the user. // With enforcement 'followup' (weak models that never ask on their own) an // unreviewed substantive answer earns one more request in which the model is // asked to call Advisor itself; the warning is then left for that pass. if (turn < maxTurns && completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal) && advisorNudge.followUpDue(assistantText) && (await advisorFollowUpEnabled(options))) { advisorNudge.markFollowedUp(); advisorFollowUp = true; } else { const unreviewed = advisorNudge.unreviewedWarning(assistantText); if (unreviewed) yield { type: 'warning', message: unreviewed }; } } const memoryPublication = checkMemoryReceipt ? checkMemoryPublication(assistantText, evidenceLedger.snapshot()) : undefined; if (options.hasQueuedInput?.()) { if (liveStarted) yield* commitLiveAnswer('progress'); if (canSteer()) continue; yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; return; } const memoryWarning = memoryPublication?.warning; if (memoryPublication && memoryWarning) { // Preserve other work in the answer while explicitly correcting the // unsupported claim before publication, including non-streaming hosts. assistantText = memoryPublication.body + `\n\n【记忆状态】${memoryWarning}`; assistantMsg.content = assistantText; } if (emptyResponse) { // Recover once within the existing turn budget, retaining tool receipts and // advisor state. Never replay tools or expose an empty candidate as an answer. if (!resultPresented && !emptyResponseRecoveryAttempted && turn < maxTurns) { emptyResponseRecoveryAttempted = true; emptyResponseRecoveryReason = lastFinishReason === 'length' ? '输出额度耗尽' : lastFinishReason === 'unknown' ? '响应流缺少正常结束状态' : '响应为空或仅含思考内容'; const message: Message = { role: 'system', content: '正在恢复回答,已保留调查结果与工作进展。', id: crypto.randomUUID(), timestamp: Date.now(), _ephemeral: true, _uiProgress: true, }; history.push(message); yield { type: 'injected_message', message }; continue; } yield* retireDraft('empty_response'); } else { // Publication is a one-way boundary: the text that passed every gate is // exactly what the user sees and what history keeps — streamed live // when nothing could hold it back, otherwise published verbatim now. // It used to be regenerated by a second tool-free request: a third // text no gate had seen, at the cost of a full-context call. // // A closed gate does not silence the user: it publishes a clearly // labelled progress message plus the reason and recovery path, and the // message is never registered as the final answer. const publication = planFinalPublication({ gate: deliveryGate, formalDeliveryRequired, resultPresented, structuredOutput: Boolean(options.responseFormat), liveStarted, candidate: assistantText, shownLength, }); if (!liveStarted && !options.responseFormat && runtimeContext.profile === 'main' && output.finalDelivery === 'stream') yield { type: 'stage_change', stage: 'streaming' }; // Status before the body; text that already streamed stays visible but is // labelled progress and is never registered as the final answer. if (publication.warning) yield { type: 'warning', message: publication.warning }; // No await/yield between this check and final registration below. if (options.hasQueuedInput?.()) { if (liveStarted) yield* commitLiveAnswer('progress'); if (canSteer()) continue; yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; return; } assistantMsg.presentation = publication.presentation; if (publication.replaced) assistantMsg.content = publication.body; // 终态回执随消息落盘:截断/无终止 EOF 都不能算正常完成,但文本照常发布。 const finalReceipt = generationReceipt( completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal) ? 'completed' : 'incomplete', publication.shownChars, { ...(lastFinishReason !== 'unknown' ? { stopReason: lastFinishReason } : {}), ...(streamEndedWithoutTerminal ? { source: 'transport_error' as const } : {}), }, ); assistantMsg.generation = finalReceipt; finalReceipt.messageId = assistantMsg.id; trace('final_published'); history.push(assistantMsg); // `text` carries exactly what is published (candidate or runtime status // body); hosts that build the answer from `text` (-p, JSON) rely on it. if (!liveStarted && publication.body) yield { type: 'text', delta: publication.body }; yield { type: 'assistant_message', message: assistantMsg as Extract, }; yield { type: 'generation_outcome', outcome: finalReceipt }; } if (advisorFollowUp) { pushAdvisorFollowUpMarker(history); continue; } // R2:最终回答被 provider 因 max_tokens 截断(finish_reason='length')时, // 不能静默当正常 end_turn 收尾 —— 否则 -p 宿主会拿到半截答案却以为成功。 // 走通用 warning(text/json 都落 stderr,不污染 json 那一行 stdout 契约)。 if (lastFinishReason === 'length') { yield { type: 'warning', message: '⚠️ 模型回答可能被截断(finish_reason=length,触顶 max_tokens),本轮回答或不完整。' + '可调大模型的 max_tokens 上限,或让模型分段输出。', }; } // The final answer has already consumed the latest screenshot. Persist only a compact // marker so the next turn does not resend a large screen image. evictPriorVisionShots(history); const estimatedTokens = countMessagesTokens(history) + estimateToolsTokens(activeTools); const usedTokens = Math.min(provider.contextWindow, Math.max(lastPromptTokens ?? 0, estimatedTokens)); yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('complete') }; const claimValidation = validateFinalClaims(assistantText, evidenceLedger.snapshot()); if (memoryWarning) { claimValidation.verified = false; claimValidation.warnings.push(memoryWarning); } for (const warning of claimValidation.warnings) yield { type: 'warning', message: warning }; yield { type: 'context_usage', usedTokens, contextWindow: provider.contextWindow, remainingTokens: Math.max(0, provider.contextWindow - usedTokens), compactThreshold: modelInputLimit(provider), source: lastPromptTokens === undefined ? 'estimated' : 'actual', // 缓存观测只在有真实 usage 时才附带——估算路径没有缓存信息, // 不能拿估算值冒充命中率(见 types.ts 的 context_usage 注释)。 ...(lastPromptTokens !== undefined && lastCachedPromptTokens !== undefined ? { cachedPromptTokens: lastCachedPromptTokens } : {}), ...(lastPromptTokens !== undefined && lastCacheWriteTokens !== undefined ? { cacheWriteTokens: lastCacheWriteTokens } : {}), ...(lastPromptTokens !== undefined && lastCacheMissTokens !== undefined ? { cacheMissTokens: lastCacheMissTokens } : {}), promptCacheUsage: lastPromptCacheUsage, }; // 资源账本挂到**每一条** turn_done 出口上。⚠️ 别只挂在 'completed' 那条: // 失败、交付不全、声明未核实的回合照样烧了 token,漏掉它们会让预算系统性少算, // 而少算的方向恰好是「让循环继续跑」—— 这正是本仓库记过账的 // 「turn_done.completionStatus 被 print.ts 整条丢弃」同一类错误的反面。 const usage = usageSnapshot(); if (emptyResponse && !resultPresented) { const warning = emptyResponseRecoveryAttempted ? '自动恢复后仍未生成最终答复,已有进展已保留。可以继续本轮或检查模型服务。' : '本轮未生成最终答复,已有进展已保留。可以重试上一回合。'; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'no_answer', warning, usage }; } else if (pendingDelegations.length) { const warning = `必要子任务尚未收口:${pendingDelegations.map((r) => r.id).join(', ')}。本轮不能视为全部完成。`; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, pendingRequired: pendingRequiredSummary(pendingDelegations), usage, }; } else if (gateUnknown) { const warning = `无法确认子任务账本状态:${gateUnknown}。本轮不能视为全部完成。`; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage }; } else if (formalDeliveryRequired && !resultPresented) { const warning = '交付未完成:用户明确要求提供文件,但本轮没有成功提交可打开的文件结果。'; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage }; } else if (!completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal)) { const warning = '模型响应未完整结束,已有文字与工具结果已保留;不能将本轮或子任务记为成功完成。'; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage }; } else if (resultPresented && presentedResultUnverified) { const warning = '结果已提交,但至少一个文件尚未通过结构化验证。'; yield { type: 'warning', message: warning }; yield { type: 'turn_done', completionStatus: 'delivery_unverified', warning, usage }; } else if (!claimValidation.verified) { yield { type: 'turn_done', completionStatus: 'claims_unverified', warning: claimValidation.warnings.join('\n'), usage, }; } else { yield { type: 'turn_done', completionStatus: 'completed', usage, ...(emptyResponse ? { warning: '成果已提交,未生成文字总结;请查看已提交的成果。' } : {}), }; } return; } assistantMsg.presentation = 'progress'; trace('progress_published'); history.push(assistantMsg); yield { type: 'assistant_message', message: assistantMsg as Extract, }; // 5. 执行工具调用 // // R1:按 isConcurrencySafe 决定并发策略 —— 工具早就声明了这个字段,此前却没有 // 任何执行路径消费它(全程无条件并行),这里让它真正生效: // - 连续的并发安全工具形成执行段(Read/Grep/Glob/WebSearch/WebFetch 等) // → 并行:用事件队列把多个 worker 的 tool_start/tool_end 按真实完成顺序交错 yield。 // - 写类/未知工具是顺序屏障:前段完成后执行,再启动后段,不跨屏障重排。 // - 用户提问和 Advisor 之后的预生成调用仍暂缓,交还模型重新规划。 // 两种路径下,history 里的 tool 消息都严格按 toolCallsByIndex 索引顺序回填 // (OpenAI 协议要求 tool 消息与上一条 assistant 的 tool_calls 一一对应)。 yield { type: 'stage_change', stage: 'tool_executing' }; const readBudgets = planReadBudgets(prepared.remainingTokens, toolCallsByIndex, currentEffectiveToolSet.tools); let reservedReadChars = 0; const { runOne, failureReviews } = createToolExecutor({ options, runtimeContext, toolCallContext, readBudgets, onReadReserved: count => { reservedReadChars += count; }, currentEffectiveToolSet, advisorNudge, stallGuard, modelEnvironmentCwd, observedRuleScopes, pendingRuleScopes, currentUserMessageId: userMessage.id!, executeToolFn, }); let anyAborted = false; // Commit serial outcomes before the next tool starts: Advisor must see the // latest evidence and versions. Parallel batches commit in call order once // settled. Both paths use this single writer, avoiding duplicate observation. const commitOutcome = async function* ({ tc, result, executed }: WorkerOutcome): AsyncGenerator { if (executed && result.ok && !recallInvalidated) { const name = tc.function.name; if (['UpdateMemory', 'ForgetMemory', 'RememberMemory'].includes(name) || (name === 'MemoryMaintenance' && !getToolGateDetails(name, tc.function.arguments, toolCallContext)?.isReadOnly)) invalidateRecall(); } if (executed) advisorNudge.observeToolResult( tc, result, advisorSemanticsFor( tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }, ), ); if (executed) { evidenceLedger.record(tc.function.name, tc.function.arguments, result); } if (!result.ok && result.error === 'aborted') anyAborted = true; const browserArtifact = result.ok && result.metadata?.kind === 'browser_download' ? result.metadata.artifact : undefined; if ( result.ok && ((tc.function.name === 'PresentResult' && result.metadata?.kind === 'result_manifest') || browserArtifact) ) { resultPresented = true; // `not_run` only says that no optional, format-specific validator was // invoked. The PresentResult boundary has still checked the file and // persisted its fingerprint, so it must not downgrade a normal delivery. const manifest = result.metadata?.kind === 'result_manifest' ? result.metadata.manifest : browserArtifact; presentedResultUnverified ||= manifest?.files.some((file) => file.verification === 'failed') ?? false; } const actionHint = advisorNudge.takeActionHint(); const rawContent = result.ok ? result.content : `Error: ${result.error}`; const basePolicy = result.policy ?? getToolResultPolicy(tc.function.name); // 超大结果先归档再压缩:归档失败时保留原文,绝不因为磁盘问题破坏上下文。 const archived = result.ok && sessionState && !(basePolicy.boundedWindow && basePolicy.archiveRef) ? await archiveToolResult(rawContent, sessionState.microCompact.archiveKey, tc.function.name) : { content: rawContent, originalChars: rawContent.length }; // 归档退化必须发声:撞会话上限后每条超长结果都退回原文塞进上下文, // 也就是这个机制本来要解决的问题原样回来了 —— 静默的话没人会发现。 if (archived.degraded && !archiveDegradedWarned) { archiveDegradedWarned = true; yield { type: 'warning', message: archived.degraded === 'session-limit' ? '工具结果归档已达本会话上限,后续超长结果将直接进入上下文(归档不再生效)。建议 /new 开新会话。' : '工具结果归档写盘失败,后续超长结果将直接进入上下文。请检查磁盘空间与权限。', }; } const policy = archived.archiveRef ? { ...basePolicy, archiveRef: archived.archiveRef, originalChars: archived.originalChars } : basePolicy; // 微压缩仅对成功结果走;policy 会保护高价值结果,避免不可逆中段丢失。 const compacted = result.ok ? microCompact(tc.function.name, archived.content, sessionState?.microCompact, policy) : rawContent; const content = actionHint ? `${compacted}\n\n${actionHint}` : compacted; history.push({ role: 'tool', display_ok: result.ok, content, tool_call_id: tc.id, tool_result_policy: policy, toolResultDisposition: executed ? 'executed' : !result.ok && result.disposition === 'deferred' ? 'deferred' : 'not_executed', ...(result.metadata ? { display_metadata: result.metadata } : {}), timestamp: Date.now(), id: crypto.randomUUID(), ...(options.messageProvenance ? { provenance: options.messageProvenance } : {}), }); }; const settled = yield* executeToolBatch({ toolCallsByIndex, currentEffectiveToolSet, options, runOne, commitOutcome, context: toolCallContext, onDeferredAdvisorReads: calls => { for (const [call, amount] of planReadBudgets( prepared.remainingTokens - 2 * reservedReadChars, calls, currentEffectiveToolSet.tools, )) readBudgets.set(call, amount); }, }); // Publish after every pending tool result has been appended, so hosts see a // complete protocol chain when persisting the compacted history. while (optimizationEvents.length > 0) yield optimizationEvents.shift()!; const childHandoff = options.agentHandoff?.current(); if (childHandoff && childHandoff.kind !== 'help') { yield { type: 'turn_done', completionStatus: childHandoff.kind === 'result' ? 'completed' : 'delivery_incomplete', warning: childHandoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined, usage: usageSnapshot(), }; return; } // Failures are recorded at execution time; batch observation now supplements // them with the existing no-progress signal without counting attempts twice. const stall = failureReviews.at(-1) ?? (turn + 1 < maxTurns ? stallGuard.observe( settled.map((item) => item.tc), settled.map((item) => item.result), assistantText, ) : { stalled: false as const }); if (stall.stalled) { const message = stall.reason === 'repeated_failure' ? '同一问题两次尝试失败,请停止原样重试;顾问可用时,继续解决或交付前先咨询,由主 Agent 自行核验和决策。只读诊断仍可继续。' : '检测到连续工具轮次没有产生新文本或新结果;请切换路径或咨询 Advisor。'; if (stall.reason !== 'repeated_failure') advisorNudge.notifyStalled(stall.signature ?? stall.reason ?? 'no_progress'); yield { type: 'warning', message }; } // 关键节点截图回填:把工具附带的实况截图作为一条带图 user 消息喂给(视觉)模型自我核验, // 并 yield injected_message 让宿主在对话里即时展示这张实况截图。 // 纯增强:读图/编码等任何失败都静默跳过,绝不打断本轮(与工具「失败不抛异常」一致)。 let injectedShot: Message | null = null; try { injectedShot = await injectVisionFollowups(history, settled, provider); } catch { /* 截图回填失败不影响主流程 */ } // The history copy is intentionally downgraded after the turn. Emit a detached snapshot // so TUI/Desktop stores do not see their already-rendered image mutate underneath them. if (injectedShot) { visionRequiredThisTurn = true; yield { type: 'injected_message', message: structuredClone(injectedShot) }; } if (anyAborted || signal?.aborted) { if (!signal?.aborted && options.hasQueuedInput?.() && canSteer()) continue; if (options.hasQueuedInput?.()) { pushQueuedInputMarker(history); yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; } else { pushManualInterruptMarker(history); yield { type: 'interrupted', reason: 'manual', usage: usageSnapshot() }; } return; } if (options.hasQueuedInput?.()) { if (canSteer()) continue; pushQueuedInputMarker(history); yield { type: 'interrupted', reason: 'queued_input', usage: usageSnapshot() }; return; } // 6. 继续 while 让模型看到 tool_result 后继续推理 } // code='max_turns':撞最大轮数上限而终结,stop_reason='max_turns' yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('max_turns') }; yield { type: 'error', error: `达到最大轮数 ${maxTurns},提前结束(防止失控)。如果合理可以提高 maxTurns。`, code: 'max_turns', usage: usageSnapshot(), }; }