@roll-agent/runtime 0.17.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{buildFileToolset as h}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as m}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as g,EXEC_LIST_NAME as v,EXEC_POLL_NAME as f,buildSessionExecToolset as y}from"../tool-bridge/session-exec-tool.js";import{SessionManager as T}from"../bash/session/session-manager.js";import{isTerminalSessionState as C}from"../bash/session/types.js";import{withCleanEnv as k}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as b,SESSION_CANCELLATION_REASONS as x,TURN_TIMEOUT_ABORT_REASON as S,USER_CANCELLATION_ABORT_REASON as I,createTurnCancellationMessage as M,isTurnTimeoutAbortReason as E,stripTurnCancellationMetadata as w}from"../types/cancellation.js";import{ToolRegistry as P}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as R,TOOL_OUTCOME_KINDS as q,createToolResult as A,failedToolResult as N,isNormalizedToolResult as O,normalizeToolResult as $,readDisplayOutput as j,readToolOutcome as W}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as D}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as L,prepareToolExecutionRecordForPersistence as F,redactSecretText as U,toRedactedToolExecutionRecordSummary as V}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as _,ToolExecutionCoordinator as G}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as z}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as B,compactMessages as H,CompactionDraftFallbackError as K,estimateMessagesTokens as Y,estimateTextTokens as Q,isCompactionSummaryAcknowledgement as X,readCompactionSummaryPayload as Z}from"./compactor.js";import{AsyncEventQueue as ee}from"./event-queue.js";import{applyExplicitSkillContext as te,attachExplicitSkillCheckpoint as se,prepareExplicitSkillContext as oe,readExplicitSkillCheckpoint as ie,stripExplicitSkillCheckpoints as ne}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as re,createToolLedgerGapRecoveryMessage as ae,materializeCancelledTurnRecoveryMessages as ce,stripCancelledTurnRecoveryMessages as le}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as ue,CAPABILITY_TOOL_ROLES as pe,buildEffectiveCapabilityTurnContext as de,buildEffectiveCapabilityManifest as he,findCapabilityToolId as me}from"./capability-manifest.js";import{buildCapabilityTurnReminder as ge,buildChatSystemPromptFromManifest as ve}from"./system-prompt.js";import{buildCompactionCheckpointReminder as fe,buildCompactionToolState as ye,COMPACTION_CHECKPOINT_VERSION as Te,createCompactionCheckpoint as Ce,createCompactionSummary as ke,createCheckpointSemanticReminderProjection as be,findLatestRealUserGoal as xe,resolveActiveCompactionConstraints as Se,TRANSCRIPT_MESSAGE_PROVENANCES as Ie}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Me,buildCompactionSemanticEvidenceRegistry as Ee,mergeCompactionSemanticState as we,replaceCompactionSemanticConstraints as Pe,replaceCompactionSemanticGoal as Re,renderCompactionSemanticSummary as qe,seedCompactionSemanticConstraints as Ae,seedLegacyCompactionSnapshotUncertainties as Ne,validateCompactionModelDraft as Oe}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as $e,repairActiveToolProtocol as je}from"./tool-protocol-repair.js";import{buildTranscriptToolset as We}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as De}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Le}from"../tool-bridge/user-input-tool.js";const Fe=6e3,Ue=3e5,Ve=4,_e=2,Ge=1,ze={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Je="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Be=1024,He="AI_InvalidToolInputError:",Ke={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Ye(t){const s=[...t];if(s.length<=Be)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Be-[...o].length).join("")}${o}`}function Qe(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function Xe(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function Ze(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function et(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function tt(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function st(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function ot(e){return e instanceof Error?e.message:String(e)}function it(e){const t=ie(e.message),[s]=ne([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(r(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function nt(e){return JSON.stringify(e)??String(e)}function rt(e){const t=F(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:nt(t.input.value),resultSummary:nt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===q.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function at(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==Z(e.content)||"assistant"===e.role&&X(e.content)}function ct(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=Z(e.content);if(void 0!==t)return 0===t.length?[]:[U(t)]}return"assistant"===e.role&&X(e.content)?[]:[U(it({sequence:t,provenance:Ie[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!at(e)).length}}function lt(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function ut(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===Te?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function pt(e,t){return t.aborted?Promise.reject(t.reason):new Promise((s,o)=>{let i=!1;const n=e=>{i||(i=!0,t.removeEventListener("abort",r),e())},r=()=>n(()=>o(t.reason));t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(e=>n(()=>s(e)),e=>n(()=>o(e)))})}function dt(e){return ot(j(e))}function ht(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(He)?q.invalidInput:q.toolFailed}function mt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>W(e.output).kind===q.userRejected)??!1}function gt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(ot(e))}function vt(e){const t=e.inputTokenDetails?.cacheReadTokens,s=e.inputTokenDetails?.cacheWriteTokens,o=e.outputTokenDetails?.reasoningTokens;return{...void 0!==e.inputTokens?{inputTokens:e.inputTokens}:{},...void 0!==e.outputTokens?{outputTokens:e.outputTokens}:{},...void 0!==e.totalTokens?{totalTokens:e.totalTokens}:{},...void 0!==t?{cachedInputTokens:t}:{},...void 0!==s?{cacheWriteTokens:s}:{},...void 0!==o?{reasoningTokens:o}:{}}}function ft(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function yt(e,t){const s=ft(e.cachedInputTokens,t.cachedInputTokens),o=ft(e.cacheWriteTokens,t.cacheWriteTokens),i=ft(e.reasoningTokens,t.reasoningTokens);return{inputTokens:(e.inputTokens??0)+(t.inputTokens??0),outputTokens:(e.outputTokens??0)+(t.outputTokens??0),totalTokens:(e.totalTokens??0)+(t.totalTokens??0),...void 0!==s?{cachedInputTokens:s}:{},...void 0!==o?{cacheWriteTokens:o}:{},...void 0!==i?{reasoningTokens:i}:{}}}function Tt(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function Ct(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function kt(e,t){return void 0!==e?e:E(t)?x.timeout:x.runtime}function bt(e){return e.flatMap(e=>{if("assistant"!==e.role||!Array.isArray(e.content))return[e];const t=e.content.filter(e=>"reasoning"!==e.type);return 0===t.length?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function xt(e,t,s){for(const o of Object.keys(t))e[o]=s}function St(e,t,s){const o={[g]:pe.sessionCommand,[f]:pe.sessionPoll,[v]:pe.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function It(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;gate=new z;userInputInteractions=new De;toolCoordinator=new G;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?bt(e.initialMessages):[];this.messages=[...je(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?ct(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=ut(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)at(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Ie[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName));const o=new P,i={},n=Le({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,xt(i,n.tools,pe.userInput);const r=e.readCheckpointTranscript?We(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};xt(i,r,pe.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};xt(i,a,pe.skill);const c=new J,l=e.fileTools?h(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(xt(i,l.readTools,pe.fileRead),xt(i,l.editTools,pe.fileEdit),xt(i,l.verifyTools,pe.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},g=e.bashClassifier?{classifier:e.bashClassifier}:{},v=e.bash?m(e.bash,o,d,g):{};xt(i,v,pe.shell),e.bashSession&&(this.sessionManager=new T({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:k(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity}));const f=e.bashSession&&this.sessionManager?y({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...g,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};St(i,f,o);const C=e.agentInstall,b=C?p({catalog:C.catalog,install:async(e,t)=>{const s=await C.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};xt(i,b,pe.agentInstall);const x=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);xt(i,x.tools,pe.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...v,...f,...b,...x.tools},this.registry=x.registry,this.toolRoles=i,this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return he({tools:this.tools,toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??ue.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=ve(this.capabilityManifest,{...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);xt(this.toolRoles,t.tools,pe.agent),this.tools={...this.tools,...t.tools},this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);xt(this.toolRoles,e,pe.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=n(e),s=new ee;this.emit=e=>s.push(e);const o=Qe();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:ot(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new ee;this.emit=e=>t.push(e);const s=Qe();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:ot(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${ot(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:ot(t)})}if(s.aborted||s.abortController.signal.aborted)return l=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(e,s,l,r);e.push({type:"message-start",messageId:t()}),void 0!==this.turnTimeoutMs&&(s.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),u=setTimeout(()=>{s.abortController.signal.aborted||(this.captureCancellationActivity(s),s.aborted=!0,s.cancellationReason=x.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(S))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=oe({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},m=d.skillNames.length>0?se(h,d):h;let g={};try{g=await pt(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(m),s.cancellationReason=kt(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:ot(t)})}const v=de(this.capabilityManifest,{explicitSkillNames:d.skillNames,...g.ruleIds?{ruleIds:g.ruleIds}:{},...g.vcs?{vcs:g.vcs}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=v;const f=ge(v);let y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||this.messages.push(m);const n=me(this.capabilityManifest,pe.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:Q(u),h=ne(w(ce(this.messages))),g=It(d.skillNames.length>0?te(h,d):h,u?`${f}\n\n${u}`:f);this.debug(e,"model","calling streamText",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let v=0;const T=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.tools,prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),mt(),this.stopOnContextPressure(s)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(s,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:s.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{Xe(s,e),v=Y(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)Xe(s,t)}});let C;try{C=T()}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!gt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,m,!1,r),void e.push({type:"error",stage:"execute",message:ot(t)})}this.debug(e,"model","streamText returned",r);let k,b,S,I,M,P,R,A="",j="",W=!1,F=0,U=!1,V=!1;const _=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of C.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=x.runtime;break}switch(V||(V=!0,this.clearDebugTimer(_),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!W){const s=j+t.text;if(Ct(s,d.userPrompt)){j=s;break}if(j.length>0){const s=j+t.text;j="",A+=s,e.push({type:"text-delta",delta:s});break}}A+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{W=!0,j="";const o=this.trackPendingToolCall(s,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));e.push({type:"tool-call",toolCallId:t.toolCallId,agentName:o.agentName,toolName:o.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=s.pendingToolCalls.get(t.toolCallId),n=O(t.output)?t.output:$(t.output),r=n.outcome,a=n.display,c=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==q.userRejected&&r.kind!==q.policyDenied&&r.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===q.success&&void 0!==i&&this.rememberCompactionResources(c,i.resources),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,outcome:r,display:a,output:a,isError:r.kind!==q.success}),s.aborted||s.abortController.signal.aborted||r.kind!==q.userRejected||(R=dt(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=ht(t.error),n=(i===q.invalidInput?D(t.error):void 0)??dt(t.error),r=N(i,n,{raw:t.error}),a=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:n,isError:!0});break}case"finish-step":{const s=vt(t.usage);b=Tt(b,s.inputTokens),S=s.outputTokens,F+=1,M=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(I=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!W&&j.length>0&&(A+=j,e.push({type:"text-delta",delta:j}),j=""),k=vt(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||E(t.error)){s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,t.error);break}U=gt(t.error),U&&(this.needsCompaction=!0),P=ot(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||E(e)?(s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,e)):(U=gt(e),U&&(this.needsCompaction=!0),P=ot(e))}finally{this.clearDebugTimer(_)}if(this.debug(e,"model","fullStream finished",r,{textChars:A.length}),void 0!==P){if(this.messages.splice(l),U){const t=0===A.length&&!W,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${P}${a}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:P})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=kt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let G;this.debug(e,"model","awaiting response messages",r);const z=this.scheduleDebug(e,"model","still awaiting response messages",r);try{G=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(z),this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=gt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===A.length&&!W,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${ot(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:ot(t)})}finally{this.clearDebugTimer(z)}if(this.debug(e,"model","response messages ready",r,{responseMessages:G.length}),this.isTurnAborted(s))return s.cancellationReason=kt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const J=bt(G);if(this.messages.push(...J),void 0!==R){const t=0===A.length?R:`\n${R}`;A+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:R})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),st(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),k&&(this.sessionUsage=yt(this.sessionUsage,k));const B=b??k?.inputTokens;void 0!==B&&(this.lastInputTokens=B,this.lastStepOutputTokens=S,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,B-Y(this.messages)+(S??0)+v-p)),s.completedStepCount+=F;const H=s.completedStepCount>=this.maxSteps&&"tool-calls"===M;if(e.push({type:"message-finish",text:A,...k?{totalUsage:k}:{},sessionUsage:{...this.sessionUsage},...void 0!==b?{contextInputTokens:b}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:ot(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=kt(s.cancellationReason,s.abortController.signal.reason??t),void(void 0!==l?this.persistCancelledTurn(e,s,l,r):this.emitCancellation(e,s));void 0!==l&&this.messages.splice(l),this.debug(e,"turn","error",r,{message:ot(t)}),e.push({type:"error",stage:"execute",message:ot(t)})}finally{void 0!==u&&clearTimeout(u),this.toolCoordinator.finishTurn(),this.activeTurn===s&&(this.activeTurn=void 0),e.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)at(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Ie[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=ae(e);this.messages.push(s);try{this.persistMessages([s],"recovery_evidence")}catch(e){throw this.messages.splice(t),e}}persistContextFailure(e,t,s,o,i){if(!this.persistPendingToolCancellationsOrReport(e,t,"上下文溢出工具状态持久化失败"))return;const n=t.toolExecutions.some(e=>e.outcome.kind!==q.policyDenied&&e.outcome.kind!==q.userRejected&&e.outcome.kind!==q.invalidInput&&(e.outcome.kind!==q.cancelled||e.outcome.executionState!==R.notExecuted)),r=["本轮因上下文窗口溢出而中断,未自动重放。"];o&&r.push("本轮已产生部分文本,持久历史仅保留此中断标记。"),n&&r.push("本轮已有操作开始执行,部分结果可能已经生效且不会自动撤销,请先检查实际结果。");const a=[...this.uncoveredToolExecutions.values()];this.appendInterruptedTurnMessages(e,t,i,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...0===a.length?[]:[ae(a)],{role:"assistant",content:r.join("")}],debugLabel:"persisting context-overflow marker",debugDetails:{hadToolActivity:n,producedText:o},failureLabel:"上下文溢出记录持久化失败"})}persistFailedTurn(e,t,s,o){if(this.closed)return;const i=Ze(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=je(bt(et(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,re({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${Je}`}failedTurnDisplayMessage(e){const t=this.cancellationActivity(e);return`本轮因运行错误而中断,未自动重试。之前的对话和已完成进度会保留。${t.hadPotentialSideEffects?"部分操作可能已经生效且不会自动撤销,请先检查实际结果,再决定是否继续。":t.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"你可以继续输入或重试。"}`}appendInterruptedTurnMessages(e,t,s,o){if(t.pendingToolCalls.size>0)return e.push({type:"error",stage:"execute",message:`${o.failureLabel}: 存在未写入账本的待处理工具调用,已拒绝持久化中断记录`}),!1;this.messages.push(...o.messages),this.debug(e,"persist",o.debugLabel,s,{appendedMessages:this.messages.length-o.rollbackTo,...o.debugDetails});try{return this.persistMessages(this.messages.slice(o.rollbackTo),"recovery_evidence"),!0}catch(t){return this.messages.splice(o.rollbackTo),e.push({type:"error",stage:"execute",message:`${o.failureLabel}: ${ot(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:Ye(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===_.write||t.mode!==_.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+Ue,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ne(le(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({...V(e),sequence:e.sequence}))}getToolExecution(e,t=!1){const s=this.getPersistedToolExecution?.(e),o=s??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();return!o||t?o:{...V(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>W(e.output).kind===q.userRejected))return!1;const i=vt(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Y(this.messages)+Y(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Y(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Y([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Y(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Y(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(me(this.capabilityManifest,pe.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Q(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?fe(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,Ze(t));t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,s,{rollbackTo:this.messages.length,messages:o,debugLabel:"persisting paused turn cancellation",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}compactionTargetTokens(e){const t=this.compaction;if(void 0===t||void 0===this.contextWindow)return;const s=void 0===e?0:Y([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ie(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:C(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=xe(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===Te?this.compactionCheckpoint.semanticState:void 0,u=Ae(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&lt(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?Ne(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=ut(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,y=e.filter(e=>e.sequence>v),T=new Set(y.filter(e=>e.provenance===Ie[1]&&at(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),k=Ee({messages:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:it(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(rt),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),b=Me(k,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:k,modelContext:b.prompt,presentedEvidenceIds:b.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=Oe({draft:s??Ke,evidenceRegistry:t.registry,presentedEvidenceIds:t.presentedEvidenceIds,...void 0!==t.previousSemanticState?{previousState:t.previousSemanticState}:{},...void 0!==t.goal?{harnessGoal:{verbatimRequest:t.goal.verbatimRequest,sourceSequence:t.goal.sourceSequence}}:{}});let r=we(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Se(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=Pe(r,e);const o=void 0===this.compactionCheckpoint?.goal?t.goal:void 0===t.goal||void 0===t.newGoalSourceSequence||s?this.compactionCheckpoint.goal:t.goal;r=Re(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:xe(t.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??t.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?qe(r):void 0,d=void 0!==p?ke(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(be(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=ye(t.transcript.map(e=>e.message),t.toolExecutions,32,t.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...t.resources],toolState:g,runningWork:[...t.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:e("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(t.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:t.expectedActiveMessages,expectedLatestCheckpointId:t.expectedLatestCheckpointId,evidenceWatermarks:t.evidenceWatermarks,legacySnapshotTranscriptFragments:t.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:ot(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g;try{const t=Date.now();try{g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new K(B.missingObject,"structured compaction draft is missing")}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!K.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:ot(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const v=g.removed>0||g.truncatedTools>0,f=Date.now(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=je(g.messages),C=[...T.messages];if(T.status===$e.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(at))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const k=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),b=v&&k(C)<k(this.messages),x=b?C:[...this.messages],S=b?this.advanceCompactionSemanticEvidenceWatermarks(h,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(b){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=Ce({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,...b&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,truncatedTools:b?g.truncatedTools:0,progressed:b}),b}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:ot(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!C(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${ot(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=x.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(b))}currentCancellationActivity(e){const t=this.activeExecSessionIds(e),s=[...e.pendingToolCalls.values()].filter(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence));return{execSessionIds:t,hadCompletedProgress:e.toolExecutions.length>0||e.completedStepResponses.size>0,hadInFlightWork:s.length>0||t.length>0,hadPotentialSideEffects:e.hadPotentialSideEffects||s.some(e=>e.potentialSideEffect)}}captureCancellationActivity(e){e.cancellationActivity??=this.currentCancellationActivity(e)}cancellationActivity(e){return e.cancellationActivity??this.currentCancellationActivity(e)}cancellationDisplayMessage(e){const t=e.cancellationReason??x.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===x.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===x.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=me(this.capabilityManifest,pe.sessionList);switch(t){case x.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case x.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":this.capabilityManifest.lifecycle.hostMode===ue.oneShot?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case x.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??x.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=me(this.capabilityManifest,pe.sessionList),n=Je;switch(t){case x.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case x.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:this.capabilityManifest.lifecycle.hostMode===ue.oneShot?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case x.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=x.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,ze.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=ze.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===ze.keepRaw,r=n?je(bt(et(t))).messages:[],a=n?Ze(t):tt(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[re({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),M(this.cancellationDisplayMessage(e),e.cancellationReason??x.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${ot(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??x.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?R.outcomeUnknown:R.notExecuted,i=o===R.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=A({kind:q.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:ot(e.abortController.signal.reason)}});this.persistToolExecution(L({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=x.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(I),!0)}close(){if(void 0!==this.closePromise)return this.closePromise;this.closed=!0;const e=this.activeTurn;return e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=x.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(b)),this.closePromise=(async()=>{const e=(this.sessionManager?.close()??Promise.resolve([])).then(e=>{for(const t of e)void 0!==t.cleanupError&&process.stderr.write(`roll chat: 后台会话 ${String(t.sessionId)} 清理失败: ${t.cleanupError}\n`)},e=>{process.stderr.write(`roll chat: 会话 ${this.id} 后台清理失败: ${ot(e)}\n`)});await s(e,Fe)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Fe)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${ot(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${ot(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
1
+ import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{buildFileToolset as h}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as m}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as g,EXEC_LIST_NAME as v,EXEC_POLL_NAME as f,buildSessionExecToolset as y}from"../tool-bridge/session-exec-tool.js";import{SessionManager as T}from"../bash/session/session-manager.js";import{isTerminalSessionState as C}from"../bash/session/types.js";import{withCleanEnv as k}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as b,SESSION_CANCELLATION_REASONS as x,TURN_TIMEOUT_ABORT_REASON as S,USER_CANCELLATION_ABORT_REASON as I,createTurnCancellationMessage as M,isTurnTimeoutAbortReason as E,stripTurnCancellationMetadata as w}from"../types/cancellation.js";import{ToolRegistry as P}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as R,TOOL_OUTCOME_KINDS as q,createToolResult as A,failedToolResult as N,isNormalizedToolResult as O,normalizeToolResult as $,readDisplayOutput as j,readToolOutcome as W}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as D}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as L,prepareToolExecutionRecordForPersistence as F,redactSecretText as U,toRedactedToolExecutionRecordSummary as V}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as _,ToolExecutionCoordinator as G}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as z}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as B,compactMessages as H,CompactionDraftFallbackError as K,estimateMessagesTokens as Y,estimateTextTokens as Q,isCompactionSummaryAcknowledgement as X,readCompactionSummaryPayload as Z}from"./compactor.js";import{AsyncEventQueue as ee}from"./event-queue.js";import{applyExplicitSkillContext as te,attachExplicitSkillCheckpoint as se,prepareExplicitSkillContext as oe,readExplicitSkillCheckpoint as ie,stripExplicitSkillCheckpoints as ne}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as re,createToolLedgerGapRecoveryMessage as ae,materializeCancelledTurnRecoveryMessages as ce,stripCancelledTurnRecoveryMessages as le}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as ue,CAPABILITY_TOOL_ROLES as pe,buildEffectiveCapabilityTurnContext as de,buildEffectiveCapabilityManifest as he,findCapabilityToolId as me}from"./capability-manifest.js";import{buildCapabilityTurnReminder as ge,buildChatSystemPromptFromManifest as ve}from"./system-prompt.js";import{buildCompactionCheckpointReminder as fe,buildCompactionToolState as ye,COMPACTION_CHECKPOINT_VERSION as Te,createCompactionCheckpoint as Ce,createCompactionSummary as ke,createCheckpointSemanticReminderProjection as be,findLatestRealUserGoal as xe,resolveActiveCompactionConstraints as Se,TRANSCRIPT_MESSAGE_PROVENANCES as Ie}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Me,buildCompactionSemanticEvidenceRegistry as Ee,mergeCompactionSemanticState as we,replaceCompactionSemanticConstraints as Pe,replaceCompactionSemanticGoal as Re,renderCompactionSemanticSummary as qe,seedCompactionSemanticConstraints as Ae,seedLegacyCompactionSnapshotUncertainties as Ne,validateCompactionModelDraft as Oe}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as $e,repairActiveToolProtocol as je}from"./tool-protocol-repair.js";import{buildTranscriptToolset as We}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as De}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Le}from"../tool-bridge/user-input-tool.js";const Fe=6e3,Ue=3e5,Ve=4,_e=2,Ge=1,ze={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Je="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Be=1024,He="AI_InvalidToolInputError:",Ke={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Ye(t){const s=[...t];if(s.length<=Be)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Be-[...o].length).join("")}${o}`}function Qe(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function Xe(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function Ze(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function et(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function tt(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function st(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function ot(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e){if("message"in e&&"string"==typeof e.message&&e.message.length>0)return e.message;const t=it(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function it(e){try{return JSON.stringify(e)??void 0}catch{return}}function nt(e){const t=ie(e.message),[s]=ne([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(r(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function rt(e){return JSON.stringify(e)??String(e)}function at(e){const t=F(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:rt(t.input.value),resultSummary:rt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===q.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function ct(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==Z(e.content)||"assistant"===e.role&&X(e.content)}function lt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=Z(e.content);if(void 0!==t)return 0===t.length?[]:[U(t)]}return"assistant"===e.role&&X(e.content)?[]:[U(nt({sequence:t,provenance:Ie[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!ct(e)).length}}function ut(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function pt(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===Te?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function dt(e,t){return t.aborted?Promise.reject(t.reason):new Promise((s,o)=>{let i=!1;const n=e=>{i||(i=!0,t.removeEventListener("abort",r),e())},r=()=>n(()=>o(t.reason));t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(e=>n(()=>s(e)),e=>n(()=>o(e)))})}function ht(e){return ot(j(e))}function mt(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(He)?q.invalidInput:q.toolFailed}function gt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>W(e.output).kind===q.userRejected)??!1}function vt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(ot(e))}function ft(e){const t=e.inputTokenDetails?.cacheReadTokens,s=e.inputTokenDetails?.cacheWriteTokens,o=e.outputTokenDetails?.reasoningTokens;return{...void 0!==e.inputTokens?{inputTokens:e.inputTokens}:{},...void 0!==e.outputTokens?{outputTokens:e.outputTokens}:{},...void 0!==e.totalTokens?{totalTokens:e.totalTokens}:{},...void 0!==t?{cachedInputTokens:t}:{},...void 0!==s?{cacheWriteTokens:s}:{},...void 0!==o?{reasoningTokens:o}:{}}}function yt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function Tt(e,t){const s=yt(e.cachedInputTokens,t.cachedInputTokens),o=yt(e.cacheWriteTokens,t.cacheWriteTokens),i=yt(e.reasoningTokens,t.reasoningTokens);return{inputTokens:(e.inputTokens??0)+(t.inputTokens??0),outputTokens:(e.outputTokens??0)+(t.outputTokens??0),totalTokens:(e.totalTokens??0)+(t.totalTokens??0),...void 0!==s?{cachedInputTokens:s}:{},...void 0!==o?{cacheWriteTokens:o}:{},...void 0!==i?{reasoningTokens:i}:{}}}function Ct(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function kt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function bt(e,t){return void 0!==e?e:E(t)?x.timeout:x.runtime}function xt(e){return e.flatMap(e=>{if("assistant"!==e.role||!Array.isArray(e.content))return[e];const t=e.content.filter(e=>"reasoning"!==e.type);return 0===t.length?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function St(e,t,s){for(const o of Object.keys(t))e[o]=s}function It(e,t,s){const o={[g]:pe.sessionCommand,[f]:pe.sessionPoll,[v]:pe.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function Mt(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;gate=new z;userInputInteractions=new De;toolCoordinator=new G;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?xt(e.initialMessages):[];this.messages=[...je(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?lt(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=pt(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)ct(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Ie[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName));const o=new P,i={},n=Le({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,St(i,n.tools,pe.userInput);const r=e.readCheckpointTranscript?We(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};St(i,r,pe.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};St(i,a,pe.skill);const c=new J,l=e.fileTools?h(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(St(i,l.readTools,pe.fileRead),St(i,l.editTools,pe.fileEdit),St(i,l.verifyTools,pe.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},g=e.bashClassifier?{classifier:e.bashClassifier}:{},v=e.bash?m(e.bash,o,d,g):{};St(i,v,pe.shell),e.bashSession&&(this.sessionManager=new T({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:k(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity}));const f=e.bashSession&&this.sessionManager?y({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...g,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};It(i,f,o);const C=e.agentInstall,b=C?p({catalog:C.catalog,install:async(e,t)=>{const s=await C.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};St(i,b,pe.agentInstall);const x=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);St(i,x.tools,pe.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...v,...f,...b,...x.tools},this.registry=x.registry,this.toolRoles=i,this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return he({tools:this.tools,toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??ue.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=ve(this.capabilityManifest,{...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);St(this.toolRoles,t.tools,pe.agent),this.tools={...this.tools,...t.tools},this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);St(this.toolRoles,e,pe.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=n(e),s=new ee;this.emit=e=>s.push(e);const o=Qe();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:ot(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new ee;this.emit=e=>t.push(e);const s=Qe();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:ot(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${ot(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:ot(t)})}if(s.aborted||s.abortController.signal.aborted)return l=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(e,s,l,r);e.push({type:"message-start",messageId:t()}),void 0!==this.turnTimeoutMs&&(s.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),u=setTimeout(()=>{s.abortController.signal.aborted||(this.captureCancellationActivity(s),s.aborted=!0,s.cancellationReason=x.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(S))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=oe({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},m=d.skillNames.length>0?se(h,d):h;let g={};try{g=await dt(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(m),s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:ot(t)})}const v=de(this.capabilityManifest,{explicitSkillNames:d.skillNames,...g.ruleIds?{ruleIds:g.ruleIds}:{},...g.vcs?{vcs:g.vcs}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=v;const f=ge(v);let y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||this.messages.push(m);const n=me(this.capabilityManifest,pe.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:Q(u),h=ne(w(ce(this.messages))),g=Mt(d.skillNames.length>0?te(h,d):h,u?`${f}\n\n${u}`:f);this.debug(e,"model","calling streamText",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let v=0;const T=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.tools,prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),gt(),this.stopOnContextPressure(s)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(s,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:s.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{Xe(s,e),v=Y(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)Xe(s,t)}});let C;try{C=T()}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!vt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,m,!1,r),void e.push({type:"error",stage:"execute",message:ot(t)})}this.debug(e,"model","streamText returned",r);let k,b,S,I,M,P,R,A="",j="",W=!1,F=0,U=!1,V=!1;const _=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of C.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=x.runtime;break}switch(V||(V=!0,this.clearDebugTimer(_),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!W){const s=j+t.text;if(kt(s,d.userPrompt)){j=s;break}if(j.length>0){const s=j+t.text;j="",A+=s,e.push({type:"text-delta",delta:s});break}}A+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{W=!0,j="";const o=this.trackPendingToolCall(s,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));e.push({type:"tool-call",toolCallId:t.toolCallId,agentName:o.agentName,toolName:o.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=s.pendingToolCalls.get(t.toolCallId),n=O(t.output)?t.output:$(t.output),r=n.outcome,a=n.display,c=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==q.userRejected&&r.kind!==q.policyDenied&&r.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===q.success&&void 0!==i&&this.rememberCompactionResources(c,i.resources),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,outcome:r,display:a,output:a,isError:r.kind!==q.success}),s.aborted||s.abortController.signal.aborted||r.kind!==q.userRejected||(R=ht(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=mt(t.error),n=(i===q.invalidInput?D(t.error):void 0)??ht(t.error),r=N(i,n,{raw:t.error}),a=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:n,isError:!0});break}case"finish-step":{const s=ft(t.usage);b=Ct(b,s.inputTokens),S=s.outputTokens,F+=1,M=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(I=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!W&&j.length>0&&(A+=j,e.push({type:"text-delta",delta:j}),j=""),k=ft(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||E(t.error)){s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t.error);break}U=vt(t.error),U&&(this.needsCompaction=!0),P=ot(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||E(e)?(s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,e)):(U=vt(e),U&&(this.needsCompaction=!0),P=ot(e))}finally{this.clearDebugTimer(_)}if(this.debug(e,"model","fullStream finished",r,{textChars:A.length}),void 0!==P){if(this.messages.splice(l),U){const t=0===A.length&&!W,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${P}${a}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:P})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let G;this.debug(e,"model","awaiting response messages",r);const z=this.scheduleDebug(e,"model","still awaiting response messages",r);try{G=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(z),this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=vt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===A.length&&!W,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${ot(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:ot(t)})}finally{this.clearDebugTimer(z)}if(this.debug(e,"model","response messages ready",r,{responseMessages:G.length}),this.isTurnAborted(s))return s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const J=xt(G);if(this.messages.push(...J),void 0!==R){const t=0===A.length?R:`\n${R}`;A+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:R})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),st(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),k&&(this.sessionUsage=Tt(this.sessionUsage,k));const B=b??k?.inputTokens;void 0!==B&&(this.lastInputTokens=B,this.lastStepOutputTokens=S,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,B-Y(this.messages)+(S??0)+v-p)),s.completedStepCount+=F;const H=s.completedStepCount>=this.maxSteps&&"tool-calls"===M;if(e.push({type:"message-finish",text:A,...k?{totalUsage:k}:{},sessionUsage:{...this.sessionUsage},...void 0!==b?{contextInputTokens:b}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:ot(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason??t),void(void 0!==l?this.persistCancelledTurn(e,s,l,r):this.emitCancellation(e,s));void 0!==l&&this.messages.splice(l),this.debug(e,"turn","error",r,{message:ot(t)}),e.push({type:"error",stage:"execute",message:ot(t)})}finally{void 0!==u&&clearTimeout(u),this.toolCoordinator.finishTurn(),this.activeTurn===s&&(this.activeTurn=void 0),e.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)ct(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Ie[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=ae(e);this.messages.push(s);try{this.persistMessages([s],"recovery_evidence")}catch(e){throw this.messages.splice(t),e}}persistContextFailure(e,t,s,o,i){if(!this.persistPendingToolCancellationsOrReport(e,t,"上下文溢出工具状态持久化失败"))return;const n=t.toolExecutions.some(e=>e.outcome.kind!==q.policyDenied&&e.outcome.kind!==q.userRejected&&e.outcome.kind!==q.invalidInput&&(e.outcome.kind!==q.cancelled||e.outcome.executionState!==R.notExecuted)),r=["本轮因上下文窗口溢出而中断,未自动重放。"];o&&r.push("本轮已产生部分文本,持久历史仅保留此中断标记。"),n&&r.push("本轮已有操作开始执行,部分结果可能已经生效且不会自动撤销,请先检查实际结果。");const a=[...this.uncoveredToolExecutions.values()];this.appendInterruptedTurnMessages(e,t,i,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...0===a.length?[]:[ae(a)],{role:"assistant",content:r.join("")}],debugLabel:"persisting context-overflow marker",debugDetails:{hadToolActivity:n,producedText:o},failureLabel:"上下文溢出记录持久化失败"})}persistFailedTurn(e,t,s,o){if(this.closed)return;const i=Ze(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=je(xt(et(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,re({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${Je}`}failedTurnDisplayMessage(e){const t=this.cancellationActivity(e);return`本轮因运行错误而中断,未自动重试。之前的对话和已完成进度会保留。${t.hadPotentialSideEffects?"部分操作可能已经生效且不会自动撤销,请先检查实际结果,再决定是否继续。":t.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"你可以继续输入或重试。"}`}appendInterruptedTurnMessages(e,t,s,o){if(t.pendingToolCalls.size>0)return e.push({type:"error",stage:"execute",message:`${o.failureLabel}: 存在未写入账本的待处理工具调用,已拒绝持久化中断记录`}),!1;this.messages.push(...o.messages),this.debug(e,"persist",o.debugLabel,s,{appendedMessages:this.messages.length-o.rollbackTo,...o.debugDetails});try{return this.persistMessages(this.messages.slice(o.rollbackTo),"recovery_evidence"),!0}catch(t){return this.messages.splice(o.rollbackTo),e.push({type:"error",stage:"execute",message:`${o.failureLabel}: ${ot(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:Ye(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===_.write||t.mode!==_.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+Ue,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ne(le(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({...V(e),sequence:e.sequence}))}getToolExecution(e,t=!1){const s=this.getPersistedToolExecution?.(e),o=s??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();return!o||t?o:{...V(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>W(e.output).kind===q.userRejected))return!1;const i=ft(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Y(this.messages)+Y(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Y(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Y([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Y(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Y(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(me(this.capabilityManifest,pe.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Q(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?fe(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,Ze(t));t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,s,{rollbackTo:this.messages.length,messages:o,debugLabel:"persisting paused turn cancellation",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}compactionTargetTokens(e){const t=this.compaction;if(void 0===t||void 0===this.contextWindow)return;const s=void 0===e?0:Y([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ie(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:C(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=xe(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===Te?this.compactionCheckpoint.semanticState:void 0,u=Ae(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&ut(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?Ne(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=pt(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,y=e.filter(e=>e.sequence>v),T=new Set(y.filter(e=>e.provenance===Ie[1]&&ct(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),k=Ee({messages:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:nt(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(at),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),b=Me(k,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:k,modelContext:b.prompt,presentedEvidenceIds:b.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=Oe({draft:s??Ke,evidenceRegistry:t.registry,presentedEvidenceIds:t.presentedEvidenceIds,...void 0!==t.previousSemanticState?{previousState:t.previousSemanticState}:{},...void 0!==t.goal?{harnessGoal:{verbatimRequest:t.goal.verbatimRequest,sourceSequence:t.goal.sourceSequence}}:{}});let r=we(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Se(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=Pe(r,e);const o=void 0===this.compactionCheckpoint?.goal?t.goal:void 0===t.goal||void 0===t.newGoalSourceSequence||s?this.compactionCheckpoint.goal:t.goal;r=Re(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:xe(t.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??t.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?qe(r):void 0,d=void 0!==p?ke(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(be(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=ye(t.transcript.map(e=>e.message),t.toolExecutions,32,t.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...t.resources],toolState:g,runningWork:[...t.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:e("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(t.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:t.expectedActiveMessages,expectedLatestCheckpointId:t.expectedLatestCheckpointId,evidenceWatermarks:t.evidenceWatermarks,legacySnapshotTranscriptFragments:t.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:ot(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g;try{const t=Date.now();try{g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new K(B.missingObject,"structured compaction draft is missing")}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!K.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:ot(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const v=g.removed>0||g.truncatedTools>0,f=Date.now(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=je(g.messages),C=[...T.messages];if(T.status===$e.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(ct))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const k=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),b=v&&k(C)<k(this.messages),x=b?C:[...this.messages],S=b?this.advanceCompactionSemanticEvidenceWatermarks(h,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(b){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=Ce({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,...b&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,truncatedTools:b?g.truncatedTools:0,progressed:b}),b}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:ot(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!C(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${ot(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=x.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(b))}currentCancellationActivity(e){const t=this.activeExecSessionIds(e),s=[...e.pendingToolCalls.values()].filter(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence));return{execSessionIds:t,hadCompletedProgress:e.toolExecutions.length>0||e.completedStepResponses.size>0,hadInFlightWork:s.length>0||t.length>0,hadPotentialSideEffects:e.hadPotentialSideEffects||s.some(e=>e.potentialSideEffect)}}captureCancellationActivity(e){e.cancellationActivity??=this.currentCancellationActivity(e)}cancellationActivity(e){return e.cancellationActivity??this.currentCancellationActivity(e)}cancellationDisplayMessage(e){const t=e.cancellationReason??x.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===x.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===x.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=me(this.capabilityManifest,pe.sessionList);switch(t){case x.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case x.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":this.capabilityManifest.lifecycle.hostMode===ue.oneShot?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case x.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??x.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=me(this.capabilityManifest,pe.sessionList),n=Je;switch(t){case x.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case x.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:this.capabilityManifest.lifecycle.hostMode===ue.oneShot?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case x.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=x.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,ze.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=ze.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===ze.keepRaw,r=n?je(xt(et(t))).messages:[],a=n?Ze(t):tt(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[re({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),M(this.cancellationDisplayMessage(e),e.cancellationReason??x.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${ot(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??x.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?R.outcomeUnknown:R.notExecuted,i=o===R.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=A({kind:q.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:ot(e.abortController.signal.reason)}});this.persistToolExecution(L({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=x.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(I),!0)}close(){if(void 0!==this.closePromise)return this.closePromise;this.closed=!0;const e=this.activeTurn;return e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=x.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(b)),this.closePromise=(async()=>{const e=(this.sessionManager?.close()??Promise.resolve([])).then(e=>{for(const t of e)void 0!==t.cleanupError&&process.stderr.write(`roll chat: 后台会话 ${String(t.sessionId)} 清理失败: ${t.cleanupError}\n`)},e=>{process.stderr.write(`roll chat: 会话 ${this.id} 后台清理失败: ${ot(e)}\n`)});await s(e,Fe)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Fe)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${ot(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${ot(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
@@ -1 +1 @@
1
- const w=[{match:"claude-fable-5",window:1e6},{match:"claude-mythos-5",window:1e6},{match:"claude-opus-4-8",window:1e6},{match:"claude-opus-4-7",window:1e6},{match:"claude-opus-4-6",window:1e6},{match:"claude-sonnet-5",window:1e6},{match:"claude-sonnet-4-6",window:1e6},{match:"claude-haiku-4-5",window:2e5},{match:"claude",window:2e5},{match:"gpt-5.5",window:105e4},{match:"gpt-5.4-mini",window:4e5},{match:"gpt-5.4-nano",window:4e5},{match:"gpt-5.4",window:105e4},{match:"gpt-5-mini",window:4e5},{match:"gpt-5-nano",window:4e5},{match:"gpt-5",window:4e5},{match:"gpt-4.1",window:128e3},{match:"gpt-4o",window:128e3},{match:"gpt-4-turbo",window:128e3},{match:"o3",window:2e5},{match:"o1-mini",window:128e3},{match:"o1",window:2e5},{match:"grok-4.5",window:5e5},{match:"deepseek-v4",window:1e6},{match:"deepseek-chat",window:1e6},{match:"deepseek-reasoner",window:1e6},{match:"deepseek",window:128e3},{match:"qwen-long",window:1e7},{match:"qwen3-coder",window:1e6},{match:"qwen3.8-plus",window:1e6},{match:"qwen3.8-max",window:1e6},{match:"qwen3.7-plus",window:1e6},{match:"qwen3.7-max",window:1e6},{match:"qwen3.6-plus",window:1e6},{match:"qwen3.5-plus",window:1e6},{match:"qwen3.5-flash",window:1e6},{match:"qwen-plus",window:1e6},{match:"qwen-flash",window:1e6},{match:"qwen3-max",window:262144},{match:"qwen3-vl-plus",window:262144},{match:"qwen-vl-plus",window:131072},{match:"qwen",window:131072},{match:"gemini",window:1e6},{match:"kimi",window:128e3},{match:"glm",window:128e3}];export function lookupContextWindow(e){const n=e.toLowerCase();return w.find(w=>n.includes(w.match))?.window}export function resolveContextWindow(w,e){return void 0!==e?e:lookupContextWindow(w)}
1
+ const w=[{match:"claude-fable-5",window:1e6},{match:"claude-mythos-5",window:1e6},{match:"claude-opus-4-8",window:1e6},{match:"claude-opus-4-7",window:1e6},{match:"claude-opus-4-6",window:1e6},{match:"claude-sonnet-5",window:1e6},{match:"claude-sonnet-4-6",window:1e6},{match:"claude-haiku-4-5",window:2e5},{match:"claude",window:2e5},{match:"gpt-5.5",window:105e4},{match:"gpt-5.4-mini",window:4e5},{match:"gpt-5.4-nano",window:4e5},{match:"gpt-5.4",window:105e4},{match:"gpt-5-mini",window:4e5},{match:"gpt-5-nano",window:4e5},{match:"gpt-5",window:4e5},{match:"gpt-4.1",window:128e3},{match:"gpt-4o",window:128e3},{match:"gpt-4-turbo",window:128e3},{match:"o3",window:2e5},{match:"o1-mini",window:128e3},{match:"o1",window:2e5},{match:"grok-4.6",window:5e5},{match:"grok-4.5",window:5e5},{match:"deepseek-v4",window:1e6},{match:"deepseek-chat",window:1e6},{match:"deepseek-reasoner",window:1e6},{match:"deepseek",window:128e3},{match:"qwen-long",window:1e7},{match:"qwen3-coder",window:1e6},{match:"qwen3.8-plus",window:1e6},{match:"qwen3.8-max",window:1e6},{match:"qwen3.7-plus",window:1e6},{match:"qwen3.7-max",window:1e6},{match:"qwen3.6-plus",window:1e6},{match:"qwen3.5-plus",window:1e6},{match:"qwen3.5-flash",window:1e6},{match:"qwen-plus",window:1e6},{match:"qwen-flash",window:1e6},{match:"qwen3-max",window:262144},{match:"qwen3-vl-plus",window:262144},{match:"qwen-vl-plus",window:131072},{match:"qwen",window:131072},{match:"gemini",window:1e6},{match:"kimi",window:128e3},{match:"glm",window:128e3}];export function lookupContextWindow(e){const n=e.toLowerCase();return w.find(w=>n.includes(w.match))?.window}export function resolveContextWindow(w,e){return void 0!==e?e:lookupContextWindow(w)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roll-agent/runtime",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^22.0.0",
39
- "@roll-agent/core": "0.32.0"
39
+ "@roll-agent/core": "0.33.0"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/obfuscate.mjs",