@robota-sdk/agent-session 3.0.4 → 3.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @robota-sdk/agent-session
2
2
 
3
+ ## 3.0.6
4
+ ### Patch Changes
5
+
6
+ - Tighten legacy world-readable session records to owner-only when the session store reads or lists them.
7
+ - Redact `authToken` values from persisted session logs and share artifacts.
8
+ - Updated dependencies [7c4eb0d]
9
+ - @robota-sdk/agent-file-authority@3.0.6
10
+ - @robota-sdk/agent-core@3.0.6
11
+ - @robota-sdk/agent-interface-execution@3.0.6
12
+ - @robota-sdk/agent-interface-session@3.0.6
13
+
14
+ ## 3.0.5
15
+ ### Patch Changes
16
+
17
+ - @robota-sdk/agent-core@3.0.5
18
+ - @robota-sdk/agent-file-authority@3.0.5
19
+ - @robota-sdk/agent-interface-execution@3.0.5
20
+ - @robota-sdk/agent-interface-session@3.0.5
21
+
3
22
  ## 3.0.4
4
23
  ### Patch Changes
5
24
 
@@ -4,7 +4,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
4
4
  `);return[this.basePrompt??zt,r,``,`Conversation:`,i].join(`
5
5
  `)}};const Vt=.835;var Ht=class{contextUsedTokens=0;contextMaxTokens;contextMaxTokensOverride;autoCompactThreshold;constructor(e,n,r){this.contextMaxTokensOverride=n,this.contextMaxTokens=n??(0,t.getModelContextWindow)(e),this.autoCompactThreshold=Ut(r)}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?(0,t.estimateContextTokensFromMessages)(e).usedTokens:this.contextUsedTokens)>=this.contextMaxTokens*this.autoCompactThreshold}setModel(e){this.contextMaxTokens=this.contextMaxTokensOverride??(0,t.getModelContextWindow)(e)}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=Ut(e)}updateFromHistory(e){this.contextUsedTokens=(0,t.estimateContextTokensFromMessages)(e).usedTokens}reset(){this.contextUsedTokens=0}};function Ut(e){if(e===void 0)return Vt;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 Wt(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 Gt(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 Kt(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:Gt(await Wt(i(),e.signal))}const qt=`robota-session/approval`;function Jt(e){return e?.waits.some(e=>e.request.kind===qt)??!1}async function Yt(n,r,i){let a=r?.waits.filter(e=>e.request.kind===qt)??[];if(!i&&!a.length)return;if(!r||r.action.toolName!==n.toolName)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Checkpointed approval requires the current journaled action`);let o=(0,e.realpathSync)(n.cwd);for(let{request:e}of a)if(e.data.version!==1||e.data.sessionId!==n.sessionId||e.data.cwd!==o||e.data.toolName!==n.toolName)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Saved approval belongs to a different Session or tool`);let s=await r.request({kind:qt,data:{version:1,sessionId:n.sessionId,cwd:o,toolName:n.toolName,arguments:structuredClone(n.toolArgs)}});if(Object.keys(s).length!==1||typeof s.approved!=`boolean`)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Approval response must contain only a boolean approved decision`);return s.approved}function Xt(e,t){return`${e}\u0000${JSON.stringify(t)}`}var Zt=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(Xt(e,t))}takeRetry(e,t){return this.retries.delete(Xt(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 Qt(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function $t(e,t){switch(e){case`path`:{let e=Qt(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 en(e,n){let r=(0,t.getToolPermissionProfile)(e).argument;if(r===void 0)return e;let i=n[r.key];if(typeof i!=`string`||i===``)return e;let a=$t(r.kind,i);return a===void 0?e:`${e}(${a})`}function tn(e,r,i){let a=(0,t.getToolPermissionProfile)(e).argument;if(a===void 0||a.kind!==`path`)return r;let o=r[a.key];return typeof o!=`string`||o===``||(0,n.isAbsolute)(o)?r:{...r,[a.key]:(0,n.resolve)(i,o)}}function z(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function nn(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}),z(`threw`,r)}const rn=z(`denied`,`Permission denied. The user did not approve this action.`),an=(0,t.createLogger)(`ToolHookHelpers`);function on(e){if((0,t.wasToolResultAdmitted)(e)||typeof e.data!=`string`||e.data.length<=3e4)return e;let n=15e3,r=e.data.substring(0,n),i=e.data.substring(e.data.length-n),a=`${r}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${n.toLocaleString()} chars ...]\n\n${i}`;return{...e,data:a}}function sn(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 cn(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 ln(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:z(`hook-blocked`,`PreToolUse updatedInput must be an object.`)};let e=tn(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:z(`hook-blocked`,s,{blocked:!0,reason:s})}}async function ln(e,n,r,i){let a=await(0,t.runHooks)(e,`PreToolUse`,n,r,i);if(a.blocked){let e=a.reason??`Blocked by hook`;return{result:z(`hook-blocked`,e,{blocked:!0,reason:e}),hookResult:a}}if((0,t.isEnforcing)(`PreToolUse`)){let e=a.errors,t=e?.[0],n=a.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,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return{result:z(`hook-blocked`,i,{blocked:!0,reason:i}),hookResult:a}}if(r!==``)return{result:z(`hook-blocked`,r,{blocked:!0,reason:r}),hookResult:a}}return{result:null,hookResult:a}}function un(e,n,r,i,a){(0,t.runHooks)(e,`PostToolUse`,{...n,hook_event_name:`PostToolUse`,tool_output:typeof r.data==`string`?r.data:JSON.stringify(r.data)},i,a).catch(e=>an.warn(`hook failed`,{error:e}))}function dn(e,n){let r=(0,t.getToolPermissionProfile)(e).argument?.key;if(r===void 0)return;let i=n[r];if(typeof i==`string`)return i.length>200?`${i.slice(0,200)}…`:i}var fn=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=dn(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 pn=(0,t.createLogger)(`ToolBodyTrace`);var B=class extends Error{result;constructor(e){super(`Effective tool arguments were not authorized`),this.result=e}};function mn(e,n){try{e?.eventService?.emit(t.TOOL_PERMISSION_EVENTS.DECIDED,{timestamp:new Date,executionId:e.executionId,decidedAt:new Date().toISOString(),decision:n})}catch(e){pn.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function hn(e,n){let r=e.execute.bind(e),i=e.executeWithAdmission?.bind(e),a=(0,t.snapshotToolProvenance)(e.provenance),o=e=>{if(e.type!==`end`||!a)return n.onToolExecution?.(e);let r=(0,t.withToolProvenance)({success:e.success??!1,parts:e.toolResultParts},a);n.onToolExecution?.({...e,toolResultParts:r.parts})},s=t.DEFAULT_ABSTRACT_EVENT_SERVICE,c=Object.create(e);Object.defineProperty(c,"provenance",{value:a,enumerable:!0});let l=async(a,c,l)=>{let u=a,d=`(unknown)`;try{d=e.getName(),u=tn(d,a,n.cwd),n.log(`tool_call`,{tool:d,args:u});let f=sn(n.sessionId,n.cwd,d,u,n.getPermissionMode(),n.transcriptPath),p=await cn(n.config.hooks,f,n.hookTypeExecutors,c?.hookTraceEnv);if(p.refusal)return n.log(`tool_blocked`,{tool:d,reason:`hook`}),mn(c,`hook-blocked`),p.refusal;p.parameters!==void 0&&(u=p.parameters,f={...f,tool_input:u});let m=await n.checkPermission(d,u,c?.signal,c?.permissionInteraction,c?.hookTraceEnv,c?.continuation,p.decision,c?.executionId);if(m!==!0)return n.log(`tool_denied`,{tool:d,reason:`permission`}),mn(c,`denied`),o({type:`end`,toolName:d,toolArgs:u,success:!1,denied:!0,executionId:c?.executionId}),typeof m==`object`?z(`denied`,m.message):rn;mn(c,`allowed`),c?.signal?.throwIfAborted(),o({type:`start`,toolName:d,toolArgs:structuredClone(u),executionId:c?.executionId}),c?.signal?.throwIfAborted();let h,g=async e=>{c?.signal?.throwIfAborted();let t=tn(d,e,n.cwd);if(JSON.stringify(t)!==JSON.stringify(e))throw new B(z(`denied`,`Tool admission requires final canonical arguments; relative paths must be resolved before admission.`));if(JSON.stringify(t)!==JSON.stringify(u)){let e=sn(n.sessionId,n.cwd,d,t,n.getPermissionMode(),n.transcriptPath),r=await cn(n.config.hooks,e,n.hookTypeExecutors,c?.hookTraceEnv);if(r.refusal)throw new B(r.refusal);if(r.parameters!==void 0&&JSON.stringify(r.parameters)!==JSON.stringify(t))throw new B(z(`hook-blocked`,`A hook cannot replace arguments already settled by the tool; retry as a new call.`));let i=await n.checkPermission(d,t,c?.signal,c?.permissionInteraction,c?.hookTraceEnv,c?.continuation,r.decision,c?.executionId);if(i!==!0)throw new B(typeof i==`object`?z(`denied`,i.message):rn);f=e}u=structuredClone(e),c?.signal?.throwIfAborted(),await l?.(u),c?.signal?.throwIfAborted(),h=Date.now()},_=`failure`,v;try{let e=c===void 0?void 0:{...c,parameters:u,instanceEventService:s};l&&i?v=await i(u,e,g):(l?await g(u):h=Date.now(),c?.signal?.throwIfAborted(),v=await r(u,e)),_=c?.signal?.aborted?`interrupted`:v.success?`success`:`failure`}catch(e){throw _=c?.signal?.aborted||(0,t.isAbortFailure)(e)?`interrupted`:`failure`,e}finally{try{h!==void 0&&c?.eventService?.emit(t.TOOL_BODY_EVENTS.COMPLETED,{timestamp:new Date,executionId:c.executionId,startedAt:new Date(h).toISOString(),endedAt:new Date(Math.max(Date.now(),h)).toISOString(),outcome:_,toolName:d,...typeof c.toolBodyId==`string`?{toolBodyId:c.toolBodyId}:{}})}catch(e){pn.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let y=on(v);y!==v&&typeof v.data==`string`&&n.terminal.writeLine(` ⚠ Output truncated: ${v.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),o({type:`end`,toolName:d,toolArgs:u,success:y.success,toolResultData:typeof y.data==`string`?y.data:JSON.stringify(y.data),toolResultParts:y.parts,executionId:c?.executionId,...y.view?{view:y.view}:{}});let b=typeof y.data==`string`?y.data.length:JSON.stringify(y.data)?.length??0;return n.log(`tool_result`,{tool:d,success:y.success,dataChars:b,truncated:y!==v}),un(n.config.hooks,f,y,n.hookTypeExecutors,c?.hookTraceEnv),y}catch(e){if((0,t.isExecutionControlError)(e))throw e;return e instanceof B?e.result:nn(e,o,{toolName:d,toolArgs:u,executionId:c?.executionId})}},u=async(...e)=>(0,t.withToolProvenance)(await l(...e),a);return c.execute=u,c.executeWithAdmission=u,c.setEventService=n=>{s=n??t.DEFAULT_ABSTRACT_EVENT_SERVICE,e.setEventService(n)},c}function gn(t){let r=t,i=[];for(;;)try{let t=(0,e.realpathSync)(r);return i.length===0?t:(0,n.resolve)(t,...i.reverse())}catch{let e=(0,n.dirname)(r);if(e===r)return t;i.push(r.slice(e.length).replace(/^[\\/]/,``)),r=e}}function _n(e,t){let r=(0,n.relative)(e,t);return r===``||!r.startsWith(`..`)&&!(0,n.isAbsolute)(r)}function vn(e){return(t,r)=>{let i=gn(e),a=gn((0,n.resolve)(t??i,r));return _n(i,a)?a:void 0}}function yn(e){let n=[...(0,t.findInvalidPermissionPatterns)(e.allow,`allow`),...(0,t.findInvalidPermissionPatterns)(e.restrictive,`deny`)];if(n.length===0)return;let r=n.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${r}. Fix the pattern where it is configured (issue #2428).`)}var bn=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 fn;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]},yn(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??(0,i.homedir)(),this.pathProtection=e.pathProtection,this.resolveInWorkspace=vn(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new Zt(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 n=(0,t.getToolPermissionProfile)(e);return!this.peerTurn&&n.repliesToPeer===!0||this.peerTurn&&n.notInPeerTurn===!0?!1:!(0,t.isToolDeniedOutright)(e,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(e){for(let n of e){let e=n.schema;if(e===void 0)continue;let r=e.parameters?.properties??{};(0,t.registerToolPermissionProfile)(e.name,{parameters:Object.keys(r)})}let n=this.configuredRules();yn(n);for(let{pattern:e,reason:r}of(0,t.findPermissionPatternWarnings)(n.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${e}" ${r}.`)}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=>hn(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 n=(0,t.applyPresetToolLists)(this.presetFreeRules,e);this.config.permissions.allow=n.allow,this.config.permissions.deny=n.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=sn(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath),i=await cn(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 Yt({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a.continuation,!1)??!0):o}async evaluateToolPermission(e,n,r,i=`interactive`,a,o={}){let s=this.permissionPolicy===void 0?void 0:(0,t.projectPermissionPolicy)(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),c=this.getPermissionMode(),l=[...this.config.permissions.allow,...s?.allow??[]],u={allow:c===`auto`?(0,t.allowRulesForAutoMode)(l):l,deny:[...this.config.permissions.deny,...s?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory,pathProtection:this.pathProtection},f=(0,t.evaluatePermission)(e,n,c,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:o.sandboxed!==!1&&this.sandboxAutoApproves(e,n),...s?.ceiling===void 0?{}:{ceiling:s.ceiling},askAll:s?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(e,n,f,a),f===`deny`)return this.denials.record(e,n,`policy`),!1;if(o.hookDecision===`ask`)return this.promptForApproval(e,n,r,i,!0,o);if(f===`auto`)return!0;let p=(0,t.requiresFreshApproval)(e,n,u,d);return c===`auto`&&this.autoMode!==void 0&&!p&&s?.askAll!==!0?this.decideInAutoMode(this.autoMode,e,n,r,i,a,o):o.hookDecision===`allow`&&!p&&s?.askAll!==!0||this.promptForApproval(e,n,r,i,p,o)}async decideInAutoMode(e,n,r,i,a,o,s){if(e.takeRetry(n,r)||(0,t.matchesAnyPattern)(n,r,(0,t.allowRulesForAutoMode)([...this.sessionAllowedTools])))return!0;if(e.isPaused()){let t=await this.promptForApproval(n,r,i,a,!0,s);return t&&!this.checkpointedApprovals&&!Jt(s.continuation)&&e.resume(),t}let c=await e.judge({toolName:n,toolArgs:r,cwd:this.cwd},i);return i?.aborted===!0?!1:this.getPermissionMode()===`auto`?c.kind===`allow`?!0:(this.denials.record(n,r,`classifier`,c.reason),{message:c.message}):this.decidePermission(n,r,i,a,o,s)}async promptForApproval(e,n,r,i=`interactive`,a=!1,{continuation:o,executionId:s}={}){let c=!a&&(0,t.matchesAnyPattern)(e,n,[...this.sessionAllowedTools]);if(this.checkpointedApprovals&&!c||Jt(o)){if(r?.aborted||i!==`interactive`)return!1;let t=await Yt({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:n},o,!0);return t!==!0&&this.denials.record(e,n,`user`),t===!0}let l=en(e,n),u=r?.aborted===!0,d=i===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),f=await Kt({toolName:e,alreadyAllowed:c,...i===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...i===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:n,...r?{signal:r}:{},...s===void 0?{}:{executionId:s}});if(!f.allowed&&!u&&this.denials.record(e,n,d?`user`:`no-approver`),a)return f.allowed;if(f.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(l)}return f.rememberForSession&&this.sessionAllowedTools.add(l),f.allowed}firePermissionDecisionHook(e,n,r,i){let a=this.getPermissionMode();(0,t.runHooks)(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:e,tool_input:n,permission_decision:r,...a!==void 0&&{permission_mode:a},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,i).catch(()=>void 0)}sandboxAutoApproves(e,n){if(this.commandSandbox===void 0)return!1;let r=(0,t.getToolPermissionProfile)(e).argument;if(r?.kind!==`command`)return!1;let i=n[r.key];return typeof i==`string`&&this.commandSandbox.autoApproves(e,i)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function xn(e,t,n,r,i){return new bn({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 Sn(e,t,n,r){return{contextTracker:new Ht(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new Bt({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Cn(e,n,r,i,a,o,s){let c=n.wrapTools(r);return new t.ConversationAgent({name:e.agentName??`agent`,aiProviders:[i],...e.providerOwnership===void 0?{}:{providerOwnership:{[i.name]:e.providerOwnership}},defaultModel:{provider:i.name,model:a,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}},systemMessage:o,tools:c,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},isToolVisible:e=>n.isToolVisible(e),logging:{enabled:!1},eventService:s,...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 wn(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 Tn(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 En=(0,t.createLogger)(`SessionHistoryOps`);function Dn(e,t){return{...e,...t}}async function On(e,n,r){r?.throwIfAborted();let i=n.agent.getHistory(),a=i.filter(e=>e.role!==`system`);if(a.length===0)return;n.contextTracker.updateFromHistory(i);let o=n.contextTracker.getContextState(),s=wn(i),c=await n.compactionOrchestrator.compact(n.aiProvider,a,e,r,n.trigger,n.hookTraceEnv,n.executionJournal);n.agent.clearHistory(),n.agent.injectMessage(`system`,n.systemMessage),n.agent.injectMessage(`assistant`,`[Context Summary]\n${c}`),s.length>0&&n.agent.injectRawMessage(Tn(s)),n.contextTracker.updateFromHistory(n.agent.getHistory());let l={session_id:n.sessionId,cwd:n.cwd,hook_event_name:`PostCompact`,trigger:n.trigger,compact_summary:c};(0,t.runHooks)(n.hooks,`PostCompact`,l,n.hookTypeExecutors,n.hookTraceEnv).catch(e=>En.warn(`hook failed`,{error:e}));let u=n.contextTracker.getContextState();n.log(`context_compact`,{trigger:n.trigger,before:o,after:u}),n.onCompactEventCallback?.({trigger:n.trigger,before:o,after:u}),n.onCompactCallback&&n.onCompactCallback(c)}function kn(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 kt(e.sessionStore.save(i)),{status:`valid`,record:i}}const An=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function jn(){return`session_${(0,r.randomUUID)()}`}function V(e){return e.length>0&&e.length<=128&&An.test(e)}function H(e){if(!V(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 Mn=(0,t.createLogger)(`SessionLifecycle`);function Nn(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function Pn(e,n,r,i,a,o,s){(0,t.runHooks)(r,`SessionStart`,{session_id:e,cwd:n,hook_event_name:`SessionStart`,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:e}},i).then(e=>{e.stdout&&a(e.stdout)}).catch(e=>Mn.warn(`SessionStart hook failed`,{error:e}))}async function Fn(e,n,r,i,a,o,s){await(0,t.runHooks)(i,`SessionEnd`,{session_id:e,cwd:n,hook_event_name:`SessionEnd`,reason:r,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:e}},a)}const In=`unknown_tool`;function Ln(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,pendingArgs:new Map,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function Rn(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){let t=U(n.toolCallId);t&&e.pendingArgs.set(t,Vn(n.parameters)),zn(e,n);return}t===`tool_execution_result`&&Bn(e,n)}}function zn(e,t){let n=U(t.toolName),r=U(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:Vn(t.parameters)}))}function Bn(e,t){let n=U(t.toolName),r=U(t.toolCallId);if(!n||!r)return;let i=Hn(t.metadata),a=e.pendingArgs.get(r);if(e.pendingArgs.delete(r),t.success===!1&&i?.dispatchStatus===`not-dispatched`){let o=U(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===In))return;e.unknownToolCallIds.delete(r);let o=U(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:o,errorCode:In,requestedTool:U(i?.requestedTool)??n,availableTools:Un(i?.availableTools)})})}function Vn(e){let t=Hn(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 U(e){return typeof e==`string`&&e.length>0?e:void 0}function Hn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Un(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const Wn=(0,t.createLogger)(`SessionRunObservation`);function Gn(e,n,r,i){let a=typeof r.model==`string`?r.model:e.model,o=typeof r.provider==`string`?r.provider:e.aiProvider.name,s=r.effort,c=typeof s==`string`&&(0,t.isModelEffort)(s)?s:e.effort??(typeof e.agent.getModel==`function`?e.agent.getModel().effort:void 0)??`high`,l=typeof r.round==`number`?r.round:void 0;(0,t.runHooks)(e.hooks,n,{session_id:e.sessionId,cwd:e.cwd,hook_event_name:n,model:a,provider:o,effort:c,...l!==void 0&&{round:l},...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,i).catch(e=>Wn.warn(`hook failed`,{error:e}))}function Kn(e,n){let r=n?(0,t.traceEnvFor)(`hooks`,n,n.parentSpanId):void 0,i=Ln({knownToolNames:e.knownToolNames??[],...e.onToolExecution&&{onToolExecution:e.onToolExecution}}),a=e.onTextDelta?t=>{e.log(`text_delta`,{delta:t}),e.onTextDelta?.(t)}:void 0,o={};return{onExecutionEvent:(n,a)=>{if(n===`history_mutation`&&a.mutation===`append_message`){let t=a.message;(t?.role===`user`||t?.role===`assistant`&&Array.isArray(t.toolCalls)&&t.toolCalls.length>0)&&e.checkpointHistory?.()}if(n!==t.PROVIDER_CALL_EVENTS.COMPLETED&&e.log(n,a),Rn(i,n,a),n===`provider_request`){let t=a;o={model:t.model,provider:t.provider},Gn(e,`PreModelCall`,t,r)}else if(n===`provider_response_normalized`)Gn(e,`PostModelCall`,{...a,...o},r);else if(n===t.PROVIDER_FALLBACK_EVENTS.SWITCHED){let n=(0,t.readModelFallbackNotice)(a);n!==void 0&&(Gn(e,`PostModelCall`,{round:a.round,model:n.from.model,provider:n.from.provider},r),e.emitProviderFallback?.(n))}else if(n===t.PROVIDER_CALL_EVENTS.COMPLETED&&e.emitProviderCallCompleted){let t=a;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}})}n===`assistant_message_committed`&&(e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()))},...a&&{onTextDelta:a},...e.onThinkingDelta&&{onThinkingDelta:e.onThinkingDelta}}}async function qn(e,t){let n=await e.agent.resume({...t,...Kn(e,t.traceContext)});return e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()),n}function Jn(t,n){let r=(0,e.realpathSync)(n.cwd);return{append:async e=>{if((e.kind===`model-request`||e.kind===`model-cache-hit`)&&e.checkpoint){let i=structuredClone(e);i.checkpoint.owner={kind:`agent-session`,version:1,state:{sessionId:n.sessionId,cwd:r,peerTurn:n.peerTurn,executionId:e.executionId}},await t.append(i)}else await t.append(e)}}}function Yn(n,r,i,a){let o,s=(0,e.realpathSync)(i);return{read:async e=>{let c=structuredClone(await n.read(e)),l;for(let n of c){if(n.kind!==`model-request`&&n.kind!==`model-cache-hit`)continue;let i=n.checkpoint?.owner,a=i?.state;if(!i||i.kind!==`agent-session`||i.version!==1||!a||a.sessionId!==r||a.cwd!==s||a.executionId!==e||typeof a.peerTurn!=`boolean`||l!==void 0&&l!==a.peerTurn||a.peerTurn&&n.checkpoint?.continuation?.options.withholdHostedTools!==!0)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session continuation owner or scope is incompatible`);l=a.peerTurn}if(l===void 0)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`No Session owner checkpoint exists`);return o=Jn(n,{sessionId:r,cwd:i,peerTurn:l}),a(l),c},append:async e=>{if(!o)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session owner has not been restored`);await o.append(e)}}}function Xn(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 Zn=(0,t.createLogger)(`SessionRun`);async function Qn(e,n,r,i,a){let o=a?.traceContext,s=o?(0,t.traceEnvFor)(`hooks`,o,o.parentSpanId):void 0;r.log(`user`,{content:e});let c=await(0,t.runHooks)(r.hooks,`UserPromptSubmit`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`UserPromptSubmit`,user_message:n??e,prompt:n??e,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s),l=[r.sessionStartStdout,c.stdout].filter(Boolean).join(`
7
- `),u=l?`<system-reminder>\n${l}\n</system-reminder>\n${e}`:e,d=(0,t.createUserMessage)(u),f=a?.ephemeralSystemContext,p=[d,...f?.trim()?[(0,t.createSystemMessage)(f)]:[]];r.contextTracker.updateFromHistory(r.agent.getHistory()),r.contextTracker.shouldAutoCompact([...r.agent.getHistory(),...p])&&(a?.executionJournal?await r.compact(i,s,a.executionJournal):await(s?r.compact(i,s):r.compact(i))),r.clearSessionStartStdout();let m=r.agent.getHistory(),h=JSON.stringify(m),g=(0,t.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:m.length,historyChars:h.length,historyEstTokens:Math.ceil(h.length/t.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:u,history:m,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:g.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:g.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:g.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:g.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...m,...p]),r.onContextUpdate?.(r.contextTracker.getContextState());let _;try{if(_=await r.agent.run(u,{signal:i,maxExecutionRounds:r.maxTurns??0,...Xn(a),...Kn(r,o)}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof t.ExecutionSuspendedError)throw e;try{r.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:r.agent.getHistory().length})}catch{}throw(0,t.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Zn.warn(`hook failed`,{error:e})),e}let v=r.agent.getHistory(),y=v.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}:{}}});r.log(`assistant`,{content:_,historyLength:v.length,estimatedChars:JSON.stringify(v).length,history:v,historyStructure:y}),r.contextTracker.updateFromHistory(v);let b=r.contextTracker.getContextState();return r.onContextUpdate?.(b),r.log(`context`,{maxTokens:b.maxTokens,usedTokens:b.usedTokens,usedPercentage:b.usedPercentage,remainingPercentage:b.remainingPercentage}),(0,t.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:_.substring(0,500),last_assistant_message:_,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Zn.warn(`hook failed`,{error:e})),_}function $n(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function er(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 tr(e,t,n){let r=er(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 nr(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 rr(e,n,r){let i=er(e);if(!i||i.assistant.metadata?.executionId!==n.executionId)return[];let a=new Set((r?n.requests:[]).map(e=>e.toolCallId));return i.open.map(e=>{let n=a.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(0,t.createToolMessage)(`Error: ${n}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:n,toolName:e.function.name}})})}async function ir(e,n){if(!n||typeof n.append!=`function`||typeof n.read!=`function`)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof t.ExecutionSuspendedError)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var ar=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 i=this.claim.claim(),a=W(i,n?.signal);try{return i.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??(0,r.randomUUID)(),sessionId:this.sessionId,signal:i.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(i.signal)}:{}}),await this.execution}finally{this.execution=null,a(),this.claim.release(i)}}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 W(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var or=class extends Nt{agent;eventService=new t.ObservableEventService;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:n,provider:r,systemMessage:i}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=i,this.toolSchemas=n.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??jn(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?t.TRUST_TO_MODE[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:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,Nn(r,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=xn(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:a,compactionOrchestrator:o}=Sn(e,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.agent=Cn(e,this.permissionEnforcer,n,r,this.model,i,this.eventService),this.runtimeTools=new ar(this.agent,this.turnClaim,this.sessionId,e.ask),Pn(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 ir(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,n,r,i){let a=r?{...r}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let o=this.turnClaim.claim(),s=W(o,a?.signal),{signal:c}=o;this.permissionEnforcer.beginTurn(a?.peerTurn===!0,i);try{c.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let t=a?.executionJournal?{...a,executionJournal:Jn(a.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:a.peerTurn===!0})}:a,r=await Qn(e,n,this.buildRunContext(a?.executionJournal!==void 0),c,t);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof t.ExecutionSuspendedError?(this.setPending($n(e),!0),c.throwIfAborted()):a?.executionJournal&&this.setPending(tr(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),s(),this.turnClaim.release(o)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return ir(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,n){let r={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==r.executionId)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let i=this.turnClaim.claim(),a=W(i,r.signal),o=new Set;try{i.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=Yn(nr(r.journal,o,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,n)),t=await qn(this.buildRunContext(!0),{...r,journal:e,signal:i.signal});return this.setPending(void 0),this.commitConversation(r.executionId),t}catch(e){throw e instanceof t.ExecutionSuspendedError?(this.setPending($n(e),!0),i.signal.throwIfAborted()):this.setPending(tr(this.agent.getHistory(),this.pendingExecution,o)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),a(),this.turnClaim.release(i)}}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 t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let n=this.pendingExecution;if(!n)return;if(n.executionId!==e)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim();try{let t=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of rr(this.agent.getHistory(),n,t))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(r)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new t.ExecutionRecoveryError(`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 t.ExecutionRecoveryError(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:(0,e.realpathSync)(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(n){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(n.id!==this.sessionId||(0,e.realpathSync)(n.cwd)!==(0,e.realpathSync)(this.cwd))throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let r=Tt({id:n.id,cwd:n.cwd,messages:n.messages,...n.pendingExecution===void 0?{}:{pendingExecution:n.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(r.status!==`valid`)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let i=structuredClone(r.record);this.agent.clearHistory();for(let e of i.messages)this.agent.injectRawMessage(e);this.setPending(i.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?kt(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(n){if(e instanceof t.ExecutionSuspendedError)throw n;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${n instanceof Error?n.message:String(n)}`,stack:n instanceof Error?n.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=kn({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`,()=>Fn(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=W(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 On(e,Dn(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(tr(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(t.PROVIDER_CALL_EVENTS.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(t.PROVIDER_FALLBACK_EVENTS.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 sr(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function cr(e,t={}){let n={schemaVersion:2,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function lr(e){let t=Dt(sr(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 ur=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function dr(e){return ur.test(e)}function fr(e,t,n){if(e!==void 0&&dr(e))return n;if(Array.isArray(t))return t.map(e=>fr(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]=fr(t,i,n);return r}return t}function pr(e,t=`[REDACTED]`){return fr(void 0,e,t)}const mr={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 hr(e,t){return e.event===t}function gr(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=_r(e,a,o,n,r);return i}function _r(e,t,n,r,i){if(dr(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return vr(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return vr(e,n.map(n=>_r(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]=_r(e,n,o,r,i);return vr(e,a,r,i)}return String(n)}function vr(e,t,n,i){let a=JSON.stringify(t);if(a===void 0||Buffer.byteLength(a)<=n.externalPayloadThresholdBytes||i===void 0)return t;let o=(0,r.createHash)(`sha256`).update(a).digest(`hex`);return i.writeJson(e,o,a)}const yr=(0,t.createLogger)(`FileSessionLogger`),br=new Set([`text_delta`]),G=new Set;let xr=!1;function Sr(e){G.add(e),!xr&&(typeof process>`u`||typeof process.on!=`function`||(xr=!0,process.on(`exit`,()=>{for(let e of G)e.flush()})))}var Cr=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(V(e))try{let r=gr(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
7
+ `),u=l?`<system-reminder>\n${l}\n</system-reminder>\n${e}`:e,d=(0,t.createUserMessage)(u),f=a?.ephemeralSystemContext,p=[d,...f?.trim()?[(0,t.createSystemMessage)(f)]:[]];r.contextTracker.updateFromHistory(r.agent.getHistory()),r.contextTracker.shouldAutoCompact([...r.agent.getHistory(),...p])&&(a?.executionJournal?await r.compact(i,s,a.executionJournal):await(s?r.compact(i,s):r.compact(i))),r.clearSessionStartStdout();let m=r.agent.getHistory(),h=JSON.stringify(m),g=(0,t.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:m.length,historyChars:h.length,historyEstTokens:Math.ceil(h.length/t.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:u,history:m,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:g.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:g.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:g.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:g.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...m,...p]),r.onContextUpdate?.(r.contextTracker.getContextState());let _;try{if(_=await r.agent.run(u,{signal:i,maxExecutionRounds:r.maxTurns??0,...Xn(a),...Kn(r,o)}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof t.ExecutionSuspendedError)throw e;try{r.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:r.agent.getHistory().length})}catch{}throw(0,t.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Zn.warn(`hook failed`,{error:e})),e}let v=r.agent.getHistory(),y=v.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}:{}}});r.log(`assistant`,{content:_,historyLength:v.length,estimatedChars:JSON.stringify(v).length,history:v,historyStructure:y}),r.contextTracker.updateFromHistory(v);let b=r.contextTracker.getContextState();return r.onContextUpdate?.(b),r.log(`context`,{maxTokens:b.maxTokens,usedTokens:b.usedTokens,usedPercentage:b.usedPercentage,remainingPercentage:b.remainingPercentage}),(0,t.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:_.substring(0,500),last_assistant_message:_,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>Zn.warn(`hook failed`,{error:e})),_}function $n(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function er(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 tr(e,t,n){let r=er(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 nr(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 rr(e,n,r){let i=er(e);if(!i||i.assistant.metadata?.executionId!==n.executionId)return[];let a=new Set((r?n.requests:[]).map(e=>e.toolCallId));return i.open.map(e=>{let n=a.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(0,t.createToolMessage)(`Error: ${n}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:n,toolName:e.function.name}})})}async function ir(e,n){if(!n||typeof n.append!=`function`||typeof n.read!=`function`)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof t.ExecutionSuspendedError)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var ar=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 i=this.claim.claim(),a=W(i,n?.signal);try{return i.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??(0,r.randomUUID)(),sessionId:this.sessionId,signal:i.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(i.signal)}:{}}),await this.execution}finally{this.execution=null,a(),this.claim.release(i)}}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 W(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var or=class extends Nt{agent;eventService=new t.ObservableEventService;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:n,provider:r,systemMessage:i}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=i,this.toolSchemas=n.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??jn(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?t.TRUST_TO_MODE[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:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,Nn(r,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=xn(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:a,compactionOrchestrator:o}=Sn(e,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.agent=Cn(e,this.permissionEnforcer,n,r,this.model,i,this.eventService),this.runtimeTools=new ar(this.agent,this.turnClaim,this.sessionId,e.ask),Pn(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 ir(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,n,r,i){let a=r?{...r}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let o=this.turnClaim.claim(),s=W(o,a?.signal),{signal:c}=o;this.permissionEnforcer.beginTurn(a?.peerTurn===!0,i);try{c.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let t=a?.executionJournal?{...a,executionJournal:Jn(a.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:a.peerTurn===!0})}:a,r=await Qn(e,n,this.buildRunContext(a?.executionJournal!==void 0),c,t);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof t.ExecutionSuspendedError?(this.setPending($n(e),!0),c.throwIfAborted()):a?.executionJournal&&this.setPending(tr(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),s(),this.turnClaim.release(o)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return ir(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,n){let r={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==r.executionId)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let i=this.turnClaim.claim(),a=W(i,r.signal),o=new Set;try{i.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=Yn(nr(r.journal,o,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,n)),t=await qn(this.buildRunContext(!0),{...r,journal:e,signal:i.signal});return this.setPending(void 0),this.commitConversation(r.executionId),t}catch(e){throw e instanceof t.ExecutionSuspendedError?(this.setPending($n(e),!0),i.signal.throwIfAborted()):this.setPending(tr(this.agent.getHistory(),this.pendingExecution,o)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),a(),this.turnClaim.release(i)}}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 t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let n=this.pendingExecution;if(!n)return;if(n.executionId!==e)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim();try{let t=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of rr(this.agent.getHistory(),n,t))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(r)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new t.ExecutionRecoveryError(`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 t.ExecutionRecoveryError(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:(0,e.realpathSync)(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(n){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(n.id!==this.sessionId||(0,e.realpathSync)(n.cwd)!==(0,e.realpathSync)(this.cwd))throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let r=Tt({id:n.id,cwd:n.cwd,messages:n.messages,...n.pendingExecution===void 0?{}:{pendingExecution:n.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(r.status!==`valid`)throw new t.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let i=structuredClone(r.record);this.agent.clearHistory();for(let e of i.messages)this.agent.injectRawMessage(e);this.setPending(i.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?kt(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(n){if(e instanceof t.ExecutionSuspendedError)throw n;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${n instanceof Error?n.message:String(n)}`,stack:n instanceof Error?n.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=kn({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`,()=>Fn(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=W(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 On(e,Dn(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(tr(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(t.PROVIDER_CALL_EVENTS.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(t.PROVIDER_FALLBACK_EVENTS.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 sr(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function cr(e,t={}){let n={schemaVersion:2,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function lr(e){let t=Dt(sr(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 ur=/^(api[-_]?key|authorization|auth[-_]?token|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function dr(e){return ur.test(e)}function fr(e,t,n){if(e!==void 0&&dr(e))return n;if(Array.isArray(t))return t.map(e=>fr(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]=fr(t,i,n);return r}return t}function pr(e,t=`[REDACTED]`){return fr(void 0,e,t)}const mr={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 hr(e,t){return e.event===t}function gr(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=_r(e,a,o,n,r);return i}function _r(e,t,n,r,i){if(dr(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return vr(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return vr(e,n.map(n=>_r(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]=_r(e,n,o,r,i);return vr(e,a,r,i)}return String(n)}function vr(e,t,n,i){let a=JSON.stringify(t);if(a===void 0||Buffer.byteLength(a)<=n.externalPayloadThresholdBytes||i===void 0)return t;let o=(0,r.createHash)(`sha256`).update(a).digest(`hex`);return i.writeJson(e,o,a)}const yr=(0,t.createLogger)(`FileSessionLogger`),br=new Set([`text_delta`]),G=new Set;let xr=!1;function Sr(e){G.add(e),!xr&&(typeof process>`u`||typeof process.on!=`function`||(xr=!0,process.on(`exit`,()=>{for(let e of G)e.flush()})))}var Cr=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(V(e))try{let r=gr(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
8
8
  `;if(br.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){G.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,G.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){Sr(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){yr.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},wr=class{log(){}};const Tr=(0,t.createLogger)(`NodeSessionLogSink`),Er=/^[0-9a-f]{64}$/;function Dr(e,t){let n=(0,r.createHash)(`sha256`).update(t).digest(`hex`);if(!Er.test(e)||e!==n)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function Or(e,t,r){return H(e),Dr(t,r),{kind:`external-payload`,encoding:`json`,sha256:t,byteLength:Buffer.byteLength(r),relativePath:(0,n.join)(`${e}.payloads`,`${t}.json`)}}var kr=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,Tr.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(t,r){if(H(t),!this.enabled)return;let i=(0,n.join)(this.logDirectory,`${t}.jsonl`);(0,a.tightenExistingFile)(i),(0,e.appendFileSync)(i,r,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(t,r,i){let o=Or(t,r,i),s=`${t}.payloads`;if(this.enabled){(0,a.ensureOwnerOnlyDirectory)((0,n.join)(this.logDirectory,s));let t=(0,n.join)(this.logDirectory,o.relativePath);try{(0,e.writeFileSync)(t,i,{encoding:`utf8`,mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(e){if(e.code!==`EEXIST`)throw e;(0,a.tightenExistingFile)(t)}}return o}};const K=e=>({decode:e}),q=e=>({decode:e,optional:!0}),Ar=(e,t,n)=>S(e,t,n,h),jr=(e,t,n)=>S(e,t,n,N),Mr=(e,t,n)=>S(e,t,n,St),Nr=(e,t,n)=>typeof e==`string`?e:N(e,t,n),J=(e,t,n)=>{let r=_(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function Pr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Y(e,t,n){if(!Pr(e)){n.push({path:t,message:`expected an object, received ${f(e)}`});return}for(let[r,i]of Object.entries(e))X(i,l(t,r),n);return e}const Fr=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function Ir(e,t,n){let r=w(e,t,n,Fr);if(r===void 0)return;let i=g(r.maxTokens,l(t,`maxTokens`),n),a=g(r.usedTokens,l(t,`usedTokens`),n),o=g(r.usedPercentage,l(t,`usedPercentage`),n),s=g(r.remainingPercentage,l(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 Lr=(e,t,n)=>S(e,t,n,(e,t,n)=>{let r=w(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=h(r.type,l(t,`type`),n),a=h(r.id,l(t,`id`),n);return i===void 0||a===void 0?void 0:{type:i,id:a}});function X(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 ${f(e)}`});return}if(!Array.isArray(e)&&!Pr(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${f(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++)X(e[i],u(t,i),n,r);else for(let[i,a]of Object.entries(e))X(a,l(t,i),n,r);return r.delete(e),e}function Rr(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)?Rr(e[i],u(t,i),n,r):n.push({path:u(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))Rr(a,l(t,i),n,r);r.delete(e)}}const Z=(...e)=>(t,n,r)=>y(t,e,n,r),zr={session_init:{cwd:K(h),systemPromptLength:K(J),systemPrompt:K(h),toolSchemas:K(Mr),model:K(h),provider:K(h)},session_shutdown:{reason:K(h)},session_shutdown_step_error:{step:K(h),error:K(h)},context:{maxTokens:K(g),usedTokens:K(g),usedPercentage:K(g),remainingPercentage:K(g)},context_compact:{trigger:K(h),before:K(Ir),after:K(Ir)},error:{message:K(h),stack:K(h),historyLength:K(J)},history_mutation:{executionId:q(h),conversationId:q(h),round:q(J),batchId:q(h),usageObservationId:q(h),providerId:q(h),modelId:q(h),providerError:q(v),contextOverflow:q(v),mutation:K(Z(`append_message`)),index:K(J),message:K(N)},provider_request:{executionId:K(h),conversationId:q(h),round:K(J),provider:K(h),model:K(h),effort:q(h),forcedSummary:q(v),messages:K(jr),tools:q(Mr)},provider_native_raw_payload:{executionId:K(h),conversationId:q(h),round:K(J),provider:K(h),apiSurface:q(h),payloadKind:K(Z(`request`,`response`,`stream_event`)),sequence:K(J),payload:q(X),metadata:q(Y)},provider_stream_raw_delta:{executionId:K(h),conversationId:q(h),round:K(J),sequence:K(J),delta:K(h)},provider_response_raw:{executionId:K(h),conversationId:q(h),round:K(J),effort:q(h),response:K(N),responseKind:K(h)},provider_response_normalized:{executionId:K(h),conversationId:q(h),round:K(J),response:K(N),toolCallsCount:q(J)},structured_output_transport:{executionId:K(h),conversationId:q(h),round:K(J),provider:K(h),model:K(h),mechanism:K(Z(`response_schema`,`json_object`,`none`)),provenance:K(Z(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:K(v),schemaInPrompt:K(v),reason:q(h)},provider_fallback:{executionId:K(h),conversationId:q(h),round:K(J),fromProvider:K(h),fromModel:K(h),toProvider:K(h),toModel:K(h),reason:K(h)},assistant_message_committed:{executionId:K(h),conversationId:q(h),round:K(J),message:K(Nr)},tool_execution_request:{executionId:K(h),conversationId:q(h),round:K(J),batchId:q(h),index:q(J),toolName:K(h),toolCallId:K(h),parameters:K(Y),ownerPath:q(Lr)},tool_execution_result:{executionId:K(h),conversationId:q(h),round:K(J),batchId:q(h),index:q(J),toolName:q(h),toolCallId:q(h),success:K(v),result:q(X),error:q(h),metadata:q(Y)},tool_batch_started:{executionId:K(h),conversationId:q(h),round:K(J),batchId:q(h),mode:K(Z(`parallel`,`sequential`)),maxConcurrency:K(J),requestCount:K(J),tools:K(Ar)},tool_message_committed:{executionId:K(h),conversationId:q(h),round:K(J),batchId:q(h),index:q(J),message:K(N)},background_task_event:{backgroundEventType:q(h),backgroundEvent:q(Ge),data:q(Ge),taskId:q(h),originToolCallId:q(h)},background_job_group_event:{backgroundJobGroupEvent:q(ke),data:q(ke)},memory_event:{memoryEvent:q(tt),data:q(tt)},user:{content:K(h)},pre_run:{historyLength:K(J),historyChars:K(J),historyEstTokens:K(J),input:K(h),history:K(jr),model:K(h),provider:K(h),maxTokens:K(g),nativeWebSearchSupported:K(v),nativeWebSearchEnabled:K(v),nativeWebFetchSupported:K(v),nativeWebFetchEnabled:K(v)},text_delta:{delta:K(h)},assistant:{content:K(h),historyLength:K(J),estimatedChars:K(J),history:K(jr),historyStructure:K((e,t,n)=>S(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${f(e)}`});return}let r=e;y(r.role,[`user`,`assistant`,`system`,`tool`],l(t,`role`),n),J(r.contentLength,l(t,`contentLength`),n),v(r.hasToolCalls,l(t,`hasToolCalls`),n),Ar(r.toolCallNames,l(t,`toolCallNames`),n),r.metadata!==void 0&&Y(r.metadata,l(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:l(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:K(h),args:K(Y)},tool_result:{tool:K(h),success:K(v),dataChars:K(J),truncated:K(v)},tool_blocked:{tool:K(h),reason:K(h)},tool_denied:{tool:K(h),reason:K(h)},server_tool:{tool:K(h)}};var Br=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 Vr=new Set(Object.values(mr));function Hr(e,t={}){if(!Array.isArray(e))throw new Br(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${f(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=Ur(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 Br(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function Ur(e,t,n){if(!Pr(e))return n.push({path:t,message:`expected an object, received ${f(e)}`}),{};let r=n.length;if(Rr(e,t,n),n.length!==r)return{};let i=Wr(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(Gr(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function Wr(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:l(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:l(t,`schemaVersion`),message:`expected schema version 1, received ${f(r)}`})}let a=b(e.timestamp,l(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=h(e.sessionId,l(t,`sessionId`),n);o===``&&n.push({path:l(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!Vr.has(s)?(n.push({path:l(t,`event`),message:`expected a declared event name, received ${f(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function Gr(e,t,n,r,i){let a=zr[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],l(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:l(n,o),message:`unknown event payload field`});continue}let s=X(e[o],l(n,o),i);s!==void 0&&(r[o]=s)}Kr(e,t,n,i)}function Kr(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 qr(e){if(e.trim().length===0||e.includes(`\0`)||(0,n.isAbsolute)(e)||n.win32.isAbsolute(e))throw Yr(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Yr(e);return t}function Jr(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 Yr(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Xr(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Yr(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 Zr=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,n.resolve)(e)}readBytes(e,t){Jr(t);let n=qr(e);try{let e=(0,o.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof o.StableFileAuthorityError?Xr(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Qr=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 Zr((0,n.dirname)(e))}readText(){return(0,e.existsSync)(this.logFile)?(0,e.readFileSync)(this.logFile,`utf8`):void 0}};const $r=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,ei=8*1024*1024,ti=e.constants.O_WRONLY|e.constants.O_CREAT|e.constants.O_EXCL|(e.constants.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},ni=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(t={}){let r=t.parentDirectory??(0,i.tmpdir)();if(this.retentionMs=t.retentionMs??36e5,this.now=t.now??Date.now,this.onCleanupFailure=t.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new $(`invalid-options`);try{let t=(0,e.lstatSync)(r);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,e.mkdtempSync)((0,n.join)(r,`agent-tool-results-`)),process.platform!==`win32`&&(0,e.chmodSync)(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let t=(0,e.lstatSync)(this.directory);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&t.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(t){if(this.closed)throw new $(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(t,`utf8`)>ei)throw new $(`write-failed`);let i=(0,r.randomBytes)(18).toString(`base64url`),a=`${(0,r.randomBytes)(18).toString(`base64url`)}.partial`,o=`${i}.txt`,s=(0,n.join)(this.directory,a),c=(0,n.join)(this.directory,o),l,u=!1;try{l=(0,e.openSync)(s,ti,384),(0,e.writeFileSync)(l,t,`utf8`),(0,e.fsyncSync)(l),(0,e.closeSync)(l),l=void 0,(0,e.linkSync)(s,c),u=!0,(0,e.unlinkSync)(s);let n=`tool-result:${i}`;return this.entries.set(n,{fileName:o,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:n}}catch{let t=!1;if(l!==void 0)try{(0,e.closeSync)(l)}catch{t=!0}try{(0,e.unlinkSync)(s)}catch(e){e.code!==`ENOENT`&&(t=!0)}if(u)try{(0,e.unlinkSync)(c)}catch{t=!0}throw new $(t?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!$r.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 Zr(this.directory).readBytes(t.fileName,ei);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(t,r){this.assertRoot();try{(0,e.unlinkSync)((0,n.join)(this.directory,r.fileName)),this.entries.delete(t)}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((0,e.readdirSync)(this.directory).length!==0)throw Error(`unexpected files`);(0,e.rmdirSync)(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};function ri(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 ii(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(ri(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function ai(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=ii(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function oi(e){return e.code===`ENOENT`}var si=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(t){(0,a.ensureOwnerOnlyDirectory)((0,n.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,e.appendFileSync)(this.path,`${JSON.stringify(t)}\n`,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(t){let n;try{n=(0,e.openSync)(this.path,e.constants.O_RDONLY|(e.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&oi(e))return;throw e}try{let r=(0,e.fstatSync)(n).size,i=Buffer.alloc(0);for(;r>0&&!t.signal.aborted;){let t=Math.min(this.blockBytes,r);r-=t;let a=Buffer.alloc(t),o=(0,e.readSync)(n,a,0,t,r),s=Buffer.concat([a.subarray(0,o),i]),c=r===0?-1:s.indexOf(10);i=c===-1&&r>0?s:s.subarray(0,c+1);let l=r===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);r>0&&c===-1||(yield ai(l.toString(`utf8`).split(`
9
9
  `).reverse()))}}finally{(0,e.closeSync)(n)}}};const ci=/^[0-9a-f]{64}$/i;function li(e){if(!ui(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 ui(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`&&ci.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function di(e,t){return mi(e,fi(t),0)}function fi(e){let t=pi(`maxDepth`,e.maxDepth??32),n=pi(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function pi(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 mi(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 _i(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw _i(`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(vi(e))return hi(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>mi(e,t,n))}finally{t.activeObjects.delete(e)}}if(!yi(e))throw _i(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,mi(r,t,n)]))}finally{t.activeObjects.delete(e)}}function hi(e,t,n){let r=li(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=gi(r,t);t.activePayloadPaths.add(r.relativePath);try{return mi(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function gi(e,t){let n=t.maxTotalBytes-t.totalBytes,i=t.source?.readBytes(e.relativePath,n);if(i===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let a=t.totalBytes+i.byteLength;if(!Number.isSafeInteger(a)||a>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:a});if(t.totalBytes=a,i.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:i.byteLength});let o=(0,r.createHash)(`sha256`).update(i).digest(`hex`);if(o!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:o});try{return JSON.parse(Buffer.from(i).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function _i(e){return new Q(`INVALID_JSON`,e)}function vi(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function yi(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bi(e){let t=[],n=xi(),r=Si();return Hr(e).forEach((e,i)=>{Ai(e,i,t),wi(e,i,t),Ci(n,e,i),Ti(r,e,i)}),Ei(n,t),Di(r,t),{ok:t.length===0,issues:t}}function xi(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function Si(){return{requests:new Map,results:new Set}}function Ci(e,t,n){let r=Oi(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`&&!ji(t.response)&&e.normalizedResponses.add(r.key))}function wi(e,t,n){ji(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 Ti(e,t,n){let r=ki(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 Ei(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 Di(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 Oi(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 ki(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 Ai(e,t,n){if(Array.isArray(e)){e.forEach(e=>Ai(e,t,n));return}if(Mi(e)){if(e.kind===`external-payload`){ui(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>Ai(e,t,n))}}function ji(e){return Array.isArray(e)?e.some(e=>ji(e)):Mi(e)?e.kind===`external-payload`||Object.values(e).some(e=>ji(e)):!1}function Mi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ni(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 Br(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),Hr(di(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Pi(e){let n=[],r=[],i={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},a,o,s,c;for(let l of Hr(e))a??=l.sessionId,s??=l.timestamp,c=l.timestamp,l.event===`session_init`&&(o=typeof l.cwd==`string`?l.cwd:o),l.event===`history_mutation`&&l.mutation===`append_message`&&(n.push(l.message),r.push((0,t.messageToHistoryEntry)(l.message))),Fi(l,i);return{sessionId:a,cwd:o,createdAt:s,updatedAt:c,messages:n,history:r,backgroundTaskEvents:i.backgroundTaskEvents,backgroundJobGroupEvents:i.backgroundJobGroupEvents,memoryEvents:i.memoryEvents}}function Fi(e,t){if(e.event===`background_task_event`){Li(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){Li(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&Li(t.memoryEvents,e,`memoryEvent`,`data`)}function Ii(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function Li(e,t,n,r){let i=Ii(t,n)??Ii(t,r);i&&e.push(i)}function Ri(e){return e instanceof Error?e.message:`unknown error`}function zi(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Dt(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 Bi(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Vi=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){H(e);let t=(0,c.resolve)(this.baseDir),n=(0,c.resolve)(t,`${e}.json`);if(!n.startsWith(t+c.sep))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!(0,s.existsSync)(t))return{status:`missing`};let n;try{n=(0,s.readFileSync)(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Ri(e)}`}]}}return zi(n)}list(){return(0,s.existsSync)(this.baseDir)?(0,s.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(Bi):[]}outcomeForListedId(e){return V(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);(0,s.existsSync)(t)&&(0,s.unlinkSync)(t)}},Hi=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}};exports.AUTO_COMPACT_THRESHOLD=Vt,exports.AutoModeGate=Zt,exports.CONSECUTIVE_BLOCK_LIMIT=3,exports.CheckpointTree=Hi,exports.CompactionError=Rt,exports.CompactionOrchestrator=Bt,exports.ContextWindowTracker=Ht,exports.DEFAULT_COMPACTION_PROMPT=zt,exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.FileSessionLogger=Cr,exports.INTERACTIVE_SESSION_RECORD_KEYS=wt,exports.NodeExternalPayloadSource=Zr,exports.NodePromptHistoryFile=si,exports.NodeSessionLogSink=kr,exports.NodeSessionLogSource=Qr,exports.NodeSessionStore=Vi,exports.NodeToolResultSpillStore=ni,exports.PermissionEnforcer=bn,exports.SENSITIVE_KEY_PATTERN=ur,exports.SESSION_LOG_EVENT=mr,exports.SESSION_LOG_SCHEMA_VERSION=1,exports.SESSION_RECORD_ENVELOPE_VERSION=2,exports.Session=or,exports.SessionBusyError=jt,exports.SessionLogDecodeError=Br,exports.SessionLogPayloadResolutionError=Q,exports.SilentSessionLogger=wr,exports.TOTAL_BLOCK_LIMIT=20,exports.ToolResultSpillError=$,exports.TurnClaim=Mt,exports.assertSafeSessionId=H,exports.consentScopeFor=en,exports.createSessionLogExternalPayloadReference=Or,exports.decodeInteractiveSessionRecord=Tt,exports.decodeSessionLogEntries=Hr,exports.decodeVersionedInteractiveSessionRecord=Dt,exports.deserializeSessionArtifact=lr,exports.formatConversationEntries=Lt,exports.isSafeSessionId=V,exports.isSensitiveKey=dr,exports.isSessionLogEvent=hr,exports.loadSessionLogEntries=Ni,exports.parsePromptHistoryLine=ii,exports.replaySessionLogEntries=Pi,exports.resolveSessionLogExternalPayloads=di,exports.scrubSensitiveKeys=pr,exports.serializeSessionArtifact=cr,exports.validateSessionReplayLogEntries=bi;
10
+ `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new Br(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),Hr(di(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Pi(e){let n=[],r=[],i={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},a,o,s,c;for(let l of Hr(e))a??=l.sessionId,s??=l.timestamp,c=l.timestamp,l.event===`session_init`&&(o=typeof l.cwd==`string`?l.cwd:o),l.event===`history_mutation`&&l.mutation===`append_message`&&(n.push(l.message),r.push((0,t.messageToHistoryEntry)(l.message))),Fi(l,i);return{sessionId:a,cwd:o,createdAt:s,updatedAt:c,messages:n,history:r,backgroundTaskEvents:i.backgroundTaskEvents,backgroundJobGroupEvents:i.backgroundJobGroupEvents,memoryEvents:i.memoryEvents}}function Fi(e,t){if(e.event===`background_task_event`){Li(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){Li(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&Li(t.memoryEvents,e,`memoryEvent`,`data`)}function Ii(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function Li(e,t,n,r){let i=Ii(t,n)??Ii(t,r);i&&e.push(i)}function Ri(e){return e instanceof Error?e.message:`unknown error`}function zi(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Dt(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 Bi(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Vi=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){H(e);let t=(0,c.resolve)(this.baseDir),n=(0,c.resolve)(t,`${e}.json`);if(!n.startsWith(t+c.sep))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!(0,s.existsSync)(t))return{status:`missing`};let n;try{n=(0,s.readFileSync)(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Ri(e)}`}]}}try{(0,a.tightenExistingFile)(t)}catch{}return zi(n)}list(){return(0,s.existsSync)(this.baseDir)?(0,s.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(Bi):[]}outcomeForListedId(e){return V(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);(0,s.existsSync)(t)&&(0,s.unlinkSync)(t)}},Hi=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}};exports.AUTO_COMPACT_THRESHOLD=Vt,exports.AutoModeGate=Zt,exports.CONSECUTIVE_BLOCK_LIMIT=3,exports.CheckpointTree=Hi,exports.CompactionError=Rt,exports.CompactionOrchestrator=Bt,exports.ContextWindowTracker=Ht,exports.DEFAULT_COMPACTION_PROMPT=zt,exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.FileSessionLogger=Cr,exports.INTERACTIVE_SESSION_RECORD_KEYS=wt,exports.NodeExternalPayloadSource=Zr,exports.NodePromptHistoryFile=si,exports.NodeSessionLogSink=kr,exports.NodeSessionLogSource=Qr,exports.NodeSessionStore=Vi,exports.NodeToolResultSpillStore=ni,exports.PermissionEnforcer=bn,exports.SENSITIVE_KEY_PATTERN=ur,exports.SESSION_LOG_EVENT=mr,exports.SESSION_LOG_SCHEMA_VERSION=1,exports.SESSION_RECORD_ENVELOPE_VERSION=2,exports.Session=or,exports.SessionBusyError=jt,exports.SessionLogDecodeError=Br,exports.SessionLogPayloadResolutionError=Q,exports.SilentSessionLogger=wr,exports.TOTAL_BLOCK_LIMIT=20,exports.ToolResultSpillError=$,exports.TurnClaim=Mt,exports.assertSafeSessionId=H,exports.consentScopeFor=en,exports.createSessionLogExternalPayloadReference=Or,exports.decodeInteractiveSessionRecord=Tt,exports.decodeSessionLogEntries=Hr,exports.decodeVersionedInteractiveSessionRecord=Dt,exports.deserializeSessionArtifact=lr,exports.formatConversationEntries=Lt,exports.isSafeSessionId=V,exports.isSensitiveKey=dr,exports.isSessionLogEvent=hr,exports.loadSessionLogEntries=Ni,exports.parsePromptHistoryLine=ii,exports.replaySessionLogEntries=Pi,exports.resolveSessionLogExternalPayloads=di,exports.scrubSensitiveKeys=pr,exports.serializeSessionArtifact=cr,exports.validateSessionReplayLogEntries=bi;
@@ -1190,7 +1190,9 @@ declare function deserializeSessionArtifact(bytes: string): IInteractiveSessionR
1190
1190
  type TScrubbableValue = string | number | boolean | object | null | undefined;
1191
1191
  /**
1192
1192
  * Keys whose VALUE is a secret and must be redacted before persistence or sharing:
1193
- * `apiKey`/`authorization`/`accessToken`/`refreshToken`/`secret`/`password`/`xApiKey` (case/`-`/`_`-insensitive).
1193
+ * `apiKey`/`authorization`/`authToken`/`accessToken`/`refreshToken`/`secret`/`password`/`xApiKey`
1194
+ * (case/`-`/`_`-insensitive). `authToken` is how a provider's bearer credential is stored in
1195
+ * settings, so it must be redacted alongside `apiKey`; bare `token` stays unmatched (too broad).
1194
1196
  */
1195
1197
  declare const SENSITIVE_KEY_PATTERN: RegExp;
1196
1198
  /** True when a key's value should be redacted. The one predicate both the logger and the artifact scrub use. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/context-window-tracker.ts","../../src/session-log-reference-types.ts","../../src/session-log-sinks.ts","../../src/session-logger.ts","../../src/auto-mode-gate.ts","../../src/permission-types.ts","../../src/session-types.ts","../../src/session-resume.ts","../../src/session-recoverable.ts","../../src/turn-claim.ts","../../src/compaction-orchestrator.ts","../../src/permission-denial-log.ts","../../src/permission-enforcer.ts","../../src/session-base.ts","../../src/session.ts","../../src/consent-scope.ts","../../src/conversation-transcript.ts","../../src/session-artifact.ts","../../src/scrub-sensitive.ts","../../src/session-log-events.ts","../../src/session-log-entry-types.ts","../../src/session-log-codec/index.ts","../../src/external-payload-source-types.ts","../../src/session-log-sources.ts","../../src/tool-result-spill-store.ts","../../src/prompt-history-file.ts","../../src/external-payload-resolution-contracts.ts","../../src/external-payload-resolver.ts","../../src/session-log-validation.ts","../../src/session-log-replay.ts","../../src/session-id.ts","../../src/session-store.ts","../../src/checkpoint-tree.ts","../../src/session-record-codec/decode-outcome.ts","../../src/session-record-codec/record-decoder.ts"],"mappings":";;;;cAca;KAED;cAEC;UACH;UACA;mBACS;UACT;EAGN,YAAA,eACA,2BACA,uBAAuB;;EAQzB,mBAAmB;;EAcnB,kBAAkB,kBAAkB;;EAWpC,SAA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;;;;;;;;;;;;;;;cCY9E;;UAGI;EACf;EACA,QAAQ;;;;;;;;;cAUG;;;;;;;iBAgCG,+BAA+B,iBAAiB;;;;;;;;iBAuChD,wCACd,iBACC"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/context-window-tracker.ts","../../src/session-log-reference-types.ts","../../src/session-log-sinks.ts","../../src/session-logger.ts","../../src/auto-mode-gate.ts","../../src/permission-types.ts","../../src/session-types.ts","../../src/session-resume.ts","../../src/session-recoverable.ts","../../src/turn-claim.ts","../../src/compaction-orchestrator.ts","../../src/permission-denial-log.ts","../../src/permission-enforcer.ts","../../src/session-base.ts","../../src/session.ts","../../src/consent-scope.ts","../../src/conversation-transcript.ts","../../src/session-artifact.ts","../../src/scrub-sensitive.ts","../../src/session-log-events.ts","../../src/session-log-entry-types.ts","../../src/session-log-codec/index.ts","../../src/external-payload-source-types.ts","../../src/session-log-sources.ts","../../src/tool-result-spill-store.ts","../../src/prompt-history-file.ts","../../src/external-payload-resolution-contracts.ts","../../src/external-payload-resolver.ts","../../src/session-log-validation.ts","../../src/session-log-replay.ts","../../src/session-id.ts","../../src/session-store.ts","../../src/checkpoint-tree.ts","../../src/session-record-codec/decode-outcome.ts","../../src/session-record-codec/record-decoder.ts"],"mappings":";;;;cAca;KAED;cAEC;UACH;UACA;mBACS;UACT;EAGN,YAAA,eACA,2BACA,uBAAuB;;EAQzB,mBAAmB;;EAcnB,kBAAkB,kBAAkB;;EAWpC,SAAS;;EAKT,2BAA2B;;EAK3B,wBAAwB,sBAAsB;;;;;;;;;;EAa9C,kBAAkB,SAAS;;EAK3B;;;;;;;;;;;UCjFe;EACf;EACA;EACA;EACA;EACA;;;KAIU;KACA,kBAAkB,eAAe;UAE5B;EACf;EACA;;;;;iBCKc,yCACd,mBACA,gBACA,qBACC;;UAac;EACf,UAAU,mBAAmB,gBAAgB,qBAAqB;;;UAInD;EACf,OAAO,mBAAmB;WACjB,sBAAsB;;;cAIpB,8BAA8B,iBAAiB;m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BACA,WAAU,2CACV;;;;;;;;iBCJY,kCACd,gBACA,SAAS;;;UC/BM;EACf;EAOA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA,QAAQ;;iBAGM,gCACd,kBAAkB,qBACjB;;;UChBc;EACf;EACA;EACA;EACA;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;KAGU,yBAAyB,KAAK;WAC/B,wBAAwB;;iBASnB,sBACd,QAAQ,mBACR,UAAS,yBACR;iBA6Ba,wBACd,kBAAkB,qBACjB;;;;;;;;;;iBCpCa,gBAAgB;;iBAKhB,oBAAoB;;;;;;;;;cCuCvB,4BAA4B;mBACtB;mBACA;;;;;;;;;EAUL,YAAA,iBAAiB;;;;;;;;;;UAcrB;;;;;;;;;;;;;;UAoBA;;;;;;;;;;;;;;;EA0BR,KAAK,SAAS;;;;;;;;;EAoBd,KAAK,aAAa;;;;;;;;;EA0ClB,iBAAiB;;;;;;;;;;;;;UAuBT;;;;;EAcR,OAAO;;;;;;;;;;;;;;;;;;UCxOQ;EACf;;EAEA;;cAGW;mBACM;;mBAEA;UACT;;;;;;;SAQD,UAAU,OAAO,mBAAmB,oBAAoB;;;;;EAuB/D,cAAc;;;;;EAgBd,KAAK;;EAOL,OAAO;;EAMP;;EAKA;;;;;;EAaA,UAAU;;EAWV,IAAI;;MAKA;;;;;;;;;;;;KC1FM;WACG;WAA0B,QAAQ;;WAElC;WACA,iBAAiB;WACjB;;WAEA;WAAgC;WAA4C;;;;;;;;;;;;;;;;;;;;;;;;;cCY9E;;UAGI;EACf;EACA,QAAQ;;;;;;;;;cAUG;;;;;;;iBAgCG,+BAA+B,iBAAiB;;;;;;;;iBAuChD,wCACd,iBACC"}
@@ -1190,7 +1190,9 @@ declare function deserializeSessionArtifact(bytes: string): IInteractiveSessionR
1190
1190
  type TScrubbableValue = string | number | boolean | object | null | undefined;
1191
1191
  /**
1192
1192
  * Keys whose VALUE is a secret and must be redacted before persistence or sharing:
1193
- * `apiKey`/`authorization`/`accessToken`/`refreshToken`/`secret`/`password`/`xApiKey` (case/`-`/`_`-insensitive).
1193
+ * `apiKey`/`authorization`/`authToken`/`accessToken`/`refreshToken`/`secret`/`password`/`xApiKey`
1194
+ * (case/`-`/`_`-insensitive). `authToken` is how a provider's bearer credential is stored in
1195
+ * settings, so it must be redacted alongside `apiKey`; bare `token` stays unmatched (too broad).
1194
1196
  */
1195
1197
  declare const SENSITIVE_KEY_PATTERN: RegExp;
1196
1198
  /** True when a key's value should be redacted. The one predicate both the logger and the artifact scrub use. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/context-window-tracker.ts","../../src/session-log-reference-types.ts","../../src/session-log-sinks.ts","../../src/session-logger.ts","../../src/auto-mode-gate.ts","../../src/permission-types.ts","../../src/session-types.ts","../../src/session-resume.ts","../../src/session-recoverable.ts","../../src/turn-claim.ts","../../src/compaction-orchestrator.ts","../../src/permission-denial-log.ts","../../src/permission-enforcer.ts","../../src/session-base.ts","../../src/session.ts","../../src/consent-scope.ts","../../src/conversation-transcript.ts","../../src/session-artifact.ts","../../src/scrub-sensitive.ts","../../src/session-log-events.ts","../../src/session-log-entry-types.ts","../../src/session-log-codec/index.ts","../../src/external-payload-source-types.ts","../../src/session-log-sources.ts","../../src/tool-result-spill-store.ts","../../src/prompt-history-file.ts","../../src/external-payload-resolution-contracts.ts","../../src/external-payload-resolver.ts","../../src/session-log-validation.ts","../../src/session-log-replay.ts","../../src/session-id.ts","../../src/session-store.ts","../../src/checkpoint-tree.ts","../../src/session-record-codec/decode-outcome.ts","../../src/session-record-codec/record-decoder.ts"],"mappings":";;;;cAca;KAED;cAEC;UACH;UACA;mBACS;UACT;EAGN,YAAA,eACA,2BACA,uBAAuB;;EAQzB,mBAAmB;;EAcnB,kBAAkB,kBAAkB;;EAWpC,SAAS;;EAKT,2BAA2B;;EAK3B,wBAAwB,sBAAsB;;;;;;;;;;EAa9C,kBAAkB,SAAS;;EAK3B;;;;;;;;;;;UCjFe;EACf;EACA;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,wCACd,iBACC"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/context-window-tracker.ts","../../src/session-log-reference-types.ts","../../src/session-log-sinks.ts","../../src/session-logger.ts","../../src/auto-mode-gate.ts","../../src/permission-types.ts","../../src/session-types.ts","../../src/session-resume.ts","../../src/session-recoverable.ts","../../src/turn-claim.ts","../../src/compaction-orchestrator.ts","../../src/permission-denial-log.ts","../../src/permission-enforcer.ts","../../src/session-base.ts","../../src/session.ts","../../src/consent-scope.ts","../../src/conversation-transcript.ts","../../src/session-artifact.ts","../../src/scrub-sensitive.ts","../../src/session-log-events.ts","../../src/session-log-entry-types.ts","../../src/session-log-codec/index.ts","../../src/external-payload-source-types.ts","../../src/session-log-sources.ts","../../src/tool-result-spill-store.ts","../../src/prompt-history-file.ts","../../src/external-payload-resolution-contracts.ts","../../src/external-payload-resolver.ts","../../src/session-log-validation.ts","../../src/session-log-replay.ts","../../src/session-id.ts","../../src/session-store.ts","../../src/checkpoint-tree.ts","../../src/session-record-codec/decode-outcome.ts","../../src/session-record-codec/record-decoder.ts"],"mappings":";;;;cAca;KAED;cAEC;UACH;UACA;mBACS;UACT;EAGN,YAAA,eACA,2BACA,uBAAuB;;EAQzB,mBAAmB;;EAcnB,kBAAkB,kBAAkB;;EAWpC,SAAS;;EAKT,2BAA2B;;EAK3B,wBAAwB,sBAAsB;;;;;;;;;;EAa9C,kBAAkB,SAAS;;EAK3B;;;;;;;;;;;UCjFe;EACf;EACA;EACA;EACA;EACA;;;KAIU;KACA,kBAAkB,eAAe;UAE5B;EACf;EACA;;;;;iBCKc,yCACd,mBACA,gBACA,qBACC;;UAac;EACf,UAAU,mBAAmB,gBAAgB,qBAAqB;;;UAInD;EACf,OAAO,mBAAmB;WACjB,sBAAsB;;;cAIpB,8BAA8B,iBAAiB;mBAI7B;WAHpB,qBAAqB;mBACb;EAEY,YAAA;EAqB7B,OAAO,mBAAmB;EAW1B,UAAU,mBAAmB,gBAAgB,qBAAqB;;;;;;;;;;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