@roll-agent/runtime 0.19.0 → 0.20.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.
Files changed (33) hide show
  1. package/dist/engine/agent-session.d.ts +35 -4
  2. package/dist/engine/agent-session.js +1 -1
  3. package/dist/engine/compaction-checkpoint.d.ts +16 -16
  4. package/dist/engine/compaction-semantic-state.d.ts +2 -2
  5. package/dist/engine/context-window.d.ts +18 -0
  6. package/dist/engine/context-window.js +1 -1
  7. package/dist/engine/conversation-engine.d.ts +28 -4
  8. package/dist/engine/conversation-engine.js +1 -1
  9. package/dist/engine/model-catalog-default.d.ts +2 -0
  10. package/dist/engine/model-catalog-default.js +1 -0
  11. package/dist/engine/model-catalog-snapshot.d.ts +2 -0
  12. package/dist/engine/model-catalog-snapshot.js +1 -0
  13. package/dist/engine/model-catalog.d.ts +72 -0
  14. package/dist/engine/model-catalog.js +1 -0
  15. package/dist/engine/system-prompt.d.ts +2 -0
  16. package/dist/engine/system-prompt.js +1 -1
  17. package/dist/index.d.ts +15 -3
  18. package/dist/index.js +1 -1
  19. package/dist/scheduler/schedule-store.d.ts +24 -1
  20. package/dist/scheduler/schedule-store.js +1 -1
  21. package/dist/scheduler/types.d.ts +38 -0
  22. package/dist/server/protocol.d.ts +2 -2
  23. package/dist/service/runtime-service.js +1 -1
  24. package/dist/store/thread-origin.d.ts +135 -0
  25. package/dist/store/thread-origin.js +1 -0
  26. package/dist/store/thread-store.d.ts +44 -2
  27. package/dist/store/thread-store.js +1 -1
  28. package/dist/tool-bridge/build-tools.d.ts +2 -0
  29. package/dist/tool-bridge/build-tools.js +1 -1
  30. package/dist/tool-bridge/file-tools/read-file-tool.d.ts +2 -2
  31. package/dist/tool-bridge/schedule-tool.js +1 -1
  32. package/dist/tool-bridge/transcript-tool.d.ts +2 -2
  33. package/package.json +5 -5
@@ -4,6 +4,7 @@ import { type ModelMessage } from "ai";
4
4
  import type { LanguageModelV4, LanguageModelV4CallOptions, SharedV4ProviderOptions } from "@ai-sdk/provider";
5
5
  import type { UserInputResult } from "@roll-agent/protocol";
6
6
  import type { SkillLibrary, SkillSummary } from "@roll-agent/core/skills/library";
7
+ import type { JsonSchemaRefIssue } from "@roll-agent/core/tool-runtime/json-schema-refs";
7
8
  import type { ContextCompactionReason, ContextCompactionStrategy, SessionEvent, SessionTokenUsage } from "../types/events.ts";
8
9
  import type { ToolPolicy } from "../types/policy.ts";
9
10
  import { type AgentToolSource } from "../tool-bridge/build-tools.ts";
@@ -16,6 +17,7 @@ import type { CommandClassifier } from "../types/command-classification.ts";
16
17
  import { type RedactedToolExecutionRecordSummary, type ToolExecutionRecord } from "../tool-bridge/tool-execution-record.ts";
17
18
  import type { AppendMessagesOptions, CommitCompactionInput, ListToolExecutionsOptions, ListTranscriptMessagesOptions, SequencedToolExecutionRecord } from "../store/thread-store.ts";
18
19
  import { type CapabilityAgentOnboardingCatalogEntry, type CapabilityExternalDynamicContext, type CapabilityHostMode, type EffectiveCapabilityTurnContext, type EffectiveCapabilityManifest } from "./capability-manifest.ts";
20
+ import { type ThreadDerivedFrom } from "../store/thread-origin.ts";
19
21
  import type { WorkspaceInstructionsSource } from "./workspace-instructions.ts";
