@roll-agent/runtime 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bash/session/session-manager.d.ts +1 -0
- package/dist/bash/session/session-manager.js +1 -1
- package/dist/engine/agent-session.d.ts +9 -1
- package/dist/engine/agent-session.js +1 -1
- package/dist/engine/conversation-engine.d.ts +5 -0
- package/dist/engine/conversation-engine.js +1 -1
- package/dist/host-contracts/index.d.ts +1 -0
- package/dist/host-contracts/index.js +1 -1
- package/dist/host-contracts/session-ownership.d.ts +12 -0
- package/dist/host-contracts/session-ownership.js +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/ownership/session-claims.d.ts +61 -0
- package/dist/ownership/session-claims.js +1 -0
- package/dist/server/runtime-protocol-adapter.d.ts +1 -0
- package/dist/server/runtime-protocol-adapter.js +1 -1
- package/dist/server/runtime-server.js +1 -1
- package/dist/service/attachment-store.js +1 -1
- package/dist/service/reasoning-display-buffer.d.ts +11 -0
- package/dist/service/reasoning-display-buffer.js +1 -0
- package/dist/service/runtime-service.d.ts +17 -1
- package/dist/service/runtime-service.js +1 -1
- package/dist/service/turn-reasoning-display.d.ts +20 -0
- package/dist/service/turn-reasoning-display.js +1 -0
- package/dist/store/thread-store.d.ts +51 -1
- package/dist/store/thread-store.js +1 -1
- package/dist/tool-bridge/file-tools/rg-exec.js +1 -1
- package/dist/types/events.d.ts +5 -0
- package/package.json +2 -2
|
@@ -34,6 +34,7 @@ export declare class SessionManager {
|
|
|
34
34
|
private readonly terminations;
|
|
35
35
|
private readonly options;
|
|
36
36
|
private acceptingSessions;
|
|
37
|
+
private readonly cleanupFailures;
|
|
37
38
|
constructor(options: SessionManagerOptions);
|
|
38
39
|
spawn(request: SpawnRequest): ManagedSession;
|
|
39
40
|
get(id: number): ManagedSession | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{performance as t}from"node:perf_hooks";import{waitForPromiseSettlement as e}from"../../bounded-wait.js";import{spawnSession as s}from"./session-exec.js";import{isTerminalSessionState as
|
|
1
|
+
import{performance as t}from"node:perf_hooks";import{waitForPromiseSettlement as e}from"../../bounded-wait.js";import{spawnSession as s}from"./session-exec.js";import{isTerminalSessionState as i,SESSION_STATES as r,SESSION_TERMINATION_CAUSES as o}from"./types.js";const n=150,a=2500,l=2e3,c=1e3,d=50,p=120;export class SessionCapError extends Error{constructor(t){super(`会话数已达上限 ${String(t)},且无空闲会话可回收`),this.name="SessionCapError"}}function u(){return 1e3+Math.floor(99e3*Math.random())}function h(t){return t instanceof Error?t.message:String(t)}function m(t){const e=Array.from(t,t=>{const e=t.codePointAt(0)??0;return e<32||127===e?" ":t}).join("").replace(/\s+/gu," ").trim(),s=Array.from(e);return s.length<=p?e:`${s.slice(0,119).join("")}…`}export class SessionManager{sessions=new Map;terminations=new Map;options;acceptingSessions=!0;cleanupFailures=new Map;constructor(t){this.options=t}spawn(t){if(!this.acceptingSessions)throw new Error("会话管理器已关闭,不再接受新命令");if(this.trimTombstones(),this.size()>=this.options.maxSessions)throw new SessionCapError(this.options.maxSessions);const e=this.allocateId(),i=s({id:e,command:t.command,workdir:t.workdir,profile:this.options.profile,env:t.env??this.options.env,bufferCapacity:this.options.bufferCapacity,...t.onDelta?{onDelta:t.onDelta}:{}});return this.sessions.set(e,i),void 0!==i.child.pid&&this.options.onSpawn?.(i.child),this.observeLifecycle(i),i}get(t){return this.sessions.get(t)}delete(t){const e=this.sessions.get(t);return!(void 0===e||!i(e.state))&&this.sessions.delete(t)}size(){let t=0;for(const e of this.sessions.values())e.state!==r.completed&&(t+=1);return t}list(){const e=t.now();return[...this.sessions.values()].sort((t,e)=>t.startedAt-e.startedAt).map(t=>({sessionId:t.id,commandPreview:m(t.command),workdir:t.workdir,state:t.state,startedAt:t.startedAt,lastUsedAt:t.lastUsedAt,wallTimeMs:(t.completedAt??e)-t.startedAt,...void 0!==t.exitCode?{exitCode:t.exitCode}:{},...t.terminationCause?{terminationCause:t.terminationCause}:{},...t.cleanupError?{cleanupError:t.cleanupError}:{}}))}async interrupt(t){return this.stopTargets(t,o.interrupt)}async terminate(t){return this.stopTargets(t,o.terminate)}async interruptAll(){return this.stopTargets(this.activeIds(),o.interrupt)}async terminateAll(){return this.stopTargets(this.activeIds(),o.terminate)}async close(){this.acceptingSessions=!1;const t=await this.terminateAll(),e=new Map(t.map(t=>[t.sessionId,t]));for(const[t,s]of this.cleanupFailures)e.set(t,s);return[...e.values()]}activeIds(){return[...this.sessions.values()].filter(t=>!i(t.state)).map(t=>t.id)}async stopTargets(t,e){const s="number"==typeof t?[t]:[...new Set(t)],r=[];for(const t of s){const s=this.sessions.get(t);void 0===s||i(s.state)||r.push(this.requestStop(s,e))}return Promise.all(r)}requestStop(t,e,s){const i=this.terminations.get(t.id);if(void 0!==i)return e===o.terminate&&(i.intent=e),void 0===s||i.errors.includes(s)||i.errors.push(s),i.promise;t.markStopping(e);const n={intent:e,errors:void 0===s?[]:[s],promise:Promise.resolve({sessionId:t.id,state:r.cleanupFailed})};return this.terminations.set(t.id,n),n.promise=this.runTermination(t,n).finally(()=>{this.terminations.delete(t.id),this.trimTombstones()}),n.promise}async runTermination(t,s){const r=s.intent,a=await this.killTree(t,r);let p=void 0!==a;if(void 0!==a&&s.errors.push(a),r===o.interrupt&&!t.closeObserved){s.intent!==o.terminate&&await e(t.waitClose(),this.options.interruptGraceMs??n);const i=t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit;if(!t.closeObserved&&!i){const e=await this.killTree(t,o.terminate);void 0!==e&&(p=!0,s.errors.push(e))}}const u=this.options.rootSettleTimeoutMs??c;if(t.exitObserved||p||await e(t.waitExit(),u),!t.exitObserved){const i=this.forceKillRoot(t);void 0!==i&&s.errors.push(i),await e(t.waitExit(),u)}t.exitObserved||s.errors.push("根进程在强制终止请求后仍未确认退出"),t.closeObserved||await e(t.waitClose(),this.options.closeDrainTimeoutMs??l),t.closeObserved||(this.destroyStreams(t),await e(t.waitClose(),d)),t.closeObserved||s.errors.push("进程树终止后仍未观察到根进程退出与 stdio close"),s.errors.length>0?t.markCleanupFailed(s.errors.join(";")):t.markCompleted(),i(t.state)||t.markCleanupFailed("会话清理未能收口");const h=t.state;if(!i(h))throw new Error(`会话 ${String(t.id)} 清理后仍处于非终态`);const m={sessionId:t.id,state:h,...t.cleanupError?{cleanupError:t.cleanupError}:{}};return void 0!==m.cleanupError&&this.cleanupFailures.set(t.id,m),m}async killTree(t,e){if(t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit)return"根进程已退出,不能安全复用旧 PID 清理或确认后代进程树";const s=this.options.killTreeTimeoutMs??a,i=new AbortController;let r;try{const o=t.profile.killTree(t.child.pid,e,{signal:i.signal});return void await Promise.race([o,new Promise((t,e)=>{r=setTimeout(()=>{e(new Error(`进程树终止在 ${String(s)}ms 内未完成`)),i.abort()},s)})])}catch(t){return h(t)}finally{void 0!==r&&clearTimeout(r),i.abort()}}forceKillRoot(t){if(!t.exitObserved)try{return t.child.kill("SIGKILL")?void 0:"根进程强制终止请求未被接受"}catch(t){return`根进程强制终止请求失败: ${h(t)}`}}destroyStreams(t){t.child.stdin?.destroy(),t.child.stdout?.destroy(),t.child.stderr?.destroy(),t.child.unref()}observeLifecycle(t){t.waitSettled().then(()=>this.trimTombstones()),t.waitExit().then(()=>{if(t.closeObserved||i(t.state))return;const s=this.options.closeDrainTimeoutMs??l;e(t.waitSettled(),s).then(e=>{e||i(t.state)||this.requestStop(t,o.terminate,`根进程退出后 stdio 在 ${String(s)}ms 内未关闭`).catch(e=>{t.markCleanupFailed(`会话自动清理失败:${h(e)}`)})})})}trimTombstones(){const t=[...this.sessions.values()].filter(t=>t.state===r.completed&&!this.terminations.has(t.id)).sort((t,e)=>(t.completedAt??0)-(e.completedAt??0)),e=t.length-this.options.maxSessions;for(let s=0;s<e;s+=1){const e=t[s];void 0!==e&&this.sessions.delete(e.id)}}allocateId(){const t=this.options.generateId??u;for(let e=0;e<1e3;e+=1){const e=t();if(!this.sessions.has(e))return e}throw new Error("无法分配唯一会话 id")}}
|
|
@@ -7,7 +7,7 @@ import type { LanguageModelV4, LanguageModelV4CallOptions, SharedV4ProviderOptio
|
|
|
7
7
|
import type { UserInputResult } from "@roll-agent/protocol";
|
|
8
8
|
import type { SkillLibrary, SkillSummary } from "../skills/contracts.ts";
|
|
9
9
|
import type { JsonSchemaRefIssue } from "../tool-contracts/json-schema-refs.ts";
|
|
10
|
-
import type { ContextCompactionReason, ContextCompactionStrategy, SessionEvent, SessionTokenUsage } from "../types/events.ts";
|
|
10
|
+
import type { ContextCompactionReason, ContextCompactionStrategy, ReasoningPresentation, SessionEvent, SessionTokenUsage } from "../types/events.ts";
|
|
11
11
|
import type { ToolPolicy } from "../types/policy.ts";
|
|
12
12
|
import { type AgentToolSource } from "../tool-bridge/build-tools.ts";
|
|
13
13
|
import { type AgentInstallToolCatalogEntry, type AgentInstallToolOutcome } from "../tool-bridge/agent-install-tool.ts";
|
|
@@ -57,6 +57,7 @@ export interface SessionModelSwitch {
|
|
|
57
57
|
export interface AgentSessionOptions {
|
|
58
58
|
readonly id: string;
|
|
59
59
|
readonly model: LanguageModelV4;
|
|
60
|
+
readonly resolveReasoningPresentation?: (model: Pick<LanguageModelV4, "provider" | "modelId">, options: SharedV4ProviderOptions | undefined) => ReasoningPresentation | undefined;
|
|
60
61
|
/** @internal Synchronous engine admission before accepting input or starting compaction. */
|
|
61
62
|
readonly onBeforeTurn?: () => void;
|
|
62
63
|
readonly modelRecovery?: ModelTurnRecovery;
|
|
@@ -150,6 +151,7 @@ export type SessionToolExecutionRecordView = SequencedToolExecutionRecord | (Red
|
|
|
150
151
|
export declare class AgentSession {
|
|
151
152
|
readonly id: string;
|
|
152
153
|
private model;
|
|
154
|
+
private readonly resolveReasoningPresentation;
|
|
153
155
|
private modelRecovery;
|
|
154
156
|
private readonly maxSteps;
|
|
155
157
|
private readonly messages;
|
|
@@ -218,6 +220,9 @@ export declare class AgentSession {
|
|
|
218
220
|
private emit;
|
|
219
221
|
private activeTurn;
|
|
220
222
|
private closePromise;
|
|
223
|
+
private readonly executionJobs;
|
|
224
|
+
private readonly closeBarriers;
|
|
225
|
+
private executionFailure;
|
|
221
226
|
private closed;
|
|
222
227
|
private sessionUsage;
|
|
223
228
|
private lastInputTokens;
|
|
@@ -333,6 +338,9 @@ export declare class AgentSession {
|
|
|
333
338
|
private persistRecoveryCancellations;
|
|
334
339
|
private persistPendingToolCancellations;
|
|
335
340
|
cancel(): boolean;
|
|
341
|
+
assertWritable(): void;
|
|
342
|
+
addCloseBarrier(barrier: () => Promise<void>): void;
|
|
343
|
+
private trackExecution;
|
|
336
344
|
close(): Promise<void>;
|
|
337
345
|
abort(): void;
|
|
338
346
|
private debug;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeAppOutput as e}from"@roll-agent/protocol";import{randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{buildSessionModelRequest as o}from"./model-request.js";import{ModelRecoveryBudget as i}from"./model-recovery.js";import{ContextMaintenanceRequired as n,RequestBudgetTracker as r}from"./request-budget.js";import{buildUserMessageContent as a,normalizeSessionSendInput as l}from"./session-attachments.js";import{stepCountIs as c,streamText as u,wrapLanguageModel as d,InvalidToolInputError as p,NoOutputGeneratedError as h}from"ai";import{COMPACTION_FAILURE_REASONS as m}from"../types/events.js";import{buildAgentToolset as g}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as v}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as f,skillInputErrorResult as b}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as y}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as T}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as C}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as I}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as k,EXEC_LIST_NAME as x,EXEC_POLL_NAME as S,buildSessionExecToolset as w}from"../tool-bridge/session-exec-tool.js";import{SessionManager as M}from"../bash/session/session-manager.js";import{isTerminalSessionState as E}from"../bash/session/types.js";import{withCleanEnv as R}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as P,SESSION_CANCELLATION_REASONS as O,TURN_TIMEOUT_ABORT_REASON as A,USER_CANCELLATION_ABORT_REASON as N,createTurnCancellationMessage as j,isTurnTimeoutAbortReason as q}from"../types/cancellation.js";import{ToolRegistry as $}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as L,TOOL_OUTCOME_KINDS as W,createToolResult as D,failedToolResult as F,isNormalizedToolResult as B,normalizeToolResult as _,readDisplayOutput as U,readToolOutcome as z}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as H}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as G,toRedactedToolExecutionRecordSummary as K}from"../tool-bridge/tool-execution-record.js";import{ToolExecutionCoordinator as V}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as Y}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{CompactionTimeoutError as Q,compactMessages as X,estimateMessagesTokens as Z,estimateTextTokens as ee,isCompactionSummaryAcknowledgement as te,readCompactionSummaryPayload as se}from"./compactor.js";import{AsyncEventQueue as oe}from"./event-queue.js";import{ToolInputActivityTracker as ie}from"./tool-input-activity.js";import{projectTurnInputSkillCheckpoint as ne,turnInputSkillCheckpointSchema as re}from"../store/turn-input.js";import{attachExplicitSkillCheckpoint as ae,prepareExplicitSkillContext as le,readExplicitSkillCheckpoint as ce,stripExplicitSkillCheckpoints as ue}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as de,createToolLedgerGapRecoveryMessage as pe,stripCancelledTurnRecoveryMessages as he}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as me,CAPABILITY_TOOL_ROLES as ge,buildEffectiveCapabilityTurnContext as ve,buildEffectiveCapabilityManifest as fe,findCapabilityToolId as be,isProcessBoundHostMode as ye}from"./capability-manifest.js";import{buildCapabilityTurnReminder as Te,buildChatSystemPromptFromManifest as Ce}from"./system-prompt.js";import{threadDerivedFromSchema as Ie}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as ke,buildCompactionToolState as xe,createSummaryCheckpoint as Se,TRANSCRIPT_MESSAGE_PROVENANCES as we}from"./compaction-checkpoint.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Me,repairActiveToolProtocol as Ee}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Re}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as Pe}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as Oe}from"./observation-readback.js";import{canonicalObservationOutput as Ae,projectObservationMessages as Ne,restoreCanonicalObservationOutputs as je}from"./observation-projection.js";import{UserInputInteractionManager as qe}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as $e}from"../tool-bridge/user-input-tool.js";const Le=6e3,We=3e5,De=1,Fe={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Be="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",_e="AI_InvalidToolInputError:";function Ue(){return{inputId:t(),abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalToolOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0,userRejected:!1}}function ze(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=je(t.response.messages,e.canonicalToolOutputs);return e.completedStepResponses.set(s,i),i}function He(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??je(t.response.messages,e.canonicalToolOutputs))}function Ge(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function Ke(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ve(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ye(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function Je(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e){if("message"in e&&"string"==typeof e.message&&e.message.length>0)return e.message;const t=Qe(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function Qe(e){try{return JSON.stringify(e)??void 0}catch{return}}function Xe(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==se(e.content)||"assistant"===e.role&&te(e.content)}function Ze(e,t){return t.aborted?Promise.reject(t.reason):new Promise((s,o)=>{let i=!1;const n=e=>{i||(i=!0,t.removeEventListener("abort",r),e())},r=()=>n(()=>o(t.reason));t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(e=>n(()=>s(e)),e=>n(()=>o(e)))})}function et(e){return Je(U(e))}function tt(e){return p.isInstance(e)||"string"==typeof e&&e.startsWith(_e)?W.invalidInput:W.toolFailed}function st(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>z(e.output).kind===W.userRejected)??!1}function ot(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(Je(e))}function it(e){const t=e.inputTokenDetails?.cacheReadTokens,s=e.inputTokenDetails?.cacheWriteTokens,o=e.outputTokenDetails?.reasoningTokens;return{...void 0!==e.inputTokens?{inputTokens:e.inputTokens}:{},...void 0!==e.outputTokens?{outputTokens:e.outputTokens}:{},...void 0!==e.totalTokens?{totalTokens:e.totalTokens}:{},...void 0!==t?{cachedInputTokens:t}:{},...void 0!==s?{cacheWriteTokens:s}:{},...void 0!==o?{reasoningTokens:o}:{}}}function nt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function rt(e,t){const s=nt(e.cachedInputTokens,t.cachedInputTokens),o=nt(e.cacheWriteTokens,t.cacheWriteTokens),i=nt(e.reasoningTokens,t.reasoningTokens);return{inputTokens:(e.inputTokens??0)+(t.inputTokens??0),outputTokens:(e.outputTokens??0)+(t.outputTokens??0),totalTokens:(e.totalTokens??0)+(t.totalTokens??0),...void 0!==s?{cachedInputTokens:s}:{},...void 0!==o?{cacheWriteTokens:o}:{},...void 0!==i?{reasoningTokens:i}:{}}}function at(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function lt(e,t){return void 0!==e?e:q(t)?O.timeout:O.runtime}function ct(e){return e.flatMap(e=>{if("assistant"!==e.role||!Array.isArray(e.content))return[e];const t=e.content.filter(e=>"reasoning"!==e.type);return 0===t.length?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function ut(e,t,s){for(const o of Object.keys(t))e[o]=s}function dt(e,t,s){const o={[k]:ge.sessionCommand,[S]:ge.sessionPoll,[x]:ge.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}export class AgentSession{id;model;modelRecovery;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];contextWindow;compaction;turnTimeoutMs;onClose;onBeforeTurn;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillExecutionLibrary;skillToolId;refreshSkillLibrary;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new Y;userInputInteractions=new qe;onAcceptInput;onRecordInputSkillCheckpoint;getInputSkillCheckpoint;inputSkillCheckpoints=new Map;toolCoordinator=new V;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;requestBudgets=new r;contextWindowSource;constructor(e){this.id=e.id,this.model=e.model,this.modelRecovery=e.modelRecovery,this.contextWindowSource=e.contextWindowSource,this.maxSteps=e.maxSteps;const t=e.initialMessages?ct(e.initialMessages):[];this.messages=[...Ee(t).messages],this.onPersist=e.onPersist,this.onAcceptInput=e.onAcceptInput,this.onRecordInputSkillCheckpoint=e.onRecordInputSkillCheckpoint,this.getInputSkillCheckpoint=e.getInputSkillCheckpoint,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=(e.initialCheckpoint?.transcript.messages.throughSequence??-1)+1;for(const e of this.messages)Xe(e)||(this.inMemoryTranscript.push({sequence:s,provenance:we[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.onBeforeTurn=e.onBeforeTurn,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.derivedFrom=void 0===e.derivedFrom?void 0:Ie.parse(e.derivedFrom),this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillExecutionLibrary=e.skillLibrary,this.refreshSkillLibrary=e.refreshSkillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName)),this.toolSchemaPolicy=e.toolSchemaPolicy,this.onToolExcluded=e.onToolExcluded;const o=new $,i={},n=$e({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,ut(i,n.tools,ge.userInput);const r=e.readCheckpointTranscript?Re(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};ut(i,r,ge.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};ut(i,a,ge.skill);const l=new J,c=e.fileTools?C(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:l}):void 0;c&&(ut(i,c.readTools,ge.fileRead),ut(i,c.editTools,ge.fileEdit),ut(i,c.verifyTools,ge.fileVerify));const u={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},d=e.bashClassifier?{classifier:e.bashClassifier}:{},p=e.bash?I(e.bash,o,u,d):{};ut(i,p,ge.shell),e.bashSession&&(this.sessionManager=new M({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:R(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const h=e.bashSession&&this.sessionManager?w({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,u,{...d,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};dt(i,h,o);const m=e.agentInstall,f=m?v({catalog:m.catalog,install:async(e,t)=>{const s=await m.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};ut(i,f,ge.agentInstall);const b=e.schedules?y(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};ut(i,b.createTools,ge.scheduleCreate),ut(i,b.extendTools,ge.scheduleExtend),ut(i,b.listTools,ge.scheduleList);const T=g(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);ut(i,T.tools,ge.agent);const k=T.observationRetentionByToolId.size>0?Pe(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(k)[0],ut(i,k,ge.observationRead),this.tools={...r,...k,...a,...c?{...c.readTools,...c.editTools,...c.verifyTools}:{},...p,...h,...f,...b.createTools,...b.extendTools,...b.listTools,...T.tools},this.registry=T.registry;for(const[e,t]of T.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(T.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return fe({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??me.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=Ce(this.capabilityManifest,{...void 0!==this.derivedFrom?{derivedFrom:this.derivedFrom}:{},...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){const t=f(()=>{if(!this.skillExecutionLibrary)throw new Error("skill library 不可用");return this.skillExecutionLibrary},e,this.toolCoordinator,{...void 0===this.skillToolId?{}:{toolId:this.skillToolId},names:this.skillSummaries.map(e=>e.name)});return this.skillToolId??=Object.keys(t)[0],t}applySkillLibrary(e){const t=e?.list()??[],s=t.length!==this.skillSummaries.length||t.some((e,t)=>e.name!==this.skillSummaries[t]?.name),o=JSON.stringify(t)!==JSON.stringify(this.skillSummaries);if(this.skillLibrary=e,this.skillSummaries=t,s){if(void 0!==this.skillToolId){const e={...this.tools};delete e[this.skillToolId],delete this.toolRoles[this.skillToolId],this.tools=e}const e=this.buildSkillTools(this.registry);ut(this.toolRoles,e,ge.skill),this.tools={...this.tools,...e}}o&&this.refreshCapabilityManifest()}async refreshSkills(e){if(void 0!==this.refreshSkillLibrary){const t=await Ze(this.refreshSkillLibrary(e),e);e.throwIfAborted(),this.applySkillLibrary(t)}this.skillExecutionLibrary=this.skillLibrary}skillToolInputError(e,t){return e===this.skillToolId&&void 0!==this.skillExecutionLibrary?b(this.skillExecutionLibrary,t):void 0}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=g([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);ut(this.toolRoles,t.tools,ge.agent),this.tools={...this.tools,...t.tools};for(const[e,s]of t.observationRetentionByToolId)this.observationRetentionByToolId.set(e,s);if(void 0===this.observationRecallToolId&&this.observationRetentionByToolId.size>0){const e=Pe(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],ut(this.toolRoles,e,ge.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.toolSourceAgentNames.add(e.source.agentName)}e.skillLibrary&&this.applySkillLibrary(e.skillLibrary),e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");this.onBeforeTurn?.();const t=l(e),s=new oe;this.emit=e=>s.push(e);const o=Ue();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:Je(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");this.onBeforeTurn?.();const t=new oe;this.emit=e=>t.push(e);const s=Ue();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:Je(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(s,r,l){const m=Date.now(),g=this.modelRecovery,v=void 0===g?void 0:new i(g);let f,b,y;const C=()=>{r.abortController.signal.aborted||(this.captureCancellationActivity(r),r.aborted=!0,r.cancellationReason=O.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),r.abortController.abort(A))},I=a(l.text,l.attachments);try{g?.onTurnStart?.();const i={role:"user",content:I};let a;try{void 0!==this.onAcceptInput?a=this.onAcceptInput(r.inputId,i).transcriptSequence:(a=(this.listCompactionTranscriptEvidence().at(-1)?.sequence??-1)+1,this.onPersist?.([i])),this.recordPersistedMessagesInMemory([i]),this.messages.push(i),r.userMessagePersisted=!0,b=this.messages.length}catch(e){return void s.push({type:"error",stage:"plan",message:`输入持久化失败,未开始模型请求: ${Je(e)}`})}if(void 0!==this.turnTimeoutMs){const e=Math.max(0,this.turnTimeoutMs-(Date.now()-m));r.expiresAt=new Date(m+this.turnTimeoutMs).toISOString(),y=setTimeout(C,e),0===e&&C()}this.debug(s,"turn","start",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...l.attachments.length>0?{attachments:l.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void s.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${Je(e)}`})}if(b=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);this.syncWorkspaceInstructions(),await this.refreshSkills(r.abortController.signal);let k,x=!0,S=0,w=!1;const M=()=>Math.max(1024,.05*(this.contextWindow??0)),E=e=>void 0===k||e>=k.calibratedInputEstimate+M(),R=new Set;let P;const A=T(),N=le({rawInput:l.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary});void 0!==r.expiresAt&&Date.now()>=Date.parse(r.expiresAt)&&C();const j=i;if(N.skillNames.length>0&&!this.isTurnAborted(r)){const e=ce(ae(i,N));if(void 0===e)throw new Error("Explicit Skill checkpoint could not be created");this.onRecordInputSkillCheckpoint?.(r.inputId,e),this.inputSkillCheckpoints.set(a,re.parse(e))}if(b=this.messages.length,this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);s.push({type:"message-start",messageId:t()});let $={};try{$=await Ze(this.resolveDynamicCapabilityContext?.(r.abortController.signal)??{},r.abortController.signal)??{}}catch(e){if(this.isTurnAborted(r))return b=this.messages.length,r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason??e),void this.persistCancelledTurn(s,r,b,m);this.debug(s,"turn","dynamic capability context unavailable",m,{message:Je(e)})}const L=ve(this.capabilityManifest,{explicitSkillNames:N.skillNames,...$.ruleIds?{ruleIds:$.ruleIds}:{},...$.vcs?{vcs:$.vcs}:{},...$.origin?{origin:$.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=L;const D=Te(L);let U;for(;;){b=this.messages.length,r.pausedForContextPressure=!1;const i=be(this.capabilityManifest,ge.transcriptRead),a=this.currentCheckpointReminder(i),l=void 0===a?0:ee(a),y=this.modelTools(),T=(e=[])=>o({history:this.messages,completedMessages:e,explicitSkill:N,capabilityReminder:D,...void 0===a?{}:{checkpointReminder:a},system:this.systemPrompt,tools:y,...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions},project:e=>this.projectModelMessages(e)}),C=T();let I=C.shapeContext;this.debug(s,"model","calling streamText",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:S,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let $,L=0,z=0;const K=[];let V,Y,J,Q=!1;const X=d({model:this.model,middleware:{specificationVersion:"v4",wrapStream:async({params:e,doStream:t})=>{if(r.abortController.signal.aborted)throw r.abortController.signal.reason;const s=this.requestBudgets.prepare(e,{provider:this.model.provider,model:this.model.modelId,...void 0===this.contextWindow?{}:{window:this.contextWindow},...void 0===this.contextWindowSource?{}:{windowSource:this.contextWindowSource},threshold:this.compaction?.threshold??.75},I,r.inputId),o=s.maintenanceTarget,i=this.modelTools(),a=Object.keys(i).length!==Object.keys(y).length||Object.entries(y).some(([e,t])=>i[e]!==t),l=void 0!==s.availableInputCeiling&&s.calibratedInputEstimate>s.availableInputCeiling,c=!w&&!0===this.compaction?.enabled&&void 0!==o&&s.calibratedInputEstimate>=o&&(E(s.calibratedInputEstimate)||void 0!==k&&(s.shapeFingerprint!==k.shapeFingerprint||s.rawInputEstimate>=k.rawInputEstimate+M())),u=R.has(s.fingerprint)||void 0!==P&&s.rawInputEstimate>=P.rawInputEstimate;if(a||l||c||u)throw a&&(x=!0),V=new n(s,a?"shape_changed":u?"provider_rejected":l?"budget":"soft_target"),V;w=!1,Y=s,this.requestBudgets.dispatchedRequest(),Q=!1;const d=await t();if(void 0===g)return d;const p=d.stream.getReader();let h=!1;return{...d,stream:new ReadableStream({async pull(e){let t;try{t=await p.read()}catch(t){return Q=!1,e.enqueue({type:"error",error:t}),e.close(),void p.releaseLock()}if(t.done)return e.close(),void p.releaseLock();const s=t.value;if("finish"!==s.type||!h){if("finish"===s.type&&"error"===s.finishReason.unified)return h=!0,Q=!1,void e.enqueue({type:"error",error:new Error("模型未成功完成本步骤,未执行待处理工具。")});"finish"===s.type&&(Q=!0),"error"===s.type&&(Q=!1,h=!0),e.enqueue(s)}},async cancel(e){try{await p.cancel(e)}finally{p.releaseLock()}}})}}}}),te=()=>u({model:X,...void 0===g?{}:{maxRetries:0},system:C.system,messages:C.messages,tools:y,prepareStep:async()=>{x||await this.refreshSkills(r.abortController.signal),x=!1,L=Z(this.projectModelMessages([...this.messages,...K]));const e=T(K);return I=e.shapeContext,z=this.requestBudgets.projectedMessageTokens(e.messages),{messages:e.messages,system:e.system}},stopWhen:[()=>void 0!==g&&!Q,c(Math.max(1,this.maxSteps-r.completedStepCount)),st(),A.stop,this.stopOnContextPressure(r,()=>L,()=>this.requestBudgets.predict(T(K).messages,z),E)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(r,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t,usage:s,finishReason:o})=>{if(void 0===g||"error"!==o){for(const e of t){if("tool-call"!==e.type||!("invalid"in e)||!0!==e.invalid)continue;const t=this.skillToolInputError(e.toolName,e.input);void 0!==t&&r.canonicalToolOutputs.set(e.toolCallId,t.model)}J=rt(J??{},it(s)),void 0!==Y&&this.requestBudgets.measured(Y,s.inputTokens),this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}]))}},abortSignal:r.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{(void 0===g||Q)&&K.push(...ze(r,e))},onAbort:({steps:e})=>{if(void 0===g)for(const t of e)ze(r,t)}});let se;try{se=te()}catch(e){if(this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,b,m);if(!ot(e))throw e;this.messages.splice(b);const t=S<1,o=!!t&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(o&&t){S+=1;continue}return this.persistContextFailure(s,r,j,!1,m),void s.push({type:"error",stage:"execute",message:Je(e)})}this.debug(s,"model","streamText returned",m);let oe,ne,re,ae,le,ce,ue,de="",pe="",he=!1,me=0,ve=!1,fe=!1,ye=!1;const Te=this.scheduleDebug(s,"model","waiting for first stream event",m,{messages:this.messages.length}),Ce=new ie(e=>{const t=this.registry.resolve(e);return void 0===t?void 0:`${t.agentName}.${t.toolName}`},e=>s.push(e)),Ie=()=>Ce.clear();r.abortController.signal.addEventListener("abort",Ie,{once:!0});try{for await(const t of se.fullStream){if(this.closed){r.aborted=!0,r.cancellationReason??=O.runtime;break}switch(ye||(ye=!0,this.clearDebugTimer(Te),this.debug(s,"model","first stream event",m,{part:t.type})),t.type){case"start-step":void 0!==g&&s.push({type:"model-step-start"});break;case"tool-input-start":Ce.start(t.id,t.toolName);break;case"tool-input-delta":Ce.delta(t.id);break;case"tool-input-end":Ce.end(t.id);break;case"reasoning-start":s.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":s.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":s.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!he){const e=pe+t.text;if(at(e,N.userPrompt)){pe=e;break}if(pe.length>0){const e=pe+t.text;pe="",de+=e,s.push({type:"text-delta",delta:e});break}}de+=t.text,s.push({type:"text-delta",delta:t.text});break;case"tool-call":{Ce.end(t.toolCallId),he=!0,pe="";const e=this.trackPendingToolCall(r,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));s.push({type:"tool-call",toolCallId:t.toolCallId,agentName:e.agentName,toolName:e.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=r.pendingToolCalls.get(t.toolCallId),n=B(t.output)?t.output:_(t.output),a=n.outcome,l=n.display,c=G({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,r);const u=a.kind===W.success?Ae(n.raw,this.observationRetentionByToolId.get(t.toolName)):void 0;if(u){r.canonicalToolOutputs.set(t.toolCallId,u);const e=this.observationResultIds.get(t.toolCallId);void 0!==e&&e!==c.id&&this.ambiguousObservationCallIds.add(t.toolCallId),this.observationResultIds.set(t.toolCallId,this.ambiguousObservationCallIds.has(t.toolCallId)?void 0:c.id)}!0===i?.potentialSideEffect&&a.kind!==W.userRejected&&a.kind!==W.policyDenied&&a.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:a,display:l,output:l,isError:a.kind!==W.success}),r.aborted||r.abortController.signal.aborted||a.kind!==W.userRejected||(ue=et(t.output));break}case"tool-error":{Ce.end(t.toolCallId);const o=this.registry.resolve(t.toolName),i=tt(t.error),n=(i===W.invalidInput?H(t.error):void 0)??et(t.error),a=r.pendingToolCalls.get(t.toolCallId)?.input??(p.isInstance(t.error)?t.error.toolInput:void 0),l=this.skillToolInputError(t.toolName,a)??F(i,n,{raw:t.error}),c=et(l);t.toolName===this.skillToolId&&r.canonicalToolOutputs.set(t.toolCallId,l.model);const u=G({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:a,result:l});this.persistToolExecution(u,r),!0===r.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&l.outcome.kind!==W.invalidInput&&(r.hadPotentialSideEffects=!0),r.pendingToolCalls.delete(t.toolCallId),s.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:u.id,...void 0===u.appOutput?{}:{appOutput:e(u.appOutput)},outcome:l.outcome,display:l.display,output:c,isError:!0});break}case"finish-step":{if(Ce.clear(),void 0!==g&&void 0!==le)break;const e=it(t.usage);void 0!==e.inputTokens&&(ne=e.inputTokens,$=L),me+=1,ae=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(re=o),s.push({type:"step-finish",finishReason:t.finishReason,usage:e});break}case"finish":!he&&pe.length>0&&(de+=pe,s.push({type:"text-delta",delta:pe}),pe=""),oe=it(t.totalUsage);break;case"error":if(Ce.clear(),this.isTurnAborted(r)||q(t.error)){r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,t.error);break}fe=ot(t.error),ce=t.error,ve=!0,le=Je(t.error);break;case"abort":Ce.clear(),r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(r)||q(e)?(r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e)):(fe=ot(e),ce=e,ve=!1,le=Je(e))}finally{r.abortController.signal.removeEventListener("abort",Ie),Ce.dispose(),this.clearDebugTimer(Te)}if(this.debug(s,"model","fullStream finished",m,{textChars:de.length}),void 0!==V){try{await Ze(se.steps,r.abortController.signal)}catch{}if(this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);if(r.pendingToolCalls.size>0)return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:"context_maintenance_unsettled_tools:输入已保存,请先核对未结算操作。"});const e=ct(Ke(r));this.messages.push(...e),e.length>0&&this.persistMessages(e,"raw_transcript"),Ye(r),b=this.messages.length,r.completedStepCount+=me,void 0!==J&&(U=void 0===U?J:rt(U,J),this.sessionUsage=rt(this.sessionUsage,J)),this.toolCoordinator.finishTurn();const i=V;if(e.length>0){if(r.completedStepCount>=this.maxSteps)return void s.push({type:"message-finish",text:de,stoppedAtStepLimit:!0,sessionUsage:{...this.sessionUsage},...void 0===U?{}:{totalUsage:U},...void 0===ne?{}:{contextInputTokens:ne}});s.push({type:"message-start",messageId:t()});continue}if("shape_changed"===i.reason)continue;if(w||!0!==this.compaction?.enabled)return void s.push({type:"error",stage:"plan",message:`context_request_budget_unrecoverable:输入和已完成操作已保留;当前请求未通过预算检查(${i.reason},估算输入 ${Math.ceil(i.budget.calibratedInputEstimate)},输入上限 ${i.budget.availableInputCeiling??"未知"},最近实测 ${i.budget.latestMeasuredInput??"未知"})。可继续发送较小的新要求或手动压缩。`});w=!0,this.requestBudgets.beginMaintenance(i.budget,r.inputId);const n=void 0===i.budget.maintenanceTarget?void 0:Math.max(1,.5*i.budget.maintenanceTarget-(i.budget.calibratedInputEstimate-i.budget.messageTokens));let a=!1;try{a=await this.runCompaction(s,"auto",r,!1,n,(e,t)=>o({history:e,explicitSkill:N,capabilityReminder:D,...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:y,project:e=>this.projectModelMessages(e),...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions}}).messages)}catch(e){if(this.isTurnAborted(r))throw e;this.debug(s,"compaction","summary failed; original context retained",m,{message:Je(e)})}if(k=a?void 0:i.budget,b=this.messages.length,this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,m);s.push({type:"message-start",messageId:t()});continue}if(void 0!==le&&this.isTurnAborted(r))return void this.persistCancelledTurn(s,r,b,m);if(void 0!==le&&!fe&&ve&&g?.isRecoverable(ce)&&void 0!==v&&!r.userRejected&&void 0===ue&&void 0===A.message){f=ce;try{await Ze(se.steps,r.abortController.signal)}catch(e){if(r.abortController.signal.throwIfAborted(),!h.isInstance(e)&&e!==ce)throw e}const e=ct(Ke(r)),t=new Map;for(const s of e)if("tool"===s.role)for(const e of s.content)"tool-result"===e.type&&t.set(e.toolCallId,(t.get(e.toolCallId)??0)+1);if([...this.uncoveredToolExecutions.values()].some(e=>{const s=t.get(e.toolCallId)??0;return t.set(e.toolCallId,s-1),0===s})||[...r.pendingToolCalls.values()].some(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence)))ve=!1,le="网络中断且操作结果尚未完整结算;已停止自动恢复,请先核对结果。";else{if(this.toolCoordinator.finishTurn(),e.length>0&&(this.persistMessages(e,"raw_transcript"),this.messages.push(...e)),Ye(r),b=this.messages.length,this.persistRecoveryCancellations(s,r),b=this.messages.length,r.completedStepCount+=me,void 0!==J&&(U=void 0===U?J:rt(U,J),this.sessionUsage=rt(this.sessionUsage,J)),r.completedStepCount>=this.maxSteps)return void s.push({type:"error",stage:"execute",message:"已达单轮最大工具步数;未完成的回复已丢弃,输入和已完成的操作已保留。"});const t=await v.attempt(ce,r.abortController.signal,e=>s.push({type:"model-recovery",attempt:e}));if(t.recovered){f=void 0;continue}ce=t.error,le=Je(t.error)}}if(void 0!==le){if(ve&&!fe&&(f=ce),ve&&!fe&&g?.formatError&&(le=g.formatError(ce)),fe&&void 0!==Y&&(R.add(Y.fingerprint),P=Y),this.messages.splice(b),fe){const e=0===de.length&&!he,t=e&&S<1,o=!(!t&&e)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(e&&o&&t){S+=1;continue}const i=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,j,de.length>0,m),void s.push({type:"error",stage:"execute",message:`${le}${i}`})}return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:le})}if(r.aborted||r.abortController.signal.aborted)return r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,b,m);let ke;this.debug(s,"model","awaiting response messages",m);const xe=this.scheduleDebug(s,"model","still awaiting response messages",m);try{const e=await se.steps;ke=He(r,e)}catch(e){if(this.clearDebugTimer(xe),this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,e),void this.persistCancelledTurn(s,r,b,m);const t=ot(e);if(t&&void 0!==Y&&(P=Y,R.add(Y.fingerprint)),this.messages.splice(b),t){const t=0===de.length&&!he,o=t&&S<1,i=!(!o&&t)&&await this.recoverFromContextError(s,r);if(this.isTurnAborted(r))return void this.persistCancelledRecoveryTurn(s,r,j,m);if(t&&i&&o){S+=1;continue}const n=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(s,r,j,de.length>0,m),void s.push({type:"error",stage:"execute",message:`${Je(e)}${n}`})}return this.persistFailedTurn(s,r,j,m),void s.push({type:"error",stage:"execute",message:Je(e)})}finally{this.clearDebugTimer(xe)}if(this.debug(s,"model","response messages ready",m,{responseMessages:ke.length}),this.isTurnAborted(r))return r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason),void this.persistCancelledTurn(s,r,b,m);const Se=ct(ke);this.messages.push(...Se);const we=ue??A.message;if(void 0!==we){const e=0===de.length?we:`\n${we}`;de+=e,s.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:we})}this.debug(s,"persist","persisting messages",m,{appendedMessages:this.messages.length-b}),this.persistMessages(this.messages.slice(b),"raw_transcript"),Ye(r),b=this.messages.length,this.debug(s,"persist","messages persisted",m,{totalMessages:this.messages.length}),oe&&(U=void 0===U?oe:rt(U,oe),this.sessionUsage=rt(this.sessionUsage,oe));const Me=ne;void 0!==Me&&(this.lastInputTokens=Me,this.measuredProjectedTokens=$??L,this.promptOverhead=Math.max(0,Me-this.measuredProjectedTokens-l)),r.completedStepCount+=me;const Ee=r.completedStepCount>=this.maxSteps&&"tool-calls"===ae;if(s.push({type:"message-finish",text:de,...void 0===U?{}:{totalUsage:U},sessionUsage:{...this.sessionUsage},...void 0!==ne?{contextInputTokens:ne}:{},...void 0!==re?{outputTokensPerSecond:re}:{},...Ee?{stoppedAtStepLimit:!0}:{}}),!r.pausedForContextPressure||"tool-calls"!==ae||Ee||void 0!==we)return;if(r.pausedForContextPressure=!1,this.debug(s,"compaction","turn paused for context pressure",m,{continuations:r.contextPressureContinuations,pressureTokens:this.contextPressureTokens()}),this.isTurnAborted(r))return void this.persistPausedTurnCancellation(s,r,m);s.push({type:"message-start",messageId:t()})}}catch(e){if(this.isTurnAborted(r)||q(e))return r.aborted=!0,r.cancellationReason=lt(r.cancellationReason,r.abortController.signal.reason??e),void(void 0!==b?this.persistCancelledTurn(s,r,b,m):this.emitCancellation(s,r));void 0!==b&&this.messages.splice(b),this.debug(s,"turn","error",m,{message:Je(e)}),s.push({type:"error",stage:"execute",message:Je(e)})}finally{this.requestBudgets.abandonMaintenance(r.inputId),void 0!==y&&clearTimeout(y),this.toolCoordinator.finishTurn();try{g?.onTurnEnd?.(this.isTurnAborted(r)?void 0:f)}finally{this.activeTurn===r&&(this.activeTurn=void 0),s.close()}}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)Xe(o)||(this.inMemoryTranscript.push({sequence:t,provenance:we[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=pe(e);this.messages.push(s);try{this.persistMessages([s],"recovery_evidence")}catch(e){throw this.messages.splice(t),e}}persistContextFailure(e,t,s,o,i){if(!this.persistPendingToolCancellationsOrReport(e,t,"上下文溢出工具状态持久化失败"))return;const n=t.toolExecutions.some(e=>e.outcome.kind!==W.policyDenied&&e.outcome.kind!==W.userRejected&&e.outcome.kind!==W.invalidInput&&(e.outcome.kind!==W.cancelled||e.outcome.executionState!==L.notExecuted)),r=["本轮因上下文窗口溢出而中断,未自动重放。"];o&&r.push("本轮已产生部分文本,持久历史仅保留此中断标记。"),n&&r.push("本轮已有操作开始执行,部分结果可能已经生效且不会自动撤销,请先检查实际结果。");const a=[...this.uncoveredToolExecutions.values()];this.appendInterruptedTurnMessages(e,t,i,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...0===a.length?[]:[pe(a)],{role:"assistant",content:r.join("")}],debugLabel:"persisting context-overflow marker",debugDetails:{hadToolActivity:n,producedText:o},failureLabel:"上下文溢出记录持久化失败"})}persistFailedTurn(e,t,s,o){if(this.closed)return;const i=Ge(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Ee(ct(Ke(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,de({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${Be}`}failedTurnDisplayMessage(e){const t=this.cancellationActivity(e);return`本轮因运行错误而中断,未自动重试。之前的对话和已完成进度会保留。${t.hadPotentialSideEffects?"部分操作可能已经生效且不会自动撤销,请先检查实际结果,再决定是否继续。":t.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"你可以继续输入或重试。"}`}appendInterruptedTurnMessages(e,t,s,o){if(t.pendingToolCalls.size>0)return e.push({type:"error",stage:"execute",message:`${o.failureLabel}: 存在未写入账本的待处理工具调用,已拒绝持久化中断记录`}),!1;this.messages.push(...o.messages),this.debug(e,"persist",o.debugLabel,s,{appendedMessages:this.messages.length-o.rollbackTo,...o.debugDetails});try{return this.persistMessages(this.messages.slice(o.rollbackTo),"recovery_evidence"),!0}catch(t){return this.messages.splice(o.rollbackTo),e.push({type:"error",stage:"execute",message:`${o.failureLabel}: ${Je(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+We,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{},...void 0!==e.fullDiff?{fullDiff:e.fullDiff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){const s=this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}});return s&&void 0!==this.activeTurn&&(this.activeTurn.userRejected=!0),s}getMessages(){return ue(he(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({...K(e),sequence:e.sequence}))}getToolExecution(e,t=!1){const s=this.getPersistedToolExecution?.(e),o=s??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();return!o||t?o:{...K(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getRequestBudgetState(){return this.requestBudgets.view()}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.onProviderOptionsChange?.(e),this.providerOptions=e}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.modelRecovery=e.modelRecovery,this.requestBudgets=new r,this.contextWindowSource=e.contextWindowSource,this.contextWindow=e.contextWindow,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,this.promptOverhead=void 0,void 0!==e.toolSchemaPolicy&&(this.toolSchemaPolicy=e.toolSchemaPolicy,this.applyToolSchemaPolicy()&&this.refreshCapabilityManifest())}modelTools(){if(0===this.excludedToolIds.size)return this.tools;const e=this.excludedToolIds;return Object.fromEntries(Object.entries(this.tools).filter(([t])=>!e.has(t)))}recordToolSchemaIssues(e){for(const[t,s]of Object.entries(e))this.agentToolSchemaIssues.set(t,s)}applyToolSchemaPolicy(){const e=this.toolSchemaPolicy,t=new Set;if(e)for(const[s,o]of this.agentToolSchemaIssues)e(o)||t.add(s);const s=this.excludedToolIds,o=t.size!==s.size||[...t].some(e=>!s.has(e));for(const e of t)if(!s.has(e)){const t=this.registry.resolve(e);this.onToolExcluded?.({toolId:e,agentName:t?.agentName??"",toolName:t?.toolName??e,issues:this.agentToolSchemaIssues.get(e)??[]})}return this.excludedToolIds=t,o}stopOnContextPressure(e,t,s,o=()=>!0){return({steps:i})=>{const n=this.compaction,r=i.at(-1);if(void 0===n||!n.enabled||void 0===this.contextWindow||void 0===r||"tool-calls"!==r.finishReason||i.length<2&&this.messages.length<2||r.toolResults.some(e=>z(e.output).kind===W.userRejected))return!1;const a=it(r.usage),l=Z(this.projectModelMessages([...this.messages,...He(e,i)])),c=s?.()??(void 0===a.inputTokens?this.promptOverheadTokens()+l:Math.max(0,a.inputTokens+l-t()));return!(c/this.contextWindow<n.threshold||!o(c))&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Z([{role:"user",content:e}]),s=Z(this.projectModelMessages(this.messages));return void 0!==this.lastInputTokens&&void 0!==this.measuredProjectedTokens?Math.max(0,this.lastInputTokens+s-this.measuredProjectedTokens+t):this.promptOverheadTokens()+s+t}observationResultId(e){if(this.observationResultIds.has(e))return this.observationResultIds.get(e);const t=this.listPersistedToolExecutions?.({toolCallId:e,limit:2})??[];t.length>1&&this.ambiguousObservationCallIds.add(e);const s=1===t.length?t[0]?.id:void 0;return this.observationResultIds.set(e,s),s}readObservation(e){const t=this.getPersistedToolExecution?.(e.resultId)??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e.resultId),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();if(!t)throw new Error("当前会话中没有这个工具结果");const s=[...this.observationRetentionByToolId].find(([e])=>{const s=this.registry.resolve(e);return s?.agentName===t.agentName&&s.toolName===t.toolName})?.[1];if(!s)throw new Error("该结果不是可回查的浏览器观察");return Oe(e,t,[...this.messages,...this.activeTurn?Ke(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return Ne(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(be(this.capabilityManifest,ge.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:ee(e))}currentCheckpointReminder(e){return void 0===this.compactionCheckpoint?void 0:ke(this.compactionCheckpoint,this.sessionManagerInstanceId,e)}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,Ge(t));t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,s,{rollbackTo:this.messages.length,messages:o,debugLabel:"persisting paused turn cancellation",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}compactionTargetTokens(e){const t=this.compaction;if(void 0===t||void 0===this.contextWindow)return;const s=void 0===e?0:Z([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages,t=e=>({...e,message:ne(e.message,this.getInputSkillCheckpoint?.(e.sequence)??this.inputSkillCheckpoints.get(e.sequence))});if(void 0===e)return this.inMemoryTranscript.map(t);const s=[];let o=-1;for(;;){const i=e({afterSequence:o,limit:500});s.push(...i.map(t));const n=i.at(-1)?.sequence;if(i.length<500||void 0===n||n<=o)break;o=n}return s}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,this.compactionTargetTokens())}catch(s){this.isTurnAborted(t)?this.emitCancellation(e,t):e.push({type:"error",stage:"plan",message:Je(s)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}async runCompaction(e,t,s,i,n,r){const a=Date.now(),l=this.lastInputTokens,c=this.compaction,u=c?.strategy??"summarize";e.push({type:"compaction-start",reason:t});const d=s=>(e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:0,kept:this.messages.length,...s?{failure:s}:"manual"===t?{recoveryNotice:"当前内容未产生可用的压缩,已保留原上下文。"}:{}}),!1);if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(!c)return d();try{const p=[...this.messages],h=this.compactionCheckpoint,m=be(this.capabilityManifest,ge.transcriptRead),g=void 0===h?void 0:3===h.version?h.taskSummary:ke(h,this.sessionManagerInstanceId,m),v=await X({messages:p,strategy:u,keepRecentTurns:c.keepRecentTurns,keepRecentTokens:c.keepRecentTokens,model:this.model,...void 0===g?{}:{previousSummary:g},...void 0===n?{}:{targetTokens:n},...void 0===this.contextWindow?{}:{contextWindow:this.contextWindow},...void 0===c.timeoutMs?{}:{timeoutMs:c.timeoutMs},...void 0===c.maxOutputTokens?{}:{maxOutputTokens:c.maxOutputTokens},...void 0===this.structuredOutputReasoning?{}:{structuredOutputReasoning:this.structuredOutputReasoning},...void 0===this.structuredOutputProviderOptions?{}:{structuredOutputProviderOptions:this.structuredOutputProviderOptions},...void 0===s?{}:{abortSignal:s.abortController.signal}});if(this.isTurnAborted(s))return i&&s&&this.emitCancellation(e,s),d();if(0===v.removed)return d();const f=v.summary??("truncate"===u?g??"Earlier messages were archived. Consult the original transcript for historical details.":void 0);if(void 0===f||0===f.trim().length)return d();if(Ee(v.messages).status===Me.repaired)return d();const b=this.currentCheckpointReminder(m),y=(e,t)=>void 0===r?this.requestBudgets.projectedMessageTokens(o({history:e,explicitSkill:{skillNames:[],userPrompt:"",modelUserContent:""},capabilityReminder:"",...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:this.modelTools(),project:e=>this.projectModelMessages(e)}).messages):this.requestBudgets.projectedMessageTokens(r(e,t)),T=y(p,b),C=new Error("compaction_candidate_did_not_shrink");let I=T;const k=e=>{const t=ke(e,this.sessionManagerInstanceId,m);if(I=y(v.messages,t),I>=T)throw C};let x;try{if(this.commitPersistedCompaction)x=this.commitPersistedCompaction({messages:v.messages,expectedActiveMessages:p,expectedLatestCheckpointId:h?.id,summary:f,validateCheckpoint:k});else{const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=Se({summary:f,generation:(h?.generation??0)+1,...h?{previousCheckpointId:h.id}:{},transcript:{messages:{fromSequenceExclusive:-1,throughSequence:e.at(-1)?.sequence??h?.transcript.messages.throughSequence??-1},toolExecutions:{fromSequenceExclusive:-1,throughSequence:t.at(-1)?.sequence??h?.transcript.toolExecutions.throughSequence??-1},completeness:h?.transcript.completeness??"complete"},toolState:xe(e.map(e=>e.message),t)});k(s),this.onReplace?.(v.messages),x=s}}catch(e){if(e===C)return d();throw e}return this.messages.splice(0,this.messages.length,...v.messages),this.compactionCheckpoint=x,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:v.removed,kept:v.kept,checkpointId:x.id,checkpointGeneration:x.generation,checkpointSummaryStatus:"summarize"===u?"valid":"skipped"}),this.debug(e,"compaction","task summary committed",a,{removed:v.removed,kept:v.kept,beforeEstimatedTokens:T,afterEstimatedTokens:I}),!0}catch(e){throw d(this.isTurnAborted(s)?void 0:e instanceof Q?{reason:m.timeout,timeoutMs:e.timeoutMs}:{reason:m.error}),e}}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(s){return this.isTurnAborted(t)||e.push({type:"error",stage:"plan",message:Je(s)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!E(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${Je(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=O.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(P))}currentCancellationActivity(e){const t=this.activeExecSessionIds(e),s=[...e.pendingToolCalls.values()].filter(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence));return{execSessionIds:t,hadCompletedProgress:e.toolExecutions.length>0||e.completedStepResponses.size>0,hadInFlightWork:s.length>0||t.length>0,hadPotentialSideEffects:e.hadPotentialSideEffects||s.some(e=>e.potentialSideEffect)}}captureCancellationActivity(e){e.cancellationActivity??=this.currentCancellationActivity(e)}cancellationActivity(e){return e.cancellationActivity??this.currentCancellationActivity(e)}cancellationDisplayMessage(e){const t=e.cancellationReason??O.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const o=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。",i=e.userMessagePersisted?"本轮输入已保存,但进度或中断记录未能保存。":"刚才的对话和进度未能保存。";return t===O.timeout?`本轮等待时间过长,已自动停止。${i}${o}`:t===O.runtime?`本轮因运行异常而中断。${i}${o}`:`已停止本轮。${i}${o}`}const o=s.execSessionIds,i=be(this.capabilityManifest,ge.sessionList);switch(t){case O.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case O.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":ye(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case O.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??O.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=be(this.capabilityManifest,ge.sessionList),n=Be;switch(t){case O.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case O.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:ye(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case O.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=O.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,Fe.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Fe.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s);const n=i===Fe.keepRaw,r=n?Ee(ct(Ke(t))).messages:[],a=n?Ge(t):Ve(t);t.cancellationPersisted=!0;const l=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...l],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[de({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),j(this.cancellationDisplayMessage(e),e.cancellationReason??O.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(e,t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${Je(t)}`}),!1}}persistRecoveryCancellations(e,t){const s=[];for(const o of t.pendingToolCalls.values()){const i=D({kind:W.cancelled,reason:O.runtime,executionState:L.notExecuted},"模型连接中断,本工具调用确定未执行;重新生成的调用仍需正常校验与审批。"),n=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:i});this.persistToolExecution(n,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:n.id,outcome:i.outcome,display:i.display,output:i.display,isError:!0});const r=`${o.agentName}__${o.toolName}`;s.push({role:"assistant",content:[{type:"tool-call",toolCallId:o.toolCallId,toolName:r,input:o.input}]},{role:"tool",content:[{type:"tool-result",toolCallId:o.toolCallId,toolName:r,output:i.model}]}),t.pendingToolCalls.delete(o.toolCallId)}s.length>0&&(this.persistMessages(s,"raw_transcript"),this.messages.push(...s))}persistPendingToolCancellations(e,t){const s=t.cancellationReason??O.runtime;for(const o of t.pendingToolCalls.values()){const i=this.toolCoordinator.hasExecutionStarted(o.executionOccurrence)?L.outcomeUnknown:L.notExecuted,n=i===L.notExecuted?`工具调用在开始执行前因本轮 ${s} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${s} 中断而取消;最终结果尚未确认`,r=D({kind:W.cancelled,reason:s,executionState:i},n,{raw:{cancellationReason:s,executionState:i,abortReason:Je(t.abortController.signal.reason)}}),a=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:r});this.persistToolExecution(a,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:r.display,isError:!0}),t.pendingToolCalls.delete(o.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=O.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(N),!0)}close(){if(void 0!==this.closePromise)return this.closePromise;this.closed=!0;const e=this.activeTurn;return e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=O.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(P)),this.closePromise=(async()=>{const e=(this.sessionManager?.close()??Promise.resolve([])).then(e=>{for(const t of e)void 0!==t.cleanupError&&process.stderr.write(`roll chat: 后台会话 ${String(t.sessionId)} 清理失败: ${t.cleanupError}\n`)},e=>{process.stderr.write(`roll chat: 会话 ${this.id} 后台清理失败: ${Je(e)}\n`)});await s(e,Le)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Le)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${Je(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${Je(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
|
|
1
|
+
import{describeAppOutput as e}from"@roll-agent/protocol";import{randomUUID as t}from"node:crypto";import{buildSessionModelRequest as s}from"./model-request.js";import{ModelRecoveryBudget as o}from"./model-recovery.js";import{ContextMaintenanceRequired as i,RequestBudgetTracker as n}from"./request-budget.js";import{buildUserMessageContent as r,normalizeSessionSendInput as a}from"./session-attachments.js";import{stepCountIs as l,streamText as c,wrapLanguageModel as u,InvalidToolInputError as d,NoOutputGeneratedError as p}from"ai";import{InvalidResponseDataError as h,JSONParseError as m,TypeValidationError as g}from"@ai-sdk/provider";import{COMPACTION_FAILURE_REASONS as v}from"../types/events.js";import{buildAgentToolset as f}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as b}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as y,skillInputErrorResult as T}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as C}from"../tool-bridge/schedule-tool.js";import{createInvalidScheduleRetryGuard as I}from"../tool-bridge/invalid-schedule-retry.js";import{buildFileToolset as k}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as x}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as S,EXEC_LIST_NAME as w,EXEC_POLL_NAME as E,buildSessionExecToolset as M}from"../tool-bridge/session-exec-tool.js";import{SessionManager as R}from"../bash/session/session-manager.js";import{isTerminalSessionState as P}from"../bash/session/types.js";import{withCleanEnv as O}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as A,SESSION_CANCELLATION_REASONS as N,TURN_TIMEOUT_ABORT_REASON as j,USER_CANCELLATION_ABORT_REASON as q,createTurnCancellationMessage as $,isTurnTimeoutAbortReason as L}from"../types/cancellation.js";import{ToolRegistry as W}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as D,TOOL_OUTCOME_KINDS as F,createToolResult as B,failedToolResult as _,isNormalizedToolResult as U,normalizeToolResult as z,readDisplayOutput as J,readToolOutcome as H}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as V}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as G,toRedactedToolExecutionRecordSummary as K}from"../tool-bridge/tool-execution-record.js";import{ToolExecutionCoordinator as Y}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as Q}from"../approval/approval-gate.js";import{SessionApprovalMemory as X}from"../approval/approval-memory.js";import{CompactionTimeoutError as Z,compactMessages as ee,estimateMessagesTokens as te,estimateTextTokens as se,isCompactionSummaryAcknowledgement as oe,readCompactionSummaryPayload as ie}from"./compactor.js";import{AsyncEventQueue as ne}from"./event-queue.js";import{ToolInputActivityTracker as re}from"./tool-input-activity.js";import{projectTurnInputSkillCheckpoint as ae,turnInputSkillCheckpointSchema as le}from"../store/turn-input.js";import{attachExplicitSkillCheckpoint as ce,prepareExplicitSkillContext as ue,readExplicitSkillCheckpoint as de,stripExplicitSkillCheckpoints as pe}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as he,createToolLedgerGapRecoveryMessage as me,stripCancelledTurnRecoveryMessages as ge}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as ve,CAPABILITY_TOOL_ROLES as fe,buildEffectiveCapabilityTurnContext as be,buildEffectiveCapabilityManifest as ye,findCapabilityToolId as Te,isProcessBoundHostMode as Ce}from"./capability-manifest.js";import{buildCapabilityTurnReminder as Ie,buildChatSystemPromptFromManifest as ke}from"./system-prompt.js";import{threadDerivedFromSchema as xe}from"../store/thread-origin.js";import{buildCompactionCheckpointReminder as Se,buildCompactionToolState as we,createSummaryCheckpoint as Ee,TRANSCRIPT_MESSAGE_PROVENANCES as Me}from"./compaction-checkpoint.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as Re,repairActiveToolProtocol as Pe}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Oe}from"../tool-bridge/transcript-tool.js";import{buildObservationRecallToolset as Ae}from"../tool-bridge/observation-recall-tool.js";import{readObservationPage as Ne}from"./observation-readback.js";import{canonicalObservationOutput as je,projectObservationMessages as qe,restoreCanonicalObservationOutputs as $e}from"./observation-projection.js";import{UserInputInteractionManager as Le}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as We}from"../tool-bridge/user-input-tool.js";const De=3e5,Fe=1,Be={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},_e="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Ue="AI_InvalidToolInputError:";function ze(){return{inputId:t(),abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,canonicalToolOutputs:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0,userRejected:!1}}function Je(e,t){const s=`${t.callId}:${String(t.stepNumber)}`,o=e.completedStepResponses.get(s);if(o)return[...o];const i=$e(t.response.messages,e.canonicalToolOutputs);return e.completedStepResponses.set(s,i),i}function He(e,t){return t.flatMap(t=>e.completedStepResponses.get(`${t.callId}:${String(t.stepNumber)}`)??$e(t.response.messages,e.canonicalToolOutputs))}function Ve(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function Ge(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ke(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function Ye(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function Qe(e){const t=new Set;for(;e instanceof Error&&!t.has(e);){if(g.isInstance(e)||h.isInstance(e)||m.isInstance(e))return e;t.add(e),e=e.cause}}function Xe(e){const t=Qe(e);if(t)return m.isInstance(t)?"模型调用返回了无效的 JSON。":"模型调用的数据未通过格式校验。"}function Ze(e){if(e instanceof Error){const t=Qe(e);return t===e?"数据格式无效。":t?.message?e.message.replaceAll(t.message,"数据格式无效。"):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=et(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function et(e){try{return JSON.stringify(e)??void 0}catch{return}}function tt(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==ie(e.content)||"assistant"===e.role&&oe(e.content)}function st(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 ot(e){return Ze(J(e))}function it(e){return d.isInstance(e)||"string"==typeof e&&e.startsWith(Ue)?F.invalidInput:F.toolFailed}function nt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>H(e.output).kind===F.userRejected)??!1}function rt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(Xe(e)??Ze(e))}function at(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 lt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function ct(e,t){const s=lt(e.cachedInputTokens,t.cachedInputTokens),o=lt(e.cacheWriteTokens,t.cacheWriteTokens),i=lt(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 ut(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function dt(e,t){return void 0!==e?e:L(t)?N.timeout:N.runtime}function pt(e){return e.flatMap(e=>{if("assistant"!==e.role||!Array.isArray(e.content))return[e];const t=e.content.filter(e=>"reasoning"!==e.type);return 0===t.length?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function ht(e,t,s){for(const o of Object.keys(t))e[o]=s}function mt(e,t,s){const o={[S]:fe.sessionCommand,[E]:fe.sessionPoll,[w]:fe.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;resolveReasoningPresentation;modelRecovery;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];contextWindow;compaction;turnTimeoutMs;onClose;onBeforeTurn;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;derivedFrom;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillExecutionLibrary;skillToolId;refreshSkillLibrary;toolSourceAgentNames;toolSchemaPolicy;onToolExcluded;agentToolSchemaIssues=new Map;excludedToolIds=new Set;gate=new Q;userInputInteractions=new Le;onAcceptInput;onRecordInputSkillCheckpoint;getInputSkillCheckpoint;inputSkillCheckpoints=new Map;toolCoordinator=new Y;tools;registry;observationRecallToolId;observationRetentionByToolId=new Map;observationResultIds=new Map;ambiguousObservationCallIds=new Set;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;executionJobs=new Set;closeBarriers=new Set;executionFailure;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;measuredProjectedTokens;promptOverhead;requestBudgets=new n;contextWindowSource;constructor(e){this.id=e.id,this.model=e.model,this.resolveReasoningPresentation=e.resolveReasoningPresentation,this.modelRecovery=e.modelRecovery,this.contextWindowSource=e.contextWindowSource,this.maxSteps=e.maxSteps;const t=e.initialMessages?pt(e.initialMessages):[];this.messages=[...Pe(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)tt(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Me[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.onBeforeTurn=e.onBeforeTurn,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.derivedFrom=void 0===e.derivedFrom?void 0:xe.parse(e.derivedFrom),this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillExecutionLibrary=e.skillLibrary,this.refreshSkillLibrary=e.refreshSkillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName)),this.toolSchemaPolicy=e.toolSchemaPolicy,this.onToolExcluded=e.onToolExcluded;const o=new W,i={},n=We({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,ht(i,n.tools,fe.userInput);const r=e.readCheckpointTranscript?Oe(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};ht(i,r,fe.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};ht(i,a,fe.skill);const l=new X,c=e.fileTools?k(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:l}):void 0;c&&(ht(i,c.readTools,fe.fileRead),ht(i,c.editTools,fe.fileEdit),ht(i,c.verifyTools,fe.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?x(e.bash,o,u,d):{};ht(i,p,fe.shell),e.bashSession&&(this.sessionManager=new R({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:O(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const h=e.bashSession&&this.sessionManager?M({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)}):{};mt(i,h,o);const m=e.agentInstall,g=m?b({catalog:m.catalog,install:async(e,t)=>{const s=await m.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};ht(i,g,fe.agentInstall);const v=e.schedules?C(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},extendTools:{},listTools:{}};ht(i,v.createTools,fe.scheduleCreate),ht(i,v.extendTools,fe.scheduleExtend),ht(i,v.listTools,fe.scheduleList);const y=f(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);ht(i,y.tools,fe.agent);const T=y.observationRetentionByToolId.size>0?Ae(e=>this.readObservation(e),o,this.toolCoordinator,`thread:${this.id}:observation`):{};this.observationRecallToolId=Object.keys(T)[0],ht(i,T,fe.observationRead),this.tools={...r,...T,...a,...c?{...c.readTools,...c.editTools,...c.verifyTools}:{},...p,...h,...g,...v.createTools,...v.extendTools,...v.listTools,...y.tools},this.registry=y.registry;for(const[e,t]of y.observationRetentionByToolId)this.observationRetentionByToolId.set(e,t);this.toolRoles=i,this.recordToolSchemaIssues(y.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 ye({tools:this.modelTools(),toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??ve.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=ke(this.capabilityManifest,{...void 0!==this.derivedFrom?{derivedFrom:this.derivedFrom}:{},...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){const t=y(()=>{if(!this.skillExecutionLibrary)throw new Error("skill library 不可用");return this.skillExecutionLibrary},e,this.toolCoordinator,{...void 0===this.skillToolId?{}:{toolId:this.skillToolId},names:this.skillSummaries.map(e=>e.name)});return this.skillToolId??=Object.keys(t)[0],t}applySkillLibrary(e){const t=e?.list()??[],s=t.length!==this.skillSummaries.length||t.some((e,t)=>e.name!==this.skillSummaries[t]?.name),o=JSON.stringify(t)!==JSON.stringify(this.skillSummaries);if(this.skillLibrary=e,this.skillSummaries=t,s){if(void 0!==this.skillToolId){const e={...this.tools};delete e[this.skillToolId],delete this.toolRoles[this.skillToolId],this.tools=e}const e=this.buildSkillTools(this.registry);ht(this.toolRoles,e,fe.skill),this.tools={...this.tools,...e}}o&&this.refreshCapabilityManifest()}async refreshSkills(e){if(void 0!==this.refreshSkillLibrary){const t=await st(this.refreshSkillLibrary(e),e);e.throwIfAborted(),this.applySkillLibrary(t)}this.skillExecutionLibrary=this.skillLibrary}skillToolInputError(e,t){return e===this.skillToolId&&void 0!==this.skillExecutionLibrary?T(this.skillExecutionLibrary,t):void 0}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=f([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);ht(this.toolRoles,t.tools,fe.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=Ae(e=>this.readObservation(e),this.registry,this.toolCoordinator,`thread:${this.id}:observation`);this.observationRecallToolId=Object.keys(e)[0],ht(this.toolRoles,e,fe.observationRead),this.tools={...this.tools,...e}}this.recordToolSchemaIssues(t.schemaIssuesByToolId),this.applyToolSchemaPolicy(),this.toolSourceAgentNames.add(e.source.agentName)}e.skillLibrary&&this.applySkillLibrary(e.skillLibrary),e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");this.onBeforeTurn?.();const t=a(e),s=new ne;this.emit=e=>s.push(e);const o=ze();this.activeTurn=o,this.trackExecution(this.runTurn(s,o,t).catch(e=>{this.executionFailure=e,s.push({type:"error",stage:"execute",message:Ze(e)}),s.close()}));try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");this.onBeforeTurn?.();const t=new ne;this.emit=e=>t.push(e);const s=ze();this.activeTurn=s,this.trackExecution(this.runCompactionTurn(t,s,e).catch(e=>{this.executionFailure=e,t.push({type:"error",stage:"plan",message:Ze(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(n,a,h){const m=Date.now(),g=this.modelRecovery,v=void 0===g?void 0:new o(g);let f,b,y;const T=()=>{a.abortController.signal.aborted||(this.captureCancellationActivity(a),a.aborted=!0,a.cancellationReason=N.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),a.abortController.abort(j))},C=r(h.text,h.attachments);try{g?.onTurnStart?.();const o={role:"user",content:C};let r;try{void 0!==this.onAcceptInput?r=this.onAcceptInput(a.inputId,o).transcriptSequence:(r=(this.listCompactionTranscriptEvidence().at(-1)?.sequence??-1)+1,this.onPersist?.([o])),this.recordPersistedMessagesInMemory([o]),this.messages.push(o),a.userMessagePersisted=!0,b=this.messages.length}catch(e){return void n.push({type:"error",stage:"plan",message:`输入持久化失败,未开始模型请求: ${Ze(e)}`})}if(void 0!==this.turnTimeoutMs){const e=Math.max(0,this.turnTimeoutMs-(Date.now()-m));a.expiresAt=new Date(m+this.turnTimeoutMs).toISOString(),y=setTimeout(T,e),0===e&&T()}this.debug(n,"turn","start",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,maxSteps:this.maxSteps,...h.attachments.length>0?{attachments:h.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(e){return void n.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${Ze(e)}`})}if(b=this.messages.length,this.isTurnAborted(a))return void this.persistCancelledTurn(n,a,b,m);this.syncWorkspaceInstructions(),await this.refreshSkills(a.abortController.signal);let k,x=!0,S=0,w=!1;const E=()=>Math.max(1024,.05*(this.contextWindow??0)),M=e=>void 0===k||e>=k.calibratedInputEstimate+E(),R=new Set;let P;const O=I(),A=ue({rawInput:h.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary});void 0!==a.expiresAt&&Date.now()>=Date.parse(a.expiresAt)&&T();const j=o;if(A.skillNames.length>0&&!this.isTurnAborted(a)){const e=de(ce(o,A));if(void 0===e)throw new Error("Explicit Skill checkpoint could not be created");this.onRecordInputSkillCheckpoint?.(a.inputId,e),this.inputSkillCheckpoints.set(r,le.parse(e))}if(b=this.messages.length,this.isTurnAborted(a))return void this.persistCancelledTurn(n,a,b,m);n.push({type:"message-start",messageId:t()});let q={};try{q=await st(this.resolveDynamicCapabilityContext?.(a.abortController.signal)??{},a.abortController.signal)??{}}catch(e){if(this.isTurnAborted(a))return b=this.messages.length,a.cancellationReason=dt(a.cancellationReason,a.abortController.signal.reason??e),void this.persistCancelledTurn(n,a,b,m);this.debug(n,"turn","dynamic capability context unavailable",m,{message:Ze(e)})}const $=be(this.capabilityManifest,{explicitSkillNames:A.skillNames,...q.ruleIds?{ruleIds:q.ruleIds}:{},...q.vcs?{vcs:q.vcs}:{},...q.origin?{origin:q.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=$;const W=Ie($);let D;for(;;){b=this.messages.length,a.pausedForContextPressure=!1;const o=Te(this.capabilityManifest,fe.transcriptRead),r=this.currentCheckpointReminder(o),h=void 0===r?0:se(r),y=this.modelTools(),T=(e=[])=>s({history:this.messages,completedMessages:e,explicitSkill:A,capabilityReminder:W,...void 0===r?{}:{checkpointReminder:r},system:this.systemPrompt,tools:y,...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions},project:e=>this.projectModelMessages(e)}),C=T();let I=C.shapeContext;this.debug(n,"model","calling streamText",m,{messages:this.messages.length,tools:Object.keys(this.modelTools()).length,contextRecoveryAttempts:S,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let q,$=0,B=0;const J=[];let H,K,Y,Q=!1;const X=u({model:this.model,middleware:{specificationVersion:"v4",wrapStream:async({params:e,doStream:t})=>{if(a.abortController.signal.aborted)throw a.abortController.signal.reason;const s=this.requestBudgets.prepare(e,{provider:this.model.provider,model:this.model.modelId,...void 0===this.contextWindow?{}:{window:this.contextWindow},...void 0===this.contextWindowSource?{}:{windowSource:this.contextWindowSource},threshold:this.compaction?.threshold??.75},I,a.inputId),o=s.maintenanceTarget,n=this.modelTools(),r=Object.keys(n).length!==Object.keys(y).length||Object.entries(y).some(([e,t])=>n[e]!==t),l=void 0!==s.availableInputCeiling&&s.calibratedInputEstimate>s.availableInputCeiling,c=!w&&!0===this.compaction?.enabled&&void 0!==o&&s.calibratedInputEstimate>=o&&(M(s.calibratedInputEstimate)||void 0!==k&&(s.shapeFingerprint!==k.shapeFingerprint||s.rawInputEstimate>=k.rawInputEstimate+E())),u=R.has(s.fingerprint)||void 0!==P&&s.rawInputEstimate>=P.rawInputEstimate;if(r||l||c||u)throw r&&(x=!0),H=new i(s,r?"shape_changed":u?"provider_rejected":l?"budget":"soft_target"),H;w=!1,K=s,this.requestBudgets.dispatchedRequest(),Q=!1;const d=await t();if(void 0===g)return d;const p=d.stream.getReader();let h=!1;return{...d,stream:new ReadableStream({async pull(e){let t;try{t=await p.read()}catch(t){return Q=!1,e.enqueue({type:"error",error:t}),e.close(),void p.releaseLock()}if(t.done)return e.close(),void p.releaseLock();const s=t.value;if("finish"!==s.type||!h){if("finish"===s.type&&"error"===s.finishReason.unified)return h=!0,Q=!1,void e.enqueue({type:"error",error:new Error("模型未成功完成本步骤,未执行待处理工具。")});"finish"===s.type&&(Q=!0),"error"===s.type&&(Q=!1,h=!0),e.enqueue(s)}},async cancel(e){try{await p.cancel(e)}finally{p.releaseLock()}}})}}}}),Z=this.providerOptions,ee=this.resolveReasoningPresentation?.(this.model,Z),oe=()=>c({model:X,...ee?{include:{rawChunks:!0}}:{},...void 0===g?{}:{maxRetries:0},system:C.system,messages:C.messages,tools:y,prepareStep:async()=>{x||await this.refreshSkills(a.abortController.signal),x=!1,$=te(this.projectModelMessages([...this.messages,...J]));const e=T(J);return I=e.shapeContext,B=this.requestBudgets.projectedMessageTokens(e.messages),{messages:e.messages,system:e.system}},stopWhen:[()=>void 0!==g&&!Q,l(Math.max(1,this.maxSteps-a.completedStepCount)),nt(),O.stop,this.stopOnContextPressure(a,()=>$,()=>this.requestBudgets.predict(T(J).messages,B),M)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(a,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t,usage:s,finishReason:o})=>{if(void 0===g||"error"!==o){for(const e of t){if("tool-call"!==e.type||!("invalid"in e)||!0!==e.invalid)continue;const t=this.skillToolInputError(e.toolName,e.input);void 0!==t&&a.canonicalToolOutputs.set(e.toolCallId,t.model)}Y=ct(Y??{},at(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:a.abortController.signal,...Z?{providerOptions:Z}:{},onError:()=>{},onStepEnd:e=>{(void 0===g||Q)&&J.push(...Je(a,e))},onAbort:({steps:e})=>{if(void 0===g)for(const t of e)Je(a,t)}});let ie;try{ie=oe()}catch(e){if(this.isTurnAborted(a)||L(e))return a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,e),void this.persistCancelledTurn(n,a,b,m);if(!rt(e))throw e;this.messages.splice(b);const t=S<1,s=!!t&&await this.recoverFromContextError(n,a);if(this.isTurnAborted(a))return void this.persistCancelledRecoveryTurn(n,a,j,m);if(s&&t){S+=1;continue}return this.persistContextFailure(n,a,j,!1,m),void n.push({type:"error",stage:"execute",message:Ze(e)})}this.debug(n,"model","streamText returned",m);let ne,ae,le,ce,ue,de,pe,he="",me="",ge=!1,ve=0,be=!1,ye=!1,Ce=!1;const Ie=this.scheduleDebug(n,"model","waiting for first stream event",m,{messages:this.messages.length}),ke=new re(e=>{const t=this.registry.resolve(e);return void 0===t?void 0:`${t.agentName}.${t.toolName}`},e=>n.push(e)),xe=()=>ke.clear();a.abortController.signal.addEventListener("abort",xe,{once:!0});try{let t,s=0;for await(const o of ie.fullStream){if(this.closed){a.aborted=!0,a.cancellationReason??=N.runtime;break}switch(Ce||(Ce=!0,this.clearDebugTimer(Ie),this.debug(n,"model","first stream event",m,{part:o.type})),o.type){case"start-step":t=void 0,void 0!==g&&n.push({type:"model-step-start"});break;case"tool-input-start":ke.start(o.id,o.toolName);break;case"tool-input-delta":ke.delta(o.id);break;case"tool-input-end":ke.end(o.id);break;case"raw":t=ee?.readDeltas(o.rawValue),s=0;break;case"reasoning-start":n.push({type:"reasoning-start",reasoningId:o.id});break;case"reasoning-delta":{const e=t?.[s]===o.text?ee?.kind:void 0;e?s++:t=void 0,n.push({type:"reasoning-delta",reasoningId:o.id,delta:o.text,...e?{presentation:e}:{}});break}case"reasoning-end":n.push({type:"reasoning-end",reasoningId:o.id});break;case"text-delta":if(!ge){const e=me+o.text;if(ut(e,A.userPrompt)){me=e;break}if(me.length>0){const e=me+o.text;me="",he+=e,n.push({type:"text-delta",delta:e});break}}he+=o.text,n.push({type:"text-delta",delta:o.text});break;case"tool-call":{ke.end(o.toolCallId),ge=!0,me="";const e=this.trackPendingToolCall(a,o.toolCallId,o.toolName,o.input,this.toolCoordinator.describeResources(o.toolName,o.input));n.push({type:"tool-call",toolCallId:o.toolCallId,agentName:e.agentName,toolName:e.toolName,input:o.input});break}case"tool-result":{const t=this.registry.resolve(o.toolName),s=a.pendingToolCalls.get(o.toolCallId),i=U(o.output)?o.output:z(o.output),r=i.outcome,l=i.display,c=G({toolCallId:o.toolCallId,agentName:t?.agentName??o.toolName,toolName:t?.toolName??o.toolName,input:s?.input,result:i});this.persistToolExecution(c,a);const u=r.kind===F.success?je(i.raw,this.observationRetentionByToolId.get(o.toolName)):void 0;if(u){a.canonicalToolOutputs.set(o.toolCallId,u);const e=this.observationResultIds.get(o.toolCallId);void 0!==e&&e!==c.id&&this.ambiguousObservationCallIds.add(o.toolCallId),this.observationResultIds.set(o.toolCallId,this.ambiguousObservationCallIds.has(o.toolCallId)?void 0:c.id)}!0===s?.potentialSideEffect&&r.kind!==F.userRejected&&r.kind!==F.policyDenied&&r.kind!==F.invalidInput&&(a.hadPotentialSideEffects=!0),a.pendingToolCalls.delete(o.toolCallId),n.push({type:"tool-result",toolCallId:o.toolCallId,agentName:t?.agentName??o.toolName,toolName:t?.toolName??o.toolName,executionId:c.id,...void 0===c.appOutput?{}:{appOutput:e(c.appOutput)},outcome:r,display:l,output:l,isError:r.kind!==F.success}),a.aborted||a.abortController.signal.aborted||r.kind!==F.userRejected||(pe=ot(o.output));break}case"tool-error":{ke.end(o.toolCallId);const t=this.registry.resolve(o.toolName),s=it(o.error),i=(s===F.invalidInput?V(o.error):void 0)??ot(o.error),r=a.pendingToolCalls.get(o.toolCallId)?.input??(d.isInstance(o.error)?o.error.toolInput:void 0),l=this.skillToolInputError(o.toolName,r)??_(s,i,{raw:o.error}),c=ot(l);o.toolName===this.skillToolId&&a.canonicalToolOutputs.set(o.toolCallId,l.model);const u=G({toolCallId:o.toolCallId,agentName:t?.agentName??o.toolName,toolName:t?.toolName??o.toolName,input:r,result:l});this.persistToolExecution(u,a),!0===a.pendingToolCalls.get(o.toolCallId)?.potentialSideEffect&&l.outcome.kind!==F.invalidInput&&(a.hadPotentialSideEffects=!0),a.pendingToolCalls.delete(o.toolCallId),n.push({type:"tool-result",toolCallId:o.toolCallId,agentName:t?.agentName??o.toolName,toolName:t?.toolName??o.toolName,executionId:u.id,...void 0===u.appOutput?{}:{appOutput:e(u.appOutput)},outcome:l.outcome,display:l.display,output:c,isError:!0});break}case"finish-step":{if(ke.clear(),void 0!==g&&void 0!==ue)break;const e=at(o.usage);void 0!==e.inputTokens&&(ae=e.inputTokens,q=$),ve+=1,ce=o.finishReason;const t=o.performance.outputTokensPerSecond??o.performance.effectiveOutputTokensPerSecond;void 0!==t&&Number.isFinite(t)&&(le=t),n.push({type:"step-finish",finishReason:o.finishReason,usage:e});break}case"finish":!ge&&me.length>0&&(he+=me,n.push({type:"text-delta",delta:me}),me=""),ne=at(o.totalUsage);break;case"error":if(ke.clear(),this.isTurnAborted(a)||L(o.error)){a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,o.error);break}ye=rt(o.error),de=o.error,be=!0,ue=Xe(o.error)??Ze(o.error);break;case"abort":ke.clear(),a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,o.reason)}}}catch(e){this.isTurnAborted(a)||L(e)?(a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,e)):(ye=rt(e),de=e,be=!1,ue=Ze(e))}finally{a.abortController.signal.removeEventListener("abort",xe),ke.dispose(),this.clearDebugTimer(Ie)}if(this.debug(n,"model","fullStream finished",m,{textChars:he.length}),void 0!==H){try{await st(ie.steps,a.abortController.signal)}catch{}if(this.isTurnAborted(a))return void this.persistCancelledTurn(n,a,b,m);if(a.pendingToolCalls.size>0)return this.persistFailedTurn(n,a,j,m),void n.push({type:"error",stage:"execute",message:"context_maintenance_unsettled_tools:输入已保存,请先核对未结算操作。"});const e=pt(Ge(a));this.messages.push(...e),e.length>0&&this.persistMessages(e,"raw_transcript"),Ye(a),b=this.messages.length,a.completedStepCount+=ve,void 0!==Y&&(D=void 0===D?Y:ct(D,Y),this.sessionUsage=ct(this.sessionUsage,Y)),this.toolCoordinator.finishTurn();const o=H;if(e.length>0){if(a.completedStepCount>=this.maxSteps)return void n.push({type:"message-finish",text:he,stoppedAtStepLimit:!0,sessionUsage:{...this.sessionUsage},...void 0===D?{}:{totalUsage:D},...void 0===ae?{}:{contextInputTokens:ae}});n.push({type:"message-start",messageId:t()});continue}if("shape_changed"===o.reason)continue;if(w||!0!==this.compaction?.enabled)return void n.push({type:"error",stage:"plan",message:`context_request_budget_unrecoverable:输入和已完成操作已保留;当前请求未通过预算检查(${o.reason},估算输入 ${Math.ceil(o.budget.calibratedInputEstimate)},输入上限 ${o.budget.availableInputCeiling??"未知"},最近实测 ${o.budget.latestMeasuredInput??"未知"})。可继续发送较小的新要求或手动压缩。`});w=!0,this.requestBudgets.beginMaintenance(o.budget,a.inputId);const i=void 0===o.budget.maintenanceTarget?void 0:Math.max(1,.5*o.budget.maintenanceTarget-(o.budget.calibratedInputEstimate-o.budget.messageTokens));let r=!1;try{r=await this.runCompaction(n,"auto",a,!1,i,(e,t)=>s({history:e,explicitSkill:A,capabilityReminder:W,...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:y,project:e=>this.projectModelMessages(e),...void 0===this.providerOptions?{}:{providerOptions:this.providerOptions}}).messages)}catch(e){if(this.isTurnAborted(a))throw e;this.debug(n,"compaction","summary failed; original context retained",m,{message:Ze(e)})}if(k=r?void 0:o.budget,b=this.messages.length,this.isTurnAborted(a))return void this.persistPausedTurnCancellation(n,a,m);n.push({type:"message-start",messageId:t()});continue}if(void 0!==ue&&this.isTurnAborted(a))return void this.persistCancelledTurn(n,a,b,m);if(void 0!==ue&&!ye&&be&&g?.isRecoverable(de)&&void 0!==v&&!a.userRejected&&void 0===pe&&void 0===O.message){f=de;try{await st(ie.steps,a.abortController.signal)}catch(e){if(a.abortController.signal.throwIfAborted(),!p.isInstance(e)&&e!==de)throw e}const e=pt(Ge(a)),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})||[...a.pendingToolCalls.values()].some(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence)))be=!1,ue="网络中断且操作结果尚未完整结算;已停止自动恢复,请先核对结果。";else{if(this.toolCoordinator.finishTurn(),e.length>0&&(this.persistMessages(e,"raw_transcript"),this.messages.push(...e)),Ye(a),b=this.messages.length,this.persistRecoveryCancellations(n,a),b=this.messages.length,a.completedStepCount+=ve,void 0!==Y&&(D=void 0===D?Y:ct(D,Y),this.sessionUsage=ct(this.sessionUsage,Y)),a.completedStepCount>=this.maxSteps)return void n.push({type:"error",stage:"execute",message:"已达单轮最大工具步数;未完成的回复已丢弃,输入和已完成的操作已保留。"});const t=await v.attempt(de,a.abortController.signal,e=>n.push({type:"model-recovery",attempt:e}));if(t.recovered){f=void 0;continue}de=t.error,ue=Ze(t.error)}}if(void 0!==ue){if(be&&!ye&&(f=de),be&&!ye&&g?.formatError&&(ue=Xe(de)??g.formatError(de)),ye&&void 0!==K&&(R.add(K.fingerprint),P=K),this.messages.splice(b),ye){const e=0===he.length&&!ge,t=e&&S<1,s=!(!t&&e)&&await this.recoverFromContextError(n,a);if(this.isTurnAborted(a))return void this.persistCancelledRecoveryTurn(n,a,j,m);if(e&&s&&t){S+=1;continue}const o=e?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(n,a,j,he.length>0,m),void n.push({type:"error",stage:"execute",message:`${ue}${o}`})}return this.persistFailedTurn(n,a,j,m),void n.push({type:"error",stage:"execute",message:ue})}if(a.aborted||a.abortController.signal.aborted)return a.cancellationReason=dt(a.cancellationReason,a.abortController.signal.reason),void this.persistCancelledTurn(n,a,b,m);let Se;this.debug(n,"model","awaiting response messages",m);const we=this.scheduleDebug(n,"model","still awaiting response messages",m);try{const e=await ie.steps;Se=He(a,e)}catch(e){if(this.clearDebugTimer(we),this.isTurnAborted(a)||L(e))return a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,e),void this.persistCancelledTurn(n,a,b,m);const t=rt(e);if(t&&void 0!==K&&(P=K,R.add(K.fingerprint)),this.messages.splice(b),t){const t=0===he.length&&!ge,s=t&&S<1,o=!(!s&&t)&&await this.recoverFromContextError(n,a);if(this.isTurnAborted(a))return void this.persistCancelledRecoveryTurn(n,a,j,m);if(t&&o&&s){S+=1;continue}const i=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(n,a,j,he.length>0,m),void n.push({type:"error",stage:"execute",message:`${Ze(e)}${i}`})}return this.persistFailedTurn(n,a,j,m),void n.push({type:"error",stage:"execute",message:Ze(e)})}finally{this.clearDebugTimer(we)}if(this.debug(n,"model","response messages ready",m,{responseMessages:Se.length}),this.isTurnAborted(a))return a.cancellationReason=dt(a.cancellationReason,a.abortController.signal.reason),void this.persistCancelledTurn(n,a,b,m);const Ee=pt(Se);this.messages.push(...Ee);const Me=pe??O.message;if(void 0!==Me){const e=0===he.length?Me:`\n${Me}`;he+=e,n.push({type:"text-delta",delta:e}),this.messages.push({role:"assistant",content:Me})}this.debug(n,"persist","persisting messages",m,{appendedMessages:this.messages.length-b}),this.persistMessages(this.messages.slice(b),"raw_transcript"),Ye(a),b=this.messages.length,this.debug(n,"persist","messages persisted",m,{totalMessages:this.messages.length}),ne&&(D=void 0===D?ne:ct(D,ne),this.sessionUsage=ct(this.sessionUsage,ne));const Re=ae;void 0!==Re&&(this.lastInputTokens=Re,this.measuredProjectedTokens=q??$,this.promptOverhead=Math.max(0,Re-this.measuredProjectedTokens-h)),a.completedStepCount+=ve;const Pe=a.completedStepCount>=this.maxSteps&&"tool-calls"===ce;if(n.push({type:"message-finish",text:he,...void 0===D?{}:{totalUsage:D},sessionUsage:{...this.sessionUsage},...void 0!==ae?{contextInputTokens:ae}:{},...void 0!==le?{outputTokensPerSecond:le}:{},...Pe?{stoppedAtStepLimit:!0}:{}}),!a.pausedForContextPressure||"tool-calls"!==ce||Pe||void 0!==Me)return;if(a.pausedForContextPressure=!1,this.debug(n,"compaction","turn paused for context pressure",m,{continuations:a.contextPressureContinuations,pressureTokens:this.contextPressureTokens()}),this.isTurnAborted(a))return void this.persistPausedTurnCancellation(n,a,m);n.push({type:"message-start",messageId:t()})}}catch(e){if(this.isTurnAborted(a)||L(e))return a.aborted=!0,a.cancellationReason=dt(a.cancellationReason,a.abortController.signal.reason??e),void(void 0!==b?this.persistCancelledTurn(n,a,b,m):this.emitCancellation(n,a));void 0!==b&&this.messages.splice(b),this.debug(n,"turn","error",m,{message:Ze(e)}),n.push({type:"error",stage:"execute",message:Ze(e)})}finally{this.requestBudgets.abandonMaintenance(a.inputId),void 0!==y&&clearTimeout(y),this.toolCoordinator.finishTurn();try{g?.onTurnEnd?.(this.isTurnAborted(a)?void 0:f)}finally{this.activeTurn===a&&(this.activeTurn=void 0),n.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)tt(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Me[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=me(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!==F.policyDenied&&e.outcome.kind!==F.userRejected&&e.outcome.kind!==F.invalidInput&&(e.outcome.kind!==F.cancelled||e.outcome.executionState!==D.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?[]:[me(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=Ve(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=Pe(pt(Ge(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,he({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 的操作。${_e}`}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}: ${Ze(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+De,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 pe(ge(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({...K(e),sequence:e.sequence}))}getToolExecution(e,t=!1){const s=this.getPersistedToolExecution?.(e),o=s??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();return!o||t?o:{...K(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getRequestBudgetState(){return this.requestBudgets.view()}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.onProviderOptionsChange?.(e),this.providerOptions=e}canSwitchModel(){return void 0===this.activeTurn}switchModel(e){if(!this.canSwitchModel())throw new Error("会话正在生成回复,稍后再切换模型");this.model=e.model,this.modelRecovery=e.modelRecovery,this.requestBudgets=new n,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=>H(e.output).kind===F.userRejected))return!1;const a=at(r.usage),l=te(this.projectModelMessages([...this.messages,...He(e,i)])),c=s?.()??(void 0===a.inputTokens?this.promptOverheadTokens()+l:Math.max(0,a.inputTokens+l-t()));return!(c/this.contextWindow<n.threshold||!o(c))&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:te([{role:"user",content:e}]),s=te(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 Ne(e,t,[...this.messages,...this.activeTurn?Ge(this.activeTurn):[]],s,this.observationResultId(t.toolCallId)===t.id)}projectModelMessages(e){return qe(e,{declarations:this.observationRetentionByToolId,resultId:e=>this.observationResultId(e),...this.observationRecallToolId?{recallToolId:this.observationRecallToolId}:{}})}promptOverheadTokens(){const e=this.currentCheckpointReminder(Te(this.capabilityManifest,fe.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:se(e))}currentCheckpointReminder(e){return void 0===this.compactionCheckpoint?void 0:Se(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,Ve(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:te([{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:ae(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:Ze(s)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}async runCompaction(e,t,o,i,n,r){const a=Date.now(),l=this.lastInputTokens,c=this.compaction,u=c?.strategy??"summarize";e.push({type:"compaction-start",reason:t});const d=s=>(e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:0,kept:this.messages.length,...s?{failure:s}:"manual"===t?{recoveryNotice:"当前内容未产生可用的压缩,已保留原上下文。"}:{}}),!1);if(this.isTurnAborted(o))return i&&o&&this.emitCancellation(e,o),d();if(!c)return d();try{const p=[...this.messages],h=this.compactionCheckpoint,m=Te(this.capabilityManifest,fe.transcriptRead),g=void 0===h?void 0:3===h.version?h.taskSummary:Se(h,this.sessionManagerInstanceId,m),v=await ee({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===o?{}:{abortSignal:o.abortController.signal}});if(this.isTurnAborted(o))return i&&o&&this.emitCancellation(e,o),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(Pe(v.messages).status===Re.repaired)return d();const b=this.currentCheckpointReminder(m),y=(e,t)=>void 0===r?this.requestBudgets.projectedMessageTokens(s({history:e,explicitSkill:{skillNames:[],userPrompt:"",modelUserContent:""},capabilityReminder:"",...void 0===t?{}:{checkpointReminder:t},system:this.systemPrompt,tools:this.modelTools(),project:e=>this.projectModelMessages(e)}).messages):this.requestBudgets.projectedMessageTokens(r(e,t)),T=y(p,b),C=new Error("compaction_candidate_did_not_shrink");let I=T;const k=e=>{const t=Se(e,this.sessionManagerInstanceId,m);if(I=y(v.messages,t),I>=T)throw C};let x;try{if(this.commitPersistedCompaction)x=this.commitPersistedCompaction({messages:v.messages,expectedActiveMessages:p,expectedLatestCheckpointId:h?.id,summary:f,validateCheckpoint:k});else{const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=Ee({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:we(e.map(e=>e.message),t)});k(s),this.onReplace?.(v.messages),x=s}}catch(e){if(e===C)return d();throw e}return this.messages.splice(0,this.messages.length,...v.messages),this.compactionCheckpoint=x,this.lastInputTokens=void 0,this.measuredProjectedTokens=void 0,e.push({type:"context-compacted",...void 0===l?{}:{beforeInputTokens:l},reason:t,strategy:u,removed:v.removed,kept:v.kept,checkpointId:x.id,checkpointGeneration:x.generation,checkpointSummaryStatus:"summarize"===u?"valid":"skipped"}),this.debug(e,"compaction","task summary committed",a,{removed:v.removed,kept:v.kept,beforeEstimatedTokens:T,afterEstimatedTokens:I}),!0}catch(e){throw d(this.isTurnAborted(o)?void 0:e instanceof Z?{reason:v.timeout,timeoutMs:e.timeoutMs}:{reason:v.error}),e}}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(s){return this.isTurnAborted(t)||e.push({type:"error",stage:"plan",message:Ze(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&&!P(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${Ze(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=N.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(A))}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??N.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const o=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。",i=e.userMessagePersisted?"本轮输入已保存,但进度或中断记录未能保存。":"刚才的对话和进度未能保存。";return t===N.timeout?`本轮等待时间过长,已自动停止。${i}${o}`:t===N.runtime?`本轮因运行异常而中断。${i}${o}`:`已停止本轮。${i}${o}`}const o=s.execSessionIds,i=Te(this.capabilityManifest,fe.sessionList);switch(t){case N.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case N.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":Ce(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case N.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??N.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=Te(this.capabilityManifest,fe.sessionList),n=_e;switch(t){case N.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case N.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:Ce(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case N.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=N.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,Be.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Be.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s);const n=i===Be.keepRaw,r=n?Pe(pt(Ge(t))).messages:[],a=n?Ve(t):Ke(t);t.cancellationPersisted=!0;const l=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...l],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[he({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),$(this.cancellationDisplayMessage(e),e.cancellationReason??N.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}: ${Ze(t)}`}),!1}}persistRecoveryCancellations(e,t){const s=[];for(const o of t.pendingToolCalls.values()){const i=B({kind:F.cancelled,reason:N.runtime,executionState:D.notExecuted},"模型连接中断,本工具调用确定未执行;重新生成的调用仍需正常校验与审批。"),n=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:i});this.persistToolExecution(n,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:n.id,outcome:i.outcome,display:i.display,output:i.display,isError:!0});const r=`${o.agentName}__${o.toolName}`;s.push({role:"assistant",content:[{type:"tool-call",toolCallId:o.toolCallId,toolName:r,input:o.input}]},{role:"tool",content:[{type:"tool-result",toolCallId:o.toolCallId,toolName:r,output:i.model}]}),t.pendingToolCalls.delete(o.toolCallId)}s.length>0&&(this.persistMessages(s,"raw_transcript"),this.messages.push(...s))}persistPendingToolCancellations(e,t){const s=t.cancellationReason??N.runtime;for(const o of t.pendingToolCalls.values()){const i=this.toolCoordinator.hasExecutionStarted(o.executionOccurrence)?D.outcomeUnknown:D.notExecuted,n=i===D.notExecuted?`工具调用在开始执行前因本轮 ${s} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${s} 中断而取消;最终结果尚未确认`,r=B({kind:F.cancelled,reason:s,executionState:i},n,{raw:{cancellationReason:s,executionState:i,abortReason:Ze(t.abortController.signal.reason)}}),a=G({toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,input:o.input,result:r});this.persistToolExecution(a,t),e.push({type:"tool-result",toolCallId:o.toolCallId,agentName:o.agentName,toolName:o.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:r.display,isError:!0}),t.pendingToolCalls.delete(o.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=N.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(q),!0)}assertWritable(){if(this.closed)throw new Error("session is closing or closed");this.onBeforeTurn?.()}addCloseBarrier(e){if(this.closed)throw new Error("Cannot register work on a closing session");this.closeBarriers.add(e)}trackExecution(e){this.executionJobs.add(e),e.finally(()=>this.executionJobs.delete(e))}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??=N.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(A)),this.closePromise=(async()=>{const e=this.sessionManager?.close()??Promise.resolve([]),[,t]=await Promise.all([Promise.all(this.executionJobs),e]),s=t.filter(e=>void 0!==e.cleanupError);if(s.length>0)throw new Error(`后台会话清理失败: ${s.map(e=>e.cleanupError).join("; ")}`);if(void 0!==this.executionFailure)throw this.executionFailure;for(const e of this.closeBarriers)await e();this.onClose?.()})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${Ze(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)}}
|
|
@@ -33,6 +33,7 @@ export interface ConversationEngineOptions {
|
|
|
33
33
|
readonly maxSteps?: number;
|
|
34
34
|
readonly providerOptions?: SharedV4ProviderOptions;
|
|
35
35
|
readonly modelRecovery?: AgentSessionOptions["modelRecovery"];
|
|
36
|
+
readonly resolveReasoningPresentation?: AgentSessionOptions["resolveReasoningPresentation"];
|
|
36
37
|
readonly structuredOutputProviderOptions?: SharedV4ProviderOptions;
|
|
37
38
|
readonly structuredOutputReasoning?: NonNullable<LanguageModelV4CallOptions["reasoning"]>;
|
|
38
39
|
readonly debugEvents?: boolean;
|
|
@@ -90,6 +91,7 @@ export declare class ConversationEngine {
|
|
|
90
91
|
private readonly maxSteps;
|
|
91
92
|
private providerOptions;
|
|
92
93
|
private modelRecovery;
|
|
94
|
+
private readonly resolveReasoningPresentation;
|
|
93
95
|
private modelOverride;
|
|
94
96
|
private modelName;
|
|
95
97
|
private provider;
|
|
@@ -120,6 +122,8 @@ export declare class ConversationEngine {
|
|
|
120
122
|
private shellProfileResolution;
|
|
121
123
|
private shellUnsupportedWarned;
|
|
122
124
|
private readonly liveSessions;
|
|
125
|
+
private readonly openingSessions;
|
|
126
|
+
private readonly sessionClaims;
|
|
123
127
|
private readonly shutdownController;
|
|
124
128
|
private disposePromise;
|
|
125
129
|
private closing;
|
|
@@ -127,6 +131,7 @@ export declare class ConversationEngine {
|
|
|
127
131
|
createSession(input?: CreateSessionInput): Promise<AgentSession>;
|
|
128
132
|
resumeSession(threadId: string): Promise<AgentSession>;
|
|
129
133
|
forkSession(snapshot: ThreadSnapshot, input?: ForkSessionInput): Promise<AgentSession>;
|
|
134
|
+
private openSession;
|
|
130
135
|
private assertAcceptingSessions;
|
|
131
136
|
private resolveRuntimeShellProfile;
|
|
132
137
|
private resolveShellSettings;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{AgentSession as s}from"./agent-session.js";import{resolveModelContextWindow as t}from"./context-window.js";import{createDefaultModelCatalog as o}from"./model-catalog-default.js";import{createWorkspaceInstructionsSource as i,parseWorkspaceInstructionsSetting as r}from"./workspace-instructions.js";import{CAPABILITY_HOST_MODES as n,shouldOfferAgentInstall as l,shouldOfferScheduleCreate as a}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as h}from"../types/command-classification.js";import{resolveShellProfile as c}from"../bash/profile.js";import{inspectGitVcsContext as d}from"./vcs-context.js";import{createToolLedgerGapRecoveryMessage as p}from"./cancelled-turn-recovery.js";const u="ConversationEngine is closing",m=e=>0===e.length;export function buildSessionExecSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),profile:e.profile,maxSessions:s.session.maxSessions,defaultYieldMs:s.session.defaultYieldMs,maxOutputTokens:s.session.maxOutputTokens,bufferCapacity:s.maxCaptureBytes,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}export function buildSessionBashSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),defaultTimeoutMs:s.defaultTimeoutMs,maxTimeoutMs:s.maxTimeoutMs,turnTimeoutMs:e.settings.turnTimeoutMs,maxCaptureBytes:s.maxCaptureBytes,maxModelOutputChars:s.maxModelOutputChars,profile:e.profile,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}function v(){return new Error(u)}function g(e){if(null===e.workspaceInstructions)return;if(void 0!==e.workspaceInstructions)return e.workspaceInstructions;const s=process.cwd();return i({cwd:s,setting:r(e.settings.instructions,s),...e.onWorkspaceInstructionsIssue?{onIssue:e.onWorkspaceInstructionsIssue}:{}})}export class ConversationEngine{settings;agentHost;store;policy;fileToolsEnabled;maxSteps;providerOptions;modelRecovery;modelOverride;modelName;provider;toolSchemaPolicy;switchingProviderName;modelCatalog;structuredOutputProviderOptions;structuredOutputReasoning;debugEvents;explicitModel;explicitSources;explicitSkillLibrary;workspaceInstructions;onAgentBootstrapIssue;hostMode;scheduleTools;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;inspectVcsContext;shellEnv;onShellCommandSpawn;ready;refreshChain=Promise.resolve();resolvedCatalog=[];pendingInstalls=new Set;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;shutdownController=new AbortController;disposePromise;closing=!1;constructor(e){if(!e.model)throw new Error("ConversationEngine requires a model supplied by its host");if(void 0!==e.agentHost&&void 0!==e.sources)throw new Error("ConversationEngine accepts either sources or agentHost, not both");this.settings=e.settings,this.agentHost=e.agentHost,this.provider=e.provider,this.modelName=e.modelName,this.toolSchemaPolicy=e.toolSchemaPolicy??m,this.store=e.store,this.modelCatalog=e.modelCatalog??o(),this.policy=e.policy,this.fileToolsEnabled=e.fileToolsEnabled??!0,this.maxSteps=e.maxSteps??e.settings.maxSteps,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??n.embedded,this.scheduleTools=e.scheduleTools??void 0,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??c,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.workspaceInstructions=g(e),this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.inspectVcsContext=e.inspectVcsContext??d,this.shellEnv={...e.shellEnv??process.env},this.onShellCommandSpawn=e.onShellCommandSpawn}async createSession(s={}){this.assertAcceptingSessions();const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store?this.store.createThread({...void 0===s.id?{}:{id:s.id},...void 0===s.origin?{}:{origin:s.origin},...s.title?{title:s.title}:{},model:this.resolveModelName()}):s.id??e();return this.buildSession(t,o,[])}async resumeSession(e){if(this.assertAcceptingSessions(),!this.store)throw new Error("resumeSession requires a ThreadStore");if("scheduled"===this.store.getThread(e)?.origin.kind)throw new Error("定时执行会话是只读记录;请基于该次运行创建新对话");const s=this.liveSessions.get(e);if(void 0!==s)return s;if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.liveSessions.get(e);if(void 0!==o)return o;this.recoverUncoveredToolExecutionContext(e);const i=this.store.loadSessionState(e);return this.buildSession(t,e,i.messages,i.checkpoint)}async forkSession(e,s={}){if(this.assertAcceptingSessions(),!this.store)throw new Error("forkSession requires a ThreadStore");const t=await this.ensureReady();this.assertAcceptingSessions();const o=this.store.forkSnapshot(e,{...s,model:this.resolveModelName()});try{this.recoverUncoveredToolExecutionContext(o);const e=this.store.loadSessionState(o);return this.buildSession(t,o,e.messages,e.checkpoint)}catch(e){throw this.store.deleteThread(o),e}}assertAcceptingSessions(){if(this.closing)throw v()}resolveRuntimeShellProfile(){if(!this.settings.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const s="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${s},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){return buildSessionBashSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}})}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const s=this.settings.shell;return s.enabled&&s.session.enabled&&e.supportsSessionExec?buildSessionExecSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}}):void 0}buildSession(e,t,o,i){const r=this.store,n=r?.getThread(t)?.derivedFrom,c=this.resolveContextWindowFor(this.resolveProviderName(),this.resolveModelName()),d=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,p=void 0===this.explicitSkillLibrary?this.agentHost?.refreshSkills?.bind(this.agentHost):void 0,u=this.resolveRuntimeShellProfile(),m=u?this.resolveShellSettings(u):void 0,v=this.fileToolsEnabled?{workdir:m?.workdir??process.cwd()}:void 0,g=u?this.resolveSessionExecSettings(u):void 0,S=u?u.supportsSafeCommandClassification&&this.settings.shell.autoApproveSafe?u:h:void 0,f=l(this.hostMode)?this.resolveAgentInstallBinding():void 0,w=this.scheduleTools,y=this.composeCapabilityContext(e.sources.length,u),C=new s({id:t,model:this.activeModel(e),onBeforeTurn:this.assertModelUpdateIdle,...void 0===this.modelRecovery?{}:{modelRecovery:this.modelRecovery},sources:e.sources,toolSchemaPolicy:this.toolSchemaPolicy,onToolExcluded:e=>this.onAgentBootstrapIssue?.({agentName:e.agentName,message:`工具 "${e.toolName}" 的参数 schema 含当前 provider "${this.resolveToolSchemaProviderName()}" 无法接受的引用(${e.issues.map(e=>e.ref).join("、")}),已从本会话工具集移除`}),capabilityContext:y,resolveDynamicCapabilityContext:async e=>{const[s,t]=await Promise.all([this.inspectVcsContext(y.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),o=t.vcs??s;return{...t.ruleIds?{ruleIds:t.ruleIds}:{},...o?{vcs:o}:{},...t.origin?{origin:t.origin}:{}}},...d?{skillLibrary:d}:{},...p?{refreshSkillLibrary:e=>p({...this.hostOperation(),signal:e})}:{},...this.workspaceInstructions?{workspaceInstructions:this.workspaceInstructions}:{},...v?{fileTools:v}:{},...m?{bash:m}:{},...S?{bashClassifier:S}:{},...g?{bashSession:g}:{},...f?{agentInstall:f}:{},...w?{schedules:{port:w,sessionCwd:y.cwd,includeCreate:a(this.hostMode)}}:{},maxSteps:this.maxSteps,compaction:this.settings.compaction,turnTimeoutMs:this.settings.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==c?{contextWindow:c.window,contextWindowSource:c.source}:{},...this.policy?{policy:this.policy}:{},initialMessages:o,...void 0!==n?{derivedFrom:n}:{},...i?{initialCheckpoint:i}:{},...r?{onAcceptInput:(e,s)=>r.acceptTurnInput(t,e,s),onRecordInputSkillCheckpoint:(e,s)=>r.recordTurnSkillCheckpoint(t,e,s),getInputSkillCheckpoint:e=>r.getTurnInputSkillCheckpoint(t,e),onPersist:(e,s)=>r.appendMessages(t,e,s),onReplace:e=>r.replaceMessages(t,e),onToolExecution:e=>r.appendToolExecution(t,e),listToolExecutions:e=>r.listToolExecutions(t,e),getToolExecution:e=>r.getToolExecution(t,e),recoverUncoveredToolExecutions:()=>this.recoverUncoveredToolExecutionContext(t),listTranscriptMessages:e=>r.listTranscriptMessages(t,e),commitCompaction:e=>r.commitCompaction(t,e),readCheckpointTranscript:e=>r.readCheckpointTranscript(t,e)}:{},onClose:()=>{this.liveSessions.get(t)===C&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,C),C}recoverUncoveredToolExecutionContext(e){const s=this.store?.recoverUncoveredToolExecutions(e,p);return void 0===s?[]:[s]}assertModelUpdateIdle=()=>{if(void 0!==this.switchingProviderName)throw new Error("模型配置正在更新,请稍后再试")};syncProviderOptions(e){this.assertModelUpdateIdle(),this.switchingProviderName=this.provider;try{this.agentHost?.updateSampling(this.modelOverride??this.explicitModel,e),this.providerOptions=e}finally{this.switchingProviderName=void 0}}switchModel(e){this.assertAcceptingSessions(),this.assertModelUpdateIdle(),this.switchingProviderName=e.provider;try{const s=this.resolveContextWindowFor(e.provider,e.modelName),t={model:e.model,...void 0===e.modelRecovery?{}:{modelRecovery:e.modelRecovery},...void 0!==s?{contextWindow:s.window,contextWindowSource:s.source}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.structuredOutputProviderOptions?{structuredOutputProviderOptions:e.structuredOutputProviderOptions}:{},...e.structuredOutputReasoning?{structuredOutputReasoning:e.structuredOutputReasoning}:{},toolSchemaPolicy:e.toolSchemaPolicy??m};for(const e of this.liveSessions.values())if(!e.canSwitchModel())throw new Error("存在正在生成回复的会话,稍后再切换模型");this.agentHost?.updateSampling(e.model,e.providerOptions);for(const e of this.liveSessions.values())e.switchModel(t);this.modelOverride=e.model,this.modelName=e.modelName,this.provider=e.provider,this.toolSchemaPolicy=t.toolSchemaPolicy,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning;for(const s of this.liveSessions.keys())this.store?.updateModel(s,e.modelName);return s}finally{this.switchingProviderName=void 0}}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}hostOperation(){return{model:this.modelOverride??this.explicitModel,...this.providerOptions?{providerOptions:this.providerOptions}:{},signal:this.shutdownController.signal}}async bootstrap(){const e=this.agentHost?await this.agentHost.prepare(this.hostOperation()):{sources:this.explicitSources??[]};this.assertAcceptingSessions(),this.resolvedCatalog=e.catalog??[];const s=e.skillLibrary,t=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??s,o=this.modelOverride??this.explicitModel;return this.agentHost?.updateSampling(o,this.providerOptions),{model:o,sources:e.sources,...t?{skillLibrary:t}:{}}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const s=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=s.then(()=>{},()=>{}),s}async runAgentRefresh(e){const s=await this.ensureReady();if(this.assertAcceptingSessions(),!this.agentHost)throw new Error("Agent refresh requires an agentHost");const t=await this.agentHost.refresh(e,this.hostOperation());this.assertAcceptingSessions();const o=[...s.sources.filter(e=>e.agentName!==t.source.agentName),t.source],i=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??t.skillLibrary;this.agentHost.updateSampling(this.activeModel(s),this.providerOptions),this.ready=Promise.resolve({model:this.activeModel(s),sources:o,...i?{skillLibrary:i}:{}});const r=i?.list()??[],n=i&&r.length>0?i:void 0,l=this.resolveRuntimeShellProfile();return{source:t.source,...n?{skillLibrary:n}:{},capabilityContext:this.composeCapabilityContext(o.length,l)}}composeCapabilityContext(e,s){const t=this.resolveAgentOnboardingInfo();return{profile:s?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...s?{shellHints:s.systemPromptHints()}:{},agentCount:e,...t?{agentOnboardingCatalog:t}:{}}}resolveAgentOnboardingInfo(){return this.resolvedCatalog.length>0?this.resolvedCatalog:void 0}resolveAgentInstallBinding(){if(this.agentHost?.install&&0!==this.resolvedCatalog.length)return{catalog:this.resolvedCatalog,install:(e,s)=>this.installCatalogAgent(e,s)}}installCatalogAgent(e,s){this.assertAcceptingSessions();const t=this.runAgentInstall(e,s);return this.pendingInstalls.add(t),t.then(()=>this.pendingInstalls.delete(t),()=>this.pendingInstalls.delete(t)),t}async runAgentInstall(e,s){const t=this.agentHost;if(!t?.install||!this.resolvedCatalog.some(s=>s.shortName===e))return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const{outcome:o}=await t.install(e,s,this.shutdownController.signal);if(!o.ok||this.closing)return{outcome:o};try{const e=await this.ensureReady();if(this.assertAcceptingSessions(),e.sources.some(e=>e.agentName===o.agentName))return s(`Agent "${o.agentName}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:o};const t=await this.prepareAgentRefresh(o.agentName);return{outcome:o,refresh:t}}catch(e){return s(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:o}}}resolveProviderName(){return this.provider}resolveContextWindowFor(e,s){return t({provider:e,model:s,...void 0!==this.settings.contextWindow?{override:this.settings.contextWindow}:{},catalog:this.modelCatalog})}resolveModelName(){return this.modelName}resolveToolSchemaProviderName(){return this.switchingProviderName??this.resolveProviderName()}activeModel(e){return this.modelOverride??e.model}async getContextSummary(){const e=await this.ensureReady();this.assertAcceptingSessions();const s=this.workspaceInstructions?.current()?.path;return{agentCount:e.sources.length,toolCount:e.sources.reduce((e,s)=>e+s.tools.length,0),skillCount:e.skillLibrary?.list().length??0,...void 0!==s?{instructionsPath:s}:{}}}async dispose(){return void 0!==this.disposePromise||(this.closing=!0,this.disposePromise=Promise.resolve().then(async()=>{const e=[],s=await Promise.allSettled([...this.liveSessions.values()].map(e=>e.close()));for(const t of s)"rejected"===t.status&&e.push(t.reason);this.liveSessions.clear(),await Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain,...this.pendingInstalls]);try{await(this.agentHost?.dispose())}catch(s){e.push(s)}if(1===e.length)throw e[0];if(e.length>1)throw new AggregateError(e,"ConversationEngine 关闭 session 与宿主资源失败。")}),this.shutdownController.abort(v())),this.disposePromise}}
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{AgentSession as s}from"./agent-session.js";import{resolveModelContextWindow as t}from"./context-window.js";import{createDefaultModelCatalog as o}from"./model-catalog-default.js";import{createWorkspaceInstructionsSource as i,parseWorkspaceInstructionsSetting as r}from"./workspace-instructions.js";import{CAPABILITY_HOST_MODES as n,shouldOfferAgentInstall as l,shouldOfferScheduleCreate as a}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as h}from"../types/command-classification.js";import{resolveShellProfile as c}from"../bash/profile.js";import{inspectGitVcsContext as d}from"./vcs-context.js";import{createToolLedgerGapRecoveryMessage as p}from"./cancelled-turn-recovery.js";const u="ConversationEngine is closing",m=e=>0===e.length;export function buildSessionExecSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),profile:e.profile,maxSessions:s.session.maxSessions,defaultYieldMs:s.session.defaultYieldMs,maxOutputTokens:s.session.maxOutputTokens,bufferCapacity:s.maxCaptureBytes,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}export function buildSessionBashSettings(e){const s=e.settings.shell;return{workdir:process.cwd(),defaultTimeoutMs:s.defaultTimeoutMs,maxTimeoutMs:s.maxTimeoutMs,turnTimeoutMs:e.settings.turnTimeoutMs,maxCaptureBytes:s.maxCaptureBytes,maxModelOutputChars:s.maxModelOutputChars,profile:e.profile,env:e.env,...e.onCommandSpawn?{onCommandSpawn:e.onCommandSpawn}:{}}}function g(){return new Error(u)}function v(e){if(null===e.workspaceInstructions)return;if(void 0!==e.workspaceInstructions)return e.workspaceInstructions;const s=process.cwd();return i({cwd:s,setting:r(e.settings.instructions,s),...e.onWorkspaceInstructionsIssue?{onIssue:e.onWorkspaceInstructionsIssue}:{}})}export class ConversationEngine{settings;agentHost;store;policy;fileToolsEnabled;maxSteps;providerOptions;modelRecovery;resolveReasoningPresentation;modelOverride;modelName;provider;toolSchemaPolicy;switchingProviderName;modelCatalog;structuredOutputProviderOptions;structuredOutputReasoning;debugEvents;explicitModel;explicitSources;explicitSkillLibrary;workspaceInstructions;onAgentBootstrapIssue;hostMode;scheduleTools;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;inspectVcsContext;shellEnv;onShellCommandSpawn;ready;refreshChain=Promise.resolve();resolvedCatalog=[];pendingInstalls=new Set;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;openingSessions=new Map;sessionClaims=new Map;shutdownController=new AbortController;disposePromise;closing=!1;constructor(e){if(!e.model)throw new Error("ConversationEngine requires a model supplied by its host");if(void 0!==e.agentHost&&void 0!==e.sources)throw new Error("ConversationEngine accepts either sources or agentHost, not both");this.settings=e.settings,this.agentHost=e.agentHost,this.provider=e.provider,this.modelName=e.modelName,this.toolSchemaPolicy=e.toolSchemaPolicy??m,this.store=e.store,this.modelCatalog=e.modelCatalog??o(),this.policy=e.policy,this.fileToolsEnabled=e.fileToolsEnabled??!0,this.maxSteps=e.maxSteps??e.settings.maxSteps,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.resolveReasoningPresentation=e.resolveReasoningPresentation,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??n.embedded,this.scheduleTools=e.scheduleTools??void 0,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??c,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.workspaceInstructions=v(e),this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.inspectVcsContext=e.inspectVcsContext??d,this.shellEnv={...e.shellEnv??process.env},this.onShellCommandSpawn=e.onShellCommandSpawn}async createSession(s={}){const t=s.id??e();return this.openSession(t,async()=>{const e=this.store?.retainSession(t);try{const o=await this.ensureReady();return this.assertAcceptingSessions(),e?.assert(),this.store?.createThread({...s,id:t,model:this.resolveModelName()}),this.buildSession(o,t,[],void 0,e)}catch(s){throw e?.release(),s}})}async resumeSession(e){if(this.assertAcceptingSessions(),"scheduled"===this.store?.getThread(e)?.origin.kind)throw new Error("定时执行会话是只读记录;请基于该次运行创建新对话");return this.openSession(e,async()=>{if(!this.store)throw new Error("resumeSession requires a ThreadStore");const s=this.store.retainSession(e);try{if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);if("scheduled"===this.store.getThread(e)?.origin.kind)throw new Error("定时执行会话是只读记录;请基于该次运行创建新对话");const t=await this.ensureReady();this.assertAcceptingSessions(),s?.assert(),this.recoverUncoveredToolExecutionContext(e);const o=this.store.loadSessionState(e);return this.buildSession(t,e,o.messages,o.checkpoint,s)}catch(e){throw s?.release(),e}})}async forkSession(s,t={}){const o=e();return this.openSession(o,async()=>{if(!this.store)throw new Error("forkSession requires a ThreadStore");const e=this.store.retainSession(o);let i=!1;try{const r=await this.ensureReady();this.assertAcceptingSessions(),e?.assert(),this.store.forkSnapshot(s,{...t,id:o,model:this.resolveModelName()}),i=!0,this.recoverUncoveredToolExecutionContext(o);const n=this.store.loadSessionState(o);return this.buildSession(r,o,n.messages,n.checkpoint,e)}catch(s){throw i&&(e?.assert(),this.store.deleteThread(o)),e?.release(),s}})}openSession(e,s){this.assertAcceptingSessions();const t=this.liveSessions.get(e);if(void 0!==t)return t.assertWritable(),Promise.resolve(t);const o=this.openingSessions.get(e);if(void 0!==o)return o;const i=Promise.resolve().then(s).finally(()=>this.openingSessions.delete(e));return this.openingSessions.set(e,i),i}assertAcceptingSessions(){if(this.closing)throw g()}resolveRuntimeShellProfile(){if(!this.settings.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const s="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${s},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){return buildSessionBashSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}})}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const s=this.settings.shell;return s.enabled&&s.session.enabled&&e.supportsSessionExec?buildSessionExecSettings({settings:this.settings,profile:e,env:this.shellEnv,...this.onShellCommandSpawn?{onCommandSpawn:this.onShellCommandSpawn}:{}}):void 0}buildSession(e,t,o,i,r){const n=this.store,c=e=>(r?.assert(),e()),d=n?.getThread(t)?.derivedFrom,p=this.resolveContextWindowFor(this.resolveProviderName(),this.resolveModelName()),u=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,m=void 0===this.explicitSkillLibrary?this.agentHost?.refreshSkills?.bind(this.agentHost):void 0,g=this.resolveRuntimeShellProfile(),v=g?this.resolveShellSettings(g):void 0,S=this.fileToolsEnabled?{workdir:v?.workdir??process.cwd()}:void 0,w=g?this.resolveSessionExecSettings(g):void 0,f=g?g.supportsSafeCommandClassification&&this.settings.shell.autoApproveSafe?g:h:void 0,y=l(this.hostMode)?this.resolveAgentInstallBinding():void 0,C=this.scheduleTools,x=this.composeCapabilityContext(e.sources.length,g),P=new s({id:t,model:this.activeModel(e),...this.resolveReasoningPresentation?{resolveReasoningPresentation:this.resolveReasoningPresentation}:{},onBeforeTurn:()=>{r?.assert(),this.assertModelUpdateIdle()},...void 0===this.modelRecovery?{}:{modelRecovery:this.modelRecovery},sources:e.sources,toolSchemaPolicy:this.toolSchemaPolicy,onToolExcluded:e=>this.onAgentBootstrapIssue?.({agentName:e.agentName,message:`工具 "${e.toolName}" 的参数 schema 含当前 provider "${this.resolveToolSchemaProviderName()}" 无法接受的引用(${e.issues.map(e=>e.ref).join("、")}),已从本会话工具集移除`}),capabilityContext:x,resolveDynamicCapabilityContext:async e=>{const[s,t]=await Promise.all([this.inspectVcsContext(x.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),o=t.vcs??s;return{...t.ruleIds?{ruleIds:t.ruleIds}:{},...o?{vcs:o}:{},...t.origin?{origin:t.origin}:{}}},...u?{skillLibrary:u}:{},...m?{refreshSkillLibrary:e=>m({...this.hostOperation(),signal:e})}:{},...this.workspaceInstructions?{workspaceInstructions:this.workspaceInstructions}:{},...S?{fileTools:S}:{},...v?{bash:v}:{},...f?{bashClassifier:f}:{},...w?{bashSession:w}:{},...y?{agentInstall:y}:{},...C?{schedules:{port:C,sessionCwd:x.cwd,includeCreate:a(this.hostMode)}}:{},maxSteps:this.maxSteps,compaction:this.settings.compaction,turnTimeoutMs:this.settings.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==p?{contextWindow:p.window,contextWindowSource:p.source}:{},...this.policy?{policy:this.policy}:{},initialMessages:o,...void 0!==d?{derivedFrom:d}:{},...i?{initialCheckpoint:i}:{},...n?{onAcceptInput:(e,s)=>c(()=>n.acceptTurnInput(t,e,s)),onRecordInputSkillCheckpoint:(e,s)=>c(()=>n.recordTurnSkillCheckpoint(t,e,s)),getInputSkillCheckpoint:e=>n.getTurnInputSkillCheckpoint(t,e),onPersist:(e,s)=>c(()=>n.appendMessages(t,e,s)),onReplace:e=>c(()=>n.replaceMessages(t,e)),onToolExecution:e=>c(()=>n.appendToolExecution(t,e)),listToolExecutions:e=>n.listToolExecutions(t,e),getToolExecution:e=>n.getToolExecution(t,e),recoverUncoveredToolExecutions:()=>c(()=>this.recoverUncoveredToolExecutionContext(t)),listTranscriptMessages:e=>n.listTranscriptMessages(t,e),commitCompaction:e=>c(()=>n.commitCompaction(t,e)),readCheckpointTranscript:e=>n.readCheckpointTranscript(t,e)}:{},onClose:()=>{r?.release(),this.sessionClaims.delete(t),this.liveSessions.get(t)===P&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,P),void 0!==r&&this.sessionClaims.set(t,r),P}recoverUncoveredToolExecutionContext(e){const s=this.store?.recoverUncoveredToolExecutions(e,p);return void 0===s?[]:[s]}assertModelUpdateIdle=()=>{if(void 0!==this.switchingProviderName)throw new Error("模型配置正在更新,请稍后再试")};syncProviderOptions(e){this.assertModelUpdateIdle(),this.switchingProviderName=this.provider;try{this.agentHost?.updateSampling(this.modelOverride??this.explicitModel,e),this.providerOptions=e}finally{this.switchingProviderName=void 0}}switchModel(e){this.assertAcceptingSessions(),this.assertModelUpdateIdle(),this.switchingProviderName=e.provider;try{const s=this.resolveContextWindowFor(e.provider,e.modelName),t={model:e.model,...void 0===e.modelRecovery?{}:{modelRecovery:e.modelRecovery},...void 0!==s?{contextWindow:s.window,contextWindowSource:s.source}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.structuredOutputProviderOptions?{structuredOutputProviderOptions:e.structuredOutputProviderOptions}:{},...e.structuredOutputReasoning?{structuredOutputReasoning:e.structuredOutputReasoning}:{},toolSchemaPolicy:e.toolSchemaPolicy??m};for(const e of this.liveSessions.values())if(!e.canSwitchModel())throw new Error("存在正在生成回复的会话,稍后再切换模型");this.agentHost?.updateSampling(e.model,e.providerOptions);for(const e of this.liveSessions.values())e.switchModel(t);this.modelOverride=e.model,this.modelName=e.modelName,this.provider=e.provider,this.toolSchemaPolicy=t.toolSchemaPolicy,this.providerOptions=e.providerOptions,this.modelRecovery=e.modelRecovery,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning;for(const s of this.liveSessions.keys())this.sessionClaims.get(s)?.assert(),this.store?.updateModel(s,e.modelName);return s}finally{this.switchingProviderName=void 0}}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}hostOperation(){return{model:this.modelOverride??this.explicitModel,...this.providerOptions?{providerOptions:this.providerOptions}:{},signal:this.shutdownController.signal}}async bootstrap(){const e=this.agentHost?await this.agentHost.prepare(this.hostOperation()):{sources:this.explicitSources??[]};this.assertAcceptingSessions(),this.resolvedCatalog=e.catalog??[];const s=e.skillLibrary,t=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??s,o=this.modelOverride??this.explicitModel;return this.agentHost?.updateSampling(o,this.providerOptions),{model:o,sources:e.sources,...t?{skillLibrary:t}:{}}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const s=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=s.then(()=>{},()=>{}),s}async runAgentRefresh(e){const s=await this.ensureReady();if(this.assertAcceptingSessions(),!this.agentHost)throw new Error("Agent refresh requires an agentHost");const t=await this.agentHost.refresh(e,this.hostOperation());this.assertAcceptingSessions();const o=[...s.sources.filter(e=>e.agentName!==t.source.agentName),t.source],i=null===this.explicitSkillLibrary?void 0:this.explicitSkillLibrary??t.skillLibrary;this.agentHost.updateSampling(this.activeModel(s),this.providerOptions),this.ready=Promise.resolve({model:this.activeModel(s),sources:o,...i?{skillLibrary:i}:{}});const r=i?.list()??[],n=i&&r.length>0?i:void 0,l=this.resolveRuntimeShellProfile();return{source:t.source,...n?{skillLibrary:n}:{},capabilityContext:this.composeCapabilityContext(o.length,l)}}composeCapabilityContext(e,s){const t=this.resolveAgentOnboardingInfo();return{profile:s?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...s?{shellHints:s.systemPromptHints()}:{},agentCount:e,...t?{agentOnboardingCatalog:t}:{}}}resolveAgentOnboardingInfo(){return this.resolvedCatalog.length>0?this.resolvedCatalog:void 0}resolveAgentInstallBinding(){if(this.agentHost?.install&&0!==this.resolvedCatalog.length)return{catalog:this.resolvedCatalog,install:(e,s)=>this.installCatalogAgent(e,s)}}installCatalogAgent(e,s){this.assertAcceptingSessions();const t=this.runAgentInstall(e,s);return this.pendingInstalls.add(t),t.then(()=>this.pendingInstalls.delete(t),()=>this.pendingInstalls.delete(t)),t}async runAgentInstall(e,s){const t=this.agentHost;if(!t?.install||!this.resolvedCatalog.some(s=>s.shortName===e))return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const{outcome:o}=await t.install(e,s,this.shutdownController.signal);if(!o.ok||this.closing)return{outcome:o};try{const e=await this.ensureReady();if(this.assertAcceptingSessions(),e.sources.some(e=>e.agentName===o.agentName))return s(`Agent "${o.agentName}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:o};const t=await this.prepareAgentRefresh(o.agentName);return{outcome:o,refresh:t}}catch(e){return s(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:o}}}resolveProviderName(){return this.provider}resolveContextWindowFor(e,s){return t({provider:e,model:s,...void 0!==this.settings.contextWindow?{override:this.settings.contextWindow}:{},catalog:this.modelCatalog})}resolveModelName(){return this.modelName}resolveToolSchemaProviderName(){return this.switchingProviderName??this.resolveProviderName()}activeModel(e){return this.modelOverride??e.model}async getContextSummary(){const e=await this.ensureReady();this.assertAcceptingSessions();const s=this.workspaceInstructions?.current()?.path;return{agentCount:e.sources.length,toolCount:e.sources.reduce((e,s)=>e+s.tools.length,0),skillCount:e.skillLibrary?.list().length??0,...void 0!==s?{instructionsPath:s}:{}}}async dispose(){return void 0!==this.disposePromise||(this.closing=!0,this.disposePromise=Promise.resolve().then(async()=>{const e=[];await Promise.allSettled(this.openingSessions.values());const s=await Promise.allSettled([...this.liveSessions.values()].map(e=>e.close()));for(const t of s)"rejected"===t.status&&e.push(t.reason);this.liveSessions.clear(),await Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain,...this.pendingInstalls]);try{await(this.agentHost?.dispose())}catch(s){e.push(s)}if(1===e.length)throw e[0];if(e.length>1)throw new AggregateError(e,"ConversationEngine 关闭 session 与宿主资源失败。")}),this.shutdownController.abort(g())),this.disposePromise}}
|
|
@@ -5,3 +5,4 @@ export { AGENT_BOOTSTRAP_MAX_CONCURRENCY, mapWithBoundedConcurrency, } from "../
|
|
|
5
5
|
export type { AgentToolSource, SourceTool } from "../tool-bridge/build-tools.ts";
|
|
6
6
|
export type { ToolAnnotations } from "../types/policy.ts";
|
|
7
7
|
export type { ToolResourceHint } from "../tool-contracts/resource-hints.ts";
|
|
8
|
+
export { SESSION_OWNER_LIVENESS, type SessionOwnershipHost } from "./session-ownership.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./schedule-tools.js";export*from"./agent-host.js";export*from"./runtime-settings.js";export{AGENT_BOOTSTRAP_MAX_CONCURRENCY,mapWithBoundedConcurrency}from"../engine/agent-bootstrap.js";
|
|
1
|
+
export*from"./schedule-tools.js";export*from"./agent-host.js";export*from"./runtime-settings.js";export{AGENT_BOOTSTRAP_MAX_CONCURRENCY,mapWithBoundedConcurrency}from"../engine/agent-bootstrap.js";export{SESSION_OWNER_LIVENESS}from"./session-ownership.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const SESSION_OWNER_LIVENESS: readonly ["alive", "dead", "unknown"];
|
|
2
|
+
/** Host-owned identity. Runtime deliberately does not interpret process IDs or OS tokens. */
|
|
3
|
+
export interface SessionOwnershipHost {
|
|
4
|
+
readonly identity: string;
|
|
5
|
+
readonly owner: {
|
|
6
|
+
readonly kind: string;
|
|
7
|
+
readonly label: string;
|
|
8
|
+
readonly workspace?: string;
|
|
9
|
+
};
|
|
10
|
+
/** Only positive OS evidence may return dead. No TTL or PID-name heuristics. */
|
|
11
|
+
probe(identity: string): (typeof SESSION_OWNER_LIVENESS)[number];
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SESSION_OWNER_LIVENESS=["alive","dead","unknown"];
|
package/dist/index.d.ts
CHANGED
|
@@ -79,3 +79,5 @@ export type { FileChangeDiff, FileChangeDisplay, FileChangeKind } from "@roll-ag
|
|
|
79
79
|
export { readScheduleHistory, readScheduleRun } from "./scheduler/schedule-store.ts";
|
|
80
80
|
export type { ReadScheduleHistoryOptions, ScheduleHistoryReadResult, ScheduleRunReadResult, } from "./scheduler/schedule-store.ts";
|
|
81
81
|
export type { BackfillThreadReferenceInput, RegisterThreadReferenceInput, ScheduleThreadReference, ScheduleRunHistoryEntry, ScheduleHistoryTask, } from "./scheduler/types.ts";
|
|
82
|
+
export { SESSION_OCCUPANCY_CAPABILITY, SessionOccupiedError, SessionClaims, canonicalSessionDatabasePath, type SessionClaim, } from "./ownership/session-claims.ts";
|
|
83
|
+
export { inspectThreadLibrary, migrateThreadLibrary, ThreadLibraryMigrationRequiredError, THREAD_STORE_SCHEMA_VERSION, type ThreadLibraryPreflight, } from "./store/thread-store.ts";
|