@robota-sdk/agent-session 3.0.0-beta.81 → 3.0.0-beta.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import{CONTEXT_ESTIMATE_CHARS_PER_TOKEN as e,ObservableEventService as t,PROVIDER_CALL_EVENTS as n,PROVIDER_FALLBACK_EVENTS as r,Robota as i,TOOL_BODY_EVENTS as a,TOOL_PERMISSION_EVENTS as o,TRUST_TO_MODE as s,allowRulesForAutoMode as c,applyPresetToolLists as l,createLogger as u,createUserMessage as d,estimateContextTokensFromMessages as f,evaluatePermission as p,findInvalidPermissionPatterns as m,findPermissionPatternWarnings as h,getModelContextWindow as g,getProviderCapabilities as _,getToolPermissionProfile as v,isAbortFailure as y,isEnforcing as b,isModelEffort as x,isToolDeniedOutright as ee,matchesAnyPattern as te,messageToHistoryEntry as ne,peerDriverOf as re,printablePeerDriver as ie,projectPermissionPolicy as ae,readModelFallbackNotice as oe,registerToolPermissionProfile as se,requiresFreshApproval as ce,runHooks as S,traceEnvFor as le,wasToolResultAdmitted as ue}from"@robota-sdk/agent-core";import{dirname as de,isAbsolute as fe,join as C,relative as pe,resolve as me,win32 as he}from"node:path";import{createHash as ge,randomBytes as _e,randomUUID as ve}from"node:crypto";import{homedir as ye,tmpdir as be}from"node:os";import{appendFileSync as xe,chmodSync as Se,closeSync as Ce,constants as w,existsSync as we,fstatSync as Te,fsyncSync as Ee,linkSync as De,lstatSync as Oe,mkdtempSync as ke,openSync as Ae,readFileSync as je,readSync as Me,readdirSync as Ne,realpathSync as Pe,rmdirSync as Fe,unlinkSync as Ie,writeFileSync as Le}from"node:fs";import{OWNER_ONLY_FILE_MODE as Re,ensureOwnerOnlyDirectory as ze,tightenExistingFile as Be,writeOwnerOnlyFile as Ve}from"@robota-sdk/agent-core/node";import{StableFileAuthorityError as He,createStableRootedFileReader as Ue}from"@robota-sdk/agent-file-authority";import{existsSync as We,readFileSync as Ge,readdirSync as Ke,unlinkSync as qe}from"fs";import{resolve as Je,sep as Ye}from"path";function Xe(e){if(typeof e!=`string`||e.length===0)throw Error("Session requires `cwd`: the absolute path this session executes in (ARCH-010). It feeds every hook input, CLAUDE_PROJECT_DIR, the permission root and the persisted record. Pass `process.cwd()` explicitly if that is genuinely what you mean.");if(!fe(e))throw Error(`Session requires an ABSOLUTE \`cwd\`; got ${JSON.stringify(e)} (ARCH-010). A relative root is resolved against the process directory downstream, which is the ambient value this field exists to replace. Resolve it at your composition root.`);return e}var Ze=class extends Error{recoverable=!0;constructor(e){super(e),this.name=`SessionBusyError`}},Qe=class{controller=null;claim(){if(this.controller!==null)throw new Ze(`This session is already running a turn. A session is a single conversation: await the turn in flight, abort() it and await it, or use a separate session for concurrent work.`);return this.controller=new AbortController,this.controller}release(e){this.controller===e&&(this.controller=null)}abort(){this.controller?.abort()}isRunning(){return this.controller!==null}},$e=class{cwd;constructor(e){this.cwd=Xe(e)}turnClaim=new Qe;permissionModeGuards=new Set;getPermissionMode(){return this.permissionMode}setPermissionMode(e){for(let t of this.permissionModeGuards)t(e);this.permissionMode=e}addPermissionModeGuard(e){return this.permissionModeGuards.add(e),()=>this.permissionModeGuards.delete(e)}getActivePresetId(){return this.activePresetId}setActivePresetId(e){this.activePresetId=e}getParallelSubagentsEnabled(){return this.parallelSubagentsEnabled}setParallelSubagentsEnabled(e){this.parallelSubagentsEnabled=e}getSessionId(){return this.sessionId}getCwd(){return this.cwd}getSystemMessage(){return this.systemMessage}updateSystemMessage(e){this.systemMessage=e,this.agent.updateSystemPrompt(e)}async applyModelOptions(e){await this.agent.ensureReady();let t=e.model??this.model;this.agent.setModel({provider:this.aiProvider.name,model:t,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}}),this.model=t}getModelEffort(){let e=this.agent.getModel;if(e===void 0)return`auto`;try{return e.call(this.agent).effort??`auto`}catch(e){if(e instanceof Error&&/disposed/i.test(e.message))return`auto`;throw e}}async withScopedModelEffort(e,t){let n=this.getModelEffort();await this.applyModelOptions({effort:e});try{return await t()}finally{await this.applyModelOptions({effort:n})}}async applyAgentName(e){await this.agent.updateConfiguration({name:e})}getToolSchemas(){return this.toolSchemas}getMessageCount(){return this.messageCount}applyPresetToolLists(e){this.permissionEnforcer.applyPresetToolLists(e)}getPermissionRules(){let e=this.permissionEnforcer.currentPermissionRules();return{allow:[...e.allow],deny:[...e.deny],ask:[...e.ask]}}getSessionAllowedTools(){return this.permissionEnforcer.getSessionAllowedTools()}checkToolPermission(e,t,n){return this.permissionEnforcer.checkDelegatedToolCall(e,t,n)}requireClassifierFor(e){if(e===`auto`&&!this.permissionEnforcer.hasPermissionClassifier())throw Error(`Auto mode is unavailable: this session has no permission classifier.`)}retryPermissionDenial(e){return this.permissionEnforcer.allowRetryOfDenial(e)}getRecentPermissionDenials(){return this.permissionEnforcer.getRecentDenials()}clearSessionAllowedTools(){this.permissionEnforcer.clearSessionAllowedTools()}abort(){this.turnClaim.abort()}isRunning(){return this.turnClaim.isRunning()}getContextState(){return this.contextTracker.getContextState()}syncContextFromHistory(){this.contextTracker.updateFromHistory(this.agent.getHistory())}getAutoCompactThreshold(){return this.contextTracker.getAutoCompactThreshold()}setAutoCompactThreshold(e){this.contextTracker.setAutoCompactThreshold(e)}getHistory(){return this.agent.getHistory()}getFullHistory(){return this.agent.getFullHistory()}getSessionTokenUsage(){let e=0,t=0,n=!1;for(let r of this.getFullHistory()){if(r.category!==`event`||r.type!==`usage-summary`)continue;let i=r.data;e+=i?.promptTokens??0,t+=i?.completionTokens??0,n=!0}return n?{inputTokens:e,outputTokens:t}:void 0}getModelId(){return this.model}getOfferedToolSchemas(){return this.agent.getOfferedToolSchemas()}getProvider(){return this.aiProvider}getProviderId(){return this.aiProvider.name}addHistoryEntry(e){this.agent.addHistoryEntry(e)}injectMessage(e,t,n){this.agent.injectMessage(e,t,n)}injectRawMessage(e){this.agent.injectRawMessage(e)}clearHistory(){this.agent.clearHistory(),this.contextTracker.reset()}};function T(e){return JSON.stringify(typeof e==`string`?e:e??``)}function et(e){let t=re(e);return t?`user [from ${JSON.stringify(ie(t))}]`:`user`}function tt(e){switch(e.role){case`user`:return[`${et(e)}: ${T(e.content)}`];case`assistant`:{let t=[];e.content!==null&&e.content!==``&&t.push(`assistant: ${T(e.content)}`);for(let n of e.toolCalls??[])t.push(`assistant tool call ${JSON.stringify(n.function.name)} [${JSON.stringify(n.id)}]: ${T(n.function.arguments)}`);return t.length>0?t:[`assistant: ""`]}case`tool`:return[`tool result${e.name?` ${JSON.stringify(e.name)}`:``} [${JSON.stringify(e.toolCallId)}]: ${T(e.content)}`];case`system`:return[`system: ${T(e.content)}`]}}function nt(e){return e.map(e=>tt(e).join(`
2
- `))}var rt=class extends Error{constructor(e){super(e),this.name=`CompactionError`}};const it=[`Summarize the following conversation concisely, preserving:`,`- User's original requests and goals`,`- Key decisions, conclusions, and important state`,`- Identifiers, names, and references needed to continue the work`,`- Current task status and next steps`,`Drop verbose intermediate outputs and exploratory work that didn't lead to results.`].join(`
3
- `);var at=class{sessionId;cwd;model;hooks;compactInstructions;basePrompt;hookTypeExecutors;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.model=e.model,this.hooks=e.hooks,this.compactInstructions=e.compactInstructions,this.basePrompt=e.basePrompt,this.hookTypeExecutors=e.hookTypeExecutors}async compact(e,t,n,r,i=`manual`,a){if(r?.throwIfAborted(),t.length===0)throw new rt(`Compaction was asked to summarise an empty history; conversation history preserved untouched`);let o={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:i};await S(this.hooks,`PreCompact`,o,this.hookTypeExecutors,a);let s=this.buildCompactionPrompt(t,n),c=await e.chat([{id:ve(),role:`user`,content:s,state:`complete`,timestamp:new Date}],{model:this.model,toolChoice:`none`,preserveContextWindow:!0,...r===void 0?{}:{signal:r}});if(r?.throwIfAborted(),typeof c.content!=`string`||c.content.trim()===``)throw new rt(`Compaction produced an invalid summary (provider=${e.name}, content type=${typeof c.content}); conversation history preserved untouched`);return c.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``,r=n?`\nAdditional focus:\n${n}\n`:``,i=nt(e).join(`
4
- `);return[this.basePrompt??it,r,``,`Conversation:`,i].join(`
5
- `)}};const ot=.835;var st=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(e,t,n){this.contextMaxTokens=t??g(e),this.autoCompactThreshold=ct(n)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold!==!1&&this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=ct(e)}updateFromHistory(e){this.contextUsedTokens=f(e).usedTokens}reset(){this.contextUsedTokens=0}};function ct(e){if(e===void 0)return ot;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 lt(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 ut(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 dt(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.handler?()=>e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return n===void 0?t:ut(await lt(n(),e.signal))}const ft=3,pt=20;function mt(e,t){return`${e}\u0000${JSON.stringify(t)}`}var ht=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(mt(e,t))}takeRetry(e,t){return this.retries.delete(mt(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 gt(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=gt(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 vt(e,t){let n=v(e).argument;if(n===void 0)return e;let r=t[n.key];if(typeof r!=`string`||r===``)return e;let i=_t(n.kind,r);return i===void 0?e:`${e}(${i})`}function E(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function yt(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}),E(`threw`,r)}const bt=E(`denied`,`Permission denied. The user did not approve this action.`),xt=u(`ToolHookHelpers`);function St(e){if(ue(e)||typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function Ct(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 wt(e,t,n,r){let i=await S(e,`PreToolUse`,t,n,r);if(i.blocked){let e=i.reason??`Blocked by hook`;return E(`hook-blocked`,e,{blocked:!0,reason:e})}if(b(`PreToolUse`)){let e=i.errors,t=e?.[0],n=i.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return E(`hook-blocked`,i,{blocked:!0,reason:i})}if(r!==``)return E(`hook-blocked`,r,{blocked:!0,reason:r})}return null}function Tt(e,t,n,r,i){S(e,`PostToolUse`,{...t,hook_event_name:`PostToolUse`,tool_output:typeof n.data==`string`?n.data:JSON.stringify(n.data)},r,i).catch(e=>xt.warn(`hook failed`,{error:e}))}function Et(e,t){let n=v(e).argument?.key;if(n===void 0)return;let r=t[n];if(typeof r==`string`)return r.length>200?`${r.slice(0,200)}…`:r}var Dt=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=Et(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]}};function Ot(e,t,n){let r=v(e).argument;if(r===void 0||r.kind!==`path`)return t;let i=t[r.key];return typeof i!=`string`||i===``||fe(i)?t:{...t,[r.key]:me(n,i)}}const kt=u(`ToolBodyTrace`);function At(e,t){try{e?.eventService?.emit(o.DECIDED,{timestamp:new Date,executionId:e.executionId,decidedAt:new Date().toISOString(),decision:t})}catch(e){kt.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function jt(e,t){let n=e.execute.bind(e),r=Object.create(e);return r.execute=async(r,i)=>{let o=r,s=`(unknown)`;try{s=e.getName(),o=Ot(s,r,t.cwd),t.log(`tool_call`,{tool:s,args:o});let c=Ct(t.sessionId,t.cwd,s,o,t.getPermissionMode(),t.transcriptPath),l=await wt(t.config.hooks,c,t.hookTypeExecutors,i?.hookTraceEnv);if(l)return t.log(`tool_blocked`,{tool:s,reason:`hook`}),At(i,`hook-blocked`),l;let u=await t.checkPermission(s,o,i?.signal,i?.permissionInteraction,i?.hookTraceEnv);if(u!==!0)return t.log(`tool_denied`,{tool:s,reason:`permission`}),At(i,`denied`),t.onToolExecution?.({type:`end`,toolName:s,toolArgs:o,success:!1,denied:!0,executionId:i?.executionId}),typeof u==`object`?E(`denied`,u.message):bt;At(i,`allowed`),i?.signal?.throwIfAborted(),t.onToolExecution?.({type:`start`,toolName:s,toolArgs:o,executionId:i?.executionId});let d=Date.now(),f=`failure`,p;try{p=await n(o,i),f=i?.signal?.aborted?`interrupted`:p.success?`success`:`failure`}catch(e){throw f=i?.signal?.aborted||y(e)?`interrupted`:`failure`,e}finally{try{i?.eventService?.emit(a.COMPLETED,{timestamp:new Date,executionId:i.executionId,startedAt:new Date(d).toISOString(),endedAt:new Date(Math.max(Date.now(),d)).toISOString(),outcome:f,...typeof i.toolBodyId==`string`?{toolBodyId:i.toolBodyId}:{}})}catch(e){kt.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let m=St(p);m!==p&&typeof p.data==`string`&&t.terminal.writeLine(` ⚠ Output truncated: ${p.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),t.onToolExecution?.({type:`end`,toolName:s,toolArgs:o,success:m.success,toolResultData:typeof m.data==`string`?m.data:JSON.stringify(m.data),executionId:i?.executionId});let h=typeof m.data==`string`?m.data.length:JSON.stringify(m.data)?.length??0;return t.log(`tool_result`,{tool:s,success:m.success,dataChars:h,truncated:m!==p}),Tt(t.config.hooks,c,m,t.hookTypeExecutors,i?.hookTraceEnv),m}catch(e){return yt(e,t.onToolExecution,{toolName:s,toolArgs:o,executionId:i?.executionId})}},r.setEventService=t=>{e.setEventService(t)},r}function Mt(e){let t=e,n=[];for(;;)try{let e=Pe(t);return n.length===0?e:me(e,...n.reverse())}catch{let r=de(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Nt(e,t){let n=pe(e,t);return n===``||!n.startsWith(`..`)&&!fe(n)}function Pt(e){return(t,n)=>{let r=Mt(e),i=Mt(me(t??r,n));return Nt(r,i)?i:void 0}}function Ft(e){let t=[...m(e.allow,`allow`),...m(e.restrictive,`deny`)];if(t.length===0)return;let n=t.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${n}. Fix the pattern where it is configured (issue #2428).`)}var It=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;homeDirectory;resolveInWorkspace;commandSandbox;denials=new Dt;peerTurn=!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]},Ft(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??ye(),this.resolveInWorkspace=Pt(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new ht(e.permissionClassifier))}beginTurn(e){this.peerTurn=e}endTurn(){this.peerTurn=!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){return!this.peerTurn&&v(e).repliesToPeer===!0?!1:!ee(e,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(e){for(let t of e){let e=t.schema;if(e===void 0)continue;let n=e.parameters?.properties??{};se(e.name,{parameters:Object.keys(n)})}let t=this.configuredRules();Ft(t);for(let{pattern:e,reason:n}of h(t.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${e}" ${n}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i)=>this.decidePermission(e,t,n,r,i)};return e.map(e=>jt(e,t))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}getRecentDenials(){return this.denials.list()}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}currentPermissionRules(){return{allow:[...this.config.permissions.allow],deny:[...this.config.permissions.deny],ask:[...this.config.permissions.ask??[]]}}applyPresetToolLists(e){let t=l(this.presetFreeRules,e);this.config.permissions.allow=t.allow,this.config.permissions.deny=t.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=Ct(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath);return await wt(this.config.hooks,r,this.hookTypeExecutors)?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1})===!0}async decidePermission(e,t,n,r=`interactive`,i,a={}){let o=this.permissionPolicy===void 0?void 0:ae(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),s=this.getPermissionMode(),l=[...this.config.permissions.allow,...o?.allow??[]],u={allow:s===`auto`?c(l):l,deny:[...this.config.permissions.deny,...o?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory},f=p(e,t,s,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:a.sandboxed!==!1&&this.sandboxAutoApproves(e,t),...o?.ceiling===void 0?{}:{ceiling:o.ceiling},askAll:o?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(e,t,f,i),f===`auto`)return!0;if(f===`deny`)return this.denials.record(e,t,`policy`),!1;let m=ce(e,t,u,d);return s===`auto`&&this.autoMode!==void 0&&!m&&o?.askAll!==!0?this.decideInAutoMode(this.autoMode,e,t,n,r,i,a):this.promptForApproval(e,t,n,r,m)}async decideInAutoMode(e,t,n,r,i,a,o){if(e.takeRetry(t,n)||te(t,n,c([...this.sessionAllowedTools])))return!0;if(e.isPaused()){let a=await this.promptForApproval(t,n,r,i,!0);return a&&e.resume(),a}let s=await e.judge({toolName:t,toolArgs:n,cwd:this.cwd},r);return r?.aborted===!0?!1:this.getPermissionMode()===`auto`?s.kind===`allow`?!0:(this.denials.record(t,n,`classifier`,s.reason),{message:s.message}):this.decidePermission(t,n,r,i,a,o)}async promptForApproval(e,t,n,r=`interactive`,i=!1){let a=vt(e,t),o=n?.aborted===!0,s=r===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),c=await dt({toolName:e,alreadyAllowed:!i&&te(e,t,[...this.sessionAllowedTools]),...r===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...r===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:t,...n?{signal:n}:{}});if(!c.allowed&&!o&&this.denials.record(e,t,s?`user`:`no-approver`),i)return c.allowed;if(c.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(a)}return c.rememberForSession&&this.sessionAllowedTools.add(a),c.allowed}firePermissionDecisionHook(e,t,n,r){let i=this.getPermissionMode();S(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:e,tool_input:t,permission_decision:n,...i!==void 0&&{permission_mode:i},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,r).catch(()=>void 0)}sandboxAutoApproves(e,t){if(this.commandSandbox===void 0)return!1;let n=v(e).argument;if(n?.kind!==`command`)return!1;let r=t[n.key];return typeof r==`string`&&this.commandSandbox.autoApproves(e,r)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function Lt(e,t,n,r,i){return new It({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 Rt(e,t,n,r){return{contextTracker:new st(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new at({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function zt(e,t,n,r,a,o,s){let c=t.wrapTools(n);return new i({name:e.agentName??`agent`,aiProviders:[r],defaultModel:{provider:r.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,isToolVisible:e=>t.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}})}const Bt=u(`SessionHistoryOps`);function Vt(e,t){return{...e,...t}}async function Ht(e,t,n){n?.throwIfAborted();let r=t.agent.getHistory(),i=r.filter(e=>e.role!==`system`);if(i.length===0)return;t.contextTracker.updateFromHistory(r);let a=t.contextTracker.getContextState(),o=await t.compactionOrchestrator.compact(t.aiProvider,i,e,n,t.trigger,t.hookTraceEnv);t.agent.clearHistory(),t.agent.injectMessage(`system`,t.systemMessage),t.agent.injectMessage(`assistant`,`[Context Summary]\n${o}`),t.contextTracker.updateFromHistory(t.agent.getHistory());let s={session_id:t.sessionId,cwd:t.cwd,hook_event_name:`PostCompact`,trigger:t.trigger,compact_summary:o};S(t.hooks,`PostCompact`,s,t.hookTypeExecutors,t.hookTraceEnv).catch(e=>Bt.warn(`hook failed`,{error:e}));let c=t.contextTracker.getContextState();t.log(`context_compact`,{trigger:t.trigger,before:a,after:c}),t.onCompactEventCallback?.({trigger:t.trigger,before:a,after:c}),t.onCompactCallback&&t.onCompactCallback(o)}function Ut(e){let t=e.agent.getHistory(),n=new Date().toISOString(),r=e.sessionStore.load(e.sessionId);if(r.status!==`valid`&&r.status!==`missing`)return r;let i=r.status===`valid`?r.record:void 0,a={...i,id:e.sessionId,name:i?.name,cwd:e.cwd,createdAt:i?.createdAt??n,updatedAt:n,messages:t,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};return e.sessionStore.save(a),{status:`valid`,record:a}}const Wt=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Gt(){return`session_${ve()}`}function Kt(e){return e.length>0&&e.length<=128&&Wt.test(e)}function qt(e){if(!Kt(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 Jt=u(`SessionLifecycle`);function Yt(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function Xt(e,t,n,r,i,a,o){S(n,`SessionStart`,{session_id:e,cwd:t,hook_event_name:`SessionStart`,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},r).then(e=>{e.stdout&&i(e.stdout)}).catch(e=>Jt.warn(`SessionStart hook failed`,{error:e}))}async function Zt(e,t,n,r,i,a,o){await S(r,`SessionEnd`,{session_id:e,cwd:t,hook_event_name:`SessionEnd`,reason:n,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},i)}function Qt(e){return{...e?.ephemeralSystemContext!==void 0&&{ephemeralSystemContext:e.ephemeralSystemContext},...e?.driverId!==void 0&&{driverId:e.driverId},...e?.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e?.traceContext!==void 0&&{traceContext:e.traceContext},...e?.peerTurn===!0&&{withholdHostedTools:!0}}}const $t=`unknown_tool`;function en(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function tn(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){nn(e,n);return}t===`tool_execution_result`&&rn(e,n)}}function nn(e,t){let n=D(t.toolName),r=D(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:an(t.parameters)}))}function rn(e,t){let n=D(t.toolName),r=D(t.toolCallId);if(!n||!r)return;let i=on(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===$t))return;e.unknownToolCallIds.delete(r);let a=D(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:$t,requestedTool:D(i?.requestedTool)??n,availableTools:sn(i?.availableTools)})})}function an(e){let t=on(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 D(e){return typeof e==`string`&&e.length>0?e:void 0}function on(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function sn(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const cn=u(`SessionRun`);function ln(e,t,n,r){let i=typeof n.model==`string`?n.model:e.model,a=typeof n.provider==`string`?n.provider:e.aiProvider.name,o=n.effort,s=typeof o==`string`&&x(o)?o:e.effort??(typeof e.agent.getModel==`function`?e.agent.getModel().effort:void 0)??`high`,c=typeof n.round==`number`?n.round:void 0;S(e.hooks,t,{session_id:e.sessionId,cwd:e.cwd,hook_event_name:t,model:i,provider:a,effort:s,...c!==void 0&&{round:c},...e.permissionMode!==void 0&&{permission_mode:e.permissionMode},...e.transcriptPath!==void 0&&{transcript_path:e.transcriptPath},env:{CLAUDE_PROJECT_DIR:e.cwd,CLAUDE_SESSION_ID:e.sessionId}},e.hookTypeExecutors,r).catch(e=>cn.warn(`hook failed`,{error:e}))}async function un(t,i,a,o,s){let c=s?.traceContext,l=c?le(`hooks`,c,c.parentSpanId):void 0;if(a.contextTracker.updateFromHistory(a.agent.getHistory()),a.contextTracker.shouldAutoCompact()){let e=a.aiProvider,t=e.onTextDelta;e.onTextDelta=void 0;try{await(l?a.compact(o,l):a.compact(o))}finally{e.onTextDelta=t}}a.log(`user`,{content:t});let u=await S(a.hooks,`UserPromptSubmit`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`UserPromptSubmit`,user_message:i??t,prompt:i??t,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l),f=[a.sessionStartStdout,u.stdout].filter(Boolean).join(`
6
- `),p=f?`<system-reminder>\n${f}\n</system-reminder>\n${t}`:t;a.clearSessionStartStdout();let m=a.agent.getHistory(),h=JSON.stringify(m),g=_(a.aiProvider);a.log(`pre_run`,{historyLength:m.length,historyChars:h.length,historyEstTokens:Math.ceil(h.length/e),input:p,history:m,model:a.model,provider:a.aiProvider.name,maxTokens:a.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:g.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:g.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:g.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:g.nativeWebTools.webFetch.enabled}),a.contextTracker.updateFromHistory([...m,d(p)]),a.onContextUpdate?.(a.contextTracker.getContextState());let v;try{let e=en({knownToolNames:a.knownToolNames??[],...a.onToolExecution&&{onToolExecution:a.onToolExecution}}),t=a.onTextDelta?e=>{a.log(`text_delta`,{delta:e}),a.onTextDelta?.(e)}:void 0,i={};if(v=await a.agent.run(p,{signal:o,maxExecutionRounds:a.maxTurns??0,...Qt(s),onExecutionEvent:(t,o)=>{if(t!==n.COMPLETED&&a.log(t,o),tn(e,t,o),t===`provider_request`){let e=o;i={model:e.model,provider:e.provider},ln(a,`PreModelCall`,e,l)}else if(t===`provider_response_normalized`)ln(a,`PostModelCall`,{...o,...i},l);else if(t===r.SWITCHED){let e=oe(o);e!==void 0&&(ln(a,`PostModelCall`,{round:o.round,model:e.from.model,provider:e.from.provider},l),a.emitProviderFallback?.(e))}else if(t===n.COMPLETED&&a.emitProviderCallCompleted){let e=o;Number.isSafeInteger(e.round)&&e.round>0&&typeof e.startedAt==`string`&&typeof e.endedAt==`string`&&(e.outcome===`success`||e.outcome===`failure`||e.outcome===`interrupted`)&&a.emitProviderCallCompleted({round:e.round,startedAt:e.startedAt,endedAt:e.endedAt,outcome:e.outcome,...typeof e.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(e.callId)&&{callId:e.callId},...(e.disposition===`invoked`||e.disposition===`cache-hit`||e.disposition===`preflight-refused`)&&{disposition:e.disposition},...typeof e.providerId==`string`&&e.providerId.length>0&&e.providerId.length<=128&&[...e.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:e.providerId},...typeof e.modelId==`string`&&e.modelId.length>0&&e.modelId.length<=128&&[...e.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:e.modelId},...(e.usageProvenance===`complete`||e.usageProvenance===`partial`||e.usageProvenance===`absent`)&&{usageProvenance:e.usageProvenance},...e.usageProvenance===`complete`&&typeof e.promptTokens==`number`&&Number.isSafeInteger(e.promptTokens)&&e.promptTokens>=0&&typeof e.completionTokens==`number`&&Number.isSafeInteger(e.completionTokens)&&e.completionTokens>=0&&typeof e.totalTokens==`number`&&Number.isSafeInteger(e.totalTokens)&&e.totalTokens===e.promptTokens+e.completionTokens&&{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens},...e.disposition===`invoked`&&typeof e.providerRequestId==`string`&&{providerRequestId:e.providerRequestId}})}t===`assistant_message_committed`&&(a.contextTracker.updateFromHistory(a.agent.getHistory()),a.onContextUpdate?.(a.contextTracker.getContextState()))},...t&&{onTextDelta:t}}),o.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){throw a.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:a.agent.getHistory().length}),S(a.hooks,`StopFailure`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l).catch(e=>cn.warn(`hook failed`,{error:e})),e}let y=a.agent.getHistory(),b=y.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});a.log(`assistant`,{content:v,historyLength:y.length,estimatedChars:JSON.stringify(y).length,history:y,historyStructure:b}),a.contextTracker.updateFromHistory(y);let x=a.contextTracker.getContextState();return a.onContextUpdate?.(x),a.log(`context`,{maxTokens:x.maxTokens,usedTokens:x.usedTokens,usedPercentage:x.usedPercentage,remainingPercentage:x.remainingPercentage}),S(a.hooks,`Stop`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`Stop`,response:v.substring(0,500),last_assistant_message:v,stop_hook_active:!1,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l).catch(e=>cn.warn(`hook failed`,{error:e})),a.getSessionStore()&&a.persistSession(),v}var dn=class{agent;claim;sessionId;execution=null;constructor(e,t,n){this.agent=e,this.claim=t,this.sessionId=n}async invoke(e,t,n){let r=this.claim.claim(),i=fn(r,n);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:ve(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:`deny`}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}async drain(){await this.execution}};function fn(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var pn=class extends $e{agent;eventService=new t;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.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??Gt(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?s[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,Yt(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=Lt(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Rt(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=zt(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new dn(this.agent,this.turnClaim,this.sessionId),Xt(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);let r=this.turnClaim.claim(),i=fn(r,n?.signal),{signal:a}=r;this.permissionEnforcer.beginTurn(n?.peerTurn===!0);try{a.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let r=await un(e,t,this.buildRunContext(),a,n);return this.messageCount+=1,r}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}addTools(e){return 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.runtimeTools.invoke(e,t,n?.signal)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&Ut({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,agent:this.agent,getFullHistory:()=>this.getFullHistory()})}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()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>Zt(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){this.agent.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`,n){await this.compactWith(e,t,n)}async compactWith(e,t,n,r){let i={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{}};await Ht(e,Vt(this.buildRunContext(),i),n)}buildRunContext(){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)=>this.compactWith(void 0,`auto`,e,t),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(n.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(r.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 O(e,t){return e.length===0?t:`${e}.${t}`}function k(e,t){return`${e}[${t}]`}function A(e,t,n){e.push({path:t,message:n})}function j(e){if(e===null)return`null`;if(Array.isArray(e))return`an array`;if(e instanceof Date)return`a Date`;switch(typeof e){case`undefined`:return`nothing`;case`string`:return`a string`;case`number`:return`a number`;case`boolean`:return`a boolean`;case`object`:return`an object`;default:return`a ${typeof e}`}}function M(e,t,n){n!==void 0&&(e[t]=n)}function N(e,t,n,r){if(e!==void 0)return r(e,t,n)}function P(e,t,n){if(typeof e==`string`)return e;A(n,t,`expected a string, received ${j(e)}`)}function F(e,t,n){if(typeof e==`number`&&Number.isFinite(e))return e;A(n,t,`expected a finite number, received ${j(e)}`)}function I(e,t,n){if(typeof e==`number`&&Number.isInteger(e))return e;A(n,t,`expected an integer, received ${j(e)}`)}function L(e,t,n){if(typeof e==`boolean`)return e;A(n,t,`expected a boolean, received ${j(e)}`)}function R(e,t,n,r){if(typeof e==`string`&&t.includes(e))return e;A(r,n,`expected one of ${t.join(` | `)}, received ${j(e)}`)}function z(e,t,n){if(typeof e!=`string`){A(n,t,`expected an ISO-8601 timestamp string, received ${j(e)}`);return}if(Number.isNaN(Date.parse(e))){A(n,t,`expected a timestamp a date can be parsed from`);return}return e}function mn(e,t,n){if(e instanceof Date){if(Number.isNaN(e.getTime())){A(n,t,`expected a valid Date, received an invalid one`);return}return e}if(typeof e==`string`&&!Number.isNaN(Date.parse(e)))return new Date(e);A(n,t,`expected a Date or an ISO-8601 timestamp string, received ${j(e)}`)}function B(e,t,n,r){if(!Array.isArray(e)){A(n,t,`expected an array, received ${j(e)}`);return}let i=[];return e.forEach((e,a)=>{let o=r(e,k(t,a),n);o!==void 0&&i.push(o)}),i}function hn(e,t,n){return B(e,t,n,P)}function V(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){A(n,t,`expected an object, received ${j(e)}`);return}let i=e,a=new Set(r);for(let e of Object.keys(i))a.has(e)||A(n,O(t,e),`unknown key; the record contract does not declare it`);return i}function H(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){A(n,t,`expected an object, received ${j(e)}`);return}let i={};for(let[a,o]of Object.entries(e)){let e=r(o,O(t,a),n);e!==void 0&&(i[a]=e)}return i}function gn(e,t,n){if(e===null||e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){let r=[];return e.forEach((e,i)=>{let a=gn(e,k(t,i),n);a!==void 0&&r.push(a)}),r}if(typeof e==`object`)return H(e,t,n,gn);A(n,t,`expected a JSON-compatible value, received ${j(e)}`)}function _n(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;A(n,t,`expected a string, number or boolean, received ${j(e)}`)}const vn=[`complete`,`interrupted`],yn=[`id`,`timestamp`,`state`,`metadata`,`role`,`content`,`parts`],bn={user:[...yn,`name`],assistant:[...yn,`toolCalls`],system:[...yn,`name`],tool:[...yn,`toolCallId`,`name`]};function xn(e,t,n){if(e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.every(e=>typeof e==`string`)||e.every(e=>typeof e==`number`))return e;A(n,t,`expected an array of only strings or only numbers`);return}if(typeof e==`object`&&e){let r={};for(let[i,a]of Object.entries(e)){if(typeof a!=`number`){A(n,O(t,i),`expected a number, received ${j(a)}`);continue}r[i]=a}return r}A(n,t,`expected a metadata value, received ${j(e)}`)}function Sn(e,t,n){return H(e,t,n,xn)}function Cn(e,t,n){let r=R(e?.type,[`text`,`image_inline`,`image_uri`],O(t,`type`),n);if(r===void 0)return;if(r===`text`){let r=V(e,t,n,[`type`,`text`]);if(r===void 0)return;let i=P(r.text,O(t,`text`),n);return i===void 0?void 0:{type:`text`,text:i}}if(r===`image_inline`){let r=V(e,t,n,[`type`,`mimeType`,`data`]);if(r===void 0)return;let i=P(r.mimeType,O(t,`mimeType`),n),a=P(r.data,O(t,`data`),n);return i===void 0||a===void 0?void 0:{type:`image_inline`,mimeType:i,data:a}}let i=V(e,t,n,[`type`,`uri`,`mimeType`]);if(i===void 0)return;let a=P(i.uri,O(t,`uri`),n);if(a===void 0)return;let o={type:`image_uri`,uri:a};return M(o,`mimeType`,N(i.mimeType,O(t,`mimeType`),n,P)),o}function wn(e,t,n){let r=V(e,t,n,[`id`,`type`,`function`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=R(r.type,[`function`],O(t,`type`),n),o=O(t,`function`),s=V(r.function,o,n,[`name`,`arguments`]),c=s===void 0?void 0:P(s.name,O(o,`name`),n),l=s===void 0?void 0:P(s.arguments,O(o,`arguments`),n);if(i!==void 0&&a!==void 0&&c!==void 0&&l!==void 0)return{id:i,type:a,function:{name:c,arguments:l}}}function Tn(e,t,n){let r=P(e.id,O(t,`id`),n),i=mn(e.timestamp,O(t,`timestamp`),n),a=R(e.state,vn,O(t,`state`),n);if(r!==void 0&&i!==void 0&&a!==void 0)return{id:r,timestamp:i,state:a}}function En(e,t,n,r){M(e,`metadata`,N(t.metadata,O(n,`metadata`),r,Sn)),M(e,`parts`,N(t.parts,O(n,`parts`),r,(e,t,n)=>B(e,t,n,Cn)))}function U(e,t,n){let r=R(e?.role,[`user`,`assistant`,`system`,`tool`],O(t,`role`),n);if(r===void 0)return;let i=V(e,t,n,bn[r]);if(i===void 0)return;let a=Tn(i,t,n);if(a===void 0)return;let o=O(t,`content`);if(r===`assistant`){let e=i.content===null?null:P(i.content,o,n);if(e===void 0)return;let s={...a,role:r,content:e};return En(s,i,t,n),M(s,`toolCalls`,N(i.toolCalls,O(t,`toolCalls`),n,(e,t,n)=>B(e,t,n,wn))),s}let s=P(i.content,o,n);if(s===void 0)return;if(r===`tool`){let e=P(i.toolCallId,O(t,`toolCallId`),n);if(e===void 0)return;let o={...a,role:r,content:s,toolCallId:e};return En(o,i,t,n),M(o,`name`,N(i.name,O(t,`name`),n,P)),o}let c={...a,role:r,content:s};return En(c,i,t,n),M(c,`name`,N(i.name,O(t,`name`),n,P)),c}function Dn(e,t,n){let r=V(e,t,n,[`id`,`timestamp`,`category`,`type`,`data`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=mn(r.timestamp,O(t,`timestamp`),n),o=P(r.category,O(t,`category`),n),s=P(r.type,O(t,`type`),n);if(i===void 0||a===void 0||o===void 0||s===void 0)return;let c={id:i,timestamp:a,category:o,type:s};return M(c,`data`,N(r.data,O(t,`data`),n,gn)),c}const On=[`agent`,`process`,`scheduled`,`tool-invocation`],kn=[`foreground`,`background`],An=[`none`,`worktree`],jn=[`queued`,`running`,`waiting_permission`,`sleeping`,`paused`,`completed`,`failed`,`cancelled`],Mn=[`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`],Nn=[`validation`,`capacity`,`permission`,`timeout`,`runner`,`crash`,`provider`,`process`];function Pn(e,t,n){return H(e,t,n,_n)}function Fn(e,t,n){return H(e,t,n,P)}function In(e,t,n){let r=V(e,t,n,[`category`,`message`,`recoverable`]);if(r===void 0)return;let i=R(r.category,Nn,O(t,`category`),n),a=P(r.message,O(t,`message`),n),o=L(r.recoverable,O(t,`recoverable`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{category:i,message:a,recoverable:o}}function Ln(e,t,n){let r=V(e,t,n,[`promptTokens`,`completionTokens`,`totalTokens`]);if(r===void 0)return;let i=I(r.promptTokens,O(t,`promptTokens`),n),a=I(r.completionTokens,O(t,`completionTokens`),n),o=I(r.totalTokens,O(t,`totalTokens`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{promptTokens:i,completionTokens:a,totalTokens:o}}function Rn(e,t,n){let r=V(e,t,n,[`taskId`,`kind`,`output`,`exitCode`,`signalCode`,`metadata`,`usage`]);if(r===void 0)return;let i=P(r.taskId,O(t,`taskId`),n),a=R(r.kind,On,O(t,`kind`),n),o=P(r.output,O(t,`output`),n);if(i===void 0||a===void 0||o===void 0)return;let s=N(r.exitCode,O(t,`exitCode`),n,I),c=N(r.signalCode,O(t,`signalCode`),n,P),l=N(r.metadata,O(t,`metadata`),n,Pn),u=N(r.usage,O(t,`usage`),n,Ln);switch(a!==`process`&&s!==void 0&&A(n,O(t,`exitCode`),`must not be set for a '${a}' result`),a!==`process`&&c!==void 0&&A(n,O(t,`signalCode`),`must not be set for a '${a}' result`),a!==`agent`&&u!==void 0&&A(n,O(t,`usage`),`must not be set for a '${a}' result`),a){case`process`:{let e={taskId:i,kind:a,output:o};return M(e,`exitCode`,s),M(e,`signalCode`,c),M(e,`metadata`,l),e}case`agent`:{let e={taskId:i,kind:a,output:o};return M(e,`metadata`,l),M(e,`usage`,u),e}case`scheduled`:{let e={taskId:i,kind:a,output:o};return M(e,`metadata`,l),e}case`tool-invocation`:{let e={taskId:i,kind:a,output:o};return M(e,`metadata`,l),e}}}function zn(e,t,n){let r=V(e,t,n,[`cronExpression`,`agentInstruction`,`command`,`shell`,`env`]);if(r===void 0)return;let i=P(r.cronExpression,O(t,`cronExpression`),n);if(i===void 0)return;let a={cronExpression:i};for(let e of[`agentInstruction`,`command`,`shell`])M(a,e,N(r[e],O(t,e),n,P));return M(a,`env`,N(r.env,O(t,`env`),n,Fn)),a}const Bn=[`detached`,`wait_all`,`wait_any`,`manual`],Vn=[`running`,`completed`],Hn=[`background_job_group_created`,`background_job_group_updated`,`background_job_group_completed`];function Un(e,t,n){let r=V(e,t,n,[`taskId`,`label`,`status`,`summary`,`outputRef`,`error`,`startedAt`,`completedAt`]);if(r===void 0)return;let i=P(r.taskId,O(t,`taskId`),n),a=P(r.label,O(t,`label`),n),o=R(r.status,jn,O(t,`status`),n);if(i===void 0||a===void 0||o===void 0)return;let s={taskId:i,label:a,status:o};for(let e of[`summary`,`outputRef`])M(s,e,N(r[e],O(t,e),n,P));for(let e of[`startedAt`,`completedAt`])M(s,e,N(r[e],O(t,e),n,z));return M(s,`error`,N(r.error,O(t,`error`),n,In)),s}function Wn(e,t,n){let r=V(e,t,n,[`id`,`parentSessionId`,`waitPolicy`,`taskIds`,`status`,`createdAt`,`updatedAt`,`label`,`completedAt`,`results`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.parentSessionId,O(t,`parentSessionId`),n),o=R(r.waitPolicy,Bn,O(t,`waitPolicy`),n),s=hn(r.taskIds,O(t,`taskIds`),n),c=R(r.status,Vn,O(t,`status`),n),l=z(r.createdAt,O(t,`createdAt`),n),u=z(r.updatedAt,O(t,`updatedAt`),n),d=B(r.results,O(t,`results`),n,Un);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,parentSessionId:a,waitPolicy:o,taskIds:s,status:c,createdAt:l,updatedAt:u,results:d};return M(f,`label`,N(r.label,O(t,`label`),n,P)),M(f,`completedAt`,N(r.completedAt,O(t,`completedAt`),n,z)),f}function Gn(e,t,n){let r=R(e?.type,Hn,O(t,`type`),n);if(r===void 0)return;let i=V(e,t,n,[`type`,`group`]);if(i===void 0)return;let a=Wn(i.group,O(t,`group`),n);return a===void 0?void 0:{type:r,group:a}}const Kn=[`parentTaskId`,`currentAction`,`logPath`,`transcriptPath`],qn=[`agentType`,`resumeSessionId`,`promptPreview`,`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`],Jn=[`commandPreview`],Yn=[`startedAt`,`lastActivityAt`,`completedAt`],Xn=[`id`,`kind`,`label`,`status`,`mode`,`parentSessionId`,`depth`,`cwd`,`pid`,`updatedAt`,`isolation`,`unread`,`result`,`error`,`timeoutReason`,`schedule`,`nextFireAt`,`metadata`,...Kn,...qn,...Jn,...Yn];function Zn(e,t,n){let r=V(e,t,n,Xn);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=R(r.kind,On,O(t,`kind`),n),o=P(r.label,O(t,`label`),n),s=R(r.status,jn,O(t,`status`),n),c=R(r.mode,kn,O(t,`mode`),n),l=P(r.parentSessionId,O(t,`parentSessionId`),n),u=I(r.depth,O(t,`depth`),n),d=P(r.cwd,O(t,`cwd`),n),f=z(r.updatedAt,O(t,`updatedAt`),n),p=L(r.unread,O(t,`unread`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0||p===void 0)return;let m={id:i,label:o,status:s,mode:c,parentSessionId:l,depth:u,cwd:d,updatedAt:f,unread:p};for(let e of Kn)M(m,e,N(r[e],O(t,e),n,P));for(let e of Yn)M(m,e,N(r[e],O(t,e),n,z));M(m,`pid`,N(r.pid,O(t,`pid`),n,I)),M(m,`timeoutReason`,N(r.timeoutReason,O(t,`timeoutReason`),n,(e,t,n)=>R(e,Mn,t,n))),M(m,`metadata`,N(r.metadata,O(t,`metadata`),n,Pn)),M(m,`error`,N(r.error,O(t,`error`),n,In));let h=N(r.result,O(t,`result`),n,Rn);h!==void 0&&(h.taskId!==i&&A(n,O(O(t,`result`),`taskId`),`must match the task ID`),h.kind!==a&&A(n,O(O(t,`result`),`kind`),`must match the task kind`));let g=N(r.agentType,O(t,`agentType`),n,P),_=N(r.resumeSessionId,O(t,`resumeSessionId`),n,P),v=N(r.promptPreview,O(t,`promptPreview`),n,P),y=N(r.isolation,O(t,`isolation`),n,(e,t,n)=>R(e,An,t,n)),b={};for(let e of[`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`])b[e]=N(r[e],O(t,e),n,P);for(let e of qn){let r=e===`agentType`?g:e===`resumeSessionId`?_:e===`promptPreview`?v:b[e];a!==`agent`&&r!==void 0&&A(n,O(t,e),`must not be set for a '${a}' task`)}a!==`agent`&&y!==void 0&&A(n,O(t,`isolation`),`must not be set for a '${a}' task`);let x=N(r.commandPreview,O(t,`commandPreview`),n,P);a===`agent`&&x!==void 0&&A(n,O(t,`commandPreview`),`must not be set for a '${a}' task`);let ee=N(r.schedule,O(t,`schedule`),n,zn),te=N(r.nextFireAt,O(t,`nextFireAt`),n,z);switch(a!==`scheduled`&&ee!==void 0&&A(n,O(t,`schedule`),`must not be set for a '${a}' task`),a!==`scheduled`&&te!==void 0&&A(n,O(t,`nextFireAt`),`must not be set for a '${a}' task`),a){case`agent`:{let e=h?.kind===`agent`?h:void 0,t={...m,kind:a};return M(t,`result`,e),M(t,`agentType`,g),M(t,`resumeSessionId`,_),M(t,`promptPreview`,v),M(t,`isolation`,y),M(t,`worktreePath`,b.worktreePath),M(t,`branchName`,b.branchName),M(t,`worktreeStatus`,b.worktreeStatus),M(t,`worktreeNextAction`,b.worktreeNextAction),M(t,`worktreeBaseRevision`,b.worktreeBaseRevision),M(t,`parentWorktreeStatus`,b.parentWorktreeStatus),t}case`process`:{let e=h?.kind===`process`?h:void 0,t={...m,kind:a};return M(t,`result`,e),M(t,`commandPreview`,x),t}case`tool-invocation`:{let e=h?.kind===`tool-invocation`?h:void 0,t={...m,kind:a};return M(t,`result`,e),M(t,`commandPreview`,x),t}case`scheduled`:{let e=h?.kind===`scheduled`?h:void 0,t={...m,kind:a};return M(t,`result`,e),M(t,`commandPreview`,x),M(t,`schedule`,ee),M(t,`nextFireAt`,te),t}}}const Qn=[`background_task_created`,`background_task_started`,`background_task_updated`,`background_task_completed`,`background_task_failed`,`background_task_cancelled`,`background_task_text_delta`,`background_task_tool_start`,`background_task_tool_end`,`background_task_permission_request`,`background_task_closed`,`background_task_waking`];function W(e,t,n){return P(e.taskId,O(t,`taskId`),n)}function $n(e,t,n){let r=V(e,t,n,[`type`,`taskId`,`delta`]);if(r===void 0)return;let i=W(r,t,n),a=P(r.delta,O(t,`delta`),n);if(i!==void 0&&a!==void 0)return{type:`background_task_text_delta`,taskId:i,delta:a}}function er(e,t,n){let r=V(e,t,n,[`type`,`taskId`,`toolName`,`firstArg`]);if(r===void 0)return;let i=W(r,t,n),a=P(r.toolName,O(t,`toolName`),n);if(i===void 0||a===void 0)return;let o={type:`background_task_tool_start`,taskId:i,toolName:a};return M(o,`firstArg`,N(r.firstArg,O(t,`firstArg`),n,P)),o}function tr(e,t,n){let r=V(e,t,n,[`type`,`taskId`,`toolName`,`success`,`error`]);if(r===void 0)return;let i=W(r,t,n),a=P(r.toolName,O(t,`toolName`),n),o=L(r.success,O(t,`success`),n);if(i===void 0||a===void 0||o===void 0)return;let s={type:`background_task_tool_end`,taskId:i,toolName:a,success:o};return M(s,`error`,N(r.error,O(t,`error`),n,P)),s}function nr(e,t,n){let r=V(e,t,n,[`type`,`taskId`,`requestId`,`toolName`,`toolArgs`]);if(r===void 0)return;let i=W(r,t,n),a=P(r.requestId,O(t,`requestId`),n),o=P(r.toolName,O(t,`toolName`),n),s=Pn(r.toolArgs,O(t,`toolArgs`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{type:`background_task_permission_request`,taskId:i,requestId:a,toolName:o,toolArgs:s}}function rr(e,t,n){let r=V(e,t,n,[`type`,`taskId`]);if(r===void 0)return;let i=W(r,t,n);return i===void 0?void 0:{type:`background_task_closed`,taskId:i}}function ir(e,t,n){let r=V(e,t,n,[`type`,`taskId`,`instruction`]);if(r===void 0)return;let i=W(r,t,n);if(i===void 0)return;let a={type:`background_task_waking`,taskId:i};return M(a,`instruction`,N(r.instruction,O(t,`instruction`),n,P)),a}function ar(e,t,n,r){let i=V(t,n,r,[`type`,`task`]);if(i===void 0)return;let a=Zn(i.task,O(n,`task`),r);if(a!==void 0)return{type:e,task:a}}const or={background_task_text_delta:$n,background_task_tool_start:er,background_task_tool_end:tr,background_task_permission_request:nr,background_task_closed:rr,background_task_waking:ir};function sr(e,t,n){let r=R(e?.type,Qn,O(t,`type`),n);if(r===void 0)return;let i=or[r];return i===void 0?ar(r,e,t,n):i(e,t,n)}const cr=[`skill`,`plugin`],lr=[`user-slash`,`model-tool`],ur=[`inject`,`fork`],dr=[`started`,`completed`,`failed`],fr=[`memory_candidate_extracted`,`memory_candidate_queued`,`memory_candidate_saved`,`memory_candidate_skipped`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`],pr=[`manual`,`prompt-reference`,`system`],mr=[`active`,`observed`];function hr(e,t,n){let r=V(e,t,n,[`type`,`skillName`,`source`,`invocation`,`mode`,`status`,`timestamp`,`qualifiedName`,`error`]);if(r===void 0)return;let i=R(r.type,[`skill-activation`],O(t,`type`),n),a=P(r.skillName,O(t,`skillName`),n),o=R(r.source,cr,O(t,`source`),n),s=R(r.invocation,lr,O(t,`invocation`),n),c=R(r.mode,ur,O(t,`mode`),n),l=R(r.status,dr,O(t,`status`),n),u=z(r.timestamp,O(t,`timestamp`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d=N(r.qualifiedName,O(t,`qualifiedName`),n,P),f=N(r.error,O(t,`error`),n,P);return{type:i,skillName:a,source:o,invocation:s,mode:c,status:l,timestamp:u,...d===void 0?{}:{qualifiedName:d},...f===void 0?{}:{error:f}}}function gr(e,t,n){let r=V(e,t,n,[`topic`,`path`,`score`,`truncated`]);if(r===void 0)return;let i=P(r.topic,O(t,`topic`),n),a=P(r.path,O(t,`path`),n),o=F(r.score,O(t,`score`),n),s=L(r.truncated,O(t,`truncated`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{topic:i,path:a,score:o,truncated:s}}function _r(e,t,n){let r=V(e,t,n,[`type`,`at`,`candidateId`,`topic`,`reason`,`data`]);if(r===void 0)return;let i=R(r.type,fr,O(t,`type`),n),a=z(r.at,O(t,`at`),n);if(i===void 0||a===void 0)return;let o={type:i,at:a};for(let e of[`candidateId`,`topic`,`reason`])M(o,e,N(r[e],O(t,e),n,P));return M(o,`data`,N(r.data,O(t,`data`),n,(e,t,n)=>H(e,t,n,gn))),o}function vr(e,t,n){let r=V(e,t,n,[`id`,`sourcePath`,`relativePath`,`originalReference`,`loadType`,`status`,`byteLength`,`loadedAt`,`lastUsedAt`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.sourcePath,O(t,`sourcePath`),n),o=P(r.relativePath,O(t,`relativePath`),n),s=P(r.originalReference,O(t,`originalReference`),n),c=R(r.loadType,pr,O(t,`loadType`),n),l=R(r.status,mr,O(t,`status`),n),u=I(r.byteLength,O(t,`byteLength`),n),d=z(r.loadedAt,O(t,`loadedAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,sourcePath:a,relativePath:o,originalReference:s,loadType:c,status:l,byteLength:u,loadedAt:d};return M(f,`lastUsedAt`,N(r.lastUsedAt,O(t,`lastUsedAt`),n,z)),f}const yr=[`active`,`satisfied`,`stopped`],br=[`satisfied`,`max-iterations`,`cancelled`,`no-progress`],xr=[`continue`,`satisfied`],Sr=[`pending`,`in-progress`,`done`],Cr=[`planning`,`awaiting-approval`,`executing`,`completed`];function wr(e,t,n){let r=V(e,t,n,[`iteration`,`signal`,`reason`]);if(r===void 0)return;let i=I(r.iteration,O(t,`iteration`),n),a=R(r.signal,xr,O(t,`signal`),n),o=P(r.reason,O(t,`reason`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{iteration:i,signal:a,reason:o}}function Tr(e,t,n){let r=V(e,t,n,[`id`,`objective`,`status`,`stopReason`,`iterations`,`maxIterations`,`startedAt`,`progress`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.objective,O(t,`objective`),n),o=R(r.status,yr,O(t,`status`),n),s=I(r.iterations,O(t,`iterations`),n),c=I(r.maxIterations,O(t,`maxIterations`),n),l=z(r.startedAt,O(t,`startedAt`),n),u=B(r.progress,O(t,`progress`),n,wr);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d={id:i,objective:a,status:o,iterations:s,maxIterations:c,startedAt:l,progress:u};return M(d,`stopReason`,N(r.stopReason,O(t,`stopReason`),n,(e,t,n)=>R(e,br,t,n))),d}function Er(e,t,n){let r=V(e,t,n,[`id`,`description`,`status`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.description,O(t,`description`),n),o=R(r.status,Sr,O(t,`status`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{id:i,description:a,status:o}}function Dr(e,t,n){let r=V(e,t,n,[`id`,`objective`,`steps`,`phase`,`createdAt`,`approvedAt`]);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.objective,O(t,`objective`),n),o=B(r.steps,O(t,`steps`),n,Er),s=R(r.phase,Cr,O(t,`phase`),n),c=z(r.createdAt,O(t,`createdAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,objective:a,steps:o,phase:s,createdAt:c};return M(l,`approvedAt`,N(r.approvedAt,O(t,`approvedAt`),n,z)),l}function Or(e,t,n){let r=V(e,t,n,[`branchId`,`checkpointId`]);if(r===void 0)return;let i=P(r.branchId,O(t,`branchId`),n),a=P(r.checkpointId,O(t,`checkpointId`),n);if(i!==void 0&&a!==void 0)return{branchId:i,checkpointId:a}}const kr=[`waiting`,`pending`,`running`,`stopped`,`expired`],Ar=[`loopId`,`instruction`,`useDefaultPrompt`,`createdAt`,`expiresAt`,`revision`,`generation`,`phase`,`nextAllowedAt`,`delaySeconds`,`reason`,`fallbackUsed`,`terminalReason`];function jr(e,t,n){let r=V(e,t,n,Ar);if(!r)return;let i=P(r.loopId,O(t,`loopId`),n),a=P(r.instruction,O(t,`instruction`),n),o=N(r.useDefaultPrompt,O(t,`useDefaultPrompt`),n,L),s=z(r.createdAt,O(t,`createdAt`),n),c=z(r.expiresAt,O(t,`expiresAt`),n),l=I(r.revision,O(t,`revision`),n),u=I(r.generation,O(t,`generation`),n),d=R(r.phase,kr,O(t,`phase`),n),f=L(r.fallbackUsed,O(t,`fallbackUsed`),n),p=N(r.nextAllowedAt,O(t,`nextAllowedAt`),n,z),m=N(r.delaySeconds,O(t,`delaySeconds`),n,I),h=N(r.reason,O(t,`reason`),n,P),g=N(r.terminalReason,O(t,`terminalReason`),n,P);if(l!==void 0&&(!Number.isSafeInteger(l)||l<0)&&A(n,O(t,`revision`),`expected a non-negative safe integer`),u!==void 0&&(!Number.isSafeInteger(u)||u<0)&&A(n,O(t,`generation`),`expected a non-negative safe integer`),m!==void 0&&(m<60||m>3600)&&A(n,O(t,`delaySeconds`),`expected a delay between 60 and 3600 seconds`),i!==void 0&&!i.trim()&&A(n,O(t,`loopId`),`expected a non-empty loop ID`),a!==void 0&&!a.trim()&&A(n,O(t,`instruction`),`expected a non-empty instruction`),d===`waiting`&&p===void 0&&r.nextAllowedAt===void 0&&A(n,O(t,`nextAllowedAt`),`waiting loop needs a next wake time`),i===void 0||a===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0)return;let _={loopId:i,instruction:a,createdAt:s,expiresAt:c,revision:l,generation:u,phase:d,fallbackUsed:f};return M(_,`useDefaultPrompt`,o),M(_,`nextAllowedAt`,p),M(_,`delaySeconds`,m),M(_,`reason`,h),M(_,`terminalReason`,g),_}const Mr=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`],Nr=[`type`,`description`,`enum`,`items`,`properties`,`required`,`anyOf`,`additionalProperties`,`minimum`,`maximum`,`pattern`,`format`,`default`];function Pr(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;A(n,t,`expected a string, number or boolean, received ${j(e)}`)}function Fr(e,t,n){return e===null?null:Pr(e,t,n)}function Ir(e,t,n){return typeof e==`boolean`?e:G(e,t,n)}function G(e,t,n){let r=V(e,t,n,Nr);if(r===void 0)return;let i={};return M(i,`type`,N(r.type,O(t,`type`),n,(e,t,n)=>R(e,Mr,t,n))),M(i,`description`,N(r.description,O(t,`description`),n,P)),M(i,`enum`,N(r.enum,O(t,`enum`),n,(e,t,n)=>B(e,t,n,Pr))),M(i,`items`,N(r.items,O(t,`items`),n,G)),M(i,`properties`,N(r.properties,O(t,`properties`),n,(e,t,n)=>H(e,t,n,G))),M(i,`required`,N(r.required,O(t,`required`),n,hn)),M(i,`anyOf`,N(r.anyOf,O(t,`anyOf`),n,(e,t,n)=>B(e,t,n,G))),M(i,`additionalProperties`,N(r.additionalProperties,O(t,`additionalProperties`),n,Ir)),M(i,`minimum`,N(r.minimum,O(t,`minimum`),n,F)),M(i,`maximum`,N(r.maximum,O(t,`maximum`),n,F)),M(i,`pattern`,N(r.pattern,O(t,`pattern`),n,P)),M(i,`format`,N(r.format,O(t,`format`),n,P)),M(i,`default`,N(r.default,O(t,`default`),n,Fr)),i}function Lr(e,t,n){let r=G(e,t,n);if(r!==void 0){if(r.type!==`object`){A(n,O(t,`type`),`expected the root parameter schema to be type 'object'`);return}if(r.properties===void 0){A(n,O(t,`properties`),`expected the root parameter schema to name its properties`);return}return{...r,type:`object`,properties:r.properties}}}function Rr(e,t,n){let r=V(e,t,n,[`name`,`description`,`parameters`,`outputSchema`]);if(r===void 0)return;let i=P(r.name,O(t,`name`),n),a=P(r.description,O(t,`description`),n),o=Lr(r.parameters,O(t,`parameters`),n);if(i===void 0||a===void 0||o===void 0)return;let s={name:i,description:a,parameters:o};return M(s,`outputSchema`,N(r.outputSchema,O(t,`outputSchema`),n,G)),s}function K(e,t,n,r,i){return N(e[t],O(n,t),r,(e,t,n)=>B(e,t,n,i))}function zr(e,t,n,r){for(let i of[`name`,`systemPrompt`,`sandboxSnapshotId`])M(e,i,N(t[i],O(n,i),r,P));M(e,`history`,K(t,`history`,n,r,Dn)),M(e,`toolSchemas`,K(t,`toolSchemas`,n,r,Rr)),M(e,`backgroundTasks`,K(t,`backgroundTasks`,n,r,Zn)),M(e,`backgroundTaskEvents`,K(t,`backgroundTaskEvents`,n,r,sr)),M(e,`backgroundJobGroups`,K(t,`backgroundJobGroups`,n,r,Wn)),M(e,`backgroundJobGroupEvents`,K(t,`backgroundJobGroupEvents`,n,r,Gn)),M(e,`sessionLoops`,K(t,`sessionLoops`,n,r,jr)),M(e,`skillActivationEvents`,K(t,`skillActivationEvents`,n,r,hr)),M(e,`memoryEvents`,K(t,`memoryEvents`,n,r,_r)),M(e,`usedMemoryReferences`,K(t,`usedMemoryReferences`,n,r,gr)),M(e,`contextReferences`,K(t,`contextReferences`,n,r,vr)),M(e,`goal`,N(t.goal,O(n,`goal`),r,Tr)),M(e,`plan`,N(t.plan,O(n,`plan`),r,Dr)),M(e,`activeBranch`,N(t.activeBranch,O(n,`activeBranch`),r,Or))}const Br=1,Vr=[`id`,`name`,`cwd`,`createdAt`,`updatedAt`,`messages`,`history`,`systemPrompt`,`toolSchemas`,`backgroundTasks`,`backgroundTaskEvents`,`backgroundJobGroups`,`backgroundJobGroupEvents`,`sessionLoops`,`skillActivationEvents`,`memoryEvents`,`usedMemoryReferences`,`contextReferences`,`sandboxSnapshotId`,`goal`,`plan`,`activeBranch`];function Hr(e){let t=[],n=Wr(e,``,t);return n===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:n}}function Ur(e){let t=[],n=V(e,``,t,[`schemaVersion`,`record`]);if(n===void 0)return{status:`corrupt`,issues:t};let r=n.schemaVersion;if(typeof r!=`number`||!Number.isFinite(r))return{status:`unsupported`,schemaVersion:void 0};if(r!==1)return{status:`unsupported`,schemaVersion:r};let i=Wr(n.record,`record`,t);return i===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:i}}function Wr(e,t,n){let r=V(e,t,n,Vr);if(r===void 0)return;let i=P(r.id,O(t,`id`),n),a=P(r.cwd,O(t,`cwd`),n),o=z(r.createdAt,O(t,`createdAt`),n),s=z(r.updatedAt,O(t,`updatedAt`),n),c=B(r.messages,O(t,`messages`),n,U);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,cwd:a,createdAt:o,updatedAt:s,messages:c};return zr(l,r,t,n),l}function Gr(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function Kr(e,t={}){let n={schemaVersion:1,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function qr(e){let t=Ur(Gr(e));if(t.status===`unsupported`)throw Error(`Unsupported session artifact schema version ${t.schemaVersion??`(absent or not a number)`} (this build reads 1).`);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 Jr=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Yr(e){return Jr.test(e)}function Xr(e,t,n){if(e!==void 0&&Yr(e))return n;if(Array.isArray(t))return t.map(e=>Xr(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]=Xr(t,i,n);return r}return t}function Zr(e,t=`[REDACTED]`){return Xr(void 0,e,t)}const Qr=1,$r={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 ei(e,t){return e.event===t}function ti(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=ni(e,a,o,n,r);return i}function ni(e,t,n,r,i){if(Yr(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return ri(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return ri(e,n.map(n=>ni(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]=ni(e,n,o,r,i);return ri(e,a,r,i)}return String(n)}function ri(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=ge(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const ii=u(`FileSessionLogger`),ai=new Set([`text_delta`]),oi=new Set;let si=!1;function ci(e){oi.add(e),!si&&(typeof process>`u`||typeof process.on!=`function`||(si=!0,process.on(`exit`,()=>{for(let e of oi)e.flush()})))}var li=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(Kt(e))try{let r=ti(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
7
- `;if(ai.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){oi.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,oi.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){ci(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){ii.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},ui=class{log(){}};const di=u(`NodeSessionLogSink`),fi=/^[0-9a-f]{64}$/;function pi(e,t){let n=ge(`sha256`).update(t).digest(`hex`);if(!fi.test(e)||e!==n)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function mi(e,t,n){return qt(e),pi(t,n),{kind:`external-payload`,encoding:`json`,sha256:t,byteLength:Buffer.byteLength(n),relativePath:C(`${e}.payloads`,`${t}.json`)}}var hi=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{ze(e),this.enabled=!0}catch(t){this.enabled=!1,di.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,t){if(qt(e),!this.enabled)return;let n=C(this.logDirectory,`${e}.jsonl`);Be(n),xe(n,t,{mode:Re})}writeJson(e,t,n){let r=mi(e,t,n),i=`${e}.payloads`;if(this.enabled){ze(C(this.logDirectory,i));let e=C(this.logDirectory,r.relativePath);try{Le(e,n,{encoding:`utf8`,mode:Re,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;Be(e)}}return r}};const q=e=>({decode:e}),J=e=>({decode:e,optional:!0}),gi=(e,t,n)=>B(e,t,n,P),_i=(e,t,n)=>B(e,t,n,U),vi=(e,t,n)=>B(e,t,n,Rr),yi=(e,t,n)=>typeof e==`string`?e:U(e,t,n),Y=(e,t,n)=>{let r=I(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function bi(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function X(e,t,n){if(!bi(e)){n.push({path:t,message:`expected an object, received ${j(e)}`});return}for(let[r,i]of Object.entries(e))Z(i,O(t,r),n);return e}const xi=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function Si(e,t,n){let r=V(e,t,n,xi);if(r===void 0)return;let i=F(r.maxTokens,O(t,`maxTokens`),n),a=F(r.usedTokens,O(t,`usedTokens`),n),o=F(r.usedPercentage,O(t,`usedPercentage`),n),s=F(r.remainingPercentage,O(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 Ci=(e,t,n)=>B(e,t,n,(e,t,n)=>{let r=V(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=P(r.type,O(t,`type`),n),a=P(r.id,O(t,`id`),n);return i===void 0||a===void 0?void 0:{type:i,id:a}});function Z(e,t,n,r=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||e instanceof Date){n.push({path:t,message:`expected a JSON-compatible value, received ${j(e)}`});return}if(!Array.isArray(e)&&!bi(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${j(e)}`});return}if(r.has(e)){n.push({path:t,message:`expected an acyclic JSON-compatible value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Z(e[i],k(t,i),n,r);else for(let[i,a]of Object.entries(e))Z(a,O(t,i),n,r);return r.delete(e),e}function wi(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)?wi(e[i],k(t,i),n,r):n.push({path:k(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))wi(a,O(t,i),n,r);r.delete(e)}}const Ti=(...e)=>(t,n,r)=>R(t,e,n,r),Ei={session_init:{cwd:q(P),systemPromptLength:q(Y),systemPrompt:q(P),toolSchemas:q(vi),model:q(P),provider:q(P)},session_shutdown:{reason:q(P)},session_shutdown_step_error:{step:q(P),error:q(P)},context:{maxTokens:q(F),usedTokens:q(F),usedPercentage:q(F),remainingPercentage:q(F)},context_compact:{trigger:q(P),before:q(Si),after:q(Si)},error:{message:q(P),stack:q(P),historyLength:q(Y)},history_mutation:{executionId:J(P),conversationId:J(P),round:J(Y),batchId:J(P),usageObservationId:J(P),providerId:J(P),modelId:J(P),providerError:J(L),contextOverflow:J(L),mutation:q(Ti(`append_message`)),index:q(Y),message:q(U)},provider_request:{executionId:q(P),conversationId:J(P),round:q(Y),provider:q(P),model:q(P),effort:J(P),forcedSummary:J(L),messages:q(_i),tools:J(vi)},provider_native_raw_payload:{executionId:q(P),conversationId:J(P),round:q(Y),provider:q(P),apiSurface:J(P),payloadKind:q(Ti(`request`,`response`,`stream_event`)),sequence:q(Y),payload:J(Z),metadata:J(X)},provider_stream_raw_delta:{executionId:q(P),conversationId:J(P),round:q(Y),sequence:q(Y),delta:q(P)},provider_response_raw:{executionId:q(P),conversationId:J(P),round:q(Y),effort:J(P),response:q(U),responseKind:q(P)},provider_response_normalized:{executionId:q(P),conversationId:J(P),round:q(Y),response:q(U),toolCallsCount:J(Y)},structured_output_transport:{executionId:q(P),conversationId:J(P),round:q(Y),provider:q(P),model:q(P),mechanism:q(Ti(`response_schema`,`json_object`,`none`)),provenance:q(Ti(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:q(L),schemaInPrompt:q(L),reason:J(P)},provider_fallback:{executionId:q(P),conversationId:J(P),round:q(Y),fromProvider:q(P),fromModel:q(P),toProvider:q(P),toModel:q(P),reason:q(P)},assistant_message_committed:{executionId:q(P),conversationId:J(P),round:q(Y),message:q(yi)},tool_execution_request:{executionId:q(P),conversationId:J(P),round:q(Y),batchId:J(P),index:J(Y),toolName:q(P),toolCallId:q(P),parameters:q(X),ownerPath:J(Ci)},tool_execution_result:{executionId:q(P),conversationId:J(P),round:q(Y),batchId:J(P),index:J(Y),toolName:J(P),toolCallId:J(P),success:q(L),result:J(Z),error:J(P),metadata:J(X)},tool_batch_started:{executionId:q(P),conversationId:J(P),round:q(Y),batchId:J(P),mode:q(Ti(`parallel`,`sequential`)),maxConcurrency:q(Y),requestCount:q(Y),tools:q(gi)},tool_message_committed:{executionId:q(P),conversationId:J(P),round:q(Y),batchId:J(P),index:J(Y),message:q(U)},background_task_event:{backgroundEventType:J(P),backgroundEvent:J(sr),data:J(sr),taskId:J(P),originToolCallId:J(P)},background_job_group_event:{backgroundJobGroupEvent:J(Gn),data:J(Gn)},memory_event:{memoryEvent:J(_r),data:J(_r)},user:{content:q(P)},pre_run:{historyLength:q(Y),historyChars:q(Y),historyEstTokens:q(Y),input:q(P),history:q(_i),model:q(P),provider:q(P),maxTokens:q(F),nativeWebSearchSupported:q(L),nativeWebSearchEnabled:q(L),nativeWebFetchSupported:q(L),nativeWebFetchEnabled:q(L)},text_delta:{delta:q(P)},assistant:{content:q(P),historyLength:q(Y),estimatedChars:q(Y),history:q(_i),historyStructure:q((e,t,n)=>B(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${j(e)}`});return}let r=e;R(r.role,[`user`,`assistant`,`system`,`tool`],O(t,`role`),n),Y(r.contentLength,O(t,`contentLength`),n),L(r.hasToolCalls,O(t,`hasToolCalls`),n),gi(r.toolCallNames,O(t,`toolCallNames`),n),r.metadata!==void 0&&X(r.metadata,O(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:O(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:q(P),args:q(X)},tool_result:{tool:q(P),success:q(L),dataChars:q(Y),truncated:q(L)},tool_blocked:{tool:q(P),reason:q(P)},tool_denied:{tool:q(P),reason:q(P)},server_tool:{tool:q(P)}};var Di=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 Oi=new Set(Object.values($r));function ki(e,t={}){if(!Array.isArray(e))throw new Di(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${j(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=Ai(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 Di(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function Ai(e,t,n){if(!bi(e))return n.push({path:t,message:`expected an object, received ${j(e)}`}),{};let r=n.length;if(wi(e,t,n),n.length!==r)return{};let i=ji(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(Mi(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function ji(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:O(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:O(t,`schemaVersion`),message:`expected schema version 1, received ${j(r)}`})}let a=z(e.timestamp,O(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=P(e.sessionId,O(t,`sessionId`),n);o===``&&n.push({path:O(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!Oi.has(s)?(n.push({path:O(t,`event`),message:`expected a declared event name, received ${j(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function Mi(e,t,n,r,i){let a=Ei[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],O(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:O(n,o),message:`unknown event payload field`});continue}let s=Z(e[o],O(n,o),i);s!==void 0&&(r[o]=s)}Ni(e,t,n,i)}function Ni(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 Pi(e){if(e.trim().length===0||e.includes(`\0`)||fe(e)||he.isAbsolute(e))throw Ii(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Ii(e);return t}function Fi(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 Ii(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Li(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Ii(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 Ri=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=me(e)}readBytes(e,t){Fi(t);let n=Pi(e);try{let e=Ue(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof He?Li(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},zi=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 Ri(de(e))}readText(){return we(this.logFile)?je(this.logFile,`utf8`):void 0}};const Bi=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Vi=8*1024*1024,Hi=w.O_WRONLY|w.O_CREAT|w.O_EXCL|(w.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},Ui=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let t=e.parentDirectory??be();if(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new $(`invalid-options`);try{let e=Oe(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=ke(C(t,`agent-tool-results-`)),process.platform!==`win32`&&Se(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=Oe(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new $(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new $(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>Vi)throw new $(`write-failed`);let t=_e(18).toString(`base64url`),n=`${_e(18).toString(`base64url`)}.partial`,r=`${t}.txt`,i=C(this.directory,n),a=C(this.directory,r),o,s=!1;try{o=Ae(i,Hi,384),Le(o,e,`utf8`),Ee(o),Ce(o),o=void 0,De(i,a),s=!0,Ie(i);let n=`tool-result:${t}`;return this.entries.set(n,{fileName:r,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:n}}catch{let e=!1;if(o!==void 0)try{Ce(o)}catch{e=!0}try{Ie(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(s)try{Ie(a)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!Bi.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 Ri(this.directory).readBytes(t.fileName,Vi);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,t){this.assertRoot();try{Ie(C(this.directory,t.fileName)),this.entries.delete(e)}catch{throw new $(`cleanup-failed`)}}async cleanupExpired(){if(this.closed)throw new $(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(Ne(this.directory).length!==0)throw Error(`unexpected files`);Fe(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};const Wi=64*1024;function Gi(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 Ki(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Gi(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function qi(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=Ki(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function Ji(e){return e.code===`ENOENT`}var Yi=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){ze(de(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),Be(this.path),xe(this.path,`${JSON.stringify(e)}\n`,{mode:Re})}async*read(e){let t;try{t=Ae(this.path,w.O_RDONLY|(w.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Ji(e))return;throw e}try{let n=Te(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let i=Buffer.alloc(e),a=Me(t,i,0,e,n),o=Buffer.concat([i.subarray(0,a),r]),s=n===0?-1:o.indexOf(10);r=s===-1&&n>0?o:o.subarray(0,s+1);let c=n===0?o:s===-1?Buffer.alloc(0):o.subarray(s+1);n>0&&s===-1||(yield qi(c.toString(`utf8`).split(`
8
- `).reverse()))}}finally{Ce(t)}}};const Xi=/^[0-9a-f]{64}$/i;function Zi(e){if(!Qi(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 Qi(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`&&Xi.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function $i(e,t){return na(e,ea(t),0)}function ea(e){let t=ta(`maxDepth`,e.maxDepth??32),n=ta(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function ta(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 na(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 aa(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw aa(`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(oa(e))return ra(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>na(e,t,n))}finally{t.activeObjects.delete(e)}}if(!sa(e))throw aa(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,na(r,t,n)]))}finally{t.activeObjects.delete(e)}}function ra(e,t,n){let r=Zi(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=ia(r,t);t.activePayloadPaths.add(r.relativePath);try{return na(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function ia(e,t){let n=t.maxTotalBytes-t.totalBytes,r=t.source?.readBytes(e.relativePath,n);if(r===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let i=t.totalBytes+r.byteLength;if(!Number.isSafeInteger(i)||i>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:i});if(t.totalBytes=i,r.byteLength!==e.byteLength)throw new Q(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:r.byteLength});let a=ge(`sha256`).update(r).digest(`hex`);if(a!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:a});try{return JSON.parse(Buffer.from(r).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function aa(e){return new Q(`INVALID_JSON`,e)}function oa(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function sa(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ca(e){let t=[],n=la(),r=ua();return ki(e).forEach((e,i)=>{va(e,i,t),fa(e,i,t),da(n,e,i),pa(r,e,i)}),ma(n,t),ha(r,t),{ok:t.length===0,issues:t}}function la(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function ua(){return{requests:new Map,results:new Set}}function da(e,t,n){let r=ga(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`&&!ya(t.response)&&e.normalizedResponses.add(r.key))}function fa(e,t,n){ya(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 pa(e,t,n){let r=_a(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 ma(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 ha(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 ga(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 _a(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 va(e,t,n){if(Array.isArray(e)){e.forEach(e=>va(e,t,n));return}if(ba(e)){if(e.kind===`external-payload`){Qi(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>va(e,t,n))}}function ya(e){return Array.isArray(e)?e.some(e=>ya(e)):ba(e)?e.kind===`external-payload`||Object.values(e).some(e=>ya(e)):!1}function ba(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xa(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
9
- `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new Di(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),ki($i(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Sa(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of ki(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(ne(c.message))),Ca(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function Ca(e,t){if(e.event===`background_task_event`){Ta(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){Ta(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&Ta(t.memoryEvents,e,`memoryEvent`,`data`)}function wa(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function Ta(e,t,n,r){let i=wa(t,n)??wa(t,r);i&&e.push(i)}function Ea(e){return e instanceof Error?e.message:`unknown error`}function Da(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Ur(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion}:{status:`corrupt`,issues:n.issues}}function Oa(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var ka=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){ze(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){qt(e);let t=Je(this.baseDir),n=Je(t,`${e}.json`);if(!n.startsWith(t+Ye))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Ve(this.filePath(e.id),JSON.stringify({schemaVersion:1,record:e},null,2))}load(e){let t=this.filePath(e);if(!We(t))return{status:`missing`};let n;try{n=Ge(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Ea(e)}`}]}}return Da(n)}list(){return We(this.baseDir)?Ke(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(Oa):[]}outcomeForListedId(e){return Kt(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);We(t)&&qe(t)}},Aa=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};export{ot as AUTO_COMPACT_THRESHOLD,ht as AutoModeGate,ft as CONSECUTIVE_BLOCK_LIMIT,Aa as CheckpointTree,rt as CompactionError,at as CompactionOrchestrator,st as ContextWindowTracker,it as DEFAULT_COMPACTION_PROMPT,Wi as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,li as FileSessionLogger,Vr as INTERACTIVE_SESSION_RECORD_KEYS,Ri as NodeExternalPayloadSource,Yi as NodePromptHistoryFile,hi as NodeSessionLogSink,zi as NodeSessionLogSource,ka as NodeSessionStore,Ui as NodeToolResultSpillStore,It as PermissionEnforcer,Jr as SENSITIVE_KEY_PATTERN,$r as SESSION_LOG_EVENT,Qr as SESSION_LOG_SCHEMA_VERSION,Br as SESSION_RECORD_ENVELOPE_VERSION,pn as Session,Ze as SessionBusyError,Di as SessionLogDecodeError,Q as SessionLogPayloadResolutionError,ui as SilentSessionLogger,pt as TOTAL_BLOCK_LIMIT,$ as ToolResultSpillError,Qe as TurnClaim,qt as assertSafeSessionId,vt as consentScopeFor,mi as createSessionLogExternalPayloadReference,Hr as decodeInteractiveSessionRecord,ki as decodeSessionLogEntries,Ur as decodeVersionedInteractiveSessionRecord,qr as deserializeSessionArtifact,nt as formatConversationEntries,Kt as isSafeSessionId,Yr as isSensitiveKey,ei as isSessionLogEvent,xa as loadSessionLogEntries,Ki as parsePromptHistoryLine,Sa as replaySessionLogEntries,$i as resolveSessionLogExternalPayloads,Zr as scrubSensitiveKeys,Kr as serializeSessionArtifact,ca as validateSessionReplayLogEntries};
1
+ import{CONTEXT_ESTIMATE_CHARS_PER_TOKEN as e,DEFAULT_ABSTRACT_EVENT_SERVICE as t,ObservableEventService as n,PROVIDER_CALL_EVENTS as r,PROVIDER_FALLBACK_EVENTS as i,Robota as a,TOOL_BODY_EVENTS as o,TOOL_PERMISSION_EVENTS as s,TRUST_TO_MODE as c,allowRulesForAutoMode as l,applyPresetToolLists as u,createLogger as d,createUserMessage as f,estimateContextTokensFromMessages as p,evaluatePermission as m,findInvalidPermissionPatterns as h,findPermissionPatternWarnings as g,getModelContextWindow as _,getProviderCapabilities as ee,getToolPermissionProfile as v,isAbortFailure as y,isEnforcing as b,isModelEffort as te,isToolDeniedOutright as ne,matchesAnyPattern as re,messageToHistoryEntry as ie,peerDriverOf as ae,printablePeerDriver as oe,projectPermissionPolicy as se,readModelFallbackNotice as ce,registerToolPermissionProfile as le,requiresFreshApproval as ue,runHooks as x,traceEnvFor as de,wasToolResultAdmitted as fe}from"@robota-sdk/agent-core";import{dirname as pe,isAbsolute as me,join as S,relative as he,resolve as ge,win32 as _e}from"node:path";import{createHash as ve,randomBytes as ye,randomUUID as be}from"node:crypto";import{homedir as xe,tmpdir as Se}from"node:os";import{appendFileSync as Ce,chmodSync as we,closeSync as Te,constants as C,existsSync as Ee,fstatSync as De,fsyncSync as Oe,linkSync as ke,lstatSync as Ae,mkdtempSync as je,openSync as Me,readFileSync as Ne,readSync as Pe,readdirSync as Fe,realpathSync as Ie,rmdirSync as Le,unlinkSync as Re,writeFileSync as ze}from"node:fs";import{OWNER_ONLY_FILE_MODE as Be,ensureOwnerOnlyDirectory as Ve,tightenExistingFile as He,writeOwnerOnlyFile as Ue}from"@robota-sdk/agent-core/node";import{StableFileAuthorityError as We,createStableRootedFileReader as Ge}from"@robota-sdk/agent-file-authority";import{existsSync as Ke,readFileSync as qe,readdirSync as Je,unlinkSync as Ye}from"fs";import{resolve as Xe,sep as Ze}from"path";function Qe(e){if(typeof e!=`string`||e.length===0)throw Error("Session requires `cwd`: the absolute path this session executes in (ARCH-010). It feeds every hook input, CLAUDE_PROJECT_DIR, the permission root and the persisted record. Pass `process.cwd()` explicitly if that is genuinely what you mean.");if(!me(e))throw Error(`Session requires an ABSOLUTE \`cwd\`; got ${JSON.stringify(e)} (ARCH-010). A relative root is resolved against the process directory downstream, which is the ambient value this field exists to replace. Resolve it at your composition root.`);return e}var $e=class extends Error{recoverable=!0;constructor(e){super(e),this.name=`SessionBusyError`}},et=class{controller=null;claim(){if(this.controller!==null)throw new $e(`This session is already running a turn. A session is a single conversation: await the turn in flight, abort() it and await it, or use a separate session for concurrent work.`);return this.controller=new AbortController,this.controller}release(e){this.controller===e&&(this.controller=null)}abort(){this.controller?.abort()}isRunning(){return this.controller!==null}},tt=class{cwd;constructor(e){this.cwd=Qe(e)}turnClaim=new et;permissionModeGuards=new Set;getPermissionMode(){return this.permissionMode}setPermissionMode(e){for(let t of this.permissionModeGuards)t(e);this.permissionMode=e}addPermissionModeGuard(e){return this.permissionModeGuards.add(e),()=>this.permissionModeGuards.delete(e)}getActivePresetId(){return this.activePresetId}setActivePresetId(e){this.activePresetId=e}getParallelSubagentsEnabled(){return this.parallelSubagentsEnabled}setParallelSubagentsEnabled(e){this.parallelSubagentsEnabled=e}getSessionId(){return this.sessionId}getCwd(){return this.cwd}getSystemMessage(){return this.systemMessage}updateSystemMessage(e){this.systemMessage=e,this.agent.updateSystemPrompt(e)}async applyModelOptions(e){await this.agent.ensureReady();let t=e.model??this.model;this.agent.setModel({provider:this.aiProvider.name,model:t,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}}),this.model=t}getModelEffort(){let e=this.agent.getModel;if(e===void 0)return`auto`;try{return e.call(this.agent).effort??`auto`}catch(e){if(e instanceof Error&&/disposed/i.test(e.message))return`auto`;throw e}}async withScopedModelEffort(e,t){let n=this.getModelEffort();await this.applyModelOptions({effort:e});try{return await t()}finally{await this.applyModelOptions({effort:n})}}async applyAgentName(e){await this.agent.updateConfiguration({name:e})}getToolSchemas(){return this.toolSchemas}getMessageCount(){return this.messageCount}applyPresetToolLists(e){this.permissionEnforcer.applyPresetToolLists(e)}getPermissionRules(){let e=this.permissionEnforcer.currentPermissionRules();return{allow:[...e.allow],deny:[...e.deny],ask:[...e.ask]}}getSessionAllowedTools(){return this.permissionEnforcer.getSessionAllowedTools()}checkToolPermission(e,t,n){return this.permissionEnforcer.checkDelegatedToolCall(e,t,n)}requireClassifierFor(e){if(e===`auto`&&!this.permissionEnforcer.hasPermissionClassifier())throw Error(`Auto mode is unavailable: this session has no permission classifier.`)}retryPermissionDenial(e){return this.permissionEnforcer.allowRetryOfDenial(e)}getRecentPermissionDenials(){return this.permissionEnforcer.getRecentDenials()}clearSessionAllowedTools(){this.permissionEnforcer.clearSessionAllowedTools()}abort(){this.turnClaim.abort()}isRunning(){return this.turnClaim.isRunning()}getContextState(){return this.contextTracker.getContextState()}syncContextFromHistory(){this.contextTracker.updateFromHistory(this.agent.getHistory())}getAutoCompactThreshold(){return this.contextTracker.getAutoCompactThreshold()}setAutoCompactThreshold(e){this.contextTracker.setAutoCompactThreshold(e)}getHistory(){return this.agent.getHistory()}getFullHistory(){return this.agent.getFullHistory()}getSessionTokenUsage(){let e=0,t=0,n=!1;for(let r of this.getFullHistory()){if(r.category!==`event`||r.type!==`usage-summary`)continue;let i=r.data;e+=i?.promptTokens??0,t+=i?.completionTokens??0,n=!0}return n?{inputTokens:e,outputTokens:t}:void 0}getModelId(){return this.model}getOfferedToolSchemas(){return this.agent.getOfferedToolSchemas()}getProvider(){return this.aiProvider}getProviderId(){return this.aiProvider.name}addHistoryEntry(e){this.agent.addHistoryEntry(e)}injectMessage(e,t,n){this.agent.injectMessage(e,t,n)}injectRawMessage(e){this.agent.injectRawMessage(e)}clearHistory(){this.agent.clearHistory(),this.contextTracker.reset()}};function w(e){return JSON.stringify(typeof e==`string`?e:e??``)}function nt(e){let t=ae(e);return t?`user [from ${JSON.stringify(oe(t))}]`:`user`}function rt(e){switch(e.role){case`user`:return[`${nt(e)}: ${w(e.content)}`];case`assistant`:{let t=[];e.content!==null&&e.content!==``&&t.push(`assistant: ${w(e.content)}`);for(let n of e.toolCalls??[])t.push(`assistant tool call ${JSON.stringify(n.function.name)} [${JSON.stringify(n.id)}]: ${w(n.function.arguments)}`);return t.length>0?t:[`assistant: ""`]}case`tool`:return[`tool result${e.name?` ${JSON.stringify(e.name)}`:``} [${JSON.stringify(e.toolCallId)}]: ${w(e.content)}`];case`system`:return[`system: ${w(e.content)}`]}}function it(e){return e.map(e=>rt(e).join(`
2
+ `))}var at=class extends Error{constructor(e){super(e),this.name=`CompactionError`}};const ot=[`Summarize the following conversation concisely, preserving:`,`- User's original requests and goals`,`- Key decisions, conclusions, and important state`,`- Identifiers, names, and references needed to continue the work`,`- Current task status and next steps`,`Drop verbose intermediate outputs and exploratory work that didn't lead to results.`].join(`
3
+ `);var st=class{sessionId;cwd;model;hooks;compactInstructions;basePrompt;hookTypeExecutors;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.model=e.model,this.hooks=e.hooks,this.compactInstructions=e.compactInstructions,this.basePrompt=e.basePrompt,this.hookTypeExecutors=e.hookTypeExecutors}async compact(e,t,n,r,i=`manual`,a){if(r?.throwIfAborted(),t.length===0)throw new at(`Compaction was asked to summarise an empty history; conversation history preserved untouched`);let o={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:i};await x(this.hooks,`PreCompact`,o,this.hookTypeExecutors,a);let s=this.buildCompactionPrompt(t,n),c=await e.chat([{id:be(),role:`user`,content:s,state:`complete`,timestamp:new Date}],{model:this.model,toolChoice:`none`,preserveContextWindow:!0,...r===void 0?{}:{signal:r}});if(r?.throwIfAborted(),typeof c.content!=`string`||c.content.trim()===``)throw new at(`Compaction produced an invalid summary (provider=${e.name}, content type=${typeof c.content}); conversation history preserved untouched`);return c.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``,r=n?`\nAdditional focus:\n${n}\n`:``,i=it(e).join(`
4
+ `);return[this.basePrompt??ot,r,``,`Conversation:`,i].join(`
5
+ `)}};const ct=.835;var lt=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(e,t,n){this.contextMaxTokens=t??_(e),this.autoCompactThreshold=ut(n)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold!==!1&&this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=ut(e)}updateFromHistory(e){this.contextUsedTokens=p(e).usedTokens}reset(){this.contextUsedTokens=0}};function ut(e){if(e===void 0)return ct;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 dt(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 ft(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 pt(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.handler?()=>e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return n===void 0?t:ft(await dt(n(),e.signal))}const mt=3,ht=20;function gt(e,t){return`${e}\u0000${JSON.stringify(t)}`}var _t=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(gt(e,t))}takeRetry(e,t){return this.retries.delete(gt(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 vt(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function yt(e,t){switch(e){case`path`:{let e=vt(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 bt(e,t){let n=v(e).argument;if(n===void 0)return e;let r=t[n.key];if(typeof r!=`string`||r===``)return e;let i=yt(n.kind,r);return i===void 0?e:`${e}(${i})`}function T(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function xt(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}),T(`threw`,r)}const St=T(`denied`,`Permission denied. The user did not approve this action.`),Ct=d(`ToolHookHelpers`);function wt(e){if(fe(e)||typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function Tt(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 Et(e,t,n,r){let i=await x(e,`PreToolUse`,t,n,r);if(i.blocked){let e=i.reason??`Blocked by hook`;return T(`hook-blocked`,e,{blocked:!0,reason:e})}if(b(`PreToolUse`)){let e=i.errors,t=e?.[0],n=i.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return T(`hook-blocked`,i,{blocked:!0,reason:i})}if(r!==``)return T(`hook-blocked`,r,{blocked:!0,reason:r})}return null}function Dt(e,t,n,r,i){x(e,`PostToolUse`,{...t,hook_event_name:`PostToolUse`,tool_output:typeof n.data==`string`?n.data:JSON.stringify(n.data)},r,i).catch(e=>Ct.warn(`hook failed`,{error:e}))}function Ot(e,t){let n=v(e).argument?.key;if(n===void 0)return;let r=t[n];if(typeof r==`string`)return r.length>200?`${r.slice(0,200)}…`:r}var kt=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=Ot(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]}};function At(e,t,n){let r=v(e).argument;if(r===void 0||r.kind!==`path`)return t;let i=t[r.key];return typeof i!=`string`||i===``||me(i)?t:{...t,[r.key]:ge(n,i)}}const jt=d(`ToolBodyTrace`);function Mt(e,t){try{e?.eventService?.emit(s.DECIDED,{timestamp:new Date,executionId:e.executionId,decidedAt:new Date().toISOString(),decision:t})}catch(e){jt.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function Nt(e,n){let r=e.execute.bind(e),i=t,a=Object.create(e);return a.execute=async(t,a)=>{let s=t,c=`(unknown)`;try{c=e.getName(),s=At(c,t,n.cwd),n.log(`tool_call`,{tool:c,args:s});let l=Tt(n.sessionId,n.cwd,c,s,n.getPermissionMode(),n.transcriptPath),u=await Et(n.config.hooks,l,n.hookTypeExecutors,a?.hookTraceEnv);if(u)return n.log(`tool_blocked`,{tool:c,reason:`hook`}),Mt(a,`hook-blocked`),u;let d=await n.checkPermission(c,s,a?.signal,a?.permissionInteraction,a?.hookTraceEnv);if(d!==!0)return n.log(`tool_denied`,{tool:c,reason:`permission`}),Mt(a,`denied`),n.onToolExecution?.({type:`end`,toolName:c,toolArgs:s,success:!1,denied:!0,executionId:a?.executionId}),typeof d==`object`?T(`denied`,d.message):St;Mt(a,`allowed`),a?.signal?.throwIfAborted(),n.onToolExecution?.({type:`start`,toolName:c,toolArgs:s,executionId:a?.executionId});let f=Date.now(),p=`failure`,m;try{let e=a===void 0?void 0:{...a,instanceEventService:i};m=await r(s,e),p=a?.signal?.aborted?`interrupted`:m.success?`success`:`failure`}catch(e){throw p=a?.signal?.aborted||y(e)?`interrupted`:`failure`,e}finally{try{a?.eventService?.emit(o.COMPLETED,{timestamp:new Date,executionId:a.executionId,startedAt:new Date(f).toISOString(),endedAt:new Date(Math.max(Date.now(),f)).toISOString(),outcome:p,...typeof a.toolBodyId==`string`?{toolBodyId:a.toolBodyId}:{}})}catch(e){jt.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let h=wt(m);h!==m&&typeof m.data==`string`&&n.terminal.writeLine(` ⚠ Output truncated: ${m.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),n.onToolExecution?.({type:`end`,toolName:c,toolArgs:s,success:h.success,toolResultData:typeof h.data==`string`?h.data:JSON.stringify(h.data),executionId:a?.executionId});let g=typeof h.data==`string`?h.data.length:JSON.stringify(h.data)?.length??0;return n.log(`tool_result`,{tool:c,success:h.success,dataChars:g,truncated:h!==m}),Dt(n.config.hooks,l,h,n.hookTypeExecutors,a?.hookTraceEnv),h}catch(e){return xt(e,n.onToolExecution,{toolName:c,toolArgs:s,executionId:a?.executionId})}},a.setEventService=n=>{i=n??t,e.setEventService(n)},a}function Pt(e){let t=e,n=[];for(;;)try{let e=Ie(t);return n.length===0?e:ge(e,...n.reverse())}catch{let r=pe(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function Ft(e,t){let n=he(e,t);return n===``||!n.startsWith(`..`)&&!me(n)}function It(e){return(t,n)=>{let r=Pt(e),i=Pt(ge(t??r,n));return Ft(r,i)?i:void 0}}function Lt(e){let t=[...h(e.allow,`allow`),...h(e.restrictive,`deny`)];if(t.length===0)return;let n=t.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${n}. Fix the pattern where it is configured (issue #2428).`)}var Rt=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;homeDirectory;resolveInWorkspace;commandSandbox;denials=new kt;peerTurn=!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]},Lt(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??xe(),this.resolveInWorkspace=It(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new _t(e.permissionClassifier))}beginTurn(e){this.peerTurn=e}endTurn(){this.peerTurn=!1}hasPermissionClassifier(){return this.autoMode!==void 0}allowRetryOfDenial(e){let t=this.denials.list()[e],n=this.denials.callAt(e);if(t?.reason===`classifier`&&n!==void 0&&this.autoMode!==void 0)return this.autoMode.grantRetry(n.toolName,n.toolArgs),t}configuredRules(e={config:this.config,...this.taskPermissions===void 0?{}:{taskPermissions:this.taskPermissions}}){return{allow:[...e.config.permissions.allow,...e.taskPermissions?.allow??[]],restrictive:[...e.config.permissions.deny,...e.config.permissions.ask??[],...e.taskPermissions?.deny??[]]}}isToolVisible(e){let t=v(e);return!this.peerTurn&&t.repliesToPeer===!0||this.peerTurn&&t.notInPeerTurn===!0?!1:!ne(e,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(e){for(let t of e){let e=t.schema;if(e===void 0)continue;let n=e.parameters?.properties??{};le(e.name,{parameters:Object.keys(n)})}let t=this.configuredRules();Lt(t);for(let{pattern:e,reason:n}of g(t.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${e}" ${n}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i)=>this.decidePermission(e,t,n,r,i)};return e.map(e=>Nt(e,t))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}getRecentDenials(){return this.denials.list()}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}currentPermissionRules(){return{allow:[...this.config.permissions.allow],deny:[...this.config.permissions.deny],ask:[...this.config.permissions.ask??[]]}}applyPresetToolLists(e){let t=u(this.presetFreeRules,e);this.config.permissions.allow=t.allow,this.config.permissions.deny=t.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=Tt(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath);return await Et(this.config.hooks,r,this.hookTypeExecutors)?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1})===!0}async decidePermission(e,t,n,r=`interactive`,i,a={}){let o=this.permissionPolicy===void 0?void 0:se(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),s=this.getPermissionMode(),c=[...this.config.permissions.allow,...o?.allow??[]],u={allow:s===`auto`?l(c):c,deny:[...this.config.permissions.deny,...o?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory},f=m(e,t,s,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:a.sandboxed!==!1&&this.sandboxAutoApproves(e,t),...o?.ceiling===void 0?{}:{ceiling:o.ceiling},askAll:o?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(e,t,f,i),f===`auto`)return!0;if(f===`deny`)return this.denials.record(e,t,`policy`),!1;let p=ue(e,t,u,d);return s===`auto`&&this.autoMode!==void 0&&!p&&o?.askAll!==!0?this.decideInAutoMode(this.autoMode,e,t,n,r,i,a):this.promptForApproval(e,t,n,r,p)}async decideInAutoMode(e,t,n,r,i,a,o){if(e.takeRetry(t,n)||re(t,n,l([...this.sessionAllowedTools])))return!0;if(e.isPaused()){let a=await this.promptForApproval(t,n,r,i,!0);return a&&e.resume(),a}let s=await e.judge({toolName:t,toolArgs:n,cwd:this.cwd},r);return r?.aborted===!0?!1:this.getPermissionMode()===`auto`?s.kind===`allow`?!0:(this.denials.record(t,n,`classifier`,s.reason),{message:s.message}):this.decidePermission(t,n,r,i,a,o)}async promptForApproval(e,t,n,r=`interactive`,i=!1){let a=bt(e,t),o=n?.aborted===!0,s=r===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),c=await pt({toolName:e,alreadyAllowed:!i&&re(e,t,[...this.sessionAllowedTools]),...r===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...r===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:t,...n?{signal:n}:{}});if(!c.allowed&&!o&&this.denials.record(e,t,s?`user`:`no-approver`),i)return c.allowed;if(c.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(a)}return c.rememberForSession&&this.sessionAllowedTools.add(a),c.allowed}firePermissionDecisionHook(e,t,n,r){let i=this.getPermissionMode();x(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:e,tool_input:t,permission_decision:n,...i!==void 0&&{permission_mode:i},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,r).catch(()=>void 0)}sandboxAutoApproves(e,t){if(this.commandSandbox===void 0)return!1;let n=v(e).argument;if(n?.kind!==`command`)return!1;let r=t[n.key];return typeof r==`string`&&this.commandSandbox.autoApproves(e,r)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function zt(e,t,n,r,i){return new Rt({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 Bt(e,t,n,r){return{contextTracker:new lt(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new st({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Vt(e,t,n,r,i,o,s){let c=t.wrapTools(n);return new a({name:e.agentName??`agent`,aiProviders:[r],defaultModel:{provider:r.name,model:i,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}},systemMessage:o,tools:c,isToolVisible:e=>t.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}})}const Ht=d(`SessionHistoryOps`);function Ut(e,t){return{...e,...t}}async function Wt(e,t,n){n?.throwIfAborted();let r=t.agent.getHistory(),i=r.filter(e=>e.role!==`system`);if(i.length===0)return;t.contextTracker.updateFromHistory(r);let a=t.contextTracker.getContextState(),o=await t.compactionOrchestrator.compact(t.aiProvider,i,e,n,t.trigger,t.hookTraceEnv);t.agent.clearHistory(),t.agent.injectMessage(`system`,t.systemMessage),t.agent.injectMessage(`assistant`,`[Context Summary]\n${o}`),t.contextTracker.updateFromHistory(t.agent.getHistory());let s={session_id:t.sessionId,cwd:t.cwd,hook_event_name:`PostCompact`,trigger:t.trigger,compact_summary:o};x(t.hooks,`PostCompact`,s,t.hookTypeExecutors,t.hookTraceEnv).catch(e=>Ht.warn(`hook failed`,{error:e}));let c=t.contextTracker.getContextState();t.log(`context_compact`,{trigger:t.trigger,before:a,after:c}),t.onCompactEventCallback?.({trigger:t.trigger,before:a,after:c}),t.onCompactCallback&&t.onCompactCallback(o)}function Gt(e){let t=e.agent.getHistory(),n=new Date().toISOString(),r=e.sessionStore.load(e.sessionId);if(r.status!==`valid`&&r.status!==`missing`)return r;let i=r.status===`valid`?r.record:void 0,a={...i,id:e.sessionId,name:i?.name,cwd:e.cwd,createdAt:i?.createdAt??n,updatedAt:n,messages:t,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};return e.sessionStore.save(a),{status:`valid`,record:a}}const Kt=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function qt(){return`session_${be()}`}function Jt(e){return e.length>0&&e.length<=128&&Kt.test(e)}function Yt(e){if(!Jt(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 Xt=d(`SessionLifecycle`);function Zt(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function Qt(e,t,n,r,i,a,o){x(n,`SessionStart`,{session_id:e,cwd:t,hook_event_name:`SessionStart`,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},r).then(e=>{e.stdout&&i(e.stdout)}).catch(e=>Xt.warn(`SessionStart hook failed`,{error:e}))}async function $t(e,t,n,r,i,a,o){await x(r,`SessionEnd`,{session_id:e,cwd:t,hook_event_name:`SessionEnd`,reason:n,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},i)}function en(e){return{...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 tn=`unknown_tool`;function nn(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function rn(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){an(e,n);return}t===`tool_execution_result`&&on(e,n)}}function an(e,t){let n=E(t.toolName),r=E(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:sn(t.parameters)}))}function on(e,t){let n=E(t.toolName),r=E(t.toolCallId);if(!n||!r)return;let i=cn(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===tn))return;e.unknownToolCallIds.delete(r);let a=E(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:tn,requestedTool:E(i?.requestedTool)??n,availableTools:ln(i?.availableTools)})})}function sn(e){let t=cn(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 E(e){return typeof e==`string`&&e.length>0?e:void 0}function cn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ln(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const un=d(`SessionRun`);function dn(e,t,n,r){let i=typeof n.model==`string`?n.model:e.model,a=typeof n.provider==`string`?n.provider:e.aiProvider.name,o=n.effort,s=typeof o==`string`&&te(o)?o:e.effort??(typeof e.agent.getModel==`function`?e.agent.getModel().effort:void 0)??`high`,c=typeof n.round==`number`?n.round:void 0;x(e.hooks,t,{session_id:e.sessionId,cwd:e.cwd,hook_event_name:t,model:i,provider:a,effort:s,...c!==void 0&&{round:c},...e.permissionMode!==void 0&&{permission_mode:e.permissionMode},...e.transcriptPath!==void 0&&{transcript_path:e.transcriptPath},env:{CLAUDE_PROJECT_DIR:e.cwd,CLAUDE_SESSION_ID:e.sessionId}},e.hookTypeExecutors,r).catch(e=>un.warn(`hook failed`,{error:e}))}async function fn(t,n,a,o,s){let c=s?.traceContext,l=c?de(`hooks`,c,c.parentSpanId):void 0;if(a.contextTracker.updateFromHistory(a.agent.getHistory()),a.contextTracker.shouldAutoCompact()){let e=a.aiProvider,t=e.onTextDelta;e.onTextDelta=void 0;try{await(l?a.compact(o,l):a.compact(o))}finally{e.onTextDelta=t}}a.log(`user`,{content:t});let u=await x(a.hooks,`UserPromptSubmit`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`UserPromptSubmit`,user_message:n??t,prompt:n??t,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l),d=[a.sessionStartStdout,u.stdout].filter(Boolean).join(`
6
+ `),p=d?`<system-reminder>\n${d}\n</system-reminder>\n${t}`:t;a.clearSessionStartStdout();let m=a.agent.getHistory(),h=JSON.stringify(m),g=ee(a.aiProvider);a.log(`pre_run`,{historyLength:m.length,historyChars:h.length,historyEstTokens:Math.ceil(h.length/e),input:p,history:m,model:a.model,provider:a.aiProvider.name,maxTokens:a.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:g.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:g.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:g.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:g.nativeWebTools.webFetch.enabled}),a.contextTracker.updateFromHistory([...m,f(p)]),a.onContextUpdate?.(a.contextTracker.getContextState());let _;try{let e=nn({knownToolNames:a.knownToolNames??[],...a.onToolExecution&&{onToolExecution:a.onToolExecution}}),t=a.onTextDelta?e=>{a.log(`text_delta`,{delta:e}),a.onTextDelta?.(e)}:void 0,n={};if(_=await a.agent.run(p,{signal:o,maxExecutionRounds:a.maxTurns??0,...en(s),onExecutionEvent:(t,o)=>{if(t!==r.COMPLETED&&a.log(t,o),rn(e,t,o),t===`provider_request`){let e=o;n={model:e.model,provider:e.provider},dn(a,`PreModelCall`,e,l)}else if(t===`provider_response_normalized`)dn(a,`PostModelCall`,{...o,...n},l);else if(t===i.SWITCHED){let e=ce(o);e!==void 0&&(dn(a,`PostModelCall`,{round:o.round,model:e.from.model,provider:e.from.provider},l),a.emitProviderFallback?.(e))}else if(t===r.COMPLETED&&a.emitProviderCallCompleted){let e=o;Number.isSafeInteger(e.round)&&e.round>0&&typeof e.startedAt==`string`&&typeof e.endedAt==`string`&&(e.outcome===`success`||e.outcome===`failure`||e.outcome===`interrupted`)&&a.emitProviderCallCompleted({round:e.round,startedAt:e.startedAt,endedAt:e.endedAt,outcome:e.outcome,...typeof e.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(e.callId)&&{callId:e.callId},...(e.disposition===`invoked`||e.disposition===`cache-hit`||e.disposition===`preflight-refused`)&&{disposition:e.disposition},...typeof e.providerId==`string`&&e.providerId.length>0&&e.providerId.length<=128&&[...e.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:e.providerId},...typeof e.modelId==`string`&&e.modelId.length>0&&e.modelId.length<=128&&[...e.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:e.modelId},...(e.usageProvenance===`complete`||e.usageProvenance===`partial`||e.usageProvenance===`absent`)&&{usageProvenance:e.usageProvenance},...e.usageProvenance===`complete`&&typeof e.promptTokens==`number`&&Number.isSafeInteger(e.promptTokens)&&e.promptTokens>=0&&typeof e.completionTokens==`number`&&Number.isSafeInteger(e.completionTokens)&&e.completionTokens>=0&&typeof e.totalTokens==`number`&&Number.isSafeInteger(e.totalTokens)&&e.totalTokens===e.promptTokens+e.completionTokens&&{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens},...e.disposition===`invoked`&&typeof e.providerRequestId==`string`&&{providerRequestId:e.providerRequestId}})}t===`assistant_message_committed`&&(a.contextTracker.updateFromHistory(a.agent.getHistory()),a.onContextUpdate?.(a.contextTracker.getContextState()))},...t&&{onTextDelta:t}}),o.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){throw a.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:a.agent.getHistory().length}),x(a.hooks,`StopFailure`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l).catch(e=>un.warn(`hook failed`,{error:e})),e}let v=a.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}:{}}});a.log(`assistant`,{content:_,historyLength:v.length,estimatedChars:JSON.stringify(v).length,history:v,historyStructure:y}),a.contextTracker.updateFromHistory(v);let b=a.contextTracker.getContextState();return a.onContextUpdate?.(b),a.log(`context`,{maxTokens:b.maxTokens,usedTokens:b.usedTokens,usedPercentage:b.usedPercentage,remainingPercentage:b.remainingPercentage}),x(a.hooks,`Stop`,{session_id:a.sessionId,cwd:a.cwd,hook_event_name:`Stop`,response:_.substring(0,500),last_assistant_message:_,stop_hook_active:!1,...a.permissionMode!==void 0&&{permission_mode:a.permissionMode},...a.transcriptPath!==void 0&&{transcript_path:a.transcriptPath},env:{CLAUDE_PROJECT_DIR:a.cwd,CLAUDE_SESSION_ID:a.sessionId}},a.hookTypeExecutors,l).catch(e=>un.warn(`hook failed`,{error:e})),a.getSessionStore()&&a.persistSession(),_}var pn=class{agent;claim;sessionId;execution=null;constructor(e,t,n){this.agent=e,this.claim=t,this.sessionId=n}async invoke(e,t,n){let r=this.claim.claim(),i=mn(r,n);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:be(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:`deny`}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}async drain(){await this.execution}};function mn(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var hn=class extends tt{agent;eventService=new n;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.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??qt(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?c[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,Zt(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=zt(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Bt(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=Vt(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new pn(this.agent,this.turnClaim,this.sessionId),Qt(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);let r=this.turnClaim.claim(),i=mn(r,n?.signal),{signal:a}=r;this.permissionEnforcer.beginTurn(n?.peerTurn===!0);try{a.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let r=await fn(e,t,this.buildRunContext(),a,n);return this.messageCount+=1,r}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}addTools(e){return 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.runtimeTools.invoke(e,t,n?.signal)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&Gt({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,agent:this.agent,getFullHistory:()=>this.getFullHistory()})}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()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>$t(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){this.agent.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`,n){await this.compactWith(e,t,n)}async compactWith(e,t,n,r){let i={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{}};await Wt(e,Ut(this.buildRunContext(),i),n)}buildRunContext(){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)=>this.compactWith(void 0,`auto`,e,t),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(r.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(i.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 D(e,t){return e.length===0?t:`${e}.${t}`}function O(e,t){return`${e}[${t}]`}function k(e,t,n){e.push({path:t,message:n})}function A(e){if(e===null)return`null`;if(Array.isArray(e))return`an array`;if(e instanceof Date)return`a Date`;switch(typeof e){case`undefined`:return`nothing`;case`string`:return`a string`;case`number`:return`a number`;case`boolean`:return`a boolean`;case`object`:return`an object`;default:return`a ${typeof e}`}}function j(e,t,n){n!==void 0&&(e[t]=n)}function M(e,t,n,r){if(e!==void 0)return r(e,t,n)}function N(e,t,n){if(typeof e==`string`)return e;k(n,t,`expected a string, received ${A(e)}`)}function P(e,t,n){if(typeof e==`number`&&Number.isFinite(e))return e;k(n,t,`expected a finite number, received ${A(e)}`)}function F(e,t,n){if(typeof e==`number`&&Number.isInteger(e))return e;k(n,t,`expected an integer, received ${A(e)}`)}function I(e,t,n){if(typeof e==`boolean`)return e;k(n,t,`expected a boolean, received ${A(e)}`)}function L(e,t,n,r){if(typeof e==`string`&&t.includes(e))return e;k(r,n,`expected one of ${t.join(` | `)}, received ${A(e)}`)}function R(e,t,n){if(typeof e!=`string`){k(n,t,`expected an ISO-8601 timestamp string, received ${A(e)}`);return}if(Number.isNaN(Date.parse(e))){k(n,t,`expected a timestamp a date can be parsed from`);return}return e}function gn(e,t,n){if(e instanceof Date){if(Number.isNaN(e.getTime())){k(n,t,`expected a valid Date, received an invalid one`);return}return e}if(typeof e==`string`&&!Number.isNaN(Date.parse(e)))return new Date(e);k(n,t,`expected a Date or an ISO-8601 timestamp string, received ${A(e)}`)}function z(e,t,n,r){if(!Array.isArray(e)){k(n,t,`expected an array, received ${A(e)}`);return}let i=[];return e.forEach((e,a)=>{let o=r(e,O(t,a),n);o!==void 0&&i.push(o)}),i}function _n(e,t,n){return z(e,t,n,N)}function B(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){k(n,t,`expected an object, received ${A(e)}`);return}let i=e,a=new Set(r);for(let e of Object.keys(i))a.has(e)||k(n,D(t,e),`unknown key; the record contract does not declare it`);return i}function V(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){k(n,t,`expected an object, received ${A(e)}`);return}let i={};for(let[a,o]of Object.entries(e)){let e=r(o,D(t,a),n);e!==void 0&&(i[a]=e)}return i}function vn(e,t,n){if(e===null||e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){let r=[];return e.forEach((e,i)=>{let a=vn(e,O(t,i),n);a!==void 0&&r.push(a)}),r}if(typeof e==`object`)return V(e,t,n,vn);k(n,t,`expected a JSON-compatible value, received ${A(e)}`)}function yn(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;k(n,t,`expected a string, number or boolean, received ${A(e)}`)}const bn=[`complete`,`interrupted`],xn=[`id`,`timestamp`,`state`,`metadata`,`role`,`content`,`parts`],Sn={user:[...xn,`name`],assistant:[...xn,`toolCalls`],system:[...xn,`name`],tool:[...xn,`toolCallId`,`name`]};function Cn(e,t,n){if(e instanceof Date||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.every(e=>typeof e==`string`)||e.every(e=>typeof e==`number`))return e;k(n,t,`expected an array of only strings or only numbers`);return}if(typeof e==`object`&&e){let r={};for(let[i,a]of Object.entries(e)){if(typeof a!=`number`){k(n,D(t,i),`expected a number, received ${A(a)}`);continue}r[i]=a}return r}k(n,t,`expected a metadata value, received ${A(e)}`)}function wn(e,t,n){return V(e,t,n,Cn)}function Tn(e,t,n){let r=L(e?.type,[`text`,`image_inline`,`image_uri`],D(t,`type`),n);if(r===void 0)return;if(r===`text`){let r=B(e,t,n,[`type`,`text`]);if(r===void 0)return;let i=N(r.text,D(t,`text`),n);return i===void 0?void 0:{type:`text`,text:i}}if(r===`image_inline`){let r=B(e,t,n,[`type`,`mimeType`,`data`]);if(r===void 0)return;let i=N(r.mimeType,D(t,`mimeType`),n),a=N(r.data,D(t,`data`),n);return i===void 0||a===void 0?void 0:{type:`image_inline`,mimeType:i,data:a}}let i=B(e,t,n,[`type`,`uri`,`mimeType`]);if(i===void 0)return;let a=N(i.uri,D(t,`uri`),n);if(a===void 0)return;let o={type:`image_uri`,uri:a};return j(o,`mimeType`,M(i.mimeType,D(t,`mimeType`),n,N)),o}function En(e,t,n){let r=B(e,t,n,[`id`,`type`,`function`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=L(r.type,[`function`],D(t,`type`),n),o=D(t,`function`),s=B(r.function,o,n,[`name`,`arguments`]),c=s===void 0?void 0:N(s.name,D(o,`name`),n),l=s===void 0?void 0:N(s.arguments,D(o,`arguments`),n);if(i!==void 0&&a!==void 0&&c!==void 0&&l!==void 0)return{id:i,type:a,function:{name:c,arguments:l}}}function Dn(e,t,n){let r=N(e.id,D(t,`id`),n),i=gn(e.timestamp,D(t,`timestamp`),n),a=L(e.state,bn,D(t,`state`),n);if(r!==void 0&&i!==void 0&&a!==void 0)return{id:r,timestamp:i,state:a}}function On(e,t,n,r){j(e,`metadata`,M(t.metadata,D(n,`metadata`),r,wn)),j(e,`parts`,M(t.parts,D(n,`parts`),r,(e,t,n)=>z(e,t,n,Tn)))}function H(e,t,n){let r=L(e?.role,[`user`,`assistant`,`system`,`tool`],D(t,`role`),n);if(r===void 0)return;let i=B(e,t,n,Sn[r]);if(i===void 0)return;let a=Dn(i,t,n);if(a===void 0)return;let o=D(t,`content`);if(r===`assistant`){let e=i.content===null?null:N(i.content,o,n);if(e===void 0)return;let s={...a,role:r,content:e};return On(s,i,t,n),j(s,`toolCalls`,M(i.toolCalls,D(t,`toolCalls`),n,(e,t,n)=>z(e,t,n,En))),s}let s=N(i.content,o,n);if(s===void 0)return;if(r===`tool`){let e=N(i.toolCallId,D(t,`toolCallId`),n);if(e===void 0)return;let o={...a,role:r,content:s,toolCallId:e};return On(o,i,t,n),j(o,`name`,M(i.name,D(t,`name`),n,N)),o}let c={...a,role:r,content:s};return On(c,i,t,n),j(c,`name`,M(i.name,D(t,`name`),n,N)),c}function kn(e,t,n){let r=B(e,t,n,[`id`,`timestamp`,`category`,`type`,`data`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=gn(r.timestamp,D(t,`timestamp`),n),o=N(r.category,D(t,`category`),n),s=N(r.type,D(t,`type`),n);if(i===void 0||a===void 0||o===void 0||s===void 0)return;let c={id:i,timestamp:a,category:o,type:s};return j(c,`data`,M(r.data,D(t,`data`),n,vn)),c}const An=[`agent`,`process`,`scheduled`,`tool-invocation`],jn=[`foreground`,`background`],Mn=[`none`,`worktree`],Nn=[`queued`,`running`,`waiting_permission`,`sleeping`,`paused`,`completed`,`failed`,`cancelled`],Pn=[`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`],Fn=[`validation`,`capacity`,`permission`,`timeout`,`runner`,`crash`,`provider`,`process`];function In(e,t,n){return V(e,t,n,yn)}function Ln(e,t,n){return V(e,t,n,N)}function Rn(e,t,n){let r=B(e,t,n,[`category`,`message`,`recoverable`]);if(r===void 0)return;let i=L(r.category,Fn,D(t,`category`),n),a=N(r.message,D(t,`message`),n),o=I(r.recoverable,D(t,`recoverable`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{category:i,message:a,recoverable:o}}function zn(e,t,n){let r=B(e,t,n,[`promptTokens`,`completionTokens`,`totalTokens`]);if(r===void 0)return;let i=F(r.promptTokens,D(t,`promptTokens`),n),a=F(r.completionTokens,D(t,`completionTokens`),n),o=F(r.totalTokens,D(t,`totalTokens`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{promptTokens:i,completionTokens:a,totalTokens:o}}function Bn(e,t,n){let r=B(e,t,n,[`taskId`,`kind`,`output`,`exitCode`,`signalCode`,`metadata`,`usage`]);if(r===void 0)return;let i=N(r.taskId,D(t,`taskId`),n),a=L(r.kind,An,D(t,`kind`),n),o=N(r.output,D(t,`output`),n);if(i===void 0||a===void 0||o===void 0)return;let s=M(r.exitCode,D(t,`exitCode`),n,F),c=M(r.signalCode,D(t,`signalCode`),n,N),l=M(r.metadata,D(t,`metadata`),n,In),u=M(r.usage,D(t,`usage`),n,zn);switch(a!==`process`&&s!==void 0&&k(n,D(t,`exitCode`),`must not be set for a '${a}' result`),a!==`process`&&c!==void 0&&k(n,D(t,`signalCode`),`must not be set for a '${a}' result`),a!==`agent`&&u!==void 0&&k(n,D(t,`usage`),`must not be set for a '${a}' result`),a){case`process`:{let e={taskId:i,kind:a,output:o};return j(e,`exitCode`,s),j(e,`signalCode`,c),j(e,`metadata`,l),e}case`agent`:{let e={taskId:i,kind:a,output:o};return j(e,`metadata`,l),j(e,`usage`,u),e}case`scheduled`:{let e={taskId:i,kind:a,output:o};return j(e,`metadata`,l),e}case`tool-invocation`:{let e={taskId:i,kind:a,output:o};return j(e,`metadata`,l),e}}}function Vn(e,t,n){let r=B(e,t,n,[`cronExpression`,`agentInstruction`,`command`,`shell`,`env`]);if(r===void 0)return;let i=N(r.cronExpression,D(t,`cronExpression`),n);if(i===void 0)return;let a={cronExpression:i};for(let e of[`agentInstruction`,`command`,`shell`])j(a,e,M(r[e],D(t,e),n,N));return j(a,`env`,M(r.env,D(t,`env`),n,Ln)),a}const Hn=[`detached`,`wait_all`,`wait_any`,`manual`],Un=[`running`,`completed`],Wn=[`background_job_group_created`,`background_job_group_updated`,`background_job_group_completed`];function Gn(e,t,n){let r=B(e,t,n,[`taskId`,`label`,`status`,`summary`,`outputRef`,`error`,`startedAt`,`completedAt`]);if(r===void 0)return;let i=N(r.taskId,D(t,`taskId`),n),a=N(r.label,D(t,`label`),n),o=L(r.status,Nn,D(t,`status`),n);if(i===void 0||a===void 0||o===void 0)return;let s={taskId:i,label:a,status:o};for(let e of[`summary`,`outputRef`])j(s,e,M(r[e],D(t,e),n,N));for(let e of[`startedAt`,`completedAt`])j(s,e,M(r[e],D(t,e),n,R));return j(s,`error`,M(r.error,D(t,`error`),n,Rn)),s}function Kn(e,t,n){let r=B(e,t,n,[`id`,`parentSessionId`,`waitPolicy`,`taskIds`,`status`,`createdAt`,`updatedAt`,`label`,`completedAt`,`results`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.parentSessionId,D(t,`parentSessionId`),n),o=L(r.waitPolicy,Hn,D(t,`waitPolicy`),n),s=_n(r.taskIds,D(t,`taskIds`),n),c=L(r.status,Un,D(t,`status`),n),l=R(r.createdAt,D(t,`createdAt`),n),u=R(r.updatedAt,D(t,`updatedAt`),n),d=z(r.results,D(t,`results`),n,Gn);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,parentSessionId:a,waitPolicy:o,taskIds:s,status:c,createdAt:l,updatedAt:u,results:d};return j(f,`label`,M(r.label,D(t,`label`),n,N)),j(f,`completedAt`,M(r.completedAt,D(t,`completedAt`),n,R)),f}function qn(e,t,n){let r=L(e?.type,Wn,D(t,`type`),n);if(r===void 0)return;let i=B(e,t,n,[`type`,`group`]);if(i===void 0)return;let a=Kn(i.group,D(t,`group`),n);return a===void 0?void 0:{type:r,group:a}}const Jn=[`parentTaskId`,`currentAction`,`logPath`,`transcriptPath`],Yn=[`agentType`,`resumeSessionId`,`promptPreview`,`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`],Xn=[`commandPreview`],Zn=[`startedAt`,`lastActivityAt`,`completedAt`],Qn=[`id`,`kind`,`label`,`status`,`mode`,`parentSessionId`,`depth`,`cwd`,`pid`,`updatedAt`,`isolation`,`unread`,`result`,`error`,`timeoutReason`,`schedule`,`nextFireAt`,`metadata`,...Jn,...Yn,...Xn,...Zn];function $n(e,t,n){let r=B(e,t,n,Qn);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=L(r.kind,An,D(t,`kind`),n),o=N(r.label,D(t,`label`),n),s=L(r.status,Nn,D(t,`status`),n),c=L(r.mode,jn,D(t,`mode`),n),l=N(r.parentSessionId,D(t,`parentSessionId`),n),u=F(r.depth,D(t,`depth`),n),d=N(r.cwd,D(t,`cwd`),n),f=R(r.updatedAt,D(t,`updatedAt`),n),p=I(r.unread,D(t,`unread`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0||p===void 0)return;let m={id:i,label:o,status:s,mode:c,parentSessionId:l,depth:u,cwd:d,updatedAt:f,unread:p};for(let e of Jn)j(m,e,M(r[e],D(t,e),n,N));for(let e of Zn)j(m,e,M(r[e],D(t,e),n,R));j(m,`pid`,M(r.pid,D(t,`pid`),n,F)),j(m,`timeoutReason`,M(r.timeoutReason,D(t,`timeoutReason`),n,(e,t,n)=>L(e,Pn,t,n))),j(m,`metadata`,M(r.metadata,D(t,`metadata`),n,In)),j(m,`error`,M(r.error,D(t,`error`),n,Rn));let h=M(r.result,D(t,`result`),n,Bn);h!==void 0&&(h.taskId!==i&&k(n,D(D(t,`result`),`taskId`),`must match the task ID`),h.kind!==a&&k(n,D(D(t,`result`),`kind`),`must match the task kind`));let g=M(r.agentType,D(t,`agentType`),n,N),_=M(r.resumeSessionId,D(t,`resumeSessionId`),n,N),ee=M(r.promptPreview,D(t,`promptPreview`),n,N),v=M(r.isolation,D(t,`isolation`),n,(e,t,n)=>L(e,Mn,t,n)),y={};for(let e of[`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`])y[e]=M(r[e],D(t,e),n,N);for(let e of Yn){let r=e===`agentType`?g:e===`resumeSessionId`?_:e===`promptPreview`?ee:y[e];a!==`agent`&&r!==void 0&&k(n,D(t,e),`must not be set for a '${a}' task`)}a!==`agent`&&v!==void 0&&k(n,D(t,`isolation`),`must not be set for a '${a}' task`);let b=M(r.commandPreview,D(t,`commandPreview`),n,N);a===`agent`&&b!==void 0&&k(n,D(t,`commandPreview`),`must not be set for a '${a}' task`);let te=M(r.schedule,D(t,`schedule`),n,Vn),ne=M(r.nextFireAt,D(t,`nextFireAt`),n,R);switch(a!==`scheduled`&&te!==void 0&&k(n,D(t,`schedule`),`must not be set for a '${a}' task`),a!==`scheduled`&&ne!==void 0&&k(n,D(t,`nextFireAt`),`must not be set for a '${a}' task`),a){case`agent`:{let e=h?.kind===`agent`?h:void 0,t={...m,kind:a};return j(t,`result`,e),j(t,`agentType`,g),j(t,`resumeSessionId`,_),j(t,`promptPreview`,ee),j(t,`isolation`,v),j(t,`worktreePath`,y.worktreePath),j(t,`branchName`,y.branchName),j(t,`worktreeStatus`,y.worktreeStatus),j(t,`worktreeNextAction`,y.worktreeNextAction),j(t,`worktreeBaseRevision`,y.worktreeBaseRevision),j(t,`parentWorktreeStatus`,y.parentWorktreeStatus),t}case`process`:{let e=h?.kind===`process`?h:void 0,t={...m,kind:a};return j(t,`result`,e),j(t,`commandPreview`,b),t}case`tool-invocation`:{let e=h?.kind===`tool-invocation`?h:void 0,t={...m,kind:a};return j(t,`result`,e),j(t,`commandPreview`,b),t}case`scheduled`:{let e=h?.kind===`scheduled`?h:void 0,t={...m,kind:a};return j(t,`result`,e),j(t,`commandPreview`,b),j(t,`schedule`,te),j(t,`nextFireAt`,ne),t}}}const er=[`background_task_created`,`background_task_started`,`background_task_updated`,`background_task_completed`,`background_task_failed`,`background_task_cancelled`,`background_task_text_delta`,`background_task_tool_start`,`background_task_tool_end`,`background_task_permission_request`,`background_task_closed`,`background_task_waking`];function U(e,t,n){return N(e.taskId,D(t,`taskId`),n)}function tr(e,t,n){let r=B(e,t,n,[`type`,`taskId`,`delta`]);if(r===void 0)return;let i=U(r,t,n),a=N(r.delta,D(t,`delta`),n);if(i!==void 0&&a!==void 0)return{type:`background_task_text_delta`,taskId:i,delta:a}}function nr(e,t,n){let r=B(e,t,n,[`type`,`taskId`,`toolName`,`firstArg`]);if(r===void 0)return;let i=U(r,t,n),a=N(r.toolName,D(t,`toolName`),n);if(i===void 0||a===void 0)return;let o={type:`background_task_tool_start`,taskId:i,toolName:a};return j(o,`firstArg`,M(r.firstArg,D(t,`firstArg`),n,N)),o}function rr(e,t,n){let r=B(e,t,n,[`type`,`taskId`,`toolName`,`success`,`error`]);if(r===void 0)return;let i=U(r,t,n),a=N(r.toolName,D(t,`toolName`),n),o=I(r.success,D(t,`success`),n);if(i===void 0||a===void 0||o===void 0)return;let s={type:`background_task_tool_end`,taskId:i,toolName:a,success:o};return j(s,`error`,M(r.error,D(t,`error`),n,N)),s}function ir(e,t,n){let r=B(e,t,n,[`type`,`taskId`,`requestId`,`toolName`,`toolArgs`]);if(r===void 0)return;let i=U(r,t,n),a=N(r.requestId,D(t,`requestId`),n),o=N(r.toolName,D(t,`toolName`),n),s=In(r.toolArgs,D(t,`toolArgs`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{type:`background_task_permission_request`,taskId:i,requestId:a,toolName:o,toolArgs:s}}function ar(e,t,n){let r=B(e,t,n,[`type`,`taskId`]);if(r===void 0)return;let i=U(r,t,n);return i===void 0?void 0:{type:`background_task_closed`,taskId:i}}function or(e,t,n){let r=B(e,t,n,[`type`,`taskId`,`instruction`]);if(r===void 0)return;let i=U(r,t,n);if(i===void 0)return;let a={type:`background_task_waking`,taskId:i};return j(a,`instruction`,M(r.instruction,D(t,`instruction`),n,N)),a}function sr(e,t,n,r){let i=B(t,n,r,[`type`,`task`]);if(i===void 0)return;let a=$n(i.task,D(n,`task`),r);if(a!==void 0)return{type:e,task:a}}const cr={background_task_text_delta:tr,background_task_tool_start:nr,background_task_tool_end:rr,background_task_permission_request:ir,background_task_closed:ar,background_task_waking:or};function lr(e,t,n){let r=L(e?.type,er,D(t,`type`),n);if(r===void 0)return;let i=cr[r];return i===void 0?sr(r,e,t,n):i(e,t,n)}const ur=[`skill`,`plugin`],dr=[`user-slash`,`model-tool`],fr=[`inject`,`fork`],pr=[`started`,`completed`,`failed`],mr=[`memory_candidate_extracted`,`memory_candidate_queued`,`memory_candidate_saved`,`memory_candidate_skipped`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`],hr=[`manual`,`prompt-reference`,`system`],gr=[`active`,`observed`];function _r(e,t,n){let r=B(e,t,n,[`type`,`skillName`,`source`,`invocation`,`mode`,`status`,`timestamp`,`qualifiedName`,`error`]);if(r===void 0)return;let i=L(r.type,[`skill-activation`],D(t,`type`),n),a=N(r.skillName,D(t,`skillName`),n),o=L(r.source,ur,D(t,`source`),n),s=L(r.invocation,dr,D(t,`invocation`),n),c=L(r.mode,fr,D(t,`mode`),n),l=L(r.status,pr,D(t,`status`),n),u=R(r.timestamp,D(t,`timestamp`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d=M(r.qualifiedName,D(t,`qualifiedName`),n,N),f=M(r.error,D(t,`error`),n,N);return{type:i,skillName:a,source:o,invocation:s,mode:c,status:l,timestamp:u,...d===void 0?{}:{qualifiedName:d},...f===void 0?{}:{error:f}}}function vr(e,t,n){let r=B(e,t,n,[`topic`,`path`,`score`,`truncated`]);if(r===void 0)return;let i=N(r.topic,D(t,`topic`),n),a=N(r.path,D(t,`path`),n),o=P(r.score,D(t,`score`),n),s=I(r.truncated,D(t,`truncated`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{topic:i,path:a,score:o,truncated:s}}function yr(e,t,n){let r=B(e,t,n,[`type`,`at`,`candidateId`,`topic`,`reason`,`data`]);if(r===void 0)return;let i=L(r.type,mr,D(t,`type`),n),a=R(r.at,D(t,`at`),n);if(i===void 0||a===void 0)return;let o={type:i,at:a};for(let e of[`candidateId`,`topic`,`reason`])j(o,e,M(r[e],D(t,e),n,N));return j(o,`data`,M(r.data,D(t,`data`),n,(e,t,n)=>V(e,t,n,vn))),o}function br(e,t,n){let r=B(e,t,n,[`id`,`sourcePath`,`relativePath`,`originalReference`,`loadType`,`status`,`byteLength`,`loadedAt`,`lastUsedAt`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.sourcePath,D(t,`sourcePath`),n),o=N(r.relativePath,D(t,`relativePath`),n),s=N(r.originalReference,D(t,`originalReference`),n),c=L(r.loadType,hr,D(t,`loadType`),n),l=L(r.status,gr,D(t,`status`),n),u=F(r.byteLength,D(t,`byteLength`),n),d=R(r.loadedAt,D(t,`loadedAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0)return;let f={id:i,sourcePath:a,relativePath:o,originalReference:s,loadType:c,status:l,byteLength:u,loadedAt:d};return j(f,`lastUsedAt`,M(r.lastUsedAt,D(t,`lastUsedAt`),n,R)),f}const xr=[`active`,`satisfied`,`stopped`],Sr=[`satisfied`,`max-iterations`,`cancelled`,`no-progress`],Cr=[`continue`,`satisfied`],wr=[`pending`,`in-progress`,`done`],Tr=[`planning`,`awaiting-approval`,`executing`,`completed`];function Er(e,t,n){let r=B(e,t,n,[`iteration`,`signal`,`reason`]);if(r===void 0)return;let i=F(r.iteration,D(t,`iteration`),n),a=L(r.signal,Cr,D(t,`signal`),n),o=N(r.reason,D(t,`reason`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{iteration:i,signal:a,reason:o}}function Dr(e,t,n){let r=B(e,t,n,[`id`,`objective`,`status`,`stopReason`,`iterations`,`maxIterations`,`startedAt`,`progress`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.objective,D(t,`objective`),n),o=L(r.status,xr,D(t,`status`),n),s=F(r.iterations,D(t,`iterations`),n),c=F(r.maxIterations,D(t,`maxIterations`),n),l=R(r.startedAt,D(t,`startedAt`),n),u=z(r.progress,D(t,`progress`),n,Er);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0)return;let d={id:i,objective:a,status:o,iterations:s,maxIterations:c,startedAt:l,progress:u};return j(d,`stopReason`,M(r.stopReason,D(t,`stopReason`),n,(e,t,n)=>L(e,Sr,t,n))),d}function Or(e,t,n){let r=B(e,t,n,[`id`,`description`,`status`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.description,D(t,`description`),n),o=L(r.status,wr,D(t,`status`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{id:i,description:a,status:o}}function kr(e,t,n){let r=B(e,t,n,[`id`,`objective`,`steps`,`phase`,`createdAt`,`approvedAt`]);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.objective,D(t,`objective`),n),o=z(r.steps,D(t,`steps`),n,Or),s=L(r.phase,Tr,D(t,`phase`),n),c=R(r.createdAt,D(t,`createdAt`),n);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,objective:a,steps:o,phase:s,createdAt:c};return j(l,`approvedAt`,M(r.approvedAt,D(t,`approvedAt`),n,R)),l}function Ar(e,t,n){let r=B(e,t,n,[`branchId`,`checkpointId`]);if(r===void 0)return;let i=N(r.branchId,D(t,`branchId`),n),a=N(r.checkpointId,D(t,`checkpointId`),n);if(i!==void 0&&a!==void 0)return{branchId:i,checkpointId:a}}const jr=[`waiting`,`pending`,`running`,`stopped`,`expired`],Mr=[`loopId`,`instruction`,`useDefaultPrompt`,`createdAt`,`expiresAt`,`revision`,`generation`,`phase`,`nextAllowedAt`,`delaySeconds`,`reason`,`fallbackUsed`,`terminalReason`];function Nr(e,t,n){let r=B(e,t,n,Mr);if(!r)return;let i=N(r.loopId,D(t,`loopId`),n),a=N(r.instruction,D(t,`instruction`),n),o=M(r.useDefaultPrompt,D(t,`useDefaultPrompt`),n,I),s=R(r.createdAt,D(t,`createdAt`),n),c=R(r.expiresAt,D(t,`expiresAt`),n),l=F(r.revision,D(t,`revision`),n),u=F(r.generation,D(t,`generation`),n),d=L(r.phase,jr,D(t,`phase`),n),f=I(r.fallbackUsed,D(t,`fallbackUsed`),n),p=M(r.nextAllowedAt,D(t,`nextAllowedAt`),n,R),m=M(r.delaySeconds,D(t,`delaySeconds`),n,F),h=M(r.reason,D(t,`reason`),n,N),g=M(r.terminalReason,D(t,`terminalReason`),n,N);if(l!==void 0&&(!Number.isSafeInteger(l)||l<0)&&k(n,D(t,`revision`),`expected a non-negative safe integer`),u!==void 0&&(!Number.isSafeInteger(u)||u<0)&&k(n,D(t,`generation`),`expected a non-negative safe integer`),m!==void 0&&(m<60||m>3600)&&k(n,D(t,`delaySeconds`),`expected a delay between 60 and 3600 seconds`),i!==void 0&&!i.trim()&&k(n,D(t,`loopId`),`expected a non-empty loop ID`),a!==void 0&&!a.trim()&&k(n,D(t,`instruction`),`expected a non-empty instruction`),d===`waiting`&&p===void 0&&r.nextAllowedAt===void 0&&k(n,D(t,`nextAllowedAt`),`waiting loop needs a next wake time`),i===void 0||a===void 0||s===void 0||c===void 0||l===void 0||u===void 0||d===void 0||f===void 0)return;let _={loopId:i,instruction:a,createdAt:s,expiresAt:c,revision:l,generation:u,phase:d,fallbackUsed:f};return j(_,`useDefaultPrompt`,o),j(_,`nextAllowedAt`,p),j(_,`delaySeconds`,m),j(_,`reason`,h),j(_,`terminalReason`,g),_}const Pr=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`],Fr=[`type`,`description`,`enum`,`items`,`properties`,`required`,`anyOf`,`additionalProperties`,`minimum`,`maximum`,`pattern`,`format`,`default`];function Ir(e,t,n){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;k(n,t,`expected a string, number or boolean, received ${A(e)}`)}function Lr(e,t,n){return e===null?null:Ir(e,t,n)}function Rr(e,t,n){return typeof e==`boolean`?e:W(e,t,n)}function W(e,t,n){let r=B(e,t,n,Fr);if(r===void 0)return;let i={};return j(i,`type`,M(r.type,D(t,`type`),n,(e,t,n)=>L(e,Pr,t,n))),j(i,`description`,M(r.description,D(t,`description`),n,N)),j(i,`enum`,M(r.enum,D(t,`enum`),n,(e,t,n)=>z(e,t,n,Ir))),j(i,`items`,M(r.items,D(t,`items`),n,W)),j(i,`properties`,M(r.properties,D(t,`properties`),n,(e,t,n)=>V(e,t,n,W))),j(i,`required`,M(r.required,D(t,`required`),n,_n)),j(i,`anyOf`,M(r.anyOf,D(t,`anyOf`),n,(e,t,n)=>z(e,t,n,W))),j(i,`additionalProperties`,M(r.additionalProperties,D(t,`additionalProperties`),n,Rr)),j(i,`minimum`,M(r.minimum,D(t,`minimum`),n,P)),j(i,`maximum`,M(r.maximum,D(t,`maximum`),n,P)),j(i,`pattern`,M(r.pattern,D(t,`pattern`),n,N)),j(i,`format`,M(r.format,D(t,`format`),n,N)),j(i,`default`,M(r.default,D(t,`default`),n,Lr)),i}function zr(e,t,n){let r=W(e,t,n);if(r!==void 0){if(r.type!==`object`){k(n,D(t,`type`),`expected the root parameter schema to be type 'object'`);return}if(r.properties===void 0){k(n,D(t,`properties`),`expected the root parameter schema to name its properties`);return}return{...r,type:`object`,properties:r.properties}}}function Br(e,t,n){let r=B(e,t,n,[`name`,`description`,`parameters`,`outputSchema`]);if(r===void 0)return;let i=N(r.name,D(t,`name`),n),a=N(r.description,D(t,`description`),n),o=zr(r.parameters,D(t,`parameters`),n);if(i===void 0||a===void 0||o===void 0)return;let s={name:i,description:a,parameters:o};return j(s,`outputSchema`,M(r.outputSchema,D(t,`outputSchema`),n,W)),s}function G(e,t,n,r,i){return M(e[t],D(n,t),r,(e,t,n)=>z(e,t,n,i))}function Vr(e,t,n,r){for(let i of[`name`,`systemPrompt`,`sandboxSnapshotId`])j(e,i,M(t[i],D(n,i),r,N));j(e,`history`,G(t,`history`,n,r,kn)),j(e,`toolSchemas`,G(t,`toolSchemas`,n,r,Br)),j(e,`backgroundTasks`,G(t,`backgroundTasks`,n,r,$n)),j(e,`backgroundTaskEvents`,G(t,`backgroundTaskEvents`,n,r,lr)),j(e,`backgroundJobGroups`,G(t,`backgroundJobGroups`,n,r,Kn)),j(e,`backgroundJobGroupEvents`,G(t,`backgroundJobGroupEvents`,n,r,qn)),j(e,`sessionLoops`,G(t,`sessionLoops`,n,r,Nr)),j(e,`skillActivationEvents`,G(t,`skillActivationEvents`,n,r,_r)),j(e,`memoryEvents`,G(t,`memoryEvents`,n,r,yr)),j(e,`usedMemoryReferences`,G(t,`usedMemoryReferences`,n,r,vr)),j(e,`contextReferences`,G(t,`contextReferences`,n,r,br)),j(e,`goal`,M(t.goal,D(n,`goal`),r,Dr)),j(e,`plan`,M(t.plan,D(n,`plan`),r,kr)),j(e,`activeBranch`,M(t.activeBranch,D(n,`activeBranch`),r,Ar))}const Hr=1,Ur=[`id`,`name`,`cwd`,`createdAt`,`updatedAt`,`messages`,`history`,`systemPrompt`,`toolSchemas`,`backgroundTasks`,`backgroundTaskEvents`,`backgroundJobGroups`,`backgroundJobGroupEvents`,`sessionLoops`,`skillActivationEvents`,`memoryEvents`,`usedMemoryReferences`,`contextReferences`,`sandboxSnapshotId`,`goal`,`plan`,`activeBranch`];function Wr(e){let t=[],n=Kr(e,``,t);return n===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:n}}function Gr(e){let t=[],n=B(e,``,t,[`schemaVersion`,`record`]);if(n===void 0)return{status:`corrupt`,issues:t};let r=n.schemaVersion;if(typeof r!=`number`||!Number.isFinite(r))return{status:`unsupported`,schemaVersion:void 0};if(r!==1)return{status:`unsupported`,schemaVersion:r};let i=Kr(n.record,`record`,t);return i===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:i}}function Kr(e,t,n){let r=B(e,t,n,Ur);if(r===void 0)return;let i=N(r.id,D(t,`id`),n),a=N(r.cwd,D(t,`cwd`),n),o=R(r.createdAt,D(t,`createdAt`),n),s=R(r.updatedAt,D(t,`updatedAt`),n),c=z(r.messages,D(t,`messages`),n,H);if(i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)return;let l={id:i,cwd:a,createdAt:o,updatedAt:s,messages:c};return Vr(l,r,t,n),l}function qr(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function Jr(e,t={}){let n={schemaVersion:1,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function Yr(e){let t=Gr(qr(e));if(t.status===`unsupported`)throw Error(`Unsupported session artifact schema version ${t.schemaVersion??`(absent or not a number)`} (this build reads 1).`);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 Xr=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Zr(e){return Xr.test(e)}function Qr(e,t,n){if(e!==void 0&&Zr(e))return n;if(Array.isArray(t))return t.map(e=>Qr(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]=Qr(t,i,n);return r}return t}function $r(e,t=`[REDACTED]`){return Qr(void 0,e,t)}const ei=1,ti={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 ni(e,t){return e.event===t}function ri(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=ii(e,a,o,n,r);return i}function ii(e,t,n,r,i){if(Zr(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return ai(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return ai(e,n.map(n=>ii(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]=ii(e,n,o,r,i);return ai(e,a,r,i)}return String(n)}function ai(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=ve(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const oi=d(`FileSessionLogger`),si=new Set([`text_delta`]),ci=new Set;let li=!1;function ui(e){ci.add(e),!li&&(typeof process>`u`||typeof process.on!=`function`||(li=!0,process.on(`exit`,()=>{for(let e of ci)e.flush()})))}var di=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(Jt(e))try{let r=ri(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
7
+ `;if(si.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){ci.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,ci.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){ui(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){oi.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},fi=class{log(){}};const pi=d(`NodeSessionLogSink`),mi=/^[0-9a-f]{64}$/;function hi(e,t){let n=ve(`sha256`).update(t).digest(`hex`);if(!mi.test(e)||e!==n)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function gi(e,t,n){return Yt(e),hi(t,n),{kind:`external-payload`,encoding:`json`,sha256:t,byteLength:Buffer.byteLength(n),relativePath:S(`${e}.payloads`,`${t}.json`)}}var _i=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{Ve(e),this.enabled=!0}catch(t){this.enabled=!1,pi.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,t){if(Yt(e),!this.enabled)return;let n=S(this.logDirectory,`${e}.jsonl`);He(n),Ce(n,t,{mode:Be})}writeJson(e,t,n){let r=gi(e,t,n),i=`${e}.payloads`;if(this.enabled){Ve(S(this.logDirectory,i));let e=S(this.logDirectory,r.relativePath);try{ze(e,n,{encoding:`utf8`,mode:Be,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;He(e)}}return r}};const K=e=>({decode:e}),q=e=>({decode:e,optional:!0}),vi=(e,t,n)=>z(e,t,n,N),yi=(e,t,n)=>z(e,t,n,H),bi=(e,t,n)=>z(e,t,n,Br),xi=(e,t,n)=>typeof e==`string`?e:H(e,t,n),J=(e,t,n)=>{let r=F(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function Si(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(!Si(e)){n.push({path:t,message:`expected an object, received ${A(e)}`});return}for(let[r,i]of Object.entries(e))X(i,D(t,r),n);return e}const Ci=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function wi(e,t,n){let r=B(e,t,n,Ci);if(r===void 0)return;let i=P(r.maxTokens,D(t,`maxTokens`),n),a=P(r.usedTokens,D(t,`usedTokens`),n),o=P(r.usedPercentage,D(t,`usedPercentage`),n),s=P(r.remainingPercentage,D(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 Ti=(e,t,n)=>z(e,t,n,(e,t,n)=>{let r=B(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=N(r.type,D(t,`type`),n),a=N(r.id,D(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 ${A(e)}`});return}if(!Array.isArray(e)&&!Si(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${A(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],O(t,i),n,r);else for(let[i,a]of Object.entries(e))X(a,D(t,i),n,r);return r.delete(e),e}function Ei(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)?Ei(e[i],O(t,i),n,r):n.push({path:O(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))Ei(a,D(t,i),n,r);r.delete(e)}}const Z=(...e)=>(t,n,r)=>L(t,e,n,r),Di={session_init:{cwd:K(N),systemPromptLength:K(J),systemPrompt:K(N),toolSchemas:K(bi),model:K(N),provider:K(N)},session_shutdown:{reason:K(N)},session_shutdown_step_error:{step:K(N),error:K(N)},context:{maxTokens:K(P),usedTokens:K(P),usedPercentage:K(P),remainingPercentage:K(P)},context_compact:{trigger:K(N),before:K(wi),after:K(wi)},error:{message:K(N),stack:K(N),historyLength:K(J)},history_mutation:{executionId:q(N),conversationId:q(N),round:q(J),batchId:q(N),usageObservationId:q(N),providerId:q(N),modelId:q(N),providerError:q(I),contextOverflow:q(I),mutation:K(Z(`append_message`)),index:K(J),message:K(H)},provider_request:{executionId:K(N),conversationId:q(N),round:K(J),provider:K(N),model:K(N),effort:q(N),forcedSummary:q(I),messages:K(yi),tools:q(bi)},provider_native_raw_payload:{executionId:K(N),conversationId:q(N),round:K(J),provider:K(N),apiSurface:q(N),payloadKind:K(Z(`request`,`response`,`stream_event`)),sequence:K(J),payload:q(X),metadata:q(Y)},provider_stream_raw_delta:{executionId:K(N),conversationId:q(N),round:K(J),sequence:K(J),delta:K(N)},provider_response_raw:{executionId:K(N),conversationId:q(N),round:K(J),effort:q(N),response:K(H),responseKind:K(N)},provider_response_normalized:{executionId:K(N),conversationId:q(N),round:K(J),response:K(H),toolCallsCount:q(J)},structured_output_transport:{executionId:K(N),conversationId:q(N),round:K(J),provider:K(N),model:K(N),mechanism:K(Z(`response_schema`,`json_object`,`none`)),provenance:K(Z(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:K(I),schemaInPrompt:K(I),reason:q(N)},provider_fallback:{executionId:K(N),conversationId:q(N),round:K(J),fromProvider:K(N),fromModel:K(N),toProvider:K(N),toModel:K(N),reason:K(N)},assistant_message_committed:{executionId:K(N),conversationId:q(N),round:K(J),message:K(xi)},tool_execution_request:{executionId:K(N),conversationId:q(N),round:K(J),batchId:q(N),index:q(J),toolName:K(N),toolCallId:K(N),parameters:K(Y),ownerPath:q(Ti)},tool_execution_result:{executionId:K(N),conversationId:q(N),round:K(J),batchId:q(N),index:q(J),toolName:q(N),toolCallId:q(N),success:K(I),result:q(X),error:q(N),metadata:q(Y)},tool_batch_started:{executionId:K(N),conversationId:q(N),round:K(J),batchId:q(N),mode:K(Z(`parallel`,`sequential`)),maxConcurrency:K(J),requestCount:K(J),tools:K(vi)},tool_message_committed:{executionId:K(N),conversationId:q(N),round:K(J),batchId:q(N),index:q(J),message:K(H)},background_task_event:{backgroundEventType:q(N),backgroundEvent:q(lr),data:q(lr),taskId:q(N),originToolCallId:q(N)},background_job_group_event:{backgroundJobGroupEvent:q(qn),data:q(qn)},memory_event:{memoryEvent:q(yr),data:q(yr)},user:{content:K(N)},pre_run:{historyLength:K(J),historyChars:K(J),historyEstTokens:K(J),input:K(N),history:K(yi),model:K(N),provider:K(N),maxTokens:K(P),nativeWebSearchSupported:K(I),nativeWebSearchEnabled:K(I),nativeWebFetchSupported:K(I),nativeWebFetchEnabled:K(I)},text_delta:{delta:K(N)},assistant:{content:K(N),historyLength:K(J),estimatedChars:K(J),history:K(yi),historyStructure:K((e,t,n)=>z(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${A(e)}`});return}let r=e;L(r.role,[`user`,`assistant`,`system`,`tool`],D(t,`role`),n),J(r.contentLength,D(t,`contentLength`),n),I(r.hasToolCalls,D(t,`hasToolCalls`),n),vi(r.toolCallNames,D(t,`toolCallNames`),n),r.metadata!==void 0&&Y(r.metadata,D(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:D(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:K(N),args:K(Y)},tool_result:{tool:K(N),success:K(I),dataChars:K(J),truncated:K(I)},tool_blocked:{tool:K(N),reason:K(N)},tool_denied:{tool:K(N),reason:K(N)},server_tool:{tool:K(N)}};var Oi=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 ki=new Set(Object.values(ti));function Ai(e,t={}){if(!Array.isArray(e))throw new Oi(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${A(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=ji(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 Oi(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function ji(e,t,n){if(!Si(e))return n.push({path:t,message:`expected an object, received ${A(e)}`}),{};let r=n.length;if(Ei(e,t,n),n.length!==r)return{};let i=Mi(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(Ni(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function Mi(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:D(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:D(t,`schemaVersion`),message:`expected schema version 1, received ${A(r)}`})}let a=R(e.timestamp,D(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=N(e.sessionId,D(t,`sessionId`),n);o===``&&n.push({path:D(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!ki.has(s)?(n.push({path:D(t,`event`),message:`expected a declared event name, received ${A(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function Ni(e,t,n,r,i){let a=Di[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],D(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:D(n,o),message:`unknown event payload field`});continue}let s=X(e[o],D(n,o),i);s!==void 0&&(r[o]=s)}Pi(e,t,n,i)}function Pi(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 Fi(e){if(e.trim().length===0||e.includes(`\0`)||me(e)||_e.isAbsolute(e))throw Li(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw Li(e);return t}function Ii(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 Li(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Ri(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Li(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 zi=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=ge(e)}readBytes(e,t){Ii(t);let n=Fi(e);try{let e=Ge(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof We?Ri(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Bi=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 zi(pe(e))}readText(){return Ee(this.logFile)?Ne(this.logFile,`utf8`):void 0}};const Vi=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Hi=8*1024*1024,Ui=C.O_WRONLY|C.O_CREAT|C.O_EXCL|(C.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},Wi=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let t=e.parentDirectory??Se();if(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new $(`invalid-options`);try{let e=Ae(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=je(S(t,`agent-tool-results-`)),process.platform!==`win32`&&we(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=Ae(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new $(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new $(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>Hi)throw new $(`write-failed`);let t=ye(18).toString(`base64url`),n=`${ye(18).toString(`base64url`)}.partial`,r=`${t}.txt`,i=S(this.directory,n),a=S(this.directory,r),o,s=!1;try{o=Me(i,Ui,384),ze(o,e,`utf8`),Oe(o),Te(o),o=void 0,ke(i,a),s=!0,Re(i);let n=`tool-result:${t}`;return this.entries.set(n,{fileName:r,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:n}}catch{let e=!1;if(o!==void 0)try{Te(o)}catch{e=!0}try{Re(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(s)try{Re(a)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!Vi.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 zi(this.directory).readBytes(t.fileName,Hi);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,t){this.assertRoot();try{Re(S(this.directory,t.fileName)),this.entries.delete(e)}catch{throw new $(`cleanup-failed`)}}async cleanupExpired(){if(this.closed)throw new $(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(Fe(this.directory).length!==0)throw Error(`unexpected files`);Le(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};const Gi=64*1024;function Ki(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 qi(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Ki(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Ji(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=qi(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function Yi(e){return e.code===`ENOENT`}var Xi=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){Ve(pe(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),He(this.path),Ce(this.path,`${JSON.stringify(e)}\n`,{mode:Be})}async*read(e){let t;try{t=Me(this.path,C.O_RDONLY|(C.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Yi(e))return;throw e}try{let n=De(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let i=Buffer.alloc(e),a=Pe(t,i,0,e,n),o=Buffer.concat([i.subarray(0,a),r]),s=n===0?-1:o.indexOf(10);r=s===-1&&n>0?o:o.subarray(0,s+1);let c=n===0?o:s===-1?Buffer.alloc(0):o.subarray(s+1);n>0&&s===-1||(yield Ji(c.toString(`utf8`).split(`
8
+ `).reverse()))}}finally{Te(t)}}};const Zi=/^[0-9a-f]{64}$/i;function Qi(e){if(!$i(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 $i(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`&&Zi.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function ea(e,t){return ra(e,ta(t),0)}function ta(e){let t=na(`maxDepth`,e.maxDepth??32),n=na(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function na(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 ra(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 oa(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw oa(`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(sa(e))return ia(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>ra(e,t,n))}finally{t.activeObjects.delete(e)}}if(!ca(e))throw oa(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,ra(r,t,n)]))}finally{t.activeObjects.delete(e)}}function ia(e,t,n){let r=Qi(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=aa(r,t);t.activePayloadPaths.add(r.relativePath);try{return ra(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function aa(e,t){let n=t.maxTotalBytes-t.totalBytes,r=t.source?.readBytes(e.relativePath,n);if(r===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let i=t.totalBytes+r.byteLength;if(!Number.isSafeInteger(i)||i>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:i});if(t.totalBytes=i,r.byteLength!==e.byteLength)throw new Q(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:r.byteLength});let a=ve(`sha256`).update(r).digest(`hex`);if(a!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:a});try{return JSON.parse(Buffer.from(r).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function oa(e){return new Q(`INVALID_JSON`,e)}function sa(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function ca(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function la(e){let t=[],n=ua(),r=da();return Ai(e).forEach((e,i)=>{ya(e,i,t),pa(e,i,t),fa(n,e,i),ma(r,e,i)}),ha(n,t),ga(r,t),{ok:t.length===0,issues:t}}function ua(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function da(){return{requests:new Map,results:new Set}}function fa(e,t,n){let r=_a(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`&&!ba(t.response)&&e.normalizedResponses.add(r.key))}function pa(e,t,n){ba(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 ma(e,t,n){let r=va(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 ha(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 ga(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 _a(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 va(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 ya(e,t,n){if(Array.isArray(e)){e.forEach(e=>ya(e,t,n));return}if(xa(e)){if(e.kind===`external-payload`){$i(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>ya(e,t,n))}}function ba(e){return Array.isArray(e)?e.some(e=>ba(e)):xa(e)?e.kind===`external-payload`||Object.values(e).some(e=>ba(e)):!1}function xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sa(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
9
+ `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new Oi(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),Ai(ea(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Ca(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of Ai(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(ie(c.message))),wa(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function wa(e,t){if(e.event===`background_task_event`){Ea(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){Ea(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&Ea(t.memoryEvents,e,`memoryEvent`,`data`)}function Ta(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function Ea(e,t,n,r){let i=Ta(t,n)??Ta(t,r);i&&e.push(i)}function Da(e){return e instanceof Error?e.message:`unknown error`}function Oa(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Gr(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion}:{status:`corrupt`,issues:n.issues}}function ka(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Aa=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){Ve(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){Yt(e);let t=Xe(this.baseDir),n=Xe(t,`${e}.json`);if(!n.startsWith(t+Ze))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Ue(this.filePath(e.id),JSON.stringify({schemaVersion:1,record:e},null,2))}load(e){let t=this.filePath(e);if(!Ke(t))return{status:`missing`};let n;try{n=qe(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Da(e)}`}]}}return Oa(n)}list(){return Ke(this.baseDir)?Je(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(ka):[]}outcomeForListedId(e){return Jt(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);Ke(t)&&Ye(t)}},ja=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};export{ct as AUTO_COMPACT_THRESHOLD,_t as AutoModeGate,mt as CONSECUTIVE_BLOCK_LIMIT,ja as CheckpointTree,at as CompactionError,st as CompactionOrchestrator,lt as ContextWindowTracker,ot as DEFAULT_COMPACTION_PROMPT,Gi as DEFAULT_PROMPT_HISTORY_BLOCK_BYTES,di as FileSessionLogger,Ur as INTERACTIVE_SESSION_RECORD_KEYS,zi as NodeExternalPayloadSource,Xi as NodePromptHistoryFile,_i as NodeSessionLogSink,Bi as NodeSessionLogSource,Aa as NodeSessionStore,Wi as NodeToolResultSpillStore,Rt as PermissionEnforcer,Xr as SENSITIVE_KEY_PATTERN,ti as SESSION_LOG_EVENT,ei as SESSION_LOG_SCHEMA_VERSION,Hr as SESSION_RECORD_ENVELOPE_VERSION,hn as Session,$e as SessionBusyError,Oi as SessionLogDecodeError,Q as SessionLogPayloadResolutionError,fi as SilentSessionLogger,ht as TOTAL_BLOCK_LIMIT,$ as ToolResultSpillError,et as TurnClaim,Yt as assertSafeSessionId,bt as consentScopeFor,gi as createSessionLogExternalPayloadReference,Wr as decodeInteractiveSessionRecord,Ai as decodeSessionLogEntries,Gr as decodeVersionedInteractiveSessionRecord,Yr as deserializeSessionArtifact,it as formatConversationEntries,Jt as isSafeSessionId,Zr as isSensitiveKey,ni as isSessionLogEvent,Sa as loadSessionLogEntries,qi as parsePromptHistoryLine,Ca as replaySessionLogEntries,ea as resolveSessionLogExternalPayloads,$r as scrubSensitiveKeys,Jr as serializeSessionArtifact,la as validateSessionReplayLogEntries};
10
10
  //# sourceMappingURL=index.js.map