@robota-sdk/agent-session 3.0.0-beta.84 → 3.0.0-beta.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/dist/node/index.cjs +5 -5
- package/dist/node/index.d.cts +1 -1
- package/dist/node/index.d.cts.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +9 -9
- package/dist/node/index.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# @robota-sdk/agent-session
|
|
2
2
|
|
|
3
|
+
## 3.0.0-beta.86
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- @robota-sdk/agent-core@3.0.0-beta.86
|
|
8
|
+
- @robota-sdk/agent-file-authority@3.0.0-beta.86
|
|
9
|
+
- @robota-sdk/agent-interface-execution@3.0.0-beta.86
|
|
10
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.86
|
|
11
|
+
|
|
12
|
+
## 3.0.0-beta.85
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- 94b2c87: A PreToolUse `command` hook can now steer a tool call, not only refuse it. The permission gate
|
|
17
|
+
applies the winning `hookSpecificOutput.permissionDecision`:
|
|
18
|
+
|
|
19
|
+
- `allow` skips the prompt a person would otherwise get. Deny rules, refusals from the mode, the
|
|
20
|
+
`auto` mode classifier and asks that must reach a person (an `ask` rule, a protected path, a
|
|
21
|
+
policy that asks about everything) still apply.
|
|
22
|
+
- `ask` sends the call to a person even when the mode or a remembered consent would run it. The
|
|
23
|
+
answer is not remembered, and with no one to ask the call is refused.
|
|
24
|
+
- `defer` leaves the call to the normal flow, as before.
|
|
25
|
+
|
|
26
|
+
Before this change these decisions were read and then ignored.
|
|
27
|
+
|
|
28
|
+
`updatedInput` is still not applied: the call runs the input it was made with, and an `allow` sent
|
|
29
|
+
with an `updatedInput` is not applied either, since it approved another input.
|
|
30
|
+
|
|
31
|
+
`runHooks` (agent-core) now reads a decision and an `updatedInput` only from `command` hooks: a
|
|
32
|
+
`prompt` or `agent` hook answers from a model that reads the tool input it judges, so it can only
|
|
33
|
+
refuse. With several hooks, `ask` now outranks `defer` (`deny` > `ask` > `defer` > `allow`), and the
|
|
34
|
+
reported `updatedInput` is the one sent with the winning decision.
|
|
35
|
+
|
|
36
|
+
### Patch Changes
|
|
37
|
+
|
|
38
|
+
- 10597b2: Apply command-hook PreToolUse input rewrites only after every enforcing hook evaluates the final
|
|
39
|
+
input. Permission checks and tool execution share those arguments; rewrite cycles and replacements
|
|
40
|
+
that a delegated or already-settled action cannot apply are refused.
|
|
41
|
+
- Updated dependencies [41cca13]
|
|
42
|
+
- Updated dependencies [ada3841]
|
|
43
|
+
- Updated dependencies [5093a30]
|
|
44
|
+
- Updated dependencies [94b2c87]
|
|
45
|
+
- Updated dependencies [3ab2eca]
|
|
46
|
+
- @robota-sdk/agent-core@3.0.0-beta.85
|
|
47
|
+
- @robota-sdk/agent-interface-execution@3.0.0-beta.85
|
|
48
|
+
- @robota-sdk/agent-interface-session@3.0.0-beta.85
|
|
49
|
+
- @robota-sdk/agent-file-authority@3.0.0-beta.85
|
|
50
|
+
|
|
3
51
|
## 3.0.0-beta.84
|
|
4
52
|
|
|
5
53
|
### Minor Changes
|
package/dist/node/index.cjs
CHANGED
|
@@ -2,8 +2,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
|
|
|
2
2
|
`))}var _=class extends Error{constructor(e){super(e),this.name=`CompactionError`}};const v=[`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
3
|
`);var y=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(t,r,i,a,o=`manual`,s,c){if(a?.throwIfAborted(),r.length===0)throw new _(`Compaction was asked to summarise an empty history; conversation history preserved untouched`);let l={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:o};await(0,e.runHooks)(this.hooks,`PreCompact`,l,this.hookTypeExecutors,s);let u=this.buildCompactionPrompt(r,i),d=(0,n.randomUUID)(),f=(0,n.randomUUID)(),p=t.resolveModelRoute?.(this.model,f)??{provider:t.name,model:this.model},m=await(0,e.callJournaledProvider)((e,n)=>t.chat(e,n),[{id:(0,n.randomUUID)(),role:`user`,content:u,state:`complete`,timestamp:new Date}],{model:this.model,executionId:f,onModelFallback:e=>{p={...e.to}},toolChoice:`none`,preserveContextWindow:!0,...a===void 0?{}:{signal:a}},c?{journal:c,executionId:f,callId:d,route:()=>({providerId:p.provider,modelId:p.model})}:void 0);if(a?.throwIfAborted(),typeof m.content!=`string`||m.content.trim()===``)throw new _(`Compaction produced an invalid summary (provider=${t.name}, content type=${typeof m.content}); conversation history preserved untouched`);return m.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``,r=n?`\nAdditional focus:\n${n}\n`:``,i=g(e).join(`
|
|
4
4
|
`);return[this.basePrompt??v,r,``,`Conversation:`,i].join(`
|
|
5
|
-
`)}};const b=.835;var x=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(t,n,r){this.contextMaxTokens=n??(0,e.getModelContextWindow)(t),this.autoCompactThreshold=S(r)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold!==!1&&this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=S(e)}updateFromHistory(t){this.contextUsedTokens=(0,e.estimateContextTokensFromMessages)(t).usedTokens}reset(){this.contextUsedTokens=0}};function S(e){if(e===void 0)return b;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 ee(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 te(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 ne(e){let t={allowed:!1,rememberForSession:!1,rememberForProject:!1};if(e.alreadyAllowed)return{allowed:!0,rememberForSession:!1,rememberForProject:!1};if(e.signal?.aborted===!0)return t;let n=e.handler?()=>e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return n===void 0?t:te(await ee(n(),e.signal))}const re=`robota-session/approval`;function ie(e){return e?.waits.some(e=>e.request.kind===re)??!1}async function ae(t,n,r){let a=n?.waits.filter(e=>e.request.kind===re)??[];if(!r&&!a.length)return;if(!n||n.action.toolName!==t.toolName)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Checkpointed approval requires the current journaled action`);let o=(0,i.realpathSync)(t.cwd);for(let{request:n}of a)if(n.data.version!==1||n.data.sessionId!==t.sessionId||n.data.cwd!==o||n.data.toolName!==t.toolName)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Saved approval belongs to a different Session or tool`);let s=await n.request({kind:re,data:{version:1,sessionId:t.sessionId,cwd:o,toolName:t.toolName,arguments:structuredClone(t.toolArgs)}});if(Object.keys(s).length!==1||typeof s.approved!=`boolean`)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Approval response must contain only a boolean approved decision`);return s.approved}function oe(e,t){return`${e}\u0000${JSON.stringify(t)}`}var se=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(oe(e,t))}takeRetry(e,t){return this.retries.delete(oe(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 ce(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function le(e,t){switch(e){case`path`:{let e=ce(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 ue(t,n){let r=(0,e.getToolPermissionProfile)(t).argument;if(r===void 0)return t;let i=n[r.key];if(typeof i!=`string`||i===``)return t;let a=le(r.kind,i);return a===void 0?t:`${t}(${a})`}function C(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function de(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}),C(`threw`,r)}const fe=C(`denied`,`Permission denied. The user did not approve this action.`),pe=(0,e.createLogger)(`ToolHookHelpers`);function me(t){if((0,e.wasToolResultAdmitted)(t)||typeof t.data!=`string`||t.data.length<=3e4)return t;let n=15e3,r=t.data.substring(0,n),i=t.data.substring(t.data.length-n),a=`${r}\n\n[... output truncated: ${t.data.length.toLocaleString()} chars total, showing first and last ${n.toLocaleString()} chars ...]\n\n${i}`;return{...t,data:a}}function he(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 ge(t,n,r,i){let a=await(0,e.runHooks)(t,`PreToolUse`,n,r,i);if(a.blocked){let e=a.reason??`Blocked by hook`;return C(`hook-blocked`,e,{blocked:!0,reason:e})}if((0,e.isEnforcing)(`PreToolUse`)){let e=a.errors,t=e?.[0],n=a.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return C(`hook-blocked`,i,{blocked:!0,reason:i})}if(r!==``)return C(`hook-blocked`,r,{blocked:!0,reason:r})}return null}function _e(t,n,r,i,a){(0,e.runHooks)(t,`PostToolUse`,{...n,hook_event_name:`PostToolUse`,tool_output:typeof r.data==`string`?r.data:JSON.stringify(r.data)},i,a).catch(e=>pe.warn(`hook failed`,{error:e}))}function ve(t,n){let r=(0,e.getToolPermissionProfile)(t).argument?.key;if(r===void 0)return;let i=n[r];if(typeof i==`string`)return i.length>200?`${i.slice(0,200)}…`:i}var ye=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=ve(e,t);this.entries.unshift({toolName:e,...i===void 0?{}:{argument:i},reason:n,...r===void 0?{}:{detail:r},at:this.now()}),this.calls.unshift({toolName:e,toolArgs:t}),this.calls.length>this.capacity&&(this.calls.length=this.capacity),this.entries.length>this.capacity&&(this.entries.length=this.capacity)}list(){return[...this.entries]}callAt(e){return this.calls[e]}};function be(n,r,i){let a=(0,e.getToolPermissionProfile)(n).argument;if(a===void 0||a.kind!==`path`)return r;let o=r[a.key];return typeof o!=`string`||o===``||(0,t.isAbsolute)(o)?r:{...r,[a.key]:(0,t.resolve)(i,o)}}const xe=(0,e.createLogger)(`ToolBodyTrace`);var Se=class extends Error{result;constructor(e){super(`Effective tool arguments were not authorized`),this.result=e}};function Ce(t,n){try{t?.eventService?.emit(e.TOOL_PERMISSION_EVENTS.DECIDED,{timestamp:new Date,executionId:t.executionId,decidedAt:new Date().toISOString(),decision:n})}catch(e){xe.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function we(t,n){let r=t.execute.bind(t),i=t.executeWithAdmission?.bind(t),a=e.DEFAULT_ABSTRACT_EVENT_SERVICE,o=Object.create(t),s=async(o,s,c)=>{let l=o,u=`(unknown)`;try{u=t.getName(),l=be(u,o,n.cwd),n.log(`tool_call`,{tool:u,args:l});let d=he(n.sessionId,n.cwd,u,l,n.getPermissionMode(),n.transcriptPath),f=await ge(n.config.hooks,d,n.hookTypeExecutors,s?.hookTraceEnv);if(f)return n.log(`tool_blocked`,{tool:u,reason:`hook`}),Ce(s,`hook-blocked`),f;let p=await n.checkPermission(u,l,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation);if(p!==!0)return n.log(`tool_denied`,{tool:u,reason:`permission`}),Ce(s,`denied`),n.onToolExecution?.({type:`end`,toolName:u,toolArgs:l,success:!1,denied:!0,executionId:s?.executionId}),typeof p==`object`?C(`denied`,p.message):fe;Ce(s,`allowed`),s?.signal?.throwIfAborted(),n.onToolExecution?.({type:`start`,toolName:u,toolArgs:structuredClone(l),executionId:s?.executionId}),s?.signal?.throwIfAborted();let m,h=async e=>{s?.signal?.throwIfAborted();let t=be(u,e,n.cwd);if(JSON.stringify(t)!==JSON.stringify(e))throw new Se(C(`denied`,`Tool admission requires final canonical arguments; relative paths must be resolved before admission.`));if(JSON.stringify(t)!==JSON.stringify(l)){let e=he(n.sessionId,n.cwd,u,t,n.getPermissionMode(),n.transcriptPath),r=await ge(n.config.hooks,e,n.hookTypeExecutors,s?.hookTraceEnv);if(r)throw new Se(r);let i=await n.checkPermission(u,t,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation);if(i!==!0)throw new Se(typeof i==`object`?C(`denied`,i.message):fe);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,instanceEventService:a};c&&i?_=await i(l,e,h):(c?await h(l):m=Date.now(),s?.signal?.throwIfAborted(),_=await r(l,e)),g=s?.signal?.aborted?`interrupted`:_.success?`success`:`failure`}catch(t){throw g=s?.signal?.aborted||(0,e.isAbortFailure)(t)?`interrupted`:`failure`,t}finally{try{m!==void 0&&s?.eventService?.emit(e.TOOL_BODY_EVENTS.COMPLETED,{timestamp:new Date,executionId:s.executionId,startedAt:new Date(m).toISOString(),endedAt:new Date(Math.max(Date.now(),m)).toISOString(),outcome:g,...typeof s.toolBodyId==`string`?{toolBodyId:s.toolBodyId}:{}})}catch(e){xe.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let v=me(_);v!==_&&typeof _.data==`string`&&n.terminal.writeLine(` ⚠ Output truncated: ${_.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),n.onToolExecution?.({type:`end`,toolName:u,toolArgs:l,success:v.success,toolResultData:typeof v.data==`string`?v.data:JSON.stringify(v.data),executionId:s?.executionId});let y=typeof v.data==`string`?v.data.length:JSON.stringify(v.data)?.length??0;return n.log(`tool_result`,{tool:u,success:v.success,dataChars:y,truncated:v!==_}),_e(n.config.hooks,d,v,n.hookTypeExecutors,s?.hookTraceEnv),v}catch(t){if((0,e.isExecutionControlError)(t))throw t;return t instanceof Se?t.result:de(t,n.onToolExecution,{toolName:u,toolArgs:l,executionId:s?.executionId})}};return o.execute=s,o.executeWithAdmission=s,o.setEventService=n=>{a=n??e.DEFAULT_ABSTRACT_EVENT_SERVICE,t.setEventService(n)},o}function Te(e){let n=e,r=[];for(;;)try{let e=(0,i.realpathSync)(n);return r.length===0?e:(0,t.resolve)(e,...r.reverse())}catch{let i=(0,t.dirname)(n);if(i===n)return e;r.push(n.slice(i.length).replace(/^[\\/]/,``)),n=i}}function Ee(e,n){let r=(0,t.relative)(e,n);return r===``||!r.startsWith(`..`)&&!(0,t.isAbsolute)(r)}function De(e){return(n,r)=>{let i=Te(e),a=Te((0,t.resolve)(n??i,r));return Ee(i,a)?a:void 0}}function Oe(t){let n=[...(0,e.findInvalidPermissionPatterns)(t.allow,`allow`),...(0,e.findInvalidPermissionPatterns)(t.restrictive,`deny`)];if(n.length===0)return;let r=n.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${r}. Fix the pattern where it is configured (issue #2428).`)}var ke=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;homeDirectory;resolveInWorkspace;commandSandbox;denials=new ye;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]},Oe(this.configuredRules(e)),this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool,this.permissionPolicy=e.permissionPolicy,this.taskPermissions=e.taskPermissions,this.homeDirectory=e.homeDirectory??(0,r.homedir)(),this.resolveInWorkspace=De(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new se(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(t){let n=(0,e.getToolPermissionProfile)(t);return!this.peerTurn&&n.repliesToPeer===!0||this.peerTurn&&n.notInPeerTurn===!0?!1:!(0,e.isToolDeniedOutright)(t,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(t){for(let n of t){let t=n.schema;if(t===void 0)continue;let r=t.parameters?.properties??{};(0,e.registerToolPermissionProfile)(t.name,{parameters:Object.keys(r)})}let n=this.configuredRules();Oe(n);for(let{pattern:t,reason:r}of(0,e.findPermissionPatternWarnings)(n.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${t}" ${r}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i,a)=>this.decidePermission(e,t,n,r,i,{continuation:a})};return e.map(e=>we(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(t){let n=(0,e.applyPresetToolLists)(this.presetFreeRules,t);this.config.permissions.allow=n.allow,this.config.permissions.deny=n.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=he(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath);return await ge(this.config.hooks,r,this.hookTypeExecutors)?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1})===!0}async decidePermission(e,t,n,r=`interactive`,i,a={}){let o=await this.evaluateToolPermission(e,t,n,r,i,a);return o===!0?(n?.throwIfAborted(),await ae({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a.continuation,!1)??!0):o}async evaluateToolPermission(t,n,r,i=`interactive`,a,o={}){let s=this.permissionPolicy===void 0?void 0:(0,e.projectPermissionPolicy)(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),c=this.getPermissionMode(),l=[...this.config.permissions.allow,...s?.allow??[]],u={allow:c===`auto`?(0,e.allowRulesForAutoMode)(l):l,deny:[...this.config.permissions.deny,...s?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory},f=(0,e.evaluatePermission)(t,n,c,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:o.sandboxed!==!1&&this.sandboxAutoApproves(t,n),...s?.ceiling===void 0?{}:{ceiling:s.ceiling},askAll:s?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(t,n,f,a),f===`auto`)return!0;if(f===`deny`)return this.denials.record(t,n,`policy`),!1;let p=(0,e.requiresFreshApproval)(t,n,u,d);return c===`auto`&&this.autoMode!==void 0&&!p&&s?.askAll!==!0?this.decideInAutoMode(this.autoMode,t,n,r,i,a,o):this.promptForApproval(t,n,r,i,p,o.continuation)}async decideInAutoMode(t,n,r,i,a,o,s){if(t.takeRetry(n,r)||(0,e.matchesAnyPattern)(n,r,(0,e.allowRulesForAutoMode)([...this.sessionAllowedTools])))return!0;if(t.isPaused()){let e=await this.promptForApproval(n,r,i,a,!0,s.continuation);return e&&!this.checkpointedApprovals&&!ie(s.continuation)&&t.resume(),e}let c=await t.judge({toolName:n,toolArgs:r,cwd:this.cwd},i);return i?.aborted===!0?!1:this.getPermissionMode()===`auto`?c.kind===`allow`?!0:(this.denials.record(n,r,`classifier`,c.reason),{message:c.message}):this.decidePermission(n,r,i,a,o,s)}async promptForApproval(t,n,r,i=`interactive`,a=!1,o){let s=!a&&(0,e.matchesAnyPattern)(t,n,[...this.sessionAllowedTools]);if(this.checkpointedApprovals&&!s||ie(o)){if(r?.aborted||i!==`interactive`)return!1;let e=await ae({sessionId:this.sessionId,cwd:this.cwd,toolName:t,toolArgs:n},o,!0);return e!==!0&&this.denials.record(t,n,`user`),e===!0}let c=ue(t,n),l=r?.aborted===!0,u=i===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),d=await ne({toolName:t,alreadyAllowed:s,...i===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...i===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:n,...r?{signal:r}:{}});if(!d.allowed&&!l&&this.denials.record(t,n,u?`user`:`no-approver`),a)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(t,n,r,i){let a=this.getPermissionMode();(0,e.runHooks)(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:t,tool_input:n,permission_decision:r,...a!==void 0&&{permission_mode:a},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,i).catch(()=>void 0)}sandboxAutoApproves(t,n){if(this.commandSandbox===void 0)return!1;let r=(0,e.getToolPermissionProfile)(t).argument;if(r?.kind!==`command`)return!1;let i=n[r.key];return typeof i==`string`&&this.commandSandbox.autoApproves(t,i)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function Ae(e,t,n,r,i){return new ke({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 je(e,t,n,r){return{contextTracker:new x(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new y({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Me(t,n,r,i,a,o,s){let c=n.wrapTools(r);return new e.Robota({name:t.agentName??`agent`,aiProviders:[i],defaultModel:{provider:i.name,model:a,...t.effort!==void 0&&{effort:t.effort},...t.temperature!==void 0&&{temperature:t.temperature},...t.maxOutputTokens!==void 0&&{maxTokens:t.maxOutputTokens}},systemMessage:o,tools:c,isToolVisible:e=>n.isToolVisible(e),logging:{enabled:!1},eventService:s,...t.providerTimeout!==void 0&&{timeout:t.providerTimeout},...t.responseFormat?{responseFormat:t.responseFormat}:{},...t.ask?{ask:t.ask}:{},...t.contextCapacityHint===void 0?{}:{contextCapacityHint:t.contextCapacityHint}})}const Ne=(0,e.createLogger)(`SessionHistoryOps`);function Pe(e,t){return{...e,...t}}async function Fe(t,n,r){r?.throwIfAborted();let i=n.agent.getHistory(),a=i.filter(e=>e.role!==`system`);if(a.length===0)return;n.contextTracker.updateFromHistory(i);let o=n.contextTracker.getContextState(),s=await n.compactionOrchestrator.compact(n.aiProvider,a,t,r,n.trigger,n.hookTraceEnv,n.executionJournal);n.agent.clearHistory(),n.agent.injectMessage(`system`,n.systemMessage),n.agent.injectMessage(`assistant`,`[Context Summary]\n${s}`),n.contextTracker.updateFromHistory(n.agent.getHistory());let c={session_id:n.sessionId,cwd:n.cwd,hook_event_name:`PostCompact`,trigger:n.trigger,compact_summary:s};(0,e.runHooks)(n.hooks,`PostCompact`,c,n.hookTypeExecutors,n.hookTraceEnv).catch(e=>Ne.warn(`hook failed`,{error:e}));let l=n.contextTracker.getContextState();n.log(`context_compact`,{trigger:n.trigger,before:o,after:l}),n.onCompactEventCallback?.({trigger:n.trigger,before:o,after:l}),n.onCompactCallback&&n.onCompactCallback(s)}function Ie(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 Le=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Re(){return`session_${(0,n.randomUUID)()}`}function ze(e){return e.length>0&&e.length<=128&&Le.test(e)}function Be(e){if(!ze(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 Ve=(0,e.createLogger)(`SessionLifecycle`);function He(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function Ue(t,n,r,i,a,o,s){(0,e.runHooks)(r,`SessionStart`,{session_id:t,cwd:n,hook_event_name:`SessionStart`,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},i).then(e=>{e.stdout&&a(e.stdout)}).catch(e=>Ve.warn(`SessionStart hook failed`,{error:e}))}async function We(t,n,r,i,a,o,s){await(0,e.runHooks)(i,`SessionEnd`,{session_id:t,cwd:n,hook_event_name:`SessionEnd`,reason:r,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},a)}const Ge=`unknown_tool`;function Ke(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function qe(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){Je(e,n);return}t===`tool_execution_result`&&Ye(e,n)}}function Je(e,t){let n=w(t.toolName),r=w(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:Xe(t.parameters)}))}function Ye(e,t){let n=w(t.toolName),r=w(t.toolCallId);if(!n||!r)return;let i=Ze(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===Ge))return;e.unknownToolCallIds.delete(r);let a=w(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:Ge,requestedTool:w(i?.requestedTool)??n,availableTools:Qe(i?.availableTools)})})}function Xe(e){let t=Ze(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 w(e){return typeof e==`string`&&e.length>0?e:void 0}function Ze(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Qe(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const $e=(0,e.createLogger)(`SessionRunObservation`);function et(t,n,r,i){let a=typeof r.model==`string`?r.model:t.model,o=typeof r.provider==`string`?r.provider:t.aiProvider.name,s=r.effort,c=typeof s==`string`&&(0,e.isModelEffort)(s)?s:t.effort??(typeof t.agent.getModel==`function`?t.agent.getModel().effort:void 0)??`high`,l=typeof r.round==`number`?r.round:void 0;(0,e.runHooks)(t.hooks,n,{session_id:t.sessionId,cwd:t.cwd,hook_event_name:n,model:a,provider:o,effort:c,...l!==void 0&&{round:l},...t.permissionMode!==void 0&&{permission_mode:t.permissionMode},...t.transcriptPath!==void 0&&{transcript_path:t.transcriptPath},env:{CLAUDE_PROJECT_DIR:t.cwd,CLAUDE_SESSION_ID:t.sessionId}},t.hookTypeExecutors,i).catch(e=>$e.warn(`hook failed`,{error:e}))}function tt(t,n){let r=n?(0,e.traceEnvFor)(`hooks`,n,n.parentSpanId):void 0,i=Ke({knownToolNames:t.knownToolNames??[],...t.onToolExecution&&{onToolExecution:t.onToolExecution}}),a=t.onTextDelta?e=>{t.log(`text_delta`,{delta:e}),t.onTextDelta?.(e)}:void 0,o={};return{onExecutionEvent:(n,a)=>{if(n!==e.PROVIDER_CALL_EVENTS.COMPLETED&&t.log(n,a),qe(i,n,a),n===`provider_request`){let e=a;o={model:e.model,provider:e.provider},et(t,`PreModelCall`,e,r)}else if(n===`provider_response_normalized`)et(t,`PostModelCall`,{...a,...o},r);else if(n===e.PROVIDER_FALLBACK_EVENTS.SWITCHED){let n=(0,e.readModelFallbackNotice)(a);n!==void 0&&(et(t,`PostModelCall`,{round:a.round,model:n.from.model,provider:n.from.provider},r),t.emitProviderFallback?.(n))}else if(n===e.PROVIDER_CALL_EVENTS.COMPLETED&&t.emitProviderCallCompleted){let e=a;Number.isSafeInteger(e.round)&&e.round>0&&typeof e.startedAt==`string`&&typeof e.endedAt==`string`&&(e.outcome===`success`||e.outcome===`failure`||e.outcome===`interrupted`)&&t.emitProviderCallCompleted({round:e.round,startedAt:e.startedAt,endedAt:e.endedAt,outcome:e.outcome,...typeof e.callId==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.callId)&&{callId:e.callId},...(e.disposition===`invoked`||e.disposition===`cache-hit`||e.disposition===`preflight-refused`)&&{disposition:e.disposition},...typeof e.providerId==`string`&&e.providerId.length>0&&e.providerId.length<=128&&[...e.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:e.providerId},...typeof e.modelId==`string`&&e.modelId.length>0&&e.modelId.length<=128&&[...e.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:e.modelId},...(e.usageProvenance===`complete`||e.usageProvenance===`partial`||e.usageProvenance===`absent`)&&{usageProvenance:e.usageProvenance},...e.usageProvenance===`complete`&&typeof e.promptTokens==`number`&&Number.isSafeInteger(e.promptTokens)&&e.promptTokens>=0&&typeof e.completionTokens==`number`&&Number.isSafeInteger(e.completionTokens)&&e.completionTokens>=0&&typeof e.totalTokens==`number`&&Number.isSafeInteger(e.totalTokens)&&e.totalTokens===e.promptTokens+e.completionTokens&&{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens},...e.disposition===`invoked`&&typeof e.providerRequestId==`string`&&{providerRequestId:e.providerRequestId}})}n===`assistant_message_committed`&&(t.contextTracker.updateFromHistory(t.agent.getHistory()),t.onContextUpdate?.(t.contextTracker.getContextState()))},...a&&{onTextDelta:a}}}async function nt(e,t){let n=await e.agent.resume({...t,...tt(e,t.traceContext)});return e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()),e.getSessionStore()&&e.persistSession(),n}function rt(e,t){let n=(0,i.realpathSync)(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:`robota-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 it(t,n,r,a){let o,s=(0,i.realpathSync)(r);return{read:async i=>{let c=structuredClone(await t.read(i)),l;for(let t of c){if(t.kind!==`model-request`&&t.kind!==`model-cache-hit`)continue;let r=t.checkpoint?.owner,a=r?.state;if(!r||r.kind!==`robota-session`||r.version!==1||!a||a.sessionId!==n||a.cwd!==s||a.executionId!==i||typeof a.peerTurn!=`boolean`||l!==void 0&&l!==a.peerTurn||a.peerTurn&&t.checkpoint?.continuation?.options.withholdHostedTools!==!0)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session continuation owner or scope is incompatible`);l=a.peerTurn}if(l===void 0)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`No Session owner checkpoint exists`);return o=rt(t,{sessionId:n,cwd:r,peerTurn:l}),a(l),c},append:async t=>{if(!o)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session owner has not been restored`);await o.append(t)}}}function at(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 ot=(0,e.createLogger)(`SessionRun`);async function st(t,n,r,i,a){let o=a?.traceContext,s=o?(0,e.traceEnvFor)(`hooks`,o,o.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{a?.executionJournal?await r.compact(i,s,a.executionJournal):await(s?r.compact(i,s):r.compact(i))}finally{e.onTextDelta=t}}r.log(`user`,{content:t});let c=await(0,e.runHooks)(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,s),l=[r.sessionStartStdout,c.stdout].filter(Boolean).join(`
|
|
6
|
-
`),u=l?`<system-reminder>\n${l}\n</system-reminder>\n${t}`:t;r.clearSessionStartStdout();let d=r.agent.getHistory(),f=JSON.stringify(d),p=(0,e.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:d.length,historyChars:f.length,historyEstTokens:Math.ceil(f.length/e.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:u,history:d,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:p.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:p.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:p.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:p.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...d,(0,e.createUserMessage)(u)]),r.onContextUpdate?.(r.contextTracker.getContextState());let m;try{if(m=await r.agent.run(u,{signal:i,maxExecutionRounds:r.maxTurns??0,...at(a),...tt(r,o)}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(t){if(t instanceof e.ExecutionSuspendedError)throw t;try{r.log(`error`,{message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack??``:``,historyLength:r.agent.getHistory().length})}catch{}throw(0,e.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:t instanceof Error?t.message:String(t),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>ot.warn(`hook failed`,{error:e})),t}let h=r.agent.getHistory(),g=h.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:m,historyLength:h.length,estimatedChars:JSON.stringify(h).length,history:h,historyStructure:g}),r.contextTracker.updateFromHistory(h);let _=r.contextTracker.getContextState();return r.onContextUpdate?.(_),r.log(`context`,{maxTokens:_.maxTokens,usedTokens:_.usedTokens,usedPercentage:_.usedPercentage,remainingPercentage:_.remainingPercentage}),(0,e.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:m.substring(0,500),last_assistant_message:m,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>ot.warn(`hook failed`,{error:e})),r.getSessionStore()&&r.persistSession(),m}function ct(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function lt(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 ut(e,t,n){let r=lt(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 dt(e,t){return{read:t=>e.read(t),append:n=>(n.kind===`tool-effect-start`&&t.add(n.actionId),e.append(n))}}function ft(t,n){let r=lt(t);if(!r||r.assistant.metadata?.executionId!==n.executionId)return[];let i=new Set(n.requests.map(e=>e.toolCallId));return r.open.map(t=>{let n=i.has(t.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return(0,e.createToolMessage)(`Error: ${n}`,{toolCallId:t.id,name:t.function.name,metadata:{success:!1,error:n,toolName:t.function.name}})})}async function pt(t,n){if(!n||typeof n.append!=`function`||typeof n.read!=`function`)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await t()}}catch(t){if(t instanceof e.ExecutionSuspendedError)return{status:`waiting`,requests:structuredClone(t.requests)};throw t}}var mt=class{agent;claim;sessionId;execution=null;constructor(e,t,n){this.agent=e,this.claim=t,this.sessionId=n}async invoke(e,t,r){let i=this.claim.claim(),a=ht(i,r);try{return i.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:(0,n.randomUUID)(),sessionId:this.sessionId,signal:i.signal,permissionInteraction:`deny`}),await this.execution}finally{this.execution=null,a(),this.claim.release(i)}}async drain(){await this.execution}};function ht(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var gt=class extends f{agent;eventService=new e.ObservableEventService;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;pendingExecution;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(t){super(t.cwd);let{tools:n,provider:r,systemMessage:i}=t;this.terminal=t.terminal,this.sessionStore=t.sessionStore,this.systemMessage=i,this.toolSchemas=n.map(e=>e.schema),this.wrapAddedTools=t.wrapAddedTools,this.sessionLogger=t.sessionLogger,this.hooks=t.hooks,this.hookTypeExecutors=t.hookTypeExecutors,this.onTextDeltaCallback=t.onTextDelta,this.onContextUpdateCallback=t.onContextUpdate,this.onToolExecutionCallback=t.onToolExecution,this.onCompactCallback=t.onCompact,this.onCompactEventCallback=t.onCompactEvent,this.maxTurns=t.maxTurns,this.model=t.model??`claude-sonnet-4-5`,this.sessionId=t.sessionId??Re(),this.permissionMode=t.permissionMode??(t.defaultTrustLevel?e.TRUST_TO_MODE[t.defaultTrustLevel]:void 0)??`default`,this.activePresetId=t.activePresetId??`default`,this.parallelSubagentsEnabled=t.enableParallelSubagents??!0,this.transcriptPath=t.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,He(r,t,(e,t)=>this.log(e,t)),this.permissionEnforcer=Ae(t,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:a,compactionOrchestrator:o}=je(t,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.agent=Me(t,this.permissionEnforcer,n,r,this.model,i,this.eventService),this.runtimeTools=new mt(this.agent,this.turnClaim,this.sessionId),Ue(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 pt(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(t,n,r,i){let a=r?{...r}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.pendingExecution)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`);let o=this.turnClaim.claim(),s=ht(o,a?.signal),{signal:c}=o;this.permissionEnforcer.beginTurn(a?.peerTurn===!0,i);try{c.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=a?.executionJournal?{...a,executionJournal:rt(a.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:a.peerTurn===!0})}:a,r=await st(t,n,this.buildRunContext(),c,e);return this.messageCount+=1,r}catch(t){throw t instanceof e.ExecutionSuspendedError?(this.pendingExecution=ct(t),c.throwIfAborted()):a?.executionJournal&&(this.pendingExecution=ut(this.agent.getHistory(),void 0,new Set)),t}finally{this.permissionEnforcer.endTurn(),s(),this.turnClaim.release(o)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return pt(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(t,n){let r={...t,toolResponses:structuredClone(t.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.pendingExecution&&this.pendingExecution.executionId!==r.executionId)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let i=this.turnClaim.claim(),a=ht(i,r.signal),o=new Set;try{i.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=it(dt(r.journal,o),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,n)),t=await nt(this.buildRunContext(),{...r,journal:e,signal:i.signal});return this.pendingExecution=void 0,t}catch(t){throw t instanceof e.ExecutionSuspendedError?(this.pendingExecution=ct(t),i.signal.throwIfAborted()):this.pendingExecution=ut(this.agent.getHistory(),this.pendingExecution,o),t}finally{this.permissionEnforcer.endTurn(),a(),this.turnClaim.release(i)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(t){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);let n=this.pendingExecution;if(!n)return;if(n.executionId!==t)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim();try{for(let e of ft(this.agent.getHistory(),n))this.agent.injectRawMessage(e);this.pendingExecution=void 0,this.persistSessionInternal()}finally{this.turnClaim.release(r)}}addTools(e){return this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.runtimeTools.invoke(e,t,n?.signal)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&Ie({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,agent:this.agent,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>We(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 Fe(e,Pe(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(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:t=>this.eventService.emit(e.PROVIDER_CALL_EVENTS.COMPLETED,{timestamp:new Date,...t},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:t=>this.eventService.emit(e.PROVIDER_FALLBACK_EVENTS.SWITCHED,{timestamp:new Date,fromProvider:t.from.provider,fromModel:t.from.model,toProvider:t.to.provider,toModel:t.to.model,reason:t.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};function T(e,t){return e.length===0?t:`${e}.${t}`}function E(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 _t(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,E(t,a),n);o!==void 0&&i.push(o)}),i}function vt(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,T(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,T(t,a),n);e!==void 0&&(i[a]=e)}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,E(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 yt(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)}`)}const bt=[`complete`,`interrupted`],V=[`id`,`timestamp`,`state`,`metadata`,`role`,`content`,`parts`],xt={user:[...V,`name`],assistant:[...V,`toolCalls`],system:[...V,`name`],tool:[...V,`toolCallId`,`name`]};function St(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){let r={};for(let[i,a]of Object.entries(e)){if(typeof a!=`number`){D(n,T(t,i),`expected a number, received ${O(a)}`);continue}r[i]=a}return r}D(n,t,`expected a metadata value, received ${O(e)}`)}function Ct(e,t,n){return z(e,t,n,St)}function wt(e,t,n){let r=F(e?.type,[`text`,`image_inline`,`image_uri`],T(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,T(t,`text`),n);return i===void 0?void 0:{type:`text`,text:i}}if(r===`image_inline`){let r=R(e,t,n,[`type`,`mimeType`,`data`]);if(r===void 0)return;let i=j(r.mimeType,T(t,`mimeType`),n),a=j(r.data,T(t,`data`),n);return i===void 0||a===void 0?void 0:{type:`image_inline`,mimeType:i,data:a}}let i=R(e,t,n,[`type`,`uri`,`mimeType`]);if(i===void 0)return;let a=j(i.uri,T(t,`uri`),n);if(a===void 0)return;let o={type:`image_uri`,uri:a};return k(o,`mimeType`,A(i.mimeType,T(t,`mimeType`),n,j)),o}function Tt(e,t,n){let r=R(e,t,n,[`id`,`type`,`function`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=F(r.type,[`function`],T(t,`type`),n),o=T(t,`function`),s=R(r.function,o,n,[`name`,`arguments`]),c=s===void 0?void 0:j(s.name,T(o,`name`),n),l=s===void 0?void 0:j(s.arguments,T(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 Et(e,t,n){let r=j(e.id,T(t,`id`),n),i=_t(e.timestamp,T(t,`timestamp`),n),a=F(e.state,bt,T(t,`state`),n);if(r!==void 0&&i!==void 0&&a!==void 0)return{id:r,timestamp:i,state:a}}function Dt(e,t,n,r){k(e,`metadata`,A(t.metadata,T(n,`metadata`),r,Ct)),k(e,`parts`,A(t.parts,T(n,`parts`),r,(e,t,n)=>L(e,t,n,wt)))}function H(e,t,n){let r=F(e?.role,[`user`,`assistant`,`system`,`tool`],T(t,`role`),n);if(r===void 0)return;let i=R(e,t,n,xt[r]);if(i===void 0)return;let a=Et(i,t,n);if(a===void 0)return;let o=T(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 Dt(s,i,t,n),k(s,`toolCalls`,A(i.toolCalls,T(t,`toolCalls`),n,(e,t,n)=>L(e,t,n,Tt))),s}let s=j(i.content,o,n);if(s===void 0)return;if(r===`tool`){let e=j(i.toolCallId,T(t,`toolCallId`),n);if(e===void 0)return;let o={...a,role:r,content:s,toolCallId:e};return Dt(o,i,t,n),k(o,`name`,A(i.name,T(t,`name`),n,j)),o}let c={...a,role:r,content:s};return Dt(c,i,t,n),k(c,`name`,A(i.name,T(t,`name`),n,j)),c}function Ot(e,t,n){let r=R(e,t,n,[`id`,`timestamp`,`category`,`type`,`data`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=_t(r.timestamp,T(t,`timestamp`),n),o=j(r.category,T(t,`category`),n),s=j(r.type,T(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,T(t,`data`),n,B)),c}const kt=[`agent`,`process`,`scheduled`,`tool-invocation`],At=[`foreground`,`background`],jt=[`none`,`worktree`],Mt=[`queued`,`running`,`waiting_permission`,`sleeping`,`paused`,`completed`,`failed`,`cancelled`],Nt=[`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`],Pt=[`validation`,`capacity`,`permission`,`timeout`,`runner`,`crash`,`provider`,`process`],Ft=[`denied-by-person`,`no-approver`,`approver-error`,`cancelled`];function It(e,t,n){return z(e,t,n,yt)}function Lt(e,t,n){return z(e,t,n,j)}function Rt(e,t,n){let r=R(e,t,n,[`category`,`message`,`recoverable`]);if(r===void 0)return;let i=F(r.category,Pt,T(t,`category`),n),a=j(r.message,T(t,`message`),n),o=P(r.recoverable,T(t,`recoverable`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{category:i,message:a,recoverable:o}}function zt(e,t,n){let r=R(e,t,n,[`promptTokens`,`completionTokens`,`totalTokens`]);if(r===void 0)return;let i=N(r.promptTokens,T(t,`promptTokens`),n),a=N(r.completionTokens,T(t,`completionTokens`),n),o=N(r.totalTokens,T(t,`totalTokens`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{promptTokens:i,completionTokens:a,totalTokens:o}}function Bt(e,t,n){let r=R(e,t,n,[`total`,`byReason`]);if(r===void 0)return;let i=N(r.total,T(t,`total`),n),a=T(t,`byReason`),o=R(r.byReason,a,n,Ft);if(i===void 0||o===void 0)return;let s={},c=!0;for(let e of Ft){let t=N(o[e],T(a,e),n);if(t===void 0){c=!1;continue}s[e]=t}if(c)return{total:i,byReason:s}}function Vt(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,T(t,`taskId`),n),a=F(r.kind,kt,T(t,`kind`),n),o=j(r.output,T(t,`output`),n);if(i===void 0||a===void 0||o===void 0)return;let s=A(r.exitCode,T(t,`exitCode`),n,N),c=A(r.signalCode,T(t,`signalCode`),n,j),l=A(r.metadata,T(t,`metadata`),n,It),u=A(r.usage,T(t,`usage`),n,zt),d=A(r.deniedToolCalls,T(t,`deniedToolCalls`),n,Bt);switch(a!==`process`&&s!==void 0&&D(n,T(t,`exitCode`),`must not be set for a '${a}' result`),a!==`process`&&c!==void 0&&D(n,T(t,`signalCode`),`must not be set for a '${a}' result`),a!==`agent`&&u!==void 0&&D(n,T(t,`usage`),`must not be set for a '${a}' result`),a!==`agent`&&d!==void 0&&D(n,T(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 Ht(e,t,n){let r=R(e,t,n,[`cronExpression`,`agentInstruction`,`command`,`shell`,`env`]);if(r===void 0)return;let i=j(r.cronExpression,T(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],T(t,e),n,j));return k(a,`env`,A(r.env,T(t,`env`),n,Lt)),a}const Ut=[`detached`,`wait_all`,`wait_any`,`manual`],Wt=[`running`,`completed`],Gt=[`background_job_group_created`,`background_job_group_updated`,`background_job_group_completed`];function Kt(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,T(t,`taskId`),n),a=j(r.label,T(t,`label`),n),o=F(r.status,Mt,T(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],T(t,e),n,j));for(let e of[`startedAt`,`completedAt`])k(s,e,A(r[e],T(t,e),n,I));return k(s,`error`,A(r.error,T(t,`error`),n,Rt)),s}function qt(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,T(t,`id`),n),a=j(r.parentSessionId,T(t,`parentSessionId`),n),o=F(r.waitPolicy,Ut,T(t,`waitPolicy`),n),s=vt(r.taskIds,T(t,`taskIds`),n),c=F(r.status,Wt,T(t,`status`),n),l=I(r.createdAt,T(t,`createdAt`),n),u=I(r.updatedAt,T(t,`updatedAt`),n),d=L(r.results,T(t,`results`),n,Kt);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,T(t,`label`),n,j)),k(f,`completedAt`,A(r.completedAt,T(t,`completedAt`),n,I)),f}function Jt(e,t,n){let r=F(e?.type,Gt,T(t,`type`),n);if(r===void 0)return;let i=R(e,t,n,[`type`,`group`]);if(i===void 0)return;let a=qt(i.group,T(t,`group`),n);return a===void 0?void 0:{type:r,group:a}}const Yt=[`parentTaskId`,`currentAction`,`logPath`,`transcriptPath`],Xt=[`agentType`,`resumeSessionId`,`promptPreview`,`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`],Zt=[`commandPreview`],Qt=[`startedAt`,`lastActivityAt`,`completedAt`],$t=[`id`,`kind`,`label`,`status`,`mode`,`parentSessionId`,`depth`,`cwd`,`pid`,`updatedAt`,`isolation`,`unread`,`result`,`error`,`timeoutReason`,`schedule`,`nextFireAt`,`metadata`,...Yt,...Xt,...Zt,...Qt];function en(e,t,n){let r=R(e,t,n,$t);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=F(r.kind,kt,T(t,`kind`),n),o=j(r.label,T(t,`label`),n),s=F(r.status,Mt,T(t,`status`),n),c=F(r.mode,At,T(t,`mode`),n),l=j(r.parentSessionId,T(t,`parentSessionId`),n),u=N(r.depth,T(t,`depth`),n),d=j(r.cwd,T(t,`cwd`),n),f=I(r.updatedAt,T(t,`updatedAt`),n),p=P(r.unread,T(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 Yt)k(m,e,A(r[e],T(t,e),n,j));for(let e of Qt)k(m,e,A(r[e],T(t,e),n,I));k(m,`pid`,A(r.pid,T(t,`pid`),n,N)),k(m,`timeoutReason`,A(r.timeoutReason,T(t,`timeoutReason`),n,(e,t,n)=>F(e,Nt,t,n))),k(m,`metadata`,A(r.metadata,T(t,`metadata`),n,It)),k(m,`error`,A(r.error,T(t,`error`),n,Rt));let h=A(r.result,T(t,`result`),n,Vt);h!==void 0&&(h.taskId!==i&&D(n,T(T(t,`result`),`taskId`),`must match the task ID`),h.kind!==a&&D(n,T(T(t,`result`),`kind`),`must match the task kind`));let g=A(r.agentType,T(t,`agentType`),n,j),_=A(r.resumeSessionId,T(t,`resumeSessionId`),n,j),v=A(r.promptPreview,T(t,`promptPreview`),n,j),y=A(r.isolation,T(t,`isolation`),n,(e,t,n)=>F(e,jt,t,n)),b={};for(let e of[`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`])b[e]=A(r[e],T(t,e),n,j);for(let e of Xt){let r=e===`agentType`?g:e===`resumeSessionId`?_:e===`promptPreview`?v:b[e];a!==`agent`&&r!==void 0&&D(n,T(t,e),`must not be set for a '${a}' task`)}a!==`agent`&&y!==void 0&&D(n,T(t,`isolation`),`must not be set for a '${a}' task`);let x=A(r.commandPreview,T(t,`commandPreview`),n,j);a===`agent`&&x!==void 0&&D(n,T(t,`commandPreview`),`must not be set for a '${a}' task`);let S=A(r.schedule,T(t,`schedule`),n,Ht),ee=A(r.nextFireAt,T(t,`nextFireAt`),n,I);switch(a!==`scheduled`&&S!==void 0&&D(n,T(t,`schedule`),`must not be set for a '${a}' task`),a!==`scheduled`&&ee!==void 0&&D(n,T(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 tn=[`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,T(t,`taskId`),n)}function nn(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,T(t,`delta`),n);if(i!==void 0&&a!==void 0)return{type:`background_task_text_delta`,taskId:i,delta:a}}function rn(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,T(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,T(t,`firstArg`),n,j)),o}function an(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,T(t,`toolName`),n),o=P(r.success,T(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,T(t,`error`),n,j)),s}function on(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,T(t,`requestId`),n),o=j(r.toolName,T(t,`toolName`),n),s=It(r.toolArgs,T(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 sn(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 cn(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,T(t,`instruction`),n,j)),a}function ln(e,t,n,r){let i=R(t,n,r,[`type`,`task`]);if(i===void 0)return;let a=en(i.task,T(n,`task`),r);if(a!==void 0)return{type:e,task:a}}const un={background_task_text_delta:nn,background_task_tool_start:rn,background_task_tool_end:an,background_task_permission_request:on,background_task_closed:sn,background_task_waking:cn};function dn(e,t,n){let r=F(e?.type,tn,T(t,`type`),n);if(r===void 0)return;let i=un[r];return i===void 0?ln(r,e,t,n):i(e,t,n)}const fn=[`skill`,`plugin`],pn=[`user-slash`,`model-tool`],mn=[`inject`,`fork`],hn=[`started`,`completed`,`failed`],gn=[`memory_candidate_extracted`,`memory_candidate_queued`,`memory_candidate_saved`,`memory_candidate_skipped`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`],_n=[`manual`,`prompt-reference`,`system`],vn=[`active`,`observed`];function yn(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`],T(t,`type`),n),a=j(r.skillName,T(t,`skillName`),n),o=F(r.source,fn,T(t,`source`),n),s=F(r.invocation,pn,T(t,`invocation`),n),c=F(r.mode,mn,T(t,`mode`),n),l=F(r.status,hn,T(t,`status`),n),u=I(r.timestamp,T(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,T(t,`qualifiedName`),n,j),f=A(r.error,T(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 bn(e,t,n){let r=R(e,t,n,[`topic`,`path`,`score`,`truncated`]);if(r===void 0)return;let i=j(r.topic,T(t,`topic`),n),a=j(r.path,T(t,`path`),n),o=M(r.score,T(t,`score`),n),s=P(r.truncated,T(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 xn(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,gn,T(t,`type`),n),a=I(r.at,T(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],T(t,e),n,j));return k(o,`data`,A(r.data,T(t,`data`),n,(e,t,n)=>z(e,t,n,B))),o}function Sn(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,T(t,`id`),n),a=j(r.sourcePath,T(t,`sourcePath`),n),o=j(r.relativePath,T(t,`relativePath`),n),s=j(r.originalReference,T(t,`originalReference`),n),c=F(r.loadType,_n,T(t,`loadType`),n),l=F(r.status,vn,T(t,`status`),n),u=N(r.byteLength,T(t,`byteLength`),n),d=I(r.loadedAt,T(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,T(t,`lastUsedAt`),n,I)),f}const Cn=[`active`,`satisfied`,`stopped`],wn=[`satisfied`,`max-iterations`,`cancelled`,`no-progress`],Tn=[`continue`,`satisfied`],En=[`pending`,`in-progress`,`done`],Dn=[`planning`,`awaiting-approval`,`executing`,`completed`];function On(e,t,n){let r=R(e,t,n,[`iteration`,`signal`,`reason`]);if(r===void 0)return;let i=N(r.iteration,T(t,`iteration`),n),a=F(r.signal,Tn,T(t,`signal`),n),o=j(r.reason,T(t,`reason`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{iteration:i,signal:a,reason:o}}function kn(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,T(t,`id`),n),a=j(r.objective,T(t,`objective`),n),o=F(r.status,Cn,T(t,`status`),n),s=N(r.iterations,T(t,`iterations`),n),c=N(r.maxIterations,T(t,`maxIterations`),n),l=I(r.startedAt,T(t,`startedAt`),n),u=L(r.progress,T(t,`progress`),n,On);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,T(t,`stopReason`),n,(e,t,n)=>F(e,wn,t,n))),d}function An(e,t,n){let r=R(e,t,n,[`id`,`description`,`status`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=j(r.description,T(t,`description`),n),o=F(r.status,En,T(t,`status`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{id:i,description:a,status:o}}function jn(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,T(t,`id`),n),a=j(r.objective,T(t,`objective`),n),o=L(r.steps,T(t,`steps`),n,An),s=F(r.phase,Dn,T(t,`phase`),n),c=I(r.createdAt,T(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,T(t,`approvedAt`),n,I)),l}function Mn(e,t,n){let r=R(e,t,n,[`branchId`,`checkpointId`]);if(r===void 0)return;let i=j(r.branchId,T(t,`branchId`),n),a=j(r.checkpointId,T(t,`checkpointId`),n);if(i!==void 0&&a!==void 0)return{branchId:i,checkpointId:a}}const Nn=[`waiting`,`pending`,`running`,`stopped`,`expired`],Pn=[`loopId`,`instruction`,`useDefaultPrompt`,`createdAt`,`expiresAt`,`revision`,`generation`,`phase`,`nextAllowedAt`,`delaySeconds`,`reason`,`fallbackUsed`,`terminalReason`];function Fn(e,t,n){let r=R(e,t,n,Pn);if(!r)return;let i=j(r.loopId,T(t,`loopId`),n),a=j(r.instruction,T(t,`instruction`),n),o=A(r.useDefaultPrompt,T(t,`useDefaultPrompt`),n,P),s=I(r.createdAt,T(t,`createdAt`),n),c=I(r.expiresAt,T(t,`expiresAt`),n),l=N(r.revision,T(t,`revision`),n),u=N(r.generation,T(t,`generation`),n),d=F(r.phase,Nn,T(t,`phase`),n),f=P(r.fallbackUsed,T(t,`fallbackUsed`),n),p=A(r.nextAllowedAt,T(t,`nextAllowedAt`),n,I),m=A(r.delaySeconds,T(t,`delaySeconds`),n,N),h=A(r.reason,T(t,`reason`),n,j),g=A(r.terminalReason,T(t,`terminalReason`),n,j);if(l!==void 0&&(!Number.isSafeInteger(l)||l<0)&&D(n,T(t,`revision`),`expected a non-negative safe integer`),u!==void 0&&(!Number.isSafeInteger(u)||u<0)&&D(n,T(t,`generation`),`expected a non-negative safe integer`),m!==void 0&&(m<60||m>3600)&&D(n,T(t,`delaySeconds`),`expected a delay between 60 and 3600 seconds`),i!==void 0&&!i.trim()&&D(n,T(t,`loopId`),`expected a non-empty loop ID`),a!==void 0&&!a.trim()&&D(n,T(t,`instruction`),`expected a non-empty instruction`),d===`waiting`&&p===void 0&&r.nextAllowedAt===void 0&&D(n,T(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 In=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`],Ln=[`type`,`description`,`enum`,`items`,`properties`,`required`,`anyOf`,`additionalProperties`,`minimum`,`maximum`,`pattern`,`format`,`default`];function Rn(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 zn(e,t,n){return e===null?null:Rn(e,t,n)}function Bn(e,t,n){return typeof e==`boolean`?e:W(e,t,n)}function W(e,t,n){let r=R(e,t,n,Ln);if(r===void 0)return;let i={};return k(i,`type`,A(r.type,T(t,`type`),n,(e,t,n)=>F(e,In,t,n))),k(i,`description`,A(r.description,T(t,`description`),n,j)),k(i,`enum`,A(r.enum,T(t,`enum`),n,(e,t,n)=>L(e,t,n,Rn))),k(i,`items`,A(r.items,T(t,`items`),n,W)),k(i,`properties`,A(r.properties,T(t,`properties`),n,(e,t,n)=>z(e,t,n,W))),k(i,`required`,A(r.required,T(t,`required`),n,vt)),k(i,`anyOf`,A(r.anyOf,T(t,`anyOf`),n,(e,t,n)=>L(e,t,n,W))),k(i,`additionalProperties`,A(r.additionalProperties,T(t,`additionalProperties`),n,Bn)),k(i,`minimum`,A(r.minimum,T(t,`minimum`),n,M)),k(i,`maximum`,A(r.maximum,T(t,`maximum`),n,M)),k(i,`pattern`,A(r.pattern,T(t,`pattern`),n,j)),k(i,`format`,A(r.format,T(t,`format`),n,j)),k(i,`default`,A(r.default,T(t,`default`),n,zn)),i}function Vn(e,t,n){let r=W(e,t,n);if(r!==void 0){if(r.type!==`object`){D(n,T(t,`type`),`expected the root parameter schema to be type 'object'`);return}if(r.properties===void 0){D(n,T(t,`properties`),`expected the root parameter schema to name its properties`);return}return{...r,type:`object`,properties:r.properties}}}function Hn(e,t,n){let r=R(e,t,n,[`name`,`description`,`parameters`,`outputSchema`]);if(r===void 0)return;let i=j(r.name,T(t,`name`),n),a=j(r.description,T(t,`description`),n),o=Vn(r.parameters,T(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,T(t,`outputSchema`),n,W)),s}function G(e,t,n,r,i){return A(e[t],T(n,t),r,(e,t,n)=>L(e,t,n,i))}function Un(e,t,n,r){for(let i of[`name`,`systemPrompt`,`sandboxSnapshotId`])k(e,i,A(t[i],T(n,i),r,j));k(e,`history`,G(t,`history`,n,r,Ot)),k(e,`toolSchemas`,G(t,`toolSchemas`,n,r,Hn)),k(e,`backgroundTasks`,G(t,`backgroundTasks`,n,r,en)),k(e,`backgroundTaskEvents`,G(t,`backgroundTaskEvents`,n,r,dn)),k(e,`backgroundJobGroups`,G(t,`backgroundJobGroups`,n,r,qt)),k(e,`backgroundJobGroupEvents`,G(t,`backgroundJobGroupEvents`,n,r,Jt)),k(e,`sessionLoops`,G(t,`sessionLoops`,n,r,Fn)),k(e,`skillActivationEvents`,G(t,`skillActivationEvents`,n,r,yn)),k(e,`memoryEvents`,G(t,`memoryEvents`,n,r,xn)),k(e,`usedMemoryReferences`,G(t,`usedMemoryReferences`,n,r,bn)),k(e,`contextReferences`,G(t,`contextReferences`,n,r,Sn)),k(e,`goal`,A(t.goal,T(n,`goal`),r,kn)),k(e,`plan`,A(t.plan,T(n,`plan`),r,jn)),k(e,`activeBranch`,A(t.activeBranch,T(n,`activeBranch`),r,Mn))}const Wn=[`id`,`name`,`cwd`,`createdAt`,`updatedAt`,`messages`,`history`,`systemPrompt`,`toolSchemas`,`backgroundTasks`,`backgroundTaskEvents`,`backgroundJobGroups`,`backgroundJobGroupEvents`,`sessionLoops`,`skillActivationEvents`,`memoryEvents`,`usedMemoryReferences`,`contextReferences`,`sandboxSnapshotId`,`goal`,`plan`,`activeBranch`];function Gn(e){let t=[],n=Yn(e,``,t);return n===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:n}}function Kn(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 qn(e){return e===void 0?{}:{cwd:e}}function Jn(e){let t=[],n=R(e,``,t,[`schemaVersion`,`record`]);if(n===void 0)return{status:`corrupt`,issues:t,...qn(Kn(e))};let r=n.schemaVersion;if(typeof r!=`number`||!Number.isFinite(r))return{status:`unsupported`,schemaVersion:void 0,...qn(Kn(e))};if(r!==1)return{status:`unsupported`,schemaVersion:r,...qn(Kn(e))};let i=Yn(n.record,`record`,t);return i===void 0||t.length>0?{status:`corrupt`,issues:t,...qn(Kn(e))}:{status:`valid`,record:i}}function Yn(e,t,n){let r=R(e,t,n,Wn);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=j(r.cwd,T(t,`cwd`),n),o=I(r.createdAt,T(t,`createdAt`),n),s=I(r.updatedAt,T(t,`updatedAt`),n),c=L(r.messages,T(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 Un(l,r,t,n),l}function Xn(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function Zn(e,t={}){let n={schemaVersion:1,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function Qn(e){let t=Jn(Xn(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 $n=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function er(e){return $n.test(e)}function tr(e,t,n){if(e!==void 0&&er(e))return n;if(Array.isArray(t))return t.map(e=>tr(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]=tr(t,i,n);return r}return t}function nr(e,t=`[REDACTED]`){return tr(void 0,e,t)}const rr={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 ir(e,t){return e.event===t}function ar(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=or(e,a,o,n,r);return i}function or(e,t,n,r,i){if(er(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return sr(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return sr(e,n.map(n=>or(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]=or(e,n,o,r,i);return sr(e,a,r,i)}return String(n)}function sr(e,t,r,i){let a=JSON.stringify(t);if(a===void 0||Buffer.byteLength(a)<=r.externalPayloadThresholdBytes||i===void 0)return t;let o=(0,n.createHash)(`sha256`).update(a).digest(`hex`);return i.writeJson(e,o,a)}const cr=(0,e.createLogger)(`FileSessionLogger`),lr=new Set([`text_delta`]),ur=new Set;let dr=!1;function fr(e){ur.add(e),!dr&&(typeof process>`u`||typeof process.on!=`function`||(dr=!0,process.on(`exit`,()=>{for(let e of ur)e.flush()})))}var pr=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(ze(e))try{let r=ar(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
|
|
7
|
-
`;if(lr.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){ur.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,ur.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){fr(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){cr.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},mr=class{log(){}};const hr=(0,e.createLogger)(`NodeSessionLogSink`),gr=/^[0-9a-f]{64}$/;function _r(e,t){let r=(0,n.createHash)(`sha256`).update(t).digest(`hex`);if(!gr.test(e)||e!==r)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function vr(e,n,r){return Be(e),_r(n,r),{kind:`external-payload`,encoding:`json`,sha256:n,byteLength:Buffer.byteLength(r),relativePath:(0,t.join)(`${e}.payloads`,`${n}.json`)}}var yr=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,hr.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,n){if(Be(e),!this.enabled)return;let r=(0,t.join)(this.logDirectory,`${e}.jsonl`);(0,a.tightenExistingFile)(r),(0,i.appendFileSync)(r,n,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(e,n,r){let o=vr(e,n,r),s=`${e}.payloads`;if(this.enabled){(0,a.ensureOwnerOnlyDirectory)((0,t.join)(this.logDirectory,s));let e=(0,t.join)(this.logDirectory,o.relativePath);try{(0,i.writeFileSync)(e,r,{encoding:`utf8`,mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;(0,a.tightenExistingFile)(e)}}return o}};const K=e=>({decode:e}),q=e=>({decode:e,optional:!0}),br=(e,t,n)=>L(e,t,n,j),xr=(e,t,n)=>L(e,t,n,H),Sr=(e,t,n)=>L(e,t,n,Hn),Cr=(e,t,n)=>typeof e==`string`?e:H(e,t,n),J=(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 wr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Y(e,t,n){if(!wr(e)){n.push({path:t,message:`expected an object, received ${O(e)}`});return}for(let[r,i]of Object.entries(e))X(i,T(t,r),n);return e}const Tr=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function Er(e,t,n){let r=R(e,t,n,Tr);if(r===void 0)return;let i=M(r.maxTokens,T(t,`maxTokens`),n),a=M(r.usedTokens,T(t,`usedTokens`),n),o=M(r.usedPercentage,T(t,`usedPercentage`),n),s=M(r.remainingPercentage,T(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 Dr=(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,T(t,`type`),n),a=j(r.id,T(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 ${O(e)}`});return}if(!Array.isArray(e)&&!wr(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++)X(e[i],E(t,i),n,r);else for(let[i,a]of Object.entries(e))X(a,T(t,i),n,r);return r.delete(e),e}function Or(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)?Or(e[i],E(t,i),n,r):n.push({path:E(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))Or(a,T(t,i),n,r);r.delete(e)}}const Z=(...e)=>(t,n,r)=>F(t,e,n,r),kr={session_init:{cwd:K(j),systemPromptLength:K(J),systemPrompt:K(j),toolSchemas:K(Sr),model:K(j),provider:K(j)},session_shutdown:{reason:K(j)},session_shutdown_step_error:{step:K(j),error:K(j)},context:{maxTokens:K(M),usedTokens:K(M),usedPercentage:K(M),remainingPercentage:K(M)},context_compact:{trigger:K(j),before:K(Er),after:K(Er)},error:{message:K(j),stack:K(j),historyLength:K(J)},history_mutation:{executionId:q(j),conversationId:q(j),round:q(J),batchId:q(j),usageObservationId:q(j),providerId:q(j),modelId:q(j),providerError:q(P),contextOverflow:q(P),mutation:K(Z(`append_message`)),index:K(J),message:K(H)},provider_request:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),model:K(j),effort:q(j),forcedSummary:q(P),messages:K(xr),tools:q(Sr)},provider_native_raw_payload:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),apiSurface:q(j),payloadKind:K(Z(`request`,`response`,`stream_event`)),sequence:K(J),payload:q(X),metadata:q(Y)},provider_stream_raw_delta:{executionId:K(j),conversationId:q(j),round:K(J),sequence:K(J),delta:K(j)},provider_response_raw:{executionId:K(j),conversationId:q(j),round:K(J),effort:q(j),response:K(H),responseKind:K(j)},provider_response_normalized:{executionId:K(j),conversationId:q(j),round:K(J),response:K(H),toolCallsCount:q(J)},structured_output_transport:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),model:K(j),mechanism:K(Z(`response_schema`,`json_object`,`none`)),provenance:K(Z(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:K(P),schemaInPrompt:K(P),reason:q(j)},provider_fallback:{executionId:K(j),conversationId:q(j),round:K(J),fromProvider:K(j),fromModel:K(j),toProvider:K(j),toModel:K(j),reason:K(j)},assistant_message_committed:{executionId:K(j),conversationId:q(j),round:K(J),message:K(Cr)},tool_execution_request:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),toolName:K(j),toolCallId:K(j),parameters:K(Y),ownerPath:q(Dr)},tool_execution_result:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),toolName:q(j),toolCallId:q(j),success:K(P),result:q(X),error:q(j),metadata:q(Y)},tool_batch_started:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),mode:K(Z(`parallel`,`sequential`)),maxConcurrency:K(J),requestCount:K(J),tools:K(br)},tool_message_committed:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),message:K(H)},background_task_event:{backgroundEventType:q(j),backgroundEvent:q(dn),data:q(dn),taskId:q(j),originToolCallId:q(j)},background_job_group_event:{backgroundJobGroupEvent:q(Jt),data:q(Jt)},memory_event:{memoryEvent:q(xn),data:q(xn)},user:{content:K(j)},pre_run:{historyLength:K(J),historyChars:K(J),historyEstTokens:K(J),input:K(j),history:K(xr),model:K(j),provider:K(j),maxTokens:K(M),nativeWebSearchSupported:K(P),nativeWebSearchEnabled:K(P),nativeWebFetchSupported:K(P),nativeWebFetchEnabled:K(P)},text_delta:{delta:K(j)},assistant:{content:K(j),historyLength:K(J),estimatedChars:K(J),history:K(xr),historyStructure:K((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`],T(t,`role`),n),J(r.contentLength,T(t,`contentLength`),n),P(r.hasToolCalls,T(t,`hasToolCalls`),n),br(r.toolCallNames,T(t,`toolCallNames`),n),r.metadata!==void 0&&Y(r.metadata,T(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:T(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:K(j),args:K(Y)},tool_result:{tool:K(j),success:K(P),dataChars:K(J),truncated:K(P)},tool_blocked:{tool:K(j),reason:K(j)},tool_denied:{tool:K(j),reason:K(j)},server_tool:{tool:K(j)}};var Ar=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 jr=new Set(Object.values(rr));function Mr(e,t={}){if(!Array.isArray(e))throw new Ar(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${O(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=Nr(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 Ar(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function Nr(e,t,n){if(!wr(e))return n.push({path:t,message:`expected an object, received ${O(e)}`}),{};let r=n.length;if(Or(e,t,n),n.length!==r)return{};let i=Pr(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(Fr(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function Pr(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:T(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:T(t,`schemaVersion`),message:`expected schema version 1, received ${O(r)}`})}let a=I(e.timestamp,T(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=j(e.sessionId,T(t,`sessionId`),n);o===``&&n.push({path:T(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!jr.has(s)?(n.push({path:T(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 Fr(e,t,n,r,i){let a=kr[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],T(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:T(n,o),message:`unknown event payload field`});continue}let s=X(e[o],T(n,o),i);s!==void 0&&(r[o]=s)}Ir(e,t,n,i)}function Ir(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 Lr(e){if(e.trim().length===0||e.includes(`\0`)||(0,t.isAbsolute)(e)||t.win32.isAbsolute(e))throw zr(e);let n=e.split(/[\\/]+/u);if(n.some(e=>e===`.`||e===`..`))throw zr(e);return n}function Rr(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 zr(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Br(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?zr(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 Vr=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,t.resolve)(e)}readBytes(e,t){Rr(t);let n=Lr(e);try{let e=(0,o.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof o.StableFileAuthorityError?Br(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Hr=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 Vr((0,t.dirname)(e))}readText(){return(0,i.existsSync)(this.logFile)?(0,i.readFileSync)(this.logFile,`utf8`):void 0}};const Ur=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Wr=8*1024*1024,Gr=i.constants.O_WRONLY|i.constants.O_CREAT|i.constants.O_EXCL|(i.constants.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},Kr=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let n=e.parentDirectory??(0,r.tmpdir)();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=(0,i.lstatSync)(n);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,i.mkdtempSync)((0,t.join)(n,`agent-tool-results-`)),process.platform!==`win32`&&(0,i.chmodSync)(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=(0,i.lstatSync)(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`)>Wr)throw new $(`write-failed`);let r=(0,n.randomBytes)(18).toString(`base64url`),a=`${(0,n.randomBytes)(18).toString(`base64url`)}.partial`,o=`${r}.txt`,s=(0,t.join)(this.directory,a),c=(0,t.join)(this.directory,o),l,u=!1;try{l=(0,i.openSync)(s,Gr,384),(0,i.writeFileSync)(l,e,`utf8`),(0,i.fsyncSync)(l),(0,i.closeSync)(l),l=void 0,(0,i.linkSync)(s,c),u=!0,(0,i.unlinkSync)(s);let t=`tool-result:${r}`;return this.entries.set(t,{fileName:o,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:t}}catch{let e=!1;if(l!==void 0)try{(0,i.closeSync)(l)}catch{e=!0}try{(0,i.unlinkSync)(s)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(u)try{(0,i.unlinkSync)(c)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!Ur.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 Vr(this.directory).readBytes(t.fileName,Wr);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,n){this.assertRoot();try{(0,i.unlinkSync)((0,t.join)(this.directory,n.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((0,i.readdirSync)(this.directory).length!==0)throw Error(`unexpected files`);(0,i.rmdirSync)(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};function qr(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 Jr(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(qr(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Yr(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=Jr(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function Xr(e){return e.code===`ENOENT`}var Zr=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){(0,a.ensureOwnerOnlyDirectory)((0,t.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,i.appendFileSync)(this.path,`${JSON.stringify(e)}\n`,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,i.openSync)(this.path,i.constants.O_RDONLY|(i.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Xr(e))return;throw e}try{let n=(0,i.fstatSync)(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let a=Buffer.alloc(e),o=(0,i.readSync)(t,a,0,e,n),s=Buffer.concat([a.subarray(0,o),r]),c=n===0?-1:s.indexOf(10);r=c===-1&&n>0?s:s.subarray(0,c+1);let l=n===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);n>0&&c===-1||(yield Yr(l.toString(`utf8`).split(`
|
|
8
|
-
`).reverse()))}}finally{(0,i.closeSync)(t)}}};const
|
|
9
|
-
`).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new
|
|
5
|
+
`)}};const b=.835;var x=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(t,n,r){this.contextMaxTokens=n??(0,e.getModelContextWindow)(t),this.autoCompactThreshold=ee(r)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold!==!1&&this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=ee(e)}updateFromHistory(t){this.contextUsedTokens=(0,e.estimateContextTokensFromMessages)(t).usedTokens}reset(){this.contextUsedTokens=0}};function ee(e){if(e===void 0)return b;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 te(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 ne(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 re(e){let t={allowed:!1,rememberForSession:!1,rememberForProject:!1};if(e.alreadyAllowed)return{allowed:!0,rememberForSession:!1,rememberForProject:!1};if(e.signal?.aborted===!0)return t;let n=e.handler?()=>e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return n===void 0?t:ne(await te(n(),e.signal))}const ie=`robota-session/approval`;function ae(e){return e?.waits.some(e=>e.request.kind===ie)??!1}async function oe(t,n,r){let a=n?.waits.filter(e=>e.request.kind===ie)??[];if(!r&&!a.length)return;if(!n||n.action.toolName!==t.toolName)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Checkpointed approval requires the current journaled action`);let o=(0,i.realpathSync)(t.cwd);for(let{request:n}of a)if(n.data.version!==1||n.data.sessionId!==t.sessionId||n.data.cwd!==o||n.data.toolName!==t.toolName)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Saved approval belongs to a different Session or tool`);let s=await n.request({kind:ie,data:{version:1,sessionId:t.sessionId,cwd:o,toolName:t.toolName,arguments:structuredClone(t.toolArgs)}});if(Object.keys(s).length!==1||typeof s.approved!=`boolean`)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Approval response must contain only a boolean approved decision`);return s.approved}function se(e,t){return`${e}\u0000${JSON.stringify(t)}`}var ce=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(se(e,t))}takeRetry(e,t){return this.retries.delete(se(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 le(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function ue(e,t){switch(e){case`path`:{let e=le(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 de(t,n){let r=(0,e.getToolPermissionProfile)(t).argument;if(r===void 0)return t;let i=n[r.key];if(typeof i!=`string`||i===``)return t;let a=ue(r.kind,i);return a===void 0?t:`${t}(${a})`}function fe(n,r,i){let a=(0,e.getToolPermissionProfile)(n).argument;if(a===void 0||a.kind!==`path`)return r;let o=r[a.key];return typeof o!=`string`||o===``||(0,t.isAbsolute)(o)?r:{...r,[a.key]:(0,t.resolve)(i,o)}}function S(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function pe(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}),S(`threw`,r)}const me=S(`denied`,`Permission denied. The user did not approve this action.`),he=(0,e.createLogger)(`ToolHookHelpers`);function ge(t){if((0,e.wasToolResultAdmitted)(t)||typeof t.data!=`string`||t.data.length<=3e4)return t;let n=15e3,r=t.data.substring(0,n),i=t.data.substring(t.data.length-n),a=`${r}\n\n[... output truncated: ${t.data.length.toLocaleString()} chars total, showing first and last ${n.toLocaleString()} chars ...]\n\n${i}`;return{...t,data:a}}function _e(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 ve(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 ye(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:S(`hook-blocked`,`PreToolUse updatedInput must be an object.`)};let e=fe(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:S(`hook-blocked`,s,{blocked:!0,reason:s})}}async function ye(t,n,r,i){let a=await(0,e.runHooks)(t,`PreToolUse`,n,r,i);if(a.blocked){let e=a.reason??`Blocked by hook`;return{result:S(`hook-blocked`,e,{blocked:!0,reason:e}),hookResult:a}}if((0,e.isEnforcing)(`PreToolUse`)){let e=a.errors,t=e?.[0],n=a.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,i=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return{result:S(`hook-blocked`,i,{blocked:!0,reason:i}),hookResult:a}}if(r!==``)return{result:S(`hook-blocked`,r,{blocked:!0,reason:r}),hookResult:a}}return{result:null,hookResult:a}}function be(t,n,r,i,a){(0,e.runHooks)(t,`PostToolUse`,{...n,hook_event_name:`PostToolUse`,tool_output:typeof r.data==`string`?r.data:JSON.stringify(r.data)},i,a).catch(e=>he.warn(`hook failed`,{error:e}))}function xe(t,n){let r=(0,e.getToolPermissionProfile)(t).argument?.key;if(r===void 0)return;let i=n[r];if(typeof i==`string`)return i.length>200?`${i.slice(0,200)}…`:i}var Se=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=xe(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 Ce=(0,e.createLogger)(`ToolBodyTrace`);var C=class extends Error{result;constructor(e){super(`Effective tool arguments were not authorized`),this.result=e}};function we(t,n){try{t?.eventService?.emit(e.TOOL_PERMISSION_EVENTS.DECIDED,{timestamp:new Date,executionId:t.executionId,decidedAt:new Date().toISOString(),decision:n})}catch(e){Ce.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function Te(t,n){let r=t.execute.bind(t),i=t.executeWithAdmission?.bind(t),a=e.DEFAULT_ABSTRACT_EVENT_SERVICE,o=Object.create(t),s=async(o,s,c)=>{let l=o,u=`(unknown)`;try{u=t.getName(),l=fe(u,o,n.cwd),n.log(`tool_call`,{tool:u,args:l});let d=_e(n.sessionId,n.cwd,u,l,n.getPermissionMode(),n.transcriptPath),f=await ve(n.config.hooks,d,n.hookTypeExecutors,s?.hookTraceEnv);if(f.refusal)return n.log(`tool_blocked`,{tool:u,reason:`hook`}),we(s,`hook-blocked`),f.refusal;f.parameters!==void 0&&(l=f.parameters,d={...d,tool_input:l});let p=await n.checkPermission(u,l,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,f.decision);if(p!==!0)return n.log(`tool_denied`,{tool:u,reason:`permission`}),we(s,`denied`),n.onToolExecution?.({type:`end`,toolName:u,toolArgs:l,success:!1,denied:!0,executionId:s?.executionId}),typeof p==`object`?S(`denied`,p.message):me;we(s,`allowed`),s?.signal?.throwIfAborted(),n.onToolExecution?.({type:`start`,toolName:u,toolArgs:structuredClone(l),executionId:s?.executionId}),s?.signal?.throwIfAborted();let m,h=async e=>{s?.signal?.throwIfAborted();let t=fe(u,e,n.cwd);if(JSON.stringify(t)!==JSON.stringify(e))throw new C(S(`denied`,`Tool admission requires final canonical arguments; relative paths must be resolved before admission.`));if(JSON.stringify(t)!==JSON.stringify(l)){let e=_e(n.sessionId,n.cwd,u,t,n.getPermissionMode(),n.transcriptPath),r=await ve(n.config.hooks,e,n.hookTypeExecutors,s?.hookTraceEnv);if(r.refusal)throw new C(r.refusal);if(r.parameters!==void 0&&JSON.stringify(r.parameters)!==JSON.stringify(t))throw new C(S(`hook-blocked`,`A hook cannot replace arguments already settled by the tool; retry as a new call.`));let i=await n.checkPermission(u,t,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,r.decision);if(i!==!0)throw new C(typeof i==`object`?S(`denied`,i.message):me);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:a};c&&i?_=await i(l,e,h):(c?await h(l):m=Date.now(),s?.signal?.throwIfAborted(),_=await r(l,e)),g=s?.signal?.aborted?`interrupted`:_.success?`success`:`failure`}catch(t){throw g=s?.signal?.aborted||(0,e.isAbortFailure)(t)?`interrupted`:`failure`,t}finally{try{m!==void 0&&s?.eventService?.emit(e.TOOL_BODY_EVENTS.COMPLETED,{timestamp:new Date,executionId:s.executionId,startedAt:new Date(m).toISOString(),endedAt:new Date(Math.max(Date.now(),m)).toISOString(),outcome:g,...typeof s.toolBodyId==`string`?{toolBodyId:s.toolBodyId}:{}})}catch(e){Ce.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let v=ge(_);v!==_&&typeof _.data==`string`&&n.terminal.writeLine(` ⚠ Output truncated: ${_.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),n.onToolExecution?.({type:`end`,toolName:u,toolArgs:l,success:v.success,toolResultData:typeof v.data==`string`?v.data:JSON.stringify(v.data),executionId:s?.executionId});let y=typeof v.data==`string`?v.data.length:JSON.stringify(v.data)?.length??0;return n.log(`tool_result`,{tool:u,success:v.success,dataChars:y,truncated:v!==_}),be(n.config.hooks,d,v,n.hookTypeExecutors,s?.hookTraceEnv),v}catch(t){if((0,e.isExecutionControlError)(t))throw t;return t instanceof C?t.result:pe(t,n.onToolExecution,{toolName:u,toolArgs:l,executionId:s?.executionId})}};return o.execute=s,o.executeWithAdmission=s,o.setEventService=n=>{a=n??e.DEFAULT_ABSTRACT_EVENT_SERVICE,t.setEventService(n)},o}function Ee(e){let n=e,r=[];for(;;)try{let e=(0,i.realpathSync)(n);return r.length===0?e:(0,t.resolve)(e,...r.reverse())}catch{let i=(0,t.dirname)(n);if(i===n)return e;r.push(n.slice(i.length).replace(/^[\\/]/,``)),n=i}}function De(e,n){let r=(0,t.relative)(e,n);return r===``||!r.startsWith(`..`)&&!(0,t.isAbsolute)(r)}function Oe(e){return(n,r)=>{let i=Ee(e),a=Ee((0,t.resolve)(n??i,r));return De(i,a)?a:void 0}}function ke(t){let n=[...(0,e.findInvalidPermissionPatterns)(t.allow,`allow`),...(0,e.findInvalidPermissionPatterns)(t.restrictive,`deny`)];if(n.length===0)return;let r=n.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${r}. Fix the pattern where it is configured (issue #2428).`)}var Ae=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;homeDirectory;resolveInWorkspace;commandSandbox;denials=new Se;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]},ke(this.configuredRules(e)),this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool,this.permissionPolicy=e.permissionPolicy,this.taskPermissions=e.taskPermissions,this.homeDirectory=e.homeDirectory??(0,r.homedir)(),this.resolveInWorkspace=Oe(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new ce(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(t){let n=(0,e.getToolPermissionProfile)(t);return!this.peerTurn&&n.repliesToPeer===!0||this.peerTurn&&n.notInPeerTurn===!0?!1:!(0,e.isToolDeniedOutright)(t,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(t){for(let n of t){let t=n.schema;if(t===void 0)continue;let r=t.parameters?.properties??{};(0,e.registerToolPermissionProfile)(t.name,{parameters:Object.keys(r)})}let n=this.configuredRules();ke(n);for(let{pattern:t,reason:r}of(0,e.findPermissionPatternWarnings)(n.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${t}" ${r}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i,a,o)=>this.decidePermission(e,t,n,r,i,{continuation:a,...o===void 0?{}:{hookDecision:o}})};return e.map(e=>Te(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(t){let n=(0,e.applyPresetToolLists)(this.presetFreeRules,t);this.config.permissions.allow=n.allow,this.config.permissions.deny=n.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=_e(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath),i=await ve(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 oe({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a.continuation,!1)??!0):o}async evaluateToolPermission(t,n,r,i=`interactive`,a,o={}){let s=this.permissionPolicy===void 0?void 0:(0,e.projectPermissionPolicy)(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),c=this.getPermissionMode(),l=[...this.config.permissions.allow,...s?.allow??[]],u={allow:c===`auto`?(0,e.allowRulesForAutoMode)(l):l,deny:[...this.config.permissions.deny,...s?.deny??[]],ask:this.config.permissions.ask??[]},d={cwd:this.cwd,homeDirectory:this.homeDirectory},f=(0,e.evaluatePermission)(t,n,c,u,{...d,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:o.sandboxed!==!1&&this.sandboxAutoApproves(t,n),...s?.ceiling===void 0?{}:{ceiling:s.ceiling},askAll:s?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(t,n,f,a),f===`deny`)return this.denials.record(t,n,`policy`),!1;if(o.hookDecision===`ask`)return this.promptForApproval(t,n,r,i,!0,o.continuation);if(f===`auto`)return!0;let p=(0,e.requiresFreshApproval)(t,n,u,d);return c===`auto`&&this.autoMode!==void 0&&!p&&s?.askAll!==!0?this.decideInAutoMode(this.autoMode,t,n,r,i,a,o):o.hookDecision===`allow`&&!p&&s?.askAll!==!0||this.promptForApproval(t,n,r,i,p,o.continuation)}async decideInAutoMode(t,n,r,i,a,o,s){if(t.takeRetry(n,r)||(0,e.matchesAnyPattern)(n,r,(0,e.allowRulesForAutoMode)([...this.sessionAllowedTools])))return!0;if(t.isPaused()){let e=await this.promptForApproval(n,r,i,a,!0,s.continuation);return e&&!this.checkpointedApprovals&&!ae(s.continuation)&&t.resume(),e}let c=await t.judge({toolName:n,toolArgs:r,cwd:this.cwd},i);return i?.aborted===!0?!1:this.getPermissionMode()===`auto`?c.kind===`allow`?!0:(this.denials.record(n,r,`classifier`,c.reason),{message:c.message}):this.decidePermission(n,r,i,a,o,s)}async promptForApproval(t,n,r,i=`interactive`,a=!1,o){let s=!a&&(0,e.matchesAnyPattern)(t,n,[...this.sessionAllowedTools]);if(this.checkpointedApprovals&&!s||ae(o)){if(r?.aborted||i!==`interactive`)return!1;let e=await oe({sessionId:this.sessionId,cwd:this.cwd,toolName:t,toolArgs:n},o,!0);return e!==!0&&this.denials.record(t,n,`user`),e===!0}let c=de(t,n),l=r?.aborted===!0,u=i===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),d=await re({toolName:t,alreadyAllowed:s,...i===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...i===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:n,...r?{signal:r}:{}});if(!d.allowed&&!l&&this.denials.record(t,n,u?`user`:`no-approver`),a)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(t,n,r,i){let a=this.getPermissionMode();(0,e.runHooks)(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:t,tool_input:n,permission_decision:r,...a!==void 0&&{permission_mode:a},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,i).catch(()=>void 0)}sandboxAutoApproves(t,n){if(this.commandSandbox===void 0)return!1;let r=(0,e.getToolPermissionProfile)(t).argument;if(r?.kind!==`command`)return!1;let i=n[r.key];return typeof i==`string`&&this.commandSandbox.autoApproves(t,i)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function je(e,t,n,r,i){return new Ae({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 Me(e,t,n,r){return{contextTracker:new x(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new y({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function Ne(t,n,r,i,a,o,s){let c=n.wrapTools(r);return new e.Robota({name:t.agentName??`agent`,aiProviders:[i],defaultModel:{provider:i.name,model:a,...t.effort!==void 0&&{effort:t.effort},...t.temperature!==void 0&&{temperature:t.temperature},...t.maxOutputTokens!==void 0&&{maxTokens:t.maxOutputTokens}},systemMessage:o,tools:c,isToolVisible:e=>n.isToolVisible(e),logging:{enabled:!1},eventService:s,...t.providerTimeout!==void 0&&{timeout:t.providerTimeout},...t.responseFormat?{responseFormat:t.responseFormat}:{},...t.ask?{ask:t.ask}:{},...t.contextCapacityHint===void 0?{}:{contextCapacityHint:t.contextCapacityHint}})}const Pe=(0,e.createLogger)(`SessionHistoryOps`);function Fe(e,t){return{...e,...t}}async function Ie(t,n,r){r?.throwIfAborted();let i=n.agent.getHistory(),a=i.filter(e=>e.role!==`system`);if(a.length===0)return;n.contextTracker.updateFromHistory(i);let o=n.contextTracker.getContextState(),s=await n.compactionOrchestrator.compact(n.aiProvider,a,t,r,n.trigger,n.hookTraceEnv,n.executionJournal);n.agent.clearHistory(),n.agent.injectMessage(`system`,n.systemMessage),n.agent.injectMessage(`assistant`,`[Context Summary]\n${s}`),n.contextTracker.updateFromHistory(n.agent.getHistory());let c={session_id:n.sessionId,cwd:n.cwd,hook_event_name:`PostCompact`,trigger:n.trigger,compact_summary:s};(0,e.runHooks)(n.hooks,`PostCompact`,c,n.hookTypeExecutors,n.hookTraceEnv).catch(e=>Pe.warn(`hook failed`,{error:e}));let l=n.contextTracker.getContextState();n.log(`context_compact`,{trigger:n.trigger,before:o,after:l}),n.onCompactEventCallback?.({trigger:n.trigger,before:o,after:l}),n.onCompactCallback&&n.onCompactCallback(s)}function Le(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 Re=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function ze(){return`session_${(0,n.randomUUID)()}`}function Be(e){return e.length>0&&e.length<=128&&Re.test(e)}function Ve(e){if(!Be(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 He=(0,e.createLogger)(`SessionLifecycle`);function Ue(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function We(t,n,r,i,a,o,s){(0,e.runHooks)(r,`SessionStart`,{session_id:t,cwd:n,hook_event_name:`SessionStart`,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},i).then(e=>{e.stdout&&a(e.stdout)}).catch(e=>He.warn(`SessionStart hook failed`,{error:e}))}async function Ge(t,n,r,i,a,o,s){await(0,e.runHooks)(i,`SessionEnd`,{session_id:t,cwd:n,hook_event_name:`SessionEnd`,reason:r,...o!==void 0&&{permission_mode:o},...s!==void 0&&{transcript_path:s},env:{CLAUDE_PROJECT_DIR:n,CLAUDE_SESSION_ID:t}},a)}const Ke=`unknown_tool`;function qe(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function Je(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){Ye(e,n);return}t===`tool_execution_result`&&Xe(e,n)}}function Ye(e,t){let n=w(t.toolName),r=w(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:Ze(t.parameters)}))}function Xe(e,t){let n=w(t.toolName),r=w(t.toolCallId);if(!n||!r)return;let i=Qe(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===Ke))return;e.unknownToolCallIds.delete(r);let a=w(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:Ke,requestedTool:w(i?.requestedTool)??n,availableTools:$e(i?.availableTools)})})}function Ze(e){let t=Qe(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 w(e){return typeof e==`string`&&e.length>0?e:void 0}function Qe(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function $e(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const et=(0,e.createLogger)(`SessionRunObservation`);function tt(t,n,r,i){let a=typeof r.model==`string`?r.model:t.model,o=typeof r.provider==`string`?r.provider:t.aiProvider.name,s=r.effort,c=typeof s==`string`&&(0,e.isModelEffort)(s)?s:t.effort??(typeof t.agent.getModel==`function`?t.agent.getModel().effort:void 0)??`high`,l=typeof r.round==`number`?r.round:void 0;(0,e.runHooks)(t.hooks,n,{session_id:t.sessionId,cwd:t.cwd,hook_event_name:n,model:a,provider:o,effort:c,...l!==void 0&&{round:l},...t.permissionMode!==void 0&&{permission_mode:t.permissionMode},...t.transcriptPath!==void 0&&{transcript_path:t.transcriptPath},env:{CLAUDE_PROJECT_DIR:t.cwd,CLAUDE_SESSION_ID:t.sessionId}},t.hookTypeExecutors,i).catch(e=>et.warn(`hook failed`,{error:e}))}function nt(t,n){let r=n?(0,e.traceEnvFor)(`hooks`,n,n.parentSpanId):void 0,i=qe({knownToolNames:t.knownToolNames??[],...t.onToolExecution&&{onToolExecution:t.onToolExecution}}),a=t.onTextDelta?e=>{t.log(`text_delta`,{delta:e}),t.onTextDelta?.(e)}:void 0,o={};return{onExecutionEvent:(n,a)=>{if(n!==e.PROVIDER_CALL_EVENTS.COMPLETED&&t.log(n,a),Je(i,n,a),n===`provider_request`){let e=a;o={model:e.model,provider:e.provider},tt(t,`PreModelCall`,e,r)}else if(n===`provider_response_normalized`)tt(t,`PostModelCall`,{...a,...o},r);else if(n===e.PROVIDER_FALLBACK_EVENTS.SWITCHED){let n=(0,e.readModelFallbackNotice)(a);n!==void 0&&(tt(t,`PostModelCall`,{round:a.round,model:n.from.model,provider:n.from.provider},r),t.emitProviderFallback?.(n))}else if(n===e.PROVIDER_CALL_EVENTS.COMPLETED&&t.emitProviderCallCompleted){let e=a;Number.isSafeInteger(e.round)&&e.round>0&&typeof e.startedAt==`string`&&typeof e.endedAt==`string`&&(e.outcome===`success`||e.outcome===`failure`||e.outcome===`interrupted`)&&t.emitProviderCallCompleted({round:e.round,startedAt:e.startedAt,endedAt:e.endedAt,outcome:e.outcome,...typeof e.callId==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e.callId)&&{callId:e.callId},...(e.disposition===`invoked`||e.disposition===`cache-hit`||e.disposition===`preflight-refused`)&&{disposition:e.disposition},...typeof e.providerId==`string`&&e.providerId.length>0&&e.providerId.length<=128&&[...e.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:e.providerId},...typeof e.modelId==`string`&&e.modelId.length>0&&e.modelId.length<=128&&[...e.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:e.modelId},...(e.usageProvenance===`complete`||e.usageProvenance===`partial`||e.usageProvenance===`absent`)&&{usageProvenance:e.usageProvenance},...e.usageProvenance===`complete`&&typeof e.promptTokens==`number`&&Number.isSafeInteger(e.promptTokens)&&e.promptTokens>=0&&typeof e.completionTokens==`number`&&Number.isSafeInteger(e.completionTokens)&&e.completionTokens>=0&&typeof e.totalTokens==`number`&&Number.isSafeInteger(e.totalTokens)&&e.totalTokens===e.promptTokens+e.completionTokens&&{promptTokens:e.promptTokens,completionTokens:e.completionTokens,totalTokens:e.totalTokens},...e.disposition===`invoked`&&typeof e.providerRequestId==`string`&&{providerRequestId:e.providerRequestId}})}n===`assistant_message_committed`&&(t.contextTracker.updateFromHistory(t.agent.getHistory()),t.onContextUpdate?.(t.contextTracker.getContextState()))},...a&&{onTextDelta:a}}}async function rt(e,t){let n=await e.agent.resume({...t,...nt(e,t.traceContext)});return e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()),e.getSessionStore()&&e.persistSession(),n}function it(e,t){let n=(0,i.realpathSync)(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:`robota-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 at(t,n,r,a){let o,s=(0,i.realpathSync)(r);return{read:async i=>{let c=structuredClone(await t.read(i)),l;for(let t of c){if(t.kind!==`model-request`&&t.kind!==`model-cache-hit`)continue;let r=t.checkpoint?.owner,a=r?.state;if(!r||r.kind!==`robota-session`||r.version!==1||!a||a.sessionId!==n||a.cwd!==s||a.executionId!==i||typeof a.peerTurn!=`boolean`||l!==void 0&&l!==a.peerTurn||a.peerTurn&&t.checkpoint?.continuation?.options.withholdHostedTools!==!0)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session continuation owner or scope is incompatible`);l=a.peerTurn}if(l===void 0)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`No Session owner checkpoint exists`);return o=it(t,{sessionId:n,cwd:r,peerTurn:l}),a(l),c},append:async t=>{if(!o)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Session owner has not been restored`);await o.append(t)}}}function ot(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 st=(0,e.createLogger)(`SessionRun`);async function ct(t,n,r,i,a){let o=a?.traceContext,s=o?(0,e.traceEnvFor)(`hooks`,o,o.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{a?.executionJournal?await r.compact(i,s,a.executionJournal):await(s?r.compact(i,s):r.compact(i))}finally{e.onTextDelta=t}}r.log(`user`,{content:t});let c=await(0,e.runHooks)(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,s),l=[r.sessionStartStdout,c.stdout].filter(Boolean).join(`
|
|
6
|
+
`),u=l?`<system-reminder>\n${l}\n</system-reminder>\n${t}`:t;r.clearSessionStartStdout();let d=r.agent.getHistory(),f=JSON.stringify(d),p=(0,e.getProviderCapabilities)(r.aiProvider);r.log(`pre_run`,{historyLength:d.length,historyChars:f.length,historyEstTokens:Math.ceil(f.length/e.CONTEXT_ESTIMATE_CHARS_PER_TOKEN),input:u,history:d,model:r.model,provider:r.aiProvider.name,maxTokens:r.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:p.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:p.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:p.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:p.nativeWebTools.webFetch.enabled}),r.contextTracker.updateFromHistory([...d,(0,e.createUserMessage)(u)]),r.onContextUpdate?.(r.contextTracker.getContextState());let m;try{if(m=await r.agent.run(u,{signal:i,maxExecutionRounds:r.maxTurns??0,...ot(a),...nt(r,o)}),i.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(t){if(t instanceof e.ExecutionSuspendedError)throw t;try{r.log(`error`,{message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack??``:``,historyLength:r.agent.getHistory().length})}catch{}throw(0,e.runHooks)(r.hooks,`StopFailure`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`StopFailure`,reason:t instanceof Error?t.message:String(t),stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>st.warn(`hook failed`,{error:e})),t}let h=r.agent.getHistory(),g=h.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:m,historyLength:h.length,estimatedChars:JSON.stringify(h).length,history:h,historyStructure:g}),r.contextTracker.updateFromHistory(h);let _=r.contextTracker.getContextState();return r.onContextUpdate?.(_),r.log(`context`,{maxTokens:_.maxTokens,usedTokens:_.usedTokens,usedPercentage:_.usedPercentage,remainingPercentage:_.remainingPercentage}),(0,e.runHooks)(r.hooks,`Stop`,{session_id:r.sessionId,cwd:r.cwd,hook_event_name:`Stop`,response:m.substring(0,500),last_assistant_message:m,stop_hook_active:!1,...r.permissionMode!==void 0&&{permission_mode:r.permissionMode},...r.transcriptPath!==void 0&&{transcript_path:r.transcriptPath},env:{CLAUDE_PROJECT_DIR:r.cwd,CLAUDE_SESSION_ID:r.sessionId}},r.hookTypeExecutors,s).catch(e=>st.warn(`hook failed`,{error:e})),r.getSessionStore()&&r.persistSession(),m}function lt(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function ut(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 dt(e,t,n){let r=ut(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 ft(e,t){return{read:t=>e.read(t),append:n=>(n.kind===`tool-effect-start`&&t.add(n.actionId),e.append(n))}}function pt(t,n){let r=ut(t);if(!r||r.assistant.metadata?.executionId!==n.executionId)return[];let i=new Set(n.requests.map(e=>e.toolCallId));return r.open.map(t=>{let n=i.has(t.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return(0,e.createToolMessage)(`Error: ${n}`,{toolCallId:t.id,name:t.function.name,metadata:{success:!1,error:n,toolName:t.function.name}})})}async function mt(t,n){if(!n||typeof n.append!=`function`||typeof n.read!=`function`)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await t()}}catch(t){if(t instanceof e.ExecutionSuspendedError)return{status:`waiting`,requests:structuredClone(t.requests)};throw t}}var ht=class{agent;claim;sessionId;execution=null;constructor(e,t,n){this.agent=e,this.claim=t,this.sessionId=n}async invoke(e,t,r){let i=this.claim.claim(),a=gt(i,r);try{return i.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:(0,n.randomUUID)(),sessionId:this.sessionId,signal:i.signal,permissionInteraction:`deny`}),await this.execution}finally{this.execution=null,a(),this.claim.release(i)}}async drain(){await this.execution}};function gt(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var _t=class extends f{agent;eventService=new e.ObservableEventService;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;pendingExecution;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(t){super(t.cwd);let{tools:n,provider:r,systemMessage:i}=t;this.terminal=t.terminal,this.sessionStore=t.sessionStore,this.systemMessage=i,this.toolSchemas=n.map(e=>e.schema),this.wrapAddedTools=t.wrapAddedTools,this.sessionLogger=t.sessionLogger,this.hooks=t.hooks,this.hookTypeExecutors=t.hookTypeExecutors,this.onTextDeltaCallback=t.onTextDelta,this.onContextUpdateCallback=t.onContextUpdate,this.onToolExecutionCallback=t.onToolExecution,this.onCompactCallback=t.onCompact,this.onCompactEventCallback=t.onCompactEvent,this.maxTurns=t.maxTurns,this.model=t.model??`claude-sonnet-4-5`,this.sessionId=t.sessionId??ze(),this.permissionMode=t.permissionMode??(t.defaultTrustLevel?e.TRUST_TO_MODE[t.defaultTrustLevel]:void 0)??`default`,this.activePresetId=t.activePresetId??`default`,this.parallelSubagentsEnabled=t.enableParallelSubagents??!0,this.transcriptPath=t.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:i.length,systemPrompt:i,toolSchemas:this.toolSchemas,model:this.model,provider:r.name}),this.aiProvider=r,Ue(r,t,(e,t)=>this.log(e,t)),this.permissionEnforcer=je(t,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:a,compactionOrchestrator:o}=Me(t,this.model,this.sessionId,this.cwd);this.contextTracker=a,this.compactionOrchestrator=o,this.agent=Ne(t,this.permissionEnforcer,n,r,this.model,i,this.eventService),this.runtimeTools=new ht(this.agent,this.turnClaim,this.sessionId),We(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 mt(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(t,n,r,i){let a=r?{...r}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.pendingExecution)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`);let o=this.turnClaim.claim(),s=gt(o,a?.signal),{signal:c}=o;this.permissionEnforcer.beginTurn(a?.peerTurn===!0,i);try{c.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=a?.executionJournal?{...a,executionJournal:it(a.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:a.peerTurn===!0})}:a,r=await ct(t,n,this.buildRunContext(),c,e);return this.messageCount+=1,r}catch(t){throw t instanceof e.ExecutionSuspendedError?(this.pendingExecution=lt(t),c.throwIfAborted()):a?.executionJournal&&(this.pendingExecution=dt(this.agent.getHistory(),void 0,new Set)),t}finally{this.permissionEnforcer.endTurn(),s(),this.turnClaim.release(o)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return mt(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(t,n){let r={...t,toolResponses:structuredClone(t.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.pendingExecution&&this.pendingExecution.executionId!==r.executionId)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let i=this.turnClaim.claim(),a=gt(i,r.signal),o=new Set;try{i.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=at(ft(r.journal,o),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,n)),t=await rt(this.buildRunContext(),{...r,journal:e,signal:i.signal});return this.pendingExecution=void 0,t}catch(t){throw t instanceof e.ExecutionSuspendedError?(this.pendingExecution=lt(t),i.signal.throwIfAborted()):this.pendingExecution=dt(this.agent.getHistory(),this.pendingExecution,o),t}finally{this.permissionEnforcer.endTurn(),a(),this.turnClaim.release(i)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(t){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);let n=this.pendingExecution;if(!n)return;if(n.executionId!==t)throw new e.ExecutionRecoveryError(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim();try{for(let e of pt(this.agent.getHistory(),n))this.agent.injectRawMessage(e);this.pendingExecution=void 0,this.persistSessionInternal()}finally{this.turnClaim.release(r)}}addTools(e){return this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.runtimeTools.invoke(e,t,n?.signal)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&Le({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,agent:this.agent,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>Ge(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 Ie(e,Fe(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(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:t=>this.eventService.emit(e.PROVIDER_CALL_EVENTS.COMPLETED,{timestamp:new Date,...t},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:t=>this.eventService.emit(e.PROVIDER_FALLBACK_EVENTS.SWITCHED,{timestamp:new Date,fromProvider:t.from.provider,fromModel:t.from.model,toProvider:t.to.provider,toModel:t.to.model,reason:t.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};function T(e,t){return e.length===0?t:`${e}.${t}`}function E(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 vt(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,E(t,a),n);o!==void 0&&i.push(o)}),i}function yt(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,T(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,T(t,a),n);e!==void 0&&(i[a]=e)}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,E(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 bt(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)}`)}const xt=[`complete`,`interrupted`],V=[`id`,`timestamp`,`state`,`metadata`,`role`,`content`,`parts`],St={user:[...V,`name`],assistant:[...V,`toolCalls`],system:[...V,`name`],tool:[...V,`toolCallId`,`name`]};function Ct(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){let r={};for(let[i,a]of Object.entries(e)){if(typeof a!=`number`){D(n,T(t,i),`expected a number, received ${O(a)}`);continue}r[i]=a}return r}D(n,t,`expected a metadata value, received ${O(e)}`)}function wt(e,t,n){return z(e,t,n,Ct)}function Tt(e,t,n){let r=F(e?.type,[`text`,`image_inline`,`image_uri`],T(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,T(t,`text`),n);return i===void 0?void 0:{type:`text`,text:i}}if(r===`image_inline`){let r=R(e,t,n,[`type`,`mimeType`,`data`]);if(r===void 0)return;let i=j(r.mimeType,T(t,`mimeType`),n),a=j(r.data,T(t,`data`),n);return i===void 0||a===void 0?void 0:{type:`image_inline`,mimeType:i,data:a}}let i=R(e,t,n,[`type`,`uri`,`mimeType`]);if(i===void 0)return;let a=j(i.uri,T(t,`uri`),n);if(a===void 0)return;let o={type:`image_uri`,uri:a};return k(o,`mimeType`,A(i.mimeType,T(t,`mimeType`),n,j)),o}function Et(e,t,n){let r=R(e,t,n,[`id`,`type`,`function`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=F(r.type,[`function`],T(t,`type`),n),o=T(t,`function`),s=R(r.function,o,n,[`name`,`arguments`]),c=s===void 0?void 0:j(s.name,T(o,`name`),n),l=s===void 0?void 0:j(s.arguments,T(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 Dt(e,t,n){let r=j(e.id,T(t,`id`),n),i=vt(e.timestamp,T(t,`timestamp`),n),a=F(e.state,xt,T(t,`state`),n);if(r!==void 0&&i!==void 0&&a!==void 0)return{id:r,timestamp:i,state:a}}function Ot(e,t,n,r){k(e,`metadata`,A(t.metadata,T(n,`metadata`),r,wt)),k(e,`parts`,A(t.parts,T(n,`parts`),r,(e,t,n)=>L(e,t,n,Tt)))}function H(e,t,n){let r=F(e?.role,[`user`,`assistant`,`system`,`tool`],T(t,`role`),n);if(r===void 0)return;let i=R(e,t,n,St[r]);if(i===void 0)return;let a=Dt(i,t,n);if(a===void 0)return;let o=T(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 Ot(s,i,t,n),k(s,`toolCalls`,A(i.toolCalls,T(t,`toolCalls`),n,(e,t,n)=>L(e,t,n,Et))),s}let s=j(i.content,o,n);if(s===void 0)return;if(r===`tool`){let e=j(i.toolCallId,T(t,`toolCallId`),n);if(e===void 0)return;let o={...a,role:r,content:s,toolCallId:e};return Ot(o,i,t,n),k(o,`name`,A(i.name,T(t,`name`),n,j)),o}let c={...a,role:r,content:s};return Ot(c,i,t,n),k(c,`name`,A(i.name,T(t,`name`),n,j)),c}function kt(e,t,n){let r=R(e,t,n,[`id`,`timestamp`,`category`,`type`,`data`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=vt(r.timestamp,T(t,`timestamp`),n),o=j(r.category,T(t,`category`),n),s=j(r.type,T(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,T(t,`data`),n,B)),c}const At=[`agent`,`process`,`scheduled`,`tool-invocation`],jt=[`foreground`,`background`],Mt=[`none`,`worktree`],Nt=[`queued`,`running`,`waiting_permission`,`sleeping`,`paused`,`completed`,`failed`,`cancelled`],Pt=[`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`],Ft=[`validation`,`capacity`,`permission`,`timeout`,`runner`,`crash`,`provider`,`process`],It=[`denied-by-person`,`no-approver`,`approver-error`,`cancelled`];function Lt(e,t,n){return z(e,t,n,bt)}function Rt(e,t,n){return z(e,t,n,j)}function zt(e,t,n){let r=R(e,t,n,[`category`,`message`,`recoverable`]);if(r===void 0)return;let i=F(r.category,Ft,T(t,`category`),n),a=j(r.message,T(t,`message`),n),o=P(r.recoverable,T(t,`recoverable`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{category:i,message:a,recoverable:o}}function Bt(e,t,n){let r=R(e,t,n,[`promptTokens`,`completionTokens`,`totalTokens`]);if(r===void 0)return;let i=N(r.promptTokens,T(t,`promptTokens`),n),a=N(r.completionTokens,T(t,`completionTokens`),n),o=N(r.totalTokens,T(t,`totalTokens`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{promptTokens:i,completionTokens:a,totalTokens:o}}function Vt(e,t,n){let r=R(e,t,n,[`total`,`byReason`]);if(r===void 0)return;let i=N(r.total,T(t,`total`),n),a=T(t,`byReason`),o=R(r.byReason,a,n,It);if(i===void 0||o===void 0)return;let s={},c=!0;for(let e of It){let t=N(o[e],T(a,e),n);if(t===void 0){c=!1;continue}s[e]=t}if(c)return{total:i,byReason:s}}function Ht(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,T(t,`taskId`),n),a=F(r.kind,At,T(t,`kind`),n),o=j(r.output,T(t,`output`),n);if(i===void 0||a===void 0||o===void 0)return;let s=A(r.exitCode,T(t,`exitCode`),n,N),c=A(r.signalCode,T(t,`signalCode`),n,j),l=A(r.metadata,T(t,`metadata`),n,Lt),u=A(r.usage,T(t,`usage`),n,Bt),d=A(r.deniedToolCalls,T(t,`deniedToolCalls`),n,Vt);switch(a!==`process`&&s!==void 0&&D(n,T(t,`exitCode`),`must not be set for a '${a}' result`),a!==`process`&&c!==void 0&&D(n,T(t,`signalCode`),`must not be set for a '${a}' result`),a!==`agent`&&u!==void 0&&D(n,T(t,`usage`),`must not be set for a '${a}' result`),a!==`agent`&&d!==void 0&&D(n,T(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 Ut(e,t,n){let r=R(e,t,n,[`cronExpression`,`agentInstruction`,`command`,`shell`,`env`]);if(r===void 0)return;let i=j(r.cronExpression,T(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],T(t,e),n,j));return k(a,`env`,A(r.env,T(t,`env`),n,Rt)),a}const Wt=[`detached`,`wait_all`,`wait_any`,`manual`],Gt=[`running`,`completed`],Kt=[`background_job_group_created`,`background_job_group_updated`,`background_job_group_completed`];function qt(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,T(t,`taskId`),n),a=j(r.label,T(t,`label`),n),o=F(r.status,Nt,T(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],T(t,e),n,j));for(let e of[`startedAt`,`completedAt`])k(s,e,A(r[e],T(t,e),n,I));return k(s,`error`,A(r.error,T(t,`error`),n,zt)),s}function Jt(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,T(t,`id`),n),a=j(r.parentSessionId,T(t,`parentSessionId`),n),o=F(r.waitPolicy,Wt,T(t,`waitPolicy`),n),s=yt(r.taskIds,T(t,`taskIds`),n),c=F(r.status,Gt,T(t,`status`),n),l=I(r.createdAt,T(t,`createdAt`),n),u=I(r.updatedAt,T(t,`updatedAt`),n),d=L(r.results,T(t,`results`),n,qt);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,T(t,`label`),n,j)),k(f,`completedAt`,A(r.completedAt,T(t,`completedAt`),n,I)),f}function Yt(e,t,n){let r=F(e?.type,Kt,T(t,`type`),n);if(r===void 0)return;let i=R(e,t,n,[`type`,`group`]);if(i===void 0)return;let a=Jt(i.group,T(t,`group`),n);return a===void 0?void 0:{type:r,group:a}}const Xt=[`parentTaskId`,`currentAction`,`logPath`,`transcriptPath`],Zt=[`agentType`,`resumeSessionId`,`promptPreview`,`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`],Qt=[`commandPreview`],$t=[`startedAt`,`lastActivityAt`,`completedAt`],en=[`id`,`kind`,`label`,`status`,`mode`,`parentSessionId`,`depth`,`cwd`,`pid`,`updatedAt`,`isolation`,`unread`,`result`,`error`,`timeoutReason`,`schedule`,`nextFireAt`,`metadata`,...Xt,...Zt,...Qt,...$t];function tn(e,t,n){let r=R(e,t,n,en);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=F(r.kind,At,T(t,`kind`),n),o=j(r.label,T(t,`label`),n),s=F(r.status,Nt,T(t,`status`),n),c=F(r.mode,jt,T(t,`mode`),n),l=j(r.parentSessionId,T(t,`parentSessionId`),n),u=N(r.depth,T(t,`depth`),n),d=j(r.cwd,T(t,`cwd`),n),f=I(r.updatedAt,T(t,`updatedAt`),n),p=P(r.unread,T(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 Xt)k(m,e,A(r[e],T(t,e),n,j));for(let e of $t)k(m,e,A(r[e],T(t,e),n,I));k(m,`pid`,A(r.pid,T(t,`pid`),n,N)),k(m,`timeoutReason`,A(r.timeoutReason,T(t,`timeoutReason`),n,(e,t,n)=>F(e,Pt,t,n))),k(m,`metadata`,A(r.metadata,T(t,`metadata`),n,Lt)),k(m,`error`,A(r.error,T(t,`error`),n,zt));let h=A(r.result,T(t,`result`),n,Ht);h!==void 0&&(h.taskId!==i&&D(n,T(T(t,`result`),`taskId`),`must match the task ID`),h.kind!==a&&D(n,T(T(t,`result`),`kind`),`must match the task kind`));let g=A(r.agentType,T(t,`agentType`),n,j),_=A(r.resumeSessionId,T(t,`resumeSessionId`),n,j),v=A(r.promptPreview,T(t,`promptPreview`),n,j),y=A(r.isolation,T(t,`isolation`),n,(e,t,n)=>F(e,Mt,t,n)),b={};for(let e of[`worktreePath`,`branchName`,`worktreeStatus`,`worktreeNextAction`,`worktreeBaseRevision`,`parentWorktreeStatus`])b[e]=A(r[e],T(t,e),n,j);for(let e of Zt){let r=e===`agentType`?g:e===`resumeSessionId`?_:e===`promptPreview`?v:b[e];a!==`agent`&&r!==void 0&&D(n,T(t,e),`must not be set for a '${a}' task`)}a!==`agent`&&y!==void 0&&D(n,T(t,`isolation`),`must not be set for a '${a}' task`);let x=A(r.commandPreview,T(t,`commandPreview`),n,j);a===`agent`&&x!==void 0&&D(n,T(t,`commandPreview`),`must not be set for a '${a}' task`);let ee=A(r.schedule,T(t,`schedule`),n,Ut),te=A(r.nextFireAt,T(t,`nextFireAt`),n,I);switch(a!==`scheduled`&&ee!==void 0&&D(n,T(t,`schedule`),`must not be set for a '${a}' task`),a!==`scheduled`&&te!==void 0&&D(n,T(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`,ee),k(t,`nextFireAt`,te),t}}}const nn=[`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,T(t,`taskId`),n)}function rn(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,T(t,`delta`),n);if(i!==void 0&&a!==void 0)return{type:`background_task_text_delta`,taskId:i,delta:a}}function an(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,T(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,T(t,`firstArg`),n,j)),o}function on(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,T(t,`toolName`),n),o=P(r.success,T(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,T(t,`error`),n,j)),s}function sn(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,T(t,`requestId`),n),o=j(r.toolName,T(t,`toolName`),n),s=Lt(r.toolArgs,T(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 cn(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 ln(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,T(t,`instruction`),n,j)),a}function un(e,t,n,r){let i=R(t,n,r,[`type`,`task`]);if(i===void 0)return;let a=tn(i.task,T(n,`task`),r);if(a!==void 0)return{type:e,task:a}}const dn={background_task_text_delta:rn,background_task_tool_start:an,background_task_tool_end:on,background_task_permission_request:sn,background_task_closed:cn,background_task_waking:ln};function fn(e,t,n){let r=F(e?.type,nn,T(t,`type`),n);if(r===void 0)return;let i=dn[r];return i===void 0?un(r,e,t,n):i(e,t,n)}const pn=[`skill`,`plugin`],mn=[`user-slash`,`model-tool`],hn=[`inject`,`fork`],gn=[`started`,`completed`,`failed`],_n=[`memory_candidate_extracted`,`memory_candidate_queued`,`memory_candidate_saved`,`memory_candidate_skipped`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`],vn=[`manual`,`prompt-reference`,`system`],yn=[`active`,`observed`];function bn(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`],T(t,`type`),n),a=j(r.skillName,T(t,`skillName`),n),o=F(r.source,pn,T(t,`source`),n),s=F(r.invocation,mn,T(t,`invocation`),n),c=F(r.mode,hn,T(t,`mode`),n),l=F(r.status,gn,T(t,`status`),n),u=I(r.timestamp,T(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,T(t,`qualifiedName`),n,j),f=A(r.error,T(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 xn(e,t,n){let r=R(e,t,n,[`topic`,`path`,`score`,`truncated`]);if(r===void 0)return;let i=j(r.topic,T(t,`topic`),n),a=j(r.path,T(t,`path`),n),o=M(r.score,T(t,`score`),n),s=P(r.truncated,T(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 Sn(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,_n,T(t,`type`),n),a=I(r.at,T(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],T(t,e),n,j));return k(o,`data`,A(r.data,T(t,`data`),n,(e,t,n)=>z(e,t,n,B))),o}function Cn(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,T(t,`id`),n),a=j(r.sourcePath,T(t,`sourcePath`),n),o=j(r.relativePath,T(t,`relativePath`),n),s=j(r.originalReference,T(t,`originalReference`),n),c=F(r.loadType,vn,T(t,`loadType`),n),l=F(r.status,yn,T(t,`status`),n),u=N(r.byteLength,T(t,`byteLength`),n),d=I(r.loadedAt,T(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,T(t,`lastUsedAt`),n,I)),f}const wn=[`active`,`satisfied`,`stopped`],Tn=[`satisfied`,`max-iterations`,`cancelled`,`no-progress`],En=[`continue`,`satisfied`],Dn=[`pending`,`in-progress`,`done`],On=[`planning`,`awaiting-approval`,`executing`,`completed`];function kn(e,t,n){let r=R(e,t,n,[`iteration`,`signal`,`reason`]);if(r===void 0)return;let i=N(r.iteration,T(t,`iteration`),n),a=F(r.signal,En,T(t,`signal`),n),o=j(r.reason,T(t,`reason`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{iteration:i,signal:a,reason:o}}function An(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,T(t,`id`),n),a=j(r.objective,T(t,`objective`),n),o=F(r.status,wn,T(t,`status`),n),s=N(r.iterations,T(t,`iterations`),n),c=N(r.maxIterations,T(t,`maxIterations`),n),l=I(r.startedAt,T(t,`startedAt`),n),u=L(r.progress,T(t,`progress`),n,kn);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,T(t,`stopReason`),n,(e,t,n)=>F(e,Tn,t,n))),d}function jn(e,t,n){let r=R(e,t,n,[`id`,`description`,`status`]);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=j(r.description,T(t,`description`),n),o=F(r.status,Dn,T(t,`status`),n);if(i!==void 0&&a!==void 0&&o!==void 0)return{id:i,description:a,status:o}}function Mn(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,T(t,`id`),n),a=j(r.objective,T(t,`objective`),n),o=L(r.steps,T(t,`steps`),n,jn),s=F(r.phase,On,T(t,`phase`),n),c=I(r.createdAt,T(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,T(t,`approvedAt`),n,I)),l}function Nn(e,t,n){let r=R(e,t,n,[`branchId`,`checkpointId`]);if(r===void 0)return;let i=j(r.branchId,T(t,`branchId`),n),a=j(r.checkpointId,T(t,`checkpointId`),n);if(i!==void 0&&a!==void 0)return{branchId:i,checkpointId:a}}const Pn=[`waiting`,`pending`,`running`,`stopped`,`expired`],Fn=[`loopId`,`instruction`,`useDefaultPrompt`,`createdAt`,`expiresAt`,`revision`,`generation`,`phase`,`nextAllowedAt`,`delaySeconds`,`reason`,`fallbackUsed`,`terminalReason`];function In(e,t,n){let r=R(e,t,n,Fn);if(!r)return;let i=j(r.loopId,T(t,`loopId`),n),a=j(r.instruction,T(t,`instruction`),n),o=A(r.useDefaultPrompt,T(t,`useDefaultPrompt`),n,P),s=I(r.createdAt,T(t,`createdAt`),n),c=I(r.expiresAt,T(t,`expiresAt`),n),l=N(r.revision,T(t,`revision`),n),u=N(r.generation,T(t,`generation`),n),d=F(r.phase,Pn,T(t,`phase`),n),f=P(r.fallbackUsed,T(t,`fallbackUsed`),n),p=A(r.nextAllowedAt,T(t,`nextAllowedAt`),n,I),m=A(r.delaySeconds,T(t,`delaySeconds`),n,N),h=A(r.reason,T(t,`reason`),n,j),g=A(r.terminalReason,T(t,`terminalReason`),n,j);if(l!==void 0&&(!Number.isSafeInteger(l)||l<0)&&D(n,T(t,`revision`),`expected a non-negative safe integer`),u!==void 0&&(!Number.isSafeInteger(u)||u<0)&&D(n,T(t,`generation`),`expected a non-negative safe integer`),m!==void 0&&(m<60||m>3600)&&D(n,T(t,`delaySeconds`),`expected a delay between 60 and 3600 seconds`),i!==void 0&&!i.trim()&&D(n,T(t,`loopId`),`expected a non-empty loop ID`),a!==void 0&&!a.trim()&&D(n,T(t,`instruction`),`expected a non-empty instruction`),d===`waiting`&&p===void 0&&r.nextAllowedAt===void 0&&D(n,T(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 Ln=[`string`,`number`,`integer`,`boolean`,`array`,`object`,`null`],Rn=[`type`,`description`,`enum`,`items`,`properties`,`required`,`anyOf`,`additionalProperties`,`minimum`,`maximum`,`pattern`,`format`,`default`];function zn(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 Bn(e,t,n){return e===null?null:zn(e,t,n)}function Vn(e,t,n){return typeof e==`boolean`?e:W(e,t,n)}function W(e,t,n){let r=R(e,t,n,Rn);if(r===void 0)return;let i={};return k(i,`type`,A(r.type,T(t,`type`),n,(e,t,n)=>F(e,Ln,t,n))),k(i,`description`,A(r.description,T(t,`description`),n,j)),k(i,`enum`,A(r.enum,T(t,`enum`),n,(e,t,n)=>L(e,t,n,zn))),k(i,`items`,A(r.items,T(t,`items`),n,W)),k(i,`properties`,A(r.properties,T(t,`properties`),n,(e,t,n)=>z(e,t,n,W))),k(i,`required`,A(r.required,T(t,`required`),n,yt)),k(i,`anyOf`,A(r.anyOf,T(t,`anyOf`),n,(e,t,n)=>L(e,t,n,W))),k(i,`additionalProperties`,A(r.additionalProperties,T(t,`additionalProperties`),n,Vn)),k(i,`minimum`,A(r.minimum,T(t,`minimum`),n,M)),k(i,`maximum`,A(r.maximum,T(t,`maximum`),n,M)),k(i,`pattern`,A(r.pattern,T(t,`pattern`),n,j)),k(i,`format`,A(r.format,T(t,`format`),n,j)),k(i,`default`,A(r.default,T(t,`default`),n,Bn)),i}function Hn(e,t,n){let r=W(e,t,n);if(r!==void 0){if(r.type!==`object`){D(n,T(t,`type`),`expected the root parameter schema to be type 'object'`);return}if(r.properties===void 0){D(n,T(t,`properties`),`expected the root parameter schema to name its properties`);return}return{...r,type:`object`,properties:r.properties}}}function Un(e,t,n){let r=R(e,t,n,[`name`,`description`,`parameters`,`outputSchema`]);if(r===void 0)return;let i=j(r.name,T(t,`name`),n),a=j(r.description,T(t,`description`),n),o=Hn(r.parameters,T(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,T(t,`outputSchema`),n,W)),s}function G(e,t,n,r,i){return A(e[t],T(n,t),r,(e,t,n)=>L(e,t,n,i))}function Wn(e,t,n,r){for(let i of[`name`,`systemPrompt`,`sandboxSnapshotId`])k(e,i,A(t[i],T(n,i),r,j));k(e,`history`,G(t,`history`,n,r,kt)),k(e,`toolSchemas`,G(t,`toolSchemas`,n,r,Un)),k(e,`backgroundTasks`,G(t,`backgroundTasks`,n,r,tn)),k(e,`backgroundTaskEvents`,G(t,`backgroundTaskEvents`,n,r,fn)),k(e,`backgroundJobGroups`,G(t,`backgroundJobGroups`,n,r,Jt)),k(e,`backgroundJobGroupEvents`,G(t,`backgroundJobGroupEvents`,n,r,Yt)),k(e,`sessionLoops`,G(t,`sessionLoops`,n,r,In)),k(e,`skillActivationEvents`,G(t,`skillActivationEvents`,n,r,bn)),k(e,`memoryEvents`,G(t,`memoryEvents`,n,r,Sn)),k(e,`usedMemoryReferences`,G(t,`usedMemoryReferences`,n,r,xn)),k(e,`contextReferences`,G(t,`contextReferences`,n,r,Cn)),k(e,`goal`,A(t.goal,T(n,`goal`),r,An)),k(e,`plan`,A(t.plan,T(n,`plan`),r,Mn)),k(e,`activeBranch`,A(t.activeBranch,T(n,`activeBranch`),r,Nn))}const Gn=[`id`,`name`,`cwd`,`createdAt`,`updatedAt`,`messages`,`history`,`systemPrompt`,`toolSchemas`,`backgroundTasks`,`backgroundTaskEvents`,`backgroundJobGroups`,`backgroundJobGroupEvents`,`sessionLoops`,`skillActivationEvents`,`memoryEvents`,`usedMemoryReferences`,`contextReferences`,`sandboxSnapshotId`,`goal`,`plan`,`activeBranch`];function Kn(e){let t=[],n=Xn(e,``,t);return n===void 0||t.length>0?{status:`corrupt`,issues:t}:{status:`valid`,record:n}}function qn(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 Jn(e){return e===void 0?{}:{cwd:e}}function Yn(e){let t=[],n=R(e,``,t,[`schemaVersion`,`record`]);if(n===void 0)return{status:`corrupt`,issues:t,...Jn(qn(e))};let r=n.schemaVersion;if(typeof r!=`number`||!Number.isFinite(r))return{status:`unsupported`,schemaVersion:void 0,...Jn(qn(e))};if(r!==1)return{status:`unsupported`,schemaVersion:r,...Jn(qn(e))};let i=Xn(n.record,`record`,t);return i===void 0||t.length>0?{status:`corrupt`,issues:t,...Jn(qn(e))}:{status:`valid`,record:i}}function Xn(e,t,n){let r=R(e,t,n,Gn);if(r===void 0)return;let i=j(r.id,T(t,`id`),n),a=j(r.cwd,T(t,`cwd`),n),o=I(r.createdAt,T(t,`createdAt`),n),s=I(r.updatedAt,T(t,`updatedAt`),n),c=L(r.messages,T(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 Wn(l,r,t,n),l}function Zn(e){try{return JSON.parse(e)}catch{throw Error(`Invalid session artifact: the bytes are not JSON.`)}}function Qn(e,t={}){let n={schemaVersion:1,record:t.redact?t.redact(e):e};return JSON.stringify(n,null,2)}function $n(e){let t=Yn(Zn(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 er=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function tr(e){return er.test(e)}function nr(e,t,n){if(e!==void 0&&tr(e))return n;if(Array.isArray(t))return t.map(e=>nr(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]=nr(t,i,n);return r}return t}function rr(e,t=`[REDACTED]`){return nr(void 0,e,t)}const ir={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 ar(e,t){return e.event===t}function or(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=sr(e,a,o,n,r);return i}function sr(e,t,n,r,i){if(tr(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return cr(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return cr(e,n.map(n=>sr(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]=sr(e,n,o,r,i);return cr(e,a,r,i)}return String(n)}function cr(e,t,r,i){let a=JSON.stringify(t);if(a===void 0||Buffer.byteLength(a)<=r.externalPayloadThresholdBytes||i===void 0)return t;let o=(0,n.createHash)(`sha256`).update(a).digest(`hex`);return i.writeJson(e,o,a)}const lr=(0,e.createLogger)(`FileSessionLogger`),ur=new Set([`text_delta`]),dr=new Set;let fr=!1;function pr(e){dr.add(e),!fr&&(typeof process>`u`||typeof process.on!=`function`||(fr=!0,process.on(`exit`,()=>{for(let e of dr)e.flush()})))}var mr=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(Be(e))try{let r=or(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
|
|
7
|
+
`;if(ur.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){dr.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,dr.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){pr(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){lr.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},hr=class{log(){}};const gr=(0,e.createLogger)(`NodeSessionLogSink`),_r=/^[0-9a-f]{64}$/;function vr(e,t){let r=(0,n.createHash)(`sha256`).update(t).digest(`hex`);if(!_r.test(e)||e!==r)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function yr(e,n,r){return Ve(e),vr(n,r),{kind:`external-payload`,encoding:`json`,sha256:n,byteLength:Buffer.byteLength(r),relativePath:(0,t.join)(`${e}.payloads`,`${n}.json`)}}var br=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{(0,a.ensureOwnerOnlyDirectory)(e),this.enabled=!0}catch(t){this.enabled=!1,gr.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,n){if(Ve(e),!this.enabled)return;let r=(0,t.join)(this.logDirectory,`${e}.jsonl`);(0,a.tightenExistingFile)(r),(0,i.appendFileSync)(r,n,{mode:a.OWNER_ONLY_FILE_MODE})}writeJson(e,n,r){let o=yr(e,n,r),s=`${e}.payloads`;if(this.enabled){(0,a.ensureOwnerOnlyDirectory)((0,t.join)(this.logDirectory,s));let e=(0,t.join)(this.logDirectory,o.relativePath);try{(0,i.writeFileSync)(e,r,{encoding:`utf8`,mode:a.OWNER_ONLY_FILE_MODE,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;(0,a.tightenExistingFile)(e)}}return o}};const K=e=>({decode:e}),q=e=>({decode:e,optional:!0}),xr=(e,t,n)=>L(e,t,n,j),Sr=(e,t,n)=>L(e,t,n,H),Cr=(e,t,n)=>L(e,t,n,Un),wr=(e,t,n)=>typeof e==`string`?e:H(e,t,n),J=(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 Tr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Y(e,t,n){if(!Tr(e)){n.push({path:t,message:`expected an object, received ${O(e)}`});return}for(let[r,i]of Object.entries(e))X(i,T(t,r),n);return e}const Er=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function Dr(e,t,n){let r=R(e,t,n,Er);if(r===void 0)return;let i=M(r.maxTokens,T(t,`maxTokens`),n),a=M(r.usedTokens,T(t,`usedTokens`),n),o=M(r.usedPercentage,T(t,`usedPercentage`),n),s=M(r.remainingPercentage,T(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 Or=(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,T(t,`type`),n),a=j(r.id,T(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 ${O(e)}`});return}if(!Array.isArray(e)&&!Tr(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++)X(e[i],E(t,i),n,r);else for(let[i,a]of Object.entries(e))X(a,T(t,i),n,r);return r.delete(e),e}function kr(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)?kr(e[i],E(t,i),n,r):n.push({path:E(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))kr(a,T(t,i),n,r);r.delete(e)}}const Z=(...e)=>(t,n,r)=>F(t,e,n,r),Ar={session_init:{cwd:K(j),systemPromptLength:K(J),systemPrompt:K(j),toolSchemas:K(Cr),model:K(j),provider:K(j)},session_shutdown:{reason:K(j)},session_shutdown_step_error:{step:K(j),error:K(j)},context:{maxTokens:K(M),usedTokens:K(M),usedPercentage:K(M),remainingPercentage:K(M)},context_compact:{trigger:K(j),before:K(Dr),after:K(Dr)},error:{message:K(j),stack:K(j),historyLength:K(J)},history_mutation:{executionId:q(j),conversationId:q(j),round:q(J),batchId:q(j),usageObservationId:q(j),providerId:q(j),modelId:q(j),providerError:q(P),contextOverflow:q(P),mutation:K(Z(`append_message`)),index:K(J),message:K(H)},provider_request:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),model:K(j),effort:q(j),forcedSummary:q(P),messages:K(Sr),tools:q(Cr)},provider_native_raw_payload:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),apiSurface:q(j),payloadKind:K(Z(`request`,`response`,`stream_event`)),sequence:K(J),payload:q(X),metadata:q(Y)},provider_stream_raw_delta:{executionId:K(j),conversationId:q(j),round:K(J),sequence:K(J),delta:K(j)},provider_response_raw:{executionId:K(j),conversationId:q(j),round:K(J),effort:q(j),response:K(H),responseKind:K(j)},provider_response_normalized:{executionId:K(j),conversationId:q(j),round:K(J),response:K(H),toolCallsCount:q(J)},structured_output_transport:{executionId:K(j),conversationId:q(j),round:K(J),provider:K(j),model:K(j),mechanism:K(Z(`response_schema`,`json_object`,`none`)),provenance:K(Z(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:K(P),schemaInPrompt:K(P),reason:q(j)},provider_fallback:{executionId:K(j),conversationId:q(j),round:K(J),fromProvider:K(j),fromModel:K(j),toProvider:K(j),toModel:K(j),reason:K(j)},assistant_message_committed:{executionId:K(j),conversationId:q(j),round:K(J),message:K(wr)},tool_execution_request:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),toolName:K(j),toolCallId:K(j),parameters:K(Y),ownerPath:q(Or)},tool_execution_result:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),toolName:q(j),toolCallId:q(j),success:K(P),result:q(X),error:q(j),metadata:q(Y)},tool_batch_started:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),mode:K(Z(`parallel`,`sequential`)),maxConcurrency:K(J),requestCount:K(J),tools:K(xr)},tool_message_committed:{executionId:K(j),conversationId:q(j),round:K(J),batchId:q(j),index:q(J),message:K(H)},background_task_event:{backgroundEventType:q(j),backgroundEvent:q(fn),data:q(fn),taskId:q(j),originToolCallId:q(j)},background_job_group_event:{backgroundJobGroupEvent:q(Yt),data:q(Yt)},memory_event:{memoryEvent:q(Sn),data:q(Sn)},user:{content:K(j)},pre_run:{historyLength:K(J),historyChars:K(J),historyEstTokens:K(J),input:K(j),history:K(Sr),model:K(j),provider:K(j),maxTokens:K(M),nativeWebSearchSupported:K(P),nativeWebSearchEnabled:K(P),nativeWebFetchSupported:K(P),nativeWebFetchEnabled:K(P)},text_delta:{delta:K(j)},assistant:{content:K(j),historyLength:K(J),estimatedChars:K(J),history:K(Sr),historyStructure:K((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`],T(t,`role`),n),J(r.contentLength,T(t,`contentLength`),n),P(r.hasToolCalls,T(t,`hasToolCalls`),n),xr(r.toolCallNames,T(t,`toolCallNames`),n),r.metadata!==void 0&&Y(r.metadata,T(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:T(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:K(j),args:K(Y)},tool_result:{tool:K(j),success:K(P),dataChars:K(J),truncated:K(P)},tool_blocked:{tool:K(j),reason:K(j)},tool_denied:{tool:K(j),reason:K(j)},server_tool:{tool:K(j)}};var jr=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 Mr=new Set(Object.values(ir));function Nr(e,t={}){if(!Array.isArray(e))throw new jr(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${O(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=Pr(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 jr(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function Pr(e,t,n){if(!Tr(e))return n.push({path:t,message:`expected an object, received ${O(e)}`}),{};let r=n.length;if(kr(e,t,n),n.length!==r)return{};let i=Fr(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(Ir(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function Fr(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:T(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:T(t,`schemaVersion`),message:`expected schema version 1, received ${O(r)}`})}let a=I(e.timestamp,T(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=j(e.sessionId,T(t,`sessionId`),n);o===``&&n.push({path:T(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!Mr.has(s)?(n.push({path:T(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 Ir(e,t,n,r,i){let a=Ar[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],T(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:T(n,o),message:`unknown event payload field`});continue}let s=X(e[o],T(n,o),i);s!==void 0&&(r[o]=s)}Lr(e,t,n,i)}function Lr(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 Rr(e){if(e.trim().length===0||e.includes(`\0`)||(0,t.isAbsolute)(e)||t.win32.isAbsolute(e))throw Br(e);let n=e.split(/[\\/]+/u);if(n.some(e=>e===`.`||e===`..`))throw Br(e);return n}function zr(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 Br(e,t){return new Q(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function Vr(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?Br(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 Hr=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=(0,t.resolve)(e)}readBytes(e,t){zr(t);let n=Rr(e);try{let e=(0,o.createStableRootedFileReader)(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof Q?n:n instanceof o.StableFileAuthorityError?Vr(n,e,t):new Q(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}},Ur=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 Hr((0,t.dirname)(e))}readText(){return(0,i.existsSync)(this.logFile)?(0,i.readFileSync)(this.logFile,`utf8`):void 0}};const Wr=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,Gr=8*1024*1024,Kr=i.constants.O_WRONLY|i.constants.O_CREAT|i.constants.O_EXCL|(i.constants.O_NOFOLLOW??0);var $=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},qr=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let n=e.parentDirectory??(0,r.tmpdir)();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=(0,i.lstatSync)(n);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=(0,i.mkdtempSync)((0,t.join)(n,`agent-tool-results-`)),process.platform!==`win32`&&(0,i.chmodSync)(this.directory,448),this.assertRoot()}catch{throw new $(`unsafe-root`)}}assertRoot(){try{let e=(0,i.lstatSync)(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`)>Gr)throw new $(`write-failed`);let r=(0,n.randomBytes)(18).toString(`base64url`),a=`${(0,n.randomBytes)(18).toString(`base64url`)}.partial`,o=`${r}.txt`,s=(0,t.join)(this.directory,a),c=(0,t.join)(this.directory,o),l,u=!1;try{l=(0,i.openSync)(s,Kr,384),(0,i.writeFileSync)(l,e,`utf8`),(0,i.fsyncSync)(l),(0,i.closeSync)(l),l=void 0,(0,i.linkSync)(s,c),u=!0,(0,i.unlinkSync)(s);let t=`tool-result:${r}`;return this.entries.set(t,{fileName:o,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:t}}catch{let e=!1;if(l!==void 0)try{(0,i.closeSync)(l)}catch{e=!0}try{(0,i.unlinkSync)(s)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(u)try{(0,i.unlinkSync)(c)}catch{e=!0}throw new $(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new $(`closed`);if(!Wr.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 Hr(this.directory).readBytes(t.fileName,Gr);if(e===void 0)throw new $(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof $?e:new $(`read-failed`)}}removeEntry(e,n){this.assertRoot();try{(0,i.unlinkSync)((0,t.join)(this.directory,n.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((0,i.readdirSync)(this.directory).length!==0)throw Error(`unexpected files`);(0,i.rmdirSync)(this.directory),this.closed=!0}catch{throw new $(`cleanup-failed`)}}}};function Jr(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 Yr(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(Jr(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function Xr(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=Yr(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function Zr(e){return e.code===`ENOENT`}var Qr=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){(0,a.ensureOwnerOnlyDirectory)((0,t.dirname)(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),(0,a.tightenExistingFile)(this.path),(0,i.appendFileSync)(this.path,`${JSON.stringify(e)}\n`,{mode:a.OWNER_ONLY_FILE_MODE})}async*read(e){let t;try{t=(0,i.openSync)(this.path,i.constants.O_RDONLY|(i.constants.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&Zr(e))return;throw e}try{let n=(0,i.fstatSync)(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let a=Buffer.alloc(e),o=(0,i.readSync)(t,a,0,e,n),s=Buffer.concat([a.subarray(0,o),r]),c=n===0?-1:s.indexOf(10);r=c===-1&&n>0?s:s.subarray(0,c+1);let l=n===0?s:c===-1?Buffer.alloc(0):s.subarray(c+1);n>0&&c===-1||(yield Xr(l.toString(`utf8`).split(`
|
|
8
|
+
`).reverse()))}}finally{(0,i.closeSync)(t)}}};const $r=/^[0-9a-f]{64}$/i;function ei(e){if(!ti(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 ti(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`&&$r.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function ni(e,t){return ai(e,ri(t),0)}function ri(e){let t=ii(`maxDepth`,e.maxDepth??32),n=ii(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function ii(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 ai(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 ci(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw ci(`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(li(e))return oi(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>ai(e,t,n))}finally{t.activeObjects.delete(e)}}if(!ui(e))throw ci(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,ai(r,t,n)]))}finally{t.activeObjects.delete(e)}}function oi(e,t,n){let r=ei(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=si(r,t);t.activePayloadPaths.add(r.relativePath);try{return ai(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function si(e,t){let r=t.maxTotalBytes-t.totalBytes,i=t.source?.readBytes(e.relativePath,r);if(i===void 0)throw new Q(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let a=t.totalBytes+i.byteLength;if(!Number.isSafeInteger(a)||a>t.maxTotalBytes)throw new Q(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:a});if(t.totalBytes=a,i.byteLength!==e.byteLength)throw new Q(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:i.byteLength});let o=(0,n.createHash)(`sha256`).update(i).digest(`hex`);if(o!==e.sha256)throw new Q(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:o});try{return JSON.parse(Buffer.from(i).toString(`utf8`))}catch(t){throw new Q(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function ci(e){return new Q(`INVALID_JSON`,e)}function li(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function ui(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function di(e){let t=[],n=fi(),r=pi();return Nr(e).forEach((e,i)=>{xi(e,i,t),hi(e,i,t),mi(n,e,i),gi(r,e,i)}),_i(n,t),vi(r,t),{ok:t.length===0,issues:t}}function fi(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function pi(){return{requests:new Map,results:new Set}}function mi(e,t,n){let r=yi(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`&&!Si(t.response)&&e.normalizedResponses.add(r.key))}function hi(e,t,n){Si(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 gi(e,t,n){let r=bi(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 _i(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 vi(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 yi(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 bi(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 xi(e,t,n){if(Array.isArray(e)){e.forEach(e=>xi(e,t,n));return}if(Ci(e)){if(e.kind===`external-payload`){ti(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>xi(e,t,n))}}function Si(e){return Array.isArray(e)?e.some(e=>Si(e)):Ci(e)?e.kind===`external-payload`||Object.values(e).some(e=>Si(e)):!1}function Ci(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wi(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
|
|
9
|
+
`).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new jr(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),Nr(ni(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Ti(t){let n=[],r=[],i={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},a,o,s,c;for(let l of Nr(t))a??=l.sessionId,s??=l.timestamp,c=l.timestamp,l.event===`session_init`&&(o=typeof l.cwd==`string`?l.cwd:o),l.event===`history_mutation`&&l.mutation===`append_message`&&(n.push(l.message),r.push((0,e.messageToHistoryEntry)(l.message))),Ei(l,i);return{sessionId:a,cwd:o,createdAt:s,updatedAt:c,messages:n,history:r,backgroundTaskEvents:i.backgroundTaskEvents,backgroundJobGroupEvents:i.backgroundJobGroupEvents,memoryEvents:i.memoryEvents}}function Ei(e,t){if(e.event===`background_task_event`){Oi(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){Oi(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&Oi(t.memoryEvents,e,`memoryEvent`,`data`)}function Di(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function Oi(e,t,n,r){let i=Di(t,n)??Di(t,r);i&&e.push(i)}function ki(e){return e instanceof Error?e.message:`unknown error`}function Ai(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=Yn(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 ji(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Mi=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){(0,a.ensureOwnerOnlyDirectory)(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){Ve(e);let t=(0,c.resolve)(this.baseDir),n=(0,c.resolve)(t,`${e}.json`);if(!n.startsWith(t+c.sep))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),(0,a.writeOwnerOnlyFile)(this.filePath(e.id),JSON.stringify({schemaVersion:1,record:e},null,2))}load(e){let t=this.filePath(e);if(!(0,s.existsSync)(t))return{status:`missing`};let n;try{n=(0,s.readFileSync)(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${ki(e)}`}]}}return Ai(n)}list(){return(0,s.existsSync)(this.baseDir)?(0,s.readdirSync)(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(ji):[]}outcomeForListedId(e){return Be(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);(0,s.existsSync)(t)&&(0,s.unlinkSync)(t)}},Ni=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};exports.AUTO_COMPACT_THRESHOLD=b,exports.AutoModeGate=ce,exports.CONSECUTIVE_BLOCK_LIMIT=3,exports.CheckpointTree=Ni,exports.CompactionError=_,exports.CompactionOrchestrator=y,exports.ContextWindowTracker=x,exports.DEFAULT_COMPACTION_PROMPT=v,exports.DEFAULT_PROMPT_HISTORY_BLOCK_BYTES=65536,exports.FileSessionLogger=mr,exports.INTERACTIVE_SESSION_RECORD_KEYS=Gn,exports.NodeExternalPayloadSource=Hr,exports.NodePromptHistoryFile=Qr,exports.NodeSessionLogSink=br,exports.NodeSessionLogSource=Ur,exports.NodeSessionStore=Mi,exports.NodeToolResultSpillStore=qr,exports.PermissionEnforcer=Ae,exports.SENSITIVE_KEY_PATTERN=er,exports.SESSION_LOG_EVENT=ir,exports.SESSION_LOG_SCHEMA_VERSION=1,exports.SESSION_RECORD_ENVELOPE_VERSION=1,exports.Session=_t,exports.SessionBusyError=u,exports.SessionLogDecodeError=jr,exports.SessionLogPayloadResolutionError=Q,exports.SilentSessionLogger=hr,exports.TOTAL_BLOCK_LIMIT=20,exports.ToolResultSpillError=$,exports.TurnClaim=d,exports.assertSafeSessionId=Ve,exports.consentScopeFor=de,exports.createSessionLogExternalPayloadReference=yr,exports.decodeInteractiveSessionRecord=Kn,exports.decodeSessionLogEntries=Nr,exports.decodeVersionedInteractiveSessionRecord=Yn,exports.deserializeSessionArtifact=$n,exports.formatConversationEntries=g,exports.isSafeSessionId=Be,exports.isSensitiveKey=tr,exports.isSessionLogEvent=ar,exports.loadSessionLogEntries=wi,exports.parsePromptHistoryLine=Yr,exports.replaySessionLogEntries=Ti,exports.resolveSessionLogExternalPayloads=ni,exports.scrubSensitiveKeys=rr,exports.serializeSessionArtifact=Qn,exports.validateSessionReplayLogEntries=di;
|
package/dist/node/index.d.cts
CHANGED
|
@@ -752,7 +752,7 @@ declare class PermissionEnforcer {
|
|
|
752
752
|
/**
|
|
753
753
|
* SELFHOST-009: fire the PermissionDecision hook (informational-only, non-blocking) via the shared
|
|
754
754
|
* `runHooks` path. Fire-and-forget — the result is never awaited or consulted, so it cannot gate the
|
|
755
|
-
* permission outcome. The sole blocking gate remains PreToolUse (`
|
|
755
|
+
* permission outcome. The sole blocking gate remains PreToolUse (`runPreToolGate`).
|
|
756
756
|
*/
|
|
757
757
|
private firePermissionDecisionHook;
|
|
758
758
|
/** Whether the OS sandbox confines this shell command and lets it run without a prompt. */
|