@roll-agent/runtime 0.22.0 → 0.23.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.
@@ -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{buildFileToolset as m}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as g}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as v,EXEC_LIST_NAME as f,EXEC_POLL_NAME as T,buildSessionExecToolset as y}from"../tool-bridge/session-exec-tool.js";import{SessionManager as C}from"../bash/session/session-manager.js";import{isTerminalSessionState as b}from"../bash/session/types.js";import{withCleanEnv as k}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as x,SESSION_CANCELLATION_REASONS as S,TURN_TIMEOUT_ABORT_REASON as I,USER_CANCELLATION_ABORT_REASON as M,createTurnCancellationMessage as E,isTurnTimeoutAbortReason as w,stripTurnCancellationMetadata as P}from"../types/cancellation.js";import{ToolRegistry as R}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as q,TOOL_OUTCOME_KINDS as A,createToolResult as O,failedToolResult as N,isNormalizedToolResult as j,normalizeToolResult as $,readDisplayOutput as W,readToolOutcome as D}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as F}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as L,prepareToolExecutionRecordForPersistence as U,redactSecretText as V,toRedactedToolExecutionRecordSummary as _}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as z,ToolExecutionCoordinator as G}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as B}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as H,compactMessages as K,CompactionDraftFallbackError as Y,estimateMessagesTokens as Q,estimateTextTokens as X,isCompactionSummaryAcknowledgement as Z,readCompactionSummaryPayload as ee}from"./compactor.js";import{AsyncEventQueue as te}from"./event-queue.js";import{applyExplicitSkillContext as se,attachExplicitSkillCheckpoint as oe,prepareExplicitSkillContext as ie,readExplicitSkillCheckpoint as ne,stripExplicitSkillCheckpoints as re}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as ae,createToolLedgerGapRecoveryMessage as ce,materializeCancelledTurnRecoveryMessages as le,stripCancelledTurnRecoveryMessages as ue}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as pe,CAPABILITY_TOOL_ROLES as de,buildEffectiveCapabilityTurnContext as he,buildEffectiveCapabilityManifest as me,findCapabilityToolId as ge,isProcessBoundHostMode as ve}from"./capability-manifest.js";import{buildCapabilityTurnReminder as fe,buildChatSystemPromptFromManifest as Te}from"./system-prompt.js";import{threadDerivedFromSchema as ye}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as Ce,buildCompactionToolState as be,COMPACTION_CHECKPOINT_VERSION as ke,createCompactionCheckpoint as xe,createCompactionSummary as Se,createCheckpointSemanticReminderProjection as Ie,findLatestRealUserGoal as Me,resolveActiveCompactionConstraints as Ee,TRANSCRIPT_MESSAGE_PROVENANCES as we}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Pe,buildCompactionSemanticEvidenceRegistry as Re,mergeCompactionSemanticState as qe,replaceCompactionSemanticConstraints as Ae,replaceCompactionSemanticGoal as Oe,renderCompactionSemanticSummary as Ne,seedCompactionSemanticConstraints as je,seedLegacyCompactionSnapshotUncertainties as $e,validateCompactionModelDraft as We}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as De,repairActiveToolProtocol as Fe}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Le}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as Ue}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ve}from"../tool-bridge/user-input-tool.js";const _e=6e3,ze=3e5,Ge=4,Be=2,Je=1,He={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Ke="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Ye=1024,Qe="AI_InvalidToolInputError:",Xe={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Ze(t){const s=[...t];if(s.length<=Ye)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Ye-[...o].length).join("")}${o}`}function et(){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 tt(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function st(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function ot(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function it(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function nt(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function rt(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=at(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function at(e){try{return JSON.stringify(e)??void 0}catch{return}}function ct(e){const t=ne(e.message),[s]=re([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 lt(e){return JSON.stringify(e)??String(e)}function ut(e){const t=U(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:lt(t.input.value),resultSummary:lt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===A.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function pt(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==ee(e.content)||"assistant"===e.role&&Z(e.content)}function dt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=ee(e.content);if(void 0!==t)return 0===t.length?[]:[V(t)]}return"assistant"===e.role&&Z(e.content)?[]:[V(ct({sequence:t,provenance:we[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!pt(e)).length}}function ht(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 mt(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===ke?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function gt(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 vt(e){return rt(W(e))}function ft(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(Qe)?A.invalidInput:A.toolFailed}function Tt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>D(e.output).kind===A.userRejected)??!1}function yt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(rt(e))}function Ct(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 bt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function kt(e,t){const s=bt(e.cachedInputTokens,t.cachedInputTokens),o=bt(e.cacheWriteTokens,t.cacheWriteTokens),i=bt(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 xt(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function St(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function It(e,t){return void 0!==e?e:w(t)?S.timeout:S.runtime}function Mt(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 Et(e,t,s){for(const o of Object.keys(t))e[o]=s}function wt(e,t,s){const o={[v]:de.sessionCommand,[T]:de.sessionPoll,[f]:de.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 Pt(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 B;userInputInteractions=new Ue;toolCoordinator=new G;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?Mt(e.initialMessages):[];this.messages=[...Fe(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?dt(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=mt(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)pt(e)||(this.inMemoryTranscript.push({sequence:s,provenance:we[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:ye.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 R,i={},n=Ve({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,Et(i,n.tools,de.userInput);const r=e.readCheckpointTranscript?Le(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};Et(i,r,de.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};Et(i,a,de.skill);const c=new J,l=e.fileTools?m(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(Et(i,l.readTools,de.fileRead),Et(i,l.editTools,de.fileEdit),Et(i,l.verifyTools,de.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},v=e.bashClassifier?{classifier:e.bashClassifier}:{},f=e.bash?g(e.bash,o,d,v):{};Et(i,f,de.shell),e.bashSession&&(this.sessionManager=new C({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:k(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const T=e.bashSession&&this.sessionManager?y({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...v,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};wt(i,T,o);const b=e.agentInstall,x=b?p({catalog:b.catalog,install:async(e,t)=>{const s=await b.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}):{};Et(i,x,de.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:{}};Et(i,S.createTools,de.scheduleCreate),Et(i,S.extendTools,de.scheduleExtend),Et(i,S.listTools,de.scheduleList);const I=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);Et(i,I.tools,de.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...f,...T,...x,...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 me({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??pe.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=Te(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);Et(this.toolRoles,t.tools,de.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);Et(this.toolRoles,e,de.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 te;this.emit=e=>s.push(e);const o=et();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:rt(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 te;this.emit=e=>t.push(e);const s=et();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:rt(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:`工具执行恢复状态持久化失败: ${rt(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:rt(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=S.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(I))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=ie({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},m=d.skillNames.length>0?oe(h,d):h;let g={};try{g=await gt(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(m),s.cancellationReason=It(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:rt(t)})}const v=he(this.capabilityManifest,{explicitSkillNames:d.skillNames,...g.ruleIds?{ruleIds:g.ruleIds}:{},...g.vcs?{vcs:g.vcs}:{},...g.origin?{origin:g.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=v;const f=fe(v);let T=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,T||this.messages.push(m);const n=ge(this.capabilityManifest,de.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:X(u),h=re(P(le(this.messages))),g=Pt(d.skillNames.length>0?se(h,d):h,u?`${f}\n\n${u}`:f);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 v=0;const y=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.modelTools(),prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),Tt(),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=>{tt(s,e),v=Q(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)tt(s,t)}});let C;try{C=y()}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=It(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!yt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,m,!1,r),void e.push({type:"error",stage:"execute",message:rt(t)})}this.debug(e,"model","streamText returned",r);let b,k,x,I,M,E,R,q="",O="",W=!1,D=0,U=!1,V=!1;const _=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of C.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=S.runtime;break}switch(V||(V=!0,this.clearDebugTimer(_),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!W){const s=O+t.text;if(St(s,d.userPrompt)){O=s;break}if(O.length>0){const s=O+t.text;O="",q+=s,e.push({type:"text-delta",delta:s});break}}q+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{W=!0,O="";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=j(t.output)?t.output:$(t.output),r=n.outcome,a=n.display,c=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==A.userRejected&&r.kind!==A.policyDenied&&r.kind!==A.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===A.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!==A.success}),s.aborted||s.abortController.signal.aborted||r.kind!==A.userRejected||(R=vt(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=ft(t.error),n=(i===A.invalidInput?F(t.error):void 0)??vt(t.error),r=N(i,n,{raw:t.error}),a=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==A.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=Ct(t.usage);k=xt(k,s.inputTokens),x=s.outputTokens,D+=1,M=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(I=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!W&&O.length>0&&(q+=O,e.push({type:"text-delta",delta:O}),O=""),b=Ct(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||w(t.error)){s.aborted=!0,s.cancellationReason=It(s.cancellationReason,t.error);break}U=yt(t.error),U&&(this.needsCompaction=!0),E=rt(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=It(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||w(e)?(s.aborted=!0,s.cancellationReason=It(s.cancellationReason,e)):(U=yt(e),U&&(this.needsCompaction=!0),E=rt(e))}finally{this.clearDebugTimer(_)}if(this.debug(e,"model","fullStream finished",r,{textChars:q.length}),void 0!==E){if(this.messages.splice(l),U){const t=0===q.length&&!W,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,q.length>0,r),void e.push({type:"error",stage:"execute",message:`${E}${a}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:E})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=It(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let z;this.debug(e,"model","awaiting response messages",r);const G=this.scheduleDebug(e,"model","still awaiting response messages",r);try{z=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(G),this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=It(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=yt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===q.length&&!W,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,q.length>0,r),void e.push({type:"error",stage:"execute",message:`${rt(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:rt(t)})}finally{this.clearDebugTimer(G)}if(this.debug(e,"model","response messages ready",r,{responseMessages:z.length}),this.isTurnAborted(s))return s.cancellationReason=It(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const B=Mt(z);if(this.messages.push(...B),void 0!==R){const t=0===q.length?R:`\n${R}`;q+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:R})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),nt(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),b&&(this.sessionUsage=kt(this.sessionUsage,b));const J=k??b?.inputTokens;void 0!==J&&(this.lastInputTokens=J,this.lastStepOutputTokens=x,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,J-Q(this.messages)+(x??0)+v-p)),s.completedStepCount+=D;const H=s.completedStepCount>=this.maxSteps&&"tool-calls"===M;if(e.push({type:"message-finish",text:q,...b?{totalUsage:b}:{},sessionUsage:{...this.sessionUsage},...void 0!==k?{contextInputTokens:k}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:rt(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,T=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=It(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:rt(t)}),e.push({type:"error",stage:"execute",message:rt(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)pt(o)||(this.inMemoryTranscript.push({sequence:t,provenance:we[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=ce(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!==A.policyDenied&&e.outcome.kind!==A.userRejected&&e.outcome.kind!==A.invalidInput&&(e.outcome.kind!==A.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?[]:[ce(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=st(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Fe(Mt(ot(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,ae({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 的操作。${Ke}`}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}: ${rt(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:Ze(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===z.write||t.mode!==z.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+ze,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 re(ue(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=>({..._(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:{..._(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=>D(e.output).kind===A.userRejected))return!1;const i=Ct(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Q(this.messages)+Q(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Q(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Q([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Q(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Q(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(ge(this.capabilityManifest,de.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:X(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?Ce(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,st(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:Q([{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?[]:ne(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:b(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=Me(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===ke?this.compactionCheckpoint.semanticState:void 0,u=je(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&ht(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?$e(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=mt(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,T=e.filter(e=>e.sequence>v),y=new Set(T.filter(e=>e.provenance===we[1]&&pt(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),b=Re({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:ct(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(ut),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),k=Pe(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=We({draft:s??Xe,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=qe(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Ee(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=Ae(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=Oe(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:Me(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?Ne(r):void 0,d=void 0!==p?Se(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Ie(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=be(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:rt(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g;try{const t=Date.now();try{g=await K({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 Y(H.missingObject,"structured compaction draft is missing")}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!Y.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:rt(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await K({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const v=g.removed>0||g.truncatedTools>0,f=Date.now(),T=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:T?.semanticRejectionCount??0}),void 0!==T&&T.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:T.semanticRejectionCount}),void 0!==T&&!T.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=Fe(g.messages),C=[...y.messages];if(y.status===De.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(pt))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=v&&b(C)<b(this.messages),x=k?C:[...this.messages],S=k?this.advanceCompactionSemanticEvidenceWatermarks(h,T?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(k){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===T)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:T.expectedActiveMessages,expectedLatestCheckpointId:T.expectedLatestCheckpointId,draft:T.draft,semanticState:T.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:T.evidenceWatermarks,...T.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:T.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===T)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=xe({draft:T.draft,semanticState:T.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:T.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:T.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:rt(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&&!b(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${rt(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=S.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(x))}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??S.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===S.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===S.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=ge(this.capabilityManifest,de.sessionList);switch(t){case S.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case S.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":ve(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case S.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??S.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=ge(this.capabilityManifest,de.sessionList),n=Ke;switch(t){case S.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case S.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:ve(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case S.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=S.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,He.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=He.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===He.keepRaw,r=n?Fe(Mt(ot(t))).messages:[],a=n?st(t):it(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[ae({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),E(this.cancellationDisplayMessage(e),e.cancellationReason??S.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}: ${rt(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??S.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=O({kind:A.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:rt(e.abortController.signal.reason)}});this.persistToolExecution(L({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=S.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(M),!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??=S.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(x)),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} 后台清理失败: ${rt(e)}\n`)});await s(e,_e)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(_e)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${rt(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${rt(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
1
+ import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{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&&gt(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)}}
@@ -1690,6 +1690,13 @@ export interface CompactionSemanticModelContext {
1690
1690
  export declare function buildCompactionSemanticModelContext(registry: CompactionSemanticEvidenceRegistry, previousState: CompactionSemanticState | undefined, maxChars?: number): CompactionSemanticModelContext;
1691
1691
  /** Includes prior stable IDs/text so the model can explicitly retain or resolve known items. */
1692
1692
  export declare function renderCompactionSemanticModelContext(registry: CompactionSemanticEvidenceRegistry, previousState: CompactionSemanticState | undefined, maxChars?: number): string;
1693
+ /** Only failures in a newly assembled candidate are eligible for draft recovery. */
1694
+ export declare class CompactionSemanticCandidateError extends Error {
1695
+ constructor(message: string, options?: ErrorOptions);
1696
+ }
1697
+ type CompactionSemanticItem = CompactionSemanticTextItem | CompactionSemanticResource | CompactionSemanticRunningSession;
1698
+ /** Coalesce grounded candidates before limits/uniqueness checks, never persisted state. */
1699
+ export declare function normalizeCompactionSemanticItems<T extends CompactionSemanticItem>(items: readonly T[]): T[];
1693
1700
  /**
1694
1701
  * Validates a model-authored semantic candidate against Harness-owned evidence.
1695
1702
  * Invalid individual claims are rejected without turning the remaining grounded
@@ -1742,3 +1749,4 @@ export declare function mergeCompactionSemanticState(previousInput: CompactionSe
1742
1749
  export declare function createCompactionSemanticReminderProjection(stateInput: CompactionSemanticState, maxChars?: number): CompactionSemanticReminderProjection;
1743
1750
  /** Renders a deterministic, bounded presentation derived only from grounded state. */
1744
1751
  export declare function renderCompactionSemanticSummary(stateInput: CompactionSemanticState, maxChars?: number): string;
1752
+ export {};
@@ -1 +1 @@
1
- import{createHash as e}from"node:crypto";import{z as n}from"zod";import{TOOL_OUTCOME_KINDS as t}from"../tool-bridge/normalize-result.js";export const COMPACTION_SEMANTIC_STATE_VERSION=1;export const COMPACTION_PROVENANCE_KINDS=["message","tool_execution","resource","running_session","legacy_snapshot"];export const COMPACTION_SEMANTIC_ITEM_KINDS=["goal","constraint","decision","completed_work","pending_work","resource","running_session","uncertainty"];const o=["goal","constraint","pending_work","uncertainty","decision","resource","completed_work"],r=/^semantic_(?:goal|constraint|decision|completed_work|pending_work|resource|running_session|uncertainty)_[0-9a-f]{24}$/u,s=1024,i=1024,a=8,c=8,u=512,d=64,m=128,p=128,l=128,g=256,I=128,v=128,S=131072,h=12e3,y=512,f=16,_=16e3,x=512,k=32;export const legacyCompactionTranscriptFragmentsSchema=n.array(n.string().trim().min(1).max(u)).max(v).readonly();export const compactionSemanticItemIdSchema=n.string().regex(r).brand();export const compactionProvenanceRefSchema=n.object({kind:n.enum(COMPACTION_PROVENANCE_KINDS),messageSequence:n.number().int().nonnegative().nullable(),toolExecutionId:n.string().uuid().nullable(),resourceKey:n.string().trim().min(1).nullable(),managerInstanceId:n.string().uuid().nullable(),sessionId:n.number().int().nonnegative().nullable(),checkpointId:n.string().uuid().nullable().default(null),snapshotIndex:n.number().int().nonnegative().nullable().default(null)}).strict().superRefine((e,t)=>{const o=["messageSequence","toolExecutionId","resourceKey","managerInstanceId","sessionId","checkpointId","snapshotIndex"],r=new Set({message:["messageSequence"],tool_execution:["toolExecutionId"],resource:["resourceKey"],running_session:["managerInstanceId","sessionId"],legacy_snapshot:["checkpointId","snapshotIndex"]}[e.kind]);for(const s of o){const o=e[s];(r.has(s)?null===o:null!==o)&&t.addIssue({code:n.ZodIssueCode.custom,message:`${s} must be ${r.has(s)?"non-null":"null"} for ${e.kind}`,path:[s]})}}).readonly();const w={priorItemId:n.string().trim().min(1).max(128).nullable(),text:n.string().trim().min(1).max(s),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).min(1).max(8)},C=n.object(w).strict().readonly(),b={priorItemId:n.string().trim().min(1).max(128).nullable(),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8)},E=n.object(b).strict().readonly(),$={priorItemId:n.string().trim().min(1).max(128).nullable(),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8)},N=n.object($).strict().readonly(),M=n.object({targetItemId:n.string().trim().min(1).max(128),targetCategory:n.enum(["constraint","decision","pending_work","uncertainty"]),action:n.enum(["cancel","supersede","clarify","revoke"]),reason:n.string().trim().min(1).max(i),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).min(1).max(8)}).strict().readonly(),K=n.object({evidenceId:n.string().trim().min(1).max(128),disposition:n.enum(["irrelevant","uncertain"]),reason:n.string().trim().min(1).max(i)}).strict().readonly();export const compactionModelDraftSchema=n.object({startsNewGoalScope:n.boolean(),goal:C.nullable(),constraints:n.array(C).max(m),decisions:n.array(C).max(d),completedWork:n.array(C).max(p),pendingWork:n.array(C).max(l),resources:n.array(E).max(g),runningSessions:n.array(N).max(I),uncertainties:n.array(C).max(v),resolutions:n.array(M).max(256),evidenceReviews:n.array(K).max(512)}).strict().readonly();export function createEmptyCompactionModelDraft(){return compactionModelDraftSchema.parse({startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]})}const q={id:compactionSemanticItemIdSchema,text:n.string().trim().min(1).max(s),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).max(8).default([])},R=n.object(q).strict().readonly(),W={id:compactionSemanticItemIdSchema,resourceKey:n.string().trim().min(1).max(s),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8)},j=n.object(W).strict().readonly(),Q={id:compactionSemanticItemIdSchema,managerInstanceId:n.string().uuid(),sessionId:n.number().int().nonnegative(),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8)},O=n.object(Q).strict().readonly(),P=n.object({constraint:n.number().int().nonnegative().default(0),decision:n.number().int().nonnegative(),completed_work:n.number().int().nonnegative(),pending_work:n.number().int().nonnegative(),resource:n.number().int().nonnegative(),running_session:n.number().int().nonnegative(),uncertainty:n.number().int().nonnegative()}).strict().readonly(),T=Object.freeze({constraint:0,decision:0,completed_work:0,pending_work:0,resource:0,running_session:0,uncertainty:0});export const compactionSemanticStateSchema=n.object({version:n.literal(1),goal:R.nullable(),constraints:n.array(R).max(m).default([]),decisions:n.array(R).max(d),completedWork:n.array(R).max(p),pendingWork:n.array(R).max(l),resources:n.array(j).max(g),runningSessions:n.array(O).max(I),uncertainties:n.array(R).max(v),prunedItemCounts:P.default(T)}).strict().superRefine((e,t)=>{const o=new Set,r=[...null===e.goal?[]:[["goal",e.goal.id]],...e.constraints.map(e=>["constraint",e.id]),...e.decisions.map(e=>["decision",e.id]),...e.completedWork.map(e=>["completed_work",e.id]),...e.pendingWork.map(e=>["pending_work",e.id]),...e.resources.map(e=>["resource",e.id]),...e.runningSessions.map(e=>["running_session",e.id]),...e.uncertainties.map(e=>["uncertainty",e.id])];for(const[e,s]of r)s.startsWith(`semantic_${e}_`)||t.addIssue({code:n.ZodIssueCode.custom,message:`semantic item ID does not match category ${e}`}),o.has(s)&&t.addIssue({code:n.ZodIssueCode.custom,message:`duplicate semantic item ID: ${s}`}),o.add(s)}).readonly();const A=n.object({itemId:compactionSemanticItemIdSchema,category:n.enum(COMPACTION_SEMANTIC_ITEM_KINDS),text:n.string().trim().min(1).max(x),sourceQuotes:n.array(n.string().trim().min(1).max(u)).max(8)}).strict().readonly(),D=n.object({goal:n.number().int().nonnegative(),constraint:n.number().int().nonnegative(),decision:n.number().int().nonnegative(),completed_work:n.number().int().nonnegative(),pending_work:n.number().int().nonnegative(),resource:n.number().int().nonnegative(),running_session:n.number().int().nonnegative(),uncertainty:n.number().int().nonnegative()}).strict().readonly();export const compactionSemanticReminderProjectionSchema=n.object({version:n.literal(1),items:n.array(A),omittedCounts:D}).strict().readonly();export const COMPACTION_SEMANTIC_REJECTION_REASONS=["unknown_provenance","missing_required_provenance","completed_work_without_success_evidence","resource_not_observed","running_session_not_observed","unknown_resolution_target","resolution_target_category_mismatch","invalid_resolution_action","unsupported_source_quote","unknown_evidence_review"];function G(e){return e.trim().replace(/\s+/gu," ")}function U(e){switch(e.kind){case"message":return`message:${String(e.messageSequence)}`;case"tool_execution":return`tool_execution:${String(e.toolExecutionId)}`;case"resource":return`resource:${String(e.resourceKey)}`;case"running_session":return`running_session:${String(e.managerInstanceId)}:${String(e.sessionId)}`;case"legacy_snapshot":return`legacy_snapshot:${String(e.checkpointId)}:${String(e.snapshotIndex)}`}}function F(n,t,o){const r=[n,G(t),...o.map(U).sort((e,n)=>e.localeCompare(n))].join("\n"),s=e("sha256").update(r).digest("hex").slice(0,24);return compactionSemanticItemIdSchema.parse(`semantic_${n}_${s}`)}function J(n,t){return`evidence_${e("sha256").update(`${n}\n${t}`).digest("hex").slice(0,24)}`}function z(e){return compactionProvenanceRefSchema.parse({kind:e.kind,messageSequence:"message"===e.kind?e.sequence:null,toolExecutionId:"tool_execution"===e.kind?e.executionId:null,resourceKey:"resource"===e.kind?e.resourceKey:null,managerInstanceId:"running_session"===e.kind?e.managerInstanceId:null,sessionId:"running_session"===e.kind?e.sessionId:null,checkpointId:"legacy_snapshot"===e.kind?e.checkpointId:null,snapshotIndex:"legacy_snapshot"===e.kind?e.snapshotIndex:null})}export function buildCompactionSemanticEvidenceRegistry(e){const n=[];for(const t of e.messages){const e=z({kind:"message",sequence:t.sequence});n.push({evidenceId:J("message",String(t.sequence)),summary:me(t.summary,512),provenance:e,...void 0===t.role?{}:{messageRole:t.role}})}for(const t of e.toolExecutions){const e=z({kind:"tool_execution",executionId:t.id});n.push({evidenceId:J("tool_execution",t.id),summary:me([`${t.agentName??"agent"}/${t.toolName??"tool"}: ${t.outcome.kind}`,...void 0===t.outcome.executionState?[]:[`executionState=${t.outcome.executionState}`],...void 0===t.inputSummary?[]:[`input=${me(t.inputSummary,160)}`],...void 0===t.resultSummary?[]:[`result=${me(t.resultSummary,256)}`]].join("; "),512),provenance:e,toolOutcomeKind:t.outcome.kind,...void 0===t.outcome.executionState?{}:{toolCancellationExecutionState:t.outcome.executionState}})}for(const t of e.resources){const e=z({kind:"resource",resourceKey:t.key});n.push({evidenceId:J("resource",t.key),summary:me(`${void 0===t.mode?"resource":t.mode}: ${t.key}`,512),provenance:e})}for(const t of e.runningSessions){const e=`${t.managerInstanceId}:${String(t.sessionId)}`,o=z({kind:"running_session",managerInstanceId:t.managerInstanceId,sessionId:t.sessionId});n.push({evidenceId:J("running_session",e),summary:me(`session ${t.state??"observed"}`,512),provenance:o})}const t=new Map;for(const e of n)t.has(e.evidenceId)||t.set(e.evidenceId,e);return[...t.values()]}function V(e){return e.map(e=>({evidenceId:e.evidenceId,kind:e.provenance.kind,summary:Z(e),...void 0===e.messageRole?{}:{role:e.messageRole},...void 0===e.toolOutcomeKind?{}:{outcome:e.toolOutcomeKind},...void 0===e.toolCancellationExecutionState?{}:{executionState:e.toolCancellationExecutionState}}))}function Z(e){return me(e.summary,256)}function L(e){if(void 0===e)return[];const n=compactionSemanticStateSchema.parse(e),t=(e,n)=>n.slice(-16).map(n=>({itemId:n.id,category:e,text:me(n.text,256),sourceQuotes:n.sourceQuotes.map(e=>me(e,256))}));return[...null===n.goal?[]:[{itemId:n.goal.id,category:"goal",text:me(n.goal.text,256),sourceQuotes:n.goal.sourceQuotes.map(e=>me(e,256))}],...t("constraint",n.constraints),...t("pending_work",n.pendingWork),...t("uncertainty",n.uncertainties),...t("decision",n.decisions),...t("completed_work",n.completedWork),...n.resources.slice(-16).map(e=>({itemId:e.id,category:"resource",text:me(e.resourceKey,256),sourceQuotes:[me(e.resourceKey,256)]}))]}function B(e,n,t){const o=[],r=[],s=()=>JSON.stringify({previousSemanticItems:o,evidence:r,omittedPreviousItemCount:n.length-o.length,omittedEvidenceCount:e.length-r.length}),i=(e,n)=>(e.push(n),[...s()].length<=t||(e.pop(),!1));let a=0,c=0;void 0!==n[0]&&i(o,n[0])&&(a=1),void 0!==e[0]&&i(r,e[0])&&(c=1);for(const n of e.slice(c)){if(r.length>=k)break;if(!i(r,n))break}for(const e of n.slice(a))if(!i(o,e))break;return{prompt:s(),includedEvidenceIds:r.map(e=>e.evidenceId)}}export function renderCompactionSemanticEvidenceRegistry(e,n=24e3){if(!Number.isInteger(n)||n<1024||n>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return B(V(e),[],n).prompt}export function buildCompactionSemanticModelContext(e,n,t=24e3){if(!Number.isInteger(t)||t<1024||t>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return B(V(e),L(n),t)}export function renderCompactionSemanticModelContext(e,n,t=24e3){if(!Number.isInteger(t)||t<1024||t>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return buildCompactionSemanticModelContext(e,n,t).prompt}function H(e){const n=e=>new Map(e?.map(e=>[e.id,e.text])??[]);return{goal:new Map(null==e?.goal?[]:[[e.goal.id,e.goal.text]]),constraint:n(e?.constraints),decision:n(e?.decisions),completed_work:n(e?.completedWork),pending_work:n(e?.pendingWork),resource:new Map(e?.resources.map(e=>[e.id,e.resourceKey])??[]),running_session:new Map(e?.runningSessions.map(e=>[e.id,`${e.managerInstanceId}:${String(e.sessionId)}`])??[]),uncertainty:n(e?.uncertainties)}}function X(e,n,t,o,r){const s=null===e?void 0:r.get(e);return void 0!==s&&G(s)===G(t)?compactionSemanticItemIdSchema.parse(e):F(n,t,o)}function Y(e){return 1===e.length&&"tool_execution"===e[0]?.provenance.kind&&e[0].toolOutcomeKind===t.success}function ee(e){return 1===e.length&&e.every(e=>"message"===e.provenance.kind&&"user"===e.messageRole)}function ne(e,n){return!!Y(e)&&se(e,n)}function te(e,n){const t=e.map(e=>e.replace(/^message \d+ (?:user|assistant|system|tool): /u,"")).map(G).join("; ");return me(void 0===n?t:`${n}: ${t}`,s)}function oe(e){return"tool_execution"===e.provenance.kind&&e.toolOutcomeKind===t.success}function re(e){return[...new Map(e.map(e=>[U(e.provenance),e.provenance])).values()]}function se(e,n){const t=e.map(Z);return t.length===n.length&&t.every((e,t)=>e===n[t])}export function validateCompactionModelDraft(e){const n=compactionModelDraftSchema.parse(e.draft),t=void 0===e.previousState?void 0:compactionSemanticStateSchema.parse(e.previousState),o=H(t),r=new Map([...t?.constraints.map(e=>[e.id,"constraint"])??[],...t?.decisions.map(e=>[e.id,"decision"])??[],...t?.pendingWork.map(e=>[e.id,"pending_work"])??[],...t?.uncertainties.map(e=>[e.id,"uncertainty"])??[]]),i=new Map((t?.completedWork??[]).map(e=>[e.id,e])),a=new Map;for(const n of e.evidenceRegistry){const e={...n,provenance:compactionProvenanceRefSchema.parse(n.provenance)};if(a.has(e.evidenceId))throw new Error(`Duplicate compaction evidence ID: ${e.evidenceId}`);a.set(e.evidenceId,e)}const c=void 0===e.presentedEvidenceIds?void 0:new Set(e.presentedEvidenceIds),S=e=>{if(new Set(e).size!==e.length)return;const n=[];for(const t of e){if(void 0!==c&&!c.has(t))return;const e=a.get(t);if(void 0===e)return;n.push(e)}return n},h=[],y=new Set,f=e=>{for(const n of e)y.add(n)},_=(e,n,t,r,s=!1)=>{const a=[];return t.forEach((t,c)=>{const u=r&&null!==t.priorItemId?i.get(t.priorItemId):void 0;if(void 0!==u&&G(t.text)===u.text)return void a.push(u);const d=S(t.sourceEvidenceIds);if(void 0===d)return void h.push({category:e,index:c,reason:"unknown_provenance"});if(!se(d,t.sourceQuotes))return void h.push({category:e,index:c,reason:"unsupported_source_quote"});if(s&&!ee(d))return void h.push({category:e,index:c,reason:"missing_required_provenance"});if(r&&!ne(d,t.sourceQuotes))return void h.push({category:e,index:c,reason:"completed_work_without_success_evidence"});const m=r?te(t.sourceQuotes,"Successful Tool evidence"):te(t.sourceQuotes);f(t.sourceEvidenceIds),a.push(R.parse({text:m,provenance:re(d),sourceQuotes:[...t.sourceQuotes],id:X(t.priorItemId,n,m,re(d),o[n])}))}),a};let x=null;if(null!==n.goal){const e=S(n.goal.sourceEvidenceIds);if(void 0===e)h.push({category:"goal",index:0,reason:"unknown_provenance"});else if(ee(e))if(se(e,n.goal.sourceQuotes)){const t=re(e);f(n.goal.sourceEvidenceIds);const r=te(n.goal.sourceQuotes);x=R.parse({text:r,provenance:t,sourceQuotes:[...n.goal.sourceQuotes],id:X(n.goal.priorItemId,"goal",r,t,o.goal)})}else h.push({category:"goal",index:0,reason:"unsupported_source_quote"});else h.push({category:"goal",index:0,reason:"missing_required_provenance"})}const k=e.harnessGoal,w=void 0===k?void 0:z({kind:"message",sequence:k.sourceSequence}),C=void 0===k?void 0:me(k.verbatimRequest,s),b=void 0===k||void 0===w||void 0===C?null:R.parse({text:C,provenance:[w],sourceQuotes:[me(k.verbatimRequest,u)],id:X(null,"goal",C,[w],o.goal)});if(void 0!==k&&null==t?.goal)for(const e of a.values())"message"===e.provenance.kind&&e.provenance.messageSequence===k.sourceSequence&&y.add(e.evidenceId);const E=null!=t?.goal&&n.startsNewGoalScope&&null!==x,$=E?x:t?.goal??b??x,N=[];n.resources.forEach((e,n)=>{const t=S(e.sourceEvidenceIds);if(void 0===t)return void h.push({category:"resource",index:n,reason:"unknown_provenance"});const r=t.filter(e=>"resource"===e.provenance.kind),i=r[0]?.provenance.resourceKey;if(1!==r.length||null==i)return void h.push({category:"resource",index:n,reason:"resource_not_observed"});const a=re(t);f(e.sourceEvidenceIds);const c=me(i,s);N.push(j.parse({resourceKey:c,provenance:a,id:X(e.priorItemId,"resource",c,a,o.resource)}))});const M=new Set(N.map(e=>e.resourceKey));for(const e of a.values()){const n=e.provenance.resourceKey;"resource"!==e.provenance.kind||null===n||M.has(n)||(N.push(j.parse({resourceKey:me(n,s),provenance:[e.provenance],id:F("resource",me(n,s),[e.provenance])})),M.add(n))}const K=[];n.runningSessions.forEach((e,n)=>{const t=S(e.sourceEvidenceIds);if(void 0===t)return void h.push({category:"running_session",index:n,reason:"unknown_provenance"});const r=t.filter(e=>"running_session"===e.provenance.kind),s=r[0]?.provenance;if(1!==r.length||null==s?.managerInstanceId||null===s.sessionId)return void h.push({category:"running_session",index:n,reason:"running_session_not_observed"});const i=`${s.managerInstanceId}:${String(s.sessionId)}`,a=re(t);f(e.sourceEvidenceIds),K.push(O.parse({managerInstanceId:s.managerInstanceId,sessionId:s.sessionId,provenance:a,id:X(e.priorItemId,"running_session",i,a,o.running_session)}))});const q=new Set(K.map(e=>`${e.managerInstanceId}:${String(e.sessionId)}`));for(const e of a.values()){const n=e.provenance;if("running_session"!==n.kind||null===n.managerInstanceId||null===n.sessionId)continue;const t=`${n.managerInstanceId}:${String(n.sessionId)}`;q.has(t)||(K.push(O.parse({managerInstanceId:n.managerInstanceId,sessionId:n.sessionId,provenance:[n],id:F("running_session",t,[n])})),q.add(t))}const W=[];n.resolutions.forEach((e,n)=>{const t=r.get(e.targetItemId);if(void 0===t)return void h.push({category:"resolution",index:n,reason:"unknown_resolution_target"});if(t!==e.targetCategory)return void h.push({category:"resolution",index:n,reason:"resolution_target_category_mismatch"});if(!("constraint"===t&&"revoke"===e.action||"decision"===t&&"supersede"===e.action||"pending_work"===t&&"cancel"===e.action||"uncertainty"===t&&"clarify"===e.action))return void h.push({category:"resolution",index:n,reason:"invalid_resolution_action"});const o=S(e.sourceEvidenceIds);if(void 0===o)return void h.push({category:"resolution",index:n,reason:"unknown_provenance"});if(!se(o,e.sourceQuotes))return void h.push({category:"resolution",index:n,reason:"unsupported_source_quote"});if(!ee(o))return void h.push({category:"resolution",index:n,reason:"missing_required_provenance"});f(e.sourceEvidenceIds);const s=re(o);W.push({targetItemId:compactionSemanticItemIdSchema.parse(e.targetItemId),targetCategory:e.targetCategory,action:e.action,reason:G(e.reason),provenance:s})});const Q=_("decision","decision",n.decisions,!1),P=_("constraint","constraint",n.constraints,!1,!0),T=_("completed_work","completed_work",n.completedWork,!0),A=_("pending_work","pending_work",n.pendingWork,!1),D=_("uncertainty","uncertainty",n.uncertainties,!1),U=[],J=(e,n)=>{if(oe(e))return;const t=me(`${n}: ${e.summary}`,s);U.push(R.parse({id:F("uncertainty",t,[e.provenance]),text:t,provenance:[e.provenance],sourceQuotes:[me(e.summary,u)]}))};n.evidenceReviews.forEach((e,n)=>{const t=a.get(e.evidenceId);void 0!==t?(y.add(e.evidenceId),"message"!==t.provenance.kind&&"tool_execution"!==t.provenance.kind||"irrelevant"===e.disposition&&"assistant"===t.messageRole||J(t,"uncertain"===e.disposition?"Unresolved evidence":"User or Tool evidence classified as irrelevant")):h.push({category:"evidence_review",index:n,reason:"unknown_evidence_review"})});for(const n of e.presentedEvidenceIds??[]){if(y.has(n))continue;const e=a.get(n);void 0===e||"message"!==e.provenance.kind&&"tool_execution"!==e.provenance.kind||(J(e,"Unclassified evidence"),y.add(n))}const V=ce(P,m),Z=ce(Q,d),L=ce(T,p),B=ce(A,l),Y=ce(N,g),ie=ce(K,I),ae=ce([...D,...U],v);return{state:compactionSemanticStateSchema.parse({version:1,goal:$,constraints:V.items,decisions:Z.items,completedWork:L.items,pendingWork:B.items,resources:Y.items,runningSessions:ie.items,uncertainties:ae.items,prunedItemCounts:{constraint:V.prunedCount,decision:Z.prunedCount,completed_work:L.prunedCount,pending_work:B.prunedCount,resource:Y.prunedCount,running_session:ie.prunedCount,uncertainty:ae.prunedCount}}),resolutions:W,rejections:h,coveredEvidenceIds:[...y],startsNewGoalScope:E}}export function createEmptyCompactionSemanticState(){return compactionSemanticStateSchema.parse({version:1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],prunedItemCounts:T})}export function seedCompactionSemanticConstraints(e,n){const t=void 0===e?createEmptyCompactionSemanticState():compactionSemanticStateSchema.parse(e),o=ae(n),r=ue(t.constraints,o,new Set,m);return de(compactionSemanticStateSchema.parse({...t,constraints:r.items,prunedItemCounts:{...t.prunedItemCounts,constraint:t.prunedItemCounts.constraint+r.prunedCount}}))}function ie(e,n){const t=[];let o="";for(const r of e){if(o.length>0&&o.length+r.length>n){const e=o.trim();e.length>0&&t.push(e),o=r;continue}o+=r}const r=o.trim();return r.length>0&&t.push(r),t}export function seedLegacyCompactionSnapshotUncertainties(e,n){const t=compactionSemanticStateSchema.parse(e),o=n.fragments.flatMap(e=>ie(e,u));if(0===o.length)return{state:t,requiredItemIds:[],transcriptFragments:[],complete:!0};const r=o.map((e,t)=>{const o=z({kind:"legacy_snapshot",checkpointId:n.checkpointId,snapshotIndex:t}),r=me(`Unverified legacy V1 active snapshot; confirm before acting: ${e}`,s);return R.parse({id:F("uncertainty",r,[o]),text:r,provenance:[o],sourceQuotes:[e]})}),i=ue(t.uncertainties,r,new Set,v),a=de(compactionSemanticStateSchema.parse({...t,uncertainties:i.items,prunedItemCounts:{...t.prunedItemCounts,uncertainty:t.prunedItemCounts.uncertainty+i.prunedCount}})),c=new Set(a.uncertainties.map(e=>e.id)),d=r.every(e=>c.has(e.id));return{state:a,requiredItemIds:r.map(e=>e.id),transcriptFragments:d?legacyCompactionTranscriptFragmentsSchema.parse(o):legacyCompactionTranscriptFragmentsSchema.parse([]),complete:d}}function ae(e){return e.map(e=>{const n=z({kind:"message",sequence:e.sourceSequence}),t=me(e.quote,u);return R.parse({id:F("constraint",t,[n]),text:t,provenance:[n],sourceQuotes:[t]})})}export function replaceCompactionSemanticConstraints(e,n){const t=compactionSemanticStateSchema.parse(e),o=ce(ae(n),m);return de(compactionSemanticStateSchema.parse({...t,constraints:o.items,prunedItemCounts:{...t.prunedItemCounts,constraint:t.prunedItemCounts.constraint+o.prunedCount}}))}export function replaceCompactionSemanticGoal(e,n){const t=compactionSemanticStateSchema.parse(e);if(void 0===n)return de(compactionSemanticStateSchema.parse({...t,goal:null}));const o=z({kind:"message",sequence:n.sourceSequence}),r=me(n.verbatimRequest,s),i=me(n.verbatimRequest,u);return de(compactionSemanticStateSchema.parse({...t,goal:R.parse({id:F("goal",r,[o]),text:r,provenance:[o],sourceQuotes:[i]})}))}function ce(e,n){const t=Math.max(0,e.length-n);return{items:0===t?[...e]:e.slice(-n),prunedCount:t}}function ue(e,n,t,o){const r=new Map;for(const n of e)t.has(n.id)||r.set(n.id,n);for(const e of n)t.has(e.id)||r.set(e.id,e);return ce([...r.values()],o)}function de(e){const n=compactionSemanticStateSchema.parse(e),t=[...n.constraints],o=[...n.decisions],r=[...n.completedWork],s=[...n.pendingWork],i=[...n.resources],a=[...n.runningSessions],c=[...n.uncertainties],u={...n.prunedItemCounts},d=()=>compactionSemanticStateSchema.parse({...n,constraints:t,decisions:o,completedWork:r,pendingWork:s,resources:i,runningSessions:a,uncertainties:c,prunedItemCounts:u}),m=[{countKey:"completed_work",items:r},{countKey:"resource",items:i},{countKey:"decision",items:o},{countKey:"running_session",items:a},{countKey:"uncertainty",items:c},{countKey:"constraint",items:t},{countKey:"pending_work",items:s}];let p=!0;for(;Buffer.byteLength(JSON.stringify(d()),"utf8")>S;){const e=m.find(({items:e})=>p?e.length>1:e.length>0);if(void 0===e){if(p){p=!1;continue}throw new Error("Compaction semantic state exceeds its aggregate storage budget")}e.items.shift(),u[e.countKey]+=1}return d()}export function mergeCompactionSemanticState(e,n,t){const o=void 0===e?createEmptyCompactionSemanticState():compactionSemanticStateSchema.parse(e),r=compactionSemanticStateSchema.parse(n.state),s=new Set(n.resolutions.filter(e=>"constraint"===e.targetCategory).map(e=>e.targetItemId)),i=new Set(n.resolutions.filter(e=>"decision"===e.targetCategory).map(e=>e.targetItemId)),a=new Set(n.resolutions.filter(e=>"pending_work"===e.targetCategory).map(e=>e.targetItemId)),c=new Set(n.resolutions.filter(e=>"uncertainty"===e.targetCategory).map(e=>e.targetItemId)),u=t.startsNewGoalScope&&n.startsNewGoalScope,I=ue(o.constraints,r.constraints,s,m),S=ue(o.decisions,r.decisions,i,d),h=ue(o.completedWork,r.completedWork,new Set,p),y=ue(o.pendingWork,r.pendingWork,a,l),f=ue(o.resources,r.resources,new Set,g),_=ue(o.uncertainties,r.uncertainties,c,v);return de(compactionSemanticStateSchema.parse({version:1,goal:u||null!==r.goal?r.goal:o.goal,constraints:I.items,decisions:S.items,completedWork:h.items,pendingWork:y.items,resources:f.items,runningSessions:r.runningSessions.slice(-128),uncertainties:_.items,prunedItemCounts:{constraint:o.prunedItemCounts.constraint+r.prunedItemCounts.constraint+I.prunedCount,decision:o.prunedItemCounts.decision+r.prunedItemCounts.decision+S.prunedCount,completed_work:o.prunedItemCounts.completed_work+r.prunedItemCounts.completed_work+h.prunedCount,pending_work:o.prunedItemCounts.pending_work+r.prunedItemCounts.pending_work+y.prunedCount,resource:o.prunedItemCounts.resource+r.prunedItemCounts.resource+f.prunedCount,running_session:o.prunedItemCounts.running_session+r.prunedItemCounts.running_session,uncertainty:o.prunedItemCounts.uncertainty+r.prunedItemCounts.uncertainty+_.prunedCount}}))}function me(e,n){const t=G(e),o=[...t];return o.length<=n?t:`${o.slice(0,Math.max(0,n-1)).join("")}…`}function pe(e){const n=(e,n)=>n.map(n=>({itemId:n.id,category:e,text:me(n.text,x),sourceQuotes:n.sourceQuotes.map(e=>me(e,u))}));return[...null===e.goal?[]:[{itemId:e.goal.id,category:"goal",text:me(e.goal.text,x),sourceQuotes:e.goal.sourceQuotes.map(e=>me(e,u))}],...n("constraint",e.constraints),...n("pending_work",e.pendingWork),...n("uncertainty",e.uncertainties),...n("decision",e.decisions),...e.resources.map(e=>({itemId:e.id,category:"resource",text:me(e.resourceKey,x),sourceQuotes:[me(e.resourceKey,u)]})),...n("completed_work",e.completedWork)]}export function createCompactionSemanticReminderProjection(e,n=16e3){if(!Number.isInteger(n)||n<1024||n>32e3)throw new Error("maxChars must be an integer between 1024 and 32000");const t=compactionSemanticStateSchema.parse(e),r=o,s=pe(t),i=new Map(r.map(e=>[e,s.filter(n=>n.category===e)])),a=[],c=()=>{const e=new Map(r.map(e=>[e,a.filter(n=>n.category===e).length]));return compactionSemanticReminderProjectionSchema.parse({version:1,items:a,omittedCounts:{goal:(i.get("goal")?.length??0)-(e.get("goal")??0),constraint:t.prunedItemCounts.constraint+(i.get("constraint")?.length??0)-(e.get("constraint")??0),decision:t.prunedItemCounts.decision+(i.get("decision")?.length??0)-(e.get("decision")??0),completed_work:t.prunedItemCounts.completed_work+(i.get("completed_work")?.length??0)-(e.get("completed_work")??0),pending_work:t.prunedItemCounts.pending_work+(i.get("pending_work")?.length??0)-(e.get("pending_work")??0),resource:t.prunedItemCounts.resource+(i.get("resource")?.length??0)-(e.get("resource")??0),running_session:t.prunedItemCounts.running_session+t.runningSessions.length,uncertainty:t.prunedItemCounts.uncertainty+(i.get("uncertainty")?.length??0)-(e.get("uncertainty")??0)}})},u=Math.max(0,...[...i.values()].map(e=>e.length));for(let e=0;e<u;e+=1)for(const t of r){const o=(i.get(t)??[]).at(-(e+1));void 0!==o&&(a.push(o),JSON.stringify(c()).length>n&&a.pop())}const d=c();if(JSON.stringify(d).length>n)throw new Error("Unable to create bounded semantic reminder projection");return d}export function renderCompactionSemanticSummary(e,n=12e3){if(!Number.isInteger(n)||n<1024||n>32e3)throw new Error("maxChars must be an integer between 1024 and 32000");const t=createCompactionSemanticReminderProjection(compactionSemanticStateSchema.parse(e),n),r={goal:"Goal",constraint:"Active constraints",pending_work:"Pending work",uncertainty:"Uncertainties",decision:"Decisions",resource:"Resources",completed_work:"Completed work"},s=t.omittedCounts,i=["Evidence-grounded structured compaction state:","Each semantic item is a classification; its source quote is the authoritative wording."];for(const e of o){i.push(`${r[e]}:`);const n=t.items.filter(n=>n.category===e);0===n.length?i.push("- (none retained in prompt projection)"):i.push(...n.map(e=>{const n=e.sourceQuotes.map(e=>me(e,y)).join(" | ");return`- [${e.itemId}] interpretation=${me(e.text,y)}; source=${n}`})),s[e]>0&&i.push(`- … ${String(s[e])} item(s) omitted; use transcript evidence`)}const a="\n… summary truncated",c=n-[...a].length,u=[];for(const e of i){if([...[...u,e].join("\n")].length>c)break;u.push(e)}const d=u.join("\n");return u.length===i.length?d:`${d}${a}`}
1
+ import{createHash as e}from"node:crypto";import{z as n}from"zod";import{TOOL_OUTCOME_KINDS as t}from"../tool-bridge/normalize-result.js";export const COMPACTION_SEMANTIC_STATE_VERSION=1;export const COMPACTION_PROVENANCE_KINDS=["message","tool_execution","resource","running_session","legacy_snapshot"];export const COMPACTION_SEMANTIC_ITEM_KINDS=["goal","constraint","decision","completed_work","pending_work","resource","running_session","uncertainty"];const o=["goal","constraint","pending_work","uncertainty","decision","resource","completed_work"],r=/^semantic_(?:goal|constraint|decision|completed_work|pending_work|resource|running_session|uncertainty)_[0-9a-f]{24}$/u,s=1024,i=1024,a=8,c=8,u=512,d=64,m=128,p=128,l=128,g=256,I=128,v=128,S=131072,h=12e3,f=512,y=16,_=16e3,x=512,k=32;export const legacyCompactionTranscriptFragmentsSchema=n.array(n.string().trim().min(1).max(u)).max(v).readonly();export const compactionSemanticItemIdSchema=n.string().regex(r).brand();export const compactionProvenanceRefSchema=n.object({kind:n.enum(COMPACTION_PROVENANCE_KINDS),messageSequence:n.number().int().nonnegative().nullable(),toolExecutionId:n.string().uuid().nullable(),resourceKey:n.string().trim().min(1).nullable(),managerInstanceId:n.string().uuid().nullable(),sessionId:n.number().int().nonnegative().nullable(),checkpointId:n.string().uuid().nullable().default(null),snapshotIndex:n.number().int().nonnegative().nullable().default(null)}).strict().superRefine((e,t)=>{const o=["messageSequence","toolExecutionId","resourceKey","managerInstanceId","sessionId","checkpointId","snapshotIndex"],r=new Set({message:["messageSequence"],tool_execution:["toolExecutionId"],resource:["resourceKey"],running_session:["managerInstanceId","sessionId"],legacy_snapshot:["checkpointId","snapshotIndex"]}[e.kind]);for(const s of o){const o=e[s];(r.has(s)?null===o:null!==o)&&t.addIssue({code:n.ZodIssueCode.custom,message:`${s} must be ${r.has(s)?"non-null":"null"} for ${e.kind}`,path:[s]})}}).readonly();const C={priorItemId:n.string().trim().min(1).max(128).nullable(),text:n.string().trim().min(1).max(s),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).min(1).max(8)},w=n.object(C).strict().readonly(),b={priorItemId:n.string().trim().min(1).max(128).nullable(),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8)},E=n.object(b).strict().readonly(),$={priorItemId:n.string().trim().min(1).max(128).nullable(),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8)},N=n.object($).strict().readonly(),M=n.object({targetItemId:n.string().trim().min(1).max(128),targetCategory:n.enum(["constraint","decision","pending_work","uncertainty"]),action:n.enum(["cancel","supersede","clarify","revoke"]),reason:n.string().trim().min(1).max(i),sourceEvidenceIds:n.array(n.string().trim().min(1).max(128)).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).min(1).max(8)}).strict().readonly(),K=n.object({evidenceId:n.string().trim().min(1).max(128),disposition:n.enum(["irrelevant","uncertain"]),reason:n.string().trim().min(1).max(i)}).strict().readonly();export const compactionModelDraftSchema=n.object({startsNewGoalScope:n.boolean(),goal:w.nullable(),constraints:n.array(w).max(m),decisions:n.array(w).max(d),completedWork:n.array(w).max(p),pendingWork:n.array(w).max(l),resources:n.array(E).max(g),runningSessions:n.array(N).max(I),uncertainties:n.array(w).max(v),resolutions:n.array(M).max(256),evidenceReviews:n.array(K).max(512)}).strict().readonly();export function createEmptyCompactionModelDraft(){return compactionModelDraftSchema.parse({startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]})}const Q={id:compactionSemanticItemIdSchema,text:n.string().trim().min(1).max(s),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8),sourceQuotes:n.array(n.string().trim().min(1).max(u)).max(8).default([])},q=n.object(Q).strict().readonly(),R={id:compactionSemanticItemIdSchema,resourceKey:n.string().trim().min(1).max(s),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8)},W=n.object(R).strict().readonly(),j={id:compactionSemanticItemIdSchema,managerInstanceId:n.string().uuid(),sessionId:n.number().int().nonnegative(),provenance:n.array(compactionProvenanceRefSchema).min(1).max(8)},O=n.object(j).strict().readonly(),P=n.object({constraint:n.number().int().nonnegative().default(0),decision:n.number().int().nonnegative(),completed_work:n.number().int().nonnegative(),pending_work:n.number().int().nonnegative(),resource:n.number().int().nonnegative(),running_session:n.number().int().nonnegative(),uncertainty:n.number().int().nonnegative()}).strict().readonly(),T=Object.freeze({constraint:0,decision:0,completed_work:0,pending_work:0,resource:0,running_session:0,uncertainty:0});export const compactionSemanticStateSchema=n.object({version:n.literal(1),goal:q.nullable(),constraints:n.array(q).max(m).default([]),decisions:n.array(q).max(d),completedWork:n.array(q).max(p),pendingWork:n.array(q).max(l),resources:n.array(W).max(g),runningSessions:n.array(O).max(I),uncertainties:n.array(q).max(v),prunedItemCounts:P.default(T)}).strict().superRefine((e,t)=>{const o=new Set,r=[...null===e.goal?[]:[["goal",e.goal.id]],...e.constraints.map(e=>["constraint",e.id]),...e.decisions.map(e=>["decision",e.id]),...e.completedWork.map(e=>["completed_work",e.id]),...e.pendingWork.map(e=>["pending_work",e.id]),...e.resources.map(e=>["resource",e.id]),...e.runningSessions.map(e=>["running_session",e.id]),...e.uncertainties.map(e=>["uncertainty",e.id])];for(const[e,s]of r)s.startsWith(`semantic_${e}_`)||t.addIssue({code:n.ZodIssueCode.custom,message:`semantic item ID does not match category ${e}`}),o.has(s)&&t.addIssue({code:n.ZodIssueCode.custom,message:`duplicate semantic item ID: ${s}`}),o.add(s)}).readonly();const A=n.object({itemId:compactionSemanticItemIdSchema,category:n.enum(COMPACTION_SEMANTIC_ITEM_KINDS),text:n.string().trim().min(1).max(x),sourceQuotes:n.array(n.string().trim().min(1).max(u)).max(8)}).strict().readonly(),D=n.object({goal:n.number().int().nonnegative(),constraint:n.number().int().nonnegative(),decision:n.number().int().nonnegative(),completed_work:n.number().int().nonnegative(),pending_work:n.number().int().nonnegative(),resource:n.number().int().nonnegative(),running_session:n.number().int().nonnegative(),uncertainty:n.number().int().nonnegative()}).strict().readonly();export const compactionSemanticReminderProjectionSchema=n.object({version:n.literal(1),items:n.array(A),omittedCounts:D}).strict().readonly();export const COMPACTION_SEMANTIC_REJECTION_REASONS=["unknown_provenance","missing_required_provenance","completed_work_without_success_evidence","resource_not_observed","running_session_not_observed","unknown_resolution_target","resolution_target_category_mismatch","invalid_resolution_action","unsupported_source_quote","unknown_evidence_review"];function z(e){return e.trim().replace(/\s+/gu," ")}function G(e){switch(e.kind){case"message":return`message:${String(e.messageSequence)}`;case"tool_execution":return`tool_execution:${String(e.toolExecutionId)}`;case"resource":return`resource:${String(e.resourceKey)}`;case"running_session":return`running_session:${String(e.managerInstanceId)}:${String(e.sessionId)}`;case"legacy_snapshot":return`legacy_snapshot:${String(e.checkpointId)}:${String(e.snapshotIndex)}`}}function J(n,t,o){const r=[n,z(t),...o.map(G).sort((e,n)=>e.localeCompare(n))].join("\n"),s=e("sha256").update(r).digest("hex").slice(0,24);return compactionSemanticItemIdSchema.parse(`semantic_${n}_${s}`)}function U(n,t){return`evidence_${e("sha256").update(`${n}\n${t}`).digest("hex").slice(0,24)}`}function F(e){return compactionProvenanceRefSchema.parse({kind:e.kind,messageSequence:"message"===e.kind?e.sequence:null,toolExecutionId:"tool_execution"===e.kind?e.executionId:null,resourceKey:"resource"===e.kind?e.resourceKey:null,managerInstanceId:"running_session"===e.kind?e.managerInstanceId:null,sessionId:"running_session"===e.kind?e.sessionId:null,checkpointId:"legacy_snapshot"===e.kind?e.checkpointId:null,snapshotIndex:"legacy_snapshot"===e.kind?e.snapshotIndex:null})}export function buildCompactionSemanticEvidenceRegistry(e){const n=[];for(const t of e.messages){const e=F({kind:"message",sequence:t.sequence});n.push({evidenceId:U("message",String(t.sequence)),summary:pe(t.summary,512),provenance:e,...void 0===t.role?{}:{messageRole:t.role}})}for(const t of e.toolExecutions){const e=F({kind:"tool_execution",executionId:t.id});n.push({evidenceId:U("tool_execution",t.id),summary:pe([`${t.agentName??"agent"}/${t.toolName??"tool"}: ${t.outcome.kind}`,...void 0===t.outcome.executionState?[]:[`executionState=${t.outcome.executionState}`],...void 0===t.inputSummary?[]:[`input=${pe(t.inputSummary,160)}`],...void 0===t.resultSummary?[]:[`result=${pe(t.resultSummary,256)}`]].join("; "),512),provenance:e,toolOutcomeKind:t.outcome.kind,...void 0===t.outcome.executionState?{}:{toolCancellationExecutionState:t.outcome.executionState}})}for(const t of e.resources){const e=F({kind:"resource",resourceKey:t.key});n.push({evidenceId:U("resource",t.key),summary:pe(`${void 0===t.mode?"resource":t.mode}: ${t.key}`,512),provenance:e})}for(const t of e.runningSessions){const e=`${t.managerInstanceId}:${String(t.sessionId)}`,o=F({kind:"running_session",managerInstanceId:t.managerInstanceId,sessionId:t.sessionId});n.push({evidenceId:U("running_session",e),summary:pe(`session ${t.state??"observed"}`,512),provenance:o})}const t=new Map;for(const e of n)t.has(e.evidenceId)||t.set(e.evidenceId,e);return[...t.values()]}function V(e){return e.map(e=>({evidenceId:e.evidenceId,kind:e.provenance.kind,summary:Z(e),...void 0===e.messageRole?{}:{role:e.messageRole},...void 0===e.toolOutcomeKind?{}:{outcome:e.toolOutcomeKind},...void 0===e.toolCancellationExecutionState?{}:{executionState:e.toolCancellationExecutionState}}))}function Z(e){return pe(e.summary,256)}function L(e){if(void 0===e)return[];const n=compactionSemanticStateSchema.parse(e),t=(e,n)=>n.slice(-16).map(n=>({itemId:n.id,category:e,text:pe(n.text,256),sourceQuotes:n.sourceQuotes.map(e=>pe(e,256))}));return[...null===n.goal?[]:[{itemId:n.goal.id,category:"goal",text:pe(n.goal.text,256),sourceQuotes:n.goal.sourceQuotes.map(e=>pe(e,256))}],...t("constraint",n.constraints),...t("pending_work",n.pendingWork),...t("uncertainty",n.uncertainties),...t("decision",n.decisions),...t("completed_work",n.completedWork),...n.resources.slice(-16).map(e=>({itemId:e.id,category:"resource",text:pe(e.resourceKey,256),sourceQuotes:[pe(e.resourceKey,256)]}))]}function B(e,n,t){const o=[],r=[],s=()=>JSON.stringify({previousSemanticItems:o,evidence:r,omittedPreviousItemCount:n.length-o.length,omittedEvidenceCount:e.length-r.length}),i=(e,n)=>(e.push(n),[...s()].length<=t||(e.pop(),!1));let a=0,c=0;void 0!==n[0]&&i(o,n[0])&&(a=1),void 0!==e[0]&&i(r,e[0])&&(c=1);for(const n of e.slice(c)){if(r.length>=k)break;if(!i(r,n))break}for(const e of n.slice(a))if(!i(o,e))break;return{prompt:s(),includedEvidenceIds:r.map(e=>e.evidenceId)}}export function renderCompactionSemanticEvidenceRegistry(e,n=24e3){if(!Number.isInteger(n)||n<1024||n>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return B(V(e),[],n).prompt}export function buildCompactionSemanticModelContext(e,n,t=24e3){if(!Number.isInteger(t)||t<1024||t>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return B(V(e),L(n),t)}export function renderCompactionSemanticModelContext(e,n,t=24e3){if(!Number.isInteger(t)||t<1024||t>64e3)throw new Error("maxChars must be an integer between 1024 and 64000");return buildCompactionSemanticModelContext(e,n,t).prompt}function H(e){const n=e=>new Map(e?.map(e=>[e.id,e.text])??[]);return{goal:new Map(null==e?.goal?[]:[[e.goal.id,e.goal.text]]),constraint:n(e?.constraints),decision:n(e?.decisions),completed_work:n(e?.completedWork),pending_work:n(e?.pendingWork),resource:new Map(e?.resources.map(e=>[e.id,e.resourceKey])??[]),running_session:new Map(e?.runningSessions.map(e=>[e.id,`${e.managerInstanceId}:${String(e.sessionId)}`])??[]),uncertainty:n(e?.uncertainties)}}function X(e,n,t,o,r){const s=null===e?void 0:r.get(e);return void 0!==s&&z(s)===z(t)?compactionSemanticItemIdSchema.parse(e):J(n,t,o)}function Y(e){return 1===e.length&&"tool_execution"===e[0]?.provenance.kind&&e[0].toolOutcomeKind===t.success}function ee(e){return 1===e.length&&e.every(e=>"message"===e.provenance.kind&&"user"===e.messageRole)}function ne(e,n){return!!Y(e)&&ie(e,n)}function te(e,n){const t=e.map(e=>e.replace(/^message \d+ (?:user|assistant|system|tool): /u,"")).map(z).join("; ");return pe(void 0===n?t:`${n}: ${t}`,s)}function oe(e){return"tool_execution"===e.provenance.kind&&e.toolOutcomeKind===t.success}function re(e){return[...new Map(e.map(e=>[G(e.provenance),e.provenance])).values()]}export class CompactionSemanticCandidateError extends Error{constructor(e,n){super(e,n),this.name="CompactionSemanticCandidateError"}}function se(e){return"text"in e?JSON.stringify(["text",z(e.text)]):"resourceKey"in e?JSON.stringify(["resource",e.resourceKey]):JSON.stringify(["running_session",e.managerInstanceId,e.sessionId])}export function normalizeCompactionSemanticItems(e){const n=new Map;for(const t of e){const e=n.get(t.id);if(void 0===e){n.set(t.id,t);continue}if(se(e)!==se(t))throw new CompactionSemanticCandidateError(`conflicting semantic item ID: ${t.id}`);const o=[...new Map([...e.provenance,...t.provenance].map(e=>[G(e),e])).values()],r="sourceQuotes"in e&&"sourceQuotes"in t?[...new Set([...e.sourceQuotes,...t.sourceQuotes])]:void 0;if(o.length>8||(r?.length??0)>8)throw new CompactionSemanticCandidateError(`semantic item evidence limit exceeded: ${t.id}`);n.set(t.id,{...e,provenance:o,...void 0===r?{}:{sourceQuotes:r}})}return[...n.values()]}function ie(e,n){const t=e.map(Z);return t.length===n.length&&t.every((e,t)=>e===n[t])}export function validateCompactionModelDraft(e){const n=compactionModelDraftSchema.parse(e.draft),t=void 0===e.previousState?void 0:compactionSemanticStateSchema.parse(e.previousState),o=H(t),r=new Map([...t?.constraints.map(e=>[e.id,"constraint"])??[],...t?.decisions.map(e=>[e.id,"decision"])??[],...t?.pendingWork.map(e=>[e.id,"pending_work"])??[],...t?.uncertainties.map(e=>[e.id,"uncertainty"])??[]]),i=new Map((t?.completedWork??[]).map(e=>[e.id,e])),a=new Map;for(const n of e.evidenceRegistry){const e={...n,provenance:compactionProvenanceRefSchema.parse(n.provenance)};if(a.has(e.evidenceId))throw new Error(`Duplicate compaction evidence ID: ${e.evidenceId}`);a.set(e.evidenceId,e)}const c=void 0===e.presentedEvidenceIds?void 0:new Set(e.presentedEvidenceIds),S=e=>{if(new Set(e).size!==e.length)return;const n=[];for(const t of e){if(void 0!==c&&!c.has(t))return;const e=a.get(t);if(void 0===e)return;n.push(e)}return n},h=[],f=new Set,y=e=>{for(const n of e)f.add(n)},_=(e,n,t,r,s=!1)=>{const a=[];return t.forEach((t,c)=>{const u=r&&null!==t.priorItemId?i.get(t.priorItemId):void 0;if(void 0!==u&&z(t.text)===u.text)return void a.push(u);const d=S(t.sourceEvidenceIds);if(void 0===d)return void h.push({category:e,index:c,reason:"unknown_provenance"});if(!ie(d,t.sourceQuotes))return void h.push({category:e,index:c,reason:"unsupported_source_quote"});if(s&&!ee(d))return void h.push({category:e,index:c,reason:"missing_required_provenance"});if(r&&!ne(d,t.sourceQuotes))return void h.push({category:e,index:c,reason:"completed_work_without_success_evidence"});const m=r?te(t.sourceQuotes,"Successful Tool evidence"):te(t.sourceQuotes);y(t.sourceEvidenceIds),a.push(q.parse({text:m,provenance:re(d),sourceQuotes:[...t.sourceQuotes],id:X(t.priorItemId,n,m,re(d),o[n])}))}),a};let x=null;if(null!==n.goal){const e=S(n.goal.sourceEvidenceIds);if(void 0===e)h.push({category:"goal",index:0,reason:"unknown_provenance"});else if(ee(e))if(ie(e,n.goal.sourceQuotes)){const t=re(e);y(n.goal.sourceEvidenceIds);const r=te(n.goal.sourceQuotes);x=q.parse({text:r,provenance:t,sourceQuotes:[...n.goal.sourceQuotes],id:X(n.goal.priorItemId,"goal",r,t,o.goal)})}else h.push({category:"goal",index:0,reason:"unsupported_source_quote"});else h.push({category:"goal",index:0,reason:"missing_required_provenance"})}const k=e.harnessGoal,C=void 0===k?void 0:F({kind:"message",sequence:k.sourceSequence}),w=void 0===k?void 0:pe(k.verbatimRequest,s),b=void 0===k||void 0===C||void 0===w?null:q.parse({text:w,provenance:[C],sourceQuotes:[pe(k.verbatimRequest,u)],id:X(null,"goal",w,[C],o.goal)});if(void 0!==k&&null==t?.goal)for(const e of a.values())"message"===e.provenance.kind&&e.provenance.messageSequence===k.sourceSequence&&f.add(e.evidenceId);const E=null!=t?.goal&&n.startsNewGoalScope&&null!==x,$=E?x:t?.goal??b??x,N=[];n.resources.forEach((e,n)=>{const t=S(e.sourceEvidenceIds);if(void 0===t)return void h.push({category:"resource",index:n,reason:"unknown_provenance"});const r=t.filter(e=>"resource"===e.provenance.kind),i=r[0]?.provenance.resourceKey;if(1!==r.length||null==i)return void h.push({category:"resource",index:n,reason:"resource_not_observed"});const a=re(t);y(e.sourceEvidenceIds);const c=pe(i,s);N.push(W.parse({resourceKey:c,provenance:a,id:X(e.priorItemId,"resource",c,a,o.resource)}))});const M=new Set(N.map(e=>e.resourceKey));for(const e of a.values()){const n=e.provenance.resourceKey;"resource"!==e.provenance.kind||null===n||M.has(n)||(N.push(W.parse({resourceKey:pe(n,s),provenance:[e.provenance],id:J("resource",pe(n,s),[e.provenance])})),M.add(n))}const K=[];n.runningSessions.forEach((e,n)=>{const t=S(e.sourceEvidenceIds);if(void 0===t)return void h.push({category:"running_session",index:n,reason:"unknown_provenance"});const r=t.filter(e=>"running_session"===e.provenance.kind),s=r[0]?.provenance;if(1!==r.length||null==s?.managerInstanceId||null===s.sessionId)return void h.push({category:"running_session",index:n,reason:"running_session_not_observed"});const i=`${s.managerInstanceId}:${String(s.sessionId)}`,a=re(t);y(e.sourceEvidenceIds),K.push(O.parse({managerInstanceId:s.managerInstanceId,sessionId:s.sessionId,provenance:a,id:X(e.priorItemId,"running_session",i,a,o.running_session)}))});const Q=new Set(K.map(e=>`${e.managerInstanceId}:${String(e.sessionId)}`));for(const e of a.values()){const n=e.provenance;if("running_session"!==n.kind||null===n.managerInstanceId||null===n.sessionId)continue;const t=`${n.managerInstanceId}:${String(n.sessionId)}`;Q.has(t)||(K.push(O.parse({managerInstanceId:n.managerInstanceId,sessionId:n.sessionId,provenance:[n],id:J("running_session",t,[n])})),Q.add(t))}const R=[];n.resolutions.forEach((e,n)=>{const t=r.get(e.targetItemId);if(void 0===t)return void h.push({category:"resolution",index:n,reason:"unknown_resolution_target"});if(t!==e.targetCategory)return void h.push({category:"resolution",index:n,reason:"resolution_target_category_mismatch"});if(!("constraint"===t&&"revoke"===e.action||"decision"===t&&"supersede"===e.action||"pending_work"===t&&"cancel"===e.action||"uncertainty"===t&&"clarify"===e.action))return void h.push({category:"resolution",index:n,reason:"invalid_resolution_action"});const o=S(e.sourceEvidenceIds);if(void 0===o)return void h.push({category:"resolution",index:n,reason:"unknown_provenance"});if(!ie(o,e.sourceQuotes))return void h.push({category:"resolution",index:n,reason:"unsupported_source_quote"});if(!ee(o))return void h.push({category:"resolution",index:n,reason:"missing_required_provenance"});y(e.sourceEvidenceIds);const s=re(o);R.push({targetItemId:compactionSemanticItemIdSchema.parse(e.targetItemId),targetCategory:e.targetCategory,action:e.action,reason:z(e.reason),provenance:s})});const j=_("decision","decision",n.decisions,!1),P=_("constraint","constraint",n.constraints,!1,!0),T=_("completed_work","completed_work",n.completedWork,!0),A=_("pending_work","pending_work",n.pendingWork,!1),D=_("uncertainty","uncertainty",n.uncertainties,!1),G=[],U=(e,n)=>{if(oe(e))return;const t=pe(`${n}: ${e.summary}`,s);G.push(q.parse({id:J("uncertainty",t,[e.provenance]),text:t,provenance:[e.provenance],sourceQuotes:[pe(e.summary,u)]}))};n.evidenceReviews.forEach((e,n)=>{const t=a.get(e.evidenceId);void 0!==t?(f.add(e.evidenceId),"message"!==t.provenance.kind&&"tool_execution"!==t.provenance.kind||"irrelevant"===e.disposition&&"assistant"===t.messageRole||U(t,"uncertain"===e.disposition?"Unresolved evidence":"User or Tool evidence classified as irrelevant")):h.push({category:"evidence_review",index:n,reason:"unknown_evidence_review"})});for(const n of e.presentedEvidenceIds??[]){if(f.has(n))continue;const e=a.get(n);void 0===e||"message"!==e.provenance.kind&&"tool_execution"!==e.provenance.kind||(U(e,"Unclassified evidence"),f.add(n))}const V=ue(normalizeCompactionSemanticItems(P),m),Z=ue(normalizeCompactionSemanticItems(j),d),L=ue(normalizeCompactionSemanticItems(T),p),B=ue(normalizeCompactionSemanticItems(A),l),Y=ue(normalizeCompactionSemanticItems(N),g),se=ue(normalizeCompactionSemanticItems(K),I),ae=ue(normalizeCompactionSemanticItems([...D,...G]),v),ce=compactionSemanticStateSchema.safeParse({version:1,goal:$,constraints:V.items,decisions:Z.items,completedWork:L.items,pendingWork:B.items,resources:Y.items,runningSessions:se.items,uncertainties:ae.items,prunedItemCounts:{constraint:V.prunedCount,decision:Z.prunedCount,completed_work:L.prunedCount,pending_work:B.prunedCount,resource:Y.prunedCount,running_session:se.prunedCount,uncertainty:ae.prunedCount}});if(!ce.success)throw new CompactionSemanticCandidateError("invalid semantic candidate state",{cause:ce.error});return{state:ce.data,resolutions:R,rejections:h,coveredEvidenceIds:[...f],startsNewGoalScope:E}}export function createEmptyCompactionSemanticState(){return compactionSemanticStateSchema.parse({version:1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],prunedItemCounts:T})}export function seedCompactionSemanticConstraints(e,n){const t=void 0===e?createEmptyCompactionSemanticState():compactionSemanticStateSchema.parse(e),o=ce(n),r=de(t.constraints,o,new Set,m);return me(compactionSemanticStateSchema.parse({...t,constraints:r.items,prunedItemCounts:{...t.prunedItemCounts,constraint:t.prunedItemCounts.constraint+r.prunedCount}}))}function ae(e,n){const t=[];let o="";for(const r of e){if(o.length>0&&o.length+r.length>n){const e=o.trim();e.length>0&&t.push(e),o=r;continue}o+=r}const r=o.trim();return r.length>0&&t.push(r),t}export function seedLegacyCompactionSnapshotUncertainties(e,n){const t=compactionSemanticStateSchema.parse(e),o=n.fragments.flatMap(e=>ae(e,u));if(0===o.length)return{state:t,requiredItemIds:[],transcriptFragments:[],complete:!0};const r=o.map((e,t)=>{const o=F({kind:"legacy_snapshot",checkpointId:n.checkpointId,snapshotIndex:t}),r=pe(`Unverified legacy V1 active snapshot; confirm before acting: ${e}`,s);return q.parse({id:J("uncertainty",r,[o]),text:r,provenance:[o],sourceQuotes:[e]})}),i=de(t.uncertainties,r,new Set,v),a=me(compactionSemanticStateSchema.parse({...t,uncertainties:i.items,prunedItemCounts:{...t.prunedItemCounts,uncertainty:t.prunedItemCounts.uncertainty+i.prunedCount}})),c=new Set(a.uncertainties.map(e=>e.id)),d=r.every(e=>c.has(e.id));return{state:a,requiredItemIds:r.map(e=>e.id),transcriptFragments:d?legacyCompactionTranscriptFragmentsSchema.parse(o):legacyCompactionTranscriptFragmentsSchema.parse([]),complete:d}}function ce(e){return e.map(e=>{const n=F({kind:"message",sequence:e.sourceSequence}),t=pe(e.quote,u);return q.parse({id:J("constraint",t,[n]),text:t,provenance:[n],sourceQuotes:[t]})})}export function replaceCompactionSemanticConstraints(e,n){const t=compactionSemanticStateSchema.parse(e),o=ue(ce(n),m);return me(compactionSemanticStateSchema.parse({...t,constraints:o.items,prunedItemCounts:{...t.prunedItemCounts,constraint:t.prunedItemCounts.constraint+o.prunedCount}}))}export function replaceCompactionSemanticGoal(e,n){const t=compactionSemanticStateSchema.parse(e);if(void 0===n)return me(compactionSemanticStateSchema.parse({...t,goal:null}));const o=F({kind:"message",sequence:n.sourceSequence}),r=pe(n.verbatimRequest,s),i=pe(n.verbatimRequest,u);return me(compactionSemanticStateSchema.parse({...t,goal:q.parse({id:J("goal",r,[o]),text:r,provenance:[o],sourceQuotes:[i]})}))}function ue(e,n){const t=Math.max(0,e.length-n);return{items:0===t?[...e]:e.slice(-n),prunedCount:t}}function de(e,n,t,o){const r=new Map;for(const n of e)t.has(n.id)||r.set(n.id,n);for(const e of n)t.has(e.id)||r.set(e.id,e);return ue([...r.values()],o)}function me(e){const n=compactionSemanticStateSchema.parse(e),t=[...n.constraints],o=[...n.decisions],r=[...n.completedWork],s=[...n.pendingWork],i=[...n.resources],a=[...n.runningSessions],c=[...n.uncertainties],u={...n.prunedItemCounts},d=()=>compactionSemanticStateSchema.parse({...n,constraints:t,decisions:o,completedWork:r,pendingWork:s,resources:i,runningSessions:a,uncertainties:c,prunedItemCounts:u}),m=[{countKey:"completed_work",items:r},{countKey:"resource",items:i},{countKey:"decision",items:o},{countKey:"running_session",items:a},{countKey:"uncertainty",items:c},{countKey:"constraint",items:t},{countKey:"pending_work",items:s}];let p=!0;for(;Buffer.byteLength(JSON.stringify(d()),"utf8")>S;){const e=m.find(({items:e})=>p?e.length>1:e.length>0);if(void 0===e){if(p){p=!1;continue}throw new Error("Compaction semantic state exceeds its aggregate storage budget")}e.items.shift(),u[e.countKey]+=1}return d()}export function mergeCompactionSemanticState(e,n,t){const o=void 0===e?createEmptyCompactionSemanticState():compactionSemanticStateSchema.parse(e),r=compactionSemanticStateSchema.parse(n.state),s=new Set(n.resolutions.filter(e=>"constraint"===e.targetCategory).map(e=>e.targetItemId)),i=new Set(n.resolutions.filter(e=>"decision"===e.targetCategory).map(e=>e.targetItemId)),a=new Set(n.resolutions.filter(e=>"pending_work"===e.targetCategory).map(e=>e.targetItemId)),c=new Set(n.resolutions.filter(e=>"uncertainty"===e.targetCategory).map(e=>e.targetItemId)),u=t.startsNewGoalScope&&n.startsNewGoalScope,I=de(o.constraints,r.constraints,s,m),S=de(o.decisions,r.decisions,i,d),h=de(o.completedWork,r.completedWork,new Set,p),f=de(o.pendingWork,r.pendingWork,a,l),y=de(o.resources,r.resources,new Set,g),_=de(o.uncertainties,r.uncertainties,c,v);return me(compactionSemanticStateSchema.parse({version:1,goal:u||null!==r.goal?r.goal:o.goal,constraints:I.items,decisions:S.items,completedWork:h.items,pendingWork:f.items,resources:y.items,runningSessions:r.runningSessions.slice(-128),uncertainties:_.items,prunedItemCounts:{constraint:o.prunedItemCounts.constraint+r.prunedItemCounts.constraint+I.prunedCount,decision:o.prunedItemCounts.decision+r.prunedItemCounts.decision+S.prunedCount,completed_work:o.prunedItemCounts.completed_work+r.prunedItemCounts.completed_work+h.prunedCount,pending_work:o.prunedItemCounts.pending_work+r.prunedItemCounts.pending_work+f.prunedCount,resource:o.prunedItemCounts.resource+r.prunedItemCounts.resource+y.prunedCount,running_session:o.prunedItemCounts.running_session+r.prunedItemCounts.running_session,uncertainty:o.prunedItemCounts.uncertainty+r.prunedItemCounts.uncertainty+_.prunedCount}}))}function pe(e,n){const t=z(e),o=[...t];return o.length<=n?t:`${o.slice(0,Math.max(0,n-1)).join("")}…`}function le(e){const n=(e,n)=>n.map(n=>({itemId:n.id,category:e,text:pe(n.text,x),sourceQuotes:n.sourceQuotes.map(e=>pe(e,u))}));return[...null===e.goal?[]:[{itemId:e.goal.id,category:"goal",text:pe(e.goal.text,x),sourceQuotes:e.goal.sourceQuotes.map(e=>pe(e,u))}],...n("constraint",e.constraints),...n("pending_work",e.pendingWork),...n("uncertainty",e.uncertainties),...n("decision",e.decisions),...e.resources.map(e=>({itemId:e.id,category:"resource",text:pe(e.resourceKey,x),sourceQuotes:[pe(e.resourceKey,u)]})),...n("completed_work",e.completedWork)]}export function createCompactionSemanticReminderProjection(e,n=16e3){if(!Number.isInteger(n)||n<1024||n>32e3)throw new Error("maxChars must be an integer between 1024 and 32000");const t=compactionSemanticStateSchema.parse(e),r=o,s=le(t),i=new Map(r.map(e=>[e,s.filter(n=>n.category===e)])),a=[],c=()=>{const e=new Map(r.map(e=>[e,a.filter(n=>n.category===e).length]));return compactionSemanticReminderProjectionSchema.parse({version:1,items:a,omittedCounts:{goal:(i.get("goal")?.length??0)-(e.get("goal")??0),constraint:t.prunedItemCounts.constraint+(i.get("constraint")?.length??0)-(e.get("constraint")??0),decision:t.prunedItemCounts.decision+(i.get("decision")?.length??0)-(e.get("decision")??0),completed_work:t.prunedItemCounts.completed_work+(i.get("completed_work")?.length??0)-(e.get("completed_work")??0),pending_work:t.prunedItemCounts.pending_work+(i.get("pending_work")?.length??0)-(e.get("pending_work")??0),resource:t.prunedItemCounts.resource+(i.get("resource")?.length??0)-(e.get("resource")??0),running_session:t.prunedItemCounts.running_session+t.runningSessions.length,uncertainty:t.prunedItemCounts.uncertainty+(i.get("uncertainty")?.length??0)-(e.get("uncertainty")??0)}})},u=Math.max(0,...[...i.values()].map(e=>e.length));for(let e=0;e<u;e+=1)for(const t of r){const o=(i.get(t)??[]).at(-(e+1));void 0!==o&&(a.push(o),JSON.stringify(c()).length>n&&a.pop())}const d=c();if(JSON.stringify(d).length>n)throw new Error("Unable to create bounded semantic reminder projection");return d}export function renderCompactionSemanticSummary(e,n=12e3){if(!Number.isInteger(n)||n<1024||n>32e3)throw new Error("maxChars must be an integer between 1024 and 32000");const t=createCompactionSemanticReminderProjection(compactionSemanticStateSchema.parse(e),n),r={goal:"Goal",constraint:"Active constraints",pending_work:"Pending work",uncertainty:"Uncertainties",decision:"Decisions",resource:"Resources",completed_work:"Completed work"},s=t.omittedCounts,i=["Evidence-grounded structured compaction state:","Each semantic item is a classification; its source quote is the authoritative wording."];for(const e of o){i.push(`${r[e]}:`);const n=t.items.filter(n=>n.category===e);0===n.length?i.push("- (none retained in prompt projection)"):i.push(...n.map(e=>{const n=e.sourceQuotes.map(e=>pe(e,f)).join(" | ");return`- [${e.itemId}] interpretation=${pe(e.text,f)}; source=${n}`})),s[e]>0&&i.push(`- … ${String(s[e])} item(s) omitted; use transcript evidence`)}const a="\n… summary truncated",c=n-[...a].length,u=[];for(const e of i){if([...[...u,e].join("\n")].length>c)break;u.push(e)}const d=u.join("\n");return u.length===i.length?d:`${d}${a}`}