@robota-sdk/agent-session 3.0.5 → 3.0.7

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.
@@ -4,8 +4,8 @@ import{appendFileSync as e,chmodSync as t,closeSync as n,constants as r,existsSy
4
4
  `);return[this.basePrompt??rr,r,``,`Conversation:`,i].join(`
5
5
  `)}};const ar=.835;var or=class{contextUsedTokens=0;contextMaxTokens;contextMaxTokensOverride;autoCompactThreshold;constructor(e,t,n){this.contextMaxTokensOverride=t,this.contextMaxTokens=t??_e(e),this.autoCompactThreshold=sr(n)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(e){return this.autoCompactThreshold!==!1&&(e?pe(e).usedTokens:this.contextUsedTokens)>=this.contextMaxTokens*this.autoCompactThreshold}setModel(e){this.contextMaxTokens=this.contextMaxTokensOverride??_e(e)}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=sr(e)}updateFromHistory(e){this.contextUsedTokens=pe(e).usedTokens}reset(){this.contextUsedTokens=0}};function sr(e){if(e===void 0)return ar;if(e===!1)return!1;if(!Number.isFinite(e)||e<=0||e>1)throw RangeError(`autoCompactThreshold must be a number greater than 0 and at most 1.`);return e}async function cr(e,t){if(t===void 0)return e;if(t.aborted)return!1;let n;try{return await Promise.race([e,new Promise(e=>{n=()=>e(!1),t.addEventListener(`abort`,n,{once:!0})})])}finally{n!==void 0&&t.removeEventListener(`abort`,n)}}function lr(e){return e===`allow-session`?{allowed:!0,rememberForSession:!0,rememberForProject:!1}:e===`allow-project`?{allowed:!0,rememberForSession:!0,rememberForProject:!0}:{allowed:e===!0,rememberForSession:!1,rememberForProject:!1}}async function ur(e){let t={allowed:!1,rememberForSession:!1,rememberForProject:!1};if(e.alreadyAllowed)return{allowed:!0,rememberForSession:!1,rememberForProject:!1};if(e.signal?.aborted===!0)return t;let n={...e.signal?{signal:e.signal}:{},...e.executionId===void 0?{}:{executionId:e.executionId}},r=e.signal!==void 0||e.executionId!==void 0,i=e.handler?()=>r?e.handler(e.toolName,e.toolArgs,n):e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return i===void 0?t:lr(await cr(i(),e.signal))}const dr=`robota-session/approval`;function fr(e){return e?.waits.some(e=>e.request.kind===dr)??!1}async function pr(e,t,n){let r=t?.waits.filter(e=>e.request.kind===dr)??[];if(!n&&!r.length)return;if(!t||t.action.toolName!==e.toolName)throw new x(`EXECUTION_RECOVERY_INVALID`,`Checkpointed approval requires the current journaled action`);let i=m(e.cwd);for(let{request:t}of r)if(t.data.version!==1||t.data.sessionId!==e.sessionId||t.data.cwd!==i||t.data.toolName!==e.toolName)throw new x(`EXECUTION_RECOVERY_INVALID`,`Saved approval belongs to a different Session or tool`);let a=await t.request({kind:dr,data:{version:1,sessionId:e.sessionId,cwd:i,toolName:e.toolName,arguments:structuredClone(e.toolArgs)}});if(Object.keys(a).length!==1||typeof a.approved!=`boolean`)throw new x(`EXECUTION_RECOVERY_INVALID`,`Approval response must contain only a boolean approved decision`);return a.approved}const mr=3,hr=20;function gr(e,t){return`${e}\u0000${JSON.stringify(t)}`}var _r=class{classifier;consecutive=0;total=0;paused=!1;retries=new Set;constructor(e){this.classifier=e}isPaused(){return this.paused}resume(){this.paused=!1,this.consecutive=0}grantRetry(e,t){this.retries.add(gr(e,t))}takeRetry(e,t){return this.retries.delete(gr(e,t))}async judge(e,t){let n;try{n=await this.classifier.classify(e,t)}catch{n=void 0}if(n===void 0){t?.aborted!==!0&&(this.consecutive+=1);let e=this.consecutive>=3;return e&&(this.paused=!0),{kind:`unusable`,reason:`no usable verdict`,message:`The auto-mode classifier gave no usable verdict, so the call was not run. Try again, or ask the user to approve it.`+(e?` Auto mode is paused: the next calls ask the user.`:``)}}if(n.decision===`allow`)return this.consecutive=0,{kind:`allow`};this.consecutive+=1,this.total+=1;let r=this.consecutive>=3||this.total>=20;return this.total>=20&&(this.total=0),r&&(this.paused=!0),{kind:`block`,reason:n.reason,message:`Blocked by the auto-mode classifier: ${n.reason}. Do not retry the same action; take another approach or ask the user.`+(r?` Auto mode is paused after repeated blocks: the next calls ask the user.`:``)}}};function vr(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function yr(e,t){switch(e){case`path`:{let e=vr(t);return e===`/`?`/**`:`${e}/**`}case`url`:try{let e=new URL(t);return`${e.protocol}//${e.host}/**`}catch{return t}case`command`:{let e=t.trim().split(/\s+/)[0];return e?`${e} *`:void 0}default:return}}function br(e,t){let n=ye(e).argument;if(n===void 0)return e;let r=t[n.key];if(typeof r!=`string`||r===``)return e;let i=yr(n.kind,r);return i===void 0?e:`${e}(${i})`}function xr(e,t,n){let r=ye(e).argument;if(r===void 0||r.kind!==`path`)return t;let i=t[r.key];return typeof i!=`string`||i===``||ze(i)?t:{...t,[r.key]:Ve(n,i)}}function K(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function Sr(e,t,n){let r=e instanceof Error?e.message:String(e);return t?.({type:`end`,toolName:n.toolName,toolArgs:n.toolArgs,success:!1,executionId:n.executionId}),K(`threw`,r)}const Cr=K(`denied`,`Permission denied. The user did not approve this action.`),wr=C(`ToolHookHelpers`);function Tr(e){if(Ie(e)||typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function Er(e,t,n,r,i,a){return{session_id:e,cwd:t,hook_event_name:`PreToolUse`,tool_name:n,tool_input:r,...i!==void 0&&{permission_mode:i},...a!==void 0&&{transcript_path:a}}}async function Dr(e,t,n,r){let i=t,a,o=new Set([JSON.stringify(i.tool_input)]);for(let t=0;t<8;t++){let t=await Or(e,i,n,r);if(t.result!==null)return{refusal:t.result};let{permissionDecision:s,updatedInput:c}=t.hookResult;if(c!==void 0){if(typeof c!=`object`||!c||Array.isArray(c))return{refusal:K(`hook-blocked`,`PreToolUse updatedInput must be an object.`)};let e=xr(i.tool_name??``,c,i.cwd),t=JSON.stringify(e);if(t!==JSON.stringify(i.tool_input)){if(o.has(t))break;o.add(t),a=e,i={...i,tool_input:e};continue}}return{refusal:null,...a===void 0?{}:{parameters:a},...s===`allow`||s===`ask`?{decision:s}:{}}}let s=`PreToolUse input rewriting did not stabilize; no tool call was executed.`;return{refusal:K(`hook-blocked`,s,{blocked:!0,reason:s})}}async function Or(e,t,n,r){let i=await w(e,`PreToolUse`,t,n,r);if(i.blocked){let e=i.reason??`Blocked by hook`;return{result:K(`hook-blocked`,e,{blocked:!0,reason:e}),hookResult:i}}if(xe(`PreToolUse`)){let e=i.errors,t=e?.[0],n=i.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,a=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return{result:K(`hook-blocked`,a,{blocked:!0,reason:a}),hookResult:i}}if(r!==``)return{result:K(`hook-blocked`,r,{blocked:!0,reason:r}),hookResult:i}}return{result:null,hookResult:i}}function kr(e,t,n,r,i){w(e,`PostToolUse`,{...t,hook_event_name:`PostToolUse`,tool_output:typeof n.data==`string`?n.data:JSON.stringify(n.data)},r,i).catch(e=>wr.warn(`hook failed`,{error:e}))}function Ar(e,t){let n=ye(e).argument?.key;if(n===void 0)return;let r=t[n];if(typeof r==`string`)return r.length>200?`${r.slice(0,200)}…`:r}var jr=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=Ar(e,t);this.entries.unshift({toolName:e,...i===void 0?{}:{argument:i},reason:n,...r===void 0?{}:{detail:r},at:this.now()}),this.calls.unshift({toolName:e,toolArgs:t}),this.calls.length>this.capacity&&(this.calls.length=this.capacity),this.entries.length>this.capacity&&(this.entries.length=this.capacity)}list(){return[...this.entries]}callAt(e){return this.calls[e]}};const Mr=C(`ToolBodyTrace`);var Nr=class extends Error{result;constructor(e){super(`Effective tool arguments were not authorized`),this.result=e}};function Pr(e,t){try{e?.eventService?.emit(ie.DECIDED,{timestamp:new Date,executionId:e.executionId,decidedAt:new Date().toISOString(),decision:t})}catch(e){Mr.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function Fr(e,t){let n=e.execute.bind(e),r=e.executeWithAdmission?.bind(e),i=Pe(e.provenance),a=e=>{if(e.type!==`end`||!i)return t.onToolExecution?.(e);let n=Le({success:e.success??!1,parts:e.toolResultParts},i);t.onToolExecution?.({...e,toolResultParts:n.parts})},o=b,s=Object.create(e);Object.defineProperty(s,"provenance",{value:i,enumerable:!0});let c=async(i,s,c)=>{let l=i,u=`(unknown)`;try{u=e.getName(),l=xr(u,i,t.cwd),t.log(`tool_call`,{tool:u,args:l});let d=Er(t.sessionId,t.cwd,u,l,t.getPermissionMode(),t.transcriptPath),f=await Dr(t.config.hooks,d,t.hookTypeExecutors,s?.hookTraceEnv);if(f.refusal)return t.log(`tool_blocked`,{tool:u,reason:`hook`}),Pr(s,`hook-blocked`),f.refusal;f.parameters!==void 0&&(l=f.parameters,d={...d,tool_input:l});let p=await t.checkPermission(u,l,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,f.decision,s?.executionId);if(p!==!0)return t.log(`tool_denied`,{tool:u,reason:`permission`}),Pr(s,`denied`),a({type:`end`,toolName:u,toolArgs:l,success:!1,denied:!0,executionId:s?.executionId}),typeof p==`object`?K(`denied`,p.message):Cr;Pr(s,`allowed`),s?.signal?.throwIfAborted(),a({type:`start`,toolName:u,toolArgs:structuredClone(l),executionId:s?.executionId}),s?.signal?.throwIfAborted();let m,h=async e=>{s?.signal?.throwIfAborted();let n=xr(u,e,t.cwd);if(JSON.stringify(n)!==JSON.stringify(e))throw new Nr(K(`denied`,`Tool admission requires final canonical arguments; relative paths must be resolved before admission.`));if(JSON.stringify(n)!==JSON.stringify(l)){let e=Er(t.sessionId,t.cwd,u,n,t.getPermissionMode(),t.transcriptPath),r=await Dr(t.config.hooks,e,t.hookTypeExecutors,s?.hookTraceEnv);if(r.refusal)throw new Nr(r.refusal);if(r.parameters!==void 0&&JSON.stringify(r.parameters)!==JSON.stringify(n))throw new Nr(K(`hook-blocked`,`A hook cannot replace arguments already settled by the tool; retry as a new call.`));let i=await t.checkPermission(u,n,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,r.decision,s?.executionId);if(i!==!0)throw new Nr(typeof i==`object`?K(`denied`,i.message):Cr);d=e}l=structuredClone(e),s?.signal?.throwIfAborted(),await c?.(l),s?.signal?.throwIfAborted(),m=Date.now()},g=`failure`,_;try{let e=s===void 0?void 0:{...s,parameters:l,instanceEventService:o};c&&r?_=await r(l,e,h):(c?await h(l):m=Date.now(),s?.signal?.throwIfAborted(),_=await n(l,e)),g=s?.signal?.aborted?`interrupted`:_.success?`success`:`failure`}catch(e){throw g=s?.signal?.aborted||be(e)?`interrupted`:`failure`,e}finally{try{m!==void 0&&s?.eventService?.emit(re.COMPLETED,{timestamp:new Date,executionId:s.executionId,startedAt:new Date(m).toISOString(),endedAt:new Date(Math.max(Date.now(),m)).toISOString(),outcome:g,toolName:u,...typeof s.toolBodyId==`string`?{toolBodyId:s.toolBodyId}:{}})}catch(e){Mr.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let v=Tr(_);v!==_&&typeof _.data==`string`&&t.terminal.writeLine(` ⚠ Output truncated: ${_.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),a({type:`end`,toolName:u,toolArgs:l,success:v.success,toolResultData:typeof v.data==`string`?v.data:JSON.stringify(v.data),toolResultParts:v.parts,executionId:s?.executionId,...v.view?{view:v.view}:{}});let y=typeof v.data==`string`?v.data.length:JSON.stringify(v.data)?.length??0;return t.log(`tool_result`,{tool:u,success:v.success,dataChars:y,truncated:v!==_}),kr(t.config.hooks,d,v,t.hookTypeExecutors,s?.hookTraceEnv),v}catch(e){if(Se(e))throw e;return e instanceof Nr?e.result:Sr(e,a,{toolName:u,toolArgs:l,executionId:s?.executionId})}},l=async(...e)=>Le(await c(...e),i);return s.execute=l,s.executeWithAdmission=l,s.setEventService=t=>{o=t??b,e.setEventService(t)},s}function Ir(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:Ve(e,...n.reverse())}catch{let r=Re(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Lr(e,t){let n=Be(e,t);return n===``||!n.startsWith(`..`)&&!ze(n)}function Rr(e){return(t,n)=>{let r=Ir(e),i=Ir(Ve(t??r,n));return Lr(r,i)?i:void 0}}function zr(e){let t=[...he(e.allow,`allow`),...he(e.restrictive,`deny`)];if(t.length===0)return;let n=t.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${n}. Fix the pattern where it is configured (issue #2428).`)}var Br=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;pathProtection;homeDirectory;resolveInWorkspace;commandSandbox;denials=new jr;peerTurn=!1;checkpointedApprovals=!1;autoMode;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.getPermissionMode=e.getPermissionMode,this.config=e.config,this.presetFreeRules=e.presetFreePermissions??{allow:[...e.config.permissions.allow],deny:[...e.config.permissions.deny]},zr(this.configuredRules(e)),this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool,this.permissionPolicy=e.permissionPolicy,this.taskPermissions=e.taskPermissions,this.homeDirectory=e.homeDirectory??Ke(),this.pathProtection=e.pathProtection,this.resolveInWorkspace=Rr(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new _r(e.permissionClassifier))}beginTurn(e,t=!1){this.peerTurn=e,this.checkpointedApprovals=t}endTurn(){this.peerTurn=!1,this.checkpointedApprovals=!1}hasPermissionClassifier(){return this.autoMode!==void 0}allowRetryOfDenial(e){let t=this.denials.list()[e],n=this.denials.callAt(e);if(t?.reason===`classifier`&&n!==void 0&&this.autoMode!==void 0)return this.autoMode.grantRetry(n.toolName,n.toolArgs),t}configuredRules(e={config:this.config,...this.taskPermissions===void 0?{}:{taskPermissions:this.taskPermissions}}){return{allow:[...e.config.permissions.allow,...e.taskPermissions?.allow??[]],restrictive:[...e.config.permissions.deny,...e.config.permissions.ask??[],...e.taskPermissions?.deny??[]]}}isToolVisible(e){let t=ye(e);return!this.peerTurn&&t.repliesToPeer===!0||this.peerTurn&&t.notInPeerTurn===!0?!1:!we(e,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(e){for(let t of e){let e=t.schema;if(e===void 0)continue;let n=e.parameters?.properties??{};Me(e.name,{parameters:Object.keys(n)})}let t=this.configuredRules();zr(t);for(let{pattern:e,reason:n}of ge(t.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${e}" ${n}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i,a,o,s)=>this.decidePermission(e,t,n,r,i,{continuation:a,...o===void 0?{}:{hookDecision:o},...s===void 0?{}:{executionId:s}})};return e.map(e=>Fr(e,t))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}getRecentDenials(){return this.denials.list()}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}currentPermissionRules(){return{allow:[...this.config.permissions.allow],deny:[...this.config.permissions.deny],ask:[...this.config.permissions.ask??[]]}}applyPresetToolLists(e){let t=se(this.presetFreeRules,e);this.config.permissions.allow=t.allow,this.config.permissions.deny=t.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=Er(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath),i=await Dr(this.config.hooks,r,this.hookTypeExecutors);return i.refusal||i.parameters!==void 0?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1,...i.decision===void 0?{}:{hookDecision:i.decision}})===!0}async decidePermission(e,t,n,r=`interactive`,i,a={}){let o=await this.evaluateToolPermission(e,t,n,r,i,a);return o===!0?(n?.throwIfAborted(),await pr({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a.continuation,!1)??!0):o}async evaluateToolPermission(e,t,n,r=`interactive`,i,a={}){let o=this.permissionPolicy===void 0?void 0:Ae(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),s=this.getPermissionMode(),c=[...this.config.permissions.allow,...o?.allow??[]],l={allow:s===`auto`?oe(c):c,deny:[...this.config.permissions.deny,...o?.deny??[]],ask:this.config.permissions.ask??[]},u={cwd:this.cwd,homeDirectory:this.homeDirectory,pathProtection:this.pathProtection},d=me(e,t,s,l,{...u,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:a.sandboxed!==!1&&this.sandboxAutoApproves(e,t),...o?.ceiling===void 0?{}:{ceiling:o.ceiling},askAll:o?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(e,t,d,i),d===`deny`)return this.denials.record(e,t,`policy`),!1;if(a.hookDecision===`ask`)return this.promptForApproval(e,t,n,r,!0,a);if(d===`auto`)return!0;let f=Ne(e,t,l,u);return s===`auto`&&this.autoMode!==void 0&&!f&&o?.askAll!==!0?this.decideInAutoMode(this.autoMode,e,t,n,r,i,a):a.hookDecision===`allow`&&!f&&o?.askAll!==!0||this.promptForApproval(e,t,n,r,f,a)}async decideInAutoMode(e,t,n,r,i,a,o){if(e.takeRetry(t,n)||Te(t,n,oe([...this.sessionAllowedTools])))return!0;if(e.isPaused()){let a=await this.promptForApproval(t,n,r,i,!0,o);return a&&!this.checkpointedApprovals&&!fr(o.continuation)&&e.resume(),a}let s=await e.judge({toolName:t,toolArgs:n,cwd:this.cwd},r);return r?.aborted===!0?!1:this.getPermissionMode()===`auto`?s.kind===`allow`?!0:(this.denials.record(t,n,`classifier`,s.reason),{message:s.message}):this.decidePermission(t,n,r,i,a,o)}async promptForApproval(e,t,n,r=`interactive`,i=!1,{continuation:a,executionId:o}={}){let s=!i&&Te(e,t,[...this.sessionAllowedTools]);if(this.checkpointedApprovals&&!s||fr(a)){if(n?.aborted||r!==`interactive`)return!1;let i=await pr({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a,!0);return i!==!0&&this.denials.record(e,t,`user`),i===!0}let c=br(e,t),l=n?.aborted===!0,u=r===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),d=await ur({toolName:e,alreadyAllowed:s,...r===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...r===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:t,...n?{signal:n}:{},...o===void 0?{}:{executionId:o}});if(!d.allowed&&!l&&this.denials.record(e,t,u?`user`:`no-approver`),i)return d.allowed;if(d.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(c)}return d.rememberForSession&&this.sessionAllowedTools.add(c),d.allowed}firePermissionDecisionHook(e,t,n,r){let i=this.getPermissionMode();w(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:e,tool_input:t,permission_decision:n,...i!==void 0&&{permission_mode:i},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,r).catch(()=>void 0)}sandboxAutoApproves(e,t){if(this.commandSandbox===void 0)return!1;let n=ye(e).argument;if(n?.kind!==`command`)return!1;let r=t[n.key];return typeof r==`string`&&this.commandSandbox.autoApproves(e,r)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function Vr(e,t,n,r,i){return new Br({pathProtection:e.pathProtection,sessionId:t,cwd:n,getPermissionMode:r,config:{permissions:e.permissions??{allow:[],deny:[]},hooks:e.hooks},...e.presetFreePermissions===void 0?{}:{presetFreePermissions:e.presetFreePermissions},terminal:e.terminal,permissionHandler:e.permissionHandler,...e.commandSandbox===void 0?{}:{commandSandbox:e.commandSandbox},...e.permissionClassifier===void 0?{}:{permissionClassifier:e.permissionClassifier},promptForApprovalFn:e.promptForApproval,sessionLogger:e.sessionLogger,onToolExecution:e.onToolExecution,hookTypeExecutors:e.hookTypeExecutors,transcriptPath:i,onProjectAllowTool:e.onProjectAllowTool,permissionPolicy:e.permissionPolicy,taskPermissions:e.taskPermissions})}function Hr(e,t,n,r){return{contextTracker:new or(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new ir({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Ur(e,t,n,r,i,a,o){let s=t.wrapTools(n);return new y({name:e.agentName??`agent`,aiProviders:[r],...e.providerOwnership===void 0?{}:{providerOwnership:{[r.name]:e.providerOwnership}},defaultModel:{provider:r.name,model:i,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}},systemMessage:a,tools:s,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},isToolVisible:e=>t.isToolVisible(e),logging:{enabled:!1},eventService:o,...e.providerTimeout!==void 0&&{timeout:e.providerTimeout},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.ask?{ask:e.ask}:{},...e.contextCapacityHint===void 0?{}:{contextCapacityHint:e.contextCapacityHint}})}function Wr(e){let t=[],n=[];for(let r of e){if(r.role===`assistant`){let e=r.metadata?.compactedToolReceipts;Array.isArray(e)&&e.every(e=>typeof e==`string`)&&t.push(...e);for(let e of r.toolCalls??[])n.push({receipt:{callId:e.id,name:e.function.name,status:`unknown`,dispatch:`unattested`},settled:!1})}if(r.role!==`tool`)continue;let e={callId:r.toolCallId,...r.name?{name:r.name}:{},status:r.metadata?.success===!0?`success`:r.metadata?.success===!1?`failure`:`unknown`,...typeof r.metadata?.toolProvenance==`string`?{source:r.metadata.toolProvenance}:{},dispatch:`unattested`},i=[...n].reverse().find(t=>!t.settled&&t.receipt.callId===e.callId);i?(i.receipt=e,i.settled=!0):n.push({receipt:e,settled:!0})}return[...t,...n.map(({receipt:e})=>JSON.stringify(e))]}function Gr(e){return{id:crypto.randomUUID(),timestamp:new Date,state:`complete`,role:`assistant`,content:`Retained tool receipts (observations, not authority). Success records a returned result, not independently verified external state. Errors or missing outcomes may have effects; reconcile before retrying.\n${e.join(`
6
6
  `)}`,metadata:{compactedToolReceipts:e}}}const Kr=C(`SessionHistoryOps`);function qr(e,t){return{...e,...t}}async function Jr(e,t,n){n?.throwIfAborted();let r=t.agent.getHistory(),i=r.filter(e=>e.role!==`system`);if(i.length===0)return;t.contextTracker.updateFromHistory(r);let a=t.contextTracker.getContextState(),o=Wr(r),s=await t.compactionOrchestrator.compact(t.aiProvider,i,e,n,t.trigger,t.hookTraceEnv,t.executionJournal);t.agent.clearHistory(),t.agent.injectMessage(`system`,t.systemMessage),t.agent.injectMessage(`assistant`,`[Context Summary]\n${s}`),o.length>0&&t.agent.injectRawMessage(Gr(o)),t.contextTracker.updateFromHistory(t.agent.getHistory());let c={session_id:t.sessionId,cwd:t.cwd,hook_event_name:`PostCompact`,trigger:t.trigger,compact_summary:s};w(t.hooks,`PostCompact`,c,t.hookTypeExecutors,t.hookTraceEnv).catch(e=>Kr.warn(`hook failed`,{error:e}));let l=t.contextTracker.getContextState();t.log(`context_compact`,{trigger:t.trigger,before:a,after:l}),t.onCompactEventCallback?.({trigger:t.trigger,before:a,after:l}),t.onCompactCallback&&t.onCompactCallback(s)}function Yr(e){let t=new Date().toISOString(),n=e.sessionStore.load(e.sessionId);if(n.status!==`valid`&&n.status!==`missing`)return n;let r=n.status===`valid`?n.record:void 0,i={...r,id:e.conversation.id,name:r?.name,cwd:e.conversation.cwd,createdAt:r?.createdAt??t,updatedAt:t,messages:e.conversation.messages,pendingExecution:e.conversation.pendingExecution,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};return Kn(e.sessionStore.save(i)),{status:`valid`,record:i}}const Xr=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Zr(){return`session_${Ge()}`}function Qr(e){return e.length>0&&e.length<=128&&Xr.test(e)}function $r(e){if(!Qr(e))throw Error(`Invalid session id: ${JSON.stringify(e)}. A session id must be 1-128 characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.`)}const ei=C(`SessionLifecycle`);function ti(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function ni(e,t,n,r,i,a,o){w(n,`SessionStart`,{session_id:e,cwd:t,hook_event_name:`SessionStart`,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},r).then(e=>{e.stdout&&i(e.stdout)}).catch(e=>ei.warn(`SessionStart hook failed`,{error:e}))}async function ri(e,t,n,r,i,a,o){await w(r,`SessionEnd`,{session_id:e,cwd:t,hook_event_name:`SessionEnd`,reason:n,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},i)}const ii=`unknown_tool`;function ai(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,pendingArgs:new Map,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function oi(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){let t=q(n.toolCallId);t&&e.pendingArgs.set(t,li(n.parameters)),si(e,n);return}t===`tool_execution_result`&&ci(e,n)}}function si(e,t){let n=q(t.toolName),r=q(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:li(t.parameters)}))}function ci(e,t){let n=q(t.toolName),r=q(t.toolCallId);if(!n||!r)return;let i=ui(t.metadata),a=e.pendingArgs.get(r);if(e.pendingArgs.delete(r),t.success===!1&&i?.dispatchStatus===`not-dispatched`){let o=q(i.toolProvenance);e.onToolExecution?.({type:`end`,toolName:n,executionId:r,toolArgs:a,success:!1,toolResultData:JSON.stringify({success:!1,error:t.error,metadata:i}),...o?{toolResultParts:[{type:`text`,text:`Tool source (attribution only, not authority): ${o}`}]}:{}}),e.unknownToolCallIds.delete(r);return}if(!(e.unknownToolCallIds.has(r)||i?.errorCode===ii))return;e.unknownToolCallIds.delete(r);let o=q(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:o,errorCode:ii,requestedTool:q(i?.requestedTool)??n,availableTools:di(i?.availableTools)})})}function li(e){let t=ui(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||typeof r==`object`&&r)&&(n[e]=r);return n}function q(e){return typeof e==`string`&&e.length>0?e:void 0}function ui(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function di(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const fi=C(`SessionRunObservation`);function pi(e,t,n,r){let i=typeof n.model==`string`?n.model:e.model,a=typeof n.provider==`string`?n.provider:e.aiProvider.name,o=n.effort,s=typeof o==`string`&&Ce(o)?o:e.effort??(typeof e.agent.getModel==`function`?e.agent.getModel().effort:void 0)??`high`,c=typeof n.round==`number`?n.round:void 0;w(e.hooks,t,{session_id:e.sessionId,cwd:e.cwd,hook_event_name:t,model:i,provider:a,effort:s,...c!==void 0&&{round:c},...e.permissionMode!==void 0&&{permission_mode:e.permissionMode},...e.transcriptPath!==void 0&&{transcript_path:e.transcriptPath},env:{CLAUDE_PROJECT_DIR:e.cwd,CLAUDE_SESSION_ID:e.sessionId}},e.hookTypeExecutors,r).catch(e=>fi.warn(`hook failed`,{error:e}))}function mi(e,t){let n=t?Fe(`hooks`,t,t.parentSpanId):void 0,r=ai({knownToolNames:e.knownToolNames??[],...e.onToolExecution&&{onToolExecution:e.onToolExecution}}),i=e.onTextDelta?t=>{e.log(`text_delta`,{delta:t}),e.onTextDelta?.(t)}:void 0,a={};return{onExecutionEvent:(t,i)=>{if(t===`history_mutation`&&i.mutation===`append_message`){let t=i.message;(t?.role===`user`||t?.role===`assistant`&&Array.isArray(t.toolCalls)&&t.toolCalls.length>0)&&e.checkpointHistory?.()}if(t!==te.COMPLETED&&e.log(t,i),oi(r,t,i),t===`provider_request`){let t=i;a={model:t.model,provider:t.provider},pi(e,`PreModelCall`,t,n)}else if(t===`provider_response_normalized`)pi(e,`PostModelCall`,{...i,...a},n);else if(t===ne.SWITCHED){let t=je(i);t!==void 0&&(pi(e,`PostModelCall`,{round:i.round,model:t.from.model,provider:t.from.provider},n),e.emitProviderFallback?.(t))}else if(t===te.COMPLETED&&e.emitProviderCallCompleted){let t=i;Number.isSafeInteger(t.round)&&t.round>0&&typeof t.startedAt==`string`&&typeof t.endedAt==`string`&&(t.outcome===`success`||t.outcome===`failure`||t.outcome===`interrupted`)&&e.emitProviderCallCompleted({round:t.round,startedAt:t.startedAt,endedAt:t.endedAt,outcome:t.outcome,...typeof t.callId==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t.callId)&&{callId:t.callId},...(t.disposition===`invoked`||t.disposition===`cache-hit`||t.disposition===`preflight-refused`)&&{disposition:t.disposition},...typeof t.providerId==`string`&&t.providerId.length>0&&t.providerId.length<=128&&[...t.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:t.providerId},...typeof t.modelId==`string`&&t.modelId.length>0&&t.modelId.length<=128&&[...t.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:t.modelId},...(t.usageProvenance===`complete`||t.usageProvenance===`partial`||t.usageProvenance===`absent`)&&{usageProvenance:t.usageProvenance},...t.usageProvenance===`complete`&&typeof t.promptTokens==`number`&&Number.isSafeInteger(t.promptTokens)&&t.promptTokens>=0&&typeof t.completionTokens==`number`&&Number.isSafeInteger(t.completionTokens)&&t.completionTokens>=0&&typeof t.totalTokens==`number`&&Number.isSafeInteger(t.totalTokens)&&t.totalTokens===t.promptTokens+t.completionTokens&&{promptTokens:t.promptTokens,completionTokens:t.completionTokens,totalTokens:t.totalTokens},...t.disposition===`invoked`&&typeof t.providerRequestId==`string`&&{providerRequestId:t.providerRequestId}})}t===`assistant_message_committed`&&(e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()))},...i&&{onTextDelta:i},...e.onThinkingDelta&&{onThinkingDelta:e.onThinkingDelta}}}async function hi(e,t){let n=await e.agent.resume({...t,...mi(e,t.traceContext)});return e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()),n}function gi(e,t){let n=m(t.cwd);return{append:async r=>{if((r.kind===`model-request`||r.kind===`model-cache-hit`)&&r.checkpoint){let i=structuredClone(r);i.checkpoint.owner={kind:`agent-session`,version:1,state:{sessionId:t.sessionId,cwd:n,peerTurn:t.peerTurn,executionId:r.executionId}},await e.append(i)}else await e.append(r)}}}function _i(e,t,n,r){let i,a=m(n);return{read:async o=>{let s=structuredClone(await e.read(o)),c;for(let e of s){if(e.kind!==`model-request`&&e.kind!==`model-cache-hit`)continue;let n=e.checkpoint?.owner,r=n?.state;if(!n||n.kind!==`agent-session`||n.version!==1||!r||r.sessionId!==t||r.cwd!==a||r.executionId!==o||typeof r.peerTurn!=`boolean`||c!==void 0&&c!==r.peerTurn||r.peerTurn&&e.checkpoint?.continuation?.options.withholdHostedTools!==!0)throw new x(`EXECUTION_RECOVERY_INVALID`,`Session continuation owner or scope is incompatible`);c=r.peerTurn}if(c===void 0)throw new x(`EXECUTION_RECOVERY_INVALID`,`No Session owner checkpoint exists`);return i=gi(e,{sessionId:t,cwd:n,peerTurn:c}),r(c),s},append:async e=>{if(!i)throw new x(`EXECUTION_RECOVERY_INVALID`,`Session owner has not been restored`);await i.append(e)}}}function vi(e){return{...e?.executionJournal!==void 0&&{executionJournal:e.executionJournal},...e?.ephemeralSystemContext!==void 0&&{ephemeralSystemContext:e.ephemeralSystemContext},...e?.driverId!==void 0&&{driverId:e.driverId},...e?.turnSource!==void 0&&{turnSource:e.turnSource},...e?.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e?.traceContext!==void 0&&{traceContext:e.traceContext},...e?.peerTurn===!0&&{withholdHostedTools:!0}}}const yi=C(`SessionRun`);async function bi(e,t,n,r,i){let a=i?.traceContext,o=a?Fe(`hooks`,a,a.parentSpanId):void 0;n.log(`user`,{content:e});let s=await w(n.hooks,`UserPromptSubmit`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`UserPromptSubmit`,user_message:t??e,prompt:t??e,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o),c=[n.sessionStartStdout,s.stdout].filter(Boolean).join(`
7
- `),l=c?`<system-reminder>\n${c}\n</system-reminder>\n${e}`:e,u=fe(l),d=i?.ephemeralSystemContext,f=[u,...d?.trim()?[ue(d)]:[]];n.contextTracker.updateFromHistory(n.agent.getHistory()),n.contextTracker.shouldAutoCompact([...n.agent.getHistory(),...f])&&(i?.executionJournal?await n.compact(r,o,i.executionJournal):await(o?n.compact(r,o):n.compact(r))),n.clearSessionStartStdout();let p=n.agent.getHistory(),m=JSON.stringify(p),h=ve(n.aiProvider);n.log(`pre_run`,{historyLength:p.length,historyChars:m.length,historyEstTokens:Math.ceil(m.length/v),input:l,history:p,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:h.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:h.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:h.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:h.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...p,...f]),n.onContextUpdate?.(n.contextTracker.getContextState());let g;try{if(g=await n.agent.run(l,{signal:r,maxExecutionRounds:n.maxTurns??0,...vi(i),...mi(n,a)}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof S)throw e;try{n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.agent.getHistory().length})}catch{}throw w(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>yi.warn(`hook failed`,{error:e})),e}let _=n.agent.getHistory(),y=_.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:g,historyLength:_.length,estimatedChars:JSON.stringify(_).length,history:_,historyStructure:y}),n.contextTracker.updateFromHistory(_);let b=n.contextTracker.getContextState();return n.onContextUpdate?.(b),n.log(`context`,{maxTokens:b.maxTokens,usedTokens:b.usedTokens,usedPercentage:b.usedPercentage,remainingPercentage:b.remainingPercentage}),w(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:g.substring(0,500),last_assistant_message:g,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>yi.warn(`hook failed`,{error:e})),g}function xi(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function Si(e){let t=e.findLastIndex(e=>e.role===`assistant`),n=e[t];if(n?.role!==`assistant`)return;let r=new Set(e.slice(t+1).flatMap(e=>e.role===`tool`?[e.toolCallId]:[]));return{assistant:n,open:(n.toolCalls??[]).filter(e=>!r.has(e.id)),ending:e.slice(t+1).every(e=>e.role===`tool`)}}function Ci(e,t,n){let r=Si(e),i=r?.assistant.metadata?.executionId;if(!r?.ending||!r.open.length||typeof i!=`string`)return;let a=new Set(r.open.map(e=>e.id)),o=t?.executionId===i?t.requests.filter(e=>a.has(e.toolCallId)&&!n.has(e.actionId)):[];return{executionId:i,requests:structuredClone(o)}}function wi(e,t,n){return{read:t=>e.read(t),append:r=>(r.kind===`tool-effect-start`&&(t.add(r.actionId),n?.()),e.append(r))}}function Ti(e,t,n){let r=Si(e);if(!r||r.assistant.metadata?.executionId!==t.executionId)return[];let i=new Set((n?t.requests:[]).map(e=>e.toolCallId));return r.open.map(e=>{let t=i.has(e.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return de(`Error: ${t}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:t,toolName:e.function.name}})})}async function Ei(e,t){if(!t||typeof t.append!=`function`||typeof t.read!=`function`)throw new x(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof S)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var Di=class{agent;claim;sessionId;ask;execution=null;constructor(e,t,n,r){this.agent=e,this.claim=t,this.sessionId=n,this.ask=r}async invoke(e,t,n){let r=this.claim.claim(),i=Oi(r,n?.signal);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??Ge(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(r.signal)}:{}}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}askUnder(e){let t=this.ask;if(t===void 0)throw Error(`No ask port`);return(n,r)=>t(n,{signal:r?.signal??e})}async drain(){await this.execution}};function Oi(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var ki=class extends Xn{agent;eventService=new ee;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;checkpointHistoryCallback;hooks;hookTypeExecutors;onTextDeltaCallback;onThinkingDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;recoveryState={kind:`ready`};checkpointing=!1;get pendingExecution(){return this.recoveryState.kind===`ready`?void 0:this.recoveryState.pending}setPending(e,t=!1){this.recoveryState.kind!==`save-required`&&(this.recoveryState=e?{kind:`pending`,pending:e,liveWaits:t}:{kind:`ready`})}shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onThinkingDeltaCallback=e.onThinkingDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??Zr(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?ae[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,ti(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=Vr(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Hr(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=Ur(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new Di(this.agent,this.turnClaim,this.sessionId,e.ask),ni(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){return this.runTurn(e,t,n,!1)}runRecoverable(e,t,n){return Ei(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,t,n,r){let i=n?{...n}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let a=this.turnClaim.claim(),o=Oi(a,i?.signal),{signal:s}=a;this.permissionEnforcer.beginTurn(i?.peerTurn===!0,r);try{s.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let n=i?.executionJournal?{...i,executionJournal:gi(i.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:i.peerTurn===!0})}:i,r=await bi(e,t,this.buildRunContext(i?.executionJournal!==void 0),s,n);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof S?(this.setPending(xi(e),!0),s.throwIfAborted()):i?.executionJournal&&this.setPending(Ci(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),o(),this.turnClaim.release(a)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return Ei(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,t){let n={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==n.executionId)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim(),i=Oi(r,n.signal),a=new Set;try{r.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=_i(wi(n.journal,a,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,t)),i=await hi(this.buildRunContext(!0),{...n,journal:e,signal:r.signal});return this.setPending(void 0),this.commitConversation(n.executionId),i}catch(e){throw e instanceof S?(this.setPending(xi(e),!0),r.signal.throwIfAborted()):this.setPending(Ci(this.agent.getHistory(),this.pendingExecution,a)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(e){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.recoveryState.kind===`save-required`){if(this.recoveryState.executionId!==e||this.pendingExecution)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let t=this.pendingExecution;if(!t)return;if(t.executionId!==e)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let n=this.turnClaim.claim();try{let n=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of Ti(this.agent.getHistory(),t,n))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(n)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new x(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`)}assertCheckpointSettled(){if(this.checkpointing||this.recoveryState.kind===`save-required`)throw new x(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:m(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(e){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(e.id!==this.sessionId||m(e.cwd)!==m(this.cwd))throw new x(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let t=Vn({id:e.id,cwd:e.cwd,messages:e.messages,...e.pendingExecution===void 0?{}:{pendingExecution:e.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(t.status!==`valid`)throw new x(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let n=structuredClone(t.record);this.agent.clearHistory();for(let e of n.messages)this.agent.injectRawMessage(e);this.setPending(n.pendingExecution),this.syncContextFromHistory()}checkpoint(){if(this.turnClaim.isRunning()||this.checkpointing)throw Error(`Cannot checkpoint during a Session transition`);if(!this.checkpointHistoryCallback&&!this.sessionStore)throw Error(`Session checkpoint requires a persistence sink`);this.commitConversation(this.recoveryState.kind===`save-required`?this.recoveryState.executionId:void 0)}commitConversation(e){if(!this.checkpointHistoryCallback&&!this.sessionStore)return;if(this.checkpointing)throw Error(`Reentrant Session checkpoint`);let t=this.pendingExecution,n=this.recoveryState.kind!==`ready`&&this.recoveryState.liveWaits;this.checkpointing=!0;try{this.checkpointHistoryCallback?Kn(this.checkpointHistoryCallback()):this.persistSessionInternal(!0),this.recoveryState=t?{kind:`pending`,pending:t,liveWaits:n}:{kind:`ready`}}catch(r){throw this.recoveryState={kind:`save-required`,pending:t,liveWaits:n,executionId:e??t?.executionId},r}finally{this.checkpointing=!1}}saveAfterFailure(e){if(this.recoveryState.kind!==`save-required`)try{this.commitConversation()}catch(t){if(e instanceof S)throw t;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${t instanceof Error?t.message:String(t)}`,stack:t instanceof Error?t.stack??``:``,historyLength:this.agent.getHistory().length})}catch{}}}addTools(e){return this.assertInputAllowed(),this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.assertInputAllowed(),this.runtimeTools.invoke(e,t,n)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(e=!1){if(!this.sessionStore)return;let t=Yr({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,conversation:this.getConversationSnapshot(),getFullHistory:()=>this.getFullHistory()});if(e&&t.status!==`valid`)throw Error(`Session history could not be durably checkpointed: ${t.status}`)}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>ri(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.agent.destroy()})})(),this.shutdownPromise}swapProvider(e,t,n){this.assertInputAllowed(),this.agent.swapDefaultProvider(e,t,n),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e,this.setActiveModel(t)}async compact(e,t=`manual`,n,r){this.assertInputAllowed();let i=this.turnClaim.claim(),a=Oi(i,n);try{await this.compactWith(e,t,i.signal,void 0,r)}finally{a(),this.turnClaim.release(i)}}async compactWith(e,t,n,r,i){let a={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{},...i?{executionJournal:i}:{}};await Jr(e,qr(this.buildRunContext(),a),n)}buildRunContext(e=!1){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,effort:this.getModelEffort(),agent:this.agent,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:(e,t,n)=>this.compactWith(void 0,`auto`,e,t,n),persistSession:()=>this.persistSessionInternal(),checkpointHistory:this.checkpointHistoryCallback||this.sessionStore?()=>{e&&this.setPending(Ci(this.agent.getHistory(),this.pendingExecution,new Set)),this.commitConversation()}:void 0,getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onThinkingDelta:this.onThinkingDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(te.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(ne.SWITCHED,{timestamp:new Date,fromProvider:e.from.provider,fromModel:e.from.model,toProvider:e.to.provider,toModel:e.to.model,reason:e.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};function Ai(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function ji(e,t={}){let n={schemaVersion:2,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function Mi(e){let t=Wn(Ai(e));if(t.status===`unsupported`)throw Error(`Unsupported session artifact schema version ${t.schemaVersion??`(absent or not a number)`} (this build reads 2).`);if(t.status===`corrupt`){let e=t.issues.slice(0,5),n=e.map(e=>`${e.path===``?`(root)`:e.path}: ${e.message}`).join(`; `),r=t.issues.length>e.length?` (+${t.issues.length-e.length} more)`:``;throw Error(`Invalid session artifact: ${n}${r}`)}return t.record}const Ni=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Pi(e){return Ni.test(e)}function Fi(e,t,n){if(e!==void 0&&Pi(e))return n;if(Array.isArray(t))return t.map(e=>Fi(void 0,e,n));if(typeof t==`object`&&t&&!(t instanceof Date)){let e=t,r={};for(let[t,i]of Object.entries(e))r[t]=Fi(t,i,n);return r}return t}function Ii(e,t=`[REDACTED]`){return Fi(void 0,e,t)}const Li=1,Ri={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,sessionShutdownStepError:`session_shutdown_step_error`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerStreamRawDelta:`provider_stream_raw_delta`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,structuredOutputTransport:`structured_output_transport`,providerFallback:`provider_fallback`,assistantMessageCommitted:`assistant_message_committed`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,toolBatchStarted:`tool_batch_started`,toolMessageCommitted:`tool_message_committed`,backgroundTaskEvent:`background_task_event`,backgroundJobGroupEvent:`background_job_group_event`,memoryEvent:`memory_event`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function zi(e,t){return e.event===t}function Bi(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=Vi(e,a,o,n,r);return i}function Vi(e,t,n,r,i){if(Pi(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return Hi(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return Hi(e,n.map(n=>Vi(e,t,n,r,i)),r,i);if(typeof n==`object`){let t=n,a={};for(let[n,o]of Object.entries(t))a[n]=Vi(e,n,o,r,i);return Hi(e,a,r,i)}return String(n)}function Hi(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=Ue(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const Ui=C(`FileSessionLogger`),Wi=new Set([`text_delta`]),Gi=new Set;let Ki=!1;function qi(e){Gi.add(e),!Ki&&(typeof process>`u`||typeof process.on!=`function`||(Ki=!0,process.on(`exit`,()=>{for(let e of Gi)e.flush()})))}var Ji=class{sink;options;pending=new Map;pendingBytes=0;constructor(e,t={}){this.sink=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`}}log(e,t,n){if(Qr(e))try{let r=Bi(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
7
+ `),l=c?`<system-reminder>\n${c}\n</system-reminder>\n${e}`:e,u=fe(l),d=i?.ephemeralSystemContext,f=[u,...d?.trim()?[ue(d)]:[]];n.contextTracker.updateFromHistory(n.agent.getHistory()),n.contextTracker.shouldAutoCompact([...n.agent.getHistory(),...f])&&(i?.executionJournal?await n.compact(r,o,i.executionJournal):await(o?n.compact(r,o):n.compact(r))),n.clearSessionStartStdout();let p=n.agent.getHistory(),m=JSON.stringify(p),h=ve(n.aiProvider);n.log(`pre_run`,{historyLength:p.length,historyChars:m.length,historyEstTokens:Math.ceil(m.length/v),input:l,history:p,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:h.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:h.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:h.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:h.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...p,...f]),n.onContextUpdate?.(n.contextTracker.getContextState());let g;try{if(g=await n.agent.run(l,{signal:r,maxExecutionRounds:n.maxTurns??0,...vi(i),...mi(n,a)}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof S)throw e;try{n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.agent.getHistory().length})}catch{}throw w(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>yi.warn(`hook failed`,{error:e})),e}let _=n.agent.getHistory(),y=_.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:g,historyLength:_.length,estimatedChars:JSON.stringify(_).length,history:_,historyStructure:y}),n.contextTracker.updateFromHistory(_);let b=n.contextTracker.getContextState();return n.onContextUpdate?.(b),n.log(`context`,{maxTokens:b.maxTokens,usedTokens:b.usedTokens,usedPercentage:b.usedPercentage,remainingPercentage:b.remainingPercentage}),w(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:g.substring(0,500),last_assistant_message:g,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>yi.warn(`hook failed`,{error:e})),g}function xi(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function Si(e){let t=e.findLastIndex(e=>e.role===`assistant`),n=e[t];if(n?.role!==`assistant`)return;let r=new Set(e.slice(t+1).flatMap(e=>e.role===`tool`?[e.toolCallId]:[]));return{assistant:n,open:(n.toolCalls??[]).filter(e=>!r.has(e.id)),ending:e.slice(t+1).every(e=>e.role===`tool`)}}function Ci(e,t,n){let r=Si(e),i=r?.assistant.metadata?.executionId;if(!r?.ending||!r.open.length||typeof i!=`string`)return;let a=new Set(r.open.map(e=>e.id)),o=t?.executionId===i?t.requests.filter(e=>a.has(e.toolCallId)&&!n.has(e.actionId)):[];return{executionId:i,requests:structuredClone(o)}}function wi(e,t,n){return{read:t=>e.read(t),append:r=>(r.kind===`tool-effect-start`&&(t.add(r.actionId),n?.()),e.append(r))}}function Ti(e,t,n){let r=Si(e);if(!r||r.assistant.metadata?.executionId!==t.executionId)return[];let i=new Set((n?t.requests:[]).map(e=>e.toolCallId));return r.open.map(e=>{let t=i.has(e.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return de(`Error: ${t}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:t,toolName:e.function.name}})})}async function Ei(e,t){if(!t||typeof t.append!=`function`||typeof t.read!=`function`)throw new x(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof S)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var Di=class{agent;claim;sessionId;ask;execution=null;constructor(e,t,n,r){this.agent=e,this.claim=t,this.sessionId=n,this.ask=r}async invoke(e,t,n){let r=this.claim.claim(),i=Oi(r,n?.signal);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??Ge(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(r.signal)}:{}}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}askUnder(e){let t=this.ask;if(t===void 0)throw Error(`No ask port`);return(n,r)=>t(n,{signal:r?.signal??e})}async drain(){await this.execution}};function Oi(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var ki=class extends Xn{agent;eventService=new ee;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;checkpointHistoryCallback;hooks;hookTypeExecutors;onTextDeltaCallback;onThinkingDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;recoveryState={kind:`ready`};checkpointing=!1;get pendingExecution(){return this.recoveryState.kind===`ready`?void 0:this.recoveryState.pending}setPending(e,t=!1){this.recoveryState.kind!==`save-required`&&(this.recoveryState=e?{kind:`pending`,pending:e,liveWaits:t}:{kind:`ready`})}shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onThinkingDeltaCallback=e.onThinkingDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??Zr(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?ae[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,ti(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=Vr(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Hr(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=Ur(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new Di(this.agent,this.turnClaim,this.sessionId,e.ask),ni(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){return this.runTurn(e,t,n,!1)}runRecoverable(e,t,n){return Ei(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,t,n,r){let i=n?{...n}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let a=this.turnClaim.claim(),o=Oi(a,i?.signal),{signal:s}=a;this.permissionEnforcer.beginTurn(i?.peerTurn===!0,r);try{s.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let n=i?.executionJournal?{...i,executionJournal:gi(i.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:i.peerTurn===!0})}:i,r=await bi(e,t,this.buildRunContext(i?.executionJournal!==void 0),s,n);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof S?(this.setPending(xi(e),!0),s.throwIfAborted()):i?.executionJournal&&this.setPending(Ci(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),o(),this.turnClaim.release(a)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return Ei(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,t){let n={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==n.executionId)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim(),i=Oi(r,n.signal),a=new Set;try{r.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=_i(wi(n.journal,a,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,t)),i=await hi(this.buildRunContext(!0),{...n,journal:e,signal:r.signal});return this.setPending(void 0),this.commitConversation(n.executionId),i}catch(e){throw e instanceof S?(this.setPending(xi(e),!0),r.signal.throwIfAborted()):this.setPending(Ci(this.agent.getHistory(),this.pendingExecution,a)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(e){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.recoveryState.kind===`save-required`){if(this.recoveryState.executionId!==e||this.pendingExecution)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let t=this.pendingExecution;if(!t)return;if(t.executionId!==e)throw new x(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let n=this.turnClaim.claim();try{let n=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of Ti(this.agent.getHistory(),t,n))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(n)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new x(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`)}assertCheckpointSettled(){if(this.checkpointing||this.recoveryState.kind===`save-required`)throw new x(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:m(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(e){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(e.id!==this.sessionId||m(e.cwd)!==m(this.cwd))throw new x(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let t=Vn({id:e.id,cwd:e.cwd,messages:e.messages,...e.pendingExecution===void 0?{}:{pendingExecution:e.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(t.status!==`valid`)throw new x(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let n=structuredClone(t.record);this.agent.clearHistory();for(let e of n.messages)this.agent.injectRawMessage(e);this.setPending(n.pendingExecution),this.syncContextFromHistory()}checkpoint(){if(this.turnClaim.isRunning()||this.checkpointing)throw Error(`Cannot checkpoint during a Session transition`);if(!this.checkpointHistoryCallback&&!this.sessionStore)throw Error(`Session checkpoint requires a persistence sink`);this.commitConversation(this.recoveryState.kind===`save-required`?this.recoveryState.executionId:void 0)}commitConversation(e){if(!this.checkpointHistoryCallback&&!this.sessionStore)return;if(this.checkpointing)throw Error(`Reentrant Session checkpoint`);let t=this.pendingExecution,n=this.recoveryState.kind!==`ready`&&this.recoveryState.liveWaits;this.checkpointing=!0;try{this.checkpointHistoryCallback?Kn(this.checkpointHistoryCallback()):this.persistSessionInternal(!0),this.recoveryState=t?{kind:`pending`,pending:t,liveWaits:n}:{kind:`ready`}}catch(r){throw this.recoveryState={kind:`save-required`,pending:t,liveWaits:n,executionId:e??t?.executionId},r}finally{this.checkpointing=!1}}saveAfterFailure(e){if(this.recoveryState.kind!==`save-required`)try{this.commitConversation()}catch(t){if(e instanceof S)throw t;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${t instanceof Error?t.message:String(t)}`,stack:t instanceof Error?t.stack??``:``,historyLength:this.agent.getHistory().length})}catch{}}}addTools(e){return this.assertInputAllowed(),this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.assertInputAllowed(),this.runtimeTools.invoke(e,t,n)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(e=!1){if(!this.sessionStore)return;let t=Yr({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,conversation:this.getConversationSnapshot(),getFullHistory:()=>this.getFullHistory()});if(e&&t.status!==`valid`)throw Error(`Session history could not be durably checkpointed: ${t.status}`)}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>ri(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.agent.destroy()})})(),this.shutdownPromise}swapProvider(e,t,n){this.assertInputAllowed(),this.agent.swapDefaultProvider(e,t,n),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e,this.setActiveModel(t)}async compact(e,t=`manual`,n,r){this.assertInputAllowed();let i=this.turnClaim.claim(),a=Oi(i,n);try{await this.compactWith(e,t,i.signal,void 0,r)}finally{a(),this.turnClaim.release(i)}}async compactWith(e,t,n,r,i){let a={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{},...i?{executionJournal:i}:{}};await Jr(e,qr(this.buildRunContext(),a),n)}buildRunContext(e=!1){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,effort:this.getModelEffort(),agent:this.agent,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:(e,t,n)=>this.compactWith(void 0,`auto`,e,t,n),persistSession:()=>this.persistSessionInternal(),checkpointHistory:this.checkpointHistoryCallback||this.sessionStore?()=>{e&&this.setPending(Ci(this.agent.getHistory(),this.pendingExecution,new Set)),this.commitConversation()}:void 0,getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onThinkingDelta:this.onThinkingDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(te.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(ne.SWITCHED,{timestamp:new Date,fromProvider:e.from.provider,fromModel:e.from.model,toProvider:e.to.provider,toModel:e.to.model,reason:e.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};function Ai(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function ji(e,t={}){let n={schemaVersion:2,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function Mi(e){let t=Wn(Ai(e));if(t.status===`unsupported`)throw Error(`Unsupported session artifact schema version ${t.schemaVersion??`(absent or not a number)`} (this build reads 2).`);if(t.status===`corrupt`){let e=t.issues.slice(0,5),n=e.map(e=>`${e.path===``?`(root)`:e.path}: ${e.message}`).join(`; `),r=t.issues.length>e.length?` (+${t.issues.length-e.length} more)`:``;throw Error(`Invalid session artifact: ${n}${r}`)}return t.record}const Ni=/^(api[-_]?key|authorization|auth[-_]?token|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Pi(e){return Ni.test(e)}function Fi(e,t,n){if(e!==void 0&&Pi(e))return n;if(Array.isArray(t))return t.map(e=>Fi(void 0,e,n));if(typeof t==`object`&&t&&!(t instanceof Date)){let e=t,r={};for(let[t,i]of Object.entries(e))r[t]=Fi(t,i,n);return r}return t}function Ii(e,t=`[REDACTED]`){return Fi(void 0,e,t)}const Li=1,Ri={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,sessionShutdownStepError:`session_shutdown_step_error`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerStreamRawDelta:`provider_stream_raw_delta`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,structuredOutputTransport:`structured_output_transport`,providerFallback:`provider_fallback`,assistantMessageCommitted:`assistant_message_committed`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,toolBatchStarted:`tool_batch_started`,toolMessageCommitted:`tool_message_committed`,backgroundTaskEvent:`background_task_event`,backgroundJobGroupEvent:`background_job_group_event`,memoryEvent:`memory_event`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function zi(e,t){return e.event===t}function Bi(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=Vi(e,a,o,n,r);return i}function Vi(e,t,n,r,i){if(Pi(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return Hi(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return Hi(e,n.map(n=>Vi(e,t,n,r,i)),r,i);if(typeof n==`object`){let t=n,a={};for(let[n,o]of Object.entries(t))a[n]=Vi(e,n,o,r,i);return Hi(e,a,r,i)}return String(n)}function Hi(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=Ue(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const Ui=C(`FileSessionLogger`),Wi=new Set([`text_delta`]),Gi=new Set;let Ki=!1;function qi(e){Gi.add(e),!Ki&&(typeof process>`u`||typeof process.on!=`function`||(Ki=!0,process.on(`exit`,()=>{for(let e of Gi)e.flush()})))}var Ji=class{sink;options;pending=new Map;pendingBytes=0;constructor(e,t={}){this.sink=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`}}log(e,t,n){if(Qr(e))try{let r=Bi(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
8
8
  `;if(Wi.has(t)){this.buffer(e,i);return}this.flush(),this.write(e,i)}catch(n){this.report(e,t,n)}}flush(){if(this.pending.size===0){Gi.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,Gi.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){qi(this);let n=this.pending.get(e)??[];n.push(t),this.pending.set(e,n),this.pendingBytes+=t.length,this.pendingBytes>=65536&&this.flush()}write(e,t){this.sink.append(e,t)}report(e,t,n){Ui.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},Yi=class{log(){}};const Xi=C(`NodeSessionLogSink`),Zi=/^[0-9a-f]{64}$/;function Qi(e,t){let n=Ue(`sha256`).update(t).digest(`hex`);if(!Zi.test(e)||e!==n)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function $i(e,t,n){return $r(e),Qi(t,n),{kind:`external-payload`,encoding:`json`,sha256:t,byteLength:Buffer.byteLength(n),relativePath:T(`${e}.payloads`,`${t}.json`)}}var ea=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{Ye(e),this.enabled=!0}catch(t){this.enabled=!1,Xi.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(t,n){if($r(t),!this.enabled)return;let r=T(this.logDirectory,`${t}.jsonl`);Xe(r),e(r,n,{mode:Je})}writeJson(e,t,n){let r=$i(e,t,n),i=`${e}.payloads`;if(this.enabled){Ye(T(this.logDirectory,i));let e=T(this.logDirectory,r.relativePath);try{_(e,n,{encoding:`utf8`,mode:Je,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;Xe(e)}}return r}};const J=e=>({decode:e}),Y=e=>({decode:e,optional:!0}),ta=(e,t,n)=>L(e,t,n,j),na=(e,t,n)=>L(e,t,n,H),ra=(e,t,n)=>L(e,t,n,Ln),ia=(e,t,n)=>typeof e==`string`?e:H(e,t,n),X=(e,t,n)=>{let r=N(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function aa(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function oa(e,t,n){if(!aa(e)){n.push({path:t,message:`expected an object, received ${O(e)}`});return}for(let[r,i]of Object.entries(e))Z(i,E(t,r),n);return e}const sa=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function ca(e,t,n){let r=R(e,t,n,sa);if(r===void 0)return;let i=M(r.maxTokens,E(t,`maxTokens`),n),a=M(r.usedTokens,E(t,`usedTokens`),n),o=M(r.usedPercentage,E(t,`usedPercentage`),n),s=M(r.remainingPercentage,E(t,`remainingPercentage`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{maxTokens:i,usedTokens:a,usedPercentage:o,remainingPercentage:s}}const la=(e,t,n)=>L(e,t,n,(e,t,n)=>{let r=R(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=j(r.type,E(t,`type`),n),a=j(r.id,E(t,`id`),n);return i===void 0||a===void 0?void 0:{type:i,id:a}});function Z(e,t,n,r=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||e instanceof Date){n.push({path:t,message:`expected a JSON-compatible value, received ${O(e)}`});return}if(!Array.isArray(e)&&!aa(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${O(e)}`});return}if(r.has(e)){n.push({path:t,message:`expected an acyclic JSON-compatible value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Z(e[i],ot(t,i),n,r);else for(let[i,a]of Object.entries(e))Z(a,E(t,i),n,r);return r.delete(e),e}function ua(e,t,n,r=new WeakSet){if(!(typeof e!=`object`||!e||e instanceof Date)){if(r.has(e)){n.push({path:t,message:`expected an acyclic value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Object.hasOwn(e,i)?ua(e[i],ot(t,i),n,r):n.push({path:ot(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))ua(a,E(t,i),n,r);r.delete(e)}}const da=(...e)=>(t,n,r)=>F(t,e,n,r),fa={session_init:{cwd:J(j),systemPromptLength:J(X),systemPrompt:J(j),toolSchemas:J(ra),model:J(j),provider:J(j)},session_shutdown:{reason:J(j)},session_shutdown_step_error:{step:J(j),error:J(j)},context:{maxTokens:J(M),usedTokens:J(M),usedPercentage:J(M),remainingPercentage:J(M)},context_compact:{trigger:J(j),before:J(ca),after:J(ca)},error:{message:J(j),stack:J(j),historyLength:J(X)},history_mutation:{executionId:Y(j),conversationId:Y(j),round:Y(X),batchId:Y(j),usageObservationId:Y(j),providerId:Y(j),modelId:Y(j),providerError:Y(P),contextOverflow:Y(P),mutation:J(da(`append_message`)),index:J(X),message:J(H)},provider_request:{executionId:J(j),conversationId:Y(j),round:J(X),provider:J(j),model:J(j),effort:Y(j),forcedSummary:Y(P),messages:J(na),tools:Y(ra)},provider_native_raw_payload:{executionId:J(j),conversationId:Y(j),round:J(X),provider:J(j),apiSurface:Y(j),payloadKind:J(da(`request`,`response`,`stream_event`)),sequence:J(X),payload:Y(Z),metadata:Y(oa)},provider_stream_raw_delta:{executionId:J(j),conversationId:Y(j),round:J(X),sequence:J(X),delta:J(j)},provider_response_raw:{executionId:J(j),conversationId:Y(j),round:J(X),effort:Y(j),response:J(H),responseKind:J(j)},provider_response_normalized:{executionId:J(j),conversationId:Y(j),round:J(X),response:J(H),toolCallsCount:Y(X)},structured_output_transport:{executionId:J(j),conversationId:Y(j),round:J(X),provider:J(j),model:J(j),mechanism:J(da(`response_schema`,`json_object`,`none`)),provenance:J(da(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:J(P),schemaInPrompt:J(P),reason:Y(j)},provider_fallback:{executionId:J(j),conversationId:Y(j),round:J(X),fromProvider:J(j),fromModel:J(j),toProvider:J(j),toModel:J(j),reason:J(j)},assistant_message_committed:{executionId:J(j),conversationId:Y(j),round:J(X),message:J(ia)},tool_execution_request:{executionId:J(j),conversationId:Y(j),round:J(X),batchId:Y(j),index:Y(X),toolName:J(j),toolCallId:J(j),parameters:J(oa),ownerPath:Y(la)},tool_execution_result:{executionId:J(j),conversationId:Y(j),round:J(X),batchId:Y(j),index:Y(X),toolName:Y(j),toolCallId:Y(j),success:J(P),result:Y(Z),error:Y(j),metadata:Y(oa)},tool_batch_started:{executionId:J(j),conversationId:Y(j),round:J(X),batchId:Y(j),mode:J(da(`parallel`,`sequential`)),maxConcurrency:J(X),requestCount:J(X),tools:J(ta)},tool_message_committed:{executionId:J(j),conversationId:Y(j),round:J(X),batchId:Y(j),index:Y(X),message:J(H)},background_task_event:{backgroundEventType:Y(j),backgroundEvent:Y(on),data:Y(on),taskId:Y(j),originToolCallId:Y(j)},background_job_group_event:{backgroundJobGroupEvent:Y(Ut),data:Y(Ut)},memory_event:{memoryEvent:Y(gn),data:Y(gn)},user:{content:J(j)},pre_run:{historyLength:J(X),historyChars:J(X),historyEstTokens:J(X),input:J(j),history:J(na),model:J(j),provider:J(j),maxTokens:J(M),nativeWebSearchSupported:J(P),nativeWebSearchEnabled:J(P),nativeWebFetchSupported:J(P),nativeWebFetchEnabled:J(P)},text_delta:{delta:J(j)},assistant:{content:J(j),historyLength:J(X),estimatedChars:J(X),history:J(na),historyStructure:J((e,t,n)=>L(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${O(e)}`});return}let r=e;F(r.role,[`user`,`assistant`,`system`,`tool`],E(t,`role`),n),X(r.contentLength,E(t,`contentLength`),n),P(r.hasToolCalls,E(t,`hasToolCalls`),n),ta(r.toolCallNames,E(t,`toolCallNames`),n),r.metadata!==void 0&&oa(r.metadata,E(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:E(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:J(j),args:J(oa)},tool_result:{tool:J(j),success:J(P),dataChars:J(X),truncated:J(P)},tool_blocked:{tool:J(j),reason:J(j)},tool_denied:{tool:J(j),reason:J(j)},server_tool:{tool:J(j)}};var pa=class extends Error{code;issues;schemaVersion;constructor(e,t,n={}){super(`Session log decode failed: ${e}${t[0]?` at ${t[0].path}: ${t[0].message}`:``}`,{cause:n.cause}),this.name=`SessionLogDecodeError`,this.code=e,this.issues=t,n.schemaVersion!==void 0&&(this.schemaVersion=n.schemaVersion)}};const ma=new Set(Object.values(Ri));function ha(e,t={}){if(!Array.isArray(e))throw new pa(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${O(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=ga(o,t.lineNumbers?.[a]===void 0?`[${a}]`:`line ${t.lineNumbers[a]}`,n);e.entry!==void 0&&r.push(e.entry),i??=e.unsupported}if(n.length>0)throw new pa(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function ga(e,t,n){if(!aa(e))return n.push({path:t,message:`expected an object, received ${O(e)}`}),{};let r=n.length;if(ua(e,t,n),n.length!==r)return{};let i=_a(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(va(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function _a(e,t,n){let r={schemaVersion:1},i;if(e.schemaVersion!==1){let r=e.schemaVersion;typeof r==`number`&&Number.isSafeInteger(r)&&r>=0?(i=r,n.push({path:E(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:E(t,`schemaVersion`),message:`expected schema version 1, received ${O(r)}`})}let a=I(e.timestamp,E(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=j(e.sessionId,E(t,`sessionId`),n);o===``&&n.push({path:E(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!ma.has(s)?(n.push({path:E(t,`event`),message:`expected a declared event name, received ${O(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function va(e,t,n,r,i){let a=fa[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],E(n,t),i);a!==void 0&&(r[t]=a)}for(let o of Object.keys(e)){if([`schemaVersion`,`timestamp`,`sessionId`,`event`,...Object.keys(a)].includes(o))continue;if(t!==`server_tool`){i.push({path:E(n,o),message:`unknown event payload field`});continue}let s=Z(e[o],E(n,o),i);s!==void 0&&(r[o]=s)}ya(e,t,n,i)}function ya(e,t,n,r){t===`background_task_event`&&e.backgroundEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background task event payload`}),t===`background_job_group_event`&&e.backgroundJobGroupEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background job group event payload`}),t===`memory_event`&&e.memoryEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a memory event payload`})}var Q=class extends Error{code;metadata;constructor(e,t,n={},r){super(t,r===void 0?void 0:{cause:r}),this.name=`SessionLogPayloadResolutionError`,this.code=e,this.metadata=n}};function ba(e){if(e.trim().length===0||e.includes(`\0`)||ze(e)||He.isAbsolute(e))throw Sa(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Sa(e);return t}function xa(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new Q(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function Sa(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Ca(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Sa(t,e):e.code===`UNSUPPORTED_BACKEND`?new Q(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}var wa=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=Ve(e)}readBytes(e,t){xa(t);let n=ba(e);try{let e=$e(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof Qe?Ca(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Ta=class{logFile;externalPayloadSource;constructor(e){if(this.logFile=e,e.trim().length===0)throw Error(`Session log-file path must not be empty.`);this.externalPayloadSource=new wa(Re(e))}readText(){return i(this.logFile)?d(this.logFile,`utf8`):void 0}};const Ea=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Da=8*1024*1024,Oa=r.O_WRONLY|r.O_CREAT|r.O_EXCL|(r.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},ka=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let n=e.parentDirectory??qe();if(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new $(`invalid-options`);try{let e=c(n);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=l(T(n,`agent-tool-results-`)),process.platform!==`win32`&&t(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=c(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new $(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new $(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>Da)throw new $(`write-failed`);let t=We(18).toString(`base64url`),r=`${We(18).toString(`base64url`)}.partial`,i=`${t}.txt`,a=T(this.directory,r),c=T(this.directory,i),l,d=!1;try{l=u(a,Oa,384),_(l,e,`utf8`),o(l),n(l),l=void 0,s(a,c),d=!0,g(a);let r=`tool-result:${t}`;return this.entries.set(r,{fileName:i,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:r}}catch{let e=!1;if(l!==void 0)try{n(l)}catch{e=!0}try{g(a)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(d)try{g(c)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!Ea.test(e))throw new $(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new $(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new $(`expired`);this.assertRoot();try{let e=new wa(this.directory).readBytes(t.fileName,Da);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,t){this.assertRoot();try{g(T(this.directory,t.fileName)),this.entries.delete(e)}catch{throw new $(`cleanup-failed`)}}async cleanupExpired(){if(this.closed)throw new $(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(p(this.directory).length!==0)throw Error(`unexpected files`);h(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};const Aa=64*1024;function ja(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function Ma(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(ja(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Na(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=Ma(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function Pa(e){return e.code===`ENOENT`}var Fa=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(t){Ye(Re(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),Xe(this.path),e(this.path,`${JSON.stringify(t)}\n`,{mode:Je})}async*read(e){let t;try{t=u(this.path,r.O_RDONLY|(r.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Pa(e))return;throw e}try{let n=a(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let i=Buffer.alloc(e),a=f(t,i,0,e,n),o=Buffer.concat([i.subarray(0,a),r]),s=n===0?-1:o.indexOf(10);r=s===-1&&n>0?o:o.subarray(0,s+1);let c=n===0?o:s===-1?Buffer.alloc(0):o.subarray(s+1);n>0&&s===-1||(yield Na(c.toString(`utf8`).split(`
9
9
  `).reverse()))}}finally{n(t)}}};const Ia=/^[0-9a-f]{64}$/i;function La(e){if(!Ra(e))throw new Q(`INVALID_REFERENCE`,`External payload reference has an invalid shape.`);return{kind:`external-payload`,encoding:`json`,sha256:String(e.sha256).toLowerCase(),byteLength:Number(e.byteLength),relativePath:String(e.relativePath)}}function Ra(e){let t=Object.keys(e).sort(),n=[`byteLength`,`encoding`,`kind`,`relativePath`,`sha256`];return t.length===n.length&&t.every((e,t)=>e===n[t])&&e.kind===`external-payload`&&e.encoding===`json`&&typeof e.sha256==`string`&&Ia.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function za(e,t){return Ha(e,Ba(t),0)}function Ba(e){let t=Va(`maxDepth`,e.maxDepth??32),n=Va(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function Va(e,t){if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw new Q(`INVALID_LIMIT`,`${e} must be a finite, non-negative safe integer.`,{actual:String(t)});return t}function Ha(e,t,n){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`number`)throw Ga(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw Ga(`Unsupported session-log JSON value type: ${typeof e}.`);if(t.activeObjects.has(e))throw new Q(`CIRCULAR_REFERENCE`,`Circular in-memory value encountered while resolving external payloads.`,{depth:n});if(Ka(e))return Ua(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>Ha(e,t,n))}finally{t.activeObjects.delete(e)}}if(!qa(e))throw Ga(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Ha(r,t,n)]))}finally{t.activeObjects.delete(e)}}function Ua(e,t,n){let r=La(e);if(n>=t.maxDepth)throw new Q(`MAX_DEPTH_EXCEEDED`,`External-payload reference depth exceeds the configured maximum of ${t.maxDepth}.`,{relativePath:r.relativePath,depth:n});if(t.source===void 0)throw new Q(`UNRESOLVED_REFERENCE`,`An external session-log payload requires an explicit payload source.`,{relativePath:r.relativePath,depth:n});if(t.activePayloadPaths.has(r.relativePath))throw new Q(`CIRCULAR_REFERENCE`,`External payload ${r.relativePath} recursively references an active payload.`,{relativePath:r.relativePath,depth:n});let i=Wa(r,t);t.activePayloadPaths.add(r.relativePath);try{return Ha(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function Wa(e,t){let n=t.maxTotalBytes-t.totalBytes,r=t.source?.readBytes(e.relativePath,n);if(r===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let i=t.totalBytes+r.byteLength;if(!Number.isSafeInteger(i)||i>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:i});if(t.totalBytes=i,r.byteLength!==e.byteLength)throw new Q(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:r.byteLength});let a=Ue(`sha256`).update(r).digest(`hex`);if(a!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:a});try{return JSON.parse(Buffer.from(r).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function Ga(e){return new Q(`INVALID_JSON`,e)}function Ka(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function qa(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ja(e){let t=[],n=Ya(),r=Xa();return ha(e).forEach((e,i)=>{io(e,i,t),Qa(e,i,t),Za(n,e,i),$a(r,e,i)}),eo(n,t),to(r,t),{ok:t.length===0,issues:t}}function Ya(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function Xa(){return{requests:new Map,results:new Set}}function Za(e,t,n){let r=no(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&!ao(t.response)&&e.normalizedResponses.add(r.key))}function Qa(e,t,n){ao(e.event===`history_mutation`?e.message:e.event===`provider_response_normalized`?e.response:void 0)&&n.push({code:`UNRESOLVED_REPLAY_PAYLOAD`,message:`Replay substrate ${e.event} contains an unresolved external payload.`,eventIndex:t,executionId:typeof e.executionId==`string`?e.executionId:void 0,round:typeof e.round==`number`?e.round:void 0})}function $a(e,t,n){let r=ro(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function eo(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function to(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function no(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function ro(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function io(e,t,n){if(Array.isArray(e)){e.forEach(e=>io(e,t,n));return}if(oo(e)){if(e.kind===`external-payload`){Ra(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>io(e,t,n))}}function ao(e){return Array.isArray(e)?e.some(e=>ao(e)):oo(e)?e.kind===`external-payload`||Object.values(e).some(e=>ao(e)):!1}function oo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function so(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
10
- `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new pa(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),ha(za(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function co(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of ha(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(Ee(c.message))),lo(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function lo(e,t){if(e.event===`background_task_event`){fo(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){fo(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&fo(t.memoryEvents,e,`memoryEvent`,`data`)}function uo(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function fo(e,t,n,r){let i=uo(t,n)??uo(t,r);i&&e.push(i)}function po(e){return e instanceof Error?e.message:`unknown error`}function mo(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Wn(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}function ho(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var go=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){Ye(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){$r(e);let t=it(this.baseDir),n=it(t,`${e}.json`);if(!n.startsWith(t+at))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Ze(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!et(t))return{status:`missing`};let n;try{n=tt(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${po(e)}`}]}}return mo(n)}list(){return et(this.baseDir)?nt(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(ho):[]}outcomeForListedId(e){return Qr(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);et(t)&&rt(t)}},_o=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};export{ar as AUTO_COMPACT_THRESHOLD,_r as AutoModeGate,mr as CONSECUTIVE_BLOCK_LIMIT,_o as CheckpointTree,nr as CompactionError,ir as CompactionOrchestrator,or as ContextWindowTracker,rr as DEFAULT_COMPACTION_PROMPT,Aa as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,Ji as FileSessionLogger,Bn as INTERACTIVE_SESSION_RECORD_KEYS,wa as NodeExternalPayloadSource,Fa as NodePromptHistoryFile,ea as NodeSessionLogSink,Ta as NodeSessionLogSource,go as NodeSessionStore,ka as NodeToolResultSpillStore,Br as PermissionEnforcer,Ni as SENSITIVE_KEY_PATTERN,Ri as SESSION_LOG_EVENT,Li as SESSION_LOG_SCHEMA_VERSION,zn as SESSION_RECORD_ENVELOPE_VERSION,ki as Session,Jn as SessionBusyError,pa as SessionLogDecodeError,Q as SessionLogPayloadResolutionError,Yi as SilentSessionLogger,hr as TOTAL_BLOCK_LIMIT,$ as ToolResultSpillError,Yn as TurnClaim,$r as assertSafeSessionId,br as consentScopeFor,$i as createSessionLogExternalPayloadReference,Vn as decodeInteractiveSessionRecord,ha as decodeSessionLogEntries,Wn as decodeVersionedInteractiveSessionRecord,Mi as deserializeSessionArtifact,tr as formatConversationEntries,Qr as isSafeSessionId,Pi as isSensitiveKey,zi as isSessionLogEvent,so as loadSessionLogEntries,Ma as parsePromptHistoryLine,co as replaySessionLogEntries,za as resolveSessionLogExternalPayloads,Ii as scrubSensitiveKeys,ji as serializeSessionArtifact,Ja as validateSessionReplayLogEntries};
10
+ `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new pa(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),ha(za(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function co(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of ha(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(Ee(c.message))),lo(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function lo(e,t){if(e.event===`background_task_event`){fo(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){fo(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&fo(t.memoryEvents,e,`memoryEvent`,`data`)}function uo(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function fo(e,t,n,r){let i=uo(t,n)??uo(t,r);i&&e.push(i)}function po(e){return e instanceof Error?e.message:`unknown error`}function mo(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Wn(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}function ho(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var go=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){Ye(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){$r(e);let t=it(this.baseDir),n=it(t,`${e}.json`);if(!n.startsWith(t+at))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Ze(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!et(t))return{status:`missing`};let n;try{n=tt(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${po(e)}`}]}}try{Xe(t)}catch{}return mo(n)}list(){return et(this.baseDir)?nt(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(ho):[]}outcomeForListedId(e){return Qr(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);et(t)&&rt(t)}},_o=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};export{ar as AUTO_COMPACT_THRESHOLD,_r as AutoModeGate,mr as CONSECUTIVE_BLOCK_LIMIT,_o as CheckpointTree,nr as CompactionError,ir as CompactionOrchestrator,or as ContextWindowTracker,rr as DEFAULT_COMPACTION_PROMPT,Aa as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,Ji as FileSessionLogger,Bn as INTERACTIVE_SESSION_RECORD_KEYS,wa as NodeExternalPayloadSource,Fa as NodePromptHistoryFile,ea as NodeSessionLogSink,Ta as NodeSessionLogSource,go as NodeSessionStore,ka as NodeToolResultSpillStore,Br as PermissionEnforcer,Ni as SENSITIVE_KEY_PATTERN,Ri as SESSION_LOG_EVENT,Li as SESSION_LOG_SCHEMA_VERSION,zn as SESSION_RECORD_ENVELOPE_VERSION,ki as Session,Jn as SessionBusyError,pa as SessionLogDecodeError,Q as SessionLogPayloadResolutionError,Yi as SilentSessionLogger,hr as TOTAL_BLOCK_LIMIT,$ as ToolResultSpillError,Yn as TurnClaim,$r as assertSafeSessionId,br as consentScopeFor,$i as createSessionLogExternalPayloadReference,Vn as decodeInteractiveSessionRecord,ha as decodeSessionLogEntries,Wn as decodeVersionedInteractiveSessionRecord,Mi as deserializeSessionArtifact,tr as formatConversationEntries,Qr as isSafeSessionId,Pi as isSensitiveKey,zi as isSessionLogEvent,so as loadSessionLogEntries,Ma as parsePromptHistoryLine,co as replaySessionLogEntries,za as resolveSessionLogExternalPayloads,Ii as scrubSensitiveKeys,ji as serializeSessionArtifact,Ja as validateSessionReplayLogEntries};
11
11
  //# sourceMappingURL=index.js.map