@roll-agent/runtime 0.23.0 → 0.24.0
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.js +1 -1
- package/dist/engine/capability-manifest.d.ts +2 -0
- package/dist/engine/capability-manifest.js +1 -1
- package/dist/engine/compaction-checkpoint.d.ts +244 -244
- package/dist/engine/compaction-semantic-state.d.ts +124 -124
- package/dist/engine/context-window.js +1 -1
- package/dist/engine/conversation-engine.js +1 -1
- package/dist/server/runtime-protocol-adapter.js +1 -1
- package/dist/service/runtime-service.d.ts +5 -4
- package/dist/service/runtime-service.js +1 -1
- package/dist/store/thread-store.d.ts +14 -3
- package/dist/store/thread-store.js +1 -1
- package/dist/tool-bridge/app-output-content.d.ts +2 -0
- package/dist/tool-bridge/app-output-content.js +1 -0
- package/dist/tool-bridge/build-tools.js +1 -1
- package/dist/tool-bridge/naming.d.ts +2 -0
- package/dist/tool-bridge/naming.js +1 -1
- package/dist/tool-bridge/normalize-app-output.d.ts +5 -0
- package/dist/tool-bridge/normalize-app-output.js +1 -0
- package/dist/tool-bridge/normalize-result.d.ts +3 -1
- package/dist/tool-bridge/normalize-result.js +1 -1
- package/dist/tool-bridge/tool-approval-continuation.js +1 -1
- package/dist/tool-bridge/tool-execution-record.d.ts +5 -0
- package/dist/tool-bridge/tool-execution-record.js +1 -1
- package/dist/types/events.d.ts +2 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as h}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as m}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as g}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as v}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as f,EXEC_LIST_NAME as T,EXEC_POLL_NAME as y,buildSessionExecToolset as C}from"../tool-bridge/session-exec-tool.js";import{SessionManager as b}from"../bash/session/session-manager.js";import{isTerminalSessionState as k}from"../bash/session/types.js";import{withCleanEnv as x}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as S,SESSION_CANCELLATION_REASONS as I,TURN_TIMEOUT_ABORT_REASON as M,USER_CANCELLATION_ABORT_REASON as E,createTurnCancellationMessage as w,isTurnTimeoutAbortReason as P,stripTurnCancellationMetadata as R}from"../types/cancellation.js";import{ToolRegistry as A}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as q,TOOL_OUTCOME_KINDS as O,createToolResult as N,failedToolResult as j,isNormalizedToolResult as $,normalizeToolResult as W,readDisplayOutput as D,readToolOutcome as F}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as L}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as U,prepareToolExecutionRecordForPersistence as V,redactSecretText as _,toRedactedToolExecutionRecordSummary as z}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as G,ToolExecutionCoordinator as B}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as J}from"../approval/approval-gate.js";import{SessionApprovalMemory as H}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as K,compactMessages as Y,CompactionDraftFallbackError 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{applyExplicitSkillContext as oe,attachExplicitSkillCheckpoint as ie,prepareExplicitSkillContext as ne,readExplicitSkillCheckpoint as re,stripExplicitSkillCheckpoints as ae}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as ce,createToolLedgerGapRecoveryMessage as le,materializeCancelledTurnRecoveryMessages as ue,stripCancelledTurnRecoveryMessages as pe}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as de,CAPABILITY_TOOL_ROLES as he,buildEffectiveCapabilityTurnContext as me,buildEffectiveCapabilityManifest as ge,findCapabilityToolId as ve,isProcessBoundHostMode as fe}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 be,buildCompactionToolState as ke,COMPACTION_CHECKPOINT_VERSION as xe,createCompactionCheckpoint as Se,createCompactionSummary as Ie,createCheckpointSemanticReminderProjection as Me,findLatestRealUserGoal as Ee,resolveActiveCompactionConstraints as we,TRANSCRIPT_MESSAGE_PROVENANCES as Pe}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Re,buildCompactionSemanticEvidenceRegistry as Ae,CompactionSemanticCandidateError as qe,mergeCompactionSemanticState as Oe,replaceCompactionSemanticConstraints as Ne,replaceCompactionSemanticGoal as je,renderCompactionSemanticSummary as $e,seedCompactionSemanticConstraints as We,seedLegacyCompactionSnapshotUncertainties as De,validateCompactionModelDraft as Fe}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Le,repairActiveToolProtocol as Ue}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Ve}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as _e}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as ze}from"../tool-bridge/user-input-tool.js";const Ge=6e3,Be=3e5,Je=4,He=2,Ke=1,Ye={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Qe="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Xe=1024,Ze="AI_InvalidToolInputError:",et={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function tt(t){const s=[...t];if(s.length<=Xe)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Xe-[...o].length).join("")}${o}`}function st(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function ot(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function it(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function nt(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function rt(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function at(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function ct(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=lt(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function lt(e){try{return JSON.stringify(e)??void 0}catch{return}}function ut(e){const t=re(e.message),[s]=ae([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(r(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function pt(e){return JSON.stringify(e)??String(e)}function dt(e){const t=V(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:pt(t.input.value),resultSummary:pt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===O.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function ht(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==te(e.content)||"assistant"===e.role&&ee(e.content)}function mt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=te(e.content);if(void 0!==t)return 0===t.length?[]:[_(t)]}return"assistant"===e.role&&ee(e.content)?[]:[_(ut({sequence:t,provenance:Pe[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!ht(e)).length}}function gt(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function vt(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===xe?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function ft(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 Tt(e){return ct(D(e))}function yt(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(Ze)?O.invalidInput:O.toolFailed}function Ct(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>F(e.output).kind===O.userRejected)??!1}function bt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(ct(e))}function kt(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 xt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function St(e,t){const s=xt(e.cachedInputTokens,t.cachedInputTokens),o=xt(e.cacheWriteTokens,t.cacheWriteTokens),i=xt(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 It(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function Mt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function Et(e,t){return void 0!==e?e:P(t)?I.timeout:I.runtime}function wt(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 Pt(e,t,s){for(const o of Object.keys(t))e[o]=s}function Rt(e,t,s){const o={[f]:he.sessionCommand,[y]:he.sessionPoll,[T]:he.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function At(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new J;userInputInteractions=new _e;toolCoordinator=new B;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?wt(e.initialMessages):[];this.messages=[...Ue(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?mt(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=vt(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)ht(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Pe[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.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 A,i={},n=ze({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,Pt(i,n.tools,he.userInput);const r=e.readCheckpointTranscript?Ve(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};Pt(i,r,he.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};Pt(i,a,he.skill);const c=new H,l=e.fileTools?g(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(Pt(i,l.readTools,he.fileRead),Pt(i,l.editTools,he.fileEdit),Pt(i,l.verifyTools,he.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},m=e.bashClassifier?{classifier:e.bashClassifier}:{},f=e.bash?v(e.bash,o,d,m):{};Pt(i,f,he.shell),e.bashSession&&(this.sessionManager=new b({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:x(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const T=e.bashSession&&this.sessionManager?C({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...m,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};Rt(i,T,o);const y=e.agentInstall,k=y?p({catalog:y.catalog,install:async(e,t)=>{const s=await y.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}):{};Pt(i,k,he.agentInstall);const S=e.schedules?h(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};Pt(i,S.createTools,he.scheduleCreate),Pt(i,S.extendTools,he.scheduleExtend),Pt(i,S.listTools,he.scheduleList);const I=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);Pt(i,I.tools,he.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...f,...T,...k,...S.createTools,...S.extendTools,...S.listTools,...I.tools},this.registry=I.registry,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 ge({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??de.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,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);Pt(this.toolRoles,t.tools,he.agent),this.tools={...this.tools,...t.tools},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);Pt(this.toolRoles,e,he.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=n(e),s=new se;this.emit=e=>s.push(e);const o=st();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:ct(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new se;this.emit=e=>t.push(e);const s=st();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:ct(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${ct(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:ct(t)})}if(s.aborted||s.abortController.signal.aborted)return l=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(e,s,l,r);e.push({type:"message-start",messageId:t()}),void 0!==this.turnTimeoutMs&&(s.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),u=setTimeout(()=>{s.abortController.signal.aborted||(this.captureCancellationActivity(s),s.aborted=!0,s.cancellationReason=I.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(M))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=ne({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},g=d.skillNames.length>0?ie(h,d):h;let v={};try{v=await ft(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(g),s.cancellationReason=Et(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:ct(t)})}const f=me(this.capabilityManifest,{explicitSkillNames:d.skillNames,...v.ruleIds?{ruleIds:v.ruleIds}:{},...v.vcs?{vcs:v.vcs}:{},...v.origin?{origin:v.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=f;const T=Te(f);let y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||this.messages.push(g);const n=ve(this.capabilityManifest,he.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:Z(u),h=ae(R(ue(this.messages))),v=At(d.skillNames.length>0?oe(h,d):h,u?`${T}\n\n${u}`:T);this.debug(e,"model","calling streamText",r,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let f=0;const C=m(),b=()=>c({model:this.model,system:this.systemPrompt,messages:v,tools:this.modelTools(),prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),Ct(),C.stop,this.stopOnContextPressure(s)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(s,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:s.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{ot(s,e),f=X(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)ot(s,t)}});let k;try{k=b()}catch(t){if(this.isTurnAborted(s)||P(t))return s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!bt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,g,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,g,!1,r),void e.push({type:"error",stage:"execute",message:ct(t)})}this.debug(e,"model","streamText returned",r);let x,S,M,E,w,A,q,N="",D="",F=!1,V=0,_=!1,z=!1;const G=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of k.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=I.runtime;break}switch(z||(z=!0,this.clearDebugTimer(G),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!F){const s=D+t.text;if(Mt(s,d.userPrompt)){D=s;break}if(D.length>0){const s=D+t.text;D="",N+=s,e.push({type:"text-delta",delta:s});break}}N+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{F=!0,D="";const o=this.trackPendingToolCall(s,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));e.push({type:"tool-call",toolCallId:t.toolCallId,agentName:o.agentName,toolName:o.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=s.pendingToolCalls.get(t.toolCallId),n=$(t.output)?t.output:W(t.output),r=n.outcome,a=n.display,c=U({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==O.userRejected&&r.kind!==O.policyDenied&&r.kind!==O.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===O.success&&void 0!==i&&this.rememberCompactionResources(c,i.resources),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,outcome:r,display:a,output:a,isError:r.kind!==O.success}),s.aborted||s.abortController.signal.aborted||r.kind!==O.userRejected||(q=Tt(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=yt(t.error),n=(i===O.invalidInput?L(t.error):void 0)??Tt(t.error),r=j(i,n,{raw:t.error}),a=U({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==O.invalidInput&&(s.hadPotentialSideEffects=!0),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:n,isError:!0});break}case"finish-step":{const s=kt(t.usage);S=It(S,s.inputTokens),M=s.outputTokens,V+=1,w=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(E=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!F&&D.length>0&&(N+=D,e.push({type:"text-delta",delta:D}),D=""),x=kt(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||P(t.error)){s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,t.error);break}_=bt(t.error),_&&(this.needsCompaction=!0),A=ct(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||P(e)?(s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,e)):(_=bt(e),_&&(this.needsCompaction=!0),A=ct(e))}finally{this.clearDebugTimer(G)}if(this.debug(e,"model","fullStream finished",r,{textChars:N.length}),void 0!==A){if(this.messages.splice(l),_){const t=0===N.length&&!F,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,g,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,g,N.length>0,r),void e.push({type:"error",stage:"execute",message:`${A}${a}`})}return this.persistFailedTurn(e,s,g,r),void e.push({type:"error",stage:"execute",message:A})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=Et(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let B;this.debug(e,"model","awaiting response messages",r);const J=this.scheduleDebug(e,"model","still awaiting response messages",r);try{B=(await k.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(J),this.isTurnAborted(s)||P(t))return s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=bt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===N.length&&!F,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,g,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,g,N.length>0,r),void e.push({type:"error",stage:"execute",message:`${ct(t)}${c}`})}return this.persistFailedTurn(e,s,g,r),void e.push({type:"error",stage:"execute",message:ct(t)})}finally{this.clearDebugTimer(J)}if(this.debug(e,"model","response messages ready",r,{responseMessages:B.length}),this.isTurnAborted(s))return s.cancellationReason=Et(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const H=wt(B);this.messages.push(...H);const K=q??C.message;if(void 0!==K){const t=0===N.length?K:`\n${K}`;N+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:K})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),at(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),x&&(this.sessionUsage=St(this.sessionUsage,x));const Y=S??x?.inputTokens;void 0!==Y&&(this.lastInputTokens=Y,this.lastStepOutputTokens=M,this.lastStepToolResultTokens=f,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,Y-X(this.messages)+(M??0)+f-p)),s.completedStepCount+=V;const Q=s.completedStepCount>=this.maxSteps&&"tool-calls"===w;if(e.push({type:"message-finish",text:N,...x?{totalUsage:x}:{},sessionUsage:{...this.sessionUsage},...void 0!==S?{contextInputTokens:S}:{},...void 0!==E?{outputTokensPerSecond:E}:{},...Q?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==w||Q||void 0!==K)return;let ee;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{ee=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:ct(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=ee?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||P(t))return s.aborted=!0,s.cancellationReason=Et(s.cancellationReason,s.abortController.signal.reason??t),void(void 0!==l?this.persistCancelledTurn(e,s,l,r):this.emitCancellation(e,s));void 0!==l&&this.messages.splice(l),this.debug(e,"turn","error",r,{message:ct(t)}),e.push({type:"error",stage:"execute",message:ct(t)})}finally{void 0!==u&&clearTimeout(u),this.toolCoordinator.finishTurn(),this.activeTurn===s&&(this.activeTurn=void 0),e.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)ht(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Pe[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=le(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!==O.policyDenied&&e.outcome.kind!==O.userRejected&&e.outcome.kind!==O.invalidInput&&(e.outcome.kind!==O.cancelled||e.outcome.executionState!==q.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?[]:[le(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=it(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Ue(wt(nt(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,ce({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 的操作。${Qe}`}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}: ${ct(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:tt(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===G.write||t.mode!==G.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+Be,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ae(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=>({...z(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:{...z(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredMessageCount=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}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>F(e.output).kind===O.userRejected))return!1;const i=kt(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+X(this.messages)+X(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+X(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:X([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+X(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+X(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(ve(this.capabilityManifest,he.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Z(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?be(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,it(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)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:re(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:k(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=Ee(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===xe?this.compactionCheckpoint.semanticState:void 0,u=We(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&>(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?De(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=vt(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,T=e.filter(e=>e.sequence>v),y=new Set(T.filter(e=>e.provenance===Pe[1]&&ht(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),b=Ae({messages:[...T.filter(e=>!y.has(e.sequence)),...void 0===C||T.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:ut(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(dt),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),k=Re(b,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:b,modelContext:k.prompt,presentedEvidenceIds:k.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:y,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=Fe({draft:s??et,evidenceRegistry:t.registry,presentedEvidenceIds:t.presentedEvidenceIds,...void 0!==t.previousSemanticState?{previousState:t.previousSemanticState}:{},...void 0!==t.goal?{harnessGoal:{verbatimRequest:t.goal.verbatimRequest,sourceSequence:t.goal.sourceSequence}}:{}});let r=Oe(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=we(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=Ne(r,e);const o=void 0===this.compactionCheckpoint?.goal?t.goal:void 0===t.goal||void 0===t.newGoalSourceSequence||s?this.compactionCheckpoint.goal:t.goal;r=je(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:Ee(t.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??t.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?$e(r):void 0,d=void 0!==p?Ie(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Me(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=ke(t.transcript.map(e=>e.message),t.toolExecutions,32,t.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...t.resources],toolState:g,runningWork:[...t.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:e("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(t.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:t.expectedActiveMessages,expectedLatestCheckpointId:t.expectedLatestCheckpointId,evidenceWatermarks:t.evidenceWatermarks,legacySnapshotTranscriptFragments:t.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:ct(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g,v;const f=t=>{if(this.isTurnAborted(s)||0===t.removed&&0===t.truncatedTools)return;const o=Date.now();try{const s=this.buildCompactionDraft(h,t.semanticDraft,"summarize"===u&&t.removed>0,l);return this.debug(e,"compaction","checkpoint validation finished",o,{semanticRejections:s.semanticRejectionCount}),s}catch(e){if(void 0!==t.semanticDraft&&e instanceof qe)throw new Q(K.invalidStructuredOutput,"semantic checkpoint validation failed",{cause:e});throw e}};try{const t=Date.now();try{g=await Y({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new Q(K.missingObject,"structured compaction draft is missing");v=f(g)}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!Q.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:ct(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await Y({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a),v=f(g)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const T=g.removed>0||g.truncatedTools>0;if(void 0!==v&&v.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:v.semanticRejectionCount}),void 0!==v&&!v.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const y=Ue(g.messages),C=[...y.messages];if(y.status===Le.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:y.removedToolCallIds.join(","),removedToolResultIds:y.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(ht))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const b=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),k=T&&b(C)<b(this.messages),x=k?C:[...this.messages],S=k?this.advanceCompactionSemanticEvidenceWatermarks(h,v?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(k){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:v.expectedActiveMessages,expectedLatestCheckpointId:v.expectedLatestCheckpointId,draft:v.draft,semanticState:v.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:v.evidenceWatermarks,...v.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:v.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=Se({draft:v.draft,semanticState:v.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:v.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:v.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:k?g.removed:0,kept:x.length,...k&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:k?g.removed:0,kept:x.length,truncatedTools:k?g.truncatedTools:0,progressed:k}),k}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:ct(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!k(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${ct(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=I.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(S))}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??I.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===I.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===I.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=ve(this.capabilityManifest,he.sessionList);switch(t){case I.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case I.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":fe(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case I.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??I.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=ve(this.capabilityManifest,he.sessionList),n=Qe;switch(t){case I.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case I.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:fe(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case I.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=I.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,Ye.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Ye.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===Ye.keepRaw,r=n?Ue(wt(nt(t))).messages:[],a=n?it(t):rt(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[ce({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),w(this.cancellationDisplayMessage(e),e.cancellationReason??I.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${ct(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??I.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?q.outcomeUnknown:q.notExecuted,i=o===q.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=N({kind:O.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:ct(e.abortController.signal.reason)}});this.persistToolExecution(U({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=I.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(E),!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??=I.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(S)),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} 后台清理失败: ${ct(e)}\n`)});await s(e,Ge)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Ge)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${ct(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${ct(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{createHash as t,randomUUID as s}from"node:crypto";import{waitForPromiseSettlement as o}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as i}from"./relocate-tool-images.js";import{buildUserMessageContent as n,normalizeSessionSendInput as r,redactBinaryPartsForEvidence as a}from"./session-attachments.js";import{stepCountIs as c,streamText as l,InvalidToolInputError as u}from"ai";import{buildAgentToolset as p}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as d}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as h}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as m}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as g}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as v}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as f}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as T,EXEC_LIST_NAME as y,EXEC_POLL_NAME as C,buildSessionExecToolset as b}from"../tool-bridge/session-exec-tool.js";import{SessionManager as k}from"../bash/session/session-manager.js";import{isTerminalSessionState as x}from"../bash/session/types.js";import{withCleanEnv as S}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as I,SESSION_CANCELLATION_REASONS as M,TURN_TIMEOUT_ABORT_REASON as E,USER_CANCELLATION_ABORT_REASON as w,createTurnCancellationMessage as P,isTurnTimeoutAbortReason as R,stripTurnCancellationMetadata as A}from"../types/cancellation.js";import{ToolRegistry as q}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as O,TOOL_OUTCOME_KINDS as N,createToolResult as j,failedToolResult as $,isNormalizedToolResult as W,normalizeToolResult as D,readDisplayOutput as F,readToolOutcome as L}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as U}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as V,prepareToolExecutionRecordForPersistence as _,redactSecretText as z,toRedactedToolExecutionRecordSummary as G}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as B,ToolExecutionCoordinator as J}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as H}from"../approval/approval-gate.js";import{SessionApprovalMemory as K}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as Y,compactMessages as Q,CompactionDraftFallbackError 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{applyExplicitSkillContext as ie,attachExplicitSkillCheckpoint as ne,prepareExplicitSkillContext as re,readExplicitSkillCheckpoint as ae,stripExplicitSkillCheckpoints as ce}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as le,createToolLedgerGapRecoveryMessage as ue,materializeCancelledTurnRecoveryMessages as pe,stripCancelledTurnRecoveryMessages as de}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 Te}from"./capability-manifest.js";import{buildCapabilityTurnReminder as ye,buildChatSystemPromptFromManifest as Ce}from"./system-prompt.js";import{threadDerivedFromSchema as be}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as ke,buildCompactionToolState as xe,COMPACTION_CHECKPOINT_VERSION as Se,createCompactionCheckpoint as Ie,createCompactionSummary as Me,createCheckpointSemanticReminderProjection as Ee,findLatestRealUserGoal as we,resolveActiveCompactionConstraints as Pe,TRANSCRIPT_MESSAGE_PROVENANCES as Re}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Ae,buildCompactionSemanticEvidenceRegistry as qe,CompactionSemanticCandidateError as Oe,mergeCompactionSemanticState as Ne,replaceCompactionSemanticConstraints as je,replaceCompactionSemanticGoal as $e,renderCompactionSemanticSummary as We,seedCompactionSemanticConstraints as De,seedLegacyCompactionSnapshotUncertainties as Fe,validateCompactionModelDraft as Le}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Ue,repairActiveToolProtocol as Ve}from"./tool-protocol-repair.js";import{buildTranscriptToolset as _e}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as ze}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ge}from"../tool-bridge/user-input-tool.js";const Be=6e3,Je=3e5,He=4,Ke=2,Ye=1,Qe={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Xe="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Ze=1024,et="AI_InvalidToolInputError:",tt={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function st(e){const s=[...e];if(s.length<=Ze)return e;const o=`…#${t("sha256").update(e).digest("hex").slice(0,16)}`;return`${s.slice(0,Ze-[...o].length).join("")}${o}`}function ot(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function it(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function nt(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function rt(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function at(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function ct(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function lt(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=ut(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function ut(e){try{return JSON.stringify(e)??void 0}catch{return}}function pt(e){const t=ae(e.message),[s]=ce([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(a(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function dt(e){return JSON.stringify(e)??String(e)}function ht(e){const t=_(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:dt(t.input.value),resultSummary:dt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===N.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function mt(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==se(e.content)||"assistant"===e.role&&te(e.content)}function gt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=se(e.content);if(void 0!==t)return 0===t.length?[]:[z(t)]}return"assistant"===e.role&&te(e.content)?[]:[z(pt({sequence:t,provenance:Re[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!mt(e)).length}}function vt(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function ft(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===Se?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function Tt(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 yt(e){return lt(F(e))}function Ct(e){return u.isInstance(e)||"string"==typeof e&&e.startsWith(et)?N.invalidInput:N.toolFailed}function bt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>L(e.output).kind===N.userRejected)??!1}function kt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(lt(e))}function xt(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 St(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function It(e,t){const s=St(e.cachedInputTokens,t.cachedInputTokens),o=St(e.cacheWriteTokens,t.cacheWriteTokens),i=St(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 Mt(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function Et(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function wt(e,t){return void 0!==e?e:R(t)?M.timeout:M.runtime}function Pt(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 Rt(e,t,s){for(const o of Object.keys(t))e[o]=s}function At(e,t,s){const o={[T]:me.sessionCommand,[C]:me.sessionPoll,[y]: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)}}function qt(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new H;userInputInteractions=new ze;toolCoordinator=new J;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=s();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?Pt(e.initialMessages):[];this.messages=[...Ve(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?gt(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=ft(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)mt(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Re[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.derivedFrom=void 0===e.derivedFrom?void 0:be.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=Ge({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,Rt(i,n.tools,me.userInput);const r=e.readCheckpointTranscript?_e(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};Rt(i,r,me.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};Rt(i,a,me.skill);const c=new K,l=e.fileTools?v(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(Rt(i,l.readTools,me.fileRead),Rt(i,l.editTools,me.fileEdit),Rt(i,l.verifyTools,me.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},h=e.bashClassifier?{classifier:e.bashClassifier}:{},g=e.bash?f(e.bash,o,u,h):{};Rt(i,g,me.shell),e.bashSession&&(this.sessionManager=new k({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:S(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const T=e.bashSession&&this.sessionManager?b({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...h,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};At(i,T,o);const y=e.agentInstall,C=y?d({catalog:y.catalog,install:async(e,t)=>{const s=await y.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}):{};Rt(i,C,me.agentInstall);const x=e.schedules?m(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};Rt(i,x.createTools,me.scheduleCreate),Rt(i,x.extendTools,me.scheduleExtend),Rt(i,x.listTools,me.scheduleList);const I=p(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);Rt(i,I.tools,me.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...g,...T,...C,...x.createTools,...x.extendTools,...x.listTools,...I.tools},this.registry=I.registry,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=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){return this.skillToolBuilt=!0,h(()=>{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=p([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);Rt(this.toolRoles,t.tools,me.agent),this.tools={...this.tools,...t.tools},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);Rt(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");const t=r(e),s=new oe;this.emit=e=>s.push(e);const o=ot();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:lt(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new oe;this.emit=e=>t.push(e);const s=ot();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:lt(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(t,o,r){const a=Date.now();let u,p;const d=n(r.text,r.attachments);try{this.debug(t,"turn","start",a,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...r.attachments.length>0?{attachments:r.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void t.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${lt(e)}`})}try{await this.runAutoCompactionPasses(t,o,a,d)}catch(e){return void t.push({type:"error",stage:"plan",message:lt(e)})}if(o.aborted||o.abortController.signal.aborted)return u=this.messages.length,this.messages.push({role:"user",content:d}),void this.persistCancelledTurn(t,o,u,a);t.push({type:"message-start",messageId:s()}),void 0!==this.turnTimeoutMs&&(o.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),p=setTimeout(()=>{o.abortController.signal.aborted||(this.captureCancellationActivity(o),o.aborted=!0,o.cancellationReason=M.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),o.abortController.abort(E))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let n=0;const h=re({rawInput:r.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),m={role:"user",content:d},v=h.skillNames.length>0?ne(m,h):m;let f={};try{f=await Tt(this.resolveDynamicCapabilityContext?.(o.abortController.signal)??{},o.abortController.signal)??{}}catch(e){if(this.isTurnAborted(o))return u=this.messages.length,this.messages.push(v),o.cancellationReason=wt(o.cancellationReason,o.abortController.signal.reason??e),void this.persistCancelledTurn(t,o,u,a);this.debug(t,"turn","dynamic capability context unavailable",a,{message:lt(e)})}const T=ge(this.capabilityManifest,{explicitSkillNames:h.skillNames,...f.ruleIds?{ruleIds:f.ruleIds}:{},...f.vcs?{vcs:f.vcs}:{},...f.origin?{origin:f.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=T;const y=ye(T);let C=!1;for(;;){u=this.messages.length,o.pausedForContextPressure=!1,C||this.messages.push(v);const r=fe(this.capabilityManifest,me.transcriptRead),p=this.currentCheckpointReminder(r),d=void 0===p?0:ee(p),m=ce(A(pe(this.messages))),f=qt(h.skillNames.length>0?ie(m,h):m,p?`${y}\n\n${p}`:y);this.debug(t,"model","calling streamText",a,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:n,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let T=0;const b=g(),k=()=>l({model:this.model,system:this.systemPrompt,messages:f,tools:this.modelTools(),prepareStep:({messages:e})=>({messages:i(e)}),stopWhen:[c(Math.max(1,this.maxSteps-o.completedStepCount)),bt(),b.stop,this.stopOnContextPressure(o)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(o,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:o.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{it(o,e),T=Z(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)it(o,t)}});let x;try{x=k()}catch(e){if(this.isTurnAborted(o)||R(e))return o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,e),void this.persistCancelledTurn(t,o,u,a);if(!kt(e))throw e;this.needsCompaction=!0,this.messages.splice(u);const s=n<1,i=!!s&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(i&&s){n+=1;continue}return this.persistContextFailure(t,o,v,!1,a),void t.push({type:"error",stage:"execute",message:lt(e)})}this.debug(t,"model","streamText returned",a);let S,I,E,w,P,q,O,j="",F="",L=!1,_=0,z=!1,G=!1;const B=this.scheduleDebug(t,"model","waiting for first stream event",a,{messages:this.messages.length});try{for await(const s of x.fullStream){if(this.closed){o.aborted=!0,o.cancellationReason??=M.runtime;break}switch(G||(G=!0,this.clearDebugTimer(B),this.debug(t,"model","first stream event",a,{part:s.type})),s.type){case"reasoning-start":t.push({type:"reasoning-start",reasoningId:s.id});break;case"reasoning-delta":t.push({type:"reasoning-delta",reasoningId:s.id,delta:s.text});break;case"reasoning-end":t.push({type:"reasoning-end",reasoningId:s.id});break;case"text-delta":if(!L){const e=F+s.text;if(Et(e,h.userPrompt)){F=e;break}if(F.length>0){const e=F+s.text;F="",j+=e,t.push({type:"text-delta",delta:e});break}}j+=s.text,t.push({type:"text-delta",delta:s.text});break;case"tool-call":{L=!0,F="";const e=this.trackPendingToolCall(o,s.toolCallId,s.toolName,s.input,this.toolCoordinator.describeResources(s.toolName,s.input));t.push({type:"tool-call",toolCallId:s.toolCallId,agentName:e.agentName,toolName:e.toolName,input:s.input});break}case"tool-result":{const i=this.registry.resolve(s.toolName),n=o.pendingToolCalls.get(s.toolCallId),r=W(s.output)?s.output:D(s.output),a=r.outcome,c=r.display,l=V({toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,input:n?.input,result:r});this.persistToolExecution(l,o),!0===n?.potentialSideEffect&&a.kind!==N.userRejected&&a.kind!==N.policyDenied&&a.kind!==N.invalidInput&&(o.hadPotentialSideEffects=!0),a.kind===N.success&&void 0!==n&&this.rememberCompactionResources(l,n.resources),o.pendingToolCalls.delete(s.toolCallId),t.push({type:"tool-result",toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,executionId:l.id,...void 0===l.appOutput?{}:{appOutput:e(l.appOutput)},outcome:a,display:c,output:c,isError:a.kind!==N.success}),o.aborted||o.abortController.signal.aborted||a.kind!==N.userRejected||(O=yt(s.output));break}case"tool-error":{const i=this.registry.resolve(s.toolName),n=Ct(s.error),r=(n===N.invalidInput?U(s.error):void 0)??yt(s.error),a=$(n,r,{raw:s.error}),c=V({toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,input:o.pendingToolCalls.get(s.toolCallId)?.input,result:a});this.persistToolExecution(c,o),!0===o.pendingToolCalls.get(s.toolCallId)?.potentialSideEffect&&a.outcome.kind!==N.invalidInput&&(o.hadPotentialSideEffects=!0),o.pendingToolCalls.delete(s.toolCallId),t.push({type:"tool-result",toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a.outcome,display:a.display,output:r,isError:!0});break}case"finish-step":{const e=xt(s.usage);I=Mt(I,e.inputTokens),E=e.outputTokens,_+=1,P=s.finishReason;const o=s.performance.outputTokensPerSecond??s.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(w=o),t.push({type:"step-finish",finishReason:s.finishReason,usage:e});break}case"finish":!L&&F.length>0&&(j+=F,t.push({type:"text-delta",delta:F}),F=""),S=xt(s.totalUsage);break;case"error":if(this.isTurnAborted(o)||R(s.error)){o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,s.error);break}z=kt(s.error),z&&(this.needsCompaction=!0),q=lt(s.error);break;case"abort":o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,s.reason)}}}catch(e){this.isTurnAborted(o)||R(e)?(o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,e)):(z=kt(e),z&&(this.needsCompaction=!0),q=lt(e))}finally{this.clearDebugTimer(B)}if(this.debug(t,"model","fullStream finished",a,{textChars:j.length}),void 0!==q){if(this.messages.splice(u),z){const e=0===j.length&&!L,s=e&&n<1,i=!(!s&&e)&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(e&&i&&s){n+=1;continue}const r=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(t,o,v,j.length>0,a),void t.push({type:"error",stage:"execute",message:`${q}${r}`})}return this.persistFailedTurn(t,o,v,a),void t.push({type:"error",stage:"execute",message:q})}if(o.aborted||o.abortController.signal.aborted)return o.cancellationReason=wt(o.cancellationReason,o.abortController.signal.reason),void this.persistCancelledTurn(t,o,u,a);let J;this.debug(t,"model","awaiting response messages",a);const H=this.scheduleDebug(t,"model","still awaiting response messages",a);try{J=(await x.steps).flatMap(e=>e.response.messages)}catch(e){if(this.clearDebugTimer(H),this.isTurnAborted(o)||R(e))return o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,e),void this.persistCancelledTurn(t,o,u,a);const s=kt(e);if(s&&(this.needsCompaction=!0),this.messages.splice(u),s){const s=0===j.length&&!L,i=s&&n<1,r=!(!i&&s)&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(s&&r&&i){n+=1;continue}const c=s?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(t,o,v,j.length>0,a),void t.push({type:"error",stage:"execute",message:`${lt(e)}${c}`})}return this.persistFailedTurn(t,o,v,a),void t.push({type:"error",stage:"execute",message:lt(e)})}finally{this.clearDebugTimer(H)}if(this.debug(t,"model","response messages ready",a,{responseMessages:J.length}),this.isTurnAborted(o))return o.cancellationReason=wt(o.cancellationReason,o.abortController.signal.reason),void this.persistCancelledTurn(t,o,u,a);const K=Pt(J);this.messages.push(...K);const Y=O??b.message;if(void 0!==Y){const e=0===j.length?Y:`\n${Y}`;j+=e,t.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:Y})}this.debug(t,"persist","persisting messages",a,{appendedMessages:this.messages.length-u}),this.persistMessages(this.messages.slice(u),"raw_transcript"),ct(o),u=this.messages.length,this.debug(t,"persist","messages persisted",a,{totalMessages:this.messages.length}),S&&(this.sessionUsage=It(this.sessionUsage,S));const Q=I??S?.inputTokens;void 0!==Q&&(this.lastInputTokens=Q,this.lastStepOutputTokens=E,this.lastStepToolResultTokens=T,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,Q-Z(this.messages)+(E??0)+T-d)),o.completedStepCount+=_;const X=o.completedStepCount>=this.maxSteps&&"tool-calls"===P;if(t.push({type:"message-finish",text:j,...S?{totalUsage:S}:{},sessionUsage:{...this.sessionUsage},...void 0!==I?{contextInputTokens:I}:{},...void 0!==w?{outputTokensPerSecond:w}:{},...X?{stoppedAtStepLimit:!0}:{}}),!o.pausedForContextPressure||"tool-calls"!==P||X||void 0!==Y)return;let te;o.pausedForContextPressure=!1,this.debug(t,"compaction","turn paused for context pressure",a,{continuations:o.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{te=await this.runAutoCompactionPasses(t,o,a)}catch(e){return this.isTurnAborted(o)?void this.persistPausedTurnCancellation(t,o,a):void t.push({type:"error",stage:"plan",message:lt(e)})}if(this.isTurnAborted(o))return void this.persistPausedTurnCancellation(t,o,a);o.contextPressureContinuations=te?o.contextPressureContinuations+1:2,C=!0,t.push({type:"message-start",messageId:s()})}}catch(e){if(this.isTurnAborted(o)||R(e))return o.aborted=!0,o.cancellationReason=wt(o.cancellationReason,o.abortController.signal.reason??e),void(void 0!==u?this.persistCancelledTurn(t,o,u,a):this.emitCancellation(t,o));void 0!==u&&this.messages.splice(u),this.debug(t,"turn","error",a,{message:lt(e)}),t.push({type:"error",stage:"execute",message:lt(e)})}finally{void 0!==p&&clearTimeout(p),this.toolCoordinator.finishTurn(),this.activeTurn===o&&(this.activeTurn=void 0),t.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)mt(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Re[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=ue(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!==N.policyDenied&&e.outcome.kind!==N.userRejected&&e.outcome.kind!==N.invalidInput&&(e.outcome.kind!==N.cancelled||e.outcome.executionState!==O.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?[]:[ue(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=nt(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Ve(Pt(rt(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,le({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 的操作。${Xe}`}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}: ${lt(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:st(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===B.write||t.mode!==B.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+Je,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const t=s(),o=this.gate.request(t);if(void 0===this.emit)return this.gate.resolve(t,{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:t,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ce(de(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}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredMessageCount=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}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>L(e.output).kind===N.userRejected))return!1;const i=xt(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Z(this.messages)+Z(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Z(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Z([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Z(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Z(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(fe(this.capabilityManifest,me.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:ee(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?ke(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,nt(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)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ae(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:x(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=we(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===Se?this.compactionCheckpoint.semanticState:void 0,u=De(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&vt(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?Fe(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=ft(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,T=e.filter(e=>e.sequence>v),y=new Set(T.filter(e=>e.provenance===Re[1]&&mt(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),b=qe({messages:[...T.filter(e=>!y.has(e.sequence)),...void 0===C||T.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:pt(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(ht),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),k=Ae(b,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:b,modelContext:k.prompt,presentedEvidenceIds:k.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:y,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(e,s,o,i){const n=Le({draft:s??tt,evidenceRegistry:e.registry,presentedEvidenceIds:e.presentedEvidenceIds,...void 0!==e.previousSemanticState?{previousState:e.previousSemanticState}:{},...void 0!==e.goal?{harnessGoal:{verbatimRequest:e.goal.verbatimRequest,sourceSequence:e.goal.sourceSequence}}:{}});let r=Ne(e.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const t=Pe(e.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(t)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=je(r,t);const o=void 0===this.compactionCheckpoint?.goal?e.goal:void 0===e.goal||void 0===e.newGoalSourceSequence||s?this.compactionCheckpoint.goal:e.goal;r=$e(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:we(e.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??e.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?We(r):void 0,d=void 0!==p?Me(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Ee(r).items.map(e=>e.itemId)),m=0===e.legacySnapshotRequiredItemIds.length||e.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=xe(e.transcript.map(e=>e.message),e.toolExecutions,32,e.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...e.resources],toolState:g,runningWork:[...e.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:t("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(e.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:e.expectedActiveMessages,expectedLatestCheckpointId:e.expectedLatestCheckpointId,evidenceWatermarks:e.evidenceWatermarks,legacySnapshotTranscriptFragments:e.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:lt(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g,v;const f=t=>{if(this.isTurnAborted(s)||0===t.removed&&0===t.truncatedTools)return;const o=Date.now();try{const s=this.buildCompactionDraft(h,t.semanticDraft,"summarize"===u&&t.removed>0,l);return this.debug(e,"compaction","checkpoint validation finished",o,{semanticRejections:s.semanticRejectionCount}),s}catch(e){if(void 0!==t.semanticDraft&&e instanceof Oe)throw new X(Y.invalidStructuredOutput,"semantic checkpoint validation failed",{cause:e});throw e}};try{const t=Date.now();try{g=await Q({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new X(Y.missingObject,"structured compaction draft is missing");v=f(g)}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!X.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:lt(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await Q({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a),v=f(g)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const T=g.removed>0||g.truncatedTools>0;if(void 0!==v&&v.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:v.semanticRejectionCount}),void 0!==v&&!v.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const y=Ve(g.messages),C=[...y.messages];if(y.status===Ue.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:y.removedToolCallIds.join(","),removedToolResultIds:y.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(mt))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const b=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),k=T&&b(C)<b(this.messages),x=k?C:[...this.messages],S=k?this.advanceCompactionSemanticEvidenceWatermarks(h,v?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(k){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:v.expectedActiveMessages,expectedLatestCheckpointId:v.expectedLatestCheckpointId,draft:v.draft,semanticState:v.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:v.evidenceWatermarks,...v.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:v.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=Ie({draft:v.draft,semanticState:v.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:v.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:v.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:k?g.removed:0,kept:x.length,...k&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:k?g.removed:0,kept:x.length,truncatedTools:k?g.truncatedTools:0,progressed:k}),k}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:lt(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!x(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${lt(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=M.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(I))}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??M.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===M.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===M.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=fe(this.capabilityManifest,me.sessionList);switch(t){case M.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case M.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":Te(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case M.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??M.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=fe(this.capabilityManifest,me.sessionList),n=Xe;switch(t){case M.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case M.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:Te(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case M.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=M.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,Qe.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Qe.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===Qe.keepRaw,r=n?Ve(Pt(rt(t))).messages:[],a=n?nt(t):at(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[le({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),P(this.cancellationDisplayMessage(e),e.cancellationReason??M.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${lt(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??M.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?O.outcomeUnknown:O.notExecuted,i=o===O.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=j({kind:N.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:lt(e.abortController.signal.reason)}});this.persistToolExecution(V({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=M.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(w),!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??=M.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(I)),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} 后台清理失败: ${lt(e)}\n`)});await o(e,Be)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Be)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${lt(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${lt(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,3 +1,4 @@
|
|
|
1
|
+
import type { AppOutputDeclaration } from "@roll-agent/protocol/app-output";
|
|
1
2
|
import { type ToolSet } from "ai";
|
|
2
3
|
import type { JSONValue } from "@ai-sdk/provider";
|
|
3
4
|
import type { SkillSummary } from "@roll-agent/core/skills/library";
|
|
@@ -108,6 +109,7 @@ export interface EffectiveToolCapability {
|
|
|
108
109
|
readonly transport?: AgentTransport["type"];
|
|
109
110
|
readonly runtimeOwnership?: AgentRuntimeOwnership;
|
|
110
111
|
readonly annotations?: ToolAnnotations;
|
|
112
|
+
readonly appOutput?: AppOutputDeclaration;
|
|
111
113
|
readonly role: CapabilityToolRole;
|
|
112
114
|
readonly approval: CapabilityApprovalMode;
|
|
113
115
|
readonly description?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=2;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",scheduleCreate:"schedule-create",scheduleExtend:"schedule-extend",scheduleList:"schedule-list",transcriptRead:"transcript-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server",background:"background"};export function isProcessBoundHostMode(e){return e===CAPABILITY_HOST_MODES.oneShot||e===CAPABILITY_HOST_MODES.background}export function shouldOfferAgentInstall(e){return e!==CAPABILITY_HOST_MODES.background}export function shouldOfferScheduleCreate(e){return e!==CAPABILITY_HOST_MODES.background}export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};export const CAPABILITY_TURN_ORIGIN_KINDS={scheduled:"scheduled"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},r=new Set(["default","example","examples"]),s=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function u(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function
|
|
1
|
+
import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=2;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",scheduleCreate:"schedule-create",scheduleExtend:"schedule-extend",scheduleList:"schedule-list",transcriptRead:"transcript-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server",background:"background"};export function isProcessBoundHostMode(e){return e===CAPABILITY_HOST_MODES.oneShot||e===CAPABILITY_HOST_MODES.background}export function shouldOfferAgentInstall(e){return e!==CAPABILITY_HOST_MODES.background}export function shouldOfferScheduleCreate(e){return e!==CAPABILITY_HOST_MODES.background}export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};export const CAPABILITY_TURN_ORIGIN_KINDS={scheduled:"scheduled"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},r=new Set(["default","example","examples"]),s=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function u(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function p(e){return e.length>=256&&/^[a-z0-9+/_=-]+$/iu.test(e)}function I(e){return p(e)?d:u(n(e,l).replace(a,c))}function m(e,t){if(!Object.hasOwn(e,t))return t;let n=1;for(;;){const o=`~${String(n)}`,r=`${t.slice(0,i.objectKeyChars-o.length)}${o}`;if(!Object.hasOwn(e,r))return r;n+=1}}function O(e,n){if(n.depth>=i.depth)return"[nested value omitted]";if("string"==typeof e)return n.sensitive&&!s.has(n.key.toLowerCase())?l:I(e);if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if(Array.isArray(e)){const t=e.slice(0,i.arrayItems).map(e=>O(e,{...n,depth:n.depth+1}));return e.length>i.arrayItems&&t.push(`[${String(e.length-i.arrayItems)} items omitted]`),t}const o=Object.entries(e).filter(e=>void 0!==e[1]&&!r.has(e[0].toLowerCase())).sort(([e],[t])=>e.localeCompare(t)),a={};for(const[e,r]of o.slice(0,i.objectEntries)){a[m(a,u(I(e),i.objectKeyChars))]=O(r,{depth:n.depth+1,key:e,sensitive:n.sensitive||t(e)})}return o.length>i.objectEntries&&(a[m(a,"__roll_snapshot_omitted__")]=o.length-i.objectEntries),a}function A(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function f(e,t=0){if(t>32)return"[nested value omitted]";if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>f(e,t+1));if(A(e)){const n={};for(const[o,i]of Object.entries(e))void 0!==i&&(n[o]=f(i,t+1));return n}return"number"==typeof e?String(e):void 0===e?null:String(e)}const L={[CAPABILITY_TOOL_ROLES.skill]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.fileRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.sessionList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.transcriptRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.agentInstall]:CAPABILITY_APPROVAL_MODES.alwaysConfirm,[CAPABILITY_TOOL_ROLES.scheduleList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.userInput]:CAPABILITY_APPROVAL_MODES.readOnly};function C(e){return L[e]??CAPABILITY_APPROVAL_MODES.runtimePolicy}function S(e,t){return t!==CAPABILITY_TOOL_ROLES.agent?CAPABILITY_TOOL_SOURCE_KINDS.builtIn:e.agentSource??CAPABILITY_TOOL_SOURCE_KINDS.agent}function _(e,t){const n=new Set(e.map(e=>e.role)),o=[CAPABILITY_TOOL_ROLES.sessionCommand,CAPABILITY_TOOL_ROLES.sessionPoll,CAPABILITY_TOOL_ROLES.sessionList].every(e=>n.has(e));return{manifest:CAPABILITY_MANIFEST_LIFECYCLES.manifest,turnContext:CAPABILITY_MANIFEST_LIFECYCLES.turnContext,hostMode:t,sessionExec:o?CAPABILITY_SESSION_EXEC_LIFECYCLES.resumable:CAPABILITY_SESSION_EXEC_LIFECYCLES.unavailable,sessionDurability:o?CAPABILITY_SESSION_DURABILITIES.processLocal:CAPABILITY_SESSION_DURABILITIES.unavailable}}export function buildEffectiveCapabilityManifest(t){const n=Object.keys(t.tools).sort((e,t)=>e.localeCompare(t)).map(n=>{const o=t.tools[n],i=t.resolveRoute(n);if(!o||!i)throw new Error(`无法为已注册工具 ${n} 构建 capability manifest`);const r=t.toolRoles[n];if(!r)throw new Error(`已注册工具 ${n} 缺少 capability role`);const s="description"in o?o.description:void 0;return{id:n,agentName:i.agentName,toolName:i.toolName,source:S(i,r),...i.transport?{transport:i.transport}:{},...i.runtimeOwnership?{runtimeOwnership:i.runtimeOwnership}:{},...i.annotations?{annotations:{...i.annotations}}:{},...i.appOutput?{appOutput:{schemaId:i.appOutput.schemaId,schemaVersion:i.appOutput.schemaVersion,remoteReadable:i.appOutput.remoteReadable}}:{},role:r,approval:C(r),..."string"==typeof s&&s.length>0?{description:s}:{},inputSchema:f(e(o.inputSchema).jsonSchema)}});return{version:1,audience:"roll-chat",profile:t.profile,lifecycle:_(n,t.hostMode??CAPABILITY_HOST_MODES.embedded),tools:n,skills:t.skills.map(e=>({...e})),agentCount:t.agentCount,agentOnboardingCatalog:(t.agentOnboardingCatalog??[]).map(e=>({...e})),stableContext:{rules:o,shellHints:[...t.shellHints??[]]},dynamicContext:{cwd:t.cwd,platform:t.platform??process.platform}}}export function findCapabilityToolId(e,t){return e.tools.find(e=>e.role===t)?.id}export function listCapabilityToolIds(e,t){return e.tools.filter(e=>e.role===t).map(e=>e.id)}function T(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}export function buildEffectiveCapabilityTurnContext(e,t={}){const n=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.sessionList),o=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.transcriptRead);return{version:2,audience:e.audience,profile:e.profile,lifecycle:{...e.lifecycle},cwd:e.dynamicContext.cwd,platform:e.dynamicContext.platform,date:T(t.now??new Date),dynamic:{ruleIds:[...t.ruleIds??e.stableContext.rules],sessions:(t.sessions??[]).map(e=>({...e})),...t.vcs?{vcs:{...t.vcs}}:{},...t.origin?{origin:{...t.origin}}:{}},effectiveToolIds:e.tools.map(e=>e.id),explicitSkillNames:[...t.explicitSkillNames??[]],...n?{sessionListToolId:n}:{},...o?{transcriptReadToolId:o}:{}}}function y(e){return e.slice(0,i.arrayItems).map(e=>I(e))}function h(e){return{id:I(e.id),agentName:I(e.agentName),toolName:I(e.toolName),source:e.source,...e.transport?{transport:e.transport}:{},...e.runtimeOwnership?{runtimeOwnership:e.runtimeOwnership}:{},...e.annotations?{annotations:{...e.annotations}}:{},...e.appOutput?{appOutput:{...e.appOutput}}:{},role:e.role,approval:e.approval,...e.description?{description:I(e.description)}:{},inputSchema:O(e.inputSchema,{depth:0,key:"inputSchema",sensitive:!1})}}function E(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},tools:e.tools.slice(0,i.arrayItems).map(h),skills:e.skills.slice(0,i.arrayItems).map(e=>({name:I(e.name),description:I(e.description),source:e.source})),agentCount:e.agentCount,agentOnboardingCatalog:e.agentOnboardingCatalog.slice(0,i.arrayItems).map(e=>({shortName:I(e.shortName),description:I(e.description)})),stableContext:{rules:y(e.stableContext.rules),shellHints:y(e.stableContext.shellHints)},dynamicContext:{cwd:I(e.dynamicContext.cwd),platform:e.dynamicContext.platform}}}function g(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},cwd:I(e.cwd),platform:e.platform,date:I(e.date),dynamic:{ruleIds:y(e.dynamic.ruleIds),sessions:e.dynamic.sessions.slice(0,i.arrayItems).map(e=>({...e})),...e.dynamic.vcs?{vcs:{...e.dynamic.vcs,...e.dynamic.vcs.branch?{branch:I(e.dynamic.vcs.branch)}:{}}}:{},...e.dynamic.origin?{origin:{kind:e.dynamic.origin.kind,scheduleId:I(e.dynamic.origin.scheduleId),invocationId:I(e.dynamic.origin.invocationId),scheduledFor:I(e.dynamic.origin.scheduledFor),unattended:e.dynamic.origin.unattended}}:{}},effectiveToolIds:y(e.effectiveToolIds),explicitSkillNames:y(e.explicitSkillNames),...e.sessionListToolId?{sessionListToolId:I(e.sessionListToolId)}:{},...e.transcriptReadToolId?{transcriptReadToolId:I(e.transcriptReadToolId)}:{}}}export function createSafeCapabilitySnapshot(e,t){return{manifest:E(e),...t?{turnContext:g(t)}:{}}}
|