20
22
  import { type ArchivedTranscriptMessage, type CompactionCheckpoint } from "./compaction-checkpoint.ts";
21
23
  import { type TranscriptReader } from "../tool-bridge/transcript-tool.ts";
@@ -31,6 +33,21 @@ export interface SessionCompactionSettings {
31
33
  readonly keepRecentTurns: number;
32
34
  readonly keepRecentTokens: number;
33
35
  }
36
+ export type ToolSchemaPolicy = (issues: readonly JsonSchemaRefIssue[]) => boolean;
37
+ export interface SessionToolExclusion {
38
+ readonly toolId: string;
39
+ readonly agentName: string;
40
+ readonly toolName: string;
41
+ readonly issues: readonly JsonSchemaRefIssue[];
42
+ }
43
+ export interface SessionModelSwitch {
44
+ readonly model: LanguageModelV4;
45
+ readonly contextWindow?: number;
46
+ readonly providerOptions?: SharedV4ProviderOptions;
47
+ readonly structuredOutputProviderOptions?: SharedV4ProviderOptions;
48
+ readonly structuredOutputReasoning?: NonNullable<LanguageModelV4CallOptions["reasoning"]>;
49
+ readonly toolSchemaPolicy?: ToolSchemaPolicy;
50
+ }
34
51
  export interface AgentSessionOptions {
35
52
  readonly id: string;
36
53
  readonly model: LanguageModelV4;
@@ -45,6 +62,8 @@ export interface AgentSessionOptions {
45
62
  readonly getToolExecution?: (executionId: string) => SequencedToolExecutionRecord | undefined;
46
63
  readonly recoverUncoveredToolExecutions?: () => readonly ModelMessage[];
47
64
  readonly initialCheckpoint?: CompactionCheckpoint;
65
+ /** Persisted lineage rendered only in the model's system context, never user history. */
66
+ readonly derivedFrom?: ThreadDerivedFrom;
48
67
  readonly listTranscriptMessages?: (options?: ListTranscriptMessagesOptions) => readonly ArchivedTranscriptMessage[];
49
68
  readonly commitCompaction?: (input: CommitCompactionInput) => CompactionCheckpoint;
50
69
  readonly readCheckpointTranscript?: TranscriptReader;
@@ -56,6 +75,8 @@ export interface AgentSessionOptions {
56
75
  readonly structuredOutputReasoning?: NonNullable<LanguageModelV4CallOptions["reasoning"]>;
57
76
  /** `setProviderOptions()` 生效后触发;ConversationEngine 用它同步子 Agent Sampling。 */
58
77
  readonly onProviderOptionsChange?: (providerOptions: SharedV4ProviderOptions | undefined) => void;
78
+ readonly toolSchemaPolicy?: ToolSchemaPolicy;
79
+ readonly onToolExcluded?: (exclusion: SessionToolExclusion) => void;
59
80
  readonly debugEvents?: boolean;
60
81
  /**
61
82
  * 追加到 capability-driven 基础 prompt 之后的会话指令。
@@ -114,7 +135,7 @@ export type SessionToolExecutionRecordView = SequencedToolExecutionRecord | (Red
114
135
  });
115
136
  export declare class AgentSession {
116
137
  readonly id: string;
117
- private readonly model;
138
+ private model;
118
139
  private readonly maxSteps;
119
140
  private readonly messages;
120
141
  private readonly onPersist;
@@ -130,18 +151,19 @@ export declare class AgentSession {
130
151
  private readonly inMemoryTranscript;
131
152
  private readonly legacyV1ActiveSnapshot;
132
153
  private readonly compactionResources;
133
- private readonly contextWindow;
154
+ private contextWindow;
134
155
  private readonly compaction;
135
156
  private readonly turnTimeoutMs;
136
157
  private readonly onClose;
137
158
  private providerOptions;
138
- private readonly structuredOutputProviderOptions;
139
- private readonly structuredOutputReasoning;
159
+ private structuredOutputProviderOptions;
160
+ private structuredOutputReasoning;
140
161
  private readonly onProviderOptionsChange;
141
162
  private readonly debugEvents;
142
163
  private readonly policy;
143
164
  private systemPrompt;
144
165
  private readonly explicitSystemPrompt;
166
+ private readonly derivedFrom;
145
167
  private lastExtraPrompt;
146
168
  private readonly workspaceInstructions;
147
169
  private appliedWorkspaceInstructions;
@@ -154,6 +176,10 @@ export declare class AgentSession {
154
176
  private skillLibrary;
155
177
  private skillToolBuilt;
156
178
  private readonly toolSourceAgentNames;
179
+ private toolSchemaPolicy;
180
+ private readonly onToolExcluded;
181
+ private readonly agentToolSchemaIssues;
182
+ private excludedToolIds;
157
183
  private readonly gate;
158
184
  private readonly userInputInteractions;
159
185
  private readonly toolCoordinator;
@@ -215,6 +241,11 @@ export declare class AgentSession {
215
241
  getSessionUsage(): SessionTokenUsage;
216
242
  getSkillSummaries(): readonly SessionSkillSummary[];
217
243
  setProviderOptions(providerOptions: SharedV4ProviderOptions | undefined): void;
244
+ canSwitchModel(): boolean;
245
+ switchModel(input: SessionModelSwitch): void;
246
+ private modelTools;
247
+ private recordToolSchemaIssues;
248
+ private applyToolSchemaPolicy;
218
249
  private runAutoCompactionPasses;
219
250
  private stopOnContextPressure;
220
251
  private contextPressureTokens;
@@ -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 y,buildSessionExecToolset as T}from"../tool-bridge/session-exec-tool.js";import{SessionManager as C}from"../bash/session/session-manager.js";import{isTerminalSessionState as k}from"../bash/session/types.js";import{withCleanEnv as b}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 N,failedToolResult as O,isNormalizedToolResult as $,normalizeToolResult as j,readDisplayOutput as W,readToolOutcome as D}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as L}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as F,prepareToolExecutionRecordForPersistence as U,redactSecretText as V,toRedactedToolExecutionRecordSummary as _}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as G,ToolExecutionCoordinator as z}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as J}from"../approval/approval-gate.js";import{SessionApprovalMemory as B}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 ye}from"./system-prompt.js";import{buildCompactionCheckpointReminder as Te,buildCompactionToolState as Ce,COMPACTION_CHECKPOINT_VERSION as ke,createCompactionCheckpoint as be,createCompactionSummary as xe,createCheckpointSemanticReminderProjection as Se,findLatestRealUserGoal as Ie,resolveActiveCompactionConstraints as Me,TRANSCRIPT_MESSAGE_PROVENANCES as Ee}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as we,buildCompactionSemanticEvidenceRegistry as Pe,mergeCompactionSemanticState as Re,replaceCompactionSemanticConstraints as qe,replaceCompactionSemanticGoal as Ae,renderCompactionSemanticSummary as Ne,seedCompactionSemanticConstraints as Oe,seedLegacyCompactionSnapshotUncertainties as $e,validateCompactionModelDraft as je}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as We,repairActiveToolProtocol as De}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Le}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as Fe}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ue}from"../tool-bridge/user-input-tool.js";const Ve=6e3,_e=3e5,Ge=4,ze=2,Je=1,Be={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},He="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Ke=1024,Ye="AI_InvalidToolInputError:",Qe={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Xe(t){const s=[...t];if(s.length<=Ke)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Ke-[...o].length).join("")}${o}`}function Ze(){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 et(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function tt(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function st(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function ot(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function it(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function nt(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=rt(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function rt(e){try{return JSON.stringify(e)??void 0}catch{return}}function at(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 ct(e){return JSON.stringify(e)??String(e)}function lt(e){const t=U(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:ct(t.input.value),resultSummary:ct(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===A.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function ut(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==ee(e.content)||"assistant"===e.role&&Z(e.content)}function pt(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(at({sequence:t,provenance:Ee[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!ut(e)).length}}function dt(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 ht(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 mt(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 gt(e){return nt(W(e))}function vt(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(Ye)?A.invalidInput:A.toolFailed}function ft(){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(nt(e))}function Tt(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 Ct(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function kt(e,t){const s=Ct(e.cachedInputTokens,t.cachedInputTokens),o=Ct(e.cacheWriteTokens,t.cacheWriteTokens),i=Ct(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 bt(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function xt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function St(e,t){return void 0!==e?e:w(t)?S.timeout:S.runtime}function It(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 Mt(e,t,s){for(const o of Object.keys(t))e[o]=s}function Et(e,t,s){const o={[v]:de.sessionCommand,[y]: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 wt(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;gate=new J;userInputInteractions=new Fe;toolCoordinator=new z;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?It(e.initialMessages):[];this.messages=[...De(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?pt(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=ht(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)ut(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Ee[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName));const o=new R,i={},n=Ue({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,Mt(i,n.tools,de.userInput);const r=e.readCheckpointTranscript?Le(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};Mt(i,r,de.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};Mt(i,a,de.skill);const c=new B,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&&(Mt(i,l.readTools,de.fileRead),Mt(i,l.editTools,de.fileEdit),Mt(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):{};Mt(i,f,de.shell),e.bashSession&&(this.sessionManager=new C({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:b(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const y=e.bashSession&&this.sessionManager?T({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)}):{};Et(i,y,o);const k=e.agentInstall,x=k?p({catalog:k.catalog,install:async(e,t)=>{const s=await k.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}):{};Mt(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:{},listTools:{}};Mt(i,S.createTools,de.scheduleCreate),Mt(i,S.listTools,de.scheduleList);const I=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);Mt(i,I.tools,de.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...f,...y,...x,...S.createTools,...S.listTools,...I.tools},this.registry=I.registry,this.toolRoles=i,this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return me({tools:this.tools,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=ye(this.capabilityManifest,{...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);Mt(this.toolRoles,t.tools,de.agent),this.tools={...this.tools,...t.tools},this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);Mt(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=Ze();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:nt(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=Ze();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:nt(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${nt(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:nt(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 mt(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=St(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:nt(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 y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||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=wt(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.tools).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let v=0;const T=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.tools,prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),ft(),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=>{et(s,e),v=Q(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)et(s,t)}});let C;try{C=T()}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(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:nt(t)})}this.debug(e,"model","streamText returned",r);let k,b,x,I,M,E,R,q="",N="",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=N+t.text;if(xt(s,d.userPrompt)){N=s;break}if(N.length>0){const s=N+t.text;N="",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,N="";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:j(t.output),r=n.outcome,a=n.display,c=F({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=gt(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=vt(t.error),n=(i===A.invalidInput?L(t.error):void 0)??gt(t.error),r=O(i,n,{raw:t.error}),a=F({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=Tt(t.usage);b=bt(b,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&&N.length>0&&(q+=N,e.push({type:"text-delta",delta:N}),N=""),k=Tt(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||w(t.error)){s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t.error);break}U=yt(t.error),U&&(this.needsCompaction=!0),E=nt(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||w(e)?(s.aborted=!0,s.cancellationReason=St(s.cancellationReason,e)):(U=yt(e),U&&(this.needsCompaction=!0),E=nt(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=St(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let G;this.debug(e,"model","awaiting response messages",r);const z=this.scheduleDebug(e,"model","still awaiting response messages",r);try{G=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(z),this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(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:`${nt(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:nt(t)})}finally{this.clearDebugTimer(z)}if(this.debug(e,"model","response messages ready",r,{responseMessages:G.length}),this.isTurnAborted(s))return s.cancellationReason=St(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const J=It(G);if(this.messages.push(...J),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"),it(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),k&&(this.sessionUsage=kt(this.sessionUsage,k));const B=b??k?.inputTokens;void 0!==B&&(this.lastInputTokens=B,this.lastStepOutputTokens=x,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,B-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,...k?{totalUsage:k}:{},sessionUsage:{...this.sessionUsage},...void 0!==b?{contextInputTokens:b}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:nt(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(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:nt(t)}),e.push({type:"error",stage:"execute",message:nt(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)ut(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Ee[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=tt(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=De(It(st(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 的操作。${He}`}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}: ${nt(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:Xe(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+_e,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)}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=Tt(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?Te(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,tt(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: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=Ie(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=Oe(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&dt(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=ht(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,y=e.filter(e=>e.sequence>v),T=new Set(y.filter(e=>e.provenance===Ee[1]&&ut(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),k=Pe({messages:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:at(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(lt),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),b=we(k,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:k,modelContext:b.prompt,presentedEvidenceIds:b.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=je({draft:s??Qe,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=Re(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Me(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=qe(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=Ae(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:Ie(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?xe(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Se(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=Ce(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:nt(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:nt(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(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=De(g.messages),C=[...T.messages];if(T.status===We.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(ut))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const k=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),b=v&&k(C)<k(this.messages),x=b?C:[...this.messages],S=b?this.advanceCompactionSemanticEvidenceWatermarks(h,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(b){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=be({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,...b&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,truncatedTools:b?g.truncatedTools:0,progressed:b}),b}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:nt(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: 中断后台会话失败: ${nt(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=He;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,Be.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Be.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===Be.keepRaw,r=n?De(It(st(t))).messages:[],a=n?tt(t):ot(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}: ${nt(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=N({kind:A.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:nt(e.abortController.signal.reason)}});this.persistToolExecution(F({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} 后台清理失败: ${nt(e)}\n`)});await s(e,Ve)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Ve)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${nt(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${nt(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{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 y,buildSessionExecToolset as T}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 ye}from"./system-prompt.js";import{threadDerivedFromSchema as Te}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 yt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>D(e.output).kind===A.userRejected)??!1}function Tt(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,[y]: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:Te.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 y=e.bashSession&&this.sessionManager?T({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,y,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:{},listTools:{}};Et(i,S.createTools,de.scheduleCreate),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,...y,...x,...S.createTools,...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=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);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 y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||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 T=()=>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)),yt(),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=T()}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(!Tt(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=Tt(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=Tt(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=Tt(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,y=!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,y=e.filter(e=>e.sequence>v),T=new Set(y.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:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.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:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=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(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=Fe(g.messages),C=[...T.messages];if(T.status===De.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(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,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(k){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=xe({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed: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)}}
@@ -46,13 +46,13 @@ declare const compactionResourceSchema: z.ZodReadonly<z.ZodObject<{
46
46
  evidenceToolCallId: z.ZodString;
47
47
  evidenceExecutionId: z.ZodString;
48
48
  }, "strict", z.ZodTypeAny, {
49
- mode: "read" | "write";
50
49
  key: string;
50
+ mode: "read" | "write";
51
51
  evidenceToolCallId: string;
52
52
  evidenceExecutionId: string;
53
53
  }, {
54
- mode: "read" | "write";
55
54
  key: string;
55
+ mode: "read" | "write";
56
56
  evidenceToolCallId: string;
57
57
  evidenceExecutionId: string;
58
58
  }>>;
@@ -411,13 +411,13 @@ export declare const compactionCheckpointDraftSchema: z.ZodReadonly<z.ZodObject<
411
411
  evidenceToolCallId: z.ZodString;
412
412
  evidenceExecutionId: z.ZodString;
413
413
  }, "strict", z.ZodTypeAny, {
414
- mode: "read" | "write";
415
414
  key: string;
415
+ mode: "read" | "write";
416
416
  evidenceToolCallId: string;
417
417
  evidenceExecutionId: string;
418
418
  }, {
419
- mode: "read" | "write";
420
419
  key: string;
420
+ mode: "read" | "write";
421
421
  evidenceToolCallId: string;
422
422
  evidenceExecutionId: string;
423
423
  }>>, "many">;
@@ -677,8 +677,8 @@ export declare const compactionCheckpointDraftSchema: z.ZodReadonly<z.ZodObject<
677
677
  systemPromptSha256?: string | undefined;
678
678
  }>;
679
679
  resources: Readonly<{
680
- mode: "read" | "write";
681
680
  key: string;
681
+ mode: "read" | "write";
682
682
  evidenceToolCallId: string;
683
683
  evidenceExecutionId: string;
684
684
  }>[];
@@ -755,8 +755,8 @@ export declare const compactionCheckpointDraftSchema: z.ZodReadonly<z.ZodObject<
755
755
  systemPromptSha256?: string | undefined;
756
756
  }>;
757
757
  resources: Readonly<{
758
- mode: "read" | "write";
759
758
  key: string;
759
+ mode: "read" | "write";
760
760
  evidenceToolCallId: string;
761
761
  evidenceExecutionId: string;
762
762
  }>[];
@@ -912,13 +912,13 @@ export declare const compactionCheckpointV1Schema: z.ZodReadonly<z.ZodObject<{
912
912
  evidenceToolCallId: z.ZodString;
913
913
  evidenceExecutionId: z.ZodString;
914
914
  }, "strict", z.ZodTypeAny, {
915
- mode: "read" | "write";
916
915
  key: string;
916
+ mode: "read" | "write";
917
917
  evidenceToolCallId: string;
918
918
  evidenceExecutionId: string;
919
919
  }, {
920
- mode: "read" | "write";
921
920
  key: string;
921
+ mode: "read" | "write";
922
922
  evidenceToolCallId: string;
923
923
  evidenceExecutionId: string;
924
924
  }>>, "many">;
@@ -1182,8 +1182,8 @@ export declare const compactionCheckpointV1Schema: z.ZodReadonly<z.ZodObject<{
1182
1182
  systemPromptSha256?: string | undefined;
1183
1183
  }>;
1184
1184
  resources: Readonly<{
1185
- mode: "read" | "write";
1186
1185
  key: string;
1186
+ mode: "read" | "write";
1187
1187
  evidenceToolCallId: string;
1188
1188
  evidenceExecutionId: string;
1189
1189
  }>[];
@@ -1276,8 +1276,8 @@ export declare const compactionCheckpointV1Schema: z.ZodReadonly<z.ZodObject<{
1276
1276
  systemPromptSha256?: string | undefined;
1277
1277
  }>;
1278
1278
  resources: Readonly<{
1279
- mode: "read" | "write";
1280
1279
  key: string;
1280
+ mode: "read" | "write";
1281
1281
  evidenceToolCallId: string;
1282
1282
  evidenceExecutionId: string;
1283
1283
  }>[];
@@ -2632,13 +2632,13 @@ export declare const compactionCheckpointV2Schema: z.ZodReadonly<z.ZodEffects<z.
2632
2632
  evidenceToolCallId: z.ZodString;
2633
2633
  evidenceExecutionId: z.ZodString;
2634
2634
  }, "strict", z.ZodTypeAny, {
2635
- mode: "read" | "write";
2636
2635
  key: string;
2636
+ mode: "read" | "write";
2637
2637
  evidenceToolCallId: string;
2638
2638
  evidenceExecutionId: string;
2639
2639
  }, {
2640
- mode: "read" | "write";
2641
2640
  key: string;
2641
+ mode: "read" | "write";
2642
2642
  evidenceToolCallId: string;
2643
2643
  evidenceExecutionId: string;
2644
2644
  }>>, "many">;
@@ -2902,8 +2902,8 @@ export declare const compactionCheckpointV2Schema: z.ZodReadonly<z.ZodEffects<z.
2902
2902
  systemPromptSha256?: string | undefined;
2903
2903
  }>;
2904
2904
  resources: Readonly<{
2905
- mode: "read" | "write";
2906
2905
  key: string;
2906
+ mode: "read" | "write";
2907
2907
  evidenceToolCallId: string;
2908
2908
  evidenceExecutionId: string;
2909
2909
  }>[];
@@ -3131,8 +3131,8 @@ export declare const compactionCheckpointV2Schema: z.ZodReadonly<z.ZodEffects<z.
3131
3131
  systemPromptSha256?: string | undefined;
3132
3132
  }>;
3133
3133
  resources: Readonly<{
3134
- mode: "read" | "write";
3135
3134
  key: string;
3135
+ mode: "read" | "write";
3136
3136
  evidenceToolCallId: string;
3137
3137
  evidenceExecutionId: string;
3138
3138
  }>[];
@@ -3360,8 +3360,8 @@ export declare const compactionCheckpointV2Schema: z.ZodReadonly<z.ZodEffects<z.
3360
3360
  systemPromptSha256?: string | undefined;
3361
3361
  }>;
3362
3362
  resources: Readonly<{
3363
- mode: "read" | "write";
3364
3363
  key: string;
3364
+ mode: "read" | "write";
3365
3365
  evidenceToolCallId: string;
3366
3366
  evidenceExecutionId: string;
3367
3367
  }>[];
@@ -3589,8 +3589,8 @@ export declare const compactionCheckpointV2Schema: z.ZodReadonly<z.ZodEffects<z.
3589
3589
  systemPromptSha256?: string | undefined;
3590
3590
  }>;
3591
3591
  resources: Readonly<{
3592
- mode: "read" | "write";
3593
3592
  key: string;
3593
+ mode: "read" | "write";
3594
3594
  evidenceToolCallId: string;
3595
3595
  evidenceExecutionId: string;
3596
3596
  }>[];
@@ -1565,13 +1565,13 @@ export declare const compactionSemanticReminderProjectionSchema: z.ZodReadonly<z
1565
1565
  uncertainty: number;
1566
1566
  }>>;
1567
1567
  }, "strict", z.ZodTypeAny, {
1568
- version: 1;
1569
1568
  items: Readonly<{
1570
1569
  text: string;
1571
1570
  sourceQuotes: string[];
1572
1571
  itemId: string & z.BRAND<"CompactionSemanticItemId">;
1573
1572
  category: "resource" | "decision" | "running_session" | "goal" | "constraint" | "completed_work" | "pending_work" | "uncertainty";
1574
1573
  }>[];
1574
+ version: 1;
1575
1575
  omittedCounts: Readonly<{
1576
1576
  resource: number;
1577
1577
  decision: number;
@@ -1583,13 +1583,13 @@ export declare const compactionSemanticReminderProjectionSchema: z.ZodReadonly<z
1583
1583
  uncertainty: number;
1584
1584
  }>;
1585
1585
  }, {
1586
- version: 1;
1587
1586
  items: Readonly<{
1588
1587
  text: string;
1589
1588
  sourceQuotes: string[];
1590
1589
  itemId: string;
1591
1590
  category: "resource" | "decision" | "running_session" | "goal" | "constraint" | "completed_work" | "pending_work" | "uncertainty";
1592
1591
  }>[];
1592
+ version: 1;
1593
1593
  omittedCounts: Readonly<{
1594
1594
  resource: number;
1595
1595
  decision: number;
@@ -1,2 +1,20 @@
1
+ import type { ModelCatalog } from "./model-catalog.ts";
1
2
  export declare function lookupContextWindow(modelName: string): number | undefined;
2
3
  export declare function resolveContextWindow(modelName: string, override?: number): number | undefined;
4
+ export declare const CONTEXT_WINDOW_SOURCES: {
5
+ readonly override: "override";
6
+ readonly catalog: "catalog";
7
+ readonly rule: "rule";
8
+ };
9
+ export type ContextWindowSource = (typeof CONTEXT_WINDOW_SOURCES)[keyof typeof CONTEXT_WINDOW_SOURCES];
10
+ export interface ContextWindowResolution {
11
+ readonly window: number;
12
+ readonly source: ContextWindowSource;
13
+ }
14
+ export interface ResolveModelContextWindowInput {
15
+ readonly provider: string;
16
+ readonly model: string;
17
+ readonly override?: number;
18
+ readonly catalog?: ModelCatalog;
19
+ }
20
+ export declare function resolveModelContextWindow(input: ResolveModelContextWindowInput): ContextWindowResolution | undefined;