@roll-agent/runtime 1.0.1 → 1.0.2
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.
- package/dist/engine/agent-session.d.ts +7 -1
- package/dist/engine/agent-session.js +1 -1
- package/dist/engine/conversation-engine.js +1 -1
- package/dist/host-contracts/agent-host.d.ts +2 -0
- package/dist/tool-bridge/skill-tool.d.ts +6 -1
- package/dist/tool-bridge/skill-tool.js +1 -1
- package/package.json +1 -1
|
@@ -99,6 +99,7 @@ export interface AgentSessionOptions {
|
|
|
99
99
|
readonly capabilityContext?: AgentSessionCapabilityContext;
|
|
100
100
|
readonly resolveDynamicCapabilityContext?: (abortSignal: AbortSignal) => CapabilityExternalDynamicContext | Promise<CapabilityExternalDynamicContext>;
|
|
101
101
|
readonly skillLibrary?: SkillLibrary;
|
|
102
|
+
readonly refreshSkillLibrary?: (signal: AbortSignal) => Promise<SkillLibrary | undefined>;
|
|
102
103
|
readonly workspaceInstructions?: WorkspaceInstructionsSource;
|
|
103
104
|
readonly fileTools?: SessionFileToolsSettings;
|
|
104
105
|
readonly bash?: SessionBashSettings;
|
|
@@ -187,7 +188,9 @@ export declare class AgentSession {
|
|
|
187
188
|
private readonly toolRoles;
|
|
188
189
|
private skillSummaries;
|
|
189
190
|
private skillLibrary;
|
|
190
|
-
private
|
|
191
|
+
private skillExecutionLibrary;
|
|
192
|
+
private skillToolId;
|
|
193
|
+
private readonly refreshSkillLibrary;
|
|
191
194
|
private readonly toolSourceAgentNames;
|
|
192
195
|
private toolSchemaPolicy;
|
|
193
196
|
private readonly onToolExcluded;
|
|
@@ -233,6 +236,9 @@ export declare class AgentSession {
|
|
|
233
236
|
private requestUserInput;
|
|
234
237
|
private trackPendingToolCall;
|
|
235
238
|
private buildSkillTools;
|
|
239
|
+
private applySkillLibrary;
|
|
240
|
+
private refreshSkills;
|
|
241
|
+
private skillToolInputError;
|
|
236
242
|
applyAgentRefresh(refresh: SessionAgentRefresh): void;
|
|
237
243
|
send(input: string | SessionSendInput): AsyncIterable<SessionEvent>;
|
|
238
244
|
compact(reason?: ContextCompactionReason): AsyncIterable<SessionEvent>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeAppOutput as e}from"@roll-agent/protocol";import{randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{buildSessionModelRequest as o}from"./model-request.js";import{ModelRecoveryBudget as i}from"./model-recovery.js";import{ContextMaintenanceRequired as n,RequestBudgetTracker as r}from"./request-budget.js";import{buildUserMessageContent as a,normalizeSessionSendInput as l}from"./session-attachments.js";import{stepCountIs as c,streamText as u,wrapLanguageModel as d,InvalidToolInputError as p,NoOutputGeneratedError as h}from"ai";import{COMPACTION_FAILURE_REASONS as m}from"../types/events.js";import{buildAgentToolset as g}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as v}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as f}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as b}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as T}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as y}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as C}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as I,EXEC_LIST_NAME as x,EXEC_POLL_NAME as k,buildSessionExecToolset as S}from"../tool-bridge/session-exec-tool.js";import{SessionManager as w}from"../bash/session/session-manager.js";import{isTerminalSessionState as M}from"../bash/session/types.js";import{withCleanEnv as E}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as R,SESSION_CANCELLATION_REASONS as P,TURN_TIMEOUT_ABORT_REASON as O,USER_CANCELLATION_ABORT_REASON as A,createTurnCancellationMessage as N,isTurnTimeoutAbortReason as j}from"../types/cancellation.js";import{ToolRegistry as q}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as $,TOOL_OUTCOME_KINDS as W,createToolResult as L,failedToolResult as D,isNormalizedToolResult as F,normalizeToolResult as B,readDisplayOutput as _,readToolOutcome as U}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as z}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as H,toRedactedToolExecutionRecordSummary as G}from"../tool-bridge/tool-execution-record.js";import{ToolExecutionCoordinator as K}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as V}from"../approval/approval-gate.js";import{SessionApprovalMemory as Y}from"../approval/approval-memory.js";import{CompactionTimeoutError as J,compactMessages as Q,estimateMessagesTokens as X,estimateTextTokens as Z,isCompactionSummaryAcknowledgement as ee,readCompactionSummaryPayload as te}from"./compactor.js";import{AsyncEventQueue as se}from"./event-queue.js";import{ToolInputActivityTracker as oe}from"./tool-input-activity.js";import{projectTurnInputSkillCheckpoint as ie,turnInputSkillCheckpointSchema as ne}from"../store/turn-input.js";import{attachExplicitSkillCheckpoint as re,prepareExplicitSkillContext as ae,readExplicitSkillCheckpoint as le,stripExplicitSkillCheckpoints as ce}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as ue,createToolLedgerGapRecoveryMessage as de,stripCancelledTurnRecoveryMessages as pe}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as he,CAPABILITY_TOOL_ROLES as me,buildEffectiveCapabilityTurnContext as ge,buildEffectiveCapabilityManifest as ve,findCapabilityToolId as fe,isProcessBoundHostMode as be}from"./capability-manifest.js";import{buildCapabilityTurnReminder as Te,buildChatSystemPromptFromManifest as ye}from"./system-prompt.js";import{threadDerivedFromSchema as Ce}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as Ie,buildCompactionToolState as xe,createSummaryCheckpoint as ke,TRANSCRIPT_MESSAGE_PROVENANCES as Se}from"./compaction-checkpoint.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as we,repairActiveToolProtocol as Me}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Ee}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as Re}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as Pe}from"./observation-readback.js";import{canonicalObservationOutput as Oe,projectObservationMessages as Ae,restoreCanonicalObservationOutputs as Ne}from"./observation-projection.js";import{UserInputInteractionManager as je}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as qe}from"../tool-bridge/user-input-tool.js";const $e=6e3,We=3e5,Le=1,De={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Fe="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Be="AI_InvalidToolInputError:";function _e(){return{inputId:t(),abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalObservationOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0,userRejected:!1}}function Ue(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=Ne(t.response.messages,e.canonicalObservationOutputs);return e.completedStepResponses.set(s,i),i}function ze(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??Ne(t.response.messages,e.canonicalObservationOutputs))}function He(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function Ge(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ke(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ve(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function Ye(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=Je(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function Je(e){try{return JSON.stringify(e)??void 0}catch{return}}function Qe(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==te(e.content)||"assistant"===e.role&&ee(e.content)}function Xe(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 Ze(e){return Ye(_(e))}function et(e){return p.isInstance(e)||"string"==typeof e&&e.startsWith(Be)?W.invalidInput:W.toolFailed}function tt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>U(e.output).kind===W.userRejected)??!1}function st(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(Ye(e))}function ot(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 it(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function nt(e,t){const s=it(e.cachedInputTokens,t.cachedInputTokens),o=it(e.cacheWriteTokens,t.cacheWriteTokens),i=it(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 rt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function at(e,t){return void 0!==e?e:j(t)?P.timeout:P.runtime}function lt(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 ct(e,t,s){for(const o of Object.keys(t))e[o]=s}function ut(e,t,s){const o={[I]:me.sessionCommand,[k]:me.sessionPoll,[x]:me.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}export class AgentSession{id;model;modelRecovery;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];contextWindow;compaction;turnTimeoutMs;onClose;onBeforeTurn;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new V;userInputInteractions=new je;onAcceptInput;onRecordInputSkillCheckpoint;getInputSkillCheckpoint;inputSkillCheckpoints=new Map;toolCoordinator=new K;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;requestBudgets=new r;contextWindowSource;constructor(e){this.id=e.id,this.model=e.model,this.modelRecovery=e.modelRecovery,this.contextWindowSource=e.contextWindowSource,this.maxSteps=e.maxSteps;const t=e.initialMessages?lt(e.initialMessages):[];this.messages=[...Me(t).messages],this.onPersist=e.onPersist,this.onAcceptInput=e.onAcceptInput,this.onRecordInputSkillCheckpoint=e.onRecordInputSkillCheckpoint,this.getInputSkillCheckpoint=e.getInputSkillCheckpoint,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=(e.initialCheckpoint?.transcript.messages.throughSequence??-1)+1;for(const e of this.messages)Qe(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Se[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.onBeforeTurn=e.onBeforeTurn,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.derivedFrom=void 0===e.derivedFrom?void 0:Ce.parse(e.derivedFrom),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)),this.toolSchemaPolicy=e.toolSchemaPolicy,this.onToolExcluded=e.onToolExcluded;const o=new q,i={},n=qe({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,ct(i,n.tools,me.userInput);const r=e.readCheckpointTranscript?Ee(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};ct(i,r,me.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};ct(i,a,me.skill);const l=new Y,c=e.fileTools?y(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:l}):void 0;c&&(ct(i,c.readTools,me.fileRead),ct(i,c.editTools,me.fileEdit),ct(i,c.verifyTools,me.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},d=e.bashClassifier?{classifier:e.bashClassifier}:{},p=e.bash?C(e.bash,o,u,d):{};ct(i,p,me.shell),e.bashSession&&(this.sessionManager=new w({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:E(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const h=e.bashSession&&this.sessionManager?S({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...d,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};ut(i,h,o);const m=e.agentInstall,f=m?v({catalog:m.catalog,install:async(e,t)=>{const s=await m.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}):{};ct(i,f,me.agentInstall);const T=e.schedules?b(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};ct(i,T.createTools,me.scheduleCreate),ct(i,T.extendTools,me.scheduleExtend),ct(i,T.listTools,me.scheduleList);const I=g(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);ct(i,I.tools,me.agent);const x=I.observationRetentionByToolId.size>0?Re(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(x)[0],ct(i,x,me.observationRead),this.tools={...r,...x,...a,...c?{...c.readTools,...c.editTools,...c.verifyTools}:{},...p,...h,...f,...T.createTools,...T.extendTools,...T.listTools,...I.tools},this.registry=I.registry;for(const[e,t]of I.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(I.schemaIssuesByToolId),this.applyToolSchemaPolicy(),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 ve({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??he.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=ye(this.capabilityManifest,{...void 0!==this.derivedFrom?{derivedFrom:this.derivedFrom}:{},...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,f(()=>{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=g([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);ct(this.toolRoles,t.tools,me.agent),this.tools={...this.tools,...t.tools};for(const[e,s]of t.observationRetentionByToolId)this.observationRetentionByToolId.set(e,s);if(void 0===this.observationRecallToolId&&this.observationRetentionByToolId.size>0){const e=Re(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],ct(this.toolRoles,e,me.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),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);ct(this.toolRoles,e,me.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");this.onBeforeTurn?.();const t=l(e),s=new se;this.emit=e=>s.push(e);const o=_e();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:Ye(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");this.onBeforeTurn?.();const t=new se;this.emit=e=>t.push(e);const s=_e();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:Ye(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(s,r,l){const p=Date.now(),m=this.modelRecovery,g=void 0===m?void 0:new i(m);let v,f,b;const y=()=>{r.abortController.signal.aborted||(this.captureCancellationActivity(r),r.aborted=!0,r.cancellationReason=P.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),r.abortController.abort(O))},C=a(l.text,l.attachments);try{m?.onTurnStart?.();const i={role:"user",content:C};let a;try{void 0!==this.onAcceptInput?a=this.onAcceptInput(r.inputId,i).transcriptSequence:(a=(this.listCompactionTranscriptEvidence().at(-1)?.sequence??-1)+1,this.onPersist?.([i])),this.recordPersistedMessagesInMemory([i]),this.messages.push(i),r.userMessagePersisted=!0,f=this.messages.length}catch(e){return void s.push({type:"error",stage:"plan",message:`输入持久化失败,未开始模型请求: ${Ye(e)}`})}if(void 0!==this.turnTimeoutMs){const e=Math.max(0,this.turnTimeoutMs-(Date.now()-p));r.expiresAt=new Date(p+this.turnTimeoutMs).toISOString(),b=setTimeout(y,e),0===e&&y()}this.debug(s,"turn","start",p,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...l.attachments.length>0?{attachments:l.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void s.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${Ye(e)}`})}if(f=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);this.syncWorkspaceInstructions();let I,x=0,k=!1;const S=()=>Math.max(1024,.05*(this.contextWindow??0)),w=e=>void 0===I||e>=I.calibratedInputEstimate+S(),M=new Set;let E;const R=T(),O=ae({rawInput:l.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary});void 0!==r.expiresAt&&Date.now()>=Date.parse(r.expiresAt)&&y();const A=i;if(O.skillNames.length>0&&!this.isTurnAborted(r)){const e=le(re(i,O));if(void 0===e)throw new Error("Explicit Skill checkpoint could not be created");this.onRecordInputSkillCheckpoint?.(r.inputId,e),this.inputSkillCheckpoints.set(a,ne.parse(e))}if(f=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);s.push({type:"message-start",messageId:t()});let N={};try{N=await Xe(this.resolveDynamicCapabilityContext?.(r.abortController.signal)??{},r.abortController.signal)??{}}catch(e){if(this.isTurnAborted(r))return f=this.messages.length,r.cancellationReason=at(r.cancellationReason,r.abortController.signal.reason??e),void this.persistCancelledTurn(s,r,f,p);this.debug(s,"turn","dynamic capability context unavailable",p,{message:Ye(e)})}const q=ge(this.capabilityManifest,{explicitSkillNames:O.skillNames,...N.ruleIds?{ruleIds:N.ruleIds}:{},...N.vcs?{vcs:N.vcs}:{},...N.origin?{origin:N.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=q;const $=Te(q);let L;for(;;){f=this.messages.length,r.pausedForContextPressure=!1;const i=fe(this.capabilityManifest,me.transcriptRead),a=this.currentCheckpointReminder(i),l=void 0===a?0:Z(a),b=this.modelTools(),T=(e=[])=>o({history:this.messages,completedMessages:e,explicitSkill:O,capabilityReminder:$,...void 0===a?{}:{checkpointReminder:a},system:this.systemPrompt,tools:b,...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions},project:e=>this.projectModelMessages(e)}),y=T();let C=y.shapeContext;this.debug(s,"model","calling streamText",p,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:x,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let N,q=0,_=0;const U=[];let G,K,V,Y=!1;const J=d({model:this.model,middleware:{specificationVersion:"v4",wrapStream:async({params:e,doStream:t})=>{if(r.abortController.signal.aborted)throw r.abortController.signal.reason;const s=this.requestBudgets.prepare(e,{provider:this.model.provider,model:this.model.modelId,...void 0===this.contextWindow?{}:{window:this.contextWindow},...void 0===this.contextWindowSource?{}:{windowSource:this.contextWindowSource},threshold:this.compaction?.threshold??.75},C,r.inputId),o=s.maintenanceTarget,i=this.modelTools(),a=Object.keys(i).length!==Object.keys(b).length||Object.entries(b).some(([e,t])=>i[e]!==t),l=void 0!==s.availableInputCeiling&&s.calibratedInputEstimate>s.availableInputCeiling,c=!k&&!0===this.compaction?.enabled&&void 0!==o&&s.calibratedInputEstimate>=o&&(w(s.calibratedInputEstimate)||void 0!==I&&(s.shapeFingerprint!==I.shapeFingerprint||s.rawInputEstimate>=I.rawInputEstimate+S())),u=M.has(s.fingerprint)||void 0!==E&&s.rawInputEstimate>=E.rawInputEstimate;if(a||l||c||u)throw G=new n(s,a?"shape_changed":u?"provider_rejected":l?"budget":"soft_target"),G;k=!1,K=s,this.requestBudgets.dispatchedRequest(),Y=!1;const d=await t();if(void 0===m)return d;const p=d.stream.getReader();let h=!1;return{...d,stream:new ReadableStream({async pull(e){let t;try{t=await p.read()}catch(t){return Y=!1,e.enqueue({type:"error",error:t}),e.close(),void p.releaseLock()}if(t.done)return e.close(),void p.releaseLock();const s=t.value;if("finish"!==s.type||!h){if("finish"===s.type&&"error"===s.finishReason.unified)return h=!0,Y=!1,void e.enqueue({type:"error",error:new Error("模型未成功完成本步骤,未执行待处理工具。")});"finish"===s.type&&(Y=!0),"error"===s.type&&(Y=!1,h=!0),e.enqueue(s)}},async cancel(e){try{await p.cancel(e)}finally{p.releaseLock()}}})}}}}),Q=()=>u({model:J,...void 0===m?{}:{maxRetries:0},system:y.system,messages:y.messages,tools:b,prepareStep:()=>{q=X(this.projectModelMessages([...this.messages,...U]));const e=T(U);return C=e.shapeContext,_=this.requestBudgets.projectedMessageTokens(e.messages),{messages:e.messages,system:e.system}},stopWhen:[()=>void 0!==m&&!Y,c(Math.max(1,this.maxSteps-r.completedStepCount)),tt(),R.stop,this.stopOnContextPressure(r,()=>q,()=>this.requestBudgets.predict(T(U).messages,_),w)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(r,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,usage:s,finishReason:o})=>{void 0!==m&&"error"===o||(V=nt(V??{},ot(s)),void 0!==K&&this.requestBudgets.measured(K,s.inputTokens),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:r.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{(void 0===m||Y)&&U.push(...Ue(r,e))},onAbort:({steps:e})=>{if(void 0===m)for(const t of e)Ue(r,t)}});let ee;try{ee=Q()}catch(e){if(this.isTurnAborted(r)||j(e))return r.aborted=!0,r.cancellationReason=at(r.cancellationReason,e),void this.persistCancelledTurn(s,r,f,p);if(!st(e))throw e;this.messages.splice(f);const t=x<1,o=!!t&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(o&&t){x+=1;continue}return this.persistContextFailure(s,r,A,!1,p),void s.push({type:"error",stage:"execute",message:Ye(e)})}this.debug(s,"model","streamText returned",p);let te,se,ie,ne,re,ae,le,ce="",ue="",de=!1,pe=0,he=!1,ge=!1,ve=!1;const be=this.scheduleDebug(s,"model","waiting for first stream event",p,{messages:this.messages.length}),Te=new oe(e=>{const t=this.registry.resolve(e);return void 0===t?void 0:`${t.agentName}.${t.toolName}`},e=>s.push(e)),ye=()=>Te.clear();r.abortController.signal.addEventListener("abort",ye,{once:!0});try{for await(const t of ee.fullStream){if(this.closed){r.aborted=!0,r.cancellationReason??=P.runtime;break}switch(ve||(ve=!0,this.clearDebugTimer(be),this.debug(s,"model","first stream event",p,{part:t.type})),t.type){case"start-step":void 0!==m&&s.push({type:"model-step-start"});break;case"tool-input-start":Te.start(t.id,t.toolName);break;case"tool-input-delta":Te.delta(t.id);break;case"tool-input-end":Te.end(t.id);break;case"reasoning-start":s.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":s.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":s.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!de){const e=ue+t.text;if(rt(e,O.userPrompt)){ue=e;break}if(ue.length>0){const e=ue+t.text;ue="",ce+=e,s.push({type:"text-delta",delta:e});break}}ce+=t.text,s.push({type:"text-delta",delta:t.text});break;case"tool-call":{Te.end(t.toolCallId),de=!0,ue="";const e=this.trackPendingToolCall(r,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));s.push({type:"tool-call",toolCallId:t.toolCallId,agentName:e.agentName,toolName:e.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=r.pendingToolCalls.get(t.toolCallId),n=F(t.output)?t.output:B(t.output),a=n.outcome,l=n.display,c=H({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,r);const u=a.kind===W.success?Oe(n.raw,this.observationRetentionByToolId.get(t.toolName)):void 0;if(u){r.canonicalObservationOutputs.set(t.toolCallId,u);const e=this.observationResultIds.get(t.toolCallId);void 0!==e&&e!==c.id&&this.ambiguousObservationCallIds.add(t.toolCallId),this.observationResultIds.set(t.toolCallId,this.ambiguousObservationCallIds.has(t.toolCallId)?void 0:c.id)}!0===i?.potentialSideEffect&&a.kind!==W.userRejected&&a.kind!==W.policyDenied&&a.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a,display:l,output:l,isError:a.kind!==W.success}),r.aborted||r.abortController.signal.aborted||a.kind!==W.userRejected||(le=Ze(t.output));break}case"tool-error":{Te.end(t.toolCallId);const o=this.registry.resolve(t.toolName),i=et(t.error),n=(i===W.invalidInput?z(t.error):void 0)??Ze(t.error),a=D(i,n,{raw:t.error}),l=H({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:r.pendingToolCalls.get(t.toolCallId)?.input,result:a});this.persistToolExecution(l,r),!0===r.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&a.outcome.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:l.id,...void 0===l.appOutput?{}:{appOutput:e(l.appOutput)},outcome:a.outcome,display:a.display,output:n,isError:!0});break}case"finish-step":{if(Te.clear(),void 0!==m&&void 0!==re)break;const e=ot(t.usage);void 0!==e.inputTokens&&(se=e.inputTokens,N=q),pe+=1,ne=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(ie=o),s.push({type:"step-finish",finishReason:t.finishReason,usage:e});break}case"finish":!de&&ue.length>0&&(ce+=ue,s.push({type:"text-delta",delta:ue}),ue=""),te=ot(t.totalUsage);break;case"error":if(Te.clear(),this.isTurnAborted(r)||j(t.error)){r.aborted=!0,r.cancellationReason=at(r.cancellationReason,t.error);break}ge=st(t.error),ae=t.error,he=!0,re=Ye(t.error);break;case"abort":Te.clear(),r.aborted=!0,r.cancellationReason=at(r.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(r)||j(e)?(r.aborted=!0,r.cancellationReason=at(r.cancellationReason,e)):(ge=st(e),ae=e,he=!1,re=Ye(e))}finally{r.abortController.signal.removeEventListener("abort",ye),Te.dispose(),this.clearDebugTimer(be)}if(this.debug(s,"model","fullStream finished",p,{textChars:ce.length}),void 0!==G){try{await Xe(ee.steps,r.abortController.signal)}catch{}if(this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);if(r.pendingToolCalls.size>0)return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:"context_maintenance_unsettled_tools:输入已保存,请先核对未结算操作。"});const e=lt(Ge(r));this.messages.push(...e),e.length>0&&this.persistMessages(e,"raw_transcript"),Ve(r),f=this.messages.length,r.completedStepCount+=pe,void 0!==V&&(L=void 0===L?V:nt(L,V),this.sessionUsage=nt(this.sessionUsage,V)),this.toolCoordinator.finishTurn();const i=G;if(e.length>0){if(r.completedStepCount>=this.maxSteps)return void s.push({type:"message-finish",text:ce,stoppedAtStepLimit:!0,sessionUsage:{...this.sessionUsage},...void 0===L?{}:{totalUsage:L},...void 0===se?{}:{contextInputTokens:se}});s.push({type:"message-start",messageId:t()});continue}if("shape_changed"===i.reason)continue;if(k||!0!==this.compaction?.enabled)return void s.push({type:"error",stage:"plan",message:`context_request_budget_unrecoverable:输入和已完成操作已保留;当前请求未通过预算检查(${i.reason},估算输入 ${Math.ceil(i.budget.calibratedInputEstimate)},输入上限 ${i.budget.availableInputCeiling??"未知"},最近实测 ${i.budget.latestMeasuredInput??"未知"})。可继续发送较小的新要求或手动压缩。`});k=!0,this.requestBudgets.beginMaintenance(i.budget,r.inputId);const n=void 0===i.budget.maintenanceTarget?void 0:Math.max(1,.5*i.budget.maintenanceTarget-(i.budget.calibratedInputEstimate-i.budget.messageTokens));let a=!1;try{a=await this.runCompaction(s,"auto",r,!1,n,(e,t)=>o({history:e,explicitSkill:O,capabilityReminder:$,...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:b,project:e=>this.projectModelMessages(e),...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions}}).messages)}catch(e){if(this.isTurnAborted(r))throw e;this.debug(s,"compaction","summary failed; original context retained",p,{message:Ye(e)})}if(I=a?void 0:i.budget,f=this.messages.length,this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,p);s.push({type:"message-start",messageId:t()});continue}if(void 0!==re&&this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);if(void 0!==re&&!ge&&he&&m?.isRecoverable(ae)&&void 0!==g&&!r.userRejected&&void 0===le&&void 0===R.message){v=ae;try{await Xe(ee.steps,r.abortController.signal)}catch(e){if(r.abortController.signal.throwIfAborted(),!h.isInstance(e)&&e!==ae)throw e}const e=lt(Ge(r)),t=new Map;for(const s of e)if("tool"===s.role)for(const e of s.content)"tool-result"===e.type&&t.set(e.toolCallId,(t.get(e.toolCallId)??0)+1);if([...this.uncoveredToolExecutions.values()].some(e=>{const s=t.get(e.toolCallId)??0;return t.set(e.toolCallId,s-1),0===s})||[...r.pendingToolCalls.values()].some(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence)))he=!1,re="网络中断且操作结果尚未完整结算;已停止自动恢复,请先核对结果。";else{if(this.toolCoordinator.finishTurn(),e.length>0&&(this.persistMessages(e,"raw_transcript"),this.messages.push(...e)),Ve(r),f=this.messages.length,this.persistRecoveryCancellations(s,r),f=this.messages.length,r.completedStepCount+=pe,void 0!==V&&(L=void 0===L?V:nt(L,V),this.sessionUsage=nt(this.sessionUsage,V)),r.completedStepCount>=this.maxSteps)return void s.push({type:"error",stage:"execute",message:"已达单轮最大工具步数;未完成的回复已丢弃,输入和已完成的操作已保留。"});const t=await g.attempt(ae,r.abortController.signal,e=>s.push({type:"model-recovery",attempt:e}));if(t.recovered){v=void 0;continue}ae=t.error,re=Ye(t.error)}}if(void 0!==re){if(he&&!ge&&(v=ae),he&&!ge&&m?.formatError&&(re=m.formatError(ae)),ge&&void 0!==K&&(M.add(K.fingerprint),E=K),this.messages.splice(f),ge){const e=0===ce.length&&!de,t=e&&x<1,o=!(!t&&e)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(e&&o&&t){x+=1;continue}const i=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,A,ce.length>0,p),void s.push({type:"error",stage:"execute",message:`${re}${i}`})}return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:re})}if(r.aborted||r.abortController.signal.aborted)return r.cancellationReason=at(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,f,p);let Ce;this.debug(s,"model","awaiting response messages",p);const Ie=this.scheduleDebug(s,"model","still awaiting response messages",p);try{const e=await ee.steps;Ce=ze(r,e)}catch(e){if(this.clearDebugTimer(Ie),this.isTurnAborted(r)||j(e))return r.aborted=!0,r.cancellationReason=at(r.cancellationReason,e),void this.persistCancelledTurn(s,r,f,p);const t=st(e);if(t&&void 0!==K&&(E=K,M.add(K.fingerprint)),this.messages.splice(f),t){const t=0===ce.length&&!de,o=t&&x<1,i=!(!o&&t)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(t&&i&&o){x+=1;continue}const n=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,A,ce.length>0,p),void s.push({type:"error",stage:"execute",message:`${Ye(e)}${n}`})}return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:Ye(e)})}finally{this.clearDebugTimer(Ie)}if(this.debug(s,"model","response messages ready",p,{responseMessages:Ce.length}),this.isTurnAborted(r))return r.cancellationReason=at(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,f,p);const xe=lt(Ce);this.messages.push(...xe);const ke=le??R.message;if(void 0!==ke){const e=0===ce.length?ke:`\n${ke}`;ce+=e,s.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:ke})}this.debug(s,"persist","persisting messages",p,{appendedMessages:this.messages.length-f}),this.persistMessages(this.messages.slice(f),"raw_transcript"),Ve(r),f=this.messages.length,this.debug(s,"persist","messages persisted",p,{totalMessages:this.messages.length}),te&&(L=void 0===L?te:nt(L,te),this.sessionUsage=nt(this.sessionUsage,te));const Se=se;void 0!==Se&&(this.lastInputTokens=Se,this.measuredProjectedTokens=N??q,this.promptOverhead=Math.max(0,Se-this.measuredProjectedTokens-l)),r.completedStepCount+=pe;const we=r.completedStepCount>=this.maxSteps&&"tool-calls"===ne;if(s.push({type:"message-finish",text:ce,...void 0===L?{}:{totalUsage:L},sessionUsage:{...this.sessionUsage},...void 0!==se?{contextInputTokens:se}:{},...void 0!==ie?{outputTokensPerSecond:ie}:{},...we?{stoppedAtStepLimit:!0}:{}}),!r.pausedForContextPressure||"tool-calls"!==ne||we||void 0!==ke)return;if(r.pausedForContextPressure=!1,this.debug(s,"compaction","turn paused for context pressure",p,{continuations:r.contextPressureContinuations,pressureTokens:this.contextPressureTokens()}),this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,p);s.push({type:"message-start",messageId:t()})}}catch(e){if(this.isTurnAborted(r)||j(e))return r.aborted=!0,r.cancellationReason=at(r.cancellationReason,r.abortController.signal.reason??e),void(void 0!==f?this.persistCancelledTurn(s,r,f,p):this.emitCancellation(s,r));void 0!==f&&this.messages.splice(f),this.debug(s,"turn","error",p,{message:Ye(e)}),s.push({type:"error",stage:"execute",message:Ye(e)})}finally{this.requestBudgets.abandonMaintenance(r.inputId),void 0!==b&&clearTimeout(b),this.toolCoordinator.finishTurn();try{m?.onTurnEnd?.(this.isTurnAborted(r)?void 0:v)}finally{this.activeTurn===r&&(this.activeTurn=void 0),s.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)Qe(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Se[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=de(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!==W.policyDenied&&e.outcome.kind!==W.userRejected&&e.outcome.kind!==W.invalidInput&&(e.outcome.kind!==W.cancelled||e.outcome.executionState!==$.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?[]:[de(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=He(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Me(lt(Ge(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,ue({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 的操作。${Fe}`}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}: ${Ye(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+We,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}:{},...void 0!==e.fullDiff?{fullDiff:e.fullDiff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){const s=this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}});return s&&void 0!==this.activeTurn&&(this.activeTurn.userRejected=!0),s}getMessages(){return ce(pe(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=>({...G(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:{...G(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getRequestBudgetState(){return this.requestBudgets.view()}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.onProviderOptionsChange?.(e),this.providerOptions=e}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.modelRecovery=e.modelRecovery,this.requestBudgets=new r,this.contextWindowSource=e.contextWindowSource,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,this.promptOverhead=void 0,void 0!==e.toolSchemaPolicy&&(this.toolSchemaPolicy=e.toolSchemaPolicy,this.applyToolSchemaPolicy()&&this.refreshCapabilityManifest())}modelTools(){if(0===this.excludedToolIds.size)return this.tools;const e=this.excludedToolIds;return Object.fromEntries(Object.entries(this.tools).filter(([t])=>!e.has(t)))}recordToolSchemaIssues(e){for(const[t,s]of Object.entries(e))this.agentToolSchemaIssues.set(t,s)}applyToolSchemaPolicy(){const e=this.toolSchemaPolicy,t=new Set;if(e)for(const[s,o]of this.agentToolSchemaIssues)e(o)||t.add(s);const s=this.excludedToolIds,o=t.size!==s.size||[...t].some(e=>!s.has(e));for(const e of t)if(!s.has(e)){const t=this.registry.resolve(e);this.onToolExcluded?.({toolId:e,agentName:t?.agentName??"",toolName:t?.toolName??e,issues:this.agentToolSchemaIssues.get(e)??[]})}return this.excludedToolIds=t,o}stopOnContextPressure(e,t,s,o=()=>!0){return({steps:i})=>{const n=this.compaction,r=i.at(-1);if(void 0===n||!n.enabled||void 0===this.contextWindow||void 0===r||"tool-calls"!==r.finishReason||i.length<2&&this.messages.length<2||r.toolResults.some(e=>U(e.output).kind===W.userRejected))return!1;const a=ot(r.usage),l=X(this.projectModelMessages([...this.messages,...ze(e,i)])),c=s?.()??(void 0===a.inputTokens?this.promptOverheadTokens()+l:Math.max(0,a.inputTokens+l-t()));return!(c/this.contextWindow<n.threshold||!o(c))&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:X([{role:"user",content:e}]),s=X(this.projectModelMessages(this.messages));return void 0!==this.lastInputTokens&&void 0!==this.measuredProjectedTokens?Math.max(0,this.lastInputTokens+s-this.measuredProjectedTokens+t):this.promptOverheadTokens()+s+t}observationResultId(e){if(this.observationResultIds.has(e))return this.observationResultIds.get(e);const t=this.listPersistedToolExecutions?.({toolCallId:e,limit:2})??[];t.length>1&&this.ambiguousObservationCallIds.add(e);const s=1===t.length?t[0]?.id:void 0;return this.observationResultIds.set(e,s),s}readObservation(e){const t=this.getPersistedToolExecution?.(e.resultId)??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e.resultId),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();if(!t)throw new Error("当前会话中没有这个工具结果");const s=[...this.observationRetentionByToolId].find(([e])=>{const s=this.registry.resolve(e);return s?.agentName===t.agentName&&s.toolName===t.toolName})?.[1];if(!s)throw new Error("该结果不是可回查的浏览器观察");return Pe(e,t,[...this.messages,...this.activeTurn?Ge(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return Ae(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(fe(this.capabilityManifest,me.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Z(e))}currentCheckpointReminder(e){return void 0===this.compactionCheckpoint?void 0:Ie(this.compactionCheckpoint,this.sessionManagerInstanceId,e)}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,He(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:X([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages,t=e=>({...e,message:ie(e.message,this.getInputSkillCheckpoint?.(e.sequence)??this.inputSkillCheckpoints.get(e.sequence))});if(void 0===e)return this.inMemoryTranscript.map(t);const s=[];let o=-1;for(;;){const i=e({afterSequence:o,limit:500});s.push(...i.map(t));const n=i.at(-1)?.sequence;if(i.length<500||void 0===n||n<=o)break;o=n}return s}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}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,this.compactionTargetTokens())}catch(s){this.isTurnAborted(t)?this.emitCancellation(e,t):e.push({type:"error",stage:"plan",message:Ye(s)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}async runCompaction(e,t,s,i,n,r){const a=Date.now(),l=this.lastInputTokens,c=this.compaction,u=c?.strategy??"summarize";e.push({type:"compaction-start",reason:t});const d=s=>(e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:0,kept:this.messages.length,...s?{failure:s}:"manual"===t?{recoveryNotice:"当前内容未产生可用的压缩,已保留原上下文。"}:{}}),!1);if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(!c)return d();try{const p=[...this.messages],h=this.compactionCheckpoint,m=fe(this.capabilityManifest,me.transcriptRead),g=void 0===h?void 0:3===h.version?h.taskSummary:Ie(h,this.sessionManagerInstanceId,m),v=await Q({messages:p,strategy:u,keepRecentTurns:c.keepRecentTurns,keepRecentTokens:c.keepRecentTokens,model:this.model,...void 0===g?{}:{previousSummary:g},...void 0===n?{}:{targetTokens:n},...void 0===this.contextWindow?{}:{contextWindow:this.contextWindow},...void 0===c.timeoutMs?{}:{timeoutMs:c.timeoutMs},...void 0===c.maxOutputTokens?{}:{maxOutputTokens:c.maxOutputTokens},...void 0===this.structuredOutputReasoning?{}:{structuredOutputReasoning:this.structuredOutputReasoning},...void 0===this.structuredOutputProviderOptions?{}:{structuredOutputProviderOptions:this.structuredOutputProviderOptions},...void 0===s?{}:{abortSignal:s.abortController.signal}});if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(0===v.removed)return d();const f=v.summary??("truncate"===u?g??"Earlier messages were archived. Consult the original transcript for historical details.":void 0);if(void 0===f||0===f.trim().length)return d();if(Me(v.messages).status===we.repaired)return d();const b=this.currentCheckpointReminder(m),T=(e,t)=>void 0===r?this.requestBudgets.projectedMessageTokens(o({history:e,explicitSkill:{skillNames:[],userPrompt:"",modelUserContent:""},capabilityReminder:"",...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:this.modelTools(),project:e=>this.projectModelMessages(e)}).messages):this.requestBudgets.projectedMessageTokens(r(e,t)),y=T(p,b),C=new Error("compaction_candidate_did_not_shrink");let I=y;const x=e=>{const t=Ie(e,this.sessionManagerInstanceId,m);if(I=T(v.messages,t),I>=y)throw C};let k;try{if(this.commitPersistedCompaction)k=this.commitPersistedCompaction({messages:v.messages,expectedActiveMessages:p,expectedLatestCheckpointId:h?.id,summary:f,validateCheckpoint:x});else{const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=ke({summary:f,generation:(h?.generation??0)+1,...h?{previousCheckpointId:h.id}:{},transcript:{messages:{fromSequenceExclusive:-1,throughSequence:e.at(-1)?.sequence??h?.transcript.messages.throughSequence??-1},toolExecutions:{fromSequenceExclusive:-1,throughSequence:t.at(-1)?.sequence??h?.transcript.toolExecutions.throughSequence??-1},completeness:h?.transcript.completeness??"complete"},toolState:xe(e.map(e=>e.message),t)});x(s),this.onReplace?.(v.messages),k=s}}catch(e){if(e===C)return d();throw e}return this.messages.splice(0,this.messages.length,...v.messages),this.compactionCheckpoint=k,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:v.removed,kept:v.kept,checkpointId:k.id,checkpointGeneration:k.generation,checkpointSummaryStatus:"summarize"===u?"valid":"skipped"}),this.debug(e,"compaction","task summary committed",a,{removed:v.removed,kept:v.kept,beforeEstimatedTokens:y,afterEstimatedTokens:I}),!0}catch(e){throw d(this.isTurnAborted(s)?void 0:e instanceof J?{reason:m.timeout,timeoutMs:e.timeoutMs}:{reason:m.error}),e}}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(s){return this.isTurnAborted(t)||e.push({type:"error",stage:"plan",message:Ye(s)}),!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&&!M(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${Ye(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=P.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(R))}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??P.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const o=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。",i=e.userMessagePersisted?"本轮输入已保存,但进度或中断记录未能保存。":"刚才的对话和进度未能保存。";return t===P.timeout?`本轮等待时间过长,已自动停止。${i}${o}`:t===P.runtime?`本轮因运行异常而中断。${i}${o}`:`已停止本轮。${i}${o}`}const o=s.execSessionIds,i=fe(this.capabilityManifest,me.sessionList);switch(t){case P.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case P.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":be(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case P.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??P.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=fe(this.capabilityManifest,me.sessionList),n=Fe;switch(t){case P.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case P.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:be(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case P.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=P.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,De.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=De.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);const n=i===De.keepRaw,r=n?Me(lt(Ge(t))).messages:[],a=n?He(t):Ke(t);t.cancellationPersisted=!0;const l=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...l],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[ue({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),N(this.cancellationDisplayMessage(e),e.cancellationReason??P.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(e,t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${Ye(t)}`}),!1}}persistRecoveryCancellations(e,t){const s=[];for(const o of t.pendingToolCalls.values()){const i=L({kind:W.cancelled,reason:P.runtime,executionState:$.notExecuted},"模型连接中断,本工具调用确定未执行;重新生成的调用仍需正常校验与审批。"),n=H({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:i});this.persistToolExecution(n,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:n.id,outcome:i.outcome,display:i.display,output:i.display,isError:!0});const r=`${o.agentName}__${o.toolName}`;s.push({role:"assistant",content:[{type:"tool-call",toolCallId:o.toolCallId,toolName:r,input:o.input}]},{role:"tool",content:[{type:"tool-result",toolCallId:o.toolCallId,toolName:r,output:i.model}]}),t.pendingToolCalls.delete(o.toolCallId)}s.length>0&&(this.persistMessages(s,"raw_transcript"),this.messages.push(...s))}persistPendingToolCancellations(e,t){const s=t.cancellationReason??P.runtime;for(const o of t.pendingToolCalls.values()){const i=this.toolCoordinator.hasExecutionStarted(o.executionOccurrence)?$.outcomeUnknown:$.notExecuted,n=i===$.notExecuted?`工具调用在开始执行前因本轮 ${s} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${s} 中断而取消;最终结果尚未确认`,r=L({kind:W.cancelled,reason:s,executionState:i},n,{raw:{cancellationReason:s,executionState:i,abortReason:Ye(t.abortController.signal.reason)}}),a=H({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:r});this.persistToolExecution(a,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:r.display,isError:!0}),t.pendingToolCalls.delete(o.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=P.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(A),!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??=P.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(R)),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} 后台清理失败: ${Ye(e)}\n`)});await s(e,$e)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String($e)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${Ye(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${Ye(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{describeAppOutput as e}from"@roll-agent/protocol";import{randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{buildSessionModelRequest as o}from"./model-request.js";import{ModelRecoveryBudget as i}from"./model-recovery.js";import{ContextMaintenanceRequired as n,RequestBudgetTracker as r}from"./request-budget.js";import{buildUserMessageContent as a,normalizeSessionSendInput as l}from"./session-attachments.js";import{stepCountIs as c,streamText as u,wrapLanguageModel as d,InvalidToolInputError as p,NoOutputGeneratedError as h}from"ai";import{COMPACTION_FAILURE_REASONS as m}from"../types/events.js";import{buildAgentToolset as g}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as v}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as f,skillInputErrorResult as b}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as y}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as T}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as C}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as I}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as k,EXEC_LIST_NAME as x,EXEC_POLL_NAME as S,buildSessionExecToolset as w}from"../tool-bridge/session-exec-tool.js";import{SessionManager as M}from"../bash/session/session-manager.js";import{isTerminalSessionState as E}from"../bash/session/types.js";import{withCleanEnv as R}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as P,SESSION_CANCELLATION_REASONS as O,TURN_TIMEOUT_ABORT_REASON as A,USER_CANCELLATION_ABORT_REASON as N,createTurnCancellationMessage as j,isTurnTimeoutAbortReason as q}from"../types/cancellation.js";import{ToolRegistry as $}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as L,TOOL_OUTCOME_KINDS as W,createToolResult as D,failedToolResult as F,isNormalizedToolResult as B,normalizeToolResult as _,readDisplayOutput as U,readToolOutcome as z}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as H}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as G,toRedactedToolExecutionRecordSummary as K}from"../tool-bridge/tool-execution-record.js";import{ToolExecutionCoordinator as V}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as Y}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{CompactionTimeoutError as Q,compactMessages as X,estimateMessagesTokens as Z,estimateTextTokens as ee,isCompactionSummaryAcknowledgement as te,readCompactionSummaryPayload as se}from"./compactor.js";import{AsyncEventQueue as oe}from"./event-queue.js";import{ToolInputActivityTracker as ie}from"./tool-input-activity.js";import{projectTurnInputSkillCheckpoint as ne,turnInputSkillCheckpointSchema as re}from"../store/turn-input.js";import{attachExplicitSkillCheckpoint as ae,prepareExplicitSkillContext as le,readExplicitSkillCheckpoint as ce,stripExplicitSkillCheckpoints as ue}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as de,createToolLedgerGapRecoveryMessage as pe,stripCancelledTurnRecoveryMessages as he}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as me,CAPABILITY_TOOL_ROLES as ge,buildEffectiveCapabilityTurnContext as ve,buildEffectiveCapabilityManifest as fe,findCapabilityToolId as be,isProcessBoundHostMode as ye}from"./capability-manifest.js";import{buildCapabilityTurnReminder as Te,buildChatSystemPromptFromManifest as Ce}from"./system-prompt.js";import{threadDerivedFromSchema as Ie}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as ke,buildCompactionToolState as xe,createSummaryCheckpoint as Se,TRANSCRIPT_MESSAGE_PROVENANCES as we}from"./compaction-checkpoint.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Me,repairActiveToolProtocol as Ee}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Re}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as Pe}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as Oe}from"./observation-readback.js";import{canonicalObservationOutput as Ae,projectObservationMessages as Ne,restoreCanonicalObservationOutputs as je}from"./observation-projection.js";import{UserInputInteractionManager as qe}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as $e}from"../tool-bridge/user-input-tool.js";const Le=6e3,We=3e5,De=1,Fe={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Be="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",_e="AI_InvalidToolInputError:";function Ue(){return{inputId:t(),abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalToolOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0,userRejected:!1}}function ze(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=je(t.response.messages,e.canonicalToolOutputs);return e.completedStepResponses.set(s,i),i}function He(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??je(t.response.messages,e.canonicalToolOutputs))}function Ge(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function Ke(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ve(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ye(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function Je(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=Qe(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function Qe(e){try{return JSON.stringify(e)??void 0}catch{return}}function Xe(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==se(e.content)||"assistant"===e.role&&te(e.content)}function Ze(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 et(e){return Je(U(e))}function tt(e){return p.isInstance(e)||"string"==typeof e&&e.startsWith(_e)?W.invalidInput:W.toolFailed}function st(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>z(e.output).kind===W.userRejected)??!1}function ot(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(Je(e))}function it(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 nt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function rt(e,t){const s=nt(e.cachedInputTokens,t.cachedInputTokens),o=nt(e.cacheWriteTokens,t.cacheWriteTokens),i=nt(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 at(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function lt(e,t){return void 0!==e?e:q(t)?O.timeout:O.runtime}function ct(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 ut(e,t,s){for(const o of Object.keys(t))e[o]=s}function dt(e,t,s){const o={[k]:ge.sessionCommand,[S]:ge.sessionPoll,[x]:ge.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}export class AgentSession{id;model;modelRecovery;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];contextWindow;compaction;turnTimeoutMs;onClose;onBeforeTurn;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillExecutionLibrary;skillToolId;refreshSkillLibrary;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new Y;userInputInteractions=new qe;onAcceptInput;onRecordInputSkillCheckpoint;getInputSkillCheckpoint;inputSkillCheckpoints=new Map;toolCoordinator=new V;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;requestBudgets=new r;contextWindowSource;constructor(e){this.id=e.id,this.model=e.model,this.modelRecovery=e.modelRecovery,this.contextWindowSource=e.contextWindowSource,this.maxSteps=e.maxSteps;const t=e.initialMessages?ct(e.initialMessages):[];this.messages=[...Ee(t).messages],this.onPersist=e.onPersist,this.onAcceptInput=e.onAcceptInput,this.onRecordInputSkillCheckpoint=e.onRecordInputSkillCheckpoint,this.getInputSkillCheckpoint=e.getInputSkillCheckpoint,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=(e.initialCheckpoint?.transcript.messages.throughSequence??-1)+1;for(const e of this.messages)Xe(e)||(this.inMemoryTranscript.push({sequence:s,provenance:we[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.onBeforeTurn=e.onBeforeTurn,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.derivedFrom=void 0===e.derivedFrom?void 0:Ie.parse(e.derivedFrom),this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillExecutionLibrary=e.skillLibrary,this.refreshSkillLibrary=e.refreshSkillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName)),this.toolSchemaPolicy=e.toolSchemaPolicy,this.onToolExcluded=e.onToolExcluded;const o=new $,i={},n=$e({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,ut(i,n.tools,ge.userInput);const r=e.readCheckpointTranscript?Re(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};ut(i,r,ge.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};ut(i,a,ge.skill);const l=new J,c=e.fileTools?C(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:l}):void 0;c&&(ut(i,c.readTools,ge.fileRead),ut(i,c.editTools,ge.fileEdit),ut(i,c.verifyTools,ge.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},d=e.bashClassifier?{classifier:e.bashClassifier}:{},p=e.bash?I(e.bash,o,u,d):{};ut(i,p,ge.shell),e.bashSession&&(this.sessionManager=new M({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:R(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const h=e.bashSession&&this.sessionManager?w({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...d,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};dt(i,h,o);const m=e.agentInstall,f=m?v({catalog:m.catalog,install:async(e,t)=>{const s=await m.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}):{};ut(i,f,ge.agentInstall);const b=e.schedules?y(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};ut(i,b.createTools,ge.scheduleCreate),ut(i,b.extendTools,ge.scheduleExtend),ut(i,b.listTools,ge.scheduleList);const T=g(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);ut(i,T.tools,ge.agent);const k=T.observationRetentionByToolId.size>0?Pe(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(k)[0],ut(i,k,ge.observationRead),this.tools={...r,...k,...a,...c?{...c.readTools,...c.editTools,...c.verifyTools}:{},...p,...h,...f,...b.createTools,...b.extendTools,...b.listTools,...T.tools},this.registry=T.registry;for(const[e,t]of T.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(T.schemaIssuesByToolId),this.applyToolSchemaPolicy(),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 fe({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??me.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=Ce(this.capabilityManifest,{...void 0!==this.derivedFrom?{derivedFrom:this.derivedFrom}:{},...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){const t=f(()=>{if(!this.skillExecutionLibrary)throw new Error("skill library 不可用");return this.skillExecutionLibrary},e,this.toolCoordinator,{...void 0===this.skillToolId?{}:{toolId:this.skillToolId},names:this.skillSummaries.map(e=>e.name)});return this.skillToolId??=Object.keys(t)[0],t}applySkillLibrary(e){const t=e?.list()??[],s=t.length!==this.skillSummaries.length||t.some((e,t)=>e.name!==this.skillSummaries[t]?.name),o=JSON.stringify(t)!==JSON.stringify(this.skillSummaries);if(this.skillLibrary=e,this.skillSummaries=t,s){if(void 0!==this.skillToolId){const e={...this.tools};delete e[this.skillToolId],delete this.toolRoles[this.skillToolId],this.tools=e}const e=this.buildSkillTools(this.registry);ut(this.toolRoles,e,ge.skill),this.tools={...this.tools,...e}}o&&this.refreshCapabilityManifest()}async refreshSkills(e){if(void 0!==this.refreshSkillLibrary){const t=await Ze(this.refreshSkillLibrary(e),e);e.throwIfAborted(),this.applySkillLibrary(t)}this.skillExecutionLibrary=this.skillLibrary}skillToolInputError(e,t){return e===this.skillToolId&&void 0!==this.skillExecutionLibrary?b(this.skillExecutionLibrary,t):void 0}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=g([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);ut(this.toolRoles,t.tools,ge.agent),this.tools={...this.tools,...t.tools};for(const[e,s]of t.observationRetentionByToolId)this.observationRetentionByToolId.set(e,s);if(void 0===this.observationRecallToolId&&this.observationRetentionByToolId.size>0){const e=Pe(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],ut(this.toolRoles,e,ge.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.toolSourceAgentNames.add(e.source.agentName)}e.skillLibrary&&this.applySkillLibrary(e.skillLibrary),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");this.onBeforeTurn?.();const t=l(e),s=new oe;this.emit=e=>s.push(e);const o=Ue();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:Je(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");this.onBeforeTurn?.();const t=new oe;this.emit=e=>t.push(e);const s=Ue();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:Je(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(s,r,l){const m=Date.now(),g=this.modelRecovery,v=void 0===g?void 0:new i(g);let f,b,y;const C=()=>{r.abortController.signal.aborted||(this.captureCancellationActivity(r),r.aborted=!0,r.cancellationReason=O.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),r.abortController.abort(A))},I=a(l.text,l.attachments);try{g?.onTurnStart?.();const i={role:"user",content:I};let a;try{void 0!==this.onAcceptInput?a=this.onAcceptInput(r.inputId,i).transcriptSequence:(a=(this.listCompactionTranscriptEvidence().at(-1)?.sequence??-1)+1,this.onPersist?.([i])),this.recordPersistedMessagesInMemory([i]),this.messages.push(i),r.userMessagePersisted=!0,b=this.messages.length}catch(e){return void s.push({type:"error",stage:"plan",message:`输入持久化失败,未开始模型请求: ${Je(e)}`})}if(void 0!==this.turnTimeoutMs){const e=Math.max(0,this.turnTimeoutMs-(Date.now()-m));r.expiresAt=new Date(m+this.turnTimeoutMs).toISOString(),y=setTimeout(C,e),0===e&&C()}this.debug(s,"turn","start",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...l.attachments.length>0?{attachments:l.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void s.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${Je(e)}`})}if(b=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);this.syncWorkspaceInstructions(),await this.refreshSkills(r.abortController.signal);let k,x=!0,S=0,w=!1;const M=()=>Math.max(1024,.05*(this.contextWindow??0)),E=e=>void 0===k||e>=k.calibratedInputEstimate+M(),R=new Set;let P;const A=T(),N=le({rawInput:l.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary});void 0!==r.expiresAt&&Date.now()>=Date.parse(r.expiresAt)&&C();const j=i;if(N.skillNames.length>0&&!this.isTurnAborted(r)){const e=ce(ae(i,N));if(void 0===e)throw new Error("Explicit Skill checkpoint could not be created");this.onRecordInputSkillCheckpoint?.(r.inputId,e),this.inputSkillCheckpoints.set(a,re.parse(e))}if(b=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);s.push({type:"message-start",messageId:t()});let $={};try{$=await Ze(this.resolveDynamicCapabilityContext?.(r.abortController.signal)??{},r.abortController.signal)??{}}catch(e){if(this.isTurnAborted(r))return b=this.messages.length,r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason??e),void this.persistCancelledTurn(s,r,b,m);this.debug(s,"turn","dynamic capability context unavailable",m,{message:Je(e)})}const L=ve(this.capabilityManifest,{explicitSkillNames:N.skillNames,...$.ruleIds?{ruleIds:$.ruleIds}:{},...$.vcs?{vcs:$.vcs}:{},...$.origin?{origin:$.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=L;const D=Te(L);let U;for(;;){b=this.messages.length,r.pausedForContextPressure=!1;const i=be(this.capabilityManifest,ge.transcriptRead),a=this.currentCheckpointReminder(i),l=void 0===a?0:ee(a),y=this.modelTools(),T=(e=[])=>o({history:this.messages,completedMessages:e,explicitSkill:N,capabilityReminder:D,...void 0===a?{}:{checkpointReminder:a},system:this.systemPrompt,tools:y,...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions},project:e=>this.projectModelMessages(e)}),C=T();let I=C.shapeContext;this.debug(s,"model","calling streamText",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:S,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let $,L=0,z=0;const K=[];let V,Y,J,Q=!1;const X=d({model:this.model,middleware:{specificationVersion:"v4",wrapStream:async({params:e,doStream:t})=>{if(r.abortController.signal.aborted)throw r.abortController.signal.reason;const s=this.requestBudgets.prepare(e,{provider:this.model.provider,model:this.model.modelId,...void 0===this.contextWindow?{}:{window:this.contextWindow},...void 0===this.contextWindowSource?{}:{windowSource:this.contextWindowSource},threshold:this.compaction?.threshold??.75},I,r.inputId),o=s.maintenanceTarget,i=this.modelTools(),a=Object.keys(i).length!==Object.keys(y).length||Object.entries(y).some(([e,t])=>i[e]!==t),l=void 0!==s.availableInputCeiling&&s.calibratedInputEstimate>s.availableInputCeiling,c=!w&&!0===this.compaction?.enabled&&void 0!==o&&s.calibratedInputEstimate>=o&&(E(s.calibratedInputEstimate)||void 0!==k&&(s.shapeFingerprint!==k.shapeFingerprint||s.rawInputEstimate>=k.rawInputEstimate+M())),u=R.has(s.fingerprint)||void 0!==P&&s.rawInputEstimate>=P.rawInputEstimate;if(a||l||c||u)throw a&&(x=!0),V=new n(s,a?"shape_changed":u?"provider_rejected":l?"budget":"soft_target"),V;w=!1,Y=s,this.requestBudgets.dispatchedRequest(),Q=!1;const d=await t();if(void 0===g)return d;const p=d.stream.getReader();let h=!1;return{...d,stream:new ReadableStream({async pull(e){let t;try{t=await p.read()}catch(t){return Q=!1,e.enqueue({type:"error",error:t}),e.close(),void p.releaseLock()}if(t.done)return e.close(),void p.releaseLock();const s=t.value;if("finish"!==s.type||!h){if("finish"===s.type&&"error"===s.finishReason.unified)return h=!0,Q=!1,void e.enqueue({type:"error",error:new Error("模型未成功完成本步骤,未执行待处理工具。")});"finish"===s.type&&(Q=!0),"error"===s.type&&(Q=!1,h=!0),e.enqueue(s)}},async cancel(e){try{await p.cancel(e)}finally{p.releaseLock()}}})}}}}),te=()=>u({model:X,...void 0===g?{}:{maxRetries:0},system:C.system,messages:C.messages,tools:y,prepareStep:async()=>{x||await this.refreshSkills(r.abortController.signal),x=!1,L=Z(this.projectModelMessages([...this.messages,...K]));const e=T(K);return I=e.shapeContext,z=this.requestBudgets.projectedMessageTokens(e.messages),{messages:e.messages,system:e.system}},stopWhen:[()=>void 0!==g&&!Q,c(Math.max(1,this.maxSteps-r.completedStepCount)),st(),A.stop,this.stopOnContextPressure(r,()=>L,()=>this.requestBudgets.predict(T(K).messages,z),E)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(r,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,usage:s,finishReason:o})=>{if(void 0===g||"error"!==o){for(const e of t){if("tool-call"!==e.type||!("invalid"in e)||!0!==e.invalid)continue;const t=this.skillToolInputError(e.toolName,e.input);void 0!==t&&r.canonicalToolOutputs.set(e.toolCallId,t.model)}J=rt(J??{},it(s)),void 0!==Y&&this.requestBudgets.measured(Y,s.inputTokens),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:r.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{(void 0===g||Q)&&K.push(...ze(r,e))},onAbort:({steps:e})=>{if(void 0===g)for(const t of e)ze(r,t)}});let se;try{se=te()}catch(e){if(this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,b,m);if(!ot(e))throw e;this.messages.splice(b);const t=S<1,o=!!t&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(o&&t){S+=1;continue}return this.persistContextFailure(s,r,j,!1,m),void s.push({type:"error",stage:"execute",message:Je(e)})}this.debug(s,"model","streamText returned",m);let oe,ne,re,ae,le,ce,ue,de="",pe="",he=!1,me=0,ve=!1,fe=!1,ye=!1;const Te=this.scheduleDebug(s,"model","waiting for first stream event",m,{messages:this.messages.length}),Ce=new ie(e=>{const t=this.registry.resolve(e);return void 0===t?void 0:`${t.agentName}.${t.toolName}`},e=>s.push(e)),Ie=()=>Ce.clear();r.abortController.signal.addEventListener("abort",Ie,{once:!0});try{for await(const t of se.fullStream){if(this.closed){r.aborted=!0,r.cancellationReason??=O.runtime;break}switch(ye||(ye=!0,this.clearDebugTimer(Te),this.debug(s,"model","first stream event",m,{part:t.type})),t.type){case"start-step":void 0!==g&&s.push({type:"model-step-start"});break;case"tool-input-start":Ce.start(t.id,t.toolName);break;case"tool-input-delta":Ce.delta(t.id);break;case"tool-input-end":Ce.end(t.id);break;case"reasoning-start":s.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":s.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":s.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!he){const e=pe+t.text;if(at(e,N.userPrompt)){pe=e;break}if(pe.length>0){const e=pe+t.text;pe="",de+=e,s.push({type:"text-delta",delta:e});break}}de+=t.text,s.push({type:"text-delta",delta:t.text});break;case"tool-call":{Ce.end(t.toolCallId),he=!0,pe="";const e=this.trackPendingToolCall(r,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));s.push({type:"tool-call",toolCallId:t.toolCallId,agentName:e.agentName,toolName:e.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=r.pendingToolCalls.get(t.toolCallId),n=B(t.output)?t.output:_(t.output),a=n.outcome,l=n.display,c=G({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,r);const u=a.kind===W.success?Ae(n.raw,this.observationRetentionByToolId.get(t.toolName)):void 0;if(u){r.canonicalToolOutputs.set(t.toolCallId,u);const e=this.observationResultIds.get(t.toolCallId);void 0!==e&&e!==c.id&&this.ambiguousObservationCallIds.add(t.toolCallId),this.observationResultIds.set(t.toolCallId,this.ambiguousObservationCallIds.has(t.toolCallId)?void 0:c.id)}!0===i?.potentialSideEffect&&a.kind!==W.userRejected&&a.kind!==W.policyDenied&&a.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a,display:l,output:l,isError:a.kind!==W.success}),r.aborted||r.abortController.signal.aborted||a.kind!==W.userRejected||(ue=et(t.output));break}case"tool-error":{Ce.end(t.toolCallId);const o=this.registry.resolve(t.toolName),i=tt(t.error),n=(i===W.invalidInput?H(t.error):void 0)??et(t.error),a=r.pendingToolCalls.get(t.toolCallId)?.input??(p.isInstance(t.error)?t.error.toolInput:void 0),l=this.skillToolInputError(t.toolName,a)??F(i,n,{raw:t.error}),c=et(l);t.toolName===this.skillToolId&&r.canonicalToolOutputs.set(t.toolCallId,l.model);const u=G({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:a,result:l});this.persistToolExecution(u,r),!0===r.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&l.outcome.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:u.id,...void 0===u.appOutput?{}:{appOutput:e(u.appOutput)},outcome:l.outcome,display:l.display,output:c,isError:!0});break}case"finish-step":{if(Ce.clear(),void 0!==g&&void 0!==le)break;const e=it(t.usage);void 0!==e.inputTokens&&(ne=e.inputTokens,$=L),me+=1,ae=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(re=o),s.push({type:"step-finish",finishReason:t.finishReason,usage:e});break}case"finish":!he&&pe.length>0&&(de+=pe,s.push({type:"text-delta",delta:pe}),pe=""),oe=it(t.totalUsage);break;case"error":if(Ce.clear(),this.isTurnAborted(r)||q(t.error)){r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,t.error);break}fe=ot(t.error),ce=t.error,ve=!0,le=Je(t.error);break;case"abort":Ce.clear(),r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(r)||q(e)?(r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e)):(fe=ot(e),ce=e,ve=!1,le=Je(e))}finally{r.abortController.signal.removeEventListener("abort",Ie),Ce.dispose(),this.clearDebugTimer(Te)}if(this.debug(s,"model","fullStream finished",m,{textChars:de.length}),void 0!==V){try{await Ze(se.steps,r.abortController.signal)}catch{}if(this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);if(r.pendingToolCalls.size>0)return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:"context_maintenance_unsettled_tools:输入已保存,请先核对未结算操作。"});const e=ct(Ke(r));this.messages.push(...e),e.length>0&&this.persistMessages(e,"raw_transcript"),Ye(r),b=this.messages.length,r.completedStepCount+=me,void 0!==J&&(U=void 0===U?J:rt(U,J),this.sessionUsage=rt(this.sessionUsage,J)),this.toolCoordinator.finishTurn();const i=V;if(e.length>0){if(r.completedStepCount>=this.maxSteps)return void s.push({type:"message-finish",text:de,stoppedAtStepLimit:!0,sessionUsage:{...this.sessionUsage},...void 0===U?{}:{totalUsage:U},...void 0===ne?{}:{contextInputTokens:ne}});s.push({type:"message-start",messageId:t()});continue}if("shape_changed"===i.reason)continue;if(w||!0!==this.compaction?.enabled)return void s.push({type:"error",stage:"plan",message:`context_request_budget_unrecoverable:输入和已完成操作已保留;当前请求未通过预算检查(${i.reason},估算输入 ${Math.ceil(i.budget.calibratedInputEstimate)},输入上限 ${i.budget.availableInputCeiling??"未知"},最近实测 ${i.budget.latestMeasuredInput??"未知"})。可继续发送较小的新要求或手动压缩。`});w=!0,this.requestBudgets.beginMaintenance(i.budget,r.inputId);const n=void 0===i.budget.maintenanceTarget?void 0:Math.max(1,.5*i.budget.maintenanceTarget-(i.budget.calibratedInputEstimate-i.budget.messageTokens));let a=!1;try{a=await this.runCompaction(s,"auto",r,!1,n,(e,t)=>o({history:e,explicitSkill:N,capabilityReminder:D,...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:y,project:e=>this.projectModelMessages(e),...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions}}).messages)}catch(e){if(this.isTurnAborted(r))throw e;this.debug(s,"compaction","summary failed; original context retained",m,{message:Je(e)})}if(k=a?void 0:i.budget,b=this.messages.length,this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,m);s.push({type:"message-start",messageId:t()});continue}if(void 0!==le&&this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);if(void 0!==le&&!fe&&ve&&g?.isRecoverable(ce)&&void 0!==v&&!r.userRejected&&void 0===ue&&void 0===A.message){f=ce;try{await Ze(se.steps,r.abortController.signal)}catch(e){if(r.abortController.signal.throwIfAborted(),!h.isInstance(e)&&e!==ce)throw e}const e=ct(Ke(r)),t=new Map;for(const s of e)if("tool"===s.role)for(const e of s.content)"tool-result"===e.type&&t.set(e.toolCallId,(t.get(e.toolCallId)??0)+1);if([...this.uncoveredToolExecutions.values()].some(e=>{const s=t.get(e.toolCallId)??0;return t.set(e.toolCallId,s-1),0===s})||[...r.pendingToolCalls.values()].some(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence)))ve=!1,le="网络中断且操作结果尚未完整结算;已停止自动恢复,请先核对结果。";else{if(this.toolCoordinator.finishTurn(),e.length>0&&(this.persistMessages(e,"raw_transcript"),this.messages.push(...e)),Ye(r),b=this.messages.length,this.persistRecoveryCancellations(s,r),b=this.messages.length,r.completedStepCount+=me,void 0!==J&&(U=void 0===U?J:rt(U,J),this.sessionUsage=rt(this.sessionUsage,J)),r.completedStepCount>=this.maxSteps)return void s.push({type:"error",stage:"execute",message:"已达单轮最大工具步数;未完成的回复已丢弃,输入和已完成的操作已保留。"});const t=await v.attempt(ce,r.abortController.signal,e=>s.push({type:"model-recovery",attempt:e}));if(t.recovered){f=void 0;continue}ce=t.error,le=Je(t.error)}}if(void 0!==le){if(ve&&!fe&&(f=ce),ve&&!fe&&g?.formatError&&(le=g.formatError(ce)),fe&&void 0!==Y&&(R.add(Y.fingerprint),P=Y),this.messages.splice(b),fe){const e=0===de.length&&!he,t=e&&S<1,o=!(!t&&e)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(e&&o&&t){S+=1;continue}const i=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,j,de.length>0,m),void s.push({type:"error",stage:"execute",message:`${le}${i}`})}return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:le})}if(r.aborted||r.abortController.signal.aborted)return r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,b,m);let ke;this.debug(s,"model","awaiting response messages",m);const xe=this.scheduleDebug(s,"model","still awaiting response messages",m);try{const e=await se.steps;ke=He(r,e)}catch(e){if(this.clearDebugTimer(xe),this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,b,m);const t=ot(e);if(t&&void 0!==Y&&(P=Y,R.add(Y.fingerprint)),this.messages.splice(b),t){const t=0===de.length&&!he,o=t&&S<1,i=!(!o&&t)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(t&&i&&o){S+=1;continue}const n=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,j,de.length>0,m),void s.push({type:"error",stage:"execute",message:`${Je(e)}${n}`})}return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:Je(e)})}finally{this.clearDebugTimer(xe)}if(this.debug(s,"model","response messages ready",m,{responseMessages:ke.length}),this.isTurnAborted(r))return r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,b,m);const Se=ct(ke);this.messages.push(...Se);const we=ue??A.message;if(void 0!==we){const e=0===de.length?we:`\n${we}`;de+=e,s.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:we})}this.debug(s,"persist","persisting messages",m,{appendedMessages:this.messages.length-b}),this.persistMessages(this.messages.slice(b),"raw_transcript"),Ye(r),b=this.messages.length,this.debug(s,"persist","messages persisted",m,{totalMessages:this.messages.length}),oe&&(U=void 0===U?oe:rt(U,oe),this.sessionUsage=rt(this.sessionUsage,oe));const Me=ne;void 0!==Me&&(this.lastInputTokens=Me,this.measuredProjectedTokens=$??L,this.promptOverhead=Math.max(0,Me-this.measuredProjectedTokens-l)),r.completedStepCount+=me;const Ee=r.completedStepCount>=this.maxSteps&&"tool-calls"===ae;if(s.push({type:"message-finish",text:de,...void 0===U?{}:{totalUsage:U},sessionUsage:{...this.sessionUsage},...void 0!==ne?{contextInputTokens:ne}:{},...void 0!==re?{outputTokensPerSecond:re}:{},...Ee?{stoppedAtStepLimit:!0}:{}}),!r.pausedForContextPressure||"tool-calls"!==ae||Ee||void 0!==we)return;if(r.pausedForContextPressure=!1,this.debug(s,"compaction","turn paused for context pressure",m,{continuations:r.contextPressureContinuations,pressureTokens:this.contextPressureTokens()}),this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,m);s.push({type:"message-start",messageId:t()})}}catch(e){if(this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason??e),void(void 0!==b?this.persistCancelledTurn(s,r,b,m):this.emitCancellation(s,r));void 0!==b&&this.messages.splice(b),this.debug(s,"turn","error",m,{message:Je(e)}),s.push({type:"error",stage:"execute",message:Je(e)})}finally{this.requestBudgets.abandonMaintenance(r.inputId),void 0!==y&&clearTimeout(y),this.toolCoordinator.finishTurn();try{g?.onTurnEnd?.(this.isTurnAborted(r)?void 0:f)}finally{this.activeTurn===r&&(this.activeTurn=void 0),s.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)Xe(o)||(this.inMemoryTranscript.push({sequence:t,provenance:we[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=pe(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!==W.policyDenied&&e.outcome.kind!==W.userRejected&&e.outcome.kind!==W.invalidInput&&(e.outcome.kind!==W.cancelled||e.outcome.executionState!==L.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?[]:[pe(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=Ge(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Ee(ct(Ke(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,de({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 的操作。${Be}`}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}: ${Je(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+We,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}:{},...void 0!==e.fullDiff?{fullDiff:e.fullDiff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){const s=this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}});return s&&void 0!==this.activeTurn&&(this.activeTurn.userRejected=!0),s}getMessages(){return ue(he(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=>({...K(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:{...K(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getRequestBudgetState(){return this.requestBudgets.view()}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.onProviderOptionsChange?.(e),this.providerOptions=e}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.modelRecovery=e.modelRecovery,this.requestBudgets=new r,this.contextWindowSource=e.contextWindowSource,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,this.promptOverhead=void 0,void 0!==e.toolSchemaPolicy&&(this.toolSchemaPolicy=e.toolSchemaPolicy,this.applyToolSchemaPolicy()&&this.refreshCapabilityManifest())}modelTools(){if(0===this.excludedToolIds.size)return this.tools;const e=this.excludedToolIds;return Object.fromEntries(Object.entries(this.tools).filter(([t])=>!e.has(t)))}recordToolSchemaIssues(e){for(const[t,s]of Object.entries(e))this.agentToolSchemaIssues.set(t,s)}applyToolSchemaPolicy(){const e=this.toolSchemaPolicy,t=new Set;if(e)for(const[s,o]of this.agentToolSchemaIssues)e(o)||t.add(s);const s=this.excludedToolIds,o=t.size!==s.size||[...t].some(e=>!s.has(e));for(const e of t)if(!s.has(e)){const t=this.registry.resolve(e);this.onToolExcluded?.({toolId:e,agentName:t?.agentName??"",toolName:t?.toolName??e,issues:this.agentToolSchemaIssues.get(e)??[]})}return this.excludedToolIds=t,o}stopOnContextPressure(e,t,s,o=()=>!0){return({steps:i})=>{const n=this.compaction,r=i.at(-1);if(void 0===n||!n.enabled||void 0===this.contextWindow||void 0===r||"tool-calls"!==r.finishReason||i.length<2&&this.messages.length<2||r.toolResults.some(e=>z(e.output).kind===W.userRejected))return!1;const a=it(r.usage),l=Z(this.projectModelMessages([...this.messages,...He(e,i)])),c=s?.()??(void 0===a.inputTokens?this.promptOverheadTokens()+l:Math.max(0,a.inputTokens+l-t()));return!(c/this.contextWindow<n.threshold||!o(c))&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Z([{role:"user",content:e}]),s=Z(this.projectModelMessages(this.messages));return void 0!==this.lastInputTokens&&void 0!==this.measuredProjectedTokens?Math.max(0,this.lastInputTokens+s-this.measuredProjectedTokens+t):this.promptOverheadTokens()+s+t}observationResultId(e){if(this.observationResultIds.has(e))return this.observationResultIds.get(e);const t=this.listPersistedToolExecutions?.({toolCallId:e,limit:2})??[];t.length>1&&this.ambiguousObservationCallIds.add(e);const s=1===t.length?t[0]?.id:void 0;return this.observationResultIds.set(e,s),s}readObservation(e){const t=this.getPersistedToolExecution?.(e.resultId)??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e.resultId),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();if(!t)throw new Error("当前会话中没有这个工具结果");const s=[...this.observationRetentionByToolId].find(([e])=>{const s=this.registry.resolve(e);return s?.agentName===t.agentName&&s.toolName===t.toolName})?.[1];if(!s)throw new Error("该结果不是可回查的浏览器观察");return Oe(e,t,[...this.messages,...this.activeTurn?Ke(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return Ne(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(be(this.capabilityManifest,ge.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:ee(e))}currentCheckpointReminder(e){return void 0===this.compactionCheckpoint?void 0:ke(this.compactionCheckpoint,this.sessionManagerInstanceId,e)}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,Ge(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:Z([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages,t=e=>({...e,message:ne(e.message,this.getInputSkillCheckpoint?.(e.sequence)??this.inputSkillCheckpoints.get(e.sequence))});if(void 0===e)return this.inMemoryTranscript.map(t);const s=[];let o=-1;for(;;){const i=e({afterSequence:o,limit:500});s.push(...i.map(t));const n=i.at(-1)?.sequence;if(i.length<500||void 0===n||n<=o)break;o=n}return s}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}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,this.compactionTargetTokens())}catch(s){this.isTurnAborted(t)?this.emitCancellation(e,t):e.push({type:"error",stage:"plan",message:Je(s)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}async runCompaction(e,t,s,i,n,r){const a=Date.now(),l=this.lastInputTokens,c=this.compaction,u=c?.strategy??"summarize";e.push({type:"compaction-start",reason:t});const d=s=>(e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:0,kept:this.messages.length,...s?{failure:s}:"manual"===t?{recoveryNotice:"当前内容未产生可用的压缩,已保留原上下文。"}:{}}),!1);if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(!c)return d();try{const p=[...this.messages],h=this.compactionCheckpoint,m=be(this.capabilityManifest,ge.transcriptRead),g=void 0===h?void 0:3===h.version?h.taskSummary:ke(h,this.sessionManagerInstanceId,m),v=await X({messages:p,strategy:u,keepRecentTurns:c.keepRecentTurns,keepRecentTokens:c.keepRecentTokens,model:this.model,...void 0===g?{}:{previousSummary:g},...void 0===n?{}:{targetTokens:n},...void 0===this.contextWindow?{}:{contextWindow:this.contextWindow},...void 0===c.timeoutMs?{}:{timeoutMs:c.timeoutMs},...void 0===c.maxOutputTokens?{}:{maxOutputTokens:c.maxOutputTokens},...void 0===this.structuredOutputReasoning?{}:{structuredOutputReasoning:this.structuredOutputReasoning},...void 0===this.structuredOutputProviderOptions?{}:{structuredOutputProviderOptions:this.structuredOutputProviderOptions},...void 0===s?{}:{abortSignal:s.abortController.signal}});if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(0===v.removed)return d();const f=v.summary??("truncate"===u?g??"Earlier messages were archived. Consult the original transcript for historical details.":void 0);if(void 0===f||0===f.trim().length)return d();if(Ee(v.messages).status===Me.repaired)return d();const b=this.currentCheckpointReminder(m),y=(e,t)=>void 0===r?this.requestBudgets.projectedMessageTokens(o({history:e,explicitSkill:{skillNames:[],userPrompt:"",modelUserContent:""},capabilityReminder:"",...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:this.modelTools(),project:e=>this.projectModelMessages(e)}).messages):this.requestBudgets.projectedMessageTokens(r(e,t)),T=y(p,b),C=new Error("compaction_candidate_did_not_shrink");let I=T;const k=e=>{const t=ke(e,this.sessionManagerInstanceId,m);if(I=y(v.messages,t),I>=T)throw C};let x;try{if(this.commitPersistedCompaction)x=this.commitPersistedCompaction({messages:v.messages,expectedActiveMessages:p,expectedLatestCheckpointId:h?.id,summary:f,validateCheckpoint:k});else{const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=Se({summary:f,generation:(h?.generation??0)+1,...h?{previousCheckpointId:h.id}:{},transcript:{messages:{fromSequenceExclusive:-1,throughSequence:e.at(-1)?.sequence??h?.transcript.messages.throughSequence??-1},toolExecutions:{fromSequenceExclusive:-1,throughSequence:t.at(-1)?.sequence??h?.transcript.toolExecutions.throughSequence??-1},completeness:h?.transcript.completeness??"complete"},toolState:xe(e.map(e=>e.message),t)});k(s),this.onReplace?.(v.messages),x=s}}catch(e){if(e===C)return d();throw e}return this.messages.splice(0,this.messages.length,...v.messages),this.compactionCheckpoint=x,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:v.removed,kept:v.kept,checkpointId:x.id,checkpointGeneration:x.generation,checkpointSummaryStatus:"summarize"===u?"valid":"skipped"}),this.debug(e,"compaction","task summary committed",a,{removed:v.removed,kept:v.kept,beforeEstimatedTokens:T,afterEstimatedTokens:I}),!0}catch(e){throw d(this.isTurnAborted(s)?void 0:e instanceof Q?{reason:m.timeout,timeoutMs:e.timeoutMs}:{reason:m.error}),e}}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(s){return this.isTurnAborted(t)||e.push({type:"error",stage:"plan",message:Je(s)}),!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&&!E(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${Je(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=O.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(P))}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??O.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const o=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。",i=e.userMessagePersisted?"本轮输入已保存,但进度或中断记录未能保存。":"刚才的对话和进度未能保存。";return t===O.timeout?`本轮等待时间过长,已自动停止。${i}${o}`:t===O.runtime?`本轮因运行异常而中断。${i}${o}`:`已停止本轮。${i}${o}`}const o=s.execSessionIds,i=be(this.capabilityManifest,ge.sessionList);switch(t){case O.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case O.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":ye(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case O.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??O.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=be(this.capabilityManifest,ge.sessionList),n=Be;switch(t){case O.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case O.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:ye(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case O.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=O.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,Fe.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Fe.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);const n=i===Fe.keepRaw,r=n?Ee(ct(Ke(t))).messages:[],a=n?Ge(t):Ve(t);t.cancellationPersisted=!0;const l=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...l],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[de({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),j(this.cancellationDisplayMessage(e),e.cancellationReason??O.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(e,t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${Je(t)}`}),!1}}persistRecoveryCancellations(e,t){const s=[];for(const o of t.pendingToolCalls.values()){const i=D({kind:W.cancelled,reason:O.runtime,executionState:L.notExecuted},"模型连接中断,本工具调用确定未执行;重新生成的调用仍需正常校验与审批。"),n=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:i});this.persistToolExecution(n,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:n.id,outcome:i.outcome,display:i.display,output:i.display,isError:!0});const r=`${o.agentName}__${o.toolName}`;s.push({role:"assistant",content:[{type:"tool-call",toolCallId:o.toolCallId,toolName:r,input:o.input}]},{role:"tool",content:[{type:"tool-result",toolCallId:o.toolCallId,toolName:r,output:i.model}]}),t.pendingToolCalls.delete(o.toolCallId)}s.length>0&&(this.persistMessages(s,"raw_transcript"),this.messages.push(...s))}persistPendingToolCancellations(e,t){const s=t.cancellationReason??O.runtime;for(const o of t.pendingToolCalls.values()){const i=this.toolCoordinator.hasExecutionStarted(o.executionOccurrence)?L.outcomeUnknown:L.notExecuted,n=i===L.notExecuted?`工具调用在开始执行前因本轮 ${s} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${s} 中断而取消;最终结果尚未确认`,r=D({kind:W.cancelled,reason:s,executionState:i},n,{raw:{cancellationReason:s,executionState:i,abortReason:Je(t.abortController.signal.reason)}}),a=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:r});this.persistToolExecution(a,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:r.display,isError:!0}),t.pendingToolCalls.delete(o.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=O.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(N),!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??=O.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(P)),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} 后台清理失败: ${Je(e)}\n`)});await s(e,Le)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Le)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${Je(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${Je(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
|
-
import{randomUUID as e}from"node:crypto";import{AgentSession as s}from"./agent-session.js";import{resolveModelContextWindow as t}from"./context-window.js";import{createDefaultModelCatalog as o}from"./model-catalog-default.js";import{createWorkspaceInstructionsSource as i,parseWorkspaceInstructionsSetting as r}from"./workspace-instructions.js";import{CAPABILITY_HOST_MODES as n,shouldOfferAgentInstall as l,shouldOfferScheduleCreate as a}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as h}from"../types/command-classification.js";import{resolveShellProfile as c}from"../bash/profile.js";import{inspectGitVcsContext as d}from"./vcs-context.js";import{createToolLedgerGapRecoveryMessage as u}from"./cancelled-turn-recovery.js";const p="ConversationEngine is closing",m=e=>0===e.length;export function buildSessionExecSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),profile:e.profile,maxSessions:s.session.maxSessions,defaultYieldMs:s.session.defaultYieldMs,maxOutputTokens:s.session.maxOutputTokens,bufferCapacity:s.maxCaptureBytes,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}export function buildSessionBashSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),defaultTimeoutMs:s.defaultTimeoutMs,maxTimeoutMs:s.maxTimeoutMs,turnTimeoutMs:e.settings.turnTimeoutMs,maxCaptureBytes:s.maxCaptureBytes,maxModelOutputChars:s.maxModelOutputChars,profile:e.profile,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}function v(){return new Error(p)}function g(e){if(null===e.workspaceInstructions)return;if(void 0!==e.workspaceInstructions)return e.workspaceInstructions;const s=process.cwd();return i({cwd:s,setting:r(e.settings.instructions,s),...e.onWorkspaceInstructionsIssue?{onIssue:e.onWorkspaceInstructionsIssue}:{}})}export class ConversationEngine{settings;agentHost;store;policy;fileToolsEnabled;maxSteps;providerOptions;modelRecovery;modelOverride;modelName;provider;toolSchemaPolicy;switchingProviderName;modelCatalog;structuredOutputProviderOptions;structuredOutputReasoning;debugEvents;explicitModel;explicitSources;explicitSkillLibrary;workspaceInstructions;onAgentBootstrapIssue;hostMode;scheduleTools;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;inspectVcsContext;shellEnv;onShellCommandSpawn;ready;refreshChain=Promise.resolve();resolvedCatalog=[];pendingInstalls=new Set;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;shutdownController=new AbortController;disposePromise;closing=!1;constructor(e){if(!e.model)throw new Error("ConversationEngine requires a model supplied by its host");if(void 0!==e.agentHost&&void 0!==e.sources)throw new Error("ConversationEngine accepts either sources or agentHost, not both");this.settings=e.settings,this.agentHost=e.agentHost,this.provider=e.provider,this.modelName=e.modelName,this.toolSchemaPolicy=e.toolSchemaPolicy??m,this.store=e.store,this.modelCatalog=e.modelCatalog??o(),this.policy=e.policy,this.fileToolsEnabled=e.fileToolsEnabled??!0,this.maxSteps=e.maxSteps??e.settings.maxSteps,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??n.embedded,this.scheduleTools=e.scheduleTools??void 0,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??c,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.workspaceInstructions=g(e),this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.inspectVcsContext=e.inspectVcsContext??d,this.shellEnv={...e.shellEnv??process.env},this.onShellCommandSpawn=e.onShellCommandSpawn}async createSession(s={}){this.assertAcceptingSessions();const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store?this.store.createThread({...void 0===s.id?{}:{id:s.id},...void 0===s.origin?{}:{origin:s.origin},...s.title?{title:s.title}:{},model:this.resolveModelName()}):s.id??e();return this.buildSession(t,o,[])}async resumeSession(e){if(this.assertAcceptingSessions(),!this.store)throw new Error("resumeSession requires a ThreadStore");if("scheduled"===this.store.getThread(e)?.origin.kind)throw new Error("定时执行会话是只读记录;请基于该次运行创建新对话");const s=this.liveSessions.get(e);if(void 0!==s)return s;if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.liveSessions.get(e);if(void 0!==o)return o;this.recoverUncoveredToolExecutionContext(e);const i=this.store.loadSessionState(e);return this.buildSession(t,e,i.messages,i.checkpoint)}async forkSession(e,s={}){if(this.assertAcceptingSessions(),!this.store)throw new Error("forkSession requires a ThreadStore");const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store.forkSnapshot(e,{...s,model:this.resolveModelName()});try{this.recoverUncoveredToolExecutionContext(o);const e=this.store.loadSessionState(o);return this.buildSession(t,o,e.messages,e.checkpoint)}catch(e){throw this.store.deleteThread(o),e}}assertAcceptingSessions(){if(this.closing)throw v()}resolveRuntimeShellProfile(){if(!this.settings.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const s="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${s},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){return buildSessionBashSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}})}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const s=this.settings.shell;return s.enabled&&s.session.enabled&&e.supportsSessionExec?buildSessionExecSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}}):void 0}buildSession(e,t,o,i){const r=this.store,n=r?.getThread(t)?.derivedFrom,c=this.resolveContextWindowFor(this.resolveProviderName(),this.resolveModelName()),d=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,u=this.resolveRuntimeShellProfile(),p=u?this.resolveShellSettings(u):void 0,m=this.fileToolsEnabled?{workdir:p?.workdir??process.cwd()}:void 0,v=u?this.resolveSessionExecSettings(u):void 0,g=u?u.supportsSafeCommandClassification&&this.settings.shell.autoApproveSafe?u:h:void 0,S=l(this.hostMode)?this.resolveAgentInstallBinding():void 0,f=this.scheduleTools,w=this.composeCapabilityContext(e.sources.length,u),y=new s({id:t,model:this.activeModel(e),onBeforeTurn:this.assertModelUpdateIdle,...void 0===this.modelRecovery?{}:{modelRecovery:this.modelRecovery},sources:e.sources,toolSchemaPolicy:this.toolSchemaPolicy,onToolExcluded:e=>this.onAgentBootstrapIssue?.({agentName:e.agentName,message:`工具 "${e.toolName}" 的参数 schema 含当前 provider "${this.resolveToolSchemaProviderName()}" 无法接受的引用(${e.issues.map(e=>e.ref).join("、")}),已从本会话工具集移除`}),capabilityContext:w,resolveDynamicCapabilityContext:async e=>{const[s,t]=await Promise.all([this.inspectVcsContext(w.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),o=t.vcs??s;return{...t.ruleIds?{ruleIds:t.ruleIds}:{},...o?{vcs:o}:{},...t.origin?{origin:t.origin}:{}}},...d?{skillLibrary:d}:{},...this.workspaceInstructions?{workspaceInstructions:this.workspaceInstructions}:{},...m?{fileTools:m}:{},...p?{bash:p}:{},...g?{bashClassifier:g}:{},...v?{bashSession:v}:{},...S?{agentInstall:S}:{},...f?{schedules:{port:f,sessionCwd:w.cwd,includeCreate:a(this.hostMode)}}:{},maxSteps:this.maxSteps,compaction:this.settings.compaction,turnTimeoutMs:this.settings.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==c?{contextWindow:c.window,contextWindowSource:c.source}:{},...this.policy?{policy:this.policy}:{},initialMessages:o,...void 0!==n?{derivedFrom:n}:{},...i?{initialCheckpoint:i}:{},...r?{onAcceptInput:(e,s)=>r.acceptTurnInput(t,e,s),onRecordInputSkillCheckpoint:(e,s)=>r.recordTurnSkillCheckpoint(t,e,s),getInputSkillCheckpoint:e=>r.getTurnInputSkillCheckpoint(t,e),onPersist:(e,s)=>r.appendMessages(t,e,s),onReplace:e=>r.replaceMessages(t,e),onToolExecution:e=>r.appendToolExecution(t,e),listToolExecutions:e=>r.listToolExecutions(t,e),getToolExecution:e=>r.getToolExecution(t,e),recoverUncoveredToolExecutions:()=>this.recoverUncoveredToolExecutionContext(t),listTranscriptMessages:e=>r.listTranscriptMessages(t,e),commitCompaction:e=>r.commitCompaction(t,e),readCheckpointTranscript:e=>r.readCheckpointTranscript(t,e)}:{},onClose:()=>{this.liveSessions.get(t)===y&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,y),y}recoverUncoveredToolExecutionContext(e){const s=this.store?.recoverUncoveredToolExecutions(e,u);return void 0===s?[]:[s]}assertModelUpdateIdle=()=>{if(void 0!==this.switchingProviderName)throw new Error("模型配置正在更新,请稍后再试")};syncProviderOptions(e){this.assertModelUpdateIdle(),this.switchingProviderName=this.provider;try{this.agentHost?.updateSampling(this.modelOverride??this.explicitModel,e),this.providerOptions=e}finally{this.switchingProviderName=void 0}}switchModel(e){this.assertAcceptingSessions(),this.assertModelUpdateIdle(),this.switchingProviderName=e.provider;try{const s=this.resolveContextWindowFor(e.provider,e.modelName),t={model:e.model,...void 0===e.modelRecovery?{}:{modelRecovery:e.modelRecovery},...void 0!==s?{contextWindow:s.window,contextWindowSource:s.source}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.structuredOutputProviderOptions?{structuredOutputProviderOptions:e.structuredOutputProviderOptions}:{},...e.structuredOutputReasoning?{structuredOutputReasoning:e.structuredOutputReasoning}:{},toolSchemaPolicy:e.toolSchemaPolicy??m};for(const e of this.liveSessions.values())if(!e.canSwitchModel())throw new Error("存在正在生成回复的会话,稍后再切换模型");this.agentHost?.updateSampling(e.model,e.providerOptions);for(const e of this.liveSessions.values())e.switchModel(t);this.modelOverride=e.model,this.modelName=e.modelName,this.provider=e.provider,this.toolSchemaPolicy=t.toolSchemaPolicy,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning;for(const s of this.liveSessions.keys())this.store?.updateModel(s,e.modelName);return s}finally{this.switchingProviderName=void 0}}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}hostOperation(){return{model:this.modelOverride??this.explicitModel,...this.providerOptions?{providerOptions:this.providerOptions}:{},signal:this.shutdownController.signal}}async bootstrap(){const e=this.agentHost?await this.agentHost.prepare(this.hostOperation()):{sources:this.explicitSources??[]};this.assertAcceptingSessions(),this.resolvedCatalog=e.catalog??[];const s=e.skillLibrary,t=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??s,o=this.modelOverride??this.explicitModel;return this.agentHost?.updateSampling(o,this.providerOptions),{model:o,sources:e.sources,...t?{skillLibrary:t}:{}}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const s=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=s.then(()=>{},()=>{}),s}async runAgentRefresh(e){const s=await this.ensureReady();if(this.assertAcceptingSessions(),!this.agentHost)throw new Error("Agent refresh requires an agentHost");const t=await this.agentHost.refresh(e,this.hostOperation());this.assertAcceptingSessions();const o=[...s.sources.filter(e=>e.agentName!==t.source.agentName),t.source],i=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??t.skillLibrary;this.agentHost.updateSampling(this.activeModel(s),this.providerOptions),this.ready=Promise.resolve({model:this.activeModel(s),sources:o,...i?{skillLibrary:i}:{}});const r=i?.list()??[],n=i&&r.length>0?i:void 0,l=this.resolveRuntimeShellProfile();return{source:t.source,...n?{skillLibrary:n}:{},capabilityContext:this.composeCapabilityContext(o.length,l)}}composeCapabilityContext(e,s){const t=this.resolveAgentOnboardingInfo();return{profile:s?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...s?{shellHints:s.systemPromptHints()}:{},agentCount:e,...t?{agentOnboardingCatalog:t}:{}}}resolveAgentOnboardingInfo(){return this.resolvedCatalog.length>0?this.resolvedCatalog:void 0}resolveAgentInstallBinding(){if(this.agentHost?.install&&0!==this.resolvedCatalog.length)return{catalog:this.resolvedCatalog,install:(e,s)=>this.installCatalogAgent(e,s)}}installCatalogAgent(e,s){this.assertAcceptingSessions();const t=this.runAgentInstall(e,s);return this.pendingInstalls.add(t),t.then(()=>this.pendingInstalls.delete(t),()=>this.pendingInstalls.delete(t)),t}async runAgentInstall(e,s){const t=this.agentHost;if(!t?.install||!this.resolvedCatalog.some(s=>s.shortName===e))return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const{outcome:o}=await t.install(e,s,this.shutdownController.signal);if(!o.ok||this.closing)return{outcome:o};try{const e=await this.ensureReady();if(this.assertAcceptingSessions(),e.sources.some(e=>e.agentName===o.agentName))return s(`Agent "${o.agentName}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:o};const t=await this.prepareAgentRefresh(o.agentName);return{outcome:o,refresh:t}}catch(e){return s(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:o}}}resolveProviderName(){return this.provider}resolveContextWindowFor(e,s){return t({provider:e,model:s,...void 0!==this.settings.contextWindow?{override:this.settings.contextWindow}:{},catalog:this.modelCatalog})}resolveModelName(){return this.modelName}resolveToolSchemaProviderName(){return this.switchingProviderName??this.resolveProviderName()}activeModel(e){return this.modelOverride??e.model}async getContextSummary(){const e=await this.ensureReady();this.assertAcceptingSessions();const s=this.workspaceInstructions?.current()?.path;return{agentCount:e.sources.length,toolCount:e.sources.reduce((e,s)=>e+s.tools.length,0),skillCount:e.skillLibrary?.list().length??0,...void 0!==s?{instructionsPath:s}:{}}}async dispose(){return void 0!==this.disposePromise||(this.closing=!0,this.disposePromise=Promise.resolve().then(async()=>{const e=[],s=await Promise.allSettled([...this.liveSessions.values()].map(e=>e.close()));for(const t of s)"rejected"===t.status&&e.push(t.reason);this.liveSessions.clear(),await Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain,...this.pendingInstalls]);try{await(this.agentHost?.dispose())}catch(s){e.push(s)}if(1===e.length)throw e[0];if(e.length>1)throw new AggregateError(e,"ConversationEngine 关闭 session 与宿主资源失败。")}),this.shutdownController.abort(v())),this.disposePromise}}
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{AgentSession as s}from"./agent-session.js";import{resolveModelContextWindow as t}from"./context-window.js";import{createDefaultModelCatalog as o}from"./model-catalog-default.js";import{createWorkspaceInstructionsSource as i,parseWorkspaceInstructionsSetting as r}from"./workspace-instructions.js";import{CAPABILITY_HOST_MODES as n,shouldOfferAgentInstall as l,shouldOfferScheduleCreate as a}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as h}from"../types/command-classification.js";import{resolveShellProfile as c}from"../bash/profile.js";import{inspectGitVcsContext as d}from"./vcs-context.js";import{createToolLedgerGapRecoveryMessage as p}from"./cancelled-turn-recovery.js";const u="ConversationEngine is closing",m=e=>0===e.length;export function buildSessionExecSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),profile:e.profile,maxSessions:s.session.maxSessions,defaultYieldMs:s.session.defaultYieldMs,maxOutputTokens:s.session.maxOutputTokens,bufferCapacity:s.maxCaptureBytes,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}export function buildSessionBashSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),defaultTimeoutMs:s.defaultTimeoutMs,maxTimeoutMs:s.maxTimeoutMs,turnTimeoutMs:e.settings.turnTimeoutMs,maxCaptureBytes:s.maxCaptureBytes,maxModelOutputChars:s.maxModelOutputChars,profile:e.profile,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}function v(){return new Error(u)}function g(e){if(null===e.workspaceInstructions)return;if(void 0!==e.workspaceInstructions)return e.workspaceInstructions;const s=process.cwd();return i({cwd:s,setting:r(e.settings.instructions,s),...e.onWorkspaceInstructionsIssue?{onIssue:e.onWorkspaceInstructionsIssue}:{}})}export class ConversationEngine{settings;agentHost;store;policy;fileToolsEnabled;maxSteps;providerOptions;modelRecovery;modelOverride;modelName;provider;toolSchemaPolicy;switchingProviderName;modelCatalog;structuredOutputProviderOptions;structuredOutputReasoning;debugEvents;explicitModel;explicitSources;explicitSkillLibrary;workspaceInstructions;onAgentBootstrapIssue;hostMode;scheduleTools;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;inspectVcsContext;shellEnv;onShellCommandSpawn;ready;refreshChain=Promise.resolve();resolvedCatalog=[];pendingInstalls=new Set;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;shutdownController=new AbortController;disposePromise;closing=!1;constructor(e){if(!e.model)throw new Error("ConversationEngine requires a model supplied by its host");if(void 0!==e.agentHost&&void 0!==e.sources)throw new Error("ConversationEngine accepts either sources or agentHost, not both");this.settings=e.settings,this.agentHost=e.agentHost,this.provider=e.provider,this.modelName=e.modelName,this.toolSchemaPolicy=e.toolSchemaPolicy??m,this.store=e.store,this.modelCatalog=e.modelCatalog??o(),this.policy=e.policy,this.fileToolsEnabled=e.fileToolsEnabled??!0,this.maxSteps=e.maxSteps??e.settings.maxSteps,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??n.embedded,this.scheduleTools=e.scheduleTools??void 0,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??c,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.workspaceInstructions=g(e),this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.inspectVcsContext=e.inspectVcsContext??d,this.shellEnv={...e.shellEnv??process.env},this.onShellCommandSpawn=e.onShellCommandSpawn}async createSession(s={}){this.assertAcceptingSessions();const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store?this.store.createThread({...void 0===s.id?{}:{id:s.id},...void 0===s.origin?{}:{origin:s.origin},...s.title?{title:s.title}:{},model:this.resolveModelName()}):s.id??e();return this.buildSession(t,o,[])}async resumeSession(e){if(this.assertAcceptingSessions(),!this.store)throw new Error("resumeSession requires a ThreadStore");if("scheduled"===this.store.getThread(e)?.origin.kind)throw new Error("定时执行会话是只读记录;请基于该次运行创建新对话");const s=this.liveSessions.get(e);if(void 0!==s)return s;if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.liveSessions.get(e);if(void 0!==o)return o;this.recoverUncoveredToolExecutionContext(e);const i=this.store.loadSessionState(e);return this.buildSession(t,e,i.messages,i.checkpoint)}async forkSession(e,s={}){if(this.assertAcceptingSessions(),!this.store)throw new Error("forkSession requires a ThreadStore");const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store.forkSnapshot(e,{...s,model:this.resolveModelName()});try{this.recoverUncoveredToolExecutionContext(o);const e=this.store.loadSessionState(o);return this.buildSession(t,o,e.messages,e.checkpoint)}catch(e){throw this.store.deleteThread(o),e}}assertAcceptingSessions(){if(this.closing)throw v()}resolveRuntimeShellProfile(){if(!this.settings.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const s="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${s},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){return buildSessionBashSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}})}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const s=this.settings.shell;return s.enabled&&s.session.enabled&&e.supportsSessionExec?buildSessionExecSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}}):void 0}buildSession(e,t,o,i){const r=this.store,n=r?.getThread(t)?.derivedFrom,c=this.resolveContextWindowFor(this.resolveProviderName(),this.resolveModelName()),d=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,p=void 0===this.explicitSkillLibrary?this.agentHost?.refreshSkills?.bind(this.agentHost):void 0,u=this.resolveRuntimeShellProfile(),m=u?this.resolveShellSettings(u):void 0,v=this.fileToolsEnabled?{workdir:m?.workdir??process.cwd()}:void 0,g=u?this.resolveSessionExecSettings(u):void 0,S=u?u.supportsSafeCommandClassification&&this.settings.shell.autoApproveSafe?u:h:void 0,f=l(this.hostMode)?this.resolveAgentInstallBinding():void 0,w=this.scheduleTools,y=this.composeCapabilityContext(e.sources.length,u),C=new s({id:t,model:this.activeModel(e),onBeforeTurn:this.assertModelUpdateIdle,...void 0===this.modelRecovery?{}:{modelRecovery:this.modelRecovery},sources:e.sources,toolSchemaPolicy:this.toolSchemaPolicy,onToolExcluded:e=>this.onAgentBootstrapIssue?.({agentName:e.agentName,message:`工具 "${e.toolName}" 的参数 schema 含当前 provider "${this.resolveToolSchemaProviderName()}" 无法接受的引用(${e.issues.map(e=>e.ref).join("、")}),已从本会话工具集移除`}),capabilityContext:y,resolveDynamicCapabilityContext:async e=>{const[s,t]=await Promise.all([this.inspectVcsContext(y.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),o=t.vcs??s;return{...t.ruleIds?{ruleIds:t.ruleIds}:{},...o?{vcs:o}:{},...t.origin?{origin:t.origin}:{}}},...d?{skillLibrary:d}:{},...p?{refreshSkillLibrary:e=>p({...this.hostOperation(),signal:e})}:{},...this.workspaceInstructions?{workspaceInstructions:this.workspaceInstructions}:{},...v?{fileTools:v}:{},...m?{bash:m}:{},...S?{bashClassifier:S}:{},...g?{bashSession:g}:{},...f?{agentInstall:f}:{},...w?{schedules:{port:w,sessionCwd:y.cwd,includeCreate:a(this.hostMode)}}:{},maxSteps:this.maxSteps,compaction:this.settings.compaction,turnTimeoutMs:this.settings.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==c?{contextWindow:c.window,contextWindowSource:c.source}:{},...this.policy?{policy:this.policy}:{},initialMessages:o,...void 0!==n?{derivedFrom:n}:{},...i?{initialCheckpoint:i}:{},...r?{onAcceptInput:(e,s)=>r.acceptTurnInput(t,e,s),onRecordInputSkillCheckpoint:(e,s)=>r.recordTurnSkillCheckpoint(t,e,s),getInputSkillCheckpoint:e=>r.getTurnInputSkillCheckpoint(t,e),onPersist:(e,s)=>r.appendMessages(t,e,s),onReplace:e=>r.replaceMessages(t,e),onToolExecution:e=>r.appendToolExecution(t,e),listToolExecutions:e=>r.listToolExecutions(t,e),getToolExecution:e=>r.getToolExecution(t,e),recoverUncoveredToolExecutions:()=>this.recoverUncoveredToolExecutionContext(t),listTranscriptMessages:e=>r.listTranscriptMessages(t,e),commitCompaction:e=>r.commitCompaction(t,e),readCheckpointTranscript:e=>r.readCheckpointTranscript(t,e)}:{},onClose:()=>{this.liveSessions.get(t)===C&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,C),C}recoverUncoveredToolExecutionContext(e){const s=this.store?.recoverUncoveredToolExecutions(e,p);return void 0===s?[]:[s]}assertModelUpdateIdle=()=>{if(void 0!==this.switchingProviderName)throw new Error("模型配置正在更新,请稍后再试")};syncProviderOptions(e){this.assertModelUpdateIdle(),this.switchingProviderName=this.provider;try{this.agentHost?.updateSampling(this.modelOverride??this.explicitModel,e),this.providerOptions=e}finally{this.switchingProviderName=void 0}}switchModel(e){this.assertAcceptingSessions(),this.assertModelUpdateIdle(),this.switchingProviderName=e.provider;try{const s=this.resolveContextWindowFor(e.provider,e.modelName),t={model:e.model,...void 0===e.modelRecovery?{}:{modelRecovery:e.modelRecovery},...void 0!==s?{contextWindow:s.window,contextWindowSource:s.source}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.structuredOutputProviderOptions?{structuredOutputProviderOptions:e.structuredOutputProviderOptions}:{},...e.structuredOutputReasoning?{structuredOutputReasoning:e.structuredOutputReasoning}:{},toolSchemaPolicy:e.toolSchemaPolicy??m};for(const e of this.liveSessions.values())if(!e.canSwitchModel())throw new Error("存在正在生成回复的会话,稍后再切换模型");this.agentHost?.updateSampling(e.model,e.providerOptions);for(const e of this.liveSessions.values())e.switchModel(t);this.modelOverride=e.model,this.modelName=e.modelName,this.provider=e.provider,this.toolSchemaPolicy=t.toolSchemaPolicy,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning;for(const s of this.liveSessions.keys())this.store?.updateModel(s,e.modelName);return s}finally{this.switchingProviderName=void 0}}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}hostOperation(){return{model:this.modelOverride??this.explicitModel,...this.providerOptions?{providerOptions:this.providerOptions}:{},signal:this.shutdownController.signal}}async bootstrap(){const e=this.agentHost?await this.agentHost.prepare(this.hostOperation()):{sources:this.explicitSources??[]};this.assertAcceptingSessions(),this.resolvedCatalog=e.catalog??[];const s=e.skillLibrary,t=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??s,o=this.modelOverride??this.explicitModel;return this.agentHost?.updateSampling(o,this.providerOptions),{model:o,sources:e.sources,...t?{skillLibrary:t}:{}}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const s=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=s.then(()=>{},()=>{}),s}async runAgentRefresh(e){const s=await this.ensureReady();if(this.assertAcceptingSessions(),!this.agentHost)throw new Error("Agent refresh requires an agentHost");const t=await this.agentHost.refresh(e,this.hostOperation());this.assertAcceptingSessions();const o=[...s.sources.filter(e=>e.agentName!==t.source.agentName),t.source],i=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??t.skillLibrary;this.agentHost.updateSampling(this.activeModel(s),this.providerOptions),this.ready=Promise.resolve({model:this.activeModel(s),sources:o,...i?{skillLibrary:i}:{}});const r=i?.list()??[],n=i&&r.length>0?i:void 0,l=this.resolveRuntimeShellProfile();return{source:t.source,...n?{skillLibrary:n}:{},capabilityContext:this.composeCapabilityContext(o.length,l)}}composeCapabilityContext(e,s){const t=this.resolveAgentOnboardingInfo();return{profile:s?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...s?{shellHints:s.systemPromptHints()}:{},agentCount:e,...t?{agentOnboardingCatalog:t}:{}}}resolveAgentOnboardingInfo(){return this.resolvedCatalog.length>0?this.resolvedCatalog:void 0}resolveAgentInstallBinding(){if(this.agentHost?.install&&0!==this.resolvedCatalog.length)return{catalog:this.resolvedCatalog,install:(e,s)=>this.installCatalogAgent(e,s)}}installCatalogAgent(e,s){this.assertAcceptingSessions();const t=this.runAgentInstall(e,s);return this.pendingInstalls.add(t),t.then(()=>this.pendingInstalls.delete(t),()=>this.pendingInstalls.delete(t)),t}async runAgentInstall(e,s){const t=this.agentHost;if(!t?.install||!this.resolvedCatalog.some(s=>s.shortName===e))return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const{outcome:o}=await t.install(e,s,this.shutdownController.signal);if(!o.ok||this.closing)return{outcome:o};try{const e=await this.ensureReady();if(this.assertAcceptingSessions(),e.sources.some(e=>e.agentName===o.agentName))return s(`Agent "${o.agentName}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:o};const t=await this.prepareAgentRefresh(o.agentName);return{outcome:o,refresh:t}}catch(e){return s(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:o}}}resolveProviderName(){return this.provider}resolveContextWindowFor(e,s){return t({provider:e,model:s,...void 0!==this.settings.contextWindow?{override:this.settings.contextWindow}:{},catalog:this.modelCatalog})}resolveModelName(){return this.modelName}resolveToolSchemaProviderName(){return this.switchingProviderName??this.resolveProviderName()}activeModel(e){return this.modelOverride??e.model}async getContextSummary(){const e=await this.ensureReady();this.assertAcceptingSessions();const s=this.workspaceInstructions?.current()?.path;return{agentCount:e.sources.length,toolCount:e.sources.reduce((e,s)=>e+s.tools.length,0),skillCount:e.skillLibrary?.list().length??0,...void 0!==s?{instructionsPath:s}:{}}}async dispose(){return void 0!==this.disposePromise||(this.closing=!0,this.disposePromise=Promise.resolve().then(async()=>{const e=[],s=await Promise.allSettled([...this.liveSessions.values()].map(e=>e.close()));for(const t of s)"rejected"===t.status&&e.push(t.reason);this.liveSessions.clear(),await Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain,...this.pendingInstalls]);try{await(this.agentHost?.dispose())}catch(s){e.push(s)}if(1===e.length)throw e[0];if(e.length>1)throw new AggregateError(e,"ConversationEngine 关闭 session 与宿主资源失败。")}),this.shutdownController.abort(v())),this.disposePromise}}
|
|
@@ -27,6 +27,8 @@ export interface AgentHostInstallResult {
|
|
|
27
27
|
export interface AgentHost {
|
|
28
28
|
prepare(input: AgentHostOperation): Promise<AgentHostSnapshot>;
|
|
29
29
|
refresh(agentName: string, input: AgentHostOperation): Promise<AgentHostRefresh>;
|
|
30
|
+
/** Discover skills without reconnecting agents. Undefined means no available library. */
|
|
31
|
+
refreshSkills?(input: AgentHostOperation): Promise<SkillLibrary | undefined>;
|
|
30
32
|
install?(shortName: string, report: (line: string) => void, signal: AbortSignal): Promise<AgentHostInstallResult>;
|
|
31
33
|
/**
|
|
32
34
|
* Synchronous memory update; must not open connections or perform external I/O.
|
|
@@ -12,5 +12,10 @@ declare const skillToolInputSchema: z.ZodObject<{
|
|
|
12
12
|
reference: z.ZodOptional<z.ZodString>;
|
|
13
13
|
}, z.core.$strip>;
|
|
14
14
|
export type SkillToolInput = z.infer<typeof skillToolInputSchema>;
|
|
15
|
+
/** Preserve actionable feedback when the SDK rejects a name before tool execution. */
|
|
16
|
+
export declare function skillInputErrorResult(library: SkillLibrary, input: unknown): NormalizedToolResult | undefined;
|
|
15
17
|
export declare function executeSkillTool(library: SkillLibrary, input: SkillToolInput): NormalizedToolResult;
|
|
16
|
-
export declare function buildSkillToolset(library: SkillLibrary | (() => SkillLibrary), registry: ToolRegistry, coordinator?: ToolExecutionCoordinator
|
|
18
|
+
export declare function buildSkillToolset(library: SkillLibrary | (() => SkillLibrary), registry: ToolRegistry, coordinator?: ToolExecutionCoordinator, options?: {
|
|
19
|
+
readonly toolId?: string;
|
|
20
|
+
readonly names?: readonly string[];
|
|
21
|
+
}): ToolSet;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{tool as
|
|
1
|
+
import{asSchema as e,tool as n}from"ai";import{z as r}from"zod";import{SKILL_TOOL_ID as t}from"../skills/contracts.js";import{TOOL_OUTCOME_KINDS as o,failedToolResult as l,successfulToolResult as i,toolResultToModelOutput as s}from"./normalize-result.js";import{TOOL_RESOURCE_ACCESS_MODES as c,executeCoordinatedTool as a}from"./tool-execution-coordinator.js";export const SKILL_TOOL_AGENT_NAME="roll";export const SKILL_TOOL_NAME="skill";export{t as SKILL_TOOL_ID};const m=6e4,u=new Set(["",".","./","/","skill.md","./skill.md","/skill.md"]),f=r.object({name:r.string().trim().min(1).describe("要加载的 skill 名称(见 system prompt 中的 Skills 目录)"),reference:r.string().optional().describe("仅在加载 references/ 下的文件时填写,如 references/workflows.md;加载主 SKILL.md 时省略此参数")});function d(e){return f.extend({name:r.enum(e).describe("从当前 Skills 目录选择名称并原样传入,不要附加说明文字"),reference:r.string().nullable().describe("读取主 SKILL.md 传 null;读取附加文档传 references/ 下的相对路径")})}function p(e){return e.length<=m?e:`${e.slice(0,m)}\n\n[内容过长已截断,共 ${String(e.length)} 字符]`}function k(e){if(void 0===e)return;const n=e.trim();return u.has(n.toLowerCase())?void 0:n}function I(e,n){return void 0===e?n:[`SKILL_ROOT=${e}`,"这是该 skill 的 canonical absolute root。所有 scripts/、references/ 和其它相对路径必须相对 SKILL_ROOT 解析;执行脚本时将 workdir 设为 SKILL_ROOT,不要搜索其它 skill 目录。","",n].join("\n")}function g(e,n){let r=Array.from({length:n.length+1},(e,n)=>n),t=new Array(n.length+1).fill(0);for(const[o,l]of e.entries()){t[0]=o+1;for(const[e,o]of n.entries()){const n=(r[e+1]??Number.POSITIVE_INFINITY)+1,i=(t[e]??Number.POSITIVE_INFINITY)+1,s=(r[e]??Number.POSITIVE_INFINITY)+(l===o?0:1);t[e+1]=Math.min(n,i,s)}[r,t]=[t,r]}return r[n.length]??e.length}function S(e,n){const r=Array.from(n.trim());return e.list().map((e,n)=>{const t=Array.from(e.name);return{name:e.name,index:n,distance:g(r,t),length:Math.max(r.length,t.length,1)}}).sort((e,n)=>e.distance*n.length-n.distance*e.length||e.index-n.index).map(e=>e.name)}function h(e,n){const r=S(e,n),t={code:o.invalidInput,field:"name",receivedName:n,message:"没有找到完全匹配的 skill。请结合当前任务,从 availableNames 中选择一个名称并原样传入。不要翻译、改写名称或附加说明文字,也不要原样重试此次失败的 name。",availableNamesOrder:"完整名称的标准化编辑距离由小到大排列,同分保持目录顺序;排序仅帮助查找,不代表该 skill 一定适合当前任务。",availableNames:r};return l(o.invalidInput,`skill "${n}" 不存在。可用 skill: ${r.join(", ")}`,{model:{type:"error-json",value:t}})}export function skillInputErrorResult(e,n){let r=n;if("string"==typeof n)try{r=JSON.parse(n)}catch{return}if("object"==typeof r&&null!==r&&"name"in r&&"string"==typeof r.name)return e.list().some(e=>e.name===r.name)?void 0:h(e,r.name)}function L(e,n){const r=e.load(n);if(!r)return e.list().some(e=>e.name===n)?l(o.toolFailed,`skill "${n}" 已发现,但主文档加载失败;请检查 SKILL.md 是否可读及格式是否有效`):h(e,n);const t=r.referencePaths.length>0?`\n\n可用 references(传 reference 参数加载):\n${r.referencePaths.map(e=>`- ${e}`).join("\n")}`:"";return i(I(r.skillRoot,`${p(r.content)}${t}`))}function v(e,n,r){if(!e.list().some(e=>e.name===n))return h(e,n);const t=void 0===e.loadReferenceDocument?void 0:e.loadReferenceDocument(n,r),s=void 0===e.loadReferenceDocument?e.loadReference(n,r):t?.content;return void 0===s?l(o.invalidInput,`skill "${n}" 中不存在 reference "${r}"。加载主 SKILL.md 时请省略 reference;加载附加文档时仅支持 skill 目录内 references/ 下的文件。`):i(I(t?.skillRoot,p(s)))}export function executeSkillTool(e,n){const r=k(n.reference);return void 0!==r?v(e,n.name,r):L(e,n.name)}export function buildSkillToolset(r,t,o,l={}){const i="function"==typeof r?r:()=>r,m=l.names??i().list().map(e=>e.name);if(0===m.length)return{};const u=l.toolId??t.register("roll","skill"),f={resources:()=>[{key:"skill-library",mode:c.read}]};return o?.register(u,f),{[u]:n({description:"按目录中的完整名称加载 skill。读取主说明书时 reference 传 null;读取 references/ 下的文件时传相对路径。执行涉及某个 skill 领域的任务前,先用它读取流程与约束。",inputSchema:e(d(m)),strict:!0,toModelOutput:({output:e})=>s(e),execute:(e,n)=>a(o,f,u,n.toolCallId,e,n.abortSignal,()=>Promise.resolve(executeSkillTool(i(),{name:e.name,...null===e.reference?{}:{reference:e.reference}})))})}}
|