@roll-agent/runtime 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
2
  import { type BashExecResult } from "./format-result.ts";
3
3
  import type { ShellProfile } from "./profile.ts";
4
4
  interface RunBashCommandDeps {
@@ -17,6 +17,7 @@ export interface RunBashOptions {
17
17
  readonly env?: NodeJS.ProcessEnv;
18
18
  readonly abortSignal?: AbortSignal;
19
19
  readonly onDelta?: (stream: BashStreamName, delta: string) => void;
20
+ readonly onSpawn?: (child: ChildProcess) => void;
20
21
  }
21
22
  export declare function runBashCommand(options: RunBashOptions, deps?: RunBashCommandDeps): Promise<BashExecResult>;
22
23
  export {};
package/dist/bash/exec.js CHANGED
@@ -1 +1 @@
1
- import{spawn as e}from"node:child_process";import{existsSync as t,readFileSync as o,unlinkSync as r}from"node:fs";import{constants as i}from"node:os";import{performance as n}from"node:perf_hooks";import{OutputSink as s}from"./output-buffer.js";import{parsePipeSegments as l}from"./shell-pipe.js";import{BASH_TERMINATION_CAUSES as a,EXEC_TIMEOUT_EXIT_CODE as m,normalizeExitCode as c}from"./format-result.js";import{isTimeoutAbortReason as u}from"../types/cancellation.js";const d=2e3,f=2500,p=1e3,v=130,T={spawn:e,killTreeDeadlineMs:f,rootKillSettleTimeoutMs:p};function w(e){return e instanceof Error?e.message:String(e)}function b(e,t){const o=new s(0).collect();return{exitCode:1,timedOut:!1,timeoutMs:t,wallTimeMs:0,stdout:o,stderr:o,spawnError:e}}function h(e,t){const o=new s(0).collect(),r=u(t);return{exitCode:r?m:v,timedOut:r,timeoutMs:e,wallTimeMs:0,stdout:o,stderr:o,terminationCause:r?a.timeout:a.abort}}export function runBashCommand(e,f=T){const{command:p,workdir:y,timeoutMs:M,maxCaptureBytes:C,profile:g,env:E,abortSignal:x,onDelta:S}=e;return new Promise(e=>{if(x?.aborted)return void e(h(M,x.reason));if(!t(y))return void e(b(`工作目录不存在: ${y}`,M));let T,$;try{const e=g.buildSpawn(p,y,E??process.env);$=e.rollSegmentFile,T=f.spawn(e.file,e.args,e.options)}catch(t){return void e(b(w(t),M))}const k=g.pipeCapability?.().capability??"none",D=()=>{if(void 0!==$)try{const e=o($,"utf8");return l(e)}catch{return}finally{try{r($)}catch{}}},L=n.now(),O=new s(C),j=new s(C);let K,P,A,B,F,I,_=!1,G=!1,N=!1,R=!1,q=!1,z=!1,H=null,J=null,Q=void 0!==T.pid,U=!1,V=!1;const W=e=>{I=I?`${I};${e}`:e},X=()=>{if(R||!q||!z)return;if(N&&!0===g.waitForTreeKillAfterRootExit&&!U&&!V)return;const e=null!==J?i.signals[J]:void 0,t=_?m:G?v:c({timedOut:!1,code:H,signalNumber:e}),o=D();oe({exitCode:t,timedOut:_,timeoutMs:M,wallTimeMs:n.now()-L,stdout:O.collect(),stderr:j.collect(),...K?{terminationCause:K}:{},...I?{terminationError:I}:{},...void 0!==o?{pipeSegments:o}:{},pipeCapability:k})},Y=()=>{if(R||q)return;for(const e of ie)e.stream.destroy();T.unref();const e=D();oe({exitCode:_?m:v,timedOut:_,timeoutMs:M,wallTimeMs:n.now()-L,stdout:O.collect(),stderr:j.collect(),...K?{terminationCause:K}:{},terminationError:`${I??"进程树清理未完成"};根进程在强制终止请求后仍未确认退出`,...void 0!==e?{pipeSegments:e}:{},pipeCapability:k})},Z=e=>{if(!R){if(B&&(clearTimeout(B),B=void 0),!U){U=!0;const t=void 0===e?"进程树清理未完成":w(e);W(`${t};已回退仅向根进程发送强制终止请求,无法确认后代进程是否已清理`)}if(q)X();else if(void 0===F){F=setTimeout(Y,f.rootKillSettleTimeoutMs);try{T.kill("SIGKILL")||W("根进程强制终止请求未被接受")}catch(e){W(`根进程强制终止请求失败: ${w(e)}`)}}}},ee=()=>{if(!N){N=!0,A=new AbortController,B=setTimeout(()=>Z(new Error("进程树清理超过独立期限")),f.killTreeDeadlineMs);try{g.killTree(T.pid,"terminate",{signal:A.signal}).then(()=>{V=!0,q&&B&&(clearTimeout(B),B=void 0),X()}).catch(Z)}catch(e){Z(e)}}},te=()=>{if(void 0!==K)return;const e=u(x?.reason);K=e?a.timeout:a.abort,_=e,G=!e,clearTimeout(ne),ee()},oe=t=>{R||(R=!0,clearTimeout(ne),P&&clearTimeout(P),B&&clearTimeout(B),F&&clearTimeout(F),A?.abort(),A=void 0,x?.removeEventListener("abort",te),e(t))},re=(e,t,o)=>{if(null===e)return;const r=new TextDecoder("utf-8");e.on("data",e=>{if(o.append(e),S){const o=r.decode(e,{stream:!0});o.length>0&&S(t,o)}});const i=new Promise(t=>{e.once("close",()=>t())});return{stream:e,closed:i}},ie=[re(T.stdout,"stdout",O),re(T.stderr,"stderr",j)].filter(e=>void 0!==e);T.once("spawn",()=>{Q=!0}),T.on("error",e=>{if(R)return;if(!N||!Q)return void oe(b(w(e),M));const t=`根进程终止请求失败: ${w(e)}`;U?W(t):Z(new Error(t,{cause:e}))}),T.on("exit",(e,t)=>{R||q||(q=!0,H=e,J=t,clearTimeout(ne),x?.removeEventListener("abort",te),V&&B&&(clearTimeout(B),B=void 0),F&&(clearTimeout(F),F=void 0),P=setTimeout(()=>{for(const e of ie)e.stream.destroy()},f.ioDrainTimeoutMs??d),Promise.all(ie.map(e=>e.closed)).then(()=>{z=!0,X()}).catch(()=>{}))});const ne=setTimeout(()=>{void 0===K&&(K=a.timeout,_=!0,ee())},M);x&&(x.aborted?te():x.addEventListener("abort",te))})}
1
+ import{spawn as e}from"node:child_process";import{existsSync as t,readFileSync as o,unlinkSync as r}from"node:fs";import{constants as i}from"node:os";import{performance as n}from"node:perf_hooks";import{OutputSink as s}from"./output-buffer.js";import{parsePipeSegments as l}from"./shell-pipe.js";import{BASH_TERMINATION_CAUSES as a,EXEC_TIMEOUT_EXIT_CODE as m,normalizeExitCode as c}from"./format-result.js";import{isTimeoutAbortReason as u}from"../types/cancellation.js";const d=2e3,f=2500,p=1e3,v=130,T={spawn:e,killTreeDeadlineMs:f,rootKillSettleTimeoutMs:p};function w(e){return e instanceof Error?e.message:String(e)}function b(e,t){const o=new s(0).collect();return{exitCode:1,timedOut:!1,timeoutMs:t,wallTimeMs:0,stdout:o,stderr:o,spawnError:e}}function h(e,t){const o=new s(0).collect(),r=u(t);return{exitCode:r?m:v,timedOut:r,timeoutMs:e,wallTimeMs:0,stdout:o,stderr:o,terminationCause:r?a.timeout:a.abort}}export function runBashCommand(e,f=T){const{command:p,workdir:y,timeoutMs:M,maxCaptureBytes:C,profile:g,env:E,abortSignal:S,onDelta:x,onSpawn:$}=e;return new Promise(e=>{if(S?.aborted)return void e(h(M,S.reason));if(!t(y))return void e(b(`工作目录不存在: ${y}`,M));let T,k;try{const e=g.buildSpawn(p,y,E??process.env);k=e.rollSegmentFile,T=f.spawn(e.file,e.args,e.options)}catch(t){return void e(b(w(t),M))}void 0!==T.pid&&$?.(T);const D=g.pipeCapability?.().capability??"none",L=()=>{if(void 0!==k)try{const e=o(k,"utf8");return l(e)}catch{return}finally{try{r(k)}catch{}}},O=n.now(),j=new s(C),K=new s(C);let P,A,B,F,I,_,G=!1,N=!1,R=!1,q=!1,z=!1,H=!1,J=null,Q=null,U=void 0!==T.pid,V=!1,W=!1;const X=e=>{_=_?`${_};${e}`:e},Y=()=>{if(q||!z||!H)return;if(R&&!0===g.waitForTreeKillAfterRootExit&&!V&&!W)return;const e=null!==Q?i.signals[Q]:void 0,t=G?m:N?v:c({timedOut:!1,code:J,signalNumber:e}),o=L();re({exitCode:t,timedOut:G,timeoutMs:M,wallTimeMs:n.now()-O,stdout:j.collect(),stderr:K.collect(),...P?{terminationCause:P}:{},..._?{terminationError:_}:{},...void 0!==o?{pipeSegments:o}:{},pipeCapability:D})},Z=()=>{if(q||z)return;for(const e of ne)e.stream.destroy();T.unref();const e=L();re({exitCode:G?m:v,timedOut:G,timeoutMs:M,wallTimeMs:n.now()-O,stdout:j.collect(),stderr:K.collect(),...P?{terminationCause:P}:{},terminationError:`${_??"进程树清理未完成"};根进程在强制终止请求后仍未确认退出`,...void 0!==e?{pipeSegments:e}:{},pipeCapability:D})},ee=e=>{if(!q){if(F&&(clearTimeout(F),F=void 0),!V){V=!0;const t=void 0===e?"进程树清理未完成":w(e);X(`${t};已回退仅向根进程发送强制终止请求,无法确认后代进程是否已清理`)}if(z)Y();else if(void 0===I){I=setTimeout(Z,f.rootKillSettleTimeoutMs);try{T.kill("SIGKILL")||X("根进程强制终止请求未被接受")}catch(e){X(`根进程强制终止请求失败: ${w(e)}`)}}}},te=()=>{if(!R){R=!0,B=new AbortController,F=setTimeout(()=>ee(new Error("进程树清理超过独立期限")),f.killTreeDeadlineMs);try{g.killTree(T.pid,"terminate",{signal:B.signal}).then(()=>{W=!0,z&&F&&(clearTimeout(F),F=void 0),Y()}).catch(ee)}catch(e){ee(e)}}},oe=()=>{if(void 0!==P)return;const e=u(S?.reason);P=e?a.timeout:a.abort,G=e,N=!e,clearTimeout(se),te()},re=t=>{q||(q=!0,clearTimeout(se),A&&clearTimeout(A),F&&clearTimeout(F),I&&clearTimeout(I),B?.abort(),B=void 0,S?.removeEventListener("abort",oe),e(t))},ie=(e,t,o)=>{if(null===e)return;const r=new TextDecoder("utf-8");e.on("data",e=>{if(o.append(e),x){const o=r.decode(e,{stream:!0});o.length>0&&x(t,o)}});const i=new Promise(t=>{e.once("close",()=>t())});return{stream:e,closed:i}},ne=[ie(T.stdout,"stdout",j),ie(T.stderr,"stderr",K)].filter(e=>void 0!==e);T.once("spawn",()=>{U=!0}),T.on("error",e=>{if(q)return;if(!R||!U)return void re(b(w(e),M));const t=`根进程终止请求失败: ${w(e)}`;V?X(t):ee(new Error(t,{cause:e}))}),T.on("exit",(e,t)=>{q||z||(z=!0,J=e,Q=t,clearTimeout(se),S?.removeEventListener("abort",oe),W&&F&&(clearTimeout(F),F=void 0),I&&(clearTimeout(I),I=void 0),A=setTimeout(()=>{for(const e of ne)e.stream.destroy()},f.ioDrainTimeoutMs??d),Promise.all(ne.map(e=>e.closed)).then(()=>{H=!0,Y()}).catch(()=>{}))});const se=setTimeout(()=>{void 0===P&&(P=a.timeout,G=!0,te())},M);S&&(S.aborted?oe():S.addEventListener("abort",oe))})}
@@ -1,3 +1,4 @@
1
+ import type { ChildProcess } from "node:child_process";
1
2
  import type { BashStreamName } from "../exec.ts";
2
3
  import type { ShellProfile } from "../profile.ts";
3
4
  import { type ManagedSession, type SessionSummary, type TerminalSessionState } from "./types.ts";
@@ -14,6 +15,7 @@ export interface SessionManagerOptions {
14
15
  readonly killTreeTimeoutMs?: number;
15
16
  readonly closeDrainTimeoutMs?: number;
16
17
  readonly rootSettleTimeoutMs?: number;
18
+ readonly onSpawn?: (child: ChildProcess) => void;
17
19
  }
18
20
  export interface SpawnRequest {
19
21
  readonly command: string;
@@ -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 r,SESSION_STATES as i,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 m(){return 1e3+Math.floor(99e3*Math.random())}function h(t){return t instanceof Error?t.message:String(t)}function u(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;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(),r=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,r),this.observeLifecycle(r),r}get(t){return this.sessions.get(t)}delete(t){const e=this.sessions.get(t);return!(void 0===e||!r(e.state))&&this.sessions.delete(t)}size(){let t=0;for(const e of this.sessions.values())e.state!==i.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:u(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(){return this.acceptingSessions=!1,this.terminateAll()}activeIds(){return[...this.sessions.values()].filter(t=>!r(t.state)).map(t=>t.id)}async stopTargets(t,e){const s="number"==typeof t?[t]:[...new Set(t)],i=[];for(const t of s){const s=this.sessions.get(t);void 0===s||r(s.state)||i.push(this.requestStop(s,e))}return Promise.all(i)}requestStop(t,e,s){const r=this.terminations.get(t.id);if(void 0!==r)return e===o.terminate&&(r.intent=e),void 0===s||r.errors.includes(s)||r.errors.push(s),r.promise;t.markStopping(e);const n={intent:e,errors:void 0===s?[]:[s],promise:Promise.resolve({sessionId:t.id,state:i.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 i=s.intent,a=await this.killTree(t,i);let p=void 0!==a;if(void 0!==a&&s.errors.push(a),i===o.interrupt&&!t.closeObserved){s.intent!==o.terminate&&await e(t.waitClose(),this.options.interruptGraceMs??n);const r=t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit;if(!t.closeObserved&&!r){const e=await this.killTree(t,o.terminate);void 0!==e&&(p=!0,s.errors.push(e))}}const m=this.options.rootSettleTimeoutMs??c;if(t.exitObserved||p||await e(t.waitExit(),m),!t.exitObserved){const r=this.forceKillRoot(t);void 0!==r&&s.errors.push(r),await e(t.waitExit(),m)}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(),r(t.state)||t.markCleanupFailed("会话清理未能收口");const h=t.state;if(!r(h))throw new Error(`会话 ${String(t.id)} 清理后仍处于非终态`);return{sessionId:t.id,state:h,...t.cleanupError?{cleanupError:t.cleanupError}:{}}}async killTree(t,e){if(t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit)return"根进程已退出,不能安全复用旧 PID 清理或确认后代进程树";const s=this.options.killTreeTimeoutMs??a,r=new AbortController;let i;try{const o=t.profile.killTree(t.child.pid,e,{signal:r.signal});return void await Promise.race([o,new Promise((t,e)=>{i=setTimeout(()=>{e(new Error(`进程树终止在 ${String(s)}ms 内未完成`)),r.abort()},s)})])}catch(t){return h(t)}finally{void 0!==i&&clearTimeout(i),r.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||r(t.state))return;const s=this.options.closeDrainTimeoutMs??l;e(t.waitSettled(),s).then(e=>{e||r(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===i.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??m;for(let e=0;e<1e3;e+=1){const e=t();if(!this.sessions.has(e))return e}throw new Error("无法分配唯一会话 id")}}
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 r,SESSION_STATES as i,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 h(){return 1e3+Math.floor(99e3*Math.random())}function m(t){return t instanceof Error?t.message:String(t)}function u(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;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(),r=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,r),void 0!==r.child.pid&&this.options.onSpawn?.(r.child),this.observeLifecycle(r),r}get(t){return this.sessions.get(t)}delete(t){const e=this.sessions.get(t);return!(void 0===e||!r(e.state))&&this.sessions.delete(t)}size(){let t=0;for(const e of this.sessions.values())e.state!==i.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:u(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(){return this.acceptingSessions=!1,this.terminateAll()}activeIds(){return[...this.sessions.values()].filter(t=>!r(t.state)).map(t=>t.id)}async stopTargets(t,e){const s="number"==typeof t?[t]:[...new Set(t)],i=[];for(const t of s){const s=this.sessions.get(t);void 0===s||r(s.state)||i.push(this.requestStop(s,e))}return Promise.all(i)}requestStop(t,e,s){const r=this.terminations.get(t.id);if(void 0!==r)return e===o.terminate&&(r.intent=e),void 0===s||r.errors.includes(s)||r.errors.push(s),r.promise;t.markStopping(e);const n={intent:e,errors:void 0===s?[]:[s],promise:Promise.resolve({sessionId:t.id,state:i.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 i=s.intent,a=await this.killTree(t,i);let p=void 0!==a;if(void 0!==a&&s.errors.push(a),i===o.interrupt&&!t.closeObserved){s.intent!==o.terminate&&await e(t.waitClose(),this.options.interruptGraceMs??n);const r=t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit;if(!t.closeObserved&&!r){const e=await this.killTree(t,o.terminate);void 0!==e&&(p=!0,s.errors.push(e))}}const h=this.options.rootSettleTimeoutMs??c;if(t.exitObserved||p||await e(t.waitExit(),h),!t.exitObserved){const r=this.forceKillRoot(t);void 0!==r&&s.errors.push(r),await e(t.waitExit(),h)}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(),r(t.state)||t.markCleanupFailed("会话清理未能收口");const m=t.state;if(!r(m))throw new Error(`会话 ${String(t.id)} 清理后仍处于非终态`);return{sessionId:t.id,state:m,...t.cleanupError?{cleanupError:t.cleanupError}:{}}}async killTree(t,e){if(t.exitObserved&&!0===t.profile.waitForTreeKillAfterRootExit)return"根进程已退出,不能安全复用旧 PID 清理或确认后代进程树";const s=this.options.killTreeTimeoutMs??a,r=new AbortController;let i;try{const o=t.profile.killTree(t.child.pid,e,{signal:r.signal});return void await Promise.race([o,new Promise((t,e)=>{i=setTimeout(()=>{e(new Error(`进程树终止在 ${String(s)}ms 内未完成`)),r.abort()},s)})])}catch(t){return m(t)}finally{void 0!==i&&clearTimeout(i),r.abort()}}forceKillRoot(t){if(!t.exitObserved)try{return t.child.kill("SIGKILL")?void 0:"根进程强制终止请求未被接受"}catch(t){return`根进程强制终止请求失败: ${m(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||r(t.state))return;const s=this.options.closeDrainTimeoutMs??l;e(t.waitSettled(),s).then(e=>{e||r(t.state)||this.requestStop(t,o.terminate,`根进程退出后 stdio 在 ${String(s)}ms 内未关闭`).catch(e=>{t.markCleanupFailed(`会话自动清理失败:${m(e)}`)})})})}trimTombstones(){const t=[...this.sessions.values()].filter(t=>t.state===i.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??h;for(let e=0;e<1e3;e+=1){const e=t();if(!this.sessions.has(e))return e}throw new Error("无法分配唯一会话 id")}}
@@ -1,3 +1,4 @@
1
+ import type { ChildProcess } from "node:child_process";
1
2
  import { type SessionSendInput } from "./session-attachments.ts";
2
3
  import { type ModelMessage } from "ai";
3
4
  import type { LanguageModelV4, LanguageModelV4CallOptions, SharedV4ProviderOptions } from "@ai-sdk/provider";
@@ -7,6 +8,7 @@ import type { ContextCompactionReason, ContextCompactionStrategy, SessionEvent,
7
8
  import type { ToolPolicy } from "../types/policy.ts";
8
9
  import { type AgentToolSource } from "../tool-bridge/build-tools.ts";
9
10
  import { type AgentInstallToolCatalogEntry, type AgentInstallToolOutcome } from "../tool-bridge/agent-install-tool.ts";
11
+ import { type ScheduleToolDeps } from "../tool-bridge/schedule-tool.ts";
10
12
  import { type SessionFileToolsSettings } from "../tool-bridge/file-tools/index.ts";
11
13
  import { type SessionBashSettings } from "../tool-bridge/bash-tool.ts";
12
14
  import type { ShellProfile } from "../bash/profile.ts";
@@ -69,6 +71,7 @@ export interface AgentSessionOptions {
69
71
  readonly bashClassifier?: CommandClassifier;
70
72
  readonly bashSession?: AgentSessionBashSession;
71
73
  readonly agentInstall?: AgentSessionAgentInstall;
74
+ readonly schedules?: ScheduleToolDeps;
72
75
  readonly onClose?: () => void;
73
76
  }
74
77
  export interface AgentSessionCapabilityContext {
@@ -103,6 +106,7 @@ export interface AgentSessionBashSession {
103
106
  readonly maxOutputTokens: number;
104
107
  readonly bufferCapacity: number;
105
108
  readonly env?: NodeJS.ProcessEnv;
109
+ readonly onCommandSpawn?: (child: ChildProcess) => void;
106
110
  }
107
111
  export type SessionSkillSummary = SkillSummary;
108
112
  export type SessionToolExecutionRecordView = SequencedToolExecutionRecord | (RedactedToolExecutionRecordSummary & {
@@ -1 +1 @@
1
- import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{buildFileToolset as h}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as m}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as g,EXEC_LIST_NAME as v,EXEC_POLL_NAME as f,buildSessionExecToolset as y}from"../tool-bridge/session-exec-tool.js";import{SessionManager as T}from"../bash/session/session-manager.js";import{isTerminalSessionState as C}from"../bash/session/types.js";import{withCleanEnv as k}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as b,SESSION_CANCELLATION_REASONS as x,TURN_TIMEOUT_ABORT_REASON as S,USER_CANCELLATION_ABORT_REASON as I,createTurnCancellationMessage as M,isTurnTimeoutAbortReason as E,stripTurnCancellationMetadata as w}from"../types/cancellation.js";import{ToolRegistry as P}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as R,TOOL_OUTCOME_KINDS as q,createToolResult as A,failedToolResult as N,isNormalizedToolResult as O,normalizeToolResult as $,readDisplayOutput as j,readToolOutcome as W}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as D}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as L,prepareToolExecutionRecordForPersistence as F,redactSecretText as U,toRedactedToolExecutionRecordSummary as V}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as _,ToolExecutionCoordinator as G}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as z}from"../approval/approval-gate.js";import{SessionApprovalMemory as J}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as B,compactMessages as H,CompactionDraftFallbackError as K,estimateMessagesTokens as Y,estimateTextTokens as Q,isCompactionSummaryAcknowledgement as X,readCompactionSummaryPayload as Z}from"./compactor.js";import{AsyncEventQueue as ee}from"./event-queue.js";import{applyExplicitSkillContext as te,attachExplicitSkillCheckpoint as se,prepareExplicitSkillContext as oe,readExplicitSkillCheckpoint as ie,stripExplicitSkillCheckpoints as ne}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as re,createToolLedgerGapRecoveryMessage as ae,materializeCancelledTurnRecoveryMessages as ce,stripCancelledTurnRecoveryMessages as le}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as ue,CAPABILITY_TOOL_ROLES as pe,buildEffectiveCapabilityTurnContext as de,buildEffectiveCapabilityManifest as he,findCapabilityToolId as me}from"./capability-manifest.js";import{buildCapabilityTurnReminder as ge,buildChatSystemPromptFromManifest as ve}from"./system-prompt.js";import{buildCompactionCheckpointReminder as fe,buildCompactionToolState as ye,COMPACTION_CHECKPOINT_VERSION as Te,createCompactionCheckpoint as Ce,createCompactionSummary as ke,createCheckpointSemanticReminderProjection as be,findLatestRealUserGoal as xe,resolveActiveCompactionConstraints as Se,TRANSCRIPT_MESSAGE_PROVENANCES as Ie}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as Me,buildCompactionSemanticEvidenceRegistry as Ee,mergeCompactionSemanticState as we,replaceCompactionSemanticConstraints as Pe,replaceCompactionSemanticGoal as Re,renderCompactionSemanticSummary as qe,seedCompactionSemanticConstraints as Ae,seedLegacyCompactionSnapshotUncertainties as Ne,validateCompactionModelDraft as Oe}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as $e,repairActiveToolProtocol as je}from"./tool-protocol-repair.js";import{buildTranscriptToolset as We}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as De}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Le}from"../tool-bridge/user-input-tool.js";const Fe=6e3,Ue=3e5,Ve=4,_e=2,Ge=1,ze={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},Je="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Be=1024,He="AI_InvalidToolInputError:",Ke={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Ye(t){const s=[...t];if(s.length<=Be)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Be-[...o].length).join("")}${o}`}function Qe(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function Xe(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function Ze(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function et(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function tt(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function st(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function ot(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=it(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function it(e){try{return JSON.stringify(e)??void 0}catch{return}}function nt(e){const t=ie(e.message),[s]=ne([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(r(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function rt(e){return JSON.stringify(e)??String(e)}function at(e){const t=F(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:rt(t.input.value),resultSummary:rt(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===q.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function ct(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==Z(e.content)||"assistant"===e.role&&X(e.content)}function lt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=Z(e.content);if(void 0!==t)return 0===t.length?[]:[U(t)]}return"assistant"===e.role&&X(e.content)?[]:[U(nt({sequence:t,provenance:Ie[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!ct(e)).length}}function ut(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function pt(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===Te?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function dt(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 ht(e){return ot(j(e))}function mt(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(He)?q.invalidInput:q.toolFailed}function gt(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>W(e.output).kind===q.userRejected)??!1}function vt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(ot(e))}function ft(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 yt(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function Tt(e,t){const s=yt(e.cachedInputTokens,t.cachedInputTokens),o=yt(e.cacheWriteTokens,t.cacheWriteTokens),i=yt(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 Ct(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function kt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function bt(e,t){return void 0!==e?e:E(t)?x.timeout:x.runtime}function xt(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 St(e,t,s){for(const o of Object.keys(t))e[o]=s}function It(e,t,s){const o={[g]:pe.sessionCommand,[f]:pe.sessionPoll,[v]:pe.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function Mt(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;gate=new z;userInputInteractions=new De;toolCoordinator=new G;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?xt(e.initialMessages):[];this.messages=[...je(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?lt(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=pt(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)ct(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Ie[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName));const o=new P,i={},n=Le({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,St(i,n.tools,pe.userInput);const r=e.readCheckpointTranscript?We(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};St(i,r,pe.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};St(i,a,pe.skill);const c=new J,l=e.fileTools?h(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(St(i,l.readTools,pe.fileRead),St(i,l.editTools,pe.fileEdit),St(i,l.verifyTools,pe.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},g=e.bashClassifier?{classifier:e.bashClassifier}:{},v=e.bash?m(e.bash,o,d,g):{};St(i,v,pe.shell),e.bashSession&&(this.sessionManager=new T({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:k(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity}));const f=e.bashSession&&this.sessionManager?y({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...g,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};It(i,f,o);const C=e.agentInstall,b=C?p({catalog:C.catalog,install:async(e,t)=>{const s=await C.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}):{};St(i,b,pe.agentInstall);const x=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);St(i,x.tools,pe.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...v,...f,...b,...x.tools},this.registry=x.registry,this.toolRoles=i,this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return he({tools:this.tools,toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??ue.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=ve(this.capabilityManifest,{...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);St(this.toolRoles,t.tools,pe.agent),this.tools={...this.tools,...t.tools},this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);St(this.toolRoles,e,pe.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=n(e),s=new ee;this.emit=e=>s.push(e);const o=Qe();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:ot(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new ee;this.emit=e=>t.push(e);const s=Qe();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:ot(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${ot(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:ot(t)})}if(s.aborted||s.abortController.signal.aborted)return l=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(e,s,l,r);e.push({type:"message-start",messageId:t()}),void 0!==this.turnTimeoutMs&&(s.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),u=setTimeout(()=>{s.abortController.signal.aborted||(this.captureCancellationActivity(s),s.aborted=!0,s.cancellationReason=x.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(S))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=oe({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},m=d.skillNames.length>0?se(h,d):h;let g={};try{g=await dt(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(m),s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:ot(t)})}const v=de(this.capabilityManifest,{explicitSkillNames:d.skillNames,...g.ruleIds?{ruleIds:g.ruleIds}:{},...g.vcs?{vcs:g.vcs}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=v;const f=ge(v);let y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||this.messages.push(m);const n=me(this.capabilityManifest,pe.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:Q(u),h=ne(w(ce(this.messages))),g=Mt(d.skillNames.length>0?te(h,d):h,u?`${f}\n\n${u}`:f);this.debug(e,"model","calling streamText",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let v=0;const T=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.tools,prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),gt(),this.stopOnContextPressure(s)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(s,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:s.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{Xe(s,e),v=Y(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)Xe(s,t)}});let C;try{C=T()}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!vt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,m,!1,r),void e.push({type:"error",stage:"execute",message:ot(t)})}this.debug(e,"model","streamText returned",r);let k,b,S,I,M,P,R,A="",j="",W=!1,F=0,U=!1,V=!1;const _=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of C.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=x.runtime;break}switch(V||(V=!0,this.clearDebugTimer(_),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!W){const s=j+t.text;if(kt(s,d.userPrompt)){j=s;break}if(j.length>0){const s=j+t.text;j="",A+=s,e.push({type:"text-delta",delta:s});break}}A+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{W=!0,j="";const o=this.trackPendingToolCall(s,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));e.push({type:"tool-call",toolCallId:t.toolCallId,agentName:o.agentName,toolName:o.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=s.pendingToolCalls.get(t.toolCallId),n=O(t.output)?t.output:$(t.output),r=n.outcome,a=n.display,c=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==q.userRejected&&r.kind!==q.policyDenied&&r.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===q.success&&void 0!==i&&this.rememberCompactionResources(c,i.resources),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,outcome:r,display:a,output:a,isError:r.kind!==q.success}),s.aborted||s.abortController.signal.aborted||r.kind!==q.userRejected||(R=ht(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=mt(t.error),n=(i===q.invalidInput?D(t.error):void 0)??ht(t.error),r=N(i,n,{raw:t.error}),a=L({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==q.invalidInput&&(s.hadPotentialSideEffects=!0),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:n,isError:!0});break}case"finish-step":{const s=ft(t.usage);b=Ct(b,s.inputTokens),S=s.outputTokens,F+=1,M=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(I=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!W&&j.length>0&&(A+=j,e.push({type:"text-delta",delta:j}),j=""),k=ft(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||E(t.error)){s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t.error);break}U=vt(t.error),U&&(this.needsCompaction=!0),P=ot(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||E(e)?(s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,e)):(U=vt(e),U&&(this.needsCompaction=!0),P=ot(e))}finally{this.clearDebugTimer(_)}if(this.debug(e,"model","fullStream finished",r,{textChars:A.length}),void 0!==P){if(this.messages.splice(l),U){const t=0===A.length&&!W,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${P}${a}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:P})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let G;this.debug(e,"model","awaiting response messages",r);const z=this.scheduleDebug(e,"model","still awaiting response messages",r);try{G=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(z),this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=vt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===A.length&&!W,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,A.length>0,r),void e.push({type:"error",stage:"execute",message:`${ot(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:ot(t)})}finally{this.clearDebugTimer(z)}if(this.debug(e,"model","response messages ready",r,{responseMessages:G.length}),this.isTurnAborted(s))return s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const J=xt(G);if(this.messages.push(...J),void 0!==R){const t=0===A.length?R:`\n${R}`;A+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:R})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),st(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),k&&(this.sessionUsage=Tt(this.sessionUsage,k));const B=b??k?.inputTokens;void 0!==B&&(this.lastInputTokens=B,this.lastStepOutputTokens=S,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,B-Y(this.messages)+(S??0)+v-p)),s.completedStepCount+=F;const H=s.completedStepCount>=this.maxSteps&&"tool-calls"===M;if(e.push({type:"message-finish",text:A,...k?{totalUsage:k}:{},sessionUsage:{...this.sessionUsage},...void 0!==b?{contextInputTokens:b}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:ot(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||E(t))return s.aborted=!0,s.cancellationReason=bt(s.cancellationReason,s.abortController.signal.reason??t),void(void 0!==l?this.persistCancelledTurn(e,s,l,r):this.emitCancellation(e,s));void 0!==l&&this.messages.splice(l),this.debug(e,"turn","error",r,{message:ot(t)}),e.push({type:"error",stage:"execute",message:ot(t)})}finally{void 0!==u&&clearTimeout(u),this.toolCoordinator.finishTurn(),this.activeTurn===s&&(this.activeTurn=void 0),e.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)ct(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Ie[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=ae(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!==q.policyDenied&&e.outcome.kind!==q.userRejected&&e.outcome.kind!==q.invalidInput&&(e.outcome.kind!==q.cancelled||e.outcome.executionState!==R.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?[]:[ae(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=Ze(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=je(xt(et(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,re({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 的操作。${Je}`}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}: ${ot(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:Ye(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===_.write||t.mode!==_.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+Ue,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return ne(le(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=>({...V(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:{...V(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>W(e.output).kind===q.userRejected))return!1;const i=ft(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Y(this.messages)+Y(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Y(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Y([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Y(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Y(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(me(this.capabilityManifest,pe.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:Q(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?fe(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,Ze(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:Y([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ie(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:C(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=xe(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===Te?this.compactionCheckpoint.semanticState:void 0,u=Ae(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&ut(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?Ne(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=pt(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,y=e.filter(e=>e.sequence>v),T=new Set(y.filter(e=>e.provenance===Ie[1]&&ct(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),k=Ee({messages:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:nt(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(at),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),b=Me(k,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:k,modelContext:b.prompt,presentedEvidenceIds:b.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=Oe({draft:s??Ke,evidenceRegistry:t.registry,presentedEvidenceIds:t.presentedEvidenceIds,...void 0!==t.previousSemanticState?{previousState:t.previousSemanticState}:{},...void 0!==t.goal?{harnessGoal:{verbatimRequest:t.goal.verbatimRequest,sourceSequence:t.goal.sourceSequence}}:{}});let r=we(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Se(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=Pe(r,e);const o=void 0===this.compactionCheckpoint?.goal?t.goal:void 0===t.goal||void 0===t.newGoalSourceSequence||s?this.compactionCheckpoint.goal:t.goal;r=Re(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:xe(t.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??t.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?qe(r):void 0,d=void 0!==p?ke(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(be(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=ye(t.transcript.map(e=>e.message),t.toolExecutions,32,t.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...t.resources],toolState:g,runningWork:[...t.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:e("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(t.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:t.expectedActiveMessages,expectedLatestCheckpointId:t.expectedLatestCheckpointId,evidenceWatermarks:t.evidenceWatermarks,legacySnapshotTranscriptFragments:t.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:ot(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g;try{const t=Date.now();try{g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new K(B.missingObject,"structured compaction draft is missing")}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!K.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:ot(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await H({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const v=g.removed>0||g.truncatedTools>0,f=Date.now(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=je(g.messages),C=[...T.messages];if(T.status===$e.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(ct))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const k=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),b=v&&k(C)<k(this.messages),x=b?C:[...this.messages],S=b?this.advanceCompactionSemanticEvidenceWatermarks(h,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(b){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=Ce({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,...b&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,truncatedTools:b?g.truncatedTools:0,progressed:b}),b}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:ot(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!C(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${ot(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=x.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(b))}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??x.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===x.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===x.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=me(this.capabilityManifest,pe.sessionList);switch(t){case x.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case x.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":this.capabilityManifest.lifecycle.hostMode===ue.oneShot?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case x.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??x.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=me(this.capabilityManifest,pe.sessionList),n=Je;switch(t){case x.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case x.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:this.capabilityManifest.lifecycle.hostMode===ue.oneShot?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case x.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=x.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,ze.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=ze.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===ze.keepRaw,r=n?je(xt(et(t))).messages:[],a=n?Ze(t):tt(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[re({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),M(this.cancellationDisplayMessage(e),e.cancellationReason??x.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${ot(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??x.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?R.outcomeUnknown:R.notExecuted,i=o===R.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=A({kind:q.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:ot(e.abortController.signal.reason)}});this.persistToolExecution(L({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=x.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(I),!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??=x.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(b)),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} 后台清理失败: ${ot(e)}\n`)});await s(e,Fe)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Fe)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${ot(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${ot(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
1
+ import{createHash as e,randomUUID as t}from"node:crypto";import{waitForPromiseSettlement as s}from"../bounded-wait.js";import{relocateToolImagesToUserMessages as o}from"./relocate-tool-images.js";import{buildUserMessageContent as i,normalizeSessionSendInput as n,redactBinaryPartsForEvidence as r}from"./session-attachments.js";import{stepCountIs as a,streamText as c,InvalidToolInputError as l}from"ai";import{buildAgentToolset as u}from"../tool-bridge/build-tools.js";import{buildAgentInstallToolset as p}from"../tool-bridge/agent-install-tool.js";import{buildSkillToolset as d}from"../tool-bridge/skill-tool.js";import{buildScheduleToolset as h}from"../tool-bridge/schedule-tool.js";import{buildFileToolset as m}from"../tool-bridge/file-tools/index.js";import{buildBashToolset as g}from"../tool-bridge/bash-tool.js";import{EXEC_COMMAND_NAME as v,EXEC_LIST_NAME as f,EXEC_POLL_NAME as y,buildSessionExecToolset as T}from"../tool-bridge/session-exec-tool.js";import{SessionManager as C}from"../bash/session/session-manager.js";import{isTerminalSessionState as k}from"../bash/session/types.js";import{withCleanEnv as b}from"../bash/clean-env.js";import{RUNTIME_CANCELLATION_ABORT_REASON as x,SESSION_CANCELLATION_REASONS as S,TURN_TIMEOUT_ABORT_REASON as I,USER_CANCELLATION_ABORT_REASON as M,createTurnCancellationMessage as E,isTurnTimeoutAbortReason as w,stripTurnCancellationMetadata as P}from"../types/cancellation.js";import{ToolRegistry as R}from"../tool-bridge/naming.js";import{TOOL_CANCELLATION_EXECUTION_STATES as q,TOOL_OUTCOME_KINDS as A,createToolResult as N,failedToolResult as O,isNormalizedToolResult as $,normalizeToolResult as j,readDisplayOutput as W,readToolOutcome as D}from"../tool-bridge/normalize-result.js";import{friendlyInvalidToolInputMessage as L}from"../tool-bridge/bounded-param.js";import{createToolExecutionRecord as F,prepareToolExecutionRecordForPersistence as U,redactSecretText as V,toRedactedToolExecutionRecordSummary as _}from"../tool-bridge/tool-execution-record.js";import{TOOL_RESOURCE_ACCESS_MODES as G,ToolExecutionCoordinator as z}from"../tool-bridge/tool-execution-coordinator.js";import{ApprovalGate as J}from"../approval/approval-gate.js";import{SessionApprovalMemory as B}from"../approval/approval-memory.js";import{COMPACTION_DRAFT_FALLBACK_REASONS as H,compactMessages as K,CompactionDraftFallbackError as Y,estimateMessagesTokens as Q,estimateTextTokens as X,isCompactionSummaryAcknowledgement as Z,readCompactionSummaryPayload as ee}from"./compactor.js";import{AsyncEventQueue as te}from"./event-queue.js";import{applyExplicitSkillContext as se,attachExplicitSkillCheckpoint as oe,prepareExplicitSkillContext as ie,readExplicitSkillCheckpoint as ne,stripExplicitSkillCheckpoints as re}from"./explicit-skill-context.js";import{createCancelledTurnRecoveryMessage as ae,createToolLedgerGapRecoveryMessage as ce,materializeCancelledTurnRecoveryMessages as le,stripCancelledTurnRecoveryMessages as ue}from"./cancelled-turn-recovery.js";import{CAPABILITY_HOST_MODES as pe,CAPABILITY_TOOL_ROLES as de,buildEffectiveCapabilityTurnContext as he,buildEffectiveCapabilityManifest as me,findCapabilityToolId as ge,isProcessBoundHostMode as ve}from"./capability-manifest.js";import{buildCapabilityTurnReminder as fe,buildChatSystemPromptFromManifest as ye}from"./system-prompt.js";import{buildCompactionCheckpointReminder as Te,buildCompactionToolState as Ce,COMPACTION_CHECKPOINT_VERSION as ke,createCompactionCheckpoint as be,createCompactionSummary as xe,createCheckpointSemanticReminderProjection as Se,findLatestRealUserGoal as Ie,resolveActiveCompactionConstraints as Me,TRANSCRIPT_MESSAGE_PROVENANCES as Ee}from"./compaction-checkpoint.js";import{buildCompactionSemanticModelContext as we,buildCompactionSemanticEvidenceRegistry as Pe,mergeCompactionSemanticState as Re,replaceCompactionSemanticConstraints as qe,replaceCompactionSemanticGoal as Ae,renderCompactionSemanticSummary as Ne,seedCompactionSemanticConstraints as Oe,seedLegacyCompactionSnapshotUncertainties as $e,validateCompactionModelDraft as je}from"./compaction-semantic-state.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as We,repairActiveToolProtocol as De}from"./tool-protocol-repair.js";import{buildTranscriptToolset as Le}from"../tool-bridge/transcript-tool.js";import{UserInputInteractionManager as Fe}from"../interaction/user-input-interaction-manager.js";import{buildUserInputTool as Ue}from"../tool-bridge/user-input-tool.js";const Ve=6e3,_e=3e5,Ge=4,ze=2,Je=1,Be={keepRaw:"keep-raw",ledgerOnly:"ledger-only"},He="这份恢复记录只描述上一轮的权威历史事实,不授权继续或重试旧任务。下一轮必须以最新真实用户消息的目标和约束为准;如果用户换题、放弃旧任务或禁止工具,不得为了恢复旧任务检查或调用工具。executionState=not_executed 表示工具确定未执行,无需检查;executionState=outcome_unknown 只允许在最新用户明确要求继续或核对上一任务时先检查,检查不等于重试。",Ke=1024,Ye="AI_InvalidToolInputError:",Qe={startsNewGoalScope:!1,goal:null,constraints:[],decisions:[],completedWork:[],pendingWork:[],resources:[],runningSessions:[],uncertainties:[],resolutions:[],evidenceReviews:[]};function Xe(t){const s=[...t];if(s.length<=Ke)return t;const o=`…#${e("sha256").update(t).digest("hex").slice(0,16)}`;return`${s.slice(0,Ke-[...o].length).join("")}${o}`}function Ze(){return{abortController:new AbortController,execSessionIds:new Set,pendingToolCalls:new Map,completedStepResponses:new Map,persistedStepKeys:new Set,toolExecutions:[],userMessagePersisted:!1,hadPotentialSideEffects:!1,aborted:!1,cancellationEventEmitted:!1,cancellationPersistenceAttempted:!1,cancellationPersisted:!1,pausedForContextPressure:!1,contextPressureContinuations:0,completedStepCount:0}}function et(e,t){e.completedStepResponses.set(`${t.callId}:${String(t.stepNumber)}`,[...t.response.messages])}function tt(e){return[...e.completedStepResponses.values()].flatMap(e=>[...e])}function st(e){return[...e.completedStepResponses.entries()].filter(([t])=>!e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function ot(e){return[...e.completedStepResponses.entries()].filter(([t])=>e.persistedStepKeys.has(t)).flatMap(([,e])=>[...e])}function it(e){for(const t of e.completedStepResponses.keys())e.persistedStepKeys.add(t);e.userMessagePersisted=!0}function nt(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e){if("message"in e&&"string"==typeof e.message&&e.message.length>0)return e.message;const t=rt(e);if(void 0!==t&&"{}"!==t)return t}return String(e)}function rt(e){try{return JSON.stringify(e)??void 0}catch{return}}function at(e){const t=ne(e.message),[s]=re([e.message]),o=s??e.message,i=void 0!==t&&"user"===o.role?t.snapshot.userPrompt:"string"==typeof o.content?o.content:JSON.stringify(r(o.content));return`message ${String(e.sequence)} ${o.role}: ${i}`}function ct(e){return JSON.stringify(e)??String(e)}function lt(e){const t=U(e);return{id:e.id,agentName:e.agentName,toolName:e.toolName,inputSummary:ct(t.input.value),resultSummary:ct(t.model),outcome:{kind:e.outcome.kind,...e.outcome.kind===A.cancelled&&void 0!==e.outcome.executionState?{executionState:e.outcome.executionState}:{}}}}function ut(e){return"user"===e.role&&"string"==typeof e.content&&void 0!==ee(e.content)||"assistant"===e.role&&Z(e.content)}function pt(e,t){const s=t.flatMap((e,t)=>{if("user"===e.role&&"string"==typeof e.content){const t=ee(e.content);if(void 0!==t)return 0===t.length?[]:[V(t)]}return"assistant"===e.role&&Z(e.content)?[]:[V(at({sequence:t,provenance:Ee[1],createdAt:new Date(0).toISOString(),message:e}))]});return{checkpointId:e,messageFingerprints:t.map(e=>JSON.stringify(e)),fragments:s,removableRawMessageCount:t.filter(e=>!ut(e)).length}}function dt(e,t,s){return!(1!==t?.version||t.id!==e.checkpointId||s.length<e.messageFingerprints.length)&&e.messageFingerprints.every((e,t)=>JSON.stringify(s[t])===e)}function ht(e){return void 0===e?{messagesThroughSequence:-1,toolExecutionsThroughSequence:-1}:e.version===ke?e.semanticEvidence:{messagesThroughSequence:e.transcript.messages.throughSequence,toolExecutionsThroughSequence:e.transcript.toolExecutions.throughSequence}}function mt(e,t){return t.aborted?Promise.reject(t.reason):new Promise((s,o)=>{let i=!1;const n=e=>{i||(i=!0,t.removeEventListener("abort",r),e())},r=()=>n(()=>o(t.reason));t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(e=>n(()=>s(e)),e=>n(()=>o(e)))})}function gt(e){return nt(W(e))}function vt(e){return l.isInstance(e)||"string"==typeof e&&e.startsWith(Ye)?A.invalidInput:A.toolFailed}function ft(){return({steps:e})=>e.at(-1)?.toolResults.some(e=>D(e.output).kind===A.userRejected)??!1}function yt(e){return/context[_ -]?length|context window|maximum context|token limit|too many tokens|prompt is too long|input is too long/i.test(nt(e))}function Tt(e){const t=e.inputTokenDetails?.cacheReadTokens,s=e.inputTokenDetails?.cacheWriteTokens,o=e.outputTokenDetails?.reasoningTokens;return{...void 0!==e.inputTokens?{inputTokens:e.inputTokens}:{},...void 0!==e.outputTokens?{outputTokens:e.outputTokens}:{},...void 0!==e.totalTokens?{totalTokens:e.totalTokens}:{},...void 0!==t?{cachedInputTokens:t}:{},...void 0!==s?{cacheWriteTokens:s}:{},...void 0!==o?{reasoningTokens:o}:{}}}function Ct(e,t){return void 0===e&&void 0===t?void 0:(e??0)+(t??0)}function kt(e,t){const s=Ct(e.cachedInputTokens,t.cachedInputTokens),o=Ct(e.cacheWriteTokens,t.cacheWriteTokens),i=Ct(e.reasoningTokens,t.reasoningTokens);return{inputTokens:(e.inputTokens??0)+(t.inputTokens??0),outputTokens:(e.outputTokens??0)+(t.outputTokens??0),totalTokens:(e.totalTokens??0)+(t.totalTokens??0),...void 0!==s?{cachedInputTokens:s}:{},...void 0!==o?{cacheWriteTokens:o}:{},...void 0!==i?{reasoningTokens:i}:{}}}function bt(e,t){return void 0===t?e:void 0===e?t:Math.max(e,t)}function xt(e,t){const s=e.trim(),o=t.trim();return s.length>0&&o.length>0&&o.startsWith(s)}function St(e,t){return void 0!==e?e:w(t)?S.timeout:S.runtime}function It(e){return e.flatMap(e=>{if("assistant"!==e.role||!Array.isArray(e.content))return[e];const t=e.content.filter(e=>"reasoning"!==e.type);return 0===t.length?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function Mt(e,t,s){for(const o of Object.keys(t))e[o]=s}function Et(e,t,s){const o={[v]:de.sessionCommand,[y]:de.sessionPoll,[f]:de.sessionList};for(const i of Object.keys(t)){const t=s.resolve(i),n=t?o[t.toolName]:void 0;n&&(e[i]=n)}}function wt(e,t){const s=[...e];for(let e=s.length-1;e>=0;e-=1){const o=s[e];if("user"===o?.role){s[e]={...o,content:"string"==typeof o.content?`${t}\n\n${o.content}`:[{type:"text",text:t},...o.content]};break}}return s}export class AgentSession{id;model;maxSteps;messages;onPersist;onReplace;onToolExecution;listPersistedToolExecutions;getPersistedToolExecution;recoverPersistedToolExecutionContext;listPersistedTranscriptMessages;commitPersistedCompaction;inMemoryToolExecutions=[];uncoveredToolExecutions=new Map;inMemoryTranscript=[];legacyV1ActiveSnapshot;compactionResources=new Map;contextWindow;compaction;turnTimeoutMs;onClose;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;onProviderOptionsChange;debugEvents;policy;systemPrompt;explicitSystemPrompt;lastExtraPrompt;workspaceInstructions;appliedWorkspaceInstructions;capabilityContext;resolveDynamicCapabilityContext;capabilityManifest;lastCapabilityTurnContext;toolRoles;skillSummaries;skillLibrary;skillToolBuilt=!1;toolSourceAgentNames;gate=new J;userInputInteractions=new Fe;toolCoordinator=new z;tools;registry;userInputToolId;userInputTool;userInputAvailable=!1;sessionManager;sessionManagerInstanceId=t();compactionCheckpoint;emit;activeTurn;closePromise;closed=!1;sessionUsage={inputTokens:0,outputTokens:0,totalTokens:0};lastInputTokens;lastStepOutputTokens;lastStepToolResultTokens;measuredMessageCount;promptOverhead;needsCompaction=!1;constructor(e){this.id=e.id,this.model=e.model,this.maxSteps=e.maxSteps;const t=e.initialMessages?It(e.initialMessages):[];this.messages=[...De(t).messages],this.legacyV1ActiveSnapshot=1===e.initialCheckpoint?.version?pt(e.initialCheckpoint.id,this.messages):void 0,this.onPersist=e.onPersist,this.onReplace=e.onReplace,this.onToolExecution=e.onToolExecution,this.listPersistedToolExecutions=e.listToolExecutions,this.getPersistedToolExecution=e.getToolExecution,this.recoverPersistedToolExecutionContext=e.recoverUncoveredToolExecutions,this.listPersistedTranscriptMessages=e.listTranscriptMessages,this.commitPersistedCompaction=e.commitCompaction,this.compactionCheckpoint=e.initialCheckpoint;let s=ht(e.initialCheckpoint).messagesThroughSequence+1;for(const e of this.messages)ut(e)||(this.inMemoryTranscript.push({sequence:s,provenance:Ee[0],createdAt:new Date(0).toISOString(),message:e}),s+=1);for(const t of e.initialCheckpoint?.resources??[])this.retainCompactionResource(t);this.contextWindow=e.contextWindow,this.compaction=e.compaction,this.turnTimeoutMs=e.turnTimeoutMs,this.onClose=e.onClose,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.onProviderOptionsChange=e.onProviderOptionsChange,this.debugEvents=e.debugEvents??!1,this.policy=e.policy,this.explicitSystemPrompt=e.systemPrompt,this.workspaceInstructions=e.workspaceInstructions,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary?.list()??[],this.toolSourceAgentNames=new Set(e.sources.map(e=>e.agentName));const o=new R,i={},n=Ue({sessionId:this.id,isAvailable:()=>this.userInputAvailable,request:(e,t)=>this.requestUserInput(e,t)},o,this.toolCoordinator);this.userInputToolId=n.id,this.userInputTool=n.tools,Mt(i,n.tools,de.userInput);const r=e.readCheckpointTranscript?Le(e.readCheckpointTranscript,o,this.toolCoordinator,`thread:${this.id}:transcript`):{};Mt(i,r,de.transcriptRead);const a=e.skillLibrary?this.buildSkillTools(o):{};Mt(i,a,de.skill);const c=new B,l=e.fileTools?m(e.fileTools,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator,approvalMemory:c}):void 0;l&&(Mt(i,l.readTools,de.fileRead),Mt(i,l.editTools,de.fileEdit),Mt(i,l.verifyTools,de.fileVerify));const d={...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),emitEvent:e=>this.emit?.(e),coordinator:this.toolCoordinator},v=e.bashClassifier?{classifier:e.bashClassifier}:{},f=e.bash?g(e.bash,o,d,v):{};Mt(i,f,de.shell),e.bashSession&&(this.sessionManager=new C({maxSessions:e.bashSession.maxSessions,profile:e.bashSession.profile,env:b(e.bashSession.env??process.env),bufferCapacity:e.bashSession.bufferCapacity,...e.bashSession.onCommandSpawn?{onSpawn:e.bashSession.onCommandSpawn}:{}}));const y=e.bashSession&&this.sessionManager?T({workdir:e.bashSession.workdir,defaultYieldMs:e.bashSession.defaultYieldMs,maxOutputTokens:e.bashSession.maxOutputTokens,...e.bashSession.env?{env:e.bashSession.env}:{}},this.sessionManager,o,d,{...v,onSessionTouched:e=>this.activeTurn?.execSessionIds.add(e)}):{};Et(i,y,o);const k=e.agentInstall,x=k?p({catalog:k.catalog,install:async(e,t)=>{const s=await k.install(e,t);return s.outcome.ok&&s.refresh?(this.applyAgentRefresh(s.refresh),{...s.outcome,refreshApplied:!0}):s.outcome}},o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{};Mt(i,x,de.agentInstall);const S=e.schedules?h(e.schedules,o,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator}):{createTools:{},listTools:{}};Mt(i,S.createTools,de.scheduleCreate),Mt(i,S.listTools,de.scheduleList);const I=u(e.sources,{...e.policy?{policy:e.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},o);Mt(i,I.tools,de.agent),this.tools={...r,...a,...l?{...l.readTools,...l.editTools,...l.verifyTools}:{},...f,...y,...x,...S.createTools,...S.listTools,...I.tools},this.registry=I.registry,this.toolRoles=i,this.capabilityContext=e.capabilityContext??{profile:e.bash?.profile.toolName??"no-shell",cwd:e.bash?.workdir??process.cwd(),platform:process.platform,...e.bash?{shellHints:e.bash.profile.systemPromptHints()}:{},agentCount:e.sources.length,...e.agentInstall?{agentOnboardingCatalog:e.agentInstall.catalog}:{}},this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(this.explicitSystemPrompt)}compileCapabilityManifest(){return me({tools:this.tools,toolRoles:this.toolRoles,resolveRoute:e=>this.registry.resolve(e),skills:this.skillSummaries,profile:this.capabilityContext.profile,hostMode:this.capabilityContext.hostMode??pe.embedded,cwd:this.capabilityContext.cwd,platform:this.capabilityContext.platform??process.platform,shellHints:this.capabilityContext.shellHints??[],agentCount:this.capabilityContext.agentCount,agentOnboardingCatalog:this.capabilityContext.agentOnboardingCatalog??[]})}compileSystemPrompt(e){this.lastExtraPrompt=e,this.appliedWorkspaceInstructions=this.workspaceInstructions?.current();const t=ye(this.capabilityManifest,{...void 0!==this.appliedWorkspaceInstructions?{workspaceInstructions:this.appliedWorkspaceInstructions}:{}}),s=e?.trim();return s?[t,"# 附加会话指令","以下指令可以补充任务偏好,但不能覆盖前述工具接地、能力清单和安全约束。",s].join("\n\n"):t}syncWorkspaceInstructions(){void 0!==this.workspaceInstructions&&this.workspaceInstructions.current()!==this.appliedWorkspaceInstructions&&(this.systemPrompt=this.compileSystemPrompt(this.lastExtraPrompt))}refreshCapabilityManifest(e){this.capabilityManifest=this.compileCapabilityManifest(),this.systemPrompt=this.compileSystemPrompt(e??this.explicitSystemPrompt)}setUserInputAvailable(e){if(this.userInputAvailable!==e){if(this.userInputAvailable=e,e)this.tools={...this.tools,...this.userInputTool};else{const e={...this.tools};delete e[this.userInputToolId],this.tools=e,this.userInputInteractions.cancelAll("当前客户端已撤销用户输入处理能力")}this.refreshCapabilityManifest()}}resolveUserInput(e,t){return this.userInputInteractions.resolve(e,t)}cancelUserInput(e,t){return this.userInputInteractions.cancel(e,t)}async requestUserInput(e,t){const s=this.activeTurn;if(!this.userInputAvailable||void 0===s||void 0===this.emit)return{status:"cancelled",reason:"当前无法向用户请求输入"};const o=Date.now(),i=this.interactionDeadlineMs(s,o);if(i<=o||t?.aborted)return{status:"cancelled",reason:"用户输入请求已超时"};const n=this.userInputInteractions.request(e,new Date(i).toISOString()),r=()=>{this.userInputInteractions.cancel(n.requestId,"本轮已终止")};t?.addEventListener("abort",r,{once:!0}),this.emit({type:"user-input-required",requestId:n.requestId,form:n.form,expiresAt:n.expiresAt});try{return await n.result}finally{t?.removeEventListener("abort",r);const e=await n.result;this.emit?.({type:"user-input-settled",requestId:n.requestId,status:e.status})}}trackPendingToolCall(e,t,s,o,i){const n=e.pendingToolCalls.get(t);if(n&&void 0===i)return n;const r=this.registry.resolve(s),a={toolCallId:t,executionOccurrence:n?.executionOccurrence??this.toolCoordinator.captureToolCallOccurrence(t),agentName:r?.agentName??s,toolName:r?.toolName??s,input:o,potentialSideEffect:!0!==r?.annotations?.readOnlyHint||!0===r.annotations.destructiveHint,resources:i??n?.resources??[]};return e.pendingToolCalls.set(t,a),a}buildSkillTools(e){return this.skillToolBuilt=!0,d(()=>{if(!this.skillLibrary)throw new Error("skill library 不可用");return this.skillLibrary},e,this.toolCoordinator)}applyAgentRefresh(e){if(!this.toolSourceAgentNames.has(e.source.agentName)){const t=u([e.source],{...this.policy?{policy:this.policy}:{},requestApproval:e=>this.requestApproval(e),coordinator:this.toolCoordinator},this.registry);Mt(this.toolRoles,t.tools,de.agent),this.tools={...this.tools,...t.tools},this.toolSourceAgentNames.add(e.source.agentName)}if(e.skillLibrary&&(this.skillLibrary=e.skillLibrary,this.skillSummaries=e.skillLibrary.list(),!this.skillToolBuilt)){const e=this.buildSkillTools(this.registry);Mt(this.toolRoles,e,de.skill),this.tools={...this.tools,...e}}e.capabilityContext&&(this.capabilityContext=e.capabilityContext),this.refreshCapabilityManifest(e.systemPrompt)}async*send(e){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=n(e),s=new te;this.emit=e=>s.push(e);const o=Ze();this.activeTurn=o,this.runTurn(s,o,t).catch(e=>{s.push({type:"error",stage:"execute",message:nt(e)}),s.close()});try{for await(const e of s)yield e}finally{this.activeTurn===o&&this.abandonTurn(o),void 0!==this.emit&&(this.emit=void 0)}}async*compact(e="manual"){if(this.closed)throw new Error("session is closed");if(this.activeTurn)throw new Error("session already has an active turn");const t=new te;this.emit=e=>t.push(e);const s=Ze();this.activeTurn=s,this.runCompactionTurn(t,s,e).catch(e=>{t.push({type:"error",stage:"plan",message:nt(e)}),t.close()});try{for await(const e of t)yield e}finally{this.activeTurn===s&&this.abandonTurn(s),void 0!==this.emit&&(this.emit=void 0)}}async runTurn(e,s,n){const r=Date.now();let l,u;const p=i(n.text,n.attachments);try{this.debug(e,"turn","start",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,maxSteps:this.maxSteps,...n.attachments.length>0?{attachments:n.attachments.length}:{},...void 0!==this.contextWindow?{contextWindow:this.contextWindow}:{},...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});try{this.reconcileUncoveredToolExecutionContext()}catch(t){return void e.push({type:"error",stage:"plan",message:`工具执行恢复状态持久化失败: ${nt(t)}`})}try{await this.runAutoCompactionPasses(e,s,r,p)}catch(t){return void e.push({type:"error",stage:"plan",message:nt(t)})}if(s.aborted||s.abortController.signal.aborted)return l=this.messages.length,this.messages.push({role:"user",content:p}),void this.persistCancelledTurn(e,s,l,r);e.push({type:"message-start",messageId:t()}),void 0!==this.turnTimeoutMs&&(s.expiresAt=new Date(Date.now()+this.turnTimeoutMs).toISOString(),u=setTimeout(()=>{s.abortController.signal.aborted||(this.captureCancellationActivity(s),s.aborted=!0,s.cancellationReason=S.timeout,this.gate.abortAll("本轮运行超时"),this.userInputInteractions.cancelAll("本轮运行超时"),s.abortController.abort(I))},this.turnTimeoutMs)),this.syncWorkspaceInstructions();let i=0;const d=ie({rawInput:n.text,skillSummaries:this.skillSummaries,skillLibrary:this.skillLibrary}),h={role:"user",content:p},m=d.skillNames.length>0?oe(h,d):h;let g={};try{g=await mt(this.resolveDynamicCapabilityContext?.(s.abortController.signal)??{},s.abortController.signal)??{}}catch(t){if(this.isTurnAborted(s))return l=this.messages.length,this.messages.push(m),s.cancellationReason=St(s.cancellationReason,s.abortController.signal.reason??t),void this.persistCancelledTurn(e,s,l,r);this.debug(e,"turn","dynamic capability context unavailable",r,{message:nt(t)})}const v=he(this.capabilityManifest,{explicitSkillNames:d.skillNames,...g.ruleIds?{ruleIds:g.ruleIds}:{},...g.vcs?{vcs:g.vcs}:{},...g.origin?{origin:g.origin}:{},sessions:(this.sessionManager?.list()??[]).map(e=>({sessionId:e.sessionId,state:e.state}))});this.lastCapabilityTurnContext=v;const f=fe(v);let y=!1;for(;;){l=this.messages.length,s.pausedForContextPressure=!1,y||this.messages.push(m);const n=ge(this.capabilityManifest,de.transcriptRead),u=this.currentCheckpointReminder(n),p=void 0===u?0:X(u),h=re(P(le(this.messages))),g=wt(d.skillNames.length>0?se(h,d):h,u?`${f}\n\n${u}`:f);this.debug(e,"model","calling streamText",r,{messages:this.messages.length,tools:Object.keys(this.tools).length,contextRecoveryAttempts:i,...void 0!==this.turnTimeoutMs?{timeoutMs:this.turnTimeoutMs}:{}});let v=0;const T=()=>c({model:this.model,system:this.systemPrompt,messages:g,tools:this.tools,prepareStep:({messages:e})=>({messages:o(e)}),stopWhen:[a(Math.max(1,this.maxSteps-s.completedStepCount)),ft(),this.stopOnContextPressure(s)],toolApproval:async({toolCall:e})=>{this.trackPendingToolCall(s,e.toolCallId,e.toolName,e.input),await this.toolCoordinator.prepare(e.toolCallId,e.toolName,e.input)},onLanguageModelCallStart:({callId:e})=>this.toolCoordinator.startBatch(e),onLanguageModelCallEnd:({callId:e,content:t})=>this.toolCoordinator.sealBatch(e,t.flatMap(e=>"tool-call"!==e.type||!0===e.providerExecuted||"invalid"in e&&!0===e.invalid?[]:[{toolCallId:e.toolCallId,toolId:e.toolName}])),abortSignal:s.abortController.signal,...this.providerOptions?{providerOptions:this.providerOptions}:{},onError:()=>{},onStepEnd:e=>{et(s,e),v=Q(e.response.messages.filter(e=>"tool"===e.role))},onAbort:({steps:e})=>{for(const t of e)et(s,t)}});let C;try{C=T()}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);if(!yt(t))throw t;this.needsCompaction=!0,this.messages.splice(l);const o=i<1,n=!!o&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(n&&o){i+=1;continue}return this.persistContextFailure(e,s,m,!1,r),void e.push({type:"error",stage:"execute",message:nt(t)})}this.debug(e,"model","streamText returned",r);let k,b,x,I,M,E,R,q="",N="",W=!1,D=0,U=!1,V=!1;const _=this.scheduleDebug(e,"model","waiting for first stream event",r,{messages:this.messages.length});try{for await(const t of C.fullStream){if(this.closed){s.aborted=!0,s.cancellationReason??=S.runtime;break}switch(V||(V=!0,this.clearDebugTimer(_),this.debug(e,"model","first stream event",r,{part:t.type})),t.type){case"reasoning-start":e.push({type:"reasoning-start",reasoningId:t.id});break;case"reasoning-delta":e.push({type:"reasoning-delta",reasoningId:t.id,delta:t.text});break;case"reasoning-end":e.push({type:"reasoning-end",reasoningId:t.id});break;case"text-delta":if(!W){const s=N+t.text;if(xt(s,d.userPrompt)){N=s;break}if(N.length>0){const s=N+t.text;N="",q+=s,e.push({type:"text-delta",delta:s});break}}q+=t.text,e.push({type:"text-delta",delta:t.text});break;case"tool-call":{W=!0,N="";const o=this.trackPendingToolCall(s,t.toolCallId,t.toolName,t.input,this.toolCoordinator.describeResources(t.toolName,t.input));e.push({type:"tool-call",toolCallId:t.toolCallId,agentName:o.agentName,toolName:o.toolName,input:t.input});break}case"tool-result":{const o=this.registry.resolve(t.toolName),i=s.pendingToolCalls.get(t.toolCallId),n=$(t.output)?t.output:j(t.output),r=n.outcome,a=n.display,c=F({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:i?.input,result:n});this.persistToolExecution(c,s),!0===i?.potentialSideEffect&&r.kind!==A.userRejected&&r.kind!==A.policyDenied&&r.kind!==A.invalidInput&&(s.hadPotentialSideEffects=!0),r.kind===A.success&&void 0!==i&&this.rememberCompactionResources(c,i.resources),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:c.id,outcome:r,display:a,output:a,isError:r.kind!==A.success}),s.aborted||s.abortController.signal.aborted||r.kind!==A.userRejected||(R=gt(t.output));break}case"tool-error":{const o=this.registry.resolve(t.toolName),i=vt(t.error),n=(i===A.invalidInput?L(t.error):void 0)??gt(t.error),r=O(i,n,{raw:t.error}),a=F({toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,input:s.pendingToolCalls.get(t.toolCallId)?.input,result:r});this.persistToolExecution(a,s),!0===s.pendingToolCalls.get(t.toolCallId)?.potentialSideEffect&&r.outcome.kind!==A.invalidInput&&(s.hadPotentialSideEffects=!0),s.pendingToolCalls.delete(t.toolCallId),e.push({type:"tool-result",toolCallId:t.toolCallId,agentName:o?.agentName??t.toolName,toolName:o?.toolName??t.toolName,executionId:a.id,outcome:r.outcome,display:r.display,output:n,isError:!0});break}case"finish-step":{const s=Tt(t.usage);b=bt(b,s.inputTokens),x=s.outputTokens,D+=1,M=t.finishReason;const o=t.performance.outputTokensPerSecond??t.performance.effectiveOutputTokensPerSecond;void 0!==o&&Number.isFinite(o)&&(I=o),e.push({type:"step-finish",finishReason:t.finishReason,usage:s});break}case"finish":!W&&N.length>0&&(q+=N,e.push({type:"text-delta",delta:N}),N=""),k=Tt(t.totalUsage);break;case"error":if(this.isTurnAborted(s)||w(t.error)){s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t.error);break}U=yt(t.error),U&&(this.needsCompaction=!0),E=nt(t.error);break;case"abort":s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t.reason)}}}catch(e){this.isTurnAborted(s)||w(e)?(s.aborted=!0,s.cancellationReason=St(s.cancellationReason,e)):(U=yt(e),U&&(this.needsCompaction=!0),E=nt(e))}finally{this.clearDebugTimer(_)}if(this.debug(e,"model","fullStream finished",r,{textChars:q.length}),void 0!==E){if(this.messages.splice(l),U){const t=0===q.length&&!W,o=t&&i<1,n=!(!o&&t)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(t&&n&&o){i+=1;continue}const a=t?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,q.length>0,r),void e.push({type:"error",stage:"execute",message:`${E}${a}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:E})}if(s.aborted||s.abortController.signal.aborted)return s.cancellationReason=St(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);let G;this.debug(e,"model","awaiting response messages",r);const z=this.scheduleDebug(e,"model","still awaiting response messages",r);try{G=(await C.steps).flatMap(e=>e.response.messages)}catch(t){if(this.clearDebugTimer(z),this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(s.cancellationReason,t),void this.persistCancelledTurn(e,s,l,r);const o=yt(t);if(o&&(this.needsCompaction=!0),this.messages.splice(l),o){const o=0===q.length&&!W,n=o&&i<1,a=!(!n&&o)&&await this.recoverFromContextError(e,s);if(this.isTurnAborted(s))return void this.persistCancelledRecoveryTurn(e,s,m,r);if(o&&a&&n){i+=1;continue}const c=o?"":";本次尝试已有内容或操作开始执行,为避免重复执行,未自动重试";return this.persistContextFailure(e,s,m,q.length>0,r),void e.push({type:"error",stage:"execute",message:`${nt(t)}${c}`})}return this.persistFailedTurn(e,s,m,r),void e.push({type:"error",stage:"execute",message:nt(t)})}finally{this.clearDebugTimer(z)}if(this.debug(e,"model","response messages ready",r,{responseMessages:G.length}),this.isTurnAborted(s))return s.cancellationReason=St(s.cancellationReason,s.abortController.signal.reason),void this.persistCancelledTurn(e,s,l,r);const J=It(G);if(this.messages.push(...J),void 0!==R){const t=0===q.length?R:`\n${R}`;q+=t,e.push({type:"text-delta",delta:t}),this.messages.push({role:"assistant",content:R})}this.debug(e,"persist","persisting messages",r,{appendedMessages:this.messages.length-l}),this.persistMessages(this.messages.slice(l),"raw_transcript"),it(s),l=this.messages.length,this.debug(e,"persist","messages persisted",r,{totalMessages:this.messages.length}),k&&(this.sessionUsage=kt(this.sessionUsage,k));const B=b??k?.inputTokens;void 0!==B&&(this.lastInputTokens=B,this.lastStepOutputTokens=x,this.lastStepToolResultTokens=v,this.measuredMessageCount=this.messages.length,this.promptOverhead=Math.max(0,B-Q(this.messages)+(x??0)+v-p)),s.completedStepCount+=D;const H=s.completedStepCount>=this.maxSteps&&"tool-calls"===M;if(e.push({type:"message-finish",text:q,...k?{totalUsage:k}:{},sessionUsage:{...this.sessionUsage},...void 0!==b?{contextInputTokens:b}:{},...void 0!==I?{outputTokensPerSecond:I}:{},...H?{stoppedAtStepLimit:!0}:{}}),!s.pausedForContextPressure||"tool-calls"!==M||H||void 0!==R)return;let K;s.pausedForContextPressure=!1,this.debug(e,"compaction","turn paused for context pressure",r,{continuations:s.contextPressureContinuations,pressureTokens:this.contextPressureTokens()});try{K=await this.runAutoCompactionPasses(e,s,r)}catch(t){return this.isTurnAborted(s)?void this.persistPausedTurnCancellation(e,s,r):void e.push({type:"error",stage:"plan",message:nt(t)})}if(this.isTurnAborted(s))return void this.persistPausedTurnCancellation(e,s,r);s.contextPressureContinuations=K?s.contextPressureContinuations+1:2,y=!0,e.push({type:"message-start",messageId:t()})}}catch(t){if(this.isTurnAborted(s)||w(t))return s.aborted=!0,s.cancellationReason=St(s.cancellationReason,s.abortController.signal.reason??t),void(void 0!==l?this.persistCancelledTurn(e,s,l,r):this.emitCancellation(e,s));void 0!==l&&this.messages.splice(l),this.debug(e,"turn","error",r,{message:nt(t)}),e.push({type:"error",stage:"execute",message:nt(t)})}finally{void 0!==u&&clearTimeout(u),this.toolCoordinator.finishTurn(),this.activeTurn===s&&(this.activeTurn=void 0),e.close()}}persistMessages(e,t){const s=[...this.uncoveredToolExecutions.keys()],o=0===s.length?void 0:{toolExecutionCoverage:{executionIds:s,representation:t}};this.onPersist?.(e,o),this.recordPersistedMessagesInMemory(e);for(const e of s)this.uncoveredToolExecutions.delete(e)}recordPersistedMessagesInMemory(e){if(void 0!==this.listPersistedTranscriptMessages)return;let t=(this.inMemoryTranscript.at(-1)?.sequence??-1)+1;const s=(new Date).toISOString();for(const o of e)ut(o)||(this.inMemoryTranscript.push({sequence:t,provenance:Ee[0],createdAt:s,message:o}),t+=1)}reconcileUncoveredToolExecutionContext(){if(void 0!==this.recoverPersistedToolExecutionContext){const e=this.recoverPersistedToolExecutionContext();return this.messages.push(...e),this.recordPersistedMessagesInMemory(e),void this.uncoveredToolExecutions.clear()}const e=[...this.uncoveredToolExecutions.values()];if(0===e.length)return;const t=this.messages.length,s=ce(e);this.messages.push(s);try{this.persistMessages([s],"recovery_evidence")}catch(e){throw this.messages.splice(t),e}}persistContextFailure(e,t,s,o,i){if(!this.persistPendingToolCancellationsOrReport(e,t,"上下文溢出工具状态持久化失败"))return;const n=t.toolExecutions.some(e=>e.outcome.kind!==A.policyDenied&&e.outcome.kind!==A.userRejected&&e.outcome.kind!==A.invalidInput&&(e.outcome.kind!==A.cancelled||e.outcome.executionState!==q.notExecuted)),r=["本轮因上下文窗口溢出而中断,未自动重放。"];o&&r.push("本轮已产生部分文本,持久历史仅保留此中断标记。"),n&&r.push("本轮已有操作开始执行,部分结果可能已经生效且不会自动撤销,请先检查实际结果。");const a=[...this.uncoveredToolExecutions.values()];this.appendInterruptedTurnMessages(e,t,i,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...0===a.length?[]:[ce(a)],{role:"assistant",content:r.join("")}],debugLabel:"persisting context-overflow marker",debugDetails:{hadToolActivity:n,producedText:o},failureLabel:"上下文溢出记录持久化失败"})}persistFailedTurn(e,t,s,o){if(this.closed)return;const i=tt(t);if(!(i.length>0||t.toolExecutions.length>0||t.pendingToolCalls.size>0))return;const n=De(It(st(t))).messages;this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败")&&this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:this.messages.length,messages:[...t.userMessagePersisted?[]:[s],...n,ae({context:this.failedTurnContextMessage(t),completedMessages:i,toolExecutions:t.toolExecutions}),{role:"assistant",content:this.failedTurnDisplayMessage(t)}],debugLabel:"persisting failed turn",failureLabel:"失败状态持久化失败"})}failedTurnContextMessage(e){const t=this.cancellationActivity(e).execSessionIds;return`本轮因运行错误中断,未自动重试。${t.length>0?`本轮后台任务编号: ${t.join(", ")}。`:""}已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${He}`}failedTurnDisplayMessage(e){const t=this.cancellationActivity(e);return`本轮因运行错误而中断,未自动重试。之前的对话和已完成进度会保留。${t.hadPotentialSideEffects?"部分操作可能已经生效且不会自动撤销,请先检查实际结果,再决定是否继续。":t.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"你可以继续输入或重试。"}`}appendInterruptedTurnMessages(e,t,s,o){if(t.pendingToolCalls.size>0)return e.push({type:"error",stage:"execute",message:`${o.failureLabel}: 存在未写入账本的待处理工具调用,已拒绝持久化中断记录`}),!1;this.messages.push(...o.messages),this.debug(e,"persist",o.debugLabel,s,{appendedMessages:this.messages.length-o.rollbackTo,...o.debugDetails});try{return this.persistMessages(this.messages.slice(o.rollbackTo),"recovery_evidence"),!0}catch(t){return this.messages.splice(o.rollbackTo),e.push({type:"error",stage:"execute",message:`${o.failureLabel}: ${nt(t)}`}),!1}}persistToolExecution(e,t){this.onToolExecution?.(e),this.inMemoryToolExecutions.push(e),t.toolExecutions.push(e),this.uncoveredToolExecutions.set(e.id,e)}rememberCompactionResources(e,t){for(const s of t){const t={key:Xe(s.key),mode:s.mode,evidenceToolCallId:e.toolCallId,evidenceExecutionId:e.id};this.retainCompactionResource(t)}}retainCompactionResource(e){const t=this.compactionResources.get(e.key),s=void 0===t||e.mode===G.write||t.mode!==G.write?e:t;this.compactionResources.delete(e.key),this.compactionResources.set(e.key,s)}interactionDeadlineMs(e,t){const s=void 0===e.expiresAt?Number.POSITIVE_INFINITY:Date.parse(e.expiresAt);return Math.min(t+_e,Number.isFinite(s)?s:Number.POSITIVE_INFINITY)}requestApproval(e){const s=t(),o=this.gate.request(s);if(void 0===this.emit)return this.gate.resolve(s,{approved:!1,reason:"approval event could not be delivered"}),o;const i=void 0===this.activeTurn?void 0:new Date(this.interactionDeadlineMs(this.activeTurn,Date.now())).toISOString();return this.emit({type:"confirmation-required",approvalId:s,agentName:e.agentName,toolName:e.toolName,input:e.input,...void 0!==i?{expiresAt:i}:{},...e.reason?{reason:e.reason}:{},...void 0!==e.explanation?{explanation:e.explanation}:{},...void 0!==e.sessionGrantLabel?{sessionGrantLabel:e.sessionGrantLabel}:{},...void 0!==e.diff?{diff:e.diff}:{}}),o}approve(e,t){return this.gate.resolve(e,{approved:!0,...void 0!==t?{scope:t}:{}})}reject(e,t){return this.gate.resolve(e,{approved:!1,...t?{reason:t}:{}})}getMessages(){return re(ue(this.messages))}getToolExecutions(e={},t=!1){const s=this.listPersistedToolExecutions?this.listPersistedToolExecutions(e):this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t})).filter(t=>t.sequence>(e.afterSequence??-1)&&(void 0===e.toolCallId||t.toolCallId===e.toolCallId)).slice(0,e.limit??100);return t?s:s.map(e=>({..._(e),sequence:e.sequence}))}getToolExecution(e,t=!1){const s=this.getPersistedToolExecution?.(e),o=s??(()=>{const t=this.inMemoryToolExecutions.findIndex(t=>t.id===e),s=this.inMemoryToolExecutions[t];return s?{...s,sequence:t}:void 0})();return!o||t?o:{..._(o),sequence:o.sequence}}getCapabilityManifest(){return structuredClone(this.capabilityManifest)}getCapabilityTurnContext(){return this.lastCapabilityTurnContext?structuredClone(this.lastCapabilityTurnContext):void 0}getContextWindow(){return this.contextWindow}getSessionUsage(){return{...this.sessionUsage}}getSkillSummaries(){return this.skillSummaries}setProviderOptions(e){this.providerOptions=e,this.onProviderOptionsChange?.(e)}async runAutoCompactionPasses(e,t,s,o){let i=!1;for(let n=0;n<4&&this.shouldAutoCompact(o);n+=1){this.debug(e,"compaction","auto requested",s,{pass:n,messages:this.messages.length,pressureTokens:this.contextPressureTokens(o),...void 0!==this.lastInputTokens?{lastInputTokens:this.lastInputTokens}:{}});if(!await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens(o)))break;i=!0}return i}stopOnContextPressure(e){return({steps:t})=>{const s=this.compaction,o=t.at(-1);if(void 0===s||!s.enabled||void 0===this.contextWindow||e.contextPressureContinuations>=2||void 0===o||"tool-calls"!==o.finishReason||t.length<2&&this.messages.length<2||o.toolResults.some(e=>D(e.output).kind===A.userRejected))return!1;const i=Tt(o.usage);return!((void 0===i.inputTokens?this.promptOverheadTokens()+Q(this.messages)+Q(t.flatMap(e=>e.response.messages)):i.inputTokens+(i.outputTokens??0)+Q(o.response.messages.filter(e=>"tool"===e.role)))/this.contextWindow<s.threshold)&&(e.pausedForContextPressure=!0,!0)}}contextPressureTokens(e){const t=void 0===e?0:Q([{role:"user",content:e}]);return void 0!==this.lastInputTokens&&void 0!==this.measuredMessageCount?this.lastInputTokens+(this.lastStepOutputTokens??0)+(this.lastStepToolResultTokens??0)+Q(this.messages.slice(this.measuredMessageCount))+t:this.promptOverheadTokens()+Q(this.messages)+t}promptOverheadTokens(){const e=this.currentCheckpointReminder(ge(this.capabilityManifest,de.transcriptRead));return(this.promptOverhead??0)+(void 0===e?0:X(e))}currentCheckpointReminder(e){return this.compactionCheckpoint?Te(this.compactionCheckpoint,this.sessionManagerInstanceId,e):void 0}persistPausedTurnCancellation(e,t,s){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted&&!this.closed){t.cancellationPersistenceAttempted=!0,t.cancellationPersisted=!0;const o=this.cancellationRecordMessages(t,tt(t));t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,s,{rollbackTo:this.messages.length,messages:o,debugLabel:"persisting paused turn cancellation",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}compactionTargetTokens(e){const t=this.compaction;if(void 0===t||void 0===this.contextWindow)return;const s=void 0===e?0:Q([{role:"user",content:e}]);return Math.max(1,Math.floor(this.contextWindow*t.threshold)-this.promptOverheadTokens()-s)}shouldAutoCompact(e){const t=this.compaction;return void 0!==t&&t.enabled&&(this.needsCompaction||void 0!==this.contextWindow&&this.contextPressureTokens(e)/this.contextWindow>=t.threshold)}listCompactionTranscriptEvidence(){const e=this.listPersistedTranscriptMessages;if(void 0===e)return[...this.inMemoryTranscript];const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}listCompactionToolEvidence(){const e=this.listPersistedToolExecutions;if(void 0===e)return this.inMemoryToolExecutions.map((e,t)=>({...e,sequence:t}));const t=[];let s=-1;for(;;){const o=e({afterSequence:s,limit:500});t.push(...o);const i=o.at(-1)?.sequence;if(o.length<500||void 0===i||i<=s)break;s=i}return t}latestExplicitSkillNames(e,t){if(void 0===t)return this.compactionCheckpoint?.context.explicitSkillNames??[];const s=e.find(e=>e.sequence===t);return void 0===s?[]:ne(s.message)?.snapshot.skillNames??[]}currentCompactionRunningWork(){const e=(this.compactionCheckpoint?.runningWork??[]).filter(e=>e.managerInstanceId!==this.sessionManagerInstanceId).map(e=>({...e,recoverability:"live"===e.recoverability?"stale":e.recoverability})),t=(new Date).toISOString();return[...e,...(this.sessionManager?.list()??[]).map(e=>({managerInstanceId:this.sessionManagerInstanceId,sessionId:e.sessionId,state:e.state,recoverability:k(e.state)?"unavailable":"live",commandPreview:e.commandPreview,workdir:e.workdir,observedAt:t,wallTimeMs:e.wallTimeMs,...void 0!==e.exitCode?{exitCode:e.exitCode}:{},...void 0!==e.terminationCause?{terminationCause:e.terminationCause}:{},...void 0!==e.cleanupError?{cleanupError:e.cleanupError}:{}}))].slice(-128)}captureCompactionEvidence(){const e=this.listCompactionTranscriptEvidence(),t=this.listCompactionToolEvidence(),s=[...this.compactionResources.values()].slice(-256),o=[...this.currentCompactionRunningWork()],i="legacy_snapshot"===this.compactionCheckpoint?.transcript.completeness||e.some(e=>"legacy_snapshot"===e.provenance)?"legacy_snapshot":"complete",n=this.compactionCheckpoint?.goal,r=Ie(e),a=r??n,c=void 0!==r&&(void 0===n||r.sourceSequence>n.sourceSequence)?r.sourceSequence:void 0,l=this.compactionCheckpoint?.version===ke?this.compactionCheckpoint.semanticState:void 0,u=Oe(l,this.compactionCheckpoint?.constraints??[]),p=1===this.compactionCheckpoint?.version,d=void 0!==this.legacyV1ActiveSnapshot&&dt(this.legacyV1ActiveSnapshot,this.compactionCheckpoint,this.messages),h=p?d&&void 0!==this.legacyV1ActiveSnapshot?$e(u,{checkpointId:this.legacyV1ActiveSnapshot.checkpointId,fragments:this.legacyV1ActiveSnapshot.fragments}):{state:u,requiredItemIds:[],transcriptFragments:[],complete:!1}:{state:u,requiredItemIds:[],transcriptFragments:[],complete:!0},m=h.state,g=ht(this.compactionCheckpoint),v=g.messagesThroughSequence,f=g.toolExecutionsThroughSequence,y=e.filter(e=>e.sequence>v),T=new Set(y.filter(e=>e.provenance===Ee[1]&&ut(e.message)).map(e=>e.sequence)),C=void 0===a?void 0:e.find(e=>e.sequence===a.sourceSequence),k=Pe({messages:[...y.filter(e=>!T.has(e.sequence)),...void 0===C||y.includes(C)?[]:[C]].map(e=>({sequence:e.sequence,role:e.message.role,summary:at(e)})),toolExecutions:t.filter(e=>e.sequence>f).map(lt),resources:s.slice().reverse().map(e=>({key:e.key,mode:e.mode})),runningSessions:[]}),b=we(k,m,48e3);return{transcript:e,toolExecutions:t,resources:s,runningWork:o,completeness:i,goal:a,newGoalSourceSequence:c,previousSemanticState:m,registry:k,modelContext:b.prompt,presentedEvidenceIds:b.includedEvidenceIds,expectedActiveMessages:[...this.messages],expectedLatestCheckpointId:this.compactionCheckpoint?.id,previousSemanticEvidenceWatermarks:g,autoCoveredMessageSequences:T,legacySnapshotMigrationComplete:h.complete,legacySnapshotRequiredItemIds:h.requiredItemIds,legacySnapshotTranscriptFragments:h.transcriptFragments,legacySnapshotRemovableRawMessageCount:h.complete&&d?this.legacyV1ActiveSnapshot?.removableRawMessageCount??0:0,evidenceWatermarks:{transcriptMessagesThroughSequence:Math.max(this.compactionCheckpoint?.transcript.messages.throughSequence??-1,e.at(-1)?.sequence??-1),toolExecutionsThroughSequence:Math.max(this.compactionCheckpoint?.transcript.toolExecutions.throughSequence??-1,t.at(-1)?.sequence??-1)}}}buildCompactionDraft(t,s,o,i){const n=je({draft:s??Qe,evidenceRegistry:t.registry,presentedEvidenceIds:t.presentedEvidenceIds,...void 0!==t.previousSemanticState?{previousState:t.previousSemanticState}:{},...void 0!==t.goal?{harnessGoal:{verbatimRequest:t.goal.verbatimRequest,sourceSequence:t.goal.sourceSequence}}:{}});let r=Re(t.previousSemanticState,n,{startsNewGoalScope:n.startsNewGoalScope});if(void 0===s){const e=Me(t.transcript,this.compactionCheckpoint?.constraints??[]),s=JSON.stringify(e)!==JSON.stringify(this.compactionCheckpoint?.constraints??[]);r=qe(r,e);const o=void 0===this.compactionCheckpoint?.goal?t.goal:void 0===t.goal||void 0===t.newGoalSourceSequence||s?this.compactionCheckpoint.goal:t.goal;r=Ae(r,o)}const a=r.constraints.flatMap(e=>{const t=e.provenance.find(e=>"message"===e.kind)?.messageSequence;return null==t?[]:[{quote:e.text,sourceSequence:t}]}),c=r.goal?.provenance.find(e=>"message"===e.kind)?.messageSequence,l=(null==c?void 0:Ie(t.transcript.filter(e=>e.sequence===c)))??this.compactionCheckpoint?.goal??t.goal,u=void 0!==l&&l.sourceSequence!==this.compactionCheckpoint?.goal?.sourceSequence?l.sourceSequence:void 0,p=o?Ne(r):void 0,d=void 0!==p?xe(p):void 0!==i?{status:"fallback",reason:i}:{status:"skipped"},h=new Set(Se(r).items.map(e=>e.itemId)),m=0===t.legacySnapshotRequiredItemIds.length||t.legacySnapshotRequiredItemIds.every(e=>h.has(e)),g=Ce(t.transcript.map(e=>e.message),t.toolExecutions,32,t.completeness);return{draft:{...l?{goal:l}:{},constraints:[...a],resources:[...t.resources],toolState:g,runningWork:[...t.runningWork],context:{cwd:this.capabilityManifest.dynamicContext.cwd,stableRuleIds:[...this.capabilityManifest.stableContext.rules],systemPromptSha256:e("sha256").update(this.systemPrompt).digest("hex"),skills:this.capabilityManifest.skills.map(e=>({name:e.name,source:e.source})),explicitSkillNames:[...this.latestExplicitSkillNames(t.transcript,u)]},summary:d},semanticState:r,semanticSummaryText:p,semanticRejectionCount:n.rejections.length,legacySnapshotReminderCoverageComplete:m,coveredEvidenceIds:n.coveredEvidenceIds,expectedActiveMessages:t.expectedActiveMessages,expectedLatestCheckpointId:t.expectedLatestCheckpointId,evidenceWatermarks:t.evidenceWatermarks,legacySnapshotTranscriptFragments:t.legacySnapshotTranscriptFragments}}async runCompactionTurn(e,t,s){try{this.reconcileUncoveredToolExecutionContext(),await this.runCompaction(e,s,t,!0,void 0)}catch(t){e.push({type:"error",stage:"plan",message:nt(t)})}finally{this.activeTurn===t&&(this.activeTurn=void 0),e.close()}}advanceCompactionSemanticEvidenceWatermarks(e,t){const s=e.previousSemanticEvidenceWatermarks;if(0===t.length)return s;const o=new Set(t.filter(t=>e.presentedEvidenceIds.includes(t))),i=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let n=s.messagesThroughSequence;for(let t=s.messagesThroughSequence+1;;t+=1){if(e.autoCoveredMessageSequences.has(t)){n=t;continue}const s=i.get(t);if(void 0===s||!o.has(s))break;n=t}const r=new Map(e.registry.flatMap(e=>"tool_execution"===e.provenance.kind&&null!==e.provenance.toolExecutionId?[[e.provenance.toolExecutionId,e.evidenceId]]:[])),a=new Map(e.toolExecutions.map(e=>[e.sequence,e]));let c=s.toolExecutionsThroughSequence;for(let e=s.toolExecutionsThroughSequence+1;;e+=1){const t=a.get(e);if(void 0===t)break;const s=r.get(t.id);if(void 0===s||!o.has(s))break;c=e}return{messagesThroughSequence:n,toolExecutionsThroughSequence:c}}countContiguousPresentedMessageEvidence(e){if(!e.legacySnapshotMigrationComplete)return 0;const t=new Set(e.presentedEvidenceIds),s=new Map(e.registry.flatMap(e=>"message"===e.provenance.kind&&null!==e.provenance.messageSequence?[[e.provenance.messageSequence,e.evidenceId]]:[]));let o=e.legacySnapshotRemovableRawMessageCount;for(let i=e.previousSemanticEvidenceWatermarks.messagesThroughSequence+1;;i+=1){if(e.autoCoveredMessageSequences.has(i))continue;const n=s.get(i);if(void 0===n||!t.has(n))break;o+=1}return o}async runCompaction(e,t,s,o,i){const n=Date.now(),r=this.compaction,a=r?.strategy??"summarize";if(this.debug(e,"compaction","start",n,{reason:t,messages:this.messages.length,timeoutMs:r?.timeoutMs??12e4,maxOutputTokens:r?.maxOutputTokens??8192}),e.push({type:"compaction-start",reason:t}),this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if(!r)return e.push({type:"context-compacted",reason:t,strategy:a,removed:0,kept:this.messages.length}),!1;const c=this.lastInputTokens;let l,u=r.strategy;const p=s?.abortController.signal,d=Date.now(),h=this.captureCompactionEvidence();if(this.debug(e,"compaction","evidence ready",d,{transcriptMessages:h.transcript.length,toolExecutions:h.toolExecutions.length}),1===this.compactionCheckpoint?.version&&void 0===this.commitPersistedCompaction)return this.debug(e,"compaction","legacy V1 snapshot requires durable transcript",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;if(!h.legacySnapshotMigrationComplete)return this.debug(e,"compaction","legacy V1 snapshot migration incomplete",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const m=this.countContiguousPresentedMessageEvidence(h);let g;try{const t=Date.now();try{g=await K({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,semanticEvidencePrompt:h.modelContext,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...void 0!==r.timeoutMs?{timeoutMs:r.timeoutMs}:{},...void 0!==r.maxOutputTokens?{maxOutputTokens:r.maxOutputTokens}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...p?{abortSignal:p}:{}})}finally{this.debug(e,"compaction","draft generation finished",t,{strategy:u})}if("summarize"===u&&g.removed>0&&void 0===g.semanticDraft)throw new Y(H.missingObject,"structured compaction draft is missing")}catch(t){if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;if("summarize"!==u||!Y.isInstance(t))throw t;this.debug(e,"compaction","summarize failed, fallback to truncate",n,{message:nt(t)}),l="structured checkpoint generation failed",u="truncate";const a=Date.now();g=await K({messages:this.messages,strategy:u,keepRecentTurns:r.keepRecentTurns,keepRecentTokens:r.keepRecentTokens,model:this.model,maxRemovedTranscriptMessages:m,...void 0!==i?{targetTokens:i}:{},...p?{abortSignal:p}:{}}),this.debug(e,"compaction","truncate fallback finished",a)}if(this.isTurnAborted(s))return o&&void 0!==s&&this.emitCancellation(e,s),!1;const v=g.removed>0||g.truncatedTools>0,f=Date.now(),y=v?this.buildCompactionDraft(h,g.semanticDraft,"summarize"===u&&g.removed>0,l):void 0;if(this.debug(e,"compaction","checkpoint validation finished",f,{semanticRejections:y?.semanticRejectionCount??0}),void 0!==y&&y.semanticRejectionCount>0&&this.debug(e,"compaction","rejected ungrounded semantic claims",n,{count:y.semanticRejectionCount}),void 0!==y&&!y.legacySnapshotReminderCoverageComplete)return this.debug(e,"compaction","legacy V1 snapshot exceeds reminder projection",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const T=De(g.messages),C=[...T.messages];if(T.status===We.repaired&&this.debug(e,"compaction","repaired malformed active Tool protocol",n,{removedToolCallIds:T.removedToolCallIds.join(","),removedToolResultIds:T.removedToolResultIds.join(",")}),1===this.compactionCheckpoint?.version&&C.some(ut))return this.debug(e,"compaction","legacy V1 snapshot remains in active history",n),e.push({type:"context-compacted",reason:t,strategy:u,removed:0,kept:this.messages.length}),!1;const k=e=>Buffer.byteLength(JSON.stringify(e),"utf8"),b=v&&k(C)<k(this.messages),x=b?C:[...this.messages],S=b?this.advanceCompactionSemanticEvidenceWatermarks(h,y?.coveredEvidenceIds??[]):h.previousSemanticEvidenceWatermarks;let I;if(b){const t=Date.now();if(void 0!==this.commitPersistedCompaction){if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");I=this.commitPersistedCompaction({messages:x,expectedActiveMessages:y.expectedActiveMessages,expectedLatestCheckpointId:y.expectedLatestCheckpointId,draft:y.draft,semanticState:y.semanticState,semanticEvidenceWatermarks:S,evidenceWatermarks:y.evidenceWatermarks,...y.legacySnapshotTranscriptFragments.length>0?{legacySnapshotTranscriptFragments:y.legacySnapshotTranscriptFragments}:{}})}else{if(void 0===y)throw new Error("compaction checkpoint snapshot is missing");const e=this.compactionCheckpoint;I=be({draft:y.draft,semanticState:y.semanticState,semanticEvidence:S,generation:(e?.generation??0)+1,transcript:{messages:{fromSequenceExclusive:e?.transcript.messages.throughSequence??-1,throughSequence:y.evidenceWatermarks.transcriptMessagesThroughSequence},toolExecutions:{fromSequenceExclusive:e?.transcript.toolExecutions.throughSequence??-1,throughSequence:y.evidenceWatermarks.toolExecutionsThroughSequence},completeness:h.completeness},...void 0!==e?{previousCheckpointId:e.id}:{}}),this.onReplace?.(x)}this.debug(e,"compaction","checkpoint commit finished",t,{durable:void 0!==this.commitPersistedCompaction}),this.messages.splice(0,this.messages.length,...x),void 0!==I&&(this.compactionCheckpoint=I),this.lastInputTokens=void 0,this.lastStepOutputTokens=void 0,this.lastStepToolResultTokens=void 0,this.measuredMessageCount=void 0,this.needsCompaction=!1}return e.push({type:"context-compacted",reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,...b&&g.truncatedTools>0?{truncatedTools:g.truncatedTools}:{},...void 0!==c?{beforeInputTokens:c}:{},...void 0!==I?{checkpointId:I.id,checkpointGeneration:I.generation,checkpointSummaryStatus:I.summary.status}:{}}),this.debug(e,"compaction","finish",n,{reason:t,strategy:u,removed:b?g.removed:0,kept:x.length,truncatedTools:b?g.truncatedTools:0,progressed:b}),b}async recoverFromContextError(e,t){if(!this.compaction?.enabled)return!1;try{return await this.runCompaction(e,"auto",t,!1,this.compactionTargetTokens())}catch(t){return e.push({type:"error",stage:"plan",message:nt(t)}),!1}}isTurnAborted(e){return!0===e?.aborted||!0===e?.abortController.signal.aborted}execSessionIds(e){return[...e.execSessionIds].sort((e,t)=>e-t)}activeExecSessionIds(e){return this.execSessionIds(e).filter(e=>{const t=this.sessionManager?.get(e);return void 0!==t&&!k(t.state)})}interruptExecSessions(e){const t=this.execSessionIds(e);0!==t.length&&this.sessionManager?.interrupt(t).catch(e=>{process.stderr.write(`roll chat: 中断后台会话失败: ${nt(e)}\n`)})}abandonTurn(e){this.closed||this.activeTurn!==e||e.abortController.signal.aborted||(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=S.runtime,this.gate.abortAll("本轮事件流已停止"),this.userInputInteractions.cancelAll("本轮事件流已停止"),this.interruptExecSessions(e),e.abortController.abort(x))}currentCancellationActivity(e){const t=this.activeExecSessionIds(e),s=[...e.pendingToolCalls.values()].filter(e=>this.toolCoordinator.hasExecutionStarted(e.executionOccurrence));return{execSessionIds:t,hadCompletedProgress:e.toolExecutions.length>0||e.completedStepResponses.size>0,hadInFlightWork:s.length>0||t.length>0,hadPotentialSideEffects:e.hadPotentialSideEffects||s.some(e=>e.potentialSideEffect)}}captureCancellationActivity(e){e.cancellationActivity??=this.currentCancellationActivity(e)}cancellationActivity(e){return e.cancellationActivity??this.currentCancellationActivity(e)}cancellationDisplayMessage(e){const t=e.cancellationReason??S.runtime,s=this.cancellationActivity(e);if(e.cancellationPersistenceAttempted&&!e.cancellationPersisted){const e=s.hadPotentialSideEffects?"部分操作可能已经执行,请先检查结果后再继续。":s.hadInFlightWork?"刚才的任务结果尚未确认,请先检查后再继续。":"请重新输入需要继续的内容。";return t===S.timeout?`本轮等待时间过长,已自动停止,但刚才的对话和进度未能保存。${e}`:t===S.runtime?`本轮因运行异常而中断,刚才的对话和进度未能保存。${e}`:`已停止本轮,但刚才的对话和进度未能保存。${e}`}const o=s.execSessionIds,i=ge(this.capabilityManifest,de.sessionList);switch(t){case S.user:return s.hadInFlightWork?s.hadPotentialSideEffects?"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮操作。正在进行的任务也已请求停止。之前的对话和已完成进度会保留。":s.hadCompletedProgress?s.hadPotentialSideEffects?"已停止本轮回复。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果。":"已停止本轮回复。之前的对话和已完成进度会保留,你可以继续输入。":"已停止本轮回复。之前的对话会保留,你可以继续输入。";case S.timeout:return 0===o.length?"本轮等待时间过长,已自动停止。之前的对话和已完成进度会保留,你可以继续输入或重试。":ve(this.capabilityManifest.lifecycle.hostMode)?"本轮等待时间过长,已自动停止。正在进行的任务会随本次命令结束而停止,之后无法继续查看;请先确认实际结果,再决定是否重试。":i?`本轮等待时间过长,但任务仍在运行(任务 #${o.join(", #")})。你可以在下一条消息中继续查看进度;确认结果前请勿重复执行。`:"本轮等待时间过长。任务可能仍在运行,但 Roll 暂时无法继续查看进度;请先确认实际结果,再决定是否重试。";case S.runtime:return s.hadInFlightWork?"本轮因运行异常而中断。正在进行的任务已请求停止,最终结果尚未确认;请检查结果后再继续。":s.hadPotentialSideEffects?"本轮因运行异常而中断。之前的对话和已完成进度会保留;部分已经完成的操作不会自动撤销,请检查结果后再继续。":"本轮因运行异常而中断。之前的对话会保留,你可以重试。"}}cancellationContextMessage(e){const t=e.cancellationReason??S.runtime,s=this.cancellationActivity(e).execSessionIds,o=s.length>0?`本轮后台任务编号: ${s.join(", ")}。`:"",i=ge(this.capabilityManifest,de.sessionList),n=He;switch(t){case S.user:return`用户主动停止了本轮。${o}这些任务已收到停止请求;已完成的步骤和工具记录仍然有效,不要自动重复 outcome=success 的操作。${n}`;case S.timeout:{const e=void 0!==this.turnTimeoutMs?`(${String(this.turnTimeoutMs)}ms)`:"";return 0===s.length?`本轮因超时${e}停止。已完成的步骤和工具记录仍然有效。${n}`:ve(this.capabilityManifest.lifecycle.hostMode)?`本轮因超时${e}停止。${o}当前 one-shot 进程结束时会清理这些任务,后续 CLI 进程无法恢复。${n}`:i?`本轮因超时${e}停止,但后台任务仍在当前进程运行。${o}若且仅若最新用户明确要求继续或核对上一任务,可用 ${i} 找回并查看。${n}`:`本轮因超时${e}停止,但后台任务可能仍在运行。${o}当前没有可用的任务列表工具,不能安全恢复查看。${n}`}case S.runtime:return`本轮因运行异常中断。${o}已完成的步骤和工具记录仍然有效。${n}`}}emitCancellation(e,t){if(t.cancellationEventEmitted)return;t.cancellationReason??=S.runtime,t.cancellationEventEmitted=!0;const s=this.cancellationActivity(t).execSessionIds;e.push({type:"turn-cancelled",reason:t.cancellationReason,message:this.cancellationDisplayMessage(t),...s.length>0?{execSessionIds:s}:{}})}persistCancelledRecoveryTurn(e,t,s,o){const i=this.messages.length;t.userMessagePersisted||this.messages.push(s),this.persistCancelledTurn(e,t,i,o,Be.ledgerOnly)}persistCancelledTurn(e,t,s,o,i=Be.keepRaw){if(!this.persistPendingToolCancellationsOrReport(e,t,"取消工具账本持久化失败"))return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(this.closed)return this.messages.splice(s),t.cancellationPersistenceAttempted=!0,void this.emitCancellation(e,t);if(!t.cancellationPersistenceAttempted){t.cancellationPersistenceAttempted=!0,this.messages.splice(s+1);const n=i===Be.keepRaw,r=n?De(It(st(t))).messages:[],a=n?tt(t):ot(t);t.cancellationPersisted=!0;const c=this.cancellationRecordMessages(t,a);t.cancellationPersisted=this.appendInterruptedTurnMessages(e,t,o,{rollbackTo:s,messages:[...r,...c],debugLabel:"persisting cancelled turn",failureLabel:"取消状态持久化失败"})}this.emitCancellation(e,t)}cancellationRecordMessages(e,t){return[ae({context:this.cancellationContextMessage(e),completedMessages:t,toolExecutions:e.toolExecutions}),E(this.cancellationDisplayMessage(e),e.cancellationReason??S.runtime)]}persistPendingToolCancellationsOrReport(e,t,s){this.captureCancellationActivity(t);try{return this.persistPendingToolCancellations(t),!0}catch(t){return e.push({type:"error",stage:"execute",message:`${s}: ${nt(t)}`}),!1}}persistPendingToolCancellations(e){const t=e.cancellationReason??S.runtime;for(const s of e.pendingToolCalls.values()){const o=this.toolCoordinator.hasExecutionStarted(s.executionOccurrence)?q.outcomeUnknown:q.notExecuted,i=o===q.notExecuted?`工具调用在开始执行前因本轮 ${t} 中断而取消;确定未执行`:`工具调用已开始,因本轮 ${t} 中断而取消;最终结果尚未确认`,n=N({kind:A.cancelled,reason:t,executionState:o},i,{raw:{cancellationReason:t,executionState:o,abortReason:nt(e.abortController.signal.reason)}});this.persistToolExecution(F({toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:s.input,result:n}),e),e.pendingToolCalls.delete(s.toolCallId)}}cancel(){const e=this.activeTurn;return!!e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason=S.user,this.gate.abortAll("用户取消本轮"),this.userInputInteractions.cancelAll("用户取消本轮"),this.interruptExecSessions(e),e.abortController.abort(M),!0)}close(){if(void 0!==this.closePromise)return this.closePromise;this.closed=!0;const e=this.activeTurn;return e&&(this.captureCancellationActivity(e),e.aborted=!0,e.cancellationReason??=S.runtime,this.gate.abortAll(),this.userInputInteractions.cancelAll("Runtime 正在关闭"),e.abortController.abort(x)),this.closePromise=(async()=>{const e=(this.sessionManager?.close()??Promise.resolve([])).then(e=>{for(const t of e)void 0!==t.cleanupError&&process.stderr.write(`roll chat: 后台会话 ${String(t.sessionId)} 清理失败: ${t.cleanupError}\n`)},e=>{process.stderr.write(`roll chat: 会话 ${this.id} 后台清理失败: ${nt(e)}\n`)});await s(e,Ve)||process.stderr.write(`roll chat: 会话 ${this.id} 在 ${String(Ve)}ms 内未完成全部关闭步骤\n`);try{this.onClose?.()}catch(e){process.stderr.write(`roll chat: 会话 ${this.id} 关闭回调失败: ${nt(e)}\n`)}})(),this.closePromise}abort(){this.close().catch(e=>{process.stderr.write(`roll chat: 会话 ${this.id} 关闭失败: ${nt(e)}\n`)})}debug(e,t,s,o,i){this.debugEvents&&e.push({type:"debug",stage:t,message:s,...void 0!==o?{elapsedMs:Date.now()-o}:{},...void 0!==i?{data:i}:{}})}scheduleDebug(e,t,s,o,i){if(this.debugEvents)return setTimeout(()=>{this.debug(e,t,s,o,i)},5e3)}clearDebugTimer(e){void 0!==e&&clearTimeout(e)}}
@@ -6,7 +6,7 @@ import type { ToolAnnotations } from "../types/policy.ts";
6
6
  import type { ToolRoute } from "../tool-bridge/naming.ts";
7
7
  import type { SessionState } from "../bash/session/types.ts";
8
8
  export declare const CAPABILITY_MANIFEST_VERSION: 1;
9
- export declare const CAPABILITY_TURN_CONTEXT_VERSION: 1;
9
+ export declare const CAPABILITY_TURN_CONTEXT_VERSION: 2;
10
10
  export declare const CAPABILITY_TOOL_ROLES: {
11
11
  readonly agent: "agent";
12
12
  readonly skill: "skill";
@@ -18,6 +18,8 @@ export declare const CAPABILITY_TOOL_ROLES: {
18
18
  readonly sessionPoll: "session-poll";
19
19
  readonly sessionList: "session-list";
20
20
  readonly agentInstall: "agent-install";
21
+ readonly scheduleCreate: "schedule-create";
22
+ readonly scheduleList: "schedule-list";
21
23
  readonly transcriptRead: "transcript-read";
22
24
  readonly userInput: "user-input";
23
25
  };
@@ -42,8 +44,12 @@ export declare const CAPABILITY_HOST_MODES: {
42
44
  readonly interactive: "interactive";
43
45
  readonly oneShot: "one-shot";
44
46
  readonly server: "server";
47
+ readonly background: "background";
45
48
  };
46
49
  export type CapabilityHostMode = (typeof CAPABILITY_HOST_MODES)[keyof typeof CAPABILITY_HOST_MODES];
50
+ export declare function isProcessBoundHostMode(mode: CapabilityHostMode): boolean;
51
+ export declare function shouldOfferAgentInstall(mode: CapabilityHostMode): boolean;
52
+ export declare function shouldOfferScheduleCreate(mode: CapabilityHostMode): boolean;
47
53
  export declare const CAPABILITY_SESSION_EXEC_LIFECYCLES: {
48
54
  readonly resumable: "resumable";
49
55
  readonly unavailable: "unavailable";
@@ -75,10 +81,23 @@ export interface CapabilityDynamicTurnSnapshot {
75
81
  readonly ruleIds: readonly string[];
76
82
  readonly sessions: readonly CapabilitySessionSnapshot[];
77
83
  readonly vcs?: CapabilityVcsSnapshot;
84
+ readonly origin?: CapabilityTurnOrigin;
85
+ }
86
+ export declare const CAPABILITY_TURN_ORIGIN_KINDS: {
87
+ readonly scheduled: "scheduled";
88
+ };
89
+ export type CapabilityTurnOriginKind = (typeof CAPABILITY_TURN_ORIGIN_KINDS)[keyof typeof CAPABILITY_TURN_ORIGIN_KINDS];
90
+ export interface CapabilityTurnOrigin {
91
+ readonly kind: CapabilityTurnOriginKind;
92
+ readonly scheduleId: string;
93
+ readonly invocationId: string;
94
+ readonly scheduledFor: string;
95
+ readonly unattended: boolean;
78
96
  }
79
97
  export interface CapabilityExternalDynamicContext {
80
98
  readonly ruleIds?: readonly string[];
81
99
  readonly vcs?: CapabilityVcsSnapshot;
100
+ readonly origin?: CapabilityTurnOrigin;
82
101
  }
83
102
  export interface EffectiveToolCapability {
84
103
  readonly id: string;
@@ -131,6 +150,7 @@ export interface BuildCapabilityTurnContextInput {
131
150
  readonly ruleIds?: readonly string[];
132
151
  readonly sessions?: readonly CapabilitySessionSnapshot[];
133
152
  readonly vcs?: CapabilityVcsSnapshot;
153
+ readonly origin?: CapabilityTurnOrigin;
134
154
  }
135
155
  export interface CapabilityAgentOnboardingCatalogEntry {
136
156
  readonly shortName: string;
@@ -1 +1 @@
1
- import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=1;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",transcriptRead:"transcript-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server"};export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},s=new Set(["default","example","examples"]),r=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function p(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function u(e){return e.length>=256&&/^[a-z0-9+/_=-]+$/iu.test(e)}function I(e){return u(e)?d:p(n(e,l).replace(a,c))}function m(e,t){if(!Object.hasOwn(e,t))return t;let n=1;for(;;){const o=`~${String(n)}`,s=`${t.slice(0,i.objectKeyChars-o.length)}${o}`;if(!Object.hasOwn(e,s))return s;n+=1}}function f(e,n){if(n.depth>=i.depth)return"[nested value omitted]";if("string"==typeof e)return n.sensitive&&!r.has(n.key.toLowerCase())?l:I(e);if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if(Array.isArray(e)){const t=e.slice(0,i.arrayItems).map(e=>f(e,{...n,depth:n.depth+1}));return e.length>i.arrayItems&&t.push(`[${String(e.length-i.arrayItems)} items omitted]`),t}const o=Object.entries(e).filter(e=>void 0!==e[1]&&!s.has(e[0].toLowerCase())).sort(([e],[t])=>e.localeCompare(t)),a={};for(const[e,s]of o.slice(0,i.objectEntries)){a[m(a,p(I(e),i.objectKeyChars))]=f(s,{depth:n.depth+1,key:e,sensitive:n.sensitive||t(e)})}return o.length>i.objectEntries&&(a[m(a,"__roll_snapshot_omitted__")]=o.length-i.objectEntries),a}function A(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function L(e,t=0){if(t>32)return"[nested value omitted]";if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>L(e,t+1));if(A(e)){const n={};for(const[o,i]of Object.entries(e))void 0!==i&&(n[o]=L(i,t+1));return n}return"number"==typeof e?String(e):void 0===e?null:String(e)}const C={[CAPABILITY_TOOL_ROLES.skill]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.fileRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.sessionList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.transcriptRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.agentInstall]:CAPABILITY_APPROVAL_MODES.alwaysConfirm,[CAPABILITY_TOOL_ROLES.userInput]:CAPABILITY_APPROVAL_MODES.readOnly};function O(e){return C[e]??CAPABILITY_APPROVAL_MODES.runtimePolicy}function S(e,t){return t!==CAPABILITY_TOOL_ROLES.agent?CAPABILITY_TOOL_SOURCE_KINDS.builtIn:e.agentSource??CAPABILITY_TOOL_SOURCE_KINDS.agent}function _(e,t){const n=new Set(e.map(e=>e.role)),o=[CAPABILITY_TOOL_ROLES.sessionCommand,CAPABILITY_TOOL_ROLES.sessionPoll,CAPABILITY_TOOL_ROLES.sessionList].every(e=>n.has(e));return{manifest:CAPABILITY_MANIFEST_LIFECYCLES.manifest,turnContext:CAPABILITY_MANIFEST_LIFECYCLES.turnContext,hostMode:t,sessionExec:o?CAPABILITY_SESSION_EXEC_LIFECYCLES.resumable:CAPABILITY_SESSION_EXEC_LIFECYCLES.unavailable,sessionDurability:o?CAPABILITY_SESSION_DURABILITIES.processLocal:CAPABILITY_SESSION_DURABILITIES.unavailable}}export function buildEffectiveCapabilityManifest(t){const n=Object.keys(t.tools).sort((e,t)=>e.localeCompare(t)).map(n=>{const o=t.tools[n],i=t.resolveRoute(n);if(!o||!i)throw new Error(`无法为已注册工具 ${n} 构建 capability manifest`);const s=t.toolRoles[n];if(!s)throw new Error(`已注册工具 ${n} 缺少 capability role`);const r="description"in o?o.description:void 0;return{id:n,agentName:i.agentName,toolName:i.toolName,source:S(i,s),...i.transport?{transport:i.transport}:{},...i.runtimeOwnership?{runtimeOwnership:i.runtimeOwnership}:{},...i.annotations?{annotations:{...i.annotations}}:{},role:s,approval:O(s),..."string"==typeof r&&r.length>0?{description:r}:{},inputSchema:L(e(o.inputSchema).jsonSchema)}});return{version:1,audience:"roll-chat",profile:t.profile,lifecycle:_(n,t.hostMode??CAPABILITY_HOST_MODES.embedded),tools:n,skills:t.skills.map(e=>({...e})),agentCount:t.agentCount,agentOnboardingCatalog:(t.agentOnboardingCatalog??[]).map(e=>({...e})),stableContext:{rules:o,shellHints:[...t.shellHints??[]]},dynamicContext:{cwd:t.cwd,platform:t.platform??process.platform}}}export function findCapabilityToolId(e,t){return e.tools.find(e=>e.role===t)?.id}export function listCapabilityToolIds(e,t){return e.tools.filter(e=>e.role===t).map(e=>e.id)}function T(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}export function buildEffectiveCapabilityTurnContext(e,t={}){const n=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.sessionList),o=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.transcriptRead);return{version:1,audience:e.audience,profile:e.profile,lifecycle:{...e.lifecycle},cwd:e.dynamicContext.cwd,platform:e.dynamicContext.platform,date:T(t.now??new Date),dynamic:{ruleIds:[...t.ruleIds??e.stableContext.rules],sessions:(t.sessions??[]).map(e=>({...e})),...t.vcs?{vcs:{...t.vcs}}:{}},effectiveToolIds:e.tools.map(e=>e.id),explicitSkillNames:[...t.explicitSkillNames??[]],...n?{sessionListToolId:n}:{},...o?{transcriptReadToolId:o}:{}}}function y(e){return e.slice(0,i.arrayItems).map(e=>I(e))}function E(e){return{id:I(e.id),agentName:I(e.agentName),toolName:I(e.toolName),source:e.source,...e.transport?{transport:e.transport}:{},...e.runtimeOwnership?{runtimeOwnership:e.runtimeOwnership}:{},...e.annotations?{annotations:{...e.annotations}}:{},role:e.role,approval:e.approval,...e.description?{description:I(e.description)}:{},inputSchema:f(e.inputSchema,{depth:0,key:"inputSchema",sensitive:!1})}}function h(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},tools:e.tools.slice(0,i.arrayItems).map(E),skills:e.skills.slice(0,i.arrayItems).map(e=>({name:I(e.name),description:I(e.description),source:e.source})),agentCount:e.agentCount,agentOnboardingCatalog:e.agentOnboardingCatalog.slice(0,i.arrayItems).map(e=>({shortName:I(e.shortName),description:I(e.description)})),stableContext:{rules:y(e.stableContext.rules),shellHints:y(e.stableContext.shellHints)},dynamicContext:{cwd:I(e.dynamicContext.cwd),platform:e.dynamicContext.platform}}}function b(e){return{version:e.version,audience:e.audience,profile:I(e.profile),lifecycle:{...e.lifecycle},cwd:I(e.cwd),platform:e.platform,date:I(e.date),dynamic:{ruleIds:y(e.dynamic.ruleIds),sessions:e.dynamic.sessions.slice(0,i.arrayItems).map(e=>({...e})),...e.dynamic.vcs?{vcs:{...e.dynamic.vcs,...e.dynamic.vcs.branch?{branch:I(e.dynamic.vcs.branch)}:{}}}:{}},effectiveToolIds:y(e.effectiveToolIds),explicitSkillNames:y(e.explicitSkillNames),...e.sessionListToolId?{sessionListToolId:I(e.sessionListToolId)}:{},...e.transcriptReadToolId?{transcriptReadToolId:I(e.transcriptReadToolId)}:{}}}export function createSafeCapabilitySnapshot(e,t){return{manifest:h(e),...t?{turnContext:b(t)}:{}}}
1
+ import{asSchema as e}from"ai";import{isSensitiveFieldName as t,redactSecretText as n}from"../tool-bridge/tool-execution-record.js";export const CAPABILITY_MANIFEST_VERSION=1;export const CAPABILITY_TURN_CONTEXT_VERSION=2;export const CAPABILITY_TOOL_ROLES={agent:"agent",skill:"skill",shell:"shell",fileRead:"file-read",fileEdit:"file-edit",fileVerify:"file-verify",sessionCommand:"session-command",sessionPoll:"session-poll",sessionList:"session-list",agentInstall:"agent-install",scheduleCreate:"schedule-create",scheduleList:"schedule-list",transcriptRead:"transcript-read",userInput:"user-input"};export const CAPABILITY_APPROVAL_MODES={readOnly:"read-only",alwaysConfirm:"always-confirm",runtimePolicy:"runtime-policy"};export const CAPABILITY_TOOL_SOURCE_KINDS={builtIn:"built-in",agent:"agent"};export const CAPABILITY_MANIFEST_LIFECYCLES={manifest:"session-snapshot",turnContext:"per-turn"};export const CAPABILITY_HOST_MODES={embedded:"embedded",interactive:"interactive",oneShot:"one-shot",server:"server",background:"background"};export function isProcessBoundHostMode(e){return e===CAPABILITY_HOST_MODES.oneShot||e===CAPABILITY_HOST_MODES.background}export function shouldOfferAgentInstall(e){return e!==CAPABILITY_HOST_MODES.background}export function shouldOfferScheduleCreate(e){return e!==CAPABILITY_HOST_MODES.background}export const CAPABILITY_SESSION_EXEC_LIFECYCLES={resumable:"resumable",unavailable:"unavailable"};export const CAPABILITY_SESSION_DURABILITIES={processLocal:"process-local",unavailable:"unavailable"};export const CAPABILITY_TURN_ORIGIN_KINDS={scheduled:"scheduled"};const o=["tool-grounding/v1","task-persistence/v1","output-channel/v1"],i={stringChars:512,arrayItems:128,objectEntries:128,depth:16,objectKeyChars:128},r=new Set(["default","example","examples"]),s=new Set(["type","format","$ref","$schema"]),a=/data:(?:image|audio|video)\/[^\s,]{1,80}(?:;base64)?,[^\s"'<>)]*/giu,l="[sensitive value redacted]",c="[media value omitted]",d="[binary-like value omitted]";function u(e,t=i.stringChars){return e.length<=t?e:`${e.slice(0,t-1)}…`}function I(e){return e.length>=256&&/^[a-z0-9+/_=-]+$/iu.test(e)}function p(e){return I(e)?d:u(n(e,l).replace(a,c))}function m(e,t){if(!Object.hasOwn(e,t))return t;let n=1;for(;;){const o=`~${String(n)}`,r=`${t.slice(0,i.objectKeyChars-o.length)}${o}`;if(!Object.hasOwn(e,r))return r;n+=1}}function A(e,n){if(n.depth>=i.depth)return"[nested value omitted]";if("string"==typeof e)return n.sensitive&&!s.has(n.key.toLowerCase())?l:p(e);if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if(Array.isArray(e)){const t=e.slice(0,i.arrayItems).map(e=>A(e,{...n,depth:n.depth+1}));return e.length>i.arrayItems&&t.push(`[${String(e.length-i.arrayItems)} items omitted]`),t}const o=Object.entries(e).filter(e=>void 0!==e[1]&&!r.has(e[0].toLowerCase())).sort(([e],[t])=>e.localeCompare(t)),a={};for(const[e,r]of o.slice(0,i.objectEntries)){a[m(a,u(p(e),i.objectKeyChars))]=A(r,{depth:n.depth+1,key:e,sensitive:n.sensitive||t(e)})}return o.length>i.objectEntries&&(a[m(a,"__roll_snapshot_omitted__")]=o.length-i.objectEntries),a}function f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function O(e,t=0){if(t>32)return"[nested value omitted]";if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>O(e,t+1));if(f(e)){const n={};for(const[o,i]of Object.entries(e))void 0!==i&&(n[o]=O(i,t+1));return n}return"number"==typeof e?String(e):void 0===e?null:String(e)}const L={[CAPABILITY_TOOL_ROLES.skill]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.fileRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.sessionList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.transcriptRead]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.agentInstall]:CAPABILITY_APPROVAL_MODES.alwaysConfirm,[CAPABILITY_TOOL_ROLES.scheduleList]:CAPABILITY_APPROVAL_MODES.readOnly,[CAPABILITY_TOOL_ROLES.userInput]:CAPABILITY_APPROVAL_MODES.readOnly};function C(e){return L[e]??CAPABILITY_APPROVAL_MODES.runtimePolicy}function S(e,t){return t!==CAPABILITY_TOOL_ROLES.agent?CAPABILITY_TOOL_SOURCE_KINDS.builtIn:e.agentSource??CAPABILITY_TOOL_SOURCE_KINDS.agent}function _(e,t){const n=new Set(e.map(e=>e.role)),o=[CAPABILITY_TOOL_ROLES.sessionCommand,CAPABILITY_TOOL_ROLES.sessionPoll,CAPABILITY_TOOL_ROLES.sessionList].every(e=>n.has(e));return{manifest:CAPABILITY_MANIFEST_LIFECYCLES.manifest,turnContext:CAPABILITY_MANIFEST_LIFECYCLES.turnContext,hostMode:t,sessionExec:o?CAPABILITY_SESSION_EXEC_LIFECYCLES.resumable:CAPABILITY_SESSION_EXEC_LIFECYCLES.unavailable,sessionDurability:o?CAPABILITY_SESSION_DURABILITIES.processLocal:CAPABILITY_SESSION_DURABILITIES.unavailable}}export function buildEffectiveCapabilityManifest(t){const n=Object.keys(t.tools).sort((e,t)=>e.localeCompare(t)).map(n=>{const o=t.tools[n],i=t.resolveRoute(n);if(!o||!i)throw new Error(`无法为已注册工具 ${n} 构建 capability manifest`);const r=t.toolRoles[n];if(!r)throw new Error(`已注册工具 ${n} 缺少 capability role`);const s="description"in o?o.description:void 0;return{id:n,agentName:i.agentName,toolName:i.toolName,source:S(i,r),...i.transport?{transport:i.transport}:{},...i.runtimeOwnership?{runtimeOwnership:i.runtimeOwnership}:{},...i.annotations?{annotations:{...i.annotations}}:{},role:r,approval:C(r),..."string"==typeof s&&s.length>0?{description:s}:{},inputSchema:O(e(o.inputSchema).jsonSchema)}});return{version:1,audience:"roll-chat",profile:t.profile,lifecycle:_(n,t.hostMode??CAPABILITY_HOST_MODES.embedded),tools:n,skills:t.skills.map(e=>({...e})),agentCount:t.agentCount,agentOnboardingCatalog:(t.agentOnboardingCatalog??[]).map(e=>({...e})),stableContext:{rules:o,shellHints:[...t.shellHints??[]]},dynamicContext:{cwd:t.cwd,platform:t.platform??process.platform}}}export function findCapabilityToolId(e,t){return e.tools.find(e=>e.role===t)?.id}export function listCapabilityToolIds(e,t){return e.tools.filter(e=>e.role===t).map(e=>e.id)}function T(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}export function buildEffectiveCapabilityTurnContext(e,t={}){const n=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.sessionList),o=findCapabilityToolId(e,CAPABILITY_TOOL_ROLES.transcriptRead);return{version:2,audience:e.audience,profile:e.profile,lifecycle:{...e.lifecycle},cwd:e.dynamicContext.cwd,platform:e.dynamicContext.platform,date:T(t.now??new Date),dynamic:{ruleIds:[...t.ruleIds??e.stableContext.rules],sessions:(t.sessions??[]).map(e=>({...e})),...t.vcs?{vcs:{...t.vcs}}:{},...t.origin?{origin:{...t.origin}}:{}},effectiveToolIds:e.tools.map(e=>e.id),explicitSkillNames:[...t.explicitSkillNames??[]],...n?{sessionListToolId:n}:{},...o?{transcriptReadToolId:o}:{}}}function y(e){return e.slice(0,i.arrayItems).map(e=>p(e))}function h(e){return{id:p(e.id),agentName:p(e.agentName),toolName:p(e.toolName),source:e.source,...e.transport?{transport:e.transport}:{},...e.runtimeOwnership?{runtimeOwnership:e.runtimeOwnership}:{},...e.annotations?{annotations:{...e.annotations}}:{},role:e.role,approval:e.approval,...e.description?{description:p(e.description)}:{},inputSchema:A(e.inputSchema,{depth:0,key:"inputSchema",sensitive:!1})}}function E(e){return{version:e.version,audience:e.audience,profile:p(e.profile),lifecycle:{...e.lifecycle},tools:e.tools.slice(0,i.arrayItems).map(h),skills:e.skills.slice(0,i.arrayItems).map(e=>({name:p(e.name),description:p(e.description),source:e.source})),agentCount:e.agentCount,agentOnboardingCatalog:e.agentOnboardingCatalog.slice(0,i.arrayItems).map(e=>({shortName:p(e.shortName),description:p(e.description)})),stableContext:{rules:y(e.stableContext.rules),shellHints:y(e.stableContext.shellHints)},dynamicContext:{cwd:p(e.dynamicContext.cwd),platform:e.dynamicContext.platform}}}function g(e){return{version:e.version,audience:e.audience,profile:p(e.profile),lifecycle:{...e.lifecycle},cwd:p(e.cwd),platform:e.platform,date:p(e.date),dynamic:{ruleIds:y(e.dynamic.ruleIds),sessions:e.dynamic.sessions.slice(0,i.arrayItems).map(e=>({...e})),...e.dynamic.vcs?{vcs:{...e.dynamic.vcs,...e.dynamic.vcs.branch?{branch:p(e.dynamic.vcs.branch)}:{}}}:{},...e.dynamic.origin?{origin:{kind:e.dynamic.origin.kind,scheduleId:p(e.dynamic.origin.scheduleId),invocationId:p(e.dynamic.origin.invocationId),scheduledFor:p(e.dynamic.origin.scheduledFor),unattended:e.dynamic.origin.unattended}}:{}},effectiveToolIds:y(e.effectiveToolIds),explicitSkillNames:y(e.explicitSkillNames),...e.sessionListToolId?{sessionListToolId:p(e.sessionListToolId)}:{},...e.transcriptReadToolId?{transcriptReadToolId:p(e.transcriptReadToolId)}:{}}}export function createSafeCapabilitySnapshot(e,t){return{manifest:E(e),...t?{turnContext:g(t)}:{}}}