/** * ============================================================ * src/session/runTurn.ts —— Headless 单 turn 执行器 * ------------------------------------------------------------ * 把"读 session 文件 → 跑 runQuery → 写 session 文件"封装成单一入口。 * PR 4 HTTP server 的每个请求 handler 用它即可,无需自己拼装。 * * 调用方契约: * - sessionFile: per-chat 隔离的上下文文件路径(参见 sessionPath.sessionFileFor) * - systemPrompt: 当 loadContext 返回 null(首次会话)时用它建初始 history; * 未提供则用空数组开局(少数 case 才合理,例如不需要 system prompt) * - sessionState: 多并发场景必须 per-request 创建一份,避免不同 chat 串扰 * - signal: 调用方持有 AbortController,断开/超时时主动 abort * * 落盘策略: * 用 try/finally 包住 runQuery;不管成功、抛错、还是被中断都保存当前 * history。中断时 loop.ts 内部会先把"用户按下了 ESC/Ctrl+C"标记 * 消息追加到 history,所以落盘的也是合法且完整的会话状态。 * ============================================================ */ import { acquireContextLock } from '../context/contextLock.js'; import { createLifecycleTrace } from '../runtime/lifecycleTrace.js'; import { loadAgentNoticeDelivery, loadContext, saveContext } from '../context/persistContext.js'; import { startTurnJournal } from '../memory/turnJournal.js'; import { createLearningModel } from '../memory/learningModel.js'; import type { PluginEvent } from '../plugins/pluginApi.js'; import { runWithPlugins } from '../plugins/pluginRunner.js'; import { captureCommandReply, commandRequest } from './commandTranscript.js'; import { upsertStableSystemMessage } from '../prompts/stableSystemPrompt.js'; import type { ImageDetail, ImageInputSpec, LoopEvent, Message, MessageAttachmentRef, MessageBrowserReference, Provider, } from '../types.js'; import type { SessionState } from './sessionState.js'; export interface RunTurnOptions { userInput: string; provider: Provider; sessionFile: string; systemPrompt?: string; sessionState?: SessionState; signal?: AbortSignal; maxTurns?: number; runtimeContext?: import('../runtime/agentRuntimeContext.js').AgentRuntimeContext; allowedTools?: import('../loop.js').RunQueryOptions['allowedTools']; /** * 本回合实际可调用的工具对象池(不只是名字)。缺省时 `loop.ts` 退回 `ALL_TOOLS` * 静态注册表,装不下按回合动态构造的工具(群协作工具、每次都要闭包捕获当次 * owner/群 id/回复回调)。见 `pluginRunner.ts` 里这个字段的完整头注。 */ availableTools?: import('../loop.js').RunQueryOptions['availableTools']; /** DI:透传给 runWithPlugins→runQuery(仅测试用,生产不传走默认实现)。 * 让测试用显式注入替代 mock.module(loop.js)——后者会全局泄漏污染其它测试文件。 */ chat?: import('../plugins/pluginRunner.js').PluginRunnerOptions['chat']; executeTool?: import('../plugins/pluginRunner.js').PluginRunnerOptions['executeTool']; commitFormalDelivery?: import('../plugins/pluginRunner.js').PluginRunnerOptions['commitFormalDelivery']; /** 工具执行闸门(生产用):透传给 runWithPlugins→runQuery。见 src/toolGate.ts。 */ toolGate?: import('../plugins/pluginRunner.js').PluginRunnerOptions['toolGate']; /** 只对本次模型回合可见,不写入 session。 */ transientContext?: import('../plugins/pluginRunner.js').PluginRunnerOptions['transientContext']; transientBundle?: import('../plugins/pluginRunner.js').PluginRunnerOptions['transientBundle']; promptCache?: import('../plugins/pluginRunner.js').PluginRunnerOptions['promptCache']; userAttachments?: MessageAttachmentRef[]; inputResources?: readonly import('../types.js').InvocationResource[]; /** Optional host execution identity, separate from Session and message identity. */ executionId?: string; /** Stable message identity supplied by a host/runtime request. */ userMessageId?: string; /** Explicit delivery target chosen by the host; see RunQueryOptions.deliveryId. */ deliveryId?: string; messageProvenance?: import('../types.js').ConversationProvenance; userBrowserReferences?: MessageBrowserReference[]; imageInputs?: ImageInputSpec[]; parseInlineImages?: boolean; imageDetail?: ImageDetail; imageMaxLongSidePixel?: number; browserRun?: import('../types.js').ToolCallContext['browserRun']; computerRun?: import('../types.js').ToolCallContext['computerRun']; computerIntervention?: import('../types.js').ToolCallContext['computerIntervention']; memoryContext?: import('../loop.js').RunQueryOptions['memoryContext']; /** Explicit history for an isolated, non-persistent turn. */ initialHistory?: Message[]; /** Defaults to true. False avoids reading, locking, or writing sessionFile. */ persist?: boolean; /** Host setup runs after loading history under the session lock. */ prepare?: (history: Message[]) => Promise>; /** Release turn-owned resources before releasing the session lock. */ cleanup?: () => Promise; strictPersistence?: boolean; } /** * 已有历史时,用调用方新算好的 systemPrompt(含当前日期/实时扫描的 skills·plugins 清单/ * 项目指令)替换旧的 system 消息,其余历史原样保留——与 ui/Root.tsx 的 TUI 启动逻辑、 * `refreshStableSystemPrompt()` 行为一致。堵上 headless 会话(cron-runner * 纯文本 action 等长期复用同一 sessionFile 的调用方)系统提示词只在首次开会话时生效、 * 此后永久冻结的口子——此前的行为是"已有历史就完全忽略新 systemPrompt",日期/skills/ * plugins/项目指令都不会再刷新,与"运行时实时扫描"的设计承诺矛盾。 * * 没有 loaded(全新会话)走原逻辑;调用方未传 systemPrompt 时不触碰已有历史(向后兼容)。 * * ★ 提示词缓存不变量:调用方传进来的 systemPrompt **必须是稳定层** * (buildBaseSystemPrompt,不含日期/Advisor 状态/记忆召回)。否则这里每轮重写 * history[0] 就会让 system 消息字节逐轮变化,provider 的前缀缓存从第一个 token * 起全部失配 —— 本函数是 headless/cron/Desktop 路径上最隐蔽的一处缓存杀手。 * 易变内容改走 opts.transientContext(loop 只装饰当前用户消息的模型副本)。 * 稳定层是确定性的,所以这里的"每轮刷新"退化成逐字节相同的 no-op, * 既保住了"运行时实时扫描"的承诺,又不破坏缓存。 */ function buildInitialHistory( loaded: Message[] | null, systemPrompt: string | undefined, ): Message[] { const history = loaded ? [...loaded] : []; if (systemPrompt) upsertStableSystemMessage(history, systemPrompt); return history; } export async function* runTurn( opts: RunTurnOptions, ): AsyncGenerator { const persist = opts.persist !== false; const release = persist ? await acquireContextLock(opts.sessionFile, opts.signal) : async () => {}; try { yield* runLockedTurn(opts, persist); } finally { try { await opts.cleanup?.(); } finally { await release(); } } } /** Initialization is also inside the lock lifetime; failures must not strand it. */ async function* runLockedTurn(opts: RunTurnOptions, persist: boolean): AsyncGenerator { const loaded = opts.initialHistory ?? (persist ? await loadContext(opts.sessionFile) : null); const agentNoticeDelivery = persist ? await loadAgentNoticeDelivery(opts.sessionFile) : undefined; const history: Message[] = buildInitialHistory(loaded, opts.systemPrompt); if (opts.prepare) opts = { ...opts, ...await opts.prepare(history) }; const historyStart = history.length; const userMessageId = opts.userMessageId ?? crypto.randomUUID(); // 会话原文记账:实现在 src/memory/turnJournal.ts(TUI 的 useChat 用同一份), // 刻意不下沉到 runQuery —— 子 Agent 与 workflow 步也调 runQuery,记在那里会把 // 子任务提示词当成"用户说的话"污染历史检索。 const journal = await startTurnJournal({ memoryContext: opts.memoryContext, cwd: opts.runtimeContext?.cwd, userInput: opts.userInput, history: [...history], learning: { model: createLearningModel(opts.provider, opts.chat), signal: opts.signal }, userMessageId, }).catch(error => { process.stderr.write(`[minimal-agent memory] 回合记忆初始化失败:${(error as Error).message}\n`); return null; }); let completedNormally = false; const trace = createLifecycleTrace('host'); let hostFailed = false; try { const commandReply = opts.userInput.trim().startsWith('/') ? captureCommandReply(userMessageId) : null; if (commandReply) { const request = commandRequest(opts.userInput, userMessageId); history.push(request); if (persist) await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence, agentNotices: agentNoticeDelivery }); yield { type: 'injected_message', message: request }; } for await (const event of runWithPlugins(opts.userInput, { executionId: opts.executionId, provider: opts.provider, history, signal: opts.signal, maxTurns: opts.maxTurns, runtimeContext: opts.runtimeContext, allowedTools: opts.allowedTools, availableTools: opts.availableTools, sessionState: opts.sessionState, agentNoticeDelivery, chat: opts.chat, executeTool: opts.executeTool, commitFormalDelivery: opts.commitFormalDelivery, toolGate: opts.toolGate, transientContext: opts.transientContext, transientBundle: opts.transientBundle, promptCache: opts.promptCache, userAttachments: opts.userAttachments, inputResources: opts.inputResources, userMessageId, deliveryId: opts.deliveryId, messageProvenance: opts.messageProvenance, userBrowserReferences: opts.userBrowserReferences, imageInputs: opts.imageInputs, parseInlineImages: opts.parseInlineImages, imageDetail: opts.imageDetail, imageMaxLongSidePixel: opts.imageMaxLongSidePixel, browserRun: opts.browserRun, computerRun: opts.computerRun, computerIntervention: opts.computerIntervention, memoryContext: opts.memoryContext, })) { journal?.observe(event); const commandResult = commandReply?.(event); if (commandResult) { history.push(commandResult); yield { type: 'injected_message', message: commandResult }; } // Stage records are user-visible history, not model instructions. Checkpoint // at stage boundaries so a Runtime restart does not lose the whole workflow. if (persist && (['user_message_committed', 'assistant_message', 'compact_start', 'turn_done'].includes(event.type) || (event.type === 'injected_message' && event.message && typeof event.message === 'object' && 'role' in event.message && event.message.role === 'system' && '_uiProgress' in event.message && event.message._uiProgress === true))) { trace('save_start'); try { await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence, agentNotices: agentNoticeDelivery }); trace('save_end'); } catch (error) { trace('save_error'); throw error; } } if (event.type === 'turn_done') trace('turn_done'); yield event; } completedNormally = true; } catch (error) { hostFailed = true; journal?.observe(opts.signal?.aborted ? { type: 'interrupted' } : { type: 'error', code: 'host_error' }); throw error; } finally { if (!completedNormally && !hostFailed) journal?.observe({ type: 'interrupted' }); trace('memory_start'); await journal?.finish(history, historyStart).catch(error => { process.stderr.write(`[minimal-agent memory] 本轮记忆收尾失败,不影响会话落盘:${(error as Error).message}\n`); }); trace('memory_end'); if (persist) await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence, agentNotices: agentNoticeDelivery }); } }