@roll-agent/runtime 0.25.2 → 0.27.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 (56) hide show
  1. package/dist/engine/agent-session.d.ts +51 -14
  2. package/dist/engine/agent-session.js +1 -1
  3. package/dist/engine/capability-manifest.d.ts +1 -0
  4. package/dist/engine/capability-manifest.js +1 -1
  5. package/dist/engine/compaction-checkpoint.d.ts +619 -174
  6. package/dist/engine/compaction-checkpoint.js +1 -1
  7. package/dist/engine/compaction-media.d.ts +7 -0
  8. package/dist/engine/compaction-media.js +1 -0
  9. package/dist/engine/compaction-semantic-state.d.ts +707 -457
  10. package/dist/engine/compaction-semantic-state.js +1 -1
  11. package/dist/engine/compactor.d.ts +6 -24
  12. package/dist/engine/compactor.js +1 -1
  13. package/dist/engine/conversation-engine.d.ts +2 -0
  14. package/dist/engine/conversation-engine.js +1 -1
  15. package/dist/engine/model-recovery.d.ts +21 -0
  16. package/dist/engine/model-recovery.js +1 -0
  17. package/dist/engine/model-request.d.ts +22 -0
  18. package/dist/engine/model-request.js +1 -0
  19. package/dist/engine/request-budget.d.ts +143 -0
  20. package/dist/engine/request-budget.js +1 -0
  21. package/dist/engine/system-prompt.js +1 -1
  22. package/dist/engine/tool-input-activity.d.ts +22 -0
  23. package/dist/engine/tool-input-activity.js +1 -0
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.js +1 -1
  26. package/dist/server/runtime-protocol-adapter.js +1 -1
  27. package/dist/server/runtime-server.js +1 -1
  28. package/dist/service/runtime-service.d.ts +4 -3
  29. package/dist/service/runtime-service.js +1 -1
  30. package/dist/store/semantic-ledger.d.ts +120 -0
  31. package/dist/store/semantic-ledger.js +1 -0
  32. package/dist/store/thread-store.d.ts +54 -19
  33. package/dist/store/thread-store.js +1 -1
  34. package/dist/store/turn-input.d.ts +161 -0
  35. package/dist/store/turn-input.js +1 -0
  36. package/dist/tool-bridge/build-tools.d.ts +2 -0
  37. package/dist/tool-bridge/build-tools.js +1 -1
  38. package/dist/tool-bridge/file-tools/edit-file-tool.d.ts +2 -2
  39. package/dist/tool-bridge/file-tools/edit-file-tool.js +1 -1
  40. package/dist/tool-bridge/file-tools/file-change-result.d.ts +2 -0
  41. package/dist/tool-bridge/file-tools/file-change-result.js +1 -1
  42. package/dist/tool-bridge/file-tools/file-io.d.ts +2 -0
  43. package/dist/tool-bridge/file-tools/file-io.js +1 -1
  44. package/dist/tool-bridge/file-tools/file-write-state.d.ts +31 -0
  45. package/dist/tool-bridge/file-tools/file-write-state.js +1 -0
  46. package/dist/tool-bridge/file-tools/text-diff.d.ts +7 -15
  47. package/dist/tool-bridge/file-tools/text-diff.js +1 -1
  48. package/dist/tool-bridge/file-tools/write-file-tool.d.ts +2 -1
  49. package/dist/tool-bridge/file-tools/write-file-tool.js +1 -1
  50. package/dist/tool-bridge/invalid-schedule-retry.d.ts +1 -1
  51. package/dist/tool-bridge/invalid-schedule-retry.js +1 -1
  52. package/dist/tool-bridge/session-exec-tool.d.ts +2 -2
  53. package/dist/tool-bridge/transcript-tool.d.ts +29 -4
  54. package/dist/tool-bridge/transcript-tool.js +1 -1
  55. package/dist/types/events.d.ts +21 -1
  56. package/package.json +5 -4
@@ -1,6 +1,8 @@
1
1
  import type { ChildProcess } from "node:child_process";
2
+ import { type ModelTurnRecovery } from "./model-recovery.ts";
3
+ import type { ContextWindowSource } from "./context-window.ts";
2
4
  import { type SessionSendInput } from "./session-attachments.ts";
3
- import { type ModelMessage } from "ai";
5
+ import { type ModelMessage, type UserModelMessage } from "ai";
4
6
  import type { LanguageModelV4, LanguageModelV4CallOptions, SharedV4ProviderOptions } from "@ai-sdk/provider";
5
7
  import type { UserInputResult } from "@roll-agent/protocol";
6
8
  import type { SkillLibrary, SkillSummary } from "@roll-agent/core/skills/library";
@@ -16,6 +18,8 @@ import type { ShellProfile } from "../bash/profile.ts";
16
18
  import type { CommandClassifier } from "../types/command-classification.ts";
17
19
  import { type RedactedToolExecutionRecordSummary, type ToolExecutionRecord } from "../tool-bridge/tool-execution-record.ts";
18
20
  import type { AppendMessagesOptions, CommitCompactionInput, ListToolExecutionsOptions, ListTranscriptMessagesOptions, SequencedToolExecutionRecord } from "../store/thread-store.ts";
21
+ import { type AcceptedTurnInput, type TurnInputSkillCheckpoint } from "../store/turn-input.ts";
22
+ import type { ExplicitSkillCheckpointV1 } from "./explicit-skill-context.ts";
19
23
  import { type CapabilityAgentOnboardingCatalogEntry, type CapabilityExternalDynamicContext, type CapabilityHostMode, type EffectiveCapabilityTurnContext, type EffectiveCapabilityManifest } from "./capability-manifest.ts";
20
24
  import { type ThreadDerivedFrom } from "../store/thread-origin.ts";
21
25
  import type { WorkspaceInstructionsSource } from "./workspace-instructions.ts";
@@ -42,7 +46,9 @@ export interface SessionToolExclusion {
42
46
  }
