@robota-sdk/agent-session 3.0.0-beta.95 → 3.0.0-beta.97

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