43
47
  export interface SessionModelSwitch {
44
48
  readonly model: LanguageModelV4;
49
+ readonly modelRecovery?: ModelTurnRecovery;
45
50
  readonly contextWindow?: number;
51
+ readonly contextWindowSource?: ContextWindowSource;
46
52
  readonly providerOptions?: SharedV4ProviderOptions;
47
53
  readonly structuredOutputProviderOptions?: SharedV4ProviderOptions;
48
54
  readonly structuredOutputReasoning?: NonNullable<LanguageModelV4CallOptions["reasoning"]>;
@@ -51,11 +57,15 @@ export interface SessionModelSwitch {
51
57
  export interface AgentSessionOptions {
52
58
  readonly id: string;
53
59
  readonly model: LanguageModelV4;
60
+ readonly modelRecovery?: ModelTurnRecovery;
54
61
  readonly sources: readonly AgentToolSource[];
55
62
  readonly maxSteps: number;
56
63
  readonly policy?: ToolPolicy;
57
64
  readonly initialMessages?: readonly ModelMessage[];
58
65
  readonly onPersist?: (messages: readonly ModelMessage[], options?: AppendMessagesOptions) => void;
66
+ readonly onAcceptInput?: (inputId: string, message: UserModelMessage) => AcceptedTurnInput;
67
+ readonly onRecordInputSkillCheckpoint?: (inputId: string, checkpoint: ExplicitSkillCheckpointV1) => void;
68
+ readonly getInputSkillCheckpoint?: (transcriptSequence: number) => TurnInputSkillCheckpoint | undefined;
59
69
  readonly onReplace?: (messages: readonly ModelMessage[]) => void;
60
70
  readonly onToolExecution?: (record: ToolExecutionRecord) => void;
61
71
  readonly listToolExecutions?: (options?: ListToolExecutionsOptions) => readonly SequencedToolExecutionRecord[];
@@ -68,6 +78,7 @@ export interface AgentSessionOptions {
68
78
  readonly commitCompaction?: (input: CommitCompactionInput) => CompactionCheckpoint;
69
79
  readonly readCheckpointTranscript?: TranscriptReader;
70
80
  readonly contextWindow?: number;
81
+ readonly contextWindowSource?: ContextWindowSource;
71
82
  readonly compaction?: SessionCompactionSettings;
72
83
  readonly turnTimeoutMs?: number;
73
84
  readonly providerOptions?: SharedV4ProviderOptions;
@@ -136,6 +147,7 @@ export type SessionToolExecutionRecordView = SequencedToolExecutionRecord | (Red
136
147
  export declare class AgentSession {
137
148
  readonly id: string;
138
149
  private model;
150
+ private modelRecovery;
139
151
  private readonly maxSteps;
140
152
  private readonly messages;
141
153
  private readonly onPersist;
@@ -149,8 +161,6 @@ export declare class AgentSession {
149
161
  private readonly inMemoryToolExecutions;
150
162
  private readonly uncoveredToolExecutions;
151
163
  private readonly inMemoryTranscript;
152
- private readonly legacyV1ActiveSnapshot;
153
- private readonly compactionResources;
154
164
  private contextWindow;
155
165
  private readonly compaction;
156
166
  private readonly turnTimeoutMs;
@@ -182,6 +192,10 @@ export declare class AgentSession {
182
192
  private excludedToolIds;
183
193
  private readonly gate;
184
194
  private readonly userInputInteractions;
195
+ private readonly onAcceptInput;
196
+ private readonly onRecordInputSkillCheckpoint;
197
+ private readonly getInputSkillCheckpoint;
198
+ private readonly inputSkillCheckpoints;
185
199
  private readonly toolCoordinator;
186
200
  private tools;
187
201
  private readonly registry;
@@ -203,7 +217,8 @@ export declare class AgentSession {
203
217
  private lastInputTokens;
204
218
  private measuredProjectedTokens;
205
219
  private promptOverhead;
206
- private needsCompaction;
220
+ private requestBudgets;
221
+ private contextWindowSource;
207
222
  constructor(options: AgentSessionOptions);
208
223
  private compileCapabilityManifest;
209
224
  private compileSystemPrompt;
@@ -228,8 +243,6 @@ export declare class AgentSession {
228
243
  private failedTurnDisplayMessage;
229
244
  private appendInterruptedTurnMessages;
230
245
  private persistToolExecution;
231
- private rememberCompactionResources;
232
- private retainCompactionResource;
233
246
  private interactionDeadlineMs;
234
247
  private requestApproval;
235
248
  approve(approvalId: string, scope?: "once" | "session"): boolean;
@@ -240,6 +253,36 @@ export declare class AgentSession {
240
253
  getCapabilityManifest(): EffectiveCapabilityManifest;
241
254
  getCapabilityTurnContext(): EffectiveCapabilityTurnContext | undefined;
242
255
  getContextWindow(): number | undefined;
256
+ /** Process-local numeric estimates; not durable diagnostics or a public Runtime wire event. */
257
+ getRequestBudgetState(): {
258
+ last: Readonly<{
259
+ model: string;
260
+ provider: string;
261
+ accountingVersion: 1;
262
+ estimated: true;
263
+ windowSource: "unknown" | "override" | "catalog" | "rule";
264
+ fingerprint: string;
265
+ shapeFingerprint: string;
266
+ systemTokens: number;
267
+ messageTokens: number;
268
+ toolTokens: number;
269
+ optionTokens: number;
270
+ rawInputEstimate: number;
271
+ calibratedInputEstimate: number;
272
+ calibrationResidual: number;
273
+ measurementMatched: boolean;
274
+ opaqueOrMultimodal: boolean;
275
+ outputReserve: number;
276
+ errorReserve: number;
277
+ window?: number | undefined;
278
+ latestMeasuredInput?: number | undefined;
279
+ availableInputCeiling?: number | undefined;
280
+ maintenanceTarget?: number | undefined;
281
+ }> | undefined;
282
+ comparison: import("./request-budget.ts").RequestBudgetComparison | undefined;
283
+ preparedAttempts: number;
284
+ providerCalls: number;
285
+ };
243
286
  getSessionUsage(): SessionTokenUsage;
244
287
  getSkillSummaries(): readonly SessionSkillSummary[];
245
288
  setProviderOptions(providerOptions: SharedV4ProviderOptions | undefined): void;
@@ -248,7 +291,6 @@ export declare class AgentSession {
248
291
  private modelTools;
249
292
  private recordToolSchemaIssues;
250
293
  private applyToolSchemaPolicy;
251
- private runAutoCompactionPasses;
252
294
  private stopOnContextPressure;
253
295
  private contextPressureTokens;
254
296
  private observationResultId;
@@ -258,16 +300,9 @@ export declare class AgentSession {
258
300
  private currentCheckpointReminder;
259
301
  private persistPausedTurnCancellation;
260
302
  private compactionTargetTokens;
261
- private shouldAutoCompact;
262
303
  private listCompactionTranscriptEvidence;
263
304
  private listCompactionToolEvidence;
264
- private latestExplicitSkillNames;
265
- private currentCompactionRunningWork;
266
- private captureCompactionEvidence;
267
- private buildCompactionDraft;
268
305
  private runCompactionTurn;
269
- private advanceCompactionSemanticEvidenceWatermarks;
270
- private countContiguousPresentedMessageEvidence;
271
306
  private runCompaction;
272
307
  private recoverFromContextError;
273
308
  private isTurnAborted;
@@ -285,6 +320,8 @@ export declare class AgentSession {
285
320
  private persistCancelledTurn;
286
321
  private cancellationRecordMessages;
287
322
  private persistPendingToolCancellationsOrReport;
323
+ /** Only called after the failed stream settles and every remaining occurrence is unstarted. */
324
+ private persistRecoveryCancellations;
288
325
  private persistPendingToolCancellations;
289
326
  cancel(): boolean;
290
327
  close(): Promise<void>;
@@ -1 +1 @@
1
- import{describeAppOutput as e}from"@roll-agent/protocol";import{createHash as t,randomUUID as s}from"node:crypto";import{waitForPromiseSettlement as o}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as i}from"./relocate-tool-images.js";import{buildUserMessageContent as n,normalizeSessionSendInput as r,redactBinaryPartsForEvidence as a}from"./session-attachments.js";import{stepCountIs as c,streamText as l,InvalidToolInputError as u}from"ai";import{buildAgentToolset as d}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as h}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as m}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as g}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as v}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as f}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as T,EXEC_LIST_NAME as y,EXEC_POLL_NAME as b,buildSessionExecToolset as C}from"../tool-bridge/session-exec-tool.js";import{SessionManager as k}from"../bash/session/session-manager.js";import{isTerminalSessionState as x}from"../bash/session/types.js";import{withCleanEnv as I}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as S,SESSION_CANCELLATION_REASONS as M,TURN_TIMEOUT_ABORT_REASON as E,USER_CANCELLATION_ABORT_REASON as w,createTurnCancellationMessage as R,isTurnTimeoutAbortReason as P,stripTurnCancellationMetadata as O}from"../types/cancellation.js";import{ToolRegistry as q}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as A,TOOL_OUTCOME_KINDS as N,createToolResult as j,failedToolResult as $,isNormalizedToolResult as W,normalizeToolResult as D,readDisplayOutput as F,readToolOutcome as L}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as U}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as B,prepareToolExecutionRecordForPersistence as V,redactSecretText as z,toRedactedToolExecutionRecordSummary as _}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as G,ToolExecutionCoordinator as J}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as H}from"../approval/approval-gate.js";import{SessionApprovalMemory as K}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as Y,compactMessages as Q,CompactionDraftFallbackError as X,estimateMessagesTokens as Z,estimateTextTokens as ee,isCompactionSummaryAcknowledgement as te,readCompactionSummaryPayload as se}from"./compactor.js";import{AsyncEventQueue as oe}from"./event-queue.js";import{applyExplicitSkillContext as ie,attachExplicitSkillCheckpoint as ne,prepareExplicitSkillContext as re,readExplicitSkillCheckpoint as ae,stripExplicitSkillCheckpoints as ce}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as le,createToolLedgerGapRecoveryMessage as ue,materializeCancelledTurnRecoveryMessages as de,stripCancelledTurnRecoveryMessages as pe}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as he,CAPABILITY_TOOL_ROLES as me,buildEffectiveCapabilityTurnContext as ge,buildEffectiveCapabilityManifest as ve,findCapabilityToolId as fe,isProcessBoundHostMode as Te}from"./capability-manifest.js";import{buildCapabilityTurnReminder as ye,buildChatSystemPromptFromManifest as be}from"./system-prompt.js";import{threadDerivedFromSchema as Ce}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as ke,buildCompactionToolState as xe,COMPACTION_CHECKPOINT_VERSION as Ie,createCompactionCheckpoint as Se,createCompactionSummary as Me,createCheckpointSemanticReminderProjection as Ee,findLatestRealUserGoal as we,resolveActiveCompactionConstraints as Re,TRANSCRIPT_MESSAGE_PROVENANCES as Pe}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Oe,buildCompactionSemanticEvidenceRegistry as qe,CompactionSemanticCandidateError as Ae,mergeCompactionSemanticState as Ne,replaceCompactionSemanticConstraints as je,replaceCompactionSemanticGoal as $e,renderCompactionSemanticSummary as We,seedCompactionSemanticConstraints as De,seedLegacyCompactionSnapshotUncertainties as Fe,validateCompactionModelDraft as Le}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Ue,repairActiveToolProtocol as Be}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Ve}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as ze}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as _e}from"./observation-readback.js";import{canonicalObservationOutput as Ge,projectObservationMessages as Je,restoreCanonicalObservationOutputs as He}from"./observation-projection.js";import{UserInputInteractionManager as Ke}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ye}from"../tool-bridge/user-input-tool.js";const Qe=6e3,Xe=3e5,Ze=4,et=2,tt=1,st={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},ot="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",it=1024,nt="AI_InvalidToolInputError:",rt={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function at(e){const s=[...e];if(s.length<=it)return e;const o=`…#${t("sha256").update(e).digest("hex").slice(0,16)}`;return`${s.slice(0,it-[...o].length).join("")}${o}`}function ct(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalObservationOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function lt(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=He(t.response.messages,e.canonicalObservationOutputs);return e.completedStepResponses.set(s,i),i}function ut(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??He(t.response.messages,e.canonicalObservationOutputs))}function dt(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function pt(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function ht(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function mt(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function gt(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=vt(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function vt(e){try{return JSON.stringify(e)??void 0}catch{return}}function ft(e){const t=ae(e.message),[s]=ce([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(a(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function Tt(e){return JSON.stringify(e)??String(e)}function yt(e){const t=V(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:Tt(t.input.value),resultSummary:Tt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===N.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function bt(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==se(e.content)||"assistant"===e.role&&te(e.content)}function Ct(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=se(e.content);if(void 0!==t)return 0===t.length?[]:[z(t)]}return"assistant"===e.role&&te(e.content)?[]:[z(ft({sequence:t,provenance:Pe[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!bt(e)).length}}function kt(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 xt(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===Ie?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function It(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 St(e){return gt(F(e))}function Mt(e){return u.isInstance(e)||"string"==typeof e&&e.startsWith(nt)?N.invalidInput:N.toolFailed}function Et(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>L(e.output).kind===N.userRejected)??!1}function wt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(gt(e))}function Rt(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 Pt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function Ot(e,t){const s=Pt(e.cachedInputTokens,t.cachedInputTokens),o=Pt(e.cacheWriteTokens,t.cacheWriteTokens),i=Pt(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 qt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function At(e,t){return void 0!==e?e:P(t)?M.timeout:M.runtime}function Nt(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 jt(e,t,s){for(const o of Object.keys(t))e[o]=s}function $t(e,t,s){const o={[T]:me.sessionCommand,[b]:me.sessionPoll,[y]:me.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function 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;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new H;userInputInteractions=new Ke;toolCoordinator=new J;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=s();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?Nt(e.initialMessages):[];this.messages=[...Be(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?Ct(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=xt(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)bt(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Pe[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.derivedFrom=void 0===e.derivedFrom?void 0:Ce.parse(e.derivedFrom),this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName)),this.toolSchemaPolicy=e.toolSchemaPolicy,this.onToolExcluded=e.onToolExcluded;const o=new q,i={},n=Ye({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,jt(i,n.tools,me.userInput);const r=e.readCheckpointTranscript?Ve(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};jt(i,r,me.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};jt(i,a,me.skill);const c=new K,l=e.fileTools?v(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(jt(i,l.readTools,me.fileRead),jt(i,l.editTools,me.fileEdit),jt(i,l.verifyTools,me.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},h=e.bashClassifier?{classifier:e.bashClassifier}:{},g=e.bash?f(e.bash,o,u,h):{};jt(i,g,me.shell),e.bashSession&&(this.sessionManager=new k({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:I(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const T=e.bashSession&&this.sessionManager?C({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...h,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};$t(i,T,o);const y=e.agentInstall,b=y?p({catalog:y.catalog,install:async(e,t)=>{const s=await y.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};jt(i,b,me.agentInstall);const x=e.schedules?m(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};jt(i,x.createTools,me.scheduleCreate),jt(i,x.extendTools,me.scheduleExtend),jt(i,x.listTools,me.scheduleList);const S=d(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);jt(i,S.tools,me.agent);const M=S.observationRetentionByToolId.size>0?ze(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(M)[0],jt(i,M,me.observationRead),this.tools={...r,...M,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...g,...T,...b,...x.createTools,...x.extendTools,...x.listTools,...S.tools},this.registry=S.registry;for(const[e,t]of S.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(S.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return ve({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??he.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=be(this.capabilityManifest,{...void 0!==this.derivedFrom?{derivedFrom:this.derivedFrom}:{},...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,h(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=d([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);jt(this.toolRoles,t.tools,me.agent),this.tools={...this.tools,...t.tools};for(const[e,s]of t.observationRetentionByToolId)this.observationRetentionByToolId.set(e,s);if(void 0===this.observationRecallToolId&&this.observationRetentionByToolId.size>0){const e=ze(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],jt(this.toolRoles,e,me.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);jt(this.toolRoles,e,me.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=r(e),s=new oe;this.emit=e=>s.push(e);const o=ct();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:gt(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new oe;this.emit=e=>t.push(e);const s=ct();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:gt(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(t,o,r){const a=Date.now();let u,d;const p=n(r.text,r.attachments);try{this.debug(t,"turn","start",a,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...r.attachments.length>0?{attachments:r.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void t.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${gt(e)}`})}try{await this.runAutoCompactionPasses(t,o,a,p)}catch(e){return void t.push({type:"error",stage:"plan",message:gt(e)})}if(o.aborted||o.abortController.signal.aborted)return u=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(t,o,u,a);t.push({type:"message-start",messageId:s()}),void 0!==this.turnTimeoutMs&&(o.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),d=setTimeout(()=>{o.abortController.signal.aborted||(this.captureCancellationActivity(o),o.aborted=!0,o.cancellationReason=M.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),o.abortController.abort(E))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let n=0;const h=re({rawInput:r.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),m={role:"user",content:p},v=h.skillNames.length>0?ne(m,h):m;let f={};try{f=await It(this.resolveDynamicCapabilityContext?.(o.abortController.signal)??{},o.abortController.signal)??{}}catch(e){if(this.isTurnAborted(o))return u=this.messages.length,this.messages.push(v),o.cancellationReason=At(o.cancellationReason,o.abortController.signal.reason??e),void this.persistCancelledTurn(t,o,u,a);this.debug(t,"turn","dynamic capability context unavailable",a,{message:gt(e)})}const T=ge(this.capabilityManifest,{explicitSkillNames:h.skillNames,...f.ruleIds?{ruleIds:f.ruleIds}:{},...f.vcs?{vcs:f.vcs}:{},...f.origin?{origin:f.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=T;const y=ye(T);let b=!1;for(;;){u=this.messages.length,o.pausedForContextPressure=!1,b||this.messages.push(v);const r=fe(this.capabilityManifest,me.transcriptRead),d=this.currentCheckpointReminder(r),p=void 0===d?0:ee(d),m=ce(O(de(this.messages))),f=Wt(h.skillNames.length>0?ie(m,h):m,d?`${y}\n\n${d}`:y);this.debug(t,"model","calling streamText",a,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:n,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let T,C=0;const k=[],x=g(),I=()=>l({model:this.model,system:this.systemPrompt,messages:f,tools:this.modelTools(),prepareStep:()=>(C=Z(this.projectModelMessages([...this.messages,...k])),{messages:i(this.projectModelMessages([...f,...k]))}),stopWhen:[c(Math.max(1,this.maxSteps-o.completedStepCount)),Et(),x.stop,this.stopOnContextPressure(o,()=>C)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(o,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:o.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{k.push(...lt(o,e))},onAbort:({steps:e})=>{for(const t of e)lt(o,t)}});let S;try{S=I()}catch(e){if(this.isTurnAborted(o)||P(e))return o.aborted=!0,o.cancellationReason=At(o.cancellationReason,e),void this.persistCancelledTurn(t,o,u,a);if(!wt(e))throw e;this.needsCompaction=!0,this.messages.splice(u);const s=n<1,i=!!s&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(i&&s){n+=1;continue}return this.persistContextFailure(t,o,v,!1,a),void t.push({type:"error",stage:"execute",message:gt(e)})}this.debug(t,"model","streamText returned",a);let E,w,R,q,A,j,F="",L="",V=!1,z=0,_=!1,G=!1;const J=this.scheduleDebug(t,"model","waiting for first stream event",a,{messages:this.messages.length});try{for await(const s of S.fullStream){if(this.closed){o.aborted=!0,o.cancellationReason??=M.runtime;break}switch(G||(G=!0,this.clearDebugTimer(J),this.debug(t,"model","first stream event",a,{part:s.type})),s.type){case"reasoning-start":t.push({type:"reasoning-start",reasoningId:s.id});break;case"reasoning-delta":t.push({type:"reasoning-delta",reasoningId:s.id,delta:s.text});break;case"reasoning-end":t.push({type:"reasoning-end",reasoningId:s.id});break;case"text-delta":if(!V){const e=L+s.text;if(qt(e,h.userPrompt)){L=e;break}if(L.length>0){const e=L+s.text;L="",F+=e,t.push({type:"text-delta",delta:e});break}}F+=s.text,t.push({type:"text-delta",delta:s.text});break;case"tool-call":{V=!0,L="";const e=this.trackPendingToolCall(o,s.toolCallId,s.toolName,s.input,this.toolCoordinator.describeResources(s.toolName,s.input));t.push({type:"tool-call",toolCallId:s.toolCallId,agentName:e.agentName,toolName:e.toolName,input:s.input});break}case"tool-result":{const i=this.registry.resolve(s.toolName),n=o.pendingToolCalls.get(s.toolCallId),r=W(s.output)?s.output:D(s.output),a=r.outcome,c=r.display,l=B({toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,input:n?.input,result:r});this.persistToolExecution(l,o);const u=a.kind===N.success?Ge(r.raw,this.observationRetentionByToolId.get(s.toolName)):void 0;if(u){o.canonicalObservationOutputs.set(s.toolCallId,u);const e=this.observationResultIds.get(s.toolCallId);void 0!==e&&e!==l.id&&this.ambiguousObservationCallIds.add(s.toolCallId),this.observationResultIds.set(s.toolCallId,this.ambiguousObservationCallIds.has(s.toolCallId)?void 0:l.id)}!0===n?.potentialSideEffect&&a.kind!==N.userRejected&&a.kind!==N.policyDenied&&a.kind!==N.invalidInput&&(o.hadPotentialSideEffects=!0),a.kind===N.success&&void 0!==n&&this.rememberCompactionResources(l,n.resources),o.pendingToolCalls.delete(s.toolCallId),t.push({type:"tool-result",toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,executionId:l.id,...void 0===l.appOutput?{}:{appOutput:e(l.appOutput)},outcome:a,display:c,output:c,isError:a.kind!==N.success}),o.aborted||o.abortController.signal.aborted||a.kind!==N.userRejected||(j=St(s.output));break}case"tool-error":{const i=this.registry.resolve(s.toolName),n=Mt(s.error),r=(n===N.invalidInput?U(s.error):void 0)??St(s.error),a=$(n,r,{raw:s.error}),c=B({toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,input:o.pendingToolCalls.get(s.toolCallId)?.input,result:a});this.persistToolExecution(c,o),!0===o.pendingToolCalls.get(s.toolCallId)?.potentialSideEffect&&a.outcome.kind!==N.invalidInput&&(o.hadPotentialSideEffects=!0),o.pendingToolCalls.delete(s.toolCallId),t.push({type:"tool-result",toolCallId:s.toolCallId,agentName:i?.agentName??s.toolName,toolName:i?.toolName??s.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a.outcome,display:a.display,output:r,isError:!0});break}case"finish-step":{const e=Rt(s.usage);void 0!==e.inputTokens&&(void 0===w||e.inputTokens>=w)&&(w=e.inputTokens,T=C),z+=1,q=s.finishReason;const o=s.performance.outputTokensPerSecond??s.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(R=o),t.push({type:"step-finish",finishReason:s.finishReason,usage:e});break}case"finish":!V&&L.length>0&&(F+=L,t.push({type:"text-delta",delta:L}),L=""),E=Rt(s.totalUsage);break;case"error":if(this.isTurnAborted(o)||P(s.error)){o.aborted=!0,o.cancellationReason=At(o.cancellationReason,s.error);break}_=wt(s.error),_&&(this.needsCompaction=!0),A=gt(s.error);break;case"abort":o.aborted=!0,o.cancellationReason=At(o.cancellationReason,s.reason)}}}catch(e){this.isTurnAborted(o)||P(e)?(o.aborted=!0,o.cancellationReason=At(o.cancellationReason,e)):(_=wt(e),_&&(this.needsCompaction=!0),A=gt(e))}finally{this.clearDebugTimer(J)}if(this.debug(t,"model","fullStream finished",a,{textChars:F.length}),void 0!==A){if(this.messages.splice(u),_){const e=0===F.length&&!V,s=e&&n<1,i=!(!s&&e)&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(e&&i&&s){n+=1;continue}const r=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(t,o,v,F.length>0,a),void t.push({type:"error",stage:"execute",message:`${A}${r}`})}return this.persistFailedTurn(t,o,v,a),void t.push({type:"error",stage:"execute",message:A})}if(o.aborted||o.abortController.signal.aborted)return o.cancellationReason=At(o.cancellationReason,o.abortController.signal.reason),void this.persistCancelledTurn(t,o,u,a);let H;this.debug(t,"model","awaiting response messages",a);const K=this.scheduleDebug(t,"model","still awaiting response messages",a);try{const e=await S.steps;H=ut(o,e)}catch(e){if(this.clearDebugTimer(K),this.isTurnAborted(o)||P(e))return o.aborted=!0,o.cancellationReason=At(o.cancellationReason,e),void this.persistCancelledTurn(t,o,u,a);const s=wt(e);if(s&&(this.needsCompaction=!0),this.messages.splice(u),s){const s=0===F.length&&!V,i=s&&n<1,r=!(!i&&s)&&await this.recoverFromContextError(t,o);if(this.isTurnAborted(o))return void this.persistCancelledRecoveryTurn(t,o,v,a);if(s&&r&&i){n+=1;continue}const c=s?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(t,o,v,F.length>0,a),void t.push({type:"error",stage:"execute",message:`${gt(e)}${c}`})}return this.persistFailedTurn(t,o,v,a),void t.push({type:"error",stage:"execute",message:gt(e)})}finally{this.clearDebugTimer(K)}if(this.debug(t,"model","response messages ready",a,{responseMessages:H.length}),this.isTurnAborted(o))return o.cancellationReason=At(o.cancellationReason,o.abortController.signal.reason),void this.persistCancelledTurn(t,o,u,a);const Y=Nt(H);this.messages.push(...Y);const Q=j??x.message;if(void 0!==Q){const e=0===F.length?Q:`\n${Q}`;F+=e,t.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:Q})}this.debug(t,"persist","persisting messages",a,{appendedMessages:this.messages.length-u}),this.persistMessages(this.messages.slice(u),"raw_transcript"),mt(o),u=this.messages.length,this.debug(t,"persist","messages persisted",a,{totalMessages:this.messages.length}),E&&(this.sessionUsage=Ot(this.sessionUsage,E));const X=w??E?.inputTokens;void 0!==X&&(this.lastInputTokens=X,this.measuredProjectedTokens=T??C,this.promptOverhead=Math.max(0,X-this.measuredProjectedTokens-p)),o.completedStepCount+=z;const te=o.completedStepCount>=this.maxSteps&&"tool-calls"===q;if(t.push({type:"message-finish",text:F,...E?{totalUsage:E}:{},sessionUsage:{...this.sessionUsage},...void 0!==w?{contextInputTokens:w}:{},...void 0!==R?{outputTokensPerSecond:R}:{},...te?{stoppedAtStepLimit:!0}:{}}),!o.pausedForContextPressure||"tool-calls"!==q||te||void 0!==Q)return;let se;o.pausedForContextPressure=!1,this.debug(t,"compaction","turn paused for context pressure",a,{continuations:o.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{se=await this.runAutoCompactionPasses(t,o,a)}catch(e){return this.isTurnAborted(o)?void this.persistPausedTurnCancellation(t,o,a):void t.push({type:"error",stage:"plan",message:gt(e)})}if(this.isTurnAborted(o))return void this.persistPausedTurnCancellation(t,o,a);o.contextPressureContinuations=se?o.contextPressureContinuations+1:2,b=!0,t.push({type:"message-start",messageId:s()})}}catch(e){if(this.isTurnAborted(o)||P(e))return o.aborted=!0,o.cancellationReason=At(o.cancellationReason,o.abortController.signal.reason??e),void(void 0!==u?this.persistCancelledTurn(t,o,u,a):this.emitCancellation(t,o));void 0!==u&&this.messages.splice(u),this.debug(t,"turn","error",a,{message:gt(e)}),t.push({type:"error",stage:"execute",message:gt(e)})}finally{void 0!==d&&clearTimeout(d),this.toolCoordinator.finishTurn(),this.activeTurn===o&&(this.activeTurn=void 0),t.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)bt(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Pe[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=ue(e);this.messages.push(s);try{this.persistMessages([s],"recovery_evidence")}catch(e){throw this.messages.splice(t),e}}persistContextFailure(e,t,s,o,i){if(!this.persistPendingToolCancellationsOrReport(e,t,"上下文溢出工具状态持久化失败"))return;const n=t.toolExecutions.some(e=>e.outcome.kind!==N.policyDenied&&e.outcome.kind!==N.userRejected&&e.outcome.kind!==N.invalidInput&&(e.outcome.kind!==N.cancelled||e.outcome.executionState!==A.notExecuted)),r=["本轮因上下文窗口溢出而中断,未自动重放。"];o&&r.push("本轮已产生部分文本,持久历史仅保留此中断标记。"),n&&r.push("本轮已有操作开始执行,部分结果可能已经生效且不会自动撤销,请先检查实际结果。");const a=[...this.uncoveredToolExecutions.values()];this.appendInterruptedTurnMessages(e,t,i,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...0===a.length?[]:[ue(a)],{role:"assistant",content:r.join("")}],debugLabel:"persisting context-overflow marker",debugDetails:{hadToolActivity:n,producedText:o},failureLabel:"上下文溢出记录持久化失败"})}persistFailedTurn(e,t,s,o){if(this.closed)return;const i=dt(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Be(Nt(pt(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,le({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${ot}`}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}: ${gt(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:at(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+Xe,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const t=s(),o=this.gate.request(t);if(void 0===this.emit)return this.gate.resolve(t,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:t,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ce(pe(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({..._(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.measuredProjectedTokens=void 0,this.promptOverhead=void 0,void 0!==e.toolSchemaPolicy&&(this.toolSchemaPolicy=e.toolSchemaPolicy,this.applyToolSchemaPolicy()&&this.refreshCapabilityManifest())}modelTools(){if(0===this.excludedToolIds.size)return this.tools;const e=this.excludedToolIds;return Object.fromEntries(Object.entries(this.tools).filter(([t])=>!e.has(t)))}recordToolSchemaIssues(e){for(const[t,s]of Object.entries(e))this.agentToolSchemaIssues.set(t,s)}applyToolSchemaPolicy(){const e=this.toolSchemaPolicy,t=new Set;if(e)for(const[s,o]of this.agentToolSchemaIssues)e(o)||t.add(s);const s=this.excludedToolIds,o=t.size!==s.size||[...t].some(e=>!s.has(e));for(const e of t)if(!s.has(e)){const t=this.registry.resolve(e);this.onToolExcluded?.({toolId:e,agentName:t?.agentName??"",toolName:t?.toolName??e,issues:this.agentToolSchemaIssues.get(e)??[]})}return this.excludedToolIds=t,o}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,t){return({steps:s})=>{const o=this.compaction,i=s.at(-1);if(void 0===o||!o.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===i||"tool-calls"!==i.finishReason||s.length<2&&this.messages.length<2||i.toolResults.some(e=>L(e.output).kind===N.userRejected))return!1;const n=Rt(i.usage),r=Z(this.projectModelMessages([...this.messages,...ut(e,s)]));return!((void 0===n.inputTokens?this.promptOverheadTokens()+r:Math.max(0,n.inputTokens+r-t()))/this.contextWindow<o.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Z([{role:"user",content:e}]),s=Z(this.projectModelMessages(this.messages));return void 0!==this.lastInputTokens&&void 0!==this.measuredProjectedTokens?Math.max(0,this.lastInputTokens+s-this.measuredProjectedTokens+t):this.promptOverheadTokens()+s+t}observationResultId(e){if(this.observationResultIds.has(e))return this.observationResultIds.get(e);const t=this.listPersistedToolExecutions?.({toolCallId:e,limit:2})??[];t.length>1&&this.ambiguousObservationCallIds.add(e);const s=1===t.length?t[0]?.id:void 0;return this.observationResultIds.set(e,s),s}readObservation(e){const t=this.getPersistedToolExecution?.(e.resultId)??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e.resultId),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();if(!t)throw new Error("当前会话中没有这个工具结果");const s=[...this.observationRetentionByToolId].find(([e])=>{const s=this.registry.resolve(e);return s?.agentName===t.agentName&&s.toolName===t.toolName})?.[1];if(!s)throw new Error("该结果不是可回查的浏览器观察");return _e(e,t,[...this.messages,...this.activeTurn?pt(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return Je(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(fe(this.capabilityManifest,me.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:ee(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?ke(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,dt(t));t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,s,{rollbackTo:this.messages.length,messages:o,debugLabel:"persisting paused turn cancellation",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}compactionTargetTokens(e){const t=this.compaction;if(void 0===t||void 0===this.contextWindow)return;const s=void 0===e?0:Z([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ae(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:x(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=we(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===Ie?this.compactionCheckpoint.semanticState:void 0,u=De(l,this.compactionCheckpoint?.constraints??[]),d=1===this.compactionCheckpoint?.version,p=void 0!==this.legacyV1ActiveSnapshot&&kt(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=d?p&&void 0!==this.legacyV1ActiveSnapshot?Fe(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=xt(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,T=e.filter(e=>e.sequence>v),y=new Set(T.filter(e=>e.provenance===Pe[1]&&bt(e.message)).map(e=>e.sequence)),b=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),C=qe({messages:[...T.filter(e=>!y.has(e.sequence)),...void 0===b||T.includes(b)?[]:[b]].map(e=>({sequence:e.sequence,role:e.message.role,summary:ft(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(yt),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),k=Oe(C,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:C,modelContext:k.prompt,presentedEvidenceIds:k.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:y,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&p?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(e,s,o,i){const n=Le({draft:s??rt,evidenceRegistry:e.registry,presentedEvidenceIds:e.presentedEvidenceIds,...void 0!==e.previousSemanticState?{previousState:e.previousSemanticState}:{},...void 0!==e.goal?{harnessGoal:{verbatimRequest:e.goal.verbatimRequest,sourceSequence:e.goal.sourceSequence}}:{}});let r=Ne(e.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const t=Re(e.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(t)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=je(r,t);const o=void 0===this.compactionCheckpoint?.goal?e.goal:void 0===e.goal||void 0===e.newGoalSourceSequence||s?this.compactionCheckpoint.goal:e.goal;r=$e(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:we(e.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??e.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,d=o?We(r):void 0,p=void 0!==d?Me(d):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Ee(r).items.map(e=>e.itemId)),m=0===e.legacySnapshotRequiredItemIds.length||e.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=xe(e.transcript.map(e=>e.message),e.toolExecutions,32,e.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...e.resources],toolState:g,runningWork:[...e.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:t("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(e.transcript,u)]},summary:p},semanticState:r,semanticSummaryText:d,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:e.expectedActiveMessages,expectedLatestCheckpointId:e.expectedLatestCheckpointId,evidenceWatermarks:e.evidenceWatermarks,legacySnapshotTranscriptFragments:e.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,this.compactionTargetTokens())}catch(t){e.push({type:"error",stage:"plan",message:gt(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 d=s?.abortController.signal,p=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",p,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g,v;const f=t=>{if(this.isTurnAborted(s)||0===t.removed&&0===t.truncatedTools)return;const o=Date.now();try{const s=this.buildCompactionDraft(h,t.semanticDraft,"summarize"===u&&t.removed>0,l);return this.debug(e,"compaction","checkpoint validation finished",o,{semanticRejections:s.semanticRejectionCount}),s}catch(e){if(void 0!==t.semanticDraft&&e instanceof Ae)throw new X(Y.invalidStructuredOutput,"semantic checkpoint validation failed",{cause:e});throw e}};try{const t=Date.now();try{g=await Q({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...d?{abortSignal:d}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new X(Y.missingObject,"structured compaction draft is missing");v=f(g)}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!X.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:gt(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await Q({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...d?{abortSignal:d}:{}}),this.debug(e,"compaction","truncate fallback finished",a),v=f(g)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const T=g.removed>0||g.truncatedTools>0;if(void 0!==v&&v.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:v.semanticRejectionCount}),void 0!==v&&!v.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const y=Be(g.messages),b=[...y.messages];if(y.status===Ue.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:y.removedToolCallIds.join(","),removedToolResultIds:y.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&b.some(bt))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 C=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),k=T&&C(b)<C(this.messages),x=k?b:[...this.messages],I=k?this.advanceCompactionSemanticEvidenceWatermarks(h,v?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let S;if(k){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");S=this.commitPersistedCompaction({messages:x,expectedActiveMessages:v.expectedActiveMessages,expectedLatestCheckpointId:v.expectedLatestCheckpointId,draft:v.draft,semanticState:v.semanticState,semanticEvidenceWatermarks:I,evidenceWatermarks:v.evidenceWatermarks,...v.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:v.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===v)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;S=Se({draft:v.draft,semanticState:v.semanticState,semanticEvidence:I,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:v.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:v.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==S&&(this.compactionCheckpoint=S),this.lastInputTokens=void 0,this.measuredProjectedTokens=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!==S?{checkpointId:S.id,checkpointGeneration:S.generation,checkpointSummaryStatus:S.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:gt(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!x(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${gt(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=M.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(S))}currentCancellationActivity(e){const t=this.activeExecSessionIds(e),s=[...e.pendingToolCalls.values()].filter(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence));return{execSessionIds:t,hadCompletedProgress:e.toolExecutions.length>0||e.completedStepResponses.size>0,hadInFlightWork:s.length>0||t.length>0,hadPotentialSideEffects:e.hadPotentialSideEffects||s.some(e=>e.potentialSideEffect)}}captureCancellationActivity(e){e.cancellationActivity??=this.currentCancellationActivity(e)}cancellationActivity(e){return e.cancellationActivity??this.currentCancellationActivity(e)}cancellationDisplayMessage(e){const t=e.cancellationReason??M.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===M.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===M.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=fe(this.capabilityManifest,me.sessionList);switch(t){case M.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case M.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":Te(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case M.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??M.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=fe(this.capabilityManifest,me.sessionList),n=ot;switch(t){case M.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case M.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:Te(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case M.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=M.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,st.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=st.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===st.keepRaw,r=n?Be(Nt(pt(t))).messages:[],a=n?dt(t):ht(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[le({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),R(this.cancellationDisplayMessage(e),e.cancellationReason??M.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${gt(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??M.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?A.outcomeUnknown:A.notExecuted,i=o===A.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=j({kind:N.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:gt(e.abortController.signal.reason)}});this.persistToolExecution(B({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=M.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(w),!0)}close(){if(void 0!==this.closePromise)return this.closePromise;this.closed=!0;const e=this.activeTurn;return e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=M.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(S)),this.closePromise=(async()=>{const e=(this.sessionManager?.close()??Promise.resolve([])).then(e=>{for(const t of e)void 0!==t.cleanupError&&process.stderr.write(`roll chat: 后台会话 ${String(t.sessionId)} 清理失败: ${t.cleanupError}\n`)},e=>{process.stderr.write(`roll chat: 会话 ${this.id} 后台清理失败: ${gt(e)}\n`)});await o(e,Qe)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Qe)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${gt(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${gt(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
1
+ import{describeAppOutput as e}from"@roll-agent/protocol";import{randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{buildSessionModelRequest as o}from"./model-request.js";import{ModelRecoveryBudget as i}from"./model-recovery.js";import{ContextMaintenanceRequired as n,RequestBudgetTracker as r}from"./request-budget.js";import{buildUserMessageContent as a,normalizeSessionSendInput as l}from"./session-attachments.js";import{stepCountIs as c,streamText as u,wrapLanguageModel as d,InvalidToolInputError as p,NoOutputGeneratedError as h}from"ai";import{buildAgentToolset as m}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as g}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as v}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as f}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as b}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as T}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as y}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as C,EXEC_LIST_NAME as I,EXEC_POLL_NAME as x,buildSessionExecToolset as k}from"../tool-bridge/session-exec-tool.js";import{SessionManager as S}from"../bash/session/session-manager.js";import{isTerminalSessionState as w}from"../bash/session/types.js";import{withCleanEnv as M}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as E,SESSION_CANCELLATION_REASONS as R,TURN_TIMEOUT_ABORT_REASON as P,USER_CANCELLATION_ABORT_REASON as O,createTurnCancellationMessage as A,isTurnTimeoutAbortReason as N}from"../types/cancellation.js";import{ToolRegistry as j}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as q,TOOL_OUTCOME_KINDS as $,createToolResult as W,failedToolResult as L,isNormalizedToolResult as D,normalizeToolResult as F,readDisplayOutput as B,readToolOutcome as _}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as U}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as z,toRedactedToolExecutionRecordSummary as H}from"../tool-bridge/tool-execution-record.js";import{ToolExecutionCoordinator as G}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as K}from"../approval/approval-gate.js";import{SessionApprovalMemory as V}from"../approval/approval-memory.js";import{compactMessages as Y,estimateMessagesTokens as J,estimateTextTokens as Q,isCompactionSummaryAcknowledgement as X,readCompactionSummaryPayload as Z}from"./compactor.js";import{AsyncEventQueue as ee}from"./event-queue.js";import{ToolInputActivityTracker as te}from"./tool-input-activity.js";import{projectTurnInputSkillCheckpoint as se,turnInputSkillCheckpointSchema as oe}from"../store/turn-input.js";import{attachExplicitSkillCheckpoint as ie,prepareExplicitSkillContext as ne,readExplicitSkillCheckpoint as re,stripExplicitSkillCheckpoints as ae}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as le,createToolLedgerGapRecoveryMessage as ce,stripCancelledTurnRecoveryMessages as ue}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as de,CAPABILITY_TOOL_ROLES as pe,buildEffectiveCapabilityTurnContext as he,buildEffectiveCapabilityManifest as me,findCapabilityToolId as ge,isProcessBoundHostMode as ve}from"./capability-manifest.js";import{buildCapabilityTurnReminder as fe,buildChatSystemPromptFromManifest as be}from"./system-prompt.js";import{threadDerivedFromSchema as Te}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as ye,buildCompactionToolState as Ce,createSummaryCheckpoint as Ie,TRANSCRIPT_MESSAGE_PROVENANCES as xe}from"./compaction-checkpoint.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as ke,repairActiveToolProtocol as Se}from"./tool-protocol-repair.js";import{buildTranscriptToolset as we}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as Me}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as Ee}from"./observation-readback.js";import{canonicalObservationOutput as Re,projectObservationMessages as Pe,restoreCanonicalObservationOutputs as Oe}from"./observation-projection.js";import{UserInputInteractionManager as Ae}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ne}from"../tool-bridge/user-input-tool.js";const je=6e3,qe=3e5,$e=1,We={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Le="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",De="AI_InvalidToolInputError:";function Fe(){return{inputId:t(),abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalObservationOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0,userRejected:!1}}function Be(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=Oe(t.response.messages,e.canonicalObservationOutputs);return e.completedStepResponses.set(s,i),i}function _e(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??Oe(t.response.messages,e.canonicalObservationOutputs))}function Ue(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function ze(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function He(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ge(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function Ke(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=Ve(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function Ve(e){try{return JSON.stringify(e)??void 0}catch{return}}function Ye(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==Z(e.content)||"assistant"===e.role&&X(e.content)}function Je(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 Qe(e){return Ke(B(e))}function Xe(e){return p.isInstance(e)||"string"==typeof e&&e.startsWith(De)?$.invalidInput:$.toolFailed}function Ze(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>_(e.output).kind===$.userRejected)??!1}function et(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(Ke(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 st(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function ot(e,t){const s=st(e.cachedInputTokens,t.cachedInputTokens),o=st(e.cacheWriteTokens,t.cacheWriteTokens),i=st(e.reasoningTokens,t.reasoningTokens);return{inputTokens:(e.inputTokens??0)+(t.inputTokens??0),outputTokens:(e.outputTokens??0)+(t.outputTokens??0),totalTokens:(e.totalTokens??0)+(t.totalTokens??0),...void 0!==s?{cachedInputTokens:s}:{},...void 0!==o?{cacheWriteTokens:o}:{},...void 0!==i?{reasoningTokens:i}:{}}}function it(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function nt(e,t){return void 0!==e?e:N(t)?R.timeout:R.runtime}function rt(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 at(e,t,s){for(const o of Object.keys(t))e[o]=s}function lt(e,t,s){const o={[C]:pe.sessionCommand,[x]:pe.sessionPoll,[I]:pe.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}export class AgentSession{id;model;modelRecovery;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];contextWindow;compaction;turnTimeoutMs;onClose;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 K;userInputInteractions=new Ae;onAcceptInput;onRecordInputSkillCheckpoint;getInputSkillCheckpoint;inputSkillCheckpoints=new Map;toolCoordinator=new G;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;requestBudgets=new r;contextWindowSource;constructor(e){this.id=e.id,this.model=e.model,this.modelRecovery=e.modelRecovery,this.contextWindowSource=e.contextWindowSource,this.maxSteps=e.maxSteps;const t=e.initialMessages?rt(e.initialMessages):[];this.messages=[...Se(t).messages],this.onPersist=e.onPersist,this.onAcceptInput=e.onAcceptInput,this.onRecordInputSkillCheckpoint=e.onRecordInputSkillCheckpoint,this.getInputSkillCheckpoint=e.getInputSkillCheckpoint,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=(e.initialCheckpoint?.transcript.messages.throughSequence??-1)+1;for(const e of this.messages)Ye(e)||(this.inMemoryTranscript.push({sequence:s,provenance:xe[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.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 j,i={},n=Ne({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,at(i,n.tools,pe.userInput);const r=e.readCheckpointTranscript?we(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};at(i,r,pe.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};at(i,a,pe.skill);const l=new V,c=e.fileTools?T(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:l}):void 0;c&&(at(i,c.readTools,pe.fileRead),at(i,c.editTools,pe.fileEdit),at(i,c.verifyTools,pe.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},d=e.bashClassifier?{classifier:e.bashClassifier}:{},p=e.bash?y(e.bash,o,u,d):{};at(i,p,pe.shell),e.bashSession&&(this.sessionManager=new S({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:M(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const h=e.bashSession&&this.sessionManager?k({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...d,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};lt(i,h,o);const v=e.agentInstall,b=v?g({catalog:v.catalog,install:async(e,t)=>{const s=await v.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}):{};at(i,b,pe.agentInstall);const C=e.schedules?f(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};at(i,C.createTools,pe.scheduleCreate),at(i,C.extendTools,pe.scheduleExtend),at(i,C.listTools,pe.scheduleList);const I=m(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);at(i,I.tools,pe.agent);const x=I.observationRetentionByToolId.size>0?Me(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(x)[0],at(i,x,pe.observationRead),this.tools={...r,...x,...a,...c?{...c.readTools,...c.editTools,...c.verifyTools}:{},...p,...h,...b,...C.createTools,...C.extendTools,...C.listTools,...I.tools},this.registry=I.registry;for(const[e,t]of I.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(I.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return me({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??de.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=be(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,v(()=>{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=m([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);at(this.toolRoles,t.tools,pe.agent),this.tools={...this.tools,...t.tools};for(const[e,s]of t.observationRetentionByToolId)this.observationRetentionByToolId.set(e,s);if(void 0===this.observationRecallToolId&&this.observationRetentionByToolId.size>0){const e=Me(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],at(this.toolRoles,e,pe.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);at(this.toolRoles,e,pe.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=l(e),s=new ee;this.emit=e=>s.push(e);const o=Fe();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:Ke(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new ee;this.emit=e=>t.push(e);const s=Fe();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:Ke(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(s,r,l){const p=Date.now(),m=this.modelRecovery,g=void 0===m?void 0:new i(m);let v,f,T;const y=()=>{r.abortController.signal.aborted||(this.captureCancellationActivity(r),r.aborted=!0,r.cancellationReason=R.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),r.abortController.abort(P))},C=a(l.text,l.attachments);try{m?.onTurnStart?.();const i={role:"user",content:C};let a;try{void 0!==this.onAcceptInput?a=this.onAcceptInput(r.inputId,i).transcriptSequence:(a=(this.listCompactionTranscriptEvidence().at(-1)?.sequence??-1)+1,this.onPersist?.([i])),this.recordPersistedMessagesInMemory([i]),this.messages.push(i),r.userMessagePersisted=!0,f=this.messages.length}catch(e){return void s.push({type:"error",stage:"plan",message:`输入持久化失败,未开始模型请求: ${Ke(e)}`})}if(void 0!==this.turnTimeoutMs){const e=Math.max(0,this.turnTimeoutMs-(Date.now()-p));r.expiresAt=new Date(p+this.turnTimeoutMs).toISOString(),T=setTimeout(y,e),0===e&&y()}this.debug(s,"turn","start",p,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...l.attachments.length>0?{attachments:l.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void s.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${Ke(e)}`})}if(f=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);this.syncWorkspaceInstructions();let I,x=0,k=!1;const S=()=>Math.max(1024,.05*(this.contextWindow??0)),w=e=>void 0===I||e>=I.calibratedInputEstimate+S(),M=new Set;let E;const P=b(),O=ne({rawInput:l.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary});void 0!==r.expiresAt&&Date.now()>=Date.parse(r.expiresAt)&&y();const A=i;if(O.skillNames.length>0&&!this.isTurnAborted(r)){const e=re(ie(i,O));if(void 0===e)throw new Error("Explicit Skill checkpoint could not be created");this.onRecordInputSkillCheckpoint?.(r.inputId,e),this.inputSkillCheckpoints.set(a,oe.parse(e))}if(f=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);s.push({type:"message-start",messageId:t()});let j={};try{j=await Je(this.resolveDynamicCapabilityContext?.(r.abortController.signal)??{},r.abortController.signal)??{}}catch(e){if(this.isTurnAborted(r))return f=this.messages.length,r.cancellationReason=nt(r.cancellationReason,r.abortController.signal.reason??e),void this.persistCancelledTurn(s,r,f,p);this.debug(s,"turn","dynamic capability context unavailable",p,{message:Ke(e)})}const q=he(this.capabilityManifest,{explicitSkillNames:O.skillNames,...j.ruleIds?{ruleIds:j.ruleIds}:{},...j.vcs?{vcs:j.vcs}:{},...j.origin?{origin:j.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=q;const W=fe(q);let B;for(;;){f=this.messages.length,r.pausedForContextPressure=!1;const i=ge(this.capabilityManifest,pe.transcriptRead),a=this.currentCheckpointReminder(i),l=void 0===a?0:Q(a),b=this.modelTools(),T=(e=[])=>o({history:this.messages,completedMessages:e,explicitSkill:O,capabilityReminder:W,...void 0===a?{}:{checkpointReminder:a},system:this.systemPrompt,tools:b,...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions},project:e=>this.projectModelMessages(e)}),y=T();let C=y.shapeContext;this.debug(s,"model","calling streamText",p,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:x,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let j,q=0,_=0;const H=[];let G,K,V,Y=!1;const X=d({model:this.model,middleware:{specificationVersion:"v4",wrapStream:async({params:e,doStream:t})=>{if(r.abortController.signal.aborted)throw r.abortController.signal.reason;const s=this.requestBudgets.prepare(e,{provider:this.model.provider,model:this.model.modelId,...void 0===this.contextWindow?{}:{window:this.contextWindow},...void 0===this.contextWindowSource?{}:{windowSource:this.contextWindowSource},threshold:this.compaction?.threshold??.75},C,r.inputId),o=s.maintenanceTarget,i=this.modelTools(),a=Object.keys(i).length!==Object.keys(b).length||Object.entries(b).some(([e,t])=>i[e]!==t),l=void 0!==s.availableInputCeiling&&s.calibratedInputEstimate>s.availableInputCeiling,c=!k&&!0===this.compaction?.enabled&&void 0!==o&&s.calibratedInputEstimate>=o&&(w(s.calibratedInputEstimate)||void 0!==I&&(s.shapeFingerprint!==I.shapeFingerprint||s.rawInputEstimate>=I.rawInputEstimate+S())),u=M.has(s.fingerprint)||void 0!==E&&s.rawInputEstimate>=E.rawInputEstimate;if(a||l||c||u)throw G=new n(s,a?"shape_changed":u?"provider_rejected":l?"budget":"soft_target"),G;k=!1,K=s,this.requestBudgets.dispatchedRequest(),Y=!1;const d=await t();if(void 0===m)return d;const p=d.stream.getReader();let h=!1;return{...d,stream:new ReadableStream({async pull(e){let t;try{t=await p.read()}catch(t){return Y=!1,e.enqueue({type:"error",error:t}),e.close(),void p.releaseLock()}if(t.done)return e.close(),void p.releaseLock();const s=t.value;if("finish"!==s.type||!h){if("finish"===s.type&&"error"===s.finishReason.unified)return h=!0,Y=!1,void e.enqueue({type:"error",error:new Error("模型未成功完成本步骤,未执行待处理工具。")});"finish"===s.type&&(Y=!0),"error"===s.type&&(Y=!1,h=!0),e.enqueue(s)}},async cancel(e){try{await p.cancel(e)}finally{p.releaseLock()}}})}}}}),Z=()=>u({model:X,...void 0===m?{}:{maxRetries:0},system:y.system,messages:y.messages,tools:b,prepareStep:()=>{q=J(this.projectModelMessages([...this.messages,...H]));const e=T(H);return C=e.shapeContext,_=this.requestBudgets.projectedMessageTokens(e.messages),{messages:e.messages,system:e.system}},stopWhen:[()=>void 0!==m&&!Y,c(Math.max(1,this.maxSteps-r.completedStepCount)),Ze(),P.stop,this.stopOnContextPressure(r,()=>q,()=>this.requestBudgets.predict(T(H).messages,_),w)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(r,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t,usage:s,finishReason:o})=>{void 0!==m&&"error"===o||(V=ot(V??{},tt(s)),void 0!==K&&this.requestBudgets.measured(K,s.inputTokens),this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])))},abortSignal:r.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{(void 0===m||Y)&&H.push(...Be(r,e))},onAbort:({steps:e})=>{if(void 0===m)for(const t of e)Be(r,t)}});let ee;try{ee=Z()}catch(e){if(this.isTurnAborted(r)||N(e))return r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,f,p);if(!et(e))throw e;this.messages.splice(f);const t=x<1,o=!!t&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(o&&t){x+=1;continue}return this.persistContextFailure(s,r,A,!1,p),void s.push({type:"error",stage:"execute",message:Ke(e)})}this.debug(s,"model","streamText returned",p);let se,oe,ie,ne,re,ae,le,ce="",ue="",de=!1,he=0,me=!1,ve=!1,fe=!1;const be=this.scheduleDebug(s,"model","waiting for first stream event",p,{messages:this.messages.length}),Te=new te(e=>{const t=this.registry.resolve(e);return void 0===t?void 0:`${t.agentName}.${t.toolName}`},e=>s.push(e)),ye=()=>Te.clear();r.abortController.signal.addEventListener("abort",ye,{once:!0});try{for await(const t of ee.fullStream){if(this.closed){r.aborted=!0,r.cancellationReason??=R.runtime;break}switch(fe||(fe=!0,this.clearDebugTimer(be),this.debug(s,"model","first stream event",p,{part:t.type})),t.type){case"start-step":void 0!==m&&s.push({type:"model-step-start"});break;case"tool-input-start":Te.start(t.id,t.toolName);break;case"tool-input-delta":Te.delta(t.id);break;case"tool-input-end":Te.end(t.id);break;case"reasoning-start":s.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":s.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":s.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!de){const e=ue+t.text;if(it(e,O.userPrompt)){ue=e;break}if(ue.length>0){const e=ue+t.text;ue="",ce+=e,s.push({type:"text-delta",delta:e});break}}ce+=t.text,s.push({type:"text-delta",delta:t.text});break;case"tool-call":{Te.end(t.toolCallId),de=!0,ue="";const e=this.trackPendingToolCall(r,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));s.push({type:"tool-call",toolCallId:t.toolCallId,agentName:e.agentName,toolName:e.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=r.pendingToolCalls.get(t.toolCallId),n=D(t.output)?t.output:F(t.output),a=n.outcome,l=n.display,c=z({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,r);const u=a.kind===$.success?Re(n.raw,this.observationRetentionByToolId.get(t.toolName)):void 0;if(u){r.canonicalObservationOutputs.set(t.toolCallId,u);const e=this.observationResultIds.get(t.toolCallId);void 0!==e&&e!==c.id&&this.ambiguousObservationCallIds.add(t.toolCallId),this.observationResultIds.set(t.toolCallId,this.ambiguousObservationCallIds.has(t.toolCallId)?void 0:c.id)}!0===i?.potentialSideEffect&&a.kind!==$.userRejected&&a.kind!==$.policyDenied&&a.kind!==$.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a,display:l,output:l,isError:a.kind!==$.success}),r.aborted||r.abortController.signal.aborted||a.kind!==$.userRejected||(le=Qe(t.output));break}case"tool-error":{Te.end(t.toolCallId);const o=this.registry.resolve(t.toolName),i=Xe(t.error),n=(i===$.invalidInput?U(t.error):void 0)??Qe(t.error),a=L(i,n,{raw:t.error}),l=z({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:r.pendingToolCalls.get(t.toolCallId)?.input,result:a});this.persistToolExecution(l,r),!0===r.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&a.outcome.kind!==$.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:l.id,...void 0===l.appOutput?{}:{appOutput:e(l.appOutput)},outcome:a.outcome,display:a.display,output:n,isError:!0});break}case"finish-step":{if(Te.clear(),void 0!==m&&void 0!==re)break;const e=tt(t.usage);void 0!==e.inputTokens&&(oe=e.inputTokens,j=q),he+=1,ne=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(ie=o),s.push({type:"step-finish",finishReason:t.finishReason,usage:e});break}case"finish":!de&&ue.length>0&&(ce+=ue,s.push({type:"text-delta",delta:ue}),ue=""),se=tt(t.totalUsage);break;case"error":if(Te.clear(),this.isTurnAborted(r)||N(t.error)){r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,t.error);break}ve=et(t.error),ae=t.error,me=!0,re=Ke(t.error);break;case"abort":Te.clear(),r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(r)||N(e)?(r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,e)):(ve=et(e),ae=e,me=!1,re=Ke(e))}finally{r.abortController.signal.removeEventListener("abort",ye),Te.dispose(),this.clearDebugTimer(be)}if(this.debug(s,"model","fullStream finished",p,{textChars:ce.length}),void 0!==G){try{await Je(ee.steps,r.abortController.signal)}catch{}if(this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);if(r.pendingToolCalls.size>0)return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:"context_maintenance_unsettled_tools:输入已保存,请先核对未结算操作。"});const e=rt(ze(r));this.messages.push(...e),e.length>0&&this.persistMessages(e,"raw_transcript"),Ge(r),f=this.messages.length,r.completedStepCount+=he,void 0!==V&&(B=void 0===B?V:ot(B,V),this.sessionUsage=ot(this.sessionUsage,V)),this.toolCoordinator.finishTurn();const i=G;if(e.length>0){if(r.completedStepCount>=this.maxSteps)return void s.push({type:"message-finish",text:ce,stoppedAtStepLimit:!0,sessionUsage:{...this.sessionUsage},...void 0===B?{}:{totalUsage:B},...void 0===oe?{}:{contextInputTokens:oe}});s.push({type:"message-start",messageId:t()});continue}if("shape_changed"===i.reason)continue;if(k||!0!==this.compaction?.enabled)return void s.push({type:"error",stage:"plan",message:`context_request_budget_unrecoverable:输入和已完成操作已保留;当前请求未通过预算检查(${i.reason},估算输入 ${Math.ceil(i.budget.calibratedInputEstimate)},输入上限 ${i.budget.availableInputCeiling??"未知"},最近实测 ${i.budget.latestMeasuredInput??"未知"})。可继续发送较小的新要求或手动压缩。`});k=!0,this.requestBudgets.beginMaintenance(i.budget,r.inputId);const n=void 0===i.budget.maintenanceTarget?void 0:Math.max(1,.5*i.budget.maintenanceTarget-(i.budget.calibratedInputEstimate-i.budget.messageTokens));let a=!1;try{a=await this.runCompaction(s,"auto",r,!1,n,(e,t)=>o({history:e,explicitSkill:O,capabilityReminder:W,...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:b,project:e=>this.projectModelMessages(e),...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions}}).messages)}catch(e){if(this.isTurnAborted(r))throw e;this.debug(s,"compaction","summary failed; original context retained",p,{message:Ke(e)})}if(I=a?void 0:i.budget,f=this.messages.length,this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,p);s.push({type:"message-start",messageId:t()});continue}if(void 0!==re&&this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,f,p);if(void 0!==re&&!ve&&me&&m?.isRecoverable(ae)&&void 0!==g&&!r.userRejected&&void 0===le&&void 0===P.message){v=ae;try{await Je(ee.steps,r.abortController.signal)}catch(e){if(r.abortController.signal.throwIfAborted(),!h.isInstance(e)&&e!==ae)throw e}const e=rt(ze(r)),t=new Map;for(const s of e)if("tool"===s.role)for(const e of s.content)"tool-result"===e.type&&t.set(e.toolCallId,(t.get(e.toolCallId)??0)+1);if([...this.uncoveredToolExecutions.values()].some(e=>{const s=t.get(e.toolCallId)??0;return t.set(e.toolCallId,s-1),0===s})||[...r.pendingToolCalls.values()].some(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence)))me=!1,re="网络中断且操作结果尚未完整结算;已停止自动恢复,请先核对结果。";else{if(this.toolCoordinator.finishTurn(),e.length>0&&(this.persistMessages(e,"raw_transcript"),this.messages.push(...e)),Ge(r),f=this.messages.length,this.persistRecoveryCancellations(s,r),f=this.messages.length,r.completedStepCount+=he,void 0!==V&&(B=void 0===B?V:ot(B,V),this.sessionUsage=ot(this.sessionUsage,V)),r.completedStepCount>=this.maxSteps)return void s.push({type:"error",stage:"execute",message:"已达单轮最大工具步数;未完成的回复已丢弃,输入和已完成的操作已保留。"});const t=await g.attempt(ae,r.abortController.signal,e=>s.push({type:"model-recovery",attempt:e}));if(t.recovered){v=void 0;continue}ae=t.error,re=Ke(t.error)}}if(void 0!==re){if(me&&!ve&&(v=ae),me&&!ve&&m?.formatError&&(re=m.formatError(ae)),ve&&void 0!==K&&(M.add(K.fingerprint),E=K),this.messages.splice(f),ve){const e=0===ce.length&&!de,t=e&&x<1,o=!(!t&&e)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(e&&o&&t){x+=1;continue}const i=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,A,ce.length>0,p),void s.push({type:"error",stage:"execute",message:`${re}${i}`})}return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:re})}if(r.aborted||r.abortController.signal.aborted)return r.cancellationReason=nt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,f,p);let Ce;this.debug(s,"model","awaiting response messages",p);const Ie=this.scheduleDebug(s,"model","still awaiting response messages",p);try{const e=await ee.steps;Ce=_e(r,e)}catch(e){if(this.clearDebugTimer(Ie),this.isTurnAborted(r)||N(e))return r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,f,p);const t=et(e);if(t&&void 0!==K&&(E=K,M.add(K.fingerprint)),this.messages.splice(f),t){const t=0===ce.length&&!de,o=t&&x<1,i=!(!o&&t)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,A,p);if(t&&i&&o){x+=1;continue}const n=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,A,ce.length>0,p),void s.push({type:"error",stage:"execute",message:`${Ke(e)}${n}`})}return this.persistFailedTurn(s,r,A,p),void s.push({type:"error",stage:"execute",message:Ke(e)})}finally{this.clearDebugTimer(Ie)}if(this.debug(s,"model","response messages ready",p,{responseMessages:Ce.length}),this.isTurnAborted(r))return r.cancellationReason=nt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,f,p);const xe=rt(Ce);this.messages.push(...xe);const ke=le??P.message;if(void 0!==ke){const e=0===ce.length?ke:`\n${ke}`;ce+=e,s.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:ke})}this.debug(s,"persist","persisting messages",p,{appendedMessages:this.messages.length-f}),this.persistMessages(this.messages.slice(f),"raw_transcript"),Ge(r),f=this.messages.length,this.debug(s,"persist","messages persisted",p,{totalMessages:this.messages.length}),se&&(B=void 0===B?se:ot(B,se),this.sessionUsage=ot(this.sessionUsage,se));const Se=oe;void 0!==Se&&(this.lastInputTokens=Se,this.measuredProjectedTokens=j??q,this.promptOverhead=Math.max(0,Se-this.measuredProjectedTokens-l)),r.completedStepCount+=he;const we=r.completedStepCount>=this.maxSteps&&"tool-calls"===ne;if(s.push({type:"message-finish",text:ce,...void 0===B?{}:{totalUsage:B},sessionUsage:{...this.sessionUsage},...void 0!==oe?{contextInputTokens:oe}:{},...void 0!==ie?{outputTokensPerSecond:ie}:{},...we?{stoppedAtStepLimit:!0}:{}}),!r.pausedForContextPressure||"tool-calls"!==ne||we||void 0!==ke)return;if(r.pausedForContextPressure=!1,this.debug(s,"compaction","turn paused for context pressure",p,{continuations:r.contextPressureContinuations,pressureTokens:this.contextPressureTokens()}),this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,p);s.push({type:"message-start",messageId:t()})}}catch(e){if(this.isTurnAborted(r)||N(e))return r.aborted=!0,r.cancellationReason=nt(r.cancellationReason,r.abortController.signal.reason??e),void(void 0!==f?this.persistCancelledTurn(s,r,f,p):this.emitCancellation(s,r));void 0!==f&&this.messages.splice(f),this.debug(s,"turn","error",p,{message:Ke(e)}),s.push({type:"error",stage:"execute",message:Ke(e)})}finally{this.requestBudgets.abandonMaintenance(r.inputId),void 0!==T&&clearTimeout(T),this.toolCoordinator.finishTurn();try{m?.onTurnEnd?.(this.isTurnAborted(r)?void 0:v)}finally{this.activeTurn===r&&(this.activeTurn=void 0),s.close()}}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)Ye(o)||(this.inMemoryTranscript.push({sequence:t,provenance:xe[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!==$.policyDenied&&e.outcome.kind!==$.userRejected&&e.outcome.kind!==$.invalidInput&&(e.outcome.kind!==$.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=Ue(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Se(rt(ze(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,le({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${Le}`}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}: ${Ke(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+qe,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{},...void 0!==e.fullDiff?{fullDiff:e.fullDiff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){const s=this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}});return s&&void 0!==this.activeTurn&&(this.activeTurn.userRejected=!0),s}getMessages(){return ae(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=>({...H(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:{...H(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getRequestBudgetState(){return this.requestBudgets.view()}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.modelRecovery=e.modelRecovery,this.requestBudgets=new r,this.contextWindowSource=e.contextWindowSource,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,this.promptOverhead=void 0,void 0!==e.toolSchemaPolicy&&(this.toolSchemaPolicy=e.toolSchemaPolicy,this.applyToolSchemaPolicy()&&this.refreshCapabilityManifest())}modelTools(){if(0===this.excludedToolIds.size)return this.tools;const e=this.excludedToolIds;return Object.fromEntries(Object.entries(this.tools).filter(([t])=>!e.has(t)))}recordToolSchemaIssues(e){for(const[t,s]of Object.entries(e))this.agentToolSchemaIssues.set(t,s)}applyToolSchemaPolicy(){const e=this.toolSchemaPolicy,t=new Set;if(e)for(const[s,o]of this.agentToolSchemaIssues)e(o)||t.add(s);const s=this.excludedToolIds,o=t.size!==s.size||[...t].some(e=>!s.has(e));for(const e of t)if(!s.has(e)){const t=this.registry.resolve(e);this.onToolExcluded?.({toolId:e,agentName:t?.agentName??"",toolName:t?.toolName??e,issues:this.agentToolSchemaIssues.get(e)??[]})}return this.excludedToolIds=t,o}stopOnContextPressure(e,t,s,o=()=>!0){return({steps:i})=>{const n=this.compaction,r=i.at(-1);if(void 0===n||!n.enabled||void 0===this.contextWindow||void 0===r||"tool-calls"!==r.finishReason||i.length<2&&this.messages.length<2||r.toolResults.some(e=>_(e.output).kind===$.userRejected))return!1;const a=tt(r.usage),l=J(this.projectModelMessages([...this.messages,..._e(e,i)])),c=s?.()??(void 0===a.inputTokens?this.promptOverheadTokens()+l:Math.max(0,a.inputTokens+l-t()));return!(c/this.contextWindow<n.threshold||!o(c))&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:J([{role:"user",content:e}]),s=J(this.projectModelMessages(this.messages));return void 0!==this.lastInputTokens&&void 0!==this.measuredProjectedTokens?Math.max(0,this.lastInputTokens+s-this.measuredProjectedTokens+t):this.promptOverheadTokens()+s+t}observationResultId(e){if(this.observationResultIds.has(e))return this.observationResultIds.get(e);const t=this.listPersistedToolExecutions?.({toolCallId:e,limit:2})??[];t.length>1&&this.ambiguousObservationCallIds.add(e);const s=1===t.length?t[0]?.id:void 0;return this.observationResultIds.set(e,s),s}readObservation(e){const t=this.getPersistedToolExecution?.(e.resultId)??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e.resultId),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();if(!t)throw new Error("当前会话中没有这个工具结果");const s=[...this.observationRetentionByToolId].find(([e])=>{const s=this.registry.resolve(e);return s?.agentName===t.agentName&&s.toolName===t.toolName})?.[1];if(!s)throw new Error("该结果不是可回查的浏览器观察");return Ee(e,t,[...this.messages,...this.activeTurn?ze(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return Pe(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(ge(this.capabilityManifest,pe.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Q(e))}currentCheckpointReminder(e){return void 0===this.compactionCheckpoint?void 0:ye(this.compactionCheckpoint,this.sessionManagerInstanceId,e)}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,Ue(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:J([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages,t=e=>({...e,message:se(e.message,this.getInputSkillCheckpoint?.(e.sequence)??this.inputSkillCheckpoints.get(e.sequence))});if(void 0===e)return this.inMemoryTranscript.map(t);const s=[];let o=-1;for(;;){const i=e({afterSequence:o,limit:500});s.push(...i.map(t));const n=i.at(-1)?.sequence;if(i.length<500||void 0===n||n<=o)break;o=n}return s}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,this.compactionTargetTokens())}catch(s){this.isTurnAborted(t)?this.emitCancellation(e,t):e.push({type:"error",stage:"plan",message:Ke(s)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}async runCompaction(e,t,s,i,n,r){const a=Date.now(),l=this.lastInputTokens,c=this.compaction,u=c?.strategy??"summarize";e.push({type:"compaction-start",reason:t});const d=()=>(e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:0,kept:this.messages.length,..."manual"===t?{recoveryNotice:"当前内容未产生可用的压缩,已保留原上下文。"}:{}}),!1);if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(!c)return d();try{const p=[...this.messages],h=this.compactionCheckpoint,m=ge(this.capabilityManifest,pe.transcriptRead),g=void 0===h?void 0:3===h.version?h.taskSummary:ye(h,this.sessionManagerInstanceId,m),v=await Y({messages:p,strategy:u,keepRecentTurns:c.keepRecentTurns,keepRecentTokens:c.keepRecentTokens,model:this.model,...void 0===g?{}:{previousSummary:g},...void 0===n?{}:{targetTokens:n},...void 0===this.contextWindow?{}:{contextWindow:this.contextWindow},...void 0===c.timeoutMs?{}:{timeoutMs:c.timeoutMs},...void 0===c.maxOutputTokens?{}:{maxOutputTokens:c.maxOutputTokens},...void 0===this.structuredOutputReasoning?{}:{structuredOutputReasoning:this.structuredOutputReasoning},...void 0===this.structuredOutputProviderOptions?{}:{structuredOutputProviderOptions:this.structuredOutputProviderOptions},...void 0===s?{}:{abortSignal:s.abortController.signal}});if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(0===v.removed)return d();const f=v.summary??("truncate"===u?g??"Earlier messages were archived. Consult the original transcript for historical details.":void 0);if(void 0===f||0===f.trim().length)return d();if(Se(v.messages).status===ke.repaired)return d();const b=this.currentCheckpointReminder(m),T=(e,t)=>void 0===r?this.requestBudgets.projectedMessageTokens(o({history:e,explicitSkill:{skillNames:[],userPrompt:"",modelUserContent:""},capabilityReminder:"",...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:this.modelTools(),project:e=>this.projectModelMessages(e)}).messages):this.requestBudgets.projectedMessageTokens(r(e,t)),y=T(p,b),C=new Error("compaction_candidate_did_not_shrink");let I=y;const x=e=>{const t=ye(e,this.sessionManagerInstanceId,m);if(I=T(v.messages,t),I>=y)throw C};let k;try{if(this.commitPersistedCompaction)k=this.commitPersistedCompaction({messages:v.messages,expectedActiveMessages:p,expectedLatestCheckpointId:h?.id,summary:f,validateCheckpoint:x});else{const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=Ie({summary:f,generation:(h?.generation??0)+1,...h?{previousCheckpointId:h.id}:{},transcript:{messages:{fromSequenceExclusive:-1,throughSequence:e.at(-1)?.sequence??h?.transcript.messages.throughSequence??-1},toolExecutions:{fromSequenceExclusive:-1,throughSequence:t.at(-1)?.sequence??h?.transcript.toolExecutions.throughSequence??-1},completeness:h?.transcript.completeness??"complete"},toolState:Ce(e.map(e=>e.message),t)});x(s),this.onReplace?.(v.messages),k=s}}catch(e){if(e===C)return d();throw e}return this.messages.splice(0,this.messages.length,...v.messages),this.compactionCheckpoint=k,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:v.removed,kept:v.kept,checkpointId:k.id,checkpointGeneration:k.generation,checkpointSummaryStatus:"summarize"===u?"valid":"skipped"}),this.debug(e,"compaction","task summary committed",a,{removed:v.removed,kept:v.kept,beforeEstimatedTokens:y,afterEstimatedTokens:I}),!0}catch(e){throw d(),e}}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(s){return this.isTurnAborted(t)||e.push({type:"error",stage:"plan",message:Ke(s)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!w(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${Ke(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=R.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(E))}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??R.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const o=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。",i=e.userMessagePersisted?"本轮输入已保存,但进度或中断记录未能保存。":"刚才的对话和进度未能保存。";return t===R.timeout?`本轮等待时间过长,已自动停止。${i}${o}`:t===R.runtime?`本轮因运行异常而中断。${i}${o}`:`已停止本轮。${i}${o}`}const o=s.execSessionIds,i=ge(this.capabilityManifest,pe.sessionList);switch(t){case R.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case R.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":ve(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case R.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??R.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=ge(this.capabilityManifest,pe.sessionList),n=Le;switch(t){case R.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case R.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 R.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=R.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,We.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=We.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s);const n=i===We.keepRaw,r=n?Se(rt(ze(t))).messages:[],a=n?Ue(t):He(t);t.cancellationPersisted=!0;const l=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...l],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[le({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),A(this.cancellationDisplayMessage(e),e.cancellationReason??R.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(e,t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${Ke(t)}`}),!1}}persistRecoveryCancellations(e,t){const s=[];for(const o of t.pendingToolCalls.values()){const i=W({kind:$.cancelled,reason:R.runtime,executionState:q.notExecuted},"模型连接中断,本工具调用确定未执行;重新生成的调用仍需正常校验与审批。"),n=z({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:i});this.persistToolExecution(n,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:n.id,outcome:i.outcome,display:i.display,output:i.display,isError:!0});const r=`${o.agentName}__${o.toolName}`;s.push({role:"assistant",content:[{type:"tool-call",toolCallId:o.toolCallId,toolName:r,input:o.input}]},{role:"tool",content:[{type:"tool-result",toolCallId:o.toolCallId,toolName:r,output:i.model}]}),t.pendingToolCalls.delete(o.toolCallId)}s.length>0&&(this.persistMessages(s,"raw_transcript"),this.messages.push(...s))}persistPendingToolCancellations(e,t){const s=t.cancellationReason??R.runtime;for(const o of t.pendingToolCalls.values()){const i=this.toolCoordinator.hasExecutionStarted(o.executionOccurrence)?q.outcomeUnknown:q.notExecuted,n=i===q.notExecuted?`工具调用在开始执行前因本轮 ${s} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${s} 中断而取消;最终结果尚未确认`,r=W({kind:$.cancelled,reason:s,executionState:i},n,{raw:{cancellationReason:s,executionState:i,abortReason:Ke(t.abortController.signal.reason)}}),a=z({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:r});this.persistToolExecution(a,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:r.display,isError:!0}),t.pendingToolCalls.delete(o.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=R.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(O),!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??=R.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(E)),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} 后台清理失败: ${Ke(e)}\n`)});await s(e,je)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(je)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${Ke(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${Ke(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)}}
@@ -23,6 +23,7 @@ export declare const CAPABILITY_TOOL_ROLES: {
23
23
  readonly scheduleExtend: "schedule-extend";
24
24
  readonly scheduleList: "schedule-list";
25
25
  readonly transcriptRead: "transcript-read";
26
+ readonly contextRead: "context-read";
26
27
  readonly observationRead: "observation-read";
27
28
  readonly userInput: "user-input";
28
29
  };
@@ -1 +1 @@
1
- import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=2;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",scheduleCreate:"schedule-create",scheduleExtend:"schedule-extend",scheduleList:"schedule-list",transcriptRead:"transcript-read",observationRead:"observation-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server",background:"background"};export function isProcessBoundHostMode(e){return e===CAPABILITY_HOST_MODES.oneShot||e===CAPABILITY_HOST_MODES.background}export function shouldOfferAgentInstall(e){return e!==CAPABILITY_HOST_MODES.background}export function shouldOfferScheduleCreate(e){return e!==CAPABILITY_HOST_MODES.background}export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};export const CAPABILITY_TURN_ORIGIN_KINDS={scheduled:"scheduled"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},r=new Set(["default","example","examples"]),s=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function u(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function p(e){return e.length>=256&&/^[a-z0-9+/_=-]+$/iu.test(e)}function I(e){return p(e)?d:u(n(e,l).replace(a,c))}function m(e,t){if(!Object.hasOwn(e,t))return t;let n=1;for(;;){const o=`~${String(n)}`,r=`${t.slice(0,i.objectKeyChars-o.length)}${o}`;if(!Object.hasOwn(e,r))return r;n+=1}}function O(e,n){if(n.depth>=i.depth)return"[nested value omitted]";if("string"==typeof e)return n.sensitive&&!s.has(n.key.toLowerCase())?l:I(e);if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if(Array.isArray(e)){const t=e.slice(0,i.arrayItems).map(e=>O(e,{...n,depth:n.depth+1}));return e.length>i.arrayItems&&t.push(`[${String(e.length-i.arrayItems)} items omitted]`),t}const o=Object.entries(e).filter(e=>void 0!==e[1]&&!r.has(e[0].toLowerCase())).sort(([e],[t])=>e.localeCompare(t)),a={};for(const[e,r]of o.slice(0,i.objectEntries)){a[m(a,u(I(e),i.objectKeyChars))]=O(r,{depth:n.depth+1,key:e,sensitive:n.sensitive||t(e)})}return o.length>i.objectEntries&&(a[m(a,"__roll_snapshot_omitted__")]=o.length-i.objectEntries),a}function A(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function L(e,t=0){if(t>32)return"[nested value omitted]";if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>L(e,t+1));if(A(e)){const n={};for(const[o,i]of Object.entries(e))void 0!==i&&(n[o]=L(i,t+1));return n}return"number"==typeof e?String(e):void 0===e?null:String(e)}const f={[CAPABILITY_TOOL_ROLES.skill]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.fileRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.sessionList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.transcriptRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.observationRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.agentInstall]:CAPABILITY_APPROVAL_MODES.alwaysConfirm,[CAPABILITY_TOOL_ROLES.scheduleList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.userInput]:CAPABILITY_APPROVAL_MODES.readOnly};function C(e){return f[e]??CAPABILITY_APPROVAL_MODES.runtimePolicy}function _(e,t){return t!==CAPABILITY_TOOL_ROLES.agent?CAPABILITY_TOOL_SOURCE_KINDS.builtIn:e.agentSource??CAPABILITY_TOOL_SOURCE_KINDS.agent}function S(e,t){const n=new Set(e.map(e=>e.role)),o=[CAPABILITY_TOOL_ROLES.sessionCommand,CAPABILITY_TOOL_ROLES.sessionPoll,CAPABILITY_TOOL_ROLES.sessionList].every(e=>n.has(e));return{manifest:CAPABILITY_MANIFEST_LIFECYCLES.manifest,turnContext:CAPABILITY_MANIFEST_LIFECYCLES.turnContext,hostMode:t,sessionExec:o?CAPABILITY_SESSION_EXEC_LIFECYCLES.resumable:CAPABILITY_SESSION_EXEC_LIFECYCLES.unavailable,sessionDurability:o?CAPABILITY_SESSION_DURABILITIES.processLocal:CAPABILITY_SESSION_DURABILITIES.unavailable}}export function buildEffectiveCapabilityManifest(t){const n=Object.keys(t.tools).sort((e,t)=>e.localeCompare(t)).map(n=>{const o=t.tools[n],i=t.resolveRoute(n);if(!o||!i)throw new Error(`无法为已注册工具 ${n} 构建 capability manifest`);const r=t.toolRoles[n];if(!r)throw new Error(`已注册工具 ${n} 缺少 capability role`);const s="description"in o?o.description:void 0;return{id:n,agentName:i.agentName,toolName:i.toolName,source:_(i,r),...i.transport?{transport:i.transport}:{},...i.runtimeOwnership?{runtimeOwnership:i.runtimeOwnership}:{},...i.annotations?{annotations:{...i.annotations}}:{},...i.appOutput?{appOutput:{schemaId:i.appOutput.schemaId,schemaVersion:i.appOutput.schemaVersion,remoteReadable:i.appOutput.remoteReadable}}:{},role:r,approval:C(r),..."string"==typeof s&&s.length>0?{description:s}:{},inputSchema:L(e(o.inputSchema).jsonSchema)}});return{version:1,audience:"roll-chat",profile:t.profile,lifecycle:S(n,t.hostMode??CAPABILITY_HOST_MODES.embedded),tools:n,skills:t.skills.map(e=>({...e})),agentCount:t.agentCount,agentOnboardingCatalog:(t.agentOnboardingCatalog??[]).map(e=>({...e})),stableContext:{rules:o,shellHints:[...t.shellHints??[]]},dynamicContext:{cwd:t.cwd,platform:t.platform??process.platform}}}export function findCapabilityToolId(e,t){return e.tools.find(e=>e.role===t)?.id}export function listCapabilityToolIds(e,t){return e.tools.filter(e=>e.role===t).map(e=>e.id)}function T(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}export function buildEffectiveCapabilityTurnContext(e,t={}){const n=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.sessionList),o=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.transcriptRead);return{version:2,audience:e.audience,profile:e.profile,lifecycle:{...e.lifecycle},cwd:e.dynamicContext.cwd,platform:e.dynamicContext.platform,date:T(t.now??new Date),dynamic:{ruleIds:[...t.ruleIds??e.stableContext.rules],sessions:(t.sessions??[]).map(e=>({...e})),...t.vcs?{vcs:{...t.vcs}}:{},...t.origin?{origin:{...t.origin}}:{}},effectiveToolIds:e.tools.map(e=>e.id),explicitSkillNames:[...t.explicitSkillNames??[]],...n?{sessionListToolId:n}:{},...o?{transcriptReadToolId:o}:{}}}function y(e){return e.slice(0,i.arrayItems).map(e=>I(e))}function h(e){return{id:I(e.id),agentName:I(e.agentName),toolName:I(e.toolName),source:e.source,...e.transport?{transport:e.transport}:{},...e.runtimeOwnership?{runtimeOwnership:e.runtimeOwnership}:{},...e.annotations?{annotations:{...e.annotations}}:{},...e.appOutput?{appOutput:{...e.appOutput}}:{},role:e.role,approval:e.approval,...e.description?{description:I(e.description)}:{},inputSchema:O(e.inputSchema,{depth:0,key:"inputSchema",sensitive:!1})}}function E(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},tools:e.tools.slice(0,i.arrayItems).map(h),skills:e.skills.slice(0,i.arrayItems).map(e=>({name:I(e.name),description:I(e.description),source:e.source})),agentCount:e.agentCount,agentOnboardingCatalog:e.agentOnboardingCatalog.slice(0,i.arrayItems).map(e=>({shortName:I(e.shortName),description:I(e.description)})),stableContext:{rules:y(e.stableContext.rules),shellHints:y(e.stableContext.shellHints)},dynamicContext:{cwd:I(e.dynamicContext.cwd),platform:e.dynamicContext.platform}}}function g(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},cwd:I(e.cwd),platform:e.platform,date:I(e.date),dynamic:{ruleIds:y(e.dynamic.ruleIds),sessions:e.dynamic.sessions.slice(0,i.arrayItems).map(e=>({...e})),...e.dynamic.vcs?{vcs:{...e.dynamic.vcs,...e.dynamic.vcs.branch?{branch:I(e.dynamic.vcs.branch)}:{}}}:{},...e.dynamic.origin?{origin:{kind:e.dynamic.origin.kind,scheduleId:I(e.dynamic.origin.scheduleId),invocationId:I(e.dynamic.origin.invocationId),scheduledFor:I(e.dynamic.origin.scheduledFor),unattended:e.dynamic.origin.unattended}}:{}},effectiveToolIds:y(e.effectiveToolIds),explicitSkillNames:y(e.explicitSkillNames),...e.sessionListToolId?{sessionListToolId:I(e.sessionListToolId)}:{},...e.transcriptReadToolId?{transcriptReadToolId:I(e.transcriptReadToolId)}:{}}}export function createSafeCapabilitySnapshot(e,t){return{manifest:E(e),...t?{turnContext:g(t)}:{}}}
1
+ import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=2;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",scheduleCreate:"schedule-create",scheduleExtend:"schedule-extend",scheduleList:"schedule-list",transcriptRead:"transcript-read",contextRead:"context-read",observationRead:"observation-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server",background:"background"};export function isProcessBoundHostMode(e){return e===CAPABILITY_HOST_MODES.oneShot||e===CAPABILITY_HOST_MODES.background}export function shouldOfferAgentInstall(e){return e!==CAPABILITY_HOST_MODES.background}export function shouldOfferScheduleCreate(e){return e!==CAPABILITY_HOST_MODES.background}export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};export const CAPABILITY_TURN_ORIGIN_KINDS={scheduled:"scheduled"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},r=new Set(["default","example","examples"]),s=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function u(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function p(e){return e.length>=256&&/^[a-z0-9+/_=-]+$/iu.test(e)}function I(e){return p(e)?d:u(n(e,l).replace(a,c))}function O(e,t){if(!Object.hasOwn(e,t))return t;let n=1;for(;;){const o=`~${String(n)}`,r=`${t.slice(0,i.objectKeyChars-o.length)}${o}`;if(!Object.hasOwn(e,r))return r;n+=1}}function m(e,n){if(n.depth>=i.depth)return"[nested value omitted]";if("string"==typeof e)return n.sensitive&&!s.has(n.key.toLowerCase())?l:I(e);if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if(Array.isArray(e)){const t=e.slice(0,i.arrayItems).map(e=>m(e,{...n,depth:n.depth+1}));return e.length>i.arrayItems&&t.push(`[${String(e.length-i.arrayItems)} items omitted]`),t}const o=Object.entries(e).filter(e=>void 0!==e[1]&&!r.has(e[0].toLowerCase())).sort(([e],[t])=>e.localeCompare(t)),a={};for(const[e,r]of o.slice(0,i.objectEntries)){a[O(a,u(I(e),i.objectKeyChars))]=m(r,{depth:n.depth+1,key:e,sensitive:n.sensitive||t(e)})}return o.length>i.objectEntries&&(a[O(a,"__roll_snapshot_omitted__")]=o.length-i.objectEntries),a}function A(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function L(e,t=0){if(t>32)return"[nested value omitted]";if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>L(e,t+1));if(A(e)){const n={};for(const[o,i]of Object.entries(e))void 0!==i&&(n[o]=L(i,t+1));return n}return"number"==typeof e?String(e):void 0===e?null:String(e)}const f={[CAPABILITY_TOOL_ROLES.skill]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.fileRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.sessionList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.transcriptRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.contextRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.observationRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.agentInstall]:CAPABILITY_APPROVAL_MODES.alwaysConfirm,[CAPABILITY_TOOL_ROLES.scheduleList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.userInput]:CAPABILITY_APPROVAL_MODES.readOnly};function C(e){return f[e]??CAPABILITY_APPROVAL_MODES.runtimePolicy}function _(e,t){return t!==CAPABILITY_TOOL_ROLES.agent?CAPABILITY_TOOL_SOURCE_KINDS.builtIn:e.agentSource??CAPABILITY_TOOL_SOURCE_KINDS.agent}function S(e,t){const n=new Set(e.map(e=>e.role)),o=[CAPABILITY_TOOL_ROLES.sessionCommand,CAPABILITY_TOOL_ROLES.sessionPoll,CAPABILITY_TOOL_ROLES.sessionList].every(e=>n.has(e));return{manifest:CAPABILITY_MANIFEST_LIFECYCLES.manifest,turnContext:CAPABILITY_MANIFEST_LIFECYCLES.turnContext,hostMode:t,sessionExec:o?CAPABILITY_SESSION_EXEC_LIFECYCLES.resumable:CAPABILITY_SESSION_EXEC_LIFECYCLES.unavailable,sessionDurability:o?CAPABILITY_SESSION_DURABILITIES.processLocal:CAPABILITY_SESSION_DURABILITIES.unavailable}}export function buildEffectiveCapabilityManifest(t){const n=Object.keys(t.tools).sort((e,t)=>e.localeCompare(t)).map(n=>{const o=t.tools[n],i=t.resolveRoute(n);if(!o||!i)throw new Error(`无法为已注册工具 ${n} 构建 capability manifest`);const r=t.toolRoles[n];if(!r)throw new Error(`已注册工具 ${n} 缺少 capability role`);const s="description"in o?o.description:void 0;return{id:n,agentName:i.agentName,toolName:i.toolName,source:_(i,r),...i.transport?{transport:i.transport}:{},...i.runtimeOwnership?{runtimeOwnership:i.runtimeOwnership}:{},...i.annotations?{annotations:{...i.annotations}}:{},...i.appOutput?{appOutput:{schemaId:i.appOutput.schemaId,schemaVersion:i.appOutput.schemaVersion,remoteReadable:i.appOutput.remoteReadable}}:{},role:r,approval:C(r),..."string"==typeof s&&s.length>0?{description:s}:{},inputSchema:L(e(o.inputSchema).jsonSchema)}});return{version:1,audience:"roll-chat",profile:t.profile,lifecycle:S(n,t.hostMode??CAPABILITY_HOST_MODES.embedded),tools:n,skills:t.skills.map(e=>({...e})),agentCount:t.agentCount,agentOnboardingCatalog:(t.agentOnboardingCatalog??[]).map(e=>({...e})),stableContext:{rules:o,shellHints:[...t.shellHints??[]]},dynamicContext:{cwd:t.cwd,platform:t.platform??process.platform}}}export function findCapabilityToolId(e,t){return e.tools.find(e=>e.role===t)?.id}export function listCapabilityToolIds(e,t){return e.tools.filter(e=>e.role===t).map(e=>e.id)}function T(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}export function buildEffectiveCapabilityTurnContext(e,t={}){const n=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.sessionList),o=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.transcriptRead);return{version:2,audience:e.audience,profile:e.profile,lifecycle:{...e.lifecycle},cwd:e.dynamicContext.cwd,platform:e.dynamicContext.platform,date:T(t.now??new Date),dynamic:{ruleIds:[...t.ruleIds??e.stableContext.rules],sessions:(t.sessions??[]).map(e=>({...e})),...t.vcs?{vcs:{...t.vcs}}:{},...t.origin?{origin:{...t.origin}}:{}},effectiveToolIds:e.tools.map(e=>e.id),explicitSkillNames:[...t.explicitSkillNames??[]],...n?{sessionListToolId:n}:{},...o?{transcriptReadToolId:o}:{}}}function y(e){return e.slice(0,i.arrayItems).map(e=>I(e))}function h(e){return{id:I(e.id),agentName:I(e.agentName),toolName:I(e.toolName),source:e.source,...e.transport?{transport:e.transport}:{},...e.runtimeOwnership?{runtimeOwnership:e.runtimeOwnership}:{},...e.annotations?{annotations:{...e.annotations}}:{},...e.appOutput?{appOutput:{...e.appOutput}}:{},role:e.role,approval:e.approval,...e.description?{description:I(e.description)}:{},inputSchema:m(e.inputSchema,{depth:0,key:"inputSchema",sensitive:!1})}}function E(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},tools:e.tools.slice(0,i.arrayItems).map(h),skills:e.skills.slice(0,i.arrayItems).map(e=>({name:I(e.name),description:I(e.description),source:e.source})),agentCount:e.agentCount,agentOnboardingCatalog:e.agentOnboardingCatalog.slice(0,i.arrayItems).map(e=>({shortName:I(e.shortName),description:I(e.description)})),stableContext:{rules:y(e.stableContext.rules),shellHints:y(e.stableContext.shellHints)},dynamicContext:{cwd:I(e.dynamicContext.cwd),platform:e.dynamicContext.platform}}}function P(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},cwd:I(e.cwd),platform:e.platform,date:I(e.date),dynamic:{ruleIds:y(e.dynamic.ruleIds),sessions:e.dynamic.sessions.slice(0,i.arrayItems).map(e=>({...e})),...e.dynamic.vcs?{vcs:{...e.dynamic.vcs,...e.dynamic.vcs.branch?{branch:I(e.dynamic.vcs.branch)}:{}}}:{},...e.dynamic.origin?{origin:{kind:e.dynamic.origin.kind,scheduleId:I(e.dynamic.origin.scheduleId),invocationId:I(e.dynamic.origin.invocationId),scheduledFor:I(e.dynamic.origin.scheduledFor),unattended:e.dynamic.origin.unattended}}:{}},effectiveToolIds:y(e.effectiveToolIds),explicitSkillNames:y(e.explicitSkillNames),...e.sessionListToolId?{sessionListToolId:I(e.sessionListToolId)}:{},...e.transcriptReadToolId?{transcriptReadToolId:I(e.transcriptReadToolId)}:{}}}export function createSafeCapabilitySnapshot(e,t){return{manifest:E(e),...t?{turnContext:P(t)}:{}}}